简体   繁体   English

pthreads / C:使用标志优雅地终止其他线程

[英]pthreads / C : using a flag to gracefully terminate other threads

Is it safe (and a good practice) to use a flag which is written by only one thread and only read by other threads to gracefully terminate threads?使用仅由一个线程写入并且仅由其他线程读取的标志来优雅地终止线程是否安全(并且是一种好习惯)?

Consider the following code:考虑以下代码:

#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;
}

The variable "run" is used to tell threads t1 and t2 to terminate.变量“run”用于告诉线程 t1 和 t2 终止。 Is that fine or I should use a mutex / memory barriers?那很好还是我应该使用互斥体/memory 屏障? And why?为什么? I don't care if it takes a couple more loop cycles before the threads exit, but I don't want them to run forever.我不在乎在线程退出之前是否需要更多的循环周期,但我不希望它们永远运行。 I don't want to use pthread_cancel() as I want the threads to quit only after they complete a cycle of their main loop.我不想使用 pthread_cancel() 因为我希望线程仅在完成主循环的一个周期后才退出。

thanks谢谢

The safest approach is to make run atomic.最安全的方法是使run原子化。 Modern C does support atomic types.现代 C 确实支持原子类型。

You need a mutex to protect the shared variable because that's what the pthreads standard says.您需要一个互斥锁来保护共享变量,因为这就是 pthreads 标准所说的。 You can't assume that the worst way it will fail is taking "a couple more loop cycles before the threads exit".您不能假设它失败的最坏方式是“在线程退出之前再多循环几个循环”。

It can crash.它可能会崩溃。 It can fail to ever stop.它可能无法停止。 Anything can happen.任何事情都有可能发生。

If your platform supports some kind of atomic type or atomic operations, you can use that.如果您的平台支持某种原子类型或原子操作,您可以使用它。

Some people think using volatile is acceptable only for a "shutdown" flag.有些人认为使用volatile适用于“关闭”标志。 Be aware that this is very platform-specific and may or may not work for you.请注意,这是非常特定于平台的,可能适合您,也可能不适合您。 I don't consider it acceptable on platforms that have better options, that is, on all modern platforms.我不认为它在有更好选择的平台上是可以接受的,也就是说,在所有现代平台上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM