Better thread example
This commit is contained in:
parent
38d078509e
commit
cfb2aaabef
1 changed files with 22 additions and 4 deletions
26
thread.c
26
thread.c
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue