sttuff
This commit is contained in:
@@ -1,21 +1,22 @@
|
||||
/*
|
||||
* pthreads_race_atomic.c - Uses an atomic add instruction to prevent
|
||||
* the race condition that can happen when
|
||||
* multiple threads modify a global value at the
|
||||
* multiple threads modify a global value at the
|
||||
* same time.
|
||||
*/
|
||||
|
||||
#include <pthread.h>
|
||||
#include <stdatomic.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
atomic_int global_value = 0;
|
||||
|
||||
void* thread_routine()
|
||||
void *thread_routine()
|
||||
{
|
||||
for(int i = 0; i < 100000000; i++) {
|
||||
for (int i = 0; i < 1000000; i++)
|
||||
{
|
||||
atomic_fetch_add(&global_value, 1);
|
||||
}
|
||||
return NULL;
|
||||
@@ -25,15 +26,18 @@ int main()
|
||||
{
|
||||
// Create 5 threads
|
||||
pthread_t thr_id[5];
|
||||
for(int i = 0; i < 5; i++) {
|
||||
if(pthread_create(&thr_id[i], NULL, thread_routine, NULL) == -1) {
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
if (pthread_create(&thr_id[i], NULL, thread_routine, NULL) == -1)
|
||||
{
|
||||
printf("COULD NOT CREATE A THREAD\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
}
|
||||
|
||||
// Wait for all threads to finish
|
||||
for(int i = 0; i < 5; i++) {
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
pthread_join(thr_id[i], NULL);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user