[問題] multi-thread 共用函數的問題

看板C_and_CPP作者 (總是很多心事)時間10年前 (2016/01/21 11:22), 編輯推噓6(6012)
留言18則, 10人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) Linux 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) gcc pthread 問題(Question): 一般在 multithread 共用函數時會Lock, 但請教在什麼情況下可以不用 Lock? 或者說在什麼情況下一定要 Lock? 寫了一個 sample 不 Lock 執行不會有錯誤 程式碼(Code):(請善用置底文網頁, 記得排版) #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> pthread_t thread_id_1 = 0; pthread_t thread_id_2 = 0; int sum = 0; void common(int x) { sum += x; } void thread_func_1() { int i; for (i = 0; i < 100; i++) { common(-1); } printf("thread1 end\n"); } void thread_func_2() { int i; for (i = 0; i < 100; i++) { common(1); } printf("thread2 end\n"); } void thread_create_1() { int rc = 0; rc = pthread_create(&thread_id_1, NULL, (void *) &thread_func_1, NULL); if (rc) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); return; } } void thread_create_2() { int rc = 0; rc = pthread_create(&thread_id_2, NULL, (void *) &thread_func_2, NULL); if (rc) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\n", rc); return; } } void thread_wait_1() { if (thread_id_1 != 0) { pthread_join(thread_id_1, NULL); printf("thread 1 stopped\n"); } } void thread_wait_2() { if (thread_id_2 != 0) { pthread_join(thread_id_2, NULL); printf("thread 2 stopped\n"); } } int main(void) { thread_create_1(); thread_create_2(); thread_wait_1(); thread_wait_2(); printf("sum = %d\n", sum); return EXIT_SUCCESS; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.249.106.112 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1453346562.A.A83.html

01/21 12:05, , 1F
等碰到BUG時就是Lock的時機!!!
01/21 12:05, 1F

01/21 12:09, , 2F
當多個thread對同個object執行任何改變狀態的操作時
01/21 12:09, 2F

01/21 12:10, , 3F
例如說sum就應該要是atomic才行
01/21 12:10, 3F

01/21 12:12, , 4F
因為你這邊只是單純++--,所以不會有錯誤
01/21 12:12, 4F

01/21 12:13, , 5F
但你sum最後的值不一定是0
01/21 12:13, 5F

01/21 12:14, , 6F
順帶一提,C11與C++11都有thread支援,沒必要的話,不需
01/21 12:14, 6F

01/21 12:14, , 7F
使用pthread
01/21 12:14, 7F

01/21 12:18, , 8F
更正我第一句: 當多個thread"可能同時"對同個object
01/21 12:18, 8F

01/21 12:18, , 9F
執行任何改變狀態的操作時
01/21 12:18, 9F

01/21 12:27, , 10F
不是不爆只是時候未到
01/21 12:27, 10F

01/21 13:08, , 11F
推一樓
01/21 13:08, 11F

01/21 13:45, , 12F
基本上存取變更會遇到 但是要看他的值是不會
01/21 13:45, 12F

01/21 17:07, , 13F
執行一億次試試看啊
01/21 17:07, 13F

01/21 18:27, , 14F
即使只有一個thread寫入,只要有其它thread讀取
01/21 18:27, 14F

01/21 18:27, , 15F
都有很高的機會造成race condition
01/21 18:27, 15F

01/22 06:38, , 16F
推1F, 很低的機率遇到core dump時就會知道要lock了...XD
01/22 06:38, 16F

01/22 12:14, , 17F
C11的thread library有實作品了嗎?@@
01/22 12:14, 17F

01/24 17:00, , 18F
先去學完作業系統再回來寫
01/24 17:00, 18F
文章代碼(AID): #1Me4y2g3 (C_and_CPP)