Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <conio.h>
- #include <windows.h>
- //Variável acessível pelos dois threads e pela função main
- char a = 'a';
- pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
- //função do thread 1
- void* threadFunction(void* args)
- {
- int n = 5;
- while(n--)
- {
- pthread_mutex_lock( &mutex );
- printf("Estou em threadFunction\nvar a == %c\n", a++);
- pthread_mutex_unlock( &mutex );
- }
- }
- //função do thread 2
- void* threadFunction2(void* args)
- {
- int n = 3;
- while(n--)
- {
- pthread_mutex_lock( &mutex );
- printf("Estou em threadFunction2\nvar a == %c\n", a++);
- pthread_mutex_unlock( &mutex );
- }
- }
- int main()
- {
- //thread id
- pthread_t tid1, tid2;
- int tRet;
- //criando thread 1
- tRet = pthread_create(&tid1, NULL, &threadFunction, NULL);
- //Teste para saber se foi criado com sucesso ou não
- if (tRet) {
- printf("Thread1 fail!\n");
- return 0; /*return from main*/
- }
- //criando thread 2
- tRet = pthread_create(&tid2, NULL, &threadFunction2, NULL);
- if (tRet) {
- printf("Thread2 fail!\n");
- return 0; /*return from main*/
- }
- //barreira de threads
- pthread_join(tid1, NULL);
- pthread_join(tid2, NULL);
- exit (0);
- }
Advertisement
Add Comment
Please, Sign In to add comment