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)

 

简单的线程使用实例。

posted on 2013-10-09 22:29  笔记吧... 可能只有自己看得懂  阅读(251)  评论(0编辑  收藏  举报