gpt4 book ai didi

c - 线程并发

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:28 25 4
gpt4 key购买 nike

这个程序模仿网页计数器,计算网页的访问次数。我只想问这段代码有什么问题以及为什么它的输出不同计数器值小于访问次数

#include <stdio.h> 
#include <unistd.h>
#include <pthread.h>

// repeat 100 times to mimic 100 random visits to the page
#define RPT 100

//web page visit counter int cnt=0;
void* counter() {
int cntLocalCopy;
float r;

cntLocalCopy = cnt;

// mimicking the work of the sever in serving the page to the browser
r = rand() % 2000;
usleep(r);

cnt = cntLocalCopy + 1;

}

int main () {
int i;
float r;
pthread_t tid[RPT];

// seed the random number sequence
srand(time(NULL));


for (i=0; i<RPT; i++) {

// mimicking the random access to the web page
r = rand() % 2000; usleep(r);

// a thread to respond to a connect from a browser
pthread_create (&tid[i], NULL, &counter, NULL);

}


// Wait till threads complete.
for (i=0; i<RPT; i++) {

pthread_join(tid[i], NULL);

}

// print out the counter value and the number of mimicked visits
// the 2 values should be the same if the program is written
// properly

printf ("cnt=%d, repeat=%d\n", cnt, RPT);

}

最佳答案

这根本不是一个好主意:

cntLocalCopy = cnt;
... sleep
cnt = cntLocalCopy + 1;

由于 cnt 的旧值是在休眠前读取的,因此 2 个或更多线程并发读取 cnt 的旧值然后休眠的可能性非常高。因为 sleep 持续时间是随机的,这甚至可能会减少计数器。

即使你重新排列代码如下

... sleep
cntLocalCopy = cnt;
cnt = cntLocalCopy + 1;

甚至

++cnt;

仍然需要内存屏障,因为 2 个线程可以同时读取相同 cnt 的旧值,它们都会将其递增到相同 新值,而不是同时递增值。有一个look here举个例子。

关于c - 线程并发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22703971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com