snipplets.dev/code/C/thread.c

32 lines
477 B
C
Raw Normal View History

2023-08-01 00:16:28 +03:00
/* https://www.geeksforgeeks.org/multithreading-in-c/ */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int g = 0;
void *my_thread(void *vargp) {
2024-04-27 23:54:46 +03:00
int *id = (int *)vargp;
2023-08-01 00:16:28 +03:00
2024-04-27 23:54:46 +03:00
static int s = 0;
2023-08-01 00:16:28 +03:00
2024-04-27 23:54:46 +03:00
++s;
++g;
2023-08-01 00:16:28 +03:00
2024-04-27 23:54:46 +03:00
printf("Thread ID: %d, Static: %d, Global: %d\n", *id, ++s, ++g);
2023-08-01 00:16:28 +03:00
}
int main() {
2024-04-27 23:54:46 +03:00
pthread_t tid;
2023-08-01 00:16:28 +03:00
2024-04-27 23:54:46 +03:00
int i;
for (i = 0; i < 3; i++)
2023-08-01 00:16:28 +03:00
pthread_create(&tid, NULL, my_thread, (void *)&tid);
2024-04-27 23:54:46 +03:00
pthread_exit(NULL);
2023-08-01 00:16:28 +03:00
2024-04-27 23:54:46 +03:00
return 0;
2023-08-01 00:16:28 +03:00
}