32 lines
677 B
C
32 lines
677 B
C
#include <pthread.h>
|
|
#include <stdio.h>
|
|
|
|
pthread_mutex_t lock;
|
|
int counter = 0;
|
|
|
|
void *worker(void *arg) {
|
|
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 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;
|
|
}
|