Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #define N 3
- int Counter = 0;
- pthread_mutex_t Mutex;
- pthread_t tid[N];
- void* thr_inc_module(void* ptr){
- int* module = (int*)ptr;
- while(Counter < 30){
- sleep(1);
- pthread_mutex_lock(&Mutex);
- if(Counter % 3 == module[0]){
- printf("Thread: [%d] -- Counter=%d\n",*module,Counter++);
- }
- pthread_mutex_unlock(&Mutex);
- }
- return NULL;
- }
- int main(int argc, char *argv[]) {
- int i;
- int module[3];
- pthread_mutex_init(&Mutex,NULL);
- module[0] = 0;
- module[1] = 1;
- module[2] = 2;
- for(i=0;i<N;i++){
- if (pthread_create(&tid[i], NULL, thr_inc_module, (void*)&module[i]) != 0) {
- printf("Error creating thread.\n");
- return -1;
- }
- }
- for(i=0;i<N;i++){
- if(pthread_join(tid[i], NULL) != 0) {
- printf("Error joining thread.\n");
- return -1;
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment