linux下的线程学习(一)

线程标识

#include<pthread.h>

int pthread_equal(    //用于比较两个线程是否相等

pthread_t tid1, //线程id=tid1

pthread_t tid2);//线程id=tid2

 

pthread_t pthread_self(void);    //用于返回自身的线程id

 

线程创建

#include<pthread.h>

int pthread_create(   //用于创建线程

pthread_t *restrict tidp, //线程id

const pthread_attr_t *restrict attr,//属性

void *(*start_rin)(void*),//线程开始函数

void *restrict arg);//函数的传入参数【如果想参入多个数据,用结构体】

 

实例

 1 #include <iostream>
 2 #include <pthread.h>
 3 
 4 pthread_t ntid;
 5 
 6 void printids(const char *s) {
 7 
 8   pid_t pid;
 9   pthread_t tid;
10 
11   pid = getpid();
12   tid = pthread_self();
13   printf("%s pid %u tid %u (0x%x)\n", s, (unsigned int)pid, 
14       (unsigned int)tid, (unsigned int)tid);
15 }
16 
17 void* thr_fn(void *arg) {
18   
19   printids("new thread: ");
20   return ((void*)0);
21 }
22 
23 int main() {
24   
25   int err;
26   err = pthread_create(&ntid, NULL, thr_fn, NULL);
27   if(err != 0) {
28     printf("can't create thread: %s\n", strerror(err));
29   }
30   printids("main thread: ");
31   sleep(1);
32   return 0;
33 }

 

g++ thread.cpp -o thread -lpthread

./thread

main thread:  pid 30466 tid 3892546496 (0xe8038bc0)
new thread:  pid 30466 tid 1109510464 (0x4221c940)

 

简单的线程使用实例。

转载于:https://www.cnblogs.com/xuxu8511/p/3360272.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值