Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // thread_1.c
- //
- // pthread_create() - create a thread
- // pthread_join() - wait for termination of another thread
- //
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #define MAX_NUM 100 // maximum number of threads
- int sum = 0;
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
- //
- // The thread start routine
- //
- void* f(void* a)
- {
- int k = *(int*)a;
- srand(time(NULL));
- int n = rand() % 10;
- while(sum <1000) {
- pthread_mutex_lock(&mtx);
- sum += n;
- if (sum >1000) {
- printf("Thread-ul %d a realizat trecerea",k);
- }
- pthread_mutex_unlock(&mtx);
- }
- return NULL;
- }
- int main(int argc, char* argv[])
- {
- pthread_t t[MAX_NUM]; // an array of threads
- int index[5];
- for (int k = 0; k<5; k++) {
- index[k] = k;
- }
- int i;
- for (i = 0; i < MAX_NUM; i++)
- {
- pthread_create(&t[i], NULL, f, &index[i]); // create a thread
- }
- for (i = 0; i < MAX_NUM; i++)
- {
- pthread_join(t[i], NULL); // wait for each thread to finish
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement