text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int threadCount, bufSize, itemsPerProducer; static int index = 0; int* buf; sem_t empty; sem_t full; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* producer(void* id); void* consumer(void* id); struct threadAttr { int id; }; int main(int argc, char** argv) { clock_t t1, t2; t1 = clock(); if (argc != 5){ exit(1); } bufSize = atoi(argv[1]); int producerCount = atoi(argv[2]); int consumerCount = atoi(argv[3]); itemsPerProducer = atoi(argv[4]); threadCount = producerCount; printf("Buffer Size: %d\\n" "Number of Producers: %d\\n" "Number of Consumers: %d\\n" "Items Per Producer: %d\\n", bufSize, producerCount, consumerCount, itemsPerProducer); buf = malloc(bufSize * sizeof (int)); sem_init(&empty, 0, bufSize); sem_init(&full, 0, 0); int i, retval; pthread_attr_t pta; pthread_attr_init(&pta); pthread_t prods[producerCount]; pthread_t cons[consumerCount]; struct threadAttr *producers; struct threadAttr *consumers; for (i = 0; i < producerCount; i++) { producers = malloc(sizeof (struct threadAttr)); (*producers).id = i; retval = pthread_create(&prods[i], &pta, producer, (void*) producers); if (retval < 0) { printf("Error in creating producer thread.\\n"); exit(1); } } for (i = 0; i < consumerCount; i++) { consumers = malloc(sizeof (struct threadAttr)); (*consumers).id = i; retval = pthread_create(&cons[i], &pta, consumer, (void*) consumers); if (retval < 0) { printf("Error in creating consumer thread.\\n"); exit(1); } } for (i = 0; i < producerCount; i++) { retval = pthread_join(prods[i], 0); if (retval < 0) { printf("Error in joining producer thread."); exit(1); } } for (i = 0; i < consumerCount; i++) { retval = pthread_join(cons[i], 0); if (retval < 0) { printf("Error in joining consumer thread."); exit(1); } } printf("\\n\\nAll tasks complete. Goodbye.\\n"); t2 = clock(); printf("\\nElapsed Time: %.6fs\\n", (t2 - t1) / (double) CLOCKS_PER_SEC); free(producers); free(consumers); free(buf); return (0); } void* producer(void* threadAttr) { int counter = 0; int item; struct threadAttr *prodAttr = (struct threadAttr*) threadAttr; int id = (*prodAttr).id; while (1) { sem_wait(&empty); pthread_mutex_lock(&lock); if (index < bufSize) { item = counter * threadCount + id; buf[index] = item; if (index > bufSize) { break; } index++; counter++; } pthread_mutex_unlock(&lock); sem_post(&full); if (counter == 1000) { break; } } return 0; } void* consumer(void* threadAttr) { int itemsConsumed; int item; struct threadAttr *consAttr = (struct threadAttr*) threadAttr; int id = (*consAttr).id; while (1) { sem_wait(&full); pthread_mutex_lock(&lock); item = buf[index - 1]; index--; itemsConsumed++; if (index < 0) { break; } pthread_mutex_unlock(&lock); sem_post(&empty); if (itemsConsumed == 1000) { break; } } return 0; }
1
#include <pthread.h> char * buf; int buf_size; int *num_open; pthread_mutex_t *lock; pthread_cond_t *other; pthread_cond_t *self; } arg_t; void * producer_thread(void * arg) { int pos = 0; arg_t * args = (arg_t *)arg; const char *str = "Product.\\n"; size_t len = strlen(str); while(1){ pthread_mutex_lock(args->lock); while(*args->num_open == 0) { pthread_cond_wait(args->self, args->lock); } pthread_mutex_unlock(args->lock); args->buf[pos%args->buf_size] = str[pos%len]; pos++; pthread_mutex_lock(args->lock); (*args->num_open)--; pthread_cond_signal(args->other); pthread_mutex_unlock(args->lock); } return 0; } void * consumer_thread(void * arg) { int pos = 0; char read; arg_t * args = (arg_t *)arg; while(1){ pthread_mutex_lock(args->lock); while( (*args->num_open == args->buf_size) ) { pthread_cond_wait(args->self, args->lock); } pthread_mutex_unlock(args->lock); read = args->buf[pos%args->buf_size]; pos++; printf("%c", read); fflush(stdout); pthread_mutex_lock(args->lock); (*args->num_open)++; pthread_cond_signal(args->other); pthread_mutex_unlock(args->lock); sleep(2); } return 0; } int main( int argc, char ** args ) { char * buf = (char *)malloc(4); arg_t * prod_args = (arg_t *)malloc(sizeof(arg_t)); arg_t * cons_args = (arg_t *)malloc(sizeof(arg_t)); sem_t open_sem; sem_t ready_sem; pthread_t producer, consumer; void * thexit; return 0; }
0
#include <pthread.h> void *Producer(void *); void *Consumer(void *); sem_t empty; sem_t full; pthread_mutex_t mutex; int g_data[20]; int N; int main(int args, char* argv[]) { N = atoi(argv[1]); int id[N]; pthread_t pid[N], cid[N]; sem_init(&empty, 1, 20); sem_init(&full, 1, 0); pthread_mutex_init(&mutex,0); printf("main started\\n"); int i; for(i = 0; i<N; i++){ id[i]=*(int*)malloc(sizeof(int)); id[i]=i; } for(i=0;i<N;i++){ pthread_create(&pid[i], 0, Producer, (void*)&id[i] ); pthread_create(&cid[i], 0, Consumer, (void*)&id[i] ); } for(i =0; i<N; i++){ pthread_join(pid[i], 0); pthread_join(cid[i], 0); } printf("main done\\n"); return 0; } void *Producer(void *arg) { int *id = (int*)arg; int semvalem,i=0,j; while(i < 100) { usleep(rand()%100000); sem_wait(&empty); pthread_mutex_lock(&mutex); sem_getvalue(&empty, &semvalem); g_data[20 -(semvalem-1)]=1; j=20; printf("(Producer %d, semaphore empty is %d) \\t",*id,semvalem); while(j > semvalem) { j--; printf("="); } printf("\\n"); pthread_mutex_unlock(&mutex); sem_post(&full); i++; } return 0; } void *Consumer(void *arg){ int semvalfu,i=0,j; int *id = (int*)arg; while(i<100){ usleep(rand()%100000); sem_wait(&full); pthread_mutex_lock(&mutex); sem_getvalue(&full,&semvalfu); g_data[semvalfu]=0; j=0; printf("(Consumer %d, semaphore full is %d)\\t", *id, semvalfu); while(j < semvalfu) { j++; printf("="); } printf("\\n"); pthread_mutex_unlock(&mutex); sem_post(&empty); i++; } return 0; }
1
#include <pthread.h> sem_t tray_full_sem; pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t tray_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t student_wait_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t student_total_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t cook_sleep_lock = PTHREAD_MUTEX_INITIALIZER; int trays = 8; int cook_sleep = 0; char *cook_sleep_str[] = {"Working", "Sleep"}; int total_tray = 8; int student_total = 0; int student_fetch = 0; static time_t START_TIME; void *cook(void *); void *student(void *); void monitor(void); int main() { pthread_t thread_cook; pthread_t thread_student; if(sem_init(&tray_full_sem, 0, 0) == -1) { perror("sem_init"); exit(1); } START_TIME = time(0); printf("DEU-CAFETERIA starting at %s\\n", ctime(&START_TIME)); pthread_create(&thread_cook, 0, &cook, 0); while(1) { sleep(rand() % 3 + 1); pthread_create(&thread_student, 0, &student, 0); } void *status; pthread_join(thread_cook, status); return 0; } void *cook(void *arg) { pthread_mutex_lock(&print_lock); printf("Cook created .. at %ld\\n", time(0) - START_TIME); pthread_mutex_unlock(&print_lock); unsigned int random_time; time_t now; while(1) { pthread_mutex_lock(&tray_lock); if(trays == 8) { pthread_mutex_lock(&cook_sleep_lock); cook_sleep = 1; pthread_mutex_unlock(&cook_sleep_lock); pthread_mutex_lock(&print_lock); printf( "\\x1b[32m""[ %ld ] - cook started to sleep \\n" "\\x1b[0m", time(0) - START_TIME); monitor(); pthread_mutex_unlock(&print_lock); pthread_mutex_unlock(&tray_lock); sem_wait(&tray_full_sem); pthread_mutex_lock(&cook_sleep_lock); cook_sleep = 0; pthread_mutex_unlock(&cook_sleep_lock); pthread_mutex_lock(&print_lock); printf( "\\x1b[32m" "[ %ld ] - cook awake \\n" "\\x1b[0m", time(0) - START_TIME); monitor(); pthread_mutex_unlock(&print_lock); } else pthread_mutex_unlock(&tray_lock); random_time = rand() % 5 + 2; now = time(0); pthread_mutex_lock(&print_lock); printf( "\\x1b[32m" "[ %ld ] cook started to fill %d'th tray\\n" "\\x1b[0m", time(0) - START_TIME, total_tray + 1); monitor(); pthread_mutex_unlock(&print_lock); while(time(0) - now < random_time) ; pthread_mutex_lock(&tray_lock); trays++; pthread_mutex_unlock(&tray_lock); total_tray++; pthread_mutex_lock(&print_lock); printf( "\\x1b[32m""[ %ld ] cook fished to fill %d'th tray\\n" "\\x1b[0m", time(0) - START_TIME, total_tray); monitor(); pthread_mutex_unlock(&print_lock); } } void *student(void *arg) { pthread_mutex_lock(&student_total_lock); student_total++; pthread_mutex_unlock(&student_total_lock); pthread_mutex_lock(&print_lock); printf( "\\x1b[32m" "[ %ld ] %d'th student arrived .. \\n" "\\x1b[0m", time(0) - START_TIME, student_total); monitor(); pthread_mutex_unlock(&print_lock); pthread_mutex_lock(&student_wait_lock); while(trays == 0) ; sleep(1); pthread_mutex_lock(&tray_lock); trays--; if(trays == 7) { pthread_mutex_lock(&cook_sleep_lock); if(cook_sleep == 1) sem_post(&tray_full_sem); pthread_mutex_unlock(&cook_sleep_lock); } student_fetch++; pthread_mutex_lock(&print_lock); printf( "\\x1b[32m" "[ %ld ] %d'th student fetched his tray .. \\n" "\\x1b[0m", time(0) - START_TIME, student_fetch); monitor(); pthread_mutex_unlock(&print_lock); pthread_mutex_unlock(&tray_lock); pthread_mutex_unlock(&student_wait_lock); pthread_exit(0); } void monitor(void) { printf("\\n|-------------------------------------------------------|\\n"); printf("\\x1b[31m" "|\\t\\t\\tCONVEYOR \\t\\t\\t|\\n" "\\x1b[0m"); printf("|\\t\\t---------------------- \\t\\t\\t|\\n"); printf("|\\t\\tTRAYS READY\\t:%d \\t\\t\\t|\\n", trays); printf("|\\t\\tAVAILABLE PLACE\\t:%d \\t\\t\\t|\\n", (8 - trays)); printf( "\\x1b[31m" "|\\tCOOK\\t\\t\\t\\tWAITING LINE \\t|\\n" "\\x1b[0m"); printf("| ----------------\\t\\t ------------------- |\\n"); printf("| %s\\t\\t\\t\\t %d \\t|\\n", cook_sleep_str[cook_sleep], (student_total - student_fetch)); printf("|\\t\\t\\t\\t Students are waiting|\\n"); if(cook_sleep == 0) printf("| Filling %d'th tray\\t\\t\\t\\t\\t|\\n", (total_tray + 1)); printf("|\\t\\t\\t\\t\\t\\t\\t|\\n"); printf("|\\t\\t\\t\\t\\t\\t\\t|\\n"); printf( "\\x1b[31m" "|\\t\\t CAFETERIA STATISTICS \\t\\t|\\n" "\\x1b[0m"); printf("|\\t\\t---------------------------- \\t\\t|\\n"); printf("|\\t\\tTOTAL TRAYS FILLED\\t:%d\\t\\t|\\n", total_tray); printf("|\\t\\tTOTAL STUDENTS CAME\\t:%d\\t\\t|\\n", student_total); printf("|\\t\\tTOTAL STUDENTS FETCHED\\t:%d\\t\\t|\\n", student_fetch); printf("|-------------------------------------------------------|\\n\\n"); }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo *fp; struct foo * foo_alloc(void) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } } return fp; } void foo_hold(const char *str, struct foo *fp) { pthread_mutex_lock(&fp->f_lock); printf("%s %d\\n", str, fp->f_count++); pthread_mutex_unlock(&fp->f_lock); } void foo_rele(const char *str, struct foo *fp) { int i; for (i = 0; i < 20; i++) { pthread_mutex_lock(&fp->f_lock); if (fp -> f_count == 0) { printf("%s %d\\n", str, fp->f_count); pthread_mutex_unlock(&fp->f_lock); pthread_exit((void *)0); } printf("%s %d\\n", str, --fp->f_count); pthread_mutex_unlock(&fp->f_lock); } pthread_exit((void *)0); } void *thr_fn1(void *arg) { int offset; int i; offset = (long)arg; for (i = 0; i < offset; i++) foo_hold("thread 1", fp); pthread_exit((void *)0); } void *thr_fn2(void *arg) { int offset; int i; offset = (long)arg; for (i = 0; i < offset; i++) foo_hold("thread 2", fp); pthread_exit((void *)0); } void *thr_fn3(void *arg) { foo_rele("thread 3", fp); pthread_exit((void *)0); } void *thr_fn4(void *arg) { foo_rele("thread 4", fp); pthread_exit((void *)0); } int main(void) { pthread_t tid1, tid2; pthread_t tid3, tid4; int err; void *status; if ((fp = foo_alloc()) != 0) { err = pthread_create(&tid1, 0, thr_fn1, (void *)10); if (err != 0) err_exit(err, "can't create thread 1"); err = pthread_create(&tid2, 0, thr_fn2, (void *)10); if (err != 0) err_exit(err, "can't create thread 2"); err = pthread_join(tid1, &status); if (err != 0) err_exit(err, "can't join with thread 1"); printf("thread 1 exit code %ld\\n", (long)status); err = pthread_join(tid2, &status); if (err != 0) err_exit(err, "can't join with thread 2"); printf("thread 2 exit code %ld\\n", (long)status); err = pthread_create(&tid3, 0, thr_fn3, 0); if (err != 0) err_exit(err, "can't create thread 3"); err = pthread_create(&tid4, 0, thr_fn4, 0); if (err != 0) err_exit(err, "can't create thread 4"); err = pthread_join(tid3, &status); if (err != 0) err_exit(err, "can't join with thread 3"); printf("thread 3 exit code %ld\\n", (long)status); err = pthread_join(tid4, &status); if (err != 0) err_exit(err, "can't join with thread 4"); printf("thread 4 exit code %ld\\n", (long)status); if (fp->f_count == 0) { pthread_mutex_destroy(&fp->f_lock); free(fp); printf("released\\n"); } } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; sem_t sem; struct node *head = 0; int create_sockfd(); void * pthread_fun( void *arg); void create_threads(); void send_file(int c, char *s); void recvf_ile(int c,char *s); void sig_fun(int sig) { printf("sig = %d\\n ",sig); } int main() { signal(SIGPIPE,sig_fun); pthread_mutex_init(&mutex,0); sem_init(&sem,0,0); list_init(&head); int sockfd = create_sockfd(); create_threads(); while(1) { struct sockaddr_in caddr; int len = sizeof(caddr); int c = accept(sockfd,(struct sockaddr*)&caddr,&len); if( c < 0) { continue; } pthread_mutex_lock(&mutex); list_add(head,c); pthread_mutex_unlock(&mutex); printf("accept c=%d\\n",c); sem_post(&sem); } } void send_file(int c, char *s) { int fd = open(s,O_RDONLY); if(fd == -1) { send(c,"err",3,0); return; } struct stat st; lstat(s,&st); sprintf(buff+3,"%d",st.st_size); send(c,buff,strlen(buff),0); char cli_stat[32] = {0}; if(recv(c,cli_stat,31,0)<=0) { return; } if(strncmp(cli_stat,"ok",2)!=0) { return; } char recvbuff[256] = {0}; int n = -1; while((n = recv(c,recvbuff,256,0))>0) { if(write(fd,recvbuff,n)<=0) { perror("send error"); return; } } printf("send file finish\\n"); return; } void create_threads() { pthread_t id[3]; int i=0; for(; i<3;i++) { pthread_create(&id[i],0,pthread_fun,0); } } void recv_file(int c,char *s) { char buff[32] = {0}; recv(c,buff,31,0); if(strcmp(buff,"err") == 0) { return; } send(c,"ok",2,0); int fd = open(s,O_WRONLY|O_CREAT,0600); if(fd == -1) { send(c,"err",3,0); return; } send(c,"ok",2,0); int fsize = 0; recv(c,recvbuff,256,0); sscanf(recvbuff+3,"%d",&fsize); int cursize = 0; int n = -1; while(1) { n = recv(c,recvbuff,1024,0); cursize+=n; if(n <= 0) { break; } write(fd,recvbuff,n); if(cursize == fsize) { printf("file recv success\\n"); send(c,"fileok",6,0); break; } } close(fd); } void *pthread_fun(void *arg) { printf("pthread run\\n"); while(1) { sem_wait(&sem); pthread_mutex_lock(&mutex); int c = list_get(head); pthread_mutex_unlock(&mutex); printf("c=%d\\n",c); while(1) { char buff[128] = {0}; int n = recv(c,buff,127,0); if(n == 0) { printf("ont client over\\n"); close(c); break; } char *myargv[10] = {0}; char *sp = 0; char *s = strtok_r(buff," ",&sp); if(s == 0) { continue; } int i = 0; while(s != 0) { myargv[i++] = s; s = strtok_r(0," ",&sp); } if(strcmp(myargv[0],"get") == 0) { send_file(c,myargv[1]); } else if(strcmp(myargv[0],"put") == 0) { recv_file(c,myargv[1]); continue; } else { int pipefd[2]; pipe(pipefd); pid_t pid = fork(); assert(pid != -1); if(pid == 0) { close(pipefd[0]); dup2(pipefd[1],1); dup2(pipefd[1],2); execvp(myargv[0],myargv); perror("execvp error"); exit(0); } close(pipefd[1]); wait(0); read(pipefd[0],readbuff+3,1000); send(c,readbuff,strlen(readbuff),0); } } } } int create_sockfd() { int sockfd = socket(AF_INET,SOCK_STREAM,0); assert(sockfd != -1); struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); int res = bind(sockfd,(struct sockaddr *)&saddr,sizeof(saddr)); assert(res != -1); listen(sockfd,5); return sockfd; }
0
#include <pthread.h> void * handle_clnt(void * arg); void send_msg(char * msg, int len); void error_handling(char * msg); int clnt_cnt=0; int clnt_socks[2]; char clnt_name[20]= {0}; char clnt_names[2][20]= {0}; pthread_mutex_t mutx; int main(int argc, char *argv[]) { int serv_sock, clnt_sock, i; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz; pthread_t t_id; if(argc!=2) { printf("Usage : %s <port>\\n", argv[0]); exit(1); } pthread_mutex_init(&mutx, 0); serv_sock=socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1) error_handling("bind() error"); if(listen(serv_sock, 5)==-1) error_handling("listen() error"); while(1) { clnt_adr_sz=sizeof(clnt_adr); clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz); if(clnt_cnt >= 2) { printf("CONNECT FAIL : %d \\n", clnt_sock); write(clnt_sock, "too many users. sorry", 128); continue; } pthread_mutex_lock(&mutx); clnt_socks[clnt_cnt]=clnt_sock; read(clnt_sock, clnt_name, 20); strcpy(clnt_names[clnt_cnt++], clnt_name); pthread_mutex_unlock(&mutx); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); pthread_detach(t_id); printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr)); } close(serv_sock); return 0; } void * handle_clnt(void * arg) { int clnt_sock=*((int*)arg); int str_len=0, i; int fSize = 0; const char sig_file[128] = {"file : cl->sr"}; const char Fmsg_end[128] = {"FileEnd_cl->sr"}; const char sig_file_all[128] = {"file : cl->sr_all"}; const char sig_whisper[128] = {"whisper : cl->sr"}; char msg[128] = {0}; char file_msg[128] = {0}; while((str_len=read(clnt_sock, msg, 128))!=0) { if(!strcmp(msg, sig_file)) { int j; int noCli = 0; int fileGo = 0; char tmpName[20]= {0}; read(clnt_sock, tmpName, 20); pthread_mutex_lock(&mutx); for(j=0; j<clnt_cnt; j++) { if(!strcmp(tmpName, clnt_names[j]) ) { noCli = 0; fileGo = j; break; } else if(j == clnt_cnt - 1) { noCli = 1; break; } } if(noCli == 1) { write(clnt_sock, "[NoClient_sorry]", 128); pthread_mutex_unlock(&mutx); continue; } else if(noCli == 0) { write(clnt_sock, "[continue_ok_nowgo]", 128); } write(clnt_socks[fileGo], "file : sr->cl", 128); read(clnt_sock, &fSize, sizeof(int)); printf("File size %d Byte\\n", fSize); write(clnt_socks[fileGo], &fSize, sizeof(int)); while(1) { read(clnt_sock, file_msg, 128); if(!strcmp(file_msg, Fmsg_end)) break; write(clnt_socks[fileGo], file_msg, 128); } write(clnt_socks[fileGo], "FileEnd_sr->cl", 128); pthread_mutex_unlock(&mutx); printf("(!Notice)File data transfered \\n"); } else if(!strcmp(msg, sig_file_all)) { pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) { if(clnt_sock == clnt_socks[i]) continue; write(clnt_socks[i], "file : sr->cl", 128); } read(clnt_sock, &fSize, sizeof(int)); printf("File size %d Byte\\n", fSize); for(i=0; i<clnt_cnt; i++) { if(clnt_sock == clnt_socks[i]) continue; write(clnt_socks[i], &fSize, sizeof(int)); } while(1) { read(clnt_sock, file_msg, 128); if(!strcmp(file_msg, Fmsg_end)) break; for(i=0; i<clnt_cnt; i++) { if(clnt_sock == clnt_socks[i]) continue; write(clnt_socks[i], file_msg, 128); } } for(i=0; i<clnt_cnt; i++) { if(clnt_sock == clnt_socks[i]) continue; write(clnt_socks[i], "FileEnd_sr->cl", 128); } pthread_mutex_unlock(&mutx); printf("(!Notice)File data transfered \\n"); } else if(!strcmp(msg, sig_whisper)) { int j=0; int noCli = 0; int mGo = 0; char tmpName[20]= {0}; char msg[20]= {0}; read(clnt_sock, tmpName, 20); pthread_mutex_lock(&mutx); for(j=0; j<clnt_cnt; j++) { if(!strcmp(tmpName, clnt_names[j]) ) { noCli = 0; mGo = j; break; } else if(j == clnt_cnt - 1) { noCli = 1; break; } } pthread_mutex_unlock(&mutx); read(clnt_sock, msg, 128); if(noCli == 1) { write(clnt_sock, "sorry. no client like that", 128); } else { write(clnt_socks[j], msg, 128); } } else { printf("(!Notice)Chatting message transfered \\n"); send_msg(msg, str_len); } } pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) { if(clnt_sock==clnt_socks[i]) { while(i++<clnt_cnt-1) { clnt_socks[i]=clnt_socks[i+1]; strcpy(clnt_names[i], clnt_names[i+1]); } break; } } clnt_cnt--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void send_msg(char * msg, int len) { int i; pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) write(clnt_socks[i], msg, 128); pthread_mutex_unlock(&mutx); } void error_handling(char * msg) { fputs(msg, stderr); fputc('\\n', stderr); exit(1); }
1
#include <pthread.h> unsigned int randr(int min, int max); void *random_thread_function(void *arg); void *sort_thread_function(void *arg); void *merge_thread_function(void *arg); int compare (const void * a, const void * b); int number_of_nums; int number_of_threads; int n_thread_sort; long long int random_number_size; int low_limit; int high_limit; pthread_mutex_t random_array_mutex = PTHREAD_MUTEX_INITIALIZER; int *random_array = 0; int main(int argc, char **argv) { srand(time(0)); char *sorted_file = 0; char *output_file = 0; int c; opterr = 0; while ((c = getopt (argc, argv, "r:m:l:h:n:s:o:")) != -1) { switch (c) { case 'r': number_of_threads = atoi(optarg); break; case 'm': number_of_nums = atoi(optarg); break; case 'l': low_limit = atoi(optarg); break; case 'h': high_limit = atoi(optarg); break; case 'n': sorted_file = optarg; break; case 's': n_thread_sort = atoi(optarg); break; case 'o': output_file = optarg; break; case '?': printf("Usage: ./tsort -r 2 -m 6 -l 30 -h 50 -n numbers.txt -s 4 -o sorted.txt"); return 1; default: printf("Usage: ./tsort -r 2 -m 6 -l 30 -h 50 -n numbers.txt -s 4 -o sorted.txt"); return 1; } } random_number_size = pow(2, number_of_nums); FILE *output = fopen(output_file, "w"); if(0 == output) { printf("Can't open '%s' for writing!", output_file); return 1; } FILE *sorted = fopen(sorted_file, "w"); if(0 == sorted) { printf("Can't open '%s' for writing!", sorted_file); return 1; } random_array = malloc(random_number_size * sizeof(int)); if(0 == random_array) { printf("Cannot allocate memory!"); return 1; } pthread_t *threads = malloc(number_of_threads * sizeof(pthread_t)); if(0 == threads) { printf("Cannot allocate memory!"); return 1; } pthread_t *sort_threads = malloc(n_thread_sort * sizeof(pthread_t)); if(0 == sort_threads) { printf("Cannot allocate memory!"); return 1; } long i; for(i = 0; i < number_of_threads; i++) { pthread_create(&threads[i], 0, random_thread_function, (void *) i); } for(i = 0; i < number_of_threads; i++) { pthread_join(threads[i], 0); } for(i = 0; i < random_number_size; i++) { fprintf(sorted, "%d\\n", random_array[i]); } for(i = 0; i < n_thread_sort; i++) { pthread_create(&sort_threads[i], 0, sort_thread_function, (void *) i); } for(i = 0; i < n_thread_sort; i++) { pthread_join(sort_threads[i], 0); } int k = (random_number_size / n_thread_sort) / 2; int n = 0; int m = (random_number_size / n_thread_sort); pthread_t *merge_threads = malloc(k * sizeof(pthread_t)); if(0 == merge_threads) { printf("Cannot allocate memory!"); return 1; } while(k >= 1) { for(i = 0; i < k; i++, n = n + 2) { int *arr = malloc(2 * sizeof(int)); arr[0] = k; arr[1] = i; pthread_create(&merge_threads[i], 0, merge_thread_function, (void *) arr); } int t; for(t = 0; t < k; ++t) { pthread_join(merge_threads[t], 0); } k = k / 2; n = 0; m = m*2; } for(i = 0; i < random_number_size; i++) { fprintf(output, "%d\\n", random_array[i]); } return 0; } void *random_thread_function(void *arg) { long j = (long) arg; int k = (random_number_size / number_of_threads); int h = (k * (j + 1)) - 1; int l = (h - k) + 1; int i; for(i = l; i <= h; i ++) { pthread_mutex_lock(&random_array_mutex); random_array[i] = randr(low_limit, high_limit); pthread_mutex_unlock(&random_array_mutex); } } void *sort_thread_function(void *arg) { long j = (long) arg; int k = (random_number_size / n_thread_sort); int h = (k * (j + 1)) - 1; int l = (h - k) + 1; int i, g; int *part = malloc(k + 1 * sizeof(int)); for(i = l, g = 0; i <= h; i++, g++) { part[g] = random_array[i]; } qsort (part, g, sizeof(int), compare); for(i = l, g = 0; i <= h; i++, g++) { pthread_mutex_lock(&random_array_mutex); random_array[i] = part[g]; pthread_mutex_unlock(&random_array_mutex); } } void *merge_thread_function(void *arg) { int (*j)[2] = (int(*)[2]) arg; int k = (random_number_size / n_thread_sort); int h = ((*j)[0] * ((*j)[1] + 1)) - 1; int l = (h - (*j)[0]) + 1; pthread_mutex_lock(&random_array_mutex); qsort(random_array, random_number_size, sizeof(int), compare); pthread_mutex_unlock(&random_array_mutex); } int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } unsigned int randr(int min, int max) { double scaled = (double)rand()/32767; return (max - min +1)*scaled + min; }
0
#include <pthread.h> sigset_t new_set, old_set; int lock_USR1; int error_USR2; int stp_stop; pthread_mutex_t mux[5], mux_files; char mystrings[10][10] = { "aaaaaaaaa\\n", "bbbbbbbbb\\n", "ccccccccc\\n", "ddddddddd\\n", "eeeeeeeee\\n", "fffffffff\\n", "ggggggggg\\n", "hhhhhhhhh\\n", "iiiiiiiii\\n", "jjjjjjjjj\\n" }; char* myfiles[5]; void init_myfiles () { int i; for (i=0; i< 5; i++) { myfiles[i] = malloc (15); sprintf (myfiles[i], "SO2014-%1d.txt", i); } } void* thread_escritor (void* argument) { int i; mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; int index; char *file_to_open; int fd; int it_was_locked; char *string_to_write; int j; while( stp_stop ){ pthread_mutex_lock(&mux_files); index = rand()%5; file_to_open = myfiles[index]; string_to_write = mystrings[rand()%5]; pthread_mutex_unlock(&mux_files); fd = open (file_to_open, O_RDWR | O_CREAT, mode); it_was_locked=0; if (fd == -1) { perror ("Error opening file"); exit (-1); } if(lock_USR1){ pthread_mutex_lock(&mux[index]); it_was_locked=1; } for (j=0; j<1024; j++) { if ( error_USR2){ if (j%2==0) { string_to_write[0]='z'; } else { string_to_write[0]= string_to_write[1]; } }else{ string_to_write[0]= string_to_write[1]; } if (write (fd, string_to_write, 10) == -1) { perror ("Error writing file"); exit (-1); } } if (close (fd) == -1) { perror ("Error closing file"); exit (-1); } if( it_was_locked){ pthread_mutex_unlock(&mux[index]); it_was_locked=0; } } pthread_exit(0); } void func_SIGUSR1(){ if(lock_USR1 == 1){ lock_USR1 = 0; } if(lock_USR1 == 0){ lock_USR1 = 1; } signal(SIGUSR1, func_SIGUSR1); } void func_SIGUSR2(){ if(error_USR2 == 1){ error_USR2 = 0; } if(error_USR2 == 0){ error_USR2 = 1; } signal(SIGUSR2, func_SIGUSR2); } void func_SIGTSTP(){ stp_stop = 0; } int main(){ pthread_t *t_id = (pthread_t*) malloc(sizeof(pthread_t) * 10); int i; struct timeval tvstart; lock_USR1 = 1; error_USR2 = 0; stp_stop = 1; init_myfiles (); if (gettimeofday(&tvstart, 0) == -1) { perror("Could not get time of day, exiting."); exit(-1); } srandom ((unsigned)tvstart.tv_usec); for( i=0; i<5; i++){ pthread_mutex_init(&mux[i], 0); } pthread_mutex_init(&mux_files, 0); for( i=0; i < 10; i++){ if (pthread_create(&t_id[i], 0, thread_escritor, 0) != 0){ printf("Erro a criar a string"); exit(-1); } } signal(SIGUSR1, func_SIGUSR1); signal(SIGUSR2, func_SIGUSR2); signal(SIGTSTP, func_SIGTSTP); signal(SIGINT, func_SIGTSTP); sigfillset(&new_set); sigdelset(&new_set, SIGUSR1); sigdelset(&new_set, SIGUSR2); sigdelset(&new_set, SIGTSTP); sigdelset(&new_set, SIGINT); sigprocmask(SIG_BLOCK, &new_set, &old_set); for(i=0; i< 10; i++){ if(pthread_join(t_id[i], 0)){ printf("Erro no join"); exit(-1); } } for( i=0; i<5; i++){ pthread_mutex_destroy(&mux[i]); } pthread_mutex_destroy(&mux_files); exit(0); }
1
#include <pthread.h> int source[15]; int minBound[4]; int maxBound[4]; int channel[4]; int th_id = 0; pthread_mutex_t mid; pthread_mutex_t ms[4]; void sort (int x, int y) { int aux = 0; for (int i = x; i < y; i++) { for (int j = i; j < y; j++) { if (source[i] > source[j]) { aux = source[i]; source[i] = source[j]; source[j] = aux; } } } } void *sort_thread (void * arg) { int id = -1; int x, y; pthread_mutex_lock (&mid); id = th_id; th_id++; pthread_mutex_unlock (&mid); x = minBound[id]; y = maxBound[id]; __VERIFIER_assert (x >= 0); __VERIFIER_assert (x < 15); __VERIFIER_assert (y >= 0); __VERIFIER_assert (y < 15); printf ("t%d: min %d max %d\\n", id, x, y); sort (x, y); pthread_mutex_lock (&ms[id]); channel[id] = 1; pthread_mutex_unlock (&ms[id]); return 0; } int main () { pthread_t t[4]; int i; __libc_init_poet (); i = __VERIFIER_nondet_int (0, 15 - 1); source[i] = __VERIFIER_nondet_int (0, 20); __VERIFIER_assert (source[i] >= 0); pthread_mutex_init (&mid, 0); int j = 0; int delta = 15/4; __VERIFIER_assert (delta >= 1); i = 0; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; __VERIFIER_assert (i == 4); int k = 0; while (k < 4) { i = 0; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; __VERIFIER_assert (i == 4); } __VERIFIER_assert (th_id == 4); __VERIFIER_assert (k == 4); sort (0, 15); printf ("==============\\n"); for (i = 0; i < 15; i++) printf ("m: sorted[%d] = %d\\n", i, source[i]); i = 0; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; __VERIFIER_assert (i == 4); return 0; }
0
#include <pthread.h> { int bUsed; int conf_fd ; struct sockaddr_un conf_addr ; char conf_buf[(16384)]; pthread_mutex_t atomic; char CONF_LOCAL_NAME[16]; char CONF_LISTEN_NAME[16]; int nTimeout; }LocalSockInfo_S,*LPLocalSockInfo; static LocalSockInfo_S s_localSock[(10)]; static int si_init_flag = 0; static pthread_mutex_t s_atomic; int localSockInit() { int i; if (si_init_flag) return 0; if (0 != pthread_mutex_init(&s_atomic, 0)) { return -1; } memset(s_localSock, 0x00, sizeof(s_localSock)); for(i=0; i<(10); i++) { s_localSock[i].conf_fd = -1; if (0 != pthread_mutex_init(&s_localSock[i].atomic, 0)) { return -1; } } si_init_flag = 1; return 0; } int localSockUninit() { if (!si_init_flag) return 0; int i=0; for(i=0; i<(10); i++) { if(!s_localSock[i].bUsed) continue; if (s_localSock[i].conf_fd > 0) { close(s_localSock[i].conf_fd); } s_localSock[i].conf_fd = -1; unlink(s_localSock[i].CONF_LOCAL_NAME); pthread_mutex_destroy(&s_localSock[i].atomic); } pthread_mutex_destroy(&s_atomic); si_init_flag = 0; return 0; } int getFreeIndex() { int i; pthread_mutex_lock(&s_atomic); for(i=0; i<(10); i++) { if(!s_localSock[i].bUsed) break; } pthread_mutex_unlock(&s_atomic); return i<(10)?i:-1; } int newLocalSock(const char * pLocalName,const char * pServerName, int nTimeout) { if (!si_init_flag) return -1; if(0 == pLocalName || 0 == pServerName) return -1; int index = getFreeIndex(); if(index < 0 ) return -1; snprintf(s_localSock[index].CONF_LOCAL_NAME, 15, pLocalName); snprintf(s_localSock[index].CONF_LISTEN_NAME, 15, pServerName); s_localSock[index].conf_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (s_localSock[index].conf_fd < 0) { return -1; } unlink(s_localSock[index].CONF_LOCAL_NAME); bzero(&s_localSock[index].conf_addr , sizeof(s_localSock[index].conf_addr)); s_localSock[index].conf_addr.sun_family = AF_UNIX; snprintf(s_localSock[index].conf_addr.sun_path, sizeof(s_localSock[index].conf_addr.sun_path), s_localSock[index].CONF_LOCAL_NAME); bind(s_localSock[index].conf_fd, (struct sockaddr *)&s_localSock[index].conf_addr, sizeof(s_localSock[index].conf_addr)); bzero(&s_localSock[index].conf_addr , sizeof(s_localSock[index].conf_addr)); s_localSock[index].conf_addr.sun_family = AF_UNIX; snprintf(s_localSock[index].conf_addr.sun_path, sizeof(s_localSock[index].conf_addr.sun_path), s_localSock[index].CONF_LISTEN_NAME); s_localSock[index].bUsed = 1; s_localSock[index].nTimeout = nTimeout; return index; } int freeLocalSock(int index) { if (!si_init_flag) return -1; if(!s_localSock[index].bUsed) return 0; pthread_mutex_lock(&s_atomic); if (s_localSock[index].conf_fd > 0) { close(s_localSock[index].conf_fd); } s_localSock[index].conf_fd = -1; unlink(s_localSock[index].CONF_LOCAL_NAME); s_localSock[index].bUsed = 0; pthread_mutex_unlock(&s_atomic); return 0; } static int SockSend(int index, const char *command) { int ret = -1 ; int addrlen = sizeof(struct sockaddr_un) ; int len = strlen(command); ret = sendto(s_localSock[index].conf_fd , command, len, 0, (struct sockaddr *)&s_localSock[index].conf_addr , addrlen); if (ret != len) { ret = -1 ; syslog(LOG_ERR, "send conf message failed , ret = %d , errno %d\\n", ret, errno); } return ret ; } static int SockRecv(int index, char * buf, int len) { int ret = 0; if(0xFFFF == s_localSock[index].nTimeout) { ret = recv(s_localSock[index].conf_fd , buf, len-1, 0); if (ret > 0) buf[ret] = '\\0'; else buf[0] = '\\0'; } else if(0 == s_localSock[index].nTimeout) { ret = recv(s_localSock[index].conf_fd , buf, len-1, MSG_DONTWAIT); } else { int count = 0; for (count = 0; count < s_localSock[index].nTimeout; ) { usleep(100000); ret = recv(s_localSock[index].conf_fd , buf, len-1, MSG_DONTWAIT); if (ret >= 0) { break; } count += 100; } } return ret; } static int localSockRequest(int index, const char* command, char *recvbuf, int recvlen) { int ret; if (!command || !recvbuf || !recvlen) return -1; ret = SockSend(index, command); if (ret >= 0) { ret = SockRecv(index, recvbuf, recvlen); } return ret; } int localSockSend(int index ,const char* pValue) { char *conf_buf; int ret = 0; if (!si_init_flag || !pValue) return -1; if(index<0 || index>= (10)) return -1; pthread_mutex_lock(&s_localSock[index].atomic); if(!s_localSock[index].bUsed || s_localSock[index].conf_fd < 0) { ret = -1; goto done; } ret = localSockRequest(index, pValue, s_localSock[index].conf_buf, (16384)); done: pthread_mutex_unlock(&s_localSock[index].atomic); return ret; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int counter, end; } Shared; Shared *make_shared(int end) { Shared *shared = (Shared *)malloc(sizeof(Shared)); shared->counter = 0; shared->end = end; return shared; } void desalloc_shared(Shared *shared) { free(shared); } void *increment(void *arg) { Shared *shared = (Shared *)arg; printf("Starting to increment from thread (current counter)...\\n"); while (1) { pthread_mutex_lock(&mutex); if (shared->counter < shared->end) { shared->counter++; pthread_mutex_unlock(&mutex); } else { pthread_mutex_unlock(&mutex); break; } } printf("Finish incrementing from thread.\\n"); pthread_exit(0); } int main(void) { int i; Shared *shared = make_shared(1000000); pthread_t child[50]; for (i = 0; i < 50; i++) { pthread_create(&child[i], 0, increment, (void *)shared); } for (i = 0; i < 50; i++) { pthread_join(child[i], 0); } printf("Final value: %d.\\n\\n\\n", shared->counter); desalloc_shared(shared); return 0; }
0
#include <pthread.h> struct map_2mb { uint64_t pfn_2mb; }; struct map_1gb { struct map_2mb map[1ULL << (30 - 21 + 1)]; }; struct map_128tb { struct map_1gb *map[1ULL << (47 - 30 + 1)]; }; static struct map_128tb vtophys_map_128tb = {}; static pthread_mutex_t vtophys_mutex = PTHREAD_MUTEX_INITIALIZER; static struct map_2mb * vtophys_get_map(uint64_t vfn_2mb) { struct map_1gb *map_1gb; struct map_2mb *map_2mb; uint64_t idx_128tb = ((vfn_2mb) >> (30 - 21)); uint64_t idx_1gb = ((vfn_2mb) & ((1ULL << (30 - 21 + 1)) - 1)); if (vfn_2mb & ~((1ULL << 47) - 1)) { printf("invalid usermode virtual address\\n"); return 0; } map_1gb = vtophys_map_128tb.map[idx_128tb]; if (!map_1gb) { pthread_mutex_lock(&vtophys_mutex); map_1gb = vtophys_map_128tb.map[idx_128tb]; if (!map_1gb) { map_1gb = malloc(sizeof(struct map_1gb)); if (map_1gb) { memset(map_1gb, 0xFF, sizeof(struct map_1gb)); vtophys_map_128tb.map[idx_128tb] = map_1gb; } } pthread_mutex_unlock(&vtophys_mutex); if (!map_1gb) { printf("allocation failed\\n"); return 0; } } map_2mb = &map_1gb->map[idx_1gb]; return map_2mb; } static uint64_t vtophys_get_pfn_2mb(uint64_t vfn_2mb) { uintptr_t vaddr, paddr; struct rte_mem_config *mcfg; struct rte_memseg *seg; uint32_t seg_idx; vaddr = vfn_2mb << 21; mcfg = rte_eal_get_configuration()->mem_config; for (seg_idx = 0; seg_idx < RTE_MAX_MEMSEG; seg_idx++) { seg = &mcfg->memseg[seg_idx]; if (seg->addr == 0) { break; } if (vaddr >= (uintptr_t)seg->addr && vaddr < ((uintptr_t)seg->addr + seg->len)) { paddr = seg->phys_addr; paddr += (vaddr - (uintptr_t)seg->addr); return paddr >> 21; } } fprintf(stderr, "could not find 2MB vfn 0x%jx in DPDK mem config\\n", vfn_2mb); return -1; } uint64_t vtophys(void *buf) { struct map_2mb *map_2mb; uint64_t vfn_2mb, pfn_2mb; vfn_2mb = (uint64_t)buf; vfn_2mb >>= 21; map_2mb = vtophys_get_map(vfn_2mb); if (!map_2mb) { return VTOPHYS_ERROR; } pfn_2mb = map_2mb->pfn_2mb; if (pfn_2mb == VTOPHYS_ERROR) { pfn_2mb = vtophys_get_pfn_2mb(vfn_2mb); if (pfn_2mb == VTOPHYS_ERROR) { return VTOPHYS_ERROR; } map_2mb->pfn_2mb = pfn_2mb; } return (pfn_2mb << 21) | ((uint64_t)buf & ((1ULL << 21) - 1)); }
1
#include <pthread.h> pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int i = 0; void * thread_func1(void *arg) { while(i < 9) { pthread_mutex_lock(&mux); if(i % 3 != 0) { pthread_cond_wait(&cond, &mux); printf("Consumer get i:%d\\n", i); } pthread_mutex_unlock(&mux); } pthread_exit((void *)0); } void * thread_func2(void *arg) { for(i = 0; i <= 9; i++) { pthread_mutex_lock(&mux); printf("Producer set i:%d\\n", i); if(i % 3 == 0) { pthread_cond_signal(&cond); } pthread_mutex_unlock(&mux); sleep(1); } pthread_exit((void *)0); } int main(int argc, char *argv[]) { pthread_t tid1, tid2; int err; err = pthread_create(&tid1, 0, thread_func1, 0); if(err) { printf("error while creating thread 1\\n"); } err = pthread_create(&tid2, 0, thread_func2, 0); if(err) { printf("error while creating thread 2\\n"); } pthread_join(tid1, 0); return 0; }
0
#include <pthread.h> void *writer(void*); void *reader(void*); int sharedValue = 0; int readCount = 0; int writeCount = 0; pthread_mutex_t dbMutex, readMutex; int main(int argc, char *argv[]) { int numReaders; int numWriters; int i; if (argc == 3) { numReaders = atoi(argv[1]); numWriters = atoi(argv[2]); int isNumReadersPositive = numReaders > 0; int isNumWritersPositive = numWriters > 0; if (!isNumReadersPositive) { printf("numReaders must be positive\\n"); } if (!isNumWritersPositive) { printf("numWriters must be positive\\n"); } if (!isNumReadersPositive || !isNumWritersPositive) { exit(1); } } else { printf("Usage: ./a.out <numReaders> <numWriters>\\n"); exit(1); } pthread_mutex_init(&dbMutex, 0); pthread_mutex_init(&readMutex, 0); pthread_t writer_thread_ids[numWriters]; int writer_thread_args[numWriters]; for (i = 0; i < numWriters; ++i) { writer_thread_args[i] = i; pthread_create(&writer_thread_ids[i], 0, writer, &writer_thread_args[i]); } pthread_t reader_thread_ids[numReaders]; int reader_thread_args[numReaders]; for (i = 0; i < numReaders; ++i) { reader_thread_args[i] = i; pthread_create(&reader_thread_ids[i], 0, reader, &reader_thread_args[i]); } for (i = 0; i < numReaders; ++i) { pthread_join(reader_thread_ids[i], 0); } for (i = 0; i < numWriters; ++i) { pthread_join(writer_thread_ids[i], 0); } exit(0); } void *writer(void *arg) { int writer_num; writer_num = *((int*) arg); WRITER_TRY_AGAIN: 0 + 0; if (readCount == 0) { pthread_mutex_lock(&dbMutex); printf("Writer %d is entering the database\\n",writer_num); sharedValue++; printf("Writer %d updated value to %d\\n", writer_num, sharedValue); printf("Writer %d is exiting the database\\n", writer_num); pthread_mutex_unlock(&dbMutex); pthread_exit(0); } else { goto WRITER_TRY_AGAIN; } } void *reader(void *arg) { int reader_num; reader_num = *((int*) arg); pthread_mutex_lock(&readMutex); readCount++; pthread_mutex_unlock(&readMutex); printf("Reader %d is entering the database\\n", reader_num); printf("Reader %d read value from database: %d\\n", reader_num, sharedValue); printf("Reader %d is exiting the database\\n", reader_num); pthread_mutex_lock(&readMutex); readCount--; pthread_mutex_unlock(&readMutex); pthread_exit(0); }
1
#include <pthread.h> int sigpending (sigset_t *set) { struct signal_state *ss = &_pthread_self ()->ss; pthread_mutex_lock (&ss->lock); *set = (ss->pending | process_pending) & ss->blocked; pthread_mutex_unlock (&ss->lock); 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(void) { pthread_key_create(&key, free); } char * getenv(const char *name) { int i; int len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(key, envbuf); } 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], 4096 -1); pthread+mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
1
#include <pthread.h> int thread_count; int local_n; double a, b, h, n, local_a, local_b; double local_int; double total_int = 0; pthread_mutex_t mutex; sem_t sem; void Usage(char* prog_name); void Read_data(double* a, double* b, double* n); void *Pth_trap(void* rank); double Trap(double left_endpt, double right_endpt, int trap_count, double base_len); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; if (argc != 2) Usage(argv[0]); thread_count = atoi(argv[1]); thread_handles = malloc(thread_count*sizeof(pthread_t)); sem_init(&sem, 0, 1); Read_data(&a, &b, &n); h = (b-a)/n; local_n = n/thread_count; for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Pth_trap, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); printf("With n=%lf trapazoids, our estimate\\n", n); printf("of the integral from %f to %f = %.15e\\n", a, b, total_int); printf("%d thread count\\n", thread_count); sem_destroy(&sem); return 0; } void Usage (char* prog_name) { fprintf(stderr, "usage: %s <thread_count>\\n", prog_name); exit(0); } void Read_data(double* a, double* b, double* n) { printf("Please enter value for a: "); scanf("%lf", a); printf("Please enter value for b: "); scanf("%lf", b); printf("How many parts: n="); scanf("%lf", n); } void *Pth_trap(void* rank) { long my_rank = (long) rank; local_a = a + my_rank*local_n*h; local_b = local_a + local_n*h; local_int = Trap(local_a, local_b, local_n, h); pthread_mutex_lock(&mutex); total_int += local_int; pthread_mutex_unlock(&mutex); return 0; } double Trap(double left_endpt, double right_endpt, int trap_count, double base_len) { double estimate, x; int i; estimate = (left_endpt)*(left_endpt) + ((right_endpt)*(right_endpt))/2.0; for (i = 1; i <= trap_count-1; i++) { x = left_endpt + i*base_len; estimate += x*x; } estimate = estimate*base_len; return estimate; }
0
#include <pthread.h> int number=0; void* add(void *ii) { int *num=(int*)ii; int count=10000; while(--count) { (*num)++; } return 0; } void* addlk(void *arg) { pthread_mutex_t *plock = (pthread_mutex_t*)arg; int cnt=10000; while(--cnt) { pthread_mutex_lock(plock); number++; pthread_mutex_unlock(plock); } pthread_exit(0); } int main(int argc,char *argv[]) { pthread_t p1,p2; int i=0; int *ii=&i; pthread_mutex_t lock; pthread_mutex_init(&lock,0); printf("argc = %d ",argc); if(argc-1>0) { pthread_create(&p1,0,addlk,(void*)&lock); pthread_create(&p2,0,addlk,(void*)&lock); pthread_join(p1,0); pthread_join(p1,0); pthread_mutex_destroy(&lock); printf("i = %d",number); } else{ pthread_create(&p1,0,add,(void*)ii); pthread_create(&p2,0,add,(void*)ii); pthread_join(p1,0); pthread_join(p1,0); printf("i = %d",i); } putchar('\\n'); }
1
#include <pthread.h> const char *REF_FILE = "./shm_sem_ref.dat"; int shmid_for_cleanup = 0; pthread_mutex_t *mutex_for_cleanup = 0; struct data { pthread_mutex_t mutex; }; const int SIZE = sizeof(struct data); int create_shm(key_t key, const char *txt, const char *etxt, int flags) { int shm_id = shmget(key, SIZE, flags | 0600); handle_error(shm_id, etxt, PROCESS_EXIT); return shm_id; } int create_sem(key_t key, const int sem_size, const char *txt, const char *etxt, int flags) { int semaphore_id = semget(key, sem_size, flags | 0600); handle_error(semaphore_id, etxt, PROCESS_EXIT); return semaphore_id; } int setup_sem(int semaphore_id, char *etxt) { short semval[1] = { 1 }; int retcode = semctl(semaphore_id, 1, SETALL, &semval); handle_error(retcode, etxt, PROCESS_EXIT); return retcode; } void cleanup() { if (mutex_for_cleanup != 0) { pthread_mutex_destroy(mutex_for_cleanup); mutex_for_cleanup = 0; } if (shmid_for_cleanup > 0) { int retcode = shmctl(shmid_for_cleanup, IPC_RMID, 0); shmid_for_cleanup = 0; handle_error(retcode, "removing of shm failed", NO_EXIT); } } void usage(char *argv0, char *msg) { printf("%s\\n\\n", msg); printf("Usage:\\n\\n%s\\n lock mutexes without lock\\n\\n%s -t <number>\\n lock mutexes with timout after given number of seconds\\n", argv0, argv0); exit(1); } int main(int argc, char *argv[]) { int retcode; if (is_help_requested(argc, argv)) { usage(argv[0], ""); } int use_timeout = (argc >= 2 && strcmp(argv[1], "-t") == 0); create_if_missing(REF_FILE, S_IRUSR | S_IWUSR); key_t shm_key = ftok(REF_FILE, 1); if (shm_key < 0) { handle_error(-1, "ftok failed", PROCESS_EXIT); } time_t tv_sec = (time_t) 200; long tv_nsec = (long) 0; if (use_timeout && argc >= 3) { int t = atoi(argv[2]); tv_sec = (time_t) t; } struct timespec timeout = get_future(tv_sec, tv_nsec); pid_t pid = fork(); if (pid == 0) { printf("in child: sleeping\\n"); sleep(2); int shm_id = create_shm(shm_key, "create", "shmget failed", 0); struct data *data = (struct data *) shmat(shm_id, 0, 0); printf("in child: getting mutex\\n"); if (use_timeout) { retcode = pthread_mutex_timedlock(&(data->mutex), &timeout); } else { retcode = pthread_mutex_lock(&(data->mutex)); } handle_thread_error(retcode, "child failed (timed)lock", PROCESS_EXIT); printf("child got mutex\\n"); sleep(5); printf("child releases mutex\\n"); pthread_mutex_unlock(&(data->mutex)); printf("child released mutex\\n"); sleep(10); retcode = shmdt(data); handle_error(retcode, "child: error while detaching shared memory", PROCESS_EXIT); printf("child exiting\\n"); exit(0); } else { printf("in parent: setting up\\n"); atexit(cleanup); int shm_id = create_shm(shm_key, "create", "shmget failed", IPC_CREAT); shmid_for_cleanup = shm_id; struct data *data = (struct data *) shmat(shm_id, 0, 0); pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&(data->mutex), &mutex_attr); mutex_for_cleanup = &(data->mutex); sleep(2); printf("in parent: getting mutex\\n"); if (use_timeout) { retcode = pthread_mutex_timedlock(&(data->mutex), &timeout); } else { retcode = pthread_mutex_lock(&(data->mutex)); } handle_thread_error(retcode, "parent failed (timed)lock", PROCESS_EXIT); printf("parent got mutex\\n"); sleep(5); printf("parent releases mutex\\n"); pthread_mutex_unlock(&(data->mutex)); printf("parent released mutex\\n"); printf("parent waiting for child to terminate\\n"); int status; waitpid(pid, &status, 0); pthread_mutex_destroy(&(data->mutex)); mutex_for_cleanup = 0; pthread_mutexattr_destroy(&mutex_attr); retcode = shmdt(data); handle_error(retcode, "parent: error while detaching shared memory", PROCESS_EXIT); cleanup(); printf("done\\n"); exit(0); } }
0
#include <pthread.h> struct operation { pthread_cond_t condition; unsigned status; }; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static struct vector operations; bool operations_init(void) { return vector_init(&operations, VECTOR_SIZE_BASE); } void operations_term(void) { size_t index; for(index = 0; index < operations.length; ++index) free(vector_get(&operations, index)); vector_term(&operations); pthread_mutex_destroy(&mutex); } int operation_start(void) { struct operation *operation = malloc(sizeof(*operation)); if (!operation) return ERROR_MEMORY; pthread_cond_init(&operation->condition, 0); operation->status = STATUS_RUNNING; pthread_mutex_lock(&mutex); size_t index; for(index = 0; index < operations.length; ++index) { if (!vector_get(&operations, index)) { vector_get(&operations, index) = operation; goto finally; } } if (!vector_add(&operations, operation)) { pthread_cond_destroy(&operation->condition); free(operation); return ERROR_MEMORY; } finally: pthread_mutex_unlock(&mutex); return index; } bool operation_progress(unsigned operation_id) { struct operation *operation; int status; pthread_mutex_lock(&mutex); operation = vector_get(&operations, operation_id); if (operation->status == STATUS_PAUSED) pthread_cond_wait(&operation->condition, &mutex); status = operation->status; pthread_mutex_unlock(&mutex); return (status == STATUS_RUNNING); } void operation_end(unsigned operation_id) { struct operation *operation; pthread_mutex_lock(&mutex); operation = vector_get(&operations, operation_id); vector_get(&operations, operation_id) = 0; pthread_mutex_unlock(&mutex); pthread_cond_destroy(&operation->condition); free(operation); } void operation_pause(unsigned operation_id) { struct operation *operation; pthread_mutex_lock(&mutex); operation = vector_get(&operations, operation_id); if (operation) operation->status = STATUS_PAUSED; pthread_mutex_unlock(&mutex); } void operation_resume(unsigned operation_id) { struct operation *operation; pthread_mutex_lock(&mutex); operation = vector_get(&operations, operation_id); if (operation) { operation->status = STATUS_RUNNING; pthread_cond_signal(&operation->condition); } pthread_mutex_unlock(&mutex); } void operation_cancel(unsigned operation_id) { struct operation *operation; pthread_mutex_lock(&mutex); operation = vector_get(&operations, operation_id); if (operation) { int status = operation->status; operation->status = STATUS_CANCELLED; if (status == STATUS_PAUSED) pthread_cond_signal(&operation->condition); } pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t odd_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; int countIsOdd = 0; int count = 0; void* oddCounter(void* arg) { int thread_should_exit = 0; int ID = (int)arg; for (;;) { pthread_mutex_lock(&cond_mutex); while (!countIsOdd) { pthread_cond_wait(&odd_cond, &cond_mutex); } pthread_mutex_unlock(&cond_mutex); pthread_mutex_lock( &count_mutex ); if (count < 100) { ++count; printf("Thread %d: %d\\n", ID, count); countIsOdd = 0; } if (count >= 100) { thread_should_exit = 1; } pthread_mutex_unlock( &count_mutex ); if (thread_should_exit) pthread_exit(0); } } void* evenCounter(void* arg) { int thread_should_exit = 0; int ID = (int)arg; for (;;) { pthread_mutex_lock( &count_mutex ); if (count < 100) { if (!countIsOdd) { ++count; printf("Thread %d: %d\\n", ID, count); countIsOdd = 1; pthread_cond_signal(&odd_cond); } } if (count >= 100) { thread_should_exit = 1; } pthread_mutex_unlock( &count_mutex ); if (thread_should_exit) pthread_exit(0); } } int main(void) { pthread_t thread1, thread2; pthread_create( &thread1, 0, oddCounter, (void *)1); pthread_create( &thread2, 0, evenCounter, (void *)2); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); }
0
#include <pthread.h> int broj_sobova = 0, broj_patuljaka = 0; int sob_id[ 11 ], patuljak_id[ 1024 ]; pthread_cond_t u_patuljak[ 1024 ], u_sob[ 11 ], djed; pthread_mutex_t kljuc; pthread_t dretve[ 1024 ]; int dretve_size; void clean_exit( int sig ){ exit( 0 ); } void ulaz_M( pthread_cond_t *uvjet, int *temp ) { pthread_mutex_lock( &kljuc ); while( temp == 0 ) pthread_cond_wait( uvjet, &kljuc ); *temp = 0; pthread_mutex_unlock( &kljuc ); return; } void izlaz_M( pthread_cond_t *uvjet, int *temp ) { pthread_mutex_lock( &kljuc ); *temp = 1; pthread_cond_broadcast( uvjet ); pthread_mutex_unlock( &kljuc ); return; } void *sobovi( void *arg ){ int id = *( int * )arg; pthread_mutex_lock( &kljuc ); printf( "Vratio se sob %d\\n", id + 1 ); if ( broj_sobova == 10 ) { pthread_cond_broadcast( &djed ); } pthread_cond_wait( &u_sob[ id ], &kljuc ); pthread_mutex_unlock( &kljuc ); return 0; } void *patuljci( void *arg ){ int id = *( int * )arg; pthread_mutex_lock( &kljuc ); printf( "Vratio se patuljak %d\\n", id + 1 ); if ( broj_patuljaka >= 3 ) { pthread_cond_broadcast( &djed ); } pthread_cond_wait( &u_patuljak[ id ], &kljuc ); pthread_mutex_unlock( &kljuc ); return 0; } void *djedica( void *arg ){ int i; pthread_mutex_lock( &kljuc ); while ( 1 ) { pthread_cond_wait( &djed, &kljuc ); if ( broj_sobova == 10 && broj_patuljaka > 0 ){ printf( "Raznosim poklone\\n" ); usleep( 2000000 ); for ( i = 0; i < broj_sobova; ++i ) { pthread_cond_broadcast( &u_sob[ i ] ); } broj_sobova = 0; } else if ( broj_sobova == 10 ){ printf( "Hranim sobove\\n" ); usleep( 2000000 ); } else if( broj_patuljaka >= 3 ){ printf( "Konzultacije s patuljcima\\n" ); while ( broj_patuljaka >= 3 ) { usleep( 2000000 ); for ( i = 1; i <= 3; ++i ) { pthread_cond_broadcast( &u_patuljak[ broj_patuljaka - i ] ); } broj_patuljaka -= 3; } } } pthread_mutex_unlock( &kljuc ); return 0; } void *sjeverni_pol( void *arg ){ while ( 1 ) { if( broj_sobova < 10 && rand() & 1 ){ pthread_mutex_lock( &kljuc ); sob_id[ broj_sobova ] = broj_sobova; dretve_size++; if ( pthread_create( &dretve[dretve_size], 0, sobovi, &( sob_id[broj_sobova] ) ) ){ printf( "Greska prlikom stvaraja dretve!\\n" ); clean_exit( 0 ); } broj_sobova++; pthread_mutex_unlock( &kljuc ); } usleep( 1000000 ); if( rand() & 1 ){ pthread_mutex_lock( &kljuc ); patuljak_id[ broj_patuljaka ] = broj_patuljaka; dretve_size++; if( pthread_create( &dretve[dretve_size], 0, patuljci, &( patuljak_id[ broj_patuljaka ] ) ) ){ printf( "Greska prlikom stvaranja dretve" ); clean_exit( 0 ); } broj_patuljaka++; pthread_mutex_unlock( &kljuc ); } usleep( 1000000 ); } return 0; } int main(int argc, char **argv) { srand( (unsigned)time( 0 ) ); int i = 0; sigset( SIGINT, clean_exit ); pthread_mutex_init( &kljuc, 0 ); if( pthread_create( &dretve[ dretve_size ], 0, sjeverni_pol, 0 ) ) { printf( "Greska prilikom stvaranaj dretve1\\n" ); clean_exit( 0 ); } ++dretve_size; if ( pthread_create( &dretve[ dretve_size ], 0, djedica, 0 ) ) { printf( "Greska prilikom stvaranja dretve!\\n" ); clean_exit( 0 ); } for ( i = 0; i <= dretve_size; ++i ) { pthread_join( dretve[ i ], 0 ); } return 0; }
1
#include <pthread.h> static pthread_key_t key; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t init_done = PTHREAD_ONCE_INIT; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv_r(const char *name, char *buf, int buflen) { 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(4096); if(envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } 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], 4096 - 1); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return (0); }
0
#include <pthread.h> int inc; int nbthreads; int ok; pthread_t *tid; pthread_mutex_t mutex_inc = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut_createok = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_createok = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut_sigint = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_sigint = PTHREAD_COND_INITIALIZER; void* thread_handler(void* arg) { printf("Thread [%i] créée\\n",(int)pthread_self()); pthread_mutex_lock(&mutex_inc); inc++; if(inc < nbthreads){ if(pthread_create(&tid[inc], 0, thread_handler, 0)!=0){ perror("pthread_create \\n"); exit(1); } pthread_mutex_unlock(&mutex_inc); } else { pthread_mutex_unlock(&mutex_inc); pthread_mutex_lock(&mut_createok); pthread_cond_signal(&cond_createok); pthread_mutex_unlock(&mut_createok); } pthread_mutex_lock(&mut_sigint); pthread_cond_wait(&cond_sigint, &mut_sigint); pthread_mutex_unlock(&mut_sigint); printf("Thread [%i] terminée\\n",(int)pthread_self()); pthread_exit((void*)0); } void handle_sigint(int sig){ if(sig==SIGINT) ok=1; printf("\\n CTRL+C reçu !\\n"); } int main (int argc, char **argv){ nbthreads = atoi(argv[1]); int i, inc=0; int *index = 0; index = calloc(nbthreads, sizeof(int)); for(i=0;i<nbthreads;i++) index[i]=i; tid = malloc(sizeof(pthread_t)*nbthreads); sigset_t sig_proc; sigemptyset(&sig_proc); sigfillset(&sig_proc); sigprocmask(SIG_SETMASK,&sig_proc,0); struct sigaction action; action.sa_mask=sig_proc; action.sa_flags=0; action.sa_handler=handle_sigint; sigaction(SIGINT,&action,0); if(pthread_create(&tid[0], 0, thread_handler, 0)!=0){ perror("pthread_create \\n"); exit(1); } pthread_mutex_lock(&mut_createok); pthread_cond_wait(&cond_createok, &mut_createok); pthread_mutex_unlock(&mut_createok); printf("Tous mes descendants sont créés\\n"); sigdelset(&sig_proc, SIGINT); sigprocmask(SIG_SETMASK, &sig_proc, 0); printf("En attente de CTRL+C\\n"); while(!ok) sleep(2); pthread_mutex_lock(&mut_sigint); pthread_cond_broadcast(&cond_sigint); pthread_mutex_unlock(&mut_sigint); for(i=0;i<nbthreads;i++){ if(pthread_join(tid[i], 0)!=0){ perror("pthread_join \\n"); exit(1); } } printf("Tous mes descendants sont terminés\\n"); printf("fin thread main \\n" ); return 0; }
1
#include <pthread.h> int buffer[5]; int bufferindicator = 0; pthread_mutex_t cmutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condvar = PTHREAD_COND_INITIALIZER; void* writer_thread(void *arg) { int loopindex = 0; int bufferindex = 0; pthread_mutex_lock(&cmutex); while(bufferindex < 5) { while (bufferindicator == 5) pthread_cond_wait(&condvar,&cmutex); buffer[bufferindex] = loopindex; printf("Written value in buffer[%d]\\n", bufferindex ); bufferindicator++; pthread_cond_signal(&condvar); if (++loopindex == 20) break; if (bufferindex == (5 -1)) bufferindex = 0; else bufferindex++; } pthread_mutex_unlock(&cmutex); return 0; } void* reader_thread(void *arg) { int loopindex = 0; int bufferindex = 0; pthread_mutex_lock(&cmutex); while(bufferindex < 5) { while (bufferindicator == 0) pthread_cond_wait(&condvar,&cmutex); printf("buffer[%d] = %d\\n",bufferindex, buffer[bufferindex]); bufferindicator--; pthread_cond_signal(&condvar); if (++loopindex == 20) break; if (bufferindex == (5 -1)) bufferindex = 0; else bufferindex++; } pthread_mutex_unlock(&cmutex); return 0; } int main(void) { pthread_t tid1,tid2; int rv1,rv2; pthread_attr_t attr; pthread_attr_init(&attr); rv1 = pthread_create(&tid1,&attr,(void *)writer_thread,0); if(rv1 != 0) { printf("\\n Cannot create thread"); exit(0); } rv1 = pthread_create(&tid2,&attr,(void *)reader_thread,0); if(rv1 != 0) { printf("\\n Cannot create thread"); exit(0); } pthread_join(tid1,0); pthread_join(tid2,0); return(0); }
0
#include <pthread.h> pthread_mutex_t pi_mutex; double iterations; double x,y,z; int count=0; struct timeval tm1, tm2; void start() { gettimeofday(&tm1, 0); } void stop() { gettimeofday(&tm2, 0); unsigned long long t = ((tm2.tv_sec - tm1.tv_sec) * 1000000) + (tm2.tv_usec - tm1.tv_usec); printf("\\n%llu microseconds occured\\n",t); } double getRand(double min, double max) { double d = (double)rand() / 32767; return min + d * (max - min); } void *Cal_pi(void *t) { int i=0; double min=0.00001, max=1.0; int tid = (long)t; double lines = iterations/60; double start = tid*lines; double stop = start+lines-1; for ( i=start; i<=stop; i++) { pthread_mutex_lock(&pi_mutex); x = getRand(min,max); pthread_mutex_unlock(&pi_mutex); pthread_mutex_lock(&pi_mutex); y = getRand(min,max); pthread_mutex_unlock(&pi_mutex); z = x*x+y*y; if (z<=1) { count++; } } pthread_exit(0); } int main(int argc, char* argv[]) { start(); int rc; long t; pthread_t threads[60]; pthread_mutex_init(&pi_mutex,0); double pi; int j; iterations = atof(argv[1]); for(t=0;t<60;t++) { rc = pthread_create(&threads[t],0,Cal_pi,(void *)t); if(rc) { printf("ERROR; return code from pthread_create() is %d\\n",rc); exit(-1); } } for(j=0;j<60;j++) { rc = pthread_join(threads[j], 0); if(rc) { printf("\\n Error occured in pthread_join %d",rc); } } pi=(double)count/iterations*4; printf("pi is %g \\n",pi); pthread_mutex_destroy(&pi_mutex); stop(); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t lock; void *searchString(void* nama); int main(){ char nama1[100],nama2[100]; scanf("%s",nama1); scanf("%s",nama2); pthread_t t1,t2; pthread_create(&t1,0,searchString,nama1); pthread_create(&t2,0,searchString,nama2); pthread_join(t1,0); pthread_join(t2,0); } void *searchString(void* nama){ pthread_mutex_lock(&lock); FILE *fp; fp=fopen("Novel.txt","r"); int hasil=0; char *name_it= (char *)nama; char temp[100]; while(fscanf(fp,"%100s",temp)!=EOF){ if(strcasestr(temp,name_it)){ hasil++; } } printf("total %s : %d\\n",name_it,hasil); fclose(fp); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> int ticket_cnt = 30; { int thd_id_; pthread_mutex_t *p_mutex_; }DATA, *pDATA; void *handler(void *arg) { int thd_id = ((pDATA)arg)->thd_id_; pthread_mutex_t *p_mutex = ((pDATA)arg)->p_mutex_; printf("window %d on! \\n", thd_id); while(1) { pthread_mutex_lock(p_mutex); if(ticket_cnt == 0) { printf("ticket sold out! \\n"); pthread_mutex_unlock(p_mutex); free((pDATA)arg); return (void *)0; } ticket_cnt --; sleep(rand() % 2 + 1); printf("window %d sold a ticket, ticket left %d \\n", thd_id, ticket_cnt); pthread_mutex_unlock(p_mutex); sleep(rand() % 2 +1); } } int main (int argc, char *argv[]) { srand(getpid()); pthread_mutex_t mutex; pthread_mutex_init(&mutex, 0); int thd_cnt = atoi(argv[1]); pthread_t *p_thd = (pthread_t *)calloc(thd_cnt, sizeof (pthread_t)); int ix; for(ix = 0; ix < thd_cnt; ix ++) { pDATA p_info = (pDATA)calloc(1, sizeof (DATA)); p_info->thd_id_ = ix; p_info->p_mutex_ = &mutex; pthread_create(p_thd + ix, 0, handler, (void *)p_info); } printf("joining threads....\\n"); for(ix = 0; ix < thd_cnt; ix ++) { pthread_join(p_thd[ix], 0); } pthread_mutex_destroy(&mutex); return 0 ; }
1
#include <pthread.h> pthread_t wid[2], rid[5]; struct buffer_item{ int rand; int line_number; }; FILE* buffer; int total_line = 0; int readerCnt =0, writerCnt = 0; pthread_mutex_t accessReaderCnt = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t accessWriterCnt = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t writeLock = PTHREAD_MUTEX_INITIALIZER; sem_t readerLock; pthread_mutex_t outerLock = PTHREAD_MUTEX_INITIALIZER; int write_item(int item){ buffer = fopen("output.txt","a+"); if(!buffer) return -1; fprintf(buffer, "%d\\n",item); fclose(buffer); printf("<-- writer added %d at line %d\\n",item, total_line); total_line++; return 0; } int read_item(struct buffer_item* item){ if(!buffer) return -1; if(total_line == 0){ }else if(total_line == 1){ fseek(buffer, 0, 0); fscanf(buffer,"%d\\n",&item->rand); printf("reader read %d from line 0\\n",item->rand); }else{ unsigned int seed; item->line_number = rand_r(&seed)%total_line; int copy_line_num = item->line_number; copy_line_num++; fseek(buffer, 0, 0); while(copy_line_num--){ fscanf(buffer,"%d\\n",&item->rand); } printf("reader read %d from line %d\\n",item->rand, item->line_number); } return 0; } void* writer(void* in){ while(1){ pthread_mutex_lock(&accessWriterCnt); { writerCnt++; if(writerCnt == 1) sem_wait(&readerLock); } pthread_mutex_unlock(&accessWriterCnt); pthread_mutex_lock(&writeLock); { unsigned int seed; int temp = rand_r(&seed); if(write_item(temp)) printf("error in writing\\n"); } pthread_mutex_unlock(&writeLock); pthread_mutex_lock(&accessWriterCnt); { writerCnt--; if(writerCnt ==0 )sem_post(&readerLock); } unsigned int seed; sleep(rand_r(&seed)%5); pthread_mutex_unlock(&accessWriterCnt); } pthread_exit((void*)0); } void* reader(void* in){ while(1){ pthread_mutex_lock(&outerLock); { sem_wait(&readerLock); { pthread_mutex_lock(&accessReaderCnt); { readerCnt++; if(readerCnt ==1){ pthread_mutex_lock(&writeLock); buffer = fopen("output.txt","r"); } } pthread_mutex_unlock(&accessReaderCnt); } sem_post(&readerLock); } pthread_mutex_unlock(&outerLock); struct buffer_item temp; if(read_item(&temp)) printf("error in reading\\n"); pthread_mutex_lock(&accessReaderCnt); { readerCnt--; if(readerCnt == 0){ fclose(buffer); pthread_mutex_unlock(&writeLock); } } pthread_mutex_unlock(&accessReaderCnt); unsigned int seed; sleep(rand_r(&seed)%5); } pthread_exit((void*)0); } int main(){ int i; sem_init(&readerLock,0,5); for(i=0; i<2; ++i){ pthread_create(&wid[i],0,writer,0); } for(i =0; i<5; ++i){ pthread_create(&rid[i],0,reader,0); } sleep(10); for(i=0; i<2; ++i){ pthread_cancel(wid[i]); } for(i =0; i<5; ++i){ pthread_cancel(rid[i]); } return 0; }
0
#include <pthread.h> static int print_flag = 0; int thread_num; int items_per_thread; int buf[32][10]; int in[32]; int out[32]; int no_elems[32]; int no_items_sent[32]; int no_items_received[32]; pthread_mutex_t lock[32]; pthread_cond_t cond_full[32]; } buffer_t; static buffer_t buffer; void init_buffer(void) { items_per_thread = 8*(1024*1024)/thread_num; int i = 0; for (i =0; i<thread_num; i++) { buffer.no_elems[i] = 0; buffer.in[i] = 0; buffer.out[i] = 0; buffer.no_items_sent[i] = 0; buffer.no_items_received[i] = 0; pthread_mutex_init(&buffer.lock[i], 0); pthread_cond_init(&buffer.cond_full[i],0); } } void *consumer(void *thr_id) { int item; long my_id = (long) thr_id; while(1) { pthread_mutex_lock(&buffer.lock[my_id]); if (buffer.no_elems[my_id]==0){ pthread_cond_wait(&buffer.cond_full[my_id],&buffer.lock[my_id]); } item = buffer.buf[my_id][buffer.out[my_id]]; buffer.out[my_id] = (buffer.out[my_id]+1)%10; buffer.no_elems[my_id]--; buffer.no_items_received[my_id]++; if (print_flag){ printf("Consumer %d got number %d from buffer\\n",my_id, item); fflush(stdout); } pthread_mutex_unlock(&buffer.lock[my_id]); if (buffer.no_items_received[my_id] == items_per_thread){ break; } } if (print_flag) printf("CBreak 4: tid %d\\n", my_id); pthread_exit(0); } void *producer(void *thr_id) { int item; long my_id = (long) thr_id; if (print_flag) printf("Pstart 4: tid %d\\n", my_id); while(1) { pthread_mutex_lock(&buffer.lock[my_id]); if (buffer.no_elems[my_id]<10){ item = items_per_thread*my_id + buffer.no_items_sent[my_id]; buffer.no_items_sent[my_id]++; buffer.buf[my_id][buffer.in[my_id]] = item; buffer.in[my_id] = (buffer.in[my_id] + 1) % 10; buffer.no_elems[my_id]++; pthread_cond_signal(&buffer.cond_full[my_id]); if (print_flag){ printf("Producer %d put number %d in buffer\\n", my_id, item); fflush(stdout); } } pthread_mutex_unlock(&buffer.lock[my_id]); if (buffer.no_items_sent[my_id] == items_per_thread) break; } if (print_flag) printf("PBreak 4: tid %d\\n", my_id); pthread_exit(0); } void read_options(int argc, char **argv) { char *prog; while (++argv, --argc > 0) { if (**argv == '-') switch ( *++*argv ) { case 'n': --argc; thread_num = atoi(*++argv); break; case 'p': --argc; print_flag = atoi(*++argv); break; default: break; } } } int main(int argc, char **argv) { long i; pthread_t prod_thrs[32]; pthread_t cons_thrs[32]; pthread_attr_t attr; read_options(argc,argv); init_buffer(); pthread_attr_init (&attr); printf("Buffer size = %d, items to send = %d\\n", thread_num, 8*(1024*1024)); for(i = 0; i < thread_num; i++) pthread_create(&prod_thrs[i], &attr, producer, (void *)i); for(i = 0; i < thread_num; i++) pthread_create(&cons_thrs[i], &attr, consumer, (void *)i); for (i = 0; i < thread_num; i++) pthread_join(prod_thrs[i], 0); for (i = 0; i < thread_num; i++) pthread_join(cons_thrs[i], 0); return 0; }
1
#include <pthread.h> sem_t emptyPot; sem_t fullPot; void *savage (void*); void *cook (void*); static pthread_mutex_t print_mutex; static int servings = 15; int getServingsFromPot(int savage_id) { if (servings > 0) { servings--; printf("-------serving%d------\\n",servings); sleep(2); pthread_mutex_lock (&print_mutex); printf ("Savage: %i is DONE eating\\n", savage_id); pthread_mutex_unlock (&print_mutex); } } void putServingsInPot () { servings =15; sem_post (&fullPot); } void *cook (void *id) { int cook_id = *(int *)id; int i; while ( 1 ) { sem_wait (&emptyPot); putServingsInPot (); pthread_mutex_lock (&print_mutex); printf ("\\nCook filled pot\\n\\n"); pthread_mutex_unlock (&print_mutex); } pthread_exit(0); return 0; } void *savage (void *id) { int savage_id = *(int *)id; int myServing; sleep(2); while (1) { if (servings == 0) { sem_post (&emptyPot); sem_wait (&fullPot); } pthread_mutex_lock (&print_mutex); printf ("Savage: %d is eating\\n", savage_id); pthread_mutex_unlock (&print_mutex); getServingsFromPot(savage_id); } pthread_exit(0); return 0; } int main() { int i, id[3 +1]; pthread_t tid[3 +1]; pthread_mutex_init(&print_mutex, 0); sem_init(&emptyPot, 0, 0); sem_init(&fullPot, 0, 0); for (i=0; i<3; i++) { id[i] = i; printf("Savage %d entered \\n", id[i]); pthread_create (&tid[i], 0, savage, (void *)&id[i]); } pthread_create (&tid[i], 0, cook, (void *)&id[i]); for (i=0; i<3; i++) pthread_join(tid[i], 0); }
0
#include <pthread.h> int file_fd; int philNum; char** phils; pthread_mutex_t* forks; pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; double* waitingTime; void PrintLogString(char* s, int id) { time_t timer; char logString[70] = {0}; pthread_mutex_lock(&screen); time(&timer); memcpy(logString, ctime(&timer) + 11, 8); strcat(logString, " "); strcat(logString, phils[id]); strcat(logString, s); write(file_fd, logString, strlen(logString)); pthread_mutex_unlock(&screen); } void Eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % philNum; PrintLogString(" need forks!\\n", id); struct timeval startTime, finTime; gettimeofday(&startTime, 0); for(i = 0; i < 2; i++) { pthread_mutex_lock(forks + f[i]); char s[30]; sprintf(s," has got the fork%d\\n",f[i]); PrintLogString(s, id); usleep(50000); } gettimeofday(&finTime, 0); waitingTime[id] += (double)finTime.tv_sec - (double)startTime.tv_sec + ((double)finTime.tv_usec) / 1000000 - ((double)startTime.tv_usec) / 1000000; PrintLogString(" starts eating\\n", id); for(i = 0, ration = 3 + rand() % 8; i < ration; i++) usleep(10000); PrintLogString(" finishes eating\\n", id); for(i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]); } void Think(int id) { PrintLogString(" starts thinking\\n", id); int i, t; do { t = rand() % 5; usleep(15000 + rand() % 10000); } while(t); PrintLogString(" finishes thinking\\n", id); } void* Philosophize(void* a) { int id = *(int*)a; while(1) { Think(id); Eat(id); } } int main(int argc, char** argv) { if (argc != 2) { write(1, "wrong number of arguments\\n", 26); _exit(1); } srand(time(0)); file_fd = open("LOG.txt", O_WRONLY | O_TRUNC | O_CREAT, 00200); if(file_fd < 0) { perror("open() error"); _exit(2); } philNum = atoi(argv[1]); phils = (char**)malloc(philNum*sizeof(char*)); int i; for(i = 0; i < philNum; i++) { phils[i] = (char*)malloc(20*sizeof(char)); sprintf(phils[i],"philosopher%d",i + 1); } forks = (pthread_mutex_t*)malloc(philNum*sizeof(pthread_mutex_t)); int* id = (int*)malloc(philNum*sizeof(int)); pthread_t* tid = (pthread_t*)malloc(philNum*sizeof(pthread_t)); for(i = 0; i < philNum; i++) pthread_mutex_init(forks + (id[i] = i), 0); for(i = 0; i < philNum; i++) pthread_create(tid + i, 0, Philosophize, id + i); waitingTime = (double*)calloc(philNum, sizeof(double)); sleep(20); for(i = 0; i < philNum; i++) printf("%d %f\\n", i, waitingTime[i]); free(waitingTime); for(i = 0; i < philNum; i++) pthread_cancel(tid[i]); for(i = 0; i < philNum; i++) pthread_mutex_destroy(forks + i); free(tid); free(id); for(i = 0; i < philNum; i++) free(phils[i]); free(phils); close(file_fd); pthread_mutex_destroy(&screen); return 0; }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &condition_mutex ); while( count >= 3 && count <= 6 ) { pthread_cond_wait( &condition_cond, &condition_mutex ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &condition_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_cond ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount2: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
0
#include <pthread.h> void ports_enable_class (struct port_class *class) { pthread_mutex_lock (&_ports_lock); class->flags &= ~PORT_CLASS_NO_ALLOC; if (class->flags & PORT_CLASS_ALLOC_WAIT) { class->flags &= ~PORT_CLASS_ALLOC_WAIT; pthread_cond_broadcast (&_ports_block); } pthread_mutex_unlock (&_ports_lock); }
1
#include <pthread.h> static void print_newest_message(struct arguments* args); void* writeserver_thread_func(void* arg) { struct arguments* args = arg; struct return_info return_codes; (users+args->user_id)->write_connected = 1; while(1) { print_newest_message(args); sleep(1); return_codes = send_string(&test_connection, args->socket_fd); if(return_codes.error_occured) break; } (users+args->user_id)->write_connected = 0; printf("writeshutdown\\n"); pthread_exit(0); } static void print_newest_message(struct arguments* args) { pthread_mutex_lock(&(users+args->user_id)->messages->mutex); struct string* message = dynamic_array_at((users+args->user_id)->messages,0); if(message != 0) { printf("message: %s\\n", message->data); convert_string(message); send_string(message, args->socket_fd); free(message->data); dynamic_array_remove((users+args->user_id)->messages,0); } pthread_mutex_unlock(&(users+args->user_id)->messages->mutex); }
0
#include <pthread.h> { pthread_mutex_t *right; pthread_mutex_t *left; pthread_t thread; int num; int fail; int numTimesToEat; } Philosopher; void *simulation(void *p) { Philosopher *phil = (Philosopher*)p; int failed; int tries_left; pthread_mutex_t *left, *right, *temp; int i; for(i=0;i<phil->numTimesToEat;++i) { printf("Philosopher %d is thinking\\n", phil->num+1); sleep( 1+ rand()%8); left = phil->left; right = phil->right; printf("Philosopher %d is hungry\\n", phil->num+1); tries_left = 2; do { failed = pthread_mutex_lock( left); if(tries_left>0)failed = pthread_mutex_trylock(right); else failed = pthread_mutex_lock(right); if (failed) { pthread_mutex_unlock(left); temp = left; left = right; right = temp; tries_left--; } } while(failed); if (!failed) { printf("Philosopher %d is eating\\n", phil->num+1); if(i==phil->numTimesToEat-1) printf("Philosopher %d is done eating.\\n",phil->num+1); sleep( 1+ rand() % 8); pthread_mutex_unlock( right); pthread_mutex_unlock( left); } } return 0; } int main(int argc, char * argv[]) { if(argc!=3) { printf("Error you need arguments to run this program\\n"); return -1; } sem_t mutual_exclusion; int numPhil = atoi(argv[1]); int numTimesToEat = atoi(argv[2]); int total = 0; int wait_status; if(numPhil<=2 || (numTimesToEat <1||numTimesToEat>1000)) { printf("Error you need more than 2 philosophers and they need to eat 1-1000 times\\n"); return -2; } pthread_mutex_t forks[numPhil]; Philosopher philosophers[numPhil]; Philosopher *phil; int i; for (i=0;i<numPhil; i++) pthread_mutex_init(&forks[i], 0); for (i=0;i<numPhil; i++) { phil = &philosophers[i]; phil->left = &forks[i]; phil->right = &forks[(i+1)%numPhil]; phil->num=i; phil->numTimesToEat=numTimesToEat; phil->fail = pthread_create( &phil->thread, 0, simulation, phil); } sleep(1); for(i=0; i<numPhil; i++) { phil = &philosophers[i]; pthread_join( phil->thread, 0); } return 0; }
1
#include <pthread.h> pthread_mutex_t bankSem; int num_customers; int balance; int id; int type; int amount; }cust_struct; void deposit(int i,int amt); void withdraw(int i,int amt); void cust(cust_struct * info); int main(int argc,char *argv[]){ int n,type; cust_struct *info; pthread_t cus[25]; void * retval; int stime; long ltime; if(argc != 3) { printf("error!!!!\\n"); puts("usage: bank number_of_customers initial_balance, ex bank 5 500\\n"); exit(0); } num_customers = atoi(argv[1]); balance = atoi(argv[2]); printf("the initial balance is: $%d.00\\n",balance); pthread_mutex_init(&bankSem, 0); ltime = time(0); stime = (unsigned) ltime/2; srand(stime); for (n = 0;n<num_customers;n++){ info = (cust_struct *)malloc(sizeof(cust_struct)); info->id = n; info->type = (rand()%200)/100; info->amount= rand()%400 + 1; if (pthread_create(&(cus[n]), 0, (void *)cust, info) != 0) { perror("pthread_create"); exit(1); } } for (n = 0;n<num_customers;n++){ pthread_join(cus[n],0); } return 0; } void withdraw(int i,int amt){ pthread_mutex_lock(&bankSem); printf("customer %d is trying to withdraw $%d.00,\\n",i,amt); if( balance < amt){ printf("not enough funds, withdrawer %d will need to go away\\n",i); printf("---------------------------------------------\\n"); } else { printf("customer %d is withdrawing from balance = $%d.00 an amt = $%d.00\\n",i,balance,amt); balance = balance - amt; printf("new balance is $%d.00.\\n",balance); } pthread_mutex_unlock(&bankSem); return; } void deposit(int i,int amt){ pthread_mutex_lock(&bankSem); printf("cust %d is depositing $%d.00 into balance process\\n",i, amt); balance = balance + amt; printf("new balance is $%d.00.\\n",balance); printf("---------------------------------------------\\n"); pthread_mutex_unlock(&bankSem); return; } void cust(cust_struct * info){ int n=0; switch(info->type){ case 0:{ printf("I am a depositor, ID=%d, amount = $%d.00 \\n", info->id,info->amount); deposit(info->id,info->amount); pthread_exit(0); } case 1:{ printf("I am a withdrawer, ID=%d, amount = $%d.00 \\n", info->id,info->amount); withdraw(info->id,info->amount); pthread_exit(0); } } }
0
#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 unlock locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread stared ...\\n"); pause(); return (0); } int main(int argc, char *argv[]) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) { fprintf(stderr, "pthread_atfork failed: %s\\n", strerror(err)); return (err); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { fprintf(stderr, "pthread_create failed: %s\\n", strerror(err)); return (err); } sleep(2); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) { fprintf(stderr, "fork failed: %s\\n", strerror(errno)); return (errno); } else if (pid == 0) { printf("child returned from fork\\n"); } else { printf("parent return from fork\\n"); } return 0; }
1
#include <pthread.h> struct pp_thread_info { int *msgcount; pthread_mutex_t *mutex; char *msg; int modval; }; void * pp_thread(void *arg) { int c, done; struct pp_thread_info *infop; infop = arg; done = 0; while (1) { pthread_mutex_lock(infop->mutex); done = *infop->msgcount >= 50; if (*infop->msgcount % 2 == infop->modval) { printf("%s\\n", infop->msg); c = *infop->msgcount; usleep(10); c = c + 1; *infop->msgcount = c; } pthread_mutex_unlock(infop->mutex); if (done) break; } return (0); } int main(void) { pthread_t ping_id1, pong_id1; pthread_t ping_id2, pong_id2; pthread_mutex_t mutex; struct pp_thread_info ping, pong; int msgcount; msgcount = 0; if (pthread_mutex_init(&mutex, 0) != 0) { fprintf(stderr, "Pingpong: Mutex init failed %s\\n", strerror(errno)); exit(1); } ping.msgcount = &msgcount; ping.mutex = &mutex; ping.msg = "ping"; ping.modval = 0; pong.msgcount = &msgcount; pong.mutex = &mutex; pong.msg = "pong"; pong.modval = 1; if ((pthread_create(&ping_id1, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id1, 0, &pp_thread, &pong) != 0) || (pthread_create(&ping_id2, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id2, 0, &pp_thread, &pong) != 0)) { fprintf(stderr, "pingpong: pthread_create failed %s\\n", strerror(errno)); exit(1); } pthread_join(ping_id1, 0); pthread_join(pong_id1, 0); pthread_join(ping_id2, 0); pthread_join(pong_id2, 0); pthread_mutex_destroy(&mutex); printf("Main thread exiting\\n"); }
0
#include <pthread.h> int threads=1024; int threads_max=20; int counter1=0; int counter1_start=180000; int counter1_stop=1000000; int counter1_warn=200000; int counter_de_nr=0; int koniec=0; int sleep_time=750; int *ile_watk; pthread_cond_t warunek1 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int getch (void) { int key; struct termios oldSettings, newSettings; tcgetattr(STDIN_FILENO, &oldSettings); newSettings = oldSettings; newSettings.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newSettings); key = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings); return key; } void* counter_in(void *arg) { for(;;) { pthread_mutex_lock(&mutex1); counter1++; pthread_mutex_unlock(&mutex1); usleep(900); } return 0; } void* manager(void *arg) { for(;;) { if ( counter1>=counter1_warn ) { pthread_cond_signal(&warunek1); } usleep(sleep_time); } return 0; } void* counter_de(void *arg) { int k=0; char t; t = *((int*) arg); pthread_mutex_lock(&mutex2); counter_de_nr++; pthread_mutex_unlock(&mutex2); printf("\\n"); while(koniec!=t) { pthread_mutex_lock(&mutex1); pthread_cond_wait(&warunek1 ,&mutex1); printf ("%d \\n",t); counter1--; pthread_mutex_unlock(&mutex1); usleep(5000); } printf("\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n.............................................................................\\n\\n\\n\\n\\n.%d\\n",t); pthread_mutex_unlock(&mutex1); koniec=-1; counter_de_nr--; pthread_exit(0); return 0; } void* klawiatura1(void *w) { unsigned long int *p; p=(unsigned long int*)w; pthread_t *w2=(pthread_t*)w; printf("keyboard active!\\n"); int str3[threads_max]; sleep(1); int k=0; int i=0; for(;;) { k=getch(); if (k==120) { sleep_time=sleep_time-10; k=0; } if (k==115) { sleep_time=sleep_time+10; k=0; } if (k==107) { koniec=counter_de_nr; k=0; } if (k==110 && counter_de_nr<threads_max){ str3[counter_de_nr]=counter_de_nr+1; pthread_create(&w2[counter_de_nr], 0, counter_de,&str3[counter_de_nr]); k=0; } if (k==97) { printf("\\n\\n\\nc1:\\t%d\\tsleep:\\t%d\\n",counter1,sleep_time); k=0; } if (k==122) { printf("\\n\\n\\ncounter_de_nr:\\t%d\\n",counter_de_nr); for (i=0;i<counter_de_nr;i++) { printf("%lu\\t",(unsigned long int)p[i]); } printf("\\n\\n"); k=0; } k=0; } } int main(int argc, char* argv[]) { counter1=counter1_start; pthread_t workers[threads_max]; pthread_t counter; pthread_attr_t attr; pthread_t klawiatura; pthread_attr_init( &attr ); pthread_create(&klawiatura,0,klawiatura1,(void*)workers); char str1[4]; int str2[threads_max]; int i=0; for (i=0;i<threads_max;i++) { str2[i]=i; pthread_create(&workers[i], &attr, counter_de,&str2[i]); } printf("counter_de: %d\\n",counter_de_nr); for (i=0;i<threads_max;i++) printf("%lu\\t",workers[i]); ile_watk=&i; pthread_create(&counter, &attr, counter_in, 0); manager(0); for (i=0;i<threads;i++) { pthread_join(workers[i], 0); } return 0; }
1
#include <pthread.h> struct ks_xact *ks_xact_alloc(struct ks_conn *conn) { struct ks_xact *xact; xact = malloc(sizeof(*xact)); if (!xact) return 0; memset(xact, 0, sizeof(*xact)); xact->refcnt = 1; xact->conn = conn; xact->id = conn->seqnum; xact->autocommit = TRUE; xact->state = KS_XACT_STATE_NULL; pthread_mutex_init(&xact->state_lock, 0); pthread_cond_init(&xact->state_cond, 0); return xact; } struct ks_xact *ks_xact_get(struct ks_xact *xact) { assert(xact->refcnt > 0); assert(xact->refcnt < 100000); if (xact) xact->refcnt++; return xact; } void ks_xact_put(struct ks_xact *xact) { assert(xact->refcnt > 0); assert(xact->refcnt < 100000); xact->refcnt--; if (!xact->refcnt) { pthread_cond_destroy(&xact->state_cond); pthread_mutex_destroy(&xact->state_lock); pthread_mutex_destroy(&xact->requests_lock); free(xact); } } struct ks_req *ks_xact_queue_new_request( struct ks_xact *xact, __u16 type, __u16 flags) { assert(xact->state != KS_XACT_STATE_COMPLETED); struct ks_req *req; req = ks_req_alloc(xact); if (!req) return ks_req_get(&ks_nomem_request); req->type = type; req->flags = flags; req->response_callback = 0; ks_xact_queue_request(xact, req); return req; } struct ks_req *ks_xact_queue_new_request_callback( struct ks_xact *xact, __u16 type, __u16 flags, int (*callback)(struct ks_req *req, struct nlmsghdr *nlh)) { struct ks_req *req; req = ks_req_alloc(xact); if (!req) return ks_req_get(&ks_nomem_request); req->type = type; req->flags = flags; req->response_callback = callback; pthread_mutex_lock(&xact->requests_lock); list_add_tail(&ks_req_get(req)->node, &xact->requests); pthread_mutex_unlock(&xact->requests_lock); return req; } int ks_xact_begin(struct ks_xact *xact) { struct ks_req *req; req = ks_xact_queue_new_request(xact, KS_NETLINK_BEGIN, NLM_F_REQUEST); if (req->err < 0) return req->err; ks_xact_submit(xact); ks_req_wait(req); ks_req_put(req); return 0; } int ks_xact_commit(struct ks_xact *xact) { struct ks_req *req; req = ks_xact_queue_new_request(xact, KS_NETLINK_COMMIT, NLM_F_REQUEST); if (req->err < 0) return req->err; ks_req_wait(req); ks_req_put(req); return 0; } int ks_xact_abort(struct ks_xact *xact) { struct ks_req *req; req = ks_xact_queue_new_request(xact, KS_NETLINK_ABORT, NLM_F_REQUEST); if (req->err < 0) return req->err; ks_req_wait(req); ks_req_put(req); return 0; } struct ks_req *ks_xact_queue_begin(struct ks_xact *xact) { return ks_xact_queue_new_request(xact, KS_NETLINK_BEGIN, NLM_F_REQUEST); } struct ks_req *ks_xact_queue_commit(struct ks_xact *xact) { return ks_xact_queue_new_request(xact, KS_NETLINK_COMMIT, NLM_F_REQUEST); } struct ks_req *ks_xact_queue_abort(struct ks_xact *xact) { return ks_xact_queue_new_request(xact, KS_NETLINK_ABORT, NLM_F_REQUEST); } int ks_xact_submit(struct ks_xact *xact) { assert(xact->state == KS_XACT_STATE_NULL); ks_conn_add_xact(xact->conn, xact); xact->state = KS_XACT_STATE_ACTIVE; ks_conn_send_message(xact->conn, KS_CONN_MSG_REFRESH, 0, 0); return 0; } void ks_xact_wait(struct ks_xact *xact) { pthread_mutex_lock(&xact->state_lock); while(xact->state != KS_XACT_STATE_COMPLETED) { pthread_cond_wait(&xact->state_cond, &xact->state_lock); } pthread_mutex_unlock(&xact->state_lock); } void ks_xact_need_skb(struct ks_xact *xact) { if (!xact->out_skb) xact->out_skb = alloc_skb(4096, GFP_KERNEL); }
0
#include <pthread.h> static int hash(int key) { return key % MAGICNO; } void htable_init(struct hashtable **ht, void (*value_free)(void *value)) { *ht = malloc(sizeof(struct hashtable)); assert(*ht); (*ht)->htable = malloc(sizeof(struct hashnode *) * HTSIZE); assert((*ht)->htable); memset((*ht)->htable,0,(sizeof(struct hashnode *) * HTSIZE)); assert(pthread_mutex_init(&((*ht)->htable_lock),0) == 0); (*ht)->value_free = value_free; } struct hashnode *hashnode_new(int key, void *value) { struct hashnode *new = malloc(sizeof(struct hashnode)); assert(new); new->key = key; new->value = strdup(value); assert(new->value); assert(pthread_mutex_init(&new->ref_cnt_lock,0) == 0 ); new->ref_cnt = 1; new->next = 0; return new; } void hashnode_free(struct hashtable *ht, struct hashnode *entry) { assert(ht); assert(entry); if( ht->value_free != 0 ) { ht->value_free(entry->value); } assert(pthread_mutex_destroy(&entry->ref_cnt_lock) == 0); free(entry); } void hashlist_free(struct hashtable *ht, struct hashnode *list) { struct hashnode *cur = list, *cur_next; while( cur != 0 ) { cur_next = cur->next; hashnode_free(ht, cur); cur = cur_next; } } void htable_destroy(struct hashtable *ht) { assert(ht); int i; pthread_mutex_lock(&ht->htable_lock); for( i=0 ; i<HTSIZE ; i++ ) { if( ht->htable[i] != 0 ) { hashlist_free(ht, ht->htable[i]); } } pthread_mutex_unlock(&ht->htable_lock); assert(pthread_mutex_destroy(&ht->htable_lock) == 0); free(ht->htable); free(ht); } struct hashnode *htable_search(struct hashtable *ht, int key) { assert(ht); int hash_key = hash(key); pthread_mutex_lock(&ht->htable_lock); struct hashnode *p = ht->htable[hash_key]; while( p != 0 ) { if( p->key == key ) { pthread_mutex_unlock(&ht->htable_lock); return p; } p = p->next; } pthread_mutex_unlock(&ht->htable_lock); return 0; } void htable_add(struct hashtable *ht,int key, void *value) { assert(ht); struct hashnode *entry = htable_search(ht, key); if( entry == 0 ) { struct hashnode *new = hashnode_new(key, value); int hash_key = hash(new->key); pthread_mutex_lock(&ht->htable_lock); new->next = ht->htable[hash_key]; ht->htable[hash_key] = new; pthread_mutex_unlock(&ht->htable_lock); } else { pthread_mutex_lock(&entry->ref_cnt_lock); entry->ref_cnt++; pthread_mutex_unlock(&entry->ref_cnt_lock); } } int htable_del(struct hashtable *ht, int key, struct hashnode *valptr) { assert(ht); int hash_key = hash(key); pthread_mutex_lock(&ht->htable_lock); struct hashnode *del = ht->htable[hash_key]; if( del == 0 ) { valptr = 0; pthread_mutex_unlock(&ht->htable_lock); return 0; } if( del->key == key ) { if( valptr != 0 ) { memcpy(valptr,del,sizeof(struct hashnode)); valptr->value = strdup((char *)del->value); assert(valptr->value); } pthread_mutex_lock(&del->ref_cnt_lock); if( --del->ref_cnt == 0 ) { pthread_mutex_unlock(&del->ref_cnt_lock); ht->htable[hash_key] = del->next; hashnode_free(ht, del); } else { pthread_mutex_unlock(&del->ref_cnt_lock); } pthread_mutex_unlock(&ht->htable_lock); return 1; } struct hashnode *pre_del = del; del = pre_del->next; while( del != 0 ) { if( del->key == key ) { if( valptr != 0 ) { memcpy(valptr,del,sizeof(struct hashnode)); valptr->value = strdup((char *)del->value); assert(valptr->value); } pthread_mutex_lock(&del->ref_cnt_lock); if( --del->ref_cnt == 0 ) { pthread_mutex_unlock(&del->ref_cnt_lock); pre_del->next = del->next; hashnode_free(ht, del); } else { pthread_mutex_unlock(&del->ref_cnt_lock); } pthread_mutex_unlock(&ht->htable_lock); return 1; } pre_del = del; del = pre_del->next; } valptr = 0; pthread_mutex_unlock(&ht->htable_lock); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexa, mutexb; void *fun() { int i = 1000; while(i--) { pthread_mutex_lock(&mutexa); printf("-\\n"); pthread_mutex_unlock(&mutexb); } } int main(int argc, char* argv[]) { int i = 1000; pthread_t pthid; pthread_create(&pthid, 0, fun, 0); pthread_mutex_init(&mutexa, 0); pthread_mutex_init(&mutexb, 0); pthread_mutex_lock(&mutexa); while(i--) { pthread_mutex_lock(&mutexb); sleep(2); printf("+\\n"); pthread_mutex_unlock(&mutexa); } pthread_mutex_unlock(&mutexb); pthread_join(pthid, 0); pthread_mutex_destroy(&mutexa); pthread_mutex_destroy(&mutexb); return 0; }
0
#include <pthread.h> int test1; int test2; pthread_mutex_t lock; pthread_cond_t can_cond; pthread_cond_t I_cond; void *printHello(void *args){ pthread_mutex_lock(&lock); flockfile(stdout); fprintf(stdout, "Never going to give you up\\n"); funlockfile(stdout); pthread_cond_signal(&can_cond); test1 = 1; pthread_mutex_unlock(&lock); } void *printCanYouHearMe(void *args){ pthread_mutex_lock(&lock); while(test1 == 0){ pthread_cond_wait(&can_cond, &lock); } flockfile(stdout); fprintf(stdout, "Never going to let you down\\n"); funlockfile(stdout); pthread_cond_broadcast(&I_cond); test2 = 1; pthread_mutex_unlock(&lock); } void *printIWasWondering(void *args){ pthread_mutex_lock(&lock); while(test2 == 0){ pthread_cond_wait(&I_cond, &lock); } flockfile(stdout); fprintf(stdout, "Never going to run around"); funlockfile(stdout); pthread_mutex_unlock(&lock); } int main(int argc, char **argv){ pthread_t t[3]; int i; int err; test1 = 0; test2 = 0; err = pthread_mutex_init(&lock, 0); if(err){ errno = err; perror("mutex init"); return -1; } err = pthread_cond_init(&can_cond, 0); if(err){ errno = err; perror("cond init"); pthread_mutex_destroy(&lock); return -1; } err = pthread_cond_init(&I_cond, 0); if(err){ errno = err; perror("cond init"); pthread_mutex_destroy(&lock); pthread_cond_destroy(&can_cond); return -1; } for(i = 0; i < 3; i++){ if(i == 0){ err = pthread_create(&t[i], 0, printHello, 0); }else if(i == 1){ err = pthread_create(&t[i], 0, printCanYouHearMe, 0); }else{ err = pthread_create(&t[i], 0, printIWasWondering, 0); } if(err){ errno = err; perror("pthread create"); pthread_mutex_destroy(&lock); pthread_cond_destroy(&can_cond); pthread_cond_destroy(&I_cond); return -1; } } for(i = 0; i < 3; i++){ err = pthread_join(t[i], 0); if(err){ errno = err; perror("pthread join"); pthread_mutex_destroy(&lock); pthread_cond_destroy(&can_cond); pthread_cond_destroy(&I_cond); return -1; } } printf(" and desert you\\n"); pthread_mutex_destroy(&lock); pthread_cond_destroy(&can_cond); pthread_cond_destroy(&I_cond); return 0; }
1
#include <pthread.h> int thread_count; int flag = 0; long long n; double sum = 0; pthread_mutex_t mutex; void* Thread_sum(void* rank){ long my_rank = (long) rank; double factor, my_sum = 0.0; long long i; long long my_n = n/thread_count; long long my_first_i = my_n * my_rank; long long my_last_i = my_first_i + my_n; if(my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for(i = my_first_i; i < my_last_i; i++, factor = -factor){ my_sum += factor/(2*i+1); } pthread_mutex_lock(&mutex); sum += my_sum; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char* argv[]){ long thread; pthread_t* thread_handles; struct timespec begin,end; double elapsed; scanf("%lld", &n); thread_count = strtol(argv[1], 0, 10); thread_handles = malloc (thread_count* sizeof(pthread_t)); clock_gettime(CLOCK_MONOTONIC, &begin); for(thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*) thread); for(thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); clock_gettime(CLOCK_MONOTONIC, &end); elapsed = end.tv_sec - begin.tv_sec; elapsed += (end.tv_nsec - begin.tv_nsec) / 1000000000.0; printf("%f %f\\n", 4*sum, elapsed); free(thread_handles); return 0; }
0
#include <pthread.h> { int balance; pthread_mutex_t mutex; } Account; void deposit(Account* account, int amount) { pthread_mutex_lock(&(account->mutex)); account->balance += amount; pthread_mutex_unlock(&(account->mutex)); } Account account; void *thread_start() { int i; for ( i = 0 ; i < 1000000 ; i++) { deposit( &account, 1 ); } pthread_exit(0); } int main(int argc, char** argv) { account.balance = 0; pthread_mutex_init( &account.mutex, 0 ); pthread_t threads[8]; int i; for( i = 0 ; i < 8 ; i++ ) { int res = pthread_create( &threads[i], 0, thread_start, 0 ); if (res) { printf("Error: pthread_create() failed with error code %d\\n", res); exit(-1); } } for( i = 0 ; i < 8 ; i++ ) { int res = pthread_join(threads[i], 0); if (res) { printf("Error: pthread_join() failed with error code %d\\n", res); exit(-1); } } printf("Final balance is %d\\n", account.balance ); pthread_mutex_destroy(&account.mutex); pthread_exit(0); return 0; }
1
#include <pthread.h> int dlugosc(int x){ int l=0; while(x!=0){ x/=10; l++; } return l; } char* slowo; int ilosc_rekordow; int fd; pthread_t *tablica_watkow; int ilosc_watkow; sigset_t set; }parametry; pthread_mutex_t mutex; pthread_t main_thread_id; int licznik=1; void signal_handler (int signo) { if(signo == SIGFPE) { printf("sigfpe\\n"); } } void* wersja_2(void* parameters){ int check = 0; pthread_mutex_lock(&mutex); pthread_setcancelstate(PTHREAD_CANCEL_DEFERRED, 0); parametry* p = (parametry*) parameters; char wiersz[1024]; int czytaj_rekord; printf("Licznik = %d\\n",licznik ); if (licznik==4){ raise(SIGFPE); } printf("Licznik1 = %d\\n",licznik ); for (int i=1; i<=p->ilosc_rekordow; i++) { czytaj_rekord = (int)read(p->fd, wiersz, 1024); char* id = (char*)calloc(10,sizeof(char)); int j=0; int tmp = dlugosc(licznik); while (tmp>=1) { id[j]=wiersz[j]; j++; tmp--; } licznik++; char* bez_int = wiersz+dlugosc(licznik); char* wynik = strstr(bez_int, p->slowo); if (wynik!=0){ printf("id = %s, tid = %u\\n",id,(unsigned int)pthread_self()); check++; } free(id); } if (check>0) { for (int i=0; i<p->ilosc_watkow; i++) { if (pthread_equal(pthread_self(), p->tablica_watkow[i])==0) { pthread_cancel(p->tablica_watkow[i]); } } exit(0); } pthread_mutex_unlock(&mutex); return 0; } int main(int argc, const char * argv[]) { if (argc!=5) { perror("Zła liczba argumentów\\n"); exit(1); } int ilosc_watkow = atoi(argv[1]); char* nazwa_pliku = (char*)argv[2]; int ilosc_rekordow = atoi(argv[3]); char* slowo = (char*)argv[4]; printf("%d %s %d %s\\n",ilosc_watkow,nazwa_pliku,ilosc_rekordow,slowo); int fd = open(nazwa_pliku, O_RDONLY); if (fd == 0) { perror("Nie udalo sie otworzyc pliku"); exit(1); } pthread_t *tablica_watkow = (pthread_t*)calloc(ilosc_watkow,sizeof(pthread_t)); main_thread_id = pthread_self(); pthread_mutex_init (&mutex, 0); for (int i=0; i<ilosc_watkow; i++) { parametry arg; arg.fd = fd; arg.ilosc_rekordow=ilosc_rekordow; arg.slowo=slowo; arg.tablica_watkow=tablica_watkow; arg.ilosc_watkow=ilosc_watkow; pthread_create(&tablica_watkow[i], 0, &wersja_2, &arg); } for (int i=0; i<ilosc_watkow; i++) { pthread_join(tablica_watkow[i], 0); } close(fd); free(tablica_watkow); return 0; }
0
#include <pthread.h> void fun(void); pthread_mutex_t mut= PTHREAD_MUTEX_INITIALIZER; void *thread_func(void *args) { if(pthread_mutex_trylock(&mut) == EBUSY) { printf("%lu: Mutex already Locked\\n",pthread_self()); } else { printf("Mutex was free.. So I (%lu) Taken \\n",pthread_self()); sleep(5); pthread_mutex_unlock(&mut); } } int main() { pthread_t tid1,tid2,tid3; pthread_create(&tid1, 0, thread_func, 0); pthread_create(&tid2, 0, thread_func, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); return 0; }
1
#include <pthread.h> struct Node{ int value; struct Node *next; }*head; pthread_mutex_t inserter_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t deleter_lock = PTHREAD_MUTEX_INITIALIZER; sem_t deleter_lock_searcher; sem_t deleter_lock_inserter; void searcher(); void inserter(); void deleter(); void searcher(){ struct Node *cursor; while(1){ sem_wait(&deleter_lock_searcher); cursor = head; if(cursor != 0){ printf("Searching Linked List:\\n"); while(cursor != 0){ printf("%d ", cursor->value); cursor = cursor->next; } printf("\\n"); }else{ printf("The list is empty.\\n"); } sem_post(&deleter_lock_searcher); sleep(2); } } void inserter(){ struct Node *cursor, **tail, *temp; int insert_num; while(1){ sem_wait(&deleter_lock_inserter); pthread_mutex_lock(&inserter_lock); insert_num = rand()%20; cursor = head; if(cursor == 0){ cursor = (struct Node *)malloc(sizeof(struct Node)); cursor->value = insert_num; cursor->next = 0; head = cursor; }else{ printf("Inserting %d to linked list.\\n", insert_num); tail = &head; temp = (struct Node *)malloc(sizeof(struct Node)); temp->value = insert_num; temp->next = 0; while(*tail != 0){ tail = &((*tail)->next); } *tail = temp; } sem_post(&deleter_lock_inserter); pthread_mutex_unlock(&inserter_lock); sleep(5); } } void deleter(){ int delete_num; struct Node *cursor, *prev; while(1){ sem_wait(&deleter_lock_inserter); sem_wait(&deleter_lock_searcher); pthread_mutex_lock(&deleter_lock); cursor = head; while(cursor != 0){ delete_num = rand()%20; if(cursor->value == delete_num){ printf("Deleting %d from linked list\\n", delete_num); if(cursor == head){ head = cursor->next; free(cursor); break; }else{ prev->next = cursor->next; free(cursor); break; } }else{ prev = cursor; cursor = cursor->next; } } pthread_mutex_unlock(&deleter_lock); sem_post(&deleter_lock_inserter); sem_post(&deleter_lock_searcher); sleep(5); } } int main(){ pthread_t searcher_thread[3]; pthread_t inserter_thread[3]; pthread_t deleter_thread[3]; int i; sem_init(&deleter_lock_searcher, 0 ,1); sem_init(&deleter_lock_inserter, 0, 1); struct Node *root; root = (struct Node *)malloc(sizeof(struct Node)); root->value = rand()%10; head = root; head->next = 0; for(i=0; i<3; i++){ pthread_create(&searcher_thread[i], 0, (void *)searcher,(void *)0); pthread_create(&inserter_thread[i], 0, (void *)inserter, (void *)0); pthread_create(&deleter_thread[i], 0, (void *)deleter, (void *)0); } for(i=0; i<3; i++){ pthread_join(searcher_thread[i], 0); pthread_join(inserter_thread[i], 0); pthread_join(deleter_thread[i], 0); } return 0; }
0
#include <pthread.h> int g1, g2, g3, g4; int found = 1; float goertzel(int N,int Ft, float* input) { int k, i; float floatN; float omega, sine, cosine, q0, q1, q2, power; float scalingFactor = N / 2.0; floatN = (float) N; k = (int) (0.5 + ((floatN * Ft) / Fs)); omega = (2.0 * M_PI * k) / floatN; sine = sin(omega); cosine = 2.0 *cos(omega); q0=0; q1=0; q2=0; for(i=0; i<N; i++) { q0 = cosine * q1 - q2 + input[i]; q2 = q1; q1 = q0; } power = (q2 *q2 + q1 * q1 - cosine * q1 * q2) / scalingFactor; return power; } void *finding_freq() { double elapsed; int err; usleep(100000); start = clock(); while(1) { pthread_mutex_lock(&mutex_f); { g1 = goertzel(2048, freq_up, buffer_f); g2 = goertzel(2048, freq_down, buffer_f); } if ((g1>TH) & (g2>TH)){ if(found) { found = 0; dial_num[num_det] = num_jef[num_det]; num_det++; digit = num_jef[num_det]; set_station(); start = clock(); } } else { found = 1; } pthread_mutex_unlock(&mutex_f); pthread_mutex_lock(&mutex_s); { g3 = goertzel(2048, freq_up, buffer_s); g4 = goertzel(2048, freq_down, buffer_s); } if ((g3>TH) & (g4>TH)){ if(found) { found = 0; dial_num[num_det] = num_jef[num_det]; num_det++; digit = num_jef[num_det]; set_station(); start = clock(); } } else { found = 1; } pthread_mutex_unlock(&mutex_s); end = clock(); elapsed = ((double) (end - start)) / CLOCKS_PER_SEC; if(abs(elapsed) > 3) { digit = num_jef[0]; num_det = 0; set_station(); } if(num_det == 8) { if ((err = snd_pcm_open(&handle_w, "default", SND_PCM_STREAM_PLAYBACK, 0)) < 0) { printf("Playback open error: %s\\n", snd_strerror(err)); exit(1); } if ((err = snd_pcm_set_params(handle_w, SND_PCM_FORMAT_FLOAT, SND_PCM_ACCESS_RW_INTERLEAVED, 1, Fs, 1, 100000)) < 0) { printf("Playback open error: %s\\n", snd_strerror(err)); exit(1); } pthread_create( &thread2, 0, write_, 0); num_det = 0; } } } void *write_() { usleep(100000); while((mode==0) & (ch1 != 'q')) { pthread_mutex_lock(&mutex_w1); (void) snd_pcm_writei(handle_w, buffer_f, 2048); pthread_mutex_unlock(&mutex_w1); (void) snd_pcm_writei(handle_w, buffer_s, 2048); } snd_pcm_close(handle_w); usleep(100000); } void set_station() { switch ( digit ) { case 0: freq_up = 1336; freq_down = 941; break; case 1: freq_up = 1209; freq_down = 697; break; case 2: freq_up = 1336; freq_down = 697; break; case 3: freq_up = 1477; freq_down = 697; break; case 4: freq_up = 1209; freq_down = 770; break; case 5: freq_up = 1336; freq_down = 770; break; case 6: freq_up = 1477; freq_down = 770; break; case 7: freq_up = 1209; freq_down = 852; break; case 8: freq_up = 1336; freq_down = 852; break; case 9: freq_up = 1477; freq_down = 852; break; case 10: freq_up = 1633; freq_down = 697; break; case 11: freq_up = 1633; freq_down = 770; break; case 12: freq_up = 1633; freq_down = 852; break; case 13: freq_up = 1333; freq_down = 941; break; case 14: freq_up = 1209; freq_down = 941; break; case 15: freq_up = 1477; freq_down = 941; break; default: freq_up = 10000; freq_down = 10000; break; } } unsigned long get_time_usec() { struct timeval tv; gettimeofday(&tv,0); unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec; return time_in_micros; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *watch_count(void *t); void *inc_count(void *t) ; 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, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); } 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) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } 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) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); }
0
#include <pthread.h> static const size_t NUM_ITERATIONS = 100; static const size_t NUM_THREADS = 4; { pthread_mutex_t lock; size_t value; } counter_t; counter_t* counter_init(size_t initial_value) { counter_t* counter = (counter_t*)malloc(sizeof(counter_t)); counter->value = initial_value; pthread_mutex_init(&counter->lock, 0); return counter; } void counter_free(counter_t* counter) { pthread_mutex_destroy(&counter->lock); free(counter); } void counter_increment(counter_t* counter) { pthread_mutex_lock(&counter->lock); ++counter->value; pthread_mutex_unlock(&counter->lock); } void counter_decrement(counter_t* counter) { pthread_mutex_lock(&counter->lock); --counter->value; pthread_mutex_unlock(&counter->lock); } void* test_counter(void* param) { counter_t* counter = (counter_t*)param; for (size_t i = 0; i < NUM_ITERATIONS; ++i) { counter_increment(counter); } return 0; } int main(int argc, char const* argv[]) { counter_t* counter = counter_init(0); pthread_t threads[NUM_THREADS]; for (size_t i = 0; i < NUM_THREADS; ++i) { pthread_create(&threads[i], 0, &test_counter, counter); } for (size_t i = 0; i < NUM_THREADS; ++i) { pthread_join(threads[i], 0); } printf("counter: %ld\\n", counter->value); counter_free(counter); return 0; }
1
#include <pthread.h> static volatile int keepRunning = 1; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_barrier_t mybarrier; static unsigned int maxIteration = 0; void intHandler(int _) { keepRunning = 0; } struct job { unsigned int threadNumber; unsigned int threadsCount; }; void * routine(struct job * job) { double result = 0; unsigned int number = job->threadNumber; unsigned int count = job->threadsCount; free(job); unsigned int i; for (i = number; keepRunning; i += count) { result += 1.0 / (i * 4.0 + 1.0); result -= 1.0 / (i * 4.0 + 3.0); } pthread_mutex_lock(&mutex); if (i > maxIteration) { maxIteration = i; } pthread_mutex_unlock(&mutex); pthread_barrier_wait(&mybarrier); int ourMaxIteration = (maxIteration / 4) * 4 + number; for (; i <= ourMaxIteration; i += count) { result += 1.0 / (i * 4.0 + 1.0); result -= 1.0 / (i * 4.0 + 3.0); } double * resultPtr = malloc(sizeof(double)); *resultPtr = result; pthread_exit(resultPtr); } double getPi(unsigned int threadsCount) { pthread_t * threads = malloc(sizeof(pthread_t) * threadsCount); for (unsigned int i = 0; i < threadsCount; ++i) { struct job * job = malloc(sizeof(struct job)); job->threadNumber = i; job->threadsCount = threadsCount; pthread_create(threads + i, 0, routine, job); } double pi = 0; for (int i = 0; i < threadsCount; ++i) { double * threadResult; pthread_join(threads[i], &threadResult); pi += *threadResult; free(threadResult); } free(threads); pi *= 4; return pi; } int main(int argc, char ** argv) { unsigned int threadsCount = 4; if (argc >= 2) { char * end; threadsCount = (unsigned int) strtol(argv[1], &end, 10); if (end == argv[1]) { printf("Incorrect thread count format\\n"); return 1; } } signal(SIGINT, intHandler); printf("Press Ctrl+C to stop counting and print result\\n"); pthread_barrier_init(&mybarrier, 0, threadsCount); double pi = getPi(threadsCount); pthread_barrier_destroy(&mybarrier); printf("Pi ~ %.15g\\n", pi); return 0; }
0
#include <pthread.h> pthread_cond_t var_cond ; pthread_mutex_t mutex_cond; pthread_mutex_t sem; int worms = 7; int scream = 0 ; struct DATA { int num ; char name[10]; } ; void *parent(void *dad){ struct DATA *aa = (struct DATA *)dad ; while(1){ pthread_mutex_lock(&mutex_cond); if(pthread_cond_wait(&var_cond, &mutex_cond) == 0){ worms = (rand()%7)+1; printf("\\nParent %s put %d worms on plate.\\n", aa->name, worms); } pthread_mutex_unlock(&mutex_cond); } } void *child_handler(void *data){ struct DATA *aa = (struct DATA *)data ; while(1){ sleep(rand()%4); if(worms > 0){ pthread_mutex_lock(&mutex_cond); worms-- ; if(worms == 0){ pthread_cond_signal(&var_cond); } printf("Bird N:%d take a worm. Remain %d worms\\n",aa->num, worms); pthread_mutex_unlock(&mutex_cond); } } } int main (int argc, char* argv[]){ int i = 0; pthread_mutex_init (&sem, 0); pthread_mutex_init (&mutex_cond, 0); pthread_t thread_parent; pthread_t thread_bird[10]; struct DATA data[10]; if(scream == 0 && worms == 0){ scream = 1 ; } if (pthread_cond_init(&var_cond, 0) < 0) { fprintf (stderr, "variabile condition error.\\n"); exit (1); } struct DATA dad = {0, "BaBBo"} ; if (pthread_create(&thread_parent, 0, parent, (void *)&dad ) < 0) { fprintf (stderr, "create error for PARENT.\\n"); exit (1); } for ( i = 0 ; i < 10 ; i++){ data[i].num = i ; if (pthread_create(&thread_bird[i], 0, child_handler, (void *)&data[i] ) < 0) { fprintf (stderr, "create error for BIRD N%d.\\n", data[i].num); exit (1); } } pthread_join (thread_parent, 0); for ( i = 0 ; i < 10 ; i++) { pthread_join (thread_bird[i], 0); } return 0 ; }
1
#include <pthread.h> void* producer(void*); void* consumer(void*); sem_t full_sem, empty_sem; pthread_mutex_t buffer_mutex; int buffer[10], buffer_index=0; main(){ pthread_t tid[10]; int thread[10]; sem_init(&full_sem, 0, 5); sem_init(&empty_sem, 0, 0); pthread_mutex_init(&buffer_mutex, 0); int i; for(i=0; i<10; i++){ thread[i] = i; pthread_create(&tid[i], 0, producer, &thread[i]); i++; thread[i] = i; pthread_create(&tid[i], 0, consumer, &thread[i]); } for(i=0; i<10; i++) pthread_join(tid[i], 0); sem_destroy(&full_sem); sem_destroy(&empty_sem); pthread_mutex_destroy(&buffer_mutex); } void* producer(void* n){ int thread_no = *(int*)n; int value = rand()%100; sem_wait(&full_sem); pthread_mutex_lock(&buffer_mutex); buffer[buffer_index++] = value; pthread_mutex_unlock(&buffer_mutex); sem_post(&empty_sem); printf("thread no. %d produced %d\\n", thread_no, value); pthread_exit(0); } void* consumer(void* n){ int thread_no = *(int*)n; int value; sem_wait(&empty_sem); pthread_mutex_lock(&buffer_mutex); value = buffer[--buffer_index]; pthread_mutex_unlock(&buffer_mutex); sem_post(&full_sem); printf("thread no. %d consumed %d\\n", thread_no, value); pthread_exit(0); }
0
#include <pthread.h> sem_t barber,customer; pthread_mutex_t mutex; int waiting=0; int count=0; void* barber1(void* param){ while(1){ sem_wait(&customer); pthread_mutex_lock(&mutex); waiting=waiting-1; printf("Cut Hair \\n"); sem_post(&barber); pthread_mutex_unlock(&mutex); count++; if(count==5)break; } } void* customer1(void* param){ pthread_mutex_lock(&mutex); if(waiting<5){ waiting=waiting+1; sem_post(&customer); pthread_mutex_unlock(&mutex); printf("waiting "); sem_wait(&barber); }else{ pthread_mutex_unlock(&mutex); } } int main(){ sem_init(&barber,0,0); sem_init(&customer,0,0); pthread_mutex_init(&mutex,0); pthread_t barb,customers[5]; pthread_create(&barb,0,barber1,0); int i; for(i=0;i<5;i++){ pthread_create(&customers[i],0,customer1,0); } pthread_join(barb,0); for(i=0;i<5;i++){ pthread_join(customers[i],0); } }
1
#include <pthread.h> void* LockCreate() { pthread_mutexattr_t attr; pthread_mutex_t *p_mutex = malloc(sizeof(pthread_mutex_t)); int i_result; pthread_mutexattr_init( &attr ); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); i_result = pthread_mutex_init( p_mutex, &attr ); pthread_mutexattr_destroy( &attr ); if(i_result) { free(p_mutex); return 0; } return p_mutex; } void LockDelete(void* p) { if (p) { pthread_mutex_destroy(p); free(p); } } void LockEnter(void* p) { if (p) { pthread_mutex_lock(p); } } void LockLeave(void* p) { if (p) { pthread_mutex_unlock(p); } } int ThreadPriority(void* Thread,int Priority) { return 0; } int EventWait(void* Handle,int Time,void* mutex) { if(Time>0) { struct timespec time; struct timeval date; int64_t datams; bzero(&time, sizeof(struct timespec)); bzero(&date, sizeof(struct timeval)); gettimeofday( &date, 0 ); datams = (((int64_t)date.tv_sec)*1000000 + date.tv_usec)/1000+Time; time.tv_sec = datams/1000; time.tv_nsec = datams%1000 * 1000000; pthread_cond_timedwait((pthread_cond_t*)Handle, (pthread_mutex_t*)mutex,&time); } else { pthread_cond_wait((pthread_cond_t*)Handle, (pthread_mutex_t*)mutex ); } return 1; } void* EventCreate(int ManualReset,int InitState) { pthread_condattr_t attr; pthread_cond_t *cond = malloc(sizeof(pthread_cond_t)); pthread_cond_init (cond, &attr); return cond; } void EventSet(void* Handle) { if(Handle) { pthread_cond_signal((pthread_cond_t*)Handle); } } void EventReset(void* Handle) { } void EventClose(void* Handle) { if(Handle) { pthread_cond_destroy((pthread_cond_t*)Handle); free((pthread_cond_t*)Handle); } } int ThreadId() { return pthread_self(); } void ThreadSleep(int Time) { usleep(Time*1000); } void ThreadTerminate(void* Handle) { if(Handle) { pthread_join(*(pthread_t*)Handle,0); free((pthread_t*)Handle); } } void* ThreadCreate(void* (*Start)(void*),void* Parameter,int Quantum) { pthread_attr_t attr; struct sched_param param; int ret = 0; pthread_t* thread_id = (pthread_t*)malloc(sizeof(pthread_t)); int policy = 0; int primax = 0; pthread_attr_init (&attr); ret = pthread_attr_setschedpolicy(&attr,SCHED_RR); ret = pthread_attr_getschedpolicy(&attr,&policy); primax = sched_get_priority_max(policy); param.sched_priority = primax; ret = pthread_attr_setschedparam(&attr,&param); ret = pthread_create(thread_id, &attr, Start, Parameter ); return thread_id; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static void *threads(void* arg) { (void)arg; printf("\\t->Thread %ld wartet auf Bedingung\\n", (long)pthread_self()); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("->Thread %ld hat Bedingung erhalten\\n", (long)pthread_self()); printf("->Thread %ld Sende Bedingugsvariable\\n", (long)pthread_self()); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); return 0; } int main(void) { int i; static pthread_t th[3]; printf("\\n-> Main-Thread gestartet (ID:%ld)\\n", (long)pthread_self()); for (i=0; i<3; ++i) { if (pthread_create(&th[i], 0, (void*)&threads, 0) != 0) { fprintf(stderr, "Konnte Thread nicht erzeugen ...!\\n"); exit(1); } } printf("\\n-> Main-Thread hat %d Threads erzeugt\\n", 3); sleep(1); printf("->Main-Thread: Sende Bedingugsvariable\\n"); pthread_cond_signal(&cond); for (i=0; i<3; ++i) { pthread_join(th[i], 0); } printf("<- Main-Thread beendet (ID:%ld)\\n", (long)pthread_self()); return 0; }
1
#include <pthread.h> pthread_mutex_t mut[5]; int workreq[5]; int workdone[5]; pthread_mutex_t prodmut; unsigned prodbuff; void *worker (void *arg) { unsigned id = (unsigned long) arg; int i, havework; havework = 0; for (i = 0; i < 2; i++) { pthread_mutex_lock (mut + id); if (workreq[id]) { workreq[id]--; havework = 1; } pthread_mutex_unlock (mut + id); if (havework) { workdone[id]++; havework = 0; } } return 0; } void *producer (void *arg) { unsigned dst, i, tmp; unsigned id = (unsigned long) arg; assert (id < 3); for (i = 0; i < 2; i ++) { pthread_mutex_lock (&prodmut); prodbuff = prodbuff * 3 + id; tmp = prodbuff; pthread_mutex_unlock (&prodmut); } assert (tmp <= pow (3, 2*3)); dst = tmp % 5; pthread_mutex_lock (mut + dst); workreq[dst]++; pthread_mutex_unlock (mut + dst); return 0; } int main () { pthread_t t; int i; assert (5 >= 2); for (i = 0; i < 5; i++) { pthread_mutex_init (mut + i, 0); workreq[i] = 0; workdone[i] = 0; pthread_create (&t, 0, worker, (void*) (long) i); } pthread_mutex_init (&prodmut, 0); prodbuff = 0; for (i = 0; i < 3; i++) { pthread_create (&t, 0, producer, (void*) (long) i); } pthread_exit (0); }
0
#include <pthread.h> struct validlink { char src[40]; char dst[40]; char filename[20]; int startposition; int endposition; }; int alllink=0; struct validlink link[100]; pthread_mutex_t mut; void exchange(int arg1) { int arg = arg1; FILE* fp1; FILE* fp2; fp1 = fopen("remoteinformation", "w"); fp2 = fopen("localInfor.data", "r"); char data[100]; printf("Start receiving remote information:\\n"); while (1) { memset(data,0,100); int numbytes= recv ( arg, data, 100, 0); data[numbytes] = '\\0' ; fprintf(fp1, "%s",data); printf("Received %d bytes \\n",numbytes); printf("%s",data) ; fflush(stdout); if((strncmp(&data[numbytes-3],"END",3))==0) break; } fclose(fp1); printf ( "\\nFinished receiving remote information\\n\\n\\n\\n" ) ; send(arg,"END1",4, 0) ; printf ( "Start sending Local information:\\n\\n" ) ; fflush(stdout); while(fgets(data,100,fp2)!=0) { int i=send(arg,data,100, 0) ; printf("Send %d bytes: %s \\n",i,data); fflush(stdout); memset(data,0,strlen(data)); } send( arg, "END2", 4, 0); fclose(fp2); printf ( "Finished sending local information\\n" ); printf ( "Information exchange stage is over\\n" ); close (arg) ; } void testlink(int arg1) { int arg = arg1; struct timeval tv1; struct timeval tv2; char protocol[5]; char local[30]; char data[65535]; int eachrecvbytes=0; int allrecvbytes=0; int interval=0; int speed=0; struct sockaddr_in name; int addrlen=sizeof(struct sockaddr_in); recv( arg, protocol, 5,0); recv( arg, local, 30,0); if(strncmp(protocol,"START",5)==0) { gettimeofday(&tv1,0); } while (1) { memset(data,0,65535); eachrecvbytes=recv(arg,data,65535,0); allrecvbytes=allrecvbytes+eachrecvbytes; if (strncmp(&data[eachrecvbytes-4],"TEND",4)==0) break; } gettimeofday(&tv2,0); send(arg,"TEND",4, 0) ; interval=((long long)tv2.tv_sec-(long long)tv1.tv_sec)*1000+((long long)tv2.tv_usec-(long long)tv1.tv_usec)/1000; speed=(allrecvbytes-4)/interval; printf ( "receive %dbytes time %dms speed %dKbps \\n" , allrecvbytes-4,interval,speed); close(arg); } void multireceive( int new_fd) { int temp; int thislink; char buffer[100]; int fp; int eachwritebytes=0; int allwritebytes=0; int eachrecvbytes=0; char data[655350]; bzero(buffer,100); pthread_mutex_lock(&mut); thislink=alllink; alllink++; pthread_mutex_unlock(&mut); char filename[20]; memset (filename,'\\0',20); send(new_fd,"REQUEST",7,0); recv(new_fd,filename,20,0); send(new_fd,"START1",6,0); temp=recv(new_fd,buffer,100,0); buffer[temp]='\\0'; sscanf(buffer,"%s %s %s %d %d",link[thislink].src,link[thislink].dst,link[thislink].filename,&link[thislink].startposition,&link[thislink].endposition); printf("%s %s %s %d %d \\n",link[thislink].src,link[thislink].dst,link[thislink].filename,link[thislink].startposition,link[thislink].endposition); fp=open(link[thislink].filename,O_WRONLY|O_CREAT); lseek(fp,link[thislink].startposition,0); send(new_fd,"START2",6,0); while(allwritebytes<(link[thislink].endposition-link[thislink].startposition)) { bzero(data,655350); eachrecvbytes= recv(new_fd,data,655350,0) ; eachwritebytes= write(fp,data,eachrecvbytes) ; allwritebytes=allwritebytes+eachwritebytes; } printf(" Write %d should wirte %d \\n",allwritebytes,link[thislink].endposition-link[thislink].startposition); send(new_fd,"END",3,0); close(new_fd); } void * operation( void * arg) { int new_fd = (int )arg; char protocol[5]; memset(protocol,'\\0',5); read( new_fd, protocol, 4); printf("protocol is %s\\n",protocol); switch(protocol[0]) { case 'E' : exchange(new_fd); break; case 'T' : testlink(new_fd); break; case 'M' : multireceive( new_fd); break; } } int main() { int sockfd, new_fd, allbytes,numbytes; struct sockaddr_in server_addr; struct sockaddr_in client_addr; int sin_size; pthread_t th; pthread_mutex_init(&mut,0); if ((sockfd = socket (AF_INET,SOCK_STREAM ,0) ) == - 1) { perror ("socket error") ; return 1; } memset(&client_addr,0,sizeof(struct sockaddr)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons (2012); server_addr.sin_addr.s_addr=INADDR_ANY; if (bind(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr)) == - 1) { perror ( "bind error" ) ; return 1; } int sock_buf_size=655350; setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, (char *)&sock_buf_size, sizeof(sock_buf_size) ); while(1){ if (listen(sockfd,5) == - 1){ perror ("listen error") ; return 1; } sin_size = sizeof ( struct sockaddr_in ) ; if ( ( new_fd = accept ( sockfd, ( struct sockaddr * ) & client_addr, & sin_size) )== - 1) { perror ( "accept error" ) ; } printf ( "server: got connection from %s\\n" , (char *)inet_ntoa(client_addr. sin_addr)); pthread_create(&th,0,operation, (void *) new_fd); pthread_detach(th); } return 0; }
1
#include <pthread.h> struct reg { int *inicio; int *fim; int *vet; int n; }; int somatorio; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * function (void *arg) { struct reg *valor; valor = (struct reg*) arg; printf("inicio %d\\n",valor->inicio[valor->n]); printf("fim %d\\n",valor->fim[valor->n]); int i; for (i = valor->inicio[valor->n]; i < valor->fim[valor->n]; i++) { pthread_mutex_lock(&mutex); somatorio += valor->vet[i]; pthread_mutex_unlock(&mutex); } } int* geradorDeNumeros(int M, int K){ unsigned short seed[]={12,1,2}; int i; int *vetor = malloc(sizeof(int)*M); for(i=0; i<M; i++) vetor[i] = 1 + K * erand48(seed); return vetor; } int main () { clock_t time1, time2, time_diff; int qtdnum, intervalo, *vet; struct timeval antes, depois; float delta, delta2; int K = (2048*1024); qtdnum = K; intervalo = 10000; vet = geradorDeNumeros(qtdnum, intervalo); int N = 4; pthread_t threads[N]; int vetFim[N]; int vetIni[N]; int result = K / N; vetFim[0] = result; vetIni[0] = 0; int l = 1; while(l < N) { vetIni[l] = vetFim[l-1]; vetFim[l] = vetFim[l-1] + result; l++; } struct reg x; x.inicio = vetIni; x.fim = vetFim; x.vet = vet; struct reg aux[N]; for(int i = 0; i < N; i++) { aux[i] = x; aux[i].n = i; } int i = 0; gettimeofday (&antes, 0); for(i = 0; i < N; i++) { pthread_create(&threads[i], 0, function, (void *)(&aux[i])); } for(i = 0; i < N; i++) { pthread_join(threads[i], 0); } gettimeofday (&depois, 0); printf("Somatorio %d\\n",somatorio); delta = (depois.tv_sec + depois.tv_usec/1000000.0) - (antes.tv_sec + antes.tv_usec /1000000.0); delta2 = ((depois.tv_sec * 1000000 + depois.tv_usec) - (antes.tv_sec * 1000000 + antes.tv_usec)); printf("Tempo de execução em segundos %f segundos & Diferenca de %f microsegundos\\n\\n", delta, delta2); exit(0); }
0
#include <pthread.h> int **weights; char *string1,*string2; int N, M; pthread_mutex_t **locks; struct thread_params{ int id; int s_index; int l_index; int col_height; }; int max_threads; struct thread_params *thread_info; void *initialize_locks(void *thread_info); void *compute_weights(void *thread_info); int get_value(int id,int col,int row); void set_value(int id,int col,int row,int value); int main(int argc,char **argv){ if(argc < 4) { printf("Usage : progname file1 file2 num_threads"); exit(1); } max_threads = atoi(argv[3]); if(max_threads == 0){ printf(" 0 threads are not allowed. Must be some positive number of threads \\n"); exit(1); } string1 = read_data(argv[1]); string2 = read_data(argv[2]); N = strlen(string1)+1; M = strlen(string2)+1; int i,j; locks = (pthread_mutex_t **)malloc((max_threads-1)*sizeof(pthread_mutex_t *)); for(i=0;i<max_threads-1;i++){ locks[i] = (pthread_mutex_t *)malloc(M*sizeof(pthread_mutex_t)); for(j=0;j<M;j++){ pthread_mutex_init(&locks[i][j],0); } } thread_info = (struct thread_params *)malloc(max_threads*(sizeof(struct thread_params))); int chunk = (N-1)/max_threads; for(i=0;i<max_threads;i++){ thread_info[i].id = i; thread_info[i].s_index=(i)*chunk+1; thread_info[i].col_height=M; if(i==max_threads-1){ thread_info[i].l_index= N; }else{ thread_info[i].l_index=(i+1)*chunk; } } weights = (int **) malloc((M)*sizeof(int *)); for(i=0;i<M;i++){ weights[i] = (int *) malloc((N)*sizeof(int)); for(j=0;j<N;j++){ weights[i][j] = 0; } } pthread_t *tids = (pthread_t *)malloc(max_threads*sizeof(pthread_t)); void *tret; for(i=0;i<max_threads-1;i++){ pthread_create(&tids[i],0,initialize_locks,&thread_info[i]); } for(i=0;i<max_threads-1;i++){ pthread_join(tids[i],&tret); } struct timeval t1,t2; gettimeofday(&t1,0); for(i=0;i<max_threads;i++){ pthread_create(&tids[i],0,compute_weights,&thread_info[i]); } for(i=0;i<max_threads;i++){ pthread_join(tids[i],&tret); } printf("No of matching chars = %d \\n",weights[M-1][N-1]); gettimeofday(&t2,0); int total_seconds = (t2.tv_sec - t1.tv_sec)*1000000 + (t2.tv_usec - t1.tv_usec); printf("total time taken to calculate matrix = %f\\n",total_seconds/1000000.0); output_lcs(weights,string1,string2); free(tids); free(thread_info); free(locks); free(string1); free(string2); free(weights); } int get_value(int id,int row,int col){ int value = -1; if((id !=0) && (row > 0) &&(thread_info[id-1].l_index == col)){ pthread_mutex_lock(&locks[id-1][row]); value = weights[row][col]; pthread_mutex_unlock(&locks[id-1][row]); }else{ value = weights[row][col]; } return value; } void set_value(int id,int row,int col,int value){ weights[row][col] = value; if((id!=max_threads-1) && (thread_info[id].l_index == col) && (row>0)){ pthread_mutex_unlock(&locks[id][row]); } } void *initialize_locks(void *thread_info){ struct thread_params *t_info = (struct thread_params *)thread_info; int i =0; for(i=1;i<t_info->col_height;i++){ pthread_mutex_lock(&locks[t_info->id][i]); } } void *compute_weights(void *thread_info){ struct thread_params *t_info = (struct thread_params *)thread_info; int i =0,j=0; for(i=1;i<t_info->col_height;i++){ for(j=t_info->s_index;j<=t_info->l_index;j++){ if(string2[i-1]==string1[j-1]){ set_value(t_info->id,i,j,get_value(t_info->id,i-1,j-1)+1); }else{ set_value(t_info->id,i,j, max(get_value(t_info->id,i,j-1),get_value(t_info->id,i-1,j))); } } } }
1
#include <pthread.h> double gettime(void) { struct timeval tv; gettimeofday(&tv, 0); return tv.tv_sec + tv.tv_usec * 1e-6; } int val; struct _tnode *l; struct _tnode *r; } tnode; tnode *btree_create() { return 0; } tnode *btree_insert(int v, tnode *t) { if (t == 0) { t = (tnode *)malloc(sizeof(tnode)); t->val = v; t->l = 0; t->r = 0; } else { if (v < t->val) t->l = btree_insert(v, t->l); else if (v > t->val) t->r = btree_insert(v, t->r); } return t; } void btree_destroy(tnode *t) { if (t == 0) return; btree_destroy(t->l); btree_destroy(t->r); free(t); } void btree_dump(tnode *t) { if (t == 0) return; btree_dump(t->l); printf("%d\\n", t->val); btree_dump(t->r); } tnode *tree; int next; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *func(void *arg) { int i; for (i = 0; i < 100; i++) { pthread_mutex_lock(&mutex); tree = btree_insert(next, tree); next++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(void) { pthread_t thread[100]; tree = btree_create(); next = 0; int i; double tstart = gettime(); for (i = 0; i < 100; i++) { if (pthread_create(&thread[i], 0, func, &i) != 0) { printf("ERROR : pthread_create\\n"); return - 1; } } for (i = 0; i < 100; i++) { if (pthread_join(thread[i], 0) != 0) { printf("ERROR : pthread_join\\n"); return - 1; } } double tend = gettime(); btree_dump(tree); btree_destroy(tree); pthread_mutex_destroy(&mutex); printf("%f\\n", tend - tstart); return 0; }
0
#include <pthread.h> char task[] = "abcdefg"; char buffer1[4]; char buffer2[4]; int in; int out; int buffer_is_empty(){ return in == out; } int buffer_is_full(){ return (in + 1)%4 == out; } char get_item(){ int item; item = buffer1[out]; out = (out + 1)%4; return item; } void change_item(){ buffer1[out] = buffer1[out] + 32; } void put_item(char item){ buffer1[in] = item; in = (in + 1)%4; } pthread_mutex_t mutex; pthread_cond_t wait_empty_buffer; pthread_cond_t wait_full_buffer; pthread_cond_t wait_for_calc; void* producer(void* arg){ int i; char item; for(i = 0;i < 8;i++){ pthread_mutex_lock(&mutex); while(buffer_is_full()) pthread_cond_wait(&wait_full_buffer, &mutex); item = 'a' + i; printf("produce item %c\\n", item); put_item(item); pthread_cond_signal(&wait_empty_buffer); pthread_mutex_unlock(&mutex); } return 0; } void calculator(){ } void *consumer(void* arg){ int i; char item; for(i = 0;i < 8; i++){ pthread_mutex_lock(&mutex); while(buffer_is_empty()) pthread_cond_wait(&wait_empty_buffer, &mutex); item = get_item(); printf("(consumer)consumer item is %c\\n",item); pthread_cond_signal(&wait_full_buffer); pthread_mutex_unlock(&mutex); } return 0; } int main(){ pthread_t consumer_t; in = out = 0; pthread_mutex_init(&mutex, 0); pthread_cond_init(&wait_empty_buffer, 0); pthread_cond_init(&wait_full_buffer ,0); pthread_create(&consumer_t, 0, consumer, 0); producer(0); pthread_join(consumer_t, 0); return 0; }
1
#include <pthread.h> char knockCount; char idCount; pthread_mutex_t gateLock; pthread_mutex_t idLock; pthread_mutex_t* threadLock; pthread_t gateThread; void trySort() { pthread_mutex_lock(&gateLock); knockCount++; printf("Knocked %d time(s)\\n", knockCount); pthread_mutex_unlock(&gateLock); } void waitForSort(char id) { printf("thread %d is waiting on a sort\\n", id); pthread_mutex_lock(&threadLock[id]); pthread_mutex_unlock(&threadLock[id]); printf("thread %d is resuming\\n", id); } void gateWait() { int i; for(i=0; i<numThreads; i++) { pthread_mutex_lock(&threadLock[i]); } while(knockCount < numThreads); pthread_mutex_lock(&gateLock); knockCount = 0; pthread_mutex_unlock(&gateLock); quicksort(generatedPrimes, generatedPrimesSize); for(i=0; i<numThreads; i++) { pthread_mutex_unlock(&threadLock[i]); } } int tearDown() { assert(pthread_mutex_destroy(&gateLock) == 0); assert(pthread_mutex_destroy(&idLock) == 0); int i; for(i=0; i<numThreads; i++) { assert(pthread_mutex_destroy(&threadLock[i]) == 0); } return 0; } void insertionsort(int* array, int start, int end) { ; } void quicksort(int* array, int size) { int i, j, p, t; if (size < 2) return; p = array[size / 2]; for (i = 0, j = size - 1;; i++, j--) { while (array[i] < p) i++; while (p < array[j]) j--; if (i >= j) break; t = array[i]; array[i] = array[j]; array[j] = t; } quicksort(array, i); quicksort(array + i, size - i); } void *sortMain() { int i; idCount = -1; threadLock = malloc( sizeof(pthread_mutex_t) * numThreads); pthread_mutex_init(&gateLock, 0); pthread_mutex_init(&idLock, 0); for(i=0; i<numThreads; i++) { pthread_mutex_init(&threadLock[i], 0); } while(!terminate) { gateWait(); } tearDown(); return; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", 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... Count = %d\\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, const 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, 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); return 0; }
1
#include <pthread.h> double pi_final; pthread_mutex_t m; int compute_pi(int interval, int N) { int i; double pi, step, x, sum=0.0; step = 1/(double)(long int) 1000000000; for(i=((long int) 1000000000/N)*interval; i<((long int) 1000000000/N)*(interval+1); i++) { x = (i+0.5)*step; sum+=4.0/(1.0+x*x); } pi=step*sum; pthread_mutex_lock(&m); pi_final+=pi; pthread_mutex_unlock(&m); printf("compute_pi(%i,%i): pi = %f,\\tpi_final = %f\\n", interval, N, pi, pi_final); return 0; } void *runner(void *param); int main(int argc, char *argv[]) { int tn; tname_t arg[5]; pthread_t tid[4]; pthread_attr_t attr[4]; pthread_mutex_init(&m,0); struct timespec tv_start, tv_end; clock_gettime(CLOCK_REALTIME,&tv_start); for(tn=0;tn<4;tn++) pthread_attr_init(&attr[tn]); for(tn=0;tn<4;tn++) { sprintf(arg[tn],"%d\\n",tn); pthread_create(&tid[tn],&attr[tn],runner,arg[tn]); } puts("I am parent"); for(tn=0;tn<4;tn++) pthread_join(tid[tn],0); pthread_mutex_destroy(&m); clock_gettime(CLOCK_REALTIME,&tv_end); printf("parent:\\t pi_final = %.10f\\n",pi_final); printf("parent:\\t actual PI: %.10f\\n", M_PI); printf("parent:\\t N_THREADS: %d, N_STEPS: %.0e, total time: %.3f (msec)\\n", 4, (double) (long int) 1000000000, (tv_end.tv_nsec-tv_start.tv_nsec + 1e9 * (tv_end.tv_sec-tv_start.tv_sec))/(double)1e6); return 0; } void *runner(void *param) { printf("I am thread %s", (char *) param); compute_pi(atoi(param),4); pthread_exit(0); }
0
#include <pthread.h> struct send_package_queue *InitQueue(void) { struct send_package_queue *pqueue = (struct send_package_queue *)malloc(sizeof(struct send_package_queue)); if(pqueue!=0) { pqueue->front = 0; pqueue->rear = 0; pqueue->size = 0; pthread_mutex_init(&pqueue->node_mutex, 0); } return pqueue; } char IsEmpty(struct send_package_queue *pqueue) { if(pqueue->front==0 && pqueue->rear==0 && pqueue->size==0) return 1; else return 0; } char EnQueue(struct send_package_queue *pqueue, void* node_data) { struct send_package_qnode *pnode = (struct send_package_qnode* )malloc(sizeof(struct send_package_qnode)); if(pnode != 0) { pnode->node_data = node_data; pnode->next = 0; pthread_mutex_lock(&pqueue->node_mutex); do{ if(IsEmpty(pqueue)) { pqueue->front = pnode; } else { pqueue->rear->next = pnode; } pqueue->rear = pnode; pqueue->size++; }while(0); pthread_mutex_unlock(&pqueue->node_mutex); } else return -1; return 0; } void* DeQueue(struct send_package_queue *pqueue) { struct send_package_qnode *pnode = pqueue->front; if(pnode == 0) return 0; void* node_data = 0; if(IsEmpty(pqueue) != 1 && pnode != 0) { pthread_mutex_lock(&pqueue->node_mutex); do{ node_data = pnode->node_data; pqueue->size--; pqueue->front = pnode->next; if(pqueue->size==0) pqueue->rear = 0; }while(0); pthread_mutex_unlock(&pqueue->node_mutex); } free(pnode); return node_data; } void ClearQueue(struct send_package_queue *pqueue) { while(IsEmpty(pqueue)!=1) { DeQueue(pqueue); } } void DestroyQueue(struct send_package_queue *pqueue) { if(IsEmpty(pqueue)!=1) ClearQueue(pqueue); free(pqueue); } int GetSize(struct send_package_queue *pqueue) { return pqueue->size; } struct send_package_qnode *GetFront(struct send_package_queue *pqueue) { return pqueue->front; } struct send_package_qnode *GetRear(struct send_package_queue *pqueue) { return pqueue->rear; }
1
#include <pthread.h> struct uart_send_buf rs232_send_list[SEND_BUFF_SIZE + 1]; unsigned char rs232_read_current = 0, rs232_write_current = 0; void msg_write_to_list(unsigned char *date,unsigned char len) { unsigned char parket_len = rs232_send_list[rs232_write_current].datelen; pthread_mutex_lock(&mutex_list); if((parket_len + len) <= MAX_UART_SEND_LEN) { memcpy((unsigned char *)&rs232_send_list[rs232_write_current].date_buf[parket_len], date, len); rs232_send_list[rs232_write_current].datelen = parket_len + len; } else if(len > MAX_UART_SEND_LEN) { printf("write msg is too big, this is send of no waiting\\n"); printhex(date, len); rs232_send(date, len); } else { if(rs232_write_current == SEND_BUFF_SIZE)rs232_write_current = 0; else rs232_write_current++; if(rs232_send_list[rs232_write_current].datelen != 0) { printf("write_to_list is full, this is send of no waiting\\n"); printhex(date, len); rs232_send(date, len); } else { memcpy((unsigned char *)&rs232_send_list[rs232_write_current].date_buf[0], date, len); rs232_send_list[rs232_write_current].datelen = len; } } pthread_cond_signal(&cond_list); pthread_mutex_unlock(&mutex_list); } unsigned char msg_read_to_list(void) { pthread_mutex_lock(&mutex_list); unsigned char parket_len = rs232_send_list[rs232_read_current].datelen; unsigned char ret; if(parket_len != 0) { rs232_send((unsigned char *)&rs232_send_list[rs232_read_current].date_buf, parket_len); rs232_send_list[rs232_read_current].datelen = 0; if(rs232_write_current != rs232_read_current) { if(rs232_read_current == SEND_BUFF_SIZE)rs232_read_current = 0; else rs232_read_current++; ret = 1; } else ret = 0; } else ret = 0; pthread_mutex_unlock(&mutex_list); return ret; }
0
#include <pthread.h> { unsigned long long id; unsigned char data[1024]; } Package; int fd_audio; int isbusy_audio; pthread_mutex_t mutex_isbusy_audio,mutex_isbusy_audio; unsigned long long current_recv_id,current_send_id; pthread_mutex_t mutex_local_recv,mutex_local_send,lock_local; pthread_cond_t cond_local; void resetID() { current_recv_id = 0; pthread_mutex_lock(&mutex_local_send); current_send_id = 0; pthread_mutex_unlock(&mutex_local_send); pthread_mutex_lock(&mutex_isbusy_audio); isbusy_audio = 0; pthread_mutex_unlock(&mutex_isbusy_audio); } int initDsp() { int fd; int arg; int status; fd = open("/dev/dsp", O_RDWR); if (fd < 0) { perror("open of /dev/dsp failed"); exit(1); } arg = 16; status = ioctl(fd, SOUND_PCM_WRITE_BITS, &arg); if (status == -1) perror("SOUND_PCM_WRITE_BITS ioctl failed"); if (arg != 16) perror("unable to set sample size"); arg = 2; status = ioctl(fd, SOUND_PCM_WRITE_CHANNELS, &arg); if (status == -1) perror("SOUND_PCM_WRITE_CHANNELS ioctl failed"); if (arg != 2) perror("unable to set number of channels"); arg = 22050; status = ioctl(fd, SOUND_PCM_WRITE_RATE, &arg); if (status == -1) perror("SOUND_PCM_WRITE_WRITE ioctl failed"); return fd; } int main() { current_recv_id = 0; current_send_id = 0; isbusy_audio = 0; fd_audio = initDsp(); sock_thread_local(); close(fd_audio); return 0; }
1
#include <pthread.h> int check_primes(int a, int b); int start; int end; int sum; int tid; int stolen; int jobs; }* prime_arg_t; pthread_mutex_t m; void* prime_th(void* _arg) { prime_arg_t arg = _arg; arg->sum = check_primes(arg->start, arg->end); return 0; } void* do_job(void* _arg) { TAU_REGISTER_THREAD(); { prime_arg_t arg = _arg; int j = 0; while(j < arg[0].jobs) { pthread_mutex_lock(&m); if (arg[j].stolen == 0) { arg[j].stolen = 1; pthread_mutex_unlock(&m); arg[j].sum = check_primes(arg[j].start, arg[j].end); } else { pthread_mutex_unlock(&m); } j++; } } return 0; } int parallel_prime_mutex(int start, int end, int nthreads, int divide) { int t, j; prime_arg_t args = (prime_arg_t) malloc(sizeof(struct prime_arg) * divide); pthread_t* threads = (pthread_t*) malloc(sizeof(pthread_t) * nthreads); assert(threads); assert(args); int step = (end - start) / divide; if ((end - start) - divide * step != 0) step++; for (j = 0; j < divide; j++) { args[j].start = start + j * step; args[j].end = ((end) < (start + (j+1) * step) ? (end) : (start + (j+1) * step)); args[j].sum = 0; args[j].stolen = 0; args[j].jobs = divide; } for (t = 0; t < nthreads; t++) { pthread_create(&threads[t], 0, do_job, args); } for (t = 0; t < nthreads; t++) { pthread_join(threads[t], 0); } int s = 0; for (j = 0; j < divide; j++) { s += args[j].sum; } return s; } int check_prime(int n) { int d; for (d = 2; d * d <= n; d++) { if (n % d == 0) return 0; } return 1; } int check_primes(int a, int b) { int n; int s = 0; for (n = a; n < b; n++) { s += check_prime(n); } return s; } double cur_time() { struct timeval tp[1]; gettimeofday(tp, 0); return tp->tv_usec * 1.0E-6 + tp->tv_sec; } int main(int argc, char** argv) { int N = 10000000; double t0 = cur_time(); if (argc != 3) { fprintf(stderr, "usage: %s NTHREADS JOBS", argv[0]); exit(1); } int npthread = atoi(argv[1]); int jobs = atoi(argv[2]); int np = parallel_prime_mutex(2, N, npthread, jobs); double t1 = cur_time(); printf("%d primes in %f sec\\n", np, t1 - t0); return 0; }
0
#include <pthread.h> int threads, n, range,tasks,linked_list_size=0,task_count; pthread_mutex_t mutex; pthread_rwlock_t rwlock; struct linked_list { int data; struct linked_list *next; }; struct linked_list *head,*tail,*new,*temp; void insert(int value) { if (tail == 0) { tail = (struct linked_list *)malloc(sizeof(struct linked_list)); tail->next = 0; tail->data = value; head = tail; } else { new=(struct linked_list *)malloc(sizeof(struct linked_list)); tail->next = new; new->data = value; new->next = 0; tail = new; } linked_list_size++; printf("Inserted %d \\n",value ); } void display() { temp=head; if(temp==0) { return; } printf("Elements are :"); while(temp!=0) { printf("%d ",temp->data); temp=temp->next; } printf("\\n"); } void member(int value) { int check=0; temp = head; if ((temp == 0) && (tail == 0)) { printf("List is empty"); return; } while (temp != tail) { if(temp->data==value) { check=1; printf("%d is in the list ", temp->data); break; } temp = temp->next; } if (temp == tail) if(temp->data==value) { printf("%d is in the list ", temp->data); check=1; } if(check==0) printf("%d is not in the linked list ", value); printf("\\n"); } void delete() { temp = head; if (temp == 0) { printf("List is empty"); return; } else if (temp->next != 0) { temp = temp->next; printf(" Removed %d from the linked list", head->data); free(head); head = temp; } else { printf(" Removed %d from the linked list", head->data); free(head); head = 0; tail = 0; } linked_list_size--; printf("\\n"); } void *Task_Queue(void* rank) { int i,thread_range,ct; long local_rank = (long) rank; thread_range = task_count/threads; pthread_mutex_lock(&mutex); for (i = 0; i < thread_range; i++) { ct=i%3; switch(ct) { case 0 : pthread_rwlock_wrlock(&rwlock); insert(linked_list_size+1); pthread_rwlock_unlock(&rwlock); pthread_rwlock_rdlock(&rwlock); display(); pthread_rwlock_unlock(&rwlock); printf("\\n"); break; case 1: pthread_rwlock_wrlock(&rwlock); delete(); pthread_rwlock_unlock(&rwlock); printf("\\n"); break; case 2 : pthread_rwlock_rdlock(&rwlock); member(rand()%17); pthread_rwlock_unlock(&rwlock); printf("\\n"); break; default: break; } } pthread_mutex_unlock(&mutex); return 0; } int main() { int no, ch, e; long i; pthread_t* thread_handles; head = 0; tail =0; printf("Enter the number of threads\\n"); scanf("%d",&threads); printf("Enter the number of tasks to be performed\\n"); scanf("%d",&task_count); for(int j=1;j<10;j++) { insert(j); } printf("----------------------\\n"); thread_handles = malloc (threads*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); pthread_rwlock_init(&rwlock, 0); for (i = 0; i < threads; i++) pthread_create(&thread_handles[i], 0, Task_Queue, (void*) i); for (i = 0; i < threads; i++) pthread_join(thread_handles[i], 0); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexsum; int *a, *b; long sum=0.0; void *dotprod(void *arg) { int i, start, end, offset, len; long tid; tid = (long)arg; offset = tid; len = 4; start = offset*len; end = start + len; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++) { pthread_mutex_lock(&mutexsum); sum += (a[i] * b[i]); pthread_mutex_unlock(&mutexsum); } printf("thread: %ld done. Global sum now is=%li\\n",tid,sum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; void *status; pthread_t threads[3]; pthread_attr_t attr; a = (int*) malloc (3*4*sizeof(int)); b = (int*) malloc (3*4*sizeof(int)); for (i=0; i<4*3; i++) a[i]=b[i]=1; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<3;i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_attr_destroy(&attr); for(i=0;i<3;i++) { pthread_join(threads[i], &status); } printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t count_mutex; pthread_mutex_t condition_mutex; pthread_cond_t condition_cond; void *functionCount1(); void *functionCount2(); int count = 0; main() { pthread_mutex_init(&count_mutex, 0); pthread_mutex_init(&condition_mutex, 0); pthread_cond_init(&condition_cond, 0); pthread_t thread1, thread2; pthread_create(&thread1, 0, &functionCount1, 0); pthread_create(&thread2, 0, &functionCount2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_exit(0); } void *functionCount1() { for (;;) { pthread_mutex_lock(&condition_mutex); while (count >= 3 && count <= 6) { pthread_cond_wait(&condition_cond, &condition_mutex); } pthread_mutex_unlock(&condition_mutex); pthread_mutex_lock(&count_mutex); count++; printf("Counter value functionCount1: %d\\n", count); pthread_mutex_unlock(&count_mutex); if (count >= 10) { pthread_exit(0); } } } void *functionCount2() { for (;;) { pthread_mutex_lock(&condition_mutex); if (count < 3 || count > 6) { pthread_cond_signal(&condition_cond); } pthread_mutex_unlock(&condition_mutex); pthread_mutex_lock(&count_mutex); count++; printf("Counter value functionCount2: %d\\n", count); pthread_mutex_unlock(&count_mutex); if (count >= 10) pthread_exit(0); } }
1
#include <pthread.h> struct synch_linked_list * synchronous_linked_list(void (*print)(void *), void (*destructor)(void *)){ struct synch_linked_list * list = ALLOC(*list, 1); list->mutex = ALLOC(*list->mutex, 1); pthread_mutex_init(list->mutex, 0); list->head = 0; list->tail = 0; list->size = 0; list->print = print; list->destructor = destructor; return list; } bool synch_list_insert (struct synch_linked_list *list, struct synch_node *node, void *p){ if (!list || !node) return 0; pthread_mutex_lock(list->mutex); struct synch_node *current = list->head; while (current){ if (current == node) break; current = current->next; } if (current != node){ pthread_mutex_unlock(list->mutex); return 0; } struct synch_node *element = ALLOC(*element, 1); element->element = p; element->next = node->next; element->prev = node; node->next = element; if (list->tail == node) list->tail = element; list->size++; pthread_mutex_unlock(list->mutex); return 1; } bool synch_list_add (struct synch_linked_list *list, void *p){ if (!list) return 0; pthread_mutex_lock(list->mutex); if (list->head) { struct synch_node *node = list->tail; struct synch_node *element = ALLOC(*element, 1); element->element = p; element->next = node->next; element->prev = node; node->next = element; if (list->tail == node) list->tail = element; list->size++; } else { struct synch_node *element = ALLOC(*element, 1); element->element = p; list->head = element; list->tail = element; list->size++; } pthread_mutex_unlock(list->mutex); return 1; } struct synch_node *synch_list_find(struct synch_linked_list *list, int p){ if (!list || !p) return 0; pthread_mutex_lock(list->mutex); struct synch_node *node = list->head; while (node && *((int *)node->element) != p) node = node->next; pthread_mutex_unlock(list->mutex); return node; } bool synch_list_remove (struct synch_linked_list *list, struct synch_node *node){ if (!list || !node) return 0; if (node == list->head){ if (!node->next){ list->head = 0; list->tail = 0; } else { node->next->prev = 0; list->head = node->next; } } else if (node == list->tail){ node->prev->next = 0; list->tail = node->prev; } else { node->next->prev = node->prev; node->prev->next = node->next; } list->destructor(node->element); free(node); list->size--; return 1; } bool synch_list_remove_it (struct synch_linked_list *list, struct iterator *it){ if (!list || !it) return 0; struct synch_node *next = it->data; if (next == list->head) return 0; else if (!next) return synch_list_remove(list, list->tail); return synch_list_remove(list, next->prev); } void synch_list_print (struct synch_linked_list *list){ if (!list) return; pthread_mutex_lock(list->mutex); struct synch_node *node = list->head; while (node){ list->print(node->element); node = node->next; } pthread_mutex_unlock(list->mutex); } struct iterator *synch_list_begin(struct synch_linked_list *list){ if (!list) return 0; struct iterator *it = ALLOC(*it, 1); pthread_mutex_lock(list->mutex); it->collection = list; it->data = list->head; it->destructor = destroy_synch_list_it; it->hasNext = synch_list_it_hasNext; it->next = synch_list_it_next; return it; } bool synch_list_it_hasNext(struct iterator *it){ if (it && it->data) return 1; return 0; } void *synch_list_it_next(struct iterator *it){ if (!it || !((struct synch_node *)it->data)) return 0; void *ret = ((struct synch_node *)it->data)->element; it->data = ((struct synch_node *)it->data)->next; return ret; } void destroy_synch_list_it(void *p){ if (!p) return; struct iterator *it = p; struct synch_linked_list *list = it->collection; pthread_mutex_unlock(list->mutex); free(p); } void destroy_synchronous_linked_list(void *p){ if (!p) return; struct synch_linked_list *list = p; struct synch_node *node = list->tail; if (node){ while (node->prev){ node = node->prev; list->destructor(node->next->element); free(node->next); } list->destructor(node->element); free(node); } pthread_mutex_destroy(list->mutex); free(list); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(400)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(400)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(400); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> struct signal { int active; pthread_mutex_t mutex; pthread_cond_t condition; }; static struct signal sig = { .active = 0, .mutex = PTHREAD_MUTEX_INITIALIZER, .condition = PTHREAD_COND_INITIALIZER }; void* signal_thread (void* param) { sleep(5); pthread_mutex_lock(&sig.mutex); sig.active = 1; pthread_mutex_unlock(&sig.mutex); printf ("Signal Thread -- I changed the shared resource! Signaling all other threads!\\n"); pthread_cond_broadcast(&sig.condition); pthread_exit(0); } void* wait_thread (void* param) { unsigned int* thread_num = (unsigned int*)param; pthread_mutex_lock(&sig.mutex); while (!sig.active) { pthread_cond_wait(&sig.condition, &sig.mutex); } pthread_mutex_unlock(&sig.mutex); pthread_exit(0); } int main (int argc, char** argv) { int i; pthread_t sthread_id; pthread_t wthread_id[5]; unsigned int wthread_num[5]; for (i=0; i<5; i++) { wthread_num[i] = i; pthread_create(&wthread_id[i], 0, wait_thread, &wthread_num[i]); } pthread_create(&sthread_id, 0, signal_thread, 0); for (i=0; i<5; i++) pthread_join(wthread_id[i], 0); pthread_join(sthread_id, 0); return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex; int dao_queue_init(struct DaoQueueFlag *queueFlag, int queueNum, struct DaoQueue **queues, struct DaoQueueDate **queueDates) { pthread_mutex_init(&mutex, 0); if(queueNum==0) { return DAOFAILURE; } int i; for(i=0; i<queueNum; i++) { memset((*(queueDates+i))->data, 0, sizeof(char)*(*(queueDates+i))->dataSize); (*(queues+i))->data=*(queueDates+i); (*(queues+i))->depth=0; (*(queues+i))->index=i; (*(queues+i))->queueFlag=queueFlag; } queueFlag->startQueue=queues; queueFlag->num=queueNum; queueFlag->nowSetIndex=0; queueFlag->nowGetIndex=0; queueFlag->maxIndex=0; return DAOSUCCESS; } void dao_queue_exit(struct DaoQueueFlag *queueFlag) { pthread_mutex_destroy(&mutex); } int dao_queue_reset(struct DaoQueueFlag *queueFlag) { queueFlag->maxIndex=0; queueFlag->nowGetIndex=0; queueFlag->nowSetIndex=0; int i; struct DaoQueue *queue; for(i=0; i<queueFlag->num; i++) { queue=*(queueFlag->startQueue+i); memset(queue->data->data, 0, sizeof(char)*queue->data->dataSize); queue->data->dataSize=0; queue->depth=0; } return DAOSUCCESS; } int dao_queue_set(struct DaoQueueFlag *queueFlag, int depth, char *obj){ int index=-1; pthread_mutex_lock(&mutex); index=queueFlag->nowSetIndex; queueFlag->nowSetIndex=queueFlag->nowSetIndex+1; pthread_mutex_unlock(&mutex); if(index==-1){ return DAOFAILURE; } if(index>=queueFlag->num) { return 2; } struct DaoQueue *nowQueue; struct DaoQueue *queueTmp; nowQueue=*(queueFlag->startQueue+index); if((strlen(obj)+1)>=nowQueue->totalSize){ return DAOFAILURE; } strncpy(nowQueue->data->data, obj, strlen(obj)+1); nowQueue->depth=depth; if(index>queueFlag->maxIndex) { queueFlag->maxIndex=index; } return DAOSUCCESS; } int dao_queue_get(struct DaoQueueFlag *queueFlag, struct DaoQueue **nowQueue){ int index=-1; pthread_mutex_lock(&mutex); index=queueFlag->nowGetIndex; queueFlag->nowGetIndex=queueFlag->nowGetIndex+1; pthread_mutex_unlock(&mutex); if(index==-1){ return DAOFAILURE; } *nowQueue=*(queueFlag->startQueue+index); return DAOSUCCESS; } int dao_queue_set_index(struct DaoQueueFlag *queueFlag, int index, int depth, char *obj) { if(index>=queueFlag->num) { return 2; } struct DaoQueue *nowQueue; struct DaoQueue *queueTmp; nowQueue=*(queueFlag->startQueue+index); if((strlen(obj)+1)>=nowQueue->totalSize){ return DAOFAILURE; } strncpy(nowQueue->data->data, obj, strlen(obj)+1); nowQueue->depth=depth; queueFlag->nowSetIndex=queueFlag->nowSetIndex+1; if(index>queueFlag->maxIndex) { queueFlag->maxIndex=index; } return DAOSUCCESS; } int dao_queue_get_index(struct DaoQueueFlag *queueFlag, int index, struct DaoQueue **nowQueue) { *nowQueue=*(queueFlag->startQueue+index); queueFlag->nowGetIndex=queueFlag->nowGetIndex+1; return DAOSUCCESS; }
1
#include <pthread.h> int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int nondet_int(); int stored_elements[(20)]; _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 == (20)) { 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 == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for(i=0; i<((20)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: ; } void *t2(void *arg) { int i; for(i=0; i<(20); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { goto ERROR; 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)) { goto ERROR; 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> int value; int status; enum { ON, OFF, }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread_one(void *arg) { pthread_mutex_lock(&mutex); value = 5; status = OFF; pthread_cond_signal(&cond); printf("%d\\n", value); pthread_mutex_unlock(&mutex); return (void *)0; } void *thread_two(void *arg) { pthread_mutex_lock(&mutex); while (status == ON) { pthread_cond_wait(&cond, &mutex); } value = 6; printf("%d\\n", value); pthread_mutex_unlock(&mutex); return (void *)0; } int main() { pthread_t tids[2] = {0}; int rv[2]; rv[0] = pthread_create(&tids[0], 0, thread_one, 0); rv[1] = pthread_create(&tids[1], 0, thread_two, 0); if (rv[0] != 0 || rv[1] != 0) { fprintf(stderr, "thread_one %s thread_two %s\\n", strerror(rv[0]), strerror(rv[1])); return 1; } pthread_join(tids[0], 0); pthread_join(tids[1], 0); return 0; }
1
#include <pthread.h> int buffer[1024]; int count=0; pthread_mutex_t mutex1; pthread_mutex_t mutex2; void *threadFun1(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex1); printf("Thread 1\\n"); count++; pthread_mutex_unlock(&mutex2); } } void *threadFun2(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex2); printf("Thread 2:%d\\n",count); pthread_mutex_unlock(&mutex1); } } void *threadFun3(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex2); printf("Thread 3:%d\\n",count); pthread_mutex_unlock(&mutex1); } } int main() { pthread_t tid[3]; int ret=0; int i; int t_value[3]; void *(*threadFun[])(void*) = {threadFun1, threadFun2,threadFun3}; ret = pthread_mutex_init(&mutex1,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } ret = pthread_mutex_init(&mutex2,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex2); printf("Main thread before pthread create\\n"); for(i=0; i<3; i++) { t_value[i]=i; ret=pthread_create( &(tid[i]), 0, threadFun[i], (void*)&(t_value[i])); if(ret!=0) { fprintf(stderr, "pthread create error:%s", strerror(ret)); return 1; } } printf("Main thread after pthread create\\n"); for(i=0; i<3; i++) { ret = pthread_join(tid[i],0); if(ret!=0) { fprintf(stderr, "pthread join error:%s", strerror(ret)); return 2; } } ret = pthread_mutex_destroy(&mutex1); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex2); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } printf("All threads are over!\\n"); return 0; }
0
#include <pthread.h> volatile int servings = 0; volatile int savagesNumber = 0; volatile int maxServings = 0; sem_t emptyPot; sem_t fullPot; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void getInput(){ clear(); move(0, 0); printw("Digite o numero maximo de pratos: "); refresh(); scanw("%d", &maxServings); printw("Digite o numero de selvagens: "); refresh(); scanw("%d", &savagesNumber); } void drawPanel(int id){ int i; move(0, 0); for(i = 1; i < 5; i++){ move(i, 0); } move(i, 0); move(0, 0); for(i = 1; i < 5; i++){ move(i, 49); } move(1, 3); printw("Pratos disponiveis: %d", servings); move(2, 3); printw("Total de selvagens: %d", savagesNumber); move(3, 3); printw("Selvagem %d esta pegando comida", id + 1); move(4, 3); printw("PRESSIONE QUALQUER TECLA PARA SAIR"); } void drawIdleSavages(int id){ clear(); drawPanel(id); int i; int pos; for(i = 0; i < savagesNumber; i++){ pos = 10 + (i * 4); move(pos, 0); printw(" O (%d)", i + 1); pos++; move(pos, 0); printw(" /|\\\\"); pos++; move(pos, 0); printw(" < >"); } move(8, 18); if(servings == 0){ printw("| |"); move(9, 19); printw("T"); } else { printw("|o|"); move(9, 19); printw("T"); } } void moveSavage(int id){ int i; int pos; int frame; int posIdRow = (10 + (id * 4)); int posIdCol = 0; for(frame = 0; frame < ((id * 4) + 25); frame++){ move(posIdRow, posIdCol); clrtoeol(); printw(" O (%d)", id + 1); move(posIdRow + 1, posIdCol); clrtoeol(); printw(" /|\\\\"); move(posIdRow + 2, posIdCol); clrtoeol(); printw(" / \\\\"); move(posIdRow + 3, posIdCol); clrtoeol(); if(posIdCol == 21){ posIdRow--; } else { posIdCol++; } refresh(); usleep(100000); } } void putServingsInPot(){ move(3, 3); clrtoeol(); printw("O pote esta sendo enchido"); move(3, 49); int i; for(i = 0; i < maxServings; i++){ move(6, 19); printw("o"); move(7, 19); printw(" "); refresh(); usleep(100000); move(6, 19); printw(" "); move(7, 19); printw("o"); refresh(); usleep(100000); move(8, 19); printw("o"); refresh(); usleep(100000); } move(7, 19); printw(" "); sleep(1); } void getServingFromPot(int id){ drawIdleSavages(id); moveSavage(id); servings--; drawIdleSavages(id); refresh(); } void eatAnimation(int id){ int pos = 10 + (id * 4); move(pos + 1, 4); printw("CHOMP.."); refresh(); usleep(100000); move(pos + 1, 4); printw(" "); refresh(); usleep(100000); move(pos + 1, 4); printw("CHOMP.."); refresh(); usleep(100000); move(pos + 1, 4); printw(" "); refresh(); usleep(100000); move(pos + 1, 4); printw("CHOMP.."); refresh(); usleep(100000); move(pos + 1, 4); printw(" "); refresh(); usleep(100000); move(pos + 1, 4); printw("CHOMP.."); refresh(); usleep(100000); move(pos + 1, 4); printw(" "); refresh(); usleep(100000); } void eatSleep(){ sleep(3); } void* cook(void *v) { while (1) { sem_wait(&emptyPot); putServingsInPot(); sem_post(&fullPot); } } void* savage(void *v) { int id = *(int *)v; while (1) { pthread_mutex_lock(&mutex); if (servings == 0) { sem_post(&emptyPot); sem_wait(&fullPot); servings = maxServings; } getServingFromPot(id); eatAnimation(id); pthread_mutex_unlock(&mutex); eatSleep(); } } int main() { initscr(); getInput(); servings = maxServings; int i; pthread_t thr_savages[savagesNumber]; pthread_t thr_cook; int savagesIds[savagesNumber]; for(i = 0; i < savagesNumber; i++){ savagesIds[i] = i; } curs_set(0); sem_init(&emptyPot, 0, 0); sem_init(&fullPot, 0, 0); pthread_create(&thr_cook, 0, cook, 0); for (i = 0; i < savagesNumber; i++) { pthread_create(&thr_savages[i], 0, savage, (void *)&savagesIds[i]); } getch(); endwin(); return 0; }
1
#include <pthread.h> struct server { int nr_threads; int max_requests; int max_cache_size; int *buffer; }; void fill_in(struct server *sv, int connfd); int process(struct server *sv); void worker_function (struct server *sv); int in=0; int out=0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t FULL; pthread_cond_t EMPTY; static struct file_data * file_data_init(void) { struct file_data *data; data = Malloc(sizeof(struct file_data)); data->file_name = 0; data->file_buf = 0; data->file_size = 0; return data; } static void file_data_free(struct file_data *data) { free(data->file_name); free(data->file_buf); free(data); } static void do_server_request(struct server *sv, int connfd) { int ret; struct request *rq; struct file_data *data; data = file_data_init(); rq = request_init(connfd, data); if (!rq) { file_data_free(data); return; } ret = request_readfile(rq); if (!ret) goto out; request_sendfile(rq); out: request_destroy(rq); file_data_free(data); } struct server * server_init(int nr_threads, int max_requests, int max_cache_size) { struct server *sv; int a; sv = Malloc(sizeof(struct server)); sv->nr_threads = nr_threads; sv->max_requests = max_requests+1; sv->max_cache_size = max_cache_size; if (nr_threads > 0 || max_requests > 0 || max_cache_size > 0) { sv->buffer = malloc((max_requests+1)*sizeof(int)); if (nr_threads>0) { pthread_t threads[nr_threads]; for (a=0; a<nr_threads; a++){ pthread_create (&threads[a], 0, (void *)&worker_function, sv); } } } return sv; } void server_request(struct server *sv, int connfd) { if (sv->nr_threads == 0) { do_server_request(sv, connfd); } else { fill_in(sv, connfd); } } void fill_in(struct server *sv, int connfd) { pthread_mutex_lock(&lock); while ((in-out+sv->max_requests)%(sv->max_requests) == (sv->max_requests-1)) { pthread_cond_wait (&FULL,&lock); } sv->buffer[in]=connfd; if (in==out){ pthread_cond_signal(&EMPTY); } in= (in+1)%(sv->max_requests); pthread_mutex_unlock(&lock); } int process(struct server *sv) { pthread_mutex_lock(&lock); int msg; while (in==out){ pthread_cond_wait(&EMPTY,&lock); } msg = sv->buffer[out]; if ((in-out+sv->max_requests)%sv->max_requests == sv->max_requests-1){ pthread_cond_signal(&FULL); } out = (out+1)%sv->max_requests; pthread_mutex_unlock(&lock); return msg; } void worker_function (struct server *sv) { while(1) { int connfd2 = process(sv); do_server_request(sv,connfd2); } }
0
#include <pthread.h> static int keep_ticks; static void *tickTurn(void *ptr); static struct turn_info turnInfo; static struct listenConfig listenConfig; static pthread_t turnListenThread; static pthread_t turnTickThread; static char permission_ip[1000]; static char message[100]; static char rcv_message[1000]; static char message_dst[50]; static int highlight = 1; pthread_mutex_t turnInfo_mutex = PTHREAD_MUTEX_INITIALIZER; void update_turnInfo(){ pthread_mutex_lock( &turnInfo_mutex ); print_status(status_win, &turnInfo); pthread_mutex_unlock( &turnInfo_mutex ); print_menu(menu_win, highlight); print_input(input_win); } void init_view(); void cleanup(); void doChoice(int choice); void messageCB(unsigned char *message); static void *tickTurn(void *ptr){ struct timespec timer; struct timespec remaining; uint32_t *ctx = (uint32_t *)ptr; struct turn_info *tInfo = (struct turn_info*)ptr; timer.tv_sec = 0; timer.tv_nsec = 50000000; for(;;){ nanosleep(&timer, &remaining); if(tInfo->turnAlloc_44.tInst != 0){ TurnClient_HandleTick(tInfo->turnAlloc_44.tInst); } if(tInfo->turnAlloc_46.tInst != 0){ TurnClient_HandleTick(tInfo->turnAlloc_46.tInst); } if(tInfo->turnAlloc_64.tInst != 0){ TurnClient_HandleTick(tInfo->turnAlloc_64.tInst); } if(tInfo->turnAlloc_66.tInst != 0){ TurnClient_HandleTick(tInfo->turnAlloc_66.tInst); } } } int main(int argc, char *argv[]) { int choice = 0; int c; if (argc != 5) { fprintf(stderr,"usage: testturn iface turnserver user pass\\n"); exit(1); } initTurnInfo(&turnInfo); addCredentials(&turnInfo, argv[2], argv[3], argv[4]); getRemoteTurnServerIp(&turnInfo, argv[2]); getLocalIPaddresses(&turnInfo, SOCK_DGRAM, argv[1]); init_view(); print_status(status_win, &turnInfo); while(1) { c = wgetch(menu_win); switch(c) { case KEY_LEFT: if(highlight == 1) highlight = n_choices; else --highlight; break; case KEY_RIGHT: if(highlight == n_choices) highlight = 1; else ++highlight; break; case 10: choice = highlight; break; default: refresh(); break; } print_menu(menu_win, highlight); print_input(input_win); if(choice != 0){ doChoice(choice); } choice = 0; } return 0; } void init_view() { int max_x, max_y; int start_menu_x = 0; int start_menu_y = 0; int start_input_x = 0; int start_input_y = 0; int start_message_x = 0; int start_message_y = 0; initscr(); start_color(); clear(); noecho(); cbreak(); getmaxyx(stdscr,max_y,max_x); start_menu_x = 0; start_menu_y = max_y - HEIGHT; menu_win = newwin(HEIGHT, max_x, start_menu_y, start_menu_x); keypad(menu_win, TRUE); start_input_x = 0; start_input_y = start_menu_y - 3; input_win = newwin(3, max_x, start_input_y, start_input_x); start_message_x = 0; start_message_y = start_input_y - 3; message_win = newwin(3, max_x, start_message_y, start_message_x); status_win = newwin(start_message_y-1, max_x, 0, 0); print_menu(menu_win, 1); print_input(input_win); print_message(message_win, " "); } void cleanup(){ clrtoeol(); refresh(); endwin(); close(turnInfo.turnAlloc_44.sockfd); close(turnInfo.turnAlloc_46.sockfd); close(turnInfo.turnAlloc_64.sockfd); close(turnInfo.turnAlloc_66.sockfd); system("reset"); } void doChoice(int choice) { switch(choice){ case 1: gatherAll(&turnInfo, &update_turnInfo, &listenConfig, &messageCB); pthread_create( &turnTickThread, 0, tickTurn, (void*) &turnInfo); pthread_create( &turnListenThread, 0, stunListen, (void*)&listenConfig); break; case 2: permission_ip[0]='\\0'; fillRflxPermissions(&turnInfo); sendPermissionsAll(&turnInfo); print_status(status_win, &turnInfo); break; case 3: mvwprintw(input_win,1, 1, "Enter Message: "); wrefresh(input_win); echo(); wgetstr(input_win, message); mvwprintw(input_win,1, 1, "Enter Ip: "); wrefresh(input_win); wgetstr(input_win, message_dst); noecho(); sendMessage(&turnInfo, message_dst, message); break; case 4: releaseAll(&turnInfo); break; case 5: releaseAll(&turnInfo); cleanup(); exit(0); break; } } void messageCB(unsigned char *message) { int n = sizeof(rcv_message); memcpy(rcv_message, message, n); if (n > 0) rcv_message[n - 1]= '\\0'; print_message(message_win, rcv_message); }
1
#include <pthread.h> void *assistantThread(); void *studentThread(); pthread_mutex_t assistantMutex; pthread_mutex_t studentMutex; int main() { pthread_t assistantID; srand(time(0)); pthread_mutex_t assistantMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t studentMutex = PTHREAD_MUTEX_INITIALIZER; pthread_create(&assistantID, 0, &assistantThread, 0); pthread_join(assistantID, 0); return 0; } void *assistantThread() { pthread_t studentID[10]; int idThread = 0; printf("The teaching assistant is napping right now.\\n"); for (idThread = 0; idThread < 10; idThread ++) { pthread_create(&studentID[idThread], 0, &studentThread, 0); } for (idThread = 0; idThread < 10; idThread ++) { pthread_join(studentID[idThread], 0); } } void *studentThread() { int timeLeft; timeLeft = rand() % 10 + 1; if (pthread_mutex_lock(&assistantMutex) == 0) { printf("The student woke the teaching assistant and is getting help. Estimate is %d min.\\n", timeLeft); sleep(timeLeft); pthread_mutex_unlock(&assistantMutex); } else if (pthread_mutex_lock(&studentMutex) > 2 ) { printf("The student will be coming back some other time.\\n"); } else { pthread_mutex_lock(&studentMutex); printf("The student is now doing work for the assignment until the teaching assistant is unoccupied.\\n"); pthread_mutex_lock(&assistantMutex); pthread_mutex_unlock(&studentMutex); printf("The student just ingressed the teaching assistant's office. Estimate is %d min.\\n", timeLeft); sleep(timeLeft); pthread_mutex_unlock(&assistantMutex); } }
0
#include <pthread.h> pthread_mutex_t mutex[5]; void chopsticks_init(){ int i; for (i = 0; i < 5; i++){ assert(!pthread_mutex_init(&mutex[i],0)); } } void chopsticks_destroy(){ int i; for (i = 0; i < 5; i++){ assert(!pthread_mutex_destroy(&(mutex[i]))); } } void pickup_chopsticks(int phil_id){ if (phil_id % 2 == 0) { pthread_mutex_lock(&mutex[(phil_id+1)%5]); pickup_right_chopstick(phil_id); pthread_mutex_lock(&mutex[(phil_id)%5]); pickup_left_chopstick(phil_id); } else { pthread_mutex_lock(&mutex[(phil_id)%5]); pickup_left_chopstick(phil_id); pthread_mutex_lock(&mutex[(phil_id+1)%5]); pickup_right_chopstick(phil_id); } } void putdown_chopsticks(int phil_id){ if (phil_id % 2 == 0) { putdown_right_chopstick(phil_id); pthread_mutex_unlock(&mutex[(phil_id+1)%5]); putdown_left_chopstick(phil_id); pthread_mutex_unlock(&mutex[(phil_id)%5]); } else { putdown_left_chopstick(phil_id); pthread_mutex_unlock(&mutex[(phil_id)%5]); putdown_right_chopstick(phil_id); pthread_mutex_unlock(&mutex[(phil_id+1)%5]);; } }
1
#include <pthread.h> void send(int); int receiveAndSync(int, int); void * worker(); int N_THREADS = 0; int N_LIMIT = 0; int BUFFER = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int main(int argc, char* argv[]) { if (argc < 2) { printf("Parametros: [nthreads][nlimit]\\n"); exit(1); } N_THREADS = atoi(argv[1]); N_LIMIT = atoi(argv[2]); pthread_t *ptr_threads = (pthread_t*) malloc (N_THREADS * sizeof(pthread_t)); for (int i = 0; i < N_THREADS; i++) { pthread_create(&ptr_threads[i], 0, worker, (void*) 0); } for (int i = 0; i < N_THREADS; i++) { pthread_join(ptr_threads[i], 0); } pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); return 1; } void * worker() { int timer = -1; for (int i = 0; i < N_LIMIT; i++) { pthread_mutex_lock(&lock); sleep(1); timer++; send(timer); timer = receiveAndSync(timer, i); pthread_mutex_unlock(&lock); } return 0; } void send(int timer) { BUFFER = timer; pthread_cond_broadcast(&cond); } int receiveAndSync(int timer, int it) { if (it == N_LIMIT - 1) { return timer; } pthread_cond_wait(&cond, &lock); if (timer < BUFFER) { timer = BUFFER; } return timer; }
0
#include <pthread.h> static int filename_parse(char * filename, struct dir_instance_t * elem) { int i = 0; int tokens = 0; char * str = filename; char prefix[8] = ""; char block_id[64] = ""; char ip_str[64] = ""; char * curr_str = prefix; while (*str){ if (*str == '+'){ tokens++; if (tokens == 1){ if (!strcmp(prefix, "all")){ elem->broadcast = 0xffffffff; }else if (!strcmp(prefix, "sgl")){ ; }else{ return -1; } curr_str = block_id; }else if (tokens == 2){ if(parse_u32(block_id, &elem->blockid)){ return -1; } curr_str = ip_str; } i = 0; str++; continue; } curr_str[i++] = *str; str++; } if (tokens == 1){ if(parse_u32(block_id, &elem->blockid)) return -1; return 0; }else if (tokens == 2){ if (parse_ip(ip_str, &elem->broadcast)) return -1; return 0; } return -1; } static int load_dir(struct config_instance_t * inst , const char * dir_name) { struct dir_instance_t * curr = 0; DIR *sys_dir; struct dirent *sys_elem; int i = 0; int work_idx = 0; static int cnt = 0; sys_dir = opendir(dir_name); if (!sys_dir) return 0; while ((sys_elem = readdir(sys_dir)) != 0){ if (sys_elem->d_type == DT_REG){ curr = (struct dir_instance_t*)malloc(sizeof(struct dir_instance_t)); if(curr == 0){ print_error("alloc memory fail\\n"); goto backoff; } sprintf(curr->filename, "%s%s", dir_name, sys_elem->d_name); curr->next = 0; if (filename_parse(sys_elem->d_name, curr)){ free(curr); continue; } cnt++; work_idx = curr->blockid % MAX_THREAD_PER_INST; pthread_mutex_lock(&inst->work_thread_lock[work_idx]); curr->next = inst->work_dir_head[work_idx]; inst->work_dir_head[work_idx] = curr; pthread_mutex_unlock(&inst->work_thread_lock[work_idx]); i++; if(i >= 2048) break; } } backoff: closedir(sys_dir); return 0; } void * do_dir_handler(void * arg) { struct config_instance_t * inst = (struct config_instance_t *)arg; char send_dir[512] = ""; uint64_t file_id = inst->fileid; int last_handle_time; int curr_handle_time; int i; int need_wait; signal(SIGPIPE,SIG_IGN); sprintf(send_dir, "%s/send/%llu/", sync_work_dir, file_id); if (access(send_dir, F_OK)) mkdir(send_dir, 0777); last_handle_time = get_current_seconds(); while(1){ curr_handle_time = get_current_seconds(); if((curr_handle_time - last_handle_time) < sync_period){ usleep(10000); continue; } last_handle_time = get_current_seconds(); load_dir(inst , send_dir); for(i = 0 ; i < MAX_THREAD_PER_INST ; i++) pthread_cond_signal(&inst->work_thread_wait[i]); need_wait = 0; while(1){ for(i = 0 ; i < MAX_THREAD_PER_INST ; i++){ pthread_mutex_lock(&inst->work_thread_lock[i]); if(inst->work_dir_head[i] != 0) need_wait = 1; pthread_mutex_unlock(&inst->work_thread_lock[i]); } if(need_wait == 0) break; usleep(1000); need_wait = 0; } } return 0; }
1
#include <pthread.h> struct queueNode { int key; struct queueNode *next; }; struct queueHeader { struct queueNode *head; struct queueNode *tail; }; void *hwthread(void *arg); void enqueue(struct queueHeader *qh, int key); int* dequeue(struct queueHeader *qh); int isEmpty(struct queueHeader *qh); struct queueHeader Qheader = {0,}; pthread_mutex_t lock; int main(int argc, char* argv[]) { struct timeval te; long long milliseconds; int thread_size = atoi(argv[1]), i = 0; pthread_t *p = (pthread_t *) malloc (sizeof(pthread_t) * thread_size); gettimeofday(&te, 0); milliseconds = clock(); printf("%lld start\\n", milliseconds); pthread_mutex_init(&lock, 0); for (i = 0; i < thread_size; i++) pthread_create(&p[i], 0, hwthread, 0); for (i = 0; i < thread_size; i++) pthread_join(p[i], 0); if(!isEmpty(&Qheader)) printf(" Q isn't empty\\n"); gettimeofday(&te, 0); milliseconds = clock(); printf("%lld end\\n", milliseconds); return 0; } void *hwthread(void *arg) { int i = 0; int *key = 0; for (i = 0; i<1000000;i++){ enqueue(&Qheader, i); key = dequeue(&Qheader); if (key) free(key); else printf("queue empty"); } } void enqueue(struct queueHeader *qh, int key) { struct queueNode *newNode = (struct queueNode *)malloc(sizeof(struct queueNode)); pthread_mutex_lock(&lock); newNode->key = key; newNode->next = 0; if (!qh->head) qh->head = newNode; else qh->tail->next = newNode; qh->tail = newNode; pthread_mutex_unlock(&lock); } int* dequeue(struct queueHeader *qh) { pthread_mutex_lock(&lock); if (qh->head) { int *returnval = (int *)malloc(sizeof(int)); struct queueNode *delNode = qh->head; *returnval = qh->head->key; if (qh->head == qh->tail) qh->tail = 0; qh->head = qh->head->next; delNode->next = 0; free(delNode); pthread_mutex_unlock(&lock); return returnval; } else { pthread_mutex_unlock(&lock); return 0; } } int isEmpty(struct queueHeader *qh) { if (!qh->head && !qh->tail) return 1; else return 0; }
0
#include <pthread.h> int stoj = 0, slachticiCount = 0, poddaniCount = 0; int cakajuciSlachtici = 0, slachticiVnutri = 0, poddaniVnutri = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condPoddani = PTHREAD_COND_INITIALIZER; pthread_cond_t condSlachtici = PTHREAD_COND_INITIALIZER; void klananie(void) { sleep(1); } void prestavka(void) { sleep(4); } void *slachtic( void *ptr ) { while(!stoj) { pthread_mutex_lock(&mutex); cakajuciSlachtici++; printf("SLA: cakam na klananie | cakajuci slachtici: %d\\n", cakajuciSlachtici); while(slachticiVnutri == 2 || poddaniVnutri > 1){ if(stoj){ pthread_mutex_unlock(&mutex); return 0; } pthread_cond_wait(&condSlachtici, &mutex); } cakajuciSlachtici--; slachticiVnutri++; printf("SLA: Idem sa klanat | vnutri slachticov: %d\\n", slachticiVnutri); pthread_mutex_unlock(&mutex); klananie(); pthread_mutex_lock(&mutex); slachticiVnutri--; slachticiCount++; printf("SLA: Odchadzam | poklony celkovo: %d\\n", slachticiCount); if(cakajuciSlachtici > 0){ pthread_cond_broadcast(&condSlachtici); } else if(cakajuciSlachtici == 0){ pthread_cond_broadcast(&condPoddani); } pthread_mutex_unlock(&mutex); prestavka(); } return 0; } void *poddany( void *ptr ) { while(!stoj) { pthread_mutex_lock(&mutex); while(cakajuciSlachtici > 0 || slachticiVnutri > 0){ if(stoj){ pthread_mutex_unlock(&mutex); return 0; } pthread_cond_wait(&condPoddani, &mutex); } poddaniVnutri++; printf("POD: Idem sa klanat | vnutri poddanych: %d\\n", poddaniVnutri); pthread_mutex_unlock(&mutex); klananie(); pthread_mutex_lock(&mutex); poddaniVnutri--; poddaniCount++; printf("POD: Odchadzam | poklony celkovo: %d\\n", poddaniCount); if(poddaniVnutri == 0 && cakajuciSlachtici == 0){ pthread_cond_broadcast(&condPoddani); } pthread_mutex_unlock(&mutex); prestavka(); } return 0; } int main(void) { int i; pthread_t slachtici[4]; pthread_t poddani[10]; for (i=0;i<4;i++) pthread_create( &slachtici[i], 0, &slachtic, 0); for (i=0;i<10;i++) pthread_create( &poddani[i], 0, &poddany, 0); sleep(30); pthread_mutex_lock(&mutex); printf("Koniec simulacie !!! \\n"); stoj = 1; pthread_cond_broadcast(&condSlachtici); pthread_cond_broadcast(&condPoddani); pthread_mutex_unlock(&mutex); for (i=0;i<4;i++) pthread_join( slachtici[i], 0); for (i=0;i<10;i++) pthread_join( poddani[i], 0); printf("Poddani: %d klanani\\n", poddaniCount); printf("Slachtici: %d klanani\\n", slachticiCount); exit(0); }
1
#include <pthread.h> int G_CHUNK_SIZE; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; large_uint G_current_start; large_uint G_subset_count; int G_terminated_flag; large_uint G_steps; void increment_step() { pthread_mutex_lock(&mutex); G_steps++; pthread_mutex_unlock(&mutex); } struct solution { large_int* subset; int size; }; large_uint get_next_start() { pthread_mutex_lock(&mutex); large_uint start = G_current_start; G_current_start = start + G_CHUNK_SIZE; pthread_mutex_unlock(&mutex); return start; } void print_set(large_int* set, int size, FILE* out) { int i; fprintf(out, "{"); for (i = 0; i < size; i++) { if (i > 0) { fprintf(out, ", "); } fprintf(out, "%lld", set[i]); } fprintf(out, "}\\n"); } large_int* generate_subset(large_int* set, large_uint elements, int* subset_size) { large_uint max_elements = round(log(elements) / log(2)) + 1; large_int* subset = malloc(sizeof(large_int) * max_elements); int i; int current_index = 0; for (i = 0; i < max_elements; i++) { large_uint val = (elements >> i) & 1; if (val == 1) { subset[current_index] = set[i]; current_index++; } } *subset_size = current_index; return subset; } large_int calculate_set_sum(large_int* set, int size) { large_int sum = 0; int i; for (i = 0; i < size; i++) { sum += set[i]; } return sum; } void* find_zero_subset(void* data) { large_int* set = (large_int*) data; while (1) { large_uint start = get_next_start(); large_uint i; for (i = start; i < start + G_CHUNK_SIZE; i++) { if (i >= G_subset_count || G_terminated_flag == 1) { return 0; } int size; large_int* subset = generate_subset(set, i, &size); large_int sum = calculate_set_sum(subset, size); if (sum == 0) { struct solution* sol = (struct solution*) malloc(sizeof(struct solution)); sol->subset = subset; sol->size = size; printf("Solution found!\\n"); pthread_mutex_lock(&mutex); G_terminated_flag = 1; pthread_mutex_unlock(&mutex); return ((void*) sol); } free(subset); } } return 0; } large_int* generate_set(unsigned int set_size, large_int range) { int i; large_int* set = malloc(sizeof(large_int) * set_size); for (i = 0; i < set_size; i++) { double val = (((double) pcg32_boundedrand(range)) / (range / 2.0)) - 1; large_int value = val * range; set[i] = value; } return set; } void test_multithread(FILE* file, int num_threads, int set_size, large_int range, int chunk_size) { G_CHUNK_SIZE = chunk_size; pthread_t threads[num_threads]; clock_t start = clock(); large_int* set = generate_set(set_size, range); G_subset_count = round(pow(2, set_size)); G_current_start = 1; G_terminated_flag = 0; G_steps = 0; int i; for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], 0, find_zero_subset, (void*) set); } struct solution* sol = 0; for (i = 0; i < num_threads; i++) { void* ret; pthread_join(threads[i], &ret); if (ret != 0) { printf("Thread %d found a solution!\\n", i); sol = ret; } else { printf("Thread %d was not able to find a solution.\\n", i); } } clock_t end = clock(); double delta = (((double) (end - start)) / CLOCKS_PER_SEC); printf("%.5f\\n", delta); printf("Joined with result %x and %d executions\\n", sol, G_steps); if (sol != 0) { print_set(sol->subset, sol->size, stdout); free(sol); } fprintf(file, "%d,%d,%d,%.6f\\n", G_CHUNK_SIZE, num_threads, set_size, delta); fflush(file); } void test_single(FILE* file, int set_size, large_int range) { G_CHUNK_SIZE = 32767; clock_t start = clock(); large_int* set = generate_set(set_size, range); G_subset_count = round(pow(2, set_size)); G_current_start = 1; G_terminated_flag = 0; G_steps = 0; struct solution* sol = find_zero_subset((void*) set); if (sol != 0) { print_set(sol->subset, sol->size, stdout); free(sol); } clock_t end = clock(); double delta = (((double) (end - start)) / CLOCKS_PER_SEC); fprintf(file, "%d,%.6f\\n", set_size, delta); fflush(file); } int main(int argc, char** argv) { int rounds = atoi(argv[0]); pcg32_srandom(time(0), (intptr_t) &rounds); FILE* file = fopen("out_multi_100.csv", "w"); fprintf(file, "chunk,threads,setsize,time\\n"); int ch, th, k, it; for (ch = 1; ch < 3; ch++) { for (th = 0; th < 2; th++) { for (k = 0; k < 13; k++) { for (it = 0; it < 100; it++) { int chunk = round(pow(10, (ch + 1))); int num_threads = (th + 1) * 2; int set_size = (k + 1) * 4; large_int range = round(pow(2, set_size / 2)); printf("k = %d, it = %d\\n", k, it); test_multithread(file, num_threads, set_size, range, chunk); } } } } return 0; }
0
#include <pthread.h> int thread_count; int message; int consumeOK; void *Consumer(void* rank); void *Producer(); int count; pthread_mutex_t mutex; pthread_cond_t cv; int r; int main(int argc, char* argv[]){ long thread; pthread_t idp; pthread_t* thread_handles; srand(time(0)); int i = 0; for(i = 0; i < 10; i++){ consumeOK = 0; r = rand(); printf("loop %d ----------------\\n", i); count = 0; thread_count = strtol(argv[1], 0, 10); thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cv, 0); for(thread = 0; thread<thread_count; thread++){ pthread_create(&thread_handles[thread], 0, Consumer, (void*) thread); if(thread == r%thread_count) pthread_create(&idp, 0, Producer, 0); } for(thread=0; thread<thread_count; thread++) pthread_join(thread_handles[thread], 0); free(thread_handles); } return 0; } void *Producer(){ pthread_mutex_lock(&mutex); printf("I AM THE PRODUCER\\n"); message = r; consumeOK = 1; while(count < thread_count){ pthread_cond_wait(&cv, &mutex); } pthread_mutex_unlock(&mutex); return 0; } void *Consumer(void* rank){ while(consumeOK != 1){ 0; } long my_rank = (long) rank; count++; if(count == thread_count) pthread_cond_signal(&cv); printf("%ld has received message %d\\n", my_rank, message); return 0; }
1
#include <pthread.h> struct RwLock { int nreaders; pthread_mutex_t rw_mutex; pthread_cond_t rw_cond; }; void initRwLock(struct RwLock *rwp) { rwp->nreaders = 0; pthread_mutex_init(&rwp->rw_mutex, 0); pthread_cond_init(&rwp->rw_cond, 0); } void getReadLock(struct RwLock *rwp) { pthread_mutex_lock(&rwp->rw_mutex); while(-1 == rwp->nreaders) { pthread_cond_wait(&rwp->rw_cond, &rwp->rw_mutex); } rwp->nreaders++; pthread_mutex_unlock(&rwp->rw_mutex); } void getWriteLock(struct RwLock *rwp) { pthread_mutex_lock(&rwp->rw_mutex); while(0 != rwp->nreaders) { pthread_cond_wait(&rwp->rw_cond, &rwp->rw_mutex); } rwp->nreaders = -1; pthread_mutex_unlock(&rwp->rw_mutex); } void unLock(struct RwLock *rwp) { pthread_mutex_lock(&rwp->rw_mutex); if( rwp->nreaders > 0) { rwp->nreaders--; if(rwp->nreaders == 0) { pthread_cond_broadcast(&rwp->rw_cond); } } else if(rwp->nreaders == -1) { rwp->nreaders = 0; pthread_cond_broadcast(&rwp->rw_cond); } pthread_mutex_unlock(&rwp->rw_mutex); } void destroyRwLock(struct RwLock *rwp) { pthread_mutex_destroy(&rwp->rw_mutex); pthread_cond_destroy(&rwp->rw_cond); } struct RwLock rwlock; void* reader(void* arg) { printf("Obtaining read lock.\\n"); getReadLock(&rwlock); printf("Obtained read lock.\\n"); sleep(5); printf("Releasing read lock.\\n"); unLock(&rwlock); printf("Released read lock.\\n"); } void* writer(void* arg) { printf("Obtaining write lock.\\n"); getWriteLock(&rwlock); printf("Obtained write lock.\\n"); sleep(4); printf("Releasing write lock.\\n"); unLock(&rwlock); printf("Released write lock.\\n"); } int main(int argc, char** argv) { pthread_t r1,r2,r3,w1,w2; int res; res = pthread_create(&r1, 0, reader, 0); if(0 != res) { printf("Failed to start thread.\\n"); exit(1); } res = pthread_create(&r2, 0, reader, 0); if(0 != res) { printf("Failed to start thread.\\n"); exit(1); } sleep(1); res = pthread_create(&w1, 0, writer, 0); if(0 != res) { printf("Failed to start thread.\\n"); exit(1); } res = pthread_create(&w2, 0, writer, 0); if(0 != res) { printf("Failed to start thread.\\n"); exit(1); } pthread_exit(0); }
0
#include <pthread.h> int BUFFER_SIZE = 10; int THREAD_COUNT = 6; int NUM_PRODUCERS = 2; int NUM_CONSUMERS = 2; int MAX_ITEMS = 20; int * buffer; int buffer_index; pthread_mutex_t buffer_mutex; sem_t full_semaphore; sem_t empty_semaphore; void buffer_insert(int num){ if(buffer_index < BUFFER_SIZE) { buffer[buffer_index++] = num; } } int buffer_remove(){ if(buffer_index > 0){ return buffer[--buffer_index]; } return 0; } void *producer(void *thread) { int number; int count = 0; int thread_id = *(int *)thread; while(count++ < NUM_PRODUCERS){ sleep(rand() % 10); number = rand() % 100; sem_wait(&full_semaphore); pthread_mutex_lock(&buffer_mutex); buffer_insert(number); pthread_mutex_unlock(&buffer_mutex); sem_post(&empty_semaphore); printf("Producer %d produced item %d on buffer %d", thread_id, number, count); } pthread_exit(0); } void *consumer(void *thread){ int number; int count = 0; int thread_id = *(int *)thread; while(count++ < NUM_CONSUMERS){ sem_wait(&empty_semaphore); pthread_mutex_lock(&buffer_mutex); number = buffer_remove(number); pthread_mutex_unlock(&buffer_mutex); sem_post(&full_semaphore); printf("Consumer %d consumed item %d on buffer %d", thread_id, number, count); } pthread_exit(0); } int main(int argc, char *argv[]) { if(argc >1){ BUFFER_SIZE = (int) argv[1]; NUM_PRODUCERS = (int) argv[2]; NUM_CONSUMERS = (int) argv[3]; MAX_ITEMS = (int) argv[4]; } int array[BUFFER_SIZE]; buffer = array; buffer_index = 0; pthread_mutex_init(&buffer_mutex, 0); sem_init(&full_semaphore,0,BUFFER_SIZE); sem_init(&empty_semaphore,0,0); pthread_t thread[THREAD_COUNT]; int thread_id[THREAD_COUNT]; for( int i = 0; i < THREAD_COUNT; i++){ thread[i] = i; pthread_create(thread + i, 0, producer, thread_id + i); thread_id[i] = i; pthread_create(&thread[i], 0, consumer, &thread_id[i]); } for(int j = 0; j < THREAD_COUNT; j++){ pthread_join(thread[j], 0); } pthread_mutex_destroy(&buffer_mutex); sem_destroy(&full_semaphore); sem_destroy(&empty_semaphore); return 0; }
1
#include <pthread.h> static struct { int flags; int state; struct { int flag; int sock; int time; } items[8]; pthread_t thrd; pthread_mutex_t lock; } _nexusio_mftp_watch_dog_zone; void * _nexusio_mftp_watch_dog_thrd_func(void *argp) { int f; int i; void *p ; p = argp; for(f = 0; f < 1;) { usleep(750000); pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); for(i = 0; i < 8; i ++) { if(_nexusio_mftp_watch_dog_zone.items[i].flag < 0) continue; if(_nexusio_mftp_watch_dog_zone.items[i].sock < 0) continue; if(_nexusio_mftp_watch_dog_zone.items[i].time < 9) { _nexusio_mftp_watch_dog_zone.items[i].time ++; } else if(_nexusio_mftp_watch_dog_zone.items[i].flag < 1) { nexusio_mftp_tcp_ctrl_null(_nexusio_mftp_watch_dog_zone.items[i].sock); _nexusio_mftp_watch_dog_zone.items[i].time = 0; } else { } } f = _nexusio_mftp_watch_dog_zone.flags; pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); }; return 0; } int nexusio_mftp_watch_dog_start_thread(void) { int i; pthread_attr_t attr; for(i = 0; i < 8; i ++) { _nexusio_mftp_watch_dog_zone.items[i].flag = -1; _nexusio_mftp_watch_dog_zone.items[i].sock = -1; _nexusio_mftp_watch_dog_zone.items[i].time = 0; } _nexusio_mftp_watch_dog_zone.flags = 0; _nexusio_mftp_watch_dog_zone.state = 1; pthread_mutex_init(&_nexusio_mftp_watch_dog_zone.lock, 0); pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); pthread_create(&_nexusio_mftp_watch_dog_zone.thrd, &attr, _nexusio_mftp_watch_dog_thrd_func, 0); pthread_attr_destroy (&attr); return 1 ; } int nexusio_mftp_watch_dog_close_thread(void) { pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); _nexusio_mftp_watch_dog_zone.flags = 1; pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); pthread_join(_nexusio_mftp_watch_dog_zone.thrd, 0); return(1); } int nexusio_mftp_watch_dog_alloc(int s) { int i; pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); for(i = 7; i >= 0; i --) { if(_nexusio_mftp_watch_dog_zone.items[i].flag < 0) { _nexusio_mftp_watch_dog_zone.items[i].sock = s; _nexusio_mftp_watch_dog_zone.items[i].flag = 0; _nexusio_mftp_watch_dog_zone.items[i].time = 0; break; } } pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); return i; } int nexusio_mftp_watch_dog_enter(int n) { if(n >= 0 && n <= 7) { pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); _nexusio_mftp_watch_dog_zone.items[n].flag = 1; _nexusio_mftp_watch_dog_zone.items[n].time = 0; pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); return 1; } return 0; } int nexusio_mftp_watch_dog_leave(int n) { if(n >= 0 && n <= 7) { pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); _nexusio_mftp_watch_dog_zone.items[n].flag = 0; _nexusio_mftp_watch_dog_zone.items[n].time = 0; pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); return 1; } return 0; } int nexusio_mftp_watch_dog_clean(int n) { if(n >= 0 && n <= 7) { pthread_mutex_lock(&_nexusio_mftp_watch_dog_zone.lock); _nexusio_mftp_watch_dog_zone.items[n].sock = -1; _nexusio_mftp_watch_dog_zone.items[n].flag = -1; _nexusio_mftp_watch_dog_zone.items[n].time = 0; pthread_mutex_unlock(&_nexusio_mftp_watch_dog_zone.lock); return 1; } return 0; }
0
#include <pthread.h> unsigned long totalhits; pthread_mutex_t hits_lock; void *calc_hits(int *mynum) { unsigned long localhits=0,myiter; int i; double dx, dy; short state[3]; long myseed; struct timeval now; gettimeofday(&now, 0); myseed=((long) now.tv_sec)*(*mynum + 1); state[0]=(short) myseed; state[1]=(short) myseed>>16; state[2]=(short) myseed<<3; myiter = (unsigned long) 10000000/8; if (*mynum < 10000000%8) myiter++; for (i=0; i<myiter; i++) { dx = erand48(state); dy = erand48(state); if ( (dx*dx + dy*dy) < 1) localhits++; } pthread_mutex_lock(&hits_lock); totalhits += localhits; pthread_mutex_unlock(&hits_lock); pthread_exit(0); } int main(int argc, char** argv) { int j; double Pi; pthread_t threads[8]; int tnum[8]; pthread_mutex_init(&hits_lock,0); for (j=0;j<8;j++){ tnum[j] = j; pthread_create(&(threads[j]), 0, calc_hits, &tnum[j]); } for(j=0;j<8;j++){ pthread_join(threads[j], 0); } Pi = 4.0f * totalhits/10000000; printf("Pi is approximately %.8g.\\n", Pi); return 0; }
1
#include <pthread.h> const int NUM_THREADS = 100; pthread_mutex_t mutex; { int *count; } arg_struct; void *countThread(void *arg) { int *count = ((arg_struct *) arg)->count; int i; for(i=0; i<1000; i++) { pthread_mutex_lock(&mutex); (*count)++; pthread_mutex_unlock(&mutex); } Pthread_exit(0); } int main() { volatile int count = 0; pthread_t tid[NUM_THREADS]; arg_struct thread_args; thread_args.count = &count; int i, j; clock_t start, end; double total, average = 0; pthread_mutex_init (&mutex, 0); printf("Mutex inside loop runs:\\n\\n"); for(j=0; j<10; j++) { count = 0; start = clock(); for(i=0; i<NUM_THREADS; i++) { Pthread_create(&tid[i], 0, countThread, &thread_args); } for(i=0; i<NUM_THREADS; i++) { Pthread_join(tid[i], 0); } end = clock(); total = (double)(end-start)/CLOCKS_PER_SEC; average += total; printf("final count = %d\\n", count); printf("time taken = %f\\n\\n", total); } average = average/10; printf("average time per run = %f\\n\\n", average); pthread_mutex_destroy(&mutex); Pthread_exit(0); }
0
#include <pthread.h> pthread_t tids[10]; int cherries[10]; int all_cherries; pthread_mutex_t mutex; void *ThreadAdd(void * a) { int index = (int)a; int i,j,y; y = 0; for(i = 0; i < 100000; i++) { cherries[index]++; while (pthread_mutex_trylock(&mutex) != 0) { y++; sched_yield(); } all_cherries++; printf("Thread-ID: %d yield: %d\\n", index, y); pthread_mutex_unlock (&mutex); } } int main(int argc, char * argv[]) { long sum_cherries = 0; int i; pthread_mutex_init (&mutex, 0); for ( i = 0; i < 10; i++ ) { if (pthread_create(&(tids[i]), 0, ThreadAdd, (void*)i)) { printf("\\n ERROR creating thread 1"); exit(1); } } for ( i = 0; i < 10; i++ ) { if (pthread_join(tids[i], 0)) { printf("\\n ERROR joining thread"); exit(1); } else { sum_cherries += cherries[i]; printf("%d ",cherries[i]); } } printf("MUST: %d ALL: %d\\n",100000*10,all_cherries); pthread_exit(0); }
1
#include <pthread.h> uint32_t id; uint32_t op; uint8_t *data; uint32_t leng; struct _qentry *next; } qentry; qentry *head,**tail; void *semfree,*semfull; pthread_mutex_t lock; } queue; void* queue_new(uint32_t size) { queue *q; q = (queue*)malloc(sizeof(queue)); q->head = 0; q->tail = &(q->head); if (size==0) { q->semfull = 0; } else { q->semfull = sem_new(size); } q->semfree = sem_new(0); pthread_mutex_init(&(q->lock),0); return q; } void queue_delete(void *que) { queue *q = (queue*)que; qentry *qe,*qen; for (qe = q->head ; qe ; qe = qen) { qen = qe->next; free(qe->data); free(qe); } sem_delete(q->semfree); if (q->semfull) { sem_delete(q->semfull); } pthread_mutex_destroy(&(q->lock)); free(q); } int queue_isempty(void *que) { queue *q = (queue*)que; return (sem_getresamount(q->semfree)==0); } uint32_t queue_elements(void *que) { queue *q = (queue*)que; return sem_getresamount(q->semfree); } int queue_isfull(void *que) { queue *q = (queue*)que; if (q->semfull) { return (sem_getresamount(q->semfull)==0); } return 0; } uint32_t queue_sizeleft(void *que) { queue *q = (queue*)que; if (q->semfull) { return sem_getresamount(q->semfull); } return 0xFFFFFFFF; } void queue_put(void *que,uint32_t id,uint32_t op,uint8_t *data,uint32_t leng) { queue *q = (queue*)que; qentry *qe; qe = malloc(sizeof(qentry)); qe->id = id; qe->op = op; qe->data = data; qe->leng = leng; qe->next = 0; if (q->semfull) { sem_acquire(q->semfull,leng); } pthread_mutex_lock(&(q->lock)); *(q->tail) = qe; q->tail = &(qe->next); pthread_mutex_unlock(&(q->lock)); sem_release(q->semfree,1); } int queue_tryput(void *que,uint32_t id,uint32_t op,uint8_t *data,uint32_t leng) { queue *q = (queue*)que; qentry *qe; if (q->semfull && sem_tryacquire(q->semfull,leng)<0) { return -1; } qe = malloc(sizeof(qentry)); qe->id = id; qe->op = op; qe->data = data; qe->leng = leng; qe->next = 0; pthread_mutex_lock(&(q->lock)); *(q->tail) = qe; q->tail = &(qe->next); pthread_mutex_unlock(&(q->lock)); sem_release(q->semfree,1); return 0; } void queue_get(void *que,uint32_t *id,uint32_t *op,uint8_t **data,uint32_t *leng) { queue *q = (queue*)que; qentry *qe; sem_acquire(q->semfree,1); pthread_mutex_lock(&(q->lock)); qe = q->head; q->head = qe->next; if (q->head==0) { q->tail = &(q->head); } pthread_mutex_unlock(&(q->lock)); if (q->semfull) { sem_release(q->semfull,qe->leng); } if (id) { *id = qe->id; } if (op) { *op = qe->op; } if (data) { *data = qe->data; } if (leng) { *leng = qe->leng; } free(qe); } int queue_tryget(void *que,uint32_t *id,uint32_t *op,uint8_t **data,uint32_t *leng) { queue *q = (queue*)que; qentry *qe; if (sem_tryacquire(q->semfree,1)<0) { if (id) { *id=0; } if (op) { *op=0; } if (data) { *data=0; } if (leng) { *leng=0; } return -1; } pthread_mutex_lock(&(q->lock)); qe = q->head; q->head = qe->next; if (q->head==0) { q->tail = &(q->head); } pthread_mutex_unlock(&(q->lock)); if (q->semfull) { sem_release(q->semfull,qe->leng); } if (id) { *id = qe->id; } if (op) { *op = qe->op; } if (data) { *data = qe->data; } if (leng) { *leng = qe->leng; } free(qe); return 0; }
0