text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int id; int numPhilo; int numEat; }Arguments; void *philosopher (void *id); pthread_mutex_t chopstick[1000]; pthread_t philo[1000]; int main (int argn,char **argv) { int i=0,timesEatting=0,numPhilo=0; Arguments* args; if (argn < 3||argn > 3){ printf("Wrong amount of arguments. Try again with Program name then number of philosophers then how many times each of them eat.\\n"); return 1; } args=calloc(atoi(argv[1]),sizeof(Arguments)); if(args==0){ printf("error in making struct for threads\\n"); return 1; } numPhilo=atoi(argv[1]); timesEatting=atoi(argv[2]); for (i = 0; i < numPhilo; i++) pthread_mutex_init (&chopstick[i], 0); for (i = 0; i < numPhilo; i++){ args[i].id=i; args[i].numPhilo=numPhilo; args[i].numEat=timesEatting; pthread_create (&philo[i], 0, &philosopher, &args[i]); } for (i = 0; i < numPhilo; i++) pthread_join (philo[i], 0); free(args); return 0; } void *philosopher (void *num) { Arguments* args = num; int id=0, numPhilo=0; int timesNeededToEat=0, left_chopstick=0, right_chopstick=0; id = args->id; timesNeededToEat=args->numEat; numPhilo=args->numPhilo; right_chopstick = id+1; left_chopstick = id; if (right_chopstick == numPhilo) right_chopstick = 0; while(timesNeededToEat!=0){ printf ("Philosopher %d thinking\\n", (id+1)); pthread_mutex_lock (&chopstick[right_chopstick]); pthread_mutex_lock (&chopstick[left_chopstick]); printf ("Philosopher %d eating\\n", (id+1)); usleep (5000-(timesNeededToEat+1)); pthread_mutex_unlock (&chopstick[left_chopstick]); pthread_mutex_unlock (&chopstick[right_chopstick]); timesNeededToEat--; } printf ("Philosopher %d is done eating.\\n", (id+1)); return (0); }
1
#include <pthread.h> pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t id_mutex = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int getId() { static int id = 0; pthread_mutex_lock(&id_mutex); id++; pthread_mutex_unlock(&id_mutex); return id; } void* increment(void* nothing) { int exit = 0; int shortId = getId(); while(!exit) { pthread_mutex_lock(&mutex); if (counter >= 10) { printf("[INCREMENT] %d : SIGNAL SENT\\n", shortId); pthread_cond_signal(&cond_var); exit = 1; } else { printf("[INCREMENT] %d : Counter from '%d' to '%d'\\n", shortId, counter, counter + 1); counter = counter + 1; } pthread_mutex_unlock(&mutex); usleep(1000); } printf("\\tTermination of [INCREMENT] %d\\n", shortId); return 0; } void* isReached(void* nothing) { int shortId = getId(); pthread_mutex_lock(&mutex); if (counter < 10) { printf("[ISREACHED] %d : WAITING SIGNAL\\n", shortId); pthread_cond_wait(&cond_var, &mutex); } printf("[ISREACHED] %d : SIGNAL RECEIVED\\n", shortId); printf("[ISREACHED] %d : Counter = %d\\n", shortId, counter); pthread_mutex_unlock(&mutex); printf("\\tTermination of [ISREACHED] %d\\n", shortId); return 0; } int main(int argc, char* argv[]) { printf("Synchronized Threads Lab\\n"); int i; pthread_t thread[3]; int iret[3]; iret[0] = pthread_create(&thread[0], 0, increment, 0); iret[1] = pthread_create(&thread[1], 0, increment, 0); iret[2] = pthread_create(&thread[2], 0, isReached, 0); for (i = 0 ; i < 3 ; i++) pthread_join(thread[i], 0); for (i = 0 ; i < 3 ; i++) printf("Thread %d returns: %d\\n", i, iret[i]); return 0; }
0
#include <pthread.h> void *threadfunc(void *arg); pthread_barrier_t barrier; pthread_mutex_t mutex; int serial_count; int after_barrier_count; int main(int argc, char *argv[]) { int i, ret; pthread_t new[10]; void *joinval; pthread_mutex_init(&mutex, 0); ret = pthread_barrier_init(&barrier, 0, 10); if (ret != 0) err(1, "pthread_barrier_init"); for (i = 0; i < 10; i++) { ret = pthread_create(&new[i], 0, threadfunc, (void *)(long)i); if (ret != 0) err(1, "pthread_create"); sleep(2); } for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); assert(after_barrier_count >= (10 - i)); pthread_mutex_unlock(&mutex); ret = pthread_join(new[i], &joinval); if (ret != 0) err(1, "pthread_join"); printf("main joined with thread %d\\n", i); } assert(serial_count == 1); return 0; } void * threadfunc(void *arg) { int which = (int)(long)arg; int ret; printf("thread %d entering barrier\\n", which); ret = pthread_barrier_wait(&barrier); printf("thread %d leaving barrier -> %d\\n", which, ret); pthread_mutex_lock(&mutex); after_barrier_count++; if (ret == PTHREAD_BARRIER_SERIAL_THREAD) serial_count++; pthread_mutex_unlock(&mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t chopsticks_mutex; unsigned int state = 0; int eat(int id){ int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % 5; for (i = 0; i < 2; i++) { pthread_mutex_lock(&chopsticks_mutex + f[i]); } int timer = abs(randomGaussian_r(9, 3, &state)); printf("Philosopher %i is eating for %i units\\n", id, timer); sleep(timer); for(i = 0; i < 2; i++){ pthread_mutex_unlock(&chopsticks_mutex + f[i]); } return timer; } void think(int id){ int timer = abs(randomGaussian_r(11, 7, &state)); printf("Philosopher %i is thinking for %i units \\n", id, timer); sleep(timer); } void* goPhilo(int* id){ int eaten = 0; think(*id); while(eaten < 100){ eaten += eat(*id); think(*id); } printf("Philosopher %i leaving table having eaten %i units\\n", *id, eaten); pthread_exit(0); } int main(){ pthread_t philos[5]; int* id; pthread_mutex_init(&chopsticks_mutex, 0); for(int i = 0; i < 5; i++){ id = (int*)malloc(sizeof(int)); *id = i; pthread_create(&philos[i], 0, (void*) goPhilo, (void*) id); } for(int i = 0; i < 5; i++){ pthread_join(philos[i], 0); } return 0; }
0
#include <pthread.h> static int sigsegv_caught; static pthread_t tid1; static pthread_t tid2; static sigjmp_buf env; static void* glb_si_ptr; static void* glb_si_addr; static void* glb_si_call_addr; pthread_mutex_t mutex; static const int addresses_size = 64; static void* worker_thread( void* arg ); static void* worker_thread2( void* arg ); static void signal_handler(int signal, siginfo_t *info, void *c) { int i = 0; printf("signal is %d, SIGSEGV is %d\\n", signal, SIGSEGV); printf("%s child thread tid = %u\\n", __func__, pthread_self()); if(signal == SIGSEGV){ if(tid1 == pthread_self()){ printf("right tid\\n"); if(mutex.__data.__lock == 1) { printf("SIGSEGV unlock\\n"); pthread_mutex_unlock(&mutex); } pthread_exit(0); }else{ printf("exit\\n"); exit(-1); } return ; }else{ printf("other signal\\n"); } exit(0); } int main(int argc, char *argv[]) { sigsegv_caught = 0; struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_sigaction = signal_handler; act.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &act, 0); if(pthread_mutex_init(&mutex, 0) < 0){ printf("mutex init error\\n"); } pthread_create( &tid2, 0, &worker_thread2, (void *)0 ); sleep(2); pthread_create( &tid1, 0, &worker_thread, (void *)0 ); pthread_join( tid1, 0 ); while(1) { sleep(3); } return 0; } static void* worker_thread(void* args) { int ret; int lock = 0; printf("%s child thread tid = %u\\n", __func__, pthread_self()); printf("worker_thread lock\\n"); pthread_mutex_lock(&mutex); char *cp = 0; printf("worker_thread unlock\\n"); pthread_mutex_unlock(&mutex); return 0; } static void* worker_thread2(void* args) { printf("%s child thread tid = %u\\n", __func__, pthread_self()); while(1) { printf("worker_thread2 lock\\n"); pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); printf("worker_thread2 unlock\\n"); sleep(3); } return 0; }
1
#include <pthread.h> { int count; pthread_mutex_t m; pthread_cond_t cv; } sem_t; { sem_t occupied; sem_t freeSpace; int vp; int vc; sem_t pmut; sem_t cmut; pthread_mutex_t m; } buffer_t; sem_post(sem_t *s) { pthread_mutex_lock(&s->m); s->count++; pthread_cond_signal(&s->cv); pthread_mutex_unlock(&s->m); } sem_wait(sem_t *s) { pthread_mutex_lock(&s->m); while (s->count == 0) { pthread_cond_wait(&s->cv, &s->m); } s->count--; pthread_mutex_unlock(&s->m); } int sem_init(sem_t *s, int pshared, int value) { if (pshared) { errno = ENOSYS ; return -1; } s->count = value; pthread_mutex_init(&s->m, 0); pthread_cond_init(&s->cv, 0); return 0; } void producer(buffer_t *b) { int i; sem_wait(&b->freeSpace); sem_wait(&b->pmut); pthread_mutex_lock(&b->m); printf("p"); for (i = 0; i < b->vp; i++) { printf("*"); } printf("\\n"); pthread_mutex_unlock(&b->m); b->vp = b->vp + 2; sem_post(&b->pmut); sem_post(&b->occupied); } void consumer(buffer_t *b) { int i; int rv = sem_wait(&b->occupied); sem_wait(&b->cmut); if (rv != 0) { printf("errno %d\\n", errno); } pthread_mutex_lock(&b->m); printf("c"); for (i = 0; i < b->vc; i++) { printf("*"); } printf("\\n"); pthread_mutex_unlock(&b->m); b->vc = b->vc + 2; sem_post(&b->cmut); sem_post(&b->freeSpace); } int main() { printf("example for producer and consumer problem\\n"); pthread_t tp; pthread_t tc; buffer_t buffer; sem_init(&buffer.occupied, 0, 0); sem_init(&buffer.freeSpace, 0, 1); sem_init(&buffer.pmut, 0, 1); sem_init(&buffer.cmut, 0, 1); pthread_mutex_init(&buffer.m, 0); buffer.vp = 1; buffer.vc = 2; int j = 20; while (j--) { pthread_create(&tc, 0, &consumer, (void *)&buffer); } j = 20; while (j--) { pthread_create(&tp, 0, &producer, (void *)&buffer); } sleep(2); return 0; }
0
#include <pthread.h> static void *handle_msg_shoot(void *ptr); static inline void send_msg_image_buffer(void); static inline void send_msg_status(void); static volatile int is_shooting, image_idx, image_count, shooting_idx, shooting_count, shooting_thread_count; static char image_buffer[25][70]; static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { pthread_t shooting_threads[8]; char c; int i; printf("CATIA:\\tStarting Camera Application Triggering Image Analysis\\n"); chdk_pipe_init(); int ret = serial_init("/dev/ttySAC0"); if (ret < 0) { printf("CATIA:\\tfailed to open /dev/ttySAC0\\n"); return -1; } pthread_mutex_init(&mut, 0); socket_init(1); is_shooting = 0; mora_protocol.status = 0; image_idx = 0; image_count = 0; shooting_idx = 0; shooting_count = 0; shooting_thread_count = 0; while (1) { if (read(fd, &c, 1) > 0) { parse_mora(&mora_protocol, c); } else if (errno != 11) { printf("CATIA:\\nSerial error: %d\\n" , errno); } if (mora_protocol.msg_received) { mora_protocol.msg_received = FALSE; if (mora_protocol.msg_id == MORA_SHOOT) { union dc_shot_union *shoot = (union dc_shot_union *) malloc(sizeof(union dc_shot_union)); for (i = 0; i < MORA_SHOOT_MSG_SIZE; i++) { shoot->bin[i] = mora_protocol.payload[i]; } printf("CATIA:\\tSHOT %d,%d\\n", shoot->data.nr, shoot->data.phi); pthread_create(&shooting_threads[(shooting_idx++ % 8)], 0, handle_msg_shoot, (void *)shoot); send_msg_status(); } if (mora_protocol.msg_id == MORA_BUFFER_EMPTY) { send_msg_image_buffer(); } } if (socket_recv(image_buffer[image_idx], 70) == 70) { image_idx = (image_idx + 1) % 25; if (image_count < 25) { image_count++; } } } close(fd); chdk_pipe_deinit(); printf("CATIA:\\tShutdown\\n"); return 0; } static void *handle_msg_shoot(void *ptr) { char filename[512], soda_call[512]; union dc_shot_union *shoot = (union dc_shot_union *) ptr; pthread_mutex_lock(&mut); if (is_shooting) { pthread_mutex_unlock(&mut); printf("CATIA-%d:\\tShooting: too fast\\n", shoot->data.nr); free(shoot); return 0; } is_shooting = 1; shooting_count++; shooting_thread_count++; pthread_mutex_unlock(&mut); printf("CATIA-%d:\\tShooting: start\\n", shoot->data.nr); chdk_pipe_shoot(filename); printf("CATIA-%d:\\tShooting: got image %s\\n", shoot->data.nr, filename); pthread_mutex_lock(&mut); is_shooting = 0; pthread_mutex_unlock(&mut); sprintf(soda_call, "%s %s %d %d %d %d %d %d %d %d %d %d", "/root/develop/allthings_obc2014/src/soda/soda", filename, shoot->data.nr, shoot->data.lat, shoot->data.lon, shoot->data.alt, shoot->data.phi, shoot->data.theta, shoot->data.psi, shoot->data.vground, shoot->data.course, shoot->data.groundalt); printf("CATIA-%d:\\tCalling '%s'\\n", shoot->data.nr, soda_call); short int ret = system(soda_call); printf("CATIA-%d:\\tShooting: soda return %d of image %s\\n", shoot->data.nr, ret, filename); pthread_mutex_lock(&mut); shooting_thread_count--; pthread_mutex_unlock(&mut); free(shoot); } static inline void send_msg_image_buffer(void) { int i; if (image_count > 0) { printf("CATIA:\\thandle_msg_buffer: Send %d\\n", image_idx); image_idx = (25 + image_idx - 1) % 25; image_count--; MoraHeader(MORA_PAYLOAD, MORA_PAYLOAD_MSG_SIZE); for (i = 0; i < 70; i++) { MoraPutUint8(image_buffer[image_idx][i]); } MoraTrailer(); } } static inline void send_msg_status(void) { int i; struct mora_status_struct status_msg; char *buffer = (char *) &status_msg; pthread_mutex_lock(&mut); status_msg.cpu = 0; status_msg.threads = shooting_thread_count; status_msg.shots = shooting_count; status_msg.extra = 0; pthread_mutex_unlock(&mut); MoraHeader(MORA_STATUS, MORA_STATUS_MSG_SIZE); for (i = 0; i < MORA_STATUS_MSG_SIZE; i++) { MoraPutUint8(buffer[i]); } MoraTrailer(); }
1
#include <pthread.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int avail = 0; static int data = 0; static void * producer(void *arg) { int cnt = *((int *) arg); int j,ret; for (j = 0; j < cnt; j++) { sleep(1); pthread_mutex_lock(&mtx); avail++; data++; pthread_mutex_unlock(&mtx); ret = pthread_cond_signal(&cond); if (ret != 0) perror( "pthread_cond_signal"); } return 0; } static void *consumer1(void *arg) { int ret,numConsumed = 0; Boolean done= FALSE; int totRequired=10; for (;;) { pthread_mutex_lock(&mtx); while(avail==0) { ret = pthread_cond_wait(&cond, &mtx); if (ret != 0) perror( "pthread_cond_wait"); } numConsumed ++; avail--; printf("unit Consumed by consumer1=%d\\n",data); done = numConsumed >= totRequired; pthread_mutex_unlock(&mtx); if (done) break; } } static void *consumer2(void *arg) { int ret,numConsumed = 0; Boolean done= FALSE; int totRequired=10; for (;;) { pthread_mutex_lock(&mtx); while(avail==0) { ret = pthread_cond_wait(&cond, &mtx); if (ret != 0) perror( "pthread_cond_wait"); } numConsumed ++; avail--; printf("unit Consumed by consumer2=%d\\n",data); done = numConsumed >= totRequired; pthread_mutex_unlock(&mtx); if (done) break; } } int main() { pthread_t tid; int ret, j; int totRequired = 10; ret = pthread_create(&tid, 0, producer, &totRequired); if (ret != 0) perror("pthread_create: "); ret = pthread_create(&tid, 0, consumer1, 0); if (ret != 0) perror("pthread_create: "); ret = pthread_create(&tid, 0, consumer2, 0); if (ret != 0) perror("pthread_create: "); pthread_exit(0); exit(0); }
0
#include <pthread.h> long long int size; char* D1; char* D2; int* bit1; int* bit2; int* bitr; pthread_mutex_t* D1_lock; pthread_mutex_t* D2_lock; int STATE; } database; database global_db; int is_finished = 0; long long int throughput = 0; long long int active0=0; long long int active1=0; int peroid=0; int* sec_throughput; long long int run_count = 0; int ckp_fd; void load_db(long long int size) { global_db.size = size; global_db.STATE = 0; global_db.D1 = (char *) malloc(global_db.size * 4096); global_db.D2 = (char *) malloc(global_db.size * 4096); global_db.bit1 = (int *) malloc(global_db.size * sizeof(int)); global_db.bit2 = (int *) malloc(global_db.size * sizeof(int)); global_db.bitr = (int *) malloc(global_db.size * sizeof(int)); global_db.D1_lock = (pthread_mutex_t *) malloc(global_db.size * sizeof(pthread_mutex_t)); global_db.D2_lock = (pthread_mutex_t *) malloc(global_db.size * sizeof(pthread_mutex_t)); long long int i = 0; while(i < global_db.size) { pthread_mutex_init(&(global_db.D1_lock[i]),0); pthread_mutex_init(&(global_db.D2_lock[i]),0); i++; } } void work0() { long long int index1 = rand() % (global_db.size); int value1 = rand(); global_db.bit1[index1] = 1; pthread_mutex_lock(&(global_db.D1_lock[index1])); int k =0; while(k++ < 1024) { memcpy( global_db.D1 + 4096 * index1 + 4*k , &value1, 4); } pthread_mutex_unlock(&(global_db.D1_lock[index1])); global_db.bitr[index1] = 0; sec_throughput[run_count++] = get_mtime(); } void work1(){ long long int index1 = rand() % (global_db.size); int value1 = rand(); global_db.bit2[index1] = 1; pthread_mutex_lock(&(global_db.D2_lock[index1])); int k =0; while(k++ < 1024) { memcpy( global_db.D2 + 4096 * index1 + 4*k , &value1, 4); } pthread_mutex_unlock(&(global_db.D2_lock[index1])); global_db.bitr[index1] = 0; sec_throughput[run_count++] = get_mtime(); } void* transaction(void* info) { while(is_finished==0) { int p = peroid; if(p%2==0) { __sync_fetch_and_add(&active0,1); work0(); __sync_fetch_and_sub(&active0,1); }else{ __sync_fetch_and_add(&active1,1); work1(); __sync_fetch_and_sub(&active1,1); } } } void checkpointer(int num) { char* temp; int * temp2; sleep(5); while(num--) { sleep(1); peroid++; int p = peroid; long long int i; if(p%2==1){ while(active0>0); i = 0; ckp_fd = open("./dump.dat", O_WRONLY | O_TRUNC | O_SYNC | O_CREAT, 666); while(i < global_db.size) { if(global_db.bit1[i] == 1) { write(ckp_fd, global_db.D1 + i * 4096,4096); lseek(ckp_fd, 0, 2); global_db.bit1[i] == 0; } else{ write(ckp_fd, global_db.D1 + i * 4096,4096); lseek(ckp_fd, 0, 2); } i++; } } else{ while(active1>0); i = 0; ckp_fd = open("./dump.dat", O_WRONLY | O_TRUNC | O_SYNC | O_CREAT, 666); while(i < global_db.size) { if(global_db.bit2[i] == 1) { write(ckp_fd, global_db.D2 + i * 4096,4096); lseek(ckp_fd, 0, 2); global_db.bit2[i] == 0; } else{ write(ckp_fd, global_db.D2 + i * 4096,4096); lseek(ckp_fd, 0, 2); } i++; } } } is_finished = 1; } int main(int argc, char const *argv[]) { srand((unsigned)time(0)); load_db(atoi(argv[1])); sec_throughput = (int*) malloc(10000000000 * sizeof(int)); throughput = atoi(argv[2]); for (int i = 0; i < throughput; ++i) { pthread_t pid_t; pthread_create(&pid_t,0,transaction,0); } checkpointer(10); int max,min; max_min(sec_throughput,run_count,&max,&min); int duration = max-min+1; int* result = (int*) malloc(sizeof(int) * (duration)); for (long long int i = 0; i < run_count; ++i) { result[ (sec_throughput[i] - min) ] +=1; } printf("%f\\n", 1.0*run_count / duration); return 0; }
1
#include <pthread.h> struct archivoVersion{ int v; char* archivo; }; struct archivoVersion* arch; char* ips[6]; pthread_mutex_t versiones = PTHREAD_MUTEX_INITIALIZER; int cantIps=0; int cantArch=0; int imprimirIPConectada(struct svc_req *rqstp) { printf("%d.%d.%d.%d", (rqstp->rq_xprt->xp_raddr.sin_addr.s_addr&0xFF), ((rqstp->rq_xprt->xp_raddr.sin_addr.s_addr&0xFF00)>>8), ((rqstp->rq_xprt->xp_raddr.sin_addr.s_addr&0xFF0000)>>16), ((rqstp->rq_xprt->xp_raddr.sin_addr.s_addr&0xFF000000)>>24)); return 0; } int * registrarse_1_svc(char **argp, struct svc_req *rqstp) { static int result; result=0; int existe=0; int i=0; if (cantIps<6){ while (i<cantIps && !existe) { if (!strcmp(ips[i],*argp)) existe=1; else i++; } if (!existe) { printf("se registro:%s\\n\\n",*argp); ips[cantIps]=malloc(strlen(*argp)); *(ips[cantIps])='\\0'; strcat(ips[cantIps],*argp); cantIps++; result=1; } } else result=2; return &result; } char ** getipregistradas_1_svc(void *argp, struct svc_req *rqstp) { static char * result; int i; char* aux; aux=(char *)malloc(100); *aux='\\0'; for (i=0;i<cantIps;i++) sprintf(aux,"%s%s\\n",aux,ips[i]); strcat(aux,"\\0"); result =aux; return &result; } int * eliminarip_1_svc(char **argp, struct svc_req *rqstp) { static int result; int i,j; int encontre; i=0; encontre=0; result=0; while (i<cantIps && !encontre) { if (!strcmp(ips[i],*argp)) { encontre=1; result=1; free(ips[i]); cantIps--; } else i++; } if (encontre==1){ printf("El servidor "); imprimirIPConectada(rqstp); printf(" elimino al servidor %s\\n",*argp); } if (encontre==1 && cantIps!=0) for (j=i;j<6 -1;j++) ips[j]=ips[j+1]; return &result; } char ** update_1_svc(void *argp, struct svc_req *rqstp) { static char * result; char* aux; int i=0; char c; aux=(char * )malloc((cantArch* (sizeof(struct archivoVersion)+2))+1); *aux='\\0'; while (i<cantArch){ sprintf(aux,"%s%s %i\\n",aux,(arch+i)->archivo, (arch+i)->v); i++; } c='\\0'; strcat(aux,&c); result=aux; return &result; } int * getversionaescribir_1_svc(char **argp, struct svc_req *rqstp) { static int result; int i; int encontre; if (cantArch==0) arch=(struct archivoVersion*)malloc(100* sizeof(struct archivoVersion)); else if (cantArch%100==0) arch=(struct archivoVersion*)realloc (arch,(cantArch+100)*sizeof(struct archivoVersion)); i=0; encontre=0; while (i<cantArch && !encontre) { if (strcmp((arch+i)->archivo,*argp)==0) { encontre=1; pthread_mutex_lock (&versiones); ((arch+i)->v)++; result=(arch+i)->v; pthread_mutex_unlock (&versiones); } i++; } if (encontre==0) { result=0; (arch+cantArch)->archivo=(char*)malloc(100); *((arch+cantArch)->archivo)='\\0'; strcat(((arch+cantArch)->archivo),*argp); pthread_mutex_lock (&versiones); (arch+cantArch)->v=0; cantArch++; pthread_mutex_unlock (&versiones); } return &result; }
0
#include <pthread.h> struct glob{ int a; int b; }obj; pthread_mutex_t r_mutex; int a_bakup,b_bakup; void recover(void){ pthread_mutex_consistent_np(&r_mutex); obj.a = a_bakup; obj.b = b_bakup; pthread_mutex_unlock(&r_mutex); } void *threadFunc1(void *arg){ printf("thread1 has created, tid = %lu\\n",pthread_self()); printf("thread1 locked the semaphore\\n"); pthread_mutex_lock(&r_mutex); a_bakup = obj.a ; b_bakup = obj.b; obj.a = 10; sleep(5); pthread_exit(0); obj.b = 20; pthread_mutex_unlock(&r_mutex); printf("thread1 unlocked the semaphore\\n"); } void *threadFunc2(void *arg){ printf("thread2 has created, tid = %lu\\n",pthread_self()); printf("waiting....\\n"); if(errno = pthread_mutex_lock(&r_mutex)){ perror("pthread_mutex_lock"); if(errno == EOWNERDEAD){ recover(); } } printf("mem1:%d\\n",obj.a); printf("mem2:%d\\n",obj.b); pthread_mutex_unlock(&r_mutex); } main(int argc,char *argv[]){ obj.a =1000; obj.b =2000; pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_setrobust_np(&mutexattr,PTHREAD_MUTEX_ROBUST_NP); pthread_mutex_init(&r_mutex,&mutexattr); pthread_t tid1,tid2; pthread_create(&tid1,0,threadFunc1,0); sleep(1); pthread_create(&tid2,0,threadFunc2,0); pthread_join(tid1,0); pthread_join(tid2,0); }
1
#include <pthread.h> pthread_mutex_t mutex; void * another(void* arg){ printf("in child thread,lock the mutex\\n"); pthread_mutex_lock(&mutex); sleep(5); pthread_mutex_unlock(&mutex); } int main(){ pthread_mutex_init(&mutex,0); pthread_t tid; pthread_create(&tid,0,another,0); sleep(1); int pid=fork(); if(pid<0){ pthread_join(tid,0); pthread_mutex_destroy(&mutex); return -1; } else if(pid==0){ printf("I am in the child,want to get the lock\\n"); pthread_mutex_lock(&mutex); printf("I can not run to here,oop...\\n"); pthread_mutex_unlock(&mutex); exit(0); } else{ wait(0); } pthread_join(tid,0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; char msg[100]; }user_data_t; pthread_mutex_t mutex; int ref_cnt; user_data_t* data; }comm_t; void comm_get(comm_t * p) { pthread_mutex_lock(&p->mutex); if(p->ref_cnt == 0){ p->data=malloc(sizeof(user_data_t)); pthread_mutex_init(&p->data->mutex, 0); snprintf(p->data->msg, 100, "hello world"); } p->ref_cnt ++; pthread_mutex_unlock(&p->mutex); } void comm_put(comm_t * p) { pthread_mutex_lock(&p->mutex); p->ref_cnt --; if(p->ref_cnt == 0){ pthread_mutex_destroy(&p->data->mutex); free(p->data); p->data=0; } pthread_mutex_unlock(&p->mutex); } void * thread_func1(void * param) { int command = 1; comm_t *pcomm=(comm_t*)param; sleep(20); printf("you can modify command here\\n"); switch(command){ case 0: printf("zero, do nothing\\n"); break; case 1: comm_get(pcomm); printf("doing sth with lock ref cnd hold\\n"); pthread_mutex_lock(&pcomm->data->mutex); printf("data:%s\\n", pcomm->data->msg); strcat(pcomm->data->msg, "from BWRAID"); pthread_mutex_unlock(&pcomm->data->mutex); comm_put(pcomm); break; default: printf("I don't understand this\\n"); break; } } void * thread_func2(void * param) { int command = 1; int *p=0; comm_t *pcomm=(comm_t*)param; sleep(30); printf("you can modify command here\\n"); switch(command){ case 0: printf("zero, do nothing\\n"); break; case 1: comm_get(pcomm); printf("doing sth with lock ref cnd hold\\n"); pthread_mutex_lock(&pcomm->data->mutex); printf("data:%s", pcomm->data->msg); strcat(pcomm->data->msg, "BWRAID"); pthread_mutex_unlock(&pcomm->data->mutex); comm_put(pcomm); break; default: printf("I don't understand this\\n"); break; } } comm_t g_comm; int create_thread(void*(*func)(void *), void*param, pthread_t *tid) { int rc; rc = pthread_create(tid, 0, func, param); if(rc != 0){ perror("pthread create failed\\n"); }else{ printf("created new thread: %d\\n", *tid); } return rc; } int main() { pthread_t tid1, tid2; int rc, i; pthread_mutex_init(&g_comm.mutex, 0); g_comm.ref_cnt=0; g_comm.data=0; comm_get(&g_comm); create_thread(thread_func1, &g_comm, &tid1); create_thread(thread_func2, &g_comm, &tid2); comm_put(&g_comm); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_mutex_destroy(&g_comm.mutex); }
1
#include <pthread.h> int counter = 4; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *inc_counter(void *arg) { (void) arg; pthread_mutex_lock(&mutex); counter++; fprintf(stderr, "Thread %ld : Counter value: %d\\n", pthread_self(), counter); pthread_mutex_unlock(&mutex); return 0; } int main(void) { pthread_t thread_id[10]; int ii; for (ii = 0; ii < 10; ii ++) { if (pthread_create(&thread_id[ii], 0, &inc_counter, 0) != 0) { perror("pthread_create"); exit(1); } } for (ii = 0; ii < 10; ii ++) { if (pthread_join(thread_id[ii], 0) != 0) { perror("pthread_join"); exit(1); } } printf("Final counter value %d\\n", counter); exit(0); }
0
#include <pthread.h> void init_consensus() { int i; pthread_mutex_init(&mutex_consensus, 0); consensus_state_others=(float**)malloc(sizeof(float*)*(CONSENSUS_AGENTS)); for (i=0;i<CONSENSUS_AGENTS;i++) consensus_state_others[i]=(float*)malloc(sizeof(float)*3); consensus_valid=(int*)malloc(sizeof(int)*CONSENSUS_AGENTS); for (i=0;i<CONSENSUS_AGENTS;i++) consensus_valid[i]=0; } void calculate_consensus_velocities(float* v_x, float* v_y, float state_x, float state_y) { int i; *v_x=0; *v_y=0; pthread_mutex_lock(&mutex_consensus); for (i=0;i<CONSENSUS_AGENTS;i++) { if (consensus_valid[i]==1) { consensus_valid[i]=0; *v_x=*v_x+consensus_state_others[i][STATE_X]-state_x; *v_y=*v_y+consensus_state_others[i][STATE_Y]-state_y; } } pthread_mutex_unlock(&mutex_consensus); } void get_vel_desiderate_consensus(float V_X, float V_Y, float* V_D, float* W_D, float k_v, float k_w) { float ratio; *V_D=sqrt(V_X*V_X+V_Y*V_Y); if(*V_D<=DESIDERED_VELOCITY_THRESHOLD) { *V_D=0; *W_D=0; } else{ if (V_Y==0 && V_X==0) { *W_D=0; *V_D=0; } else { *W_D=atan2(V_Y, V_X)-state[STATE_THETA]; if (*W_D > M_PI) { *W_D -= (2 * M_PI); } if (*W_D<-M_PI) { *W_D += (2 * M_PI); } *V_D=k_v*(*V_D); *W_D=k_w*(*W_D); ratio = min(MAX_LIN_VEL / (modulo(*V_D)), MAX_TURN_RATE / modulo(*W_D)); if (ratio < 1.0) { *V_D *= ratio; *W_D *= ratio; } } } } void close_consensus() { int i; pthread_mutex_destroy(&mutex_consensus); for (i=0;i<CONSENSUS_AGENTS;i++) free(consensus_state_others[i]); free(consensus_valid); }
1
#include <pthread.h> int pocz ,kon,licznik = 0; char bufor[4][255]; pthread_mutex_t mutex; pthread_cond_t puste, pelne; int pk, kk; void* producent( void* arg ) { int num = 0; int cnt = 1; int prod = 1; char str[255]; num = (int) arg; printf("Start producent: %d\\n",num); while( prod <= pk ) { pthread_mutex_lock( &mutex ); while(licznik >= 4) pthread_cond_wait(&puste,&mutex); sprintf(str, "Producent %d wstawil %d element", num, prod); strcpy(bufor[kon], str); cnt++; kon = (kon+1) %4; licznik++; prod++; pthread_cond_signal(&pelne); pthread_mutex_unlock( &mutex ); printf("%s \\n", str); sleep( 1 ); } } void* konsument( void* arg ) { int num,x = 0, kon = kk; num = (int) arg; char str[255]; printf("Start konsument: %d\\n",num); while( kon ) { pthread_mutex_lock( &mutex ); while(licznik <=0 ) pthread_cond_wait(&pelne,&mutex); strcpy(str, bufor[pocz]); pocz = (pocz+1) %4; licznik--; kon--; pthread_cond_signal(&puste); pthread_mutex_unlock( &mutex ); printf("Kons%d pobral: %s \\n", num, str ); sleep( 1 ); } } int main( int argc, const char* argv[] ) { int pc = atoi(argv[1]); pk = atoi(argv[2]); int kc = atoi(argv[3]); kk = atoi(argv[4]); int i=0; pthread_t * prod; pthread_t * kons; prod = malloc(sizeof *prod * (pc)); kons = malloc(sizeof *kons * (kc)); pthread_mutex_init(&mutex,0); pthread_cond_init(&puste,0); pthread_cond_init(&pelne,0); for(i=0; i<pc; i++) { pthread_create(&prod[i], 0, &producent, (void *)i+1); } for(i=0; i< kc; i++) { pthread_create(&kons[i], 0, &konsument, (void *)i+1); } for(i=0; i<pc; i++) { pthread_join(prod[i], 0); } for(i=0; i< kc; i++) { pthread_join(&kons[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void* thread_worker(void*); void critical_section(int thread_num, int i); int main(void) { int rtn, i; pthread_t pthread_id = 0; rtn = pthread_create(&pthread_id, 0, thread_worker, 0 ); if(rtn != 0) { printf("pthread_create ERROR!\\n"); return -1; } for (i=0; i<10000; i++) { pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); critical_section(1, i); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); return 0; } void* thread_worker(void* p) { int i; for (i=0; i<10000; i++) { pthread_mutex_lock(&mutex2); pthread_mutex_lock(&mutex1); critical_section(2, i); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } } void critical_section(int thread_num, int i) { printf("Thread%d:%d\\n", thread_num, i); }
1
#include <pthread.h> pthread_mutex_t count_lock; pthread_cond_t count_nonzero; unsigned count = 0; void * decrement_count(void *arg){ pthread_mutex_lock(&count_lock); printf("decrement_count get count_lock ^-^-%d-^-^\\n", count); while (count == 0){ printf("decrement_count count == 0 ^-^-%d-^-^\\n", count); printf("decrement_count before cond_wait ^-^-%d-^-^\\n", count); pthread_cond_wait( &count_nonzero, &count_lock); printf("decrement_count after cond_wait ^-^-%d-^-^\\n", count); } count = count -1; pthread_mutex_unlock (&count_lock); return 0; } void * increment_count(void *arg){ pthread_mutex_lock(&count_lock); printf("increment_count get count_lock ^-^-%d-^-^\\n", count); if(count == 0){ printf("increment_count before cond_signal ^-^-%d-^-^\\n", count); pthread_cond_signal(&count_nonzero); printf("increment_count after cond_signal ^-^-%d-^-^\\n", count); } count = count + 1; pthread_mutex_unlock(&count_lock); return 0; } int main(void){ pthread_t tid1, tid2; pthread_mutex_init(&count_lock, 0); pthread_cond_init(&count_nonzero, 0); pthread_create(&tid1, 0, decrement_count, 0); sleep(1); pthread_create(&tid2, 0, increment_count, 0); sleep(2); getchar(); pthread_exit(0); return 0; }
0
#include <pthread.h> int map_minerals = 5000; int owned_minerals = 0; int collected_minerals_overall = 0; int soldiers = 0; int workers_count = 0; pthread_t command_centers[200]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* command_center_activity(void* arg) { pthread_mutex_lock(&mutex); if (soldiers < 20) { if (owned_minerals >= 50) { printf("You wanna piece of me, boy?\\n"); sleep(1); soldiers += 1; owned_minerals -= 50; } else { printf("Not enough minerals\\n"); } } pthread_mutex_unlock(&mutex); } void* workers_activity(void* arg) { pthread_mutex_lock(&mutex); int num = (int) arg; printf("SCV %d is mining\\n", num); map_minerals -= 8; owned_minerals += 8; collected_minerals_overall += 8; printf("SCV %d is transporting minerals\\n", num); sleep(2); printf("SCV %d delivered minerals to Command Center 1\\n", num); pthread_create(&command_centers[num - 1], 0, command_center_activity, (void*) (arg)); pthread_mutex_unlock(&mutex); } int main() { pthread_t workers[5]; workers_count += 5; int i = 0; while (soldiers < 20) { for (i = 0; i < 5; i++) pthread_create(&workers[i], 0, workers_activity, (void*) (i + 1)); for (i = 0; i < 5; i++) pthread_join(workers[i], 0); } printf("Map minerals: 5000\\n"); printf("Left minerals: %d\\n", map_minerals); printf("Collected minerals: %d\\n", collected_minerals_overall); }
1
#include <pthread.h> { pthread_t thread; char* name; int id; sem_t* glob_dance_sem; sem_t* glob_eat_sem; int isDancing; int isEating; } customer_t; customer_t customers[12]; int dancing_status; int eating_status; int isCurfew; pthread_mutex_t dance_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t eat_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dance_one = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dance_two = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t eat_one = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t eat_two = PTHREAD_MUTEX_INITIALIZER; int dc_one; int dc_two; int ec_one; int ec_two; pthread_cond_t dance_cv_one = PTHREAD_COND_INITIALIZER; pthread_cond_t dance_cv_two = PTHREAD_COND_INITIALIZER; pthread_cond_t eat_cv_one = PTHREAD_COND_INITIALIZER; pthread_cond_t eat_cv_two = PTHREAD_COND_INITIALIZER; void declareDancing(int custid) { pthread_mutex_lock(&dance_one); if(dc_one == 2) dc_one = 1; else dc_one += 1; while(dc_one != 2 && !isCurfew) pthread_cond_wait(&dance_cv_one, &dance_one); pthread_mutex_unlock(&dance_one); pthread_cond_broadcast(&dance_cv_one); if(isCurfew) return; pthread_mutex_lock(&dance_mutex); int i; int counter = 0; char* friends[2 -1]; for(i = 0; i < 12; i++) { if(customers[i].isDancing && i != custid) { if(counter > 0) printf("Wait? Why are you here %s?\\n", customers[i].name); else friends[counter] = customers[i].name; counter++; } } if(counter == 1) printf("%s is dancing with %s.\\n", customers[custid].name, friends[0]); else printf("Your synchronization implementation is incorrect.\\n"); pthread_mutex_unlock(&dance_mutex); usleep(10); pthread_mutex_lock(&dance_two); if(dc_two == 2) dc_two = 1; else dc_two += 1; while(dc_two != 2 && !isCurfew) pthread_cond_wait(&dance_cv_two, &dance_two); pthread_mutex_unlock(&dance_two); pthread_cond_broadcast(&dance_cv_two); if(isCurfew) return; } void declareEating(int custid) { pthread_mutex_lock(&eat_one); if(ec_one == 3) ec_one = 1; else ec_one += 1; while(ec_one != 3 && !isCurfew) pthread_cond_wait(&eat_cv_one, &eat_one); pthread_mutex_unlock(&eat_one); pthread_cond_broadcast(&eat_cv_one); if(isCurfew) return; pthread_mutex_lock(&eat_mutex); int i; int counter = 0; char* friends[3 -1]; for(i = 0; i < 12; i++) { if(customers[i].isEating && i != custid) { if (counter > 1) printf("Wait? Why are you here %s?\\n", customers[i].name); else friends[counter] = customers[i].name; counter++; } } if(counter == 2) printf("%s is eating with %s and %s.\\n", customers[custid].name, friends[0], friends[1]); else printf("Your synchronization implementation is incorrect.\\n"); pthread_mutex_unlock(&eat_mutex); pthread_mutex_lock(&eat_two); if(ec_two == 3) ec_two = 1; else ec_two += 1; while(ec_two != 3 && !isCurfew) pthread_cond_wait(&eat_cv_two, &eat_two); pthread_mutex_unlock(&eat_two); pthread_cond_broadcast(&eat_cv_two); if(isCurfew) return; usleep(5); } void* fridayNight(void* customer_info) { customer_t* thisCust = (customer_t*)(customer_info); printf("customer name: %s\\n", thisCust->name); while(!isCurfew) { sem_wait(thisCust->glob_dance_sem); pthread_mutex_lock(&dance_mutex); dancing_status++; thisCust->isDancing = 1; pthread_mutex_unlock(&dance_mutex); declareDancing(thisCust->id); pthread_mutex_lock(&dance_mutex); dancing_status--; thisCust->isDancing = 0; pthread_mutex_unlock(&dance_mutex); sem_post(thisCust->glob_dance_sem); sem_wait(thisCust->glob_eat_sem); pthread_mutex_lock(&eat_mutex); eating_status++; thisCust->isEating = 1; pthread_mutex_unlock(&eat_mutex); declareEating(thisCust->id); pthread_mutex_lock(&eat_mutex); eating_status--; thisCust->isEating = 0; pthread_mutex_unlock(&eat_mutex); sem_post(thisCust->glob_eat_sem); usleep(10); } return 0; } int main() { customer_t *currCustomer; int i; int failed; dc_one = dc_two = ec_one = ec_two = 0; sem_t dance_sem; sem_t eat_sem; if(sem_init(&dance_sem, 0, 2)) { printf("dance sem failed!\\n"); exit(1); } if(sem_init(&eat_sem, 0, 3)) { printf("eat sem failed!\\n"); exit(1); } isCurfew = 0; for(i = 0; i < 12; i++) { currCustomer = &(customers[i]); currCustomer->name = malloc(sizeof(char)); currCustomer->id = i; *(currCustomer->name) = (char)(65+i); currCustomer->isDancing = 0; currCustomer->isEating = 0; currCustomer->glob_dance_sem = &dance_sem; currCustomer->glob_eat_sem = &eat_sem; pthread_create(&currCustomer->thread, 0, fridayNight, currCustomer); } sleep(5); isCurfew = 1; printf("time to clean up!\\n"); pthread_cond_broadcast(&dance_cv_one); pthread_cond_broadcast(&dance_cv_two); pthread_cond_broadcast(&eat_cv_one); pthread_cond_broadcast(&eat_cv_two); for(i = 0; i < 12; i++) { currCustomer = &customers[i]; if(pthread_join(currCustomer->thread, 0)) { printf("error joining thread for %s\\n", currCustomer->name); exit(1); } } return 0; }
0
#include <pthread.h> static int global = 0; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t v = PTHREAD_COND_INITIALIZER; void perror_exit(const char *info) { perror(info); exit(1); } void *count_times(void *args) { int i = 1; while(1){ sleep(1); fprintf(stderr,"second: %d\\n",i++); } return ((void *)0); } void *tfn(void *args) { pthread_mutex_lock(&m); while(global != 100) pthread_cond_wait(&v,&m); fprintf(stderr,"t%d: global = %d\\n",(int)args,global); pthread_mutex_unlock(&m); return((void *)0); } int main(int argc,char **argv) { if(argc != 2){ fprintf(stderr,"Usagr:%s thread-number\\n",argv[0]); return -1; } pthread_mutex_init(&m,0); pthread_cond_init(&v,0); pthread_t tid; pthread_create(&tid,0,count_times,0); int i; int thread_nums = atoi(argv[1]); for(i = 0; i< thread_nums; i++){ if(pthread_create(&tid,0,tfn,(void *)i)) perror_exit("pthread_create failed"); } sleep(1); pthread_mutex_lock(&m); global = 100; pthread_cond_broadcast(&v); sleep(3); pthread_mutex_unlock(&m); sleep(2); pthread_exit(0); return 0; }
1
#include <pthread.h> enum {ARRAY_SIZE = 1000,}; const unsigned long int LOOP_ITERATIONS = (1 << 25); pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t b; int global_array[ARRAY_SIZE]; void *reader(void *arg) { int tmp = *(int *)&m; pthread_barrier_wait(&b); while(tmp != 6) tmp = *(int *)&m; return 0; } int main(int argc, char **argv) { int nthr = 1; pthread_t r_id; struct timeval begin; struct timeval end; if (argv[1][0] == 'y') nthr = atoi(argv[2]); pthread_barrier_init(&b, 0, nthr); for (int i = 0; i < nthr - 1; i++) { pthread_create(&r_id, 0, reader, 0); } pthread_barrier_wait(&b); gettimeofday(&(begin), 0); for (int i = 0; i < LOOP_ITERATIONS; i++) { pthread_mutex_lock(&m); global_array[i % ARRAY_SIZE]++; pthread_mutex_unlock(&m); } gettimeofday(&(end), 0); printf("time %lf\\n", (((double)(end.tv_sec) + (double)(end.tv_usec / 1000000.0)) - ((double)(begin.tv_sec) + (double)(begin.tv_usec / 1000000.0)))); pthread_barrier_destroy(&b); return 0; }
0
#include <pthread.h> pthread_mutex_t xLock, yLock; int x, y; void * procA () { int flag = 9, step; while (flag--) { printf ("A: Incrementing x\\n"); pthread_mutex_lock (&xLock); for (step = 1000000; step > 0; step--) x++; pthread_mutex_unlock (&xLock); pthread_mutex_lock (&yLock); printf ("A: Reading y: %d\\n", y); pthread_mutex_unlock (&yLock); } } void * procB () { int flag = 9, step; while (flag--) { pthread_mutex_lock (&xLock); printf ("B: Reading x: %d\\n", x); pthread_mutex_unlock (&xLock); pthread_mutex_lock (&yLock); printf ("B: Incrementing y\\n"); for (step = 1000000; step > 0; step--) y++; pthread_mutex_unlock (&yLock); } } int main () { pthread_t tid[2]; if (pthread_mutex_init (&xLock, 0) != 0) return 1; if (pthread_mutex_init (&yLock, 0) != 0) { pthread_mutex_destroy (&xLock); return 1; } pthread_create ((tid+0), 0, procA, 0); pthread_create ((tid+1), 0, procB, 0); pthread_join (tid[0], 0); pthread_join (tid[1], 0); pthread_mutex_destroy (&xLock); pthread_mutex_destroy (&yLock); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; double target; void* opponent(void *arg) { for(int i = 0; i < 10000; ++i) { pthread_mutex_lock(&mutex); target -= target * 2 + tan(target); pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char **argv) { pthread_t other; target = 5.0; if(pthread_mutex_init(&mutex, 0)) { printf("Unable to initialize a mutex\\n"); return -1; } if(pthread_create(&other, 0, &opponent, 0)) { printf("Unable to spawn thread\\n"); return -1; } for(int i = 0; i < 10000; ++i) { pthread_mutex_lock(&mutex); target += target * 2 + tan(target); pthread_mutex_unlock(&mutex); } if(pthread_join(other, 0)) { printf("Could not join thread\\n"); return -1; } pthread_mutex_destroy(&mutex); printf("Result: %f\\n", target); return 0; }
0
#include <pthread.h> { struct node *next; } node; { node *head; node *tail; pthread_mutex_t headLock; pthread_mutex_t tailLock; } queue; void Queue_Init(struct queue *q); void Queue_Enqueue(struct queue *q); int Queue_Dequeue( struct queue *q); void* Thread_Enqueue(void *q); void* Thread_Dequeue(void *q); int main(){ struct queue MainQueue; Queue_Init(&MainQueue); int i = 0; for(i = 0; i< 10000; i++){ Queue_Enqueue(&MainQueue); } pthread_t enQ; pthread_t deQ; pthread_create(&enQ, 0, Thread_Enqueue, (void*) &MainQueue); pthread_create(&deQ, 0, Thread_Dequeue, (void*) &MainQueue); pthread_join(enQ, 0); pthread_join(deQ, 0); isEmpty(&MainQueue); } void Queue_Init(struct queue *q){ struct node *tmp = malloc(sizeof(node)); tmp->next = 0; q->head = tmp; q->tail = tmp; pthread_mutex_init(&q->headLock, 0); pthread_mutex_init(&q->tailLock, 0); } void isEmpty(struct queue *q){ struct node *tmp = q->head; struct node *newHead = tmp->next; if(newHead == 0){ printf("Queue is Empty"); }else{ printf("Queue is NOT Empty"); } } void Queue_Enqueue(struct queue *q){ struct node *tmp = malloc(sizeof(node)); assert(tmp != 0); tmp->next = 0; pthread_mutex_lock(&q->tailLock); q->tail->next = tmp; q->tail = tmp; pthread_mutex_unlock(&q->tailLock); } int Queue_Dequeue(struct queue *q){ pthread_mutex_lock(&q->headLock); struct node *tmp = q->head; struct node *newHead = tmp->next; if(newHead == 0){ pthread_mutex_unlock(&q->headLock); return -1; } q->head = newHead; pthread_mutex_unlock(&q->headLock); free(tmp); return 0; } void *Thread_Enqueue(void* q){ struct queue *PassedQueue = (struct queue *)q; int i = 0; for(i = 0; i< 1000000; i++){ Queue_Enqueue(PassedQueue); } } void *Thread_Dequeue(void* q){ struct queue *PassedQueue = (struct queue *)q; while(Queue_Dequeue(PassedQueue) == 0); }
1
#include <pthread.h> static const char *sem_prefix = "/AnonSem"; static int is_mutex_inited = 0; static pthread_mutex_t sem_ptr_mutex; static int sem_id = 0; static sem_t *sem_list[16]; int sem_init(sem_t *sem, int pshared, unsigned int value) { assert(sem != 0); pid_t pid; int id; char sem_name[32]; if (is_mutex_inited == 0) { pthread_mutex_init(&sem_ptr_mutex, 0); is_mutex_inited = 1; } pthread_mutex_lock(&sem_ptr_mutex); id = sem_id++; pthread_mutex_unlock(&sem_ptr_mutex); pid = getpid(); snprintf(sem_name, sizeof(sem_name), "%s/%d/%d", sem_prefix, pid, id); sem_unlink(sem_name); sem_t *sem_ptr = sem_open(sem_name, O_CREAT | O_EXCL, pshared, value); if (sem_ptr == 0) { return -1; } sem_list[id] = sem_ptr; *sem = id; return 0; } int sem_destroy(sem_t *sem) { assert(sem != 0); assert(((*sem) >= 0) && ((*sem) < 16)); int id = *sem; sem_t *sem_ptr = sem_list[id]; sem_list[id] = 0; sem_close(sem_ptr); char sem_name[32]; pid_t pid = getpid(); snprintf(sem_name, sizeof(sem_name), "%s/%d/%d", sem_prefix, pid, id); return sem_unlink(sem_name); } int sem_post(sem_t *sem) { assert(sem != 0); assert(((*sem) >= 0) && ((*sem) < 16)); sem_func_ptr post_ptr = (sem_func_ptr)dlsym(RTLD_NEXT, __func__); sem_t *sem_ptr = sem_list[*sem]; return (*post_ptr)(sem_ptr); } int sem_trywait(sem_t * sem) { assert(sem != 0); assert(((*sem) >= 0) && ((*sem) < 16)); sem_func_ptr trywait_ptr = (sem_func_ptr)dlsym(RTLD_NEXT, __func__); sem_t *sem_ptr = sem_list[*sem]; return (*trywait_ptr)(sem_ptr); } int sem_wait(sem_t * sem) { assert(sem != 0); assert(((*sem) >= 0) && ((*sem) < 16)); sem_func_ptr wait_ptr = (sem_func_ptr)dlsym(RTLD_NEXT, __func__); sem_t *sem_ptr = sem_list[*sem]; return (*wait_ptr)(sem_ptr); }
0
#include <pthread.h> static const int max_fd=40; const int pthread_num=30; const int port=8888; const char *ip="127.0.0.1"; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; int server_fd[max_fd],iget=0,iput=0,work_count_end=1,work_count_begin=1,free_count=30; void *work(void *un_use) { int fd; for(;;) { pthread_mutex_lock(&lock); while(iget==iput) pthread_cond_wait(&cond,&lock); printf("work_count_begin is %d,free_count is %d\\n",work_count_begin++,--free_count); fd=server_fd[iget]; server_fd[iget]=-1; iget=(iget+1)%max_fd; pthread_mutex_unlock(&lock); net_echo(fd); printf("work_count_end is %d,free_count is %d\\n",work_count_end++,++free_count); close(fd); } } int main() { int listen_fd; listen_fd=net_listen(ip,port,400); int i; for(i=0;i<max_fd;i++) server_fd[i]=-1; for(i=0;i<pthread_num;i++) { pthread_t tid; pthread_create(&tid,0,work,0); } int ac_count=1; for(;;) { while((iput+1)%max_fd==iget); int ac_fd=accept(listen_fd,0,0); printf("main ac ac_count is %d\\n",ac_count); ac_count++; pthread_mutex_lock(&lock); server_fd[iput]=ac_fd; iput=(iput+1)%max_fd; pthread_cond_signal(&cond); printf("main signal\\n"); pthread_mutex_unlock(&lock); } }
1
#include <pthread.h> int running = 1; int thread1_waiting = 0; pthread_t thread1; pthread_cond_t thread1_cond; int thread2_waiting = 0; pthread_t thread2; pthread_cond_t thread2_cond; void* thread1_func(void *arg){ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; while(running){ usleep(1000000); pthread_mutex_lock(&mutex); if(!thread2_waiting){ thread1_waiting = 1; while(thread1_waiting){ pthread_cond_wait(&thread1_cond, &mutex); } pthread_mutex_unlock(&mutex); }else{ thread2_waiting = 0; pthread_mutex_unlock(&mutex); pthread_cond_signal(&thread2_cond); } } pthread_exit(0); } void* thread2_func(void *arg){ pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; while(running){ usleep(1000000); pthread_mutex_lock(&mutex); if(!thread1_waiting){ thread2_waiting = 1; while(thread2_waiting){ pthread_cond_wait(&thread2_cond, &mutex); } pthread_mutex_unlock(&mutex); }else{ thread1_waiting = 0; pthread_mutex_unlock(&mutex); pthread_cond_signal(&thread1_cond); } } pthread_exit(0); } int main(int argc, char **argv){ printf("creating threads: hit any key to abort\\n\\0"); pthread_create(&thread1, 0, &thread1_func, 0); pthread_create(&thread2, 0, &thread1_func, 0); getchar(); running = 0; return(0); }
0
#include <pthread.h> pthread_mutex_t mutex ; pthread_cond_t avail; pthread_cond_t ready; int data_ready; int data; pthread_t thread; struct stage_tag * next; } stage_t; pthread_mutex_t mutex; stage_t *head; stage_t *tail; int stages; int active; } pipe_t ; int pipe_send(stage_t *stage, int process_data) { int status; printf("thread:%u in send \\n", (int)pthread_self()); sleep(1); status = pthread_mutex_lock(&stage->mutex); if (status != 0) return status ; while (stage->data_ready) { printf("thread:%u in send wait read \\n", (int)pthread_self()); status = pthread_cond_wait(&stage->ready, &stage->mutex); if (status != 0) { pthread_mutex_unlock(&stage->mutex); return status; } } printf("thread:%u in send wait read up \\n", (int)pthread_self()); stage->data = process_data ; stage->data_ready = 1 ; status = pthread_cond_signal(&stage->avail); if (status != 0) { pthread_mutex_unlock(&stage->mutex); return status ; } status = pthread_mutex_unlock(&stage->mutex); return status ; } void * pipe_stage(void *arg) { stage_t *this= (stage_t *)arg; stage_t *next = this->next; PCHECK(pthread_mutex_lock(&this->mutex)); while (1) { while (this->data_ready != 1) { printf("thread:%u send wait avail \\n", (int)pthread_self()); PCHECK(pthread_cond_wait(&this->avail, &this->mutex)); } printf("thread:%u send wait avail up\\n", (int)pthread_self()); sleep(1); pipe_send(next, this->data + 1); this->data_ready = 0; PCHECK(pthread_cond_signal(&this->ready)); } } int pipe_create(pipe_t *pipe, int stages) { int pipe_index; stage_t **link = &pipe->head, *new_stage, *stage; PCHECK(pthread_mutex_init(&pipe->mutex, 0)); pipe->stages = stages; pipe->active = 0; for (pipe_index = 0; pipe_index <= stages; ++pipe_index) { EV_TEST(0, new_stage, (stage_t*)malloc(sizeof(stage_t))); PCHECK(pthread_mutex_init(&new_stage->mutex, 0)); PCHECK(pthread_cond_init(&new_stage->avail, 0)); PCHECK(pthread_cond_init(&new_stage->ready, 0)); new_stage->data_ready = 0; *link = new_stage; link = &new_stage->next; } *link = (stage_t*)0; pipe->tail = new_stage; for (stage = pipe->head; stage->next != 0; stage = stage->next) { PCHECK(pthread_create(&stage->thread, 0, pipe_stage, (void*)stage)); } return 0; } int pipe_start(pipe_t *pipe, int value) { PCHECK(pthread_mutex_lock(&pipe->mutex)); pipe->active++; PCHECK(pthread_mutex_unlock(&pipe->mutex)); pipe_send(pipe->head, value); return 0; } int pipe_result(pipe_t *pipe, int *result) { stage_t *tail = pipe->tail; int empty = 0; printf("thread:%u result\\n", (int)pthread_self()); PCHECK(pthread_mutex_lock(&pipe->mutex)); if (pipe->active <= 0) empty = 1; else pipe->active--; PCHECK(pthread_mutex_unlock(&pipe->mutex)); if (empty) return 0; while (!tail->data_ready) pthread_cond_wait(&tail->avail, &tail->mutex); *result = tail->data; tail->data_ready = 0; pthread_cond_signal(&tail->ready); pthread_mutex_unlock(&tail->mutex); return 1; } int main(int argc, char *argv[]) { pipe_t pipe; int value, result; char line[128]; pipe_create(&pipe, 2); printf("Enter inter value, or '=' for next result\\n"); while (1) { printf("Data> "); E_TEST(0, fgets(line, sizeof(line), stdin)); if (strlen(line) <= 1) continue; if (strlen(line) <= 2 && line[0] == '=') { if (pipe_result(&pipe, &result)) printf("Result is %d\\n", result); else printf("Pipe is empty\\n"); } else { if (sscanf(line, "%d", &value) < 1) fprintf(stderr, "Enter an integer value\\n"); else pipe_start(&pipe, value); } } return 0 ; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void* thr_fn(void *arg) { int err,signo; for(;;) { err = sigwait(&mask,&signo); if(err != 0) err_exit(err,"sigwait error"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexited signal%d\\n",signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask,SIGINT); sigaddset(&mask,SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK,&mask,&oldmask)) != 0) err_exit(err,"SIG_BLOCK error"); pthread_create(&tid,0,thr_fn,0); pthread_mutex_lock(&lock); while(quitflag == 0) pthread_cond_wait(&waitloc,&lock); pthread_mutex_unlock(&lock); quitflag = 0; if(sigprocmask(SIG_SETMASK,&oldmask,0) < 0) err_sys("sig_setmask,error"); exit(0); }
0
#include <pthread.h> int joystickServer( ) { int joy_fd = open( "/dev/input/js0", O_RDONLY ); if ( joy_fd == -1 ) return 1; int num_of_axis, num_of_buttons; ioctl( joy_fd, JSIOCGAXES, &num_of_axis ); ioctl( joy_fd, JSIOCGBUTTONS, &num_of_buttons ); int * axis = ( int * ) calloc( num_of_axis, sizeof( int ) ); char * button = ( char * ) calloc( num_of_buttons, sizeof( char ) ); char * b_edge = ( char * ) calloc( num_of_buttons, sizeof( char ) ); struct js_event js; int note[ 6 ] = { 48 + 4, 48 + 3, 48 + 9, 48 + 2, 48 + 8, 48 + 5 }; int joyTab[ 16 ]; for ( int i = 0; i < 16; i++ ) { joyTab[ i ] = -1; } fcntl( joy_fd, F_SETFL, O_NONBLOCK ); while( !params.exit ) { usleep( 10000 ); read( joy_fd, &js, sizeof( struct js_event ) ); switch ( js.type & ~JS_EVENT_INIT ) { case JS_EVENT_AXIS: axis[ js.number ] = js.value; break; case JS_EVENT_BUTTON: button[ js.number ] = js.value; break; } pthread_mutex_lock( &mutex ); for ( int i = 0; i < 6; i++ ) { if( button[ i ] & ~b_edge[ i ] ) { int id = newNote( semitoneToFreq( note[ i ] ) ); if ( id != -1 ) { joyTab[ i ] = id; setEnergy( id, 1.0 ); b_edge[ i ] = 1; } } else if( ~button[ i ] & b_edge[ i ] ) { if ( joyTab[ i ] != -1 ) { dropNote( joyTab[ i ] ); joyTab[ i ] = -1; b_edge[ i ] = 0; } } } pthread_mutex_unlock( &mutex ); } free( button ); free( axis ); free( b_edge ); close( joy_fd ); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for( i=0; i<(400); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for( i=0; i<(400); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> void *passenger(void* arg); pthread_mutex_t mutex; pthread_cond_t cond; int np, n, C, T, N, headOfArray, count; long long ln; int *array; int *line; struct timeval *back_to_queue; int main(int argc, char** argv){ if(argc<5){ puts("execution error, ./hw2_SRCC n C T N"); exit(0); } struct timeval tvalBefore, tvalAfter; int i, j; count = 0; n = atoi(argv[1]); C = atoi(argv[2]); T = atoi(argv[3]); N = atoi(argv[4]); if(n<C){ puts("n<C"); exit(0); } int *tids; srand(time(0)); back_to_queue = (struct timeval*)malloc(sizeof(struct timeval)*n); array = (int*)malloc(sizeof(int)*n); line = (int*)calloc(0, sizeof(int)*n); tids = (int*)malloc(sizeof(int)*n); for(i=0;i<n;i++) tids[i] = i; pthread_t threads[n]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); np = 0; ln = 0; long int waittime=0, waitcount=0; headOfArray = 0; gettimeofday (&tvalBefore, 0); for(i=0;i<n;i++){ pthread_create(&threads[i], 0, passenger, (void *) &tids[i]); } while(count<N){ while(1){ if(ln - headOfArray >= C){ gettimeofday (&tvalAfter, 0); printf("car departures at %ld millisec. ", (tvalAfter.tv_usec-tvalBefore.tv_usec)/1000+1000*(tvalAfter.tv_sec-tvalBefore.tv_sec)); for(i=headOfArray%n,j=0;j<C;j++,i++){ printf("%d ",array[i%n]); waitcount++; waittime+=(tvalAfter.tv_usec-back_to_queue[array[i%n]].tv_usec)/1000+1000*(tvalAfter.tv_sec-back_to_queue[array[i%n]].tv_sec); } printf("passengers are in the car\\n"); usleep(T*1000); gettimeofday (&tvalAfter, 0); printf("car arrives at %ld millisec. ", (tvalAfter.tv_usec-tvalBefore.tv_usec)/1000+1000*(tvalAfter.tv_sec-tvalBefore.tv_sec)); pthread_mutex_lock(&mutex); for(i=headOfArray%n,j=0;j<C;j++,i++){ printf("%d ",array[i%n]); line[array[i%n]]=0; } printf("passengers get off\\n"); headOfArray+=C; pthread_mutex_unlock(&mutex); break; } else usleep(50); } count++; } printf("average wait time: %ld\\n",waittime/waitcount); return 0; } void *passenger(void* arg){ int id = *(int*) arg; char wonder[30]; char returnline[30]; char temp[30]; while(count<N){ gettimeofday(&back_to_queue[id], 0); pthread_mutex_lock(&mutex); array[ln%n] = id; line[id]=1; np++; ln++; pthread_mutex_unlock(&mutex); while(line[id]==1) usleep(50); printf("%d passenger wanders around the park.\\n",id); usleep((rand())%100000); printf("%d passenger returns for another ride.\\n",id); } }
1
#include <pthread.h> sem_t c_sem; int count; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *producer_thread() { while(1) { printf("\\nIN PRODUCER THREAD:[%u]\\n", pthread_self()); if(0 != pthread_mutex_lock( &mutex1)) { printf("Failed to lock, producer thread:[%u]\\n", pthread_self()); } count++; printf("IN PRODUCER THREAD:[%u] count:%d\\n", pthread_self(), count); if(count == 6) { printf("Signalling consumer\\n"); if(-1 == sem_post(&c_sem)) { printf("Signalling consumer failed\\n"); } } printf("IN PRODUCER THREAD:[%u], waiting on cond variable\\n",pthread_self()); pthread_cond_wait( &condition_var, &mutex1 ); pthread_mutex_unlock( &mutex1); } } void *consumer_thread() { while(1) { printf("IN CONSUMER THREAD, waiting on c_sem\\n"); if(-1 == sem_wait(&c_sem)) { printf("Wait on c_sem failed\\n"); return; } printf("\\nIN CONSUMER THREAD\\n"); pthread_mutex_lock( &mutex1); printf("Reinit count\\n"); count = 0; printf("IN CONSUMER THREAD : Signalling cond variable\\n"); pthread_cond_broadcast( &condition_var ); pthread_mutex_unlock( &mutex1); } } int main() { int ret_val = 0; int i = 0; pthread_t prod_thread[5]; pthread_t cons_thread; if(-1 == sem_init(&c_sem, 0, 0)) { printf("init failed\\n"); ret_val = -1; } for(i = 0; i <= 5; i++) { if(-1 == pthread_create(&prod_thread[i], 0, producer_thread, 0)) { printf("Failed to create producer threads\\n"); ret_val = -1; } } if(-1 == pthread_create(&cons_thread, 0, consumer_thread, 0)) { printf("Failed to create consumer thread\\n"); ret_val = -1; } if(-1 == pthread_join(cons_thread, 0)) { printf("Join failed\\n"); ret_val = -1; } return ret_val; }
0
#include <pthread.h> void philosopher_fn(void*); pthread_mutex_t mutex_arr[5]; int main() { int i=0; pthread_t threads[5]; for(i=0;i<5;i++){ pthread_mutex_init(&mutex_arr[i],0); } i = 0; while(i<5){ if(pthread_create(&threads[i],0,philosopher_fn,(void*)i) != 0){ perror("Error creating threads\\n"); return 1; } printf("Thread %d spawn\\n",i); i++; } for(i=0;i<5;i++){ pthread_join(threads[i],0); } return 0; } void philosopher_fn(void* no){ int i = (int)no; int right,count; right = (i+1)%5; for(count=0;count<5;count++){ printf("Philosopher %d going to think [%d]\\n",i,count); think(); pthread_mutex_lock(&mutex_arr[i]); pthread_mutex_lock(&mutex_arr[right]); printf("Philosopher %d locked chopsticks [%d]\\n",i,count); printf("Philosopher %d going to eat [%d]\\n",i,count); eat(); printf("Philosopher %d going to unlock chopsticks [%d]\\n",i,count); pthread_mutex_unlock(&mutex_arr[right]); pthread_mutex_unlock(&mutex_arr[i]); } } void think(){ sleep(1); } void eat(){ sleep(1); }
1
#include <pthread.h> pthread_mutex_t speaking; pthread_mutex_t asking; pthread_mutex_t room; pthread_cond_t question; pthread_cond_t answer; pthread_barrier_t barrier; int reporters_in_room; int done = 0; int ready = 0; int numReporters; int roomCapacity; int active_id; void *Speaker(){ pthread_mutex_lock(&speaking); while(getDone() < numReporters){ AnswerStart(); AnswerDone(); } } void *Reporter(void* arg){ int id = (int)arg - 1; int questions = (id%4)+2; EnterConferenceRoom(id); for (questions; questions > 0; questions--){ if(reporters_in_room > 1){ usleep(1000); } pthread_mutex_lock(&asking); active_id = id; QuestionStart(id); pthread_cond_wait(&answer, &speaking); QuestionDone(id); pthread_mutex_unlock(&asking); } LeaveConferenceRoom(id); pthread_barrier_wait(&barrier); } void AnswerStart(){ ready = 1; pthread_cond_wait(&question, &speaking); printf("The Speaker starts to answer a question for reporter %d.\\n", active_id); } void AnswerDone(){ printf("The Speaker is done with answer for reporter %d.\\n", active_id); ready = 0; pthread_cond_signal(&answer); } void QuestionStart(int rid){ while (ready == 0){ usleep(10000); } pthread_mutex_lock(&speaking); printf("Reporter %d asks a question.\\n", rid); pthread_cond_signal(&question); } void QuestionDone(int rid){ printf("Reporter %d is satisfied.\\n", rid); pthread_mutex_unlock(&speaking); } void EnterConferenceRoom(int rid){ while (getInRoom() == roomCapacity){ usleep(1000); } pthread_mutex_lock(&room); printf("Reporter %d enters the conference room.\\n", rid); reporters_in_room++; pthread_mutex_unlock(&room); } void LeaveConferenceRoom(int rid){ pthread_mutex_lock(&room); printf("Reporter %d leaves the conference room.\\n", rid); reporters_in_room--; done++; pthread_mutex_unlock(&room); } int getDone(){ pthread_mutex_lock(&room); int d = done; pthread_mutex_unlock(&room); return d; } int getInRoom(){ pthread_mutex_lock(&room); int n = reporters_in_room; pthread_mutex_unlock(&room); return n; } int main (int argc, char *argv[]){ if (argc != 3){ fprintf(stderr, "usage: a.out <integer value> <integer value>\\n"); return -1; } numReporters = atoi(argv[1]); roomCapacity = atoi(argv[2]); pthread_t threads[numReporters + 1]; pthread_barrier_init(&barrier, 0, numReporters+1); pthread_create(&threads[0], 0, Speaker, 0); int i=1; for (i; i < numReporters+1; i++){ int *arg = malloc(sizeof(*arg)); if (arg == 0){ fprintf(stderr, "Unable to allocate memory.\\n"); exit(1); } *arg = i; pthread_create(&threads[i], 0, Reporter, (void *) i); } pthread_barrier_wait(&barrier); return 0; }
0
#include <pthread.h> pthread_mutex_t m; pthread_mutex_t trans; int money = 1000; int transactions = 0; void* deposit(void* arg){ int taskid; taskid = (int) arg; pthread_mutex_lock(&m); money -= 100; printf("100 withdrawn from %d banker\\n", taskid); pthread_mutex_unlock(&m); pthread_mutex_lock(&trans); transactions ++; pthread_mutex_unlock(&trans); return 0; } void* withdraw(void* arg){ int taskid = (int) arg; pthread_mutex_lock(&m); money += 100; printf("100 deposited from %d banker\\n", taskid); pthread_mutex_unlock(&m); pthread_mutex_lock(&trans); transactions ++; pthread_mutex_unlock(&trans); return 0; } int main(){ if ( pthread_mutex_init (&m, 0) != 0) { perror("pthread_mutex_init"); return 1; } if ( pthread_mutex_init (&trans, 0) != 0) { perror("pthread_mutex_init"); return 1; } pthread_t banker[2]; while(transactions < 20){ if(pthread_create(&banker[0], 0, deposit, 0) != 0){ printf("Error while processing pthread"); return 1; } if(pthread_create(&banker[1], 0, withdraw, 1) != 0){ perror("pthread_create"); return 1; } } if(pthread_join(banker[0], 0) != 0){ perror("pthread_join"); return 1; } if(pthread_join(banker[1], 0) != 0){ perror("pthread_join"); return 1; } printf("current money is %d\\n", money); pthread_mutex_destroy(&m); pthread_mutex_destroy(&trans); return 0; }
1
#include <pthread.h> { int nb_ingredient1; int nb_ingredient2; int nb_ingredient3; int nb_ingredient4; pthread_t thread_epicier; pthread_t thread_cuisinieres [6]; pthread_mutex_t mutex_epicier; pthread_cond_t condition_epicier; pthread_cond_t condition_cuisinieres; } struct_commun; static struct_commun epicier = { .nb_ingredient1 = 1, .nb_ingredient2 = 1, .nb_ingredient3 = 0, .nb_ingredient4 = 0, .mutex_epicier = PTHREAD_MUTEX_INITIALIZER, .condition_epicier = PTHREAD_COND_INITIALIZER, .condition_cuisinieres = PTHREAD_COND_INITIALIZER, }; static int get_random (int max){ double val; val = (double) max * rand (); val = val / (32767 + 1.0); return ((int) val); } static void * fn_epicier (void * p_data){ while (1){ pthread_mutex_lock (& epicier.mutex_epicier); pthread_cond_wait (& epicier.condition_epicier, & epicier.mutex_epicier); int hasard_ing1 = get_random (4) + 1; switch(hasard_ing1){ case 1: epicier.nb_ingredient1++; break; case 2: epicier.nb_ingredient2++; break; case 3: epicier.nb_ingredient3++; break; case 4: epicier.nb_ingredient4++; break; } int hasard_ing2 = get_random (4) + 1; while(hasard_ing1==hasard_ing2) hasard_ing2 = get_random (4) + 1; switch(hasard_ing2){ case 1: epicier.nb_ingredient1++; break; case 2: epicier.nb_ingredient2++; break; case 3: epicier.nb_ingredient3++; break; case 4: epicier.nb_ingredient4++; break; } printf ("Remplissage du panier de l'épicier avec les ingredients %d et %d.\\n", hasard_ing1, hasard_ing2); pthread_cond_signal (& epicier.condition_cuisinieres); pthread_mutex_unlock (& epicier.mutex_epicier); } return 0; } static void * fn_cuisiniere (void * p_data){ int numero = (int) p_data; int nb_ingredient1 = 0; int nb_ingredient2 = 0; int nb_ingredient3 = 0; int nb_ingredient4 = 0; switch(numero){ case 0: nb_ingredient1 = 1000; nb_ingredient2 = 1000; break; case 1: nb_ingredient1 = 1000; nb_ingredient3 = 1000; break; case 2: nb_ingredient1 = 1000; nb_ingredient4 = 1000; break; case 3: nb_ingredient2 = 1000; nb_ingredient3 = 1000; break; case 4: nb_ingredient2 = 1000; nb_ingredient4 = 1000; break; case 5: nb_ingredient3 = 1000; nb_ingredient4 = 1000; break; } while (1){ sleep ((get_random (4) + 1)); pthread_mutex_lock (& epicier.mutex_epicier); printf ("Cuisinière %d vérifie ses ingredients.\\n", numero+1); if (epicier.nb_ingredient1+nb_ingredient1 > 0 && epicier.nb_ingredient2+nb_ingredient2 > 0 && epicier.nb_ingredient3+nb_ingredient3 > 0 && epicier.nb_ingredient4+nb_ingredient4 > 0){ epicier.nb_ingredient1 = 0; epicier.nb_ingredient2 = 0; epicier.nb_ingredient3 = 0; epicier.nb_ingredient4 = 0; printf ("Cuisinière %d utilise les ingredients de l'épicier pour faire un gateau !\\n", numero+1); printf ("Le gateau est prêt !\\n"); pthread_cond_signal (& epicier.condition_epicier); pthread_cond_wait (& epicier.condition_cuisinieres, & epicier.mutex_epicier); } pthread_mutex_unlock (& epicier.mutex_epicier); } return 0; } int main (void) { int i = 0; int ret = 0; printf ("Creation du thread de lépicier !\\n"); ret = pthread_create (& epicier.thread_epicier, 0, fn_epicier, 0); if (ret){ fprintf (stderr, "%s", strerror (ret)); } printf ("Creation des 6 threads des cuisinières!\\n"); for (i = 0; i < 6; i++){ ret = pthread_create (& epicier.thread_cuisinieres [i], 0, fn_cuisiniere, (void *) i); if (ret){ fprintf (stderr, "%s", strerror (ret)); } } pthread_join (epicier.thread_epicier, 0); return 0; }
0
#include <pthread.h> void *print(void *m); struct data { pthread_mutex_t lock1; }; int main () { int rt; pthread_t tid; pthread_attr_t attr; struct data d; struct data *dPtr = &d; rt = pthread_mutex_init(&(d.lock1), 0); rt = pthread_mutex_lock(&(d.lock1)); rt = pthread_create(&tid, 0, print, dPtr); printf("pthread create code: %d\\n", rt); printf("Parent: I'm the first\\n"); pthread_mutex_unlock(&(d.lock1)); sleep(3); pthread_mutex_lock(&(d.lock1)); printf("Main: User has pressed enter\\n"); pthread_mutex_unlock(&(d.lock1)); pthread_join(tid, 0); pthread_exit(0); return 0; } void *print(void *m) { int rt; struct data *dataPtr = m; rt = pthread_mutex_lock(&dataPtr->lock1); printf("Child: I'm the second\\n"); rt = pthread_mutex_unlock(&dataPtr->lock1); rt = pthread_mutex_lock(&dataPtr->lock1); printf("Child: Received main signal that user has pressed enter\\n"); printf("Child: Child thread exiting...\\n"); rt = pthread_mutex_unlock(&dataPtr->lock1); sleep(3); return 0; }
1
#include <pthread.h> struct quick_exit_handler { struct quick_exit_handler *next; void (*cleanup)(void); }; static struct quick_exit_handler *pool_page; static struct quick_exit_handler *pool; static size_t pool_size; static pthread_mutex_t atexit_mutex = PTHREAD_MUTEX_INITIALIZER; static struct quick_exit_handler *handlers; int at_quick_exit(void (*func)(void)) { size_t page_size = getpagesize(); struct quick_exit_handler *h; pthread_mutex_lock(&atexit_mutex); if (pool_size < sizeof(*h)) { void *ptr = mmap(0, page_size, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_PRIVATE, -1, 0); if (ptr == MAP_FAILED) { pthread_mutex_unlock(&atexit_mutex); return (1); } prctl(PR_SET_VMA, PR_SET_VMA_ANON_NAME, ptr, page_size, "at_quick_exit handlers"); pool_page = pool = ptr; pool_size = page_size; } else { if (mprotect(pool_page, page_size, PROT_READ|PROT_WRITE)) { pthread_mutex_unlock(&atexit_mutex); return (1); } } h = pool++; pool_size -= sizeof(*h); h->cleanup = func; h->next = handlers; handlers = h; mprotect(pool_page, page_size, PROT_READ); pthread_mutex_unlock(&atexit_mutex); return (0); } void quick_exit(int status) { struct quick_exit_handler *h; for (h = handlers; 0 != h; h = h->next) h->cleanup(); _Exit(status); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cc, cp; int n = 0, queue[8], head = 0, tail = 0; volatile int to_consume = 10;; volatile int to_produce = 10;; void * producer(void *ptr) { pthread_mutex_lock(&mutex); while(to_produce) { if(n == 8) pthread_cond_wait(&cp, &mutex); queue[tail] = rand(); printf("Produced %i\\n", queue[tail]); tail = (tail+1) %8; n++; to_produce--; pthread_cond_signal(&cc); } pthread_mutex_unlock(&mutex); } void * consumer(void *ptr) { pthread_mutex_lock(&mutex); while(to_consume) { if(n == 0) pthread_cond_wait(&cc, &mutex); printf("Consuming %i\\n", queue[head]); head = (head+1) %8; n--; to_consume--; pthread_cond_signal(&cp); } pthread_mutex_unlock(&mutex); } int main() { int N1, N2, i; pthread_t consumert[16], producert[16]; printf("Enter Number of producers: "); scanf("%i", &N1); printf("Enter Number of consumers: "); scanf("%i", &N2); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cc, 0); pthread_cond_init(&cp, 0); for (i = 0; i < N1; ++i) pthread_create(&producert[i], 0, &producer, 0); for (i = 0; i < N2; ++i) pthread_create(&consumert[i], 0, &consumer, 0); for (i = 0; i < N1; ++i) pthread_join(producert[i], 0); for (i = 0; i < N2; ++i) pthread_join(consumert[i], 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cc); pthread_cond_destroy(&cp); return 0; }
1
#include <pthread.h> int get_request(struct jtag_debug_data *d, struct dbg_request *req) { ssize_t br; int rc = -EAGAIN; pthread_mutex_lock(&d->lock); if (d->client_fd < 0) goto out; if (!d->more_data) goto out; br = read(d->client_fd, req, sizeof(*req)); if (br < 0 && errno == EAGAIN) { d->more_data = 0; } else if (br != sizeof(*req)) { d->more_data = 0; rc = -EIO; } else { rc = 0; } out: pthread_mutex_unlock(&d->lock); return rc; } int send_response(struct jtag_debug_data *d, const struct dbg_response *resp) { ssize_t bs; struct iovec iov = { .iov_base = (void *)resp, .iov_len = sizeof(*resp) }; bs = writev(d->client_fd, &iov, 1); if (bs < 0 && errno == EAGAIN) return -EAGAIN; else if (bs != sizeof(*resp)) return -EIO; return 0; } static void enable_reuseaddr(int fd) { int val = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val))) err(1, "failed to enable SO_REUSEADDR"); } static int spawn_server(void) { struct addrinfo *result, *rp, hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM, .ai_flags = AI_PASSIVE, }; int s, fd; s = getaddrinfo(0, "36000", &hints, &result); if (s) err(1, "getaddrinfo failed"); for (rp = result; rp; rp = rp->ai_next) { fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (fd < 0) continue; enable_reuseaddr(fd); if (!bind(fd, rp->ai_addr, rp->ai_addrlen)) break; close(fd); } if (!rp) err(1, "failed to bind server"); freeaddrinfo(result); if (listen(fd, 1)) err(1, "failed to listen on socket"); return fd; } static int establish_connection(struct jtag_debug_data *data) { struct epoll_event event = { .events = EPOLLIN | EPOLLRDHUP | EPOLLET, .data.ptr = data, }; int client = accept4(data->sock_fd, 0, 0, SOCK_NONBLOCK); if (client < 0) return -EAGAIN; if (epoll_ctl(data->epoll_fd, EPOLL_CTL_ADD, client, &event)) { warn("failed to add client to epoll (%d)", client); close(client); return -EAGAIN; } pthread_mutex_lock(&data->lock); data->client_fd = client; pthread_mutex_unlock(&data->lock); return 0; } static void close_connection(struct jtag_debug_data *data) { epoll_ctl(data->epoll_fd, EPOLL_CTL_DEL, data->client_fd, 0); pthread_mutex_lock(&data->lock); shutdown(data->client_fd, SHUT_RDWR); close(data->client_fd); data->client_fd = -1; pthread_mutex_unlock(&data->lock); } static void *server_thread(void *d) { struct jtag_debug_data *data = d; for (;;) { if (establish_connection(d)) continue; for (;;) { struct epoll_event revent; int nevents; nevents = epoll_wait(data->epoll_fd, &revent, 1, -1); if (nevents < 0) err(1, "epoll_wait() failed"); if (nevents) { if (revent.events & (EPOLLRDHUP | EPOLLHUP)) break; if (revent.events & EPOLLIN) __sync_val_compare_and_swap(&data->pending, 0, 1); } } close_connection(data); } return 0; } struct jtag_debug_data *start_server(void) { pthread_t thread; struct jtag_debug_data *data; data = calloc(1, sizeof(*data)); if (!data) err(1, "failed to allocate data"); data->sock_fd = spawn_server(); data->epoll_fd = epoll_create(1); data->client_fd = -1; if (data->epoll_fd < 0) err(1, "failed to create epoll fd"); pthread_mutex_init(&data->lock, 0); if (pthread_create(&thread, 0, server_thread, data)) err(1, "failed to spawn server thread"); return data; } void notify_runner(void) { int fd; char *fifo_name = getenv("SIM_NOTIFY_FIFO"); if (!fifo_name) return; fd = open(fifo_name, O_WRONLY); if (fd < 0) err(1, "failed to open notifcation fifo"); if (write(fd, "O", 1) != 1) err(1, "failed to write notification byte"); close(fd); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t mutex2; void *func(void *arg) { while (1) { pthread_mutex_lock(&mutex); int i; for (i = 1; i <= 5; i++) { printf("Thread 1 - %d\\n", i); } sleep(1); pthread_mutex_unlock(&mutex2); } return 0; } void *func2(void *arg) { while (1) { pthread_mutex_lock(&mutex2); printf("Thread 2 finished\\n"); sleep(1); pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char *argv[]) { int i; pthread_t thr[2]; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutex2, 0); pthread_create(&thr[0], 0, func, 0); pthread_create(&thr[1], 0, func2, 0); pthread_mutex_lock(&mutex2); for (i = 0 ; i < 2 ; i++) { pthread_join(thr[i] , 0) ; } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex2); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; int waiting_students; int students_finished; void *student(void *args) { int index = (int) args; int seed = (index + 1) * 3 * 4 * 2 * 2; int help_count = 0; while (help_count < 2) { int rand_wait_time = (rand_r(&seed) % 3) + 1; printf("\\tStudent %d programming for %d seconds\\n", index, rand_wait_time); sleep(rand_wait_time); pthread_mutex_lock(&mutex_lock); if (waiting_students < 2) { waiting_students++; pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sem_wait(&ta_sem); printf("Student %d receiving help\\n", index); help_count++; } else { pthread_mutex_unlock(&mutex_lock); printf("\\t\\t\\tStudent %d will try later\\n", index); } } students_finished++; pthread_exit(0); } void *ta(void *args) { int seed = 5 * 3 * 4 * 2 * 2; while (1) { sem_wait(&students_sem); pthread_mutex_lock(&mutex_lock); waiting_students--; int rand_wait_time = (rand_r(&seed) % 3) + 1; pthread_mutex_unlock(&mutex_lock); sem_post(&ta_sem); sleep(rand_wait_time); } } int main() { printf("CS149 SleepingTA from Stanley Plagata\\n"); pthread_t students_tid[4]; pthread_t ta_tid; pthread_mutex_init(&mutex_lock, 0); sem_init(&ta_sem, 0, 0); sem_init(&students_sem, 0, 0); pthread_create(&ta_tid, 0, ta, 0); for (int i = 0; i < 4; i++) pthread_create(&students_tid[i], 0, student, (void *) i); for (int i = 0; i < 4; i++) pthread_join(students_tid[i], 0); while (1) { if (students_finished == 4) { pthread_cancel(ta_tid); break; } } pthread_mutex_destroy(&mutex_lock); sem_destroy(&students_sem); sem_destroy(&ta_sem); }
0
#include <pthread.h> int count = 0; int in = 0; int out = 0; int buffer [20]; pthread_mutex_t mutex; pthread_t tid; pthread_cond_t full; pthread_cond_t empty; void insert(int item){ pthread_mutex_lock(&mutex); while (count == 20){ pthread_cond_wait(&full, &mutex); } buffer[in] = item; in = (in + 1) % 20; count++; if(count == 1){ pthread_cond_signal(&empty); } pthread_mutex_unlock(&mutex); } int remove_item(){ int item; pthread_mutex_lock(&mutex); while (count == 0){ pthread_cond_wait(&empty, &mutex); } item = buffer[out]; out = (out + 1) % 20; count--; if(count == 20 - 1){ pthread_cond_signal(&full); } pthread_mutex_unlock(&mutex); return item; } void * producer(void * param){ int item; while(1){ item = rand() % 20 ; insert(item); printf("inserted: %d\\n", item); } } void * consumer(void * param){ int item; while(1){ item = remove_item(); printf("removed: %d\\n", item); } } int main(int argc, char * argv[]) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&full,0); pthread_cond_init(&empty,0); int producers = atoi(argv[1]); int consumers = atoi(argv[2]); int i; for (i = 0; i < producers; i++) pthread_create(&tid, 0, producer,0); for (i = 0; i < consumers; i++) pthread_create(&tid, 0, consumer, 0); pthread_join(tid,0); }
1
#include <pthread.h> pthread_barrier_t br; pthread_cond_t cv; pthread_mutex_t lock; bool n, exiting; FILE *f; int count; void * tf (void *dummy) { bool loop = 1; pthread_setschedparam_np(0, SCHED_FIFO, 0, 0xF, PTHREAD_HARD_REAL_TIME); pthread_barrier_wait(&br); while (loop) { pthread_mutex_lock (&lock); while (n && !exiting) pthread_cond_wait (&cv, &lock); n = 1; pthread_mutex_unlock (&lock); fputs (".", f); pthread_mutex_lock (&lock); n = 0; if (exiting) loop = 0; pthread_mutex_unlock (&lock); pthread_cond_broadcast (&cv); } return 0; } int do_test (void) { f = fopen ("/dev/null", "w"); if (f == 0) { printf ("couldn't open /dev/null, %m\\n"); return 1; } count = sysconf (_SC_NPROCESSORS_ONLN); if (count <= 0) count = 1; count *= 4; pthread_barrier_init(&br, 0, count); pthread_t th[count]; int i, ret; for (i = 0; i < count; ++i) if ((ret = pthread_create (&th[i], 0, tf, 0)) != 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); fclose (f); 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> int thread_count; int n; int total = 0; pthread_mutex_t mutex; void Usage(char prog_name[]); void* Lock_and_unlock(void* rank); int main(int argc, char* argv[]) { pthread_t* thread_handles; long thread; double start, finish; if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); n = strtol(argv[2], 0, 10); thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Lock_and_unlock, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); GET_TIME(finish); printf("Total number of times mutex was locked and unlocked: %d\\n", total); printf("Elapsed time = %e seconds\\n", finish-start); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void Usage(char prog_name[]) { fprintf(stderr, "usage: %s <thread_count> <n>\\n", prog_name); fprintf(stderr, " n: number of times mutex is locked and "); fprintf(stderr, "unlocked by each thread\\n"); exit(0); } void* Lock_and_unlock(void* rank) { int i; for (i = 0; i < n; i++) { pthread_mutex_lock(&mutex); total++; pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> enum { STATE_R=1, STATE_W, STATE_Ex, STATE_T }; struct rel_fsm_st { int state; int sfd; int dfd; char buf[1024]; int len; int pos; int64_t count; char *errstr; }; struct rel_job_st { int job_state; int fd1,fd2; struct rel_fsm_st fsm12,fsm21; int fd1_save,fd2_save; pthread_mutex_t mut_job_state; pthread_cond_t cond_job_state; }; static struct rel_job_st *rel_job[REL_JOBMAX]; static pthread_mutex_t mut_rel_job = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t init_once = PTHREAD_ONCE_INIT; static void fsm_driver(struct rel_fsm_st *fsm) { int ret; switch(fsm->state) { case STATE_R: fsm->len = read(fsm->sfd,fsm->buf,1024); if(fsm->len == 0) fsm->state = STATE_T; else if(fsm->len < 0) { if(errno == EAGAIN) fsm->state = STATE_R; else { fsm->errstr = "read()"; fsm->state = STATE_Ex; } } else { fsm->pos = 0; fsm->state = STATE_W; } break; case STATE_W: ret = write(fsm->dfd,fsm->buf+fsm->pos,fsm->len); if(ret < 0) { if(errno == EAGAIN) fsm->state = STATE_W; else { fsm->errstr = "write()"; fsm->state = STATE_Ex; } } else { fsm->pos += ret; fsm->len -= ret; fsm->count += ret; if(fsm->len == 0) fsm->state = STATE_R; else fsm->state = STATE_W; } break; case STATE_Ex: perror(fsm->errstr); fsm->state = STATE_T; break; case STATE_T: break; default: abort(); } } static void *thr_relayer(void *p) { int i; while(1) { pthread_mutex_lock(&mut_rel_job); for(i = 0 ; i < REL_JOBMAX; i++) { if(rel_job[i] != 0 && rel_job[i]->job_state == STATE_RUNNING) { fsm_driver(&rel_job[i]->fsm12); fsm_driver(&rel_job[i]->fsm21); if(rel_job[i]->fsm12.state == STATE_T && rel_job[i]->fsm21.state == STATE_T) rel_job[i]->job_state = STATE_OVER; } } pthread_mutex_unlock(&mut_rel_job); } } static void module_load(void) { pthread_t tid; int err; err = pthread_create(&tid,0,thr_relayer,0); if(err) { fprintf(stderr,"pthread_create():%s\\n",strerror(err)); exit(1); } } static int get_free_pos_unlocked() { int i; for(i = 0 ; i < REL_JOBMAX; i++) { if(rel_job[i] == 0) return i; } return -1; } int rel_addjob(int fd1,int fd2) { struct rel_job_st *me; int pos; pthread_once(&init_once,module_load); if(fd1 < 0 || fd2 < 0) return -EINVAL; me = malloc(sizeof(*me)); if(me == 0) return -ENOMEM; me->fd1 = fd1; me->fd2 = fd2; me->job_state = STATE_RUNNING; me->fd1_save = fcntl(me->fd1,F_GETFL); fcntl(me->fd1,F_SETFL,me->fd1_save|O_NONBLOCK); me->fd2_save = fcntl(me->fd2,F_GETFL); fcntl(me->fd2,F_SETFL,me->fd2_save|O_NONBLOCK); me->fsm12.sfd = me->fd1; me->fsm12.dfd = me->fd2; me->fsm12.state = STATE_R; me->fsm12.count = 0; me->fsm21.sfd = me->fd2; me->fsm21.dfd = me->fd1; me->fsm21.state = STATE_R; me->fsm21.count = 0; pthread_mutex_init(&me->mut_job_state,0); pthread_cond_init(&me->cond_job_state,0); pthread_mutex_lock(&mut_rel_job); pos = get_free_pos_unlocked(); if(pos < 0) { pthread_mutex_unlock(&mut_rel_job); free(me); return -ENOSPC; } rel_job[pos] = me; pthread_mutex_unlock(&mut_rel_job); return pos; }
0
#include <pthread.h> const char *names[5] = { "Aleksander", "Marius", "Ingvald", "Gustav", "Martin" }; pthread_mutex_t forks[5]; const char *topic[5] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; __builtin_va_start((ap)); pthread_mutex_lock(&screen); printf("\\033[%d;%dH", y + 1, x), vprintf(fmt, ap); printf("\\033[%d;%dH", 5 + 1, 1), fflush(stdout); pthread_mutex_unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % 5; print(id, 12, "\\033[K"); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { pthread_mutex_lock(forks + f[i]); if (!i) print(id, 12, "\\033[K"); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { print(id, 12, "\\033[K"); sprintf(buf, "..oO (%s)", topic[t = rand() % 5]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[5]; pthread_t tid[5]; for (i = 0; i < 5; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < 5; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
1
#include <pthread.h> struct thread_data { int t_index; }; int global_count = 0; pthread_t thread_id[5]; pthread_mutex_t mutex1; void *thread_start(void *param) { struct thread_data *t_param = (struct thread_data *) param; int tid = (*t_param).t_index; pthread_mutex_lock(&mutex1); global_count++; pthread_mutex_unlock(&mutex1); printf("Thread %ld finished updating\\n", thread_id[tid]); pthread_exit(0); } int main() { int no_of_threads, i, id; struct thread_data param[5]; pthread_mutex_init(&mutex1, 0); for(i=0; i<5; i++) { param[i].t_index = i; pthread_create(&thread_id[i], 0, thread_start, (void *) &param[i]); } for(i=0; i<5; i++) { pthread_join(thread_id[i], 0); } pthread_mutex_lock(&mutex1); printf("Final Count is %d\\n", global_count); pthread_mutex_unlock(&mutex1); pthread_mutex_destroy(&mutex1); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_t thr1, thr2, thr3; pthread_attr_t attr1, attr2, attr3; void * fonction_2(void * unused) { int i, j; fprintf(stderr, " T2 demarre\\n"); fprintf(stderr, " T2 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T2 se termine\\n"); return 0; } void * fonction_3(void * unused) { int i, j; fprintf(stderr, " T3 demarre\\n"); fprintf(stderr, " T3 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, " T3 tient le mutex\\n"); fprintf(stderr, " T3 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T3 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, " T3 se termine\\n"); return 0; } void * fonction_1(void *unused) { fprintf(stderr, "T1 demarre\\n"); fprintf(stderr, "T1 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, "T1 tient le mutex\\n"); fprintf(stderr, "reveil de T3\\n"); pthread_create(& thr3, &attr3, fonction_3, 0); fprintf(stderr, "reveil de T2\\n"); pthread_create(& thr2, &attr2, fonction_2, 0); fprintf(stderr, "T1 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, "T1 se termine\\n"); return 0; } int main(int argc, char * argv []) { struct sched_param param; pthread_mutex_init(& mutex, 0); pthread_attr_init(& attr1); pthread_attr_init(& attr2); pthread_attr_init(& attr3); pthread_attr_setschedpolicy(& attr1, SCHED_FIFO); pthread_attr_setschedpolicy(& attr2, SCHED_FIFO); pthread_attr_setschedpolicy(& attr3, SCHED_FIFO); param.sched_priority = 10; pthread_attr_setschedparam(& attr1, & param); param.sched_priority = 20; pthread_attr_setschedparam(& attr2, & param); param.sched_priority = 30; pthread_attr_setschedparam(& attr3, & param); pthread_attr_setinheritsched(& attr1, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr2, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr3, PTHREAD_EXPLICIT_SCHED); if ((errno = pthread_create(& thr1, & attr1, fonction_1, 0)) != 0) { perror("pthread_create"); exit(1); } pthread_join(thr1, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t forks[5]; void eat(void *temp){ int *me; me = temp; printf("Philo %i initializing\\n\\r", *me); int left_fork = *me; int right_fork = *me+1; if(*me == 4) { right_fork = 0; } printf("Philo %i have left fork: %i, right fork: %i \\n\\r", *me, left_fork, right_fork); while(1) { pthread_mutex_lock(&forks[left_fork]); printf("Philo %i picked up left fork %i\\n\\r",*me,left_fork); pthread_mutex_lock(&forks[right_fork]); printf("Philo %i picked up right fork %i\\n\\r",*me,right_fork); pthread_mutex_unlock(&forks[left_fork]); printf("Philo %i dropped up left fork %i\\n\\r",*me,left_fork); pthread_mutex_unlock(&forks[right_fork]); printf("Philo %i dropped up right fork %i\\n\\r",*me,right_fork); } } int main(void){ pthread_t philo[5]; int args[5] = {0,1,2,3,4}; int i = 0; for(i = 0; i<5; i++) { printf("Init fork %i\\n\\r", i); pthread_mutex_init(&forks[i], 0); } for(i = 0; i<5; i++) { printf("Init philo %i\\n\\r", i); pthread_create(&philo[i], 0, eat, &args[i]); } i = 4; int j = 0; for(j = 0; j<5; j++) { pthread_join(philo[0], 0); } return 1; }
0
#include <pthread.h> pthread_mutex_t thread_sum ; static size_t limit = 4; size_t n_thread = 1; static double sec(void) { struct timeval t; gettimeofday(&t,0); return t.tv_sec + (t.tv_usec/1000000.0); } int cmp_double(double a, double b){ int result = a < b ? -1 : a == b ? 0 : 1; return result; } static int cmp(const void* ap, const void* bp) { double a; double b; a = * (const double*) ap; b = * (const double*) bp; int result = cmp_double(a,b); return cmp_double(a,b); } void* base; size_t n; size_t s; compare cmp_func; }arg_struct; void print(double* a, size_t size) { printf("-----------------\\n"); size_t i; for(i = 0; i < size; i++){ printf("%G\\n",a[i]); } printf("---------------------\\n"); } void swap(double* left, double* right) { double temp = *left; *left = *right; *right = temp; } size_t sample_pivot(double* base, size_t size){ if(size > 200){ qsort(base,200,sizeof base[0],cmp); return 100; } return 0; } int partition (double* base, size_t size) { size_t i; double pivot; size_t j; i = 0; if(size > 1){ swap(&base[size-1],&base[sample_pivot(base,size)]); pivot = base[size-1]; for (j = 0; j < size-1; ++j){ if (base[j] <= pivot) { swap(&base[i],&base[j]); i += 1; } } swap(&base[i],&base[size-1]); } return i; } void* par_sort( void* args ) { arg_struct arg1 = *(arg_struct*) args; void* base = arg1.base; size_t n = arg1.n; size_t s = arg1.s; compare cmp_func = arg1.cmp_func; int split = 0; pthread_mutex_lock (&thread_sum); if(n_thread < limit){ split = 1; n_thread+=1; } pthread_mutex_unlock (&thread_sum); if(split && n > 5){ pthread_t thread; size_t middle = partition(base,n); if(middle == 0){ arg_struct arg0 = { ((double*) base) + 1, n-1, s, cmp_func}; par_sort(&arg0); return 0; } printf("middle index is %zu of %zu ,percentage %1.2f\\n", middle,n,middle*1.0 /n); arg_struct arg0 = { base, middle, s, cmp_func}; arg_struct arg1 = { ((double*) base) + middle + 1 , n - middle - 1 , s, cmp_func }; if( pthread_create( &thread, 0, par_sort,&arg1 ) ) { fprintf(stderr,"Error creating thread\\n"); } par_sort(&arg0); if( pthread_join(thread,0) ){ fprintf(stderr,"Error joining thread\\n"); } }else{ printf("i sort this %zu\\n",n); qsort(base,n,s,cmp_func); } return 0; } int main(int ac, char** av) { int n = 20000; int i; double* a; double* b; double start, end; if (ac > 1) sscanf(av[1], "%d", &n); srand(getpid()); a = malloc(n * sizeof a[0]); b = malloc(n * sizeof a[0]); for (i = 0; i < n; i++){ a[i] = rand(); b[i] = a[i]; } pthread_mutex_init(&thread_sum, 0); arg_struct arg = {a,n,sizeof a[0],cmp}; start = sec(); par_sort(&arg); printf("par: %1.5f s\\n", (sec() - start) ); start = sec(); qsort(b, n, sizeof a[0] , cmp); printf("seq: %1.5f s\\n", (sec() - start) ); for(i = 0; i < n ; i++){ if(a[i] != b[i]){ printf("%d \\n %1.2f ",i, a[i]); printf("%1.2f \\n",b[i]); } } free(a); pthread_mutex_destroy(&thread_sum); pthread_exit(0); free(b); return 0; }
1
#include <pthread.h> struct mt { int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; }; int main(void) { int i; struct mt *mm; pid_t pid; mm = mmap(0, sizeof(*mm), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0); memset(mm, 0, sizeof(*mm)); pthread_mutexattr_init(&mm->mutexattr); pthread_mutexattr_setpshared(&mm->mutexattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mm->mutex, &mm->mutexattr); pid = fork(); if (pid == 0) { for (i = 0; i < 10; i++) { pthread_mutex_lock(&mm->mutex); (mm->num)++; pthread_mutex_unlock(&mm->mutex); printf("-child----------num++ %d\\n", mm->num); } } else if (pid > 0) { for ( i = 0; i < 10; i++) { pthread_mutex_lock(&mm->mutex); mm->num += 2; pthread_mutex_unlock(&mm->mutex); printf("-------parent---num+=2 %d\\n", mm->num); } wait(0); } pthread_mutexattr_destroy(&mm->mutexattr); pthread_mutex_destroy(&mm->mutex); munmap(mm,sizeof(*mm)); return 0; }
0
#include <pthread.h> int sum; char *dir; void *threadcp(void *args) { char buf[16384]; char pathFile[260]; char *fd; int num_read; int fileIn,fileOut; fd= args; sprintf(pathFile,"%s/copy",dir); strcat(pathFile,fd); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; fileIn= open(fd,O_RDONLY); fileOut = open(pathFile,O_WRONLY| O_CREAT, 0666); for(;;) { num_read = read(fileIn,buf,16384); if(num_read == -1) { fprintf(stderr,"Read Error!\\n"); } if(num_read == 0) { break; } if(write(fileOut,buf,num_read) != num_read) { fprintf(stderr,"Write Error!\\n"); } pthread_mutex_lock(&mutex1); sum+=num_read; pthread_mutex_unlock(&mutex1); } close(fileIn); close(fileOut); } int main(int argc, char *argv[]) { int i,iret,maxThreadNum; char *fileName; maxThreadNum = 10; pthread_t * thread = malloc(sizeof(pthread_t)*maxThreadNum); if(strcmp(argv[1],"threadcp")==0) { dir = argv[argc-1]; for (int i = 1; i < argc -2; i++) { fileName = argv[i+1]; iret = pthread_create(&thread[i], 0, &threadcp, (void *) fileName); if (iret) { fprintf(stderr, "Error - pthread_create() return code: %d\\n", iret); } } for (int i = 1; i < argc - 2; i++) { pthread_join(thread[i], 0); } printf("%d Bytes copied\\n", sum); exit(0); } }
1
#include <pthread.h> extern struct user myself; extern struct user *activeChatBuddy; extern struct group *activeChatGroup; void addUserConversationElement(struct user *src, struct user *dst, char *message) { struct user *user = (src == &myself ? dst : src); struct conversation *conv = &(user->conv); time_t now = time(0); struct tm* tm_now = localtime(&now); pthread_mutex_lock(&conv->lock); struct conversation_element *newElement = (struct conversation_element *) malloc( sizeof(struct conversation_element)); memset(newElement, 0, sizeof(struct conversation_element)); strcpy(newElement->message, message); newElement->src = src; newElement->dstUser = dst; memcpy(&newElement->timestamp, tm_now, sizeof(struct tm)); if (conv->last == 0) { conv->first = conv->last = newElement; conv->messageCount = 1; conv->unreadMessage = 1; } else { if (conv->messageCount >= MAX_CONVERSATION_ELEMENT) { struct conversation_element *deleteObject = conv->first; conv->first = conv->first->next; conv->messageCount--; free(deleteObject); } conv->last->next = newElement; conv->messageCount++; conv->last = newElement; conv->unreadMessage++; } if (src != &myself && src != activeChatBuddy) { showIncomingMessageNotificationFromUser(user); } pthread_mutex_unlock(&conv->lock); } void addGroupConversationElement(struct user *src, struct group *dst, char *message) { struct conversation *conv = &(dst->conv); time_t now = time(0); if (conv->last != 0 && strcmp(message, conv->last->message) == 0) { return; } pthread_mutex_lock(&conv->lock); struct conversation_element *newElement = (struct conversation_element *) malloc( sizeof(struct conversation_element)); memset(newElement, 0, sizeof(struct conversation_element)); strcpy(newElement->message, message); newElement->src = src; newElement->dstUser = 0; newElement->dstGroup = dst; memcpy(&newElement->timestamp, localtime(&now), sizeof(struct tm)); if (conv->last == 0) { conv->first = conv->last = newElement; conv->messageCount = 1; conv->unreadMessage = 1; } else { if (strcmp(conv->last->message, message) == 0) { pthread_mutex_unlock(&conv->lock); return; } if (conv->messageCount >= MAX_CONVERSATION_ELEMENT) { struct conversation_element *deleteObject = conv->first; conv->first = conv->first->next; conv->messageCount--; free(deleteObject); } conv->last->next = newElement; conv->messageCount++; conv->last = newElement; conv->unreadMessage++; } if (src != &myself && dst != activeChatGroup) { showIncomingMessageNotificationToGroup(dst); } pthread_mutex_unlock(&conv->lock); }
0
#include <pthread.h> int pencil = 10; pthread_mutex_t mutex; pthread_cond_t cond; int flag = 0; void *thread_producer(void *argv) { for (int i = 0; i < 100; i++) { pthread_mutex_lock(&mutex); ++pencil; printf("thread produce a pencil %d\\n", pencil); pthread_mutex_unlock(&mutex); usleep(500*1000); pthread_cond_signal(&cond); } } void *thread_consumer(void *argv) { int id = (int)argv; for (;;) { pthread_mutex_lock(&mutex); if (pencil < 1 && flag == 0) { printf("consumer[%d] is waitting\\n", id); pthread_cond_wait(&cond, &mutex); } if (flag == 1) { pthread_mutex_unlock(&mutex); return 0; } printf("thread consumer[%d] sell a pencil [%d]\\n", id, pencil); --pencil; pthread_mutex_unlock(&mutex); } } int main() { int ret; pthread_t pth_pro, pth_con1, pth_con2; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); ret = pthread_create(&pth_pro, 0, thread_producer, 0); assert(ret == 0); ret = pthread_create(&pth_con1, 0, thread_consumer, (void*)1); assert(ret == 0); ret = pthread_create(&pth_con2, 0, thread_consumer, (void*)2); pthread_join(pth_pro, 0); flag = 1; pthread_cond_broadcast(&cond); pthread_join(pth_con1, 0); pthread_join(pth_con2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> static char* output_string = 0; static pthread_mutex_t output_lock; static int initialized = 0; static pthread_t thread; static void* query_desktop_thread() { if( output_string == 0 ) { output_string = calloc( 512, sizeof(char) ); } FILE *bspcfp; char *desktop_status; char* to_free; while( initialized ) { desktop_status = calloc( 64, sizeof(char) ); to_free = desktop_status; bspcfp = popen("bspc wm --get-status", "r"); if( bspcfp == 0 ) { pthread_mutex_lock( &output_lock ); strncpy( output_string, "Could not fetch display.", 512 -1 ); pthread_mutex_unlock( &output_lock ); free(to_free); } else { fscanf( bspcfp, "%s\\n", desktop_status ); pclose( bspcfp ); char* token; token = strsep( &desktop_status, ":"); pthread_mutex_lock( &output_lock ); memset( output_string, 0, 512 ); for( int i = 1; i <= 6; i++ ) { if( (token = strsep(&desktop_status, ":")) != 0 ) { char state = token[0]; if( !state_to_color(color, state) ) { log_error("Invalid desktop state!"); } sprintf( output_string+strnlen(output_string, 512 -1), "%%{F%s}%%{A:bspc desktop -f %d | sh:} %d %%{A}%%{F-}", color, i, i ); } } pthread_mutex_unlock( &output_lock ); free(to_free); } usleep( 100000 ); } free( output_string ); output_string = 0; return 0; } int desktop_init() { if( initialized ) return 0; pthread_mutex_init( &output_lock, 0 ); pthread_create( &thread, 0, &query_desktop_thread, 0 ); initialized = 1; return 1; } int desktop_destroy() { if( !initialized ) return 0; initialized = 0; pthread_join(thread, 0 ); pthread_mutex_destroy( &output_lock ); return 1; } char* get_desktop_display() { if( !initialized ) return 0; char* desktop_string = calloc( 512, sizeof(char) ); pthread_mutex_lock( &output_lock ); if( output_string ) { strncpy( desktop_string, output_string, 512 -1 ); } pthread_mutex_unlock( &output_lock ); return desktop_string; } static int state_to_color( char* colorDest, char state ) { switch( state ) { case 'o': break; case 'f': break; case 'O': case'F': break; default: return 0; break; } return 1; }
0
#include <pthread.h> unsigned short * bellman_ford(unsigned size, unsigned vertex){ int mat[MAX][MAX], v, u, d; FILE * F; unsigned dist[MAX]; unsigned short *parent = malloc((size + 1)*sizeof(unsigned short)); if(!(F = fopen("config/enlaces.config", "r"))) return; for ( v = 1; v <= size; v++ ){ for( u = 1; u <= size; u++ ) mat[v][u] = 0; dist[v] = infinity; parent[v] = -1; } dist[vertex] = 0; parent[vertex] = vertex; while(fscanf(F, "%d %d %d", &v, &u, &d)!= EOF) mat[u][v] = mat[v][u] = d; for(d = 0; d < size - 1; d++ ) for( v = 1; v <= size; v++ ) for (u = 1; u <= size; u++ ) if(mat[v][u]) if(dist[v] > mat[v][u] + dist[u]){ dist[v] = mat[v][u] + dist[u]; parent[v] = u; } return parent; } unsigned short * next_hop(unsigned size, unsigned vertex, unsigned short * parent){ unsigned short * hop = malloc((size + 1) * sizeof(unsigned short)); unsigned i, j; for ( i = 1; i <= size; i++){ j = i; while(parent[j] != vertex){ j = parent[j]; } hop[i] = j; } return hop; } struct list * insert_list(struct package pkg){ struct list *new = malloc(sizeof(struct list)); new->pkg = pkg; new->next = _list; new->prev = 0; if(_list) _list->prev = new; return new; } int ack(unsigned id){ struct list * l = _list; while(l){ if(l->pkg.id == id){ if(l->prev) l->prev->next = l->next; if(l->next) l->next->prev = l->prev; if(!l->prev && !l->next) _list = 0; return 1; } l = l->next; } return 0; } void die(char *s){ perror(s); exit(1); } void _send(struct sockaddr_in si_other, unsigned i, int s, struct package * pkg){ si_other.sin_port = htons(ports[nextHop[i]]); if (inet_aton(ips[nextHop[i]], &si_other.sin_addr) == 0){ fprintf(stderr, "inet_aton() failed\\n"); exit(1); } if (sendto(s, pkg, sizeof(struct package) , 0 , (struct sockaddr *) &si_other, sizeof(si_other))==-1) die("sendto()"); } void * thread_resend( void * v ){ struct sockaddr_in si_other; int s, i, slen=sizeof(si_other), minute; struct list * l; if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) die("socket"); memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; while(1){ sleep(5); pthread_mutex_lock(&list_mutex); l = _list; while(l){ if(l->pkg.att++ <= 3){ _send(si_other, l->pkg.destiny, s, &l->pkg); printf("> Resend package %d.\\n", l->pkg.id); }else{ ack(l->pkg.id); printf("> Package %d can't reach destiny.\\n", l->pkg.id); } l = l->next; } pthread_mutex_unlock(&list_mutex); } } void * source(void * v){ struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); struct package * pkg = malloc(sizeof(struct package)); if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) die("socket"); memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; while(1){ scanf("%d %s",&i, pkg->message); pkg->id = message_id++; pkg->source = id; pkg->destiny = i; pkg->type = pkg->att = 1; pthread_mutex_lock(&list_mutex); _list = insert_list(*pkg); pthread_mutex_unlock(&list_mutex); _send(si_other, i, s, pkg); } free(pkg); close(s); return; } void destiny( void ){ struct sockaddr_in si_me, si_other; struct package * pkg = malloc(sizeof(struct package)); int s, i, slen = sizeof(si_other) , recv_len; struct list *l = _list; if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) die("socket"); memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(ports[id]); si_me.sin_addr.s_addr = htonl(INADDR_ANY); if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) die("bind"); while(1){ int new_d; fflush(stdout); if ((recv_len = recvfrom(s, pkg, sizeof(struct package), 0, (struct sockaddr *) &si_other, &slen)) == -1) die("recvfrom()"); printf("\\n> Received packet from %s: %d\\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); if(pkg->destiny == id){ if(pkg->type == 0){ printf("> Acknowledgment %d\\n", pkg->id); pthread_mutex_lock(&list_mutex); ack(pkg->id); pthread_mutex_unlock(&list_mutex); continue; } printf("DATA: %s\\n", pkg->message); new_d = pkg->source; pkg->type = 0; pkg->source = id; pkg->destiny = new_d; }else new_d = pkg->destiny; _send(si_other, new_d, s, pkg); } close(s); return; } void readf(){ int i; FILE * F; if(!(F = fopen("config/roteador.config", "r"))) return; while(fscanf(F, "%d", &i)!=EOF){ fscanf(F, "%hu %s", &ports[i], ips[i]); if(feof(F))break; } } void id_atoi (char * nptr){ id = atoi(nptr); }
1
#include <pthread.h> int buffer1[10]; int buffer2[10]; int buffer1_pointer; int buffer1_length; int buffer2_pointer; int buffer2_length; pthread_mutex_t buffer1_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t buffer2_mutex = PTHREAD_MUTEX_INITIALIZER; void produce1() { while (1) { int value = get_random_number(); pthread_mutex_lock(&buffer1_mutex); put1(value); pthread_mutex_unlock(&buffer1_mutex); printf("Produced: %d\\n", value); fflush(stdout); usleep(100000); } } void produce2() { while (1) { int value = get_random_number(); pthread_mutex_lock(&buffer2_mutex); put2(value); pthread_mutex_unlock(&buffer2_mutex); printf("Produced: %d\\n", value); fflush(stdout); usleep(100000); } } void consume1() { while (1) { int locked_buffer1 = pthread_mutex_trylock(&buffer1_mutex); int locked_buffer2 = pthread_mutex_trylock(&buffer2_mutex); if (locked_buffer1 && locked_buffer2) { int value = get1(); printf("Consumed: %d\\n", value); fflush(stdout); usleep(1000000); pthread_mutex_unlock(&buffer1_mutex); pthread_mutex_unlock(&buffer2_mutex); } else { } } } void consume2() { while (1) { int value = get2(); printf("Consumed: %d\\n", value); fflush(stdout); usleep(1000000); } } void put1(int value) { if ( !buffer1_full_p() ) { buffer1[(buffer1_pointer + buffer1_length) % 10] = value; buffer1_length++; } else { printf("Buffer full going to sleep....!\\n"); fflush(stdout); } } void put2(int value) { if ( !buffer2_full_p() ) { buffer2[(buffer2_pointer + buffer2_length) % 10] = value; buffer2_length++; } else { printf("Buffer full going to sleep....!\\n"); fflush(stdout); } } int get1() { if ( !buffer1_empty_p() ) { int value; buffer1_length--; value = buffer1[buffer1_pointer++ % 10]; return value; } else { printf("Buffer empty!\\n"); fflush(stdout); } } int get2() { if ( !buffer2_empty_p() ) { int value; buffer2_length--; value = buffer2[buffer2_pointer++ % 10]; return value; } else { printf("Buffer empty!\\n"); fflush(stdout); } } int buffer1_full_p() { return buffer1_length == 10; } int buffer1_empty_p() { return buffer1_length == 0; } int buffer2_full_p() { return buffer2_length == 10; } int buffer2_empty_p() { return buffer2_length == 0; } int get_random_number() { return rand() % 100; } int main() { pthread_t producer1, producer2, consumer1, consumer2; int i = 0; for( i = 0; i < 10; ++i ) buffer1[i] = 0; for( i = 0; i < 10; ++i ) buffer2[i] = 0; buffer1_pointer = 0; buffer1_length = 0; buffer2_pointer = 0; buffer2_length = 0; pthread_create(&producer1, 0, produce1, (void*)0); pthread_create(&producer2, 0, produce2, (void*)0); pthread_create(&consumer1, 0, consume1, (void*)0); pthread_create(&consumer2, 0, consume2, (void*)0); pthread_join(producer1, 0); pthread_join(consumer2, 0); pthread_join(producer1, 0); pthread_join(consumer2, 0); }
0
#include <pthread.h> void *Producer(); void *Consumer(); int BufferIndex=0; char *BUFFER; pthread_cond_t Buffer_Not_Full=PTHREAD_COND_INITIALIZER; pthread_cond_t Buffer_Not_Empty=PTHREAD_COND_INITIALIZER; pthread_mutex_t mVar=PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t ptid,ctid; BUFFER=(char *) malloc(sizeof(char) * 10); pthread_create(&ptid,0,Producer,0); pthread_create(&ctid,0,Consumer,0); pthread_join(ptid,0); pthread_join(ctid,0); return 0; } void *Producer() { for(;;) { pthread_mutex_lock(&mVar); if(BufferIndex==10) { pthread_cond_wait(&Buffer_Not_Full,&mVar); } BUFFER[BufferIndex++]='@'; printf("Produce : %d \\n",BufferIndex); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Empty); } } void *Consumer() { for(;;) { pthread_mutex_lock(&mVar); if(BufferIndex==-1) { pthread_cond_wait(&Buffer_Not_Empty,&mVar); } printf("Consume : %d \\n",BufferIndex--); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Full); } }
1
#include <pthread.h> void *thread_fmain(void *); void *thread_mmain(void *); void man_leaveRR1(); void man_leaveRR2(); void man_enter(); void woman_leaveRR1(); void woman_leaveRR2(); void woman_enter(); void use_rr(); void do_other_stuff(); int get_simple_tid(pthread_t); int maleCountRR1 = 0; int femaleCountRR1 =0; int maleCountRR2 = 0; int femaleCountRR2 =0; pthread_t threadIDs[2 +2]; sem_t rr1_semaphore; sem_t rr2_semaphore; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t full = PTHREAD_COND_INITIALIZER; int main() { pthread_attr_t attribs; int i; int tids[2 +2]; pthread_t pthreadids[2 +2]; sem_init(&rr1_semaphore, 0, 2); sem_init(&rr2_semaphore, 0, 2); pthread_mutex_init(&mutex, 0); srandom(time(0) % (unsigned int) 32767); pthread_attr_init(&attribs); for (i=0; i< 2; i++) { tids[i] = i; pthread_create(&(pthreadids[i]), &attribs, thread_fmain, &(tids[i])); } for (i=0; i< 2; i++) { tids[i+2] = i+2; pthread_create(&(pthreadids[i]), &attribs, thread_mmain, &(tids[i+2])); } for (i=0; i< 2 +2; i++) pthread_join(pthreadids[i], 0); return 0; } void *thread_fmain(void * arg) { int tid = *((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); woman_enter(); } } void *thread_mmain(void * arg) { int tid = * ((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); man_enter(); } } void woman_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread f%d trying to get in the restroom\\n", id); pthread_mutex_lock(&mutex); while((maleCountRR1 > 0 || femaleCountRR1 == 2) && (maleCountRR2 > 0 || femaleCountRR2 == 2)){ pthread_cond_wait(&full, &mutex); } if(maleCountRR1 ==0 && femaleCountRR1 !=2){ sem_wait(&rr1_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++femaleCountRR1; pthread_mutex_unlock(&mutex); printf("Thread f%d got in to restroom 1!\\n", id); use_rr(); woman_leaveRR1(); } else if(maleCountRR2 ==0 && femaleCountRR2 !=2){ sem_wait(&rr2_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++femaleCountRR2; pthread_mutex_unlock(&mutex); printf("Thread f%d got in to restroom 2!\\n", id); use_rr(); woman_leaveRR2(); } printf("Wait time for thread f%d was %f\\n", id, waittime); } void woman_leaveRR1() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr1_semaphore); --femaleCountRR1; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("thread f %d left!\\n",id); } void woman_leaveRR2() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr2_semaphore); --femaleCountRR2; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("thread f %d left!\\n",id); } void man_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread m%d trying to get in the restroom\\n", id); pthread_mutex_lock(&mutex); while((femaleCountRR1 > 0 || maleCountRR1 == 2) && (femaleCountRR2 > 0 || maleCountRR2 == 2)){ pthread_cond_wait(&full, &mutex); } if(femaleCountRR1 ==0 && maleCountRR1 !=2){ sem_wait(&rr1_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++maleCountRR1; pthread_mutex_unlock(&mutex); printf("Thread f%d got in to restroom 1!\\n", id); use_rr(); man_leaveRR1(); } else if(femaleCountRR2 ==0 && maleCountRR2 !=2){ sem_wait(&rr2_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++maleCountRR2; pthread_mutex_unlock(&mutex); printf("Thread f%d got in to restroom 2!\\n", id); use_rr(); man_leaveRR2(); } printf("Wait time for thread m%d was %f\\n", id, waittime); } void man_leaveRR1() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr1_semaphore); --maleCountRR1; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("Thread m%d left!\\n", id); } void man_leaveRR2() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr2_semaphore); --maleCountRR2; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("Thread m%d left!\\n", id); } void use_rr() { struct timespec req, rem; double usetime; usetime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(usetime); req.tv_nsec = (unsigned int) ( (usetime - (int) floor(usetime)) * 1000000000); printf("Thread %d using restroom for %lf time\\n", get_simple_tid(pthread_self()), usetime); nanosleep(&req,&rem); } void do_other_stuff() { struct timespec req, rem; double worktime; worktime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(worktime); req.tv_nsec = (unsigned int) ( (worktime - (int) floor(worktime)) * 1000000000); printf("Thread %d working for %lf time\\n", get_simple_tid(pthread_self()), worktime); nanosleep(&req,&rem); } int get_simple_tid(pthread_t lid) { int i; for (i=0; i<2 +2; i++) if (pthread_equal(lid, threadIDs[i])) return i; printf("Oops! did not find a tid for %lu\\n", lid); _exit(-1); }
0
#include <pthread.h> int buffer; int count = 0; pthread_cond_t cond; pthread_mutex_t mutex; void put(int value) { assert(count == 0); count = 1; buffer = value; } int get() { assert(count == 1); count = 0; return buffer; } void *producer(void *arg) { int i; int loops = *(int *) arg; for (i = 0; i < loops; i++) { printf("In producer loop\\n"); pthread_mutex_lock(&mutex); if (count == 1) pthread_cond_wait(&cond, &mutex); put(i); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void *consumer(void *arg) { int i; int loops = *(int *) arg; for (i = 0; i < loops; i++) { printf("In consumer loop\\n"); pthread_mutex_lock(&mutex); if (count == 0) pthread_cond_wait(&cond, &mutex); int tmp = get(); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); printf("%d\\n", tmp); } return 0; } int main(){ pthread_t p; pthread_t c1; pthread_t c2; int loops = 10; pthread_create(&p, 0, producer, &loops); pthread_create(&c1, 0, consumer, &loops); pthread_create(&c2, 0, consumer, &loops); pthread_join(p, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; int nbrF=0,nbrT=0,fichier_corrant=0; char** cp; void *conversion_func(void *agc) { char* nomF; int l; while (fichier_corrant<nbrF) { pthread_mutex_lock(&mutex); l=strlen(cp[fichier_corrant]); nomF=(char *)malloc(l*sizeof(char)); strcpy(nomF,cp[fichier_corrant]); int c; FILE* fp1, *fp2; c=1; fp1= fopen (nomF, "r"); fp2= fopen (nomF, "r+"); if ((fp1== 0) || (fp2== 0)) { perror ("fopen thread"); pthread_exit((void*)1); } while (c !=EOF) { c=fgetc(fp1); if (c!=EOF) fputc(toupper(c),fp2); } fclose (fp1); fclose (fp2); printf("Thread %d termine, le fichier '%s' a été convertit.\\n",(int)pthread_self(),nomF); fichier_corrant++; nbrT++; if (nbrT<3) { pthread_cond_wait(&cond, &mutex); } else { pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); } pthread_cond_broadcast(&cond); pthread_exit((void*)pthread_self()); } int main (int argc, char ** argv) { nbrF=argc-1; int i,status,nbrB; pthread_t tid[3]; printf("nombre de fichiers à convertir : %d\\n",nbrF); int taille; cp=(char **)malloc((argc-1)*sizeof(char*)); for (i=1;i<argc;i++) { taille=strlen(argv[i]); cp[i-1]=(char *)malloc(taille*sizeof(char)); strcpy(cp[i-1],argv[i]); } if (nbrF<3) nbrB=nbrF; else nbrB=3; for (i=0;i<nbrB;i++) { if (pthread_create(&tid[i],0,conversion_func,0)!=0) { printf("ERREUR:creation\\n"); exit(1); } } for (i=0;i<nbrB;i++) { if (pthread_join(tid[i],(void **)&status)!=0) { printf("ERREUR:joindre\\n"); exit(2); } } printf("Tous les fichiers sont convertit.\\n"); return 0; }
0
#include <pthread.h> static void setNumPuts(struct aipc_audiopluginmixer *audiopluginmixer){ int num_inputs=0; int num_outputs=0; int lokke; for(lokke=0;lokke<audiopluginmixer->num_callers;lokke++){ if(num_inputs<audiopluginmixer->callers[lokke]->num_inputs) num_inputs=audiopluginmixer->callers[lokke]->num_inputs; if(num_outputs<audiopluginmixer->callers[lokke]->num_outputs) num_outputs=audiopluginmixer->callers[lokke]->num_outputs; } audiopluginmixer->num_inputs=num_inputs; audiopluginmixer->num_outputs=num_outputs; } struct aipc_audiopluginmixer *aipc_audiopluginmixer_new(void){ struct aipc_audiopluginmixer *audiopluginmixer=calloc(1,sizeof(struct aipc_audiopluginmixer)); pthread_mutex_init(&audiopluginmixer->mutex,0); return audiopluginmixer; } void aipc_audiopluginmixer_call_audioplugins( struct aipc_audiopluginmixer *audiopluginmixer, int num_inputs, float **inputs, int num_outputs, float **outputs, int num_frames ) { int lokke; struct aipc_audioplugincaller *caller; float dummy[num_frames]; bool dummy_is_cleared=0; audiopluginmixer->is_calling=1; lokke=0; for(;;lokke++){ if(lokke >= audiopluginmixer->num_callers) break; caller=audiopluginmixer->callers[lokke]; { float *inputs_proc[caller->num_inputs]; float *outputs_proc[caller->num_outputs]; float outputdata[caller->num_outputs*num_frames]; int lokke2; for(lokke2=0;lokke2<caller->num_inputs;lokke2++){ if(lokke2 < num_inputs){ inputs_proc[lokke2]=inputs[lokke2]; }else{ inputs_proc[lokke2]=dummy; if(dummy_is_cleared==0){ memset(&dummy,0,num_frames*sizeof(float)); dummy_is_cleared=1; } } } for(lokke2=0;lokke2<caller->num_outputs;lokke2++){ outputs_proc[lokke2]=&outputdata[lokke2*num_frames]; } aipc_audioplugincaller_call_audioplugin(caller,inputs_proc,outputs_proc,num_frames); if(lokke==0){ for(lokke2=0;lokke2<num_outputs;lokke2++){ if(lokke2<caller->num_outputs){ memcpy(outputs[lokke2],outputs_proc[lokke2],num_frames*sizeof(float)); }else{ memset(outputs[lokke2],0,num_frames*sizeof(float)); } } }else{ for(lokke2=0;lokke2<(((num_outputs)<(caller->num_outputs))?(num_outputs):(caller->num_outputs));lokke2++){ int lokke3; for(lokke3=0;lokke3<num_frames;lokke3++){ outputs[lokke2][lokke3] += outputs_proc[lokke2][lokke3]; } } } } } audiopluginmixer->is_calling=0; } bool aipc_audiopluginmixer_add_caller( struct aipc_audiopluginmixer *audiopluginmixer, struct aipc_audioplugincaller *caller ) { struct aipc_audioplugincaller **new_callers; struct aipc_audioplugincaller **old_callers; pthread_mutex_lock(&audiopluginmixer->mutex); new_callers=calloc(sizeof(struct aipc_audioplugincaller*),audiopluginmixer->num_callers+1); if(audiopluginmixer->num_callers>0){ memcpy( new_callers, audiopluginmixer->callers, sizeof(struct aipc_audioplugincaller*)*audiopluginmixer->num_callers ); } new_callers[audiopluginmixer->num_callers]=caller; old_callers=audiopluginmixer->callers; audiopluginmixer->callers=new_callers; audiopluginmixer->num_callers++; setNumPuts(audiopluginmixer); free(old_callers); while(audiopluginmixer->is_calling==1) usleep(200); pthread_mutex_unlock(&audiopluginmixer->mutex); return 1; } void aipc_audiopluginmixer_remove_caller( struct aipc_audiopluginmixer *audiopluginmixer, struct aipc_audioplugincaller *caller ) { int lokke; pthread_mutex_lock(&audiopluginmixer->mutex); for(lokke=0;lokke<audiopluginmixer->num_callers - 1;lokke++){ if(audiopluginmixer->callers[lokke]==caller){ audiopluginmixer->num_callers--; audiopluginmixer->callers[lokke] = audiopluginmixer->callers[audiopluginmixer->num_callers]; setNumPuts(audiopluginmixer); while(audiopluginmixer->is_calling==1) usleep(200); pthread_mutex_unlock(&audiopluginmixer->mutex); return; } } fprintf(stderr,"aipc_audiopluginmixer_remove_caller: caller not found.\\n"); pthread_mutex_unlock(&audiopluginmixer->mutex); } void aipc_audiopluginmixer_delete( struct aipc_audiopluginmixer *audiopluginmixer ) { pthread_mutex_destroy(&audiopluginmixer->mutex); free(audiopluginmixer->callers); free(audiopluginmixer); }
1
#include <pthread.h> int sum = 0; sem_t items; sem_t slots; pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER; int producer_done = 0; void *producer(void *arg1) { int i; for(i = 1; i <= 100; i++) { sem_wait(&slots); put_item(i*i); sem_post(&items); } pthread_mutex_lock(&my_lock); producer_done = 1; for(i = 0; i < 1; i++) sem_post(&items); pthread_mutex_unlock(&my_lock); return 0; } void *consumer(void *arg2) { int myitem; for( ; ; ) { sem_wait(&items); pthread_mutex_lock(&my_lock); if(!producer_done) { pthread_mutex_unlock(&my_lock); get_item(&myitem); sem_post(&slots); sum += myitem; } else { pthread_mutex_unlock(&my_lock); break; } } return 0; } int main(void) { pthread_t prodid; pthread_t consid; int i, total; total = 0; for(i = 1; i <= 100; i++) total += i*i; printf("the actual sum should be %d\\n", total); sem_init(&items, 0, 0); sem_init(&slots, 0, 8); if(pthread_create(&consid, 0, consumer, 0)) perror("Could not create consumer"); else if(pthread_create(&prodid, 0, producer, 0)) perror("Could not create producer"); pthread_join(prodid, 0); pthread_join(consid, 0); printf("The threads producer the sum %d\\n", sum); exit(0); }
0
#include <pthread.h> void fun_thread1(char *msg); void fun_thread2(char *msg); int g_value = 1; pthread_mutex_t mutex; int main(int argc,char *argv[]) { pthread_t thread1; pthread_t thread2; if(pthread_mutex_init(&mutex,0) !=0 ) { printf("init mutex error.\\n"); exit(1); } if(pthread_create(&thread1,0,(void*)fun_thread1,0) !=0) { printf("init thread1 error.\\n"); exit(1); } if(pthread_create(&thread2,0,(void*)fun_thread2,0)!=0) { printf("init thread2 error.\\n"); exit(1); } sleep(1); printf("i am main thread,g_value is %d\\n",g_value); return 0; } void fun_thread1(char *msg) { int val; val = pthread_mutex_lock(&mutex); if(val !=0) { printf("lock error."); } g_value = 0; printf("thread1 locked,init the g_value to 0,and add 5\\n"); g_value += 5; printf("the g_value is %d\\n",g_value); pthread_mutex_unlock(&mutex); printf("thread1 unlocked.\\n"); } void fun_thread2(char *msg) { int val; val = pthread_mutex_lock(&mutex); if(val != 0) { printf("lock error\\n"); } g_value = 0; printf("thread 2 locked,init the g_value to 0 and add 5.\\n"); g_value += 6; printf("the g_value is %d\\n",g_value); pthread_mutex_unlock(&mutex); printf("thread 2 unlocked.\\n"); }
1
#include <pthread.h> static pthread_barrier_t s_barrier; static pthread_mutex_t s_mutex; static pthread_cond_t s_cond; static int s_counter; static void* thread_func(void* argp) { const int thread_num = (ptrdiff_t)(argp); pthread_mutex_t invalid_mutex; char thread_name[32]; snprintf(thread_name, sizeof(thread_name), "thread_func instance %d", thread_num + 1); ANNOTATE_THREAD_NAME(thread_name); memset(&invalid_mutex, 0xff, sizeof(invalid_mutex)); pthread_barrier_wait(&s_barrier); pthread_mutex_lock(&s_mutex); while (s_counter != thread_num) pthread_cond_wait(&s_cond, &s_mutex); fprintf(stderr, "\\n%s\\n\\n", thread_name); pthread_mutex_unlock(&invalid_mutex); s_counter++; pthread_cond_broadcast(&s_cond); pthread_mutex_unlock(&s_mutex); return 0; } int main(int arg, char** argv) { int i; pthread_t tid[10]; pthread_barrier_init(&s_barrier, 0, 10); pthread_mutex_init(&s_mutex, 0); pthread_cond_init(&s_cond, 0); for (i = 0; i < 10; i++) pthread_create(&tid[i], 0, thread_func, (void*)(ptrdiff_t)i); for (i = 0; i < 10; i++) pthread_join(tid[i], 0); pthread_cond_destroy(&s_cond); pthread_mutex_destroy(&s_mutex); return 0; }
0
#include <pthread.h> double total_grade = 0; double total_bellcurve = 0; pthread_mutex_t mutex; pthread_barrier_t barrier; void *read_grades(void *param) { FILE *fp; int i; int* grades = (int*)param; fp = fopen("grades.txt", "r"); if (fp == 0) { printf("ERROR: Could not open file to read\\n"); exit(1); } for (i = 0; i < 10; i++) { fscanf(fp, "%d", &grades[i]); } fclose(fp); pthread_exit(0); return 0; } void *save_bellcurve(void *grade) { FILE *fp; double bellcurved; pthread_mutex_lock(&mutex); total_grade += *((int*)grade); pthread_mutex_unlock(&mutex); bellcurved = *((int*)grade) * 1.5; pthread_mutex_lock(&mutex); total_bellcurve += bellcurved; pthread_mutex_unlock(&mutex); pthread_barrier_wait (&barrier); pthread_mutex_lock(&mutex); fp = fopen("bellcurve.txt", "a"); if (fp == 0) { printf("ERROR: Could not open file to write\\n"); exit(1); } fprintf(fp, "%lf\\n", bellcurved); fclose(fp); pthread_mutex_unlock(&mutex); pthread_exit(0); return 0; } int main(void) { pthread_t threads[10]; pthread_t readThread; int rc; int i; int grades[10]; pthread_barrier_init (&barrier, 0, 10 + 1); rc = pthread_mutex_init(&mutex, 0); rc = pthread_create(&readThread, 0, read_grades, (void*)grades); if (rc){ printf("ERROR: Could not create thread to read file\\n"); exit(-1); } if(pthread_join(readThread, 0)) { printf("ERROR: Could not joining thread\\n"); return 2; } for (i = 0; i < 10; i++) { rc = pthread_create(&threads[i], 0, save_bellcurve, (void*)(&grades[i])); if (rc){ printf("ERROR: Could not create thread to calculate\\n"); exit(-1); } } pthread_barrier_wait (&barrier); printf("Total grades: %lf\\n", total_grade); printf("Class average: %lf\\n", total_grade/ (double)10); printf("\\n"); printf("Total grades: %lf\\n", total_bellcurve); printf("Class average: %lf\\n", total_bellcurve/ (double)10); for (i = 0; i < 10; i++) { if(pthread_join(threads[i], 0)) { printf("ERROR: Could not joining thread\\n"); return 2; } } rc = pthread_mutex_destroy(&mutex); pthread_barrier_destroy(&barrier); return 0; }
1
#include <pthread.h> static int cant_hilos; static int resto; static pthread_mutex_t lock; static int tarea = -1; static int A[2500][2500], B[2500][2500], C[2500][2500]; struct indices { int i, j; }; void cargarMatrices(); void realizarTarea(indice indiceGral); void *mapearTarea(void *); indice getIndice(int); double getTime(); void imprimirMatrices(); int main(int argc, char *argv[]){ int i, j, k, token; pthread_t *hilos; double t1, t2; if (argc!=2) { fprintf(stderr, "Modo de uso: ./mm1d <cantidad_de_hilos>\\n"); return -1; } cant_hilos=atoi(argv[1]); hilos = (pthread_t *)malloc(sizeof(pthread_t) * (cant_hilos-1)); pthread_mutex_init(&lock, 0); cargarMatrices(); printf("Ok!!\\n\\n"); printf("Multiplicacion ...\\n"); pthread_setconcurrency(cant_hilos); t1=getTime(); for (i=0; i < cant_hilos-1; i++) pthread_create(hilos+i, 0, mapearTarea, 0); mapearTarea(0); for (i=0; i < cant_hilos-1; i++) pthread_join(hilos[i], 0); t2=getTime(); if (2500 <= 10 && 2500 <= 10 && 2500 <= 10){ imprimirMatrices(); } printf("\\n\\nDuracion total de la multilplicacion de matrices %4f segundos\\n", t2-t1); } void cargarMatrices(){ int i, j = 0; for (i=0; i < 2500; i++) for (j=0; j < 2500; j++) A[i][j] = (j+3) * (i+1); for (i=0; i < 2500; i++) for (j=0; j < 2500; j++) B[i][j] = i+j; for (i=0; i < 2500; i++) for (j=0; j < 2500; j++) C[i][j] = 0; } void realizarTarea(indice indiceGral) { int k; for (k=0; k < 2500; k++) C[indiceGral.i][indiceGral.j] += A[indiceGral.i][k] * B[k][indiceGral.j]; } void *mapearTarea(void *arg) { while (1) { pthread_mutex_lock(&lock); tarea++; pthread_mutex_unlock(&lock); if ( tarea >= 2500*2500) return 0; indice indiceGral = getIndice(tarea); realizarTarea(indiceGral); } } indice getIndice(int tarea) { indice indiceGral; indiceGral.i = tarea / 2500; indiceGral.j = tarea % 2500; return indiceGral; } double getTime() { struct timeval t; gettimeofday(&t, 0); return (double)t.tv_sec+t.tv_usec*0.000001; } void imprimirMatrices() { int i, j = 0; printf("Imprimimos matrices...\\n"); printf("Matriz A\\n"); for (i=0; i < 2500; i++) { printf("\\n\\t| "); for (j=0; j < 2500; j++) printf("%d ", A[i][j]); printf("|"); } printf("\\n"); printf("Matriz B\\n"); for (i=0; i < 2500; i++) { printf("\\n\\t| "); for (j=0; j < 2500; j++) printf("%d ", B[i][j]); printf("|"); } printf("\\n"); printf("Matriz C\\n"); for (i=0; i < 2500; i++) { printf("\\n\\t| "); for (j=0; j < 2500; j++) printf("%d ", C[i][j]); printf("|"); } printf("\\n"); }
0
#include <pthread.h> struct th_arg{ char *disk; char *bmap; char *host; int bsize; }; int finish = 0; pthread_mutex_t map_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t finish_lock = PTHREAD_MUTEX_INITIALIZER; int transfer(int sockfd, int fd, char *map, int size, long long *total) { int read_count, send_count; long long pos, i; char buf[(sizeof(long long) + sizeof(int)) + 4096]; *total = 0; for(i = 0;i < size;i++) { pthread_mutex_lock(&map_lock); if( (map[i / 8] & (1 << (i % 8))) ) { (map[i / 8] &= ~(1 << (i % 8))); pthread_mutex_unlock(&map_lock); pos = i * 4096; if( lseek(fd, pos, 0) < 0) { printf("transfer():%lld,lseek error!\\n",pos); return -1; } *(long long *)buf = pos; read_count = read(fd, buf + (sizeof(long long) + sizeof(int)) , 4096); if(read_count < 0) { printf("transfer():read error!\\n"); return -1; } *(int *)(buf + sizeof(long long)) = read_count; send_count = send(sockfd, buf, sizeof(buf), 0); if(send_count < 0) { printf("transfer():send error!\\n"); return -1; } *total += send_count; } else pthread_mutex_unlock(&map_lock); } return 0; } void * do_precopy(void * th_arg) { struct th_arg * arg; int sockfd,fd; struct hostent *host; struct sockaddr_in serv_addr; int iter; char buf[(sizeof(long long) + sizeof(int)) + 4096]; long long last_send, total_send, this_send; time_t start, end, shang, ehang; start = time(0); arg = (struct th_arg *)th_arg; if( (host = gethostbyname(arg->host)) == 0) { printf("get hostbyname error!\\n"); return 0; } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("socket error!\\n"); return 0; } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(5000); bcopy((char *) host->h_addr_list[0], (char *)&serv_addr.sin_addr.s_addr, host->h_length); if( connect( sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr) ) == -1 ) { printf("connect error!\\n"); return 0; } if( (fd = open(arg->disk, O_RDONLY)) < 0 ) { printf("do_precopy():open disk error!\\n"); return 0; } last_send = 0; total_send = 0; iter = 0; while(1) { this_send = 0; iter++; if(transfer(sockfd, fd, arg->bmap, arg->bsize, &this_send) < 0) { printf("transfer error!\\n"); return 0; } total_send += this_send; if( 2 * this_send < last_send ) { iter++; shang = time(0); if(transfer(sockfd, fd, arg->bmap, arg->bsize, &this_send) < 0) { printf("transfer error!\\n"); exit(-1); } ehang = time(0); total_send += this_send; *(long long *)buf = -1; if( send(sockfd, buf, sizeof(buf), 0) < 0) { printf("send complete flag error!\\n"); return 0; } pthread_mutex_lock(&finish_lock); finish = 1; pthread_mutex_unlock(&finish_lock); printf("migration complete!\\n"); printf("total send %lld\\n",total_send); end = time(0); printf("total time %lf\\n",difftime(end, start)); printf("hang time %lf\\n",difftime(ehang, shang)); printf("iter times %d\\n",iter); close(fd); close(sockfd); pthread_exit(0); } last_send = this_send; } } int main(int argc,char *argv[]) { int fd, i; int map_size; long long disk_len; int len,pos; struct stat stat_buf; char *bit_map; struct th_arg arg; pthread_t precopy; if( argc < 3 ) { printf("too few arguments\\n"); printf("useage:a.out disk_name host_name\\n"); return 0; } if( (fd = open(argv[1],O_RDONLY)) < 0 ) { printf("open %s error\\n",argv[1]); return -1; } if( fstat(fd,&stat_buf) < 0 ) { printf("get disk infomation failure\\n"); return -1; } close(fd); disk_len = stat_buf.st_size; printf("disk length:%lld\\n",disk_len); map_size = (disk_len / 4096 + 1) / 8 + 1; bit_map = (char *)malloc(sizeof(char) * map_size); if( bit_map == 0 ) { printf("malloc memory for bit_map failure!\\n"); return -1; } memset(bit_map,0xff,map_size); arg.bmap = bit_map; arg.disk = argv[1]; arg.host = argv[2]; i = disk_len / 4096; arg.bsize = disk_len % 4096 ? i + 1 : i; printf("exact bit number:%d\\n",arg.bsize); finish = 0; if( pthread_create(&precopy,0,do_precopy,&arg) < 0 ) { printf("create precopy thread failure!\\n"); return -1; } int first_bit,last_bit; while(1) { pthread_mutex_lock(&finish_lock); if(finish == 1) { pthread_mutex_unlock(&finish_lock); break; } else pthread_mutex_unlock(&finish_lock); srand( (unsigned int)time(0) ); len = rand() % disk_len; srand((unsigned int)time(0)); pos = rand() % disk_len; first_bit = pos / 4096; last_bit = (pos + len - 1) / 4096; while( first_bit <= last_bit ) { pthread_mutex_lock(&map_lock); (bit_map[first_bit / 8] |= (1 << (first_bit % 8))); pthread_mutex_unlock(&map_lock); first_bit++; } sleep(10); } pthread_mutex_lock(&map_lock); free(bit_map); pthread_mutex_unlock(&map_lock); return 0; }
1
#include <pthread.h> int sum; void *runner(void *param); char buffer [65536]; int letters[128]; pthread_mutex_t lock; struct threadData{ int start; int end; pthread_t tid; int index; }; int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr,"usage: a.out <filename>\\n"); return -1; } FILE *fp = fopen(argv[1], "r"); if(fp != 0){ size_t newLen = fread(buffer, sizeof(char), 65536, fp); if(ferror(fp) != 0){ printf("error"); }else { buffer[newLen++] = '\\0'; } fclose(fp); } pthread_attr_t attr; pthread_attr_init(&attr); struct threadData threadDataArray[8]; int partition = 65536/8; for(int i = 0; i < 8; i++){ threadDataArray[i].index= i; if(i == 0){ threadDataArray[i].start = 0; }else{ threadDataArray[i].start = (threadDataArray[i - 1].end) + 1; } threadDataArray[i].end = (i+1)*(65536/8); } pthread_mutex_init(&lock, 0); for (int j = 0; j < 8; j++) { pthread_create(&threadDataArray[j].tid, 0, runner, &threadDataArray[j]); } for (int k = 0; k < 8; k++) { if (pthread_join(threadDataArray[k].tid, 0) != 0) { } } char temp = 0; for(int a = 1; a < 128; a++){ int total = 0; total = letters[a]; temp = a; printf("\\n %d occurrences of ascii %c ",total, temp); } pthread_mutex_destroy(&lock); } void *runner(void *arg) { struct threadData *data = arg; for (int i = data->start; i <= data->end; ++i){ pthread_mutex_lock(&lock); letters[buffer[i]-0] += 1; pthread_mutex_unlock(&lock); } pthread_exit(0); }
0
#include <pthread.h> int isRunning; char* command_queue[1]; pthread_t sendhello_thread; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int calculate(int a, int b) { return a + b; } char* dequeue_Command(void) { char* cmd = 0; while (isRunning) { pthread_mutex_lock(&mutex); { cmd = command_queue[0]; command_queue[0] = 0; } pthread_mutex_unlock(&mutex); if (cmd == 0) usleep(250 * 1000); else break; } return cmd; } void enqueue_Command(char* cmd) { pthread_mutex_lock(&mutex); { command_queue[0] = cmd; } pthread_mutex_unlock(&mutex); } void* sendhello(void *args) { while (isRunning) { int length = 10; char* cmd = (char*)malloc(length); strcpy(cmd, "hi there"); enqueue_Command(cmd); sleep(1); } return 0; } int initialize() { isRunning = 1; command_queue[0] = 0; if (pthread_create(&sendhello_thread, 0, sendhello, 0)) return -1; else return 0; } int deinitialize() { isRunning = 0; if (pthread_join(sendhello_thread, 0)) return -1; else return 0; }
1
#include <pthread.h> int thread_id; int num_elements; float *vector_a; float *vector_b; double *sum; pthread_mutex_t *mutex_for_sum; } ARGS_FOR_THREAD; float compute_gold(float *, float *, int); float compute_using_pthreads(float *, float *, int); void *dot_product(void *); void print_args(ARGS_FOR_THREAD *); int main(int argc, char **argv) { if(argc != 2){ printf("Usage: vector_dot_product <num elements> \\n"); exit(1); } int num_elements = atoi(argv[1]); float *vector_a = (float *)malloc(sizeof(float) * num_elements); float *vector_b = (float *)malloc(sizeof(float) * num_elements); srand(time(0)); for(int i = 0; i < num_elements; i++){ vector_a[i] = ((float)rand()/(float)32767) - 0.5; vector_b[i] = ((float)rand()/(float)32767) - 0.5; } struct timeval start, stop; gettimeofday(&start, 0); float reference = compute_gold(vector_a, vector_b, num_elements); gettimeofday(&stop, 0); printf("Reference solution = %f. \\n", reference); printf("Execution time = %fs. \\n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000)); printf("\\n"); gettimeofday(&start, 0); float result = compute_using_pthreads(vector_a, vector_b, num_elements); gettimeofday(&stop, 0); printf("Pthread solution = %f. \\n", result); printf("Execution time = %fs. \\n", (float)(stop.tv_sec - start.tv_sec + (stop.tv_usec - start.tv_usec)/(float)1000000)); printf("\\n"); free((void *)vector_a); free((void *)vector_b); pthread_exit(0); } float compute_gold(float *vector_a, float *vector_b, int num_elements) { double sum = 0.0; for(int i = 0; i < num_elements; i++) sum += vector_a[i] * vector_b[i]; return (float)sum; } float compute_using_pthreads(float *vector_a, float *vector_b, int num_elements) { pthread_t thread_id[8]; pthread_attr_t attributes; pthread_attr_init(&attributes); int i; double sum = 0; pthread_mutex_t mutex_for_sum; pthread_mutex_init(&mutex_for_sum, 0); ARGS_FOR_THREAD *args_for_thread[8]; for(i = 0; i < 8; i++){ args_for_thread[i] = (ARGS_FOR_THREAD *)malloc(sizeof(ARGS_FOR_THREAD)); args_for_thread[i]->thread_id = i; args_for_thread[i]->num_elements = num_elements; args_for_thread[i]->vector_a = vector_a; args_for_thread[i]->vector_b = vector_b; args_for_thread[i]->sum = &sum; args_for_thread[i]->mutex_for_sum = &mutex_for_sum; } for(i = 0; i < 8; i++) pthread_create(&thread_id[i], &attributes, dot_product, (void *)args_for_thread[i]); for(i = 0; i < 8; i++) pthread_join(thread_id[i], 0); for(i = 0; i < 8; i++) free((void *)args_for_thread[i]); return (float)sum; } void *dot_product(void *args) { ARGS_FOR_THREAD *args_for_me = (ARGS_FOR_THREAD *)args; double partial_sum = 0.0; int offset = args_for_me->thread_id; int stride = 8; while(offset < args_for_me->num_elements){ partial_sum += args_for_me->vector_a[offset]*args_for_me->vector_b[offset]; offset += stride; } pthread_mutex_lock(args_for_me->mutex_for_sum); *(args_for_me->sum) += partial_sum; pthread_mutex_unlock(args_for_me->mutex_for_sum); pthread_exit((void *)0); } void print_args(ARGS_FOR_THREAD *args_for_thread) { printf("Thread ID: %d \\n", args_for_thread->thread_id); printf("Num elements: %d \\n", args_for_thread->num_elements); printf("Address of vector A on heap: %p \\n", args_for_thread->vector_a); printf("Address of vector B on heap: %p \\n", args_for_thread->vector_b); printf("\\n"); }
0
#include <pthread.h> int memory_chunk_size = 10000000; int wait_time_us = 10000; int autotesting; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct node { void *memory; struct node *prev; struct node *next; }; struct node head, tail; void work(void) { int i; while (1) { struct node *new = malloc(sizeof(struct node)); if (new == 0) { perror("allocating node"); exit(1); } new->memory = malloc(memory_chunk_size); if (new->memory == 0) { perror("allocating chunk"); exit(1); } pthread_mutex_lock(&mutex); new->next = &head; new->prev = head.prev; new->prev->next = new; new->next->prev = new; for (i = 0; i < memory_chunk_size / 4096; i++) { ((unsigned char *) new->memory)[i * 4096] = 1; } pthread_mutex_unlock(&mutex); if (!autotesting) { printf("+"); fflush(stdout); } usleep(wait_time_us); } } void free_memory(void) { struct node *old; pthread_mutex_lock(&mutex); old = tail.next; if (old == &head) { fprintf(stderr, "no memory left to free\\n"); exit(1); } old->prev->next = old->next; old->next->prev = old->prev; free(old->memory); free(old); pthread_mutex_unlock(&mutex); if (!autotesting) { printf("-"); fflush(stdout); } } void *poll_thread(void *dummy) { struct pollfd pfd; int fd = open("/dev/chromeos-low-mem", O_RDONLY); if (fd == -1) { perror("/dev/chromeos-low-mem"); exit(1); } pfd.fd = fd; pfd.events = POLLIN; if (autotesting) { poll(&pfd, 1, 0); if (pfd.revents != 0) { exit(0); } else { fprintf(stderr, "expected no events but " "poll() returned 0x%x\\n", pfd.revents); exit(1); } } while (1) { poll(&pfd, 1, -1); if (autotesting) { free_memory(); free_memory(); free_memory(); free_memory(); free_memory(); poll(&pfd, 1, 0); if (pfd.revents == 0) { exit(0); } else { fprintf(stderr, "expected no events but " "poll() returned 0x%x\\n", pfd.revents); exit(1); } } free_memory(); } } int main(int argc, char **argv) { pthread_t threadid; head.next = 0; head.prev = &tail; tail.next = &head; tail.prev = 0; if (argc != 3 && (argc != 2 || strcmp(argv[1], "autotesting"))) { fprintf(stderr, "usage: low-mem-test <alloc size in bytes> " "<alloc interval in microseconds>\\n" "or: low-mem-test autotesting\\n"); exit(1); } if (argc == 2) { autotesting = 1; } else { memory_chunk_size = atoi(argv[1]); wait_time_us = atoi(argv[2]); } if (pthread_create(&threadid, 0, poll_thread, 0)) { perror("pthread"); return 1; } work(); return 0; }
1
#include <pthread.h> int cont = 1; pthread_cond_t gate; pthread_cond_t S; pthread_mutex_t cont_mutex; int a = 0; void le_entrada(char** args, long int* N, int* threads){ *N = (long int) strtol(args[1], (char**) 0, 10); *threads = (int) strtol(args[2], (char**) 0, 10); } void *Semaphoro(void *v){ int id = (int) v; pthread_mutex_lock(&cont_mutex); pthread_cond_wait(&gate, &cont_mutex); pthread_cond_wait(&S, &cont_mutex); cont--; if(cont > 0){ pthread_cond_signal(&gate); } pthread_cond_signal(&S); pthread_mutex_unlock(&cont_mutex); a += (id + 1); pthread_mutex_lock(&cont_mutex); pthread_cond_wait(&S, &cont_mutex); cont++; if(cont == 1){ pthread_cond_signal(&gate); } pthread_cond_signal(&S); pthread_mutex_unlock(&cont_mutex); } void main(int x, char** args){ long int N; int threads, i; double tempo; double* vetor; le_entrada(args, &N, &threads); pthread_t t[threads]; pthread_cond_init(&gate, 0); pthread_cond_init(&S, 0); pthread_mutex_init(&cont_mutex, 0); srand(time(0)); vetor = (double*) malloc(sizeof(double)*N); tempo = omp_get_wtime(); omp_set_num_threads(threads); for(i=0; i<threads; i++){ pthread_create(&t[i], 0, Semaphoro, (void *) i); } for(i=0; i<threads; i++){ pthread_join(t[i], 0); } tempo = omp_get_wtime() - tempo; printf("%d\\n", a); pthread_cond_destroy(&gate); pthread_cond_destroy(&S); pthread_exit (0); }
0
#include <pthread.h> void error(char *msg){ fprintf(stderr, "%s: %s\\n", msg, strerror(errno)); exit(1); } pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; int beers = 200000000; void* drink_lots(void *a){ int i; pthread_mutex_lock(&beers_lock); for (i = 0; i< 10000000; i++){ beers = beers -1; } printf("beers = %i\\n", beers); pthread_mutex_unlock(&beers_lock); return 0; } int main(){ pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n",beers, beers); for (t = 0; t < 20; t++){ pthread_create(&threads[t], 0, drink_lots, 0); } void* result; for (t = 0; t < 20; t++){ pthread_join(threads[t], &result); } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started...\\n"); pause(); return (0); } void printErrMsg(char *str, int err) { printf("%s:%s\\n", str, strerror(err)); exit(1); } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) { printErrMsg("can't install fork handlers", err); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { printErrMsg("can't create thread", err); } sleep(5); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) { printf("fork failed\\n"); exit(1); } else if (0 == pid) { printf("child returned from fork\\n"); } else { printf("parent returned from fork\\n"); } exit(0); }
0
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
1
#include <pthread.h> int a; pthread_mutex_t mutex_a; pthread_cond_t cond; int end_state; } incrementer_data_t; void *incrementer_work(void *args); void *incrementer2_work(void *args); int main(int argc, char **argv) { incrementer_data_t incr_in_data; incr_in_data.a = 0; incr_in_data.end_state = 0; if (pthread_mutex_init(&incr_in_data.mutex_a, 0) != 0) { fprintf(stderr, "MASTER: Error on pthread_mutex_init\\n"); exit(1); } if (pthread_cond_init(&incr_in_data.cond, 0) != 0) { fprintf(stderr, "MASTER: Error on pthread_mutex_init\\n"); exit(1); } pthread_attr_t incrementer_attr; if (pthread_attr_init(&incrementer_attr) != 0) { fprintf(stderr, "MASTER: Error on pthread_attr_init\\n"); exit(1); } pthread_attr_setdetachstate(&incrementer_attr, PTHREAD_CREATE_JOINABLE); pthread_attr_t incrementer2_attr; if (pthread_attr_init(&incrementer2_attr) != 0) { fprintf(stderr, "MASTER: Error on pthread_attr_init\\n"); exit(1); } pthread_attr_setdetachstate(&incrementer2_attr, PTHREAD_CREATE_JOINABLE); pthread_t incrementer_thread; if (pthread_create(&incrementer_thread, &incrementer_attr, &incrementer_work, &incr_in_data) != 0) { fprintf(stderr, "MASTER: Error on pthread_create\\n"); exit(1); } pthread_t incrementer2_thread; if (pthread_create(&incrementer2_thread, &incrementer2_attr, &incrementer2_work, &incr_in_data) != 0) { fprintf(stderr, "MASTER: Error on pthread_create\\n"); exit(1); } pthread_attr_destroy(&incrementer_attr); pthread_attr_destroy(&incrementer2_attr); void *incr_out_data = 0; if (pthread_join(incrementer2_thread, &incr_out_data) != 0) { fprintf(stderr, "MASTER: Error on pthread_join (incrementer)\\n"); exit(1); } if (pthread_join(incrementer_thread, &incr_out_data) != 0) { fprintf(stderr, "MASTER: Error on pthread_join (incrementer)\\n"); exit(1); } pthread_mutex_destroy(&incr_in_data.mutex_a); pthread_cond_destroy(&incr_in_data.cond); printf("The work is done, a = %d\\n", incr_in_data.a); exit(0); } void *incrementer_work(void *args) { incrementer_data_t *data = args; for ( ; ; ) { pthread_mutex_lock(&data->mutex_a); data->a++; if (data->a == 9) pthread_cond_signal(&data->cond); if (data->end_state == 1) { pthread_mutex_unlock(&data->mutex_a); break; } pthread_mutex_unlock(&data->mutex_a); } return 0; } void *incrementer2_work(void *args) { incrementer_data_t *data = args; pthread_mutex_lock(&data->mutex_a); pthread_cond_wait(&data->cond, &data->mutex_a); printf("T2 a = %d\\n", data->a); data->a++; printf("T2 a++ = %d\\n", data->a); data->end_state = 1; pthread_mutex_unlock(&data->mutex_a); return 0; }
0
#include <pthread.h> extern pthread_mutex_t mutexLock[10]; extern volatile int condition_variable; extern pthread_barrier_t activation; extern pthread_barrier_t completion; void timespec_diff(struct timespec* time1, struct timespec* time2,struct timespec* res) { long tmp; if(time1->tv_sec < time2->tv_sec) { res->tv_sec = time2->tv_sec - time1->tv_sec - 1; tmp = time2->tv_nsec + (999999999 - time1->tv_nsec); if(tmp > 999999999) { res->tv_nsec = tmp%1000000000; res->tv_sec++; } else res->tv_nsec = tmp; } else { res->tv_sec = 0; res->tv_nsec = time2->tv_nsec - time1->tv_nsec; } } void periodic_task(void* data) { struct task_struct_t* task; struct timespec time1,time2,time3,rem,sleep_time; int loop_var = 0; int flag = 0; long int time_msec = 0; task = (struct task_struct_t*)data; pthread_barrier_wait(&activation); while( condition_variable ) { flag = 0; clock_gettime(CLOCK_MONOTONIC ,&time1); task->currpos = task->start; while(task->currpos != 0) { if(task->currpos->type == 'C') for(loop_var = 0;loop_var < task->currpos->work;loop_var++); else if(task->currpos->type == 'L'){ pthread_mutex_lock(&mutexLock[task->currpos->work] ); } else{ pthread_mutex_unlock(&mutexLock[task->currpos->work]); } task->currpos = task->currpos->next; } clock_gettime(CLOCK_MONOTONIC,&time2); timespec_diff(&time1,&time2,&time3); time_msec = (time3.tv_sec * 1000 + time3.tv_nsec/1000000); if(time_msec > task->period_event){ flag = 1; } if(!flag) { sleep_time.tv_sec = (task->period_event / 1000); sleep_time.tv_nsec = (task->period_event %1000) * 1000000; timespec_diff(&time3,&sleep_time,&rem); nanosleep(&rem,&time3); } } pthread_barrier_wait(&completion); } void event_task(void* data) { struct task_struct_t* task; sigset_t set; int sig; int loop_var; task = (struct task_struct_t*)data; sigemptyset(&set); sigaddset(&set,SIGUSR1); pthread_sigmask(SIG_BLOCK,&set,0); register_for_event(pthread_self(),task->period_event); pthread_barrier_wait(&activation); do { sigwait(&set,&sig); if(!condition_variable) break; task->currpos = task->start; while(task->currpos != 0) { if(task->currpos->type == 'C') for(loop_var = 0;loop_var < task->currpos->work;loop_var++); else if(task->currpos->type == 'L'){ pthread_mutex_lock(&mutexLock[task->currpos->work] ); } else{ pthread_mutex_unlock(&mutexLock[task->currpos->work]); } task->currpos = task->currpos->next; } }while(condition_variable); pthread_barrier_wait(&completion); }
1
#include <pthread.h> const int MAX_THREADS = 1024; long long number_of_tosses; long long number_in_circle; long thread_count; pthread_mutex_t mutex; void Get_args(int argc, char* argv[]); void Usage(char* prog_name); void* Compute_number_in_circle(); double randfrom(double min, double max); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; Get_args(argc, argv); pthread_mutex_init(&mutex, 0); thread_handles = malloc (thread_count * sizeof ( pthread_t) ); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, Compute_number_in_circle, (void*) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } long long int total_number_of_tosses = number_of_tosses * thread_count; double pi = (4 * number_in_circle) / ((double) total_number_of_tosses); printf("\\nPie estimate using Monte Carlo method: %f\\n\\n", pi); free(thread_handles); return 0; } void* Compute_number_in_circle(void* rank) { long my_rank = (long) rank; long long int toss; double x, y, distance_squared; srand(time(0)); long long int local_number_in_circle; for (toss = 0; toss < number_of_tosses; toss++) { x = randfrom(-1.0, 1.0); y = randfrom(-1.0, 1.0); distance_squared = pow(x, 2.0) + pow(y, 2.0); if (distance_squared <= 1.0) { local_number_in_circle++; } } pthread_mutex_lock(&mutex); number_in_circle += local_number_in_circle; pthread_mutex_unlock(&mutex); printf("\\nThread %ld > Out of %lld number of tosses, %lld were in the circle.\\n", my_rank, number_of_tosses, local_number_in_circle); return 0; } double randfrom(double min, double max) { double range = (max - min); double div = 32767 / range; return min + (rand() / div); } void Get_args(int argc, char* argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); number_of_tosses = strtoll(argv[2], 0, 10); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <number of tosses>\\n", prog_name); exit(0); }
0
#include <pthread.h> static int count; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *func_1(void* args) { while(1){ pthread_mutex_lock(&mutex); sleep(1); count++; printf("this is func_1, count %d!\\n",count); pthread_mutex_unlock(&mutex); } } void *func_2(void* args) { while(1){ pthread_mutex_lock(&mutex); sleep(1); count++; printf("this is func_2!, count %d\\n", count); pthread_mutex_unlock(&mutex); } } int main(int argc, char **argv) { pthread_t pid1, pid2; pid_t pid; if(pthread_create(&pid1, 0, func_1, 0)) { return -1; } if(pthread_create(&pid2, 0, func_2, 0)) { return -1; } while(1){ sleep(3); } pthread_join(pid2, 0); if ((pid=fork()) == 0) { sleep(1); count++; printf("count in child process %d(PPID %d) is %d\\n", getpid(), getppid(), count); } else { count+=100; printf("count+100 in parent process %d(PPID %d) is %d\\n", getpid(), getppid(), count); wait(0); } printf("Process %d end of main\\n", getpid()); return 0; }
1
#include <pthread.h> int numRefeicoes = 0; pthread_mutex_t palitos[5]; pthread_mutex_t mut_comida; void meditar(){ sleep (1 + rand() % 2); } void pegarPalito(long id, long palito){ pthread_mutex_lock(&palitos[palito]); printf("Filosofo %ld, pegou palito %ld.\\n", id, palito); } void soltarPalito(long id, long palito){ pthread_mutex_unlock(&palitos[palito]); printf("Filosofo %ld, soltou palito %ld.\\n", id, palito); } int pegarPalitos(long id, long palito_esq, long palito_dir){ int esq = pthread_mutex_trylock(&palitos[palito_esq]); int dir = pthread_mutex_trylock(&palitos[palito_dir]); if(dir == 0 && esq == 0) return 1; if(esq == 0) pthread_mutex_unlock(&palitos[palito_esq]); if(dir == 0) pthread_mutex_unlock(&palitos[palito_dir]); return 0; } void soltarPalitos(long id, long palito_esq, long palito_dir){ pthread_mutex_unlock(&palitos[palito_esq]); pthread_mutex_unlock(&palitos[palito_dir]); } void comer(long id){ pthread_mutex_lock(&mut_comida); printf("Filosofo %ld, esta comendo.\\n", id); numRefeicoes++; pthread_mutex_unlock(&mut_comida); } void *filosofo(void *num){ long id = (long) num; long palito_esq = id; long palito_dir = (id + 1) % 5; while(1){ if(pegarPalitos(id, palito_esq, palito_dir)){ comer(id); soltarPalitos(id, palito_esq, palito_dir); meditar(); } } } int main (){ int i; pthread_t threads[5]; pthread_mutex_init (&mut_comida, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&palitos[i], 0); for (i = 0; i < 5; i++) pthread_create (&threads[i], 0, filosofo, (void *)i); while(1){ sleep(1); pthread_mutex_lock (&mut_comida); printf ("Refeições por segundo: %d\\n", numRefeicoes) ; numRefeicoes = 0 ; pthread_mutex_unlock (&mut_comida); } }
0
#include <pthread.h> struct { pthread_mutex_t mutex; pthread_cond_t cond; int buff[10]; int nitems; } shared = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; void* produce(void* arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nitems >= 10000000) { pthread_cond_signal(&shared.cond); pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[*((int*) arg)]++; shared.nitems++; pthread_mutex_unlock(&shared.mutex); } } void* consume(void* arg) { pthread_mutex_lock(&shared.mutex); while (shared.nitems < 10000000) pthread_cond_wait(&shared.cond, &shared.mutex); pthread_mutex_unlock(&shared.mutex); int i; for (i = 0; i < 10; ++i) printf("buff[%d] = %d\\n", i, shared.buff[i]); return 0; } int main() { int i; pthread_t produce_threads[10]; pthread_t consume_thread; for (i = 0; i < 10; ++i) pthread_create(&produce_threads[i], 0, produce, &i); pthread_create(&consume_thread, 0, consume, 0); for (i = 0; i < 10; ++i) pthread_join(produce_threads[i], 0); pthread_join(consume_thread, 0); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *double_inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. \\n", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(2); } pthread_exit(0); } void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. \\n", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); 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_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, double_inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_once_t once = PTHREAD_ONCE_INIT; pthread_key_t key; void thread_init(void) { pthread_key_create(&key,free); } char *my_getenv3( const char *name ) { char *cp; int namelen,envirlen,i; extern char **environ; pthread_once(&once,thread_init); pthread_mutex_lock(&mutex); cp = (char *)pthread_getspecific(key); if (cp == 0){ cp = malloc(4096); if ( cp == 0 ){ pthread_mutex_unlock(&mutex); return 0; } pthread_setspecific(key,cp); } namelen = strlen(name); for (i = 0; environ[i] != 0;i++){ if (strncmp(name,environ[i],namelen) == 0 && environ[i][namelen] == '='){ envirlen = strlen(&environ[i][namelen+1]); if (envirlen >= 4096){ pthread_mutex_unlock(&mutex); return 0; } strcpy(cp,&environ[i][namelen+1]); pthread_mutex_unlock(&mutex); return cp; } } pthread_mutex_unlock(&mutex); return 0; } void * thr1_func( void *arg ) { printf("%s\\n",my_getenv3("HOME")); printf("thread 1 locale buffer:0x%lx\\n",pthread_getspecific(key)); sleep(1); pthread_exit((void *)0); } void * thr2_func( void *arg ) { char buf[1024]; printf("%s\\n",my_getenv3("PATH")); printf("thread 2 locale buffer:0x%lx\\n",pthread_getspecific(key)); sleep(1); pthread_exit((void *)0); } int main(void) { pthread_t tid1,tid2; for (;;){ pthread_create(&tid1,0,thr1_func,0); pthread_create(&tid2,0,thr2_func,0); } exit(0); }
1
#include <pthread.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int avail = 0; static int data = 0; static void *producer(void *arg) { int cnt = *((int *)arg); int j, ret; for (j = 0; j < cnt; j++) { sleep(1); pthread_mutex_lock(&mtx); avail++; data++; pthread_mutex_unlock(&mtx); ret = pthread_cond_signal(&cond); if (ret != 0) perror("pthread_cond_signal"); } return 0; } static void *consumer1(void *arg) { int ret, numConsumed = 0; Boolean done = FALSE; int totRequired = 10; for (;;) { pthread_mutex_lock(&mtx); while (avail == 0) { ret = pthread_cond_wait(&cond, &mtx); if (ret != 0) perror("pthread_cond_wait"); } numConsumed++; avail--; printf("unit Consumed by consumer1=%d\\n", data); done = numConsumed >= totRequired; pthread_mutex_unlock(&mtx); if (done) break; } } static void *consumer2(void *arg) { int ret, numConsumed = 0; Boolean done = FALSE; int totRequired = 10; for (;;) { pthread_mutex_lock(&mtx); while (avail == 0) { ret = pthread_cond_wait(&cond, &mtx); if (ret != 0) perror("pthread_cond_wait"); } numConsumed++; avail--; printf("unit Consumed by consumer2=%d\\n", data); done = numConsumed >= totRequired; pthread_mutex_unlock(&mtx); if (done) break; } } int main() { pthread_t tid; int ret, j; int totRequired = 10; ret = pthread_create(&tid, 0, producer, &totRequired); if (ret != 0) perror("pthread_create: "); ret = pthread_create(&tid, 0, consumer1, 0); if (ret != 0) perror("pthread_create: "); ret = pthread_create(&tid, 0, consumer2, 0); if (ret != 0) perror("pthread_create: "); pthread_exit(0); exit(0); }
0
#include <pthread.h> static void assert_rw(struct lock_object *lock, int what) { rw_assert((struct rwlock *)lock, what); } struct lock_class lock_class_rw = { .lc_name = "rw", .lc_flags = LC_SLEEPLOCK | LC_RECURSABLE | LC_UPGRADABLE, .lc_assert = assert_rw, }; void rw_sysinit(void *arg) { struct rw_args *args = arg; rw_init(args->ra_rw, args->ra_desc); } void rw_init_flags(struct rwlock *rw, const char *name, int opts) { pthread_mutexattr_t attr; int flags; MPASS((opts & ~(RW_DUPOK | RW_NOPROFILE | RW_NOWITNESS | RW_QUIET | RW_RECURSE)) == 0); ASSERT_ATOMIC_LOAD_PTR(rw->rw_lock, ("%s: rw_lock not aligned for %s: %p", __func__, name, &rw->rw_lock)); flags = LO_UPGRADABLE; if (opts & RW_DUPOK) flags |= LO_DUPOK; if (opts & RW_NOPROFILE) flags |= LO_NOPROFILE; if (!(opts & RW_NOWITNESS)) flags |= LO_WITNESS; if (opts & RW_RECURSE) flags |= LO_RECURSABLE; if (opts & RW_QUIET) flags |= LO_QUIET; lock_init(&rw->lock_object, &lock_class_rw, name, 0, flags); pthread_mutexattr_init(&attr); pthread_mutex_init(&rw->rw_lock, &attr); } void rw_destroy(struct rwlock *rw) { pthread_mutex_destroy(&rw->rw_lock); } void _rw_wlock(struct rwlock *rw, const char *file, int line) { pthread_mutex_lock(&rw->rw_lock); } int _rw_try_wlock(struct rwlock *rw, const char *file, int line) { return (!pthread_mutex_trylock(&rw->rw_lock)); } void _rw_wunlock(struct rwlock *rw, const char *file, int line) { pthread_mutex_unlock(&rw->rw_lock); } void _rw_rlock(struct rwlock *rw, const char *file, int line) { pthread_mutex_lock(&rw->rw_lock); } int _rw_try_rlock(struct rwlock *rw, const char *file, int line) { return (!pthread_mutex_trylock(&rw->rw_lock)); } void _rw_runlock(struct rwlock *rw, const char *file, int line) { pthread_mutex_unlock(&rw->rw_lock); } int _rw_try_upgrade(struct rwlock *rw, const char *file, int line) { return (0); } void _rw_downgrade(struct rwlock *rw, const char *file, int line) { }
1
#include <pthread.h> int buffer[102400]; int in=0; int out=0; pthread_mutex_t lock; void Producer() { while(1) { int item=rand()%100; if(in==102400 -1) break; else { pthread_mutex_lock(&lock); buffer[in++]=item; pthread_mutex_unlock(&lock); } } } void Consumer() { while(1) { int item; if(out==102400 -1) break; else { pthread_mutex_lock(&lock); item=buffer[out++]; pthread_mutex_unlock(&lock); } } } int main() { int i,err; pthread_t threads[2]; for(i=0;i<2;i++) { if(i==0) err=pthread_create(&threads[i],0,Producer,0); else err=pthread_create(&threads[i],0,Consumer,0); sleep(2); } for(i=0;i<2;i++) { pthread_join(threads[i],0); } return 0; }
0
#include <pthread.h> static char envbuf[ARG_MAX]; extern char **environ; char *getenv(const char *name) { int i, len; len = strlen(name); for(i = 0; environ[i] != 0; ++i) { if( (strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len + 1], sizeof(envbuf)); return envbuf; } } return 0; } pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for(i = 0; environ[i] != 0; ++i) { if( (strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len + 1]); if(olen >= buflen) { pthread_mutex_unlock(&env_mutex); return ENOSPC; } strncpy(buf, &environ[i][len + 1], buflen); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return ENOENT; } char *pathnames[] = {"PATH", "HOME"}; void *thr_fn_r(void *arg) { pthread_t tid = pthread_self(); long i = (long)arg; char *name = pathnames[i % 2]; char envbuf[ARG_MAX]; if(getenv_r(name, envbuf, sizeof(envbuf)) == 0) printf("thread: %ld, i: %ld, pathname: %s, env: %s\\n", tid, i, name, envbuf); else printf("can't not get env for thread: %ld, pathname: %s\\n", tid, name); return (void *)0; } void *thr_fn(void *arg) { pthread_t tid = pthread_self(); long i = (long)arg; char *name = pathnames[i % 2]; printf("thread: %ld, i: %ld, pathname: %s, env: %s\\n", tid, i, name, getenv(name)); return (void *)0; } int main(void) { long i; pthread_t tid; printf("not support multi threads...\\n"); for(i = 0; i < 10; ++i) { pthread_create(&tid, 0, thr_fn, (void *)i); } sleep(1); printf("support multi threads...\\n"); for(i = 0; i < 10; ++i) { pthread_create(&tid, 0, thr_fn_r, (void *)i); } while(1) sleep(1); return 0; }
1
#include <pthread.h> struct h2x_thread* h2x_thread_new(struct h2x_options* options, void *(*start_routine)(void *), uint32_t thread_id) { struct h2x_thread* thread = malloc(sizeof(struct h2x_thread)); thread->options = options; thread->thread_id = thread_id; thread->epoll_fd = 0; thread->new_connections = 0; atomic_init(&thread->should_quit, 0); thread->new_requests = 0; thread->finished_connection_lock = 0; thread->finished_connections = 0; for(uint32_t i = 0; i < H2X_ICT_COUNT; ++i) { thread->intrusive_chains[i] = 0; } thread->epoll_fd = epoll_create1(0); if(thread->epoll_fd == -1) { H2X_LOG(H2X_LOG_LEVEL_FATAL, "Unable to create epoll instance"); goto CLEANUP_THREAD; } if(pthread_mutex_init(&thread->new_data_lock, 0)) { H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to initialize thread %u new connections mutex, errno = %d", thread_id, (int) errno); goto CLEANUP_EPOLL; } pthread_attr_t thread_attr; if(pthread_attr_init(&thread_attr)) { H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to initialize thread %u thread attributes, errno = %d", thread_id, (int) errno); goto CLEANUP_MUTEX; } if(pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE)) { H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to make thread %u joinable, errno = %d", thread_id, (int) errno); goto CLEANUP_THREAD_ATTR; } if(!pthread_create(&thread->thread, 0, start_routine, thread)) { H2X_LOG(H2X_LOG_LEVEL_INFO, "Successfully created thread %u", thread_id); return thread; } H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to create thread %u, errno = %d", thread_id, (int) errno); CLEANUP_THREAD_ATTR: pthread_attr_destroy(&thread_attr); CLEANUP_MUTEX: pthread_mutex_destroy(&thread->new_data_lock); CLEANUP_EPOLL: close(thread->epoll_fd); CLEANUP_THREAD: free(thread); return 0; } void h2x_thread_set_finished_connection_channel(struct h2x_thread* thread, pthread_mutex_t* finished_connection_lock, struct h2x_connection** finished_connections) { thread->finished_connection_lock = finished_connection_lock; thread->finished_connections = finished_connections; } void h2x_thread_cleanup(struct h2x_thread* thread) { assert(thread->new_connections == 0); pthread_mutex_destroy(&thread->new_data_lock); free(thread); } int h2x_thread_add_connection(struct h2x_thread* thread, struct h2x_connection *connection) { if (thread == 0 || connection == 0) { return -1; } struct epoll_event event; event.data.ptr = connection; event.events = EPOLLIN | EPOLLET | EPOLLPRI | EPOLLERR | EPOLLOUT | EPOLLRDHUP | EPOLLHUP; int ret_val = epoll_ctl(thread->epoll_fd, EPOLL_CTL_ADD, connection->fd, &event); if (ret_val == -1) { H2X_LOG(H2X_LOG_LEVEL_INFO, "Unable to register connection %d with thread %u epoll instance", connection->fd, thread->thread_id); return -1; } return 0; } int h2x_thread_poll_new_requests_and_connections(struct h2x_thread* thread, struct h2x_connection** new_connections, struct h2x_request** new_requests) { *new_connections = 0; if(pthread_mutex_lock(&thread->new_data_lock)) { H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to lock thread %u state in order to poll new connections, errno = %d", thread->thread_id, (int) errno); return -1; } *new_connections = thread->new_connections; thread->new_connections = 0; *new_requests = thread->new_requests; thread->new_requests = 0; pthread_mutex_unlock(&thread->new_data_lock); return 0; } int h2x_thread_poll_quit_state(struct h2x_thread* thread, bool* quit_state) { *quit_state = atomic_load(&thread->should_quit); return 0; } int h2x_thread_add_request(struct h2x_thread* thread, struct h2x_request* request) { if (thread == 0 || request == 0) { return -1; } if(pthread_mutex_lock(&thread->new_data_lock)) { H2X_LOG(H2X_LOG_LEVEL_ERROR, "Failed to lock thread %u state in order to add request to connection %d, errno = %d", thread->thread_id, request->connection->fd, (int) errno); return -1; } H2X_LOG(H2X_LOG_LEVEL_INFO, "Adding new request for connection %d to thread %u", request->connection->fd, thread->thread_id); request->next = thread->new_requests; thread->new_requests = request; pthread_mutex_unlock(&thread->new_data_lock); return 0; }
0
#include <pthread.h> int available_resources = 5; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *partC(void*); void *partA(void*); int increase_count(int); int decrease_count(int); int main(int argc, char *argv[]){ if (argc != 2){ printf("incorrect number of arguments."); return -1; } int num_threads = atoi(argv[1]); char letter; printf("a or c?"); scanf("%c", &letter); if (letter == 'a'){ printf("A. The data involved in the race condition is the available_resources variable.\\n" "It is global data shared between the threads.\\n" "Its access should be controlled with a semaphore.\\n"); printf("B. The race condition occurs whenever processes try to modify the available_resources\\n" "variable without ensuring that it is locked away from other processes." "\\n ie. in the increase_count and decrease_count functions. \\n"); int i = 0; int resources_requested = 0; pthread_t threads[num_threads]; pthread_attr_t threadAttributes; pthread_attr_init(&threadAttributes); for(i=0;i<num_threads;i++){ resources_requested = (rand()%5)+1; pthread_create(&threads[i],&threadAttributes,partA,(void *)resources_requested); } for(i=0;i<num_threads;i++){ pthread_join(threads[i],0); } pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; } if (letter == 'c'){ int i = 0; int resources_requested = 0; pthread_t threads[num_threads]; pthread_attr_t threadAttributes; pthread_attr_init(&threadAttributes); for(i=0;i<num_threads;i++){ resources_requested = (rand()%5)+1; pthread_create(&threads[i],&threadAttributes,partC,(void *)resources_requested); } for(i=0;i<num_threads;i++){ pthread_join(threads[i],0); } pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; } } void* partA(void *resources){ decrease_count((int)resources); printf("Taking %d resources current count = %d\\n",(int)resources,(int)available_resources); sleep(rand()%5); increase_count((int)resources); printf("Returning %d resources current count = %d\\n",(int)resources,(int)available_resources); pthread_exit(0); } void* partC(void *resources){ while(1){ pthread_mutex_lock(&mutex); if((int)available_resources<(int)resources){ pthread_mutex_unlock(&mutex); } else{ decrease_count((int)resources); printf("Taking %d resources current count = %d\\n",(int)resources,(int)available_resources); pthread_mutex_unlock(&mutex); break; } } sleep(rand()%5); pthread_mutex_lock(&mutex); increase_count((int)resources); printf("Returning %d resources current count = %d\\n",(int)resources,(int)available_resources); pthread_mutex_unlock(&mutex); pthread_exit(0); } int increase_count(int count){ available_resources = available_resources + count; return 0; } int decrease_count(int count){ if (available_resources < count){ return -1; } available_resources = available_resources - count; return 0; }
1
#include <pthread.h> FILE *compras; { int id_cliente; int id_compra; }peticion_t; { int pos_lectura; int pos_escritura; int num_peticiones; peticion_t peticiones[5]; }buffer_peticiones_t; buffer_peticiones_t bufferPeticiones; buffer_peticiones_t bufferPrioridad; pthread_mutex_t mutex; pthread_mutex_t mutexPrioridad; pthread_cond_t normales; pthread_cond_t prioritarios; void buffer_inicializar(buffer_peticiones_t* buffer_peticiones) { buffer_peticiones->pos_lectura = 0; buffer_peticiones->pos_escritura = 0; buffer_peticiones->num_peticiones = 0; } int buffer_lleno(buffer_peticiones_t* buffer_peticiones) { if (buffer_peticiones->num_peticiones == 5) return 1; else return 0; } int buffer_vacio(buffer_peticiones_t* buffer_peticiones) { if (buffer_peticiones->num_peticiones == 0) return 1; else; return 0; } void buffer_encolar(buffer_peticiones_t* buffer,pthread_mutex_t* mutex, pthread_cond_t* cond, peticion_t* peticion) { pthread_mutex_lock(mutex); while (buffer_lleno(buffer) == 1) pthread_cond_wait(cond, mutex); buffer->peticiones[buffer->pos_escritura] = *peticion; buffer->pos_escritura = ((buffer->pos_escritura + 1) % 5); buffer->num_peticiones++; pthread_mutex_unlock(mutex); } void buffer_peticiones_atender(buffer_peticiones_t* buffer_peticiones, buffer_peticiones_t* buffer_prioridad, peticion_t* peticion) { pthread_mutex_lock(&mutexPrioridad); if (buffer_vacio(buffer_prioridad) == 0) { *peticion = buffer_prioridad->peticiones[buffer_prioridad->pos_lectura]; buffer_prioridad->pos_lectura = ((buffer_prioridad->pos_lectura + 1) % 5); buffer_prioridad->num_peticiones = buffer_prioridad->num_peticiones - 1; pthread_cond_signal(&prioritarios); fprintf(compras, "Id compra: %d; Id comprador: %d \\n", peticion->id_compra, peticion->id_cliente); } pthread_mutex_unlock(&mutexPrioridad); pthread_mutex_lock(&mutex); if ((buffer_vacio(buffer_prioridad) == 1)&&(buffer_vacio(buffer_peticiones) == 0)) { *peticion = buffer_peticiones->peticiones[buffer_peticiones->pos_lectura]; buffer_peticiones->pos_lectura = ((buffer_peticiones->pos_lectura + 1) % 5); buffer_peticiones->num_peticiones = buffer_peticiones->num_peticiones - 1; pthread_cond_signal(&normales); fprintf(compras, "Id compra: %d; Id comprador: %d \\n", peticion->id_compra, peticion->id_cliente); } pthread_mutex_unlock(&mutex); } void* consumer_function(int thread_id) { peticion_t peticion_recibida; while (1) { buffer_peticiones_atender(&bufferPeticiones, &bufferPrioridad, &peticion_recibida); if((peticion_recibida.id_cliente == 0) && (peticion_recibida.id_compra == 0)) break; } fclose(compras); pthread_exit(0); } void* producer_function(int thread_id) { int pid = (int)getpid(); int i, aleatorio; peticion_t peticion; srand(time(0) + getpid()); for (i = 1; i <= 100; i++) { aleatorio = rand() % 3; peticion.id_compra = i; peticion.id_cliente = thread_id; if (aleatorio == 0) buffer_encolar(&bufferPrioridad,&mutexPrioridad,&prioritarios, &peticion); else buffer_encolar(&bufferPeticiones,&mutex,&normales, &peticion); } pthread_exit(0); } int main(int argc, char** argv) { if(argc != 2) { printf("%s Numero de clients erroni\\n", argv[0]); return 1; } long int i; int numero_clientes = atoi(argv[1]); pthread_t consumer[1]; pthread_t *producer; producer = (pthread_t*) malloc (numero_clientes*sizeof(pthread_t)); buffer_inicializar(&bufferPeticiones); buffer_inicializar(&bufferPrioridad); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutexPrioridad, 0); pthread_cond_init(&normales, 0); pthread_cond_init(&prioritarios, 0); for (i = 0; i < numero_clientes; i++) pthread_create(producer+i, 0, (void* (*)(void*))producer_function,(void*)(i)); compras = fopen("compras.txt", "w"); if (compras == 0) perror("Error al abrir el fichero"); for (i = 0; i < 1; i++) pthread_create(consumer+i, 0, (void* (*)(void*))consumer_function,(void*)(i)); for(i = 0; i < numero_clientes; i++) pthread_join(producer[i], 0); peticion_t final; final.id_cliente = 0; final.id_compra = 0; buffer_encolar(&bufferPeticiones,&mutex,&normales, &final); for(i = 0; i < 1; i++) pthread_join(consumer[i], 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&normales); pthread_mutex_destroy(&mutexPrioridad); pthread_cond_destroy(&prioritarios); free(producer); return 0; }
0
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done=PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex=PTHREAD_MUTEX_INITIALIZER; extern char** environ; static void thread_init() { pthread_key_create(&key,free); } char* getenv(const char* name) { int i,len; char* envbuf; pthread_once(&init_done,thread_init); pthread_mutex_lock(&env_mutex); envbuf=(char*)pthread_getspecific(key); if(envbuf==0) { envbuf=malloc(1024); if(envbuf==0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(&key,envbuf); } len=strlen(name); for(int i=0;environ[i]!=0;i++) { if((strncmp(name,environ[i],len)==0)&&environ[i][len]=='=') { strncpy(envbuf,environ[i]+1,1023); pthread_mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
1
#include <pthread.h> pthread_mutex_t lock_x; void StartThread(int cs, pthread_mutex_t lock) { pthread_t pt; int* arg = malloc(sizeof(*arg)); if(arg == 0) { fprintf(stderr, "Couldn't Allocate memeory for thread argument.\\n"); exit(1); } else { *arg = cs; lock_x = lock; } int thread_return; thread_return = pthread_create(&pt, 0, thread_server, arg); if(thread_return) { fprintf(stderr, "Error - pthread_create() return code: %d\\n", thread_return); exit(1); } } void *thread_server(void *csock_ptr) { int cs; cs = *((int *) csock_ptr); HandleClient(cs); free(csock_ptr); } void HandleClient(int cs) { char message[1000]; int READSIZE; int auth = 0; char * clientName; pid_t tid = syscall(__NR_gettid); printf("Authenticating User %d\\n", tid); char *username = HandleAuth(cs); char *password; if(strcmp(username, "") == 0) { auth = 0; printf("Invalid username\\\\password\\n"); } else { strtok_r(username, " ", &password); auth = Authenticate(username, password); } printf("Authentication Result: %d (TRUE=1/FALSE=0)\\n", auth); Authenticated(auth, cs); while(auth) { printf("User: %s Logged In", username); Log(username, "Logged In"); pthread_mutex_lock(&lock_x); char *filepath = HandleFileTransfer(cs); pthread_mutex_unlock(&lock_x); if(strcmp(filepath, "Quit") == 0) { close(cs); break; } if(filepath != 0) { printf("User: %s\\nFile: %s\\nTimestamp: %s\\n", username, filepath, GetDate()); LogEntry(username, filepath, GetDate()); free(filepath); } else { Log(username, "Failed to transfer files"); } } if(auth == 0) { Log(username, "User Failed to Authenticate"); } }
0
#include <pthread.h> pthread_mutex_t buffer_mutex, bounded_queue_mutex; int buffer_space_error = 0; int fill = 0, pages_downloaded = 0; char buffer[100][50]; char *fetch(char *link) { pthread_mutex_lock(&bounded_queue_mutex); if(pages_downloaded == 1) { pthread_mutex_unlock(&bounded_queue_mutex); sleep(5); } else pthread_mutex_unlock(&bounded_queue_mutex); int fd = open(link, O_RDONLY); if (fd < 0) { fprintf(stderr, "failed to open file: %s", link); return 0; } int size = lseek(fd, 0, 2); assert(size >= 0); char *buf = Malloc(size+1); buf[size] = '\\0'; assert(buf); lseek(fd, 0, 0); char *pos = buf; while(pos < buf+size) { int rv = read(fd, pos, buf+size-pos); assert(rv > 0); pos += rv; } pthread_mutex_lock(&bounded_queue_mutex); pages_downloaded++; pthread_mutex_unlock(&bounded_queue_mutex); close(fd); return buf; } void edge(char *from, char *to) { if(!from || !to) return; char temp[50]; temp[0] = '\\0'; char *fromPage = parseURL(from); char *toPage = parseURL(to); strcpy(temp, fromPage); strcat(temp, "->"); strcat(temp, toPage); strcat(temp, "\\n"); pthread_mutex_lock(&buffer_mutex); strcpy(buffer[fill++], temp); pthread_mutex_unlock(&buffer_mutex); pthread_mutex_lock(&bounded_queue_mutex); if(pages_downloaded == 1 && fill > 3) buffer_space_error = 1; pthread_mutex_unlock(&bounded_queue_mutex); } int main(int argc, char *argv[]) { pthread_mutex_init(&buffer_mutex, 0); pthread_mutex_init(&bounded_queue_mutex, 0); int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/small_buffer/pagea", 1, 1, 1, fetch, edge); assert(rc == 0); check(buffer_space_error == 0, "Shouldn't be possible to put multiple links inside buffer as buffer has only 1 space\\n"); return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/small_buffer.out"); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void test_filelock(int locktimes) { struct flock lock, unlock; int count = 0; int fd; lock.l_type = F_WRLCK; lock.l_start = 0; lock.l_whence = 0; lock.l_len = 1; unlock.l_type = F_ULOCK; unlock.l_start = 0; unlock.l_whence = 0; unlock.l_len = 1; fd = open("lock.test", O_CREAT); for (count = 0; count < locktimes; ++count){ fcntl(fd, F_SETLKW, &lock); fcntl(fd, F_SETLKW, &unlock); } } void test_pthread_lock(int locktimes) { int i; for (i = 0; i < locktimes; ++i){ pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } } void test_semlock(int locktimes) { struct sembuf bufLock, bufUnlock; int iCount = 0; int semid = semget(0x33332222, 1, IPC_CREAT|0666); if (semid == -1){ printf("semget error/n"); return ; } semctl(semid, 0, SETVAL, 1); bufLock.sem_num = 0; bufLock.sem_op = -1; bufLock.sem_flg = SEM_UNDO; bufUnlock.sem_num = 0; bufUnlock.sem_op = 1; bufUnlock.sem_flg = SEM_UNDO; for ( iCount = 0; iCount < 10000000; ++iCount){ semop(semid, &bufLock, 1); semop(semid, &bufUnlock, 1); } } int main(int argc, char **argv) { if(argc != 3){ printf("usage: test_lock file|sem|pthread locktimes/n"); exit(1); } int locktimes = atoi(argv[2]); if(strcmp(argv[1], "file") == 0) test_filelock(locktimes); else if(strcmp(argv[1], "sem") == 0) test_semlock(locktimes); else test_pthread_lock(locktimes); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; int kap_valov,n_kobyl,stav_valov; pthread_cond_t emp_valov,fill; void* spravca(void* param){ while(1){ pthread_mutex_lock(&mutex); while(stav_valov>0){ pthread_cond_wait(&emp_valov,&mutex); } stav_valov = kap_valov; printf("Spravca naplna valov\\n"); int i; for(i=0;i<5;i++){ printf("%d/5\\n",i+1,kap_valov); sleep(1); } printf("Spravca naplnil valov\\n"); pthread_cond_broadcast(&fill); pthread_mutex_unlock(&mutex); } } void* kobyla(void* param){ while(1){ int vyhladnutie = rand() % 15 + 5; sleep(vyhladnutie); pthread_mutex_lock(&mutex); while(stav_valov==0){pthread_cond_wait(&fill,&mutex);} stav_valov--; printf("Kobila cislo %d sa nazrala\\n",param); printf("Vo valove zostalo jedlo pre %d kobyl\\n", stav_valov); if(stav_valov==0){ printf("kobyla cislo %d erdzi\\n",param); pthread_cond_broadcast(&emp_valov); pthread_cond_wait(&fill,&mutex); } pthread_mutex_unlock(&mutex); } return; } void* test(void* param){ printf("test of proces %d\\n",param); } int main(int argc, char* argv[]) { kap_valov = atoi(argv[1]); n_kobyl = atoi(argv[2]); stav_valov = kap_valov; pthread_t tid[n_kobyl]; pthread_t sprav_t; pthread_mutex_init(&mutex,0); pthread_cond_init(&emp_valov,0); pthread_cond_init(&fill,0); pthread_create(&sprav_t,0,&spravca,0); int i; for(i=0;i<n_kobyl;i++){ pthread_create(&tid[i],0,&kobyla,(void*)(i+1)); } for(i=0;i<n_kobyl;i++){ pthread_join(tid[i],0); } pthread_join(sprav_t,0); }
1
#include <pthread.h> unsigned long Flag_Count; unsigned long Flag_Range; unsigned long Flag_Threads; unsigned long Threads_Completed; pthread_mutex_t Lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t Job_Done = PTHREAD_COND_INITIALIZER; void emit_help(void); void *worker(void *unused); int main(int argc, char *argv[]) { int ch; pthread_t *tids; struct timespec wait; jkiss64_init(0); setvbuf(stdout, (char *) 0, _IOLBF, (size_t) 0); while ((ch = getopt(argc, argv, "h?c:R:t:")) != -1) { switch (ch) { case 'c': Flag_Count = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 'R': Flag_Range = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 't': Flag_Threads = flagtoul(ch, optarg, 1UL, ULONG_MAX); break; case 'h': case '?': default: emit_help(); } } argc -= optind; argv += optind; if (Flag_Count == 0 || Flag_Range == 0 || Flag_Threads == 0) emit_help(); if ((tids = calloc(sizeof(pthread_t), (size_t) Flag_Threads)) == 0) err(EX_OSERR, "could not calloc() threads list"); for (unsigned int i = 0; i < Flag_Threads; i++) { if (pthread_create(&tids[i], 0, worker, 0) != 0) err(EX_OSERR, "could not pthread_create() thread %d", i); } wait.tv_sec = 1; wait.tv_nsec = 63; for (;;) { pthread_mutex_lock(&Lock); if (Threads_Completed == Flag_Threads) break; pthread_cond_timedwait(&Job_Done, &Lock, &wait); pthread_mutex_unlock(&Lock); } exit(0); } void emit_help(void) { fprintf(stderr, "Usage: ./uniform-bias -c count -R range -t threads\\n"); exit(EX_USAGE); } void *worker(void *unused) { jkiss64_init_thread(); for (unsigned long i = 0; i < Flag_Count; i++) printf("%llu\\n", jkiss64_uniform(Flag_Range)); pthread_mutex_lock(&Lock); Threads_Completed++; pthread_mutex_unlock(&Lock); pthread_cond_signal(&Job_Done); return (void *) 0; }
0