Better thread example

This commit is contained in:
Imbus 2025-08-24 20:21:17 +02:00
parent 38d078509e
commit cfb2aaabef

View file

@ -1,14 +1,32 @@
#include <pthread.h>
#include <stdio.h>
pthread_mutex_t lock;
int counter = 0;
void *worker(void *arg) {
printf("Hello from thread\n");
printf("Hello from %s!\n", (char *)arg);
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, worker, NULL);
pthread_join(thread, NULL);
pthread_t thread1, thread2;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, worker, "Thread1");
pthread_create(&thread2, NULL, worker, "Thread2");
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&lock);
printf("Counter value: %d\n", counter);
return 0;
}