2017-03-18 36 views
-1

我在linux中編寫的C程序創建了多個線程(在本例中爲8),並且每個線程都應該運行函數compute(),這將使全局變量「total」增加1000。該程序目前在這方面按預期工作,因爲它輸出的最終總數爲8000.使用多線程保護全局變量

當前線程執行計算函數並更改「總」變量的順序並不重要,但我想確保每個線程不會改變全局變量,直到它沒有被任何其他線程使用。

如果任何人都可以點我在正確的方向上,我應該如何實現POSIX信號來實現這一點,將不勝感激,因爲這面積/一般線程是新的我。

該程序的當前代碼如下。 非常感謝!

#include <stdio.h> 
#include <stdlib.h> 
#include <math.h> 
#include <pthread.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <semaphore.h> 

#define N 8 /* define the total number of processes we want */ 
/* Set global variable */ 
float total=0; 

/* compute function just does something. */ 
int compute() 
{ 
    int i; 
    float oldTotal =0, result =0; 

    /*for a large number of times just square root and square the arbitrary number 1000*/ 
    for (int i = 0; i < 2000000000; i++) //Arbitrary number to allow process to run for a while. 
     { 
     result = sqrt(1000.0)*sqrt(1000.0); 
     } 

    /*Print the result - should be no suprise*/ 
    printf("Result is %f\n", result); 

    /*We want to keep a running total in the global variable total*/ 
    oldTotal = total; 
    total = oldTotal + result; 

    /*Print the running total so far*/ 
    printf("Total is %f\n", total); 
    return(0); 
} 


void* thread_procedure(void* param) 
{ 

    int i = (int)param; 
    /* give a message about the proc ID */ 
    printf("Process Id for process %d is %d\n",i,getpid()); 
    /* call the function to do some computation. If we used sleep 
    The process would simply sleep. We do not want that */ 

    compute(); 

    return NULL; 
} 


int main() 
{ 
    int i, j; 
    sem_init(&mutex, 0, 1); //Initialise mutex 
    pthread_t thread[N]; //Array of threads, N number of processes  


    printf("\n"); /* bit of whitespace */ 
    /* We want to loop to create the required number of processes 
    Note carefully how only the child process is left to run */ 
    for(i=0;i<N;i++) 
    { 
     /* start new thread and catch it if it/one fails */ 
     j = pthread_create(&thread[i], NULL, &thread_procedure, (void*)i); 
     if (j) 
      { 
      printf("Error"); 
      exit(1); 
      } 
    } 


    /* joining with threads */ 
    for(i=0;i<N;i++) 
     { 
      pthread_join(thread[i], NULL); 
     } 

    sem_destroy(&mutex); 
    /* nothing else to do so end main function (and program) */ 
    return 0; 
} // end function: main 
+1

[** Mut ** ual ** Ex ** clusion](http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_lock.html) – StoryTeller

+0

https://computing.llnl.gov/tutorials/pthreads /#Mutexes – user5159806

回答

0

如果我可以建議使用並行線程mutex也達到互斥共享變量的,下面的例子中完成。你試圖完成的事情可能會更快。

#include <pthread.h> 

//Shared global variable 
float total = 0; 

//Shared lock 
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; 

//some thread function that adds 1,000 to total one thread at a time 
void *compute(){ 

    //If no thread is using the lock, acquire lock and add 1,000 to total. The lock prevents other threads from executing this piece of code during a context switch. 
    pthread_mutex_lock(&lock); 
    total += 1000; 
    //Release lock 
    pthread_mutex_unlock(&lock); 

    return NULL; 

} 

這樣,如果線程T1執行計算功能和鎖是免費的,它會獲取鎖,增加總,然後釋放鎖。如果線程T2調用計算,而T1有鎖,T2將不能繼續超出代碼中的該點,並且將等待,直到鎖定資源被釋放T1。因此它保護了全球變量;當一個線程持有鎖時,希望改變共享變量的線程無法同時進行。

+0

謝謝,我用這個解決方案去了! – Ryan

0

聽起來像是你需要使用互斥鎖或信號量的