首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

子线程怎么不阻塞主线程

2012-08-01 
子线程如何不阻塞主线程我写了个子函数,子函数目的是创建一个新线程pthread_create()(或者win32的Createth

子线程如何不阻塞主线程
我写了个子函数,子函数目的是创建一个新线程pthread_create()(或者win32的Createthread());然后转去执行a任务;为了让a任务能够准确结束,子函数又添加了pthread_join()(或者win32的WaitForSingleObject());可是当主函数main()调用该子函数时主函数剩下的执行语句就会被阻塞了,直到该子函数任务结束退出才可继续执行。可我想主函数不被阻塞,怎么办呢? 还有什么更好的办法么 ?(linux下面和win32的解答都能说下最好了)

[解决办法]
如果主线程不需要等待你那个子函数里调用的子线程全部结束,那个子函数里的线程可以以分离状态运行,线程调用pthread_detach(pthread_self())或者

C/C++ code
pthread_attr_t attr;pthread_attr_init(&attr);pthread_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_create(&tid, &attr, routine, NULL);
[解决办法]
子函数中使用了pthread_join()就自然阻塞了,你要想不阻塞,只有把pthread_join放到函数外面去了。
小菜愚见,仅供参考。
[解决办法]
detach或者轮询检测标记后join。
[解决办法]
给你借鉴下:
C/C++ code
#include <stdio.h> #include <Windows.h>#include <time.h> #include <process.h>  volatile LONG g_bCon;  void printThread(void* pArg) {int i = 0; while(g_bCon) { printf("%d\n",i++); } }void countThread(void* pArg) { _beginthread(printThread,0,0); Sleep(1000); g_bCon = 0; }int main(int argc, char* argv[]) { g_bCon = 1; _beginthread(countThread,0,0); system("pause"); /*这里必须要暂停下*/ return 0; }
[解决办法]
windows中在主线程退出前必须要用WaitForSingleObject(),不然子线程也会跟着退出
[解决办法]
用消息机制
[解决办法]
子函数又添加了pthread_join()
这个就会让子函数阻塞等待了,如果想不阻塞等待的话就不能用这个函数了,可以在子函数创建线程时,设置成分离(detach)状态, pthread_detach(thread_id),让线程自己管理自己的后事,自动释放资源等。
或者创建的线程里面  pthread_detach(pthread_self())

热点排行