Last active
April 24, 2019 07:16
-
-
Save parastuffs/a7818b1ff46de40b95949943fbd53c8b to your computer and use it in GitHub Desktop.
Multithreading with pthread
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* This needs to be compiled with the pthread library. | |
* Command line: gcc -lpthread multithread.c | |
* In CodeBlocks: in the project build options, go in the "Linker settings" tab | |
* and add -lpthread in the "Other linker options" area. | |
**/ | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
// Define a structure for the thread arguments | |
typedef struct Args Args; | |
struct Args { | |
int i; | |
}; | |
// Create a global variable | |
int g = 0; | |
// Create a global mutex | |
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; | |
// This function is the entry point of the thread | |
void *myThreadFun(Args *vargp) | |
{ | |
// Store the argument passed to this thread | |
Args *arg = vargp; | |
// Create a static variable | |
static int s = 0; | |
// Normal int variable | |
int n = 0; | |
++s; | |
pthread_mutex_lock(&mutex); | |
++g; | |
pthread_mutex_unlock(&mutex); | |
++n; | |
printf("Thread ID: %d, Static: %d, Global: %d, Normal: %d\n", arg->i, s, g, n); | |
pthread_exit(NULL); | |
} | |
int main() | |
{ | |
int i; | |
int maxThreads = 3; | |
// Create thread IDs | |
pthread_t *tid = malloc(maxThreads * sizeof(pthread_t)); | |
// Create three threads | |
for (i = 0; i < maxThreads; i++) { | |
Args *arg = (Args*) malloc(sizeof(Args)); | |
arg->i = i; | |
pthread_create(&tid[i], NULL, myThreadFun, arg); | |
} | |
// Wait for all the thread to finish | |
for (i = 0; i < maxThreads; i++) { | |
pthread_join(tid[i], NULL); | |
} | |
printf("That's it, folks!\n"); | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment