c - 不确定我是否需要互斥锁

标签 c concurrency pthreads mutex

我是并发编程的新手,所以请多多关照。我有一个基本的顺序程序(用于家庭作业),我正试图将它变成一个多线程程序。我不确定我的第二个共享变量是否需要锁。线程应该修改我的变量但从不读取它们。唯一应该读取的时间计数是在生成我的所有线程的循环完成分发 key 之后。

#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;
      }
    }
}

最佳答案

如您所料,count++; 需要同步。这实际上不是您应该尝试“逃避”不做的事情。迟早,第二个线程将在第一个线程读取计数之后但在递增计数之前读取计数。那么你会错过一个计数。无法预测它发生的频率。它可能发生在极少数情况下,也可能每秒发生数千次。

关于c - 不确定我是否需要互斥锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13096598/

相关文章:

node.js - 将函数作为单独的 node.js 进程运行?

c - 在 pthread 中获取错误的 ID 值

c - 循环 strcmp 时出错

c++ - 什么时候可以安全地从compare_exchange中删除memory_order_acquire或memory_order_release?

c - 是否有可能以某种方式使该程序崩溃?

Go,将数据传递到 channel

c - 使用互斥体的 Pthread 同步未正确同步单词

c - 从主进程的线程启动子进程是否合适

c - C语言中的简单链表程序

c - 为什么 clang 和 gcc 会产生次优输出(复制结构)以将指针传递给按值结构 arg?