在C中终止一个线程

Vis*_*hal 6 c multithreading pthreads

我有一个调用线程的C程序.

iret1 = pthread_create( &thread1, NULL, readdata, NULL);
iret2 = pthread_create( &thread2, NULL, timer_func, NULL);
pthread_join(thread2, NULL);
Run Code Online (Sandbox Code Playgroud)

线程2在执行某些功能后返回,之后我想停止执行线程1.我应该怎么做?

Ant*_*tti 10

您可以使用pthread_cancel以下命令停止线程:

pthread_cancel(thread1);
Run Code Online (Sandbox Code Playgroud)

并在readdata:

/* call this when you are not ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
...
/* call this when you are ready to cancel the thread */
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参见pthread_cancel手册页 - 其中包含一个示例.

如果您不想使用pthread_cancel,则可以使用由主线程设置并由线程1读取的全局标志.此外,您可以使用任何IPC方法,例如在线程之间建立管道.