Ale*_*sen 4 c concurrency mutex pthreads
我是并发编程的新手,所以要好.我有一个基本的顺序程序(用于家庭作业),我试图把它变成一个多线程程序.我不确定我的第二个共享变量是否需要锁定.线程应修改我的变量但从不读它们.应该读取的唯一时间是在生成所有线程的循环完成分发键之后.
#define ARRAYSIZE 50000
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/time.h>
void binary_search(int *array, int key, int min, int max);
int count = 0; // count of intersections
int l_array[ARRAYSIZE * 2]; //array to check for intersection
int main(void)
{
int r_array[ARRAYSIZE]; //array of keys
int ix = 0;
struct timeval start, stop;
double elapsed;
for(ix = 0; ix < ARRAYSIZE; ix++)
{
r_array[ix] = ix;
}
for(ix = 0; ix < ARRAYSIZE * 2; ix++)
{
l_array[ix] = ix + 500;
}
gettimeofday(&start, NULL);
for(ix = 0; ix < ARRAYSIZE; ix++)
{
//this is where I will spawn off separate threads
binary_search(l_array, r_array[ix], 0, ARRAYSIZE * 2);
}
//wait for all threads to finish computation, then proceed.
fprintf(stderr, "%d\n", count);
gettimeofday(&stop, NULL);
elapsed = ((stop.tv_sec - start.tv_sec) * 1000000+(stop.tv_usec-start.tv_usec))/1000000.0;
printf("time taken is %f seconds\n", elapsed);
return 0;
}
void binary_search(int *array, int key, int min, int max)
{
int mid = 0;
if (max < min) return;
else
{
mid = (min + max) / 2;
if (array[mid] > key) return binary_search(array, key, min, mid - 1);
else if (array[mid] < key) return binary_search(array, key, mid + 1, max);
else
{
//this is where I'm not sure if I need a lock or not
count++;
return;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如您所料,count++;需要同步.这实际上不是你应该试图"逃避"不做的事情.第二个线程迟早会在第一个线程读取它之后但在它递增之前读取计数.然后你会错过一个计数.无法预测它会发生的频率.它可能发生在蓝色月亮或每秒数千次.
实际上,您编写的代码会读取和修改变量.如果您要查看为类似行生成的机器代码
count++
Run Code Online (Sandbox Code Playgroud)
你会看到它包含类似的内容
fetch count into register
increment register
store count
Run Code Online (Sandbox Code Playgroud)
所以是的,你应该在那里使用互斥锁.(即使你没有这样做也能逃脱,为什么不抓住机会练习?)