Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * @file main.c
- * @brief race-condition que recorre a 200 threads para incrementar 1000 vezes um contador partilhado.
- * @date 2019-10-14
- * @srico
- */
- #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 "args.h"
- #include "debug.h"
- #include "memory.h"
- #define C_ERRO_PTHREAD_CREATE 1
- #define C_ERRO_PTHREAD_JOIN 2
- #define C_ERRO_MUTEX_INIT 3
- #define C_ERRO_MUTEX_DESTROY 4
- int G_shared_counter; //variavel global
- // Estrutura a 'passar' às threads
- typedef struct
- {
- int incremento;
- pthread_mutex_t mutex;
- }thread_params_t;
- void *soma(void *arg);
- int main(int argc, char *argv[]){
- struct gengetopt_args_info args;
- thread_params_t thread_params;
- G_shared_counter=0;
- if (cmdline_parser(argc,argv, &args))
- {
- ERROR(1,"erro no cmdline_parser()\n");
- }
- pthread_t tids[args.threads_arg]; //vetor com as threads
- thread_params.incremento=args.incremento_arg;
- //------------iniciar o mutex------------
- if ( (errno = pthread_mutex_init(&thread_params.mutex, NULL)) != 0) {
- ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_init() failed");
- }
- //criar as N threads
- for (int i = 0; i < args.threads_arg; ++i)
- {
- if ((errno = pthread_create(&tids[i], NULL, soma,&thread_params)) != 0)
- {
- ERROR(2, "pthread_create() failed!");
- }
- }
- for (int i = 0; i < args.threads_arg; ++i)
- {
- if ((errno = pthread_join(tids[i], NULL) != 0))
- {
- ERROR(3, "pthread_join() failed!");
- }
- }
- printf("G_shared_counter =%d (expecting %d)\n", G_shared_counter, args.threads_arg * args.incremento_arg);
- //------------Destrói o mutex------------
- if ( (errno = pthread_mutex_destroy(&thread_params.mutex)) != 0) {
- ERROR(C_ERRO_MUTEX_DESTROY, "pthread_mutex_destroy() failed");
- }
- cmdline_parser_free(&args);
- return 0;
- }
- void *soma(void *arg){
- thread_params_t *thread_params = (thread_params_t*)arg;
- int incremento = thread_params->incremento; //obtem campo da estrutura
- int local;
- //------------lock------------
- if ( (errno = pthread_mutex_lock(&thread_params->mutex)) != 0) {
- ERROR(C_ERRO_MUTEX_INIT, "pthread_mutex_lock() failed");
- }
- for (int i = 0; i < incremento; ++i)
- {
- local= G_shared_counter; //pomos na variavel global para aumentar a probabilidade da race condition
- sched_yield(); //baixa a prioridade da thread (para q seja a ultima a executar)
- local=local+1;
- G_shared_counter=local;
- }
- if ( (errno = pthread_mutex_unlock(&thread_params->mutex)) != 0) {
- ERROR(C_ERRO_MUTEX_DESTROY, "pthread_mutex_unlock() failed");
- }
- //------------unlock------------
- return NULL;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement