【c++并发编程】pthread_create的使用

作用

用于创建一个线程。

头文件

#include<pthread.h>

函数声明

int pthread_create(pthread_t* restrict tidp,const pthread_attr_t* restrict_attr,void* (start_rtn)(void),void *restrict arg);

参数

  • tidp:事先创建好的pthread_t类型的参数。成功时tidp指向的内存单元被设置为新创建线程的线程ID。
  • attr:用于定制各种不同的线程属性。通常直接设为NULL。
  • start_rtn:新创建线程从此函数开始运行。无参数是arg设为NULL即可。
  • arg:start_rtn函数的参数。无参数时设为NULL即可。有参数时输入参数的地址。当多于一个参数时应当使用结构体传入。(以下举例)

返回值:

成功返回0,否则返回错误码。

简单的使用

#include <pthread.h>
#include <iostream>
#include <string>
using namespace std;
pthread_t ntid;
 
void printids(const char *s){
	pid_t		pid;
	pthread_t	tid;
 
	pid = getpid();
	tid = pthread_self();
	printf("%s pid %lu tid %lu (0x%lx)\n", s, (unsigned long)pid,
	  (unsigned long)tid, (unsigned long)tid);
}
 
struct Param {
	int a;
	int b;
	int c;
};
 
 
void *thr_fn(void *arg) {
    cout << "----enter sub thread--------" << endl;
	Param tmp = *(Param *)arg;
	cout << "tmp.a=" << tmp.a << endl;
	cout << "tmp.b=" << tmp.b << endl;
	cout << "tmp.c=" << tmp.c << endl;
 
	printids("new thread: ");
	cout << "Change to C++ code!!" << endl;
    cout << "----exit from sub thread----" << endl;
	return((void *)0);
}
 
int main(void){
	int		err;
	int num = 123;
	Param param1;
	param1.a = 11;
	param1.b = 22;
	param1.c = 33;
    //通过结构体向线程函数传入多个参数
	err = pthread_create(&ntid, NULL, thr_fn, &param1);
 
	if (err != 0)
		err_exit(err, "can't create thread");
	printids("main thread:");
	sleep(1);
	exit(0);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值