pthread创建线程

pthread可以创建线程
头文件

#include<pthread.h>

pthread_t tid:声明了所创建线程的标识符
pthread_attr_t attr:表示线程的属性
pthread_attr_init(&attr):设置线程的属性
pthread_create:创建一个独立线程
函数声明
int pthread_create(pthread_t* restrict tidp,const pthread_attr_t* restrict_attr,void* (start_rtn)(void),void *restrict arg);

  • tidp:新创建的线程的标识符
  • attr:线程属性,一般设置为NULL
  • satrt_rtn:新创线程从此开始运行
  • arg:start_rtn函数的参数
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 4
void* threadfunc(void *r) {
	printf("This is a pthread %d.\n", *(int*)r);
	pthread_exit(0);
}

int main(void) {
pthread_t workers[NUM_THREADS];
int i, ret;
int data[NUM_THREAD] = {1,2,3,4};

for (i = 0; i < NUM_THREADS; ++i){
ret = pthread_create(&workers[i], NULL, threadfunc, (void*)&data[i]);
if (ret != 0){
	printf("Create pthread %d error!\n", i);
	return 1;
}
}
printf("This is the main process.\n");

for (i = 0; i < NUM_THREADS; ++i)
	pthread_join(workers[i], NULL);
return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值