我在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
[** Mut ** ual ** Ex ** clusion](http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_mutex_lock.html) – StoryTeller
https://computing.llnl.gov/tutorials/pthreads /#Mutexes – user5159806