Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #define MAX_NUM 5
- int sum = 0;
- pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
- void * f(void * a) {
- int k = * (int * ) a;
- srand(time(NULL));
- while (sum < 1000) {
- int n = rand() % 10;
- pthread_mutex_lock( & mtx);
- if (sum < 1000) {
- 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];
- int index[MAX_NUM];
- for (int k = 0; k < MAX_NUM; k++) {
- index[k] = k;
- }
- int i;
- for (i = 0; i < MAX_NUM; i++) {
- pthread_create( & t[i], NULL, f, & index[i]);
- }
- for (i = 0; i < MAX_NUM; i++) {
- pthread_join(t[i], NULL);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement