我正在尝试了解锁在多线程中的工作原理。当我执行以下代码而没有锁定时,即使将变量sum声明为全局变量并且多个线程正在更新它,它也能正常工作。任何人都可以解释为什么这里的线程在没有锁的共享变量上工作得很好?
以下是代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NTHREADS 100
#define ARRAYSIZE 1000000
#define ITERATIONS ARRAYSIZE / NTHREADS
double sum=0.0, a[ARRAYSIZE];
pthread_mutex_t sum_mutex;
void *do_work(void *tid)
{
int i, start, *mytid, end;
double mysum=0.0;
/* Initialize my part of the global array and keep local sum */
mytid = (int *) tid;
start = (*mytid * ITERATIONS);
end = start + ITERATIONS;
printf ("Thread %d doing iterations %d to %d\n",*mytid,start,end-1);
for (i=start; i < end ; i++) {
a[i] = i * 1.0;
mysum = mysum + a[i];
}
/* Lock the mutex and update the global sum, then exit */
//pthread_mutex_lock (&sum_mutex); //here I tried not to use locks
sum = sum + mysum;
//pthread_mutex_unlock (&sum_mutex);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
int i, start, tids[NTHREADS];
pthread_t threads[NTHREADS];
pthread_attr_t attr;
/* Pthreads setup: initialize mutex and explicitly create threads in a
joinable state (for portability). Pass each thread its loop offset */
pthread_mutex_init(&sum_mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<NTHREADS; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
}
/* Wait for all threads to complete then print global sum */
for (i=0; i<NTHREADS; i++) {
pthread_join(threads[i], NULL);
}
printf ("Done. Sum= %e \n", sum);
sum=0.0;
for (i=0;i<ARRAYSIZE;i++){
a[i] = i*1.0;
sum = sum + a[i]; }
printf("Check Sum= %e\n",sum);
/* Clean up and exit */
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&sum_mutex);
pthread_exit (NULL);
}
无论有没有锁,我都得到了同样的答案!
Done. Sum= 4.999995e+11
Check Sum= 4.999995e+11
更新:user3386109建议的更改
for (i=start; i < end ; i++) {
a[i] = i * 1.0;
//pthread_mutex_lock (&sum_mutex);
sum = sum + a[i];
//pthread_mutex_lock (&sum_mutex);
}
效果:
Done. Sum= 3.878172e+11
Check Sum= 4.999995e+11
答案 0 :(得分:6)
当您有两个或多个线程访问共享资源时,互斥锁用于防止不良情况下的竞争条件。当多个线程访问共享变量sum
时,会发生竞争条件,例如代码中的竞争条件。有时,对共享变量的访问将以结果不正确的方式进行交错,有时结果将是正确的。
例如假设您有两个线程,线程A和线程B都将共享值sum
加1,从5开始。如果线程A读取sum
然后线程B读取sum
然后线程A写入一个新值,然后线程B写一个新值你将得到一个不正确的结果,6而不是7.但是它也可能比线程A读取然后写一个值(具体而言6)然后线程B读取并写入一个值(特别是7),然后得到正确的结果。关键是一些操作的交错导致正确的值,并且一些交错导致不正确的值。互斥锁的作用是强制交错始终正确。