text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct job { struct job* next; }; struct job* job_queue; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; sem_t job_queue_count; void initialize_job_queue () { job_queue = 0; sem_init(&job_queue_count, 0, 0); } void* thread_function (void *arg) { while (1) { struct job* next_job; sem_wait (&job_queue_count); pthread_mutex_lock (&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock (&job_queue_mutex); process_job (next_job); free (next_job); } return 0; } void enqueued_job ( ) { struct job* new_job; new_job = (struct job*) malloc (sizeof (struct job)); pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new_job; sem_post (&job_queue_count); pthread_mutex_unlock (&job_queue_mutex); }
1
#include <pthread.h> static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; static int g_db_group_ptr = -1; static void group_set_db_ptr(int i) { pthread_mutex_lock(&g_mutex); g_db_group_ptr = i; pthread_mutex_unlock(&g_mutex); } static struct group_t *group_new(void) { struct group_t *g; g = (struct group_t *)malloc(sizeof(*g)); if (!g) { return 0; } memset(g, 0, sizeof(*g)); g->gid = 81000; g->groupname = PACKAGE_NAME; return g; } int group_open_group(void) { group_set_db_ptr(0); return 0; } int group_close_group(void) { group_set_db_ptr(-1); return 0; } struct group_t *group_get_next_group(void) { pthread_mutex_lock(&g_mutex); if (g_db_group_ptr) { pthread_mutex_unlock(&g_mutex); return 0; } ++g_db_group_ptr; pthread_mutex_unlock(&g_mutex); return group_new(); } void group_free(struct group_t *group) { free(group); } struct group_t *group_get_group_by_groupname(const char *groupname) { if (strcmp(groupname, PACKAGE_NAME)) { return 0; } return group_new(); } struct group_t *group_get_group_by_gid(gid_t gid) { if (gid != 81000) { return 0; } return group_new(); }
0
#include <pthread.h> unsigned long long main_counter, counter[3]; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_worker(void*); void* thread_worker(void* p) { int thread_num; thread_num = *(int *)p; for(;;) { pthread_mutex_lock(&mutex); counter[thread_num]++; main_counter++; } } int main(int argc, char* argv[]) { int i, rtn= 0, ch; int x[3] = {0,1,2}; pthread_t pthread_id[3] = {0}; for(i = 0; i < 3; i++) { pthread_create(&pthread_id[i], 0, thread_worker, &x[rtn++]); } do { unsigned long long sum = 0; for(i = 0; i < 3; i++) { sum += counter[i]; printf("%llu ",counter[i]); } printf("%llu/%llu ", main_counter, sum); pthread_mutex_unlock(&mutex); }while((ch = getchar()) != 'q'); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> struct prodcons { int buffer[4]; pthread_mutex_t key; int read, write; pthread_cond_t notEmpty; pthread_cond_t notFull; } buffer; void init(struct prodcons * b) { pthread_mutex_init(&b->key, 0); pthread_cond_init(&b->notEmpty, 0); pthread_cond_init(&b->notFull, 0); b->read = 0; b->write = 0; } void Store(struct prodcons * b, int data) { pthread_mutex_lock(&b->key); while ((b->write + 1) % 4 == b->read) { pthread_cond_wait(&b->notFull, &b->key); } b->buffer[b->write] = data; b->write++; if (b->write >= 4) b->write = 0; pthread_cond_signal(&b->notEmpty); pthread_mutex_unlock(&b->key); } int Get (struct prodcons * b) { int data; pthread_mutex_lock(&b->key); while (b->write == b->read) { pthread_cond_wait(&b->notEmpty, &b->key); } data = b->buffer[b->read]; if (data != (-1)){ b->read++; } else { pthread_cond_signal(&b->notEmpty); } if (b->read >= 4) b->read = 0; pthread_cond_signal(&b->notFull); pthread_mutex_unlock(&b->key); return (data); } void * Producer(void *name) { int n; int myNum = *((int*)name); for (n = 0; n < 12; n++) { printf("P %d ---> %d\\n", myNum, n); Store(&buffer, n); sleep(rand() % 4); } Store(&buffer, (-1)); return (0); } void * Consumer(void *name) { int d; int myNum = *((int*)name); while (1) { d = Get(&buffer); if (d == (-1)) break; printf("C %d ---> %d\\n", myNum, d); sleep(rand() % 4); } return (0); } int main(void) { pthread_t th_a, th_b, th_c; void * returnValue; int th_name[3] = {0, 1, 2}; init(&buffer); srand (time(0)); pthread_create(&th_a, 0, Producer, &th_name[0]); pthread_create(&th_b, 0, Consumer, &th_name[1]); pthread_create(&th_c, 0, Consumer, &th_name[2]); pthread_join(th_a, &returnValue); printf("Prod\\n"); pthread_join(th_b, &returnValue); printf("C1\\n"); pthread_join(th_c, &returnValue); printf("C2\\n"); pthread_cond_destroy(&buffer.notEmpty); pthread_cond_destroy(&buffer.notFull); pthread_mutex_destroy(&buffer.key); return (0); }
0
#include <pthread.h> static struct tbf_st *atbf[CHN_NUMS]; pthread_mutex_t tbf_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t tid_timer; pthread_once_t once_control = PTHREAD_ONCE_INIT; static int get_index(void) { int i; for (i = 0; i < sizeof atbf / sizeof atbf[0]; ++i) { if (atbf[i] == 0) { return i; } } return -1; } static void *thr_timer_token(void *unused) { struct timespec t; while (1) { t.tv_sec = 1; t.tv_nsec = 0; while (nanosleep(&t, &t) != 0) { if (errno == EINTR) { continue; } syslog(LOG_ERR,"nanosleep failed(%s)", strerror(errno)); goto err; } int i; for (i = 0; i < sizeof atbf / sizeof atbf[0]; ++i) { if (atbf[i] != 0) { atbf[i]->tokens += atbf[i]->cps; if (atbf[i]->tokens > atbf[i]->burst) { atbf[i]->tokens = atbf[i]->burst; } pthread_cond_broadcast(&atbf[i]->cond); } } } return 0; err: return (void *)-1; } void module_load(void) { pthread_create(&tid_timer, 0, thr_timer_token, 0); } void module_unload(void) { pthread_cancel(tid_timer); pthread_join(tid_timer, 0); } struct tbf_st *tbf_init(int cps, int burst) { struct tbf_st *me; pthread_once(&once_control, module_load); me = (struct tbf_st *)malloc(sizeof(*me)); if (me == 0) { syslog(LOG_ERR, "malloc failed: %s", strerror(errno)); return 0; } me->cps = cps; me->burst = burst; me->tokens = 0; pthread_mutex_lock(&tbf_mutex); int index = get_index(); if (index == -1) { syslog(LOG_ERR, "Out of boud of array atbf"); pthread_mutex_unlock(&tbf_mutex); free(me); return 0; } atbf[index] = me; pthread_mutex_unlock(&tbf_mutex); pthread_mutex_init(&me->mutex, 0); pthread_cond_init(&me->cond, 0); atexit(module_unload); return me; } int tbf_destroy(struct tbf_st *ptbf) { pthread_mutex_destroy(&ptbf->mutex); pthread_cond_destroy(&ptbf->cond); free(ptbf); int i; for (i = 0; i < sizeof atbf / sizeof atbf[0]; ++i) { if (atbf[i] == ptbf) { atbf[i] = 0; return 0; } } syslog(LOG_ERR, "ptbf not found in atbf"); return -1; } int min(int a, int b) { return ((a) < (b) ? (a) : (b)); } int tbf_get_token(struct tbf_st *ptbf) { pthread_mutex_lock(&ptbf->mutex); if (ptbf->tokens <= 0) { pthread_cond_wait(&ptbf->cond, &ptbf->mutex); } int token = min(ptbf->tokens, ptbf->cps); ptbf->tokens -= token; pthread_mutex_unlock(&ptbf->mutex); return token; } int tbf_get_token2(struct tbf_st *ptbf, int n) { pthread_mutex_lock(&ptbf->mutex); if (ptbf->tokens <= 0) { pthread_cond_wait(&ptbf->cond, &ptbf->mutex); } int token = min(ptbf->tokens, n); ptbf->tokens -= token; pthread_mutex_unlock(&ptbf->mutex); return token; } int tbf_return_token(struct tbf_st *ptbf, int n) { pthread_mutex_lock(&ptbf->mutex); ptbf->tokens += n; if (ptbf->tokens > ptbf->burst) { ptbf->tokens = ptbf->burst; } pthread_cond_broadcast(&ptbf->cond); pthread_mutex_unlock(&ptbf->mutex); return ptbf->tokens; }
1
#include <pthread.h> int quitflags; sigset_t mask; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static void *thr_fn(void *arg) { int err, signo; for( ; ; ){ err = sigwait(&mask, &signo); if(err != 0){ perror("sigwait error"); return (void *)-1; } switch(signo){ case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: printf("\\nsigquit\\n"); pthread_mutex_lock(&mutex); quitflags = 1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); return((void*)0); default: printf("unexpected signal %d\\n", signo); exit(1); } } return((void *)1); } int main(int argc, char const *argv[]) { int err; sigset_t old_mask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &old_mask)) != 0){ perror("pthread_sigmask error"); return -1; } if((err = pthread_create(&tid, 0, thr_fn, 0)) != 0){ perror("pthread_create error"); return -1; } pthread_mutex_lock(&mutex); while(quitflags==0) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); quitflags = 0; if(sigprocmask(SIG_SETMASK, &old_mask, 0) != 0){ perror("sigprocmask error"); return -1; } return 0; }
0
#include <pthread.h> struct thread_data{ char * buffer; unsigned int chunk_size; int id; unsigned int *histo; int* howfar; pthread_mutex_t * mutex; }; void* parallel(void* threadArg){ struct thread_data *data = threadArg; unsigned int chunk_size = data->chunk_size; char *buffer = data->buffer; unsigned int *histogram; histogram = calloc(26, sizeof(*histogram)); int* howfar = data->howfar; pthread_mutex_t * mutex = data->mutex; int where=0; while(where!=-1){ pthread_mutex_lock(mutex); where = *howfar; pthread_mutex_unlock(mutex); pthread_mutex_lock(mutex); char znak = buffer[where+1]; pthread_mutex_unlock(mutex); if (znak==TERMINATOR){ pthread_mutex_lock(mutex); *howfar = -1; pthread_mutex_unlock(mutex); continue; } pthread_mutex_lock(mutex); *howfar = *howfar+chunk_size-1; pthread_mutex_unlock(mutex); pthread_mutex_lock(mutex); for (int i=where; i<chunk_size && i!=TERMINATOR; i++) { if (buffer[i] >= 'a' && buffer[i] <= 'z') histogram[buffer[i]-'a']++; else if(buffer[i] >= 'A' && buffer[i] <= 'Z') histogram[buffer[i]-'A']++; } pthread_mutex_unlock(mutex); } data->histo = histogram; return 0; } void get_histogram(char *buffer, unsigned int* histogram, unsigned int num_threads, unsigned int chunk_size) { struct thread_data *seznam; seznam = malloc(num_threads * sizeof(*seznam)); pthread_t *thread; thread = malloc(num_threads * sizeof(*thread)); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int howfar = 0; for (int i=0; i<num_threads; i++){ seznam[i].id = i; seznam[i].buffer = buffer; seznam[i].chunk_size = chunk_size; seznam[i].mutex = &mutex; seznam[i].howfar = &howfar; pthread_create(thread+i, 0, &parallel, seznam+i); } for(int i = 0; i < num_threads; ++i) { pthread_join(thread[i], 0); for(int j = 0; j < NALPHABET; j++) { histogram[j] += seznam[i].histo[j]; } free(seznam[i].histo); } free(thread); free(seznam); }
1
#include <pthread.h> pthread_mutex_t alarm_lock= PTHREAD_MUTEX_INITIALIZER; extern const char * id; int win = 0; int nombre_aleatoire = 0; { char addr [TAILLE_ADDRESS + 1]; struct Fifo * next; } Fifo; Fifo* fifoDebut; Fifo* fifoFin; void createElementFifo(char *addr, Fifo * f) { strcpy(f->addr, addr); f->next = 0; } void addFifo(Fifo * f) { if (fifoDebut == 0 || fifoDebut == 0) { fifoDebut = f; fifoFin = f; } else { fifoFin->next = f; fifoFin = f; } } void popFifo() { Fifo * tmpFifo = fifoDebut->next; free(fifoDebut); fifoDebut = tmpFifo; } void alarm_handler (int signum) { pthread_mutex_lock(&alarm_lock); popFifo(); pthread_mutex_unlock(&alarm_lock); } int check_caller(char * caller) { Fifo * tmpFifo = fifoDebut; while (tmpFifo != 0 && tmpFifo != 0) { if (strcmp(caller, tmpFifo->addr) == 0)return 0; tmpFifo = tmpFifo->next; } return 1; } void receive_play(char * nbre, char * caller) { char *ptr; long ret; ret = strtol(nbre, &ptr, 10); if (ptr != nbre + strlen(nbre) || ret > 9999) return ; int nb = atoi(nbre); if (!check_caller(caller)) return; if (nb == nombre_aleatoire) { char mess[TAILLE_MESSAGE + 1]; sprintf(mess, "%s a gagné : le nombre était %d", caller, nombre_aleatoire); send_message(mess,id); win = 1; return; } else if (nb > nombre_aleatoire) { char mess[TAILLE_MESSAGE + 1]; sprintf(mess, "le nombre est plus petit que %d", nb); send_message(mess,id); } else if (nb < nombre_aleatoire) { char mess[TAILLE_MESSAGE + 1]; sprintf(mess, "le nombre est plus grand que %d", nb); send_message(mess,id); } Fifo *f = malloc(sizeof(Fifo)); createElementFifo(caller, f); addFifo(f); alarm(10); } char * send_recap_guess() { static int first = 1; if (first) { struct sigaction new_action; new_action.sa_handler = alarm_handler; sigemptyset (&new_action.sa_mask); new_action.sa_flags = 0; sigaction (SIGALRM, &new_action, 0); srand(time(0)); nombre_aleatoire = rand() % 1000; printf("%d\\n", nombre_aleatoire); first = !first; } if (win) { sleep(10); nombre_aleatoire = rand() % 1000; printf("%d\\n", nombre_aleatoire); win = 0; } char * tamp = malloc(sizeof(char) * 20); sprintf(tamp, "Guess number !!"); return tamp; } int process_input_client_guess_number(char * buff, int descSock, char * address_caller) { int set = 1; setsockopt(descSock, SOL_SOCKET, 13, (void *)&set, sizeof(int)); int retour = 0; char mess[TAILLE_MAX_TCP]; if (strncmp(buff, "INFO", 4) == 0) { format_mess_desc(mess, "Un simple jeu ou vous devez deviner le nombre caché"); send(descSock, mess, strlen(mess), 0); send(descSock, "PLAY\\r\\n", strlen("PLAY\\r\\n"), 0); retour = send(descSock, "ENDM\\r\\n", strlen("ENDM\\r\\n"), 0); if (retour == -1) { perror(strerror(errno)); } return 1; } else if (strncmp(buff, "HELP", 4) == 0) { if (strncmp(buff + 5, "PLAY", 4) == 0) { format_mess_help(mess, "Commande pour jouer : [PLAY nombre<9999] ou nombre est écrit sur 4 octect", "PLAY"); retour = send(descSock, mess, strlen(mess), 0); if (retour == -1) { perror(strerror(errno)); } return 1; } } else if (strncmp(buff, "PLAY", 4) == 0) { char * end = strrchr(buff, '\\r'); if(end != 0) end[0] = 0; receive_play(buff + 5, address_caller); return 1; } return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = ( ((unsigned long)id) % 29 ); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[( ((unsigned long)id) % 29 )]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = ( ((unsigned long)fp->f_id) % 29 ); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cv = PTHREAD_COND_INITIALIZER; int wake; int stop; void * thr_routine(void *arg) { pthread_mutex_lock(&m); while (wake == 0) pthread_cond_wait(&cv, &m); pthread_mutex_unlock(&m); while (stop == 0) pthread_yield(); return (0); } int main(int argc, char **argv) { pthread_t td; int i; void *result; pthread_setconcurrency(1); for (i = 0; i < 10; ++i) { stop = 0; wake = 0; pthread_create(&td, 0, thr_routine, 0); sleep(1); printf("trying: %d\\n", i); pthread_mutex_lock(&m); wake = 1; pthread_cond_signal(&cv); pthread_cancel(td); pthread_mutex_unlock(&m); stop = 1; result = 0; pthread_join(td, &result); if (result == PTHREAD_CANCELED) { printf("the condition variable implementation does not\\n" "conform to SUSv3, a thread unblocked from\\n" "condition variable still can be canceled.\\n"); return (1); } } printf("OK\\n"); return (0); }
0
#include <pthread.h> int state[5]; pthread_mutex_t mutex; sem_t s[5]; pthread_t fil[5]; void test(int i){ if (state[i] == 1 && state[(i+5 -1)%5] != 2 && state[(i+1)%5] != 2){ state[i] = 2; sem_post(&(s[i])); } } void think(int i){ printf("%d: THINKING\\n", i); } void eat(int i){ pthread_mutex_lock(&mutex); if(state[i] == 2) printf("%d: EATING\\n", i); pthread_mutex_unlock(&mutex); } void take_forks(int i){ pthread_mutex_lock(&mutex); state[i] = 1; test(i); pthread_mutex_unlock(&mutex); sem_wait(&(s[i])); } void put_forks(int i){ pthread_mutex_lock(&mutex); state[i] = 0; test((i+5 -1)%5); test((i+1)%5); pthread_mutex_unlock(&mutex); } void * filosofo(void * i_aux){ int i = (int) i_aux; while(1){ think(i); sleep(1); take_forks(i); eat(i); put_forks(i); } pthread_exit(0); } int main(){ pthread_mutex_init(&mutex, 0); int a; for(a = 0; a < 5; a++) sem_init(&(s[a]), 0, 0); for(a = 0; a < 5; a++) pthread_create(&fil[a], 0, filosofo, (void *) a); for(a = 0; a < 5; a++) pthread_join(fil[a], 0); for(a = 0; a < 5; a++) sem_destroy(&(s[a])); pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> void *direccion; char *archivo; pthread_mutex_t mutex; }MAPA; pthread_mutex_t mutex; int calculate_position(char char1, char char2){ int a = toascii(char1); int b = toascii(char2); int posicion = ((a*128) + b); return posicion; } void agregarAMapa(MAPA *mapa, int posicion) { unsigned char *direccion = (unsigned char *)mapa->direccion + posicion; if(*direccion <255){ (*direccion)++; } } void* procesar(void *args) { MAPA *mapa = (MAPA *)args; FILE *file; char leido, caracter; int primera = 0, posicion; if(!(file = fopen(mapa->archivo, "r"))){ warnx("Error opening %s\\n", mapa->archivo); pthread_exit((void *)1); } while((leido=fgetc(file)) != EOF){ if(!primera){ caracter = leido; primera++; } else { posicion = calculate_position(caracter, leido); pthread_mutex_lock(&mapa->mutex); agregarAMapa(mapa, posicion); pthread_mutex_unlock(&mapa->mutex); caracter = leido; } } fclose(file); return 0; } void * crearMapa(char *fichero){ int fd; void *direccion; int length = 128*128; fd = creat(fichero, 0644); if(fd < 0) err(1, "Creat Error: cannot create map"); lseek(fd,(length)-1, 0); if(write(fd,"\\0",1) != 1) errx(1, "Write Error: impossible to write on map"); close(fd); if((fd = open(fichero, O_RDWR))<0) errx(1, "Open Error: cannot open map"); direccion = mmap(0, length, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, fd, 0); if(direccion == MAP_FAILED){ errx(1, "Map Error: cannot create mmap"); } close(fd); return direccion; } void imprimir(MAPA mapa) { int i, j; unsigned char* mapa_aux; void* direccion = mapa.direccion; mapa_aux = (unsigned char *)direccion; for(i = 0; i < 128; i++){ for(j = 0; j < 128; j++){ mapa_aux = (mapa_aux+(i*128 + j)); printf("(%d, %d): %d\\n", i, j, *mapa_aux); mapa_aux = direccion; } } } int main(int argc, char *argv[]) { MAPA mapa; int option, i=0; int length = 128*128; argc--; argv++; if(argc < 2){ errx(1, "Usage: [option][mmap name][files]"); } if(!(strcmp(argv[0], "-p"))){ option = 1; argv++; argc--; } mapa.direccion = crearMapa(argv[0]); argv++; argc--; pthread_t thread_id[argc]; pthread_mutex_init(&mapa.mutex, 0); while(i<argc){ mapa.archivo = argv[i]; pthread_create(&thread_id[i], 0, &procesar, &mapa); i++; } i=0; while(i<argc){ pthread_join(thread_id[i], 0); i++; } if(option){ imprimir(mapa); } if(munmap(mapa.direccion, length)<0){ errx(1, "Munmap Error: cannot close map"); } pthread_mutex_destroy(&mapa.mutex); exit(0); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[800]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 800) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 800; if (push(arr, tmp) == (-1)) error(); pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (top > 0) { if (pop(arr) == (-2)) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_barrier_t br; pthread_cond_t cv; pthread_mutex_t lock; bool exiting; int fd, count, spins, nn; void * tf (void *id) { pthread_setschedparam_np(0, SCHED_FIFO, 0, 0xF, PTHREAD_HARD_REAL_TIME); pthread_barrier_wait(&br); pthread_mutex_lock (&lock); if ((long) id == 0) { while (!exiting) { if ((spins++ % 1000) == 0) write (fd, ".", 1); pthread_mutex_unlock (&lock); pthread_mutex_lock (&lock); int njobs = rand () % (count + 1); nn = njobs; if ((rand () % 30) == 0) pthread_cond_broadcast (&cv); else while (njobs--) pthread_cond_signal (&cv); } pthread_cond_broadcast (&cv); } else { while (!exiting) { while (!nn && !exiting) pthread_cond_wait (&cv, &lock); --nn; pthread_mutex_unlock (&lock); pthread_mutex_lock (&lock); } } pthread_mutex_unlock (&lock); return 0; } int do_test (void) { fd = open ("/dev/null", O_WRONLY); if (fd < 0) { printf ("couldn't open /dev/null, %m\\n"); return 1; } count = sysconf (_SC_NPROCESSORS_ONLN); if (count <= 0) count = 1; count *= 8; pthread_barrier_init(&br, 0, count + 1); pthread_t th[count + 1]; int i, ret; for (i = 0; i <= count; ++i) if ((ret = pthread_create (&th[i], 0, tf, (void *) (long) i)) != 0) { errno = ret; printf ("pthread_create %d failed: %m\\n", i); return 1; } struct timespec ts = { .tv_sec = 5, .tv_nsec = 0 }; while (nanosleep (&ts, &ts) != 0); pthread_mutex_lock (&lock); exiting = 1; pthread_mutex_unlock (&lock); for (i = 0; i < count; ++i) pthread_join (th[i], 0); close (fd); return 0; } int main(void) { pthread_setschedparam_np(0, SCHED_FIFO, 0, 0xF, PTHREAD_HARD_REAL_TIME); start_rt_timer(0); pthread_cond_init(&cv, 0); pthread_mutex_init(&lock, 0); do_test(); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int i, n, N, n_start, n_master, n_slave; int *ids; double sum; void *Summator( void * ); int main( int argc, char **argv ) { if ( argc != 3 ) { printf( "Wrong numbers of parameters. Add n and N.\\n" ); return -1; } n = atoi( argv[ 1 ] ); N = atoi( argv[ 2 ] ); n_slave = (int) (N / n); n_master = n_slave + N % n; int i = 1; if ( !( ids = ( int * ) malloc( sizeof( int ) * n ) ) ) { printf( "Error of allocating memory\\n" ); exit( -1 ); } pthread_t tids[ n ]; for ( i = 0; i < n; i++ ) { ids[ i ] = i; if ( pthread_create( &tids[ i ], 0, Summator, ( void * ) &ids[ i ] ) ) { printf( "Error of creating thread: %s\\n", strerror( errno ) ); return -1; } } for ( i = 0; i < n; i++ ) { if ( pthread_join( tids[ i ], 0 ) ) { printf( "Error of joining thread: %s\\n", strerror( errno ) ); return -1; } } printf("Sum of harmonical series 1/n = %.4lf for N = %d\\n", sum, N); return 0; } void *Summator( void *arg ) { int id = *( int * ) arg, start = 1; if ( id != 0 ) { start = n_master + 1 + (id - 1) * n_slave; } int finish = n_master + 1; if ( id != 0 ) { finish = start + n_slave; } while ( start < finish ) { pthread_mutex_lock( &mutex ); sum += 1.0 / start; pthread_mutex_unlock( &mutex ); start++; } pthread_exit( 0 ); }
1
#include <pthread.h> pthread_mutex_t accion= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond= PTHREAD_COND_INITIALIZER; char vendedor_actual[10]; char comprador_actual[10]; int num_vend, precio_actual; boolean compra; int vendo(int precio, char *vendedor, char *comprador){ pthread_mutex_lock(&accion); if(!num_vend){ precio_actual = precio; strcpy(vendedor_actual,vendedor); num_vend += 1; while(!compra){ if(precio > precio_actual){ num_vend -= 1; pthread_mutex_unlock(&accion); return 0; } pthread_cond_wait(&cond, &accion); } if(strcmp(vendedor_actual,vendedor) != 0){ strcpy(comprador,comprador_actual); compra = 0; pthread_mutex_unlock(&accion); return 1; } num_vend -= 1; pthread_mutex_unlock(&accion); return 0; } else if(precio_actual > precio){ precio_actual = precio; num_vend += 1; strcpy(vendedor_actual, vendedor); pthread_cond_broadcast(&cond); while(!compra){ if(precio > precio_actual){ num_vend -= 1; pthread_mutex_unlock(&accion); return 0; } pthread_cond_wait(&cond, &accion); } strcpy(comprador,comprador_actual); compra = 0; num_vend = 0; pthread_mutex_unlock(&accion); return 1; } pthread_mutex_unlock(&accion); return 0; } int compro(char *comprador, char *vendedor){ pthread_mutex_lock(&accion); if (num_vend != 1) { pthread_mutex_unlock(&accion); return 0; } compra = 1; strcpy(comprador_actual,comprador); strcpy(vendedor,vendedor_actual); int p = precio_actual; strcpy(vendedor_actual,""); num_vend -= 1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&accion); return p; }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; int main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Final count: %d\\n",count); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); pthread_cond_wait( &condition_var, &count_mutex ); count++; printf("Counter value functionCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_var ); } else { count++; printf("Counter value functionCount2: %d\\n",count); } pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
1
#include <pthread.h> bool flag_completo = 0; int x, y, z; int par1_sensores[2]; int par2_sensores[2]; int cont_pos = -1; int resultados[24][3]; long double resultados_sumarizados[10]; int pares_especificos[10] = {2,3,4,5,6,8,10,12,15,20}; char* nome_sensores[10] = {"1 e 2", "1 e 3", "1 e 4", "1 e 5", "2 e 3", "2 e 4", "2 e 5", "3 e 4", "3 e 5", "4 e 5"}; int rand_numb1, rand_numb2; struct input{ int indices[2]; int valores[2]; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void mostra_opcoes_iniciais(); int gera_dados_sensor(int i); void sumarizador(); void gera_estado_aleatorio(); void* thread_coleta(void *arg); void* imprime_resultados(); int main(void){ pthread_t par1; pthread_t par2; mostra_opcoes_iniciais(); while(1){ gera_estado_aleatorio(); struct input *entrada = malloc(sizeof(struct input)); entrada->indices[0] = par1_sensores[0]; entrada->indices[1] = par1_sensores[1]; entrada->valores[0] = gera_dados_sensor(par1_sensores[0]); entrada->valores[1] = gera_dados_sensor(par1_sensores[1]); pthread_create(&par1, 0, thread_coleta, entrada); struct input *entrada2 = malloc(sizeof(struct input)); entrada2->indices[0] = par2_sensores[0]; entrada2->indices[1] = par2_sensores[1]; entrada2->valores[0] = gera_dados_sensor(par2_sensores[0]); entrada2->valores[1] = gera_dados_sensor(par2_sensores[1]); pthread_create(&par2, 0, thread_coleta, entrada2); pthread_join(par1, 0); pthread_join(par2, 0); } } void mostra_opcoes_iniciais(){ printf("Você deseja ver os resultados de maneira completa? S/N\\n"); char resposta; resposta = getchar(); while(resposta != 'S' && resposta != 'N'){ printf("Caracter inválido, insira S ou N\\n"); resposta = getchar(); } if(resposta == 'S') flag_completo = 1; } int gera_dados_sensor(int i){ switch(i){ case 0: return 1 + rand() % 98; case 1: return 1 + rand() % 356; case 2: return 1 + rand() % 745; case 3: return 1 + rand() % 48; case 4: return 1 + rand() % 3781; } } void* thread_coleta(void *arg){ struct input *entrada = arg; pthread_mutex_lock(&mutex); cont_pos++; pthread_mutex_unlock(&mutex); if(cont_pos >= 24){ sumarizador(); cont_pos = 0; pthread_t mostra; pthread_create(&mostra, 0, imprime_resultados, 0); pthread_join(mostra,0); } resultados[cont_pos][0] = entrada->valores[0] * entrada->valores[1]; resultados[cont_pos][1] = entrada->indices[0]; resultados[cont_pos][2] = entrada->indices[1]; pthread_exit(0); } void sumarizador(){ int x = 0, y = 0; long int medias[10]; int cont_pares[10]; for(x = 0; x < 10; x++){ resultados_sumarizados[x] = 0.0; medias[x] = 0; cont_pares[x] = 0; } for(x = 0; x < 24; x++){ int resultado_multiplicacao = (resultados[x][1] + 1) * (resultados[x][2] + 1); for(y = 0; y < 10; y++){ if(resultado_multiplicacao == pares_especificos[y]){ medias[y] += resultados[x][0]; cont_pares[y]++; } } } for(x = 0; x < 10; x++){ if(cont_pares[x] != 0) resultados_sumarizados[x] = medias[x]/cont_pares[x]; } } void gera_estado_aleatorio(){ rand_numb1 = rand() % 5; bool flag = 0; while(!flag){ rand_numb2 = rand() % 5; if(rand_numb2 != rand_numb1){ flag = 1; } } par1_sensores[0] = rand_numb1; par1_sensores[1] = rand_numb2; flag = 0; while(!flag){ rand_numb1 = rand() % 5; if(rand_numb1 != par1_sensores[0] && rand_numb1 != par1_sensores[1]){ flag = 1; } } flag = 0; while(!flag){ rand_numb2 = rand() % 5; if(rand_numb2 != rand_numb1 && rand_numb2 != par1_sensores[0] && rand_numb2 != par1_sensores[1]){ flag = 1; } } par2_sensores[0] = rand_numb1; par2_sensores[1] = rand_numb2; } void* imprime_resultados(){ printf("\\n\\n=======================================================================\\n\\n"); if(flag_completo){ for(z = 0; z < 24; z++){ printf("%d | SENSOR %d X SENSOR %d - RESULTADO : %d\\n", z, resultados[z][1] + 1, resultados[z][2] + 1, resultados[z][0]); if(z%2 != 0 && z != 0){ printf("-----------------------------------------------------------\\n"); sleep(1); } } } for(x = 0; x < 10; x++){ printf("|Sensores %s - RESULTADO: %.2Lf\\n", nome_sensores[x], resultados_sumarizados[x]); } sleep(2); printf("\\n=======================================================================\\n\\n"); pthread_exit(0); }
0
#include <pthread.h> double *a; double *b; double sum; int veclen; } dotdata; dotdata dotstr; pthread_t thread_id[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, offset, len ; double mysum, *x, *y; offset = (int)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0.0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit(0); } int main (int argc, char *argv[]) { int i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*1000*sizeof(double)); b = (double*) malloc (4*1000*sizeof(double)); for (i=0; i<1000*4; i++) { a[i]=1.0; b[i]=a[i]; } dotstr.veclen = 1000; dotstr.a = a; dotstr.b = b; dotstr.sum=0.0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&thread_id[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(thread_id[i], &status); } printf ("Sum = %6.2f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; void handler(void *data) { printf("线程退出后调用我!\\n"); pthread_mutex_unlock(&mutex); } void * odd(void *arg) { int i; for (i=1; ; i+=2) { pthread_cleanup_push(handler, 0); pthread_mutex_lock(&mutex); printf("odd number : %d\\n", i); pthread_mutex_unlock(&mutex); pthread_cleanup_pop(0); } } void * even(void *arg) { int i; for (i=0; ; i+=2) { pthread_cleanup_push(handler, 0); pthread_mutex_lock(&mutex); printf("even number : %d\\n", i); pthread_mutex_unlock(&mutex); pthread_cleanup_pop(0); } } int main( void ) { int ret; pthread_t tid1; pthread_t tid2; pthread_mutex_init(&mutex, 0); if ( (ret=pthread_create(&tid1, 0, odd, 0)) != 0) do { fprintf(stderr, "[%s][%d]:%s\\n", "odd_even.c", 56, strerror(ret)); exit(1); }while(0); if ( (ret=pthread_create(&tid2, 0, even, 0)) != 0) do { fprintf(stderr, "[%s][%d]:%s\\n", "odd_even.c", 58, strerror(ret)); exit(1); }while(0); sleep(1); pthread_cancel(tid1); sleep(1); pthread_cancel(tid2); pthread_join(tid1,0); pthread_join(tid2,0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> uint8_t grab_new_frame; void tick(int signum) { grab_new_frame = 1; } void * grabber(void * args) { struct thread_arg * ta = (struct thread_arg *)args; struct channel * output = ta->output; struct timeval tv; struct sigaction sa; struct itimerval tmr; uint8_t * test_frame_rgb, * test_frame_ir; uint32_t test_counter_rgb = 0, test_counter_ir = 0; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = tick; sigaction(SIGALRM, &sa, 0); tmr.it_value.tv_sec = SETUP_STREAM_INTERVAL / 1000; tmr.it_value.tv_usec = (SETUP_STREAM_INTERVAL * 1000) % 1000000; tmr.it_interval = tmr.it_value; setitimer(ITIMER_REAL, &tmr, 0); if(SETUP_STREAMS & SETUP_STREAM_RGB) { test_frame_rgb = malloc(SETUP_IMAGE_SIZE_RAW_RGB); memset(test_frame_rgb, 0, SETUP_IMAGE_SIZE_RAW_RGB); } if(SETUP_STREAMS & SETUP_STREAM_IR) { test_frame_ir = malloc(SETUP_IMAGE_SIZE_RAW_IR); memset(test_frame_ir, 0, SETUP_IMAGE_SIZE_RAW_IR); } while(1) { tv.tv_sec = 0; tv.tv_usec = SETUP_POLL_DELAY; select(0, 0, 0, 0, &tv); if(grab_new_frame && (time(0) - get_or_set_grab_request(0)) < 1) { grab_new_frame = 0; test_frame_rgb[test_counter_rgb] = 255; test_frame_ir[test_counter_ir] = 255; if(sem_trywait(&output->empty)) { } else { pthread_mutex_lock(&output->lock); output->serial++; if(SETUP_STREAMS & SETUP_STREAM_RGB) { output->rgb[output->serial % SETUP_BUFFER_LENGTH_G2P].size = SETUP_IMAGE_SIZE_RAW_RGB; memcpy(output->rgb[output->serial % SETUP_BUFFER_LENGTH_G2P].data, test_frame_rgb, SETUP_IMAGE_SIZE_RAW_RGB); } if(SETUP_STREAMS & SETUP_STREAM_IR) { output->ir[output->serial % SETUP_BUFFER_LENGTH_G2P].size = SETUP_IMAGE_SIZE_RAW_IR; memcpy(output->ir[output->serial % SETUP_BUFFER_LENGTH_G2P].data, test_frame_ir, SETUP_IMAGE_SIZE_RAW_IR); } sem_post(&output->full); pthread_mutex_unlock(&output->lock); } } } return 0; }
1
#include <pthread.h> int N; int *v; pthread_mutex_t *lock; }Counter; Counter ca, cb; void initialize_array(int *array, int N); void *thFuncA(void *arg); void *thFuncB(void *arg); int main(int argc, char *argv[]){ pthread_t *tha, *thb; int i; if(argc != 2){ return -1; } N = atoi(argv[1]); if((N % 2) != 0){ return -1; } tha = (pthread_t *)malloc(N * sizeof(pthread_t)); thb = (pthread_t *)malloc(N * sizeof(pthread_t)); ca.v = (int *)malloc(N * sizeof(int)); cb.v = (int *)malloc(N * sizeof(int)); ca.lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); cb.lock = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); initialize_array(ca.v, N); initialize_array(cb.v, N); for(i=0; i<N; i++){ int *j = (int *)malloc(sizeof(int)); *j = i; pthread_create(tha, 0, thFuncA, j); } for(i=0; i<N; i++){ int *j = (int *)malloc(sizeof(int)); *j = i; pthread_create(thb, 0, thFuncB, j); } pthread_exit(0); } void *thFuncA(void *arg){ pthread_detach(pthread_self()); int *kPtr = (int *)arg; int k = *kPtr; int i; int flag = 0; int A1 = k; int A2 = -2; int B1 = -2; int B2 = -2; sleep(1 + (rand() % 4)); pthread_mutex_lock(ca.lock); if(ca.v[k] >= 0 || ca.v[k] == -4){ pthread_mutex_unlock(ca.lock); return 0; } for(i=0; i<N; i++){ if(ca.v[i] == -1 && i != k){ ca.v[k] = i; ca.v[i] = k; A2 = i; printf("A%d cats A%d A%d\\n", A1, A1, A2); flag = 1; pthread_mutex_unlock(ca.lock); break; } } if(flag == 0){ ca.v[k] = -1; pthread_mutex_unlock(ca.lock); return 0; } pthread_mutex_lock(ca.lock); pthread_mutex_lock(cb.lock); for(i=0; i<N; i++){ if(cb.v[i] >= 0){ B1 = i; B2 = cb.v[i]; cb.v[B1] = -4; cb.v[B2] = -4; ca.v[A1] = -4; ca.v[A2] = -4; printf("A%d merge A%d A%d B%d B%d\\n", A1, A1, A2, B2, B1); break; } } pthread_mutex_unlock(cb.lock); pthread_mutex_unlock(ca.lock); return 0; } void *thFuncB(void *arg){ pthread_detach(pthread_self()); int *kPtr = (int *)arg; int k = *kPtr; int i; int B1 = k; int B2 = -2; int A1 = -2; int A2 = -2; int flag = 0; sleep(1 + (rand() % 4)); pthread_mutex_lock(cb.lock); if(cb.v[k] >= 0 || cb.v[k] == -4){ pthread_mutex_unlock(cb.lock); return 0; } for(i=0; i<N; i++){ if(cb.v[i] == -1 && i != k){ cb.v[k] = i; cb.v[i] = k; B2 = i; printf("B%d cats B%d B%d\\n", B1, B1, B2); flag = 1; pthread_mutex_unlock(cb.lock); break; } } if(flag == 0){ cb.v[k] = -1; pthread_mutex_unlock(cb.lock); return 0; } pthread_mutex_lock(ca.lock); pthread_mutex_lock(cb.lock); for(i=0; i<N; i++){ if(ca.v[i] >= 0){ A1 = i; A2 = ca.v[i]; cb.v[B1] = -4; cb.v[B2] = -4; ca.v[A1] = -4; ca.v[A2] = -4; printf("B%d merge B%d B%d A%d A%d\\n", B1, B1, B2, A2, A1); break; } } pthread_mutex_unlock(cb.lock); pthread_mutex_unlock(ca.lock); return 0; } void initialize_array(int *array, int N){ int i; for(i=0; i<N; i++){ array[i] = -2; } }
0
#include <pthread.h> pthread_t threads[5]; pthread_mutex_t forks[5]; void fail() { printf("Could not lock a mutex.\\n"); exit(1); } void* worker (void * arg) { int id = *(int *) arg; int left = id; int right = (id + 1) % 5; if (left > right) { int tmp = left; left = right; right = tmp; } for (;;) { if (pthread_mutex_lock(&forks[left]) != 0) { fail(); } if (pthread_mutex_lock(&forks[right]) != 0) { fail(); } printf("Philosopher %d is eating...\\n", id); pthread_mutex_unlock(&forks[left]); pthread_mutex_unlock(&forks[right]); printf("Philosopher %d is thinking...\\n", id); } } int main(void) { int args[5]; for (int i = 0; i < 5; i++) { pthread_mutex_init(&forks[i], 0); } for (int i = 0; i != 5; i++) { args[i] = i; pthread_create(&threads[i], 0, worker, &args[i]); } for (;;) sleep(1); return 0; }
1
#include <pthread.h> int send_request(struct client_connection *conn, struct Message *req) { int rc = 0; pthread_mutex_lock(&conn->mutex); rc = send_msg(conn->fd, req); pthread_mutex_unlock(&conn->mutex); return rc; } int receive_response(struct client_connection *conn, struct Message *resp) { int rc = 0; rc = receive_msg(conn->fd, resp); return rc; } void* response_process(void *arg) { struct client_connection *conn = arg; struct Message *req, *resp; int ret = 0; resp = malloc(sizeof(struct Message)); if (resp == 0) { perror("cannot allocate memory for resp"); return 0; } ret = receive_response(conn, resp); while (ret == 0) { if (resp->Type != TypeResponse) { fprintf(stderr, "Wrong type for response of seq %d\\n", resp->Seq); continue; } pthread_mutex_lock(&conn->mutex); HASH_FIND_INT(conn->msg_table, &resp->Seq, req); if (req != 0) { HASH_DEL(conn->msg_table, req); } pthread_mutex_unlock(&conn->mutex); pthread_mutex_lock(&req->mutex); memcpy(req->Data, resp->Data, req->DataLength); free(resp->Data); pthread_mutex_unlock(&req->mutex); pthread_cond_signal(&req->cond); ret = receive_response(conn, resp); } free(resp); if (ret != 0) { fprintf(stderr, "Receive response returned error"); } } void start_response_processing(struct client_connection *conn) { int rc; rc = pthread_create(&conn->response_thread, 0, &response_process, conn); if (rc < 0) { perror("Fail to create response thread"); exit(-1); } } int new_seq(struct client_connection *conn) { return __sync_fetch_and_add(&conn->seq, 1); } int process_request(struct client_connection *conn, void *buf, size_t count, off_t offset, uint32_t type) { struct Message *req = malloc(sizeof(struct Message)); int rc = 0; if (req == 0) { perror("cannot allocate memory for req"); return -EINVAL; } if (type != TypeRead && type != TypeWrite) { fprintf(stderr, "BUG: Invalid type for process_request %d\\n", type); rc = -EFAULT; goto free; } req->Seq = new_seq(conn); req->Type = type; req->Offset = offset; req->DataLength = count; req->Data = buf; if (req->Type == TypeRead) { bzero(req->Data, count); } rc = pthread_cond_init(&req->cond, 0); if (rc < 0) { perror("Fail to init phread_cond"); rc = -EFAULT; goto free; } rc = pthread_mutex_init(&req->mutex, 0); if (rc < 0) { perror("Fail to init phread_mutex"); rc = -EFAULT; goto free; } pthread_mutex_lock(&conn->mutex); HASH_ADD_INT(conn->msg_table, Seq, req); pthread_mutex_unlock(&conn->mutex); pthread_mutex_lock(&req->mutex); rc = send_request(conn, req); if (rc < 0) { goto out; } pthread_cond_wait(&req->cond, &req->mutex); out: pthread_mutex_unlock(&req->mutex); free: free(req); return rc; } int read_at(struct client_connection *conn, void *buf, size_t count, off_t offset) { process_request(conn, buf, count, offset, TypeRead); } int write_at(struct client_connection *conn, void *buf, size_t count, off_t offset) { process_request(conn, buf, count, offset, TypeWrite); } struct client_connection *new_client_connection(char *socket_path) { struct sockaddr_un addr; int fd, rc = 0; struct client_connection *conn = 0; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { perror("socket error"); exit(-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(socket_path) >= 108) { fprintf(stderr, "socket path is too long, more than 108 characters"); exit(-EINVAL); } strncpy(addr.sun_path, socket_path, strlen(socket_path)); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("connect error"); exit(-EFAULT); } conn = malloc(sizeof(struct client_connection)); if (conn == 0) { perror("cannot allocate memory for conn"); return 0; } conn->fd = fd; conn->seq = 0; conn->msg_table = 0; rc = pthread_mutex_init(&conn->mutex, 0); if (rc < 0) { perror("fail to init conn->mutex"); exit(-EFAULT); } return conn; } int shutdown_client_connection(struct client_connection *conn) { close(conn->fd); free(conn); }
0
#include <pthread.h> int value; char padding[60]; } padded_int; int count=0; padded_int counter[8]; int *array; pthread_mutex_t lock; void * global_counter_scalar(void *thread_id){ int *int_pt=array+(*((int*)thread_id)*(800000000/8)); int i; for (i=0;i<800000000/8;i++){ if(int_pt[i]==3){ pthread_mutex_lock(&lock); count++; pthread_mutex_unlock(&lock); } } } void * global_array_counter_scalar(void *thread_id){ int id=*(int*)thread_id; int *int_pt=array+(id*(800000000/8)); int i; for (i=0;i<800000000/8;i++){ if(int_pt[i]==3){ counter[id].value++; } } pthread_mutex_lock(&lock); count+=counter[id].value; pthread_mutex_unlock(&lock); } void * global_array_counter_array(void * thread_id){ int id=*(int*)thread_id; int *int_pt=array+(id*(800000000/8)); int i; for (i=0;i<800000000/8;i++){ if(int_pt[i]==3){ counter[id].value++; } } } void * local_counter_global_scalar(void *thread_id){ int id=*(int*)thread_id; int *int_pt=array+(id*(800000000/8)); int local_count=0; int i; for (i=0;i<800000000/8;i++){ if(int_pt[i]==3){ local_count++; } } pthread_mutex_lock(&lock); count+=local_count; pthread_mutex_unlock(&lock); } void * local_counter_global_array(void * thread_id){ int id=*(int*)thread_id; int *int_pt=array+(id*(800000000/8)); int i; int local_count=0; for (i=0;i<800000000/8;i++){ if(int_pt[i]==3){ local_count++; } } counter[id].value=local_count; } int main(){ extern int *array; array=create_random_int_array(800000000); pthread_t threads[8]; int i; int thread_num[8]; double time; time=get_time_sec(); for(i=0;i<8;i++){ thread_num[i]=i; pthread_create(&threads[i],0,global_counter_scalar,(void*)&thread_num[i]); } for(i=0;i<8;i++){ pthread_join(threads[i],0); } printf("global counter-scalar done. count=%d, time=%f\\n",count,get_time_sec()-time); count=0; time=get_time_sec(); for(i=0;i<8;i++){ thread_num[i]=i; counter[i].value=0; pthread_create(&threads[i],0,global_array_counter_scalar,(void*)(&thread_num[i])); } for(i=0;i<8;i++){ pthread_join(threads[i],0); } printf("global array scalar done. count=%d, time=%f\\n",count,get_time_sec()-time); count=0; time=get_time_sec(); for(i=0;i<8;i++){ thread_num[i]=i; counter[i].value=0; pthread_create(&threads[i],0,global_array_counter_array,(void*)(&thread_num[i])); } for(i=0;i<8;i++){ pthread_join(threads[i],0); } for(i=0;i<8;i++) count+=counter[i].value; printf("global array array done. count=%d, time=%f\\n",count,get_time_sec()-time); count=0; bzero((void*)counter,(size_t)8); time=get_time_sec(); for(i=0;i<8;i++){ thread_num[i]=i; pthread_create(&threads[i],0,local_counter_global_scalar,(void*)(&thread_num[i])); } for(i=0;i<8;i++){ pthread_join(threads[i],0); } printf("local counter global scalar done. count=%d, time=%f\\n",count,get_time_sec()-time); count=0; bzero((void*)counter,8); time=get_time_sec(); for(i=0;i<8;i++){ thread_num[i]=i; pthread_create(&threads[i],0,local_counter_global_array,(void*)(&thread_num[i])); } for(i=0;i<8;i++){ pthread_join(threads[i],0); } for(i=0;i<8;i++) count+=counter[i].value; printf("local counter global array done. count=%d, time=%f\\n",count,get_time_sec()-time); time=get_time_sec(); count=numOfThree(array,800000000); printf("sequential done. count=%d, time=%f\\n",count,get_time_sec()-time); }
1
#include <pthread.h> FILE *foto, *video, *chave; unsigned char **imagem; char h_imagem[7],w_imagem[7],h_video[7],w_video[7]; int i_img=0,j_img=0, num_bits; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; void *desestenografar(){ int i,j,k; unsigned char temp, temp1 =0,temp2=0,mask1 = 0x1,mask2=0x80; for(i=0; i<atoi(h_imagem); i++) for(j=0; j<atoi(w_imagem); j++){ printf("%x\\t",imagem[i][j]); pthread_mutex_lock(&mut); temp=(unsigned char )imagem[i][j]; pthread_mutex_unlock(&mut); temp1 =0; temp2 = 0; for(k=0; k<=3; k++){ pthread_mutex_lock(&mut); temp1|=(imagem[i][j]&(mask1<<k))<<(7-2*k); temp2|=(imagem[i][j]&(mask2>>k))>>(7-2*k); pthread_mutex_unlock(&mut); } temp= temp1|temp2; temp = temp>>num_bits; temp = temp<<num_bits; pthread_mutex_lock(&mut); imagem[i][j]=temp; pthread_mutex_unlock(&mut); printf("%x\\n",imagem[i][j]); } pthread_mutex_unlock(&mut); } void *desembaralha(){ int i,j; for(i=0 ; i<atoi(h_imagem);i++) for(j=0 ; j<atoi(w_imagem);j++) fread(&imagem[i][j],sizeof(unsigned char),1,video); } int main(){ FILE *foto, *video, *chave; pthread_t thread_id,thread_1,thread_0; int i,j; printf("Digite o h do imagem escondida->"); scanf("%s",h_imagem); printf("Digite o h do imagem escondida->"); scanf("%s",w_imagem); printf("Digite o h do video escondida->"); scanf("%s",h_video); printf("Digite o h do video escondida->"); scanf("%s",h_video); printf("Digite o numero de bits da esteganografia->"); scanf("%d",&num_bits); if(!(video=fopen("teste_EsteganografiaLSB_1280x720_1bit_.y","r+"))){ printf("arquivo nao pode ser aberto"); exit(0); } imagem = (unsigned char **) malloc (atoi(h_imagem)*sizeof(unsigned char*)); for(i=0 ; i<atoi(h_imagem);i++) imagem[i] = (unsigned char *) malloc (atoi(w_imagem)*sizeof(unsigned char)); pthread_create(&thread_0,0,desembaralha,0); pthread_join(thread_0,0); pthread_create(&thread_1,0,desestenografar,0); pthread_join(thread_1,0); for(i=0 ; i<atoi(h_imagem);i++) free(imagem[i]); free(imagem); }
0
#include <pthread.h> pthread_mutex_t mutex; long long number_in_circle; long long threads_tosses; long long ramain_tosses; int SEED; void* tossDarts(void*); int main(int argc, char **argv) { pthread_t* threads; long long number_of_tosses = atoll(argv[1]); long long ramain_tosses; double pi_estimate; long thread, num_threads; num_threads = get_nprocs(); SEED = time(0); threads_tosses = number_of_tosses / num_threads; ramain_tosses = number_of_tosses % num_threads; threads = malloc(sizeof(pthread_t)*num_threads); pthread_mutex_init(&mutex, 0); for(thread = 0; thread < num_threads; thread++) pthread_create(&threads[thread], 0, tossDarts, (void *)thread); pthread_mutex_destroy(&mutex); for(thread = 0; thread < num_threads; thread++) pthread_join(threads[thread], 0); free(threads); pi_estimate = 4*number_in_circle /((double)number_of_tosses); printf("%lf\\n", pi_estimate); return 0; } void* tossDarts(void* arg) { struct drand48_data drand_buf; long long tid = (long long) arg; long long result = 0; long long toss; double x, y; int seed = SEED + tid; long long tosses; srand48_r(seed, &drand_buf); tosses = threads_tosses; if(tid == 0) tosses += ramain_tosses; for(toss = 0; toss < tosses; toss++) { drand48_r(&drand_buf, &x); drand48_r(&drand_buf, &y); if(x*x + y*y <= 1) result++; } pthread_mutex_lock(&mutex); number_in_circle += result; pthread_mutex_unlock(&mutex); return; }
1
#include <pthread.h> int nbr_endormies; int client; pthread_mutex_t mutex; pthread_cond_t nb_changed; pthread_cond_t client_changed; struct fool{ int val; struct fool *next; }; struct fool *first; void consomme_req(struct fool *p); void* traiter_requete(void* arg); void attendre_connexion(); int main() { pthread_t id[4]; int i; nbr_endormies = 4; printf("nbr thread initial=%d\\n",nbr_endormies); client = -1; int adresse; int taille=1000; adresse=creer_segment("sada",taille); initialiser(adresse,taille); errno = pthread_mutex_init(&mutex, 0); if (errno) afficher_erreur("echec de pthread_mutex_init"); errno = pthread_cond_init(&client_changed, 0); if (errno) afficher_erreur("echec de pthread_cond_init"); for (i=0; i<4; i++) { errno = pthread_create(&id[i], 0, traiter_requete, 0); if (errno) afficher_erreur("echec de pthread_create"); } signal(SIGPIPE, SIG_IGN); attendre_connexion(); return 0; } void consomme_req(struct fool *p){ routine(p->val); first= p->next; } void* traiter_requete(void* arg){ struct fool *p; int soc; while (1) { errno = pthread_mutex_lock(&mutex); if (errno) afficher_erreur("echec de pthread_mutex_lock1"); while(client==-1){ errno = pthread_cond_wait(&client_changed, &mutex); if (errno)afficher_erreur("echec de pthread_cond_wait"); } soc=client; client=-1; nbr_endormies--; routine(soc); errno = pthread_mutex_unlock(&mutex); if (errno) afficher_erreur("echec de pthread_mutex_unlock2"); pthread_mutex_lock(&mutex); while(first!=0){ p=pop(first); consomme_req(p); pthread_mutex_unlock(&mutex); printf("moi %d j'ai termine mon travail\\n",(int)pthread_self()); } pthread_mutex_unlock(&mutex); errno=pthread_mutex_lock(&mutex); if (errno) afficher_erreur("echec lock 3"); nbr_endormies++; errno= pthread_mutex_unlock(&mutex); if (errno) afficher_erreur("echec unlock 3"); } } void attendre_connexion(){ int sock_contr=cree_socket_ecoute(8081); printf("Serveur actif sur le port %d socket %d\\n",8081,sock_contr); while (1) { int x; x = accept(sock_contr,0, 0); errno = pthread_mutex_lock(&mutex); if (errno) afficher_erreur("echec de pthread_mutex_lock5"); if(nbr_endormies){ client = x; if (client==-1) { if (errno==EINTR || errno==ECONNABORTED) continue; afficher_erreur("echec de accept"); } errno = pthread_cond_signal(&client_changed); if (errno) afficher_erreur("echec de pthread_cond_signal"); pthread_mutex_unlock(&mutex); } else{ first =push(first,x); printf("thread occupé\\n"); pthread_mutex_unlock(&mutex); } } }
0
#include <pthread.h> static const int DEFAULT = 0644; static pthread_mutex_t bank[10000] = {PTHREAD_MUTEX_INITIALIZER}; void* connection(int pipe[2]); void printHelp(char* programName); struct option longopts[] = { {"file", required_argument, 0, 'f'}, {"jobs", required_argument, 0, 'j'} }; int interResponse; int interDemand; int bankResponse; int bankId; }ConnectionPipe; ConnectionPipe *pipe; char* string; }RemoteAuthData; void* remoteAuth(); static int threadPoolPipe[2]; int main(int argc, char* argv[]){ int poolSize = 1; opterr = 0; int indexptr; int opt; char* *bankList = 0; int bankListSize; while((opt = getopt_long(argc, argv, "j:f:",longopts, &indexptr)) != -1){ switch(opt){ case 'j': poolSize = atoi(optarg); break; case 'f': {}FILE *bankListFile = fopen(optarg,"r"); fseek(bankListFile, 0, 2); int fileSize = ftell(bankListFile); fseek(bankListFile, 0, 0); bankListSize = fileSize/5; bankList = malloc(bankListSize); char* bankList_ = malloc(bankListSize*4+2); for(int i=0; i<bankListSize; i++){ fread(bankList_+(i*4), 1, 5, bankListFile); bankList[i] = bankList_+(i*4); } fclose(bankListFile); break; default: printHelp(argv[0]); return argc; } } if(!bankList){ printHelp(argv[0]); return argc; } pipe(threadPoolPipe); pthread_t threadId[bankListSize]; for(int i=0; i<bankListSize; i++){ char bankPath[20] = {0}; sprintf(bankPath,"resources/bank%.4s",bankList[i]); mkdir(bankPath,0755); char fifoPath[64] = {0}; int *remotePipe = malloc(2*sizeof (int)); sprintf(fifoPath,"%s/interRemoteDemande.fifo",bankPath); mkfifo(fifoPath,DEFAULT); remotePipe[READ] = open(fifoPath,O_RDONLY); sprintf(fifoPath,"%s/response.fifo",bankPath); mkfifo(fifoPath,DEFAULT); remotePipe[WRITE] = open(fifoPath,O_WRONLY); pthread_create(&threadId[i], 0, (void* (*) (void*))connection, (void*)remotePipe); } for(int i=0; i<poolSize; i++){ pthread_t threadId; pthread_create((&threadId) + (i*sizeof (pthread_t)), 0, remoteAuth, 0); } for(int i=0; i<bankListSize; i++){ pthread_join(threadId[i],0); } return 0; } void* connection(int *associatedBank_){ int associatedBank[] = {associatedBank_[0], associatedBank_[1]}; char cardNumber[16+1]; char messageType[7+1]; char value[13+1]; int end = 0; while(!end){ errno = 0; char* string = litLigne(associatedBank[READ]); if(string == 0 || decoupe(string,cardNumber,messageType,value) == 0){ perror("(interbancaire(connection)) message is wrong format"); end = 1; break; } ConnectionPipe *remotePipe = malloc(sizeof (ConnectionPipe)); remotePipe->bankResponse = dup(associatedBank[WRITE]); char bankId[5]; sprintf(bankId,"%.4s",cardNumber); remotePipe->bankId = atoi(bankId); char bankPath[20] = {0}; sprintf(bankPath,"resources/bank%.4s",bankId); mkdir(bankPath,0755); char fifoPath[64] = {0}; sprintf(fifoPath,"%s/remoteInput.fifo",bankPath); mkfifo(fifoPath,DEFAULT); remotePipe->interDemand = open(fifoPath,O_WRONLY); sprintf(fifoPath,"%s/interRéponse.fifo",bankPath); mkfifo(fifoPath,DEFAULT); remotePipe->interResponse = open(fifoPath,O_RDONLY); RemoteAuthData *data = malloc(sizeof (RemoteAuthData)); data->pipe = remotePipe; data->string = string; write(threadPoolPipe[WRITE], &data, sizeof (void*)); } return (void*)1; } void* remoteAuth(){ RemoteAuthData *data; while(read(threadPoolPipe[READ], &data, sizeof (void*)) != -1){ ConnectionPipe *remotePipe = data->pipe; char* string = data->string; pthread_mutex_lock(bank+remotePipe->bankId); ecritLigne(remotePipe->interDemand, string); free(string); string = litLigne(remotePipe->interResponse); pthread_mutex_unlock(bank+remotePipe->bankId); ecritLigne(remotePipe->bankResponse, string); close(remotePipe->interDemand); close(remotePipe->interResponse); close(remotePipe->bankResponse); free(remotePipe); free(string); free(data); } return 0; } void printHelp(char* programName){ fprintf( stderr, "Usage : %s [OPTION]...\\n" " -f,--file\\t a file containing a list of bankId (mandatory)\\n" " -j,--jobs\\t number of slot available for concurrent routing\\n", programName ); }
1
#include <pthread.h> struct queue_type *reorder_buffer; void alloc_reorder_buffer(struct ftl_request p_ftl_req) { struct queue_node *q_node_iter; for (q_node_iter = reorder_buffer->head; q_node_iter != 0; q_node_iter = q_node_iter->next) { if (q_node_iter->ftl_req.id == p_ftl_req.id) { break; } } if (q_node_iter == 0) { p_ftl_req.ack = UNDEFINE_INT; enqueue(reorder_buffer, p_ftl_req); } } void put_reorder_buffer(struct ftl_request p_ftl_req) { struct queue_node *q_node_iter; struct ftl_request ftl_req; for (q_node_iter = reorder_buffer->head; q_node_iter != 0; q_node_iter = q_node_iter->next) { if (q_node_iter->ftl_req.id == p_ftl_req.id) { q_node_iter->ftl_req = p_ftl_req; break; } } if (q_node_iter == 0) assert(0); for (q_node_iter = reorder_buffer->head; q_node_iter != 0; q_node_iter = reorder_buffer->head) { if (q_node_iter->ftl_req.ack == UNDEFINE_INT) { break; } else { ftl_req = dequeue(reorder_buffer); pthread_mutex_lock(&nand_to_ftl->mutex); if_enqueue(nand_to_ftl, ftl_req, 0); pthread_mutex_unlock(&nand_to_ftl->mutex); } } }
0
#include <pthread.h> { char key[8]; char data[56]; } Record; { Record *array; int tid; int lowRec; int hiRec; } ThdArg; void *runner(void *param); int compare(const void *a, const void *b); void mergesort(Record *array, int arrayLength); int curNumThreads; int minThreadSize; pthread_mutex_t threadLock; int main(int argc, char *argv[]) { int nThreads = atoi(argv[1]); FILE *file = fopen(argv[2], "r"); if(file == 0) { fprintf(stderr, "Can't open file\\n"); exit(1); } fseek(file, 0L, 2); int FileSize = ftell(file); rewind(file); printf("Num Threads: %d\\nFile Name: %s\\nFile Size: %d\\n", nThreads, argv[2], FileSize); int nRecs = FileSize / sizeof(Record); printf("The number of records is: %d\\n", nRecs); int nRecsPerThd = nRecs / nThreads; printf("The number of records per thread is: %d\\n", nRecsPerThd); int n = sysconf(_SC_NPROCESSORS_ONLN); printf("The number of cores is: %d\\n", n); Record recs[nRecs]; Record newRec; char *line = 0; size_t len = 0; ssize_t read; int recNum = 0; for(int i = 0; i < nRecs; i++) { read = getline(&line, &len, file); strncpy(newRec.key, line, 8); strncpy(newRec.data, line+8, 8 +56); recs[recNum] = newRec; recNum++; } printf("Before Sorting\\n"); for(int i = 0; i < nRecs; i++) { printf("%.*s%.*s \\n", 8, recs[i].key, 56,recs[i].data); } minThreadSize = nRecsPerThd; pthread_t tid; pthread_attr_t attr; mergesort(recs, nRecs); printf("After Sorting\\n"); for(int i = 0; i < nRecs; i++) { printf("%.*s%.*s \\n", 8, recs[i].key, 56, recs[i].data); } fclose(file); } Record* merge(Record *array, int low, int hi, int tid) { printf("Merging\\n"); int center = 0; int i = low; int mid = low + ((hi - low)/2); int j = mid + 1; Record *c = (Record *) malloc((hi-low+1) * sizeof(Record)); while(i <= mid && j <= hi) { if(array[i].key <= array[j].key) { j++; c[center] = array[j]; } else { center++; j++; c[center] = array[j]; } } if(i == mid + 1) { while(j <= hi) { center++; j++; c[center] = array[j]; } } else { while(i <= mid) { center++; j++; c[center] = array[i]; } } i = low; center = 0; while(i <= hi) { i++; center++; array[i] = c[center]; } free(c); } void mergesort(Record *array, int arrayLength) { ThdArg threadArgument; threadArgument.array = array; threadArgument.lowRec = 0; threadArgument.hiRec = arrayLength; curNumThreads = 0; pthread_mutex_init(&threadLock, 0); threadArgument.tid = 0; pthread_t thread; printf("Initial Thread Created\\n"); pthread_create(&thread, 0, runner, &threadArgument); pthread_join(thread, 0); } void *runner(void *param) { ThdArg *thdArg = (ThdArg *) param; int l = thdArg->lowRec; int h = thdArg->hiRec; int t = thdArg->tid; if(h - 1 + 1 <= minThreadSize) { qsort(thdArg->array+1, h-l+1, sizeof(ThdArg), compare); } else { int m = l + ((h-1)/2); ThdArg firstArg; firstArg.lowRec = l; firstArg.hiRec = h; firstArg.array = thdArg->array; pthread_mutex_lock(&threadLock); firstArg.tid = curNumThreads++; pthread_mutex_unlock(&threadLock); pthread_t firstThread; pthread_create(&firstThread, 0, runner, &firstArg); ThdArg secArg; secArg.lowRec = m + 1; secArg.hiRec = h; secArg.array = thdArg->array; pthread_mutex_lock(&threadLock); secArg.tid = curNumThreads++; pthread_mutex_unlock(&threadLock); pthread_t secondThread; pthread_create(&secondThread, 0, runner, &secArg); pthread_join(firstThread, 0); pthread_join(secondThread, 0); merge(thdArg->array, l, h, t); } pthread_exit(0); } int compare(const void *a, const void *b) { Record *recA = (Record *)a; Record *recB = (Record *)b; return (recB->key - recA->key); }
1
#include <pthread.h> int pthread_cancel (pthread_t t) { int err = 0; struct pthread_internal_t *p = (struct pthread_internal_t*) t; pthread_init(); pthread_mutex_lock (&p->cancel_lock); if (p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_PENDING) { pthread_mutex_unlock (&p->cancel_lock); return 0; } p->attr.flags |= PTHREAD_ATTR_FLAG_CANCEL_PENDING; if (!(p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_ENABLE)) { pthread_mutex_unlock (&p->cancel_lock); return 0; } if (p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_ASYNCRONOUS) { pthread_mutex_unlock (&p->cancel_lock); err = __pthread_do_cancel (p); } else { pthread_mutex_unlock (&p->cancel_lock); } return err; }
0
#include <pthread.h> int func_num; } tagTHDATA; pthread_mutex_t g_mutex; void *thread_func0(void* pData) { tagTHDATA* pThdata = (tagTHDATA*)pData; while (1) { printf("--func%d --wait mutex-----\\n", pThdata->func_num); pthread_mutex_lock(&g_mutex); printf("--func%d-- get mutex -----\\n", pThdata->func_num); printf("** func%d-- do function -----\\n", pThdata->func_num); usleep(2*1000*1000); printf("--func%d-- finish function -----\\n", pThdata->func_num); printf("--func%d-- mutex_release -----\\n", pThdata->func_num); pthread_mutex_unlock(&g_mutex); usleep(1); } } void *thread_func1(void* pData) { tagTHDATA* pThdata = (tagTHDATA*)pData; while (1) { printf("--func%d --wait mutex-----\\n", pThdata->func_num); pthread_mutex_lock(&g_mutex); printf("--func%d-- get mutex -----\\n", pThdata->func_num); printf("** func%d-- do function -----\\n", pThdata->func_num); usleep(2*1000*1000); printf("--func%d-- finish function -----\\n", pThdata->func_num); printf("--func%d-- mutex_release -----\\n", pThdata->func_num); pthread_mutex_unlock(&g_mutex); usleep(1); } } void *thread_func2(void* pData) { tagTHDATA* pThdata = (tagTHDATA*)pData; while (1) { printf("--func%d --wait mutex-----\\n", pThdata->func_num); pthread_mutex_lock(&g_mutex); printf("--func%d-- get mutex -----\\n", pThdata->func_num); printf("** func%d-- do function -----\\n", pThdata->func_num); usleep(2*1000*1000); printf("--func%d-- finish function -----\\n", pThdata->func_num); printf("--func%d-- mutex_release -----\\n", pThdata->func_num); pthread_mutex_unlock(&g_mutex); usleep(1); } } void *thread_func3(void* pData) { tagTHDATA* pThdata = (tagTHDATA*)pData; while (1) { printf("--func%d --wait mutex-----\\n", pThdata->func_num); pthread_mutex_lock(&g_mutex); printf("--func%d-- get mutex -----\\n", pThdata->func_num); printf("** func%d-- do function -----\\n", pThdata->func_num); usleep(2*1000*1000); printf("--func%d-- finish function -----\\n", pThdata->func_num); printf("--func%d-- mutex_release -----\\n", pThdata->func_num); pthread_mutex_unlock(&g_mutex); usleep(1); } } int main() { int i; const int THREAD_NUM = 4; tagTHDATA thdata[THREAD_NUM]; for (i = 0; i < THREAD_NUM; i++) { thdata[i].func_num = i; } pthread_t th[4]; pthread_mutex_init(&g_mutex, 0); pthread_create(&th[0], 0, thread_func0, (void*)&thdata[0]); usleep(1000); pthread_create(&th[1], 0, thread_func1, (void*)&thdata[1]); usleep(1000); pthread_create(&th[2], 0, thread_func2, (void*)&thdata[2]); usleep(1000); pthread_create(&th[3], 0, thread_func3, (void*)&thdata[3]); usleep(1*1000*1000); for (i = 0; i < THREAD_NUM; i++){ pthread_join(th[i], 0); } return 0; }
1
#include <pthread.h> pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER; int log_priority = LOG_ERR; int use_syslog; FILE *logfd; static void * signal_set(int signo, void (*func) (int)) { int r; struct sigaction sig; struct sigaction osig; sig.sa_handler = func; sigemptyset(&sig.sa_mask); sig.sa_flags = 0; r = sigaction(signo, &sig, &osig); if (r < 0) return (SIG_ERR); else return (osig.sa_handler); } static void sigend(int sig) { pthread_mutex_lock(&exit_mutex); pthread_cond_signal(&exit_cond); pthread_mutex_unlock(&exit_mutex); } int trawl_dir(char *dirname) { int num_files = 0; char fullpath[PATH_MAX]; struct stat dirst; time_t dtime; DIR *dirfd; struct dirent *dirent; if (stat(dirname, &dirst) < 0) { err("Cannot open %s: error %d", dirname, errno); return 0; } if (difftime(dirst.st_atime, dirst.st_mtime) < 0) { dtime = dirst.st_atime; } else { dtime = dirst.st_mtime; } if (!S_ISDIR(dirst.st_mode)) { return 1; } if (insert_inotify(dirname, 0) < 0) return 0; dirfd = opendir(dirname); if (!dirfd) { err("Cannot open directory %s: error %d", dirname, errno); return 0; } while ((dirent = readdir(dirfd))) { if (!strcmp(dirent->d_name, ".")) continue; if (!strcmp(dirent->d_name, "..")) continue; if(snprintf(fullpath, PATH_MAX, "%s/%s", dirname, dirent->d_name) >= PATH_MAX) { err("%s/%s: pathname overflow", dirname, dirent->d_name); } if ((dirent->d_type & DT_REG) || (dirent->d_type & DT_DIR)) num_files += trawl_dir(fullpath); } closedir(dirfd); return num_files; } unsigned long parse_time(char *optarg) { struct tm c; char *p, *e; unsigned long val; double ret = 0; time_t now, test; now = test = time(0); if (localtime_r(&now, &c) == 0) { err("Cannot initialize time, error %d", errno); return 0; } p = optarg; while (p) { val = strtoul(p, &e, 10); if (p == e) break; dbg("%s %s %lu", p, e, val); if (!p) { ret = val; break; } switch (*e) { case 'Y': dbg("mon: %d %lu", c.tm_mon, val); c.tm_year += val; break; case 'M': dbg("mon: %d %lu", c.tm_mon, val); c.tm_mon += val; break; case 'D': dbg("day: %d %lu", c.tm_mday, val); c.tm_mday += val + 1; break; case 'h': dbg("hour: %d %lu", c.tm_hour, val); c.tm_hour += val; break; case 'm': dbg("min: %d %lu", c.tm_min, val); c.tm_min += val; break; case 's': dbg("sec: %d %lu", c.tm_sec, val); c.tm_sec += val; break; default: err("Invalid time specifier '%c'", *e); break; } p = e + 1; } test = mktime(&c); if (test == (time_t)-1) { err("Failed to convert time '%s'", optarg); ret = -1; } ret = difftime(test, now); info("Checking every %lu secs", (long)ret); return (long)ret; } int main(int argc, char **argv) { int i, num_files; char init_dir[PATH_MAX]; unsigned long checkinterval; time_t starttime, endtime; double elapsed; while ((i = getopt(argc, argv, "c:d:")) != -1) { switch (i) { case 'c': checkinterval = parse_time(optarg); if (checkinterval < 0) { err("Invalid time '%s'", optarg); return 1; } break; case 'd': realpath(optarg, init_dir); break; default: err("usage: %s [-d <dir>]", argv[0]); return 1; } } if (optind < argc) { err("usage: %s [-d <dir>]", argv[0]); return EINVAL; } if ('\\0' == init_dir[0]) { strcpy(init_dir, "/"); } if (!strcmp(init_dir, "..")) { if (chdir(init_dir) < 0) { err("Failed to change to parent directory: %d", errno); return errno; } sprintf(init_dir, "."); } if (!strcmp(init_dir, ".") && !getcwd(init_dir, PATH_MAX)) { err("Failed to get current working directory"); return errno; } signal_set(SIGINT, sigend); signal_set(SIGTERM, sigend); start_watcher(); starttime = time(0); info("Starting at '%s'", init_dir); num_files = trawl_dir(init_dir); endtime = time(0); elapsed = difftime(endtime, starttime); info("Checked %d files in %f seconds", num_files, elapsed); list_events(); pthread_cond_wait(&exit_cond, &exit_mutex); stop_watcher(); return 0; }
0
#include <pthread.h> pthread_t bg_manager; pthread_mutex_t bg_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t bg_wait = PTHREAD_COND_INITIALIZER; pthread_mutex_t net_lock = PTHREAD_MUTEX_INITIALIZER; int acquire_netlock() { pthread_mutex_lock(&net_lock); int s = get_mode(); if(s == -1) { pthread_mutex_unlock(&net_lock); return 1; } return 0; } void release_netlock() { pthread_mutex_unlock(&net_lock); } int add_umessage(struct message *m) { int ret = 0; uint8_t *sender = &m->message[0x01]; uint8_t *payload = &m->message[0x29]; uint8_t type = m->message[0x29]; char s_hex[65]; to_hex(sender, 0x20, s_hex); LOG("message from %s of length %llu", s_hex, m->length); uint64_t p_len = decbe64(&m->message[0x21]); if(p_len + 0x29 != m->length) { return -1; } switch(type) { case 0: ret = parse_conv_message(sender, payload, p_len); break; case 1: ret = parse_friendreq(sender, payload, p_len); break; case 2: ret = parse_friendreq_response(sender, payload, p_len); break; } return ret; } int add_pkeyresp(struct message *m) { pthread_mutex_lock(&bg_lock); if(get_mode() != 2) { pthread_mutex_unlock(&bg_lock); return -1; } pkey_resp = m; pthread_cond_broadcast(&bg_wait); pthread_mutex_unlock(&bg_lock); return 0; } int add_unotfound(struct message *m) { pthread_mutex_lock(&bg_lock); if(get_mode() != 2) { pthread_mutex_unlock(&bg_lock); return -1; } pkey_resp = m; pthread_cond_broadcast(&bg_wait); pthread_mutex_unlock(&bg_lock); return 0; } void *background_thread(void *_arg) { struct server_connection *sc = (struct server_connection *) _arg; while(get_mode() != -1) { if(acquire_netlock() != 0) break; struct message *m = recv_message(sc->ch, &sc->keys, ((uint64_t) 10000ULL)); if(handler_status(sc->ch) != 0) { set_mode(-1); } if(m == 0) { release_netlock(); continue; } int ret = 0; switch(m->message[0]) { case 0: ret = add_umessage(m); break; case 1: ret = add_pkeyresp(m); break; case 0xff: ret = add_unotfound(m); break; } if(ret != 0) { break; } release_netlock(); } release_netlock(); ERR("background thread crashed"); acquire_writelock(&lock); stop = 1; release_writelock(&lock); set_mode(-1); pthread_cond_broadcast(&bg_wait); return 0; } int start_bg_thread(struct server_connection *sc) { if(pthread_create(&bg_manager, 0, background_thread, sc) != 0) { ERR("failed to start background thread"); return -1; } return 0; }
1
#include <pthread.h> char buffer_teste[40]; void iniciaRede(){ int te, tr,tet,trt; pthread_t te_rede, tr_rede, te_tabela_rotas,tr_tabela_rotas; te = pthread_create(&te_rede, 0, Prod_rede, 0); if (te) { printf("ERRO: impossivel criar a thread"); exit(-1); } tr = pthread_create(&tr_rede, 0,Cons_rede, 0); if (tr) { printf("ERRO: impossivel criar a thread : receberDatagramas\\n"); exit(-1); } tet = pthread_create(&te_tabela_rotas, 0, Envia_tabela, 0); if (te) { printf("ERRO: impossivel criar a thread"); exit(-1); } trt = pthread_create(&tr_tabela_rotas, 0,Recebe_tabela, 0); if (tr) { printf("ERRO: impossivel criar a thread : receberDatagramas\\n"); exit(-1); } pthread_join(te_rede, 0); pthread_join(tr_rede, 0); pthread_join(te_tabela_rotas,0); pthread_join(tr_tabela_rotas, 0); } void *Prod_rede() { while (1) { pthread_mutex_lock(&env1); int no=10; char *datagrama; printf("Deseja enviar para qual nó?\\n"); scanf("%d", &no); printf("Escreva uma mensagem para enviar:\\n"); strcpy(data_env.buffer,""); scanf("%s",data_env.buffer); printf("Matriz:%d\\n",matriz[1][1]); data_env.tam_buffer = strlen(data_env.buffer); data_env.no_envio = no; pthread_mutex_unlock(&env2); } } void *Cons_rede() { while (1) { pthread_mutex_lock(&rcv2); if (data_rcv.tam_buffer != 0) { printf("\\n\\nTeste-> Tam_buffer: %d Bytes, Buffer: %s\\n", data_rcv.tam_buffer, data_rcv.buffer); pthread_mutex_unlock(&rcv1); } } } void *Envia_tabela(){ } void *Recebe_tabela(){ } void *Atualizar_tabela(){ }
0
#include <pthread.h> struct job { struct job* next; int dato; }; struct job* job_queue; pthread_mutex_t job_queue_mutex; pthread_cond_t thread_flag_cv; int thread_flag; void initialize_flag (){ pthread_mutex_init (&job_queue_mutex, 0); pthread_cond_init (&thread_flag_cv, 0); thread_flag = 0; } void set_thread_flag (int flag_value){ pthread_mutex_lock (&job_queue_mutex); thread_flag = flag_value; pthread_cond_signal (&thread_flag_cv); pthread_mutex_unlock (&job_queue_mutex); } void* raiz_cuadrada (void* arg){ while (1){ struct job* next_job; pthread_mutex_lock (&job_queue_mutex); while (!thread_flag){ pthread_cond_wait (&thread_flag_cv, &job_queue_mutex); } if (job_queue == 0){ next_job = 0; }else{ next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0){ break; } set_thread_flag(1); printf("Raiz %d = %f\\n",next_job->dato,sqrt(next_job->dato)); free (next_job); } return 0; } void* logaritmo (void* arg){ while (1){ struct job* next_job; pthread_mutex_lock (&job_queue_mutex); while (!thread_flag){ pthread_cond_wait (&thread_flag_cv, &job_queue_mutex); } if (job_queue == 0){ next_job = 0; }else{ next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0){ break; } set_thread_flag(1); printf("Logaritmo %d = %f\\n",next_job->dato,log(next_job->dato)); free (next_job); } return 0; } void* exponencia (void* arg){ while (1){ struct job* next_job; pthread_mutex_lock (&job_queue_mutex); while (!thread_flag){ pthread_cond_wait (&thread_flag_cv, &job_queue_mutex); } if (job_queue == 0){ next_job = 0; }else{ next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0){ break; } set_thread_flag(1); printf("Exponencial %d = %f\\n",next_job->dato,exp(next_job->dato)); free (next_job); } return 0; } void enqueue_job (int dato){ struct job* new_job; new_job = (struct job*) malloc (sizeof (struct job)); pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new_job; job_queue->dato = dato; pthread_mutex_unlock (&job_queue_mutex); } int main(int argc, char const *argv[]){ int i; pthread_t hilo1, hilo2, hilo3; job_queue = 0; for (i = 1; i < 101; i++){ enqueue_job(i); } set_thread_flag(1); pthread_create (&hilo3, 0, &exponencia,0); pthread_create (&hilo2, 0, &logaritmo,0); pthread_create (&hilo1, 0, &raiz_cuadrada,0); pthread_join (hilo1,0); pthread_join (hilo2,0); pthread_join (hilo3,0); return 0; }
1
#include <pthread.h> void gw_dm_failed ( void *_job_id ) { gw_job_t * job; int job_id; if ( _job_id != 0 ) { job_id = *( (int *) _job_id ); job = gw_job_pool_get(job_id, GW_TRUE); if ( job == 0 ) { gw_log_print("DM",'E',"Job %i does not exist (JOB_STATE_FAILED).\\n",job_id); free(_job_id); return; } } else return; gw_log_print("DM",'I',"Job %i failed.\\n",job->id); gw_job_set_state(job, GW_JOB_STATE_FAILED, GW_FALSE); gw_job_print(job,"DM",'I',"Job failed, history:\\n"); gw_job_print_history(job); job->exit_time = time(0); if (job->history != 0) job->history->reason = GW_REASON_EXECUTION_ERROR; if ( job->client_waiting > 0 ) gw_am_trigger(gw_dm.rm_am,"GW_RM_WAIT_SUCCESS", _job_id); else free(_job_id); gw_user_pool_dec_running_jobs(job->user_id); pthread_mutex_lock(&(job->history->host->mutex)); job->history->host->running_jobs--; pthread_mutex_unlock(&(job->history->host->mutex)); pthread_mutex_unlock(&(job->mutex)); }
0
#include <pthread.h> struct img_struct* current_frame; unsigned long seqNumF; double dt2; int locX, locY; pthread_t object_detect_thread; pthread_mutex_t location_access_mutex=PTHREAD_MUTEX_INITIALIZER; struct point findBlob(struct img_struct* frame, unsigned char Ymin, unsigned char Ymax, unsigned char Umin, unsigned char Umax, unsigned char Vmin, unsigned char Vmax) { struct point centre; centre.x = 0; centre.y = 0; unsigned int i, x, y, count = 0; unsigned char Y, U, V; for(i = 2; i < frame->w*frame->h*2; i+=4) { V = *((unsigned char*)frame->buf + i); if(V>=Vmin && V<=Vmax) { *((unsigned char*)frame->buf + i) = 0; centre.x += (i%(frame->w*2))/2; centre.y += i/(frame->w*2); count++; } } if(count > 5) { centre.x /= count; centre.y /= count; } else { centre.x = frame->w/2; centre.y = frame->h/2; } return centre; } struct img_struct* compress_frame(struct img_struct* input_frame) { int i; for(i = 0; i < input_frame->w*input_frame->h/2; i++) { unsigned int fact = 2*(i%640) + 2560*((int)(i/640)); *((unsigned char*)input_frame->buf + i) = ( *((unsigned char*)input_frame->buf + (fact)) + *((unsigned char*)input_frame->buf + (fact + 1)) + *((unsigned char*)input_frame->buf + (fact + 640)) + *((unsigned char*)input_frame->buf + (fact + 641)))/4; } return input_frame; } void *object_detect_thread_main(void *data) { printf("Tracking...\\n"); double prevTime = 0.0; for (;;) { if (current_frame != 0) { struct point blob_loc = findBlob(current_frame, 91, 100, 130, 136, 160, 240); double currentTime = util_timestamp(); pthread_mutex_lock(&location_access_mutex); dt2 = currentTime-prevTime; int temp = (int)(blob_loc.x)/10; locX = 10*temp - current_frame->w/2; temp = (int)(blob_loc.y)/10; locY = -10*temp + current_frame->h/2; prevTime=currentTime; seqNumF++; pthread_mutex_unlock(&location_access_mutex); } } return 0; } int object_detect_init(struct object_detect_struct *od) { seqNumF=0; locX=0; locY=0; dt2=0; int rc = pthread_create(&object_detect_thread, 0, object_detect_thread_main, 0); if(rc) { printf("ctl_Init: Return code from pthread_create(object_detect_thread) is %d\\n", rc); return 202; } return 0; } void object_detect_getSample(struct object_detect_struct *od) { pthread_mutex_lock(&location_access_mutex); if(dt2>0) { od->locX=locX; od->locY=locY; od->dt=dt2; } od->seqNum=seqNumF; pthread_mutex_unlock(&location_access_mutex); } void object_detect_print(struct object_detect_struct *od, double xpos, double ypos) { printf("seq=%ld locX=%5.1f,locY=%5.1f, dt=%4.1f xpos=%4.1f ypos=%4.1f\\n" ,od->seqNum ,od->locX ,od->locY ,od->dt*1000 ,xpos ,ypos ); } void object_detect_close() { }
1
#include <pthread.h> int number; pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER; void *consumer(void *dummy) { int printed= 0; " now\\"\\n", pthread_self()); while (1) { pthread_mutex_lock(&mu); pthread_mutex_unlock(&mu); if (number == 10) { printf("Consumer done.. !!\\n"); break; } } } void *producer(void *dummy) { " now\\"\\n", pthread_self()); while (1) { pthread_mutex_lock(&mu); number ++; printf("Producer : %d\\n", number); if (number != 10) pthread_mutex_unlock(&mu); if (number == 10) { printf("Producer done.. !!\\n"); break; } } } int main() { int rc, i; pthread_t t[2]; number= 0; if ((rc= pthread_create(&t[1], 0, producer, 0))) printf("Error creating the producer thread..\\n"); if ((rc= pthread_create(&t[0], 0, consumer, 0))) printf("Entered an error while creating the 1st consumer thread..\\n"); if ((rc= pthread_create(&t[2], 0, consumer, 0))) printf("Entered an error while creating the 2nd consumer thread..\\n"); for (i= 0; i < 2; i ++) pthread_join(t[i], 0); printf("Done..\\n"); return number; }
0
#include <pthread.h> int hilos_entradaActivo; int active_work; void *KEY; int bufSize = 0; FILE *file_in; FILE *file_out; pthread_mutex_t mutexIN; pthread_mutex_t mutexWORK; pthread_mutex_t mutexOUT; char data; off_t offset; char state; } BufferItem; BufferItem *result; void thread_sleep(void); int estaELbufferVacio(); int vaciarArchivoAbuffer(); int hilosTrabajadoresSobreBuffer(); int hilosEncriptadoresSobreBuffer(); void inicializarBuffer(); void *IN_thread(void *param); void *WORK_thread(void *param); void *OUT_thread(void *param); int main(int argc, char *argv[]){ int i = 0; int nIN; int nOUT; int nWORK; pthread_mutex_init(&mutexIN, 0); pthread_mutex_init(&mutexWORK, 0); pthread_mutex_init(&mutexOUT, 0); if(strcmp(argv[1],"-e")==0) nIN = atoi(argv[2]); nWORK=nIN; KEY = "3"; if(strcmp(argv[3],"-d")==0) nOUT = atoi(argv[4]); if(strcmp(argv[5],"-m")==0) file_in = fopen(argv[6], "r"); if(strcmp(argv[7],"-f")==0) file_out = fopen(argv[8], "w"); bufSize = 5; hilos_entradaActivo = nIN; active_work = nWORK; pthread_t INthreads[nIN]; pthread_t OUTthreads[nOUT]; pthread_t WORKthreads[nWORK]; pthread_attr_t attr; pthread_attr_init(&attr); result = (BufferItem*)malloc(sizeof(BufferItem)*bufSize); inicializarBuffer(); int keyCheck = atoi(KEY); for (i = 0; i < nIN; i++){ pthread_create(&INthreads[i], &attr, (void *) IN_thread, file_in); } for (i = 0; i < nWORK; i++){ pthread_create(&WORKthreads[i], &attr, (void *) WORK_thread, KEY); } for (i = 0; i < nOUT; i++){ pthread_create(&OUTthreads[i], &attr, (void *) OUT_thread, file_out); } for (i = 0; i < nIN; i++){ pthread_join(INthreads[i], 0); } for (i = 0; i < nWORK; i++){ pthread_join(WORKthreads[i], 0); } for (i = 0; i < nOUT; i++){ pthread_join(OUTthreads[i], 0); } pthread_mutex_destroy(&mutexIN); pthread_mutex_destroy(&mutexOUT); pthread_mutex_destroy(&mutexWORK); fclose(file_in); fclose(file_out); free(result); return 0; } void thread_sleep(void){ struct timespec t; int seed = 0; t.tv_sec = 0; t.tv_nsec = rand_r((unsigned int*)&seed)%(10000000+1); nanosleep(&t, 0); } int estaELbufferVacio(){ int i = 0; while (i < bufSize){ if (result[i].state == 'e'){ return 1; } i++; } return 0; } int vaciarArchivoAbuffer(){ int i = 0; if (estaELbufferVacio()){ while (i < bufSize){ if (result[i].state == 'e'){ return i; } i++; } } return -1; } int hilosTrabajadoresSobreBuffer(){ int i = 0; while (i < bufSize){ if (result[i].state == 'w'){ return i; } i++; } return -1; } int hilosEncriptadoresSobreBuffer(){ int i = 0; while (i < bufSize){ if (result[i].state == 'o'){ return i; } i++; } return -1; } void inicializarBuffer(){ int i = 0; while (i < bufSize){ result[i].state = 'e'; i++; } } void *IN_thread(void *param){ int index; char curr; off_t offset; thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = vaciarArchivoAbuffer(); while (index > -1){ if (estaELbufferVacio() == 1) { thread_sleep(); } pthread_mutex_lock(&mutexIN); offset = ftell(file_in); curr = fgetc(file_in); pthread_mutex_unlock(&mutexIN); if (curr == EOF){ break; } else{ result[index].offset = offset; result[index].data = curr; result[index].state = 'w'; index = vaciarArchivoAbuffer(); } } pthread_mutex_unlock(&mutexWORK); } while (!feof(file_in)); thread_sleep(); pthread_mutex_lock(&mutexWORK); hilos_entradaActivo--; pthread_mutex_unlock(&mutexWORK); return 0; } void *WORK_thread(void *param){ int index = 0; int local_active_in; char curr; int key = atoi(param); thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = hilosTrabajadoresSobreBuffer(); if (index > -1){ curr = result[index].data; if (estaELbufferVacio() == 1) { thread_sleep(); } if (curr == EOF || curr == '\\0'){ break; } if (key >= 0 && curr > 31 && curr < 127){ curr = (((int)curr-32)+2*95+key)%95+32; } else if (key < 0 && curr > 31 && curr < 127){ curr = (((int)curr-32)+2*95-(-1*key))%95+32; } result[index].data = curr; result[index].state = 'o'; } local_active_in = hilos_entradaActivo; pthread_mutex_unlock(&mutexWORK); } while (index > -1 || local_active_in > 0); thread_sleep(); pthread_mutex_lock(&mutexWORK); active_work--; pthread_mutex_unlock(&mutexWORK); return 0; } void *OUT_thread(void *param){ int index = 0; char curr; off_t offset; int local_active_work; thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = hilosEncriptadoresSobreBuffer(); if (index > -1){ offset = result[index].offset; curr = result[index].data; if (estaELbufferVacio() == 1) { thread_sleep(); } pthread_mutex_lock(&mutexOUT); if (fseek(file_out, offset, 0) == -1) { fprintf(stderr, "error %u\\n", (unsigned int) offset); exit(-1); } if (fputc(curr, file_out) == EOF) { fprintf(stderr, "error %d \\n", curr); exit(-1); } pthread_mutex_unlock(&mutexOUT); result[index].data = '\\0'; result[index].state = 'e'; result[index].offset = 0; } local_active_work = active_work; pthread_mutex_unlock(&mutexWORK); } while (index > -1 || local_active_work > 0); thread_sleep(); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; uint32_t goal = UINT32_MAX - 100; void run_atomic(uint32_t *bob) { while(*bob < goal) __sync_fetch_and_add(bob, 1); } void run_mutex(uint32_t *bob) { while(*bob < goal) { pthread_mutex_lock(&mutex); (*bob)++; pthread_mutex_unlock(&mutex); } } int main() { uint32_t bob = 0; struct timespec start, end; float delta = 0.0; int thread_count = 4; pthread_t threads[thread_count]; pthread_mutex_init(&mutex, 0); pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex); printf("This shouldn't happen\\n"); clock_gettime(CLOCK_MONOTONIC, &start); bob = 0; while(bob < goal) bob++; clock_gettime(CLOCK_MONOTONIC, &end); delta = 1.0 * (end.tv_sec - start.tv_sec) + (1.0 * (end.tv_nsec - start.tv_nsec) / 1000000000); printf("%-12s: %6.3f %u\\n", "Unprotected", delta, bob); clock_gettime(CLOCK_MONOTONIC, &start); bob = 0; run_atomic(&bob); clock_gettime(CLOCK_MONOTONIC, &end); delta = 1.0 * (end.tv_sec - start.tv_sec) + (1.0 * (end.tv_nsec - start.tv_nsec) / 1000000000); printf("%-12s: %6.3f %u\\n", "Atomic", delta, bob); clock_gettime(CLOCK_MONOTONIC, &start); bob = 0; run_mutex(&bob); clock_gettime(CLOCK_MONOTONIC, &end); delta = 1.0 * (end.tv_sec - start.tv_sec) + (1.0 * (end.tv_nsec - start.tv_nsec) / 1000000000); printf("%-12s: %6.3f %u\\n", "Mutex", delta, bob); clock_gettime(CLOCK_MONOTONIC, &start); bob = 0; for(int i = 0; i < thread_count; i++) pthread_create(&threads[i], 0, (void *) &run_atomic, &bob); for(int i = 0; i < thread_count; i++) pthread_join(threads[i], 0); clock_gettime(CLOCK_MONOTONIC, &end); delta = 1.0 * (end.tv_sec - start.tv_sec) + (1.0 * (end.tv_nsec - start.tv_nsec) / 1000000000); printf("%-12s: %6.3f %u\\n", "Atomic MT", delta, bob); clock_gettime(CLOCK_MONOTONIC, &start); bob = 0; for(int i = 0; i < thread_count; i++) pthread_create(&threads[i], 0, (void *) &run_mutex, &bob); for(int i = 0; i < thread_count; i++) pthread_join(threads[i], 0); clock_gettime(CLOCK_MONOTONIC, &end); delta = 1.0 * (end.tv_sec - start.tv_sec) + (1.0 * (end.tv_nsec - start.tv_nsec) / 1000000000); printf("%-12s: %6.3f %u\\n", "Mutex MT", delta, bob); return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo *foo_alloc(int id) { struct foo *fp; int idx; if((fp = malloc(sizeof(struct foo))) != 0){ fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock,0) != 0){ free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp!=0;fp = fp->f_next){ if(fp->f_id == id){ foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count == 1){ pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count!=1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp -> f_id)%29); tfp = fh[idx]; if(tfp == fp){ fh[idx] =fp->f_next; }else{ while(tfp->f_next!=fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); }else{ fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> pthread_mutex_t mutex ; void thread1(void *arg) ; void thread2(void *arg) ; int main(void) { int *status1, *status2 ; pthread_t thid1 ,thid2; pthread_mutexattr_t mutexattr ; mutexattr.__align = PTHREAD_MUTEX_RECURSIVE_NP ; pthread_mutex_init (&mutex, &mutexattr) ; if(pthread_create(&thid1, 0, (void *)thread1, 0) != 0) { printf ("new thread create failed\\n") ; } if(pthread_create(&thid2, 0, (void *)thread2, 0) != 0) { printf ("new thread create failed\\n") ; } pthread_join (thid1, (void *)&status1) ; pthread_join (thid2, (void *)&status2) ; pthread_mutex_destroy (&mutex) ; return 0 ; } void thread1(void *arg) { pthread_mutex_lock (&mutex) ; sleep (10) ; pthread_mutex_unlock (&mutex) ; pthread_exit (0) ; } void thread2(void *arg) { sleep (2) ; if(pthread_mutex_trylock(&mutex) != 0) { printf ("i can't get the lock\\n") ; } if(pthread_mutex_unlock (&mutex) != 0) { printf ("i can't unlock the lock\\n") ; pthread_exit (0) ; } else { printf ("i can unlock the lock\\n") ; if(pthread_mutex_trylock (&mutex) != 0) { printf ("i can't get the lock\\n") ; } else { printf ("i get the lock\\n") ; } } pthread_exit (0) ; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<5; i++) { pthread_mutex_lock(&count_mutex); count++; printf("(%ld) count = %d\\n", my_id, count); if (count == 6) { pthread_cond_signal(&count_threshold_cv); printf("(%ld) condição atendida (count= %d).\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; pthread_mutex_lock(&count_mutex); if (count<6) { printf("(%ld) aguardando sinal.\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("(%ld) sinal recebido.\\n", my_id); count += 100; printf("(%ld) contador alterado para %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> struct mymesg { long mtype; char mtext[512 + 1]; }; struct threadinfo { int qid; int fd; int len; pthread_mutex_t mutex; pthread_cond_t ready; struct mymesg m; }; void * helper(void *arg) { int n; struct threadinfo *tip = arg; for (;;) { memset(&tip->m, 0, sizeof(struct mymesg)); if ((n = msgrcv(tip->qid, &tip->m, 512, 0, MSG_NOERROR)) < 0) err_sys("msgrcv error"); tip->len = n; pthread_mutex_lock(&tip->mutex); if (write(tip->fd, "a", sizeof(char)) < 0) err_sys("write error"); pthread_cond_wait(&tip->ready, &tip->mutex); pthread_mutex_unlock(&tip->mutex); } } int main() { char c; int i, n, err; int fd[2]; int qid[3]; struct pollfd pfd[3]; struct threadinfo ti[3]; pthread_t tid[3]; for (i = 0; i < 3; i++) { if ((qid[i] = msgget((0x123 + i), IPC_CREAT | 0666)) < 0) err_sys("msgget error"); printf("queue ID %d is %d\\n", i, qid[i]); if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fd) < 0) err_sys("socketpair error"); pfd[i].fd = fd[0]; pfd[i].events = POLLIN; ti[i].qid = qid[i]; ti[i].fd = fd[1]; if (pthread_cond_init(&ti[i].ready, 0) != 0) err_sys("pthread_cond_init error"); if (pthread_mutex_init(&ti[i].mutex, 0) != 0) err_sys("pthread_mutex_init error"); if ((err = pthread_create(&tid[i], 0, helper, &ti[i])) != 0) err_exit(err, "pthread_creat error"); } for (;;) { if (poll(pfd, 3, -1) < 0) err_sys("poll error"); for (i = 0; i < 3; i++) { if (pfd[i].revents & POLLIN) { if ((n = read(pfd[i].fd, &c, sizeof(char))) < 0) err_sys("read error"); ti[i].m.mtext[ti[i].len] = 0; printf("queue id %d, message %s\\n", qid[i], ti[i].m.mtext); pthread_mutex_lock(&ti[i].mutex); pthread_cond_signal(&ti[i].ready); pthread_mutex_unlock(&ti[i].mutex); } } } exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t semaphore; int platforms; int * station; } Data; Data * data; int id; } Tuple; int randomRange(int min, int max) { return rand() % (max - min + 1) + min; } struct tm getTime() { time_t now = time(0); return *localtime(&now); } struct tm getTimeAfter(int seconds) { time_t now = time(0) + seconds; return *localtime(&now); } void leave(int id) { int t = randomRange(5, 50); struct tm now = getTime(); struct tm end = getTimeAfter(t); printf("[%02d:%02d] Vlak %d vyjíždí na trať. Očekávaný příjezd v %02d:%02d.\\n", now.tm_min, now.tm_sec, id, end.tm_min, end.tm_sec); sleep(t); } void enter(int id, Data * data) { int i = 0, t = randomRange(5, 20); struct tm now, end; pthread_mutex_lock(&data->mutex); while((data->station)[i]) i++; (data->station)[i] = id; pthread_mutex_unlock(&data->mutex); now = getTime(); end = getTimeAfter(t); printf("[%02d:%02d] Vlak %d vjel na nástupiště %d. Očekávaný odjezd v %02d:%02d.\\n", now.tm_min, now.tm_sec, id, i, end.tm_min, end.tm_sec); sleep(t); pthread_mutex_lock(&data->mutex); (data->station)[i] = 0; pthread_mutex_unlock(&data->mutex); } void * train(Tuple * arg) { Data * data = arg->data; while(1) { leave(arg->id); sem_wait(&data->semaphore); enter(arg->id, data); sem_post(&data->semaphore); } return 0; } int main(int argc, char ** argv) { pthread_attr_t attr; pthread_t * trains; Tuple * args; Data data; int i, n; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_attr_setschedpolicy(&attr, SCHED_FIFO); if (argc != 3 || sscanf(argv[1], "%d", &data.platforms) != 1 || data.platforms <= 0 || sscanf(argv[2], "%d", &n) != 1 || n <= 0) { printf("usage: %s <počet nástupišť> <počet vlaků>\\n", argv[0]); return 1; } printf("Zmáčkni ENTER pro ukončení....\\n"); pthread_mutex_init(&data.mutex, 0); sem_init(&data.semaphore, 0, data.platforms); data.station = calloc(n, sizeof(int)); trains = malloc(n * sizeof(pthread_t)); args = malloc(n * sizeof(Tuple)); for (i = 0; i < n; i++) { args[i].data = &data; args[i].id = i + 1; pthread_create(trains + i, &attr, (void *(*)(void *))train, args + i); } getchar(); for (i = 0; i < n; i++) { pthread_cancel(trains[i]); pthread_join(trains[i], 0); } free(data.station); free(trains); free(args); pthread_attr_destroy(&attr); pthread_mutex_destroy(&data.mutex); sem_destroy(&data.semaphore); return 0; }
1
#include <pthread.h> void *ThreadMain(void *arg); struct ThreadArgs { int clntSock; }; unsigned short cur_clients; pthread_mutex_t lock; int main(int argc, char *argv[]) { int servSock; int clntSock; unsigned short servPort; unsigned short max_clients; pthread_t threadID; struct ThreadArgs *threadArgs; if (argc != 3) { fprintf(stderr, "Usage: %s <SERVER PORT>\\n", argv[0]); exit(1); } max_clients = atoi(argv[1]); servPort = atoi(argv[2]); cur_clients = 0; servSock = CreateTCPServerSocket(servPort); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } for (;;) { printf("Will shortly be accepting the connection from this client\\n"); clntSock = AcceptTCPConnection(servSock); pthread_mutex_lock(&lock); if (cur_clients < max_clients) { cur_clients++; printf("Max allowed clients: %d, Curent num clients connected: %d\\n", max_clients, cur_clients); if ((threadArgs = (struct ThreadArgs *) malloc( sizeof(struct ThreadArgs))) == 0) DieWithError("malloc() failed"); threadArgs -> clntSock = clntSock; if (pthread_create(&threadID, 0, ThreadMain, (void *) threadArgs) != 0) { DieWithError("pthread_create() failed"); } printf("with thread %ld\\n", (long int) threadID); }else{ printf("Closing the socket on this client %d\\n", clntSock); close(clntSock); } pthread_mutex_unlock(&lock); } pthread_mutex_destroy(&lock); } void *ThreadMain(void *threadArgs) { printf("Here thread main\\n"); int clntSock; pthread_detach(pthread_self()); clntSock = ((struct ThreadArgs *) threadArgs) -> clntSock; free(threadArgs); HandleTCPClient(clntSock); return (0); }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; }; static struct foo *g_foop = 0; static struct foo *foo_alloc(void) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } } return fp; } static void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); printf("ho:shared count = %d\\n", fp->f_count); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } static void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { printf("re:shared count = %d\\n", fp->f_count); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); g_foop = 0; } else { printf("re:shared count = %d\\n", fp->f_count); pthread_mutex_unlock(&fp->f_lock); } } static void *thr_fn1(void *arg) { printf("thread 1 start\\n"); int i = 0; for (i = 0; i < 10; i++) { if (g_foop != 0) { foo_hold(g_foop); sleep(1); } } printf("thread 1 end\\n"); return ((void *)1); } static void *thr_fn2(void *arg) { printf("thread 2 start\\n"); int i = 0; for (i = 0; i < 2; i++) { if (g_foop != 0) { foo_hold(g_foop); sleep(1); } } for (i = 0; i < 20; i++) { if (g_foop != 0) { foo_rele(g_foop); sleep(1); } } printf("thread 2 end\\n"); pthread_exit((void *)2); } int main(int argc, char *argv[]) { int err; pthread_t tid1, tid2; void *tret; g_foop = foo_alloc(); err = pthread_create(&tid1, 0, thr_fn1, 0); if (err != 0) { perror("create thread 1"); } err = pthread_create(&tid2, 0, thr_fn2, 0); if (err != 0) { perror("create thread 2"); } err = pthread_join(tid1, &tret); if (err != 0) { perror("join thread 1"); } printf("thread 1 exit code %d\\n", (int)tret); err = pthread_join(tid2, &tret); if (err != 0) { perror("join thread 2"); } printf("thread 2 exit code %d\\n", (int)tret); return 0; }
1
#include <pthread.h> unsigned int led_speed; pthread_mutex_t lock; static void *LEDMod(void *dummy) { unsigned int led_period; int tmp; tmp = open("/sys/class/leds/motherboard_buzzer/brightness", O_WRONLY); if (tmp < 0) exit(1); while (1) { pthread_mutex_lock(&lock); led_period = (10 - led_speed) * 16000; pthread_mutex_unlock(&lock); write(tmp, "1", 2); usleep(led_period); write(tmp, "0", 2); usleep(led_period); } } int main() { pthread_t pth; struct input_event ev; int tmp; int key_code; int size = sizeof(ev); led_speed = 5; tmp = open("/sys/class/leds/motherboard_buzzer/trigger", O_WRONLY); if (tmp < 0) return 1; close(tmp); printf("Configured LED for use\\n"); pthread_mutex_init(&lock, 0); pthread_create(&pth, 0, LEDMod, "Blinking LED..."); tmp = open("/dev/input/event0", O_RDONLY); if (tmp < 0) { printf("\\nOpen " "/dev/input/event0" " failed!\\n"); return 1; } while (1) { if (read(tmp, &ev, size) < size) { printf("\\nReading from " "/dev/input/event0" " failed!\\n"); return 1; } if (ev.value == 0 && ev.type == 1) { key_code = ev.code; printf("\\n\\rKey_code = %d", key_code); if (key_code == KEY_1) { printf(", P1\\n\\r"); pthread_mutex_lock(&lock); if (led_speed > 0) led_speed -= 1; pthread_mutex_unlock(&lock); } else if (key_code == KEY_2) { printf(", P2\\n\\r"); pthread_mutex_lock(&lock); if (led_speed < 9) led_speed += 1; pthread_mutex_unlock(&lock); } printf("Speed: %i\\n\\r", led_speed); usleep(1000); } } }
0
#include <pthread.h> struct student{ int id; int numQuestions; int questionNum; }; int totalStudents; int inOffice, studentZ; sem_t readyForQuestion, questionWait, answerWait, capacity; pthread_t professor; pthread_mutex_t question_lock; int identification; void Professor(); void *StartProfessor(); void AnswerStart(); void AnswerDone(); void Student(int id); void * StartStudent(void * student); void QuestionStart(); void QuestionDone(); void nap(); void EnterOffice(); void LeaveOffice(); void Professor() { pthread_mutex_init(&question_lock, 0); sem_init(&readyForQuestion,1,0); sem_init(&questionWait,1,0); sem_init(&answerWait,1,0); sem_init(&capacity,0,inOffice); studentZ = 0; pthread_create(&professor, 0, StartProfessor, 0); } void * StartProfessor() { while(1) { sem_post(&readyForQuestion); sem_wait(&questionWait); AnswerStart(); AnswerDone(); sem_post(&answerWait); } } void AnswerStart() { printf("Professor starts to answer question for student %d\\n", identification); } void AnswerDone() { printf("Professor is done with answer for student %d\\n", identification); } void Student(int id) { struct student * newStd = malloc(sizeof(struct student)); newStd->id = id; newStd->numQuestions = (id % 4) + 1; newStd->questionNum = 0; pthread_t stack; pthread_create(&stack, 0, (void *) StartStudent, (void *) newStd); } void *StartStudent(void * student) { struct student * std = student; studentZ++; while(std->numQuestions > std->questionNum) { sem_wait(&readyForQuestion); pthread_mutex_lock(&question_lock); identification = std->id; QuestionStart(); sem_post(&questionWait); sem_wait(&answerWait); QuestionDone(); pthread_mutex_unlock(&question_lock); std->questionNum++; if(std->questionNum == std->numQuestions) { LeaveOffice(); studentZ--; if(studentZ == 0) nap(); } } } void QuestionStart() { printf("Student %d asks a question\\n", identification); } void QuestionDone() { printf("Student %d is satisfied\\n", identification); } void nap() { printf("professor is napping...\\n"); } void EnterOffice() { printf("student %d shows up in the office\\n", identification); } void LeaveOffice() { printf("Student %d leaves the office\\n", identification); } int main(int argc, char *argv[]) { totalStudents = atoi(argv[1]); inOffice = atoi(argv[2]); int i; Professor(); for(i = 0 ; i < totalStudents; i++) { Student(i); } pthread_exit(0); }
1
#include <pthread.h> void fileTransfer(void *arg); static int threadCount = 0; pthread_mutex_t alock = PTHREAD_MUTEX_INITIALIZER; char file_name[512]; int main(int argc,char **argv) { struct sockaddr_in serv_addr; struct sockaddr_in clie_addr; int sock_id; int clie_addr_len; pthread_t thread_id; int *link_id; if ((sock_id = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Create socket failed\\n"); exit(0); } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(8000); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock_id, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { perror("Bind socket failed\\n"); exit(0); } if (-1 == listen(sock_id, 10)) { perror("Listen socket failed\\n"); exit(0); } while (1) { clie_addr_len = sizeof(clie_addr); link_id = (int *)malloc(sizeof(int)); *link_id = accept(sock_id, (struct sockaddr *)&clie_addr, &clie_addr_len); if (-1 == *link_id) { perror("Accept socket failed\\n"); continue; } while (pthread_create (&thread_id, 0, (void *)fileTransfer, (void *)link_id) != 0) { printf ("create thread error: %s.\\n\\n", strerror(errno)); break; } } printf("file %s finished transfer!\\n ", file_name); close(sock_id); return 0; } void fileTransfer(void *arg) { int *link_id; FILE *fp; int read_len; int send_len; int recv_len; char buf[1024*16]; int threadIndex; link_id = (int *)malloc(sizeof(int)); *link_id = *((int*)arg); pthread_mutex_lock(&alock); threadCount++; threadIndex = threadCount; pthread_mutex_unlock(&alock); if((recv_len = recv(*link_id, file_name, 512, 0)) == -1) { printf("recv file name error, error = %d\\n", errno); exit(1); } if ((fp = fopen(file_name, "r")) == 0) { perror("Open file failed\\n"); exit(0); } fseek(fp, 1024*1024*128*(threadIndex-1), 0); sprintf(buf, "%d", threadIndex); if((send_len = send(*link_id, buf, sizeof(buf), 0)) < sizeof(buf)) { perror("Send thread_id failed\\n"); exit(0); } bzero(buf, 1024*16); while ((read_len = fread(buf, sizeof(char), 1024*16, fp)) >0) { send_len = send(*link_id, buf, read_len, 0); if ( send_len < read_len ) { perror("Send file failed\\n"); exit(0); } bzero(buf, 1024*16); if(ftell(fp) >= 1024*1024*128*threadIndex) break; } fclose(fp); close(*link_id); pthread_exit(0); }
0
#include <pthread.h> void PANIC(char *msg); struct sockaddr_in dest; char request[1024]; size_t request_count = 0; const size_t request_limit = 100000; pthread_mutex_t count_mutex; static size_t make_request(void* p) { int sockfd, bytes_read; char buffer[1024]; size_t response_length = 0; if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) { perror("Socket"); abort() ;}; if ( connect(sockfd, (struct sockaddr*)&dest, sizeof(dest)) != 0 ) { perror("Connect"); abort() ;}; send(sockfd, request, strlen(request), 0); do { bzero(buffer, sizeof(buffer)); bytes_read = recv(sockfd, buffer, sizeof(buffer), 0); response_length += bytes_read; } while ( bytes_read > 0 ); close(sockfd); return response_length; } static void* request_loop(void* p) { printf("%s", "a request loop has been created\\r\\n"); do { make_request(0); pthread_mutex_lock(&count_mutex); request_count ++; if(!(request_count % 1000)) { printf(" %lu \\r\\n ", 100 * request_count / request_limit); } pthread_mutex_unlock(&count_mutex); } while (request_count < request_limit); } int main(int Count, char *Strings[]) { pthread_mutex_init(&count_mutex, 0); const size_t thread_count = 32; pthread_t threads[thread_count]; if ( Count < 4 ) { perror("usage: testport <IP-addr> <port> <send-msg>\\n"); abort() ;}; bzero(&dest, sizeof(dest)); dest.sin_family = AF_INET; dest.sin_port = htons(atoi(Strings[2])); if ( inet_addr(Strings[1], &dest.sin_addr.s_addr) == 0 ) { perror(Strings[1]); abort() ;}; bzero(&request, sizeof(request)); sprintf(request, "GET %s HTTP/1.1\\r\\n" "Host: %s:%s\\r\\n" "User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0\\r\\n" "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\\r\\n" "Accept-Language: en-US,en;q=0.5\\r\\n" "Cache-Control: max-age=0\\r\\n" "Connection: close\\r\\n\\r\\n" , Strings[3], Strings[1], Strings[2]); printf("%s", request); size_t response_length = make_request(0); time_t timer0; time(&timer0); int i; for(i = 0; i < thread_count; ++ i) { if(pthread_create(&threads[i], 0, request_loop, 0) != 0) { return 1; } } for(i = 0; i < thread_count; ++ i) { if(pthread_join(threads[i], 0) != 0) { return 1; } } time_t timer1; time(&timer1); float exec_time = timer1 - timer0; float us_per_request = 1e6 * exec_time / request_limit; float request_per_second = request_limit / exec_time; float request1000 = 1000 * exec_time / request_limit; printf ("Executed in %li threads\\r\\n", thread_count); printf ("Size of response in bytes %li \\r\\n", response_length); printf ("Total request count %li \\r\\n", request_limit); printf ("Total request time %f in seconds \\r\\n", exec_time); printf ("Requests per second %f \\r\\n", request_per_second); printf ("Time per request %f (us) \\r\\n", us_per_request); printf ("Time of 1K request %f (s)\\r\\n", request1000); pthread_mutex_destroy(&count_mutex); return 0; }
1
#include <pthread.h> int N=100; int T=2; pthread_mutex_t mutexMin, mutexMax; int *v; int min_min; int max_max; int ocurrencias=0; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *buscar(void *s){ int i; int max = -1; int min = 999999; int inicio=*((int *) s)*N/T; int fin=inicio+(N/T); for(i=inicio;i<fin;i++){ if(v[i] < min){ min = v[i]; } if(v[i] > max){ max = v[i]; } } pthread_mutex_lock(&mutexMin); if(min < min_min){ min_min = min; } pthread_mutex_unlock(&mutexMin); pthread_mutex_lock(&mutexMax); if(max > max_max){ max_max = max; } pthread_mutex_unlock(&mutexMax); } int main(int argc,char*argv[]){ int i; double timetick; if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[2])) <= 0)) { printf("\\nUsar: %s n t\\n n: Dimension del vector (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]); exit(1); } min_min = 999999; max_max = -1; v=malloc(sizeof(int)*N); pthread_mutex_init(&mutexMin, 0); pthread_mutex_init(&mutexMax, 0); pthread_t p_threads[T]; pthread_attr_t attr; pthread_attr_init (&attr); int id[T]; for(i=0;i<N;i++){ v[i]=i; } timetick = dwalltime(); for(i=0;i<T;i++){ id[i]=i; pthread_create(&p_threads[i], &attr, buscar, (void *) &id[i]); } for(i=0;i<T;i++){ pthread_join(p_threads[i],0); } printf("Minimo: %d\\nMaximo: %d\\n", min_min, max_max); printf("Tiempo en segundos %f\\n", dwalltime() - timetick); return(0); }
0
#include <pthread.h> pthread_mutex_t mutex; void *pforsend(void *_sock){ char sendbuf[4096]; long sockfd = (long)_sock; char sexit[10] = {'e','x','i','t','\\n',0}; while(1){ fgets(sendbuf, 4096, stdin); if(strcmp(sendbuf,sexit)==0){ exit(0); break; } pthread_mutex_lock(&mutex); if( send(sockfd, sendbuf, strlen(sendbuf), 0) < 0) { printf("\\033[32msend msg error: %s(errno: %d)\\n\\033[0m", strerror(errno), errno); exit(0); } printf("\\033[32m"); printf("I>:%s",sendbuf); printf("\\033[0m"); pthread_mutex_unlock(&mutex); usleep(100000); } return; } int myprint(char *s){ while((*s!=0)&&(*s!='\\n')){ printf("\\033[33m"); putchar(*s); printf("\\033[0m"); s++; } return 0; } int main(int argc, char** argv) { int sockfd, n; char recvline[4096], sendline[4096]; struct sockaddr_in servaddr; pthread_t pp; pthread_mutex_init(&mutex,0); if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ printf("create socket error: %s(errno: %d)\\n", strerror(errno),errno); exit(0); } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(6666); if( inet_pton(AF_INET, "121.42.164.109", &servaddr.sin_addr) <= 0){ printf("inet_pton error for %s\\n",argv[1]); exit(0); } if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){ printf("\\033[31mconnect error: %s(errno: %d)\\n\\033[0m",strerror(errno),errno); exit(0); } fcntl(sockfd,F_SETFL,O_NONBLOCK); pthread_create(&pp,0,pforsend,(void*)((long)sockfd)); while(1){ pthread_mutex_lock(&mutex); if(recv(sockfd,recvline,4096,0)>0){ myprint(recvline); printf("\\n"); } pthread_mutex_unlock(&mutex); usleep(100000); } close(sockfd); exit(0); }
1
#include <pthread.h> pthread_mutex_t garfo[5] = PTHREAD_MUTEX_INITIALIZER; int garfos[5]={0,0,0,0,0}; pthread_cond_t c[5] = {0,0,0,0,0}; void *filosofo(void *threadid) { long tid; tid = (long)threadid; while (1){ printf("Thread %ld tentando obter garfo à esquerda!\\n", tid); if (pthread_mutex_lock(&garfo[(tid+1)%5])){ while(garfos[(tid+1)%5]!=0){ pthread_cond_wait(&c[(tid+1)%5], &garfo[(tid+1)%5]); } garfos[(tid+1)%5]=1; printf("Thread %ld tentando obter garfo à direita!\\n", tid); if(pthread_mutex_lock(&garfo[tid])){ while(garfos[tid!=0]){ pthread_cond_wait(&c[tid], &garfo[tid]); } garfos[tid]=1; printf("Filosofo %ld COMENDO!\\n", tid); usleep(100); printf("Filosofo %ld liberando o garfo à direita!\\n", tid); pthread_mutex_unlock(&garfo[(tid+1)%5]); printf("Filosofo %ld liberando o garfo à direita!\\n", tid); pthread_mutex_unlock(&garfo[tid]); printf("Thread %ld fora do mutex!\\n", tid); } } garfos[(tid+1)%5]=0; garfos[tid]=0; } pthread_exit(0); } int main (int argc, char *argv[]) { pthread_t threads[5]; int rc; long t; for(t=0; t<5; t++){ printf("In main: creating thread %ld\\n", t); rc = pthread_create(&threads[t], 0, filosofo, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for (t = 0; t < 5; t++) pthread_join(threads[t],0); }
0
#include <pthread.h> int count = 0; int isDisponible = 0; void *p; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void compartir(void *ptr){ printf("Compartir...\\n"); pthread_mutex_lock(&m); if(count==0){ pthread_mutex_unlock(&m); printf("...NADIE PARA COMPARTIR\\n"); return; } else{ isDisponible=1; pthread_cond_broadcast(&cond); } pthread_mutex_unlock(&m); pthread_mutex_lock(&m); while(count!=0){ printf("WAIT DEVOLVER\\n"); pthread_cond_wait(&cond, &m); } printf("DEVOLVIO\\n"); isDisponible=0; pthread_mutex_unlock(&m); printf("...Compartir\\n"); } void *acceder(){ printf("Acceder...\\n"); pthread_mutex_lock(&m); count++; while(isDisponible==0){ printf("WAIT ACCEDER\\n"); pthread_cond_wait(&cond, &m); } sleep(1); printf("ACCEDIO\\n"); pthread_mutex_unlock(&m); printf("...Acceder\\n"); return 0; } void devolver(){ printf("Devolver...\\n"); pthread_mutex_lock(&m); count--; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&m); printf("...Devolver\\n"); } void *comp(void *pt){ compartir(pt); return 0; } void *acc(void *pt){ acceder(); return 0; } void *dev(void *pt){ devolver(); return 0; } int main(int argc, char *argv[]){ pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4; pthread_create(&t4,0,acc,0); printf("Acceder t4\\n"); pthread_create(&t3,0,acc,0); printf("Acceder t3\\n"); pthread_create(&t1,0,comp,0); printf("compartir t1\\n"); pthread_create(&t2,0,acc,0); printf("Acceder t2\\n"); pthread_create(&t4,0,dev,0); printf("Devolver t4\\n"); pthread_create(&t2,0,dev,0); printf("Devolver t2\\n"); pthread_create(&t3,0,dev,0); printf("Devolver t3\\n"); pthread_join(t4,0); pthread_join(t3,0); pthread_join(t2,0); pthread_join(t1,0); }
1
#include <pthread.h> double sum=0.0, a[10000000]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, start, *mytid, end; double mysum=0.0; mytid = (int *) tid; start = (*mytid * 10000000 / 32); end = start + 10000000 / 32; printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1); for (i=start; i < end ; i++) { a[i] = i * 1.0; mysum = mysum + a[i]; } pthread_mutex_lock (&sum_mutex); sum = sum + mysum; pthread_mutex_unlock (&sum_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, start, tids[32]; pthread_t threads[32]; pthread_attr_t attr; pthread_mutex_init(&sum_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<32; i++) { tids[i] = i; pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]); } for (i=0; i<32; i++) { pthread_join(threads[i], 0); } printf ("Done. Sum= %e \\n", sum); sum=0.0; for (i=0;i<10000000;i++){ a[i] = i*1.0; sum = sum + a[i]; } printf("Check Sum= %e\\n",sum); pthread_attr_destroy(&attr); pthread_mutex_destroy(&sum_mutex); pthread_exit (0); }
0
#include <pthread.h> void *thread_function(void*); int run_row=1; pthread_mutex_t test_mutex; void practice_mutex(){ int result; pthread_t a_thread[4]; pthread_mutex_init(&test_mutex, 0); for (long i = 0 ; i < NUM_THREADS; i++) { printf("In main: creating thread %ld\\n",i); result = pthread_create(&a_thread[i], 0, thread_function ,(void*)i); if (result) { printf("ERROR: return code from pthread_create() is %d\\n",result); exit(-1); } } for(long i = 0 ; i < NUM_THREADS;i++) { pthread_join(a_thread[i], 0); } pthread_mutex_destroy(&test_mutex); } void *thread_function(void*arg) { long tid = (long)arg; while(run_row <20) { pthread_mutex_lock(&test_mutex); run_row +=3; pthread_mutex_unlock(&test_mutex); sleep(1); } pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t comm_lockout; int init_commfd(const char *sockpath) { if(pthread_mutex_init(&comm_lockout, 0) != 0) return -1; int sock = socket(PF_LOCAL, SOCK_STREAM, PF_UNSPEC); if(sock < 0) return -1; fcntl(sock, F_SETFD, 1); { struct sockaddr_un uaddr; strncpy(uaddr.sun_path, sockpath, sizeof(uaddr.sun_path)); uaddr.sun_family = PF_LOCAL; uaddr.sun_len = SUN_LEN(&uaddr); if(connect(sock, (struct sockaddr *) &uaddr, sizeof(uaddr)) < 0) return -1; } return sock; } int set_owner(int fd, dev_t dev, ino_t ino, uid_t uid, gid_t gid) { if(pthread_mutex_lock(&comm_lockout) != 0) { perror("pthread_mutex_lock"); return -1; } struct comm_pkt pkt = { .action = SET_OWNER, .dev = dev, .ino = ino, .uid = uid, .gid = gid, }; int res = send(fd, &pkt, sizeof(pkt), 0); pthread_mutex_unlock(&comm_lockout); if(res != sizeof(pkt)) { perror("send"); return -1; } return 0; } int get_owner(int fd, dev_t dev, ino_t ino, uid_t *uid, gid_t *gid) { if(pthread_mutex_lock(&comm_lockout) != 0) { perror("pthread_mutex_lock"); return -1; } struct comm_pkt pkt = { .action = GET_OWNER, .dev = dev, .ino = ino, }; if(send(fd, &pkt, sizeof(pkt), 0) != sizeof(pkt)) { pthread_mutex_unlock(&comm_lockout); perror("send"); return -1; } if(recv(fd, &pkt, sizeof(pkt), 0) != sizeof(pkt)) { pthread_mutex_unlock(&comm_lockout); perror("recv"); return -1; } pthread_mutex_unlock(&comm_lockout); if(pkt.known) { if(uid) *uid = pkt.uid; if(gid) *gid = pkt.gid; } return pkt.known; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return (0); } idx = (((unsigned long)id) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return (fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--fp->f_count == 0) { idx = (((unsigned long)fp->f_id) % 29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while(tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
1
#include <pthread.h> static int glob = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static void * threadFunc(void *arg) { int loops = *((int*) arg); int loc, j; for (j = 0; j < loops; j++) { pthread_mutex_lock(&lock); loc = glob; loc++; if (loc > glob + 1) printf("sync failed!\\n"); glob = loc; pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int loops, s; loops = (argc > 1)? getInt(argv[1], GN_GT_O, "num-loops"): 10000000; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } s = pthread_create(&t1, 0, threadFunc, &loops); if (s != 0) { errExitEN(s, "pthread_create"); } s = pthread_create(&t2, 0, threadFunc, &loops); if (s != 0) { errExitEN(s, "pthread_create"); } s = pthread_join(t1, 0); if (s != 0) { errExitEN(s, "pthread_join"); } s = pthread_join(t2, 0); if (s != 0) { errExitEN(s, "pthread_join"); } printf("glob = %d\\n", glob); pthread_mutex_destroy(&lock); exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_garfo[5]; pthread_t ninja[5]; int id[5]; void pegar_garfos(int *filo){ pthread_mutex_lock(&(mutex_garfo[*filo])); if(*filo < 4){ pthread_mutex_lock(&(mutex_garfo[*filo + 1])); }else{ pthread_mutex_lock(&(mutex_garfo[0])); } } void largar_garfos(int *filo){ pthread_mutex_unlock(&mutex_garfo[*filo]); if(*filo < 4){ pthread_mutex_unlock(&mutex_garfo[*filo+1]); }else{ pthread_mutex_unlock(&(mutex_garfo[0])); } printf("ninja %d terminou de comer \\n",*filo); } void *vida_ninja(void * var){ int *filo = (int*)(var); while(1){ int pensar = (rand()% 10 + 2); printf("ninja %d pensado %d segundos:\\n\\n",*filo,pensar); pegar_garfos(filo); int comer = rand()%5 + 1; printf("ninja %d comendo\\n",*filo); sleep(comer); largar_garfos(filo); } pthread_exit(0); } int main(){ int i,j; system("cls"); for(i = 0 ; i <= 4; i++){ pthread_mutex_init(&(mutex_garfo[i]),0); } for(j = 0;j <= 4; j++){ id[j] = j; pthread_create(&ninja[j],0,&vida_ninja,(void*)&id[j]); } while(1){ } return 0; }
1
#include <pthread.h> int items = 0; pthread_mutex_t itemsLock; void * increment(void * args) { int tid = (int) args; int counter; printf("Thread [%d]: Starting execution ...\\n", tid); printf("Thread [%d]: Initial value of items = %d\\n", tid, items); for (counter = 0; counter < 500000; counter++) { pthread_mutex_lock(&itemsLock); items++; pthread_mutex_unlock(&itemsLock); } printf("Thread [%d]: Final value of items = %d\\n", tid, items); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t tid[10]; int ret, i; pthread_mutex_init(&itemsLock, 0); for (i = 0; i < 10; i++) { ret = pthread_create(&tid[i], 0, increment, i + 1); if (ret != 0) perror("Thread not created"); } for (i = 0; i < 10; i++) { pthread_join(tid[i], 0); } printf("Final items = %d\\n", items); pthread_mutex_destroy(&itemsLock); return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static const char * const caller[2] = {"mutex_thread", "signal handler"}; static pthread_t mutex_tid; static pthread_t sleep_tid; static volatile int signal_handler_exit = 0; static void hold_mutex(int c) { printf("enter hold_mutex [caller %s]\\n", caller[c]); pthread_mutex_lock(&mutex); while (!signal_handler_exit && c != 1) { sleep(5); } pthread_mutex_unlock(&mutex); printf("leave hold_mutex [caller %s]\\n", caller[c]); } static void *mutex_thread(void *arg) { hold_mutex(0); return 0; } static void *sleep_thread(void *arg) { sleep(10); return 0; } static void signal_handler(int signum) { hold_mutex(1); signal_handler_exit = 1; } int main() { signal(SIGUSR1, signal_handler); pthread_create(&mutex_tid, 0, mutex_thread, 0); pthread_create(&sleep_tid, 0, sleep_thread, 0); pthread_kill(sleep_tid, SIGUSR1); pthread_join(mutex_tid, 0); pthread_join(sleep_tid, 0); return 0; }
1
#include <pthread.h> int get_shmid_from_headers(struct http_header_t headers[], int num_headers) { int shmid = -1; for (int i = 0; i < num_headers; i++) { if (!strcmp(headers[i].name, IPC_HTTP_HEADER)) { shmid = atoi(headers[i].value); break; } } assert(shmid > 0); return shmid; } static int _transfer_IPC(struct shared_data_storage* shared_data, char **dst, const char* src, FILE *fp, size_t n, int signal_finish) { pthread_mutex_t *mutex = &shared_data->ipc_mutex; pthread_cond_t *condvar = &shared_data->ipc_condvar; size_t space_left = shared_data->buf + shared_data->buf_size - *dst; int ret = 0; size_t copied_this_iter = 0; pthread_mutex_lock(mutex); while(n > 0) { copied_this_iter = min_s(space_left, n); if (src != 0) { memcpy(*dst, src, copied_this_iter); src += copied_this_iter; } else if (fp != 0) { size_t nread = fread(*dst, 1, copied_this_iter, fp); if (nread != copied_this_iter && feof(fp)) { fprintf(stderr, "Reached end of file\\n"); fprintf(stderr, "File size: %zu\\n", n); fprintf(stderr, "nread: %zu\\n", nread); ret = 1; } else if (nread != copied_this_iter && ferror(fp)) { fprintf(stderr, "Error Reading File\\n"); fprintf(stderr, "File size: %zu\\n", n); fprintf(stderr, "nread: %zu\\n", nread); detach_shmem(shared_data); ret = 1; } } *dst += copied_this_iter; *dst = &shared_data->buf[(*dst - shared_data->buf) % shared_data->buf_size]; space_left = shared_data->buf + shared_data->buf_size - *dst; shared_data->bytes_written = copied_this_iter; n -= copied_this_iter; if (n <= 0) { break; } else { pthread_cond_signal(condvar); while(shared_data->bytes_written > 0) pthread_cond_wait(condvar, mutex); } } if (signal_finish) shared_data->server_finished = 1; pthread_cond_signal(condvar); pthread_mutex_unlock(mutex); assert(n == 0); return ret; } int memcpy_IPC(struct shared_data_storage* shared_data, char **dst, const char* src, size_t n, int finish) { return _transfer_IPC(shared_data, dst, src, 0, n, finish); } int fread_IPC(struct shared_data_storage* shared_data, char **dst, FILE *fp, size_t n, int finish) { return _transfer_IPC(shared_data, dst, 0, fp, n, finish); } void send_file_data_IPC(struct connection *conn, char* response_header, size_t header_size, FILE *fp, size_t file_size) { struct http_request_info_t *ri = conn->request_info; int shmid = get_shmid_from_headers(ri->http_headers, ri->num_headers); struct shared_data_storage *shared_data = attach_shmem(shmid); char *start = shared_data->buf; memcpy_IPC(shared_data, &start, response_header, header_size, 0); fread_IPC(shared_data, &start, fp, file_size, 1); detach_shmem(shared_data); } void *attach_shmem(int shmid) { void *shmem = shmat(shmid, 0, 0); if (shmem == (void *) -1) { perror("shmat"); exit(1); } return shmem; } void detach_shmem(void *shm) { int status; if ((status = shmdt(shm)) == -1) { perror("shmdt"); exit(1); } }
0
#include <pthread.h> static const int min_eat_ms[5] = {300, 300, 300, 300, 300}; static const int max_eat_ms[5] = {600, 600, 600, 600, 600}; static const int min_think_ms[5] = {300, 300, 300, 300, 300}; static const int max_think_ms[5] = {600, 600, 600, 600, 600}; static void philosopher_cycle(int thread_num, pthread_mutex_t *left_fork, pthread_mutex_t *right_fork, unsigned *seed); static void millisleep(int ms); static void sleep_rand_r(int min_ms, int max_ms, unsigned *seed); int main(int argc, char **argv) { pthread_mutex_t forks[5]; time_t t = time(0); for (int i = 0; i < 5; i++) pthread_mutex_init(&forks[i], 0); { int thread_num = omp_get_thread_num(); pthread_mutex_t *left_fork = &forks[thread_num]; pthread_mutex_t *right_fork = &forks[(thread_num + 1) % 5]; unsigned seed = t + thread_num; while (1) { philosopher_cycle(thread_num, left_fork, right_fork, &seed); } } return 0; } static void philosopher_cycle(int thread_num, pthread_mutex_t *left_fork, pthread_mutex_t *right_fork, unsigned *seed) { printf("Philosopher %d wants to eat!\\n", thread_num); if (thread_num == 5 - 1) { pthread_mutex_lock(right_fork); printf("Philosopher %d picked up his right fork.\\n", thread_num); millisleep(5); pthread_mutex_lock(left_fork); printf("Philosopher %d picked up his left fork and " "started eating.\\n", thread_num); } else { pthread_mutex_lock(left_fork); printf("Philosopher %d picked up his left fork.\\n", thread_num); millisleep(5); pthread_mutex_lock(right_fork); printf("Philosopher %d picked up his right fork and " "started eating.\\n", thread_num); } sleep_rand_r(min_eat_ms[thread_num], max_eat_ms[thread_num], seed); pthread_mutex_unlock(left_fork); pthread_mutex_unlock(right_fork); printf("Philosopher %d is done eating and has released his " "forks.\\n", thread_num); sleep_rand_r(min_think_ms[thread_num], max_think_ms[thread_num], seed); } static void millisleep(int ms) { usleep(ms * 1000); } static void sleep_rand_r(int min_ms, int max_ms, unsigned *seed) { int range = max_ms - min_ms + 1; int ms = rand_r(seed) % range + min_ms; millisleep(ms); }
1
#include <pthread.h> extern sigset_t signal_set; extern unsigned int bwritten; extern pthread_mutex_t bwritten_mutex; int parse_pasv_reply2(char *, int, struct sockaddr_in *); int parse_list_reply(char *rbuf, int len); int ftp_get_size(struct sockaddr_in *sin, char *url, int type); void *ftp_get(void *arg) { struct sockaddr_in sin_dc; struct thread_data *td; int sd_c, sd_d; char *sbuf, *rbuf; int dr, dw; long foffset; sigset_t set; pthread_t tid; tid = pthread_self(); sigfillset(&set); pthread_sigmask(SIG_BLOCK, &set, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); td = (struct thread_data *)arg; foffset = td->foffset; if(td->soffset < 0 || td->soffset >= td->foffset) { td->status = STAT_OK; pthread_exit((void *)1); return 0; } rbuf = (char *)calloc(MAXBUFSIZ, sizeof(char)); sbuf = (char *)calloc(MAXBUFSIZ, sizeof(char)); if (td->head_sd == -1) { if ((sd_c = socket(AF_INET, SOCK_STREAM, 0)) == -1) { pthread_exit((void *)1); } if ((connect(sd_c, (const struct sockaddr *)&td->sin, sizeof(struct sockaddr))) == -1) { pthread_exit((void *)1); } if(recv_reply(sd_c, rbuf, MAXBUFSIZ, 0) == -1) { fprintf(stderr, "<<<<<----- %s", rbuf); Log("recv failed: %s", strerror(errno)); pthread_exit((void *)1); } else if(rbuf[0] != '2' && rbuf[0] != '1' && rbuf[0] != '3') { fprintf(stderr, "<<<<<----- %s", rbuf); Log("Seems like the server isn't accepting connections now, bailing out..."); pthread_exit((void *)1); } if(rbuf[0] != '1' && rbuf[0] != '2' && rbuf[0] != '3') { fprintf(stderr, rbuf); handleFTPRetcode(rbuf); close(sd_c); pthread_exit((void *)1); } snprintf(sbuf, MAXBUFSIZ - 1, "USER %s\\r\\n", td->username); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); if (strncmp(rbuf, "331", 3) != 0) { fprintf(stderr, "Server didnot like username, server said\\n"); fprintf(stderr, "Server > %s\\n", rbuf); exit(1); } snprintf(sbuf, MAXBUFSIZ - 1,"PASS %s\\r\\n", td->password); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); if (strncmp(rbuf, "230", 3) != 0) { fprintf(stderr, "Server didnot accept password, server said\\n"); fprintf(stderr, "Server > %s\\n", rbuf); exit(1); } } else { sd_c = td->head_sd; recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); } snprintf(sbuf, MAXBUFSIZ - 1, "REST %ld\\r\\n", td->soffset); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); if (strncmp(rbuf, "350", 3) != 0) { fprintf(stderr, "Server doesn't accept resuming transfers."); fprintf(stderr, "Server > %s\\n", rbuf); exit(1); } sprintf(sbuf, "TYPE I\\r\\n"); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); if (strncmp(rbuf, "200", 3) != 0) { fprintf(stderr, "Server didnot accept BINARY transfer.\\n"); fprintf(stderr, "Server > %s\\n", rbuf); } sprintf(sbuf, "PASV\\r\\n"); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); recv_reply(sd_c, rbuf, MAXBUFSIZ, 0); parse_pasv_reply2(rbuf, MAXBUFSIZ, &sin_dc); if ((sd_d = socket(AF_INET, SOCK_STREAM, 0)) == -1) { Log("Socket creation failed: %s", strerror(errno)); exit(1); } if ((connect(sd_d, (const struct sockaddr *)&sin_dc, sizeof(sin_dc))) == -1) { Log("Connection failed: %s", strerror(errno)); exit(1); } snprintf(sbuf, MAXBUFSIZ - 1,"RETR %s\\r\\n", td->url + 1); memset(rbuf, 0, MAXBUFSIZ); send(sd_c, sbuf, strlen(sbuf), 0); td->offset = td->soffset; while (td->offset < foffset) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); memset(rbuf, MAXBUFSIZ, 0); dr = recv_data(sd_d, rbuf, MAXBUFSIZ); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0); if ((td->offset + dr) > foffset) dw = pwrite(td->fd, rbuf, foffset - td->offset, td->offset); else dw = pwrite(td->fd, rbuf, dr, td->offset); td->offset += dw; pthread_mutex_lock(&bwritten_mutex); bwritten += dw; pthread_mutex_unlock(&bwritten_mutex); pthread_testcancel(); } if (td->offset == td->foffset) td->status = STAT_OK; close(sd_c); close(sd_d); pthread_exit(0); return 0; }
0
#include <pthread.h> double accounts[4]; pthread_mutex_t account_locks[4]; void* worker(void* fname) { FILE* f = fopen((char*) fname, "r"); if (!f) { fprintf(stderr, "Error could not open file '%s'!\\n", (char*) fname); } while (1) { int to, from; double amount; fscanf(f, "%d %d %lf", &to, &from, &amount); if (feof(f)) { break; } pthread_mutex_lock(&account_locks[from]); accounts[from] -= amount; pthread_mutex_unlock(&account_locks[from]); pthread_mutex_lock(&account_locks[to]); accounts[to] += amount; pthread_mutex_unlock(&account_locks[to]); } fclose(f); pthread_exit(0); } int main ( ) { pthread_t threads[2]; char fnames[2][16]; int i; for (i = 0; i < 4; i++) { accounts[i] = 100.00; pthread_mutex_init(&account_locks[i], 0); } for (i = 0; i < 2; i++) { sprintf(fnames[i], "file%d.txt", i); pthread_create(&threads[i], 0, worker, fnames[i]); } for (i = 0; i < 2; i++) { pthread_join(threads[i], 0); } printf("All transactions completed!\\n"); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; int total_grade = 0; void *class_total(void *curr_grade){ pthread_mutex_lock (&mutex); total_grade += (int)curr_grade; pthread_mutex_unlock (&mutex); return 0; } int main(void) { int curr_grade = 0; pthread_t threads[10]; char buffer[32]; pthread_mutex_init(&mutex,0); for (int i = 0; i < 10; i++) { printf("Enter a student grade\\n"); fgets(buffer, 32,stdin); buffer[strlen(buffer)-1]=0; char *end; curr_grade = strtol(buffer, &end, 10); pthread_create(&threads[i], 0, &class_total, curr_grade); } for (int i = 0; i < 10; i++) { pthread_join(&threads[i],0); } pthread_mutex_lock (&mutex); printf("Total Grade:%d\\n", total_grade); pthread_mutex_unlock (&mutex); return 0; }
0
#include <pthread.h> long timeval_diff(struct timeval *t2, struct timeval *t1) { long diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); return (diff); } void error(int err, char *msg) { fprintf(stderr,"%s a retourné %d, message d'erreur : %s\\n",msg,err,strerror(errno)); exit(1); } void usage(char *arg) { printf("Usage : %s percent nthreads\\n\\n",arg); printf(" percent: 0-100 pourcentage de temps en section critique\\n"); printf(" nthreads : nombre de threads à lancer\\n"); } int percent; int nthreads; pthread_mutex_t mutex; void critique() { long j=0; for(int i=0;i<(40000*percent)/100;i++) { j+=i; } } void noncritique() { int j=0; for(int i=0;i<(40000*(100-percent))/100;i++) { j-=i; } } void *func(void * param) { for(int j=0;j<40000/nthreads;j++) { pthread_mutex_lock(&mutex); critique(); pthread_mutex_unlock(&mutex); noncritique(); } return(0); } int main (int argc, char *argv[]) { int err; struct timeval tvStart, tvEnd; long mesures[4]; long sum=0; if(argc!=3) { usage(argv[0]); return(1); } char *endptr; percent=strtol(argv[1],&endptr,10); if(percent<1 || percent >100) { usage(argv[0]); return(1); } nthreads=strtol(argv[2],&endptr,10); if(nthreads<0) { usage(argv[0]); return(1); } pthread_t thread[nthreads]; err=pthread_mutex_init( &mutex, 0); if(err!=0) error(err,"pthread_mutex_init"); for (int j=0;j<4;j++) { err=gettimeofday(&tvStart, 0); if(err!=0) exit(1); for(int i=0;i<nthreads;i++) { err=pthread_create(&(thread[i]),0,&func,0); if(err!=0) error(err,"pthread_create"); } for(int i=nthreads-1;i>=0;i--) { err=pthread_join(thread[i],0); if(err!=0) error(err,"pthread_join"); } err=gettimeofday(&tvEnd, 0); if(err!=0) exit(1); mesures[j]=timeval_diff(&tvEnd, &tvStart); sum+=mesures[j]; } printf("%d, %d, %ld\\n",nthreads,percent,sum/4); err=pthread_mutex_destroy(&mutex); if(err!=0) error(err,"pthread_destroy"); return(0); }
1
#include <pthread.h> extern pthread_mutex_t __sfp_mutex; extern pthread_cond_t __sfp_cond; extern int __sfp_state; FILE * freopen(file, mode, fp) const char *file, *mode; register FILE *fp; { int f, flags, oflags; FILE *ret; if ((flags = __sflags(mode, &oflags)) == 0) { (void) fclose(fp); return (0); } __sinit (); while (pthread_mutex_lock(&__sfp_mutex) == OK) { if (ftrylockfile(fp) == OK) { if (fp->_flags) { if (fp->_flags & __SWR) (void) __sflush(fp); __sclose(fp); if (fp->_flags & __SMBF) free((char *)fp->_bf._base); fp->_w = 0; fp->_r = 0; fp->_p = 0; fp->_bf._base = 0; fp->_bf._size = 0; fp->_lbfsize = 0; if (HASUB(fp)) FREEUB(fp); fp->_ub._size = 0; if (HASLB(fp)) FREELB(fp); fp->_lb._size = 0; } if ((f = open(file, oflags, 0666)) < OK) ret = 0; if (fp->_file >= 0 && f != fp->_file) { if (dup2(f, fp->_file) >= OK) { (void)close(f); f = fp->_file; } } fp->_flags = flags; fp->_file = f; ret = fp; } else { pthread_mutex_unlock(&__sfp_mutex); pthread_yield(); continue; } pthread_mutex_unlock(&__sfp_mutex); funlockfile(fp); return(ret); } (void)fclose(fp); return(0); }
0
#include <pthread.h> struct arg_set { char *fname; int count; int thread_id; }; struct arg_set *mailbox; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; int main(int argc,char *argv[]) { pthread_t t1,t2,t3; struct arg_set args1,args2,args3; void *count_words(void *); int reports_in = 0; int total_words = 0; if(argc != 4) { fprintf(stderr,"Usage: %s file1 file2 file3\\n",argv[0]); exit(1); } pthread_mutex_lock(&lock); args1.fname = argv[1]; args1.count = 0; args1.thread_id = 1; pthread_create(&t1,0,count_words,(void *)&args1); args2.fname = argv[2]; args2.count = 0; args2.thread_id = 2; pthread_create(&t2,0,count_words,(void *)&args2); args3.fname = argv[3]; args3.count = 0; args3.thread_id = 3; pthread_create(&t3,0,count_words,(void *)&args3); while(reports_in < 3) { printf("MAIN: waiting for flag to go up\\n"); pthread_cond_wait(&flag,&lock); printf("MAIN: Wow!flag was raised, I have the lock\\n"); printf("%7d: %s\\n",mailbox->count,mailbox->fname); total_words += mailbox->count; if(mailbox == &args1) pthread_join(t1,0); if(mailbox == &args2) pthread_join(t2,0); if(mailbox == &args3) pthread_join(t3,0); mailbox = 0; pthread_cond_signal(&flag); ++reports_in; } printf("%7d: total word\\n",total_words); return 0; } void *count_words(void *a) { struct arg_set *args = a; FILE *fp; int c,id = args->thread_id,prevc = '\\0'; if((fp = fopen(args->fname,"r")) != 0) { while((c = getc(fp)) != EOF) { if(!isalnum(c) && isalnum(prevc)) ++args->count; prevc = c; } fclose(fp); } else perror(args->fname); printf("COUNT%d: waiting to get lock\\n",id); pthread_mutex_lock(&lock); printf("COUNT%d: have lock,storing data\\n",id); while(mailbox != 0) { pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); } mailbox = args; printf("COUNT%d: rasing flag\\n",id); pthread_cond_signal(&flag); printf("COUNT%d: unlocking box\\n",id); pthread_mutex_unlock(&lock); return 0; }
1
#include <pthread.h> int storehouse[5]; int buyer_demands[3]; pthread_mutex_t store_lock[5]; bool release_condition; void InitializeStores() { int i; srand(time(0)); for (i = 0; i < 5; i++) { storehouse[i] = (rand() % 499) + 1001; } } void InitializeDemands() { int i; for (i = 0; i < 3; i++) { buyer_demands[i] = (rand() % 499) + 2501; } } void PrintStoreInfo() { int i; for (i = 0; i < 5; i++) { printf("Storehouse %d is loaded with %d goods\\n", i, storehouse[i]); } } void PrintDemandsInfo() { int i; for (i = 0; i < 3; i++) { printf("Demands of buyer %d is %d\\n", i, buyer_demands[i]); } } void *StoreLoader() { int chosen_store; int goods_amount; srand(time(0)); while (!release_condition) { goods_amount = (rand() % 99) + 201; chosen_store = (rand() % 5); pthread_mutex_lock(&store_lock[chosen_store]); storehouse[chosen_store] += goods_amount; printf("Storehouse %d is loaded with %d goods. Current amount: %d\\n", chosen_store, goods_amount, storehouse[chosen_store]); pthread_mutex_unlock(&store_lock[chosen_store]); puts("Store loader is going to sleep for 2 sec"); sleep(2); puts("Store loader has awoken"); } pthread_exit(0); } bool IsOversupply(int goods_amount, int buyer_num, int chosen_store) { if ((goods_amount > buyer_demands[buyer_num]) && (storehouse[chosen_store] > buyer_demands[buyer_num])) return 1; else return 0; } void *BuyGoods(void *chosen_buyer) { int chosen_store; int goods_amount; int goods_bought; int buyer_num = *(int *)chosen_buyer; srand(time(0)); while (buyer_demands[buyer_num] != 0) { goods_amount = (rand() % 99) + 401; chosen_store = (rand() % 5); if(pthread_mutex_trylock(&store_lock[chosen_store]) != 0) continue; if (goods_amount > storehouse[chosen_store]) { if (IsOversupply(goods_amount, buyer_num, chosen_store)) { goods_bought = buyer_demands[buyer_num]; buyer_demands[buyer_num] = 0; } else { goods_bought = storehouse[chosen_store]; buyer_demands[buyer_num] -= storehouse[chosen_store]; } storehouse[chosen_store] = 0; } else { if (IsOversupply(goods_amount, buyer_num, chosen_store)) { goods_bought = buyer_demands[buyer_num]; buyer_demands[buyer_num] = 0; } else { goods_bought = goods_amount; buyer_demands[buyer_num] -= goods_amount; } storehouse[chosen_store] -= goods_amount; } printf("Buyer %d bought %d goods from store %d. Demands: %d\\n", buyer_num, goods_bought, chosen_store, buyer_demands[buyer_num]); printf("Store %d goods left: %d\\n", chosen_store, storehouse[chosen_store]); pthread_mutex_unlock(&store_lock[chosen_store]); printf("Buyer %d is going to sleep\\n", buyer_num); sleep(1); printf("Buyer %d has awoken\\n", buyer_num); } pthread_exit(0); } int main(int argc, char *argv[]) { int i; int buyer_num[3]; pthread_t loader; pthread_t buyer[3]; pthread_attr_t attr; release_condition = 0; InitializeStores(); InitializeDemands(); printf("===INITIAL INFO===\\n"); PrintStoreInfo(); PrintDemandsInfo(); printf("==================\\n"); for (i = 0; i < 5; i++) { pthread_mutex_init(&store_lock[i], 0); } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&loader, 0, StoreLoader, 0); for (i = 0; i < 3; i++) { buyer_num[i] = i; pthread_create(&buyer[i], &attr, BuyGoods, (void *)&buyer_num[i]); } pthread_attr_destroy(&attr); for(i = 0; i < 3; i++) { pthread_join(buyer[i], 0); } release_condition = 1; pthread_join(loader, 0); pthread_mutex_destroy(store_lock); printf("===SUMMARY===\\n"); PrintStoreInfo(); PrintDemandsInfo(); pthread_exit(0); printf("=============\\n"); }
0
#include <pthread.h> struct data{ unsigned int n; int * list; }; int topstack; pthread_mutex_t mutex_q; pthread_mutex_t mutex_r; void *sieve_primes(void *arg); int find_twins(int* list, unsigned int n, int verbose); void *sieve_primes(void *arg) { unsigned int k; unsigned int m, i; struct data *d = (struct data*)arg; int * list = d->list; unsigned int n = d->n; k = 1; while (k < sqrt(n)) { m = k+1; i = 2; pthread_mutex_lock(&mutex_q); if (m < topstack) m = topstack+1; while ((m < n) && ((list[m>>3] & (1<<(m&7)))!=0)) m++; if (m > topstack) topstack = m; __sync_or_and_fetch(&list[m>>3], 1U << (m&7));; pthread_mutex_unlock(&mutex_q); while ((long)m*i < n) { if (!((list[m*i>>3] & (1<<(m*i&7)))!=0)) __sync_or_and_fetch(&list[m*i>>3], 1U << (m*i&7));; i++; } pthread_mutex_lock(&mutex_r); list[m>>3]&=(1<<(m&7))^0xFF;; pthread_mutex_unlock(&mutex_r); k = m; } pthread_exit((void*)0); } int find_twins(int* list, unsigned int n, int quiet) { unsigned int j, t; t = 0; for (j=3; (j+2 < n); j+=2) { if (!((list[j>>3] & (1<<(j&7)))!=0)) { if (!((list[(j+2)>>3] & (1<<((j+2)&7)))!=0)) { if (quiet == 1) printf("%u %u\\n", j, j+2); t++; } } } free(list); return t; } int main(int argc, char *argv[]) { unsigned int i, c; int quiet, verbose, procs; unsigned int m; struct data* d; pthread_t* thread; int * list; m = 4294967295U; quiet = 1; procs = 1; verbose = 0; topstack = 0; while ((c = getopt (argc, argv, "vqm:c:")) != -1) { switch(c) { case 'v': verbose = 1; break; case 'q': quiet = 0; break; case 'm': m = atoi(optarg); if (m < 10) m = 10; break; case 'c': procs = atoi(optarg); if (c < 1) c = 1; break; default: break; } } d = malloc(procs * sizeof(struct data)); thread = malloc(procs * sizeof(pthread_t)); list = calloc(m, 1); pthread_mutex_init(&mutex_q, 0); pthread_mutex_init(&mutex_r, 0); if (verbose == 1) { printf("Finding twin primes under m=%u\\n", m); printf("The square root of m is =%f\\n", sqrt(m)); } for (i=0; i<procs; i++) { d[i].list = list; d[i].n = m; if ( 0 != pthread_create(&thread[i], 0, sieve_primes, (void*)&d[i])) { perror("Cannot create thread"); exit(1); } } for (i=0; i<procs; i++) pthread_join(thread[i], 0); i = find_twins(list, m, quiet); if (verbose == 1) printf("Twin primes under [%u] : %d\\n",m,i); free(thread); free(d); return 0; }
1
#include <pthread.h> char *time_str = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread_create_str(void *arg) { time_t timeval; char *tmp = (char *)malloc(50); sleep(10); time(&timeval); bzero(tmp, 50); sprintf(tmp, "The date is: %s", ctime(&timeval)); pthread_mutex_lock(&mutex); time_str = tmp; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } void *thread_print_str(void *arg) { pthread_mutex_lock(&mutex); while (time_str == 0) { pthread_cond_wait(&cond, &mutex); } printf("%s", time_str); pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { pthread_t thread_create; pthread_t thread_print; pthread_create(&thread_create, 0, thread_create_str, 0); pthread_create(&thread_print, 0, thread_print_str, 0); pthread_join(thread_create, 0); pthread_join(thread_print, 0); return 0; }
0
#include <pthread.h> int buffer[5]; pthread_mutex_t mutex; sem_t pattySem; sem_t cheeseSem; sem_t bunSem; sem_t pattyFullSem; sem_t cheeseFullSem; sem_t bunFullSem; void *assemblyRobot(void *param); void *bunSupplyRobot(void *param); void *pattySupplyRobot(void *param); void *cheeseSupplyRobot(void *param); int main(int argc, char *argv[]) { int sleepTime = atoi(argv[1]); if(argc != 2) { fprintf(stderr, "Usage: ./a.out <sleep time>\\n"); } printf("------------SIMULATION STARTING FOR %d SECONDS------------\\n\\n", sleepTime); pthread_t tid1, tid2, tid3, tid4; sem_init(&bunSem, 0, 5); sem_init(&pattySem, 0, 5); sem_init(&cheeseSem, 0, 5); sem_init(&bunFullSem, 0, 0); sem_init(&pattyFullSem, 0, 0); sem_init(&cheeseFullSem, 0, 0); pthread_mutex_init(&mutex, 0); pthread_create(&tid1, 0, bunSupplyRobot, 0); pthread_create(&tid2, 0, pattySupplyRobot, 0); pthread_create(&tid3, 0, cheeseSupplyRobot, 0); pthread_create(&tid4, 0, assemblyRobot, 0); sleep(sleepTime); pthread_mutex_lock(&mutex); printf("\\n------------SIMULATION ENDING------------\\n"); return 0; } void *assemblyRobot(void *param) { int random; while(1) { random = rand() % 5; sleep(random); sem_wait(&bunFullSem); sem_wait(&pattyFullSem); sem_wait(&cheeseFullSem); pthread_mutex_lock(&mutex); printf("Assembly robot made one burger\\n"); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&bunSem); sem_post(&pattySem); sem_post(&cheeseSem); } } void *bunSupplyRobot(void *param) { int random; while (1) { random = rand() % 5; sleep(random); sem_wait(&bunSem); pthread_mutex_lock(&mutex); printf("Bun supply robot put a bun on table\\n"); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&bunFullSem); } } void *cheeseSupplyRobot(void *param) { int random; while (1) { random = rand() % 5; sleep(random); sem_wait(&cheeseSem); pthread_mutex_lock(&mutex); printf("Cheese slice supply robot put a slice on table\\n"); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&cheeseFullSem); } } void *pattySupplyRobot(void *param) { int random; while (1) { random = rand() % 5; sleep(random); sem_wait(&pattySem); pthread_mutex_lock(&mutex); printf("Patty supply robot put a patty on table\\n"); sleep(1); pthread_mutex_unlock(&mutex); sem_post(&pattyFullSem); } }
1
#include <pthread.h> int Q[20]; int front = -1; int rear = -1; pthread_mutex_t mutex; sem_t full; sem_t empty; void *Supervisor(void *arg){ int student = (int)arg; pthread_detach(pthread_self()); sem_wait(&empty); pthread_mutex_lock(&mutex); rear = rear + 1; if (rear >= 20) rear = 0; Q[rear] = student; printf("%4d. Student was called to the Presentation\\n", student+1); pthread_mutex_unlock(&mutex); sem_post(&full); } void *Student(void *arg){ int student = 0; int studentsRemoved = 0; printf("Presentation is started\\n"); while (studentsRemoved < 80){ sem_wait(&full); pthread_mutex_lock(&mutex); front = front + 1; if (front >= 20) front = 0; student = Q[front]; printf(" %4d. Student is done. It was removed from the Queue \\n", student+1); studentsRemoved++; pthread_mutex_unlock(&mutex); sem_post(&empty); usleep((int)(drand48()*500000)); } } int main(int argc,char *argv[]){ int i; pthread_t supervisorId; pthread_t QUEUEId; srand48(time(0)); pthread_mutex_init(&mutex,0); sem_init(&full, 0, 0); sem_init(&empty, 0, 20); pthread_create(&QUEUEId, 0, Student, 0); for(i=0; i < 80;i++){ pthread_create(&supervisorId, 0, Supervisor, (void *)i); } pthread_join(QUEUEId, 0); return 0; }
0
#include <pthread.h> char ch; time_t end_time; sem_t customer,barber; pthread_mutex_t accessSeats; int NumberOfFreeSeats=15 ; int NumberHairCutDone=0; void *barber_function(void *arg); void *customer_function(void *arg); int main(int argc, char **argv) { pthread_t customerid[20], barberid[5]; pthread_attr_t attr; int rc; long t; end_time=time(0)+20000; printf("...................SIMULATION PARAMETERS......................\\n"); printf("****************************************************************\\n"); printf("*MULTIPLE SLEEPING BARBER SIMULATION BY POSIX IPC \\n"); printf("*by BHASKARJYOTI DAS 2014 MTech CSE BATCH *\\n"); printf("*Number of WAITING ROOM seats =%d *\\n", 15); printf("*Number of customers = %d *\\n",20); printf("*Number of Barbers = %d * \\n",5); printf("****************************************************************\\n"); printf ("\\n\\n Program output is redirected to multibarberIPC.txt ..\\n"); printf ("\\n\\nPress a key to continue..\\n"); ch = getchar(); pthread_mutex_init(&accessSeats, 0); sem_init(&customer,0,0); sem_init(&barber,0,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t=0;t<5;t++) { printf("In main: creating Barber thread %ld\\n", t); rc = pthread_create(&barberid[t], 0, barber_function, (void *)t); if (rc){ perror("create barbers is failure!\\n"); exit(-1); } printf("This barber is ready and shop is open :%d free seats \\n",NumberOfFreeSeats); } for(t=0;t<20;t++) { printf("In main: creating customer thread %ld\\n", t); rc = pthread_create(&customerid[t], 0, customer_function, (void *)t); if (rc){ perror("create customers is failure!\\n"); exit(-1); } } pthread_attr_destroy(&attr); for(t=0;t<5;t++) { printf("In main: joining Barber thread %ld\\n", t); rc = pthread_join(barberid[t], 0); } for(t=0;t<20;t++) { printf("In main: joining customer thread %ld\\n", t); rc = pthread_join(customerid[t], 0); } pthread_mutex_destroy(&accessSeats); sem_destroy(&customer); sem_destroy(&barber); printf ("Simulation over .. check the file multibarberIPC.txt \\n"); printf ("We will exit from main \\n"); fflush(stdout); pthread_exit(0); } void *barber_function(void * threadid) { long tid = (long)threadid; while (NumberHairCutDone<20) { sem_wait(&customer); pthread_mutex_lock (&accessSeats); NumberOfFreeSeats++; printf("Barber:got a customer , Now, number of free seats is:%d.\\n",NumberOfFreeSeats); NumberHairCutDone++; pthread_mutex_unlock (&accessSeats); sleep(1); printf ("Barber has done a hair cut ..\\n"); sem_post(&barber); printf("Number of Customer got the hair cut done:%d \\n",NumberHairCutDone); if (NumberHairCutDone==20) break; } printf("Barber announcing good bye ! Day is over ..retiring \\n"); fflush(stdout); pthread_exit(0); } void *customer_function (void * threadid) { long tid = (long)threadid; pthread_mutex_lock (&accessSeats); if(NumberOfFreeSeats > 0) { NumberOfFreeSeats--; printf("Customer has taken a free waiting seat :current free seat count is:%d\\n",NumberOfFreeSeats); pthread_mutex_unlock (&accessSeats); sem_post(&customer); sem_wait(&barber); } else { pthread_mutex_unlock (&accessSeats); printf("%d seats are free.....\\n", NumberOfFreeSeats); } pthread_exit(0); }
1
#include <pthread.h> int buffer=0; int data_ready = 0; int toconsume =0; int i=0; pthread_t con; pthread_t pro; pthread_mutex_t mumu ; pthread_cond_t condc; pthread_cond_t condp; void* producer (void* arg); void* consumer (void* arg); void* producer (void* arg) { for (int i=0; i<5; i++){ printf("Producer---->\\n"); pthread_mutex_lock(&mumu); while (buffer!=0) pthread_cond_wait(&condp,&mumu); printf("Producer: is producing----> %d\\n",i); toconsume++; pthread_cond_signal(&condc); pthread_mutex_unlock(&mumu); sleep(1); } pthread_exit(0); } void* consumer (void* arg) { printf("consumer---->\\n"); for (int i=0; i<5 ; i++){ pthread_mutex_lock(&mumu); while (toconsume <=0) pthread_cond_wait(&condc,&mumu); printf("Consumer : is consuming---->%d\\n",i); toconsume--; pthread_cond_signal(&condp); pthread_mutex_unlock(&mumu); } pthread_exit(0); } int main(int argc, char const *argv[]) { pthread_mutex_init(&mumu, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con,0,consumer,0); pthread_create(&pro,0,producer,0); pthread_join(con,0); pthread_join(pro,0); pthread_mutex_destroy(&mumu); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex[2]; void *thread_one(void *arg) { pthread_mutex_lock(&mutex[0]); sleep(1); pthread_mutex_lock(&mutex[1]); printf("go %s\\n", __func__); pthread_mutex_unlock(&mutex[0]); pthread_mutex_unlock(&mutex[1]); return (void *)0; } void *thread_two(void *arg) { sleep(1); pthread_mutex_lock(&mutex[1]); pthread_mutex_lock(&mutex[0]); printf("go %s\\n", __func__); pthread_mutex_unlock(&mutex[1]); pthread_mutex_unlock(&mutex[0]); return (void *)0; } int main() { int rv[2]; pthread_t tid[2]; rv[0] = pthread_create(&tid[0], 0, thread_one, 0); rv[1] = pthread_create(&tid[1], 0, thread_two, 0); if (rv[0] != 0 || rv[1] != 0) { printf("one thread = %s:two thread = %s", strerror(rv[0]), strerror(rv[1])); return -1; } memset(rv, 0, sizeof(rv)); rv [0] = pthread_mutex_init(&mutex[0], 0); rv [1] = pthread_mutex_init(&mutex[1], 0); if (rv[0] != 0 || rv[1] != 0) { printf("one thread = %s:two thread = %s", strerror(rv[0]), strerror(rv[1])); return -1; } pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&mutex[0]); pthread_mutex_destroy(&mutex[1]); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t famoso_durmiendo; pthread_cond_t autografo; int ocupacion = 0; int firmado = 0; void *famoso(void *kk) { int i; while(1) { pthread_mutex_lock(&mutex); while (ocupacion < 5) { pthread_cond_wait(&famoso_durmiendo, &mutex); } printf("FAMOSO FIRMA. Ocupacion actual: %d\\n", ocupacion); firmado++; pthread_cond_signal(&autografo); pthread_mutex_unlock(&mutex); sleep(random() % 2); } pthread_exit(0); } void *fan(void *kk) { int i; pthread_mutex_lock(&mutex); if (ocupacion != 20) { ocupacion++; printf("fan espera: %u, Ocupacion actual: %d\\n", (unsigned) pthread_self(), ocupacion); pthread_cond_signal(&famoso_durmiendo); while (firmado == 0) { pthread_cond_wait(&autografo, &mutex); } firmado--; ocupacion--; printf("FIN fan atendido: %u, Quedan %d fans dentro\\n", (unsigned) pthread_self(), ocupacion); } else { printf("FIN fan sin atender: %u\\n", (unsigned) pthread_self()); } pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i; pthread_t th1, th2; pthread_attr_t attrfan; pthread_attr_init(&attrfan); pthread_attr_setdetachstate(&attrfan, PTHREAD_CREATE_DETACHED); pthread_mutex_init(&mutex, 0); pthread_cond_init(&famoso_durmiendo, 0); pthread_cond_init(&autografo, 0); pthread_create(&th1, 0, famoso, 0); for (i = 0; i < 40; i++) { pthread_create(&th2, &attrfan, fan, 0); sleep(random() % 1); } pthread_join(th1, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&famoso_durmiendo); pthread_cond_destroy(&autografo); return 0; }
0
#include <pthread.h> { char buffer[5]; int number; }PRODUCT; PRODUCT product ={"",0}; char ch = 'A'; pthread_mutex_t mutex; pthread_cond_t cond; void * producer_func(void * arg) { pthread_t p_id; p_id = pthread_self(); printf("producer %ld:Starting\\n",p_id); while(ch!='Z') { pthread_mutex_lock(&mutex); if(product.number!=5) { product.buffer[product.number++]=ch++; printf("Producer %ld:Putting [%c] to buffer\\n",p_id,ch-1); if(product.number==5) { printf("Producer %ld:Putting ful!!!\\n",p_id); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); } sleep(1); } printf("producer %ld:Endting\\n",p_id); return 0; } void * consumer_func(void * arg) { int i; pthread_t c_id; c_id = pthread_self(); printf("consumer %ld:Starting\\n",c_id); while(ch!='Z') { pthread_mutex_lock(&mutex); while(product.number!=5) { pthread_cond_wait(&cond,&mutex); } printf("Consumer %ld:Getting from buffer\\n",c_id); for(i=0;product.buffer[i]&&product.number;++i,product.number--) putchar(product.buffer[i]); printf("\\n"); pthread_mutex_unlock(&mutex); } printf("consumer %ld:Endting\\n",c_id); } int main(void) { pthread_t producer,consumer; void * retval; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&producer,0,(void *)producer_func,0); pthread_create(&consumer,0,(void *)consumer_func,0); pthread_join(producer,&retval); pthread_join(consumer,&retval); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static void *thr_primer(void *p); int main() { int err,i; pthread_t tid[4]; for(i = 0 ; i < 4; i++) { err = pthread_create(tid+i,0,thr_primer,(void *)i); if(err) { fprintf(stderr,"pthread_create():%s\\n",strerror(err)); exit(1); } } for(i = 30000000 ; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = i; pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = -1; pthread_mutex_unlock(&mut_num); for(i = 0 ; i < 4; i++) pthread_join(tid[i],0); pthread_mutex_destroy(&mut_num); exit(0); } static void *thr_primer(void *p) { int i,j,mark; while(1) { pthread_mutex_lock(&mut_num); while(num == 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } if(num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_mutex_unlock(&mut_num); mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); } pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head = 0; static void cleanup_handler(void *arg) { printf("Cleanup handler of second thread./n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node *p = 0; pthread_cleanup_push(cleanup_handler, p); while (1) { pthread_mutex_lock(&mtx); while (head == 0) { pthread_cond_wait(&cond, &mtx); } p = head; head = head->n_next; printf("Got %d from front of queue\\n", p->n_number); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); return 0; } int main(void) { pthread_t tid; int i; struct node *p; pthread_create(&tid, 0, thread_func, 0); sleep(1); for (i = 0; i < 10; i++) { p = malloc(sizeof(struct node)); p->n_number = i; pthread_mutex_lock(&mtx); p->n_next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread 1 wanna end the line.So cancel thread 2.\\n"); pthread_cancel(tid); pthread_join(tid, 0); printf("All done -- exiting\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int count; void *print(void *arg) { int no = *(int *)arg; while (count < 20) { pthread_mutex_lock(&mutex); if (count < 20) { printf("no.%d locking.....\\n", no); count++; printf("thread no.%d, count:%d\\n", no, count); usleep(20000); printf("no.%d unlocking....\\n", no); } pthread_mutex_unlock(&mutex); } return 0; } int main() { count = 0; pthread_mutex_init(&mutex, 0); pthread_t thread[5]; int no[5]; for (int i = 0; i < 5; i++) { no[i] = i; int retV = pthread_create(&thread[i], 0, print, &no[i]); if (retV != 0) { printf("create thread failed.\\n"); exit(0); } } for (int i = 0; i < 5; i++) { pthread_join(thread[i], 0); } printf("close mutex...\\n"); pthread_mutex_destroy(&mutex); }
0
#include <pthread.h> struct csema { pthread_mutex_t m_mutex; pthread_cond_t m_cond; int m_count; }; void csema_ctr(struct csema* p) { memset(p, 0, sizeof(*p)); pthread_mutex_init(&p->m_mutex, 0); pthread_cond_init(&p->m_cond, 0); } void csema_dtr(struct csema* p) { pthread_cond_destroy(&p->m_cond); pthread_mutex_destroy(&p->m_mutex); } void csema_p(struct csema* p, const int n) { pthread_mutex_lock(&p->m_mutex); printf("[0x%x],csema_p(),%d\\n",pthread_self(),(p->m_count < n)); while (p->m_count < n) pthread_cond_wait(&p->m_cond, &p->m_mutex); p->m_count -= n; pthread_cond_signal(&p->m_cond); pthread_mutex_unlock(&p->m_mutex); } void csema_v(struct csema* p) { printf("[0x%x],csema_v()\\n",pthread_self()); pthread_mutex_lock(&p->m_mutex); p->m_count++; pthread_cond_signal(&p->m_cond); pthread_mutex_unlock(&p->m_mutex); } struct cthread { pthread_t m_thread; int m_threadnum; struct csema* m_sema; }; void cthread_ctr(struct cthread* p) { p->m_thread = 0; p->m_sema = 0; } void cthread_dtr(struct cthread* p) { } static int s_debug = 1; static int s_trace = 1; static int s_signal_count; static pthread_mutex_t s_mutex; static pthread_cond_t s_cond; static void thread_func(struct cthread* thread_info) { int i; printf("[0x%x]1thread \\n",pthread_self()); pthread_mutex_lock(&s_mutex); for (i = 0; i < s_signal_count; i++) { csema_v(thread_info->m_sema); if (s_trace) { printf("[0x%x]2thread %d [%d] (1)\\n",pthread_self(), thread_info->m_threadnum, i); } pthread_cond_wait(&s_cond, &s_mutex); if (s_trace) { printf("[0x%x]3thread %d [%d] (2)\\n",pthread_self(), thread_info->m_threadnum, i); } } pthread_mutex_unlock(&s_mutex); } int main(int argc, char** argv) { int optchar; int thread_count; s_signal_count = 1; thread_count = 1; if (s_debug) printf("&s_cond = %p\\n", &s_cond); pthread_mutex_init(&s_mutex, 0); pthread_cond_init(&s_cond, 0); { int i; struct csema sema; struct cthread* p; struct cthread* thread_vec; csema_ctr(&sema); thread_vec = malloc(sizeof(struct cthread) * thread_count); for (p = thread_vec; p != thread_vec + thread_count; p++) { cthread_ctr(p); p->m_threadnum = p - thread_vec; p->m_sema = &sema; pthread_create(&p->m_thread, 0, (void*(*)(void*))thread_func, &*p); } printf("There are 2 threads exist \\n"); for (i = 0; i < s_signal_count; i++) { if (s_trace) printf("[0x%x]main [%d] m_count=%d (1)\\n",pthread_self(), i,sema.m_count); csema_p(&sema, thread_count); if (s_trace) printf("[0x%x]main [%d] (2)\\n",pthread_self(), i); pthread_mutex_lock(&s_mutex); pthread_cond_broadcast(&s_cond); pthread_mutex_unlock(&s_mutex); if (s_trace) printf("[0x%x]main [%d] (3)\\n",pthread_self(), i); } for (i = 0; i < thread_count; i++) { pthread_join(thread_vec[i].m_thread, 0); cthread_dtr(&thread_vec[i]); } free(thread_vec); csema_dtr(&sema); } pthread_cond_destroy(&s_cond); pthread_mutex_destroy(&s_mutex); fprintf(stderr, "Done.\\n"); return 0; }
1
#include <pthread.h> int threadIdx; }threadParams_t; pthread_t threads[3]; threadParams_t threadParams[3]; pthread_attr_t rt_sched_attr[3], attr; int rt_max_prio, rt_min_prio; struct sched_param rt_param[3]; struct sched_param main_param; pthread_attr_t main_attr; pid_t mainpid; pthread_t threadid; pthread_mutex_t mutexsem; pthread_cond_t pcond; int globalvar = 0; void *threadex1(void *threadp){ printf("\\nthread 1\\n"); threadid = pthread_self(); pthread_mutex_lock(&mutexsem); while(globalvar!= 1) pthread_cond_wait(&pcond, &mutexsem); ++globalvar; pthread_mutex_unlock(&mutexsem); printf("\\nthread 1 id is : %u\\n",threadid ); printf("\\nshared memory value (globalvar) : %d\\n", globalvar); pthread_exit(0); } void *threadex2(void *threadp){ int rc; size_t stack_size; printf("\\nthread 2\\n"); rc = pthread_getattr_np(pthread_self(), &attr); pthread_attr_getstacksize(&attr, &stack_size); printf("\\nstack size: %ld\\n", stack_size); pthread_exit(0); } void *threadex3(void *threadp){ printf("\\nthread 3\\n"); pthread_mutex_lock(&mutexsem); ++globalvar; pthread_cond_signal(&pcond); pthread_mutex_unlock(&mutexsem); } int main(){ int rc; int i; mainpid=getpid(); pthread_mutex_init(&mutexsem, 0); pthread_cond_init(&pcond, 0); rc=sched_getparam(mainpid, &main_param); if (rc) { printf("ERROR; sched_setscheduler rc is %d\\n", rc); perror(0); exit(-1); } rt_max_prio = sched_get_priority_max(SCHED_FIFO); rt_min_prio = sched_get_priority_min(SCHED_FIFO); main_param.sched_priority=rt_max_prio; rc=sched_setscheduler(getpid(), SCHED_FIFO, &main_param); if(rc < 0) perror("main_param"); for(i=0; i < 3; i++) { rc=pthread_attr_init(&rt_sched_attr[i]); rc=pthread_attr_setinheritsched(&rt_sched_attr[i], PTHREAD_EXPLICIT_SCHED); rc=pthread_attr_setschedpolicy(&rt_sched_attr[i], SCHED_FIFO); rt_param[i].sched_priority=rt_max_prio-i-1; pthread_attr_setschedparam(&rt_sched_attr[i], &rt_param[i]); threadParams[i].threadIdx=i; } pthread_create(&threads[0], &rt_sched_attr[0], threadex1, (void *)&(threadParams[0]) ); pthread_create(&threads[1], &rt_sched_attr[1], threadex2, (void *)&(threadParams[1]) ); pthread_create(&threads[2], &rt_sched_attr[2], threadex3, (void *)&(threadParams[2]) ); pthread_join(threads[0], 0); pthread_join(threads[1], 0); pthread_mutex_destroy(&mutexsem); pthread_cond_destroy(&pcond); }
0
#include <pthread.h> struct job { struct job* next; }; struct job* job_queue; extern void process_job (struct job*); pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_function (void* arg) { while (1) { struct job* next_job; pthread_mutex_lock (&job_queue_mutex); if (job_queue == 0) next_job = 0; else { next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0) break; process_job (next_job); free (next_job); } return 0; }
1
#include <pthread.h> void * thread_fcn(void * thread_arg); void enter_cr(int threadID); void leave_cr(int threadID); void init_synch(); void finish_synch(); void show_usage_and_exit(char* arg0); int num_threads = 0; int num_trips = 0; int max_cr_delay = 0; int max_non_cr_delay = 0; volatile int cr_delay_time = 0; volatile int non_cr_delay_time = 0; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char* argv[]) { int i; int * threadIDs; pthread_t * threads; if (argc < 5) { show_usage_and_exit(argv[0]); } num_threads = atoi(argv[1]); num_trips = atoi(argv[2]); max_cr_delay = atoi(argv[3]); max_non_cr_delay = atoi(argv[4]); if ((num_threads <= 0) || (num_trips <= 0) || (max_cr_delay <= 0) || (max_non_cr_delay <= 0)) { show_usage_and_exit(argv[0]); } init_synch(); threadIDs = malloc(num_threads * sizeof(int)); for (i = 0; i < num_threads; ++i) threadIDs[i] = i; threads = malloc(num_threads * sizeof(pthread_t)); for (i = 0; i < num_threads; ++i) pthread_create(&threads[i], 0, thread_fcn, (void *) &threadIDs[i]); for (i = 0; i < num_threads; ++i) pthread_join(threads[i], 0); fprintf(stdout, "Total delay time = %d (cr), %d (non-cr)\\n", cr_delay_time, non_cr_delay_time); finish_synch(); free(threadIDs); free(threads); return 0; } void * thread_fcn(void * thread_arg) { int myID = * (int *) thread_arg; int i; int delay; for (i = 0; i < num_trips; ++i) { enter_cr(myID); delay = (rand() % max_cr_delay) + 1; cr_delay_time += delay; fprintf(stdout, "thread %d starts cr, cr delay %d\\n", myID, delay); usleep(delay * 1000); delay = (rand() % max_non_cr_delay) + 1; non_cr_delay_time += delay; fprintf(stdout, "thread %d ends cr, non-cr delay %d\\n", myID, delay); leave_cr(myID); usleep(delay * 1000); } pthread_exit((void* ) 0); } void init_synch() { } void finish_synch() { } void enter_cr(int threadID) { pthread_mutex_lock(&mtx); } void leave_cr(int threadID) { pthread_mutex_unlock(&mtx); } void show_usage_and_exit(char* arg0) { fprintf(stderr, "Usage: %s num_threads num_trips max_cr_delay max_non_cr_delay\\n", arg0); fprintf(stderr, " (delays in milliseconds)\\n"); exit(1); }
0
#include <pthread.h> int buffer[3]; int add = 0; int rem = 0; int num = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_cons = PTHREAD_COND_INITIALIZER; pthread_cond_t c_prod = PTHREAD_COND_INITIALIZER; void *producer (void *param); void *consumer (void *param); int main(int argc, char *argv[]) { pthread_t tid1, tid2; int i; if (pthread_create(&tid1, 0, producer, 0) != 0) { fprintf(stderr, "Unable to create producer thread\\n"); exit(1); } if (pthread_create(&tid1, 0, consumer, 0) != 0) { fprintf(stderr, "Unable to create consumer thread\\n"); exit(1); } pthread_join(tid1, 0); pthread_join(tid2, 0); printf("Parent quitting\\n"); } void *producer(void *param) { int i; for (int i = 0; i <= 20; ++i) { pthread_mutex_lock(&m); if (num > 3) { exit(1); } while(num == 3) { pthread_cond_wait(&c_prod, &m); } buffer[add] = i; add = (add+1) % 3; num++; pthread_mutex_unlock(&m); pthread_cond_signal(&c_cons); printf("Producer: inserted %d\\n", i); fflush(stdout); } printf("Producer quitting\\n"); fflush(stdout); return 0; } void *consumer(void *param) { int i; while(1) { pthread_mutex_lock(&m); if (num < 0) { exit(1); } while(num == 0) { pthread_cond_wait(&c_cons, &m); } i = buffer[rem]; rem = (rem + 1) % 3; num--; pthread_mutex_unlock(&m); pthread_cond_signal(&c_cons); printf("Consume value %d\\n", i); fflush(stdout); } }
1
#include <pthread.h> unsigned char uart = 0; pthread_mutex_t rt_mutex; void* pthreat_recv_data(void* para) { int i = 0; int res = 0; unsigned long recv_count = 0; char recv_buf[254] = {0}; if ((uart == 1) || (uart == 2) || (uart == 3)) { while (1) { pthread_mutex_lock(&rt_mutex); if ((res = spi_rt_interface.recv_data(uart, recv_buf, sizeof(recv_buf))) <= 0) { printf("recv error! res = %d\\n", res); } else { printf("recv_data res = %d\\n", res); } recv_count++; printf("recv_count = %d\\n", recv_count); pthread_mutex_unlock(&rt_mutex); usleep(10000); } } else { PRINT("[uart_num error!]\\n"); return (void *)-1; } return (void *)0; } void* pthreat_send_data(void* para) { int i = 0; int res = 0; unsigned long send_count = 0; char send_buf[20] ="0123456789"; if ((uart == 1) || (uart == 2) || (uart == 3)) { while (1) { pthread_mutex_lock(&rt_mutex); if ((res = spi_rt_interface.send_data(uart, send_buf, sizeof(send_buf))) <= 0) { printf("send error! res = %d\\n", res); } else { printf("send_data res = %d\\n", res); } send_count++; printf("send_count = %d\\n", send_count); pthread_mutex_unlock(&rt_mutex); usleep(10000); } } else { PRINT("[uart_num error!]\\n"); return (void *)-1; } return (void *)0; } int main(int argc, char ** argv) { strcpy(common_tools.argv0, argv[0]); signal(SIGSEGV, SIG_IGN); fflush(stdout); if (argc != 2) { PRINT("[cmd uart_num!]\\n"); return -1; } uart = atoi(argv[1]); pthread_t pthread_send_id, pthread_recv_id; pthread_create(&pthread_send_id, 0, (void*)pthreat_send_data, 0); pthread_create(&pthread_recv_id, 0, (void*)pthreat_recv_data, 0); pthread_join(pthread_send_id, 0); pthread_join(pthread_recv_id, 0); return 0; }
0
#include <pthread.h> struct Queue_Node { int value; struct Queue_Node *next; }; struct Queue_Header { struct Queue_Node *head; struct Queue_Node *tail; pthread_mutex_t head_Lock; pthread_mutex_t tail_Lock; }; struct Queue_Header Q_header = { 0, 0 }; void *mythread(void *arg); void Queue_Init(struct Queue_Header *q); void Enqueue(struct Queue_Header *q, int value); int Dequeue(struct Queue_Header *q, int *value); int isEmpty(struct Queue_Header *q); static volatile int count = 0; pthread_mutex_t Lock; int main(int argc, char* argv[]) { pthread_t p1, p2; pthread_mutex_init(&Lock, 0); Queue_Init(&Q_header); pthread_create(&p1, 0, mythread, 0); pthread_create(&p2, 0, mythread, 0); pthread_join(p1, 0); pthread_join(p2, 0); if (isEmpty(&Q_header) == 0) { printf("\\n"); } printf("%d\\n", count); return 0; } void *mythread(void *arg) { int value; int i; for (i = 0; i<20000000; i++) { pthread_mutex_lock(&Lock); count = count + 1; pthread_mutex_unlock(&Lock); Enqueue(&Q_header, i); Dequeue(&Q_header, &i); } } void Queue_Init(struct Queue_Header *q) { struct Queue_Node *New_Node = (struct Queue_Node *)malloc(sizeof(struct Queue_Node)); New_Node->next = 0; q->head = q->tail = New_Node; pthread_mutex_init(&q->head_Lock, 0); pthread_mutex_init(&q->tail_Lock, 0); } void Enqueue(struct Queue_Header *q, int value) { struct Queue_Node *New_Node = (struct Queue_Node *)malloc(sizeof(struct Queue_Node)); New_Node->value = value; New_Node->next = 0; pthread_mutex_lock(&q->tail_Lock); q->tail->next = New_Node; q->tail = New_Node; pthread_mutex_unlock(&q->tail_Lock); } int Dequeue(struct Queue_Header *q, int *value) { pthread_mutex_lock(&q->head_Lock); struct Queue_Node *New_Node = q->head; struct Queue_Node *New = New_Node->next; if (New == 0) { printf("It is already Empty"); pthread_mutex_unlock(&q->head_Lock); return -1; } *value = New->value; q->head = New; pthread_mutex_unlock(&q->head_Lock); free(New_Node); return 0; } int isEmpty(struct Queue_Header *q) { if (q->head == 0 && q->tail == 0) return 1; else return 0; }
1
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[7]; int sorted[7]; void producer () { int i, idx; for (i = 0; i < 7; i++) { idx = findmaxidx (source, 7); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 7; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t cond_women; pthread_cond_t cond_man; int gender; int number=0; void woman_wants_to_enter() { pthread_mutex_lock(&the_mutex); if (gender == 1) pthread_cond_wait(&cond_women, &the_mutex); number += 1; if (number == 1) { gender = 0; } printf("woman_wants_to_enter\\n"); pthread_mutex_unlock(&the_mutex); } void man_wants_to_enter() { pthread_mutex_lock(&the_mutex); if (gender == 0) pthread_cond_wait(&cond_man, &the_mutex); number += 1; printf("man_wants_to_enter\\n"); if (number == 1) { gender = 1; } pthread_mutex_unlock(&the_mutex); } void woman_leaves() { pthread_mutex_lock(&the_mutex); if (gender == 0) { number -= 1; if (number == 0) { gender = 2; pthread_cond_signal(&cond_man); } printf("woman_leaves\\n"); } pthread_mutex_unlock(&the_mutex); } void man_leaves() { pthread_mutex_lock(&the_mutex); if (gender == 1) { number -= 1; if (number == 0) { gender = 2; pthread_cond_signal(&cond_women); } printf("man_leaves\\n"); } pthread_mutex_unlock(&the_mutex); }
1
#include <pthread.h> int Mat_Size; int No_of_Threads; int rw = 0, cl = 0; double **I_Matrix; double **Pt_Matrix; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; double get_rand(int n) { return ( ((double) rand()) / 32767 ) * n; } void Init_Mat() { int i,j,k; I_Matrix = (double **) malloc(sizeof(double *) * Mat_Size); for (k = 0; k < Mat_Size; k++) I_Matrix[k] = (double *) malloc(sizeof(double) * Mat_Size); for (i = 0; i < Mat_Size; i++) { for (j = 0; j < Mat_Size; j++) I_Matrix[i][j] = get_rand(100); } } void Sequential(double ***Mat) { int i,j,k; double sum; (*Mat) = (double **) malloc(sizeof(double *) * Mat_Size); for (k = 0; k < Mat_Size; k++) (*Mat)[k] = (double *) malloc(sizeof(double) * Mat_Size); for(i = 0; i < Mat_Size ; i++) { for(j = 0; j < Mat_Size ; j++) { sum = 0.0; for (k = 0; k < Mat_Size ; k++) sum += I_Matrix[i][k] * I_Matrix[k][j]; (*Mat)[i][j] = sum; } } } void* do_Thread(void * id) { int i,r,c ; int* id1 = (int*)id; double sum; while (1){ pthread_mutex_lock(&lock); r = rw; c = cl; if(cl >= Mat_Size ){ rw++; cl = 0; } else cl++; pthread_mutex_unlock(&lock); if (r >= Mat_Size ) break; sum = 0.0; for( i = 0 ; i < Mat_Size ; i++) sum += I_Matrix[r][i] * I_Matrix[i][c]; Pt_Matrix[r][c] = sum; } return 0; } void MultiThread() { int i ; int *tids; pthread_t *thrds; pthread_attr_t *attrs; void *retval = 0; thrds = (pthread_t*) malloc(sizeof (pthread_t)* No_of_Threads); attrs = (pthread_attr_t*) malloc(sizeof (pthread_attr_t)* No_of_Threads); tids = (int*) malloc(sizeof (int)* No_of_Threads); for(i = 0; i < No_of_Threads; i++) { if(pthread_attr_init(attrs+i)) { perror(" attr_init()"); } tids[i] = i; if(pthread_create(thrds+i, attrs+i, do_Thread, tids+i) != 0) { perror(" pthread_create()"); exit(1); } } for(i = 0; i < No_of_Threads; i++) pthread_join(thrds[i], &retval); free(attrs); free(thrds); free(tids); return; } int main(int argc, char* argv[]) { double **Seq_Res, err = 0.0000001; int i, j, flag = 0; if(argc != 3) { fprintf(stderr, "argc : Invalid number of arguements \\n"); exit(1); } Mat_Size = atoi(argv[1]); No_of_Threads = atoi(argv[2]); if(Mat_Size < 2) { fprintf(stderr, "arg 2 : Matrix size be alteast 2X2 \\n"); exit(1); } if(No_of_Threads < 2) { fprintf(stderr, "arg 3 : Atleast 2 threads for multithread program \\n"); exit(1); } Pt_Matrix = (double **) malloc(sizeof(double *) * Mat_Size); for (i = 0; i < Mat_Size; i++) Pt_Matrix[i] = (double *) malloc(sizeof(double) * Mat_Size); Init_Mat(); MultiThread(); Sequential(&Seq_Res); fflush(stdout); for(i=0;i<Mat_Size;i++){ for(j=0;j<Mat_Size;j++){ if(Seq_Res[i][j] != Pt_Matrix[i][j]){ flag = 1; break; } } } if (!flag) printf("\\nSUCCESS : Sequential and Threaded resultant matrices are same\\n\\n"); else printf("\\nOOPS!!!!....Sequential and Threaded resultant matrices are Different\\n\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t b; sem_t f; void* erzeuger( void* notused ) { while(1) { sem_wait(&f); pthread_mutex_lock(&mutex); printf("Erzeuger: Element hinzugefügt\\n"); pthread_mutex_unlock(&mutex); sem_post(&b); int b_val; int f_val; sem_getvalue(&b, &b_val); sem_getvalue(&f, &f_val); printf("Erzeuger: B: %d, F: %d \\n", b_val, f_val); sleep(1); } } void* verbraucher( void* notused ) { while(1) { sem_wait(&b); sem_wait(&b); sem_wait(&b); pthread_mutex_lock(&mutex); printf("Verbraucher: Element entfernt \\n"); pthread_mutex_unlock(&mutex); sem_post(&f); sem_post(&f); sem_post(&f); sleep(1); } } int main() { pthread_mutex_init(&mutex, 0); sem_init(&f, 0, 10); sem_init(&b, 0, 0); pthread_t dummy; pthread_create(&dummy, 0, erzeuger, 0); pthread_create(&dummy, 0, verbraucher, 0); sleep(60); return 0; }
1
#include <pthread.h> void startTrain(); void getOff(); void TrainReturn(); void * Passenger(); int timesToRun, passLeft,noBoard, capacity, flag; pthread_mutex_t entry, board, end, ready, ride; int main (int argc, char* argv[]){ int i, noPass, thrCheck; pthread_t *pasThread; noBoard=0; flag=0; printf ("How many passengers? "); scanf (" %d", &noPass); printf ("\\n"); timesToRun= noPass/10; passLeft= noPass%10; capacity= 10; if (pthread_mutex_init(&end, 0) != 0) { perror ("Mutex error"); return 1; } pthread_mutex_lock (&end); if (pthread_mutex_init(&ready, 0) != 0) { perror ("Mutex error"); return 1; } pthread_mutex_lock (&ready); if (pthread_mutex_init(&ride, 0) != 0) { perror ("Mutex error"); return 1; } pthread_mutex_lock (&ride); if (pthread_mutex_init(&entry, 0) != 0) { perror ("Mutex error"); return 1; } if (pthread_mutex_init(&board, 0) != 0) { perror ("Mutex error"); return 1; } pthread_mutex_lock (&board); if (0==(pasThread= (pthread_t*)malloc(sizeof(pthread_t)*noPass))){ perror ("Memory allocation error!!!"); return (1); } for (i=0; i<noPass; i++){ thrCheck = pthread_create( &pasThread[i], 0, Passenger , 0); if(thrCheck){ fprintf(stderr,"Error - pthread_create() return code: %d\\n",thrCheck); exit(1); } } pthread_mutex_lock (&end); pthread_mutex_destroy (&end); pthread_mutex_destroy (&entry); pthread_mutex_destroy (&board); pthread_mutex_destroy (&ready); pthread_mutex_destroy (&ride); free (pasThread); return (0); } void startTrain(){ noBoard--; printf ("YOOOOOHOOOOOOO\\n"); } void getOff(){ static int i=0; if (i==0){ printf ("End of the ride!!!!\\n"); } printf ("It Was Great!!!\\n"); i= (i+1)%capacity; if (i==0){ flag=1; } } void TrainReturn(){ int i; if (timesToRun!=0){ printf ("Returning back\\n"); for (i=0;i<3; i++){ printf (".\\n"); sleep (1); } printf ("Waiting for Passengers\\n");} else { printf ("Nothing else to do let's go home\\n"); pthread_mutex_unlock (&end); } } void *Passenger(){ pthread_mutex_lock (&entry); if ((timesToRun==0)&&(passLeft!=0)){ capacity=passLeft; pthread_mutex_unlock (&entry); } noBoard++; if (noBoard!=capacity){ pthread_mutex_unlock (&entry); }else { pthread_mutex_unlock(&board); } pthread_mutex_lock(&board); if (noBoard==capacity){ printf ("Train Starts\\n"); } startTrain(); if (noBoard!=0){ pthread_mutex_unlock (&board); } if (noBoard==0){ pthread_mutex_unlock (&ride); } pthread_mutex_lock (&ride); getOff(); if ((noBoard==0)&&(flag==1)){ flag=0; printf ("Train returns\\n"); TrainReturn(); pthread_mutex_unlock (&entry); timesToRun--; if ((timesToRun==0)&&(passLeft==0)){ printf ("Nothing else to do let's go home\\n"); pthread_mutex_unlock(&end); }else{ pthread_mutex_unlock (&entry); } } else if (flag==0){ pthread_mutex_unlock (&ride); } return (0); }
0
#include <pthread.h> struct foo{ int f_count; pthread_mutex_t f_lock; }; struct foo * foo_alloc(void) { struct foo * fp; if((fp = malloc(sizeof(struct foo))) != 0){ fp->f_count = 1; if(pthread_mutex_init(&fp->f_lock, 0) != 0){ free(fp); return 0; } } return fp; } void foo_hold(struct foo* fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo* fp) { pthread_mutex_lock(&fp->f_lock); if(--fp->f_count == 0){ printf("last the reference\\n"); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else{ pthread_mutex_unlock(&fp->f_lock); } } int main() { struct foo * fp; if((fp = foo_alloc()) == 0){ printf("foo_alloc error\\n"); return -1; } printf("After foo_alloc, the fp->f_count = %d\\n", fp->f_count); foo_hold(fp); printf("After foo_hold, the fp->f_count = %d\\n", fp->f_count); foo_hold(fp); printf("After foo_hold, the fp->f_count = %d\\n", fp->f_count); foo_rele(fp); printf("After foo_rele, the fp->f_count = %d\\n", fp->f_count); foo_rele(fp); printf("After foo_rele, the fp->f_count = %d\\n", fp->f_count); foo_rele(fp); printf("After foo_rele, the fp->f_count = %d\\n", fp->f_count); return 0; }
1
#include <pthread.h> char fileName[256]; long int fileSize; int fileMode; struct fileStruct *next; } fileStruct; extern int verbose_mode; void SwitchMemory(int *currentMemory, void **writeMemory, void *memory1, void *memory2, pthread_mutex_t *m1lockw, pthread_mutex_t *m1lockr, pthread_mutex_t *m2lockw, pthread_mutex_t *m2lockr) { *currentMemory = -(*currentMemory); switch (*currentMemory) { case -1: (*(int*)memory2) = 2; pthread_mutex_unlock(m2lockr); pthread_mutex_lock(m1lockw); pthread_mutex_lock(m1lockr); *writeMemory = memory1 + sizeof(int); break; case 1: (*(int*)memory1) = 2; pthread_mutex_unlock(m1lockr); pthread_mutex_lock(m2lockw); pthread_mutex_lock(m2lockr); *writeMemory = memory2 + sizeof(int); break; default: fprintf(stderr, "switch mem error"); exit(1); break; } } void ReadFile(struct fileStruct * list, long bufSize, void *memory1, void *memory2, pthread_mutex_t *m1lockw, pthread_mutex_t *m1lockr, pthread_mutex_t *m2lockw, pthread_mutex_t *m2lockr){ bufSize -= sizeof(int); FILE *fp; long int remainMemory = bufSize; int currentMemory = -1; void *writeMemory = memory1 + sizeof(int); fileStruct *ergodic = list; while (ergodic != 0) { if (verbose_mode) { printf("read file:%s\\n",ergodic->fileName); } if (sizeof(fileStruct) < remainMemory) { memcpy(writeMemory, ergodic, sizeof(fileStruct)); remainMemory = remainMemory - sizeof(fileStruct); writeMemory = writeMemory + sizeof(fileStruct); fp = fopen(ergodic->fileName, "r"); if (ergodic->fileSize < remainMemory) { fread(writeMemory, ergodic->fileSize, 1, fp); remainMemory = remainMemory - ergodic->fileSize; writeMemory = writeMemory + ergodic->fileSize; ergodic = ergodic->next; fclose(fp); continue; } else if (ergodic->fileSize == remainMemory) { fread(writeMemory, ergodic->fileSize, 1, fp); remainMemory = bufSize; SwitchMemory(&currentMemory, &writeMemory, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr); ergodic = ergodic->next; fclose(fp); continue; } fread(writeMemory, remainMemory, 1, fp); long int hasRead = remainMemory; SwitchMemory(&currentMemory, &writeMemory, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr); remainMemory = bufSize; int writeTimes = ceil((ergodic->fileSize - hasRead) / (float)bufSize); int i; for (i = 1; i < writeTimes;i++) { fseek(fp, hasRead + bufSize * (i - 1), 0); fread(writeMemory, bufSize, 1, fp); SwitchMemory(&currentMemory, &writeMemory, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr); } fseek(fp, hasRead + bufSize * (writeTimes - 1), 0); fread(writeMemory, ergodic->fileSize - (hasRead + bufSize * (writeTimes - 1)), 1, fp); writeMemory += ergodic->fileSize - (hasRead + bufSize * (writeTimes -1)); remainMemory = bufSize - (ergodic->fileSize - (hasRead + bufSize * (writeTimes - 1))); if (remainMemory == 0) { remainMemory = bufSize; SwitchMemory(&currentMemory, &writeMemory, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr); ergodic = ergodic->next; fclose(fp); continue; } ergodic = ergodic->next; fclose(fp); } else { remainMemory = bufSize; SwitchMemory(&currentMemory, &writeMemory, memory1, memory2, m1lockw, m1lockr, m2lockw, m2lockr); } } if (currentMemory == -1) { pthread_mutex_unlock(m1lockr); *(int*)memory1 = 1;} else { pthread_mutex_unlock(m2lockr); *(int*)memory2 = 1;} }
0