
void pthread_exit(void * rval_ptr)
当调用pthread_create()创建新线程后当前线程从pthread_create()返回继续往下执行,而新线程执行的代码由函数指针start_routine决定start_routine函数接受一个参数是由pthread_create()通过参数arg传递的,这个参数的类型是void *按什么类型解释由用户自己决定。中静态函数没有this指针(即在内存中静态函数和普通全局函数几乎没有什么区别),故可以匹配编译通过, 但是当线程函数要访问私有变量呢。巨晕,好嘛,你复习一下c或是c++指针那部分吧)就是线程要执行的代码,这里我们分别要执行tprocess1tprocess2就写成了上面的样子pthread exit,这里这个函数指针的类型定义是返回一个空类型指针,接收一个空类型指针参数的函数指针pthread exit,如果你的函数不是这个定义,那就可以直接转化一下就可以了。
int pthread_join (pthread_t tid, void **rval_ptr)
对于一个已上锁的互斥锁,若调用pthread_mutex_lock()函数再次加锁,将使调用线程阻塞,直到互斥锁被解锁.调用成功发那会0,失败返回-1.参数mutex是pthread_mutex_t数据类型的指针。这个例子线程启动后,主线程等待1秒,线程起来调用wait等在哪里,当主线程调用notify时,wait返回notify的参数”hello”,”world”,而notify返回wait的参数”hi”,”main thread”。唯一的参数是函数的返回代码,只要pthread_join中的第二个参数thread_return不是null,这个值将被传递给 thread_return.最后要说明的是,一个线程不能被多个线程等待,否则第一个接收到信号的线程成功返回,其余调用pthread_join的线程则返回错误代码esrch.。
一下程序在 开启的第奇数个线程的时候,会sleep 相应的秒数,运行时,主线程由于调用 pthread_join 阻塞,可以看到标准输出会卡。
1 #include <pthread.h>
2 #include <unistd.h>
3 #include <stdio.h>
4 struct args{
5 char name[10];
6 int exit_code;
7 };
8
9 void * thread_run(void *arg){

10 struct args* a = (struct args*)arg;
11 printf("%s run, id:%u", a->name, (unsigned int)(pthread_self())); // use arg to get the params;
12 if(a->exit_code % 2){
13sleep(a->exit_code); // make the thread sleep some second;
14printf("im thread %d, here sleep %d second!", a->exit_code, a->exit_code);
15 }
void pthread_exit(void *retval)。void pthread_exit (void *retval) 。void pthread_exit(void *value_ptr)。
17 }
18
19 int main(){
20 pthread_t tid[10]; //thread_ids
21 struct args a[10]; //thread_functions args
22 void *ec;//exit code
23 int i;

24 for(i = 0; i < 10; ++i){
25a[i].name[0] = ;
26sprintf(a[i].name, "thread_%d", i);
27a[i].exit_code = i;
28if(pthread_create(&tid[i], NULL, thread_run, (void *)(&a[i]))){ //call pthread_create to create a thread use arg[i]
29printf("error");
30return 0;
31}
32 }
33 for(i = 0; i < 10; ++i){
34pthread_join(tid[i], &ec);//wait for thread tid[i] stop;
35printf("%s exit code is:%d", a[i].name, (*(int*)ec));
36 }
37 return 0;

38 }
39
编译 :
g++ ./pthread_exit.cpp -lpthread -opthread_exit
结果:
thread_0 run, id:968255760
thread_2 run, id:951470352
thread_1 run, id:959863056
thread_3 run, id:943077648
thread_4 run, id:934684944
thread_5 run, id:926292240
thread_6 run, id:917899536
thread_7 run, id:909506832
thread_8 run, id:901114128

thread_9 run, id:892721424
thread_0 exit code is:0
im thread 1, here sleep 1 second!
thread_1 exit code is:1
thread_2 exit code is:2
im thread 3, here sleep 3 second!
thread_3 exit code is:3
thread_4 exit code is:4
im thread 5, here sleep 5 second!
thread_5 exit code is:5
thread_6 exit code is:6
im thread 7, here sleep 7 second!
thread_7 exit code is:7
thread_8 exit code is:8
im thread 9, here sleep 9 second!
thread_9 exit code is:9
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-109931-1.html
ear见面会#演好戏
质检总局连买个东西都不知道怎么买