[英]How do I prove that I need a mutex lock in this code?
我有一個非常簡單的多線程程序,我正在讀取一堆數字並最終將它們添加到全局sum
中。 我在每個線程中使用local_sum
變量,然后將其添加到全局sum
。 代碼在最后給出。
問題是——我需要在thread_runner
函數中鎖定這行代碼嗎?
sum += local_sum;
我很確定我確實需要鎖定它,但是無論如何程序總是會給出正確的結果。 如果我確實需要鎖,我如何證明這個實現是錯誤的?
注意:我在這里只對作為同步原語的互斥鎖感興趣。 也請忽略我沒有檢查返回值。
代碼:
#include <assert.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void *thread_runner(void *index);
// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
long array[100000000];
long sum = 0;
int main() {
/* Insert values in the array */
long i = 0;
for (i = 0; i < 100000000; i++) {
array[i] = i+1;
}
/* Declare thread variables */
pthread_t t1, t2, t3, t4;
int index1 = 0;
int index2 = 25000000;
int index3 = 50000000;
int index4 = 75000000;
/* Create 4 threads */
int rc = pthread_create(&t1, NULL, thread_runner, &index1);
rc = pthread_create(&t2, NULL, thread_runner, &index2);
rc = pthread_create(&t3, NULL, thread_runner, &index3);
rc = pthread_create(&t4, NULL, thread_runner, &index4);
/* Wait for threads to complete */
rc = pthread_join(t1, NULL);
rc = pthread_join(t2, NULL);
rc = pthread_join(t3, NULL);
rc = pthread_join(t4, NULL);
printf("Sum: %ld\n", sum);
return 0;
}
void *thread_runner(void *index) {
int i = 0;
int i_index = *((int*)index);
long local_sum = 0;
for (i = i_index; i < i_index+25000000; i++) {
local_sum += array[i];
}
// Do i need to lock the following statement ?
sum += local_sum;
}
我如何證明這個實現是錯誤的?
你指向行sum += local_sum
,你說,“看,線程在沒有任何鎖定和任何其他形式的同步的情況下訪問同一個共享變量,”然后你指向語言規范中的部分或者你指向給其他一些合適的權威機構說“……未定義的行為”。
數據競爭之所以糟糕,是因為它們是不可預測的。 你不能指望一個包含數據競爭的程序給出正確的答案,你也不能指望它給出錯誤的答案。 您不能依賴測試來發現數據競爭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.