text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> pthread_t thread_table[8]; pthread_mutex_t mutexsum; int sum=0; int id; char *string; }threads_param; threads_param parameters[8]; void *function_cars (void *aux) { threads_param *p = (threads_param*)aux; int random; printf("Start %s %d\\n", p->string, p->id); fflush(stdout); random = rand(); pthread_mutex_lock (&mutexsum); sum+=(1+(random%4)); pthread_mutex_unlock(&mutexsum); sleep(1+(random%4)); printf("Finish %s %d\\n", p->string, p->id); pthread_exit((void*)p->id); } int main(void){ int i, rc; void *status; sum=0; printf("Start of thread creation process...\\n"); pthread_mutex_init(&mutexsum,0); for (i=0; i<8; i++) { parameters[i].id = i; parameters[i].string = "car"; rc = pthread_create(&thread_table[i],0, function_cars, (void *)&parameters[i]); if (rc){ printf("Error creating thread\\n"); exit(-1); } } printf("End of thread process creation\\n"); printf("CARS INITIATING\\n"); for (i=0; i<8; i++) { rc = pthread_join(thread_table[i],&status); if (rc) { printf("Error joining threads\\n"); exit(-1); } } printf("All cars have REACHED THE FINISH LINE \\n"); printf("Sum of randoms is = %d \\n",sum); pthread_mutex_destroy(&mutexsum); return 0; }
1
#include <pthread.h> int N=100; int T=2; pthread_mutex_t mutex; int *v; int x; int ocurrencias=0; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *buscar(void *s){ int i; int cant=0; int inicio=*((int *) s)*N/T; int fin=inicio+(N/T); for(i=inicio;i<fin;i++){ if(v[i] == x){ cant++; } } pthread_mutex_lock(&mutex); ocurrencias += cant; pthread_mutex_unlock(&mutex); } int main(int argc,char*argv[]){ int i; double timetick; if ((argc != 4) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[3])) <= 0)) { printf("\\nUsar: %s n t\\n n: Dimension de la matriz (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]); exit(1); } x=atoi(argv[2]); v=malloc(sizeof(int)*N); pthread_mutex_init(&mutex, 0); pthread_t p_threads[T]; pthread_attr_t attr; pthread_attr_init (&attr); int id[T]; for(i=0;i<N;i++){ v[i]=N; } timetick = dwalltime(); for(i=0;i<T;i++){ id[i]=i; pthread_create(&p_threads[i], &attr, buscar, (void *) &id[i]); } for(i=0;i<T;i++){ pthread_join(p_threads[i],0); } printf("Ocurrencias: %d\\n",ocurrencias); printf("Tiempo en segundos %f\\n", dwalltime() - timetick); return(0); }
0
#include <pthread.h> void *fun1(void *); void *fun2(void *); struct tag { int shared_data; pthread_mutex_t mutex; pthread_cond_t cond1; } abc = {0,PTHREAD_MUTEX_INITIALIZER,PTHREAD_COND_INITIALIZER}; int main (void) { pthread_t thread1; pthread_t thread2; int status; status = pthread_create (&thread1, 0, fun1, 0); if (status != 0) { exit (1); } status = pthread_create (&thread2, 0, fun2, 0); if (status != 0) { exit (1); } pthread_exit (0); return 0; } void *fun1 (void *t) { while (1) { pthread_mutex_lock (&abc.mutex); if ((abc.shared_data % 2) == 0) { pthread_cond_signal ( &abc.cond1); pthread_cond_wait (&abc.cond1, &abc.mutex); } sleep(1); printf ("odd == %d\\n", abc.shared_data); (abc.shared_data)++; pthread_mutex_unlock (&abc.mutex); } } void *fun2 (void *t) { while (1) { pthread_mutex_lock (&abc.mutex); if ((abc.shared_data % 2) == 1) { pthread_cond_signal ( &abc.cond1); pthread_cond_wait (&abc.cond1, &abc.mutex); } sleep(1); printf ("even == %d\\n", abc.shared_data); (abc.shared_data)++; pthread_mutex_unlock (&abc.mutex); } }
1
#include <pthread.h> const int MAX_KEY = 65536; const int MAX_THREADS = 1024; struct node { int val; struct node* next; }; struct node* head = 0; int n = 1000; int m = 10000; float mMember = 0.50; float mInsert = 0.25; float mDelete = 0.25; int thread_count = 1; double start_time, finish_time, time_elapsed; int member_count=0; int insert_count=0; int delete_count=0; pthread_mutex_t mutex; pthread_mutex_t count_mutex; int Member(int value); int Insert(int value); int Delete(int value); void Clear_Memory(void); int Is_Empty(void); void* Thread_Function(void* rank); int main(int argc, char* argv[]) { if (argc != 2){ fprintf(stderr, "please provide a command line argument for thread count less than %d\\n", MAX_THREADS); exit(0); } thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS){ fprintf(stderr, "please provide a command line argument for thread count less than %d\\n", MAX_THREADS); exit(0); } int i=0; for(;i<n;i++){ int r = rand()%65536; if(!Insert(r)){ i--; } } pthread_t* thread_handles; thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&count_mutex, 0); start_time = clock(); for (i = 0; i < thread_count; i++) pthread_create(&thread_handles[i], 0, Thread_Function, (void*) i); for (i = 0; i < thread_count; i++) pthread_join(thread_handles[i], 0); finish_time = clock(); time_elapsed = (finish_time - start_time)/CLOCKS_PER_SEC; printf("%.10f\\n", time_elapsed); Clear_Memory(); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&count_mutex); free(thread_handles); return 0; } int Member(int value) { struct node* temp; temp = head; while (temp != 0 && temp->val < value) temp = temp->next; if (temp == 0 || temp->val > value) { return 0; } else { return 1; } } int Insert(int value) { struct node* current = head; struct node* previous = 0; struct node* temp; int return_value = 1; while (current != 0 && current->val < value) { previous = current; current = current->next; } if (current == 0 || current->val > value) { temp = malloc(sizeof(struct node)); temp->val = value; temp->next = current; if (previous == 0) head = temp; else previous->next = temp; } else { return_value = 0; } return return_value; } int Delete(int value) { struct node* current = head; struct node* previous = 0; int return_value = 1; while (current != 0 && current->val < value) { previous = current; current = current->next; } if (current != 0 && current->val == value) { if (previous == 0) { head = current->next; free(current); } else { previous->next = current->next; free(current); } } else { return_value = 0; } return return_value; } void Clear_Memory(void) { struct node* current; struct node* next; if (Is_Empty()) return; current = head; next = current->next; while (next != 0) { free(current); current = next; next = current->next; } free(current); } int Is_Empty(void) { if (head == 0) return 1; else return 0; } void* Thread_Function(void* rank) { int i, val; int my_member=0; int my_insert=0; int my_delete=0; int ops_per_thread = m/thread_count; for (i = 0; i < ops_per_thread; i++) { float operation_choice = (rand()%10000/10000.0); val = rand()%MAX_KEY; if (operation_choice < mMember) { pthread_mutex_lock(&mutex); Member(val); pthread_mutex_unlock(&mutex); my_member++; } else if (operation_choice < mMember + mInsert) { pthread_mutex_lock(&mutex); Insert(val); pthread_mutex_unlock(&mutex); my_insert++; } else { pthread_mutex_lock(&mutex); Delete(val); pthread_mutex_unlock(&mutex); my_delete++; } } pthread_mutex_lock(&count_mutex); member_count += my_member; insert_count += my_insert; delete_count += my_delete; pthread_mutex_unlock(&count_mutex); return 0; }
0
#include <pthread.h> enum { ARGV_ADDRESS = 1, ARGV_PORT = 2, ARGV_THREADS = 3, ARGV_REQUESTS = 4 }; long requests; pthread_mutex_t requests_mutex = PTHREAD_MUTEX_INITIALIZER; static void *thread_worker(void *arg) { struct addrinfo *r_ptr = 0; while (1) { pthread_mutex_lock(&requests_mutex); long new_requests = (requests > 0 ? requests-- : 0); pthread_mutex_unlock(&requests_mutex); if (new_requests == 0) { break; } for (r_ptr = (r_ptr ? r_ptr : arg); r_ptr != 0; r_ptr = r_ptr->ai_next) { int sfd = socket(r_ptr->ai_family, r_ptr->ai_socktype, r_ptr->ai_protocol); if (sfd < 0) { continue; } if (connect(sfd, r_ptr->ai_addr, r_ptr->ai_addrlen) < 0) { close(sfd); continue; } char buf[128 + 1] = {0}; ssize_t byte_read, pos = 0; while ((byte_read = recv(sfd, buf + pos, (sizeof(buf) - 1) - pos, 0)) > 0) { pos += byte_read; } printf("%s\\n", buf); close(sfd); break; } if (r_ptr == 0) { fprintf(stderr, "Error: could not connect.\\n"); exit(1); } } return 0; } int main(int argc, const char *argv[]) { if (argc != 5) { fprintf(stderr, "Usage: ./tester <address> <port> <count of threads> <count of requests>.\\n"); return 1; } struct addrinfo hints = {0}; hints.ai_socktype = SOCK_STREAM; struct addrinfo *r; int ret = getaddrinfo(argv[ARGV_ADDRESS], argv[ARGV_PORT], &hints, &r); if (ret < 0) { fprintf(stderr, "Error: %s.\\n", gai_strerror(ret)); return 1; } long threads = strtol(argv[ARGV_THREADS], 0, 10); requests = strtol(argv[ARGV_REQUESTS], 0, 10); if (threads < 1 || requests < 1) { fprintf(stderr, "Error: count of threads and requests must be > 0.\\n"); return 1; } pthread_t tid[threads]; for (long i = 0; i < threads; i++) { pthread_create(&tid[i], 0, thread_worker, r); } for (long i = 0; i < threads; i++) { pthread_join(tid[i], 0); } freeaddrinfo(r); return 0; }
1
#include <pthread.h> pthread_mutex_t mx1=PTHREAD_MUTEX_INITIALIZER; int st; int vec; int vec2[10000]; void *f1(void *arg) { int i,j; while(st) { pthread_mutex_lock(&mx1); j=0; for(i=0;i<10000;i++) if (vec2[i]==1)j++; printf("Vec %d \\n",j); pthread_mutex_unlock(&mx1); sleep(1); } pthread_exit(arg); } void *fr(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); vec--; for(i=0;i<10000;i++) if (vec2[i]==1){vec2[i]=0;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void *fw(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); vec++; for(i=0;i<10000;i++) if (vec2[i]==0){vec2[i]=1;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void ha(int i) { st=0; signal(SIGINT,ha); } int main(int args, char **argv, char **argc) { int nM,nN,i; pthread_t t; pthread_t tr[100]; pthread_t tw[100]; if(args==1) { printf("prg3 N n \\n"); } vec=0; if(args==3) { signal(SIGINT,ha); nN=atoi(&argv[1][0]); nM=atoi(&argv[2][0]); if(nN>100)exit(1); if(nM>100)exit(1); st=1; for(i=0;i<nN;i++) pthread_create(&tr[i],0,fr,0); for(i=0;i<nM;i++) pthread_create(&tw[i],0,fw,0); pthread_create(&t,0,f1,0); for(i=0;i<nM;i++) pthread_join(tw[i],0); for(i=0;i<nN;i++) pthread_join(tr[i],0); pthread_join(t,0); printf("Ok \\n"); return 0; } }
0
#include <pthread.h> pthread_mutex_t mutex; int number; char name[20]; struct node *next; struct node *previous; }Node; Node *head = 0; Node *tail = 0; void add(){ Node *p; if ((p = (Node*)malloc (sizeof (Node))) == (Node*)0){ printf ("Node could not be allocated\\n"); return; } printf("Enter name\\n"); scanf("%s", p->name); if (head == 0){ head = p; }else{ Node *temp; temp = head; while (temp != 0){ if (strcmp(temp->name, p->name) == 0){ printf("Duplicate, try again\\n"); free(p); return; } else{ temp = temp->next; } } } printf("Enter the number\\n"); scanf("%d",&p->number); if (tail != 0){ tail->next = p; } tail = p; tail->next=0; return; } void addpro(char name[20],int number){ Node *p; if ((p = (Node*)malloc (sizeof (Node))) == (Node*)0){ printf ("Node could not be allocated\\n"); return; } strcpy(p->name,name); p->number = number; if (head == 0){ head = p; } if (tail != 0){ tail->next = p; } tail = p; tail->next=0; p = p->next; return; } void delete(){ int open; Node *temp = head; printf("What is the size of table?\\n"); scanf("%d", &open); if (head->number <= open) { head = temp->next; free(temp); return; } Node *change; Node *temp2; change=temp; temp=change->next; while (temp->next != 0){ if (temp->number <= open) { temp2 = change->next; change->next = change->next->next; free(temp2); printf("Value taken out\\n"); return; }else if (temp->number > open) { change = temp; temp = temp->next; } } if(temp->number <= open){ printf("Last value taken out\\n"); free(temp); tail = change; tail->next = 0; } return; } void stats(){ Node *temp = head; while (temp != 0){ printf("Name: %s\\tNumber: %d\\n", temp->name, temp->number); temp = temp->next; } return; } void write_file(){ char input[50]; FILE *listw; listw = fopen("list.txt", "w"); if (listw == 0){ printf ("cannot open the file %s\\n",input); } Node *temp = head; while (temp != 0){ fprintf(listw, "%s %d\\n", temp->name, temp->number); temp = temp->next; } fclose(listw); } void *autosaver(void * arg){ Node*list = (Node*)arg; while (1) { pthread_mutex_lock(&mutex); printf("autosave\\n"); char input[50]; FILE *listx; listx = fopen("list.bin", "wb"); if (listx == 0){ printf ("cannot open the file %s\\n",input); } Node *temp; temp = list; while(temp != 0) { fwrite(temp,sizeof(Node),1,listx); temp = temp -> next; } fclose(listx); pthread_mutex_unlock(&mutex); sleep(5); } } void showbinary(void * arg){ Node *temp = (Node*)arg; char input[50]; FILE *listy; listy = fopen("list.bin", "rb"); if (listy == 0){ printf ("cannot open the file %s\\n",input); } printf("before read in binary nodes\\n"); Node *temp2 = 0; temp2 = temp; while(temp2 != 0) { fread(temp2, sizeof(Node), 1, listy); printf("%s\\t", temp2->name); printf("%d\\n", temp2->number); temp2 = temp2 ->next; } } int main(int argc, char *argv[]) { char namex[20]; int numberx; int command; int quit = 0; printf("Welcome to Yuya's Restaurant what would you like to do?\\n\\n"); printf("Type 1 to add waitlist\\n"); printf("Type 2 to eliminate an entry that fits the table\\n"); printf("Type 3 to show all Waitlist\\n"); printf("Type 4 to show binary content\\n"); printf("Type 5 to quit\\n"); printf("----------------------------\\n\\n"); pthread_t thr; pthread_mutex_init(&mutex,0); char input[50]; FILE *list; list = fopen(argv[1], "r"); if (list == 0){ printf ("cannot open the file %s\\n",input); } while(fscanf(list,"%s %d\\n",namex,&numberx) != EOF) { addpro(namex,numberx); } Node *p; p = head; pthread_create(&thr, 0, autosaver, (void*)p); while (quit == 0){ scanf("%d",&command); if (command == 1){ pthread_mutex_lock(&mutex); add(); pthread_mutex_unlock(&mutex); }else if (command == 2){ pthread_mutex_lock(&mutex); delete(); pthread_mutex_unlock(&mutex); }else if (command == 3){ stats(); }else if (command == 4){ pthread_mutex_lock(&mutex); showbinary((void*)p); pthread_mutex_unlock(&mutex); }else if (command == 5){ pthread_cancel(thr); write_file(); quit = 1; } printf("What would you like to do?\\n"); } return 0; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t init = PTHREAD_COND_INITIALIZER; int initialized = 0; void func1(){ pthread_mutex_lock(&lock); printf("In func1\\n"); initialized = 1; pthread_cond_signal(&init); pthread_mutex_unlock(&lock); pthread_exit(0); } void func2(){ pthread_mutex_lock(&lock); while(initialized!=1){ pthread_cond_wait(&init, &lock); } printf("In func2\\n"); initialized = 2; pthread_cond_signal(&init); pthread_mutex_unlock(&lock); pthread_exit(0); } void func3(){ pthread_mutex_lock(&lock); while(initialized!=2){ pthread_cond_wait(&init, &lock); } printf("In func3\\n"); pthread_mutex_unlock(&lock); pthread_exit(0); } int main() { pthread_t thread1, thread2, thread3; int iret1, iret2, iret3, retjoin3, retjoin1, retjoin2; iret1 = pthread_create(&thread1, 0, (void*) &func1, 0); iret2 = pthread_create(&thread2, 0, (void *) &func2, 0); iret3 = pthread_create(&thread3, 0, (void *) &func3, 0); retjoin1 = pthread_join(thread1, 0); retjoin2 = pthread_join(thread2, 0); retjoin3 = pthread_join(thread3, 0); pthread_mutex_destroy(&lock); exit(0); }
0
#include <pthread.h> char *kvp_extract_value(char *pair) { char *part2, *value; if (!(part2 = strchr(pair, '='))) { fprintf(stderr, "kvp_extract_value: not a key=value pair: %s\\n", pair); return strdup(""); } *part2++ = '\\0'; *strchr(part2, '\\n') = '\\0'; if (!(value = strdup(part2))) { fprintf(stderr, "kvp_extract_value: malloc failure\\n"); exit(-5); } return value; } int kvp_apply_to_dict(struct kvpdict *dp, char *key, char *target) { int append; size_t origtext_siz, newtext_siz; if ((append = (key[0] == '+'))) ++key; for (; dp->target; dp++) { if (!strcmp(key, dp->key)) { if (dp->pm) pthread_mutex_lock(dp->pm); if (!append) { if (*(dp->target)) free(*(dp->target)); *(dp->target) = target; } else { *(dp->target) = realloc(*(dp->target), (origtext_siz = strlen(*(dp->target))) + (newtext_siz = strlen(target)) + 2); if (!(*(dp->target))) { fprintf(stderr, "malloc failure\\n"); exit(5); } memcpy(*(dp->target) + origtext_siz, target, newtext_siz); memcpy(*(dp->target) + origtext_siz + newtext_siz, "\\n", 2); free(target); } if (dp->pm) pthread_mutex_unlock(dp->pm); return 1; } } return 0; } void kvp_free_dict(struct kvpdict *dp) { while (dp->key) { if (*(dp->target)) free(*(dp->target)); *dp->target = 0; dp++; } }
1
#include <pthread.h> pthread_t tid; int idx; long n_inc; long c[1]; long *p; } * thread_arg_t; pthread_mutex_t mutex; long g = 0; void * thread_func(void * _arg) { thread_arg_t arg = _arg; long i; long n_inc = arg->n_inc; static long s = 0; long l = 0; pthread_mutex_lock(&mutex); for (i = 0; i < n_inc; i++) { g++; } for (i = 0; i < n_inc; i++) { s++; } for (i = 0; i < n_inc; i++) { l++; } for (i = 0; i < n_inc; i++) { arg->c[0]++; } for (i = 0; i < n_inc; i++) { arg->p[0]++; } pthread_mutex_unlock(&mutex); return 0; } double cur_time() { struct timeval tp[1]; gettimeofday(tp, 0); return tp->tv_sec + tp->tv_usec * 1.0E-6; } int main(int argc, char ** argv) { if (argc <= 2) { fprintf(stderr, "usage: %s no_of_threads no_of_increments\\n" "example:\\n %s 16 10000000\\n", argv[0], argv[0]); exit(1); } int n_threads = atoi(argv[1]); long n_inc = atol(argv[2]); pthread_mutex_init(&mutex,0); struct thread_arg args[n_threads]; double t0 = cur_time(); long a_counter[1] = { 0 }; int i; for (i = 0; i < n_threads; i++) { args[i].idx = i; args[i].n_inc = n_inc; args[i].c[0] = 0; args[i].p = a_counter; pthread_create(&args[i].tid, 0, thread_func, (void *)&args[i]); } for (i = 0; i < n_threads; i++) { pthread_join(args[i].tid, 0); } double t1 = cur_time(); printf("OK: elapsed time: %f\\n", t1 - t0); return 0; }
0
#include <pthread.h> pthread_mutex_t locki[26]; pthread_mutex_t lockb[26]; int busy[26]; int inode[32]; pthread_t tids[26]; void *thread_routine(void * arg) { int i,b,j; int tid; tid = *((int *)arg); i = tid % 32; assert(i >=0 && i < 26); pthread_mutex_lock( &locki[i] ); if( inode[i]==0 ) { b = (i*2) % 26; for(j=0; j<26/2; j++) { pthread_mutex_lock( &lockb[b] ); if(!busy[b]) { busy[b] = 1; inode[i] = b+1; printf(" "); pthread_mutex_unlock( &lockb[b] ); break; } pthread_mutex_unlock( &lockb[b] ); b = (b+1) % 26; } } assert(i >=0 && i < 26); pthread_mutex_unlock(&locki[i]); pthread_exit(0); } int main() { int i; int arg[26]; for(i = 0; i < 26;i++) { pthread_mutex_init(&locki[i],0); pthread_mutex_init(&lockb[i],0); busy[i] = 0; } for(i=0;i<26;i++) { arg[i]=i; pthread_create(&tids[i], 0, thread_routine, &arg[i]); } for(i=0;i<26;i++) pthread_join(tids[i], 0); for(i=0;i<26;i++) { pthread_mutex_destroy(&locki[i]); pthread_mutex_destroy(&lockb[i]); } return 0; }
1
#include <pthread.h> pthread_mutex_t serialLock; static int serial = -1; static long long int startTime = 0; static int errorLog = 1; int initAXcomm(int baudrate) { if(pthread_mutex_init(&serialLock, 0)) { printf("ERROR : cannot create mutex\\n"); return -2; } serial = serialOpen("/dev/serial0", baudrate); if(serial == -1) { printf("ERROR : cannot open AX12 serial port\\n"); return -1; } return 0; } static int axSendPacket(uint8_t id, uint8_t instruction, uint8_t command, uint8_t arg1, uint8_t arg2, int argCount) { uint8_t checksum = ~(id + instruction + command + arg1 + arg2 + 2 + argCount); if(serial < 0) { printf("ERROR : serial port not initialized\\n"); return -1; } serialPutchar(serial, 0xFF); serialPutchar(serial, 0xFF); serialPutchar(serial, id); serialPutchar(serial, 2+argCount); serialPutchar(serial, instruction); if(argCount>0) serialPutchar(serial, command); if(argCount>1) serialPutchar(serial, arg1); if(argCount==3) serialPutchar(serial, arg2); serialPutchar(serial, checksum); return 0; } static int checkTimeout() { return getCurrentTime() - startTime > AX_MAX_ANSWER_WAIT; } static int axReceiveAnswer(uint8_t expectedId, uint16_t* result, uint8_t* statusError) { startTime = getCurrentTime(); while(!checkTimeout()) { if(serialDataAvail(serial) >= 6 && serialGetchar(serial) == 0xFF && serialGetchar(serial) == 0xFF) { uint8_t id, length, error, checksum, arg1, arg2; id = serialGetchar(serial); length = serialGetchar(serial); error = serialGetchar(serial); if(length > 2) { arg1 = serialGetchar(serial); while(!checkTimeout() && serialDataAvail(serial) < 1) waitForMicro(100); } else { arg1 = 0; } if(length > 3 && !checkTimeout()) { arg2 = serialGetchar(serial); while(!checkTimeout() && serialDataAvail(serial) < 1) waitForMicro(100); } else { arg2 = 0; } if(checkTimeout()) return -4; checksum = serialGetchar(serial); if(((uint8_t)~(id+length+error+arg1+arg2)) != checksum) return -2; if(id != expectedId) return -3; if(statusError != 0) *statusError = error; if(result != 0) *result = arg1 + (arg2 << 8); return 0; } waitForMicro(200); } return -4; } static void printCommError(int id, int code) { printf("AX12 communication ERROR (with id=%d) : ", id); switch(code) { case -1: printf("serial port not initialized\\n"); break; case -2: printf("wrong checksum\\n"); break; case -3: printf("ID doesnt match\\n"); break; case -4: printf("timeout\\n"); break; } } static void releaseSerialLock() { pthread_mutex_unlock(&serialLock); } static int axTransaction(uint8_t id, uint8_t instruction, uint8_t command, uint16_t arg, int argCount, uint16_t* result, uint8_t* error) { int code = 0; pthread_mutex_lock(&serialLock); for(int i=0; i<AX_SEND_RETRY+1; i++) { serialFlush(serial); if(axSendPacket(id, instruction, command, arg&0xFF, (arg >> 8)&0xFF, argCount)) { code = -1; break; } if(id == 0xFE) break; code = axReceiveAnswer(id, result, error); if(!code) break; } scheduleIn(15, releaseSerialLock); if(errorLog && code != 0) printCommError(id, code); return code; } int axWrite8(uint8_t id, uint8_t command, uint8_t arg, uint8_t* statusError) { return axTransaction(id, AX_WRITE_DATA, command, arg, 2, (uint16_t*)0, statusError); } int axWrite16(uint8_t id, uint8_t command, uint16_t arg, uint8_t* statusError) { return axTransaction(id, AX_WRITE_DATA, command, arg, 3, (uint16_t*)0, statusError); } int axRead8(uint8_t id, uint8_t command, uint8_t* result, uint8_t* statusError) { int code; uint16_t result16; code = axTransaction(id, AX_READ_DATA, command, 1, 2, &result16, statusError); *result = (uint8_t) result16; return code; } int axRead16(uint8_t id, uint8_t command, uint16_t* result, uint8_t* statusError) { return axTransaction(id, AX_READ_DATA, command, 2, 2, result, statusError); } int axPing(uint8_t id, uint8_t* statusError) { return axTransaction(id, AX_PING, 0, 0, 0, (uint16_t*)0, statusError); } int axFactoryReset(uint8_t id, uint8_t* statusError) { return axTransaction(id, AX_RESET, 0, 0, 0, (uint16_t*)0, statusError); } void enableErrorPrint(int enable) { errorLog = enable; }
0
#include <pthread.h> pthread_mutex_t udp_thread_status_mutex; int udp_thread_status = 0; struct udp_thread_args { char *ip; int port; int msg_len; }; void print_hex(const char *s) { while(*s) printf("%02x ", *s++); printf("\\n"); } float ntohf(uint32_t p) { float f = ((p>>16)&0x7fff); f += (p&0xffff) / 65536.0f; if (((p>>31)&0x1) == 0x1) { f = -f; } return f; } void *udp_recv_thread(void *arguments) { struct udp_thread_args *args = arguments; struct sockaddr_in si_me, si_dest; int sock, i, slen = sizeof(si_dest); int recv_len; char *buf = (char *) malloc(args->msg_len*sizeof(char)); memset(buf, 0, sizeof(buf)); unsigned long tbuf[9]; float imu_data_line[9]; if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { printf("Could not create the socket\\n"); printf("IP: %s, PORT: %d, MSG_LEN: %d\\n", args->ip, args->port, args->msg_len); pthread_exit(0); } memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(args->port); si_me.sin_addr.s_addr = htonl(INADDR_ANY); printf("Binding socket to port %d\\n",args->port); if(bind(sock, (struct sockaddr *)&si_me, sizeof(si_me)) == -1) { printf("Binding socket failed.\\n"); pthread_exit(0); } printf("Waiting for signal to start experiment..\\n"); while(1) { pthread_mutex_lock(&udp_thread_status_mutex); int ts = udp_thread_status; pthread_mutex_unlock(&udp_thread_status_mutex); if(ts == 1) break; usleep(10000); } while(1) { fflush(stdout); if((recv_len = recvfrom(sock, buf, (args->msg_len)-1, 0, (struct sockaddr *)&si_dest, &slen)) == -1) { printf("Recv failed.\\n"); } memcpy(tbuf, buf, (args->msg_len)-1); for(int i=0; i<9; i++) { imu_data_line[i] = ntohf(tbuf[i]); } pthread_mutex_lock(&udp_thread_status_mutex); int ts = udp_thread_status; pthread_mutex_unlock(&udp_thread_status_mutex); printf("Raw packet: "); print_hex(buf); printf("Received packet %f, %f, %f, %f from IP: %s, PORT: %d\\n", imu_data_line[0], imu_data_line[1], imu_data_line[2], imu_data_line[3], inet_ntoa(si_dest.sin_addr), ntohs(si_dest.sin_port)); if(ts == 0) { break; } } close(sock); } int main(int argc, char**argv) { pthread_t test_thread; struct udp_thread_args *args; args->ip = "192.168.0.1"; args->port = 9751; args->msg_len = 37; int experiment_duration; int sample_rate; char c; printf("Enter experiment duration in seconds: "); scanf("%d",&experiment_duration); printf("Enter IMU sample rate (Hz): "); scanf("%d",&sample_rate); printf("Press enter to start the experiment\\n"); c = getchar(); c = getchar(); printf("Starting experiment...\\n"); if(pthread_create(&test_thread, 0, udp_recv_thread, (void *)args) != 0) { printf("Thread creation failed\\n"); return -1; } pthread_mutex_lock(&udp_thread_status_mutex); udp_thread_status = 1; pthread_mutex_unlock(&udp_thread_status_mutex); int t0 = (int) time(0); while(1) { int t1 = (int) time(0); if((t1 - t0) >= experiment_duration) { printf("Experiment duration is over stopping program and saving data...\\n"); pthread_mutex_lock(&udp_thread_status_mutex); udp_thread_status = 0; pthread_mutex_unlock(&udp_thread_status_mutex); break; } printf("%d Seconds since start of experiment.\\n", t1 - t0); sleep(1); } return pthread_join(test_thread, 0); }
1
#include <pthread.h> pthread_mutex_t my_mutex; int ticket=10; void* thread_function1(void* arg); void* thread_function2(void* arg); int main(int argc,char* argv[]) { pthread_t thid1; pthread_t thid2; pthread_mutex_init(&my_mutex,0); pthread_create(&thid1,0,thread_function1,0); pthread_create(&thid2,0,thread_function2,0); pthread_join(thid1,0); pthread_join(thid2,0); pthread_mutex_destroy(&my_mutex); return 0; } void* thread_function1(void* arg) { while(1) { pthread_mutex_lock(&my_mutex); if(ticket>0) { printf("win1 start sale,%d left\\n",ticket); sleep(3); ticket--; printf("win1 finished,%d left\\n",ticket); } else { pthread_mutex_unlock(&my_mutex); pthread_exit(0); } pthread_mutex_unlock(&my_mutex); sleep(1); } } void* thread_function2(void* arg) { while(1) { pthread_mutex_lock(&my_mutex); if(ticket>0) { printf("win2 start sale,%d left\\n",ticket); sleep(3); ticket--; printf("win2 finished,%d left\\n",ticket); } else { pthread_mutex_unlock(&my_mutex); pthread_exit(0); } pthread_mutex_unlock(&my_mutex); sleep(1); } }
0
#include <pthread.h> static pthread_key_t g_data_key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void free_key(void *arg) { fprintf(stderr, "%s %d %s pthread_key_delete\\n", "env_key.c", 15, __func__); pthread_key_delete(g_data_key); } static void thread_init(void) { fprintf(stderr, "%s %d %s %u\\n", "env_key.c", 21, __func__, g_data_key); pthread_key_create(&g_data_key, free_key); fprintf(stderr, "%s %d %s %u\\n", "env_key.c", 23, __func__, g_data_key); } char *getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(g_data_key); if (envbuf == 0) { envbuf = malloc(ARG_MAX); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return 0; } pthread_setspecific(g_data_key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; ++i) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strcpy(envbuf, &environ[i][len + 1]); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; } void *thread1(void *arg) { char *p = (char *)arg; fprintf(stdout, "%s=%s\\n", p, getenv(p)); return 0; } void *thread2(void *arg) { char *p = (char *)arg; fprintf(stdout, "%s=%s\\n", p, getenv(p)); return 0; } int main(int argc, char *argv[]) { pthread_t tid; if (argc != 2) { fprintf(stderr, "./a.out aa\\n"); return 1; } pthread_create(&tid, 0, thread1, argv[1]); pthread_create(&tid, 0, thread2, argv[1]); return 0; }
1
#include <pthread.h> { int buf[3]; int in; int out; sem_t full; sem_t empty; pthread_mutex_t mutex; } sbuf_t; sbuf_t shared; void *Producer(void *arg) { int i, item, index; struct timeval currenttime; int sec; index = (int)arg; for (i = 0; i < 6; i++) { item = i; sem_wait(&shared.empty); pthread_mutex_lock(&shared.mutex); shared.buf[shared.in] = item; shared.in = (shared.in+1)%3; gettimeofday(&currenttime, 0); int sec = currenttime.tv_sec; printf("time: %d [P%d] Producing %d ...\\n", sec, index, item); fflush(stdout); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.full); if (i % 2 == 1) sleep(1); } return 0; } void *Consumer(void *arg) { int i, item, index; struct timeval currenttime; index = (int)arg; for (i = 4; i > 0; i--) { sem_wait(&shared.full); pthread_mutex_lock(&shared.mutex); item = i; item = shared.buf[shared.out]; shared.out = (shared.out+1)%3; int sec = currenttime.tv_sec; printf("time: %d [C%d] Consuming %d ...\\n", sec, index, item); fflush(stdout); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.empty); if (i % 2 == 1) sleep(1); } return 0; } int main() { pthread_t idP, idC; int index; sem_init(&shared.full, 0, 0); sem_init(&shared.empty, 0, 3); pthread_mutex_init(&shared.mutex, 0); for (index = 0; index < 2; index++) { pthread_create(&idP, 0, Producer, (void*)&index); } for (index = 0; index < 3; index++) { pthread_create(&idC, 0, Consumer, (void*)&index); } pthread_exit(0); }
0
#include <pthread.h> void RainGet(void) { static struct timeval tPreviousReading = { 0, 0 }; struct timeval tNow, tInterval; char *pRain = malloc(GP_LOGBUFFERSIZE); gettimeofday(&tNow, 0); timersub(&tNow, &tPreviousReading, &tInterval); writeLog(GP_LOGLEVELHIGH, "Rain: Processing interrupt.\\n"); if (tInterval.tv_usec < (RAIN_DEBOUNCETIME * 1000)) tPreviousReading = tNow; else { pthread_mutex_lock (&rainGaugeLock); ++iRainCounter; if (bDebug > GP_LOGLOW) { snprintf(pRain, GP_LOGBUFFERSIZE, "Rain: Raining (%i).\\n", iRainCounter); writeLog(GP_LOGLEVELLOW, pRain); } pthread_mutex_unlock (&rainGaugeLock); } free(pRain); } int RainInit(int iPin) { iRainCounter = 0; pullUpDnControl(iPin, PUD_UP); wiringPiISR(iPin, INT_EDGE_FALLING, RainGet); return 0; }
1
#include <pthread.h> int fire_area; static void *trigger_run(void *arg) { int buttons_fd; int flags=0, flags2=0; struct st_caller *caller; buttons_fd = open("/dev/buttons", 0); if (buttons_fd < 0) { perror("open device buttons"); exit(1); } for (;;) { char current_buttons[6]; if (read(buttons_fd, current_buttons, sizeof current_buttons) != sizeof current_buttons) { perror("read buttons:"); exit(1); } if (current_buttons[3] == '1' && flags2== 0 ){ usleep(5000); } if (current_buttons[3] == '0' && flags2 == 1){ usleep(5000); } if (current_buttons[3] == '1' && flags2 == 0){ int ret; struct st_matrix *matrix; struct st_action_unit unit; bzero(&unit, sizeof unit); flags2 = 1; pthread_mutex_lock( &plan_mutex); matrix = gmatrix; if (!matrix){ printf("head_caller err, matrix is NULL\\n"); pthread_mutex_unlock(&plan_mutex); break; } if (current_buttons[4] == '0' && flags ==1 && ARM_STATE == CALLER_SEND_BUSY){ flags = 0; pthread_mutex_lock( &plan_mutex); caller_op(CALLER_SEND_IDEL); pthread_mutex_unlock( &plan_mutex); printf(" CALLER - BUS = %x\\n", ARM_STATE); } ARM_STATE = CALLER_SEND_BUSY; matrix->matrix_state[MATRIX_STATE] = MATRIX_CALLER; unit.dev_addr = matrix->dev.addr; unit.sdata[0] = 1; unit.sdata[1] = 0xff; unit.ssize = 2; ret = dispersion(&unit); if (ret < 0){ printf("head_caller err, dispersion return err\\n"); matrix->matrix_state[MATRIX_STATE] = MATRIX_IDLE; pthread_mutex_unlock(&plan_mutex); break; } matrix->matrix_state[MATRIX_STATE] = MATRIX_BUSY; pthread_mutex_unlock( &plan_mutex); } else if ( current_buttons[3] == '0' && flags2 == 1 ){ struct st_matrix *matrix; int ret; matrix = gmatrix; printf("free\\n"); ret = matrix_load_state(matrix); if( ret < 0) matrix->matrix_state[MATRIX_STATE] = MATRIX_ERR; else matrix->matrix_state[MATRIX_STATE] = MATRIX_IDLE; { struct st_action_unit new_unit; struct st_select_amp *amp; bzero(&new_unit, sizeof(new_unit)); for( amp= gselect_amp; amp; amp = amp->next) { if( amp->select_state[SELECT_AMP_STATE] == SELECT_AMP_BUSY){ int ret; amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_CALLER; ret = select_amp_load_state(amp); if( ret < 0){ amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_ERR; continue; } amp->select_state[SELECT_AMP_STATE] = SELECT_AMP_IDLE; } } } ARM_STATE = CALLER_SEND_IDEL; flags2 = 0; } if(current_buttons[4] == '1' && flags == 0 && ARM_STATE == CALLER_SEND_IDEL) { usleep(5000); } if( current_buttons[4] == '1' && flags == 0 && ARM_STATE == CALLER_SEND_IDEL) { int ret; flags =1; pthread_mutex_lock( &plan_mutex); ret = caller_op( CALLER_SEND_LOOP ); if( ret < 0 ){ flags = 0; pthread_mutex_unlock( &plan_mutex); } pthread_mutex_unlock( &plan_mutex); for(caller=gcaller; caller; caller = caller->next) { printf("caller: \\n\\taddr=%x\\n\\tstate = %x\\n", caller->dev.addr, caller->caller_state); } printf(" CALLER - BUS = %x\\n", ARM_STATE); }else if (current_buttons[4] == '0' && flags ==1 && ARM_STATE == CALLER_SEND_BUSY){ flags = 0; pthread_mutex_lock( &plan_mutex); caller_op(CALLER_SEND_IDEL); pthread_mutex_unlock( &plan_mutex); for(caller=gcaller; caller; caller = caller->next) { printf("caller: \\n\\taddr=%x\\n\\tstate = %x\\n", caller->dev.addr, caller->caller_state); } printf(" CALLER - BUS = %x\\n", ARM_STATE); } sleep(1); } close(buttons_fd); return 0; } void trigger_start() { int res; pthread_t runid; res = pthread_create(&runid, 0, (void *)trigger_run, 0); if( res != 0 ) { trigger_debug("( trigger_start): pthread_create is err\\n"); exit(res); } }
0
#include <pthread.h> { pthread_mutex_t mutex; int n_data; pthread_cond_t cond; int max_queue; int max_send; int n_sent; } queue_t; { queue_t *queue; int id; pthread_t pid; } args_t; void *sender(void *arg) { args_t *args = (args_t *)arg; queue_t *q = args->queue; int n_sent =0; int have_data = 0; pthread_mutex_lock(&q->mutex); while (q->n_sent < q->max_send) { if (!have_data) { pthread_mutex_unlock(&q->mutex); sched_yield(); pthread_mutex_lock(&q->mutex); have_data = 1; } while(q->n_sent < q->max_send && q->n_data >= q->max_queue) pthread_cond_wait(&q->cond, &q->mutex); if (q->n_sent < q->max_send){ q->n_data++; q->n_sent++; n_sent++; have_data = 0; pthread_cond_signal(&q->cond); if (q->n_sent == q->max_send) { pthread_cond_broadcast(&q->cond); } } } pthread_mutex_unlock(&q->mutex); printf("sender %d sent %d\\n", args->id, n_sent); return 0; } void *receiver(void *arg) { args_t *args = (args_t *)arg; queue_t *q = args->queue; int n_got =0; int have_data = 0; pthread_mutex_lock(&q->mutex); while (q->n_sent < q->max_send || q->n_data) { if (have_data) { pthread_mutex_unlock(&q->mutex); sched_yield(); pthread_mutex_lock(&q->mutex); have_data = 0; } while(q->n_sent < q->max_send && !q->n_data) pthread_cond_wait(&q->cond, &q->mutex); if (q->n_data){ q->n_data--; n_got++; have_data = 1; pthread_cond_signal(&q->cond); } } pthread_mutex_unlock(&q->mutex); printf("receiver %d got %d\\n", args->id, n_got); return 0; } int main(int argc, char*argv[]) { int n_data = 1000; int n_senders = 1; int n_receivers = 1; int max_queue = 1; queue_t q; int i; args_t *senders, *receivers; void *retval; if (argc > 1) n_data = atoi(argv[1]); if (argc > 2) max_queue = atoi(argv[2]); q.n_data = q.n_sent = 0; q.max_queue = max_queue; q.max_send = n_data; pthread_mutex_init(&q.mutex, 0); pthread_cond_init(&q.cond, 0); receivers = (args_t*)malloc(n_receivers * sizeof(args_t)); for(i=0; i<n_receivers; i++) { receivers[i].id = i; receivers[i].queue = &q; pthread_create(&receivers[i].pid, 0, &receiver, (void*)&receivers[i]); } senders = (args_t*)malloc(n_senders * sizeof(args_t)); for(i=0; i<n_senders; i++) { senders[i].id = i; senders[i].queue = &q; pthread_create(&senders[i].pid, 0, &sender, (void*)&senders[i]); } for(i=0; i<n_receivers; i++) pthread_join(receivers[i].pid, &retval); for(i=0; i<n_senders; i++) pthread_join(senders[i].pid, &retval); return 0; }
1
#include <pthread.h> pthread_mutex_t global_lock; char buffer[(8)][(4096)]; int bp[(8)]; pthread_mutex_t lock[(8)]; int running = 0; void* producer(void* arg) { static struct timeval time_r_start; static struct timeval time_r_end; int p = (int)(0xff & (long)(arg)); unsigned long q = (1024 << 6); gettimeofday(&time_r_start,0); while(q>0) { pthread_mutex_lock(&lock[p]); bp[p] = (4096); int local_p; buffer[p][0] = 1; buffer[p][1] = 1; for(local_p=2;local_p<(4096);local_p++) { buffer[p][local_p] = buffer[p][local_p-1] + buffer[p][local_p-2]; } pthread_mutex_unlock(&lock[p]); do { if(bp[p]==0) { break; } }while(1); q--; } gettimeofday(&time_r_end,0); double sec = ((double)(time_r_end.tv_sec - time_r_start.tv_sec)+ (time_r_end.tv_usec-time_r_start.tv_usec)/1000000.0); pthread_mutex_lock(&global_lock); running--; printf("Produced %d in %f secs\\n", p, sec); pthread_mutex_unlock(&global_lock); } void* consumer() { int i; FILE * fp = fopen("./test.data","w"); static struct timeval time_r_start; static struct timeval time_r_end; gettimeofday(&time_r_start,0); while(running) { for(i=0;i<8;i++) { if(bp[i]!=(4096)) { continue; } if(pthread_mutex_trylock(&lock[i])!=0) { continue; } fwrite(buffer[i],(4096),1,fp); bp[i] = 0; pthread_mutex_unlock(&lock[i]); } } gettimeofday(&time_r_end,0); double sec = ((double)(time_r_end.tv_sec - time_r_start.tv_sec)+ (time_r_end.tv_usec-time_r_start.tv_usec)/1000000.0); printf("Consumed in %.2f sec\\n", sec); fclose(fp); printf("Closed.\\n"); } int main() { int i; static struct timeval time_r_start; static struct timeval time_r_end; int ts = ((4096) >> 10) * (8) * (1024 << 6) >> 20; printf("data set: %d GB\\n", ts ); pthread_mutex_init(&global_lock, 0); pthread_t tid[8]; gettimeofday(&time_r_start,0); for(i=0;i<8;i++) { pthread_mutex_init(&lock[i], 0); pthread_create(&tid[i], 0, producer, ((void*)(unsigned long)i)); pthread_mutex_lock(&global_lock); running++; pthread_mutex_unlock(&global_lock); } consumer(); for(i<0;i<8;i++) { pthread_join(tid[i], 0); pthread_mutex_destroy(&lock[i]); } gettimeofday(&time_r_end,0); double sec = ((double)(time_r_end.tv_sec - time_r_start.tv_sec)+ (time_r_end.tv_usec-time_r_start.tv_usec)/1000000.0); pthread_mutex_destroy(&global_lock); printf("Fini. %f sec\\n", sec); printf("%.2f MB/s\\n", ((double)ts)*1024/sec); return 0; }
0
#include <pthread.h> pthread_mutex_t forks[(5 -1)]; pthread_mutex_t waiter; void summon_the_boy(int philosopher) { pthread_mutex_lock(&waiter); printf("Philosopher %i snapped his fingers! \\n", philosopher); } void insult_waiter(int philosopher) { printf("Philosopher %i was super condecending! \\n", philosopher); pthread_mutex_unlock(&waiter); } void eat(int philosopher) { printf("Philosopher %i has started eating! \\n", philosopher); usleep(1000); printf("Philosopher %i has finished eating! \\n", philosopher); } void think(int philosopher) { printf("Philosopher %i is thinking super-duper hard! \\n", philosopher); } void get_left_fork(int philosopher) { int left_fork_index = philosopher; pthread_mutex_lock(&forks[left_fork_index]); printf("Philosopher %i got fork %i (left)!\\n", philosopher, left_fork_index); } void get_right_fork(int philosopher) { int right_fork_index = (philosopher-1) % 5; if (right_fork_index == -1) right_fork_index = 5 -1; pthread_mutex_lock(&forks[right_fork_index]); printf("Philosopher %i got fork %i (right)!\\n", philosopher, right_fork_index); } void drop_left_fork(int philosopher) { int left_fork_index = philosopher; printf("Philosopher %i is dropping fork %i (left)!\\n", philosopher, left_fork_index); pthread_mutex_unlock(&forks[left_fork_index]); } void drop_right_fork(int philosopher) { int right_fork_index = (philosopher-1) % 5; if (right_fork_index == -1) right_fork_index = 5 -1; printf("Philosopher %i is dropping fork %i (right)!\\n", philosopher, right_fork_index); pthread_mutex_unlock(&forks[right_fork_index]); } static void *philosophers(int philosopher) { int me = philosopher; while(1) { summon_the_boy(me); think(me); get_left_fork(me); think(me); get_right_fork(me); eat(me); drop_left_fork(me); drop_right_fork(me); insult_waiter(me); } pthread_exit(0); } int main(int argc, char **argv) { pthread_mutex_init(&waiter,0); int count; for (count = 0; count < 5; count++) { pthread_mutex_init(&forks[count],0); } pthread_t great_thinkers[5 -1]; for (count = 0; count < 5; count++) { pthread_create(&great_thinkers[count],0,philosophers,count); } for (count = 0; count < 5; count++) { pthread_join(great_thinkers[count],0); } return 0; }
1
#include <pthread.h> extern char NullAddr[21]; void Talk_Call_Task(int uFlag, const char *call_addr, const char *call_ip); void Talk_Call_End_Task(void); void Talk_Call_TimeOut_Task(void); void Talk_Call_Task(int uFlag, const char * call_addr, const char * call_ip) { int i; int j; uint32_t Ip_Int; j = 0; if ( 2 == uFlag ) { Ip_Int = inet_addr(call_ip); memcpy(&Remote.IP[j], &Ip_Int, 4); LOGD("%d.%d.%d.%d\\n", Remote.IP[j][0], Remote.IP[j][1], Remote.IP[j][2], Remote.IP[j][3]); memcpy(&Remote.Addr[j], LocalCfg.Addr, 20); Remote.Addr[j][0] = 'S'; Remote.Addr[j][7] = call_addr[0]; Remote.Addr[j][8] = call_addr[1]; Remote.Addr[j][9] = call_addr[2]; Remote.Addr[j][10] = call_addr[3]; pthread_mutex_lock(&Local.udp_lock); for (i = 0; i < UDPSENDMAX; i++) { if (Multi_Udp_Buff[i].isValid == 0) { Multi_Udp_Buff[i].SendNum = 0; Multi_Udp_Buff[i].m_Socket = m_VideoSocket; Multi_Udp_Buff[i].RemotePort = RemoteVideoPort; sprintf(Multi_Udp_Buff[i].RemoteHost, "%d.%d.%d.%d", Remote.IP[j][0], Remote.IP[j][1], Remote.IP[j][2], Remote.IP[j][3]); memcpy(&Multi_Udp_Buff[i].RemoteIP, &Multi_Udp_Buff[i].RemoteHost, 20); memcpy(Multi_Udp_Buff[i].buf, UdpPackageHead, 6); Multi_Udp_Buff[i].buf[6] = VIDEOTALK; Multi_Udp_Buff[i].buf[7] = ASK; Multi_Udp_Buff[i].buf[8] = CALL; memcpy(Multi_Udp_Buff[i].buf + 9, LocalCfg.Addr, 20); memcpy(Multi_Udp_Buff[i].buf + 29, LocalCfg.IP, 4); memcpy(Multi_Udp_Buff[i].buf + 33, Remote.Addr[j], 20); memcpy(Multi_Udp_Buff[i].buf + 53, Remote.IP[j], 4); Multi_Udp_Buff[i].buf[57] = 0; memcpy(Multi_Udp_Buff[i].buf + 58, Remote.IP, 4); Multi_Udp_Buff[i].nlength = 62; Multi_Udp_Buff[i].DelayTime = DIRECTCALLTIME; Multi_Udp_Buff[i].SendDelayTime = 0; Multi_Udp_Buff[i].isValid = 1; sem_post(&multi_send_sem); break; } } pthread_mutex_unlock(&Local.udp_lock); } } void Talk_Call_End_Task(void) { int i, j; pthread_mutex_lock(&Local.udp_lock); for (i = 0; i < UDPSENDMAX; i++) { if (Multi_Udp_Buff[i].isValid == 0) { memcpy(Multi_Udp_Buff[i].buf, UdpPackageHead, 6); Multi_Udp_Buff[i].buf[6] = VIDEOTALK; Multi_Udp_Buff[i].buf[7] = ASK; Multi_Udp_Buff[i].buf[8] = CALLEND; Multi_Udp_Buff[i].SendNum = 0; Multi_Udp_Buff[i].m_Socket = m_VideoSocket; Multi_Udp_Buff[i].RemotePort = RemoteVideoPort; Multi_Udp_Buff[i].CurrOrder = VIDEOTALK; sprintf(Multi_Udp_Buff[i].RemoteHost, "%d.%d.%d.%d", Remote.IP[j][0], Remote.IP[j][1], Remote.IP[j][2], Remote.IP[j][3]); printf("%d.%d.%d.%d\\n", Remote.IP[j][0], Remote.IP[j][1], Remote.IP[j][2], Remote.IP[j][3]); memcpy(Multi_Udp_Buff[i].buf + 9, LocalCfg.Addr, 20); memcpy(Multi_Udp_Buff[i].buf + 29, LocalCfg.IP, 4); memcpy(Multi_Udp_Buff[i].buf + 33, Remote.Addr[j], 20); memcpy(Multi_Udp_Buff[i].buf + 53, Remote.IP[j], 4); Multi_Udp_Buff[i].nlength = 57; Multi_Udp_Buff[i].DelayTime = DIRECTCALLTIME; Multi_Udp_Buff[i].SendDelayTime = 0; Multi_Udp_Buff[i].isValid = 1; sem_post(&multi_send_sem); Local.Status = 0; break; } } pthread_mutex_unlock(&Local.udp_lock); } void Talk_Call_TimeOut_Task(void) { Talk_Call_End_Task(); Local.OnlineFlag = 0; printf("call timeout\\n"); }
0
#include <pthread.h> int room_number; long expiry_time; struct node *next; } Node; Node *head; int pending; pthread_mutex_t mutex; pthread_cond_t cond; } shared_data_t; Node *insert(Node *head, int room_number, long expiry_time) { Node *newNode = (Node*) malloc(sizeof(Node)); Node *previousNode, *currentNode; newNode->room_number = room_number; newNode->expiry_time = expiry_time; if (head == 0) { newNode->next = 0; return newNode; } if (expiry_time < head->expiry_time) { newNode->next = head; return newNode; } previousNode = head; currentNode = head->next; while (currentNode != 0 && expiry_time > currentNode->expiry_time) { previousNode = currentNode; currentNode = currentNode->next; } newNode->next = previousNode->next; previousNode->next = newNode; return head; } Node *removeFirst(Node *head) { Node *tempNode = head->next; free(head); return tempNode; } void cleanup_guest(void * data_in) { printf("The guest thread is cleaning up...\\n"); printf("The guest thread says goodbye.\\n"); } void cleanup_waiter(void * data_in) { shared_data_t * data = (shared_data_t *) data_in; printf("The waiter thread is cleaning up...\\n"); while(data->head != 0) { data->head = removeFirst(data->head); data->pending--; } pthread_mutex_unlock(&data->mutex); printf("The waiter thread says goodbye\\n"); } void * guest(void *data_in) { shared_data_t *data = (shared_data_t *) data_in; int room_number; long expiry_time; unsigned int seed = time(0); pthread_cleanup_push(cleanup_guest, (void *)0); while(1) { pthread_mutex_lock(&data->mutex); room_number = 1 + (rand_r(&seed) % 5000); expiry_time = time(0) + (rand_r(&seed) % 100); data->pending++; printf("Registering:\\t%d %s\\n", room_number, ctime(&expiry_time)); data->head = insert(data->head, room_number, expiry_time); if(expiry_time == data->head->expiry_time) { pthread_cond_signal(&data->cond); } pthread_mutex_unlock(&data->mutex); sleep(rand_r(&seed) % 5); } pthread_cleanup_pop(0); return ((void *)0); } void * waiter(void *data_in) { shared_data_t *data = (shared_data_t *) data_in; int expired = 0, error; struct timespec timeout; pthread_cleanup_push(cleanup_waiter, (void *)data); while(1) { pthread_mutex_lock(&data->mutex); while(data->head == 0) { pthread_cond_wait(&data->cond, &data->mutex); } timeout.tv_sec = data->head->expiry_time; timeout.tv_nsec = 0; error = pthread_cond_timedwait(&data->cond, &data->mutex, &timeout); if(error == ETIMEDOUT) { expired++; data->pending--; printf("Wake up:\\t%d %s\\n", data->head->room_number, ctime(&data->head->expiry_time)); printf("Expired alarms:\\t%d\\n", expired); printf("Pending alarms:\\t%d\\n\\n", data->pending); data->head = removeFirst(data->head); } pthread_mutex_unlock(&data->mutex); } pthread_cleanup_pop(0); return ((void *)0); } int main() { int sig; sigset_t set; pthread_t g, w; shared_data_t data; data.head = 0; data.pending = 0; pthread_mutex_init(&data.mutex, 0); pthread_cond_init(&data.cond, 0); pthread_create(&g, 0, guest, (void *) &data); pthread_create(&w, 0, waiter, (void *) &data); sigaddset(&set, SIGINT); sigprocmask(SIG_BLOCK, &set, 0); sigwait(&set, &sig); pthread_cancel(g); pthread_cancel(w); pthread_join(g, 0); pthread_join(w, 0); pthread_mutex_destroy(&data.mutex); printf("Pending: %d\\n", data.pending); return 0; }
1
#include <pthread.h> struct object_slab { struct linked_list slabs_list; void * ready_list; unsigned int used_objects; unsigned long object_memory[]; }; static void corrupted_canary(const void * object) ; static void corrupted_canary(const void * object) { printf("memory overrun on object %p\\n", object); abort(); } void slab_create(struct slab_allocator * allocator, unsigned int objcount, unsigned int objsize, int canary) { pthread_mutex_init(&allocator->global_lock, 0); allocator->slabs_list.next = &allocator->slabs_list; allocator->slabs_list.prev = &allocator->slabs_list; objsize += sizeof(void *) - 1; objsize &= ~(sizeof(void *) - 1); canary = canary != 0; allocator->object_count = objcount; allocator->object_size = objsize; allocator->canary_check = canary; } void * slab_alloc(struct slab_allocator * allocator) { struct linked_list * list; struct object_slab * slab; void * before; void * object; pthread_mutex_lock(&allocator->global_lock); list = allocator->slabs_list.next; if (list == &allocator->slabs_list) { unsigned int i; slab = malloc(((sizeof(void *) << allocator->canary_check) + allocator->object_size) * allocator->object_count + sizeof(struct object_slab)); if (slab == 0) { object = 0; goto unlock_finish; } allocator->slabs_list.next = &slab->slabs_list; allocator->slabs_list.prev = &slab->slabs_list; slab->slabs_list.next = &allocator->slabs_list; slab->slabs_list.prev = &allocator->slabs_list; before = &slab->ready_list; object = slab->object_memory; for (i = 0; i < allocator->object_count; i++) { *((void **)before) = object; before = object; object += allocator->object_size; if (allocator->canary_check != 0) { *((void **)object) = allocator; object += sizeof(void *); } *((void **)object) = slab; object += sizeof(void *); } *((void **)before) = 0; slab->used_objects = 0; } else { slab = (void *)list - ((unsigned long)&((struct object_slab *)0)->slabs_list); } slab->used_objects++; object = slab->ready_list; slab->ready_list = *((void **)object); if (slab->ready_list == 0) { slab->slabs_list.next->prev = slab->slabs_list.prev; slab->slabs_list.prev->next = slab->slabs_list.next; } unlock_finish: pthread_mutex_unlock(&allocator->global_lock); return object; } void slab_free(struct slab_allocator * allocator, void * object) { void * lookup; struct object_slab * slab; struct object_slab * comp; struct linked_list * next; struct linked_list * prev; lookup = object; lookup += allocator->object_size; if (allocator->canary_check != 0) { if (*((void **)lookup) != allocator) corrupted_canary(object); lookup += sizeof(void *); } slab = *((void **)lookup); pthread_mutex_lock(&allocator->global_lock); slab->used_objects--; if (slab->ready_list != 0) { next = slab->slabs_list.next; prev = slab->slabs_list.prev; if (next == &allocator->slabs_list) goto insert_obj; next->prev = prev; prev->next = next; } else { prev = &allocator->slabs_list; next = prev->next; goto insert_slab; } for (;;) { comp = 0; if (next == &allocator->slabs_list) break; comp = (void *)next - ((unsigned long)&((struct object_slab *)0)->slabs_list); if (slab->used_objects >= comp->used_objects) break; prev = next; next = next->next; } if (comp != 0 && comp->used_objects == 0 && slab->used_objects == 0) goto unlock_finish; insert_slab: next->prev = &slab->slabs_list; prev->next = &slab->slabs_list; slab->slabs_list.next = next; slab->slabs_list.prev = prev; insert_obj: *((void **)object) = slab->ready_list; slab->ready_list = object; slab = 0; unlock_finish: pthread_mutex_unlock(&allocator->global_lock); if (slab != 0) free(slab); }
0
#include <pthread.h> pthread_t thread_id; pthread_mutex_t mutex_count; pthread_cond_t thr_con,pro_con; int thread_count =0; int ticket =100; sem_t *semaphore,*empty,*full; void hand(int sig) { printf("clearing\\n"); sem_close(semaphore); sem_close(empty); sem_close(full); sem_unlink("/empty"); sem_unlink("/full"); sem_unlink("/semaphore"); exit(0); } void* book_ticket(void *p) { int *x = (int *)p; pthread_mutex_lock(&mutex_count); thread_count ++; sleep(2); if(thread_count > 10) pthread_cond_wait(&thr_con,&mutex_count); printf("request received :%d",*x); if((ticket -*x)>=0) { if(100<=(ticket-*x)) ticket =100; else ticket = ticket-*x; } else { printf("request cannot be fulfilled\\n"); } sleep(rand()%3); printf("tic: %d\\n",ticket); if(thread_count<=5) pthread_cond_signal(&pro_con); pthread_cond_signal(&thr_con); pthread_mutex_unlock(&mutex_count); thread_count--; pthread_exit(0); } int main(int argc, char const *argv[]) { signal(SIGINT,hand); int shmid,shmid1,shmid2; key_t key1,key2,key3; key1 = 5678; key2 = 3567; key3 = 3891; pthread_t tid; shmid = shmget(key1,11*sizeof(int),IPC_CREAT | 0666); shmid1 = shmget(key2,sizeof(int),IPC_CREAT | 0666); shmid2 = shmget(key3,sizeof(int),IPC_CREAT | 0666); if(shmid==-1) { printf("shmget\\n"); exit(1); } if(shmid1==-1) { printf("shmget\\n"); exit(1); } if(shmid2==-1) { printf("shmget\\n"); exit(1); } semaphore = sem_open("/semaphore", O_RDWR); empty = sem_open("/empty", O_RDWR); full = sem_open("/full", O_RDWR); int *que = (int *)shmat(shmid,0,0); int *head = (int *)shmat(shmid1,0,0); int *tail = (int *)shmat(shmid2,0,0); pthread_mutex_init(&mutex_count, 0); pthread_cond_init(&pro_con, 0); pthread_cond_init(&thr_con, 0); while(1) { sleep(1); sem_wait(full); sem_wait(semaphore); if(*head == -1) printf("\\n\\nQueue is empty.\\n"); else { int item = que[*head]; if(thread_count>10) pthread_cond_wait(&pro_con,&mutex_count); if(*head == *tail) { *head = -1; *tail = -1; } else if(*head == 9) *head = 0; else (*head)++; int p = pthread_create(&tid, 0, book_ticket,(void *) &item); } sem_post(semaphore); sem_post(empty); } return 0; }
1
#include <pthread.h> int run_op(const char* command) { FILE *fp; char path[1035]; fp = popen(command, "r"); if (fp == 0) { fprintf(stderr, "Failed to run command %s\\n", command ); return(1); } while (fgets(path, sizeof(path), fp) != 0) { fprintf(stdout, "%s", path); } pclose(fp); return 0; } volatile uint8_t running_threads = 0; pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_function(void *arg) { pthread_mutex_lock(&running_mutex); running_threads--; pthread_mutex_unlock(&running_mutex); param_t id = (param_t)arg; fprintf(stdout, "Thread %lu (pid=%d, ppid=%d) alive.\\n", id, getpid(), getppid()); sleep(3); fprintf(stdout, "Thread %lu dying.\\n", id); pthread_exit(arg); } int main(int argc, char *argv[]) { int i, j, len, total, status, num_threads=0, fd, pid; char testbuf[129]; pthread_t threads[100]; if(argc >= 2) { num_threads = atoi(argv[1]); } else { fprintf(stdout, " help menu..\\n"); fprintf(stdout, " ./testApp_ch4 arg1\\n"); fprintf(stdout, " arg1: number of children to spawn (<100)\\n"); return 0; } fprintf(stdout, "Spawning %d child threads\\n", num_threads); pthread_mutex_lock(&running_mutex); for (i=0; i<num_threads; ++i) { param_t tid = i; running_threads++; if((status = pthread_create(&threads[i], 0, thread_function, (void*)tid)) != 0) { fprintf(stderr,"ERR:on pthread_create(%d):%s\\n",i,strerror(errno)); break; } } num_threads = i; pthread_mutex_unlock(&running_mutex); fprintf(stdout, "Successfully created %d child threads\\n", num_threads); while (running_threads > 0) { usleep(500000); } fprintf(stdout, "Output from reading /proc/myps:\\n"); pid = getpid(); printf("My TESTPID is %d (mine=%d,mypar=%d)\\n", pid, getpid(), getppid()); sprintf(testbuf, "/bin/echo %d > /proc/myps", pid); run_op(testbuf); run_op("/bin/cat /proc/myps"); pthread_exit(0); return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo *foo_alloc(int id) { struct foo *fp; int idx; if((fp = (struct foo *)malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)id) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->f_next) { if(fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if(--fp->f_count == 0) { idx = (((unsigned long)fp->f_id) % 29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; } else { while(tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else pthread_mutex_unlock(&hashlock); }
1
#include <pthread.h> pthread_mutex_t mutexid; pthread_mutex_t mutexres; int idcount = 0; pthread_mutex_t joinmutex[2]; int join[2]; int result[2]; int target; int sequence[(2 * 30)]; void *thread (void *arg) { int id, i, from, count, l_target; pthread_mutex_lock (&mutexid); l_target = target; id = idcount; idcount++; pthread_mutex_unlock (&mutexid); __VERIFIER_assert (id >= 0); __VERIFIER_assert (id <= 2); from = id * 30; count = 0; for (i = 0; i < 30; i++) { if (sequence[from + i] == l_target) { count++; } if (count > 30) { count = 30; } } printf ("t: id %d from %d count %d\\n", id, from, count); pthread_mutex_lock (&mutexres); result[id] = count; pthread_mutex_unlock (&mutexres); pthread_mutex_lock (&joinmutex[id]); join[id] = 1; pthread_mutex_unlock (&joinmutex[id]); return 0; } int main () { int i; pthread_t t[2]; int count; i = __VERIFIER_nondet_int (0, (2 * 30)-1); sequence[i] = __VERIFIER_nondet_int (0, 3); target = __VERIFIER_nondet_int (0, 3); printf ("m: target %d\\n", target); pthread_mutex_init (&mutexid, 0); pthread_mutex_init (&mutexres, 0); for (i = 0; i < 2; i++) { pthread_mutex_init (&joinmutex[i], 0); result[i] = 0; join[i] = 0; } i = 0; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; __VERIFIER_assert (i == 2); int j; i = 0; pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } if (i != 2) { return 0; } __VERIFIER_assert (i == 2); count = 0; for (i = 0; i < 2; i++) { count += result[i]; printf ("m: i %d result %d count %d\\n", i, result[i], count); } printf ("m: final count %d\\n", count); __VERIFIER_assert (count >= 0); __VERIFIER_assert (count <= (2 * 30)); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; int waiting_students; char locks_and_semaphores_init(); void destroy_locks_and_semaphores(); void create_student_threads (pthread_t t_ids[], unsigned int t_indexes[]); void join_student_threads (pthread_t t_ids[], unsigned int t_indexes[]); void create_ta_thread(); void cancel_ta_thread(pthread_t t_id); void* student_routine(unsigned int * index); void* ta_routine(); void take_a_seat (unsigned int index, int * num_helps_remained); void programming (unsigned int index, unsigned int *seed); int main() { if (locks_and_semaphores_init()) { printf("CS149 SleepingTA from Ly Nguyen\\n"); pthread_t ta_t_id; create_ta_thread(&ta_t_id); pthread_t student_thread_ids[4]; unsigned int student_indexes[4]; create_student_threads(student_thread_ids, student_indexes); join_student_threads(student_thread_ids, student_indexes); cancel_ta_thread(ta_t_id); } destroy_locks_and_semaphores(); return 0; } char locks_and_semaphores_init() { if (pthread_mutex_init(&mutex_lock, 0) != 0) { printf("error: failed to initialize mutex lock"); return 0; } if (sem_init(&students_sem, 0, 0) != 0 || sem_init(&ta_sem, 0, 0) != 0) { printf("error: failed to initialize semaphores"); return 0; } return 1; } void destroy_locks_and_semaphores() { pthread_mutex_destroy(&mutex_lock); sem_destroy(&ta_sem); sem_destroy(&students_sem); } void create_student_threads(pthread_t t_ids[], unsigned int t_indexes[]) { int i = 0; for (; i < 4; i++) { t_indexes[i] = i; if (pthread_create(&t_ids[i], 0, (void*) student_routine, &t_indexes[i])) printf("error: couldn't create student thread %d/n", t_indexes[i]); } } void join_student_threads(pthread_t t_ids[], unsigned int t_indexes[]) { int i = 0; for (; i < 4; i++) { if (pthread_join(t_ids[i], 0)) printf("error: coudn't join student thread %d\\n", t_indexes[i]); } } void create_ta_thread(pthread_t* t_id) { if (pthread_create(t_id, 0, (void*) ta_routine, 0)) printf("error: couldn't create TA thread\\n"); } void cancel_ta_thread(pthread_t t_id) { if (pthread_cancel(t_id)) printf("error: fail to cancel TA thread"); } void* student_routine(unsigned int * index) { int n_helps = 2; unsigned int seed = *index; seed = rand_r(&seed); while(n_helps) { programming(*index, &seed); take_a_seat(*index, &n_helps); } return 0; } void* ta_routine() { unsigned int seed = time(0); while(1) { sem_wait(&ta_sem); unsigned int t = (rand_r(&seed) % 3) + 1; pthread_mutex_lock(&mutex_lock); pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sleep(t); } return 0; } void programming(unsigned int index, unsigned int *seed) { int t = (rand_r(seed) % 3) + 1; printf(" Student %d programming for %d seconds\\n", index, t); sleep(t); } void take_a_seat(unsigned int index, int * num_helps_remained) { pthread_mutex_lock(&mutex_lock); if (waiting_students < 2) { pthread_mutex_unlock(&mutex_lock); sem_post(&ta_sem); sem_wait(&students_sem); printf("Student %d receiving help\\n", index); (*num_helps_remained)--; } else { pthread_mutex_unlock(&mutex_lock); printf(" Student %d will try later\\n", index); } }
1
#include <pthread.h> volatile int a2lFD = -1; volatile int l2aFD = -1; pthread_mutex_t * mutex; void bailout(); static void startup() { printf("initializing audit library\\n"); l2aFD = open(PIPE_L2A, O_WRONLY); if (l2aFD == -1) { perror("could not open pipe from library to auditor"); exit(1); } fcntl(l2aFD, F_SETPIPE_SZ, 1024); usleep(100000); a2lFD = open(PIPE_A2L, O_RDONLY); if (a2lFD == -1) { perror("could open pipe from auditor to library"); exit(1); } pthread_mutex_init(mutex, 0); printf("done\\n"); } extern unsigned la_version(unsigned version) { return version; } extern void la_preinit( uintptr_t * cookie) { printf("Initial library loading finished\\n"); } static void shutdown() { printf("audit library shutdown\\n"); pthread_mutex_lock(mutex); close(a2lFD); a2lFD = -1; close(l2aFD); l2aFD = -1; pthread_mutex_unlock(mutex); } extern char * la_objsearch(const char * name, uintptr_t * cookie, unsigned flag) { printf("rtld is searching for symbol in library %s\\n", name); if(strcmp("libdl.so.2", name) == 0) return (char *) name; if(strcmp("/lib64/libdl.so.2", name) == 0) return (char *) name; if(strcmp("libc.so.6", name) == 0) return (char *) name; if(strcmp("/lib64/libc.so.6", name) == 0) return (char *) name; pthread_mutex_lock(mutex); if (l2aFD > -1 && a2lFD > -1) { write(l2aFD, name, strlen(name)+1); char auditResult = 0; printf("retrieving from %d\\n", a2lFD); ssize_t size = read(a2lFD, &auditResult, sizeof(char)); if(size == -1) { perror("Encountered an error retrieving the audit result"); bailout(); } if (auditResult) { printf("loading of %s accepted\\n", name); pthread_mutex_unlock(mutex); return (char *) name; } else { printf("loading of %s denied: %d\\n", name, auditResult); pthread_mutex_unlock(mutex); shutdown(); return 0; } } else { printf("lost connection to auditor"); bailout(); } return (char *) name; } void bailout() { close(l2aFD); char buf = 0; fcntl(a2lFD, F_SETFL, O_RDONLY|O_NONBLOCK); read(a2lFD, &buf, sizeof(char)); close(a2lFD); exit(1); }
0
#include <pthread.h> struct philosopher { pthread_t tid ; pthread_cond_t cond ; int status ; } phi_buf[5] ; pthread_mutex_t phi_lock ; void print_status () { int i ; for (i = 0 ; i < 5 ; ++i ) { if (phi_buf[i].status == 0 ) printf ("哲学家 %d 正在思考\\n" , i) ; else if (phi_buf[i].status == 1 ) { printf ("哲学家 %d 很饿 \\n" , i) ; } else { printf ("哲学家 %d 正在吃吃吃吃吃吃 ~~~ \\n" , i) ; } } } void init_philosopher () { int i ; if (pthread_mutex_init (&phi_lock , 0 ) != 0 ) { perror ("Pthread_mutx_init error !") ; exit (1) ; } for ( i = 0 ; i < 5 ; ++i ) { phi_buf[i].status = 0 ; } } int test (int argu ) { if ( (phi_buf[argu].status == 1 )&& (phi_buf[((argu-1+5)%5)].status != 2) && (phi_buf[((argu+1)%5)].status != 2) ) { return 1 ; } else { return 0 ; } } void take_fork (int argu) { pthread_mutex_lock (&phi_lock) ; phi_buf[argu].status = 1 ; if ( test (argu) ) { phi_buf[argu].status = 2 ; printf ("哲学家 %d 正在进食 ~~~ \\n" , argu) ; print_status () ; phi_buf[argu].status = 0 ; if (test (((argu-1+5)%5))) { phi_buf[((argu-1+5)%5)].status = 2 ; printf ("哲学家 %d 正在进食 ~~~ \\n" , ((argu-1+5)%5)) ; pthread_cond_signal (&(phi_buf[((argu-1+5)%5)].cond)) ; print_status () ; } if (test (((argu+1)%5))) { phi_buf[((argu+1)%5)].status = 2 ; printf ("哲学家 %d 正在进食 ~~~ \\n" , ((argu+1)%5)) ; print_status () ; pthread_cond_signal (&(phi_buf[((argu+1)%5)].cond)) ; } pthread_mutex_unlock (&phi_lock) ; } else { pthread_cond_wait (&(phi_buf[argu].cond) , &phi_lock) ; } } void * func (void * argu) { while (1 ) { take_fork (argu) ; sleep (1) ; } } void create_pthread (void * (*fun)(void*) , int data) { pthread_t tid ; if (pthread_create (&tid , 0 , fun , (void*)data ) != 0 ) { perror ("Pthread_create error !") ; exit (1) ; } phi_buf[data].tid = tid ; if (pthread_cond_init(&(phi_buf[data].cond) , 0 ) != 0 ) { perror ("Pthread_cond_init error !") ; exit (1) ; } pthread_detach (tid) ; } int main(int argc, char *argv[]) { init_philosopher () ; create_pthread (func , 0) ; create_pthread (func , 1) ; create_pthread (func , 2) ; create_pthread (func , 3) ; create_pthread (func , 4) ; sleep (100000) ; return 0; }
1
#include <pthread.h> pthread_mutex_t forks[5]; pthread_t phils[5]; void *philosopher (void *id); int food_on_table (); void get_fork (int, int, char *); void down_forks (int, int); pthread_mutex_t foodlock; int sleep_seconds = 0; int main (int argn, char **argv) { int i; if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&foodlock, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&forks[i], 0); for (i = 0; i < 5; i++) pthread_create (&phils[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (phils[i], 0); return 0; } void * philosopher (void *num) { int id; int left_fork, right_fork, f; id = (int)num; printf ("Philosopher %d sitting down to dinner.\\n", id); right_fork = id; left_fork = id + 1; if (left_fork == 5) left_fork = right_fork; right_fork = 0; while (f = food_on_table ()) { if (id == 1) sleep (sleep_seconds); printf ("Philosopher %d: get dish %d.\\n", id, f); get_fork (id, right_fork, "right"); get_fork (id, left_fork, "left"); printf ("Philosopher %d: eating.\\n", id); usleep (30000 * (50 - f + 1)); down_forks (left_fork, right_fork); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table () { static int food = 50; int myfood; pthread_mutex_lock (&foodlock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&foodlock); return myfood; } void get_fork (int phil, int fork, char *hand) { pthread_mutex_lock (&forks[fork]); printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork); } void down_forks (int f1, int f2) { pthread_mutex_unlock (&forks[f1]); pthread_mutex_unlock (&forks[f2]); }
0
#include <pthread.h> pthread_t tid[4]; pthread_mutex_t lock; unsigned int length, TOTAL_BYTES, READED_BYTES, sub_length, total_found = 0; int counter = 0; long long pos = 0; char target[256]; FILE* file; char* data; int finished = 0; unsigned int string_search(char* data,int length) { unsigned int i; unsigned int found=0; if(length < strlen(target)) return 0; for (i=0;i < length-strlen(target); i++) { if (strncmp(&data[i],target,strlen(target))==0) { found++; } } return found; } void* thread_work(void *arg) { counter++; printf("Job %d started\\n", counter); while(!finished) { pthread_mutex_lock(&lock); if(TOTAL_BYTES == READED_BYTES < 5000) { sub_length = TOTAL_BYTES - READED_BYTES; } else { sub_length = 5000; while(data[READED_BYTES + sub_length] != '\\n') { sub_length++; if(READED_BYTES + sub_length == TOTAL_BYTES) break; } } if(READED_BYTES >= TOTAL_BYTES) { finished = 1; } pthread_mutex_unlock(&lock); string_search(data + READED_BYTES ,sub_length); } printf("Job %d finished\\n", counter); return 0; } int main(int argc, char** argv) { time_t a, b; a = time(0); if (argc < 2) { printf("Please pass an input file.\\n"); return 0; } file = fopen(argv[1], "r"); if (!file) { printf("Could not open %s for reading.\\n", argv[1]); return 0; } fseek(file, 0L, 2); length = ftell(file); TOTAL_BYTES = length * sizeof(char); fseek(file, 0L, 0); data = malloc(length * sizeof(char) + 1); memset(data, 0, length); fread(data, sizeof(char), length, file); b = time(0); double read = difftime(b, a); printf("Reading took %lf seconds.\\n", read); a = time(0); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } int i; int err; for(i = 0; i < 1; i++){ err = pthread_create(&(tid[i]), 0, &thread_work, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); } pthread_join(tid[0], 0); pthread_mutex_destroy(&lock); b = time(0); double search = difftime(b, a); printf("Searching took %lf seconds.\\n", search); if (total_found) { printf("Found it! %d times\\n", total_found); } else { printf("Not found...\\n"); } return 0; }
1
#include <pthread.h> int j = 0; pthread_mutex_t mutex; pthread_cond_t * cases; pthread_cond_t cercle; pthread_cond_t attente_robots; int * cases_reader; int nb_attente; pthread_t cercle_tid; void init_circle() { int i; nb_attente = 0; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cercle, 0); pthread_cond_init(&attente_robots, 0); cases = malloc(16 * sizeof(pthread_cond_t)); cases_reader = malloc(16 * sizeof(int)); for (i = 0; i < 16; i++) { cases_reader[i] = 0; pthread_cond_init(&cases[i], 0); } } void signal_fin_robot_handler() { pthread_mutex_lock(&mutex); printf("2.1 %d signal_fin_robot_handler : signal robot reçu\\n", j++); nb_attente++; if(nb_attente >= 1) { printf("2.2 %d signal_fin_robot_handler : on debloque le cercle qui attend les robots (%d/%d)\\n", j++, nb_attente, 1); pthread_cond_signal(&attente_robots); printf("2.2 %d signal_fin_robot_handler : on a debloque le cercle qui attend les robots (%d/%d)\\n", j++, nb_attente, 1); } pthread_mutex_unlock(&mutex); } void * func_circle(void * arg) { while(1<=1) { printf("0.1 func_circle : Fait tourner le cercle\\n"); pthread_mutex_lock(&mutex); printf("0.2 %d func_circle : on debloque les robots\\n", j++); pthread_cond_broadcast(&cercle); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if(nb_attente < 1) { printf("0.3 %d func_circle : attente arrivée robot (deblocage handler)\\n", j++); pthread_cond_wait(&attente_robots, &mutex); printf("0.4 %d func_circle : le handler nous debloque\\n", j++); } else { printf("0.5 %d func_circle : les robot sont déja la\\n", j++); } nb_attente = 0; pthread_mutex_unlock(&mutex); } } void * func_robot(void * arg) { while(1<=1) { pthread_mutex_lock(&mutex); printf("1.1 %d func_robot : signal cercle (SIGUSR1)\\n", j++); pthread_kill(cercle_tid, SIGUSR1); printf("1.2 %d func_robot : attend cercle debloque les robots\\n", j++); pthread_cond_wait(&cercle, &mutex); pthread_mutex_unlock(&mutex); printf("1.3 func_robot : faire le robot\\n"); } } int main() { pthread_t robot_tid; printf("main\\n"); signal(SIGUSR1, signal_fin_robot_handler); printf("signal\\n"); init_circle(); printf("init_circle\\n"); pthread_mutex_lock(&mutex); printf("pthread_mutex_lock\\n"); pthread_create(&cercle_tid, 0, func_circle, 0); printf("pthread_create\\n"); pthread_create(&robot_tid, 0, func_robot, 0); printf("pthread_create\\n"); pthread_mutex_unlock(&mutex); printf("pthread_mutex_unlock\\n"); pthread_join(robot_tid, 0); pthread_join(cercle_tid, 0); exit (0); }
0
#include <pthread.h> struct data { long counter[256]; }; const int SIZE = sizeof(struct data); static pthread_mutex_t output_mutex; static struct data data; void *run(void *raw_name) { time_t thread_start = time(0); char *name = (char *) raw_name; int fd = -1; time_t open_start = time(0); while (fd == -1) { fd = open(raw_name, O_RDONLY); if (fd < 0 && errno == EMFILE) { sleep(1); continue; } if (fd < 0) { char msg[256]; sprintf(msg, "error while opening file=%s", name); } } time_t open_duration = time(0) - open_start; time_t total_mutex_wait = 0; char buffer[16384]; struct data local_data; long *scounter = local_data.counter; while (1) { ssize_t size_read = read(fd, buffer, 16384); if (size_read == 0) { break; } if (size_read < 0) { char msg[256]; sprintf(msg, "error while reading file=%s", name); } int i; for (i = 0; i < size_read; i++) { unsigned char c = buffer[i]; scounter[c]++; } } close(fd); time_t thread_duration = time(0) - thread_start; unsigned int i; long *tcounter = data.counter; pthread_mutex_lock(&output_mutex); printf("------------------------------------------------------------\\n"); printf("%s: pid=%ld\\n", name, (long) getpid()); printf("open duration: ~ %ld sec; total wait for data: ~ %ld sec; thread duration: ~ %ld\\n", (long) open_duration, (long) total_mutex_wait, (long) thread_duration); printf("------------------------------------------------------------\\n"); for (i = 0; i < 256; i++) { tcounter[i] += scounter[i]; long val = tcounter[i]; if (! (i & 007)) { printf("\\n"); } if ((i & 0177) < 32 || i == 127) { printf("\\\\%03o: %10ld ", i, val); } else { printf("%4c: %10ld ", (char) i, val); } } printf("\\n\\n"); printf("------------------------------------------------------------\\n\\n"); fflush(stdout); pthread_mutex_unlock(&output_mutex); return 0; } int main(int argc, char *argv[]) { if (argc < 2) { printf("Usage\\n\\n"); printf("%s file1 file2 file3 ... filen\\ncount files, show accumulated output after having completed one file\\n\\n", argv[0]); exit(1); } time_t start_time = time(0); int retcode = 0; int i; printf("%d files will be read\\n", argc-1); fflush(stdout); for (i = 0; i < 256; i++) { data.counter[i] = 0L; } retcode = pthread_mutex_init(&output_mutex, 0); pthread_t *threads = malloc((argc-1)*sizeof(pthread_t)); for (i = 1; i < argc; i++) { retcode = pthread_create(&(threads[i-1]), 0, run, argv[i]); } pthread_mutex_lock(&output_mutex); printf("%d threads started\\n", argc-1); fflush(stdout); pthread_mutex_unlock(&output_mutex); for (i = 0; i < argc-1; i++) { retcode = pthread_join(threads[i], 0); } retcode = pthread_mutex_destroy(&output_mutex); time_t total_time = time(0) - start_time; printf("total %ld sec\\n", (long) total_time); printf("done\\n"); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void *taxi_arrive( void *p ) { char *name = (char *)p; printf( "taxi %s has arrived and waitting\\n",name ); pthread_mutex_lock( &mutex ); pthread_cond_wait( &cond,&mutex ); pthread_mutex_unlock( &mutex ); printf( "taxi %s has left with a clientele\\n",name ); pthread_exit(0); } void *traveler_arrive( void *p ) { char *name = ( char * )p; printf( "traveler %s has arrived\\n",name ); pthread_cond_signal( &cond ); pthread_exit(0); } int main() { char *name; pthread_t tid; pthread_mutex_init( &mutex,0 ); pthread_cond_init( &cond,0 ); name="jack"; pthread_create( &tid,0,taxi_arrive,name ); name="susan"; pthread_create( &tid,0,traveler_arrive,name ); sleep(1); name="mike"; pthread_create( &tid,0,taxi_arrive,name ); sleep(1); return 0; }
0
#include <pthread.h> int fd = -1; char *network_interface; char *serial_device; char *log_file; char *netaddr; char *netmask; FILE *fplog; pthread_mutex_t mutex1,mutex2, mutexlog; pthread_cond_t cond2,condlog; pthread_t tid1,tid2,tid3, tid4; struct frame_queue *sendque_head; struct frame_queue *recvque_head; struct msg_queue *msgque_head; int sendque_total = 0; int recvque_total = 0; int msgque_total = 0; void get_now_str(char *s_time){ struct tm *tmp; struct timeval tv; gettimeofday(&tv,0); tmp=localtime(&tv.tv_sec); sprintf(s_time,"%04d/%02d/%02d %02d:%02d:%02d.%3d", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, tv.tv_usec/1000); } void ipv6_addr_print(u_char *ip_addr){ unsigned int i; for(i = 0;i < 16;i++){ printf("%02x:",ip_addr[i]); } printf("\\n"); } void serial_init(int fd) { struct termios tio; memset(&tio, 0, sizeof(tio)); cfmakeraw(&tio); tio.c_cc[VTIME] = 0; tio.c_cc[VMIN] = 0; cfsetispeed(&tio, BAUDRATE); cfsetospeed(&tio, BAUDRATE); tcsetattr(fd, TCSANOW, &tio); } unsigned short crc( unsigned const char *pData, unsigned long lNum ) { unsigned int crc16 = 0xFFFFU; unsigned long i; int j; for ( i = 0 ; i < lNum ; i++ ){ crc16 ^= (unsigned int)pData[i]; for ( j = 0 ; j < 8 ; j++ ){ if ( crc16 & 0x0001 ){ crc16 = (crc16 >> 1) ^ 0xA001; }else { crc16 >>= 1; } } } return (unsigned short)(crc16); } unsigned short checksum(unsigned short *buf, int bufsize) { unsigned long sum = 0; while (bufsize > 1){ sum += *buf; buf++; bufsize -= 2; } if( bufsize == 1 ){ sum += *(unsigned char *)buf; } sum = (sum & 0xffff) + (sum >> 16); sum = (sum & 0xffff) + (sum >> 16); return ~sum; } void sigcatch(){ pthread_kill(tid1,SIGTERM); pthread_kill(tid2,SIGTERM); pthread_kill(tid3,SIGTERM); pthread_kill(tid4,SIGTERM); pthread_mutex_destroy(&mutex1); pthread_mutex_destroy(&mutex2); pthread_mutex_destroy(&mutexlog); pthread_cond_destroy(&cond2); pthread_cond_destroy(&condlog); fclose(fplog); exit(1); } void enq_log(char *msg){ struct msg_queue *data; struct msg_queue *temp; char msg_with_date[200]; char time_now[50]; char error_msg[] = "over msg length\\n"; get_now_str(time_now); data = (struct msg_queue*)malloc(sizeof(struct msg_queue)); if(strlen(msg) < 150){ sprintf(msg_with_date,"%s %s",time_now,msg); strcpy(data->msg, msg_with_date); } else{ sprintf(msg_with_date,"%s %s",time_now,error_msg); strcpy(data->msg, msg_with_date); } data->next = 0; pthread_mutex_lock(&mutexlog); if (msgque_total == 0){ pthread_cond_signal(&condlog); msgque_head = data; msgque_total = 1; } else{ temp = msgque_head; while(1){ if(temp->next == 0){ break; } else{ temp = temp->next; } } temp->next = data; msgque_total++; } pthread_mutex_unlock(&mutexlog); } void enq_log_ip(unsigned char *ipmsg, char *head_msg){ struct sniff_ip *iph; char msg[100]; char src_addr[20]; char dst_addr[20]; char *tmp_addr; iph = (struct sniff_ip *)ipmsg; tmp_addr = inet_ntoa(iph->ip_src); strcpy(src_addr, tmp_addr); tmp_addr = inet_ntoa(iph->ip_dst); strcpy(dst_addr, tmp_addr); sprintf(msg,"%s id:%d src:%s -> %s\\n",head_msg,ntohs(iph->ip_id),src_addr,dst_addr); enq_log(msg); }
1
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int valeur_commune = 0; void* incr_routine(void * thread_number){ int i = *(int*) thread_number; i += 1; while (1) { struct timespec tim; tim.tv_sec = 0; tim.tv_nsec = 200 * 1000000L; pthread_mutex_lock(&lock); pthread_cond_wait(&cond, &lock); printf("inc%d : before x=%d\\n", i, valeur_commune); if(valeur_commune < 5) valeur_commune++; printf("\\t after x=%d\\n", valeur_commune); pthread_mutex_unlock(&lock); nanosleep(&tim, 0); } pthread_exit(0); } void* reset_routine(void * thread_number){ int i = *(int*) thread_number; struct timespec tim; tim.tv_sec = 0; tim.tv_nsec = 200 * 1000000L; while(1){ pthread_mutex_lock(&lock); if(valeur_commune < 5) pthread_cond_signal(&cond); printf("reset%d : before x=%d\\n", i, valeur_commune); if(valeur_commune >= 5){ valeur_commune = 0; } printf("\\t after x=%d\\n", valeur_commune); pthread_mutex_unlock(&lock); nanosleep(&tim, 0); } pthread_exit(0); } int main (void){ pthread_t threads_inc[3]; pthread_t threads_reset[1]; for(int i = 0; i < 3; i++){ printf("-----this is incr%d-----\\n", i+1); pthread_create(&threads_inc[i], 0, incr_routine, (void*)&i); } for(int i = 0; i < 1; i++){ printf("=====this is reset%d=====\\n", i+1); pthread_create(&threads_reset[i], 0, reset_routine, (void*)&i); } while (1) { } return 0; }
0
#include <pthread.h> void print_account_requests(int size); void print_account_ids(int *list, int n); pthread_mutex_t mutex; int value; int request; }account; int size, *request_priority; account **account_list; pthread_cond_t account_cv; account *create_account(){ account *a = malloc(sizeof(account)); pthread_mutex_init(&a->mutex, 0); a->value = 0; a->request = 0; return a; } void create_account_list(int n){ size = n; account_list = malloc(sizeof(account*)*size); request_priority = malloc(sizeof(int) * size); pthread_cond_init(&account_cv, 0); int i; for(i = 0; i < n; i++){ account_list[i] = create_account(); request_priority[i] = 0; } } int *get_request_priority(int *accounts, int n){ int i, *list = malloc(sizeof(int)*size); for(i = 0; i < size; i++){ list[i] = 0; } for(i = 0; i < n; i++){ int id = accounts[i]; list[id - 1] = request_priority[id - 1]; } return list; } void set_request_priority(int *list, int n, int count){ int i, id; for(i = 0; i < n; i++){ id = list[i]; request_priority[id-1] = count; } } int isrequest_finished(int *priority){ int i; for(i = 0; i < size; i++){ int r = account_list[i]->request; if(priority[i] > 0 && priority[i] != r){ return i; } } return -1; } void lock_accounts(int *list, int size){ int i; pthread_cond_broadcast(&account_cv); for(i = 0; i < size; i++){ pthread_mutex_lock(&account_list[i]->mutex); } } void unlock_accounts(int *list, int size){ int i; for(i = 0; i < size; i++){ pthread_mutex_unlock(&account_list[i]->mutex); } } void account_waiting(int *list, int size){ int i; for(i = 0; i < size; i++){ pthread_cond_wait(&account_cv, &account_list[i]->mutex); } } void print_account_requests(int size){ int i; printf("[ "); for(i = 0; i < size - 1; i++){ printf("%d, ", account_list[i]->request); } printf("%d ]\\n", account_list[i]->request); } void print_account_ids(int *list, int n){ int i; printf("[ "); for(i = 0; i < n-1; i++){ printf("%d, ", list[i]); } printf("%d ]\\n", list[i]); }
1
#include <pthread.h> static void set_timer(); static void timer_handler(int sig); static void set_timer(){ struct itimerval itv,oldtv; itv.it_interval.tv_sec = configuration.time_wait_unit; itv.it_interval.tv_usec = 0; itv.it_value.tv_sec = configuration.time_wait_unit; itv.it_value.tv_usec = 0; int ret = setitimer(ITIMER_REAL,&itv,&oldtv); if(ret) syslog(project_params.syslog_level,"setitimer falure\\n"); } static void timer_handler(int sig){ int job_type; for(job_type=0; job_type<JOB_NUMBER; job_type++){ if(!job_registed[job_type]) continue; if(job_call_type[job_type] != CALL_BY_TIMER) continue; int judge_result = 0; struct Job new_job; judge_result = job_judges[job_type](&new_job); if(!judge_result) continue; pthread_mutex_lock(&(job_mutex_for_queue[job_type])); jobqueue_insert(&(job_queue[job_type]),&new_job); pthread_mutex_unlock(&(job_mutex_for_queue[job_type])); pthread_mutex_lock(&(job_mutex_for_cond[job_type])); pthread_cond_signal(&(job_cond[job_type])); pthread_mutex_unlock(&(job_mutex_for_cond[job_type])); } } extern void install_timer(){ signal(SIGALRM,timer_handler); set_timer(); }
0
#include <pthread.h> int g = 0; pthread_mutex_t l; void bar1() { g = 5; RC_ACCESS(3, RC_ALIAS | RC_MHP | RC_RACE); RC_ACCESS(3, RC_ALIAS | RC_MHP | RC_RACE); RC_ACCESS(4, RC_ALIAS | RC_MHP | RC_RACE); } void bar2() { g = 5; RC_ACCESS(1, RC_ALIAS | RC_MHP | RC_PROTECTED); RC_ACCESS(1, RC_ALIAS | RC_MHP | RC_PROTECTED); RC_ACCESS(2, RC_ALIAS | RC_MHP | RC_RACE); } void *foo(void *arg) { long x = (long)arg; if (x == 1) { pthread_mutex_lock(&l); } bar1(); if (x == 1) { bar2(); } pthread_mutex_unlock(&l); return 0; } int main(int argc, char *argv[]) { pthread_t thread[10]; int ret; long t = 1; for (int i = 0; i < 10; ++i) { ret = pthread_create(&thread[i], 0, foo, (void *)t); if (ret){ exit(-1); } } g = 1; RC_ACCESS(2, RC_ALIAS | RC_MHP | RC_RACE); RC_ACCESS(4, RC_ALIAS | RC_MHP | RC_RACE); return 0; }
1
#include <pthread.h> int pthread_barrier_timedwait( pthread_barrier_t *barrier, const struct timespec *restrict abstime, const char *desc) { int retval = 0; pthread_mutex_lock(&barrier->mutex); ++(barrier->count); if (barrier->count > barrier->tripCount) { logError("WTF. this should never happen.\\n"); retval=-1; } else if(barrier->count == barrier->tripCount) { logDebug2("%s this thread is the last thread to arrive\\n", desc); barrier->count = 0; pthread_cond_broadcast(&barrier->cond); retval=PTHREAD_BARRIER_LAST; } else { logDebug2("%s not everyone is here yet, let's wait\\n", desc); retval = pthread_cond_timedwait(&barrier->cond, &barrier->mutex, abstime); if (retval == ETIMEDOUT) { logDebug2("%s wait timer exceeded. putting count back and giving up\\n", desc); --(barrier->count); } else if (retval == PTHREAD_BARRIER_NOT_LAST) { logDebug("%s someone else was last\\n", desc); } else { logError("%s unexpected result from pthread_cond_timedwait: %d\\n", desc, retval); } } pthread_mutex_unlock(&barrier->mutex); return retval; } int pthread_barrier_waitseconds(pthread_barrier_t *barrier, const int msec, const char *desc) { struct timeval tv; struct timespec ts; bzero(&tv, sizeof(tv)); bzero(&ts, sizeof(ts)); gettimeofday(&tv, 0); ts.tv_sec = tv.tv_sec; ts.tv_nsec = msec * 1000000; return (pthread_barrier_timedwait(barrier, &ts, desc)); } int pthread_barrier_waitcancel(pthread_barrier_t *barrier, int *exitFlag, const char *desc) { long int retval = 0; while (1) { retval = pthread_barrier_waitseconds(barrier, PTHREAD_POLL_MSEC, desc); switch (retval) { case PTHREAD_BARRIER_NOT_LAST: case PTHREAD_BARRIER_LAST: logDebug2("%s thread barrier reached\\n", desc); return 0; case ETIMEDOUT: if (*exitFlag) { logDebug2("%s thread being asked to cancel\\n", desc); return 0; } else { logDebug2("%s timeout reached but no need to cancel\\n", desc); } break; default: logError("%s unexpected pthread_barrier_wait error: %ld\\n", desc, retval); *exitFlag = 1; return -1; } } }
0
#include <pthread.h> int recordSize = 1024; int threadsNr; char *fileName; int fd; int numOfRecords; int creatingFinished = 0; char *word; int rc; int someonefound = 0; int detachedNr = 0; pthread_key_t key; pthread_t *threads; int *wasJoin; pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER; long gettid() { return syscall(SYS_gettid); } void* threadFun(void *oneArg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_t threadHandle = pthread_self(); pthread_t threadID = gettid(); printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID); char **readRecords; readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_setspecific(key, readRecords); readRecords = pthread_getspecific(key); while(!creatingFinished); int finish = 0; int moreBytesToRead = 1; int numOfReadedBytes; while(!finish && moreBytesToRead) { pthread_mutex_lock(&mutexForRecords); for(int i=0;i<numOfRecords;i++) { numOfReadedBytes = read(fd, readRecords[i], 1024); if(numOfReadedBytes==-1) { perror("error while reading in threadFun"); exit(1); } if(numOfReadedBytes<1024) moreBytesToRead = 0; } pthread_mutex_unlock(&mutexForRecords); for(int i = 0; i<numOfRecords; i++) { if(strstr(readRecords[i], word) != 0) { char recID[10]; strncpy(recID, readRecords[i], 10); printf("%ld: found word in record number %d\\n", threadID, atoi(recID)); } } } if(pthread_detach(threadHandle) != 0) { perror("pthread_detach error"); exit(1); } detachedNr++; pthread_exit(0); } int openFile(char *fileName) { int fd = open(fileName, O_RDONLY); if(fd == -1) { perror("file open error"); exit(-1); } else return fd; } void createThread(pthread_t *thread) { rc = pthread_create(thread, 0, threadFun, 0); if(rc != 0) { perror("thread create error"); exit(-1); } } int main(int argc, char *argv[]) { if(argc!=6) { puts("Bad number of arguments"); puts("Appropriate arguments:"); printf("[program] [threads nr] [file] \\n"); printf("[records nr] [word to find] [test nr]"); return 1; } printf("MAIN -> PID: %d TID: %ld\\n", getpid(), pthread_self()); threadsNr = atoi(argv[1]); fileName = calloc(1,sizeof(argv[2])); fileName = argv[2]; numOfRecords = atoi(argv[3]); word = calloc(1,sizeof(argv[4])); word = argv[4]; int test = atoi(argv[5]); if(test != 1 && test != 2 && test != 3 && test != 4) { puts("wrong test number"); exit(1); } fd = openFile(fileName); char **readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_key_create(&key, 0); threads = calloc(threadsNr, sizeof(pthread_t)); wasJoin = calloc(threadsNr, sizeof(int)); for(int i=0; i<threadsNr; i++) { createThread(&threads[i]); } creatingFinished = 1; usleep(100); if(test == 1) { puts("sending SIGUSR1 signal"); kill(getpid(),SIGUSR1); } if(test == 2) { puts("sending SIGTERM signal"); kill(getpid(),SIGTERM); } if(test == 3) { puts("sending SIGKILL signal"); kill(getpid(),SIGKILL); } if(test == 4) { puts("sending SIGSTOP signal"); kill(getpid(),SIGSTOP); } while(detachedNr != threadsNr) { usleep(100); } printf("End of program\\n\\n"); if(close(fd)<0) { perror("close error"); return 1; } free(threads); return 0; }
1
#include <pthread.h> double resultado; int valor; } razao; int contador = 0, limite_inferior, limite_superior, num_threads, tam_array; razao* razoes; pthread_mutex_t count; pthread_barrier_t barrier; void encontrar_amigos_mutuos(int index){ razao primeira = razoes[index]; int j; int contadorThread = 0; for(j = index + 1; j < tam_array; j++){ if (primeira.resultado == razoes[j].resultado){ printf("%d e %d sao mutualmente amigos.\\n", primeira.valor, razoes[j].valor); contadorThread++; } } pthread_mutex_lock(&count); contador = contador + contadorThread; pthread_mutex_unlock(&count); } razao achar_divisores(int x){ int i; double soma = 0; for(i = 1; i <= (int)x/2; i++){ if(!(x % i)) soma += i; } razao retorno; retorno.resultado = (soma + x) / x; retorno.valor = x; return retorno; } void *executa_logica(void * arg){ int* id = (int*) arg; int iterador, i; iterador = 0, i = 0; while(1){ iterador = i * num_threads + *id; if(iterador >= tam_array) break; razoes[iterador] = achar_divisores(iterador + limite_inferior); i++; } pthread_barrier_wait(&barrier); iterador = 0, i = 0; while(1){ iterador = i * num_threads + *id; if(iterador >= tam_array) break; encontrar_amigos_mutuos(iterador); i++; } pthread_exit(0); } int main(int argc, char** argv[]){ limite_inferior = atoi((const char*)argv[1]); limite_superior = atoi((const char*)argv[2]); num_threads = atoi((const char*)argv[3]); pthread_mutex_init(&count, 0); pthread_barrier_init(&barrier, 0, num_threads); tam_array = limite_superior - limite_inferior + 1; razoes = (razao*) malloc(sizeof(razao) * tam_array); pthread_t thread[num_threads]; int i, id[num_threads]; for(i = 0; i < num_threads; i++){ id[i] = i; pthread_create(&thread[i], 0, executa_logica, &id[i]); } for(i = 0; i < num_threads; i++){ pthread_join(thread[i], 0); } printf("Total: %d\\n", contador); pthread_mutex_destroy(&count); pthread_barrier_destroy(&barrier); free(razoes); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t readlock; pthread_mutex_t writelock; pthread_mutex_t priority; int read_cnt=0; char buf[100]; void reader(void* arg) { pthread_mutex_lock(&priority); pthread_mutex_lock(&readlock); if(++read_cnt==1) pthread_mutex_lock(&writelock); pthread_mutex_unlock(&readlock); pthread_mutex_unlock(&priority); printf("%d读者读取内容:%s\\n",pthread_self(),buf); pthread_mutex_lock(&readlock); if(--read_cnt==0) pthread_mutex_unlock(&writelock); pthread_mutex_unlock(&readlock); pthread_exit((void*)0); } void writer(void *arg) { pthread_mutex_lock(&priority); pthread_mutex_lock(&writelock); sprintf(buf,"我是%d写者,这是我写的内容",pthread_self()); printf("%d写者写内容%s\\n",pthread_self(),buf); sleep(1); pthread_mutex_unlock(&writelock); pthread_mutex_unlock(&priority); pthread_exit((void*)0); } int main() { char buf[1000]={0}; pthread_mutex_init(&readlock,0); pthread_mutex_init(&writelock,0); pthread_mutex_init(&priority,0); pthread_t tid; pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_exit((void*)pthread_self()); return 0; }
1
#include <pthread.h> const double REAL_PI = 3.141592653589793238462643383279502884197169399; int threadid;; int num_threads; int num_steps; pthread_mutex_t *mtx; double *sump; } thr_data_t; double get_wtime() { double t; static int sec = -1; struct timeval tv; gettimeofday(&tv, (void *)0); if (sec < 0) sec = tv.tv_sec; t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec; return t; } void * compute_pi(void *dat) { int threadid = ((thr_data_t*)dat)->threadid; int num_threads = ((thr_data_t*)dat)->num_threads; int num_steps = ((thr_data_t*)dat)->num_steps; pthread_mutex_t *mtx = ((thr_data_t*)dat)->mtx; double *sump = ((thr_data_t*)dat)->sump; int i; double step; double x, local_sum; step = 1.0 / num_steps; local_sum = 0.0; for (i = threadid; i < num_steps; i += num_threads) { x = (i - 0.5)*step; local_sum += 4.0 / (1.0 + x*x); } pthread_mutex_lock(mtx); *sump = *sump + local_sum; pthread_mutex_unlock(mtx); return 0; } int main(int argc, char **argv) { int i, num_steps, num_threads; double pi, step, sum = 0.0; double t1, t2; pthread_t *threads; pthread_mutex_t mtx; thr_data_t *dat; num_steps = 100000000; num_threads = 8; if (argc > 1) { num_steps = atoi(argv[1]); if (argc > 2) { num_threads = atoi(argv[2]); } } threads = malloc(num_threads * sizeof *threads); step = 1.0 / num_steps; pthread_mutex_init(&mtx, 0); t1 = get_wtime(); dat = malloc(num_threads * sizeof *dat); for (i = 0; i < num_threads; i++) { dat[i].threadid = i; dat[i].num_threads = num_threads; dat[i].num_steps = num_steps; dat[i].mtx = &mtx; dat[i].sump = &sum; pthread_create(&threads[i], 0, compute_pi, (void *)&dat[i]); } for (i = 0; i < num_threads; i++) { pthread_join(threads[i], 0); } pi = step * sum; free(dat); t2 = get_wtime(); pthread_mutex_destroy(&mtx); free(threads); printf("pi estimate is %20.18f, after %d steps with %d threads.\\n", pi, num_steps, num_threads); printf("error is %e\\n", REAL_PI-pi); printf("time is %12.8f seconds.\\n", (t2-t1)); return 0; }
0
#include <pthread.h> struct queue_s { int *ringbuf; size_t nslots; int idx_enq; int idx_deq; pthread_mutex_t mutex; pthread_cond_t cond_not_full; pthread_cond_t cond_not_empty; }; queue_t * queue_create(size_t n) { queue_t *q; int *buf; if(0 == n) n = 128; buf = (int *)malloc(n * sizeof(int)); if(!buf) return 0; q = (queue_t *)malloc(sizeof(*q)); if(!q) { free(buf); return 0; } q->ringbuf = buf; q->nslots = n; q->idx_deq = 0; q->idx_enq = 0; pthread_mutex_init(&q->mutex, 0); pthread_cond_init(&q->cond_not_full, 0); pthread_cond_init(&q->cond_not_empty, 0); return q; } void queue_enqueue(queue_t *q, int ele) { assert(q); int cnt; pthread_mutex_lock(&q->mutex); cnt = q->idx_enq + 1 - q->idx_deq; while((cnt == 0) || (cnt == q->nslots)) { pthread_cond_wait(&q->cond_not_full, &q->mutex); cnt = q->idx_enq + 1 - q->idx_deq; } q->ringbuf[q->idx_enq] = ele; q->idx_enq = (q->idx_enq + 1) % (q->nslots); pthread_cond_signal(&q->cond_not_empty); pthread_mutex_unlock(&q->mutex); } void queue_dequeue(queue_t *q, int *ele) { assert(q); pthread_mutex_lock(&q->mutex); while(q->idx_enq == q->idx_deq) { pthread_cond_wait(&q->cond_not_empty, &q->mutex); } *ele = q->ringbuf[q->idx_deq]; q->idx_deq = (q->idx_deq + 1) % (q->nslots); pthread_cond_signal(&q->cond_not_full); pthread_mutex_unlock(&q->mutex); } void queue_destroy(queue_t *q) { assert(q); free(q->ringbuf); pthread_cond_destroy(&q->cond_not_full); pthread_cond_destroy(&q->cond_not_empty); pthread_mutex_destroy(&q->mutex); } void * thr_consumer(void *arg) { queue_t *q = (queue_t *)arg; printf("consumer thread created.\\n"); while(1) { int ele; queue_dequeue(q, &ele); printf("consumer: dequeue %d\\n", ele); } printf("consumer thread leaves now.\\n"); pthread_exit(0); return 0; } void * thr_producer(void *arg) { queue_t *q = (queue_t *)arg; int i; printf("producer thread created.\\n"); for(i = 0; i < 255; i++) { queue_enqueue(q, i); printf("producer: enqueue %d\\n", i); } printf("producer thread leaves now.\\n"); pthread_exit(0); return 0; } int main(void) { pthread_t tc, tp; int rc; queue_t *q; printf("main thread pid: %d\\n", (int)getpid()); q = queue_create(128); assert(q); rc = pthread_create(&tc, 0, thr_consumer, q); assert(!rc); rc = pthread_create(&tp, 0, thr_producer, q); assert(!rc); pthread_join(tc, 0); pthread_join(tp, 0); queue_destroy(q); return 0; }
1
#include <pthread.h> struct rtpp_queue { struct rtpp_wi *head; struct rtpp_wi *tail; pthread_cond_t cond; pthread_mutex_t mutex; int length; char *name; int qlen; }; struct rtpp_queue * rtpp_queue_init(int qlen, const char *fmt, ...) { struct rtpp_queue *queue; va_list ap; int eval; queue = malloc(sizeof(*queue)); if (queue == 0) return (0); memset(queue, '\\0', sizeof(*queue)); queue->qlen = qlen; if ((eval = pthread_cond_init(&queue->cond, 0)) != 0) { free(queue); return (0); } if (pthread_mutex_init(&queue->mutex, 0) != 0) { pthread_cond_destroy(&queue->cond); free(queue); return (0); } __builtin_va_start((ap)); vasprintf(&queue->name, fmt, ap); ; if (queue->name == 0) { pthread_cond_destroy(&queue->cond); pthread_mutex_destroy(&queue->mutex); free(queue); return (0); } return (queue); } void rtpp_queue_destroy(struct rtpp_queue *queue) { pthread_cond_destroy(&queue->cond); pthread_mutex_destroy(&queue->mutex); free(queue->name); free(queue); } void rtpp_queue_put_item(struct rtpp_wi *wi, struct rtpp_queue *queue) { pthread_mutex_lock(&queue->mutex); wi->next = 0; if (queue->head == 0) { queue->head = wi; queue->tail = wi; } else { queue->tail->next = wi; queue->tail = wi; } queue->length += 1; if (queue->length % queue->qlen == 0) { pthread_cond_signal(&queue->cond); } pthread_mutex_unlock(&queue->mutex); } void rtpp_queue_pump(struct rtpp_queue *queue) { pthread_mutex_lock(&queue->mutex); if (queue->length > 0) { pthread_cond_signal(&queue->cond); } pthread_mutex_unlock(&queue->mutex); } struct rtpp_wi * rtpp_queue_get_item(struct rtpp_queue *queue, int return_on_wake) { struct rtpp_wi *wi; pthread_mutex_lock(&queue->mutex); while (queue->head == 0) { pthread_cond_wait(&queue->cond, &queue->mutex); if (queue->head == 0 && return_on_wake != 0) { pthread_mutex_unlock(&queue->mutex); return (0); } } wi = queue->head; queue->head = wi->next; if (queue->head == 0) queue->tail = 0; queue->length -= 1; pthread_mutex_unlock(&queue->mutex); return (wi); } int rtpp_queue_get_items(struct rtpp_queue *queue, struct rtpp_wi **items, int ilen, int return_on_wake) { int i; pthread_mutex_lock(&queue->mutex); while (queue->head == 0) { pthread_cond_wait(&queue->cond, &queue->mutex); if (queue->head == 0 && return_on_wake != 0) { pthread_mutex_unlock(&queue->mutex); return (0); } } for (i = 0; i < ilen; i++) { items[i] = queue->head; queue->head = items[i]->next; if (queue->head == 0) { queue->tail = 0; i += 1; break; } } queue->length -= i; pthread_mutex_unlock(&queue->mutex); return (i); } int rtpp_queue_get_length(struct rtpp_queue *queue) { int length; pthread_mutex_lock(&queue->mutex); length = queue->length; pthread_mutex_unlock(&queue->mutex); return (length); }
0
#include <pthread.h> int buffer; int bufferindicator = 0; pthread_mutex_t cmutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condvar = PTHREAD_COND_INITIALIZER; void* writer_thread(void *arg) { int lindex = 0; while(lindex < 20) { pthread_mutex_lock(&cmutex); while (bufferindicator == 1) pthread_cond_wait(&condvar,&cmutex); scanf("%d", &buffer); printf("buffer=%d\\n",buffer); bufferindicator = 1; pthread_cond_signal(&condvar); pthread_mutex_unlock(&cmutex); lindex++; } return 0; } void* reader_thread(void *arg) { int lindex = 0; while(lindex < 20) { pthread_mutex_lock(&cmutex); while (bufferindicator == 0) { printf("Inside reader\\n"); pthread_cond_wait(&condvar,&cmutex); } printf("buffer = %d\\n",buffer); bufferindicator = 0; pthread_cond_signal(&condvar); pthread_mutex_unlock(&cmutex); lindex++; } return 0; } int main(void) { pthread_t tid1,tid2; int rv1,rv2; pthread_attr_t attr; pthread_attr_init(&attr); rv1 = pthread_create(&tid1,&attr,(void *)writer_thread,0); if(rv1 != 0) { printf("\\n Cannot create thread"); exit(0); } rv2 = pthread_create(&tid2,&attr,(void *)reader_thread,0); if(rv2 != 0) { printf("\\n Cannot create thread"); exit(0); } pthread_join(tid1,0); pthread_join(tid2,0); return(0); }
1
#include <pthread.h> void * handle_clnt(void * arg); void send_msg(char * msg, int len); void error_handling(char * msg); int clnt_cnt=0; int clnt_socks[256]; int clnt_num[256]; int clnt_sock; pthread_mutex_t mutx; void *handle_test(void *arg){ printf("00000"); } int main(int argc, char *argv[]) { int serv_sock; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz,test=0; pthread_t t_id,t_2; if(argc!=2) { printf("Usage : %s <port>\\n", argv[0]); exit(1); } pthread_create(&t_2, 0, handle_test, 0); pthread_detach(t_2); printf("sssssss\\n"); serv_sock=socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family=AF_INET; serv_adr.sin_addr.s_addr=htonl(INADDR_ANY); serv_adr.sin_port=htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1) error_handling("bind() error"); if(listen(serv_sock, 5)==-1) error_handling("listen() error"); while(1) { clnt_adr_sz=sizeof(clnt_adr); clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz); pthread_mutex_lock(&mutx); clnt_socks[clnt_cnt++]=clnt_sock; write(clnt_socks[clnt_cnt-1],(void*)&clnt_sock,1); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); printf("Connected client IP: %s clnt_socks[%d] clnt_sock : %d \\n" ,inet_ntoa(clnt_adr.sin_addr),(clnt_cnt-1),clnt_sock); } close(serv_sock); return 0; } void * handle_clnt(void * arg) { int clnt_sock=*((int*)arg); int str_len=0, i; char msg[100]; while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0) send_msg(msg, str_len); pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) { if(clnt_sock==clnt_socks[i]) { while(i++<clnt_cnt-1) clnt_socks[i]=clnt_socks[i+1]; break; } } clnt_cnt--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void send_msg(char * msg, int len) { int i, k=msg[0]; pthread_mutex_lock(&mutx); for(i=0; i<clnt_sock-2; i++){ write(clnt_socks[i],msg,len); } pthread_mutex_unlock(&mutx); } void error_handling(char * msg) { fputs(msg, stderr); fputc('\\n', stderr); exit(1); }
0
#include <pthread.h> static pthread_mutex_t oliMutexes [4] ; int oliThreadCreate(void *(*fn)(void *)) { pthread_t myThread; return pthread_create(&myThread, 0, fn, 0); } void oliLock(int key) { pthread_mutex_lock(&oliMutexes[key]); } void oliUnlock(int key) { pthread_mutex_unlock(&oliMutexes[key]); }
1
#include <pthread.h> int sum = 0; pthread_mutex_t sumLock; int compute(int i) { return i*i; } void worker(long tid) { int i, low, high, psum; low = (100/10) * tid; high = low + (100/10); psum = 0; printf("Thread id: %ld. Thread range: LOW %d HIGH %d\\n",tid, low, high); for (i = low; i < high; i++) psum += compute(i); pthread_mutex_lock(&sumLock); sum += psum; pthread_mutex_unlock(&sumLock); } int main(int argc, char **argv) { pthread_t thread[10]; long k; pthread_mutex_init(&sumLock, 0); for (k=0; k<10; k++) pthread_create(&thread[k], 0, (void*)worker, (void*)k); for (k=0; k<10; k++) pthread_join(thread[k], 0); printf("The result sum is %d\\n", sum); }
0
#include <pthread.h> int GetBit(long data, long bit); void *SSSthread(void* arg); { long index1; long index2; int targetNum; int* intset; int length; int* numofsolutions; pthread_mutex_t *mutex; }Subset; int subsetSum(int * intset, int length, int N, int numThread) { int lastInd = 1; int counter; int Numofsolutions = 0; int i; counter = pow(2, length) -1; pthread_mutex_t * mutex = malloc(numThread * sizeof(pthread_mutex_t)); pthread_t * th = malloc(numThread * sizeof(pthread_t)); pthread_attr_t * attr = malloc(numThread* sizeof(pthread_attr_t)); Subset * s = malloc(numThread * sizeof(Subset)); if(mutex == 0) { printf("Unable to allocate memory\\n"); return 1; } if(th == 0) { printf("Unable to allocate memory\\n"); return 1; } if(attr == 0) { printf("Unable to allocate memory\\n"); return 1; } if(s == 0) { printf("Unable to allocate memory\\n"); return 1; } pthread_mutex_init(mutex, 0); for(i=0; i<numThread; i++) { s[i].index1 = lastInd; lastInd += (counter/numThread); s[i].index2 = lastInd; lastInd++; s[i].intset = intset; s[i].numofsolutions = &Numofsolutions; s[i].mutex = mutex; s[i].length = length; s[i].targetNum = N; pthread_attr_init(&attr[i]); } s[numThread-1].index2 = counter+1; for(i=0; i<numThread; i++) { pthread_create(&(th[i]), &(attr[i]), SSSthread, (void*) &(s[i])); } for(i=0; i<numThread; i++) { pthread_join(th[i], 0); } free(th); free(attr); free(s); free(mutex); return Numofsolutions; } int GetBit(long data, long bit) { return data & (1 << bit); } void *SSSthread(void* arg) { Subset* s = (Subset*)arg; long index; int sum; int i; for(index = s->index1; index < s->index2; index++) { sum=0; for(i=0; i < s->length; i++) { if(GetBit(index, i) != 0) sum += s->intset[i]; } if(sum == s->targetNum) { pthread_mutex_lock(s->mutex); (*(s->numofsolutions))++; pthread_mutex_unlock(s->mutex); } } pthread_exit(0); return 0; }
1
#include <pthread.h> bool fstrm__get_best_monotonic_clock_pthread(clockid_t *c) { bool res = 0; int rc; struct timespec ts; pthread_condattr_t ca; rc = pthread_condattr_init(&ca); assert(rc == 0); out: rc = pthread_condattr_destroy(&ca); assert(rc == 0); return res; } bool fstrm__get_best_monotonic_clock_gettime(clockid_t *c) { struct timespec ts; return 0; } bool fstrm__get_best_monotonic_clocks(clockid_t *clkid_gettime, clockid_t *clkid_pthread, char **err) { if (clkid_gettime != 0 && !fstrm__get_best_monotonic_clock_gettime(clkid_gettime)) { if (err != 0) *err = my_strdup("no clock available for clock_gettime()"); return 0; } if (clkid_pthread != 0 && !fstrm__get_best_monotonic_clock_pthread(clkid_pthread)) { if (err != 0) *err = my_strdup("no clock available for pthread_cond_timedwait()"); return 0; } return 1; } int fstrm__pthread_cond_timedwait(clockid_t clock_id, pthread_cond_t *cond, pthread_mutex_t *mutex, unsigned seconds) { int res; struct timespec ts; res = clock_gettime(clock_id, &ts); assert(res == 0); ts.tv_sec += seconds; pthread_mutex_lock(mutex); res = pthread_cond_timedwait(cond, mutex, &ts); pthread_mutex_unlock(mutex); return res; }
0
#include <pthread.h> extern struct DEV_reg *DEVreg; extern int IRQ; extern int tc_count; extern int intid; extern int configured; extern int locked; extern struct sigevent interruptevent; extern struct GPSStatus displaystat; extern struct timespec timecompare,event; extern int RateSynthInterrupt,EventInterrupt,TimeCompareInterrupt,timecompareupdate,eventupdate; extern pthread_t int_thread_id,refresh_thread_id; extern int verbose; extern pthread_mutex_t gps_state_lock; int set_time_compare(int mask,struct timespec *nexttime); int set_time_compare_register(int mask,struct timespec *nexttime); int get_hdw_stat(){ int temp=0; return temp; } void * refresh_state(void *arg){ int temp; int refreshrate=1; while(1){ pthread_mutex_lock(&gps_state_lock); get_state(); pthread_mutex_unlock(&gps_state_lock); if(locked) refreshrate=10; else refreshrate=1; sleep(refreshrate); } } void * get_state(){ int temp, int_state, lock_status; int gps_sec, gps_nsec; int event_sec, event_nsec; struct timespec now; float timediff; if(verbose > 1) { fprintf(stderr,"Get state\\n"); int_state=DEVreg->intstat; fprintf(stderr," DEVreg INTSTAT: 0x%x : ", int_state); printbits(stderr,int_state); fprintf(stderr,"\\n"); fprintf(stderr," Request Time\\n"); } temp=DEVreg->timereq; lock_status=(DEVreg->time0 & 0x7000000) >> 24; temp=DEVreg->time1; gps_sec=temp; temp=DEVreg->time0; gps_nsec=(temp & 0xFFFFF)*1000; gps_nsec+=((temp >> 20) & 0xF)*100; displaystat.gpssecond=gps_sec; displaystat.gpsnsecond=gps_nsec; if(verbose > 1) { fprintf(stderr," Software Major Time: "); fprintf(stderr,"%s",ctime(&gps_sec)); fprintf(stderr," Software Nanosecs: %09d\\n", gps_nsec); if((int_state & 0x01) == 0x01) { temp=DEVreg->event1; event_sec=temp; temp=DEVreg->event0; event_nsec=(temp & 0xFFFFF)*1000; event_nsec+=((temp >> 20) & 0xF)*100; fprintf(stderr," Event Major Time: "); fprintf(stderr,"%s",ctime(&event_sec)); fprintf(stderr," Event Nanosecs: %09d\\n", event_nsec); } else { fprintf(stderr," :::::No Event::::::\\n"); } } fprintf(stderr," Status: 0x%x : ",lock_status); if (lock_status==0) { if(verbose > -1) fprintf(stderr,"Good : "); displaystat.gps_lock=1; temp=clock_gettime(CLOCK_REALTIME,&now); displaystat.syssecond=now.tv_sec; displaystat.sysnsecond=now.tv_nsec; timediff=(float)(displaystat.syssecond-displaystat.gpssecond)+((float)(displaystat.sysnsecond-displaystat.gpsnsecond))/1e9; if(fabs(timediff)>0.05 ) { if( verbose > -1 ) fprintf(stderr,"Preparing to Update System Time: %lf\\n",timediff); now.tv_sec=displaystat.gpssecond; now.tv_nsec=displaystat.gpsnsecond; clock_settime(CLOCK_REALTIME,&now); } else { if(verbose > -1) fprintf(stderr," System Time within allowed margin\\n"); } } else { if(verbose > -1) { fprintf(stderr,"Bad: "); if ((lock_status & 1)==1) fprintf(stderr," Track "); if ((lock_status & 2)==2) fprintf(stderr," Phase "); if ((lock_status & 4)==4) fprintf(stderr," Freq "); fprintf(stderr,"\\n"); } displaystat.gps_lock=0; } locked|=displaystat.gps_lock; pthread_mutex_unlock(&gps_state_lock); }
1
#include <pthread.h> double gStep = 0.0; double gPi = 0.0; pthread_mutex_t gLock; void *threadFunction(void *pArg) { int myNum = *((int *)pArg); double partialSum = 0.0, x; for ( int i=myNum; i<1000000; i+=4 ) { x = (i + 0.5f) / 1000000; partialSum += 4.0f / (1.0f + x*x); } pthread_mutex_lock(&gLock); gPi += partialSum * gStep; pthread_mutex_unlock(&gLock); } main() { pthread_t threadHandles[4]; int tNum[4]; printf("Computed value of Pi: "); pthread_mutex_init(&gLock, 0); gStep = 1.0 / 1000000; for ( int i=0; i<4; ++i ) { tNum[i] = i; pthread_create(&threadHandles[i], 0, threadFunction, (void *) &tNum[i]); } for ( int j=0; j<4; ++j ) { pthread_join(threadHandles[j], 0); } pthread_mutex_destroy(&gLock); printf("%12.9f\\n", gPi ); }
0
#include <pthread.h> int c[10]; int use[2][2]; pthread_mutex_t use_mutex; bool overlap(i,j,k,l) { return (((i<=k) && (j <= l)) || ((k<=i) && (l <= j)))? 1 : 0; } void enter_critical(int i, int j, int tid){ bool acquired = 0; while (!acquired){ pthread_mutex_lock(&use_mutex); acquired = use[1-tid][0]>j || use[1-tid][1]<i; if (acquired){ use[tid][0] = i; use[tid][1] = j; } pthread_mutex_unlock(&use_mutex); } } void exit_critical(int i, int j, int tid){ use[tid][0] = 10; use[tid][1] = -1; } void init_mutexes(){ int i; for (i = 0; i < 1; i++) { use[i][0] = 10; use[i][1] = -1; } } void destroy_mutexes(){} int randpos() { return (rand() % 10); } void atomic_perm(int i, int j, int tid){ if (i>j) { int t = i; i = j; j = t; } enter_critical(i,j,tid); int n; int fst; fst = c[i]; for(n=i; n<j; n++) c[n] = c[n+1]; c[j] = fst; exit_critical(i,j,tid); } void *threadfun(void *arg) { int n; int tid = *(int *)arg; for(n=0;n<1000000;n++){ int i = randpos(); int j = randpos(); if (i!=j) atomic_perm(i,j,tid); } printf("Fin %d\\n",tid); return 0; } int main(int argc, char **argv){ pthread_t t1,t2; srand(time(0)); int tid[2]; tid[0] = 0; tid[1] = 1; int i; for(i=0; i<10; i++) c[i] = i; init_mutexes(); pthread_create(&t1,0,threadfun,&tid[0]); pthread_create(&t2,0,threadfun,&tid[1]); pthread_join(t1,0); pthread_join(t2,0); destroy_mutexes(); for(i=0; i<10; i++) printf("c[%d] = %d\\n",i,c[i]); printf("Fin main.\\n"); }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } } void * thr_fn1(void *arg); void * thr_fn2(void *arg); int main(void) { pthread_t tid1, tid2; void *status; int err; int i; for (i = 0; i < 29; i++) foo_alloc(i); for (i = 0; i < 29; i++) { printf("%5d %3d\\n", i, fh[i]->f_count); free(fh[i]); } return 0; }
0
#include <pthread.h> { pthread_mutex_t lock; pthread_cond_t cond; }cl,*pcl; void* thread(void *p) { pcl cl_t = (pcl)p; int ret; printf("Child:start,LOCK!\\n"); pthread_mutex_lock(&cl_t->lock); printf("Child:I will sleep.\\n"); ret = pthread_cond_wait(&cl_t->cond,&cl_t->lock); if(ret != 0) { printf("Child:pthread_cond_wait error(%d)\\n",ret); return; } printf("Child:i'm wake,UNLOCK!\\n"); pthread_mutex_unlock(&cl_t->lock); printf("Child:byebye~~~\\n"); pthread_exit(0); } int main(void) { pthread_t pt; int ret; cl cl1; printf("Main:start init mutex and cond...\\n"); ret = pthread_mutex_init(&cl1.lock,0); if(ret != 0) { printf("Main:pthread_mutex_init error(%d)\\n",ret); return -1; } ret = pthread_cond_init(&cl1.cond,0); if(ret != 0) { printf("Main:pthread_cond_init error(%d)\\n",ret); return -1; } printf("Main:start child...\\n"); ret = pthread_create(&pt,0,thread,(void*)&cl1); if(ret != 0) { printf("Main:pthread_create error(%d)\\n",ret); return -1; } printf("Main:wait......\\n"); sleep(3); printf("Main:weak up my child\\n"); pthread_cond_signal(&cl1.cond); ret = pthread_join(pt,0); if(ret != 0) { printf("Main:pthread_join error(%d)\\n",ret); return -1; } printf("Main:destroy mutex and cond.\\n"); ret = pthread_mutex_destroy(&cl1.lock); if(ret != 0) { printf("Main:pthread_mutex_destory error(%d)\\n",ret); return -1; } ret = pthread_cond_destroy(&cl1.cond); if(ret != 0) { printf("Main:pthread_cond_destory error(%d)\\n",ret); return -1; } printf("Main:byebye\\n"); return 0; }
1
#include <pthread.h> struct clbuf { pthread_mutex_t lock; unsigned allocated_size; unsigned read_index; unsigned write_index; void **buffer; }; struct clbuf *clbuf_create(unsigned size) { struct clbuf *cb = (struct clbuf *) xmalloc(sizeof(struct clbuf)); pthread_mutexattr_t mta; pthread_mutexattr_init(&mta); pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&cb->lock, &mta); cb->allocated_size = size; cb->read_index = 0; cb->write_index = 0; cb->buffer = (void **) xmalloc(sizeof(void *) * size); memset(cb->buffer, 0, sizeof(void *) * size); return cb; } void clbuf_free(struct clbuf *cb) { free(cb->buffer); free(cb); } void *clbuf_push(struct clbuf *cb, void *ptr) { if (!ptr) return 0; pthread_mutex_lock(&cb->lock); if (cb->write_index == cb->read_index && cb->buffer[cb->write_index] != 0) { pthread_mutex_unlock(&cb->lock); return 0; } cb->buffer[cb->write_index] = ptr; cb->write_index++; cb->write_index %= cb->allocated_size; pthread_mutex_unlock(&cb->lock); return ptr; } void *clbuf_pop(struct clbuf *cb) { void *popped_ptr = 0; pthread_mutex_lock(&cb->lock); if (cb->write_index == cb->read_index && cb->buffer[cb->read_index] == 0) { pthread_mutex_unlock(&cb->lock); return 0; } popped_ptr = cb->buffer[cb->read_index]; cb->buffer[cb->read_index] = 0; cb->read_index++; cb->read_index %= cb->allocated_size; pthread_mutex_unlock(&cb->lock); return popped_ptr; } unsigned clbuf_count_used(struct clbuf *cb) { unsigned count; pthread_mutex_lock(&cb->lock); if (cb->write_index == cb->read_index && cb->buffer[cb->read_index] == 0) count = 0; else if (cb->write_index == cb->read_index && cb->buffer[cb->read_index] != 0) count = cb->allocated_size; else if (cb->write_index >= cb->read_index) count = cb->write_index - cb->read_index; else count = cb->write_index + cb->allocated_size - cb->read_index; pthread_mutex_unlock(&cb->lock); return count; } unsigned clbuf_count_free(struct clbuf *cb) { unsigned count_free; pthread_mutex_lock(&cb->lock); count_free = cb->allocated_size - clbuf_count_used(cb); pthread_mutex_unlock(&cb->lock); return count_free; }
0
#include <pthread.h> int beers = 2000000; pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; void * drink_lots(void *a){ int i; pthread_mutex_lock(&beers_lock); for (i = 0; i < 100000; i++){ beers = beers - 1; } pthread_mutex_unlock(&beers_lock); printf("beers = %i\\n", beers); return 0; } void error(char *msg){ fprintf(stderr, "%s: %s\\n", msg, strerror(errno)); exit(1); } int main(){ pthread_t threads[20]; int i; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers); for (i=0; i < 20; i++){ if(pthread_create(&threads[i], 0, drink_lots, 0) != 0){ error("Can't create thread."); } } void* result; for (i = 0; i < 20; i++){ if(pthread_join(threads[i], &result) != 0){ error("Can't join thread."); } } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
1
#include <pthread.h> int sum = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread1() ; void *thread2() ; void *thread3() ; void *thread4() ; void *thread5() ; void error_message(int error); void critical_section(int thread); void main() { pthread_t thread_id[5]; int i=0; if( pthread_create(&thread_id[0],0,&thread1, 0) < 0 ) error_message(1); if( pthread_create(&thread_id[1],0,&thread2,0) < 0 ) error_message(2); if( pthread_create(&thread_id[2],0,&thread3, 0) < 0 ) error_message(3); if( pthread_create(&thread_id[3],0,&thread4, 0) < 0 ) error_message(4); if( pthread_create(&thread_id[4],0,&thread5, 0) < 0 ) error_message(5); for(i=0;i<5;i++) pthread_join(thread_id[i],0); printf("Total + %d\\n",sum); } void critical_section(int thread) { int index; for(index=1;index<6;index++) { sum += index; printf("Thread %d is running... : sum : %d index : %d\\n",thread, sum,index); sleep(1); } } void *thread1() { pthread_mutex_lock(&mutex); critical_section(1); pthread_mutex_unlock(&mutex); } void *thread2() { pthread_mutex_lock(&mutex); critical_section(2); pthread_mutex_unlock(&mutex); } void *thread3() { pthread_mutex_lock(&mutex); critical_section(3); pthread_mutex_unlock(&mutex); } void *thread4() { pthread_mutex_lock(&mutex); critical_section(4); pthread_mutex_unlock(&mutex); } void *thread5() { pthread_mutex_lock(&mutex); critical_section(5); pthread_mutex_unlock(&mutex); } void error_message(int error) { printf("Unable to create thread : %d\\n",error); exit(-1); }
0
#include <pthread.h> int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(20); i++) { value = nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { goto ERROR; ERROR: ; } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { goto ERROR; ERROR: ; } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> const int DEF_THREAD_COUNT = 4; const int DEF_FIB_MAX = 40; { int n; int result; pthread_mutex_t *access_input; pthread_mutex_t *access_output; pthread_cond_t *cond_output; pthread_cond_t *cond_input; int work; } fib_params_t; int fib(int n) { if (n <= 0) return 0; else if (n == 1) return 1; return fib(n - 1) + fib(n - 2); } void *fib_thread(void *param) { fib_params_t *fib_params = (fib_params_t *)param; while (fib_params->work == 1) { pthread_mutex_lock(fib_params->access_input); while(fib_params->n == -1) { pthread_cond_wait(fib_params->cond_input, fib_params->access_input); } pthread_mutex_unlock(fib_params->access_input); pthread_mutex_lock(fib_params->access_output); fib_params->result = fib(fib_params->n); fib_params->n = -1; pthread_mutex_unlock(fib_params->access_output); pthread_cond_signal(fib_params->cond_output); } printf("thread ends\\n"); pthread_mutex_destroy(fib_params->access_input); pthread_cond_destroy(fib_params->cond_input); return 0; } int main (int argc, char *argv[]) { int thread_count = DEF_THREAD_COUNT; int max_n = DEF_FIB_MAX; if (argc > 1) thread_count = atoi(argv[1]); if (argc > 2) max_n = atoi(argv[2]); if (thread_count == 0) thread_count = DEF_THREAD_COUNT; if (max_n == 0) max_n = DEF_FIB_MAX; pthread_cond_t cond_output = PTHREAD_COND_INITIALIZER; pthread_mutex_t access_output = PTHREAD_MUTEX_INITIALIZER; printf("Calculating Fibbonaci from 0 to %d\\n", max_n); printf("Creating %d threads\\n", thread_count); fib_params_t params[thread_count]; int i; for (i = 0; i < thread_count; i++) { params[i].work = 1; params[i].n = -1; params[i].result = -1; params[i].access_input = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); params[i].access_output = &access_output; params[i].cond_input = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); params[i].cond_output = &cond_output; pthread_t thread_id; pthread_create(&thread_id, 0, &fib_thread, &params[i]); pthread_detach(thread_id); } int j; for (i = 0; i < max_n; i += thread_count) { int work_threads = thread_count; if (work_threads > (max_n - i)) work_threads = (max_n - i); for (j = 0; j < work_threads; j++) { int calc = i + j; pthread_mutex_lock(params[j].access_input); params[j].n = calc; pthread_mutex_unlock(params[j].access_input); pthread_cond_signal(params[j].cond_input); } for (j = 0; j < work_threads; j++) { pthread_mutex_lock(&access_output); while(params[j].result == -1) { pthread_cond_wait(&cond_output, &access_output); } pthread_mutex_unlock(&access_output); } for (j = 0; j < work_threads; j++) { printf("fib(%d) = %d\\n", i + j, params[j].result); params[j].result = -1; } } for (i = 0; i < thread_count; i++) { params[i].work = 0; } printf("END\\n"); return 0; }
0
#include <pthread.h> char buffer[9][18]; int done = 0; char* infile_name; char* outfile_name; FILE *infile, *outfile; pthread_cond_t empty_slot=PTHREAD_COND_INITIALIZER; pthread_cond_t avail_item=PTHREAD_COND_INITIALIZER; pthread_mutex_t buf_lock=PTHREAD_MUTEX_INITIALIZER; void *producer(); void *consumer(); int shared_buffer_counter = 0; main (int argc, char *argv[]) { int count = 1, argvcount = 0, matrixValueCount = 0; size_t length = 0; pthread_t m0, m1; if (argc != 3) { printf("Error - Incorrect Usage: Syntax is: prog3 infile outfile\\n"); exit(-1); } infile_name = argv[1]; outfile_name = argv[2]; infile = fopen(infile_name, "r"); if (infile == 0) {printf("something went wrong with opening the input file");exit(1);} outfile = fopen(outfile_name, "w"); if (outfile == 0) {printf("something went wrong with opening the output file");exit(1);} printf("main: making thread for Producer...\\n"); pthread_create(&m0, 0, (void *)producer, 0); printf("main: making thread for Consumer...\\n"); pthread_create(&m1, 0, (void *)consumer, 0); pthread_join(m0, 0); pthread_join(m1, 0); printf("main: EXITING...\\n"); fclose(infile); fclose(outfile); exit(0); } void *producer() { int in = 0; int full = 0; pthread_t self_id; self_id = pthread_self(); printf("producer: reporting in. Thread-id: %d Calculating..\\n", self_id); while(1) { while(!feof(infile)) { pthread_mutex_lock(&buf_lock); while(shared_buffer_counter == 8) { pthread_cond_wait(&empty_slot, &buf_lock); } fgets(buffer[in], 18, infile); printf("Producer: putting stuff in buffer slot: %d | %s\\n", in, buffer[in]); in = (in +1) % 9; shared_buffer_counter+=1; printf("P: SBC: %d\\n", shared_buffer_counter); pthread_cond_signal(&avail_item); pthread_mutex_unlock(&buf_lock); } done=1;printf("Consumer: FOUND EOF. Exiting\\n");break; } pthread_exit(0); } void *consumer() { int out=0; int slots = 0; int full = 0; pthread_t self_id; self_id = pthread_self(); printf("Consumer: reporting in. Thread-id: %d Calculating..\\n", self_id); while(1) { if(done==1 && shared_buffer_counter == 0){break;} pthread_mutex_lock(&buf_lock); while(shared_buffer_counter == 0) { pthread_cond_wait(&avail_item, &buf_lock); } fputs(buffer[out], outfile); printf("Consumer: out to file %d %s\\n", out, buffer[out]); out = (out+1)%9; shared_buffer_counter-=1; printf("C: SBC: %d\\n", shared_buffer_counter); pthread_cond_signal(&empty_slot); pthread_mutex_unlock(&buf_lock); } printf("Consumer got done = 1 signal\\n"); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mut1=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut2=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut3=PTHREAD_MUTEX_INITIALIZER; void sigint_handler(int s) { pthread_mutex_destroy(&mut1); pthread_mutex_destroy(&mut2); pthread_mutex_destroy(&mut3); exit(0); } void* first(void* arg) { int delta=*(int*)arg; struct timespec tps={0,delta}; while(1) { pthread_mutex_lock(&mut1); printf("f"); fflush(stdout); nanosleep(&tps, 0); printf("i"); fflush(stdout); nanosleep(&tps, 0); printf("r"); fflush(stdout); nanosleep(&tps, 0); printf("s"); fflush(stdout); nanosleep(&tps, 0); printf("t"); fflush(stdout); nanosleep(&tps, 0); printf(" "); fflush(stdout); nanosleep(&tps, 0); pthread_mutex_unlock(&mut2); } } void* second(void* arg) { int delta=*(int*)arg; struct timespec tps={0,delta}; while(1) { pthread_mutex_lock(&mut2); printf("s"); fflush(stdout); nanosleep(&tps, 0); printf("e"); fflush(stdout); nanosleep(&tps, 0); printf("c"); fflush(stdout); nanosleep(&tps, 0); printf("o"); fflush(stdout); nanosleep(&tps, 0); printf("n"); fflush(stdout); nanosleep(&tps, 0); printf("d"); fflush(stdout); nanosleep(&tps, 0); printf(" "); fflush(stdout); nanosleep(&tps, 0); pthread_mutex_unlock(&mut3); } } void* third(void* arg) { int delta=*(int*)arg; struct timespec tps={0,delta}; while(1) { pthread_mutex_lock(&mut3); printf("t"); fflush(stdout); nanosleep(&tps, 0); printf("h"); fflush(stdout); nanosleep(&tps, 0); printf("i"); fflush(stdout); nanosleep(&tps, 0); printf("r"); fflush(stdout); nanosleep(&tps, 0); printf("d"); fflush(stdout); nanosleep(&tps, 0); printf(" "); fflush(stdout); nanosleep(&tps, 0); pthread_mutex_unlock(&mut1); } } void main(int argc, char** argv) { int d1=atoi(argv[1])*10000000; int d2=atoi(argv[2])*10000000; int d3=atoi(argv[3])*10000000; struct sigaction sa; sa.sa_handler=sigint_handler; sa.sa_flags=SA_RESTART; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); pthread_t th1, th2, th3; pthread_mutex_lock(&mut2); pthread_mutex_lock(&mut3); int ptid1=pthread_create(&th1, 0, first, &d1); int ptid2=pthread_create(&th2, 0, second, &d2); int ptid3=pthread_create(&th3, 0, third, &d3); pthread_join(th1, 0); exit(0); }
0
#include <pthread.h> extern int makethread(void *(*fn)(void *), void *); struct to_info { void (*fn)(void *); void *to_arg; struct timespec to_wait; }; 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); return ((void *)0); } void timeout(const struct timespec *when, void (*func)(void *arg), void *arg){ struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((now.tv_sec < when.tv_sec) || (now.tv_sec == when.tv_sec && now.tv_nsec < when.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); } } (*func)(arg); } pthread_mutex_t mutex; pthread_mutexattr_t attr; void retry(void *arg){ pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]){ int err, condition, arg; struct timespec when; int err; err = pthread_mutexattr_init(&attr); err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); err = pthread_mutex_init(&attr); pthread_mutex_lock(&mutex); if (condition){ timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> { char name[20]; char file[1024]; }MSG; MSG msg; pthread_mutex_t mutx; void * control_clnt(void *arg); void send_msg(MSG msg,int len); int sum_clnt=0; int clnt_socks[1000]; int main(int argc,char *argv[]) { int serv_sock,clnt_sock=0; struct sockaddr_in serv_addr,clnt_addr; int clnt_adr_sz; pthread_t t_id; if(argc!=2){ printf("usage :%s <port>\\n",argv[0]); exit(1); } pthread_mutex_init(&mutx,0); serv_sock=socket(PF_INET,SOCK_STREAM,0); if(serv_sock==-1){ printf("Can't build the server socket!\\n"); exit(1); } memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family=AF_INET; serv_addr.sin_port=htons(atoi(argv[1])); serv_addr.sin_addr.s_addr=htonl(INADDR_ANY); if((bind(serv_sock,(struct sockaddr *)&serv_addr,sizeof(serv_addr)))==-1){ printf("fail to build socket\\n");exit(1); } else printf("build the server socket!\\n"); if((listen(serv_sock,100))==-1){ printf("fail to listen!\\n");return 1;} else printf("listening!!!!!!!!!!!!!!!!!!!\\n"); while(1){ clnt_adr_sz=sizeof(clnt_addr); clnt_sock=accept(serv_sock,(struct sockaddr*)&clnt_addr,&clnt_adr_sz); if(clnt_sock==-1){ printf("fail to connect the client!\\n"); exit(1); } pthread_mutex_lock(&mutx); clnt_socks[sum_clnt++]=clnt_sock; pthread_mutex_unlock(&mutx); pthread_create(&t_id,0,control_clnt,(void*)&clnt_sock); pthread_detach(t_id); printf("connect the client IP :%s \\n",inet_ntoa(clnt_addr.sin_addr)); } close(serv_sock); return 0; } void *control_clnt(void *arg) { int clnt_sock=*((int *)arg); int str_len=0,i; while((str_len=read(clnt_sock,&msg,sizeof(msg)))!=0) send_msg(msg,str_len); pthread_mutex_lock(&mutx); for(i=0;i<sum_clnt;i++) if(clnt_sock==clnt_socks[i]) { while(i<sum_clnt-1) {clnt_socks[i]=clnt_socks[i+1];i++;} break; } sum_clnt--; pthread_mutex_unlock(&mutx); close(clnt_sock);printf("关灯!\\n"); return 0; } void send_msg(MSG msg,int len) { int i; pthread_mutex_lock(&mutx); for(i=0;i<sum_clnt;i++) write(clnt_socks[i],&msg,len); pthread_mutex_unlock(&mutx); }
0
#include <pthread.h> pthread_t phil[3]; pthread_mutex_t baguette[3]; void mange(int id) { printf("Philosophe [%d] mange\\n",id); for(int i=0;i< rand(); i++) { } } void* philosophe ( void* arg ) { int *id=(int *) arg; int left = *id; int right = (left + 1) % 3; while(1) { printf("Philosophe [%d] pense\\n",*id); pthread_mutex_lock(&baguette[left]); printf("Philosophe [%d] possède baguette gauche [%d]\\n",*id,left); pthread_mutex_lock(&baguette[right]); printf("Philosophe [%d] possède baguette droite [%d]\\n",*id,right); mange(*id); pthread_mutex_unlock(&baguette[left]); printf("Philosophe [%d] a libéré baguette gauche [%d]\\n",*id,left); pthread_mutex_unlock(&baguette[right]); printf("Philosophe [%d] a libéré baguette droite [%d]\\n",*id,right); } return (0); } int main ( int argc, char *argv[]) { long i; int id[3]; srand(getpid()); for (i = 0; i < 3; i++) id[i]=i; for (i = 0; i < 3; i++) pthread_mutex_init( &baguette[i], 0); for (i = 0; i < 3; i++) pthread_create(&phil[i], 0, philosophe, (void*)&(id[i]) ); for (i = 0; i < 3; i++) pthread_join(phil[i], 0); return (0); }
1
#include <pthread.h> int first_pack = 0; struct timeval dateInicio, dateFin; pthread_mutex_t lock; int mostrarInfo = 0; int MAX_PACKS = 1; int NTHREADS = 1; double segundos; llamadaHilo(int dev_fd){ char buf[10]; int lectura; int paquetesParaAtender = MAX_PACKS/NTHREADS; int i; for(i = 0; i < paquetesParaAtender; i++) { lectura = read(dev_fd, buf, 10); if(lectura <= 0) { fprintf(stderr, "Error en el read del dispositivo (%d)\\n", lectura); exit(1); } if(first_pack==0) { pthread_mutex_lock(&lock); if(first_pack == 0) { if(mostrarInfo) printf("got first pack\\n"); first_pack = 1; gettimeofday(&dateInicio, 0); } pthread_mutex_unlock(&lock); } } } main(int argc, char **argv){ if(argc < 3){ fprintf(stderr, "Syntax Error: Esperado: ./dev_urandom MAX_PACKS NTHREADS\\n"); exit(1); } MAX_PACKS = atoi(argv[1]); NTHREADS = atoi(argv[2]); pthread_t pids[NTHREADS]; pthread_mutex_init(&lock, 0); int dev_fd; dev_fd = open("/dev/urandom", 0); if(dev_fd < 0){ fprintf(stderr, "Error al abrir el dispositivo"); exit(1); } int i; for(i=0; i < NTHREADS; i++) pthread_create(&pids[i], 0, llamadaHilo, dev_fd); for(i=0; i < NTHREADS; i++) pthread_join(pids[i], 0); gettimeofday(&dateFin, 0); segundos=(dateFin.tv_sec*1.0+dateFin.tv_usec/1000000.)-(dateInicio.tv_sec*1.0+dateInicio.tv_usec/1000000.); if(mostrarInfo){ printf("Tiempo Total = %g\\n", segundos); printf("QPS = %g\\n", MAX_PACKS*1.0/segundos); }else{ printf("%g, \\n", segundos); } exit(0); }
0
#include <pthread.h> pthread_t tidArr[4]; pthread_cond_t condArr[4]; int flag = 1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * threadFunc1(void * arg) { while(1) { pthread_mutex_lock(&mutex); while( 1 != flag) { pthread_cond_wait(condArr,&mutex); } fprintf(stdout,"%c",'A'); fflush(0); flag = 2; pthread_cond_signal(condArr + 1); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void * threadFunc2(void * arg) { while(1) { pthread_mutex_lock(&mutex); while( 2 != flag) { pthread_cond_wait(condArr + 1,&mutex); } fprintf(stdout,"%c",'B'); fflush(0); flag = 3; pthread_cond_signal(condArr + 2); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void * threadFunc3(void * arg) { while(1) { pthread_mutex_lock(&mutex); while( 3 != flag) { pthread_cond_wait(condArr + 2,&mutex); } fprintf(stdout,"%c",'C'); fflush(0); flag = 4; pthread_cond_signal(condArr + 3); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void * threadFunc4(void * arg) { while(1) { pthread_mutex_lock(&mutex); while( 4 != flag) { pthread_cond_wait(condArr + 3,&mutex); } fprintf(stdout,"%c",'D'); fflush(0); flag = 1; pthread_cond_signal(condArr); pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void sighandler(int signum) { fprintf(stdout,"SIGINT received!\\n"); int i; for(i = 0;i < 4; i++) { pthread_cancel(tidArr[i]); } } int main(int argc,char **argv) { pthread_t *ret; threadFunc_t threadFuncArr[] = {threadFunc1,threadFunc2,threadFunc3,threadFunc4}; int i; signal(SIGINT,sighandler); for(i = 0; i < 4; i++) { pthread_cond_init(condArr + i,0); } for(i = 0;i < 4; i++) { pthread_create(tidArr + i,0,threadFuncArr[i],0); } pthread_cond_signal(condArr); for(i = 0;i < 4; i++) { pthread_join(tidArr[i],(void **)&ret); } while(1) { pause(); } pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> int IsPrime = 1; int Golba_N = 0; int Global_P = 0; int SubSetLen = 0; int RemainedThread = 0; pthread_mutex_t mutexsum; void *CheckPrime(void *threadid) { int taskId, i=0; taskId = (int)threadid; int startIndex = (SubSetLen * taskId); if(taskId == 0) i=2; for(; i<SubSetLen && (Golba_N/2) >= (startIndex + i) && (startIndex + i) != 1; i++ ) { if(Golba_N % (startIndex + i) == 0) { pthread_mutex_lock(&mutexsum); IsPrime = 0; printf("taskId:%d ,\\tIsnot Prime: %d/%d=0\\n",taskId,Golba_N,(startIndex + i)); pthread_mutex_unlock(&mutexsum);return; pthread_exit(0); } } pthread_mutex_lock(&mutexsum); RemainedThread--; printf("taskId:%d ,\\tRemainedThread = %d \\n",taskId,RemainedThread); pthread_mutex_unlock(&mutexsum); pthread_exit(0); } void main(int argc, char *argv[]) { if(argc != 3){ printf("\\nInput arrguments are not correct Global_P Golba_N ...\\n"); return; } Global_P = atoi(argv[1]); RemainedThread = Global_P; Golba_N = atoi(argv[2]); SubSetLen = Golba_N/Global_P; if(SubSetLen == 0) { printf("\\nThe number of threads are more than N, Global_P must be less than Golba_N because it is impossible to divid the elements among threads\\n"); return; } pthread_t threads[Global_P]; pthread_attr_t attr; int rc, t; pthread_mutex_init(&mutexsum, 0); for(t=0; t < Global_P; t++) { printf("Creating thread : %d\\n", t); rc = pthread_create(&threads[t], 0, CheckPrime, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } while(1 ) { if (IsPrime == 0) { printf("\\n\\nMain Function: Golba_N = %d isnot prime \\n", Golba_N); pthread_mutex_destroy(&mutexsum); pthread_exit(0); return; } if(RemainedThread == 0) { printf("\\n\\nMain Function: Golba_N = %d is prime \\n", Golba_N); pthread_mutex_destroy(&mutexsum); pthread_exit(0); return; } } }
0
#include <pthread.h> pthread_mutex_t entry_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_func(void *data) { struct parking_details *pdata = (struct parking_details *)data; pthread_mutex_lock(&entry_mutex); printf("\\n enter the car details thread : %d",pdata->thread_instance); printf("\\n car number :"); scanf("%s",pdata->car_number); printf("\\n token id : "); scanf("%d",&pdata->token_id); printf("driver name :"); scanf("%s",pdata->driver_name); printf("driver mother name :"); scanf("%s",pdata->driver_mother_name); pthread_mutex_unlock(&entry_mutex); return 0; } void* thread_test(void *data) { char car_number[STRING_MAX]; int token_id; char driver_name[STRING_MAX]; char driver_mother_name[STRING_MAX]; pthread_mutex_lock(&entry_mutex); printf("\\n car number :"); scanf("%s",car_number); printf("\\n token id : "); scanf("%d",&token_id); printf("driver name :"); scanf("%s",driver_name); printf("driver mother name :"); scanf("%s",driver_mother_name); pthread_mutex_unlock(&entry_mutex); return 0; } void* thread1_func(void *data) { struct parking_details *pdata = (struct parking_details *)data; while(1) { pthread_mutex_lock(&entry_mutex); printf("\\n enter the car details thread 1"); printf("\\n car number 1 :"); scanf("%s",pdata->car_number); printf("\\n token id 1 : "); scanf("%d",&pdata->token_id); printf("\\n driver name 1 : "); scanf("%s",pdata->driver_name); printf("\\n driver mother name 1 :"); scanf("%s",pdata->driver_mother_name); pthread_mutex_unlock(&entry_mutex); } } void* thread2_func(void *data) { struct parking_details *pdata = (struct parking_details *)data; while(1) { pthread_mutex_lock(&entry_mutex); printf("\\n enter the car details 2"); printf("\\n car number 2 :"); scanf("%s",pdata->car_number); printf("\\n token id 2 : "); scanf("%d",&pdata->token_id); printf("\\n driver name 2 : "); scanf("%s",pdata->driver_name); printf("\\n driver mother name 2 :"); scanf("%s",pdata->driver_mother_name); pthread_mutex_unlock(&entry_mutex); } } int main (int argc,char* argv[]) { pthread_t thread1_id, thread2_id; time_t clk = time(0); struct parking_details car[MAX_CAR]; struct state *car_state; int segment_id; char* shared_memory; struct shmid_ds shmbuffer; int segment_size; const int shared_segment_size = 0x64; segment_id = shmget (SHMEM_KEY, shared_segment_size,IPC_CREAT | S_IRUSR | S_IWUSR); printf("entry segment id : %d \\n",segment_id); shared_memory = (char*) shmat (segment_id, 0, 0); printf ("shared memory attached at address %p\\n", shared_memory); shmctl (segment_id, IPC_STAT, &shmbuffer); segment_size = shmbuffer.shm_segsz; printf ("segment size: %d\\n", segment_size); sprintf (shared_memory, "Rangarajan"); printf("argv[0] = %s\\n",argv[0]); printf("argv[1] = %s\\n",argv[1]); printf(" Current timing of the process is %s \\n",ctime(&clk)); printf("Inside Entry system process \\n"); car[0].thread_instance = 1; pthread_create(&thread1_id,0,&thread_func,(void *)&car[0]); car[1].thread_instance = 2; pthread_create(&thread2_id,0,&thread_func,(void *)&car[1]); pthread_join(thread1_id,0); pthread_join(thread2_id,0); shmdt (shared_memory); return 0; }
1
#include <pthread.h> pthread_mutex_t exclusionMutex5; pthread_mutex_t exclusionMutex7; int nrOf5 = 0, nrOf7 = 0; void* computeThread(void *arg) { int nr = *(int *)arg; int initialNr = nr; int increment5 = 0, increment7 = 0; while(nr) { if(nr % 10 == 5) increment5++; if(nr % 10 == 7) increment7++; nr /= 10; } if(increment5) { pthread_mutex_lock(&exclusionMutex5); nrOf5 += increment5; pthread_mutex_unlock(&exclusionMutex5); } if(increment7) { pthread_mutex_lock(&exclusionMutex7); nrOf7 += increment7; pthread_mutex_unlock(&exclusionMutex7); } printf("Thread. Initial: %d . Five: %d, Seven: %d\\n", initialNr, increment5, increment7); return 0; } int main(int argc, char *argv[]) { pthread_t threads[101]; if (pthread_mutex_init(&exclusionMutex5, 0) != 0 || pthread_mutex_init(&exclusionMutex7, 0) != 0) { perror("Error creating mutex"); exit(1); } int i, j; for(i = 1; i < argc; i++) { char aux[100]; int nr = 0; for(j = 0; j < strlen(argv[i]); j++) { nr = nr * 10 + (argv[i][j] - '0'); } int *nrToSend = malloc(sizeof(int)); *nrToSend = nr; pthread_create(&threads[i], 0, computeThread, nrToSend); } for(i = 1; i < argc; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&exclusionMutex5); pthread_mutex_destroy(&exclusionMutex7); printf("Number of digits 5: %d \\n Number of digits 7: %d", nrOf5, nrOf7); }
0
#include <pthread.h> static int nmea_checksum(char *line) { uint8_t checksum = 0; while (*line){ if (*line == '$'){ line++; continue; } if (*line == '*') break; checksum ^= *line++; } return (strtoul(line+1, 0, 16) == checksum); } void *readSerial() { int STOP=FALSE; int fd, res; char line[82]; struct termios attrib; fd = open(DEVICE, O_RDONLY); if(fd == -1){ printf("Could not open %s, errno = %d", DEVICE, errno); exit(1); } attrib.c_lflag = ICANON; attrib.c_iflag = IXOFF | IUTF8; attrib.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD; tcflush(fd, TCIFLUSH); if(tcsetattr(fd, TCSANOW, &attrib) == -1){ printf("Could not set attributes!\\n"); exit(1); } while (STOP==FALSE){ res = read( fd, line, 81); line[res]=0; if(nmea_checksum(line)){ if(strstr(line, "$GPGGA")!=0){ pthread_mutex_lock(&GPGGAMutex); GPGGA_LIST = pushItem(GPGGA_LIST, line); pthread_mutex_unlock(&GPGGAMutex); } if(strstr(line, "$GPGSA")!=0){ pthread_mutex_lock(&GPGSAMutex); GPGSA_LIST = pushItem(GPGSA_LIST, line); pthread_mutex_unlock(&GPGSAMutex); } if(strstr(line, "$GPRMC")!=0){ pthread_mutex_lock(&GPRMCMutex); GPRMC_LIST = pushItem(GPRMC_LIST, line); pthread_mutex_unlock(&GPRMCMutex); } if(strstr(line, "$GPGSV")!=0){ pthread_mutex_lock(&GPGSVMutex); GPGSV_LIST = pushItem(GPGSV_LIST, line); pthread_mutex_unlock(&GPGSVMutex); } } } close(fd); return 0; }
1
#include <pthread.h> int timer_init(struct util_timer_list *list) { list->head = 0; list->tail = 0; pthread_mutex_init(&(list->mutex), 0); return MQTT_ERR_SUCCESS; } int add_timer(struct util_timer_list *list, struct util_timer *timer) { int ret; LOG_PRINT("Add the timer"); if(!list || !timer) { return MQTT_ERR_NULL; } assert(pthread_mutex_lock(&(list->mutex))==0); if(list->head == 0) { list->head = timer; list->tail = timer; assert(pthread_mutex_unlock(&(list->mutex)) == 0); return MQTT_ERR_SUCCESS; } if(timer->expire < list->head->expire) { timer->next = list->head; list->head->prev = timer; list->head = timer; assert(pthread_mutex_unlock(&(list->mutex)) == 0); return MQTT_ERR_SUCCESS; } ret = add_timer_after(list, timer, list->head); assert(pthread_mutex_unlock(&(list->mutex))==0); return ret; } int add_timer_after(struct util_timer_list *list, struct util_timer *timer, struct util_timer *tar) { assert(tar != 0); struct util_timer *tmp = tar; while(tmp->next != 0 && timer->expire > tmp->next->expire) tmp = tmp->next; if(tmp->next == 0) { timer->prev = tmp; timer->next = tmp->next; tmp->next = timer; list->tail = timer; }else{ timer->prev = tmp; tmp->next->prev = timer; timer->next = tmp->next; tmp->next = timer; } return MQTT_ERR_SUCCESS; } int adjust_timer(struct util_timer_list *list, struct util_timer *timer) { if(!list || !timer) return MQTT_ERR_NULL; struct util_timer *tmp; if(timer == list->tail) return MQTT_ERR_SUCCESS; if(timer->expire < timer->next->expire) { return MQTT_ERR_SUCCESS; } if(timer == list->head) { list->head->next->prev = 0; list->head = list->head->next; timer->next = 0; return add_timer(list, timer); }else{ timer->next->prev =timer->prev; timer->prev->next = timer->next; tmp = timer->next; timer->prev = timer->next = 0; return add_timer_after(list, timer, tmp); } } int remove_timer(struct util_timer_list *list, struct util_timer *timer) { LOG_PRINT("In funciton remove_timer"); if(!list || !list->head || !timer) return MQTT_ERR_NULL; LOG_PRINT("Remove timer"); pthread_mutex_lock(&(list->mutex)); if(timer == list->head) { list->head = timer->next; if(list->head != 0){ list->head->prev = 0; }else{ list->tail = 0; } } else if(timer == list->tail) { list->tail = timer->prev; list->tail->next = 0; } else { if(timer->next != 0 && timer->prev != 0) { timer->next->prev = timer->prev; timer->prev->next = timer->next; } } timer->next = 0; timer->prev = 0; pthread_mutex_unlock(&(list->mutex)); LOG_PRINT("Timer is Removed"); return MQTT_ERR_SUCCESS; } void timer_tick(struct util_timer_list *list) { if(!list || !list->head) return; LOG_PRINT("Timer tick!"); time_t cur = time(0); pthread_mutex_lock(&(list->mutex)); struct util_timer *tmp = list->head; while(tmp) { if(cur < tmp->expire) { break; } struct client_data *data; get_client_data(tmp, &data); assert(data); assert(data->dead_clean); assert(data->sockfd); LOG_PRINT("client [%d] time expire", data->sockfd); data->dead_clean(data->sockfd); LOG_PRINT("A"); list->head = tmp->next; LOG_PRINT("A"); if(list->head) { LOG_PRINT("A"); list->head->prev = 0; }else{ LOG_PRINT("A"); list->tail = 0; } LOG_PRINT("A"); tmp = list->head; LOG_PRINT("A"); } pthread_mutex_unlock(&(list->mutex)); LOG_PRINT("Timer no expire"); } void get_client_data(struct util_timer *timer, struct client_data **data) { *data = (struct client_data *) (timer); } int inc_timer(struct util_timer_list *list, struct util_timer *timer, uint16_t inctime) { int ret; LOG_PRINT("Update the timer"); pthread_mutex_lock(&(list->mutex)); timer->expire = time(0) + inctime; ret = adjust_timer(list, timer); pthread_mutex_unlock(&(list->mutex)); return ret; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t db; pthread_mutex_t writerLock; pthread_cond_t conditionRead; pthread_cond_t conditionWrite; int rc = 0; int writerState = 0; int waitLimit = 3; void writeData(int v); void readDB(int v); void * writer(void * v); void * reader(void * v); int main(){ pthread_mutex_init(&mutex,0); pthread_mutex_init(&db,0); pthread_mutex_init(&writerLock,0); pthread_cond_init(&conditionRead,0); pthread_cond_init(&conditionWrite,0); pthread_t readtid[5]; pthread_t writetid[3]; int readNum[5]; int writeNum[3]; int x; for(x=0;x < 5;x++){ readNum[x] = x; pthread_create(&readtid[x],0,reader,&(readNum[x])); } for(x=0;x < 3;x++){ writeNum[x] = x; pthread_create(&writetid[x],0,writer,&(writeNum[x])); } for(x=0;x < 5;x++){ pthread_join(readtid[x],0); } for(x=0;x < 3;x++){ pthread_join(writetid[x],0); } return 0; } void * reader(void * v){ int j = *((int *)v); while(1){ pthread_mutex_lock(&mutex); rc++; if(rc == 1){ pthread_mutex_lock(&db); } pthread_mutex_unlock(&mutex); readDB(j); pthread_mutex_lock(&mutex); if(writerState == 1 && rc%waitLimit == 0){ pthread_cond_signal(&conditionWrite); pthread_cond_wait(&conditionRead,&db); } pthread_mutex_unlock(&mutex); } } void * writer(void * v){ int j = *((int *)v); while(1){ pthread_mutex_lock(&writerLock); writerState = 1; pthread_cond_wait(&conditionWrite,&writerLock); pthread_mutex_lock(&db); printf("Writer %d locking db\\n",j); writeData(j); printf("Writer %d unlocking db\\n",j); pthread_mutex_unlock(&db); writerState = 0; pthread_cond_signal(&conditionRead); pthread_mutex_unlock(&writerLock); } } void readDB(int v){ printf("Reader %d reading\\n",v); } void writeData(int v){ printf("Writer %d writing\\n",v); }
1
#include <pthread.h> void do_one_thing(int *); void do_another_thing(int *); void do_wrap_up(int,int); int r1=0,r2=0,r3=0; pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER; int main(int argc, char **argv){ pthread_t thread1, thread2; r3 = atoi(argv[1]); pthread_create(&thread1, 0, (void *) do_one_thing, (void *) &r1); pthread_create(&thread2, 0, (void *) do_another_thing, (void *) &r2); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; } void do_one_thing(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("do one thing\\n"); for(j=0;j<10000;j++) x = x + i; (*pnum_times)++; } } void do_another_thing(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("do another thing\\n"); for(j=0;j<10000;j++) x = x + i; (*pnum_times)++; } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_producer = PTHREAD_COND_INITIALIZER; struct { char data[1024]; int filled; int closed; }buff = {.filled = 0, .closed = 0}; void *consumer(void *arg) { int munching = 1; while(munching){ pthread_mutex_lock(&mutex); if (buff.filled != 1) pthread_cond_wait(&cond_consumer, &mutex); printf("%s", buff.data); buff.filled = 0; if (buff.closed == 1) munching =0; pthread_cond_signal(&cond_producer); pthread_mutex_unlock(&mutex); } return 0; } void *producer (void *arg) { const char *data = " Hello, Stonehenge! Who takes the Pandorica takes the" "Universe! But, bad news everyone, 'cause guess who! Ha! Except, you lot," "you're all whizzing about, it's really very distracting. Could you all just" "stay still a minute because I am talking!"; size_t len = strlen(data); size_t pos = 0; int cooking = 1; while (cooking == 1){ pthread_mutex_lock(&mutex); if (buff.filled == 1) pthread_cond_wait(&cond_producer, &mutex); const int buf_space = sizeof(buff.data) -1; const int wlen = (len - pos) < buf_space ? len - pos : buf_space; memcpy(&buff.data[0], data + pos, wlen); buff.data[wlen] = 0; buff.filled = 1; pos += wlen; if (pos >= len){ cooking = 0; buff.closed = 1; } pthread_cond_signal(&cond_consumer); pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char ** argv) { pthread_t prod_thread, con_thread; pthread_create (&prod_thread, 0, producer, 0); pthread_create (&con_thread, 0, consumer, 0); pthread_join(prod_thread, 0); pthread_join(con_thread, 0); return 0; }
1
#include <pthread.h> struct ticket { int ticket_type; int seat_number; char sold_by; bool availability; }; struct customer { char priority; char name; char thread; }; struct seller { int min_responseTime; int max_responseTime; int avg_reponseTime; char name; char priority; char customerQueue[]; }; static const int NUMBER_OF_SELLERS = 10; static const int HIGH_PRICE_SELLERS = 1; static const int MEDIUM_PRICE_SELLERS = 3; static const int LOW_PRICE_SELLERS = 6; static const int NUMBER_OF_ROWS = 10; static const int SEATS_PER_ROW = 10; static char * const EMPTY_SEAT = "--"; static const char NEWLINE = '\\n'; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * sell(void * sellertype) { char st; st = *((char*) sellertype); printf("Seller type %c\\n", st); pthread_exit(0); } void wakeup_all_seller_threads() { pthread_mutex_lock(&mutex); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } int main(int argc, char * argv[]) { struct ticket ticket1; ticket1.seat_number = 5; printf("%d\\n", ticket1.seat_number); int n; if (argc != 2) { fprintf(stderr, "ERROR; Execution must be in form [./a.out] [int]\\n"); exit(1); } else { if (!isdigit(*argv[1])) { fprintf(stderr, "ERROR; User input must be type int\\n"); exit(1); } else { n = atoi(argv[1]); } } int i, j, rc; pthread_t tids[10]; char * seatmap[NUMBER_OF_ROWS][SEATS_PER_ROW]; for (i=0; i < NUMBER_OF_ROWS; i++) { for (j=0; j < SEATS_PER_ROW; j++) { seatmap[i][j] = EMPTY_SEAT; } } char *testchar = "5"; seatmap[5][5] = testchar;; char sellertype; sellertype = 'H'; for (i = 0; i < 1; i++) { rc = pthread_create(&tids[i], 0, sell, &sellertype); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join is %d\\n", rc); exit(1); } } sellertype = 'M'; for (i = 1; i < 4; i++) { rc = pthread_create(&tids[i], 0, sell, &sellertype); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join is %d\\n", rc); exit(1); } } sellertype = 'L'; for (i = 4; i < 10; i++) { rc = pthread_create(&tids[i], 0, sell, &sellertype); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join is %d\\n", rc); exit(1); } } for (i = 0 ; i < NUMBER_OF_SELLERS ; i++) { rc = pthread_join(tids[i], 0); if (rc) { fprintf(stderr, "ERROR; return code from pthread_join is %d\\n", rc); exit(1); } } printf("Seating Chart\\n"); for (i=0; i < NUMBER_OF_ROWS; i++) { for (j=0; j < SEATS_PER_ROW; j++) { printf("%-3s", seatmap[i][j]); } printf("%c", NEWLINE); } exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; void *start_routine(void *arg) { static int g_i = 0; pthread_mutex_lock(&mutex); pid_t pid = getpid(); pthread_t ptid = pthread_self(); printf("process_id = %d (0x%lx), thread_id = %lu (0x%lx), [%s], [g_i=%x]\\n", pid, pid, ptid, ptid, (char*)arg, g_i++); pthread_mutex_unlock(&mutex); return arg; } int main() { int ret = 0; pthread_t *thread = (pthread_t*)malloc(sizeof (pthread_t) * ((10))); const pthread_attr_t *attr = 0; void *arg; arg = malloc(5); memset(arg, 0, sizeof arg); ret = pthread_mutex_init(&mutex, 0); if (ret != 0) { printf("%s(%d)\\n", strerror(ret), ret); return ret; } pid_t pid = getpid(); pthread_t ptid = pthread_self(); printf("process_id = %d (0x%lx), thread_id = %lu (0x%lx)\\n", pid, pid, ptid, ptid); int i; for (i = 0; i < (10); i++) { sprintf(arg, "YES%d", i); ret = pthread_create(thread + i, attr, start_routine, arg); if (ret != 0) { printf("%s(%d)\\n", strerror(ret), ret); continue; } if (i == -1) { ret = pthread_detach(*(thread + i)); if (ret != 0) { printf("%s(%d)\\n", strerror(ret), ret); continue; } } } for (i = 0; i < (10); i++) { ret = pthread_join(*(thread + i), &arg); if (ret != 0) { printf("%s(%d)\\n", strerror(ret), ret); continue; } } free(arg); free(thread); ret = pthread_mutex_destroy(&mutex); if (ret != 0) { printf("%s(%d)\\n", strerror(ret), ret); return ret; } return ret; }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct daos_lru_cache* vos_get_obj_cache(void) { return vos_tls_get()->vtl_imems_inst.vis_ocache; } static inline void vos_imem_strts_destroy(struct vos_imem_strts *imem_inst) { if (imem_inst->vis_ocache) vos_obj_cache_destroy(imem_inst->vis_ocache); if (imem_inst->vis_pool_hhash) daos_uhash_destroy(imem_inst->vis_pool_hhash); if (imem_inst->vis_cont_hhash) daos_uhash_destroy(imem_inst->vis_cont_hhash); } static inline int vos_imem_strts_create(struct vos_imem_strts *imem_inst) { int rc = 0; rc = vos_obj_cache_create(LRU_CACHE_BITS, &imem_inst->vis_ocache); if (rc) { D_ERROR("Error in createing object cache\\n"); return rc; } rc = daos_uhash_create(0 , VOS_POOL_HHASH_BITS, &imem_inst->vis_pool_hhash); if (rc) { D_ERROR("Error in creating POOL ref hash: %d\\n", rc); goto failed; } rc = daos_uhash_create(0 , VOS_CONT_HHASH_BITS, &imem_inst->vis_cont_hhash); if (rc) { D_ERROR("Error in creating CONT ref hash: %d\\n", rc); goto failed; } return 0; failed: vos_imem_strts_destroy(imem_inst); return rc; } static void * vos_tls_init(const struct dss_thread_local_storage *dtls, struct dss_module_key *key) { struct vos_tls *tls; D_ALLOC_PTR(tls); if (tls == 0) return 0; if (vos_imem_strts_create(&tls->vtl_imems_inst)) { D_FREE_PTR(tls); return 0; } return tls; } static void vos_tls_fini(const struct dss_thread_local_storage *dtls, struct dss_module_key *key, void *data) { struct vos_tls *tls = data; vos_imem_strts_destroy(&tls->vtl_imems_inst); D_FREE_PTR(tls); } struct dss_module_key vos_module_key = { .dmk_tags = DAOS_SERVER_TAG, .dmk_index = -1, .dmk_init = vos_tls_init, .dmk_fini = vos_tls_fini, }; static int vos_mod_init(void) { int rc = 0; rc = vos_cont_tab_register(); if (rc) { D_ERROR("VOS CI btree initialization error\\n"); return rc; } rc = vos_obj_tab_register(); if (rc) { D_ERROR("VOS OI btree initialization error\\n"); return rc; } rc = vos_cookie_tab_register(); if (rc) { D_ERROR("VOS cookie btree initialization error\\n"); return rc; } rc = vos_obj_tree_register(); if (rc) D_ERROR("Failed to register vos trees\\n"); return rc; } static int vos_mod_fini(void) { return 0; } struct dss_module vos_srv_module = { .sm_name = "vos_srv", .sm_mod_id = DAOS_VOS_MODULE, .sm_ver = 1, .sm_init = vos_mod_init, .sm_fini = vos_mod_fini, .sm_key = &vos_module_key, }; int vos_init(void) { char *env; int rc = 0; static int is_init = 0; if (is_init) { D_ERROR("Already initialized a VOS instance\\n"); return rc; } pthread_mutex_lock(&mutex); if (is_init && vsa_imems_inst) D_GOTO(exit, rc); D_ALLOC_PTR(vsa_imems_inst); if (vsa_imems_inst == 0) D_GOTO(exit, rc); rc = vos_imem_strts_create(vsa_imems_inst); if (rc) D_GOTO(exit, rc); rc = vos_mod_init(); if (rc) D_GOTO(exit, rc); env = getenv("VOS_MEM_CLASS"); if (env && strcasecmp(env, "vmem") == 0) vos_mem_class = UMEM_CLASS_VMEM; is_init = 1; exit: pthread_mutex_unlock(&mutex); if (rc && vsa_imems_inst) D_FREE_PTR(vsa_imems_inst); return rc; } void vos_fini(void) { pthread_mutex_lock(&mutex); if (vsa_imems_inst) { vos_imem_strts_destroy(vsa_imems_inst); D_FREE_PTR(vsa_imems_inst); } pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> pthread_t sort[4096]; pthread_mutex_t mutex; pthread_cond_t cond; int barrier = 0; int data[4096]; int num = 0; int nummerge; int left; }NODE; void read_data() { FILE *fp = fopen("indata.txt", "r"); int i = 0; if(fp == 0) { printf("cannot open the file\\n"); exit(0); } while(!feof(fp)) { fscanf(fp, "%d", &data[i]); i++; num++; } num--; printf("\\n"); fclose(fp); fp = 0; } void *merge(void *arg) { NODE *sort = (NODE *)arg; int num_merge = sort->nummerge; int left = sort->left; int mid = left + num_merge/2 - 1; int a = left; int b = mid + 1; int cpy[num_merge]; int ai = 0; while(a <= mid && b <= (left + num_merge - 1)) { if(data[a] >= data[b]) { cpy[ai++] = data[b++]; }else { cpy[ai++] = data[a++]; } } while(a <= mid) { cpy[ai++] = data[a++]; } while(b <= (left + num_merge - 1)) { cpy[ai++] = data[b++]; } for(ai = 0; ai < num_merge; ai++) { data[left + ai] = cpy[ai]; } pthread_mutex_lock(&mutex); barrier--; if(barrier > 0) { pthread_cond_wait(&cond, &mutex); } if(barrier <= 0) { pthread_cond_broadcast(&cond); } pthread_mutex_unlock(&mutex); } void main() { read_data(); int k = 0, j = 0; int num_merge = 2; int num_thread = num/2; int num_now = 0; NODE m[2048]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); while(num_merge <= num) { barrier = num_thread; for(j = 0; j < num_thread; j++) { m[j].nummerge = num_merge; m[j].left = j * num_merge; pthread_create(&sort[num_now + j], 0, (void *)merge, &m[j]); } num_now = num_thread + num_now; num_merge = num_merge * 2; num_thread = num_thread / 2; if(barrier > 0) { pthread_cond_wait(&cond, &mutex); } if(barrier <= 0) { pthread_cond_broadcast(&cond); } } for(k = 0; k < num; k++) { printf("%d ", data[k]); } printf("\\n"); }
1
#include <pthread.h> int nthreads, delaylength, innerreps; double times[20 +1] ; volatile int global_barrier_flag; volatile int global_barrier_count; volatile boolean champion_sense = ((boolean) 0); volatile boolean *opponent; role_enum role; volatile boolean flag; }round_t; round_t rounds[32][3]; struct omp_v_thread { volatile int parity; volatile boolean sense; volatile round_t *myrounds; }team[32]; pthread_t p_threads[32]; extern double get_time_of_day_(void); extern void init_time_of_day_(void); time_t starttime = 0; double get_time_of_day_() { struct timeval ts; double t; int err; err = gettimeofday(&ts, 0); t = (double) (ts.tv_sec - starttime) + (double) ts.tv_usec * 1.0e-6; return t; } void init_time_of_day_() { struct timeval ts; int err; err = gettimeofday(&ts, 0); starttime = ts.tv_sec; } static int firstcall = 1; double getclock() { double time; double get_time_of_day_(void); void init_time_of_day_(void); if (firstcall) { init_time_of_day_(); firstcall = 0; } time = get_time_of_day_(); return time; } void delay(int delaylength) { int i; float a=0.; for (i=0; i<delaylength; i++) a+=i; if (a < 0) printf("%f \\n",a); } void stats (double *mtp) { double meantime, totaltime; int i; totaltime = 0.; for (i=1; i<=20; i++){ totaltime +=times[i]; } meantime = totaltime / 20; *mtp = meantime; } static inline int ompc_atomic_inc(volatile int* value) { return (__sync_fetch_and_add(value,1)+1); } void tour_barrier_init(int vpid, volatile round_t **myrounds) { int k; (*myrounds) = &(rounds[vpid][0]); for(k = 0; k < 3; k++) (*myrounds)[k].role = ((role_enum) 16); for(k = 0; k < 3; k++) { int vpid_mod_2_sup_k_plus_1 = vpid % (1 << (k+1)); if (vpid_mod_2_sup_k_plus_1 == 0) { int partner = vpid + (1 << k); if (partner < 32) (*myrounds)[k].role = ((role_enum) 2); else (*myrounds)[k].role = ((role_enum) 8); (*myrounds)[k].opponent = (boolean *) 0; } else if (vpid_mod_2_sup_k_plus_1 == (1 << k)) { (*myrounds)[k].role = ((role_enum) 1); (*myrounds)[k].opponent = &(rounds[vpid - (1<<k)][k].flag); break; } } if (vpid == 0) { (*myrounds)[k-1].role = ((role_enum) 4); } for(k = 0; k < 3; k++) { (*myrounds)[k].flag = ((boolean) 0); } } pthread_mutex_t barrier_lock; pthread_cond_t barrier_cond; void OMPC_BARRIER(); void *print_message_function( void *ptr ) { int *i; int thread_id,n; int j,k=0; double start; double meantime; i = (int *)ptr; thread_id = *i; sleep(3); for (k=0; k<=20; k++) { start = getclock(); { for (j=0; j<innerreps; j++){ delay(delaylength); OMPC_BARRIER(); } } times[k] = (getclock() - start) * 1.0e6 / (double) innerreps; } stats (&meantime); printf("TID:%d: BARRIER time = %f microseconds \\n", thread_id,meantime); } void OMPC_BARRIER() { volatile int barrier_flag = global_barrier_flag; volatile int new_count = ompc_atomic_inc(&global_barrier_count); if (new_count == 32){ pthread_mutex_lock(&barrier_lock); global_barrier_count=0; global_barrier_flag = barrier_flag^1; pthread_cond_broadcast(&barrier_cond); pthread_mutex_unlock(&barrier_lock); } else { pthread_mutex_lock(&barrier_lock); while(barrier_flag==global_barrier_flag) pthread_cond_wait(&barrier_cond, &barrier_lock); pthread_mutex_unlock(&barrier_lock); } } int main(void) { int i; delaylength = 500; innerreps = 10000; global_barrier_count=0; global_barrier_flag=0; pthread_mutex_init(&barrier_lock, 0); pthread_cond_init(&barrier_cond, 0); for(i=0;i<32;i++){ tour_barrier_init(i,&(team[i].myrounds)); team[i].parity = 0; team[i].sense = ((boolean) 1); } for(i=0;i<32;i++){ pthread_create( &p_threads[i], 0, print_message_function, (void*) &i); } for(i=0;i<32;i++) pthread_join( p_threads[i], 0); pthread_mutex_destroy(&barrier_lock); pthread_cond_destroy(&barrier_cond); pthread_exit(0); return 0; }
0
#include <pthread.h> int thread_count; long current_thread = 0; pthread_mutex_t sequence_mutex; pthread_cond_t ok_to_proceed; void Usage(char* prog_name); void *Thread_work(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); thread_handles = malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&sequence_mutex, 0); pthread_cond_init(&ok_to_proceed, 0); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], (pthread_attr_t*) 0, Thread_work, (void*) thread); for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } pthread_mutex_destroy(&sequence_mutex); pthread_cond_destroy(&ok_to_proceed); free(thread_handles); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads>\\n", prog_name); exit(0); } void *Thread_work(void* rank) { long my_rank = (long) rank; while(1) { pthread_mutex_lock(&sequence_mutex); if (current_thread == my_rank) { printf("Hello from thread %ld of %d\\n", my_rank, thread_count); fflush(stdout); pthread_cond_broadcast(&ok_to_proceed); pthread_mutex_unlock(&sequence_mutex); current_thread ++; break; } else { while (pthread_cond_wait(&ok_to_proceed, &sequence_mutex) != 0); } pthread_mutex_unlock(&sequence_mutex); } return 0; }
1
#include <pthread.h> static void *hados_thread(void * parm) { int rc; srand48(time(0)); struct hados_context context; hados_context_init(&context); for (;;) { static pthread_mutex_t accept_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&accept_mutex); rc = FCGX_Accept_r(&context.fcgxRequest); pthread_mutex_unlock(&accept_mutex); if (rc < 0) break; hados_context_transaction_init(&context); hados_command_dispatch(&context); hados_response_write(&context.response); hados_context_transaction_free(&context); FCGX_Finish_r(&context.fcgxRequest); } hados_context_free(&context); return 0 ; } int main(void) { int i; pthread_t id[20]; FCGX_Init(); for (i = 1; i < 20; i++) pthread_create(&id[i], 0, hados_thread, 0 ); hados_thread(0 ); return 0; }
0
#include <pthread.h> static char envbuf[4096]; extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; char *getenv_unsafe(const char *name) { int i, len; len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len+1], 4096); return(envbuf); } } return(0); } static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return(ENOSPC); } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return(0); } } pthread_mutex_unlock(&env_mutex); return(ENOENT); }
1
#include <pthread.h> static uint8_t rand_buf[1024 * 8]; static uint rand_buf_off = 0; static int seeded = 0; static pthread_mutex_t rand_buf_lock = PTHREAD_MUTEX_INITIALIZER; int cf_rand_reload() { if (seeded == 0) { int rfd = open("/dev/urandom", O_RDONLY); int rsz = (int)read(rfd, rand_buf, 64); if (rsz < 64) { fprintf(stderr, "warning! can't seed random number generator"); return(-1); } close(rfd); RAND_seed(rand_buf, rsz); seeded = 1; } if (1 != RAND_bytes(rand_buf, sizeof(rand_buf))) { fprintf(stderr, "RAND_bytes not so happy.\\n"); return(-1); } rand_buf_off = sizeof(rand_buf); return(0); } int cf_get_rand_buf(uint8_t *buf, int len) { if ((uint)len >= sizeof(rand_buf)) return(-1); pthread_mutex_lock(&rand_buf_lock); if (rand_buf_off < (uint)len ) { if (-1 == cf_rand_reload()) { pthread_mutex_unlock(&rand_buf_lock); return(-1); } } rand_buf_off -= len; memcpy(buf, &rand_buf[rand_buf_off] ,len); pthread_mutex_unlock(&rand_buf_lock); return(0); } uint64_t cf_get_rand64() { pthread_mutex_lock(&rand_buf_lock); if (rand_buf_off < sizeof(uint64_t) ) { if (-1 == cf_rand_reload()) { pthread_mutex_unlock(&rand_buf_lock); return(0); } } rand_buf_off -= sizeof(uint64_t); uint64_t r = *(uint64_t *) (&rand_buf[rand_buf_off]); pthread_mutex_unlock(&rand_buf_lock); return(r); } uint32_t cf_get_rand32() { pthread_mutex_lock(&rand_buf_lock); if (rand_buf_off < sizeof(uint64_t) ) { if (-1 == cf_rand_reload()) { pthread_mutex_unlock(&rand_buf_lock); return(0); } } rand_buf_off -= sizeof(uint64_t); uint64_t r; r = *(uint64_t *) (&rand_buf[rand_buf_off]); pthread_mutex_unlock(&rand_buf_lock); return((uint32_t)r); }
0
#include <pthread.h> { void *(*process)(void *arg); void *arg; struct worker *next; } CThread_worker; { pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; pthread_t *threadid; int shutdown; int max_thread_num; int cur_queue_size; } CThread_pool; static CThread_pool *pool = 0; void * thread_routine (void *arg) { while (1) { pthread_mutex_lock (&(pool->queue_lock)); while (pool->cur_queue_size == 0 && !pool->shutdown) pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); if (pool->shutdown) { pthread_mutex_unlock (&(pool->queue_lock)); pthread_exit (0); } assert (pool->cur_queue_size != 0); assert (pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock (&(pool->queue_lock)); (*(worker->process)) (worker->arg); free (worker); worker = 0; } pthread_exit (0); } void pool_init (int max_thread_num) { pool = (CThread_pool *) malloc (sizeof (CThread_pool)); pthread_mutex_init (&(pool->queue_lock), 0); pthread_cond_init (&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); int i = 0; for (i = 0; i < max_thread_num; i++) pthread_create (&(pool->threadid[i]), 0, thread_routine, 0); } int pool_add_worker (void *(*process) (void *arg), void *arg) { CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock (&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if (member != 0) { while (member->next != 0) member = member->next; member->next = newworker; } else { pool->queue_head = newworker; } assert (pool->queue_head != 0); pool->cur_queue_size++; pthread_cond_signal (&(pool->queue_ready)); pthread_mutex_unlock (&(pool->queue_lock)); return 0; } int pool_destroy () { if (pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast (&(pool->queue_ready)); int i; for (i = 0; i < pool->max_thread_num; i++) pthread_join (pool->threadid[i], 0); free (pool->threadid); CThread_worker *head = 0; while (pool->queue_head != 0) { head = pool->queue_head; pool->queue_head = pool->queue_head->next; free (head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free (pool); pool=0; return 0; }
1
#include <pthread.h> void * thread_incoming_reader (void * arg) { int socket_fd = *((int*)arg); tslog(0, "ACCEPTOR", "Connection thread has started for fd %d.", socket_fd); char buffer[10240]; int code, b; while (1) { code = read(socket_fd, buffer, 10240); if (code == -1) { tslog(0, "ACCEPTOR", "Error while reading socket %d: %s", socket_fd, strerror(errno)); tslog(0, "ACCEPTOR", "Exiting connection %d.", socket_fd); close(socket_fd); break; } else if (code == 0) { tslog(0, "ACCEPTOR", "EOF at socket %d.", socket_fd); tslog(0, "ACCEPTOR", "Exiting connection %d.", socket_fd); close(socket_fd); break; } else { tslog(0, "ACCEPTOR", "Got %d bytes from socket %d.", code, socket_fd); size_t count_total = code, count_queued; do { pthread_mutex_lock(&transport_queue_mutex); count_queued = queue_data_put(&transport_queue, buffer, count_total); count_total -= count_queued; tslog(0, "ACCEPTOR", "Put %d bytes to queue, %d bytes waiting.", count_queued, count_total); pthread_cond_broadcast(&transport_queue_cond); pthread_mutex_unlock(&transport_queue_mutex); } while (count_total); } } return 0; }
0
#include <pthread.h> int i = 0; pthread_mutex_t mtx; void* Thread1(){ pthread_mutex_lock(&mtx); for (int x = 0; x < 1000000; ++x) { i = i+1; } printf("i fra trad_1: %d\\n", i ); pthread_mutex_unlock(&mtx); return 0; } void* Thread2(){ pthread_mutex_lock(&mtx); for (int x = 0; x < 1000000; ++x) { i = i-1; } printf("i fra trad_2: %d\\n", i ); pthread_mutex_unlock(&mtx); return 0; } int main(void){ pthread_mutex_init(&mtx, 0); pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, Thread1, 0); pthread_create(&thread2, 0, Thread2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); printf("\\nIn main, threads done, i = %d\\n\\n",i); return 0; }
1
#include <pthread.h> pthread_mutex_t joblock; int64_t jobs_available = 1000000; void do_job(uint64_t job_id) { for (int i = 0; i < 5; i++) { asm("nop"); } } void *do_jobs(void *thread_id) { int64_t current_job = 0; while (1) { pthread_mutex_lock(&joblock); current_job = jobs_available; jobs_available--; pthread_mutex_unlock(&joblock); if (current_job < 1) { break; } do_job(current_job); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t threads[2]; if (pthread_mutex_init(&joblock, 0) != 0){ printf("\\n mutex init failed\\n"); } for (int i = 0; i < 2; i++) { if (pthread_create(&threads[i], 0, do_jobs, (void*)(long)i) != 0) { printf("Thread creation error!\\n"); } } for (int i = 0; i < 2; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&joblock); return 0; }
0
#include <pthread.h> void *runner(void *param); int **A, **B, **C; size_t m1, n1, m2, n2; void initMatrix(int ***a, int m, int n); void getMatrix(int ***a, int m, int n); pthread_mutex_t lock; pthread_mutex_t threadLock; int THREADS = 4; int main(int argc, char const* argv[]) { printf("Enter the dimensions of matrix 1:\\n"); scanf("%lu", &m1); scanf("%lu", &n1); printf("Enter the dimensions of matrix 2:\\n"); scanf("%lu", &m2); scanf("%lu", &n2); if (n1 != m2){ perror("Not multipliable"); exit(1); } initMatrix(&A, m1, n1); getMatrix(&A, m1, n1); initMatrix(&B, m2, n2); getMatrix(&B, m2, n2); initMatrix(&C, m1, n2); pthread_t **tidMat = calloc(sizeof(pthread_t *), m1); for (int i = 0; i < m1; i++) { tidMat[i] = calloc(sizeof(pthread_t), n2); } pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&lock, 0); pthread_mutex_init(&threadLock, 0); matIndex curIndex = {.i=0, .j=0}; for (int i = 0; i < m1; i++) { for (int j = 0; j < n2; j++) { printf("THREADS = %d", THREADS); pthread_mutex_lock(&lock); curIndex.i = i; curIndex.j = j; pthread_create(&tidMat[i][j], &attr, runner, &curIndex); pthread_mutex_lock(&threadLock); THREADS--; pthread_mutex_unlock(&threadLock); while (THREADS == 0); printf("THREADS = %d", THREADS); pthread_join(tidMat[i][j], 0); } } for (int i = 0; i < m1; i++) { for (int j = 0; j < n2; j++) { pthread_join(tidMat[i][j], 0); } } printf("Matrix C = A x B\\n"); for (int i = 0; i < m1; i++) { for (int j = 0; j < n2; j++) { printf("%d ", C[i][j]); } printf("\\n"); } return 0; } void *runner(void *param) { matIndex *index = param; int indexI = index->i; int indexJ = index->j; pthread_mutex_unlock(&lock); for (int k = 0; k < m2; k++) { C[indexI][indexJ] += A[indexI][k] * B[k][indexJ]; } pthread_mutex_lock(&threadLock); THREADS++; pthread_mutex_unlock(&threadLock); pthread_exit(0); } void initMatrix(int ***a, int m, int n) { *a = calloc(sizeof(int *), m); for (int i = 0; i < m; i++) { (*a)[i] = calloc(sizeof(int), n); } } void getMatrix(int ***a, int m, int n) { printf("Input matrix\\n"); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { scanf("%d", &(*a)[i][j]); } } }
1
#include <pthread.h> pthread_mutex_t mutex_global; sem_t sem_fichier; int nb_lecteurs; }lecteur_redacteur_t; lecteur_redacteur_t lecteur_redacteur; int iterations; int donnee; } donnees_thread_t; void debut_redaction(lecteur_redacteur_t *lect_red){ printf("Arrivée du thread redacteur %x\\n", (int) pthread_self()); sem_wait(&lect_red->sem_fichier); } void fin_redaction(lecteur_redacteur_t *lect_red){ sem_post(&lect_red->sem_fichier); } void debut_lecture(lecteur_redacteur_t *lect_red){ printf("Arrivée du thread lecteur %x\\n", (int) pthread_self()); pthread_mutex_lock(&lect_red->mutex_global); if(lect_red->nb_lecteurs == 0) sem_wait(&lect_red->sem_fichier); lect_red->nb_lecteurs++; pthread_mutex_unlock(&lect_red->mutex_global); } void fin_lecture(lecteur_redacteur_t *lect_red){ pthread_mutex_lock(&lect_red->mutex_global); lect_red->nb_lecteurs--; if(lect_red->nb_lecteurs == 0) sem_post(&lect_red->sem_fichier); pthread_mutex_unlock(&lect_red->mutex_global); } void initialiser_lecteur_redacteur(lecteur_redacteur_t *lect_red){ lect_red->nb_lecteurs = 0; pthread_mutex_init(&lect_red->mutex_global,0); sem_init(&lect_red->sem_fichier,0,1); } void detruire_lecteur_redacteur(lecteur_redacteur_t *lect_red){ pthread_mutex_destroy(&lect_red->mutex_global); sem_destroy(&lect_red->sem_fichier); } void dodo(int scale) { usleep((random()%1000000)*scale); } void *lecteur(void *args) { donnees_thread_t *d = args; int i, valeur; srandom((int) pthread_self()); for (i=0; i < d->iterations; i++) { dodo(2); debut_lecture(&d->lecteur_redacteur); printf("Thread %x : debut lecture\\n", (int) pthread_self()); valeur = d->donnee; dodo(1); printf("Thread %x : ", (int) pthread_self()); if (valeur != d->donnee) printf("LECTURE INCOHERENTE !!!\\n"); else printf("lecture coherente\\n"); fin_lecture(&d->lecteur_redacteur); } pthread_exit(0); } void *redacteur(void *args) { donnees_thread_t *d = args; int i, valeur; srandom((int) pthread_self()); for (i=0; i < d->iterations; i++) { dodo(2); debut_redaction(&d->lecteur_redacteur); printf("Thread %x : debut redaction......\\n", (int) pthread_self()); valeur = random(); d->donnee = valeur; dodo(1); printf("Thread %x : ", (int) pthread_self()); if (valeur != d->donnee) printf("REDACTION INCOHERENTE !!!\\n"); else printf("redaction coherente......\\n"); fin_redaction(&d->lecteur_redacteur); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t *threads, *thread_courant; donnees_thread_t donnees_thread; int i, nb_lecteurs, nb_redacteurs; void *resultat; if (argc < 4) { fprintf(stderr, "Utilisation: %s nb_lecteurs nb_redacteurs " "nb_iterations\\n", argv[0]); exit(1); } nb_lecteurs = atoi(argv[1]); nb_redacteurs = atoi(argv[2]); donnees_thread.iterations = atoi(argv[3]); threads = malloc((nb_lecteurs+nb_redacteurs)*sizeof(pthread_t)); thread_courant = threads; initialiser_lecteur_redacteur(&donnees_thread.lecteur_redacteur); for (i=0; i<nb_lecteurs; i++) pthread_create(thread_courant++, 0, lecteur, &donnees_thread); for (i=0; i<nb_redacteurs; i++) pthread_create(thread_courant++, 0, redacteur, &donnees_thread); for (i=0; i<nb_lecteurs+nb_redacteurs; i++) pthread_join(threads[i], &resultat); detruire_lecteur_redacteur(&donnees_thread.lecteur_redacteur); free(threads); return 0; }
0
#include <pthread.h> struct reactor { pthread_t th; pthread_mutex_t mutex; int fd; int state; }; static struct reactor g_reactor = { .mutex = PTHREAD_MUTEX_INITIALIZER, .fd = -1, .state = 0 }; void *reactor_thread(void *arg) { struct reactor *self = (struct reactor *) arg; struct reactor_event *ev; struct epoll_event evlist[128]; int n = -1; int i; while (self->state) { n = epoll_wait(self->fd, evlist, 128, 5000); if (n == -1) { ERROR("epoll_wait failed"); break; } else if (n == 0) { DEBUG("epoll_wait timeout"); continue; } for(i = 0; i < n; i++){ ev = (struct reactor_event *)evlist[i].data.ptr; if (!ev) { ERROR("epoll_wait data-ptr is null"); continue; } ev->func(ev->data, ev->fd, evlist[i].events); } } return 0; } int reactor_start(void) { struct reactor *reactor = &g_reactor; int ret = 0; pthread_mutex_lock(&reactor->mutex); if (!reactor->state) { reactor->fd = epoll_create(1); if (reactor->fd == -1){ ERROR("epoll_create1 failed"); ret = -1; goto fail_epoll; } ret = pthread_create(&reactor->th, 0, reactor_thread, (void *)reactor); if (ret) { ERROR("pthread_create failed"); goto fail_pthread; } reactor->state = 1; } pthread_mutex_unlock(&reactor->mutex); return 0; fail_pthread: close(reactor->fd); reactor->fd = -1; fail_epoll: pthread_mutex_unlock(&reactor->mutex); return ret; } int reactor_stop(void) { struct reactor *reactor = &g_reactor; int ret = 0; pthread_mutex_lock(&reactor->mutex); if (reactor->state) { reactor->state = 0; pthread_cancel(reactor->th); pthread_join(reactor->th, 0); close(reactor->fd); reactor->fd = -1; } pthread_mutex_unlock(&reactor->mutex); return ret; } int reactor_event_register(int fd, struct reactor_event *ev) { struct reactor *reactor = &g_reactor; struct epoll_event e_ev; int ret = 0; e_ev.events = ev->events; e_ev.data.ptr = ev; if (!ev->func) { ERROR("ev->func is null"); return -1; } ret = reactor_start(); if (ret != 0){ ERROR("reactor_start failed"); return -1; } ret = epoll_ctl(reactor->fd, EPOLL_CTL_ADD, fd, &e_ev); if (ret == -1){ ERROR("epoll_ctl EPOLL_CTL_ADD failed"); return -1; } DEBUG("epoll_ctl EPOLL_CTL_ADD fd=%d,%d", reactor->fd, fd); return 0; } int reactor_event_unregister(int fd) { struct reactor *reactor = &g_reactor; int ret = 0; ret = epoll_ctl(reactor->fd, EPOLL_CTL_DEL, fd, 0); if (ret){ ERROR("epoll_ctl EPOLL_CTL_DEL failed"); return -1; } return 0; } int reactor_splice_event_callback(void *data, int fd, int events) { struct reactor_event *ctx = (struct reactor_event *) data; int ret; if (events & EPOLLOUT) { ret = splice(ctx->fdin, 0, ctx->fdout, 0, ctx->buf_size, SPLICE_F_MORE | SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (ret == -1) { ret = errno; ERROR("splice/write error ret=%d %s", ret, strerror(errno)); reactor_event_unregister(fd); return ret; } } else if (events & EPOLLIN) { ret = splice(ctx->fdin, 0, ctx->fdout, 0, ctx->buf_size, SPLICE_F_MORE | SPLICE_F_MOVE | SPLICE_F_NONBLOCK); } return 0; } int reactor_generic_event_callback(void *data, int fd, int events) { struct reactor_event *ctx = (struct reactor_event *) data; int ret; if (events & EPOLLOUT) { ret = read(ctx->fdin, ctx->buf, ctx->buf_size); if (ret == 0) { reactor_event_unregister(fd); return 0; } else if (ret == -1) { ret = errno; ERROR("read input file error %s", strerror(errno)); reactor_event_unregister(fd); return ret; } ret = write(ctx->fdout, ctx->buf, ret); if (ret == -1) { ret = errno; ERROR("splice/write error ret=%d %s", ret, strerror(errno)); reactor_event_unregister(fd); return ret; } } else if (events & EPOLLIN) { ret = read(ctx->fdin, ctx->buf, ctx->buf_size); if (ret < 0) { ret = errno; ERROR("read error %s", strerror(errno)); reactor_event_unregister(fd); return ret; } else if (ret == 0) { ERROR("read bytes=0"); return 0; } ret = write(ctx->fdout, ctx->buf, ret); if (ret == -1) { ret = errno; ERROR("write output file error %s", strerror(errno)); return ret; } } return 0; }
1
#include <pthread.h> struct wd_list wd_tempbans; int wd_check_ban(char *ip) { struct wd_list_node *node; struct wd_tempban *tempban; int result = 1; pthread_mutex_lock(&(wd_tempbans.mutex)); for(node = wd_tempbans.first; node != 0; node = node->next) { tempban = node->data; if(strcmp(ip, tempban->ip) == 0) { result = -1; break; } } pthread_mutex_unlock(&(wd_tempbans.mutex)); if(result > 0 && strlen(wd_settings.banlist) > 0) { FILE *fp; char buffer[1024], *p; fp = fopen(wd_settings.banlist, "r"); if(!fp) { wd_log(LOG_WARNING, "Could not open %s: %s", wd_settings.banlist, strerror(errno)); return 0; } while(fgets(buffer, sizeof(buffer), fp) != 0) { if((p = strchr(buffer, '\\n')) != 0) *p = '\\0'; continue; if(strchr(buffer, '*')) { if(wd_ip_wildcard(buffer, ip)) { result = -1; break; } } else if(strchr(buffer, '/')) { if(wd_ip_netmask(buffer, ip)) { result = -1; break; } } else { if(strcmp(ip, buffer) == 0) { result = -1; break; } } } fclose(fp); } return result; } void wd_update_tempbans(void) { struct wd_list_node *node; struct wd_tempban *tempban; pthread_mutex_lock(&(wd_tempbans.mutex)); for(node = wd_tempbans.first; node != 0; node = node->next) { tempban = node->data; if(tempban->time + wd_settings.bantime < (unsigned int) time(0)) { wd_list_delete(&wd_tempbans, node); free(tempban); } } pthread_mutex_unlock(&(wd_tempbans.mutex)); } int wd_ip_wildcard(char *match, char *test) { char *ip, *o, *m, *t; int result = 0; o = ip = strdup(test); while((m = strsep(&match, ".")) && (t = strsep(&ip, "."))) { if(strcmp(m, t) == 0 || strcmp(m, "*") == 0) result++; } free(o); return result == 4 ? 1 : 0; } int wd_ip_netmask(char *match, char *test) { char *p, *netmask; unsigned int ip_u = 0, netmask_u = 0, test_u = 0; unsigned int bits; p = strchr(match, '/'); netmask = p + 1; *p = '\\0'; ip_u = wd_iptou(match); test_u = wd_iptou(test); if(strchr(netmask, '.')) { netmask_u = wd_iptou(netmask); } else { bits = strtoul(netmask, 0, 10); netmask_u = ((unsigned int) pow(2, bits) - 1) << (32 - bits); } return (ip_u & netmask_u) == (test_u & netmask_u); } unsigned int wd_iptou(char *ip) { char *ap, *o, *p; int i = 3, out = 0; o = p = strdup(ip); while((ap = strsep(&p, "."))) out += strtoul(ap, 0, 10) * (unsigned int) pow(256, i--); free(o); return out; }
0
#include <pthread.h> int64_t size; struct nu_free_cell* next; } nu_free_cell; static const int64_t CHUNK_SIZE = 65536; static const int64_t CELL_SIZE = (int64_t)sizeof(nu_free_cell); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static nu_free_cell* nu_bins[8]; void* opt_realloc(void* item, int64_t size) { void* result = (void*) opt_malloc(size + sizeof(int64_t)); pthread_mutex_lock(&mutex); int64_t* original_size_ptr = (item - sizeof(int64_t)); int64_t original_size = *original_size_ptr; memcpy(result, item, original_size - sizeof(int64_t)); pthread_mutex_unlock(&mutex); opt_free(item); return result; } int64_t nu_free_list_length() { int len = 0; for (int ii = 0; ii < 8; ++ii) { for (nu_free_cell* pp = nu_bins[ii]; pp != 0; pp = pp->next) { len++; } } return len; } void nu_print_free_list() { for (int ii = 0; ii < 8; ++ii) { nu_free_cell* pp = nu_bins[ii]; for (; pp != 0; pp = pp->next) { printf("%lx: (cell %ld %lx)\\n", (int64_t) pp, pp->size, (int64_t) pp->next); } } } static void nu_free_list_insert(nu_free_cell* cell, int64_t bin) { cell->next = nu_bins[bin]; nu_bins[bin] = cell; return; } int64_t choose_bin(int64_t size) { int64_t n = 32; int64_t bin = 0; while(n != size) { n *= 2; ++bin; } return bin; } static nu_free_cell* free_list_get_cell(int64_t bin) { if (!nu_bins[bin]) { return 0; } nu_free_cell* result = nu_bins[bin]; nu_bins[bin] = result->next; return result; } void split_cells(int64_t bin) { if (bin == 7) { allocate_more_bins(); return; } if (nu_bins[bin+1] == 0) { split_cells(bin+1); } nu_free_cell* cell = free_list_get_cell(bin+1); cell->size = (cell->size / 2); nu_free_cell* cell2 = (nu_free_cell*) ((size_t) cell + cell->size); cell2->size = cell->size; nu_free_list_insert(cell, bin); nu_free_list_insert(cell2, bin); return; } void allocate_more_bins() { nu_free_cell* new_alloc = mmap(0, CHUNK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); int64_t limit = CHUNK_SIZE / 4096; for (int64_t ii = 0; ii < limit; ++ii) { nu_free_cell* cell = (nu_free_cell*) ((size_t) new_alloc + (ii * 4096)); cell->size = 4096; nu_free_list_insert(cell, 7); } return; } int64_t round_to_nearest_power_of_two(int64_t num) { int64_t ii = 32; while (ii < num) { ii = ii * 2; } return ii; } void* opt_malloc(size_t usize) { int64_t size = (int64_t) usize; int64_t alloc_size = size + sizeof(int64_t); if (alloc_size < CELL_SIZE) { alloc_size = CELL_SIZE; } if (alloc_size > 4096) { void* addr = mmap(0, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); *((int64_t*)addr) = alloc_size; pthread_mutex_unlock(&mutex); return addr + sizeof(int64_t); } alloc_size = round_to_nearest_power_of_two(alloc_size); int64_t bin = choose_bin(alloc_size); pthread_mutex_lock(&mutex); nu_free_cell* cell = free_list_get_cell(bin); while (!cell) { split_cells(bin); cell = free_list_get_cell(bin); } pthread_mutex_unlock(&mutex); *((int64_t*)cell) = alloc_size; return ((void*)cell) + sizeof(int64_t); } void opt_free(void* addr) { nu_free_cell* cell = (nu_free_cell*)(addr - sizeof(int64_t)); int64_t size = cell->size; size = round_to_nearest_power_of_two(size); if (size > 4096) { munmap((void*) cell, size); } else { cell->size = size; int64_t bin = choose_bin(size); pthread_mutex_lock(&mutex); nu_free_list_insert(cell, bin); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> int x = 0; int y = 0; int z = 0; int v = 0; int c = 0; pthread_mutex_t mc; pthread_mutex_t mx; pthread_mutex_t my; pthread_mutex_t mz; pthread_mutex_t mut[12]; int tab[12]; int main1(); int main2(); void *thread1 (void *arg) { unsigned id = (unsigned long) arg; pthread_mutex_lock (mut + id); tab[id] = 123; pthread_mutex_unlock (mut + id); return 0; } void *thread_rz (void *arg) { int l, i; pthread_mutex_lock (&mz); l = z; pthread_mutex_unlock (&mz); if (l == 1 && 12 > 0) { pthread_mutex_lock (&mc); i = c; pthread_mutex_unlock (&mc); pthread_mutex_lock (mut + i); tab[i] = 8899; pthread_mutex_unlock (mut + i); } else { main2 (); } return 0; } void *thread_wc (void *arg) { int i; pthread_mutex_lock (&mz); z = 1; pthread_mutex_unlock (&mz); for (i = 1; i < 12; i++) { pthread_mutex_lock (&mc); c = i; pthread_mutex_unlock (&mc); } return 0; } int main1 () { pthread_t t[12]; pthread_t t2; pthread_t t3; int i, ret; pthread_mutex_init (&mz, 0); pthread_mutex_init (&mc, 0); for (i = 0; i < 12; i++) { pthread_mutex_init (mut + i, 0); ret = pthread_create (&t[i], 0, thread1, (void*) (long) i); assert (ret == 0); } ret = pthread_create (&t3, 0, thread_wc, 0); assert (ret == 0); ret =pthread_create (&t2, 0, thread_rz, 0); assert (ret == 0); for (i = 0; i < 12; i++) { pthread_join (t[i], 0); } pthread_join (t2, 0); pthread_join (t3, 0); return 0; } void *thread2 (void *arg) { int i; for (i = 0; i < 2; i++) { pthread_mutex_lock (&mx); x = 10; pthread_mutex_unlock (&mx); } return 0; } int main2 () { int i, ret; pthread_t t; pthread_mutex_init (&mx, 0); ret = pthread_create (&t, 0, thread2, 0); assert (ret == 0); for (i = 0; i < 2; i++) { pthread_mutex_lock (&mx); x = 20; pthread_mutex_unlock (&mx); } ret = pthread_join (t, 0); assert (ret == 0); return 0; } int main () { main1 (); return 0; }
0
#include <pthread.h> int available_wait_seats = 6; sem_t barberSem; sem_t customerSem; pthread_mutex_t wait_seats; void *get_hair_cut(void* arg){ int id = *((int *)arg); while(1){ pthread_mutex_lock(&wait_seats); if(available_wait_seats > 0){ usleep(500000); printf("customer %d is entering barbershop\\n", id); available_wait_seats--; sem_post(&customerSem); pthread_mutex_unlock(&wait_seats); usleep(200000); sem_wait(&barberSem); printf("customer %d's hair\\n", id); usleep(100000); printf("customer %d haircut is finished and leaving now.\\n", id); usleep(900000); } else{ pthread_mutex_unlock(&wait_seats); printf("customer %d leaving because waiting room is full\\n", id); usleep(900000); } } } void *cut_hair(void* arg){ while(1){ if(available_wait_seats <= 6){ sem_wait(&customerSem); pthread_mutex_lock(&wait_seats); available_wait_seats++; sem_post(&barberSem); printf("barber is cutting --\\n"); pthread_mutex_unlock(&wait_seats); usleep(500000); } else{ printf("barber is sleeping\\n"); } } } int main(){ int ids[20]; pthread_t barberThread; pthread_t customerThreads[20]; pthread_mutex_init(&wait_seats, 0); sem_init(&barberSem, 0, 0); sem_init(&customerSem, 0, 0); pthread_create(&barberThread, 0, cut_hair, 0); int i; for(i = 0; i < 20; i++){ ids[i] = i; pthread_create(&customerThreads[i], 0, get_hair_cut, &ids[i]); } for(i = 0; i < 20; i++){ pthread_join(customerThreads[i], 0); } return 0; }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char * getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return(0); } pthread_setspecific(key, envbuf); } len = strlen(name); for ( i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len+1], 4096 - 1); pthread_mutex_unlock(&env_mutex); return(envbuf); } } pthread_mutex_unlock(&env_mutex); return(0); }
0