This commit is contained in:
p-w-rs
2022-09-22 14:34:03 -05:00
parent c506ca8b3b
commit ed1585d26b
32 changed files with 253 additions and 52 deletions

View File

@@ -11,12 +11,14 @@
#include <stdlib.h>
#include <unistd.h>
int global_value = 0;
int global_value[5] = {0};
void* thread_routine()
void *thread_routine(void *arg)
{
for(int i = 0; i < 100000000; i++) {
global_value++;
int *idx = (int *)(arg);
for (int i = 0; i < 1000000; i++)
{
global_value[*idx]++;
}
return NULL;
}
@@ -25,21 +27,26 @@ 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) {
int args[5] = {0, 1, 2, 3, 4};
for (int i = 0; i < 5; i++)
{
if (pthread_create(&thr_id[i], NULL, thread_routine, (void *)&args[i]) == -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);
}
// Print out final value of global value
// 5 threads * 100000000 iterations - expected value is 500000000
printf("PARENT READS GLOBAL: %d\n", global_value);
for (int i = 0; i < 5; i++)
printf("PARENT READS GLOBAL: %d\n", global_value[i]);
// Return success
return 0;