简体   繁体   English

pthread中的共享变量

[英]Shared Variable in pthread

#include<iostream>
#include<pthread.h>
#include<chrono>

struct Arg1{
    int x,y;
};
void * process(void * threadarg){
    int x,y;
    Arg1 * myArg1;
    myArg1 = (Arg1 *) threadarg;
    x = myArg1->x;
    y=myArg1->y;
    int i=0;
    while(i<500){
        x+=1;
        y+=2;
        i++;
    }
    myArg1->x=x;
    myArg1->y=y;
    pthread_exit(NULL);
}
using namespace std;

int main(){
    int x = 0;
    int y = 0;
    int n;
    cin>>n;
    Arg1 sharedObj;
    sharedObj.x=x;
    sharedObj.y=y;
    auto start = chrono::high_resolution_clock::now();
    pthread_t *threads = new pthread_t[n];
    for(int i=0;i<n;++i){
        pthread_create(&threads[i],NULL,process,(void *)&sharedObj);
    }
    for(int i=0;i<n;++i){
        pthread_join(threads[i],NULL);
    }

    cout<<sharedObj.x<<" "<<sharedObj.y<<"\n";
    auto stop = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::microseconds>(stop-start);
    cout<<duration.count()<<"\n";
}

I wrote this code to see if using shared variables cause problems in the result.我编写了这段代码来查看使用共享变量是否会导致结果出现问题。

What it does is this- It first asks the user for number of threads n .它的作用是 - 它首先询问用户线程数n Each thread increments shared variables x and y by 1 and 2 respectively.每个线程将共享变量 x 和 y 分别增加 1 和 2。 Variables are shared via the use of the same struct object.通过使用相同的结构 object 来共享变量。 In the end I print the values of x and y from the struct object.最后,我从结构 object 中打印 x 和 y 的值。

I saw that for a small while loop in the function process , I am able to get correct results, regardless the number of threads n.我在 function process中看到了一个小的 while 循环,无论线程数 n 多少,我都能得到正确的结果。 However, for large values, about 5000, I get wrong results sometimes.但是,对于较大的值,大约 5000,我有时会得到错误的结果。

Also, the time of execution increases with the number of threads, and I don't understand whether this is because of improper multithreading or because of overhead in creating more number of threads.此外,执行时间随着线程数的增加而增加,我不明白这是因为不正确的多线程还是因为创建更多线程的开销。

Thanks for any help in advance.感谢您提前提供任何帮助。

Unless we use a mutex or some method to ensure atomicity of write, we can not guarantee that we would get a correct value in pthreaded applications.除非我们使用互斥锁或某种方法来确保写入的原子性,否则我们不能保证我们会在 pthread 应用程序中获得正确的值。 This is because, simultaneous writes can lead to a race condition, with only one of the write affecting the shared variable.这是因为,同时写入会导致竞争条件,只有一个写入会影响共享变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM