【问题标题】:How to make global variables that are contained in a different class thread safe in c如何使包含在不同类线程中的全局变量在c中安全
【发布时间】:2018-11-19 16:25:31
【问题描述】:

我必须归档一个名为 main.c 的文件和一个名为 disperse.c 的文件

disperse.c 创建线程来处理 main.c 中的负载,看起来像这样:

void *entry(void *arg) {  
    foo_function()  
}

void disperse() {  
    pthread_t thread;  
    pthread_create(&thread, NULL, entry, (void*) args);  
    pthread_join(thread, NULL);  
}

main.c 包含 foo_function() 并且该函数编辑全局变量。 有什么方法可以使 main.c 线程中包含的全局变量安全吗?

【问题讨论】:

标签: c multithreading thread-safety


【解决方案1】:

一般来说,最好避免使用全局变量,除非你绝对不能做你想做的事情。使用 pthreads,线程安全取决于函数。并非所有 pthreads 函数在共享数据上都是“线程安全的”。您还可以使用线程互斥锁来保护共享数据。这些本质上是对共享数据的一种锁定,一次只允许一个线程访问它。这篇文章对此做了很好的介绍:https://randu.org/tutorials/threads/#protect

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多