多线程输出每次都会改变

时间:2015-12-12 16:13:59

标签: c++ multithreading

我是多线程概念的新手。我编写了一些小代码来理解多线程是如何工作的。每次运行时,它都会显示不同的输出。 请帮我理解我的错误。

class Worker {
    private:
        pthread_t thread[5];
        bool stop;
        pthread_mutex_t mutex;
          int tid;
          double stuff;       
        double shared_x;

    public:
        Worker() 
        {
            stop = false;
            if (pthread_mutex_init(&mutex, NULL) != 0)
            {
              cout<<"mutex init failed";
            }

         }
        ~Worker() {
            pthread_mutex_destroy(&mutex);

        }

        void *run(){
            cout<<"tid   "<<tid<<endl;
            pthread_mutex_lock(&mutex);
           cout<<"stuff before   "<<this->stuff<<endl;
           shared_x+=this->stuff;
           cout<<"stuff After     "<<this->stuff<<endl;
           cout<<"shared_x    "<<shared_x<<endl;
           pthread_mutex_unlock(&mutex);
            pthread_exit(NULL);
        }
        void join(){
            void *status;
            for(int i=0;i<5;i++)
            {
                         pthread_join(thread[i],NULL);
            }
        }
        static void *run_helper(void* context){
            return ((Worker *)context)->run();
        }
        void stop_thread(){
            stop = true;

        }
        void start_thread(Worker worker){

             for(int i=0;i<5;i++)
            {
                tid=i;
                stuff=i+10;
                int status = pthread_create(&thread[i],NULL,run_helper,this);    
            }
        }
};
    int main(){
    Worker worker;
    worker.start_thread(worker);
    worker.join();
    cout<<"Thread exit"<<endl;
    return 0;
}

输出1

   tid   0

  stuff before   10

stuff After     10

shared_x    10

tid   2

stuff before   12

stuff After     12

shared_x    22

tid   2

stuff before   12

stuff After     12

shared_x    34

tid   3

stuff before   13

stuff After     13

shared_x    47

tid   4

stuff before   14

stuff After     14

shared_x    61

Thread exit


<b> output2</b>

tid   0

stuff before   10

stuff After     10

shared_x    10

tid   2

stuff before   12

stuff After     12

shared_x    22

tid   3

stuff before   13

stuff After     13

shared_x    35

tid   4

stuff before   14

stuff After     14

shared_x    49

tid   4

stuff before   14

stuff After     14

shared_x    63

Thread exit

1 个答案:

答案 0 :(得分:0)

由于您同时运行线程和for循环,因此无法确定何时更改或输出tidstuff。你在互斥体中唯一拥有的就是求和。

由于它们位于给予每个线程的单个对象内部,因此它们将具有它们恰好在该点处具有的任何值。您可能希望每个线程都有自己的状态对象,然后您就不会遇到此问题。