Linux下的多线程编程(一) 创建线程

本文深入探讨了线程的概念、优点、缺点以及如何在Linux环境下创建线程的实践案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的基础知识

1. 线程的定义:一个进程内部的控制序列。

2. 线程的优点:

  • 异步执行代码;

  • 将用户交互和其他部分分开;

  • 串行变并行。

3. 线程的缺点:

  • 难调试;

  • 共享变量的问题。

4. 线程的结构

线程的ID,寄存器值,栈,调度优先级和策略,信号屏蔽字,errno变量,私有数据。

进程对他下面的所有线程共享了:可执行程序文本、程序的全局内存和堆内存(操作系统分配的)、栈以及文件描述符。

创建线程

1. 见下面的 pthread_create() 函数原型:

int pthread_create(pthread_t *restrict tidp, 
			const pthread_attr_t *restrict attr, 
			void *(*start_rtn)(void), 
			void *restrict arg);
参数解释:

tidp 创建后,返回的线程id指向此变量

attr 线程的属性,用NULL表示默认的属性

start_rtn 新创建的线程,从此函数开始运行

arg 为上面start_rtn函数的参数

2. 运行实例

在Linux环境下,用 gcc t.c -o t -lpthread 编译运行。

#include <stdio.h>
#include <string.h>
#include <pthread.h>

void printThreadInfo(const char *whichThread) {
	printf("%s\n", whichThread);
	printf("The Process ID is: %u \n" , (unsigned int)getpid() );
	printf("The Thread ID is %u \n", (unsigned int)pthread_self() );
	printf("\n");
}

void *thread_function() {
	printThreadInfo("my thread");
}

int main() {
	pthread_t new_thread_id;
	int err = pthread_create(&new_thread_id, NULL, thread_function, NULL); 
	if(err == 0) {
		printf("thread created successfully! \n" );
	} else {
		printf("%s\n",strerror(err));
	}
	sleep(1);
	printThreadInfo("main thread");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值