C++(24)-多線程-POSIX(2)-兩個線程操作同一個全局變量


兩個線程要操作一個全局變量時,會發生什么。
一個線程:   完成20次+1
另一個線程:完成20次+1
結果應該是 :  40
但實際值卻是:20
為什么?當 thread_function() 將 j 的值寫回 myglobal 時, 就覆蓋了主線程所做的修改。
上代碼:
 

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

// 
int myglobal;
 void *thread_function(void *arg) 
 {
     int i,j;
     for ( i=0; i<20; i++)
    {
        j=myglobal;
        j=j+1;
        printf(".");
        fflush(stdout);
        sleep(1);
        myglobal=j;
  }
  return NULL;
}
int main(void)
{
  pthread_t mythread;
  int i;
  if ( pthread_create( &mythread, NULL, thread_function, NULL) ) 
  {
    printf("error creating thread.");
    abort();
  }
    
  for ( i=0; i<20; i++) 
  {
    myglobal=myglobal+1;
    printf("o");
    fflush(stdout);
    sleep(1);
  }
  if ( pthread_join ( mythread, NULL ) )
  {
    printf("error joining thread.");
    abort();
  }
  printf("\nmyglobal equals %d\n",myglobal);
  exit(0);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM