#ifdef WIN32 #include <windows.h> #define SLEEP(ms) Sleep(ms) #else if defined(LINUX) #include <stdio.h> #define SLEEP(ms) sleep(ms) #endif #include <cassert> #include <pthread.h> static int s_nThreadResult = 0; void * theThread(void * param) { int count = 0; while (count < 20) { printf("[Child] looping\n"); pthread_testcancel(); SLEEP(1); count ++; } s_nThreadResult = 1; pthread_exit(&s_nThreadResult); return NULL; } int main(int argc, char * argv[]) { int rc = 0; pthread_t tid; rc = pthread_create(&tid, NULL, &theThread, NULL); assert(rc == 0 && "pthread_create"); SLEEP(3); // 若启用下面代码,则子线程提前返回 //rc = pthread_cancel(tid); assert(rc == 0 && "pthread_cancel"); // 阻塞自己,等待子线程返回 void * status = NULL; rc = pthread_join(tid, &status); assert(rc == 0 && "pthread_join", rc); // 若子线程是被取消从而结束的,则无返回值 if (status != PTHREAD_CANCELED && status != NULL) { printf("Returned value from thread: %d\n", *(int *)status); } return 0; }
POSIX线程的创建和取消(3)
内容版权声明:除非注明,否则皆为本站原创文章。