Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/types.h>
- #include <sys/wait.h>
- #include <pthread.h>
- #include "debug.h"
- #include "memory.h"
- #include "args.h"
- void *task(void *arg);
- #define NUM_THREADS 200
- #define NUM_INCREMENTOS 1000
- typedef struct thread_params_t
- {
- pthread_mutex_t mutex;
- }thread_params_t;
- int G_shared_counter;
- int main(int argc, char *argv[]){
- (void)argc; (void)argv;
- G_shared_counter = 0;
- pthread_t tids[NUM_THREADS];
- thread_params_t thread_params;
- // Mutex: inicializa o mutex antes de criar a(s) thread(s)
- if ((errno = pthread_mutex_init(&thread_params.mutex, NULL)) != 0)
- ERROR(12, "pthread_mutex_init() failed");
- // Criação das threads + passagem de parâmetro
- for (int i = 0; i < NUM_THREADS; i++){
- if ((errno = pthread_create(&tids[i], NULL, task, &thread_params)) != 0)
- ERROR(10, "Erro no pthread_create()!");
- }
- // Espera que todas as threads terminem
- for (int i = 0; i < NUM_THREADS; i++){
- if ((errno = pthread_join(tids[i], NULL)) != 0)
- ERROR(11, "Erro no pthread_join()!\n");
- }
- // Mutex: liberta recurso
- if ((errno = pthread_mutex_destroy(&thread_params.mutex)) != 0)
- ERROR(13, "pthread_mutex_destroy() failed");
- printf("G_shared_counter = %d\n", G_shared_counter);
- return 0;
- }
- void *task(void *arg)
- {
- // cast para o tipo de dados enviado pela 'main thread'
- struct thread_params_t *params = (struct thread_params_t *) arg;
- int local;
- // Mutex: entra na secção crítica
- if ((errno = pthread_mutex_lock(¶ms->mutex)) != 0){
- WARNING("pthread_mutex_lock() failed");
- return NULL;
- }
- for (int i = 0; i < NUM_INCREMENTOS; ++i)
- {
- local = G_shared_counter;
- sched_yield();
- local = local + 1;
- G_shared_counter = local;
- }
- if ((errno = pthread_mutex_unlock(¶ms->mutex)) != 0){
- WARNING("pthread_mutex_unlock() failed");
- return NULL;
- }
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement