text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static pthread_mutex_t sync_lock = PTHREAD_MUTEX_INITIALIZER; void mos_atomic_add_32(uint32_t *dst, int32_t delta) { pthread_mutex_lock(&sync_lock); *dst += delta; pthread_mutex_unlock(&sync_lock); } uint32_t mos_atomic_add_32_nv(uint32_t *dst, int32_t delta) { uint32_t res; pthread_mutex_lock(&sync_lock); res = *dst + delta; *dst = res; pthread_mutex_unlock(&sync_lock); return (res); } void mos_atomic_add_64(uint64_t *dst, int64_t delta) { pthread_mutex_lock(&sync_lock); *dst += delta; pthread_mutex_unlock(&sync_lock); } uint64_t mos_atomic_add_64_nv(uint64_t *dst, int64_t delta) { uint64_t res; pthread_mutex_lock(&sync_lock); res = *dst + delta; *dst = res; pthread_mutex_unlock(&sync_lock); return (res); } uint32_t mos_atomic_get_32(uint32_t *dst) { uint32_t res; pthread_mutex_lock(&sync_lock); res = *dst; pthread_mutex_unlock(&sync_lock); return (res); } uint64_t mos_atomic_get_64(uint64_t *dst) { uint64_t res; pthread_mutex_lock(&sync_lock); res = *dst; pthread_mutex_unlock(&sync_lock); return (res); } uint32_t mos_atomic_swap_32(uint32_t *dst, uint32_t nv) { uint32_t ov; pthread_mutex_lock(&sync_lock); ov = *dst; *dst = nv; pthread_mutex_unlock(&sync_lock); return (ov); } uint64_t mos_atomic_swap_64(uint64_t *dst, uint64_t nv) { uint64_t ov; pthread_mutex_lock(&sync_lock); ov = *dst; *dst = nv; pthread_mutex_unlock(&sync_lock); return (ov); } void _mos_atomic_init(void) { }
1
#include <pthread.h> int max(int a, int b){ return ((a > b) ? a : b); } struct header { unsigned short free; struct header *next; }; static const short W_SIZE = (sizeof (void *)); static const short H_SIZE = (sizeof (struct header)); static struct header *start = 0; static long heap_size = 0; static pthread_mutex_t lock; void *mymalloc(unsigned int size) { pthread_mutex_lock(&lock); if (start == 0){ void * ret = sbrk(size + 3*H_SIZE); if (ret == (void *)(-1)) return 0; start = ret; heap_size = size + H_SIZE; start -> free = 1; struct header * temp = (struct header * )(((char *) ret) + size + 2*H_SIZE); temp -> free = 2; temp -> next = temp; start -> next = temp; ret = (void *) (start + 1); pthread_mutex_unlock(&lock); return ret; } struct header * temp = start; while (temp != temp->next){ if (temp ->free == 0){ ptrdiff_t freeSpace = temp->next - temp; freeSpace = freeSpace*H_SIZE; if (freeSpace > size + H_SIZE){ temp->free = 1; void * ret = (void *)(temp + 1); pthread_mutex_unlock(&lock); return ret; } } temp = temp->next; } void * ret = sbrk(max(size + 3*H_SIZE, 4096)); if (ret == (void *)(-1)) return 0; temp ->free = 1; temp-> next = sbrk(0)-H_SIZE; ret = temp + 1; temp = temp -> next; temp->free = 2; temp->next = temp; pthread_mutex_unlock(&lock); return ret; } unsigned int myfree(void *ptr) { struct header * temp = ptr; temp = temp - 1; temp -> free = 0; return 0; }
0
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if (res != 0) { perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if (res != 0) { perror("Thread creation failed"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit) { fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1) { pthread_mutex_lock(&work_mutex); if (work_area[0] != '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); } else { break; } } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("You input %d characters\\n", strlen(work_area) -1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while (work_area[0] == '\\0' ) { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; int i = 0; void* someThreadFunction1(){ for(int a = 0; a < 1000000; a++){ pthread_mutex_lock(&mutex); i++; pthread_mutex_unlock(&mutex); } return 0; } void* someThreadFunction2(){ for(int a = 0; a < 999999; a++){ pthread_mutex_lock(&mutex); i--; pthread_mutex_unlock(&mutex); } return 0; } int main(){ clock_t start = clock(), diff; pthread_t someThread1; pthread_t someThread2; pthread_create(&someThread1, 0, someThreadFunction1, 0); pthread_create(&someThread2, 0, someThreadFunction2, 0); pthread_join(someThread1, 0); pthread_join(someThread2, 0); printf("%d\\n",i); diff = clock() - start; int msec = diff * 1000 / CLOCKS_PER_SEC; printf("Time taken %d seconds %d milliseconds \\n", msec/1000, msec%1000); return 0; }
0
#include <pthread.h> char *read_text; pthread_mutex_t mutex_lock; int result_counter = 0; void *write_read_text(void *YouCantWorkWithoutME){ int write_status = 1; int is_end = 0; while(is_end != 1){ pthread_mutex_lock(&mutex_lock); printf("xaxa"); write_status = write(STDOUT_FILENO,read_text,strlen(read_text)); if(read_text[strlen(read_text)] == '\\0'){ is_end = 1; free(read_text); } result_counter = 0; pthread_mutex_unlock(&mutex_lock); } pthread_exit(0); } void *read_file(void *file_name){ int fd = open((char*)file_name,O_RDONLY); if(fd < 0){ perror("Open Problem"); pthread_exit((void *)-1); } int read_status = 1; read_text = (char *)malloc(sizeof(char)); int buffer_size = 20; char *buffer = (char *)malloc(buffer_size*sizeof(char)); while(read_status != 0){ read_status = read(fd,buffer,buffer_size); if(read_status < 0){ perror("Read Problem"); pthread_exit((void *) -2); }else{ pthread_mutex_lock(&mutex_lock); int i; for(i = 0; i < read_status; i++){ read_text = (char *)realloc(read_text,(result_counter+(i+1))*sizeof(char)); read_text[result_counter+i] = buffer[i]; } result_counter += buffer_size; pthread_mutex_unlock(&mutex_lock); } } pthread_exit(0); } int main(int argc,char* argv[]){ int i; pthread_t thread_id[2]; pthread_create(thread_id,0,read_file,(void *)argv[1]); pthread_create(thread_id,0,write_read_text,0); pthread_join(thread_id[0],0); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; char *test ="send"; char *test2 ="."; char *test3= "Type the name of the file u want to receive\\n"; char *message= "Iste su extensions mozemo da nastavimo sa slanjem\\n"; char *message2= "reci kako oces da se zove file koji ti primas\\n"; char *end ="end of file"; void * chat(void * socket) { int sockfd, ret; char buffer[2000]; sockfd = (int) socket; pthread_t t; int new; memset(buffer, 0, 2000); printf("chat \\n"); while (1) { printf("we are in chat (receiving messages) \\n"); ret = recvfrom(sockfd, buffer, 2000, 0, 0, 0); if (ret < 0) { printf("Error receiving data!\\n"); } else { printf("server: "); fputs(buffer, stdout); printf("\\ndosli smo \\n"); printf("sta pise u bufferu %s \\n",buffer); printf("sta pise u test %s\\n",test); int rezultat=strcmp(buffer, test); printf("rezultat %d\\n",rezultat); if (rezultat==0){ printf("it worked oce da primi file\\n"); printf("izlazimo iz chat\\n"); *conformation(sockfd); } else{ printf("u didnt type it right u lemon \\n"); } } } } void *conformation (void * socket){ int sockfd, ret; char buffer[2000]; sockfd = (int) socket; printf("we made it conformation\\n"); ret = send(sockfd,test3,2000,0); if (ret < 0) { printf("Error sending data!\\n\\t-%s", test3); exit(1); } printf("sending server to tell him to type the name of the new file \\n"); *send_some_files(sockfd); } void *send_some_files(void * socket){ int sockfd, ret; char buffer[2000]; char buffer_test[2000]; char buffer_file[1400]; sockfd = (int) socket; struct sockaddr_in addr; FILE *filefd = 0; char test_buffer[2000]; double file_size; printf("usli smo u send_some_files \\n"); pthread_mutex_lock (&m); ret = recvfrom(sockfd, buffer, 2000, 0, 0, 0); printf("primio je ime file od servera\\n"); if (ret < 0) { printf("Error sending data!\\n\\t-%s", buffer); } printf("buffer %s\\n",buffer); strcat(buffer_test, buffer); printf("buffer_test %s\\n",buffer_test); filefd= fopen(buffer_test,"r"); fgets(test_buffer, 1000, filefd); printf("\\n%s\\n",test_buffer); if (filefd == 0) { perror("open"); exit(1); } printf("we opened the file \\n"); printf("sending to server that we found the file\\n"); ret = send(sockfd,message2,2000,0); if(ret<0){ printf("Error sending data!\\n\\t-%s", message2); } fseek(filefd, 0, 2); file_size = ftell(filefd); fseek(filefd, 0, 0); ret = recv(sockfd,buffer,2000,0); printf("kako server oce da nazove file %s \\n",buffer); if(ret<0){ printf("Error sending data!\\n\\t-%s", buffer); } printf("da li je primio ime file %s\\n", buffer); char test2 ='.'; const char *buffer_const= (const char *) buffer; const char *buffer_test_c= (const char *)buffer_test; char *r; char *r2; r= strchr(buffer_test_c,'.'); r2= strchr(buffer_const,'.'); int compare; compare=strcmp(r,r2); printf("buffer_test: %s buffer: %s r:%s r2:%s \\n",buffer_test,buffer,r ,r2); if(compare!=0){ printf("the extensions arent the same we fucked up \\n"); printf("comparing %d ",compare); printf("return to begging of the program"); pthread_mutex_unlock(&m); chat(&sockfd); } memset(buffer_test,0,2000); printf("comparing %d \\n",compare); ret=send(sockfd,buffer,2000,0); ret= send(sockfd,message,2000,0); if(ret<0){ printf("Error sending data!\\n\\t-%s", message); } printf("file size is %f mb\\n",file_size/1000000); double packets = (file_size/1400 +1); int ipackets = (int)packets; printf("number of packets %d\\n",ipackets); int cpackets = htonl(packets); snprintf(buffer, 2000, "%d", ipackets); ret=0; printf("%s\\n",buffer); ret=send(sockfd,buffer,2000,0); printf("%s\\n",buffer); if(ret<0){ printf("Error sending data!\\n\\t-%s", buffer); } int count; while(1){ int nread =fread(buffer_file,1,1400,filefd); if(nread >0){ write(sockfd,buffer_file,nread); printf("nread %d\\n",nread); count++; } if(nread < 1400){ if(feof(filefd)){ printf("end of file \\n"); printf("the file was sent to %d\\n",sockfd); ret= send(sockfd,end,2000,0); if(ret<0){ printf("Error sending data!\\n\\t-%s", end); } } if (ferror(filefd)){ printf("Error reading\\n"); } pthread_mutex_unlock(&m); break; } } fclose(filefd); printf("Closing file\\n"); printf("%d",count); sleep(3); } void * chat2(void * socket){ int sockfd, ret; char buffer[2000]; sockfd = (int) socket; struct sockaddr_in addr; printf("we are in chat2,(sending messages) \\n"); while (fgets(buffer, 2000, stdin) != 0) { printf("YOU : %s",buffer); ret = send(sockfd,buffer,2000,0); if (ret < 0) { printf("Error sending data!\\n\\t-%s", buffer); } } }
0
#include <pthread.h> static int open_communication (void) { int soc; struct sockaddr_in addr; if ((soc = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0){ my_printf("%s: socket failed %s\\n", __FUNCTION__, strerror(errno)); return -1; } my_printf("%s: Socket created\\n", __FUNCTION__); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(listening_port); addr.sin_addr.s_addr = INADDR_ANY; if (bind(soc, (struct sockaddr *)&addr, sizeof(addr)) < 0){ my_printf("%s: bind failed %s\\n", __FUNCTION__, strerror(errno)); close(soc); return -1; } my_printf("%s: Socket bound to port %d\\n ", __FUNCTION__, listening_port); if (listen(soc, MAX_CLIENTS) < 0){ my_printf("%s: listen failed %s\\n", __FUNCTION__, strerror(errno)); close(soc); return -1; } my_printf("%s: Socket listened \\n ", __FUNCTION__); return soc; } static void to_sched_queue (struct job_details *job) { pthread_mutex_lock(&sched_mutex); my_printf("%s: queuing job %d\\n", __FUNCTION__, job->seqno); if (job_head1) { job->next1 = job_head1; job_head1->prev1 = job; } job_head1 = job; if (job_tail1 == 0) { job_tail1 = job; } sem_post(&sched_sem); pthread_cond_signal(&sched_cond_mutex); pthread_mutex_unlock(&sched_mutex); } void * queue_thread (void) { int ssoc, csoc; struct sockaddr_in caddr; int clen; struct job_details *job; char buffer[BUFFERSIZE], buflen; char method[BUFFERSIZE], uri[BUFFERSIZE], version[BUFFERSIZE]; char filename[BUFFERSIZE]; struct stat stat_buf; time_t curr_time; my_printf("%s: \\n", __FUNCTION__); if ((ssoc = open_communication()) < 0) { my_printf("%s: cannot open communication to clients\\n", __FUNCTION__); exit(1); } while (1) { my_printf("waiting to accept connections from client\\n"); clen = sizeof(caddr); memset((char *)&caddr, 0, sizeof(caddr)); csoc = accept(ssoc, (struct sockaddr *)&caddr, &clen); if (csoc < 0) { my_printf("%s: accept failed\\n", __FUNCTION__); continue; } my_printf("%s: got a request from client soc %d\\n", __FUNCTION__, csoc); if ((buflen = recv(csoc, buffer, BUFFERSIZE, 0)) < 0) { my_printf("%s: recv failed\\n", __FUNCTION__); close(csoc); continue; } my_printf("Req: %s\\n", buffer); if (strstr(buffer, "favicon.ico")) { my_printf("%s: bad request %s \\n", __FUNCTION__, method); close(csoc); continue; } sscanf(buffer, "%s %s %s", method, uri, version); if ((strcmp(version, "HTTP/1.0") != 0) && (strcmp(version, "HTTP/1.1") != 0)) { my_printf("%s: bad request %s \\n", __FUNCTION__, method); close(csoc); continue; } my_printf("%s: method '%s' uri '%s'\\n", __FUNCTION__, method, uri); if (strcmp(method, "GET") && strcmp(method, "HEAD")) { my_printf("%s: bad request %s \\n", __FUNCTION__, method); close(csoc); continue; } job = (struct job_details *)malloc(sizeof(struct job_details)); if (job == 0) { my_printf("%s: malloc failed\\n", __FUNCTION__); continue; } memset((char *)job, 0, sizeof(struct job_details)); if (uri[0] == '~') { char *s; s = strstr(uri, "/"); if (s) { *s = '\\0'; sprintf(filename, "/home/%s/myhttpd/%s", &uri[1], s+1); } else { sprintf(filename, "/home/%s/myhttpd/", &uri[1]); } sprintf(job->filename, "%s", filename); } else { strcpy(filename, uri); } sprintf(job->filename, "%s/%s", root_directory, filename); myhttpd_seqno += 1; job->seqno = myhttpd_seqno; curr_time = time(0); strftime(job->arrival_time, sizeof(job->arrival_time), "%d/%b/%Y:%H:%M:%S %z", gmtime(&curr_time)); strncpy(job->first_line, buffer, sizeof(job->first_line)); strcpy(job->remote_ip, inet_ntoa(caddr.sin_addr)); if (strstr(job->filename, ".jpg") || strstr(job->filename, ".gif") || strstr(job->filename, ".png")) { job->image = 1; } job->client_soc = csoc; memset((char *)&stat_buf, 0, sizeof(stat_buf)); my_printf("stat ing %s \\n", job->filename); stat(job->filename, &stat_buf); strftime(job->lastmodtime, sizeof(job->lastmodtime), "%a, %d %b %Y %H:%M:%S GMT", gmtime(&stat_buf.st_mtime)); if (S_ISREG(stat_buf.st_mode)) { job->response_size = stat_buf.st_size; job->content_type = CONTENT_FILE; } else if (S_ISDIR(stat_buf.st_mode)) { job->response_size = 0; job->content_type = CONTENT_DIR; } if (strcasecmp(method, "GET") == 0) { job->req_type = REQ_GET; } else if (strcasecmp(method, "HEAD") == 0) { job->response_size = 0; job->req_type = REQ_HEAD; } my_printf("%s: request from %s \\n", __FUNCTION__, job->remote_ip); to_sched_queue(job); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int count = 0; void* consume( void *arg) { while(1 ) { pthread_mutex_lock(&mutex ); printf("************************consumebegin lock\\n"); printf("************************consumed%d\\n",count ); sleep(2); count++; printf("************************consumed%d\\n",count); printf("************************consumeover lock\\n"); pthread_mutex_unlock(&mutex ); printf("************************I'mout of pthread_mutex\\n"); sleep(1); } } void* produce( void * arg ) { while(1 ) { pthread_mutex_lock(&mutex ); printf("productbegin lock\\n"); printf("Produced %d\\n", count ); printf("productover lock\\n"); pthread_mutex_unlock(&mutex ); printf("I'mout of pthread_mutex\\n"); sleep(1); } } int main(int argc, char*argv) { pthread_t thread1,thread2; pthread_create(&thread1, 0, &produce, 0 ); pthread_create(&thread2, 0, &consume, 0 ); pthread_join(thread1,0); pthread_join(thread2,0); return 0; }
0
#include <pthread.h> int min(int a, int b) { if(a > b) return b; else return a; } struct input { int num; int cT; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int divisor = 2; int curThread = 0; int timecount = 0; void *createThread(void *input) { struct input *in = input; int actual = in->cT; printf("Hello from thread No. %d!\\n", actual); pthread_t arr[in->num]; int tcount = 0; int maxThreads = in->num; struct input threads[maxThreads]; pthread_t p1, p2; int comp = min((int)floor(maxThreads/divisor), 16); while(tcount < maxThreads) { pthread_mutex_lock(&mutex); curThread++; struct input in; in.num = comp; printf("Debug\\n"); in.cT = curThread; threads[tcount] = in; pthread_create(&arr[tcount], 0, createThread, &threads[tcount]); pthread_mutex_unlock(&mutex); tcount++; } int i; for (i = 0; i < maxThreads; i++) pthread_join(arr[i], 0); printf("Bye from thread No. %d!\\n", actual); } int main() { struct input maxThreads; maxThreads.num = 26; maxThreads.cT = curThread; createThread(&maxThreads); printf("Insgesamt erzeugte Threads: %d\\n", curThread); }
1
#include <pthread.h> pthread_t *threads; pthread_mutex_t mutex; int threads_count, records_count, fd; char* word; void* thread_func(void *data){ pthread_t self; int read_count,i,j,record_id,actual_read_count,word_len; char *buf,*ptr; int k; buf=malloc(1024*records_count); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &i); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &i); word_len=strlen(word); self=pthread_self(); read_count=1; while(read_count){ pthread_mutex_lock(&mutex); read_count=read(fd,buf,1024*records_count); pthread_mutex_unlock(&mutex); actual_read_count=read_count/1024; ptr=buf; for(i=0;i<actual_read_count;i++){ record_id=atoi(ptr); for(j=5;j<1024 -word_len;j++){ if(word_eq(ptr+j,word_len)){ printf("Znaleziono, TID - %d, rekord - %d\\n",(unsigned int)self,record_id); for(k=0;k<threads_count;k++){ if(threads[k]!=self){ pthread_cancel(threads[k]); } } pthread_cancel(self); } } ptr+=1024; } } return 0; } bool word_eq(char* s, int word_len){ int i; char *w =word; if(!(s-1) || *(s-1)==' '){ for(i=0; i<word_len; i++){ if(s){ if(*w != *s){ return 0; } } w++; s++; } if(!(s) || *(s)==' ') return 1; } return 0; } void handler(int unused){ exit(0); } int main(int argc, char **argv){ char *file_name; int i; if(argc < 5){ printf("Needs four arguments\\n"); return -1; }else{ threads_count=atoi(argv[1]); file_name=argv[2]; records_count=atoi(argv[3]); word=argv[4]; } threads=malloc(sizeof(pthread_t)*threads_count); pthread_mutex_init(&mutex,0); fd=open(file_name,O_RDONLY); signal(SIGSEGV,handler); for(i=0; i < threads_count; i++){ pthread_create(threads+i,0,&thread_func,0); } for(i=0; i < threads_count; i++){ pthread_join(threads[i],0); } close(fd); pthread_mutex_destroy(&mutex); free(threads); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_x= PTHREAD_MUTEX_INITIALIZER; static char *pindex[10]; static int ind = 0; void initarray() { int i=0; pindex[0] = (char*)malloc(10*32); for(i=1;i<10;i++) pindex[i] = pindex[i-1]+32; for(i=0;i<10;i++) printf("%d=%p\\n",i,pindex[i]); return; } char * ma() { char *p=0; pthread_mutex_lock(&mutex_x); if((ind + 1) < 10) { p = pindex[ind++]; } pthread_mutex_unlock(&mutex_x); return p; } void fa(char *p) { pthread_mutex_lock(&mutex_x); printf("%s:%d,%p\\n",__func__,ind,p); pindex[--ind] = p; pthread_mutex_unlock(&mutex_x); return; } void *client(void *data) { int pid =(int ) data; char *p = 0; int s = 0; s = 1+(int)(10.0*rand()/(32767 +1.0)); printf("%02d,s1:%d\\n",pid,s); sleep(s); p = ma(); if(p != 0) { s = 1+(int)(10.0*rand()/(32767 +1.0)); printf("%02d,s2:%d,%p\\n",pid,s,p); sleep(s); fa(p); } return 0; } int main(void) { int i=1; pthread_t threadInfo[10]; pthread_attr_t threadInfo_attr; initarray(); for(i=0;i<10;i++) pthread_create(&threadInfo[i],0,client,(void *)i); for(i=0;i<10;i++) pthread_join(threadInfo[i],0); for(i=0;i<10;i++) printf("%d=%p\\n",i,pindex[i]); for(i=0;i<10;i++) pthread_create(&threadInfo[i],0,client,(void *)i); for(i=0;i<10;i++) pthread_join(threadInfo[i],0); for(i=0;i<10;i++) printf("%d=%p\\n",i,pindex[i]); return 0; }
1
#include <pthread.h> struct thread_pool_queue_node { struct thread_pool_task *task; struct thread_pool_queue_node *next; }; struct thread_pool_queue { unsigned int n_tasks; struct thread_pool_queue_node *head_node; struct thread_pool_queue_node *tail_node; pthread_mutex_t qmutex; }; static struct thread_pool_queue_node * thread_pool_queue_node_create ( struct thread_pool_task *task ) { DPRINTF("entered thread_pool_queue_node_create\\n"); struct thread_pool_queue_node *node = (struct thread_pool_queue_node *) malloc(sizeof(struct thread_pool_queue_node)); if (node == 0) return 0; node->task = task; node->next = 0; DPRINTF("thread_pool_queue_node created successfully\\n"); return node; } static void thread_pool_queue_node_destroy ( struct thread_pool_queue_node *node ) { DPRINTF("entered thread_pool_queue_node_destroy\\n"); if (node == 0) return; node->next = 0; free(node); DPRINTF("thread_pool_queue_node destroyed successfully\\n"); } struct thread_pool_queue * thread_pool_queue_create(void) { DPRINTF("entered thread_pool_queue_create\\n"); struct thread_pool_queue *queue = (struct thread_pool_queue *)malloc(sizeof(struct thread_pool_queue)); if (queue == 0) return 0; queue->n_tasks = 0; queue->head_node = 0; queue->tail_node = 0; if (pthread_mutex_init(&queue->qmutex, 0)) { free(queue); return 0; } DPRINTF("thread_pool_queue created successfully\\n"); return queue; } void thread_pool_queue_destroy ( struct thread_pool_queue *queue ) { DPRINTF("entered thread_pool_queue_destroy\\n"); struct thread_pool_queue_node *node; if (queue == 0) return; node = queue->head_node; while (node) { struct thread_pool_queue_node *temp = node->next; free(node); node = temp; } queue->n_tasks = 0; pthread_mutex_destroy(&queue->qmutex); free(queue); DPRINTF("thread_pool_queue destroyed successfully\\n"); } int thread_pool_queue_enqueue ( struct thread_pool_queue *queue, struct thread_pool_task *task ) { DPRINTF("entered thread_pool_queue_enqueue\\n"); struct thread_pool_queue_node *node; if (queue == 0) return THREAD_POOL_INVALID_PTR; node = thread_pool_queue_node_create(task); if (node == 0) return THREAD_POOL_ALLOC_ERROR; if (pthread_mutex_lock(&queue->qmutex)) { thread_pool_queue_node_destroy(node); return THREAD_POOL_ERROR; } if (queue->tail_node != 0) queue->tail_node->next = node; queue->tail_node = node; if (queue->head_node == 0) queue->head_node = node; ++queue->n_tasks; if (pthread_mutex_unlock(&queue->qmutex)) return THREAD_POOL_ERROR; DPRINTF("thread_pool_task enqueued successfully\\n"); return 0; } struct thread_pool_task * thread_pool_queue_dequeue ( struct thread_pool_queue *queue ) { DPRINTF("entered thread_pool_queue_dequeue\\n"); struct thread_pool_queue_node *node; struct thread_pool_task *task; if (queue == 0) return 0; if (pthread_mutex_trylock(&queue->qmutex)) return 0; DPRINTF("queue mutex acquired successfully\\n"); node = queue->head_node; if (node != 0) queue->head_node = node->next; if (queue->tail_node == node) queue->tail_node = 0; --queue->n_tasks; pthread_mutex_unlock(&queue->qmutex); task = (node == 0) ? 0 : node->task; free(node); DPRINTF("thread_pool_task dequeued successfully\\n"); return task; }
0
#include <pthread.h> int ticket=20; pthread_mutex_t lock; void* salewinds1(void* args){ while(1){ pthread_mutex_lock(&lock); if(ticket>0){ sleep(1); printf("windows1 start sale ticket!the ticket is:%d\\n",ticket); sleep(2); ticket--; printf("w1 sale ticket finish!the last ticket is:%d\\n",ticket); }else{ pthread_mutex_unlock(&lock); pthread_exit(0); } pthread_mutex_unlock(&lock); sleep(1); } } void* salewinds2(void* args){ while(1){ pthread_mutex_lock(&lock); if(ticket>0){ sleep(1); printf("windows2 start sale ticket!the ticket is:%d\\n",ticket); sleep(3); ticket--; printf("w2 sale ticket finish!the last ticket is:%d\\n",ticket); }else{ pthread_mutex_unlock(&lock); pthread_exit(0); } pthread_mutex_unlock(&lock); sleep(1); } } int main(){ pthread_t pthid1=0; pthread_t pthid2=0; pthread_mutex_init(&lock,0); pthread_create(&pthid1,0,salewinds1,0); pthread_create(&pthid2,0,salewinds2,0); pthread_join(pthid1,0); pthread_join(pthid2,0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> const int RMAX = 100; void Usage(char* prog_name); void Get_args(int argc, char* argv[], int* n_p, char* g_i_p); void Generate_list(int a[], int n); void Print_list(int a[], int n, char* title); void Read_list(int a[], int n); void Bubble_sort(void * voi); int block_size=5000,n; int nthreads=1; int* a; pthread_mutex_t *mutex; pthread_t * threads; int main(int argc, char* argv[]) { char g_i; Get_args(argc, argv, &n, &g_i); a = (int*) malloc(n*sizeof(int)); if (g_i == 'g') { Generate_list(a, n); } else { Read_list(a, n); } int i; threads = malloc(nthreads * sizeof(pthread_t)); mutex = malloc((nthreads) * sizeof(pthread_mutex_t)); double start = omp_get_wtime(); int thread; for(thread=0; thread <= nthreads; thread++){ pthread_mutex_init(&mutex[thread], 0); } for(thread=0; thread < nthreads; thread++){ pthread_create(&threads[thread], 0, Bubble_sort, (void *)a); } for(thread=0; thread < nthreads; thread++){ pthread_join( threads[thread], 0); } double end = omp_get_wtime(); printf("%3.2g\\n",end-start); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <n> <g|i>\\n", prog_name); fprintf(stderr, " n: number of elements in list\\n"); fprintf(stderr, " 'g': generate list using a random number generator\\n"); fprintf(stderr, " 'i': user input list\\n"); } void Get_args(int argc, char* argv[], int* n_p, char* g_i_p) { if (argc != 4 ) { Usage(argv[0]); exit(0); } *n_p = atoi(argv[1]); *g_i_p = argv[2][0]; nthreads = atoi(argv[3]); if (*n_p <= 0 || (*g_i_p != 'g' && *g_i_p != 'i') ) { Usage(argv[0]); exit(0); } } void Generate_list(int a[], int n) { int i; srandom(0); for (i = 0; i < n; i++) a[i] = random() % RMAX; } void Print_list(int a[], int n, char* title) { int i; printf("%s:\\n", title); for (i = 0; i < n; i++) printf("%d ", a[i]); printf("\\n\\n"); } void Read_list(int a[], int n) { int i; printf("Please enter the elements of the list\\n"); for (i = 0; i < n; i++) scanf("%d", &a[i]); } void Bubble_sort( void * voi){ int list_length=n, i,x,ind=0, temp,ltemp,max; block_size = (int)(list_length/nthreads); int ordered = 0,changed = 0; while(!ordered){ changed = 0; for(ind=0;ind<nthreads;ind++){ pthread_mutex_lock(&mutex[ind]); max = list_length>(ind+1)*block_size ? (ind+1)*block_size : list_length; for (i = ind*block_size; i < max; i++){ if (a[i] > a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; changed = 1; } } pthread_mutex_unlock(&mutex[ind]); } if(changed==0) ordered = 1; list_length--; } }
0
#include <pthread.h> struct sprite_listnode { struct tb_sprite *sprite; struct sprite_listnode *next; }; static enum tb_color sprite_color(struct tb_sprite *sprite, int x, int y); static struct sprite_listnode *sprites; static pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t move_lock = PTHREAD_MUTEX_INITIALIZER; int tb_sprite_init(struct tb_sprite *sprite, int width, int height) { sprite->x = 0; sprite->y = 0; sprite->width = width; sprite->height = height; sprite->layer = 0; sprite->tile = TB_TILE_NONE; sprite->colors = calloc(sizeof(enum tb_color), width * height); if (sprite->colors == 0) return -1; return 0; } void tb_sprite_del(struct tb_sprite *sprite) { free(sprite->colors); } int tb_sprite_show(struct tb_sprite *sprite) { struct sprite_listnode *curr_node, *next_node, *new_node; pthread_mutex_lock(&list_lock); curr_node = sprites; new_node = malloc(sizeof(struct sprite_listnode)); if (new_node == 0) goto failure; new_node->sprite = sprite; new_node->next = 0; if (curr_node == 0) { sprites = new_node; goto success; } if (sprite->layer >= curr_node->sprite->layer) { new_node->next = curr_node; sprites = new_node; goto success; } while (curr_node->next != 0) { next_node = curr_node->next; if (sprite->layer < curr_node->sprite->layer && sprite->layer >= next_node->sprite->layer) { new_node->next = next_node; curr_node->next = new_node; goto success; } curr_node = next_node; } curr_node->next = new_node; success: pthread_mutex_unlock(&list_lock); tb_sprite_redraw(sprite); return 0; failure: pthread_mutex_unlock(&list_lock); return -1; } int tb_sprite_move(struct tb_sprite *sprite, int new_x, int new_y) { pthread_mutex_lock(&move_lock); sprite->x = new_x; sprite->y = new_y; tb_sprite_redraw(sprite); pthread_mutex_unlock(&move_lock); return 0; } int tb_sprite_redraw(struct tb_sprite *sprite) { int left, right, top, bottom, maxwidth, maxheight, x, y; struct sprite_listnode *curr_node; struct tb_sprite *curr_sprite; enum tb_color color; left = sprite->x; right = left + sprite->width; top = sprite->y; bottom = top + sprite->height; tb_screen_size(&maxwidth, &maxheight); if (sprite->tile & TB_TILE_HORIZONTAL) { left = 0; right = maxwidth; } if (sprite->tile & TB_TILE_VERTICAL) { top = 0; bottom = maxheight; } for (y = top; y < bottom; ++y) { for (x = left; x < right; ++x) { curr_node = sprites; while (curr_node != 0) { curr_sprite = curr_node->sprite; color = sprite_color(curr_sprite, x, y); if (color != TB_COLOR_TRANSPARENT) { tb_screen_put(x, y, color); break; } curr_node = curr_node->next; } } } tb_screen_flush(); return 0; } enum tb_color sprite_color(struct tb_sprite *sprite, int x, int y) { int left, right, top, bottom; left = sprite->x; right = left + sprite->width; top = sprite->y; bottom = top + sprite->height; if (sprite->tile & TB_TILE_HORIZONTAL) { while (x < left) x += sprite->width; while (x >= right) x -= sprite->width; } if (sprite->tile & TB_TILE_VERTICAL) { while (y < top) y += sprite->height; while (y >= bottom) y -= sprite->height; } if (x >= left && x < right && y >= top && y < bottom) return TB_SPRITE_COLOR(*sprite, x - left, y - top); return TB_COLOR_TRANSPARENT; }
1
#include <pthread.h> char *inet_ntoa(struct in_addr in) { static pthread_mutex_t inet_ntoa_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_key_t inet_ntoa_key = -1; char *buf, *inet_ntoa_r(); if (inet_ntoa_key < 0) { pthread_mutex_lock(&inet_ntoa_mutex); if (inet_ntoa_key < 0) { if (pthread_key_create(&inet_ntoa_key, free) < 0) { pthread_mutex_unlock(&inet_ntoa_mutex); return(0); } } pthread_mutex_unlock(&inet_ntoa_mutex); } if ((buf = pthread_getspecific(inet_ntoa_key)) == 0) { if ((buf = (char *) malloc(18)) == 0) { return(0); } pthread_setspecific(inet_ntoa_key, buf); } return inet_ntoa_r(in, buf, 18); } char *inet_ntoa_r(struct in_addr in, char *buf, int bufsize) { register char *p; p = (char *)&in; (void)snprintf(buf, bufsize, "%d.%d.%d.%d", (((int)p[0])&0xff), (((int)p[1])&0xff), (((int)p[2])&0xff), (((int)p[3])&0xff)); return (buf); }
0
#include <pthread.h> const int DEF_THREAD_COUNT = 4; const int DEF_FIB_MAX = 40; { int n; int result; pthread_mutex_t *access; int work; } fib_params_t; int fib(int n) { if (n <= 0) return 0; else if (n == 1) return 1; return fib(n - 1) + fib(n - 2); } void *fib_thread(void *param) { fib_params_t *fib_params = (fib_params_t *)param; while (fib_params->work == 1) { sleep(1); pthread_mutex_lock(fib_params->access); if (fib_params->n != -1) { fib_params->result = fib(fib_params->n); fib_params->n = -1; } pthread_mutex_unlock(fib_params->access); } printf("thread ends\\n"); pthread_mutex_destroy(fib_params->access); return 0; } int main (int argc, char *argv[]) { int thread_count = DEF_THREAD_COUNT; int max_n = DEF_FIB_MAX; if (argc > 1) thread_count = atoi(argv[1]); if (argc > 2) max_n = atoi(argv[2]); if (thread_count == 0) thread_count = DEF_THREAD_COUNT; if (max_n == 0) max_n = DEF_FIB_MAX; printf("Calculating Fibbonaci from 0 to %d\\n", max_n); printf("Creating %d threads\\n", thread_count); fib_params_t params[thread_count]; int i; for (i = 0; i < thread_count; i++) { params[i].work = 1; params[i].n = -1; params[i].result = -1; params[i].access = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(params[i].access, 0); pthread_t thread_id; pthread_create(&thread_id, 0, &fib_thread, &params[i]); pthread_detach(thread_id); } int j; for (i = 0; i < max_n; i += thread_count) { int work_threads = thread_count; if (work_threads > (max_n - i)) work_threads = (max_n - i); for (j = 0; j < work_threads; j++) { int calc = i + j; pthread_mutex_lock(params[j].access); params[j].n = calc; pthread_mutex_unlock(params[j].access); } for (j = 0; j < work_threads; j++) { while(params[j].result == -1) { sleep(1); } } for (j = 0; j < work_threads; j++) { printf("fib(%d) = %d\\n", i + j, params[j].result); params[j].result = -1; } } for (i = 0; i < thread_count; i++) { params[i].work = 0; } printf("END\\n"); return 0; }
1
#include <pthread.h> void comprar_baraja(int cartas[]) { int i , j , k = 0 , l; for(l = 0; l < BARAJAS; ++l){ for(i = 0; i < PINTAS; ++i){ for(j = 0; j < CARTAS_EN_PINTA; ++j){ cartas[k] = j; ++k; } } } } void barajar_cartas(int cartas[],int num_cartas) { int i,j,aux; for( i = num_cartas -1; i > 0; --i){ j = random_port( (i + 1) ); aux = cartas[i]; cartas[i] = cartas[j]; cartas[j] = aux; } } void repartir_cartas() { int i, j, k, l, primero_recibir; for(i = 0; i < CARTAS ; ++i) cuenta_cartas[i] = 0; if( jugador_especifico == -1) primero_recibir = random_port( num_jugadores ); else if( jugador_especifico == 0) primero_recibir = 0; else if( jugador_especifico > 0) primero_recibir = jugador_especifico - 1 ; else primero_recibir = 0; for(j = 0,k = 0; j < CARTAS; ++j){ for(l = 0; l < num_jugadores; ++l){ i = (primero_recibir + l )%num_jugadores; if(k < CARTAS){ cartas_jugadores[i][j] = cartas[k]; cartas[k] = NO_CARTA; ++cuenta_cartas[i]; }else{ cartas_jugadores[i][j] = NO_CARTA; } ++k; } } } void iniciar_juego(int jugador) { init_recursos_jugadores(); int index = num_jugadores; while(index){ --index; pthread_mutex_init( &mtx_jugadores[index] , 0); pthread_mutex_lock( &mtx_jugadores[index] ); } comprar_baraja( cartas ); barajar_cartas( cartas , CARTAS ); repartir_cartas(); imprimir_juego( 0 ); fprintf(stdout, "%s %d\\n",primero_jugar, jugador + 1); poner_jugadores(); pthread_mutex_unlock( &mtx_jugadores[jugador] ); } void terminar_juego() { imprimir_juego( -1 ); quitar_jugadores( num_jugadores ); fprintf(stdout, "%s" , fin_juego); } void poner_jugadores() { int estado_hilo; long i = 0; pthread_t *index; for(index = jugadores ; index < &jugadores[num_jugadores] ; ++index){ estado_hilo = pthread_create( index , 0, manos ,(void*) i++); if( estado_hilo ){ fprintf(stderr , "%s" , crear_error); free( jugadores ); free( mtx_jugadores ); exit( 1 ); } } } void quitar_jugadores(int index) { int i = index; while( index ){ pthread_mutex_unlock( &mtx_jugadores[--index] ); } void * estado_join; int join_index; for(join_index = 0 ; join_index < num_jugadores ; ++join_index){ pthread_join( jugadores[join_index], &estado_join ); } fprintf(stdout, "\\n%s\\t%d\\n", fin_hilos, join_index ); while( i ){ pthread_mutex_unlock( &mtx_jugadores[--i] ); pthread_mutex_destroy( &mtx_jugadores[i] ); } }
0
#include <pthread.h> struct timer_mem_t { timer_t timerid; struct sigevent sev; unsigned int dspip; int clifd; unsigned short recvport; }; static pthread_mutex_t timer_lock = PTHREAD_MUTEX_INITIALIZER; static struct timer_mem_t * dsp_timer[128] = {0}; static int dsptimer_store(struct timer_mem_t ** p , unsigned int dspip) { int index = dspip & 127; pthread_mutex_lock(&timer_lock); *p = (struct timer_mem_t *)Malloc(sizeof(struct timer_mem_t)); memset(*p , 0 , sizeof(struct timer_mem_t)); if(dsp_timer[index] != 0) { pthread_mutex_unlock(&timer_lock); printf("store , (dsp_timer[index] != NULL) !! \\n"); } dsp_timer[index] = *p; pthread_mutex_unlock(&timer_lock); } static int dsptimer_release(unsigned int dspip) { int index = dspip & 127; pthread_mutex_lock(&timer_lock); if(dsp_timer[index] != 0) { timer_delete(dsp_timer[index]->timerid); free(dsp_timer[index]); dsp_timer[index] = 0; pthread_mutex_unlock(&timer_lock); return 0; } pthread_mutex_unlock(&timer_lock); printf("dsptimer_release : avtimer[index] == NULL\\n"); return -1; } static timer_t dsptimer_find(unsigned int dspip) { int index = dspip & 127; if(dsp_timer[index] != 0) return (dsp_timer[index] == 0 ? 0 : dsp_timer[index]->timerid); } static void* handler(void * p) { static int i = 0; struct timer_mem_t * pt = (struct timer_mem_t*)p; dspmgr_delete_dsp(pt->dspip); dsptimer_release(pt->dspip); } static int starttimer(int clifd , unsigned int dspip , long long timeout) { struct timer_mem_t * p; struct itimerspec its; dsptimer_store(&p , dspip); p->dspip = dspip; p->clifd = clifd; p->sev.sigev_notify = SIGEV_THREAD; p->sev.sigev_value.sival_ptr = p; p->sev.sigev_notify_function = (TIMERFUNC)handler; if (timer_create(CLOCK_REALTIME, &(p->sev), &(p->timerid)) == -1) do { perror("timer_create"); exit(1); } while (0); its.it_value.tv_sec = timeout; its.it_value.tv_nsec =0; its.it_interval.tv_sec = timeout; its.it_interval.tv_nsec = 0; if (timer_settime(p->timerid, 0, &its, 0) == -1) do { perror("timer_settime"); exit(1); } while (0); return 0; } int dspmgr_reset_dsptimer(int clifd , unsigned int dspip , long long timeout) { struct itimerspec its; timer_t timerid; if(0 != (timerid = dsptimer_find(dspip))) { its.it_value.tv_sec = timeout; its.it_value.tv_nsec =0; its.it_interval.tv_sec = timeout; its.it_interval.tv_nsec = 0; if (timer_settime(timerid, 0, &its, 0) == -1) err_sys("timer_settime"); return 0; } if(-1 == dspmgr_isexist_dsp(dspip)) { dspmgr_back_dsp(dspip); } if(!starttimer(clifd , dspip , timeout)) return 1; } int dspmgr_send_dsptimers(int fd , void * peeraddr , int addrlen) { int i; char sendbuf[256]; Sendto(fd , "----------DSP-TIMER---------- :\\n" , 32 , 0 , (struct sockaddr*)peeraddr , addrlen); for(i = 0 ; i < 128 ; i++) { if(dsp_timer[i] != 0) { sprintf(sendbuf , "keeper : fd %d , dspip 0x%.8x \\n",i , dsp_timer[i]); Sendto(fd , sendbuf , strlen(sendbuf) , 0 ,(struct sockaddr*)peeraddr , addrlen); } } return 0; }
1
#include <pthread.h> int shops[5]; pthread_mutex_t m1=PTHREAD_MUTEX_INITIALIZER; void shoping(int*need){ int buy, namber; while((*need)!=0){ pthread_mutex_lock(&m1); namber=rand()%5; buy=450+rand()%51; if(shops[namber]>buy){ shops[namber]-=buy; (*need)-=buy; if((*need)<0){ *need=0; } } else buy=0; printf("Shop №%d buy %d need %d goods %d\\n",namber,buy,*need,shops[namber]); pthread_mutex_unlock(&m1); sleep(2); } } void supply(){ int product; int i; while(1){ pthread_mutex_lock(&m1); product=300; i=rand()%5; shops[i]+=product; printf("product %d goods% d shop №%d\\n", product, shops[i], i); pthread_mutex_unlock(&m1); sleep(4); } } int main(){ srand(time(0)); int need[3]; int i,k; pthread_t tid[4]; for(i=0;i<5;i++){ shops[i]=950+rand()%101; } for(i=0; i<3; i++){ need[i]=2900+rand()%200; pthread_create(&tid[i],0,shoping,&need[i]); } pthread_create(&tid[3],0,supply,0); for(i=0; i<3; i++){ pthread_join(tid[i],0); } pthread_cancel(tid[3]); }
0
#include <pthread.h>extern void __VERIFIER_error() ; int num; pthread_mutex_t m; pthread_cond_t empty, full; void * thread1(void * arg) { pthread_mutex_lock(&m); while (num > 0) pthread_cond_wait(&empty, &m); num++; pthread_mutex_unlock(&m); pthread_cond_signal(&full); } void * thread2(void * arg) { pthread_mutex_lock(&m); while (num == 0) pthread_cond_wait(&full, &m); num--; pthread_mutex_unlock(&m); pthread_cond_signal(&empty); } int main() { pthread_t t1, t2; num = 1; pthread_mutex_init(&m, 0); pthread_cond_init(&empty, 0); pthread_cond_init(&full, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_join(t1, 0); pthread_join(t2, 0); if (num!=1) { ERROR: __VERIFIER_error(); ; } return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; int num; pthread_mutex_t m; pthread_cond_t empty, full; void * thread1(void * arg) { pthread_mutex_lock(&m); while (num > 0) pthread_cond_wait(&empty, &m); num++; pthread_mutex_unlock(&m); pthread_cond_signal(&full); } void * thread2(void * arg) { pthread_mutex_lock(&m); while (num == 0) pthread_cond_wait(&full, &m); num--; pthread_mutex_unlock(&m); pthread_cond_signal(&empty); } int main() { pthread_t t1, t2; num = 1; pthread_mutex_init(&m, 0); pthread_cond_init(&empty, 0); pthread_cond_init(&full, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_join(t1, 0); pthread_join(t2, 0); if (num!=1) { ERROR: __VERIFIER_error(); ; } return 0; }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_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 = __VERIFIER_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 = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_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]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> void all_or_nothing_put(char data[], char file_to_write[], int tid) { char data_to_write[MAX]; strcpy(data_to_write, data); struct FileSector obj1; find_sectors(file_to_write, &obj1); check_and_repair(&obj1); printf("Update...Check And Repair Passed\\n\\n"); printf("Update...Writing to Sectors Now\\n\\n"); write_and_commit(data_to_write, &obj1, tid); return; } void write_and_commit(char data[], struct FileSector *obj1, int tid) { char write_cmd[MAX]; int ret=1; pthread_mutex_lock(&lock); sprintf(write_cmd, "echo \\"%s\\" >> %s", data, obj1->fs1); ret = system(write_cmd); if(ret != 0) { printf("Write to Sector 1 failed"); } else { ret=1; sprintf(write_cmd, "echo \\"%s\\" >> %s", data, obj1->fs2); ret = system(write_cmd); if(ret != 0 ) { printf("Write to Sector 2 failed"); } else { ret=1; add_log_record_entry("write", "commit", obj1->fs1, tid); sprintf(write_cmd, "echo \\"%s\\" >> %s", data, obj1->fs3); ret = system(write_cmd); if(ret != 0) { printf("Write to Sector 3 failed"); } else { printf("Update...Write Operation Successful on all Sectors\\n\\n"); add_log_record_entry("write", "end", obj1->fs1, tid); } } } pthread_mutex_unlock(&lock); } void find_sectors(char filename[], struct FileSector *obj1) { strcpy(obj1->fs1, filename); strcpy(obj1->fs2, filename); strcpy(obj1->fs3, filename); strcat(obj1->fs2, "_sector2"); strcat(obj1->fs3, "_sector3"); } void check_and_repair(struct FileSector *obj1) { char system_cmd[MAX]; int ret = 1; match: compute_md5sum(obj1); printf("==========================================================================\\n"); printf("Sector 1 : %s\\nSector 2 : %s\\nSector 3 : %s\\n",obj1->cs1, obj1->cs2, obj1->cs3); printf("==========================================================================\\n"); pthread_mutex_lock(&lock); if(strcmp(obj1->cs1, obj1->cs2) == 0 && strcmp(obj1->cs2, obj1->cs3) == 0 ) { pthread_mutex_unlock(&lock); return; } if(strcmp(obj1->cs1, obj1->cs2) == 0) { sprintf(system_cmd, "cp -p %s %s", obj1->fs1, obj1->fs3); printf("2 : %s\\n", system_cmd); ret = system(system_cmd); if(ret != 0) printf("copy operation failed\\n"); else pthread_mutex_unlock(&lock); return; } if(strcmp(obj1->cs2, obj1->cs3) == 0) { sprintf(system_cmd, "cp -p %s %s", obj1->fs2, obj1->fs1); printf("2 : %s\\n", system_cmd); ret = system(system_cmd); if(ret != 0) printf("copy operation failed\\n"); else pthread_mutex_unlock(&lock); return; } sprintf(system_cmd, "cp -p %s %s", obj1->fs1, obj1->fs2); ret = system(system_cmd); if(ret != 0) printf("copy operation failed\\n"); sprintf(system_cmd, "cp -p %s %s", obj1->fs1, obj1->fs3); ret = system(system_cmd); if(ret != 0) printf("copy operation failed\\n"); pthread_mutex_unlock(&lock); goto match; } void compute_md5sum(struct FileSector *obj1) { char command[MAX]; char checksum[MAX] = ""; snprintf(command, sizeof(command), "md5sum %s", obj1->fs1); FILE *ls1 = popen(command, "r"); fgets(checksum, sizeof(checksum), ls1); pclose(ls1); char *temp1 = strtok(checksum, " "); strcpy(obj1->cs1, temp1); snprintf(command, sizeof(command), "md5sum %s", obj1->fs2); FILE *ls2 = popen(command, "r"); fgets(checksum, sizeof(checksum), ls2); pclose(ls2); char *temp2= strtok(checksum, " "); strcpy(obj1->cs2, temp2); snprintf(command, sizeof(command), "md5sum %s", obj1->fs3); FILE *ls3 = popen(command, "r"); fgets(checksum, sizeof(checksum), ls3); pclose(ls3); char *temp3 = strtok(checksum, " "); strcpy(obj1->cs3, temp3); }
0
#include <pthread.h> struct { int exit; int run; const struct silly_config *conf; pthread_mutex_t mutex; pthread_cond_t cond; } R; static void * thread_timer(void *arg) { (void)arg; for (;;) { silly_timer_update(); if (R.exit) break; usleep(5000); if (silly_worker_msgsize() > 0) pthread_cond_signal(&R.cond); } silly_socket_terminate(); return 0; } static void * thread_socket(void *arg) { (void)arg; for (;;) { int err = silly_socket_poll(); if (err < 0) break; pthread_cond_signal(&R.cond); } pthread_mutex_lock(&R.mutex); R.run = 0; pthread_cond_signal(&R.cond); pthread_mutex_unlock(&R.mutex); return 0; } static void * thread_worker(void *arg) { const struct silly_config *c; c = (struct silly_config *)arg; silly_worker_start(c); while (R.run) { silly_worker_dispatch(); if (!R.run) break; pthread_mutex_lock(&R.mutex); if (R.run) pthread_cond_wait(&R.cond, &R.mutex); pthread_mutex_unlock(&R.mutex); } return 0; } static void thread_create(pthread_t *tid, void *(*start)(void *), void *arg, int cpuid) { int err; err = pthread_create(tid, 0, start, arg); if (unlikely(err < 0)) { silly_log("thread create fail:%d\\n", err); exit(-1); } (void)cpuid; return ; } static void signal_term(int sig) { (void)sig; R.exit = 1; } static void signal_usr1(int sig) { (void)sig; silly_daemon_sigusr1(R.conf); } static int signal_init() { signal(SIGPIPE, SIG_IGN); signal(SIGTERM, signal_term); signal(SIGINT, signal_term); signal(SIGUSR1, signal_usr1); return 0; } void silly_run(const struct silly_config *config) { int i; int err; pthread_t pid[3]; R.run = 1; R.exit = 0; R.conf = config; pthread_mutex_init(&R.mutex, 0); pthread_cond_init(&R.cond, 0); silly_daemon_start(config); silly_log_start(); signal_init(); silly_timer_init(); err = silly_socket_init(); if (unlikely(err < 0)) { silly_log("%s socket init fail:%d\\n", config->selfname, err); silly_daemon_stop(config); exit(-1); } silly_worker_init(); srand(time(0)); thread_create(&pid[0], thread_socket, 0, config->socketaffinity); thread_create(&pid[1], thread_timer, 0, config->timeraffinity); thread_create(&pid[2], thread_worker, (void *)config, config->workeraffinity); silly_log("%s %s is running ...\\n", config->selfname, SILLY_RELEASE); silly_log("cpu affinity setting, timer:%d, socket:%d, worker:%d\\n", config->timeraffinity, config->socketaffinity, config->workeraffinity); for (i = 0; i < 3; i++) pthread_join(pid[i], 0); silly_daemon_stop(config); pthread_mutex_destroy(&R.mutex); pthread_cond_destroy(&R.cond); silly_worker_exit(); silly_timer_exit(); silly_socket_exit(); silly_log("%s has already exit...\\n", config->selfname); return ; } void silly_exit() { R.exit = 1; }
1
#include <pthread.h> void* producer(void *ptr); void* consumer(void* ptr); static char buffer[1024]; pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexB = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexC = PTHREAD_MUTEX_INITIALIZER; int main(){ pthread_t proThread, conThread; pthread_create(&proThread,0,producer,0); pthread_create(&conThread,0,consumer,0); pthread_join(proThread,0); pthread_join(conThread,0); return 0; } void* producer(void *ptr){ while(1){ pthread_mutex_lock(&mutexC); pthread_mutex_lock(&mutexA); produce(); pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); } } void* consumer(void* ptr){ while(1){ pthread_mutex_lock(&mutexB); pthread_mutex_lock(&mutexA); take(); pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexC); } } int produce(){ char line[1024]; if(!fgets(line,1024,stdin)){ perror("stdin"); } sscanf(line,"%s", buffer); return 0; } int take(){ printf("%s\\n", buffer); return 0; }
0
#include <pthread.h> int sem_trywait(sem_t *sem) { int result = 0; if (!sem) { result = EINVAL; } else if (!pthread_mutex_lock(&sem->mutex)) { if (sem->value > 0) (sem->value)--; else result = EAGAIN; pthread_mutex_unlock(&sem->mutex); } else { result = EINVAL; } if (result) { errno = result; return -1; } return 0; }
1
#include <pthread.h> int sum; pthread_mutex_t mtx, mt[2]; pthread_t t[2]; struct package { pid_t pid; int sum; }; void* doIt(void *arg) { int i, id = *(int *)arg; for(i = 0; i < 5; ++ i) { pthread_mutex_lock(&mt[id]); int x = rand() % 100; sum += x; pthread_mutex_unlock(&mt[1 - id]); } free(arg); return 0; } int main() { int i; for(i = 0; i < 10; ++ i) if(fork() == 0) { srand(time(0) ^ (getpid()<<16)); int j; pthread_mutex_init(&mtx, 0); pthread_mutex_init(&mt[0], 0); pthread_mutex_init(&mt[1], 0); pthread_mutex_lock(&mt[1]); for(j = 0; j < 2; ++ j) { int *x = (int *)malloc(sizeof(int)); *x = j; pthread_create(&t[j], 0, doIt, (void *)x); } for(j = 0; j < 2; ++ j) pthread_join(t[j], 0); printf("Process %d has sum %d\\n", getpid(), sum); int fd = open("c2p", O_WRONLY); struct package p; p.sum = sum; p.pid = getpid(); pthread_mutex_lock(&mtx); write(fd, &p, sizeof(struct package)); pthread_mutex_unlock(&mtx); close(fd); pthread_mutex_destroy(&mtx); pthread_mutex_destroy(&mt[0]); pthread_mutex_destroy(&mt[1]); exit(0); } int fd = open("c2p", O_RDONLY); for(i = 0; i < 10; ++ i) { wait(0); struct package p; read(fd, &p, sizeof(struct package)); printf("Received from pid: %d, sum: %d\\n", (int)p.pid, p.sum); } close(fd); return 0; }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int putenv_r(const char *name) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); putenv(name); pthread_mutex_unlock(&env_mutex); return(ENOENT); } void *thr_fn(void *arg) { int a=*((int *)arg); printf("thread %d is running: %u %u\\n",a,(unsigned int)pthread_self(),getpid()); putenv_r("WHATEVER=whatever"); system("env|grep WHATEVER"); } void main() { int num[10]={1,2,3,4,5,6,7,8,9,10}; int i; system("env|grep WHATEVER"); for(i=0;i<5;++i){ int err; pthread_t ntid; err=pthread_create(&ntid,0,thr_fn,num+i); if(err != 0) err_quit("can't create thread:%s \\n",strerror(err)); } sleep(100); }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg){ int err, signo; for(;;){ err = sigwait(&mask, &signo); if(err != 0){ printf("sigwait failed!"); exit(1); } switch(signo){ case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 0; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return 0; default: printf("unexpected signal %d\\n", signo); } } } int main(void){ int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0){ printf("SIG_BLOCK error"); exit(1); } err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0){ printf("create thread failed!\\n"); exit(1); } pthread_mutex_lock(&lock); while(quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0){ printf("SIG_SETMASK error!\\n"); exit(1); } exit(0); }
0
#include <pthread.h> int timer_settime (timer_t timerid, int flags, const struct itimerspec *value, struct itimerspec *ovalue) { struct timer_node *timer; struct thread_node *thread = 0; struct timespec now; int have_now = 0, need_wakeup = 0; int retval = -1; timer = timer_id2ptr (timerid); if (timer == 0) { __set_errno (EINVAL); goto bail; } if (value->it_interval.tv_nsec < 0 || value->it_interval.tv_nsec >= 1000000000 || value->it_value.tv_nsec < 0 || value->it_value.tv_nsec >= 1000000000) { __set_errno (EINVAL); goto bail; } if ((flags & TIMER_ABSTIME) == 0) { clock_gettime (timer->clock, &now); have_now = 1; } pthread_mutex_lock (&__timer_mutex); timer_addref (timer); if (! timer_valid(timer)) { __set_errno (EINVAL); goto unlock_bail; } if (ovalue != 0) { ovalue->it_interval = timer->value.it_interval; if (timer->armed) { if (! have_now) { pthread_mutex_unlock (&__timer_mutex); clock_gettime (timer->clock, &now); have_now = 1; pthread_mutex_lock (&__timer_mutex); timer_addref (timer); } timespec_sub (&ovalue->it_value, &timer->expirytime, &now); } else { ovalue->it_value.tv_sec = 0; ovalue->it_value.tv_nsec = 0; } } timer->value = *value; list_unlink_ip (&timer->links); timer->armed = 0; thread = timer->thread; if (value->it_value.tv_sec != 0 || __builtin_expect (value->it_value.tv_nsec != 0, 1)) { if ((flags & TIMER_ABSTIME) != 0) timer->expirytime = value->it_value; else timespec_add (&timer->expirytime, &now, &value->it_value); if (thread != 0) need_wakeup = __timer_thread_queue_timer (thread, timer); timer->armed = 1; } retval = 0; unlock_bail: timer_delref (timer); pthread_mutex_unlock (&__timer_mutex); bail: if (thread != 0 && need_wakeup) __timer_thread_wakeup (thread); return retval; }
1
#include <pthread.h> struct mt { int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; }; void sys_error(const char* des,int exitNum){ perror(des); exit(exitNum); } int main(){ int fd,i,nReturnValue; struct mt *m; pid_t pid; umask(0); if( -1 == (fd=open("mt_test",O_CREAT | O_RDWR,0777)) ) sys_error("open failed:",-1); if( ftruncate(fd,sizeof(*m)) ){ close(fd); sys_error("ftruncate failed:",-2); } if( (void*)-1 == (m = mmap(0,sizeof(*m),PROT_READ | PROT_WRITE,MAP_SHARED,fd,0)) ){ close(fd); sys_error("mmap failed:",-3); } close(fd); memset(m,0,sizeof(*m)); pthread_mutexattr_init(&(m->mutexattr)); pthread_mutexattr_setpshared(&(m->mutexattr),PTHREAD_PROCESS_SHARED); pthread_mutex_init(&(m->mutex),&(m->mutexattr)); if( !(pid=fork()) ){ for( i = 0; i < 10; i++ ){ pthread_mutex_lock(&(m->mutex)); (m->num)++; printf("子进程:%d\\n",m->num); pthread_mutex_unlock(&(m->mutex)); sleep( 1 ); } } else if(pid > 0){ for( i = 0; i < 10; i++ ){ pthread_mutex_lock(&(m->mutex)); m->num +=2; printf("父进程:%d\\n",m->num); pthread_mutex_unlock(&(m->mutex)); sleep( 1 ); } wait(0); } nReturnValue = pthread_mutexattr_destroy(&(m->mutexattr)); if(nReturnValue){ printf("%s\\n",strerror(nReturnValue)); } nReturnValue = pthread_mutex_destroy(&(m->mutex)); if(nReturnValue){ printf("%s\\n",strerror(nReturnValue)); } munmap(m,sizeof(*m)); unlink("mt_test"); return 0; }
0
#include <pthread.h> pthread_mutex_t cntr_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cntr_cond = PTHREAD_COND_INITIALIZER; long protVariable = 0L; void *producer(void *arg) { int i; for (i=0;i<10000;i++) { pthread_mutex_lock(&cntr_mutex); printf("Producer:make %d, product:%d\\n", i,protVariable); protVariable+=i; pthread_mutex_unlock(&cntr_mutex); pthread_cond_broadcast(&cntr_cond); } pthread_exit(0); } void *consumor(void *arg) { int no; no=*(int*)arg; pthread_detach(pthread_self()); while(1) { pthread_mutex_lock(&cntr_mutex); if (protVariable > 0) { protVariable--; printf("Consumer[%d]:eat %d\\n", no,protVariable); }else { printf("Consumer[%d]: waiting\\n",no); pthread_cond_wait(&cntr_cond, &cntr_mutex); } pthread_mutex_unlock(&cntr_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pthread; pthread_t consumers[10]; int ret; int i; int n[10]; ret=pthread_create(&pthread,0,producer,0); if (ret!=0) { perror("pthread_create"); } for(i=0;i<10;i++) { n[i]=i; pthread_create(&consumers[i],0, consumor, &n[i]); if (ret!=0) { perror("pthread_create"); } } ret=pthread_join(pthread,0); printf("protVariable:%ld",protVariable); while(protVariable>0); for(i=0;i<10;i++) { pthread_cancel(consumers[i]); } return 0; }
1
#include <pthread.h> void* whattodo(void* arg); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t tid[8]; int i, rc; int *t; for (i = 0; i < 8; i++) { t = malloc(sizeof(int)); *t = 2+(i*2); rc = pthread_create( &tid[i], 0, whattodo, t); if (rc != 0) { fprintf( stderr, "MAIN: Could not create thread (%d)\\n", rc); return 1; } } for (i = 0; i < 8; i++) { unsigned int* x; rc = pthread_join(tid[i], (void**)&x); if (rc != 0) { fprintf( stderr, "MAIN: Could not join thread (%d)\\n", rc); return 1; } printf("MAIN: Joined child thread %u, which returned %u\\n", (unsigned int)tid[i], *x); free(x); } printf("MAIN: All threads terminated successfully.\\n"); fflush(0); return 0; } void critical_section( int time ) { printf( "THREAD %u: Entered critical section.\\n", (unsigned int)pthread_self() ); sleep(time); printf( "THREAD %u: Exiting critical section.\\n", (unsigned int)pthread_self() ); } void* whattodo(void* arg) { int t = *(int*)arg; free(arg); printf("THREAD %d: I'm going to nap for %d seconds.\\n", (int)pthread_self(), t); pthread_mutex_lock( &mutex ); critical_section(t); pthread_mutex_unlock( &mutex ); printf("THREAD %d: I'm awake.\\n", (int)pthread_self()); unsigned int* x = malloc(sizeof(unsigned int)); *x = pthread_self(); pthread_exit(x); return(x); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t even = PTHREAD_COND_INITIALIZER; pthread_cond_t odd = PTHREAD_COND_INITIALIZER; void *printfun1(void *pnt); void *printfun2(void *pnt); int main(void) { pthread_t pthread1, pthread2; int ret1, ret2; ret1 = pthread_create(&pthread1, 0, printfun1, 0); if(ret1) { printf("thread creation failed"); } ret2 = pthread_create(&pthread2, 0, printfun2, 0); if(ret2) { printf("thread creation failed"); } pthread_join(pthread1, 0); pthread_join(pthread2, 0); } int counter = 0; void *printfun1(void *ptr) { while(counter < 50) { pthread_mutex_lock(&mutex); while ((counter & 1) == 1) pthread_cond_wait(&even, &mutex); printf("%d \\n", counter); counter++; pthread_cond_signal(&odd); pthread_mutex_unlock(&mutex); usleep( 1000000); } return 0; } void *printfun2(void *ptr) { while(counter < 50) { pthread_mutex_lock(&mutex); while ((counter & 1) == 0) pthread_cond_wait(&odd, &mutex); printf("%d \\n", counter); counter++; pthread_cond_signal(&even); pthread_mutex_unlock(&mutex); usleep( 1000000); } return 0; }
1
#include <pthread.h> struct lock_value{ int count; pthread_mutex_t lock1; pthread_mutex_t lock2; }; void *thr_fn1(void *arg) { struct lock_value *lock; lock = (struct lock_value*)arg; pthread_mutex_lock(&(lock->lock1)); printf("pthread 1 get the lock1\\n"); sleep(2); lock->count ++; printf("pthread 1 want the lock2...\\n"); pthread_mutex_lock(&(lock->lock2)); printf("pthread 1 get the lock2\\n"); pthread_mutex_unlock(&(lock->lock2)); pthread_mutex_unlock(&(lock->lock1)); printf("pthread 1 Done\\n"); pthread_exit((void*)0); } void *thr_fn2(void *arg) { struct lock_value *lock; lock = (struct lock_value*)arg; pthread_mutex_lock(&(lock->lock2)); printf("pthread 2 get the lock2\\n"); lock->count++; printf("pthread 2 want the lock1...\\n"); pthread_mutex_lock(&(lock->lock1)); printf("pthread 2 get the lock1\\n"); pthread_mutex_unlock(&(lock->lock1)); pthread_mutex_unlock(&(lock->lock2)); pthread_exit((void*)0); } int main(void) { int err; pthread_t tid1, tid2; struct lock_value lv; lv.count = 0; if(pthread_mutex_init(&(lv.lock1), 0) < 0){ perror("pthread_mutex_init "); exit(1); } if(pthread_mutex_init(&(lv.lock2), 0) < 0){ perror("Pthread_mutex_init"); exit(1); } err = pthread_create(&tid1, 0, thr_fn1, &lv); if(err != 0){ perror("pthread_create"); exit(1); } sleep(1); err = pthread_create(&tid2, 0, thr_fn2, &lv); if(err != 0){ perror("pthread_create 2"); exit(1); } if(pthread_join(tid1, 0) < 0){ perror("pthread_join"); exit(1); } if(pthread_join(tid2, 0) < 0){ perror("ptrhead_join2"); exit(1); } exit(1); }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_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<((400)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR:__VERIFIER_error(); } void *t2(void *arg) { int i; for(i=0; i<(400); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR:__VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR:__VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; 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==(5)) { 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<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); 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; }
0
#include <pthread.h> const int MAX_THREADS = 1024; long thread_count; long long total_tosses; long long total_in_circle; pthread_mutex_t mutex; void* Monte_Carlo (void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double estimate_pi; double start, finish, elapsed; Get_args(argc, argv); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); total_in_circle = 0; GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Monte_Carlo, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); GET_TIME(finish); elapsed = finish - start; estimate_pi = 4*total_in_circle / (double)total_tosses; printf("With number_of_tosses = %lld,\\n", total_tosses); printf(" Our estimate of pi = %.15f\\n", estimate_pi); printf("The elapsed time is %.10lf seconds\\n", elapsed); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Monte_Carlo (void* rank) { long my_rank = (long) rank; long long i; long long my_tosses = total_tosses / thread_count; long long my_in_circle = 0; double x, y, dist; struct drand48_data drand_buf; int seed = my_rank; srand48_r(seed,&drand_buf); for (i = 0; i < my_tosses; i++) { drand48_r(&drand_buf,&x); drand48_r(&drand_buf,&y); dist = x*x + y*y; if (dist <= 1) my_in_circle++; } printf("Thread %ld:> my_in_circle = %lld\\n",my_rank,my_in_circle); pthread_mutex_lock(&mutex); total_in_circle += my_in_circle; pthread_mutex_unlock(&mutex); return 0; } void Get_args(int argc, char* argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); total_tosses = strtoll(argv[2], 0, 10); if (total_tosses <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <number of tosses>\\n", prog_name); fprintf(stderr, " n is the number of tosses to the dartboard\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
1
#include <pthread.h> pthread_mutex_t a; pthread_mutex_t b; pthread_mutex_t c; int k; int j; void* fn1(void * args){ pthread_mutex_lock(&a);; if( k == 25 ){ pthread_mutex_lock(&b);; if( j ) printf("hola\\n"); else printf("adios\\n"); } else { pthread_mutex_lock(&c);; } } void* fn2(void * args){ pthread_mutex_unlock(&a);; if( k == 12 ){ j = 1; pthread_mutex_unlock(&c);; } else { j = 0; pthread_mutex_unlock(&c);; } pthread_mutex_unlock(&b);; } int main() { pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, &fn1, 0); printf("========================================================\\n"); pthread_create(&thread2, 0, &fn2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; }
0
#include <pthread.h> static pthread_mutex_t *mutex_arr= 0; void locking_function (int mode, int n, const char * file, int line) { (void) file; (void) line; if (mode & CRYPTO_LOCK) pthread_mutex_lock(&(mutex_arr[n])); else pthread_mutex_unlock(&(mutex_arr[n])); } unsigned long id_function(void) { return ((unsigned long)pthread_self( )); } int thread_openssl_setup(void) { int i; mutex_arr = (pthread_mutex_t *) malloc(CRYPTO_num_locks( ) * sizeof(pthread_mutex_t)); if (!mutex_arr) return -1; for (i = 0; i < CRYPTO_num_locks( ); i++) pthread_mutex_init(&(mutex_arr[i]), 0); CRYPTO_set_id_callback(id_function); CRYPTO_set_locking_callback(locking_function); return 0; } int thread_openssl_cleanup(void) { int i; if (! mutex_arr) return -1; CRYPTO_set_id_callback(0); CRYPTO_set_locking_callback(0); for (i = 0; i < CRYPTO_num_locks( ); i++) pthread_mutex_destroy(&(mutex_arr[i])); free(mutex_arr); mutex_arr = 0; return 0; }
1
#include <pthread.h> int num; unsigned long total; int flag; pthread_mutex_t m; pthread_cond_t empty, full; void *thread1(void *arg) { int i; i = 0; while (i < 4) { pthread_mutex_lock(&m); while (num > 0) pthread_cond_wait(&empty, &m); num++; printf("produce ....%d\\n", i); pthread_mutex_unlock(&m); pthread_cond_signal(&full); i++; } } void *thread2(void *arg) { int j; j = 0; while (j < 4) { pthread_mutex_lock(&m); while (num == 0) pthread_cond_wait(&full, &m); total = total + j; printf("total ....%d\\n", total); num--; printf("consume ....%d\\n", j); pthread_mutex_unlock(&m); pthread_cond_signal(&empty); j++; } total = total + j; printf("total ....%d\\n", total); flag = 1; } int main(void) { pthread_t t1, t2; pthread_t t3, t4; num = 0; total = 0; pthread_mutex_init(&m, 0); pthread_cond_init(&empty, 0); pthread_cond_init(&full, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread1, 0); pthread_create(&t4, 0, thread2, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); if (flag) return 0; }
0
#include <pthread.h> int * thread_counter; int total_counter = 0; int * test_array; int i, length, t; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * count3s(void * arg){ int id = *((int *) arg); id--; int length_per_thread = length/t; int start = id *length_per_thread; for(i = start; i < start+length_per_thread; i++){ if(test_array[i] == 3){ thread_counter[id]++; } } pthread_mutex_lock(&mutex); total_counter += thread_counter[id]; pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { struct timespec start, end; double cpu_time_used_iterative, cpu_time_used_threads; int i, n_threads, array_size, debug_flag; int counter_of_3 = 0; if(argc > 2){ if(argc >= 3){ array_size = atoi(argv[1]); n_threads = atoi(argv[2]); if(argc == 4){ debug_flag = 1; } else { debug_flag = 0; } } } else { fprintf(stderr, "Not enough inputs \\n"); return(1); } length = array_size; t = n_threads; test_array = (int *) malloc(sizeof(int*)*array_size); thread_counter = (int *) malloc(sizeof(int*)*array_size); for(i = 0; i < array_size; i++){ test_array[i] = (1 + rand() % ((4)+1 - (1)) ); if(debug_flag == 1 ){ printf("test_array[%d] = %d\\n", i, test_array[i]); } } clock_gettime(CLOCK_MONOTONIC, &start); for(i = 0; i < array_size; i++){ if(test_array[i] == 3) counter_of_3++; } clock_gettime(CLOCK_MONOTONIC, &end); cpu_time_used_iterative = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec); pthread_t tids[n_threads]; clock_gettime(CLOCK_MONOTONIC, &start); for(i = 0; i < n_threads; i++){ pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tids[i], &attr, count3s, &i); } int x; for(x = 0; x < n_threads; x++){ pthread_join(tids[x], 0); } clock_gettime(CLOCK_MONOTONIC, &end); cpu_time_used_threads = 1e3 * (end.tv_sec - start.tv_sec) + 1e-6 * (end.tv_nsec - start.tv_nsec); printf("%f\\n",cpu_time_used_threads); }
1
#include <pthread.h> static pthread_mutex_t gAtExitLock = PTHREAD_MUTEX_INITIALIZER; void _thread_atexit_lock( void ) { pthread_mutex_lock( &gAtExitLock ); } void _thread_atexit_unlock( void ) { pthread_mutex_unlock( &gAtExitLock ); }
0
#include <pthread.h> const unsigned int MAX_BUFF_SIZE = 1024; const unsigned int MAX_WORD_LEN = 128; const unsigned int MAX_FNAME_LEN = 256; { eFILE_NOT_FOUND = -1, eGENERIC_FAILURE = 0, eGENERIC_SUCCESS = 1, }_ERROR_CODES; unsigned int getNumOfWordsinParag(char *inputFileName); void *printWordsFromParag(void *inputFileName); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc,char *argv[]) { unsigned int numOfWordsinParag = 0, rc,i; int numofThreads = 0, thrd_id; char inputFileName[MAX_FNAME_LEN]; void *status; strcpy(inputFileName,"input.txt"); numOfWordsinParag = getNumOfWordsinParag(inputFileName); numofThreads = numOfWordsinParag; pthread_mutex_t mutex; pthread_t threads[numofThreads]; for(i = 0; i < numofThreads ; i++) { thrd_id = pthread_create(&threads[i],0,printWordsFromParag,(void *)inputFileName); } for(i = 0; i < numofThreads; i++) { pthread_join(threads[i], &status); } printf("Debug2: %d \\n", numOfWordsinParag); return 0; } unsigned int getNumOfWordsinParag(char *inputFileName) { FILE *inputFilePtr = 0; char buff[MAX_BUFF_SIZE]; char word[MAX_WORD_LEN]; unsigned int wCount = 0; inputFilePtr = fopen(inputFileName,"r"); if(!inputFilePtr) { printf("Unable to read the file %s\\n",inputFileName); return eFILE_NOT_FOUND; } else { while(fgets(buff,MAX_BUFF_SIZE,inputFilePtr)!= 0) { int i, isWord, isWhite, length; isWord = 0; length = strlen(buff); for(i = 0; i < length; i++) { isWhite = (buff[i]!=' ' && buff[i]!= '\\n' && buff[i] != '\\t') ? 1 : 0; if (isWhite == 1) { if(isWord != 1) wCount++; isWord = 1; } if(isWhite == 0 && isWord == 1) { isWord = 0; } } } } fclose(inputFilePtr); return wCount; } void *printWordsFromParag(void *inputFileName) { FILE *inputFilePtr = 0; char buff[MAX_BUFF_SIZE]; char word[MAX_WORD_LEN]; char *temp = (char *)inputFileName; inputFilePtr = fopen(temp,"r"); if(!inputFilePtr) { printf("Unable to read the file %s\\n",inputFileName); return 0; } else { pthread_mutex_lock(&mutex); while(fgets(buff,MAX_BUFF_SIZE,inputFilePtr)!= 0) { int k = 0, j = 0; int length = strlen(buff); while(k < length) { int wordlen = 0; while(buff[j] != ' ' || buff[j] == '\\n' || buff[j] == '\\t') { word[wordlen++] = buff[j++]; k++; } j++; word[wordlen] = '\\0'; printf(" %s \\n", word); memset(word,0,MAX_WORD_LEN); } } pthread_mutex_unlock(&mutex); } fclose(inputFilePtr); pthread_exit((void*) 0); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(800)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(800)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(800); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); if (top>0) { 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; }
0
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; void* th(void* p) { int i; sleep(4); for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("thread %d : wait signal\\n", (int) pthread_self()); pthread_cond_wait(&cond, &mutex); printf("thread %d : signal reçu !\\n", (int) pthread_self()); pthread_mutex_unlock(&mutex); } return 0; } int main() { int i; srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_t tids[3]; pthread_create(&tids[0], 0, th, 0); pthread_create(&tids[1], 0, th, 0); pthread_create(&tids[2], 0, th, 0); for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("main thread : 1 signal sent\\n"); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); sleep(3); pthread_mutex_lock(&mutex); pthread_cond_broadcast(&cond); printf("main thread : signal sent for all\\n"); pthread_mutex_unlock(&mutex); sleep(3); } pthread_join(tids[0], 0); pthread_join(tids[1], 0); pthread_join(tids[2], 0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); return 0; }
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 *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); system("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); } 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); }
0
#include <pthread.h> char string[100]; pthread_t thr_id_1; pthread_t thr_id_2; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond, cond1; int read = 0; void *thread_1() { pthread_mutex_lock(&lock); while (1) { pthread_cond_wait(&cond, &lock); printf("thread 1"); pthread_cond_signal(&cond1); } pthread_mutex_unlock(&lock); } void *thread_2() { pthread_mutex_lock(&lock); while (1) { printf("thread 2"); pthread_cond_signal(&cond); pthread_cond_wait(&cond1, &lock); } pthread_mutex_unlock(&lock); } int main(int argc, char *argv[]) { pthread_mutex_init(&lock, 0); pthread_cond_init (&cond, 0); pthread_cond_init (&cond1, 0); pthread_create(&thr_id_1, 0, thread_1, 0); pthread_create(&thr_id_2, 0, thread_2, 0); pthread_join(thr_id_1, 0); pthread_join(thr_id_2, 0); return 0; }
1
#include <pthread.h> const int BUFFER_LENGTH = 100; int buffer[BUFFER_LENGTH]; int front = 0, rear = -1; int size = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t empty_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER; bool producer_wait = 0; bool consumer_wait = 0; void *producer(void *arg); void *consumer(void *arg); int main(int argc, char **argv) { pthread_t producer_id; pthread_t consumer_id; pthread_create(&producer_id, 0, producer, 0); pthread_create(&consumer_id, 0, consumer, 0); sleep(1); return 0; } void *producer(void *arg) { pthread_detach(pthread_self()); while (1) { pthread_mutex_lock(&mutex); if (size == BUFFER_LENGTH) { printf("buffer is full. producer is waiting...\\n"); producer_wait = 1; pthread_cond_wait(&full_cond, &mutex); producer_wait = 0; } rear = (rear + 1) % BUFFER_LENGTH; buffer[rear] = rand() % BUFFER_LENGTH; printf("producer produces the item %d: %d\\n", rear, buffer[rear]); ++size; if (size == 1) { while (1) { if (consumer_wait) { pthread_cond_signal(&empty_cond); break; } } } pthread_mutex_unlock(&mutex); } } void *consumer(void *arg) { pthread_detach(pthread_self()); while (1) { pthread_mutex_lock(&mutex); if (size == 0) { printf("buffer is empty. consumer is waiting...\\n"); consumer_wait = 1; pthread_cond_wait(&empty_cond, &mutex); consumer_wait = 0; } printf("consumer consumes an item%d: %d\\n", front, buffer[front]); front = (front + 1) % BUFFER_LENGTH; --size; if (size == BUFFER_LENGTH-1) { while (1) { if (producer_wait) { pthread_cond_signal(&full_cond); break; } } } pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> double bank_balance = 0.0; double ivan_account = 0.0; double petar_account = 0.0; pthread_mutex_t mutex; void deposit(double amount, double *to) { *to += amount; bank_balance += amount; } void withdraw(double amount, double *from) { *from -= amount; bank_balance -= amount; } void *ivan(void *arg) { int i; for(i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); if(rand() % 2 <= 1) { deposit(rand() % 10000, &ivan_account); } else { withdraw(rand() % 10000, &ivan_account); } pthread_mutex_unlock(&mutex); } } void *petar(void *arg) { int i; for(i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); if(rand() % 1000 <= 500) { deposit(rand() % 10000, &petar_account); } else { withdraw(rand() % 10000, &petar_account); } pthread_mutex_unlock(&mutex); } } int main() { srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_t thread1, thread2; pthread_create(&thread1, 0, ivan, 0); pthread_create(&thread2, 0, petar, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&mutex); printf("%f %f\\n", ivan_account + petar_account, bank_balance); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void ThreadClean(void *arg) { pthread_mutex_unlock(&mutex); } void * child1(void *arg) { while(1){ printf("thread 1 get running \\n"); printf("thread 1 pthread_mutex_lock returns %d\\n", pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread 1 condition applied\\n"); pthread_mutex_unlock(&mutex); sleep(5); } return 0; } void *child2(void *arg) { while(1){ sleep(3); printf("thread 2 get running.\\n"); printf("thread 2 pthread_mutex_lock returns %d\\n", pthread_mutex_lock(&mutex)); pthread_cond_wait(&cond,&mutex); printf("thread 2 condition applied\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(void) { pthread_t tid1,tid2; printf("hello, condition variable test\\n"); pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1,0,child1,0); pthread_create(&tid2,0,child2,0); while(1){ sleep(2); pthread_cancel(tid1); sleep(2); pthread_cond_signal(&cond); } sleep(10); return 0; }
0
#include <pthread.h> int var; pthread_mutex_t mymutex; void *my_thread(void *arg) { int n = 10000, i = 0, m = 0; pthread_mutex_lock(&mymutex); m = var; m++; var = m; for(i = 0; i < n; i++); m = var; m--; var = m; pthread_mutex_unlock(&mymutex); pthread_exit(0); } int main(void) { int i = 0, ret[10000], r = 0; pthread_t thread_id[10000]; printf("Enter the value of global variable:"); scanf("%d", &var); r = pthread_mutex_init(&mymutex, 0); if(r != 0) { fprintf(stderr, "Error - pthread_mutex_init() return code: %d\\n", r); exit(1); } for(i = 0; i < 10000; i++) { ret[i] = pthread_create(&thread_id[i], 0, my_thread, 0); if(ret[i]) { fprintf(stderr, "Error - pthread_create() return code: %d\\n", ret[i]); exit(1); } } for(i = 0; i < 10000; i++) { pthread_join(thread_id[i], 0); } printf("Value of var at the end:%d\\n", var); pthread_mutex_destroy(&mymutex); exit(0); }
1
#include <pthread.h> int read_cnt = 0; int write_flag = 1; pthread_mutex_t read_m, access_m, write_m; int cnt = 3; void* read_rt(void *arg); void* write_rt(void* arg); int main() { pthread_t read_tid, write_tid; pthread_mutex_init(&read_m, 0); pthread_mutex_init(&access_m, 0); pthread_mutex_init(&write_m, 0); int n; srand(getpid()); while(1) { if(rand()%2 == 0) pthread_create(&read_tid, 0, read_rt, 0); else pthread_create(&write_tid, 0, write_rt, 0); sleep(1); } pthread_mutex_destroy(&read_m); pthread_mutex_destroy(&write_m); pthread_mutex_destroy(&access_m); return 0; } void* read_rt(void* arg) { pthread_detach(pthread_self()); pthread_mutex_lock(&read_m); if(read_cnt == 0) { pthread_mutex_lock(&access_m); } read_cnt++; pthread_mutex_unlock(&read_m); sleep(1); printf("read the cnt:%d\\n", cnt); pthread_mutex_lock(&read_m); read_cnt--; if(read_cnt == 0) { pthread_mutex_unlock(&access_m); } pthread_mutex_unlock(&read_m); } void* write_rt(void *arg) { pthread_detach(pthread_self()); pthread_mutex_lock(&access_m); printf("write before cnt:%d\\n", cnt); sleep(1); ++cnt; printf("write after cnt:%d\\n", cnt); pthread_mutex_unlock(&access_m); }
0
#include <pthread.h> float width; float rsum = 0.0; pthread_mutex_t mutex1; void *trapeziod(void *thing) { float partial_sum = 0.0; int me = *((int *)thing); double h1; double h2; h1 = sqrt(4.0 - me*width*me*width); h2 = sqrt(4.0 - (me*width +width)*(me*width+width)); partial_sum = .5*((h1+h2)*width); pthread_mutex_lock(&mutex1); rsum += partial_sum; pthread_mutex_unlock(&mutex1); } main() { int num_proc; int i; pthread_t threadId[50]; int segNum[50]; pthread_mutex_init(&mutex1, 0); printf("Input the number of partitions\\n"); scanf("%d", &num_proc); width = 2.0/num_proc; for(i = 0; i<num_proc; i++) { segNum[i] = i; if(pthread_create(&threadId[i], 0, trapeziod, (void *)&segNum[i]) != 0) perror("Pthread_create fails"); } for(i = 0; i < num_proc; i++) if(pthread_join(threadId[i],0) != 0) perror("Pthread_join fails"); printf("The area under the curve is %f\\n", rsum); return(0); }
1
#include <pthread.h> pthread_mutex_t mutex; sem_t roomEmpty; int n_lectores=0; void *escritor(){ while(1){ sem_wait(&roomEmpty); printf("Escribiendo\\n"); sem_post(&roomEmpty); sleep(1); } } void *lector(){ while(1){ sem_post(&roomEmpty); pthread_mutex_lock(&mutex); printf("Leyendo %d\\n",n_lectores); n_lectores++; pthread_mutex_unlock(&mutex); sleep(1); } } int main(){ pthread_t thread_escritor1; pthread_t thread_escritor2; pthread_t thread_lector1; pthread_t thread_lector2; pthread_mutex_init(&mutex, 0); sem_init(&roomEmpty,0,100); pthread_create(&thread_escritor1,0,escritor,0); pthread_create(&thread_escritor2,0,escritor,0); pthread_create(&thread_lector1,0,lector,0); pthread_create(&thread_lector2,0,lector,0); pthread_join(thread_escritor1,0); return 0; }
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; char message[1024]; int clnt_socks[256]; pthread_mutex_t mutx; int main(int argc, char *argv[]) { int serv_sock,clnt_sock; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz; pthread_t t_id; if (argc != 2) { printf("Usag : %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, 10) == -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); pthread_mutex_lock(&mutx); clnt_socks[clnt_cnt++] = clnt_sock; pthread_mutex_unlock(&mutx); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); pthread_detach(t_id); printf("Conneted 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; while((str_len=read(clnt_sock,message,sizeof(message)))!=0) { send_msg(message,str_len); printf("clnt said %s",message); } 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]; break; } } clnt_cnt--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void error_handling(char *message) { fputs(message, stderr); fputc('\\n', stderr); exit(1); } void send_msg(char *message, int len) { int i; pthread_mutex_lock(&mutx); for(i=0;i<clnt_cnt;i++) write(clnt_socks[i],message,len); pthread_mutex_unlock(&mutx); }
1
#include <pthread.h> char buf[10]; size_t len; pthread_mutex_t mutex; pthread_cond_t can_produce; pthread_cond_t can_consume; } buffer_t; int index = 0; int written = 0; int n1; char *s1; FILE *fp ; int readf(FILE * fp){ if((fp=fopen("messages.txt","r"))==0){ printf("ERROR: cant open messages.txt!\\n"); return 0; } s1=(char *)malloc(sizeof(char)*1024); if(s1==0){ printf("ERROR: Out of memory\\n"); return -1; } s1 = "hello world"; n1=strlen(s1); if(s1==0){ return -1; } return 1; } void* producer(void *arg) { buffer_t *buffer = (buffer_t*)arg; while(index < n1) { pthread_mutex_lock(&buffer->mutex); if(buffer->len == 10) { pthread_cond_wait(&buffer->can_produce, &buffer->mutex); } char t = s1[index]; index++; buffer->buf[buffer->len] = t; ++buffer->len; pthread_cond_signal(&buffer->can_consume); pthread_mutex_unlock(&buffer->mutex); } return 0; } void* consumer(void *arg) { buffer_t *buffer = (buffer_t*)arg; while(written <= index + 1) { pthread_mutex_lock(&buffer->mutex); if(buffer->len == 0) { pthread_cond_wait(&buffer->can_consume, &buffer->mutex); } --buffer->len; printf("%c", buffer->buf[written]); written++; pthread_cond_signal(&buffer->can_produce); pthread_mutex_unlock(&buffer->mutex); } return 0; } int main(int argc, char *argv[]) { int count; int i, rc; readf(fp); buffer_t buffer = { .len = 0, .mutex = PTHREAD_MUTEX_INITIALIZER, .can_produce = PTHREAD_COND_INITIALIZER, .can_consume = PTHREAD_COND_INITIALIZER }; pthread_t prod, cons; pthread_create(&prod, 0, producer, (void*)&buffer); pthread_create(&cons, 0, consumer, (void*)&buffer); pthread_join(prod, 0); pthread_join(cons, 0); return 1; }
0
#include <pthread.h> char buffer_teste[40]; int *iniciaTransporte(){ int te, tr; pthread_t te_trans, tr_trans; te = pthread_create(&te_trans, 0, prod_Transporte, 0); if (te) { printf("ERRO: impossivel criar a thread"); exit(-1); } tr = pthread_create(&tr_trans, 0,cons_Transporte, 0); if (tr) { printf("ERRO: impossivel criar a thread : receberDatagramas\\n"); exit(-1); } pthread_join(te_trans, 0); pthread_join(tr_trans, 0); return 0; } void *prod_Transporte() { int retorno_trans; struct datagrama aux; aux.no_inicio = no_inicio; while (1) { int no=10; char *datagrama; printf("Deseja enviar para qual nó?\\n"); scanf("%d", &aux.no_envio); printf("Escreva uma mensagem para enviar:\\n"); scanf("%s",aux.buffer); aux.tam_buffer = strlen(aux.buffer); pthread_mutex_lock(&trans_rede_env2); buffer_rede_trans_env.no_inicio = aux.no_inicio; buffer_rede_trans_env.no_envio = aux.no_envio; buffer_rede_trans_env.tam_buffer = aux.tam_buffer; memcpy(buffer_rede_trans_env.buffer, aux.buffer, aux.tam_buffer); pthread_mutex_unlock(&trans_rede_rcv2); pthread_mutex_lock(&controle_rede_rcv); retorno_trans = retorno_rede; pthread_mutex_unlock(&controle_rede_env); if(retorno_trans == 1) { printf("erro!\\n"); } } } void *cons_Transporte() { struct datagrama aux; while (1) { pthread_mutex_lock(&trans_rede_rcv1); aux.no_inicio = buffer_rede_trans_rcv.no_inicio; aux.no_envio = buffer_rede_trans_rcv.no_envio; aux.tam_buffer = buffer_rede_trans_env.tam_buffer; memcpy(aux.buffer, buffer_rede_trans_env.buffer, buffer_rede_trans_env.tam_buffer); pthread_mutex_unlock(&trans_rede_env1); printf("\\n\\nTeste-> Tam_buffer: %d Bytes, Buffer: %s %s\\n", aux.tam_buffer, buffer_rede_trans_env.buffer, aux.buffer); } }
1
#include <pthread.h> pthread_mutex_t lock; int requests =3; { int thread_no; char message[100]; } thdata; thdata data[4]; pthread_t station_tid[2]; pthread_t machine_tid[4]; void runMachine(void *ptr); void setup(int stations, int machines); void release(int machine); int allocate(); void reg(); int main() { int station, machine; for(int j=0; j<4;j++){ data[j].thread_no = j; } setup(machine, station); for(int i=0;i<requests; i++){ pthread_join(station_tid[i], 0); pthread_join(machine_tid[i], 0); } pthread_mutex_destroy(&lock); } int allocate(){ pthread_mutex_lock(&lock); return 1; } void release(int machine){ printf("Machine %d is available.\\n", machine); } void runMachine(void *ptr){ thdata *data; data = (thdata *) ptr; printf("Machine running, brb in 5 seconds...\\n"); sleep(5); release(data->thread_no); } void reg(){ pthread_mutex_unlock(&lock); int machine_id = allocate(); } void setup(int machines, int stations) { int i=0; while(i<requests){ stations =pthread_create(&station_tid[i],0,(void *) reg, 0); machines = pthread_create(&machine_tid[i],0,(void *)runMachine, (void *) &data[i]); i++; } }
0
#include <pthread.h> int res = 12345 ; int * px = 0 ; int * py = 0 ; pthread_mutex_t verroupx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t verroupy = PTHREAD_MUTEX_INITIALIZER; void* mon_threadpx(void * arg){ int max = *(int*)arg ; int i ; for(i = 0 ; i < max ; i++ ){ pthread_mutex_lock(&verroupx); printf("Voila la valeur contenue dans px : %d\\n",*px); pthread_mutex_unlock(&verroupx); } pthread_exit(&res); } void* mon_threadpy(void * arg){ int max = *(int*)arg ; int i ; for(i = 0 ; i < max ; i++ ){ pthread_mutex_lock(&verroupy); printf("Voila la valeur contenue dans py : %d\\n",*py); pthread_mutex_unlock(&verroupy); } pthread_exit(&res); } int main() { int x = 1 ; px = &x ; int y = 0 ; py = &y ; int m ; scanf("%d",&m); pthread_t id1 ; pthread_create(&id1,0,mon_threadpx,&m); pthread_t id2 ; pthread_create(&id2,0,mon_threadpy,&m); int j = 0 ; while(j<m){ if(pthread_mutex_trylock(&verroupx)==0){ if(pthread_mutex_trylock(&verroupy)==0){ px = 0 ; py = 0 ; printf("Valeur de j : %d \\n",j); px = &x ; py = &y ; j++ ; pthread_mutex_unlock(&verroupy); } pthread_mutex_unlock(&verroupx); } } pthread_exit(0); return 0 ; }
1
#include <pthread.h> void * writer (void * id); void * dove (void * id); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t fullOfLetters, emptyOfLetters; const int LETTERS = 30, WRITERS = 50; int lettersIn = 0; int main (int argc, char * argv[]) { pthread_t doveThread, writerThread[WRITERS]; int * idW = 0, * idD = 0, i = 0; sem_init (&fullOfLetters, 0, 0); sem_init (&emptyOfLetters, 0, LETTERS); srand (time(0)); for (i = 0; i < WRITERS; i++) { idW = (int *) malloc (sizeof(int)); *idW = i; if (pthread_create (&writerThread[i], 0, writer, (void *) idW)) { return -1; } } if (pthread_create (&doveThread, 0, dove, 0)) { return -1; } for (i = 0; i < WRITERS; i++) { if (pthread_join (writerThread[i], 0)) { return -1; } } pthread_join (doveThread, 0); return 0; } void * writer (void * id) { int i = *((int *) id) + 1; while (1) { sem_wait (&emptyOfLetters); printf ("Remetente %d: Vou escrever uma carta\\n", i); sleep ((rand()%3 + 1)); pthread_mutex_lock (&mutex); printf ("Remetente %d: Escrevendo...\\n", i); sleep (1); printf ("Remetente %d: Carta escrita\\n", i); lettersIn++; printf ("Cartas pendentes para envio: %d\\n", lettersIn); pthread_mutex_unlock (&mutex); if (lettersIn == 30) sem_post (&fullOfLetters); } pthread_exit (0); } void * dove (void * id) { int i = 0; while (1) { sem_wait (&fullOfLetters); printf ("\\nPombo pronto para enviar cartas para a cidade B\\n"); pthread_mutex_lock (&mutex); printf ("Pombo iniciando viagem...\\n"); sleep (1); printf ("Pombo viajando...\\n"); sleep (5); printf ("Cartas entregues!\\nPombo preparando para retornar\\n"); sleep (1); lettersIn = 0; printf ("Pombo retornando a cidade A...\\n"); sleep (5); pthread_mutex_unlock (&mutex); for (i = 0; i < LETTERS; i++) sem_post (&emptyOfLetters); } pthread_exit (0); }
0
#include <pthread.h> void _scoks_queue_lock(struct _socks_queue_t* q) { pthread_mutex_lock(&q->_lock); } void _scoks_queue_unlock(struct _socks_queue_t* q) { pthread_mutex_unlock(&q->_lock); } struct _socks_queue_t* socks_queue_alloc() { struct _socks_queue_t* q = (struct _socks_queue_t*)malloc(sizeof(struct _socks_queue_t)); if(0 == q){ return 0; } q->_msg_head = q->_msg_tail = 0; q->_count = 0; pthread_mutex_init(&q->_lock, 0); return q; } void socks_queue_free(struct _socks_queue_t* q) { struct socks_msg_t *msgs = q->_msg_head, *last = 0; pthread_mutex_destroy(&q->_lock); free(q); while (msgs){ last = msgs; msgs = msgs->_next; free(last); } } void socks_queue_push(struct _socks_queue_t* q, struct socks_msg_t* msg) { _scoks_queue_lock(q); msg->_next = 0; if (q->_msg_tail){ q->_msg_tail->_next = msg; } q->_msg_tail = msg; if (q->_msg_head == 0){ q->_msg_head = msg; } q->_count++; _scoks_queue_unlock(q); } struct socks_msg_t* socks_queue_pop(struct _socks_queue_t* q) { struct socks_msg_t* msg = 0; _scoks_queue_lock(q); if (q->_count > 0){ msg = q->_msg_head; if (msg){ q->_msg_head = msg->_next; if (q->_msg_head == 0) q->_msg_tail = 0; msg->_next = 0; } q->_count--; } _scoks_queue_unlock(q); return msg; }
1
#include <pthread.h> void *wolfThread(){ int i; int color[3] = {0xFF1F05,0xAF2A00,0xDF3800}; int setcolor; int lednum = 0; int ledcolor = 0; int sleeptime = 2000000; int sleepmin = SLEEPMIN; int sleepmax = SLEEPMAX; printf("Start Wolf effect\\n"); for(i=0;i<(LEDANZ-1);i=i+2){ setcolor = color[rand()%3]; setLED(i,setcolor); setLED(i+1,setcolor); if(debug == 1) printf("led:%d,%d color:%d\\n",i,i+1,setcolor); } while(1){ while(sleeptime < sleepmin) sleeptime = rand()%sleepmax; lednum=rand() % (LEDANZ-1); if(lednum%2 != 0) lednum++; ledcolor = getLEDcolor(lednum); setLED(lednum,0); setLED(lednum+1,0); if(debug == 1) printf("lednum:%d,%d\\n",lednum,lednum+1); usleep(BLINKTIME); setLED(lednum,ledcolor); setLED(lednum+1,ledcolor); for(i=0;i<1000;i++){ pthread_mutex_lock(&mutexThreadRun); if(!WolfThreadRun) { pthread_mutex_unlock(&mutexThreadRun); printf("Wolf End\\n"); goto wolfend;} pthread_mutex_unlock(&mutexThreadRun); usleep(sleeptime/1000); } } wolfend:setLEDsOFF(); printf("End Wolf effect\\n"); return; } void *starThread(){ int i; int color[3] = {0xFFFFA5,0xCFFAFF,0x9FFFFF}; int setcolor; printf("Start Star effect\\n"); for(i=0;i<(LEDANZ-1);i=i+2){ setcolor = color[rand()%3]; setLED(i,setcolor); if(debug == 1) printf("led:%d,%d color:%d\\n",i,i+1,setcolor); } setLED(22,0); setLED(8,0); while(1){ pthread_mutex_lock(&mutexThreadRun); if(!StarThreadRun) { pthread_mutex_unlock(&mutexThreadRun); break;} pthread_mutex_unlock(&mutexThreadRun); usleep(100000); } setLEDsOFF(); printf("End Star effect\\n"); return; } int main(int argc, char*argv[]){ int i,rc; int brt=50; int opt; char recvmsg[BUFSIZE]; int port = DEFAULTPORT; int thrun = 0; pthread_t wolfPThread,starPThread; pthread_mutex_init(&mutexThreadRun, 0); WolfThreadRun = 0; StarThreadRun = 0; if(initLEDs(LEDANZ)){ printf("ERROR: initLED\\n"); return -1;} while ((opt = getopt(argc, argv, "p:dhb:")) != -1) { switch (opt) { case 'p': if(optarg != 0) port = atoi(optarg); break; case 'd': debug = 1; break; case 'b': if(optarg != 0) brt = atoi(optarg); break; case 'h': printf("Help for TaPWolfServer\\n"); printf("Usage: %s [-p portnumber] [-b brightness] [-d] debug mode [-i] invert pwm output [-h] show Help\\n", argv[0]); return 0; break; default: printf("Usage: %s [-p portnumber] [-b brightness] [-d] debug mode [-i] invert pwm output [-h] show Help\\n", argv[0]); return -2; } } if(setBrightness(brt)){ printf("ERROR setBrightnes\\n"); return -1;} if(setLEDsOFF()){ printf("ERROR setLEDsOFF\\n"); return -1;} if(initUDPServer(port) != 0){ printf("ERROR while init UDP-Server\\n"); return -1; } while(1){ bzero(recvmsg, BUFSIZE); printf("Wait for command\\n"); waitForClient(recvmsg); if(parseCommand(recvmsg) != 0){ printf("ERROR wrong Syntax\\n"); continue; } if(strcmp(Mode, "WolfON") == 0){ pthread_mutex_lock(&mutexThreadRun); if(WolfThreadRun == 0 && StarThreadRun == 0) WolfThreadRun = 1; else{ printf("An effect is already running\\n"); pthread_mutex_unlock(&mutexThreadRun); goto mainloop;} pthread_mutex_unlock(&mutexThreadRun); rc = pthread_create( &wolfPThread, 0, &wolfThread, 0 ); if( rc != 0 ) { printf("Cannot create WolfThread\\n"); pthread_mutex_lock(&mutexThreadRun); WolfThreadRun = 0; pthread_mutex_unlock(&mutexThreadRun); return -1; } } if(strcmp(Mode, "WolfOFF") == 0){ pthread_mutex_lock(&mutexThreadRun); if(WolfThreadRun == 1) WolfThreadRun = 0; else{ printf("WolfThread isn't running\\n"); pthread_mutex_unlock(&mutexThreadRun); goto mainloop; } pthread_mutex_unlock(&mutexThreadRun); } if(strcmp(Mode, "StarON") == 0){ pthread_mutex_lock(&mutexThreadRun); if(WolfThreadRun == 0 && StarThreadRun == 0) StarThreadRun = 1; else{ printf("An effect is alreay running\\n"); pthread_mutex_unlock(&mutexThreadRun); goto mainloop;} pthread_mutex_unlock(&mutexThreadRun); rc = pthread_create( &starPThread, 0, &starThread, 0 ); if( rc != 0 ) { printf("Cannot create StarThread \\n"); pthread_mutex_lock(&mutexThreadRun); StarThreadRun = 0; pthread_mutex_unlock(&mutexThreadRun); return -1;} } if(strcmp(Mode, "StarOFF") == 0){ pthread_mutex_lock(&mutexThreadRun); if(StarThreadRun == 1) StarThreadRun = 0; else{ printf("Stareffect isn't running\\n"); pthread_mutex_unlock(&mutexThreadRun); goto mainloop; } pthread_mutex_unlock(&mutexThreadRun); } if(strcmp(Mode, "exit") == 0){ pthread_mutex_lock(&mutexThreadRun); StarThreadRun = 0; WolfThreadRun = 0; pthread_mutex_unlock(&mutexThreadRun); goto exitloop; } mainloop:continue; } exitloop: if(setLEDsOFF()){ printf("ERROR setLEDsOFF\\n"); return -1;} ws2811_fini(&myledstring); return 0; } int parseCommand(char command[BUFSIZE]){ int i; char copycommand[BUFSIZE]; char *splitCommand; for(i=0;i<BUFSIZE;i++) copycommand[i] = command[i]; splitCommand=strtok(copycommand,";"); if(strcmp(splitCommand, "TaPFX-DB") != 0) return -1; splitCommand=strtok(0,";"); if(strcmp(splitCommand, "WolfON") == 0 || strcmp(splitCommand, "WolfOFF") == 0 || strcmp(splitCommand, "StarON") == 0 || strcmp(splitCommand, "StarOFF") == 0 || strcmp(splitCommand, "exit") == 0) Mode = splitCommand; else return -1; return 0; }
0
#include <pthread.h> int total_all=0; int total_word=0; int total_char=0; int total_line=0; int find_longline=0; int check=0; pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER; int main(int ac, char *av[]) { pthread_t t; int che; int i; void *count_all(void *); void *count_char(void *); void *count_word(void *); void *count_line(void *); void *count_find(void *); check = ac-3; if(ac < 2) { printf("입력 예시 : wc -(매개변수) 파일명1 파일명2 ...\\n혹은 wc 파일명1 파일명2 ..."); } if(!strcmp(av[1],"-c")) { che =1; for(i=2;i<ac;i++){ pthread_create(&t,0,count_all,(void*) av[i]); pthread_join(t,0); } } else if(!strcmp(av[1],"-m")) { che =2; for(i=2;i<ac;i++){ pthread_create(&t,0,count_char,(void *)av[i]); pthread_join(t,0); } } else if(!strcmp(av[1],"-l")) { che =3; for(i=2;i<ac;i++){ pthread_create(&t,0,count_line,(void *)av[i]); pthread_join(t,0); } } else if(!strcmp(av[1],"-w")) { che=4; for(i=2;i<ac;i++){ pthread_create(&t,0,count_word,(void*) av[i]); pthread_join(t,0); } } else if(!strcmp(av[1],"-L")) { che =5; for(i=2;i<ac;i++){ pthread_create(&t,0,count_find,(void *)av[i]); pthread_join(t,0); } } else { che=4; for(i=1;i<ac;i++){ pthread_create(&t,0,count_word,(void*) av[i]); pthread_join(t,0); } } switch(che) { case 1: printf("모든 문자 수 : %d ",total_all); break; case 2: printf("모든 캐릭터 수 : %d",total_char); break; case 3: printf("모든 라인 수 : %d",total_line); break; case 4: printf("모든 단어 수 : %d",total_word); break; case 5: printf("가장 긴 라인 : %d",find_longline); break; } puts(""); return 0; } void *count_all(void *f) { char *filename = (char *)f; FILE *fp; int c; int count=0; if((fp=fopen(filename,"r"))!=0) { while((c=getc(fp))!=EOF) { if(c=='\\n' || c==' ') { } else count++; } fclose(fp); total_all+=count; if(check!=0){ printf("%s : %d\\n",filename,count); } check++; } else perror(filename); return 0; } void *count_char(void *f) { char *filename = (char*)f; FILE *fp; int c; int count=0; if((fp=fopen(filename,"r"))!=0) { while((c=getc(fp))!=EOF) { count++; } fclose(fp); total_char +=count; if(check!=0) { printf("%s : %d\\n",filename,count); } } else perror(filename); return 0; } void *count_line(void *f) { char *filename = (char *)f; FILE *fp; int c; int count=0; int line=0; if((fp=fopen(filename,"r"))!=0) { while((c=getc(fp))!=EOF) { if(c!='\\n') { } else count++; } if(check!=0){ printf("%s : %d\\n",filename,count); } total_line+=count; } } void *count_find(void *f) { char *filename = (char *)f; FILE *fp; int c; int count=0; int line=0; int maxcount=-1; if((fp=fopen(filename,"r"))!=0) { while((c=getc(fp))!=EOF) { if(c!='\\n') { count ++; } else if(c=='\\n'&& (maxcount<=count)) { line++; maxcount=count; count=0; find_longline=line; } else if(c=='\\n' && (maxcount>=count)) { line++; count=0; } } if(check!=0){ printf("%s : %d\\n",filename,find_longline); } fclose(fp); } else perror(filename); return 0; } void *count_word(void *f) { char *filename = (char*)f; FILE *fp; int c, prevc = '\\0'; int count=0; if((fp = fopen(filename,"r"))!=0) { while((c=getc(fp))!=EOF) { if(!isalnum(c) && isalnum(prevc)){ pthread_mutex_lock(&counter_lock); count++; pthread_mutex_unlock(&counter_lock); } prevc = c; } total_word +=count; if(check!=0) { printf("%s : %d\\n",filename,count); } fclose(fp); } else perror(filename); return 0; }
1
#include <pthread.h> void fifo_init(struct fifo_wait *wait) { memset(wait, 0, sizeof(struct fifo_wait)); pthread_mutex_init(&wait->mutex, 0); pthread_cond_init(&wait->cond, 0); wait->head = wait->tail = 0; } void fifo_destroy(struct fifo_wait *wait) { pthread_mutex_destroy(&wait->mutex); pthread_cond_destroy(&wait->cond); } void fifo_enter(struct fifo_wait *wait) { pthread_mutex_lock(&wait->mutex); uint8_t my_token = (wait->head)++; while (my_token != wait->tail) { pthread_cond_wait(&wait->cond, &wait->mutex); } pthread_mutex_unlock(&wait->mutex); } void fifo_leave(struct fifo_wait *wait) { pthread_mutex_lock(&wait->mutex); (wait->tail)++; pthread_cond_broadcast(&wait->cond); pthread_mutex_unlock(&wait->mutex); } static struct safe_fifo_elem *new_fifo_elem() { struct safe_fifo_elem *elem = (struct safe_fifo_elem*)malloc(sizeof(struct safe_fifo_elem)); elem->elem = 0; elem->id = 0; elem->prev = elem->next = 0; return elem; } static void free_fifo_elem(struct safe_fifo_elem *elem) { free(elem); } void safe_fifo_init(struct safe_fifo *fifo) { pthread_mutex_init(&fifo->mutex, 0); pthread_cond_init(&fifo->cond, 0); fifo->head = fifo->tail = 0; } int safe_fifo_push_back(struct safe_fifo *fifo, void *elem, int id) { struct safe_fifo_elem *nelem = new_fifo_elem(); nelem->elem = elem; pthread_mutex_lock(&fifo->mutex); if (id == -1) { id = 31400000; while (1) { bool found = 0; for (struct safe_fifo_elem *ptr = fifo->tail; ptr; ptr = ptr->next) { if (ptr->id == id) { found = 1; break; } } if (!found) { break; } id++; } } debug("insert id %d\\n", id); nelem->id = id; nelem->prev = fifo->head; if (nelem->prev) { nelem->prev->next = nelem; } fifo->head = nelem; if (!fifo->tail) { fifo->tail = nelem; } pthread_cond_broadcast(&fifo->cond); pthread_mutex_unlock(&fifo->mutex); return id; } struct safe_fifo_elem *safe_fifo_front(struct safe_fifo *fifo) { return fifo->tail; } struct safe_fifo_elem *safe_fifo_front_by_id(struct safe_fifo *fifo, int id) { debug("id = %d\\n", id); pthread_mutex_lock(&fifo->mutex); struct safe_fifo_elem *result = 0, *cur = fifo->tail; while (cur) { debug("cid = %d\\n", cur->id); if (cur->id == id) { result = cur; break; } cur = cur->next; } pthread_mutex_unlock(&fifo->mutex); return result; } void safe_fifo_erase(struct safe_fifo *fifo, struct safe_fifo_elem *elem) { pthread_mutex_lock(&fifo->mutex); if (fifo->head == elem) { fifo->head = elem->prev; } if (fifo->tail == elem) { fifo->tail = elem->next; } if (elem->prev) { elem->prev->next = elem->next; } if (elem->next) { elem->next->prev = elem->prev; } pthread_mutex_unlock(&fifo->mutex); free_fifo_elem(elem); } void safe_fifo_apply(struct safe_fifo *fifo, void (*func)(void*, void*), void *param) { pthread_mutex_lock(&fifo->mutex); for (struct safe_fifo_elem *ptr = fifo->tail; ptr; ptr = ptr->next) { func(ptr->elem, param); } pthread_mutex_unlock(&fifo->mutex); } void safe_fifo_wait_for_elem(struct safe_fifo *fifo) { pthread_mutex_lock(&fifo->mutex); while (!fifo->head) { pthread_cond_wait(&fifo->cond, &fifo->mutex); } pthread_mutex_unlock(&fifo->mutex); }
0
#include <pthread.h> char *str_clear_crlf(char *s) { int i = strlen(s) - 1; if(s) { for(int j = i;j >= 0;j--) { if(s[j] == '\\n' || s[j] == '\\r') { s[j] = 0; } else { break; } } } return s; } void print_debug(const char *file, const char *funtion,int linenum,const char *fmt, ...) { static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER; static int count=0; int flag = 0; char buf[512]={0}; char buffer[1024]={0}; int offset = 0; int level = 0; if(fmt[0] > 0 && fmt[0] < 7) { offset = 1; if(fmt[0] <= 1) { goto end; } else { level = fmt[0]; } } pthread_mutex_lock ( &log_mutex ); va_list ap; __builtin_va_start((ap)); vsnprintf(buf,512,fmt,ap); ; char *p = strrchr(file, '/'); if(p != 0) { p += 1; } else { p = (char *)file; } if(flag == 0) { fprintf(stderr,"[%d <%s> %d (%s)]: ",++count, p, linenum, funtion); } else { snprintf(buffer,1024,"[%d <%s> %d (%s)]: ", ++count, p, linenum, funtion); } if(level == 3 || level == 4 || level == 5 || level == 6) { fprintf(stderr,"\\033[31;46;5m"); if(level == 3 || level == 4) { if(flag == 0) { fprintf(stderr,"\\033[31;46;1m"); } else { strcat(buffer,"\\033[31;46;1m"); } } else { if(flag == 0) { fprintf(stderr,"\\033[31;42;1m"); } else { strcat(buffer,"\\033[31;42;1m"); } } } str_clear_crlf(buf); if(flag == 0) { fprintf(stderr,"%s",buf + offset); } else { strcat(buffer,buf + offset); } if(level == 3 || level == 4 || level == 5 || level == 6) { if(flag == 0) { fprintf(stderr,"\\033[39;49;0m"); } else { strcat(buffer,"\\033[39;49;0m"); } } if(flag == 0) { fprintf(stderr,"\\n"); } if(level == 5) { if(level == 5) { if(flag == 0) { fprintf(stderr,"\\n"); fprintf(stderr,"\\033[31;46;5m"); fprintf(stderr,"======================FATAL ERROR======================"); fprintf(stderr,"\\033[39;49;0m"); fprintf(stderr,"\\n"); } else { strcat(buffer,"\\n"); strcat(buffer,"\\033[31;46;5m"); strcat(buffer,"======================FATAL ERROR======================"); strcat(buffer,"\\033[39;49;0m"); strcat(buffer,"\\n"); } } } if(flag != 0) { FILE *fp = fopen("log.txt", "ab+"); if(fp) { fprintf(fp, "%s", buffer); fclose(fp); } } pthread_mutex_unlock ( &log_mutex ); end: return; }
1
#include <pthread.h> int dequeue_is_waiting = 0; pthread_mutex_t dequeue_is_waiting_mutex; pthread_cond_t dequeue_is_waiting_cond; int enqueue_is_waiting = 0; pthread_mutex_t enqueue_is_waiting_mutex; pthread_cond_t enqueue_is_waiting_cond; const size_t smpl_size = sizeof (jack_default_audio_sample_t) ; { int head; int tail; int recordlimit; int records; float *queue; } rtqueue_t; rtqueue_t * rtqueue_init(int recordlimit) { rtqueue_t *rtq = (rtqueue_t *) malloc(sizeof(rtqueue_t)); rtq->queue = (float *) malloc(smpl_size * (recordlimit + 1)); rtq->head = 0; rtq->tail = 0; rtq->recordlimit = recordlimit; return rtq; } int rtqueue_numrecords(rtqueue_t *rtq) { return rtq->records; } int rtqueue_isfull(rtqueue_t *rtq) { if ((rtq->tail + 1) % (rtq->recordlimit + 1) == rtq->head) return 1; else return 0; } int rtqueue_isempty(rtqueue_t *rtq) { if (rtq->head == rtq->tail) return 1; else return 0; } int rtqueue_enq(rtqueue_t *rtq, float data) { if ((rtq->tail + 1) % (rtq->recordlimit + 1) == rtq->head) { enqueue_is_waiting = 1; pthread_mutex_lock(&enqueue_is_waiting_mutex); pthread_cond_wait(&enqueue_is_waiting_cond, &enqueue_is_waiting_mutex); pthread_mutex_unlock(&enqueue_is_waiting_mutex); enqueue_is_waiting = 0; } rtq->queue[rtq->tail] = data; rtq->tail = (rtq->tail + 1) % (rtq->recordlimit + 1); rtq->records+=1; if (dequeue_is_waiting) pthread_cond_signal(&dequeue_is_waiting_cond); return 0; } float rtqueue_deq(rtqueue_t *rtq) { float data; while (rtq->head == rtq->tail) { dequeue_is_waiting = 1; pthread_mutex_lock(&dequeue_is_waiting_mutex); pthread_cond_wait(&dequeue_is_waiting_cond, &dequeue_is_waiting_mutex); pthread_mutex_unlock(&dequeue_is_waiting_mutex); dequeue_is_waiting = 0; } data = rtq->queue[rtq->head]; rtq->head = (rtq->head + 1) % (rtq->recordlimit + 1); rtq->records-=1; if (enqueue_is_waiting) pthread_cond_signal(&enqueue_is_waiting_cond); return data; }
0
#include <pthread.h> void *takeoffFunc (void *ptr); void *landingFunc (void *ptr); int ARRAY_landing [10], ARRAY_lane [10]; pthread_mutex_t lock; int main(int argc, char *argv[]) { int question = 0; int num = 0; int plane_Cont = 0; int x = 0; int lane_Cont = 0; int ux = 0; int vx = 0; int gx = 1; int run_S = 0; int rc = 0; int rx = 0; long t; while (question != 4) { switch (question) { case 0: { printf (" How many lanes will be used today? (USE INTEGER) \\n"); printf (" **The maximum number of lanes the airport can supports is 5 \\n"); scanf ("%ld", &num); if ( num < 0 || num > 5 ) question = 1; else question = 2; lane_Cont = num ;} break; case 1:{ num = 0; printf (" You did not enter a valid integer. \\n"); printf (" Enter a new integer \\n"); scanf ("%ld", &num); if ( num < 0 || num > 5) question = 1; else question = 2; lane_Cont = num ; } break; case 2:{ num = 0; printf (" How many planes will be flying to this distination?\\n "); printf (" The maximum number of planes the airport can support is 10 \\n "); scanf ("%ld", &num); if ( num < 0 || num > 10) question = 3; else question = 4; plane_Cont = num; } break; case 3:{ num = 0; printf ("You did not enter a valid integer.\\n"); printf (" Enter a new integer \\n"); scanf ("%ld", &num); if ( num < 0 || num > 10) question = 3; else question = 4 ; plane_Cont = num; } break; } run_S = plane_Cont; } printf(" You have designated %d Planes and %d Runways.\\n\\n", plane_Cont ,lane_Cont); for (ux = 0 ; ux != plane_Cont ; ux++ ) { ARRAY_landing [ux] = ux + 1; ARRAY_lane [ux] = gx; gx = gx + 1 ; if ( gx > lane_Cont) { gx = 1; } } pthread_t threads[run_S]; for(t = 0; t< plane_Cont ; t++) { rx = pthread_create(&threads[t], 0, landingFunc, (void *)t); sleep(1); } for(t = 0; t< plane_Cont ; t++) { rc = pthread_create(&threads[t], 0, takeoffFunc, (void *)t); sleep(1); } pthread_exit(0); } void *landingFunc(void *ptr) { int landing = 0; while(landing != 5) { switch(landing) { case 0: { landing = 1; sleep(1); } break; pthread_mutex_lock(&lock); case 1: { long tid; tid = (long)ptr; printf(" Plane %d had been assigned to land on runway %d.\\n\\n",ARRAY_landing[tid],ARRAY_lane[tid]); landing = 2; } break; case 2: { long tid; tid = (long)ptr; printf(" Plane %d has touch down on runway %d.\\n\\n",ARRAY_landing[tid],ARRAY_lane[tid]); landing = 3; } break; case 3: { landing = 4; sleep(1); } break; case 4: { long tid; tid = (long)ptr; printf(" Gate %d has opened for plane %d.\\n\\n",ARRAY_lane[tid],ARRAY_landing[tid]); landing = 5; pthread_exit(0); } break; pthread_mutex_unlock(&lock); } } } void *takeoffFunc(void *ptr) { int takeoff = 0; while (takeoff != 5) { switch(takeoff) { case 0: { takeoff = 1; } break; pthread_mutex_lock(&lock); case 1: { long tid; tid = (long)ptr; printf(" Gate %d has opened for plane %d.\\n\\n ", ARRAY_lane[tid] ,ARRAY_landing[tid]); takeoff = 2; } break; case 2: { takeoff = 3; } break; case 3: { long tid; tid = (long)ptr; printf(" Plane number %d has taken off from Runway %d.\\n\\n ", ARRAY_landing[tid] ,ARRAY_lane[tid]); int x = rand()%50; if (x >= 40 ) printf(" Plane %d was almost in a collision!!!!!! Collision Avoided and flight is on track.\\n\\n",ARRAY_landing[tid]); pthread_exit(0); takeoff = 4; } break; case 4: { takeoff = 5; } break; } pthread_mutex_unlock(&lock); } }
1
#include <pthread.h> int VT_mc34704_SU_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_SU_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_test_SU(void) { int rv = TPASS, fd; int event = EVENT_FLT5; fd = open(MC34704_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC34704_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); if (VT_mc34704_subscribe(fd, event) != TPASS) { rv = TFAIL; } if (VT_mc34704_unsubscribe(fd, event) != TPASS) { rv = TFAIL; } pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); if (VT_mc34704_subscribe(fd, event) != TPASS) { rv = TFAIL; } if (VT_mc34704_subscribe(fd, event) != TPASS) { rv = TFAIL; } if (VT_mc34704_unsubscribe(fd, event) != TPASS) { rv = TFAIL; } if (VT_mc34704_unsubscribe(fd, event) != TPASS) { rv = TFAIL; } if (close(fd) < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to close file descriptor %d", fd); pthread_mutex_unlock(&mutex); return TFAIL; } return rv; }
0
#include <pthread.h> unsigned short itpf_gate(const unsigned short nnn, struct cp8_ctx *cp8) { unsigned char x, y; unsigned short next = 2; switch (nnn & 0xff) { case 0x07: pthread_mutex_lock(&cp8->mtx); cp8_vreg(cp8_asm_var(x, nnn), cp8) = cp8->dt; pthread_mutex_unlock(&cp8->mtx); break; case 0x0a: x = cp8_kbdhit(); if (x != 0xff) { cp8_vreg(cp8_asm_var(x, nnn), cp8) = x; } else { next = 0; } break; case 0x15: pthread_mutex_lock(&cp8->mtx); cp8->dt = cp8_vreg(cp8_asm_var(x, nnn), cp8); pthread_mutex_unlock(&cp8->mtx); break; case 0x18: pthread_mutex_lock(&cp8->mtx); cp8->st = cp8_vreg(cp8_asm_var(x, nnn), cp8); pthread_mutex_unlock(&cp8->mtx); break; case 0x1e: cp8->i += cp8_vreg(cp8_asm_var(x, nnn), cp8); break; case 0x29: cp8->i = cp8_vreg(cp8_asm_var(x, nnn), cp8) * 0x5; break; case 0x33: x = cp8_vreg(cp8_asm_var(x, nnn), cp8); y = x / 100; cp8_memset(cp8->i, y); x = x - (y * 100); y = x / 10; cp8_memset(cp8->i + 1, y); y = x - (y * 10); cp8_memset(cp8->i + 2, y); break; case 0x55: for (x = 0; x <= cp8_asm_var(x, nnn); x++) { cp8_memset(cp8->i + x, cp8_vreg(x, cp8)); } break; case 0x65: for (x = 0; x <= cp8_asm_var(x, nnn); x++) { cp8_vreg(x, cp8) = cp8_memget(cp8->i + x); } break; } return (cp8->pc + next); }
1
#include <pthread.h> struct readerArgs { int fd; size_t number; }; ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset); void getCurrentTime(char *str, size_t maxLength); void* readerFunc(readerArgs *args); void* writerFunc(void *fd); void clearResources(int fd); pthread_mutex_t fileMutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t stdoutMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; int main() { int fd = open("File", O_CREAT | O_RDWR | O_TRUNC, 00777); pthread_t readers[10], writer; readerArgs args[10]; if (fd == -1) { printf("Error: %s", strerror(errno)); clearResources(fd); return -1; } errno = pthread_create(&writer, 0, writerFunc, &fd); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } for (int i = 0; i < 10; i++) { args[i].fd = fd; args[i].number = i + 1; errno = pthread_create(readers + i, 0, (void* (*)(void*)) readerFunc, args + i); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } } pthread_join(writer, 0); for (int i = 0; i < 10; i++) pthread_join(readers[i], 0); clearResources(fd); return 0; } ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset) { char buf[maxLength]; ssize_t retVal = pread(fd, buf, maxLength, offset); size_t newLinePos; if (retVal == -1) return -1; newLinePos = strcspn(buf, "\\n"); if (newLinePos == strlen(buf)) return 0; newLinePos++; strncpy(str, buf, newLinePos); return newLinePos; } void* readerFunc(readerArgs *args) { char str[100]; int fd = args->fd; ssize_t number = args->number, bytesCount; off_t offset = 0; do { pthread_mutex_lock(&fileMutex); while ((bytesCount = pgetLine(fd, str, 100, offset)) <= 0) { pthread_mutex_lock(&stdoutMutex); printf("Thread%lu wait for data...\\n", number); pthread_mutex_unlock(&stdoutMutex); pthread_cond_wait(&condition, &fileMutex); } pthread_mutex_unlock(&fileMutex); offset += bytesCount; if (strncmp(str, "END", 3) == 0) break; pthread_mutex_lock(&stdoutMutex); printf("Thread%lu %s", number, str); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); if (offset > 100*10) return 0; } while (1); pthread_mutex_lock(&stdoutMutex); printf("Thread%lu END\\n", number); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); return 0; } void* writerFunc(void *fd) { int _fd = *(int*)fd; char str[100], timeStr[50]; for (int i = 1; i < 10 + 1; i++) { getCurrentTime(timeStr, 50); sprintf(str, "Line %d Current time %s\\n", i, timeStr); pthread_mutex_lock(&fileMutex); write(_fd, str, strlen(str)); pthread_cond_broadcast(&condition); pthread_mutex_unlock(&fileMutex); } pthread_mutex_lock(&fileMutex); write(_fd, "END\\n", 4); pthread_cond_broadcast(&condition); pthread_mutex_unlock(&fileMutex); return 0; } void getCurrentTime(char *str, size_t maxLength) { static struct timeval timer; gettimeofday(&timer, 0); strftime(str, maxLength, "%T.", localtime(&timer.tv_sec)); sprintf(str + strlen(str), "%ld", timer.tv_usec); } void clearResources(int fd) { close(fd); pthread_mutex_destroy(&fileMutex); pthread_mutex_destroy(&stdoutMutex); }
0
#include <pthread.h> extern char reducer_pool[5*500]; extern pthread_mutex_t reducer_lock; char summarizer_pool[5*500]; int letter_table[256]={0}; pthread_mutex_t table_lock=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t summarizer_lock=PTHREAD_MUTEX_INITIALIZER; sem_t sem_read2,sem_write2; extern sem_t sem_read1,sem_write1,sem_read3,sem_read4,sem_write3,sem_write4;; extern int doneReading; extern pthread_mutex_t gen_read; extern int no_of_mapper_thread,no_of_reducer_thread,no_of_summarizer_thread; extern pthread_t mapper_thread[1000]; extern pthread_t reducer_thread[1000]; extern pthread_t summarizer_thread[1000]; extern pthread_t letter_thread; extern pthread_t write_thread; extern pthread_t file_reader; char str[500]; int count; struct node *next; }node; pthread_mutex_t node_lock=PTHREAD_MUTEX_INITIALIZER; node node_list[256]={0}; int doneReading2=0,doneReading3=0; extern int doneReading1; void* reducer(void *a) { char buffer[5*500]; char *str,prev_char='%'; char *tmp,*word_list[500]; int done; while(1) { int ind; sem_wait(&sem_write1); pthread_mutex_lock(&gen_read); done=doneReading1; if(done){ doneReading2=1; for(ind=0;ind<no_of_mapper_thread-no_of_reducer_thread;++ind) sem_post(&sem_read1); sem_post(&sem_write2); pthread_mutex_unlock(&gen_read); pthread_exit(0); } else { pthread_mutex_unlock(&gen_read); } sem_wait(&sem_read2); int i=0,i1=0,index=0,ttl_wrd=0,size=0; pthread_mutex_lock(&reducer_lock); while(reducer_pool[i1]) { buffer[i++]=reducer_pool[i1++]; } pthread_mutex_unlock(&reducer_lock); tmp=strtok(buffer," "); while(tmp) { word_list[ttl_wrd++]=tmp; tmp=strtok(0," "); } pthread_mutex_lock(&node_lock); while(index<ttl_wrd){ str=strtok(word_list[index++],","); str+=1; if(prev_char!='%' && str[0]!=prev_char){ node *tmp=&node_list[prev_char]; node *prev_tmp=tmp; tmp=tmp->next; prev_tmp->next=0; pthread_mutex_lock(&summarizer_lock); while(tmp){ sprintf(summarizer_pool+size,"(%s,%d)\\n",tmp->str,tmp->count); prev_tmp=tmp; size+=strlen(tmp->str)+5; tmp=tmp->next; prev_tmp->next=0; } pthread_mutex_unlock(&summarizer_lock); } node *tmp=&node_list[str[0]]; node *prev_tmp=tmp; tmp=tmp->next; while(tmp){ if(!strcmp(tmp->str,str)) { tmp->count++; break; } prev_tmp=tmp; tmp=tmp->next; } if(!prev_tmp->next) { node *new_node=(node*)calloc(1,sizeof(node)); strcpy(new_node->str,str); new_node->count=1; prev_tmp->next=new_node; } prev_char=str[0]; } if(prev_char!='%'){ node *tmp=&node_list[prev_char]; node *prev_tmp=tmp; tmp=tmp->next; prev_tmp->next=0; pthread_mutex_lock(&summarizer_lock); while(tmp){ sprintf(summarizer_pool+size,"(%s,%d)\\n",tmp->str,tmp->count); size+=strlen(tmp->str)+5; prev_tmp=tmp; tmp=tmp->next; prev_tmp->next=0; } pthread_mutex_unlock(&summarizer_lock); } pthread_mutex_unlock(&node_lock); sem_post(&sem_write3); sem_wait(&sem_read3); sem_post(&sem_write2); sem_post(&sem_read1); memset(buffer,0,5*500); } return 0; } void* wordCountWriter(void *a){ int done; while(1) { sem_wait(&sem_write2); pthread_mutex_lock(&gen_read); done=doneReading2; if(done){ pthread_mutex_unlock(&gen_read); FILE* fp=fopen("./wordCount.txt","a+"); if(!fp) { printf("Error in opening wordCount file...Exiting\\n"); exit(1); } pthread_mutex_lock(&summarizer_lock); int i=0,ind; while(summarizer_pool[i]) { fputc(summarizer_pool[i],fp); summarizer_pool[i]='\\0'; i++; } pthread_mutex_unlock(&summarizer_lock); fclose(fp); sem_post(&sem_read2); usleep(400); for(ind=0;ind<no_of_mapper_thread;++ind) pthread_cancel(mapper_thread[ind]); for(ind=0;ind<no_of_reducer_thread;++ind) pthread_cancel(reducer_thread[ind]); for(ind=0;ind<no_of_summarizer_thread;++ind) pthread_cancel(summarizer_thread[ind]); pthread_cancel(letter_thread); pthread_exit(0); } else { pthread_mutex_unlock(&gen_read); } FILE* fp=fopen("./wordCount.txt","a+"); if(!fp) { printf("Error in opening wordCount file...Exiting\\n"); exit(1); } pthread_mutex_lock(&summarizer_lock); int i=0; while(summarizer_pool[i]) { fputc(summarizer_pool[i],fp); summarizer_pool[i]='\\0'; i++; } pthread_mutex_unlock(&summarizer_lock); fclose(fp); sem_post(&sem_read2); } return 0; } void* summarizer(void *a) { char *str,buffer[5*500]; while(1) { int count=0,i=0,i1=0,done,ind=0; sem_wait(&sem_write3); pthread_mutex_lock(&gen_read); done=doneReading2; if(done) { doneReading3=1; sem_post(&sem_write4); sem_post(&sem_read3); pthread_mutex_unlock(&gen_read); pthread_exit(0); } else { pthread_mutex_unlock(&gen_read); } sem_wait(&sem_read4); pthread_mutex_lock(&summarizer_lock); while(summarizer_pool[i]) { buffer[i1++]=summarizer_pool[i++]; } buffer[i1]='\\0'; pthread_mutex_unlock(&summarizer_lock); str=strtok(buffer,"\\n"); char ch; while(str){ if(str){count+=(str[strlen(str)-2]-'0');} str+=1; ch=str[0]; str=strtok(0,"\\n"); } i=0; pthread_mutex_lock(&table_lock); letter_table[ch]+=count; pthread_mutex_unlock(&table_lock); sem_post(&sem_write4); sem_post(&sem_read3); } } void* write_letter(void *a) { int i,done; while(1) { sem_wait(&sem_write4); pthread_mutex_lock(&gen_read); done=doneReading3; if(done) { pthread_mutex_unlock(&gen_read); FILE *fs=fopen("./letterCount.txt","w+"); if(!fs) { printf("File to write lettercount could not be opened\\n"); sem_post(&sem_read4); pthread_exit(0); } pthread_mutex_lock(&table_lock); for(i=0;i<256;++i) { if(letter_table[i]) { fprintf(fs,"(%c,%d)\\n",i,letter_table[i]); } } pthread_mutex_unlock(&table_lock); fclose(fs); sem_post(&sem_read4); } else { pthread_mutex_unlock(&gen_read); } FILE *fs=fopen("./letterCount.txt","w+"); if(!fs) { printf("File to write lettercount could not be opened\\n"); sem_post(&sem_read4); pthread_exit(0); } pthread_mutex_lock(&table_lock); for(i=0;i<256;++i) { if(letter_table[i]) { fprintf(fs,"(%c,%d)\\n",i,letter_table[i]); } } pthread_mutex_unlock(&table_lock); fclose(fs); sem_post(&sem_read4); } }
1
#include <pthread.h> pthread_mutex_t sharedMutex; pthread_cond_t notEmptyCond; int isEmpty = 1; int isDone = 0; int numOfThreads = 0; int rc = 0; struct _linked_list* lst; int value; struct _list_node* next; struct _list_node* prev; }list_node; list_node* head; list_node* tail; int nOfElems; }linked_list; int initList(){ lst = (linked_list*)malloc(sizeof(linked_list)); lst->head = 0; lst->tail = 0; lst->nOfElems = 0; if (rc) { printf("Server: Failed list init, rc=%d.\\n", rc); return(1); } return 0; } list_node* initNode(int skfd){ list_node* node = (list_node*)malloc(sizeof(list_node)); node->value = skfd; node->next = 0; node->prev = 0; } int enqueue(list_node* node){ rc = pthread_mutex_lock(&sharedMutex); if (lst->nOfElems == 0){ lst->head = node; lst->tail = node; lst->nOfElems++; isEmpty = 0; } else { list_node* prev = lst->tail; prev->next = node; lst->tail = node; node->prev = prev; lst->nOfElems++; } rc = pthread_cond_signal(&notEmptyCond); rc = pthread_mutex_unlock(&sharedMutex); return 0; } list_node* dequeue(){ list_node* node = 0; rc = pthread_mutex_lock(&sharedMutex); while ( isEmpty && !isDone){ rc = pthread_cond_wait(&notEmptyCond, &sharedMutex); if (rc) { printf("Socket Handler Thread %u: condwait failed, rc=%d\\n", (unsigned int)pthread_self(), rc); pthread_mutex_unlock(&sharedMutex); exit(1); } } if (!isEmpty){ list_node* node = lst->tail; lst->tail = node->prev; lst->tail->next = 0; lst->nOfElems--; isEmpty = lst->nOfElems == 0 ? 1 : 0; } rc = pthread_mutex_unlock(&sharedMutex); return node; } void *handleSocket(void *parm){ list_node* node; int decfd; char recvBuff[5]; int notReaden = sizeof(recvBuff); int totalRead = 0; int nread = 0; int isClosed = 0; int res; while (!isDone || !isEmpty){ node = dequeue(); while (!isClosed && node!= 0){ decfd = node->value; while (notReaden > 0){ nread = read(decfd, recvBuff + totalRead, notReaden); if (nread < 1){ close(decfd); isClosed = 1; } totalRead += nread; notReaden -= nread; } if (totalRead == 5){ if (atoi(recvBuff) == 0) res = setos_add(ntohl(*((uint32_t *)(recvBuff + 1))),0); else if (atoi(recvBuff) == 1) res = setos_remove(ntohl(*((uint32_t *)(recvBuff + 1))), 0); else res = setos_contains(ntohl(*((uint32_t *)(recvBuff + 1)))); write(decfd, &res, 1); printf("write:Thread %u: data = %d, op = %d, res =%d\\n", (unsigned int)pthread_self(), ntohl(*((uint32_t *)(recvBuff + 1))), atoi(recvBuff), res ); } else{ printf("Socket Handler Thread %u: read fail,\\n", (unsigned int)pthread_self()); } } isClosed = 0; } return 0; } static void handler(int signum){ if (signum == SIGINT) isDone = 1; } int main(int argc, char **argv){ int i; int listenfd = 0; int connfd = 0; int numOfThreads = atoi(argv[1]); struct sockaddr_in serv_addr; char sendBuff = 0; pthread_t* thread; struct sigaction sa; sa.sa_handler = handler; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); sigaction(SIGPIPE, &sa, 0); thread = (pthread_t*)malloc(numOfThreads*sizeof(pthread_t)); rc = pthread_mutex_init(&sharedMutex ,0); rc = pthread_cond_init(&notEmptyCond, 0); initList(); setos_init(); for (i = 0; i <numOfThreads; i++) { rc = pthread_create(&thread[i], 0, handleSocket, 0); } sleep(2); listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[2])); if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))){ printf("\\n Error : Bind Failed. %s \\n", strerror(errno)); return 1; } if (listen(listenfd, 10)){ printf("\\n Error : Listen Failed. %s \\n", strerror(errno)); return 1; } while (!isDone) { connfd = accept(listenfd, (struct sockaddr*)0, 0); printf("hrtr\\n"); if (isDone) break; if (connfd<0){ printf("\\n Error : Accept Failed. %s \\n", strerror(errno)); } enqueue(initNode(connfd)); } for (i = 0; i <numOfThreads; i++) { rc = pthread_mutex_lock(&sharedMutex); assert(!rc); pthread_cond_signal(&notEmptyCond); rc = pthread_mutex_unlock(&sharedMutex); assert(!rc); } sleep(2); printf("Clean up\\n"); pthread_mutex_destroy(&sharedMutex); pthread_cond_destroy(&notEmptyCond); free(thread); setos_free(); printf("Main completed\\n"); return 0; }
0
#include <pthread.h> int row1, col1, row2, col2, currentRow = 0, currentCell = 0,flag, Matrix1[5005][5005], Matrix2[5005][5005], Result_Mat[5005][5005]; pthread_t * threads; int numberOfThreads; pthread_mutex_t mutex_Cell = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER; void prmat() { int i, j; printf("\\n MAtrix-1:\\n"); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) { printf("%d ", Matrix1[i][j]); } printf("\\n"); } printf("\\nMAtrix-2:\\n"); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) { printf("%d ", Matrix2[i][j]); } printf("\\n"); } printf("\\nFinal MAtrix:\\n"); for (i = 0; i < row1; i++) { for (j = 0; j < col2; j++) { printf("%d ", Result_Mat[i][j]); } printf("\\n"); } } void* thread_func(int Id) { int i, j, myCell, cnt; while (1) { pthread_mutex_lock(&mutex_Cell); if (currentCell >= row1*col2) { pthread_mutex_unlock(&mutex_Cell); if (Id == 0) return; pthread_exit(0); } myCell = currentCell; currentCell++; pthread_mutex_unlock(&mutex_Cell); i = myCell/col2, j = myCell%col2; if(i==row1-1 && j==col1-1){flag=1;} for (cnt = 0; cnt < col1; cnt++) Result_Mat[i][j] += Matrix1[i][cnt] * Matrix2[cnt][j]; } } int main() { int i, j, k; system("clear"); freopen("input.txt", "r", stdin); scanf("%d%d",&row1,&col1); scanf("%d%d",&row2,&col2); if (col1 != row2) { printf("col1 and row2 are not equal can't multiply.\\n"); fclose(stdin); return 0; } scanf("%d",&numberOfThreads); printf("Total threads: %d\\n\\n", numberOfThreads); for (i = 0; i < row1; i++) { for (j = 0; j < col1; j++) scanf("%d", &Matrix1[i][j]); } printf("\\n"); for (i = 0; i < row2; i++) { for (j = 0; j < col2; j++) scanf("%d", &Matrix2[i][j]); } struct timespec st, en; for (i = 0; i < row1; i++) for (j = 0; j < col2; j++) Result_Mat[i][j] = 0; threads = (pthread_t *) malloc(sizeof(pthread_t) * numberOfThreads); currentRow = 0, currentCell = 0,flag=0; clock_gettime(CLOCK_MONOTONIC, &st); for (i=1; i<numberOfThreads; i++) { if(flag==0) { printf("need more thread\\n"); pthread_create(&threads[i], 0, (void *(*) (void *))thread_func, (void *) (i+1)); } else{ printf("we are done. no more threads required.\\n"); } } for (i = 0; i < numberOfThreads; i++) { pthread_join(threads[i], 0); } clock_gettime(CLOCK_MONOTONIC, &en); printf("multithreading: %f secs.\\n", en.tv_sec - st.tv_sec + (en.tv_nsec - st.tv_nsec)/1.0e9); for (i = 0; i < row1; i++) for (j = 0; j < col2; j++) Result_Mat[i][j] = 0; clock_gettime(CLOCK_MONOTONIC, &st); for(i=0; i<row1; i++) { for(j=0; j<col2; j++) { for(k=0; k<col1; k++) { Result_Mat[i][j] += Matrix1[i][k] * Matrix2[k][j]; } } } clock_gettime(CLOCK_MONOTONIC, &en); printf("without multithreading: %f secs.\\n", en.tv_sec - st.tv_sec + (en.tv_nsec-st.tv_nsec)/1.0e9); prmat(); fclose(stdin); fclose(stdout); return 0; }
1
#include <pthread.h> int seqNo; char legend[20]; } item_t; pthread_mutex_t mutex; pthread_cond_t notFull; pthread_cond_t notEmpty; int cnt; int first, last; item_t* buf[15]; } buffer; int tot = 0; buffer buf = { .first = 0, .last = 15 -1, .cnt = 0 }; void store(int j, buffer *pb){ item_t* item= malloc(sizeof(item_t)); item->seqNo = j; sprintf(item->legend, "%u", pthread_self()); pb->buf[((pb->first)+(pb->cnt))%15] = item; pb->cnt = (pb->cnt)+1; } int retrieve(buffer *pb){ item_t* item = pb->buf[pb->first]; int j = item->seqNo; free(item); pb->cnt = (pb->cnt)-1; pb->first = ((pb->first)+1)%15; pb->last = ((pb->last)+1)%15; return j; } void* producer(void * v){ int j; for (j=0; j<100; j++){ pthread_mutex_lock(&buf.mutex); while (buf.cnt == 15){ pthread_cond_wait(&buf.notFull, &buf.mutex); } store(j, &buf); pthread_cond_signal(&buf.notEmpty); pthread_mutex_unlock(&buf.mutex); printf ("producer produce %d\\n", j); usleep(rand()%11); } } void* consumer(void * v){ item_t* k; int j=0; while (j< 100 -1){ pthread_mutex_lock(&buf.mutex); while (buf.cnt==0){ pthread_cond_wait(&buf.notEmpty, &buf.mutex); } j = retrieve(&buf); pthread_cond_signal(&buf.notFull); pthread_mutex_unlock(&buf.mutex); tot = tot + j; usleep(rand()%11); } } int main(int argc, char **argv){ pthread_t th[16]; int i; while (1){ pthread_mutex_init(&buf.mutex, 0); pthread_cond_init (&buf.notEmpty, 0); pthread_cond_init (&buf.notFull, 0); for (i = 0; i < 16/2; i++){ pthread_create(&th[i], 0, consumer, 0); } for (i = 16/2; i < 16; i++){ pthread_create(&th[i], 0, producer, 0); } for (i = 0; i < 16; i++){ pthread_join(th[i], 0); } printf ("valeur théorique de tot = %d\\n", ((100*(100 -1))/2)*16/2); printf ("valeur réelle de tot = %d\\n", tot); tot = 0; sleep(3); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_t buyer[1005]; int sum = 0 ; int buy = 0, nobuy = 0; void* buyphone(){ pthread_mutex_lock(&mutex) ; if( sum >= 800 ) { printf("I can't buy\\n"); nobuy ++ ; pthread_mutex_unlock(&mutex); pthread_exit(0); } sum ++ ; buy ++ ; printf("I buyed one\\n") ; pthread_mutex_unlock(&mutex) ; pthread_exit(0); } int main(){ pthread_mutex_init(&mutex,0); void* res; for(int i = 0;i < 1000;i ++) { int res = pthread_create(&buyer[i], 0, &buyphone, 0) ; if( res ){ perror("Create error:") ; continue; } pthread_join(buyer[i], &res) ; } printf("buyed:%d\\tnobuy:%d\\n", buy, nobuy) ; pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> char** theArray; pthread_mutex_t mutex; pthread_mutex_t fileMutex; int count; double times[MAX_THREADS]; void WriteFile(){ FILE* fp; fp = fopen("results/mutex_results.txt", "a"); if (fp == 0) { fp = fopen("results/mutex_results.txt", "w+"); } for(int i = 0; i < MAX_THREADS; i++) { fprintf(fp, "%lf\\n", times[i]); } count = 0; fclose(fp); } void* ServerDecide(void *args) { int clientFileDescriptor = (intptr_t)args; double start; double end; char* stringToWrite; char clientString[MAX_STRING_LENGTH]; char readString[MAX_STRING_LENGTH]; read(clientFileDescriptor, clientString, MAX_STRING_LENGTH); int element = strtol(clientString, &stringToWrite, 10); if(strlen(stringToWrite) == 0) { GET_TIME(start); pthread_mutex_lock(&mutex); strncpy(readString, theArray[element], MAX_STRING_LENGTH); printf("R \\t ELEMENT: %d \\t STRING: %s\\n", element, readString); pthread_mutex_unlock(&mutex); GET_TIME(end); write(clientFileDescriptor, readString, MAX_STRING_LENGTH); } else { GET_TIME(start); pthread_mutex_lock(&mutex); snprintf(theArray[element], MAX_STRING_LENGTH, "%s", stringToWrite); printf("W \\t ELEMENT: %d \\t STRING: %s\\n", element, stringToWrite); pthread_mutex_unlock(&mutex); GET_TIME(end); } pthread_mutex_lock(&fileMutex); int index = count++; pthread_mutex_unlock(&fileMutex); times[index] = (end - start); close(clientFileDescriptor); pthread_exit(0); } int main(int argc, char* argv[]) { if(argc != 3) { printf("please use the format ./server <port> <arraySize>"); return 1; } int port = atoi(argv[1]); int arraySize = atoi(argv[2]); theArray = (char**)malloc(sizeof(char*) * arraySize); for(int i = 0; i < arraySize; i++) { theArray[i] = (char*)malloc(sizeof(char) * MAX_STRING_LENGTH); } for(int i = 0; i < arraySize; i++) { snprintf(theArray[i], MAX_STRING_LENGTH, "String %d: the initial value", i); } pthread_mutex_init(&mutex, 0); pthread_mutex_init(&fileMutex, 0); pthread_t t[MAX_THREADS]; struct sockaddr_in sock_var; sock_var.sin_addr.s_addr = inet_addr("127.0.0.1"); sock_var.sin_port = port; sock_var.sin_family = AF_INET; int clientFileDescriptor; int serverFileDescriptor = socket(AF_INET,SOCK_STREAM, 0); if(bind(serverFileDescriptor, (struct sockaddr*)&sock_var,sizeof(sock_var)) >= 0) { listen(serverFileDescriptor,2000); while(1) { for(int i = 0; i < MAX_THREADS; i++) { clientFileDescriptor = accept(serverFileDescriptor, 0, 0); pthread_create(&t[i], 0, ServerDecide, (void*)(intptr_t)clientFileDescriptor); } for(int i = 0; i < MAX_THREADS; i++) { pthread_join(t[i], 0); } WriteFile(); } close(serverFileDescriptor); } else { printf("Socket creation failed\\n"); } return 0; }
0
#include <pthread.h> int upper(char *path) { FILE* fp1, *fp2; int c = 1; fp1= fopen (path, "r"); fp2= fopen (path, "r+"); if ((fp1== 0) || (fp2== 0)) { perror (path); return errno; } while (c !=EOF) { c=fgetc(fp1); if (c!=EOF) fputc(toupper(c),fp2); } fclose (fp1); fclose (fp2); return 0; } int m; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void routine(void* arg) { printf("%ld : created\\n", pthread_self()); int* fd = (int*)arg; char buf[255]; int check = 0; while (m > 0) { pthread_mutex_lock(&mutex); printf("%ld : I'm in\\n", pthread_self()); read(*fd,buf,sizeof(buf)); m--; printf("%ld : I'm out\\n", pthread_self()); pthread_mutex_unlock(&mutex); if (buf[0] == '\\n') continue; if ((check = check |upper(buf)) == -1) { perror("upper"); break; } } pthread_exit((void*)check); } int main(int argc, char** argv) { int* status; char buf[255]; pthread_t* threads; int i; int readfd, writefd; int ret = 0; int n = argc-2; const char* filename = "pipe_"; m = atoi(argv[1]); status = (int*)malloc(sizeof(int) * n); threads= (pthread_t*)malloc(sizeof(pthread_t) * n); if(mkfifo(filename,S_IRUSR|S_IWUSR) == -1 && (writefd =open(filename, O_WRONLY)) == -1) { perror("pipe creation/access"); exit(errno); } if((writefd = open(filename,O_WRONLY)) == -1) { perror("pipe creation/access"); exit(errno); } printf("opening pipe...\\n"); if((readfd = open(filename, O_RDONLY)) == -1) { perror("pipe creation/access"); exit(errno); } printf("preparing filenames...\\n"); for (i=0; i<n; i++) { strcpy(buf,argv[i+2]); buf[strlen(argv[i+2])] = '\\0'; buf[strlen(argv[i+2])+1] = '\\n'; printf("ready to send %s\\n",buf); write(writefd,buf,255); } printf("creating threads...\\n"); for (i=0; i<m; i++) { pthread_create(&threads[i],0, routine, (void*)&readfd); } printf("waiting\\n"); for (i=0; i<m; i++) { pthread_join(threads[i],(void*)&status[i]); if(status[i] == 0) ret++; } close(readfd); close(writefd); unlink(filename); return ret; }
1
#include <pthread.h> void handler_SIGINT(int signum); void rstrip_newline(char * aStr); struct serverstat_t { unsigned mTotalAccessSec; unsigned mTotalRequests; }; struct serverstat_t gServerStats; pthread_mutex_t gReportingMutex; int main(int argc, char * argv[]) { srand(time(0)); signal(SIGINT, handler_SIGINT); pthread_mutex_init(&gReportingMutex, 0); while(1) { char * lFilename = malloc((1024)); printf("Enter a filename: "); fgets(lFilename, (1024), stdin); rstrip_newline(lFilename); pthread_t lThread; if(0 != pthread_create(&lThread, 0, worker, lFilename)) { fprintf(stderr, "Error creating thread.\\n"); return -1; } } return 0; } void handler_SIGINT(int signum) { printf("\\n\\nTotal requests: %u\\n", gServerStats.mTotalRequests); printf("Average file access time: %.2fs\\n", (float)(gServerStats.mTotalAccessSec) / (float)(gServerStats.mTotalRequests)); printf("Terminating...\\n"); exit(0); } void rstrip_newline(char * aStr) { while(0 != *aStr) { aStr++; if('\\n' == *aStr) { *aStr = '\\0'; break; } } } void report(unsigned int aFileAccessTime) { pthread_mutex_lock(&gReportingMutex); gServerStats.mTotalAccessSec += aFileAccessTime; (gServerStats.mTotalRequests)++; pthread_mutex_unlock(&gReportingMutex); }
0
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cv1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cv2 = PTHREAD_COND_INITIALIZER; pthread_mutex_t ready_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ready_cv = PTHREAD_COND_INITIALIZER; int child_ready, child_done, parent_done; void* waitandsignal() { pthread_mutex_lock(&lock1); child_ready = 1; pthread_cond_signal(&cv1); while(1) { while (!parent_done) pthread_cond_wait(&cv1, &lock1); parent_done = 0; pthread_mutex_lock(&lock2); child_done = 1; pthread_cond_signal(&cv2); pthread_mutex_unlock(&lock2); } return 0; } int main(int argc, char** argv) { double* results = (double*)malloc(sizeof(double) * 10000000); int i; pthread_t p; child_ready = 0; parent_done = 0; pthread_mutex_lock(&lock2); pthread_mutex_lock(&lock1); int success = pthread_create(&p, 0, &waitandsignal, 0); if (success != 0){ fprintf(stderr,"Thread not created\\n"); exit(0); } while (child_ready == 0) pthread_cond_wait(&cv1, &lock1); for (i = 0; i < 10000000; i++) { child_done = 0; double start = TIMER_START; parent_done = 1; pthread_cond_signal(&cv1); pthread_mutex_unlock(&lock1); while (!child_done) pthread_cond_wait(&cv2, &lock2); double stop = TIMER_STOP; results[i] = stop - start; pthread_mutex_lock(&lock1); } array_to_csv(results, 10000000, "cvtest.csv"); return(0); }
1
#include <pthread.h> long cember = 0; long nokta_sayisi; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *runner(void *arg) { long runner_ici = 0; unsigned int rand_state = rand(); long i; for (i = 0; i < nokta_sayisi; i++) { double z; double x = rand_r(&rand_state) / ((double) 32767 + 1); double y = rand_r(&rand_state) / ((double) 32767 + 1); z = x * x + y * y; if (z <= 1) { runner_ici++; } } pthread_mutex_lock(&mutex); cember = runner_ici + cember; pthread_mutex_unlock(&mutex); } int main(int argc, const char *argv[]) { if (argc != 3) { fprintf(stderr, " <iterasyon sayisi> <thread sayisi>\\n"); exit(1); } long toplam_nokta = atol(argv[1]); int thread_say = atoi(argv[2]); nokta_sayisi = (toplam_nokta / thread_say); time_t start = time(0); srand((unsigned) time(0)); pthread_t *threads = malloc(thread_say * sizeof(pthread_t)); pthread_attr_t attr; pthread_attr_init(&attr); int i; for (i = 0; i < thread_say; i++) { pthread_create(&threads[i], &attr, runner, (void *) 0); } for (i = 0; i < thread_say; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); free(threads); printf("Pi: %f\\n", (4. * (double) cember) / ((double) nokta_sayisi * thread_say)); return 0; }
0
#include <pthread.h> int num = 0; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; void *add(void *arg) { int i = 0,tmp; for(; i < 500; i++){ pthread_mutex_lock(&mylock); tmp = num + 1; num = tmp; printf("+1, result is:%d\\n",num); pthread_mutex_unlock(&mylock); } } void *sub(void *arg) { int tmp; for(int i = 0; i < 500; i++){ pthread_mutex_lock(&mylock); tmp = num - 1; num = tmp; printf("-1,result is:%d\\n",num); pthread_mutex_unlock(&mylock); } } int main(int argc, char *argv[]){ pthread_t tid1,tid2; int err; void *tret; err = pthread_create(&tid1,0,add,0); if(err != 0){ printf("pthread_create error : %s\\n",strerror(err)); exit(-1); } err = pthread_create(&tid2,0,sub,0); if(err != 0 ){ printf("pthread_create error : %s\\n",strerror(err)); exit(-1); } err = pthread_join(tid1, &tret); if(err != 0){ printf("pthread_join error"); exit(-1); } printf("pthread1 exit code : %d\\n",tret); err = pthread_join(tid2, &tret); if(err != 0){ printf("pthread_join error"); exit(-1); } printf("pthread2 exit code: %d\\n",tret); return 0; }
1
#include <pthread.h> unsigned char onebyte[4096]; } BigMEMBlock; unsigned long long numblocks = (51ULL * 1024) * 1024 * 1024 / sizeof(BigMEMBlock); int numworkers = 1; int runtime = 30; int prepare = 5; size_t MEMBLOCKSIZE = sizeof(BigMEMBlock); BigMEMBlock* mfd; pthread_t *tid; pthread_mutex_t filelock; FILE* logfd; int fd; pthread_t timer_td; int shouldend = 0; int background = 0; int record = 0; long readmmap() { int idx = rand() % numblocks; struct timespec begin, end; long timediff; sleep(1); return 0; int ret; BigMEMBlock *source = ((BigMEMBlock* )mfd) + idx; BigMEMBlock tmp; clock_gettime(CLOCK_MONOTONIC, &begin); memcpy(&tmp, source, MEMBLOCKSIZE); clock_gettime(CLOCK_MONOTONIC, &end); timediff = (end.tv_sec - begin.tv_sec) * 1000000000 + (end.tv_nsec - begin.tv_nsec); if (ret < 1) { timediff = -1000000; } return timediff; } void flushlog(long *timerecords, int size) { int i = 0; if (background) { return; } pthread_mutex_lock(&filelock); for (i = 0; i < size; i++) { fprintf(logfd, "%ld\\n", timerecords[i]); } pthread_mutex_unlock(&filelock); } void *dowork() { long timerecords[10000], timediff; int timeidx = 0; printf("Child Pid: %ld\\n", syscall(SYS_gettid)); while(!shouldend) { timediff = readmmap(); if (record && !background && timeidx < 10000) { timerecords[timeidx] = timediff; timeidx ++; } if (record && !background && timeidx == 10000) { flushlog(timerecords, 10000); timeidx = 0; } } if (record && !background && timeidx != 0) { flushlog(timerecords, timeidx); } return 0; } void *timerend() { int i; for (i = 0; background || i < prepare; i++) { if (!background) { printf("Prepare: %d/%d \\r", i, prepare); fflush(stdout); } sleep(1); } record = 1; for (i = 0; background || i < runtime; i++) { if (!background) { printf("Progress: %d/%d \\r", i, runtime); } fflush(stdout); sleep(1); } shouldend = 1; return 0; } int main(int argc, char** argv) { int i; char *filenum; char filename[100]; unsigned long long length; srand((unsigned) time(0)); tid = malloc(numworkers * sizeof(pthread_t)); printf("Main Pid: %ld\\n", syscall(SYS_gettid)); sleep(10); if (argc > 1) { filenum = argv[1]; if (argc > 2) { background = 1; runtime += 5; } } mfd = (BigMEMBlock *)malloc(numblocks*sizeof(BigMEMBlock)); srand((unsigned) time(0)); for (i = 0; i < numblocks; i ++) { memset(&mfd[i], rand()%256, sizeof(BigMEMBlock)); } if (!background) { logfd = fopen("outputs/memaccess.log", "w"); } pthread_mutex_init(&filelock, 0); for(i = 0; i < numworkers; i ++) { pthread_create(&tid[i], 0, dowork, 0); } pthread_create(&timer_td, 0, timerend, 0); pthread_join(timer_td, 0); for (i = 0; i < numworkers; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&filelock); if (!background) { fclose(logfd); } }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo * f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return (0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return (fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return (fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> void* funProd(void *arg); void* funKons(void *arg); struct bufCykl { int dane[16]; int we; int wy; int licznik; }; int odczyt(struct bufCykl *buf); void zapis(struct bufCykl *buf, int wartosc); pthread_mutex_t semafor = PTHREAD_MUTEX_INITIALIZER; int main() { struct bufCykl mojBufor; pthread_t producent; pthread_t konsument; mojBufor.we = mojBufor.wy = mojBufor.licznik = 0; pthread_create(&producent, 0, funProd, &mojBufor); pthread_create(&konsument, 0, funKons, &mojBufor); pthread_join(producent, 0); pthread_join(konsument, 0); return 0; } void* funProd(void *arg) { int i; struct bufCykl *buf = (struct bufCykl *) arg; for (i=0; i<20; i++) { zapis(buf, i); sleep(1); } } void* funKons(void *arg) { int i; struct bufCykl *buf = (struct bufCykl *) arg; for (i=0; i<20; i++) { int x = odczyt(buf); printf("x=%d\\n", x); } } int odczyt(struct bufCykl *buf) { int wynik; int odczytano = 0; do { pthread_mutex_lock (&semafor); if (buf->licznik > 0) { wynik = buf->dane[buf->wy]; buf->licznik--; buf->wy++; buf->wy %= 16; odczytano = 1; } pthread_mutex_unlock (&semafor); sleep(1); } while (odczytano == 0); return wynik; } void zapis(struct bufCykl *buf, int wartosc) { int zapisano = 0; do { pthread_mutex_lock (&semafor); if (buf->licznik < 16) { buf->dane[buf->we] = wartosc; buf->licznik++; buf->we++; buf->we %= 16; zapisano = 1; } pthread_mutex_unlock (&semafor); sleep(1); } while(zapisano == 0); }
0
#include <pthread.h> void* thr_func(void* arg); static int globvar = 0; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char* argv[]) { int nloop; int thr_ret, i; pthread_t thrID1, thrID2, thrID3; if (argc != 2) { fprintf(stderr, "Uso: %s <num threads>\\n", argv[0]); exit(1); } nloop = atoi(argv[1]); if ((thr_ret = pthread_create(&thrID1, 0, thr_func, &nloop)) != 0) { fprintf(stderr, "Err. pthread_create() %s\\n", strerror(thr_ret)); exit(1); } if ((thr_ret = pthread_join(thrID1, 0)) != 0) { fprintf(stderr, "Err. pthread_join() %s\\n", strerror(thr_ret)); exit(1); } printf("Variabile globale: %d\\n", globvar); return (0); } void* thr_func(void* arg) { int tot_loops = *((int*)arg); int temp, i; for (i = 0; i < tot_loops; i++) { pthread_mutex_lock(&mtx); temp = globvar; temp++; globvar = temp; pthread_mutex_unlock(&mtx); } return (0); }
1
#include <pthread.h> void init_globals(struct globals_t* g) { memset(g, 0, sizeof(struct globals_t)); pthread_mutex_init(&g->mutex, 0); ssh_threads_set_callbacks(ssh_threads_get_pthread()); if (ssh_init() == -1) { fprintf(stderr, "ssh_init() failed\\n"); exit(1); } g->sshbind = ssh_bind_new(); g->pid_fd = -1; } static void wait_for_threads(struct globals_t* g) { size_t num_threads; pthread_t thread; do { pthread_mutex_lock(&g->mutex); { num_threads = g->n_threads; if (num_threads) { thread = g->head->thread; } } pthread_mutex_unlock(&g->mutex); if (num_threads) { pthread_kill(thread, SIGTERM); pthread_join(thread, 0); } } while (num_threads > 0); } void free_globals(struct globals_t* g) { if (g->pid_fd >= 0) { unlink(g->pid_file); close(g->pid_fd); } free(g->rsa_key); free(g->dsa_key); free(g->ecdsa_key); free(g->ed25519_key); free(g->bind_address); free(g->bind_port); free(g->pid_file); free(g->daemon_name); wait_for_threads(g); pthread_mutex_destroy(&g->mutex); ssh_bind_free(g->sshbind); ssh_finalize(); }
0
#include <pthread.h> pthread_mutex_t roomLock; pthread_cond_t occupancy; unsigned int maximum, current, studentID, numOfThread, numOfStudents; sem_t question, profAvail, done; void EnterOffice( int id ) { pthread_mutex_lock( &roomLock ); while( current == maximum ) pthread_cond_wait( &occupancy, &roomLock ); printf("Student %d shows up in the office.\\n", id); current++; pthread_mutex_unlock( &roomLock ); } void LeaveOffice( int id ) { pthread_mutex_lock( &roomLock ); current--; printf("Student %d leaves the office.\\n", id); pthread_mutex_unlock( &roomLock ); pthread_cond_signal( &occupancy ); } void QuestionStart( int id ) { studentID = id; printf("Student %d asks a question.\\n", id); } void AnswerStart() { printf("Professor starts to answer question for student %d.\\n", studentID); } void AnswerDone() { printf("Professor is done with answer for student %d.\\n", studentID); } void QuestionDone( int id ) { printf("Student %d is satisfied.\\n", id); } void * Professor() { while( numOfStudents ) { sem_wait( &question ); AnswerStart(); AnswerDone(); sem_post( &done ); } pthread_exit(0); } void * Student( void *arg) { int index, id = ( (int ) arg ); EnterOffice( id ); for(index = 0; index < ( id % 4 ) + 1; index++) { sem_wait( &profAvail ); QuestionStart( id ); sem_post( &question ); sem_wait( &done ); QuestionDone( id ); sem_post( &profAvail ); } LeaveOffice( id ); numOfStudents--; pthread_exit( 0 ); } void _my_init() { if ( pthread_mutex_init( &roomLock, 0 ) ) { printf("Error: Unable to intialize Mutex\\n"); exit(0); } if ( pthread_cond_init( &occupancy, 0 ) ) { printf("Error: Unable to intialize Condition Vatiable\\n"); exit(0); } if ( sem_init( &question, 0, 0 ) | sem_init( &profAvail, 0, 1 ) | sem_init( &done, 0, 0 ) ) { printf("Error: Unable to intialize Semaphores\\n"); exit(0); } current = 0; numOfThread = numOfStudents; } void _my_exit() { sem_destroy( &question ); sem_destroy( &profAvail ); sem_destroy( &done ); pthread_mutex_destroy( &roomLock ); pthread_cond_destroy( &occupancy ); exit(0); } int main( int argc, char* argv[] ) { if ( argc != 3) printf("Usage: office [capacity of office] [number of students]"); maximum = atoi( argv[1] ); numOfStudents = atoi( argv[2] ); _my_init(); int index, nthr; pthread_t threads[numOfThread], prof; pthread_create( &prof , 0 , Professor , 0); for (index = 0; index < numOfThread; index++) { if((nthr=pthread_create( &threads[index] , 0 , Student , (void *) index ) ) != 0) { printf("Error in thread creation: %d\\n", nthr); exit(-1); } } for(index = 0; index < numOfThread; index++) { if ( (nthr = pthread_join(threads[index], 0) ) != 0 ) { printf("Error in joining thread: %d\\n", nthr); exit(-1); } } _my_exit(); }
1
#include <pthread.h> struct collatz { int length; int input; } global_collatz; struct test_range { int min; int max; }; int CollatzLength(int n); void* LongestCollatz(void* range); const int maxValue = 1000000; int thread_count; pthread_mutex_t the_mutex; int main(int argc, const char *argv[]) { if (argc < 2) { printf("Usage: %s nthreads\\n", argv[0]); return 0; } long thread; thread_count = strtol(argv[1], 0, 10); pthread_t* thread_handles; thread_handles = malloc(thread_count*sizeof(pthread_t)); struct test_range* ranges; ranges = malloc(thread_count*sizeof(struct test_range)); pthread_mutex_init(&the_mutex, 0); global_collatz.length = 0; global_collatz.input = 0; int section_size = maxValue / thread_count; int edge_piece = maxValue - ( maxValue / thread_count ) * thread_count; for (thread = 0; thread < thread_count ; ++thread) { int local_min = section_size * thread; int local_max = local_min + section_size; if (maxValue == local_max + edge_piece) local_max += edge_piece; ranges[thread].min = local_min; ranges[thread].max = local_max; pthread_create( &thread_handles[thread], 0, LongestCollatz, &ranges[thread] ); } for (thread = 0; thread < thread_count ; ++thread) { pthread_join(thread_handles[thread], 0); } printf("The longest Collatz chain is for %d and is %d values long.\\n", global_collatz.input, global_collatz.length); free(thread_handles); pthread_mutex_destroy(&the_mutex); return 0; } int CollatzLength(int n) { if (0 >= n) return n; int counter = 1; while (1 != n) { if (0 == n % 2) { n /= 2; } else { n = 3 * n + 1; } counter++; } return counter; } void* LongestCollatz(void* range) { struct test_range *tr = (struct test_range *)range; int longestC = 0, tempC = 0, input = 0; for (int i = tr->min; i <= tr->max; ++i) { tempC = CollatzLength(i); if (tempC > longestC) { longestC = tempC; input = i; } } pthread_mutex_lock(&the_mutex); if (longestC > global_collatz.length) { global_collatz.length = longestC; global_collatz.input = input; } pthread_mutex_unlock(&the_mutex); return 0; }
0
#include <pthread.h> struct ringbuf { int ring[1000]; int tip, tail; int ringfull, ringempty; int readcount; int reading, writing; pthread_mutex_t *resourcelock; pthread_mutex_t *readaccess; pthread_cond_t *cond; pthread_cond_t *allowread; pthread_cond_t *allowwrite; }; struct ringbuf *initring(); void *producer(void *r); void *consumer(void *r); void ringadd(struct ringbuf *r, int n); void ringremove(struct ringbuf *r, int *n); int main() { pthread_t prodth, conth; struct ringbuf *ring; ring = initring(); assert(ring->resourcelock); printf("rings created\\n"); pthread_create(&prodth, 0, producer, (void *)ring); pthread_create(&conth, 0, consumer, (void *)ring); printf("threads created\\n"); pthread_join(prodth, 0); pthread_join(conth, 0); pthread_mutex_destroy(ring->resourcelock); pthread_mutex_destroy(ring->readaccess); free(ring->resourcelock); free(ring->readaccess); pthread_cond_destroy(ring->cond); free(ring->cond); free(ring); return 0; } struct ringbuf *initring() { struct ringbuf *r = (struct ringbuf *) malloc(sizeof(struct ringbuf)); r->tip = 0; r->tail = 0; r->reading = 0; r->writing = 0; r->readcount = 0; r->ringfull = 0; r->ringempty = 1; r->resourcelock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); assert(r->resourcelock); r->readaccess = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); assert(r->readaccess); r->cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t)); assert(r->cond); pthread_mutex_init(r->resourcelock, 0); pthread_mutex_init(r->readaccess, 0); pthread_cond_init(r->cond, 0); return r; } void *consumer(void *r) { printf("in reader\\n"); int n; struct ringbuf *ring = (struct ringbuf *) r; for(int i=0; i<20; i++) { printf("acquiring access lock in reader\\n"); assert(ring->readaccess); pthread_mutex_lock(ring->readaccess); ring->readcount++; printf("obtained access lock in reader\\n"); if (ring->readcount == 1) { printf("acquiring resource lock in reader\\n"); pthread_mutex_lock(ring->resourcelock); while (ring->writing) { printf("waiting on resource lock in reader\\n"); pthread_cond_wait(ring->cond, ring->resourcelock); } printf("obtained resource lock in reader\\n"); } pthread_mutex_unlock(ring->readaccess); ringremove(ring, &n); printf("read item %d\\n", n); pthread_mutex_lock(ring->readaccess); ring->readcount--; if (ring->readcount == 0) { pthread_mutex_unlock(ring->resourcelock); pthread_cond_signal(ring->cond); } pthread_mutex_unlock(ring->readaccess); usleep(2); } printf("reader done\\n"); return 0; } void *producer(void *r) { printf("in writer\\n"); struct ringbuf *ring = (struct ringbuf *) r; for(int i=0; i<20; i++) { printf("acquiring resource lock in writer\\n"); assert(ring->resourcelock); pthread_mutex_lock(ring->resourcelock); printf("obtained resource lock in writer\\n"); while (ring->readcount > 0) { printf("waiting on resource lock in writer\\n"); pthread_cond_wait(ring->cond, ring->resourcelock); } printf("obtained resource lock in writer\\n"); ring->writing = 1; ringadd(ring, i); ring->writing = 0; pthread_mutex_unlock(ring->resourcelock); pthread_cond_signal(ring->cond); usleep(2); } printf("writer done\\n"); return 0; } void ringadd(struct ringbuf *r, int n) { if (r->tip == 1000) { r->tip = 0; } r->ring[r->tip++] = n; printf("added item: %d\\n", n); if (r->tip == r->tail) r->ringfull = 1; r->ringempty = 0; } void ringremove(struct ringbuf *r, int *n) { if (r->tail == 1000) r->tail = 0; *n = r->ring[r->tail++]; if (r->tail == r->tip) r->ringempty = 1; r->ringfull = 0; }
1
#include <pthread.h> unsigned value = 0; pthread_mutex_t m; unsigned inc_flag = 0; unsigned dec_flag = 0; unsigned inc() { unsigned inc_v = 0; pthread_mutex_lock(&m); if(value == 0u-1) { pthread_mutex_unlock(&m); return 0; } else { inc_v = value; inc_flag = 1, value = inc_v + 1; pthread_mutex_unlock(&m); {pthread_mutex_lock(&m);assert(dec_flag || value > inc_v);pthread_mutex_unlock(&m);}; return inc_v + 1; } } unsigned dec() { unsigned dec_v; pthread_mutex_lock(&m); if(value == 0) { pthread_mutex_unlock(&m); return 0u-1; }else{ dec_v = value; dec_flag = 1, value = dec_v - 1; pthread_mutex_unlock(&m); {pthread_mutex_lock(&m);assert(inc_flag || value < dec_v);pthread_mutex_unlock(&m);}; return dec_v - 1; } } void* thr1(void* arg){ int r = __nondet_int(); if(r){ inc(); } else{ dec(); } return 0; } int main() { pthread_t t1,t2; pthread_create(&t1,0,thr1,0); pthread_create(&t2,0,thr1,0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_g1, mutex_g2; double g1 = 1, g2 = 1; void* geometric_mean_calc(void* arg) { int id = (int) arg; if (id % 2) { pthread_mutex_lock(&mutex_g1); g1 *= id; pthread_mutex_unlock(&mutex_g1); } else { pthread_mutex_lock(&mutex_g2); g2 *= id; pthread_mutex_unlock(&mutex_g2); } pthread_exit(0); } int main(int argc, char *argv[]) { int i, n, rc, status = 0; pthread_attr_t attribute; pthread_t *threads; printf("Unesite broj niti koje treba kreirati:\\n"); scanf("%d", &n); if(n < 0) { printf("GRESKA! Niste uneli pozitivan broj!"); exit(-1); } threads = calloc(n, sizeof(pthread_t)); pthread_attr_init(&attribute); pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex_g1, 0); pthread_mutex_init(&mutex_g2, 0); for(i = 0; i < n; i++) { rc = pthread_create(&threads[i], &attribute, geometric_mean_calc, (void *)i+1); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(1); } } pthread_attr_destroy(&attribute); for(i = 0; i < n; i++) { rc = pthread_join(threads[i], (void **)status); if (rc) { printf("GRESKA! Povratni kod iz pthread_join() je: %d", rc); exit(1); } } g2 = pow(g2, 1/(n/2 + 0.)); if (n % 2) { g1 = pow(g1, 1/((n/2) + 1.0)); } else { g1 = pow(g1, 1/(n/2 + 0.)); } printf("Geometrijska sredina prve (neparne) grupe niti je: %lf\\n", g1); printf("Geometrijska sredina druge (parne) grupe niti je: %lf", g2); pthread_mutex_destroy(&mutex_g1); pthread_mutex_destroy(&mutex_g2); free(threads); return 0; }
1
#include <pthread.h> int piao = 100; pthread_mutex_t mut; void * tprocess1(void * args) { int a = 0; while (1) { pthread_mutex_lock( & mut); if (piao > 0) { Sleep(1); piao--; printf("window1----------------%d tickets left\\n", piao); } else { a = 1; } pthread_mutex_unlock( & mut); if (a == 1) { break; } } return 0; } void * tprocess2(void * args) { int a = 0; while (1) { pthread_mutex_lock( & mut); if (piao > 0) { Sleep(1); piao--; printf("window2----------------%d tickets left\\n", piao); } else { a = 1; } pthread_mutex_unlock( & mut); if (a == 1) { break; } } return 0; } void * tprocess3(void * args) { int a = 0; while (1) { pthread_mutex_lock( & mut); if (piao > 0) { Sleep(1); piao--; printf("window3----------------%d tickets left\\n", piao); } else { a = 1; } pthread_mutex_unlock( & mut); if (a == 1) { break; } } return 0; } void * tprocess4(void * args) { int a = 0; while (1) { pthread_mutex_lock( & mut); if (piao > 0) { Sleep(1); piao--; printf("window4----------------%d tickets left\\n", piao); } else { a = 1; } pthread_mutex_unlock( & mut); if (a == 1) { break; } } return 0; } int main() { pthread_mutex_init( & mut, 0); pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4; pthread_create( & t4, 0, tprocess4, 0); pthread_create( & t1, 0, tprocess1, 0); pthread_create( & t2, 0, tprocess2, 0); pthread_create( & t3, 0, tprocess3, 0); Sleep(5000); return 0; }
0
#include <pthread.h> int global_i = 1; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait; void *polez_rab(void *num) { long t_num; t_num = (long) num; pthread_mutex_lock(&mut); global_i++; pthread_mutex_unlock(&mut); sleep (global_i); pthread_mutex_lock(&mut); if (global_i != 1 + 3) { pthread_cond_wait(&wait, &mut); } else { pthread_mutex_unlock(&mut); pthread_cond_broadcast(&wait); } } int main (){ pthread_cond_init(&wait, 0); pthread_t threads[3]; int rc, t; for(t = 0; t < 3; t++) { printf("In main: creating thread %d\\n", t); rc = pthread_create(&threads[t], 0, polez_rab, (void*) t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for(t = 0; t < 3; t++) { pthread_join(threads[t], 0); } return 0; }
1
#include <pthread.h> static struct log * stat_log; static pthread_mutex_t stat_lock = PTHREAD_MUTEX_INITIALIZER; int bfrstat_init(char * filename) { stat_log = malloc(sizeof(struct log)); char log_name[256]; snprintf(log_name, 256, "bfr_stats_%u", g_bfr.nodeId); if (log_init(log_name, filename, stat_log, LOG_OVERWRITE | LOG_NORMAL)) return -1; return 0; } void bfrstat_rcvd_bloom(struct bloom_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + BLOOM_MSG_MIN_SIZE + (msg->vector_bits / 8); pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT BLOOM_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void bfrstat_sent_bloom(struct bloom_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + BLOOM_MSG_MIN_SIZE + (msg->vector_bits / 8); pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT BLOOM_SENT %d", bytes); pthread_mutex_unlock(&stat_lock); } void bfrstat_rcvd_join(struct cluster_join_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + CLUSTER_JOIN_MSG_SIZE; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT JOIN_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void bfrstat_sent_join(struct cluster_join_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + CLUSTER_JOIN_MSG_SIZE; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT JOIN_SENT %d", bytes); pthread_mutex_unlock(&stat_lock); } void bfrstat_rcvd_cluster(struct cluster_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + CLUSTER_RESPONSE_MSG_SIZE; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT CLUSTER_RCVD %d", bytes); pthread_mutex_unlock(&stat_lock); } void bfrstat_sent_cluster(struct cluster_msg * msg) { if (!msg) return; int bytes = HDR_SIZE + CLUSTER_RESPONSE_MSG_SIZE; pthread_mutex_lock(&stat_lock); log_print(stat_log, "EVENT CLUSTER_SENT %d", bytes); pthread_mutex_unlock(&stat_lock); }
0
#include <pthread.h> int socketID[4]; char globalBuffer [2048]; char globalFileBuffer [4098], sendFile[4098]; pthread_mutex_t global_lock; FILE *fp; void fileWrite (char *fileName, char *text) { FILE *fp; fp = fopen(fileName, "w"); fputs(text, fp); fclose(fp); return; } void *msgServer(void *threadid) { long tid; tid = (long) threadid; int sid, bufferSize, i; char buffer[2048], *name; char *command, *content; sid = socketID[tid]; printf("User connected!\\n"); while (1) { bufferSize = 0; memset(buffer, '0', sizeof(char) * 2048); bufferSize = recv(sid, buffer, sizeof(buffer), 0); if (bufferSize <= 0) { printf("\\nError: Receive failed\\n"); socketID[tid] = -1; break; } buffer[bufferSize - 1] = '\\0'; command = strtok(buffer, " .\\n\\0"); if(strcmp(command, "message") == 0) { content = strtok(0, "\\\\"); name = strtok(0, "\\n\\0"); pthread_mutex_lock(&global_lock); for (i = 0; i < 4; i++) { if (socketID[i] == -1) continue; memset(globalBuffer, '0', sizeof(globalBuffer)); strcpy(globalBuffer, name); strcat(globalBuffer, ": "); strcat(globalBuffer, content); send(socketID[i], globalBuffer, sizeof(globalBuffer), 0); } pthread_mutex_unlock(&global_lock); } if (strcmp(command, "put") == 0) { content = strtok(0, "\\\\"); name = strtok(0, "\\n\\0"); pthread_mutex_lock(&global_lock); bufferSize = recv(sid, globalFileBuffer, sizeof(globalFileBuffer), 0); puts(globalFileBuffer); strcat(sendFile, "\\\\"); strcat(sendFile, content); strcat(sendFile, "*"); strcat(sendFile, globalFileBuffer); for (i = 0; i < 4; i++) { if (socketID[i] == -1) continue; send(socketID[i], sendFile, sizeof(sendFile), 0); } pthread_mutex_unlock(&global_lock); } } pthread_exit(0); } int main() { long tid; int rc; pthread_t threads[4]; char buffer[2048]; int bufferSize; struct addrinfo hints, *p, *sinfo; int sockfd, newsockfd, portno, clilen; struct sockaddr_in serv_addr, cli_addr; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_PASSIVE; if (getaddrinfo(0, "60002", &hints, &sinfo) != 0) { printf("\\nError: getaddrinfo\\n"); return 1; } for (p = sinfo; p != 0; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { printf("\\nError: socket\\n"); continue; } int i = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(int)) == -1) { printf("\\nError: setsockopt\\n"); return 1; } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); printf("\\nError: Bind failed\\n"); continue; } break; } freeaddrinfo(sinfo); if (p == 0) { printf("\\nError: Bind failed\\n"); return 1; } if (listen(sockfd, 4) == -1) { printf("\\nError: Listen failed\\n"); return 1; } tid = 0; int i = 0; for (i = 0; i < 4; i++) { socketID[i] = -1; } while(1) { clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen); if (newsockfd == -1) { printf("\\nError: Accepting failed"); continue; } printf("\\nConnection Successful!\\n"); rc = pthread_create(&threads[tid], 0, msgServer, (void *) tid); socketID[tid] = newsockfd; tid++; } pthread_exit(0); return 0; }
1
#include <pthread.h> struct s { struct s *next; int datum; } *A, *B; void init (struct s *p, int x) { p -> datum = x; p -> next = 0; } pthread_mutex_t A_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t B_mutex = PTHREAD_MUTEX_INITIALIZER; void *t_fun(void *arg) { int *ip; struct s *t, *sp; struct s *p = malloc(sizeof(struct s)); init(p,7); ip = &p->datum; sp = ((struct s *)((char *)(ip)-(unsigned long)(&((struct s *)0)->datum))); pthread_mutex_lock(&A_mutex); t = A->next; A->next = sp; sp->next = t; pthread_mutex_unlock(&A_mutex); return 0; } int main () { pthread_t t1; int *ip; struct s *sp; struct s *p = malloc(sizeof(struct s)); init(p,9); A = malloc(sizeof(struct s)); init(A,3); A->next = p; B = malloc(sizeof(struct s)); init(B,5); pthread_create(&t1, 0, t_fun, 0); ip = &p->datum; sp = ((struct s *)((char *)(ip)-(unsigned long)(&((struct s *)0)->datum))); pthread_mutex_lock(&A_mutex); sp = A->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&A_mutex); return 0; }
0
#include <pthread.h> void* declare_trial_files(void* rank) { long my_rank = rank; pthread_mutex_t mutex; int check = pthread_mutex_init(&mutex, 0); if (my_rank == 0) { pthread_mutex_lock(&mutex); fV_vs_t_id = fopen("V_vs_T.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 1) { pthread_mutex_lock(&mutex); fspiketimeid = fopen("Spiketime.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 2) { pthread_mutex_lock(&mutex); yid = fopen("Y.txt", "w"); pthread_mutex_unlock(&mutex); } if(my_rank == 3) { pthread_mutex_lock(&mutex); fVTid = fopen("VT.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 4) { pthread_mutex_lock(&mutex); fAdjacencymatrixId = fopen("RewiredMatrix.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 5) { pthread_mutex_lock(&mutex); frandomnumberId = fopen("Randomnumbers.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 6) { pthread_mutex_lock(&mutex); fNoConnectionsId = fopen("NoOfConnections.txt", "w"); pthread_mutex_unlock(&mutex); } if(my_rank == 7) { pthread_mutex_lock(&mutex); fm_noiseId = fopen("m_noise.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 8) { pthread_mutex_lock(&mutex); fmvalueId = fopen("mvalues.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 9) { pthread_mutex_lock(&mutex); fhvalueId = fopen("hvalues.txt", "w"); pthread_mutex_unlock(&mutex); } if (my_rank == 10) { pthread_mutex_lock(&mutex); fnvalueId = fopen("nvalues.txt", "w"); pthread_mutex_unlock(&mutex); } check = pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> FILE *logfile = 0, *errlogfile = 0; pthread_mutex_t errlogmutexlock, stdlogmutexlock, sysloglock; void record_std(char *record) { if(logfile == 0) { pthread_mutex_lock(&sysloglock); syslog(LOG_INFO, record); pthread_mutex_unlock(&sysloglock); } else { pthread_mutex_lock(&stdlogmutexlock); fprintf(logfile, "%s\\n", record); pthread_mutex_unlock(&stdlogmutexlock); } } void record_err(char *record) { if(errlogfile == 0) { pthread_mutex_lock(&sysloglock); syslog(LOG_ERR,record); pthread_mutex_unlock(&sysloglock); } else { pthread_mutex_lock(&errlogmutexlock); fprintf(errlogfile, "%s\\n", record); pthread_mutex_unlock(&errlogmutexlock); } } int get_file_size(char *path) { struct stat filestat; if (stat(path, &filestat) == -1) { perror("get_file_size"); return -1; } return filestat.st_size; } time_t get_file_last_modify(char *path) { struct stat filestat; if (stat(path, &filestat) == -1) { perror("get_file_last_modify"); return -1; } return filestat.st_mtime; } int send_file(int clientfd, FILE *f) { char buf[100001]; int len; int total_len = 0; while((len = fread(buf, sizeof(char), 100000, f)) != 0) { len = send_data(clientfd, buf, len); total_len += len; } return total_len; } int open_send_file(int clientfd, char *path) { FILE *f; f = fopen(path, "rb"); if (f == 0) { printf("open_send_file: file not found\\n"); return -1; } int temp = send_file(clientfd, f); fclose(f); return temp; } int open_err_log_file(char *name) { if (name[0] == 0) { pthread_mutex_init(&sysloglock, 0); openlog("webserver", 0, LOG_USER); return 1; } else if (errlogfile != 0) return 0; else { char logfilepath[200]; pthread_mutex_init(&errlogmutexlock, 0); sprintf(logfilepath, "./log/%s.err", name); errlogfile = fopen(logfilepath, "aw+"); setlinebuf(errlogfile); if (errlogfile == 0) { printf("Cannot open error logfile\\n"); return -1; } } return 0; } int open_std_log_file(char *name) { if (name[0] == 0) { pthread_mutex_init(&sysloglock, 0); openlog("webserver", 0, LOG_USER); return 1; } else if (logfile != 0) { return 0; } else { char logfilepath[200]; pthread_mutex_init(&stdlogmutexlock, 0); sprintf(logfilepath, "./log/%s.log", name); logfile = fopen(logfilepath, "aw+"); setlinebuf(logfile); if (logfile == 0) { printf("Cannot open standard logfile\\n"); return -1; } } return 0; }
0