linux线程创建++类函数,Linux线程创建

以前都是Windows编程,一直说看看Linux下的线程编程,有空了,回顾一下吧。

头文件

Linux下线程相关函数都在头文件 中,该头文件中的相关函数在专门的线程库libpthread中,编译的时候需要加上 -lpthread 选项

一些函数

pthread_self获取当前线程

pthread_self(void) //返回类型为: pthread_t

pthread_equal判断线程是否相同相等

pthread_equal(pthread_t , pthread_t) // 返回int,非0则相等

pthread_create创建线程

int pthread_create(pthread_t* pthread, const pthread_attr_t*, void* (*start_routine )(void*), void* arg )

成功返回0,错误号表示失败

pthread_t 类型变量的thread,线程的标识

pthread_attr 线程属性设置,控制线程与程序其他部分交互方式,常设为NULL,默认线程属性

start_routine 线程函数指针,是线程要执行的代码,参数为void(*)

arg 传递给start_routine的参数(如果需要传递多个参数,常设为一个结构体,将结构体指针传递给线程)

pthread_cancle线程终止

int pthread_cancle(pthread_t thread)

成功返回0

pthread_join 等待线程终止

int pthread_join(pthread_t thread, void **ptr)

成功返回0,否则失败

ptr 为返回码,常设为 NULL

代码

用gcc编译的话,得加上 -lpthread -lstdc++

#include

#include

#include

#include

#include //strerror

#include

using namespace std;

static int number = 0;

void printids(const char * s)

{

pid_t pid;

pthread_t tid;

pid = getpid(); //获取进程id

tid = pthread_self(); //获取线程id

cout << s << " pid " << (unsigned long)pid << " tid " << (unsigned long)tid << endl;

}

void *run(void* nu) //线程函数,参数得为void*

{

int num = *((int*)nu);

printids("run1 thread:");

cout << "get num from param in run1 " << num << endl;

return ((void *)0); //void* 类型的空指针

}

void *run2(void*)

{

for(int i = 0; i < 3; ++i)

{

cout << "run2 thread number : " << ++number << endl;

sleep(1);

}

return NULL;

}

int main(int argc, char* argv[])

{

//pthread_t pthread_self();

/*pthread_t t1;

cout << pthread_self() << endl;

cout << (pthread_t)t1 << endl;*/

pthread_t ntid, tid2; //线程标识

int num=5;

int err;

//创建第一个线程,线程函数run,线程函数的参数为num.

err = pthread_create(&ntid, NULL, run,(void*)(&num));

sleep(1);

if(0 != err)

{

cout << "cannot create thread: " << strerror(err) << endl;

exit(1);

}

//创建第二个线程,线程函数为run2, 函数没有参数

pthread_create(&tid2, NULL, run2, NULL);

//加上join,主线程main 会让线程2,也就是run2函数执行完毕后,才会输出最后一句

pthread_join(tid2, NULL); //如果不加上pthread_join,可能会看不到run2函数执行,main线程先执行完毕

cout << "main thread number : " << number << endl;

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值