【发布时间】:2021-05-28 05:52:21
【问题描述】:
使用仅由一个线程编写并且仅由其他线程读取的标志来优雅地终止线程是否安全(并且是一种良好的做法)?
考虑以下代码:
#include <pthread.h>
#include <stdio.h>
static int run;
static pthread_t t1, t2;
static void *threadFunc(void *context)
{
puts("thread starting");
init();
while(run)
{
do_stuff();
}
clean_up();
puts("thread exiting");
return NULL;
}
int main(int argc, char **argv)
{
puts("program starting");
run = 1;
pthread_create(&t1, NULL, threadFunc, NULL);
pthread_create(&t2, NULL, threadFunc, NULL);
do_some_stuff();
run = 0;
pthread_join(t1, NULL);
pthread_join(t2, NULL);
puts("program exiting");
return 0;
}
变量“run”用于告诉线程 t1 和 t2 终止。那很好还是我应该使用互斥体/内存屏障?为什么? 我不在乎在线程退出之前是否需要更多的循环周期,但我不希望它们永远运行。 我不想使用 pthread_cancel(),因为我希望线程只有在完成主循环的一个循环后才退出。
谢谢
【问题讨论】:
标签: c multithreading pthreads