[英]How to make global variables that are contained in a different class thread safe in c
我必須歸檔一個名為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線程中包含的全局變量安全?
通常,最好避免使用全局變量,除非您絕對不能做其他事情。 使用pthreads時,線程安全取決於函數。 並非所有的pthreads函數在共享數據上都是“線程安全的”。 您還可以使用線程互斥鎖來保護共享數據。 這些本質上是對共享數據的一種鎖,僅允許一個線程一次訪問它。 本文對此進行了很好的介紹: https : //randu.org/tutorials/threads/#protect
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.