当前位置: 技术问答>linux和unix
linux多线程优先顺序
来源: 互联网 发布时间:2017-04-06
本文导语: 本帖最后由 cyd411 于 2013-04-03 16:52:15 编辑 输出代码 this is main thread thread 2 start thread 2 push complete. cleanup: thread 2 second handler cleanup: thread 2 first handler thread 1 start thread 1 push complete. thread1 exit cod...
this is main thread
thread 2 start
thread 2 push complete.
cleanup: thread 2 second handler
cleanup: thread 2 first handler
thread 1 start
thread 1 push complete.
thread1 exit code 1
thread2 exit code 2
这里不明白了,为什么不是先输出
thread 1 start
thread 1 push complete
这个呢?下面我用pthread_join 等待线程1了,不是应该先输出thread 1 start 再输出线程2的相关打印吗? 为什么先输出的是2呢?
代码如下:
#include
#include
void *Clean(void *pArg)
{
printf("cleanup: %s n" ,((char *)pArg));
return (void *)0;
}
void *Thread1(void *pArg)
{
printf("thread 1 start n");
pthread_cleanup_push((void *)Clean, "thread 1 first handler");
pthread_cleanup_push((void *)Clean, "thread 1 second handler");
printf("thread 1 push complete. n");
if(pArg)
{
/* 这里使用的是return 返回 所以不会调用 pthread_cleanup_push 指定的Clean*/
return (void *)1;
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void *)1;
}
void *Thread2(void *pArg)
{
printf("thread 2 start n");
pthread_cleanup_push((void *)Clean, "thread 2 first handler");
pthread_cleanup_push((void *)Clean, "thread 2 second handler");
printf("thread 2 push complete. n");
if(pArg)
{
/*
void pthread_exit(void *rval_ptr)
功能:终止调用线程
rval_ptr:线程退出返回值的指针*/
pthread_exit((void *)2);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void *)2;
}
int main(void)
{
pthread_t tThreadID1, tThreadID2;
int iRst;
void *tRst;
printf("this is main threadn");
iRst = pthread_create(&tThreadID1, NULL, (void *)Thread1, (void *)1);
if(iRst!=0)
{
printf("create thread1 error .... n");
return -1;
}
iRst = pthread_create(&tThreadID2, NULL, (void *)Thread2, (void *)1);
if(iRst!=0)
{
printf("create thread2 error .... n");
return -1;
}
iRst = pthread_join(tThreadID1, &tRst);
if(iRst != 0)
{
printf("pthread_join thread1 error .... n");
return -1;
}
else
{
printf("thread1 exit code %d n", (int)tRst);
}
iRst = pthread_join(tThreadID2, &tRst);
if(iRst != 0)
{
printf("pthread_join thread2 error .... n");
return -1;
}
else
{
printf("thread2 exit code %d n", (int)tRst);
}
return 0;
}
|
pthread_join 不是你的那个作用 这个是表示主线程等待调用这个线程的函数退出
你要控制谁先打印 必须在线程函数里面做处理 线程同步机制 你学习下吧 条件变量啊 信号量等等 来挂载线程和触发线程
你要控制谁先打印 必须在线程函数里面做处理 线程同步机制 你学习下吧 条件变量啊 信号量等等 来挂载线程和触发线程