I'm brand new to pthreads, and I'm trying to understand what can be done to avoid problems when using simultaneous threads to write to the same global variables. Here's the simplest possible example:
pthread_t tid1, tid2 ;
int sum = 0 ;
void process()
{
for (int i ; i<100; i++)
sum += 1 ;
}
int main()
{
pthread_create(&tid1, NULL, (void *) process, NULL ) ;
pthread_create(&tid2, NULL, (void *) process, NULL ) ;
pthread_join(tid1, NULL) ;
pthread_join(tid2, NULL) ;
printf("Sum = %d\n", sum) ;
}
When I execute this code, it sometimes prints 200 and sometimes prints 100, implying in the latter case, I assume, that both threads were trying to write to 'sum' at exactly the same time, and one thread got blocked.
In my real world application, 'sum' might be a large array, and one thread might be trying to update one element while another is usually trying to update a different element of the same array.
What is the simplest/cleanest way to ensure that all intended read/write operations on a global variable or array succeed or at least to verify whether the operation succceeded? It isn't necessary to preserve the order of operation.
转载于:https://stackoverflow.com/questions/53148257/avoiding-memory-collisions-with-pthreads