text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int searchPosition(int i); void * find(void *pat); char *pattern; char text[1000000]; int textLength = 1000000; int patternLength; int whichThread = 0; int offset = 1000000/10; int result = -1; pthread_mutex_t lock; int main(int argc, char *argv[]) { char* pattern = argv[1]; patternLength = strlen(pattern); int count = 0; while (count < 1000000) { int status = scanf("%c", &text[count]); count++; if (status == EOF) { textLength = count; break; } } pthread_mutex_init(&lock,0); pthread_t tid[10]; for(int i=0;i<10;i++){ whichThread = i; pthread_create(&tid[i],0,find,pattern); if (result !=-1){ break; } } if (result==-1){ printf("Pattern not found\\n"); } else{ printf("\\nPattern begins at character %d\\n", result); } } int searchPosition(int i) { int j; for (j=0;j<strlen(pattern); j++) if (text[i+j] != pattern[j]) return 0; return 1; } void * find(void * pat){ pthread_mutex_lock(&lock); int j = whichThread; for(int position= j*offset;position<=((j*offset)+offset);position++){ if(searchPosition(position)==1){ result = position; break; } } pthread_mutex_unlock(&lock); }
1
#include <pthread.h> pthread_mutex_t lockStat; pthread_cond_t condLock; int32_t shared=0; void* startFunction(void * msg) { int32_t data; pthread_attr_t currentAttr; printf("Child Thread Id:%ld\\n",pthread_self()); pthread_getattr_np(pthread_self(), &currentAttr); printf("Thread1 created\\n"); pthread_attr_getdetachstate(&currentAttr,&data); printf("Thread1 Detached State:%d\\n",data); pthread_attr_getschedpolicy(&currentAttr,&data); printf("Thread1 scheduling policy:%d\\n",data); pthread_attr_getscope(&currentAttr,&data); printf("Thread1 Scope:%d\\n",data); pthread_mutex_lock(&lockStat); shared+=20; printf("Thread1 Shared:%d\\n", shared); pthread_cond_signal(&condLock); pthread_mutex_unlock(&lockStat); pthread_attr_destroy(&currentAttr); pthread_exit(0); } void* secondFun(void* msg) { if(!pthread_mutex_trylock(&lockStat)) { pthread_cond_wait(&condLock, &lockStat); shared++; printf("Thread2 Sucesss Shared:%d\\n", shared); pthread_mutex_unlock(&lockStat); } else { printf("Thread2 Failed Shared:%d\\n", shared); } } int main() { uint16_t error,ret; int32_t data; pthread_t newId, thread2; pthread_attr_t newAttr; pthread_attr_t defaultAttr; pthread_mutex_init(&lockStat,0); pthread_cond_init(&condLock, 0); pthread_getattr_default_np(&defaultAttr); pthread_attr_getdetachstate(&defaultAttr,&data); printf("Default Detached State:%d\\n",data); pthread_attr_getschedpolicy(&defaultAttr,&data); printf("Default scheduling policy:%d\\n",data); error = pthread_attr_init(&newAttr); if(error != 0) { printf("Failed in pthread_attr_init\\n"); return -1; } printf("Parent Thread Id:%ld\\n",pthread_self()); pthread_attr_setdetachstate(&newAttr, PTHREAD_CREATE_JOINABLE); error = pthread_create(&newId, &newAttr, &startFunction, (void*)0); if(error != 0) { printf("Failed in pthread_create\\n"); return -1; } error = pthread_create(&thread2, 0, &secondFun, (void*)0); if(error != 0) { printf("Failed in pthread_create\\n"); return -1; } pthread_attr_destroy(&newAttr); pthread_attr_destroy(&defaultAttr); pthread_join(newId,(void*)&ret); pthread_mutex_destroy(&lockStat); pthread_cond_destroy(&condLock); exit(0); }
0
#include <pthread.h> int get_cpu_core_num() { return 4; } char input_end = 0; pthread_mutex_t input_m; pthread_mutex_t output_m; int get_stdin_input(char *file_name) { if (input_end == 1) return 0; if(fgets(file_name, 1024, stdin) == 0) { input_end = 1; return 0; } size_t n = strlen(file_name); if (n > 0) file_name[n-1] = '\\0'; return 1; } void *crc_fun(void *a) { char file_name[1024]; char buff[1024]; char rc; uint32_t crc = ~0U; int n; while(1) { pthread_mutex_lock(&input_m); rc = get_stdin_input(file_name); pthread_mutex_unlock(&input_m); if (rc == 0) return 0; FILE *fp; fp = fopen(file_name, "rb"); if (fp == 0) continue; while ((n = fread(buff, 1, 1024, fp)) > 0) { crc = crc32_raw(buff, n, crc); } fclose(fp); pthread_mutex_lock(&output_m); printf("%s: %x\\n", file_name, crc); pthread_mutex_unlock(&output_m); } return 0; } int main(void) { pthread_t th[16]; pthread_mutex_init(&input_m, 0); pthread_mutex_init(&output_m, 0); int cpu_num = get_cpu_core_num(); for (int i = 0; i < cpu_num; i++) pthread_create(th+i, 0, crc_fun, 0); void *status; for (int i = 0; i < cpu_num; i++) pthread_join(th[i], &status); return 0; }
1
#include <pthread.h> int *numbers = 0; pthread_cond_t queueEmpty ; pthread_mutex_t queueLock ; void * Slave_Start(void * s) { int id = (*(struct Data *) s).id ; ; int min = (*(struct Data *) s).min; int max = (*(struct Data *) s).max; int k = (*(struct Data *) s).k; int i; pthread_cond_t *noWork = (*(struct Data *) s).noWork; pthread_mutex_t *infoLock = (*(struct Data *) s).infoLock; while(1) { pthread_mutex_lock(&queueLock); Enqueue(id); pthread_mutex_unlock(&queueLock); pthread_cond_signal(&queueEmpty); pthread_mutex_lock(infoLock); pthread_cond_wait(noWork, infoLock); pthread_mutex_unlock(infoLock); min = (*(struct Data *) s).min; max = (*(struct Data *) s).max; k = (*(struct Data *) s).k; if ((min % k) != 0) min = min - (min % k) + k; for (i=min; i<=max; i=i+k) { numbers[i] = 1; } } } void init() { pthread_cond_init(&queueEmpty, 0); pthread_mutex_init(&queueLock, 0); } int main (int argc, char *argv []) { int n = atoi( argv[1] ); int numSlaves = atoi( argv[2] ); int c = atoi( argv[3] ); pthread_t thread; struct Data *threadInfo; int i, k, maxK, range, numChunks, mod, modH, id; threadInfo = (struct Data*)malloc(sizeof(struct Data)*numSlaves); numbers = malloc(sizeof(int)*(n + 1)); for (i=0; i<numSlaves; i++) { pthread_cond_t noWork; pthread_mutex_t infoLock; pthread_cond_init(&noWork, 0); pthread_mutex_init(&infoLock, 0); threadInfo[i].id = i; threadInfo[i].min = -1; threadInfo[i].noWork = &noWork; threadInfo[i].infoLock = &infoLock; if(pthread_create(&thread, 0, Slave_Start, &threadInfo[i])!=0) { perror("Student thread could not be created!\\n"); exit(0); } } sleep(3); maxK = floor(sqrt(n)); for (k=2; k <= maxK; k++) { if(numbers[k] == 1) continue; range = n - k + 1; numChunks = range / c; mod = 0; modH = 0; mod = range % (numChunks+1); for (i=0; i <= numChunks; i++) { pthread_mutex_lock(&queueLock); while (front == 0) pthread_cond_wait(&queueEmpty, &queueLock) ; id = front->data; Dequeue(); pthread_mutex_unlock(&queueLock); pthread_mutex_lock(threadInfo[id].infoLock); if (mod == 0 || i < mod) { threadInfo[id].min = (i * c) + 2; int er = (i*c)+2; threadInfo[id].max = (i * c) + 1 + c; } else { threadInfo[id].min = (i * c) + 2 - modH; threadInfo[id].max = (i * c) + c - modH; modH++; } threadInfo[id].k = k; pthread_mutex_unlock((threadInfo[id].infoLock)); pthread_cond_signal((threadInfo[id].noWork)); } } if (numbers[n] == 0) printf("Prime\\n"); else printf("Not Prime\\n"); }
0
#include <pthread.h> pthread_cond_t stable, workshop, santaSleeping, elfWaiting, santaWaitElf; pthread_mutex_t elfAndReindeerCount, elfwWaitingLock; int minWait, maxWait; int elfCount; int reindeerCount; int elfDoor; void *santaThread(void *args) { while(1) { santaHelper(); } } void santaHelper() { pthread_mutex_lock(&elfAndReindeerCount); printf("Santa is sleeping.\\n"); while(reindeerCount < 9 && elfCount < 3) { pthread_cond_wait(&santaSleeping, &elfAndReindeerCount); } printf("Santa is WOKE.\\n"); if (reindeerCount == 9) { printf("Reindeer harnessed.\\n"); printf("Begin delivering presents.\\n"); deliverPresents(); pthread_cond_broadcast(&stable); } if (elfCount == 3) { printf("Begin helping elves.\\n"); helpElves(); pthread_cond_broadcast(&workshop); if (elfCount == 3) { pthread_cond_wait(&santaWaitElf, &elfAndReindeerCount); } } pthread_mutex_unlock(&elfAndReindeerCount); } void helpElves() { int amount = ((rand() % (maxWait - minWait)) + minWait) * 1000; usleep(amount); printf("Elves helped.\\n"); } void deliverPresents() { int amount = ((rand() % (maxWait - minWait)) + minWait) * 1000; usleep(amount); printf("PRESEENTS DELIVERed\\n"); reindeerCount = 0; }
1
#include <pthread.h> struct cmd_que_item { struct cmd_que_item *next; int cmd_id; }; static struct cmd_que_item *cmd_que_tail = 0; static struct cmd_que_item *cmd_que_head = 0; static pthread_mutex_t cmd_que_mutex = PTHREAD_MUTEX_INITIALIZER; int wait_for_cmd(int cmd_id, double timeout) { int cmd = -1; BLTS_DEBUG("Waiting for command %s (0x%x)...\\n", nl80211_cmd_as_string(cmd_id), cmd_id); timing_start(); while (timing_elapsed() < timeout ) { cmd = first_cmd_from_queue(); BLTS_DEBUG("."); if(cmd < 0) usleep(100000); if (cmd) { if (cmd == cmd_id) { BLTS_DEBUG("Command received\\n"); timing_stop(); return 0; } } usleep(100000); } timing_stop(); BLTS_DEBUG("Command not received within %.3f seconds\\n", timeout); return -1; } int add_to_cmd_queue(int cmd) { struct cmd_que_item *item; int ret = 0; pthread_mutex_lock(&cmd_que_mutex); item = malloc(sizeof(struct cmd_que_item)); if (!item) { BLTS_LOGGED_PERROR("malloc"); ret = -errno; goto cleanup; } memset(item, 0, sizeof(*item)); item->cmd_id = cmd; if (cmd_que_tail) cmd_que_tail->next = item; else cmd_que_head = item; cmd_que_tail = item; cleanup: pthread_mutex_unlock(&cmd_que_mutex); return ret; } int first_cmd_from_queue() { int cmd = -1; struct cmd_que_item *item; pthread_mutex_lock(&cmd_que_mutex); if (!cmd_que_head ) goto cleanup; item = cmd_que_head; cmd = item->cmd_id; BLTS_DEBUG("\\nCOMMAND: %s\\n", nl80211_cmd_as_string(cmd)); if (item->next) cmd_que_head = item->next; else cmd_que_head = cmd_que_tail = 0; free(item); cleanup: pthread_mutex_unlock(&cmd_que_mutex); return cmd; } void clear_cmd_queue() { BLTS_DEBUG("\\nclear_cmd_queue\\n"); struct cmd_que_item *item, *next; pthread_mutex_lock(&cmd_que_mutex); item = cmd_que_head; while (item) { next = item->next; free(item); item = next; } cmd_que_head = 0; cmd_que_tail = 0; pthread_mutex_unlock(&cmd_que_mutex); }
0
#include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void *threadMain(void *arg) { fprintf(stderr, "In second thread: starting\\n"); pthread_mutex_lock(&mtx); pthread_mutex_lock(&mtx); assert(0); } int main() { struct sigaction act; pthread_t thd; int i; for (i = 1; i < NSIG; i++) { sigaction(i, 0, &act); act.sa_flags |= SA_RESTART; sigaction(i, &act, 0); } pthread_create(&thd, 0, &threadMain, 0); fprintf(stderr, "In the main thread: Waiting for second thread to be ready\\n"); while (1) { sleep(1); if (0 == pthread_mutex_trylock(&mtx)) { pthread_mutex_unlock(&mtx); } else { break; } } sleep(3); fprintf(stderr, "In the main thread: Exiting\\n"); exit(0); }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for (i=0; i<100000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> void Deposit(int), BeginRegion(), EndRegion(); pthread_mutex_t mutex; main() { pthread_t idA, idB; void *MyThread(void *); if (pthread_mutex_init(&mutex, 0) < 0) { perror("pthread_mutex_init"); exit(1); } if (pthread_create(&idA, 0, MyThread, (void *)"A") != 0) { perror("pthread_create"); exit(1); } if (pthread_create(&idB, 0, MyThread, (void *)"B") != 0) { perror("pthread_create"); exit(1); } (void)pthread_join(idA, 0); (void)pthread_join(idB, 0); (void)pthread_mutex_destroy(&mutex); } int balance = 0; void *MyThread(void *arg) { char *sbName; sbName = (char *)arg; Deposit(10); printf("Balance = %d in Thread %s\\n", balance, sbName); } void Deposit(int deposit) { int newbalance; BeginRegion(); newbalance = balance + deposit; balance = newbalance; EndRegion(); } void BeginRegion() { pthread_mutex_lock(&mutex); } void EndRegion() { pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> int schedule[10] = {20, 20, 20, 20, 20, 20, 20, 20, 20, 20}; pthread_t threads[2]; pthread_mutex_t mutex; void printSchedule(){ printf("Schedule: "); for (int i = 0; i<10; i++){ printf("%d ", schedule[i]); } printf("\\n"); } void* updateFromWeb(){ time_t t; srand((unsigned) time(&t)); while(1){ pthread_mutex_lock (&mutex); sleep(2); schedule[rand() % 10] = (rand() % 100); pthread_mutex_unlock (&mutex); sleep(1); } } void* commandLine(){ char buffer[100]; char command[20]; int time; int temperature; while(1){ printf("Command Line: "); fgets(buffer, 100, stdin); sscanf(buffer, "%s %d %d", command, &time, &temperature); if (strcmp(command, "setTemp") == 0){ pthread_mutex_lock (&mutex); schedule[time-1] = temperature; pthread_mutex_unlock (&mutex); } printSchedule(); } } int main(int argc, char *argv[]){ printSchedule(); pthread_mutex_init(&mutex, 0); pthread_create(&threads[0], 0, commandLine, 0); pthread_create(&threads[1], 0, updateFromWeb, 0); pthread_exit(0); return 0; }
0
#include <pthread.h> static void *cygfuse_init_slow(int force); static void *cygfuse_init_winfsp(); static pthread_mutex_t cygfuse_mutex = PTHREAD_MUTEX_INITIALIZER; static void *cygfuse_handle = 0; static inline void *cygfuse_init_fast(void) { void *handle = cygfuse_handle; __sync_synchronize(); if (0 == handle) handle = cygfuse_init_slow(0); return handle; } static void *cygfuse_init_slow(int force) { void *handle; pthread_mutex_lock(&cygfuse_mutex); handle = cygfuse_handle; if (force || 0 == handle) { handle = cygfuse_init_winfsp(); __sync_synchronize(); cygfuse_handle = handle; } pthread_mutex_unlock(&cygfuse_mutex); return handle; } static inline int cygfuse_daemon(int nochdir, int noclose) { if (-1 == daemon(nochdir, noclose)) return -1; cygfuse_init_slow(1); return 0; } static void *cygfuse_init_fail(); static void *cygfuse_init_winfsp() { void *h; h = dlopen("winfsp-x64.dll", RTLD_NOW); if (0 == h) { char winpath[260], *psxpath; int regfd, bytes; regfd = open("/proc/registry32/HKEY_LOCAL_MACHINE/Software/WinFsp/InstallDir", O_RDONLY); if (-1 == regfd) return cygfuse_init_fail(); bytes = read(regfd, winpath, sizeof winpath - sizeof "bin\\\\" "winfsp-x64.dll"); close(regfd); if (-1 == bytes || 0 == bytes) return cygfuse_init_fail(); if ('\\0' == winpath[bytes - 1]) bytes--; memcpy(winpath + bytes, "bin\\\\" "winfsp-x64.dll", sizeof "bin\\\\" "winfsp-x64.dll"); psxpath = (char *)cygwin_create_path(CCP_WIN_A_TO_POSIX | CCP_PROC_CYGDRIVE, winpath); if (0 == psxpath) return cygfuse_init_fail(); h = dlopen(psxpath, RTLD_NOW); free(psxpath); if (0 == h) return cygfuse_init_fail(); } if (0 == (*(void **)&(pfn_fsp_fuse_signal_handler) = dlsym(h, "fsp_fuse_signal_handler"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_version) = dlsym(h, "fsp_fuse_version"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_mount) = dlsym(h, "fsp_fuse_mount"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_unmount) = dlsym(h, "fsp_fuse_unmount"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_parse_cmdline) = dlsym(h, "fsp_fuse_parse_cmdline"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_ntstatus_from_errno) = dlsym(h, "fsp_fuse_ntstatus_from_errno"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_main_real) = dlsym(h, "fsp_fuse_main_real"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_is_lib_option) = dlsym(h, "fsp_fuse_is_lib_option"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_new) = dlsym(h, "fsp_fuse_new"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_destroy) = dlsym(h, "fsp_fuse_destroy"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_loop) = dlsym(h, "fsp_fuse_loop"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_loop_mt) = dlsym(h, "fsp_fuse_loop_mt"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_exit) = dlsym(h, "fsp_fuse_exit"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_exited) = dlsym(h, "fsp_fuse_exited"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_get_context) = dlsym(h, "fsp_fuse_get_context"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_parse) = dlsym(h, "fsp_fuse_opt_parse"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_add_arg) = dlsym(h, "fsp_fuse_opt_add_arg"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_insert_arg) = dlsym(h, "fsp_fuse_opt_insert_arg"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_free_args) = dlsym(h, "fsp_fuse_opt_free_args"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_add_opt) = dlsym(h, "fsp_fuse_opt_add_opt"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_add_opt_escaped) = dlsym(h, "fsp_fuse_opt_add_opt_escaped"))) return cygfuse_init_fail();; if (0 == (*(void **)&(pfn_fsp_fuse_opt_match) = dlsym(h, "fsp_fuse_opt_match"))) return cygfuse_init_fail();; return h; } static void *cygfuse_init_fail() { fprintf(stderr, "cygfuse: initialization failed: " "winfsp-x64.dll" " not found\\n"); exit(1); return 0; }
1
#include <pthread.h> int num_of_students; int dean_status; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait_for_full_room, wait_for_students_to_leave; void* dean_code(void*); void* students_code(void*); int main(void) { pthread_t dean, students; num_of_students = 0; dean_status = -1; pthread_mutex_init(&mutex, 0); pthread_cond_init(&wait_for_full_room, 0); pthread_cond_init(&wait_for_students_to_leave, 0); pthread_create(&students, 0, students_code, 0); pthread_create(&dean, 0, dean_code, 0); pthread_join(dean, 0); pthread_join(students, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&wait_for_students_to_leave); pthread_cond_destroy(&wait_for_full_room); return 0; } void* dean_code(void* param) { pthread_mutex_lock(&mutex); if (num_of_students > 0 && num_of_students < 50) { dean_status = 0; printf("Dean is waiting\\n"); pthread_cond_wait(&wait_for_full_room, &mutex); } if (num_of_students >= 50) { dean_status = 1; printf("Dean breaks the party\\n"); pthread_cond_wait(&wait_for_students_to_leave, &mutex); } else { dean_status = 1; printf("Dean is searching the room\\n"); } dean_status = 2; printf("Dean left\\n"); pthread_mutex_unlock(&mutex); } void* students_code(void* param) { while(1) { pthread_mutex_lock(&mutex); if (dean_status == 1) { if (num_of_students > 0) { printf("Students are leaving: %d\\n", num_of_students); num_of_students--; } else { pthread_cond_signal(&wait_for_students_to_leave); pthread_mutex_unlock(&mutex); break; } } else { if (num_of_students < 50) { num_of_students++; printf("Students are partying: %d\\n", num_of_students); } if (dean_status == 0 && num_of_students >= 50) { pthread_cond_signal(&wait_for_full_room); } if (dean_status == 2 && num_of_students >= 50) break; } pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> struct account{ float balance; char name[32]; pthread_mutex_t mutex; }; int withdraw (struct account *account, int amount) { printf("%u\\t%s\\t%f\\t%d\\n", pthread_self(), account->name, account->balance, amount); pthread_mutex_lock (&account->mutex); const int balance = account->balance; if(balance < amount ) { pthread_mutex_unlock(&account->mutex); return -1; } account->balance = balance - amount; pthread_mutex_unlock (&account->mutex); printf("cash out $%d\\n", amount); return 0; } void *start_thread (void *pass_data) { struct account *customer = (struct account *) pass_data; const pthread_t me = pthread_self(); printf("%u\\t%s\\t%f\\n", me, customer->name, customer->balance); int rc = withdraw (customer, 800); if(rc){ fprintf(stderr, "can't withdraw $%d because the existent amount is $%f\\n", 800, customer->balance); } return pass_data; } int main(int argc, char *argv[]) { pthread_t thread1, thread2; struct account *customer = (struct account *) malloc (sizeof(struct account)); if (customer == 0 ){ perror("malloc failed!!"); return 1; } customer->balance=1000; memset(customer->name, 0, 32); strcpy(customer->name, "Eric"); pthread_create (&thread1, 0, start_thread, (void *) customer); pthread_create (&thread2, 0, start_thread, (void *) customer); pthread_join (thread1, 0); pthread_join (thread2, 0); free(customer); return 0; }
1
#include <pthread.h> int task_queue_pointer = -1,complete_flag = 0, complete[28] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, task_queue[28]; int dependency[28][28]={{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0,0,0,0}}; double temp_var = 1234; pthread_mutex_t dependency_array_lock,complete_array_lock,task_queue_array_lock, complete_flag_lock, task_queue_pointer_lock; void *master_thread_run(void *unused) { int tasks_complete = 0; while(tasks_complete == 0) { tasks_complete = 1; for (int i = 0; i < 28; ++i) { int row_flag = 1; for (int j = 0; j < 28; ++j) { if (dependency[i][j] == 1) { row_flag = 0; tasks_complete = 0; } } if (row_flag == 1 && complete[i] == 0) { pthread_mutex_lock(&complete_array_lock); complete[i] = 1; pthread_mutex_unlock(&complete_array_lock); pthread_mutex_lock(&task_queue_array_lock); task_queue[++task_queue_pointer] = i; pthread_mutex_unlock(&task_queue_array_lock); } } } int over = 1; for (int i = 0; i < 28; ++i) { if (complete[i] == 0) { over = 0; } } if (over == 1) { pthread_mutex_lock(&complete_flag_lock); complete_flag == 1; pthread_mutex_unlock(&complete_flag_lock); } } void *child_thread_run(void *unused) { int j; while(complete_flag == 0) { if (task_queue_pointer != 999) { pthread_mutex_lock(&task_queue_array_lock); pthread_mutex_lock(&task_queue_pointer_lock); j = task_queue[task_queue_pointer--]; pthread_mutex_unlock(&task_queue_pointer_lock); pthread_mutex_unlock(&task_queue_array_lock); if (14 <= j <= 20) { for (int Intensity = 0; Intensity < 500000; ++Intensity) { temp_var = temp_var * temp_var; temp_var = sqrt(temp_var); } } else { for (int Intensity = 0; Intensity < 100000; ++Intensity) { temp_var = temp_var * temp_var; temp_var = sqrt(temp_var); } } for (int i = 0; i < 28; ++i) { if (dependency[i][j] == 1) { pthread_mutex_lock(&dependency_array_lock); dependency[i][j] = 0; pthread_mutex_unlock(&dependency_array_lock); } } } } } int main(int argc, char const *argv[]) { pthread_t master_thread, child_thread[atoi(argv[1])]; clock_t begin = clock(); pthread_create(&master_thread, 0, master_thread_run, 0); for (int i = 0; i < atoi(argv[1]); ++i) { pthread_create(&child_thread[i], 0, child_thread_run, 0); } for (int i = 0; i < atoi(argv[1]); ++i) { pthread_join(child_thread[i], 0); } clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("\\n Time taken on %d threads is: %f", atoi(argv[1]), time_spent); }
0
#include <pthread.h> pthread_cond_t condition = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* threadAlarme (void* arg); void* threadCompteur (void* arg); int main (void) { pthread_t monThreadCompteur; pthread_t monThreadAlarme; pthread_create (&monThreadCompteur, 0, threadCompteur, (void*)0); pthread_create (&monThreadAlarme, 0, threadAlarme, (void*)0); pthread_join (monThreadCompteur, 0); pthread_join (monThreadAlarme, 0); return 0; } void* threadCompteur (void* arg) { int compteur = 0, nombre = 0; srand(time(0)); while(1) { nombre = rand()%10; compteur += nombre; printf("\\n%d", compteur); if(compteur >= 20) { pthread_mutex_lock (&mutex); pthread_cond_signal (&condition); pthread_mutex_unlock (&mutex); compteur = 0; } sleep (1); } pthread_exit(0); } void* threadAlarme (void* arg) { while(1) { pthread_mutex_lock(&mutex); pthread_cond_wait (&condition, &mutex); printf("\\nLE COMPTEUR A DÉPASSÉ 20."); pthread_mutex_unlock(&mutex); } pthread_exit(0); }
1
#include <pthread.h> struct job { struct job* next; int value; }; struct job* job_queue; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; sem_t job_queue_count; void initialize_job_queue () { job_queue = 0; sem_init (&job_queue_count, 0, 0); } void process_job(struct job* job) { printf("now thread: %d finish the job: %d\\n", (int)pthread_self(), job->value); } void* thread_function (void* arg) { printf("Thread %d start...\\n", (int) pthread_self()); while (1) { struct job* next_job; sem_wait (&job_queue_count); pthread_mutex_lock (&job_queue_mutex); next_job = job_queue; job_queue = job_queue->next; pthread_mutex_unlock (&job_queue_mutex); process_job (next_job); free (next_job); } return 0; } void enqueue_job (struct job* new_job, int value) { new_job = (struct job*) malloc (sizeof (struct job)); new_job->value = value; pthread_mutex_lock (&job_queue_mutex); new_job->next = job_queue; job_queue = new_job; sem_post (&job_queue_count); pthread_mutex_unlock (&job_queue_mutex); } int main() { int job_size = 1000; int thread_num = 5; int i; pthread_t thread_id[thread_num]; for (i = 0; i < thread_num; i++) pthread_create(&thread_id[i], 0, &thread_function, 0); struct job* jobs; for (i = 1; i < job_size; i++) { enqueue_job(jobs, i); } for (i = 0; i < thread_num; i++) pthread_join(thread_id[i], 0); return 0; }
0
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tap) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec > now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) { printf("pthread_mutextattr_init failed\\n"); exit(1); } if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) { printf("can't set recusive type\\n"); exit(1); } if ((err = pthread_mutex_init(&mutex, &attr)) != 0) { printf("can't create recursive mutext\\n"); exit(1); } pthread_mutex_lock(&mutex); if (condition) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> int DEBUG; int *array; int left; int right; int tid; } thread_data_t; int number_of_threads; pthread_mutex_t lock_number_of_threads; int my_comp(const void *larg, const void *rarg) { int l = *(int *)larg; int r = *(int *)rarg; if (l < r) { return -1; } else if (l == r) { return 0; } return 1; } void merge(int *data, int left, int right, int tid) { if (DEBUG) { printf("[%d] Merging %d to %d\\n", tid, left, right); } int ctr = 0; int i = left; int mid = left + ((right - left) / 2); int j = mid + 1; int *c = (int *) malloc((right - left + 1) * sizeof(int)); while (i <= mid && j <= right) { if (data[i] <= data[j]) { c[ctr++] = data[i++]; } else { c[ctr++] = data[j++]; } } if (i == mid + 1) { while (j <= right) { c[ctr++] = data[j++]; } } else { while (i <= mid) { c[ctr++] = data[i++]; } } i = left; ctr = 0; while (i <= right) { data[i++] = c[ctr++]; } free(c); return; } void *merge_sort_threaded(void *arg) { thread_data_t *data = (thread_data_t *) arg; int l = data->left; int r = data->right; int t = data->tid; if (r - l + 1 <= 4) { if (DEBUG) { printf("[%d] Calling qsort(%d, %d).\\n", t, l, r); } qsort(data->array + l, r - l + 1, sizeof(int), my_comp); } else { int m = l + ((r - l) / 2); thread_data_t data_0; data_0.left = l; data_0.right = m; data_0.array = data->array; pthread_mutex_lock(&lock_number_of_threads); data_0.tid = number_of_threads++; pthread_mutex_unlock(&lock_number_of_threads); pthread_t thread0; int rc = pthread_create(&thread0, 0, merge_sort_threaded, &data_0); int created_thread_0 = 1; if (rc) { if (DEBUG) { printf("[%d] Failed to create thread, calling qsort.", data_0.tid); } created_thread_0 = 0; qsort(data->array + l, m - l + 1, sizeof(int), my_comp); } thread_data_t data_1; data_1.left = m + 1; data_1.right = r; data_1.array = data->array; pthread_mutex_lock(&lock_number_of_threads); data_1.tid = number_of_threads++; pthread_mutex_unlock(&lock_number_of_threads); pthread_t thread1; rc = pthread_create(&thread1, 0, merge_sort_threaded, &data_1); int created_thread_1 = 1; if (rc) { if (DEBUG) { printf("[%d] Failed to create thread, calling qsort.", data_1.tid); } created_thread_1 = 0; qsort(data->array + m + 1, r - m, sizeof(int), my_comp); } if (created_thread_0) { pthread_join(thread0, 0); } if (created_thread_1) { pthread_join(thread1, 0); } merge(data->array, l, r, t); } pthread_exit(0); return 0; } void merge_sort(int *array, int start, int finish) { thread_data_t data; data.array = array; data.left = start; data.right = finish; number_of_threads = 0; pthread_mutex_init(&lock_number_of_threads, 0); data.tid = 0; pthread_t thread; int rc = pthread_create(&thread, 0, merge_sort_threaded, &data); if (rc) { if (DEBUG) { printf("[%d] Failed to create thread, calling qsort.", data.tid); } qsort(array + start, finish - start + 1, sizeof(int), my_comp); } pthread_join(thread, 0); return; } int *random_array(int n) { int *rand_arr = (int *)malloc(n * sizeof(int)); if (rand_arr) { int i = 0; for (i = 0; i < n; ) { rand_arr[i++] = rand(); } } return rand_arr; } int main(int argc, char **argv) { if (argc < 2) { printf("Usage: ./a.out random_array_length [want_debug_output]\\n"); printf("./a.out 2000 0 -- A 2000 random initialized array and no debug output.\\n"); return 0; } DEBUG = 1; if (argc == 3) { DEBUG = atoi(argv[2]); } int n = atoi(argv[1]); int *p = random_array(n); if (!p) { return 1; } merge_sort(p, 0, n - 1); printf("After MergeSort.\\n"); int i = 0; for (i = 0; i < n; ++i) { printf("Num: %10d\\n", p[i]); } free(p); pthread_mutex_destroy(&lock_number_of_threads); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int aux = 1; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; void* threadLockTest(void* arg) { printf("Child wants to take the mutex\\n"); pthread_mutex_lock(&mutex); printf("Child took the mutex\\n"); sleep(7); if(aux == 1) { printf("Child before wait\\n"); pthread_cond_wait(&condition, &mutex); printf("Child after wait\\n"); } sleep(5); pthread_mutex_unlock(&mutex); printf("Child left the mutex\\n"); } int main() { pthread_t threadID; pthread_create(&threadID, 0, threadLockTest, 0); sleep(5); printf("Main wants to take the mutex\\n"); pthread_mutex_lock(&mutex); printf("Main took the mutex\\n"); if(aux == 1) { printf("Main before signal\\n"); pthread_cond_signal(&condition); printf("Main after signal\\n"); } sleep(5); pthread_mutex_unlock(&mutex); printf("Main left the mutex\\n"); pthread_join(threadID, 0); return 0; }
1
#include <pthread.h> pthread_t * ids; int fl; bool threadFlag = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int iloscRekordow; int iloscWatkow; void * threadFunc(void *); void atexitFunc(); struct rekord{ int id; char * txt; }; int main(int argc, char const *argv[]) { atexit(atexitFunc); if (argc != 5) { printf("Niepoprawna ilosc argumentow\\n"); exit(-1); } iloscWatkow = atoi(argv[1]); iloscRekordow = atoi(argv[3]); char slowo[strlen(argv[4])]; strcpy(slowo, argv[4]); ids = malloc(sizeof(pthread_t)*iloscWatkow); fl = open(argv[2],O_RDONLY); if(fl == -1){ printf("Blad otwierania pliku\\n%s\\n",strerror(errno)); exit(-1); } int c; for(int i=0; i<iloscWatkow; i++){ c = pthread_create(ids+i,0,threadFunc,slowo); if(c!=0){ printf("Blad podczas tworzenia watku nr %d\\n%s\\n",i,strerror(c)); exit(-1); } } threadFlag = 1; for(int i=0; i<iloscWatkow; i++){ c = pthread_join(ids[i],0); if(c!=0){ printf("Blad podczas joinowania watku nr %d\\n%s\\n",i,strerror(c)); exit(-1); } } return 0; } void * threadFunc(void * slowo){ int czytaj = 1; struct rekord bufor[iloscRekordow]; int c; c = pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); if(c!=0) { printf("Blad podczas ustawiania typu\\n%s\\n",strerror(c)); exit(-1); } while(!threadFlag); char *tmp = malloc(sizeof(char)*1024); char *strtmp = malloc(sizeof(char)*1024); char *nmb = malloc(sizeof(char)*3); int j; int k; while(czytaj>0) { pthread_mutex_lock(&mutex); for (int i = 0; i<iloscRekordow; i++) { j = 0; czytaj = read(fl,tmp,1024 +1); if(czytaj == -1){ printf("Blad podczas czytania z pliku\\n%s\\n",strerror(errno)); exit(-1); } while((int)tmp[j]!=32) { nmb[j] = tmp[j]; j++; } bufor[i].id = atoi(nmb); bufor[i].txt = malloc(sizeof(char)*(1024)); j++; k = 0; while((int)tmp[j]!=0){ strtmp[k] = tmp[j]; j++; k++; } j++; strcpy(bufor[i].txt,strtmp); } pthread_mutex_unlock(&mutex); char * szukacz; for(int i=0; i<iloscRekordow; i++) { szukacz = strstr(bufor[i].txt,slowo); if (szukacz != 0){ for (int l = 0; l < iloscWatkow; l++) { if(ids[l]!=pthread_self()){ pthread_cancel(ids[l]); } } printf("Watek o TID: %lu Znalazl slowo w rekordzie o identyfikatorze %d\\n",(unsigned long)pthread_self(),bufor[i].id); exit(1); } } } return 0; } void atexitFunc(){ free(ids); close(fl); }
0
#include <pthread.h> static int set_priority(int priority); static int get_priority(void); pthread_mutex_t pid_mutex; pid_t pid; } pid_data; int main(int argc, char *argv[]) { printf("Server started \\n"); int file_descriptor; file_descriptor = shm_open("/sharedpid", O_RDWR | O_CREAT, S_IRWXU); ftruncate(file_descriptor, sizeof(pid_data)); void* shared_memory; shared_memory = mmap(0, sizeof(pid_data), PROT_READ | PROT_WRITE, MAP_SHARED, file_descriptor, 0); pid_data data; data.pid = getpid(); pthread_mutex_t lock = ((pid_data*)shared_memory)->pid_mutex; pthread_mutexattr_t myattr; pthread_mutexattr_init(&myattr); pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&lock, &myattr ); pthread_mutex_lock(&lock); *((pid_data*)shared_memory) = data; pthread_mutex_unlock(&lock); printf("Pid stored in shared memory \\n"); int ch_id = ChannelCreate(0); printf("Channel %d created \\n", ch_id); int rcv_id; int buffer_recv; int buffer_resp; struct _msg_info msg_info; set_priority(25); printf("Server listening... \\n"); while(1){ printf("Server priority: %d\\n", get_priority()); rcv_id = MsgReceive(ch_id, &buffer_recv, sizeof(buffer_recv), &msg_info); buffer_resp = buffer_recv + 1; printf("Received: %d, Responding: %d \\n", buffer_recv, buffer_resp); if(MsgReply(rcv_id, EOK, &buffer_resp, sizeof(buffer_resp)) != EOK){ printf("ERROR: failed to reply to message: %d \\n", buffer_recv); } } return 0; } static int set_priority(int priority){ int policy; struct sched_param param; if (priority < 1 || priority > 63) return -1; pthread_getschedparam(pthread_self(), &policy, &param); param.sched_priority = priority; return pthread_setschedparam(pthread_self(), policy, &param); } static int get_priority(void){ int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, &param); return param.sched_curpriority; }
1
#include <pthread.h> static pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; static int count; void fast_task(void *ptr) { int *pval = (int*)ptr; int i; for (i = 0; i < 1000; i++) { (*pval)++; } pthread_mutex_lock(&count_mutex); count++; pthread_mutex_unlock(&count_mutex); } void slow_task(void *ptr) { printf("slow task: count value is %d.\\n",count); pthread_mutex_lock(&count_mutex); count++; pthread_mutex_unlock(&count_mutex); } int main(int argc, char **argv) { struct threadpool *pool; int arr[1000000], i, ret, failed_count = 0; for (i = 0; i < 1000000; i++) { arr[i] = i; } if ((pool = threadpool_init(10)) == 0) { printf("Error! Failed to create a thread pool struct.\\n"); exit(1); } for (i = 0; i < 1000000; i++) { if (i % 10000 == 0) { ret = threadpool_add_task(pool,slow_task,arr + i,1); } else { ret = threadpool_add_task(pool,fast_task,arr + i,0); } if (ret == -1) { printf("An error had occurred while adding a task."); exit(1); } if (ret == -2) { failed_count++; } } threadpool_free(pool,1); printf("Example ended.\\n"); printf("%d tasks out of %d have been executed.\\n",count,1000000); printf("%d tasks out of %d did not execute since the pool was overloaded.\\n",failed_count,1000000); printf("All other tasks had not executed yet."); return 0; }
0
#include <pthread.h> static bool baro_swing_available; static int32_t baro_swing_raw; static pthread_mutex_t baro_swing_mutex = PTHREAD_MUTEX_INITIALIZER; static void *baro_read(void *data ) { struct input_event ev; ssize_t n; int fd_sonar = open("/dev/input/baro_event", O_RDONLY); if (fd_sonar == -1) { printf("Unable to open baro event to read pressure\\n"); return 0; } while (TRUE) { n = read(fd_sonar, &ev, sizeof(ev)); if (n == sizeof(ev) && ev.type == EV_ABS && ev.code == ABS_PRESSURE) { pthread_mutex_lock(&baro_swing_mutex); baro_swing_available = 1; baro_swing_raw = ev.value; pthread_mutex_unlock(&baro_swing_mutex); } } return 0; } void baro_init(void) { baro_swing_available = 0; baro_swing_raw = 0; pthread_t baro_thread; if (pthread_create(&baro_thread, 0, baro_read, 0) != 0) { printf("[swing_board] Could not create baro reading thread!\\n"); } } void baro_periodic(void) {} void baro_event(void) { pthread_mutex_lock(&baro_swing_mutex); if (baro_swing_available) { float pressure = 100.f * ((float)baro_swing_raw) / 4096.f; AbiSendMsgBARO_ABS(BARO_BOARD_SENDER_ID, pressure); baro_swing_available = 0; } pthread_mutex_unlock(&baro_swing_mutex); }
1
#include <pthread.h> char *matrica; int m,n; int pocetak, kraj, stupac; } thr_struct; thr_struct *nova; pthread_mutex_t lock; pthread_barrier_t barijera; void* thr_f( void* arg ) { int pocetak = ( (thr_struct*) arg )->pocetak; int kraj = ( (thr_struct*) arg )->kraj; int stupac = ( (thr_struct*) arg )->stupac; int k,l; for(k=pocetak; k<=kraj; ++k) if(matrica[k] == 'o') { pthread_mutex_lock(&lock); printf("(%d,%d)\\n", k/stupac,k%stupac); pthread_mutex_unlock(&lock); } pthread_barrier_wait(&barijera); return 0; } void ucitaj (int redci, int stupci, char *ime_datoteke, char *x) { int i, k=0; char znak; FILE *matrice_file; matrice_file = fopen(ime_datoteke, "r"); for (i=0; i<redci*stupci+stupci-1; ++i) { fscanf(matrice_file, "%c", &znak); if(znak == '.' || znak == 'o') x[k++]=znak; } fclose(matrice_file); } int main(int argc, char **argv) { if (argc != 5) { fprintf(stderr, "Greska pri upisu komandne linije:\\n%s \\n", argv[0]); exit(1); } char *ime_datoteke; int i, broj_dretvi, duljina; broj_dretvi = atoi(argv[1]); m = atoi(argv[2]); n = atoi(argv[3]); ime_datoteke = argv[4]; duljina = m*n; matrica = (char*)malloc(duljina*sizeof(char)); ucitaj(m, n, ime_datoteke, matrica); pthread_t *thr_idx; pthread_barrier_init(&barijera, 0, broj_dretvi); if ((thr_idx = (pthread_t *) calloc(broj_dretvi, sizeof(pthread_t))) == 0) { fprintf(stderr, "%s: memory allocation error (greska kod alokacije dretvi)\\n", argv[0]); exit(1); } nova = (thr_struct*)malloc(broj_dretvi*sizeof(thr_struct)); for (i = 0; i < broj_dretvi; ++i) { nova[i].pocetak = ((i*m*n)/broj_dretvi); nova[i].kraj = (((i+1)*m*n)/broj_dretvi)-1; nova[i].stupac = n; if (pthread_create(&thr_idx[i], 0, thr_f,(void*)&nova[i])) { printf( "%s: error creating thread %d\\n", argv[0], i); exit(1); } } if (pthread_join(thr_idx[0], 0)) { fprintf(stderr, "%s: error joining thread 0\\n", argv[0]); exit(1); } pthread_barrier_destroy(&barijera); free(thr_idx); free(matrica); free(nova); return 0; }
0
#include <pthread.h> const int MAX_THREADS = 1024; long thread_count; long long n; double sum = 0; pthread_mutex_t mutex; void* Thread_sum(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); double Serial_pi(long long n); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish, elapsed; Get_args(argc, argv); thread_handles = (pthread_t*) malloc (sizeof(pthread_t)*thread_count); GET_TIME(start); sum = Serial_pi(n); GET_TIME(finish); elapsed=finish-start; printf("Serial pi value= %.15f\\tTime elapsed = %e seconds\\n\\n", sum,elapsed); GET_TIME(start); sum = 0.0; for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0,Thread_sum, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); sum = 4.0*sum; GET_TIME(finish); elapsed=finish-start; printf("Multi thread pi value= %.15f\\tTime elapsed = %e seconds\\n\\n", sum,elapsed); free(thread_handles); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long my_n = n/thread_count; long long my_first_i = my_n*my_rank; long long my_last_i = my_first_i + my_n; double my_sum = 0.0; if (my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for (long i = my_first_i; i < my_last_i; i++, factor = -factor) my_sum += factor/(2*i+1); sum += my_sum; return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { pthread_mutex_lock(&mutex); sum += factor/(2*i+1); pthread_mutex_unlock(&mutex); } return 4.0*sum; } void Get_args(int argc, char* argv[]) { if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]); n = strtoll(argv[2], 0, 10); if (n <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
1
#include <pthread.h> int *a, *b; long sum=0; pthread_mutex_t mutex; void *dotprod(void *arg) { int i, start, end, offset, len; long tid = (long)arg; offset = tid; len = 100000; start = offset*len; end = start + len; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++){ pthread_mutex_lock(&mutex); sum += (a[i] * b[i]); pthread_mutex_unlock(&mutex); } printf("thread: %ld done. Global sum now is=%li\\n",tid,sum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; void *status; pthread_t threads[8]; pthread_attr_t attr; a = (int*) malloc (8*100000*sizeof(int)); b = (int*) malloc (8*100000*sizeof(int)); for (i=0; i<100000*8; i++) a[i]= b[i]=1; pthread_mutex_init(&mutex,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<8; i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_mutex_destroy(&mutex); pthread_attr_destroy(&attr); for(i=0; i<8; i++) pthread_join(threads[i], &status); printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int ticket=10; void* setticket(void* p) { pthread_mutex_lock(&mutex); if(ticket>0) { pthread_cond_wait(&cond,&mutex); } ticket=10; printf("set ticket success\\n"); pthread_mutex_unlock(&mutex); pthread_exit(0); } void* salewins(void* p) { while(1) { pthread_mutex_lock(&mutex); if(ticket>0) { printf("I am windows %d,the ticket is %d\\n",(int)p,ticket); ticket--; if(ticket==0) { pthread_cond_signal(&cond); } }else{ pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_t pset,psale1,psale2; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&pset,0,setticket,0); pthread_create(&psale1,0,salewins,(void*)1); pthread_create(&psale2,0,salewins,(void*)2); pthread_join(pset,0); pthread_join(psale1,0); pthread_join(psale2,0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> struct queue_node_s *next; struct queue_node_s *prev; char c; } queue_node_t; struct queue_node_s *front; struct queue_node_s *back; pthread_mutex_t lock; } queue_t; void *producer_routine(void *arg); void *consumer_routine(void *arg); long g_num_prod; pthread_mutex_t g_num_prod_lock; int main(int argc, char **argv) { queue_t queue; pthread_t producer_thread, consumer_thread; void *thread_return = 0; int result = 0; printf("Main thread started with thread id %lu\\n", pthread_self()); memset(&queue, 0, sizeof(queue)); pthread_mutex_init(&queue.lock, 0); pthread_mutex_init(&g_num_prod_lock, 0); g_num_prod = 1; result = pthread_create(&producer_thread, 0, producer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create producer thread: %s\\n", strerror(result)); exit(1); } printf("Producer thread started with thread id %lu\\n", producer_thread); result = pthread_create(&consumer_thread, 0, consumer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\\n", strerror(result)); exit(1); } result = pthread_join(producer_thread, 0); if (0 != result) { fprintf(stderr, "Failed to join producer thread: %s\\n", strerror(result)); pthread_exit(0); } result = pthread_join(consumer_thread, &thread_return); if (0 != result) { fprintf(stderr, "Failed to join consumer thread: %s\\n", strerror(result)); pthread_exit(0); } printf("\\nPrinted %lu characters.\\n", *(long*)thread_return); pthread_mutex_destroy(&queue.lock); pthread_mutex_destroy(&g_num_prod_lock); return 0; } void *producer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *new_node_p = 0; pthread_t consumer_thread; int result = 0; char c; result = pthread_create(&consumer_thread, 0, consumer_routine, queue_p); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\\n", strerror(result)); exit(1); } result = pthread_detach(consumer_thread); if (0 != result) fprintf(stderr, "Failed to detach consumer thread: %s\\n", strerror(result)); for (c = 'a'; c <= 'z'; ++c) { new_node_p = malloc(sizeof(queue_node_t)); new_node_p->c = c; new_node_p->next = 0; pthread_mutex_lock(&queue_p->lock); if (queue_p->back == 0) { assert(queue_p->front == 0); new_node_p->prev = 0; queue_p->front = new_node_p; queue_p->back = new_node_p; } else { assert(queue_p->front != 0); new_node_p->prev = queue_p->back; queue_p->back->next = new_node_p; queue_p->back = new_node_p; } pthread_mutex_unlock(&queue_p->lock); sched_yield(); } pthread_mutex_lock(&g_num_prod_lock); --g_num_prod; pthread_mutex_unlock(&g_num_prod_lock); pthread_exit(0); } void *consumer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *prev_node_p = 0; long count = 0; printf("Consumer thread started with thread id %lu\\n", pthread_self()); while(queue_p->front != 0 || g_num_prod > 0) { if (queue_p->front != 0) { pthread_mutex_lock(&queue_p->lock); prev_node_p = queue_p->front; if (queue_p->front->next == 0) queue_p->back = 0; else queue_p->front->next->prev = 0; queue_p->front = queue_p->front->next; pthread_mutex_unlock(&queue_p->lock); printf("%c", prev_node_p->c); free(prev_node_p); ++count; } else { sched_yield(); } } pthread_exit(&count); }
0
#include <pthread.h> int q[4]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 4) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 4); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[8]; int sorted[8]; void producer () { int i, idx; for (i = 0; i < 8; i++) { idx = findmaxidx (source, 8); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 8); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 8; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 8); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 8; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number; int i; void *thread1() { pthread_detach(pthread_self()); printf ("pthread1 : I'm thread 1\\n"); for (i = 0; i < 15; i++) { pthread_mutex_lock(&mut); number++; printf("pthread1 : number = %d\\n",number); pthread_mutex_unlock(&mut); usleep(1); } printf("pthread1 : done the thread\\n"); pthread_exit(0); } void *thread2() { pthread_detach(pthread_self()); printf("pthread2 : I'm thread 2\\n"); for (i = 0; i < 15; i++) { pthread_mutex_lock(&mut); number++; printf("pthread2 : number = %d\\n",number); pthread_mutex_unlock(&mut); usleep(1); } printf("pthread2 : done the thread\\n"); pthread_exit(0); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0){ printf("create pthread 1 failed!\\n"); } else{ printf("create pthread 1 done\\n"); } if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0){ printf("create pthread 2 failed"); } else{ printf("create pthread 2 done\\n"); } } int main() { number=0; pthread_mutex_init(&mut,0); printf("I'm the main process, do the thread_create\\n"); thread_create(); printf("I'm the main process, do the thread_wait\\n"); while(1); return 0; }
0
#include <pthread.h> uint64_t * nombresPremiers(uint64_t n, int * taille); uint64_t * factorisation(uint64_t n, int * taille); void * print_prime_factors(void * n); static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; int main() { FILE * f; if((f=fopen("numbers.txt","r")) != 0) { uint64_t n; uint64_t n2; while(fscanf(f, "%lld",&n) != EOF) { pthread_t t1=0; pthread_t t2=0; pthread_create(&t1, 0, print_prime_factors, &n); if(fscanf(f, "%lld",&n2) != EOF) { pthread_create(&t2, 0, print_prime_factors, &n2); } pthread_join(t1, 0); if(t2 != 0) { pthread_join(t2, 0); } } fclose(f); } pthread_mutex_destroy(&mutex); return 0; } uint64_t * nombresPremiers(uint64_t n, int * taille) { uint64_t i; uint64_t * renvoi = (uint64_t *) malloc(sizeof(uint64_t)*n); int indice = 2; int saut = 2; renvoi[0]=2; renvoi[1]=3; for(i=5; i<=n; i+=saut, saut=6-saut) { uint64_t j; for(j=(uint64_t)(sqrt(i-1)+1); j>1 && i%j!=0; j--); if(j=1) { renvoi[indice++] = i; } } *taille=indice; return renvoi; } uint64_t * factorisation(uint64_t n, int * taille) { uint64_t * renvoi = (uint64_t *) malloc(sizeof(uint64_t)*((uint64_t)sqrt(n)+1)); int indice = 0; int taillePremier=0; uint64_t * tabPremier = nombresPremiers(sqrt(n)+2, &taillePremier); int i; uint64_t produit = 1; for(i=0; i<taillePremier && produit < n; i++) { if(n%tabPremier[i]==0) { renvoi[indice++]=tabPremier[i]; produit *= tabPremier[i]; n/=tabPremier[i]; i--; } } if(indice==0 || n!= 1) { renvoi[indice++]=n; } *taille=indice; free(tabPremier); return renvoi; } void * print_prime_factors(void * n) { uint64_t nombre = *(uint64_t*)n; int t=0; uint64_t * tab = factorisation(nombre, &t); int i; pthread_mutex_lock(&mutex); printf("%lld : ", nombre); for(i=0; i<t; i++) { printf(" %lld", tab[i]); } printf("\\n"); pthread_mutex_unlock(&mutex); free(tab); pthread_exit(0); }
1
#include <pthread.h> void *thread_function(void *arg); int run_now = 1; char message[] = "Hello World"; unsigned int num; const unsigned int count = 20000000; pthread_mutex_t work_mutex; int main() { int res; pthread_t a_thread; void *thread_result; int print_count1 = 0; int n = 0; res = pthread_mutex_init(&work_mutex, 0); if (res != 0) { perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, (void *)message); if (res != 0) { perror("Thread creation failed"); exit(1); } for (n = 0; n < count; n++) { pthread_mutex_lock(&work_mutex); num++; pthread_mutex_unlock(&work_mutex); } printf("\\nWaiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); printf("num is :%lu\\n", num); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); exit(0); } void *thread_function(void *arg) { int print_count2 = 0; int n; for (n = 0; n < count; n++) { pthread_mutex_lock(&work_mutex); num++; pthread_mutex_unlock(&work_mutex); } }
0
#include <pthread.h> struct car { int destination; int source; int position; pthread_mutex_t lock; }; pthread_mutex_t quadrants[4]; pthread_mutex_t check; pthread_t car_threads[20]; struct car cars[20]; void *run_car(void *carID) { int id = (int) carID; pthread_mutex_lock(&cars[id].lock); while (1) { int i, posCount = -1, destination, position; int source = rand() % 4; do { destination = rand() % 4; } while (source == destination); for (i = 0; i < 20; i++) { if (cars[i].source == source && cars[i].position < 0) { posCount--; } } position = posCount; cars[id].source = source; cars[id].destination = destination; cars[id].position = position; while (cars[id].position != cars[id].destination) { if (cars[id].position >= -1 && cars[id].position <= 5) { int nextMove, updatePreviousCars; int i, madeMove = 0, deadlockCount = 0, canMakeMove = 1, wontCauseDeadlock = 1; pthread_mutex_lock(&check); if (cars[id].position == -1) { nextMove = (cars[id].source + 1) % 4; updatePreviousCars = 1; } else { nextMove = (cars[id].position + 1) % 4; } pthread_mutex_unlock(&check); pthread_mutex_lock(&quadrants[nextMove]); for (i = 0; i < 20; i++) { canMakeMove = canMakeMove && !(cars[i].position == nextMove); } for (i = 0; i < 20; i++) { if (cars[i].position >= 0 && cars[i].position <= 3 && i != id && cars[i].destination != cars[i].position) { deadlockCount++; } } wontCauseDeadlock = (deadlockCount < 3); if (canMakeMove && wontCauseDeadlock) { cars[id].position = nextMove; madeMove = 1; if (updatePreviousCars) { for (i = 0; i < 20; i++) { if (cars[i].source == cars[id].source && cars[i].position < -1) { cars[i].position++; } } } for (i = 0; i < 20; i++) { if (cars[i].position >= -1 && cars[i].position <= 3 && i != id) { pthread_mutex_unlock(&cars[i].lock); } } } pthread_mutex_unlock(&quadrants[nextMove]); if (!madeMove) { } } else { pthread_mutex_lock(&cars[id].lock); } } } } int main(int argc, char *argv[]) { int i, status; for (i = 0; i < 4; i++) { pthread_mutex_init(&quadrants[i], 0); } pthread_mutex_init(&check, 0); srand(time(0)); for (i = 0; i < 20; i++) { cars[i].position = 5; pthread_mutex_init(&cars[i].lock, 0); } for (i=0; i < 20; i++) { status = pthread_create(&car_threads[i], 0, run_car, (void *) i); if (status != 0) { exit(-1); } } for (i=0; i < 20; i++) { status = pthread_join(car_threads[i], 0); if (status != 0) { exit(-1); } } exit(0); }
1
#include <pthread.h> void *thread_open(void *); void *thread_even(void *); void *thread_odd(void *); pthread_t threadID[5]; pthread_mutex_t mutex1, mutex2; int fd, ret; int main() { int threadFD, i = 0,k = 2, j = 1; char *rt; ret = pthread_mutex_init(&mutex1, 0); ret = pthread_mutex_init(&mutex2, 0); if (ret != 0){ perror("MUTEX Initialization failed"); exit(1); } threadFD = pthread_create(&threadID[i],0,&thread_open,(void *)&i); pthread_join(threadID[i],(void **)&rt); printf("exit code for open: %s\\n",rt); threadFD = pthread_create(&threadID[k],0,&thread_odd,(void *)&k); pthread_join(threadID[k],(void **)&rt); printf("exit code for odd: %s\\n",rt); threadFD = pthread_create(&threadID[j],0,&thread_even,(void *)&j); pthread_join(threadID[j],(void **)&rt); printf("exit code for even: %s\\n",rt); return 0; } void *thread_open(void *arg) { int i; i = *(int *)arg; printf("thread_fd in open function: %d\\n",i); fd = open("thread_text.txt", O_RDWR|O_CREAT); if (fd < 0) { perror("open"); exit(1); } printf("fd = %d\\n",fd); pthread_exit("thread_open: bye"); } void *thread_even(void *arg) { int i, val; i = *(int *)arg; printf("thread_fd in thread_even function: %d\\n",i); for(val = 0; val <= 10; val += 2){ pthread_mutex_unlock(&mutex1); printf("even val: %d\\n",val); sleep(1); pthread_mutex_lock(&mutex2); sleep(1); } sleep(1); pthread_exit("thread_even: bye"); } void *thread_odd(void *arg) { int i, val; i = *(int *)arg; printf("thread_fd in thread_odd function: %d\\n",i); for(val = 1; val <= 10; val += 2){ pthread_mutex_unlock(&mutex2); printf("odd val: %d\\n",val); sleep(1); pthread_mutex_lock(&mutex1); sleep(1); } sleep(1); pthread_exit("thread_odd: bye"); }
0
#include <pthread.h> int value; int divisors; } result_t; int g_max; int g_next; pthread_mutex_t g_next_mtx; result_t g_best; int g_processed; pthread_mutex_t g_best_mtx; pthread_cond_t g_best_cnd; int num_divisors(int v) { int cnt = 0; for (int i = 1; i <= v; i++) if (v % i == 0) cnt++; return (cnt); } int inc_value() { int r; pthread_mutex_lock(&g_next_mtx); r = g_next++; pthread_mutex_unlock(&g_next_mtx); return (r); } void update_best(result_t *res) { pthread_mutex_lock(&g_best_mtx); g_processed++; if (g_best.divisors < res->divisors) { g_best = *res; } pthread_cond_signal(&g_best_cnd); pthread_mutex_unlock(&g_best_mtx); } void *thread(void *p) { result_t res; while ((res.value = inc_value()) <= g_max) { res.divisors = num_divisors(res.value); update_best(&res); } return (0); } int main(int argc, char *argv[]) { pthread_t thread_pool[5]; void *r; int value; if (argc < 2) { fprintf(stderr, "chybi argument\\n"); return (1); } bzero(&g_best, sizeof (result_t)); value = 0; g_max = atoi(argv[1]); g_next = 0; g_processed = 0; pthread_mutex_init(&g_next_mtx, 0); pthread_mutex_init(&g_best_mtx, 0); pthread_cond_init(&g_best_cnd, 0); for (int i = 0; i < 5; i++) pthread_create(&thread_pool[i], 0, thread, 0); pthread_mutex_lock(&g_best_mtx); do { pthread_cond_wait(&g_best_cnd, &g_best_mtx); if (g_best.value != value) { printf("\\nNovy nejlepsi vysledek [%d]: %d\\n", g_best.value, g_best.divisors); value = g_best.value; } printf("\\r%3.02f%%", 100.0f * ((float) g_processed / (float) g_max)); } while (g_processed < g_max); pthread_mutex_unlock(&g_best_mtx); printf("\\nNejvice delitelu ma %d: %d\\n", g_best.value, g_best.divisors); for (int i = 0; i < 5; i++) pthread_join(thread_pool[i], &r); pthread_cond_destroy(&g_best_cnd); pthread_mutex_destroy(&g_best_mtx); pthread_mutex_destroy(&g_next_mtx); return (0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void** buffer; unsigned int capacity; unsigned int head; unsigned int size; char is_closed; } channel; channel* chan_create(unsigned int capacity) { capacity += 1; channel* chan = malloc(sizeof(channel)); pthread_mutex_init(&chan->mutex, 0); pthread_cond_init(&chan->cond, 0); chan->buffer = malloc(sizeof(void*) * capacity); chan->capacity = capacity; chan->head = 0; chan->size = 0; chan->is_closed = 0; return chan; } void chan_close(channel* chan) { pthread_mutex_lock(&chan->mutex); chan->is_closed = 1; pthread_mutex_unlock(&chan->mutex); } void chan_destroy(channel* chan) { chan_close(chan); pthread_mutex_destroy(&chan->mutex); pthread_cond_destroy(&chan->cond); free(chan->buffer); free(chan); } int chan_send(channel* chan, void* data) { pthread_mutex_lock(&chan->mutex); if(chan->is_closed) { pthread_mutex_unlock(&chan->mutex); return -1; } while(chan->size == chan->capacity) { pthread_cond_wait(&chan->cond, &chan->mutex); } unsigned int index = (chan->head + chan->size) % chan->capacity; chan->buffer[index] = data; chan->size++; pthread_cond_broadcast(&chan->cond); while(chan->size == chan->capacity) { pthread_cond_wait(&chan->cond, &chan->mutex); } pthread_mutex_unlock(&chan->mutex); return 0; } int chan_recv(channel* chan, void** data) { pthread_mutex_lock(&chan->mutex); if(chan->size == 0 && chan->is_closed) { pthread_mutex_unlock(&chan->mutex); return -1; } while(chan->size == 0) { pthread_cond_wait(&chan->cond, &chan->mutex); } *data = chan->buffer[chan->head]; chan->head = (chan->head + 1) % chan->capacity; chan->size--; pthread_cond_broadcast(&chan->cond); pthread_mutex_unlock(&chan->mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutexS1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexS2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexS3 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER; char *ingredients[3] = {"tobacco", "paper", "matches"}; int ai1; int ai2; int random_0_2() { return 3 * (rand() / (32767 + 1.0)); } void *runS1() { while (1) { pthread_mutex_lock(&mutexS1); printf("Smoker 1 has %s, so he makes and smokes a cigarette.\\n\\n", ingredients[1]); pthread_mutex_unlock(&mutexA); } } void *runS2() { while (1) { pthread_mutex_lock(&mutexS2); printf("Smoker 2 has %s, so he makes and smokes a cigarette.\\n\\n", ingredients[0]); pthread_mutex_unlock(&mutexA); } } void *runS3() { while (1) { pthread_mutex_lock(&mutexS3); printf("Smoker 3 has %s, so he makes and smokes a cigarette.\\n\\n", ingredients[2]); pthread_mutex_unlock(&mutexA); } } void *runA() { while (1) { pthread_mutex_lock(&mutexA); ai1 = random_0_2(); ai2 = random_0_2(); if (ai1 == ai2) { ai2 = (ai1 + 2) % 3; } printf("Agent Places %s and %s on the table.\\n", ingredients[ai1], ingredients[ai2]); if ((ai1 == 0 && ai2 == 2 ) || (ai1 == 2 && ai2 == 0 )) { pthread_mutex_unlock(&mutexS1); } else if ((ai1 == 1 && ai2 == 2 ) || (ai1 == 2 && ai2 == 1 )) { pthread_mutex_unlock(&mutexS2); } else { pthread_mutex_unlock(&mutexS3); } } } int main(int argc, const char * argv[]) { int rS1, rS2, rS3, rA; pthread_t threadS1, threadS2, threadS3, threadA; pthread_mutex_lock(&mutexS1); pthread_mutex_lock(&mutexS2); pthread_mutex_lock(&mutexS3); if ((rS1=pthread_create(&threadS1, 0, runS1, 0))) { printf("ThreadS1 creation failed: %d\\n", rS1); } if ((rS2=pthread_create(&threadS2, 0, runS2, 0))) { printf("ThreadS2 creation failed: %d\\n", rS2); } if ((rS3=pthread_create(&threadS3, 0, runS3, 0))) { printf("ThreadS3 creation failed: %d\\n", rS3); } if ((rA=pthread_create(&threadA, 0, runA, 0))) { printf("ThreadA creation failed: %d\\n", rA); } pthread_join(threadS1, 0); pthread_join(threadS2, 0); pthread_join(threadS3, 0); pthread_join(threadA, 0); return 0; }
1
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; struct foo *foo_alloc(int id) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1; pthread_mutex_t mutex; int pdev; void *thread1(void *arg) { pthread_mutex_lock(&mutex); pdev = 6; pthread_mutex_unlock(&mutex); } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread1, 0); pdev = 2; ldv_assert(pdev==2); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
1
#include <pthread.h> int data; int countR; }b; pthread_mutex_t mutex; pthread_t readtid[1000],writetid; b buffer[5]; int numC,flag[5][1000],f[1000]; pthread_attr_t attr; int limit = 100; void *reader(void *arg); void *writer(void *arg); void writeData(int i); void initialize() { int i,j; for(i=0;i<5;i++) { buffer[i].data = -1; buffer[i].countR = 0; for(j=0;j<numC;j++) flag[i][j] = 0; f[i]=0; } } int main() { int i,j,sTime; printf("Number of consumers : "); scanf("%d",&numC); initialize(); pthread_mutex_init(&mutex,0); pthread_attr_init(&attr); pthread_create(&writetid,&attr,writer,0); for(i=0;i<numC;i++) { int index = i; pthread_create(&readtid[i],0,reader,(void*)index); } sleep(100); printf("Exit the program\\n"); exit(0); } void *writer(void *arg) { int temp; while(1) { temp = rand()%5; if(buffer[temp].countR%numC == 0 && f[temp]==0) { pthread_mutex_lock(&mutex); writeData(temp); pthread_mutex_unlock(&mutex); } else { while(buffer[temp].countR%numC != 0 || f[temp]!=0); pthread_mutex_lock(&mutex); writeData(temp); pthread_mutex_unlock(&mutex); } } } void writeData(int i) { int j; buffer[i].data = rand()%limit; buffer[i].countR = 0; printf("Writer writes %d at %d\\n",buffer[i].data,i); f[i]=1; for(j=0;j<numC;j++) { flag[i][j]=0; } } void *reader(void *arg) { int a = (int)arg; int i,j,temp,pos=0,count=0; while(1) { sleep(1); pthread_mutex_lock(&mutex); pos = rand()%5; if (flag[pos][a]==0 && buffer[pos].data>=0) { printf("Reader %d reads %d at position %d\\n",a,buffer[pos].data,pos); flag[pos][a] = 1; buffer[pos].countR += 1; } if(buffer[pos].countR==numC) { f[pos]=0; buffer[pos].countR = 0; } pthread_mutex_unlock(&mutex); count++; } }
0
#include <pthread.h> void *control_pos(void *arg) { struct task_par *tp; tp = (struct task_par *)arg; float buff_in[5]; float out_pos[5]; float aux_i[5]; float aux_p[5]; float Ki, Kp, Kd, J, L, b, R, Ke, Kt, ref; struct par_mgt par_mgt_p; int i = 0; set_period(tp); while(1) { pthread_mutex_lock(&mux_us[POS_COLUMN]); set_par(&Ki, &Kp, &Kd, &J, &L, &b, &R, &Ke, &Kt, &ref, &PID_p[(*tp).arg], &motor_p[(*tp).arg]); pthread_mutex_unlock(&mux_us[POS_COLUMN]); tf_position(&par_mgt_p, Ki, Kp, Kd, J, L, b, R, Ke, Kt); control_position_compute(par_mgt_p, ref, buff_in, aux_i, aux_p, out_pos, i); if((*tp).arg == n_p) { pthread_mutex_lock(&mux_p[(*tp).arg]); out_ctr_p[(*tp).arg] = out_pos[0]; pthread_mutex_unlock(&mux_p[(*tp).arg]); } else out_ctr_p[(*tp).arg] = out_pos[0]; i++; if(deadline_miss(tp)) { printf("Missed deadline of System control position thread!! System n. %d\\n", (*tp).arg); } wait_for_period(tp); } } void *control_vel (void *arg) { struct task_par *tp; tp = (struct task_par *)arg; float buff_in[5]; float out_vel[5]; float aux_i[5]; float aux_v[5]; float Ki, Kp, Kd, J, L, b, R, Ke, Kt, ref; struct par_mgt par_mgt_v; int i = 0; set_period(tp); while(1) { pthread_mutex_lock(&mux_us[VEL_COLUMN]); set_par(&Ki, &Kp, &Kd, &J, &L, &b, &R, &Ke, &Kt, &ref, &PID_v[(*tp).arg], &motor_v[(*tp).arg]); pthread_mutex_unlock(&mux_us[VEL_COLUMN]); tf_velocity(&par_mgt_v, Ki, Kp, Kd, J, L, b, R, Ke, Kt); control_velocity_compute(par_mgt_v, ref, buff_in, aux_i, aux_v, out_vel, i); if((*tp).arg == n_v) { pthread_mutex_lock(&mux_v[(*tp).arg]); out_ctr_v[(*tp).arg] = out_vel[0]; pthread_mutex_unlock(&mux_v[(*tp).arg]); } else out_ctr_v[(*tp).arg] = out_vel[0]; i++; if(deadline_miss(tp)) { printf("Missed deadline of System control velocity thread!! System n. %d\\n", (*tp).arg); } wait_for_period(tp); } } void *control_tor(void *arg) { struct task_par *tp; tp = (struct task_par *)arg; float buff_in[5]; float out_tor[5]; float aux_i[5]; float aux_t[5]; float Ki, Kp, Kd, J, L, b, R, Ke, Kt, ref; struct par_mgt par_mgt_t; int i = 0; set_period(tp); while(1) { pthread_mutex_lock(&mux_us[TOR_COLUMN]); set_par(&Ki, &Kp, &Kd, &J, &L, &b, &R, &Ke, &Kt, &ref, &PID_t[(*tp).arg], &motor_t[(*tp).arg]); pthread_mutex_unlock(&mux_us[TOR_COLUMN]); tf_torque(&par_mgt_t, Ki, Kp, Kd, J, L, b, R, Ke, Kt); control_torque_compute(par_mgt_t, ref, buff_in, aux_i, aux_t, out_tor, i); if((*tp).arg == n_t) { pthread_mutex_lock(&mux_t[(*tp).arg]); out_ctr_t[(*tp).arg] = out_tor[0]; pthread_mutex_unlock(&mux_t[(*tp).arg]); } else out_ctr_t[(*tp).arg] = out_tor[0]; i++; if(deadline_miss(tp)) { printf("Missed deadline of System control torque thread!! System n. %d\\n", (*tp).arg); } wait_for_period(tp); } }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int final_result=0; void *filter (void *threadarg){ int x; int checksum =0; int y = *((int *)threadarg); for (x = 0; x < 1000; x++){ int sum = 0; int pixelsAveraged = 1; if (y-1 >= 0 && x-1 >= 0){ sum+= input[y-1][x-1]*3; pixelsAveraged++; } if (y-1 >= 0 && x+1 < 1000){ sum+= input[y-1][x+1]*3; pixelsAveraged++; } if (y+1 < 6 && x+1 < 1000){ sum+= input[y+1][x+1]*3; pixelsAveraged++; } if (y+1 < 6 && x-1 >= 0) { sum+= input[y+1][x-1]*3; pixelsAveraged++; } if (y-1 >= 0) { sum+= input[y-1][x]*3; pixelsAveraged++; } if (x-1 >= 0) { sum+= input[y][x-1]*3; pixelsAveraged++; } if (y+1 < 6) { sum+= input[y+1][x]*3; pixelsAveraged++; } if (x+1 < 1000) { sum+= input[y][x+1]*3; pixelsAveraged++; } sum+=input[y][x]; checksum += sum/pixelsAveraged; } pthread_mutex_lock (&mutex); final_result += checksum; pthread_mutex_unlock (&mutex); pthread_exit(0); } int main(){ int y,x; pthread_t threads[6]; int i[6]; for (y = 0; y < 6; y++) { i[y] = y; pthread_create(&threads[y], 0, filter, (void *)&i[y]); } for (y = 0; y < 6; y++) { pthread_join(threads[y], 0); } printf ("Result: %d\\n", final_result); if (final_result == 87798) { printf("RESULT: PASS\\n"); } else { printf("RESULT: FAIL\\n"); } }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc,condp; int buffer=0; void *producer(void *prt) { int i; for(i=1;i<=10;i++) { pthread_mutex_lock(&the_mutex); while(buffer!=0) { sleep(1); pthread_cond_wait(&condp,&the_mutex); } printf("I`m the producer\\n"); buffer=i; pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void* ptr) { int i; for(i=1;i<=10;i++) { pthread_mutex_lock(&the_mutex); while(buffer==0) { sleep(1); pthread_cond_wait(&condc,&the_mutex); } printf("I am the consumer\\n"); buffer=0; pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro,con; pthread_mutex_init(&the_mutex,0); pthread_cond_init(&condc,0); pthread_cond_init(&condp,0); pthread_create(&con,0,consumer,0); pthread_create(&pro,0,producer,0); pthread_join(pro,0); pthread_join(con,0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); }
1
#include <pthread.h> static struct hash_map *literals; static pthread_mutex_t literals_mutex = PTHREAD_MUTEX_INITIALIZER; struct string *alloc_str(void) { int err; struct string *str = malloc(sizeof *str); if (!str) return 0; memset(str, 0, sizeof *str); err = str_resize(str, 100); if (err) { free(str); return 0; } memset(str->value, 0, str->capacity); return str; } struct string *string_from_cstr(char *s) { struct string *str = malloc(sizeof *str); if (!str) return 0; str->length = str->capacity = strlen(s); str->value = s; return str; } struct string *string_from_cstr_dup(const char *s) { char *dup = strdup(s); if (!dup) return 0; return string_from_cstr(dup); } struct string *string_intern_cstr(const char *s) { struct string *result; pthread_mutex_lock(&literals_mutex); if (!hash_map_get(literals, s, (void **) &result)) goto out; result = string_from_cstr_dup(s); if (!result) goto out; if (hash_map_put(literals, result->value, result)) { free_str(result); result = 0; } out: pthread_mutex_unlock(&literals_mutex); return result; } void init_string_intern(void) { literals = alloc_hash_map(&string_key); if (!literals) die("Unable to initialize string literal hash map"); } void free_str(struct string *str) { free(str->value); free(str); } int str_resize(struct string *str, unsigned long capacity) { char *buffer; buffer = realloc(str->value, capacity); if (!buffer) return -ENOMEM; str->value = buffer; str->capacity = capacity; return 0; } static unsigned long str_remaining(struct string *str, int offset) { return str->capacity - offset; } static int str_vprintf(struct string *str, unsigned long offset, const char *fmt, va_list args) { unsigned long size; va_list tmp_args; int nr, err = 0; retry: size = str_remaining(str, offset); va_copy(tmp_args, args); nr = vsnprintf(str->value + offset, size, fmt, tmp_args); ; if ((unsigned long)nr >= size) { err = str_resize(str, str->capacity * 2); if (err) goto out; goto retry; } str->length = offset + nr; out: return err; } int str_printf(struct string *str, const char *fmt, ...) { int err; va_list args; __builtin_va_start((args)); err = str_vprintf(str, 0, fmt, args); ; return err; } int str_vappend(struct string *str, const char *fmt, va_list args) { return str_vprintf(str, str->length, fmt, args); } int str_append(struct string *str, const char *fmt, ...) { int err; va_list args; __builtin_va_start((args)); err = str_vappend(str, fmt, args); ; return err; }
0
#include <pthread.h> void* func(void* m); void* funcn(); void* check(); union semun { int val; struct semid_ds *buf; unsigned short int *array; }; int val; int game[4][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}}; int count[5]={0,0,0,0,0}; int sem_id; pthread_mutex_t lock; int main() { pthread_t tid[5]; pthread_t thrdid; sem_id=semget(7153,16, IPC_CREAT | 666); pthread_mutex_init(&lock,0); if(sem_id==-1) { perror("semget error!\\n"); exit(1); } union semun T; T.val=1; int i; for(i=0; i<16; i++) { if(semctl(sem_id, i,SETVAL, T)==-1) { printf("semctl error!\\n"); exit(1); } } int x,y; while(count[0]!=4 && count[1]!=4 && count[2]!=4 && count[3]!=4 && count[4]!=4) { printf("enter the x coordinate\\n"); scanf("%d",&x); printf("enter the y coordinate\\n"); scanf("%d",&y); game[x-1][y-1]=5; count[4]++; for(i=0;i<4;i++) { pthread_create(&tid[i],0,func,(void* )(i+1)); } for(i=0;i<4;i++) pthread_join(tid[i],0); } } void* func(void* m) { int i,j; int id=(int)m; int flag=0; { for(i=0;i<4;i++) { for(j=0;j<4;j++) { struct sembuf tk; tk.sem_num=4*i+j; tk.sem_flg=IPC_NOWAIT; tk.sem_op=-1; int x=semop(sem_id, &tk,1); if(game[i][j]==0 && x==0) { count[id-1]++; game[i][j]=id; flag=1; break; }} if(flag==1) break; } } pthread_mutex_lock(&lock); for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("%d ",game[i][j]); } printf("\\n"); } pthread_mutex_unlock(&lock); } void* check() { int i=0; int j=0; int temp; int cnt=0; for(i=0;i<4;i++) { temp=game[i][0]; if(temp!=0) { cnt=0; for(j=1;j<4;j++) { if(temp==game[i][j]) cnt++; } if(cnt==4) { printf("winner is %d\\n",game[i][3]); exit(0); } } } for(i=0;i<4;i++) { temp=game[0][i]; if(temp!=0) { cnt=0; for(j=0;j<4;j++) { if(temp==game[j][i]) cnt++; } if(cnt==4) printf("winner is %d\\n",game[3][i]); } } temp=game[0][0]; if(temp!=0) { cnt=0; for(i=1;i<4;i++) { if(temp==game[i][i]) cnt++; } if(cnt==4) printf("winner is %d\\n",game[0][0]); } temp=game[0][3]; if(temp!=0) { for(i=1;i<4;i++) { if(temp==game[i][3-i]) cnt++; } if(cnt==4) printf("winner is %d\\n",game[0][3]); }}
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *idp) { int j,i; double result=0.0; int *my_id = idp; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %d, count = %d Threshold reached.\\n", *my_id, count); } printf("inc_count(): thread %d, count = %d, unlocking mutex\\n", *my_id, count); pthread_mutex_unlock(&count_mutex); for (j=0; j<1000; j++) result = result + (double)random(); } pthread_exit(0); } void *watch_count(void *idp) { int *my_id = idp; printf("Starting watch_count(): thread %d\\n", *my_id); pthread_mutex_lock(&count_mutex); if (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %d Condition signal received.\\n", *my_id); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, ret_count; pthread_t threads[3]; pthread_attr_t attr; ret_count=pthread_mutex_init(&count_mutex, 0); if (ret_count) { printf("ERROR; return code from pthread_mutex_init() is %d\\n", ret_count); exit(-1); } pthread_cond_init (&count_threshold_cv, 0); ret_count=pthread_attr_init(&attr); if (ret_count) { printf("ERROR; return code from pthread_attr_init() is %d\\n", ret_count); exit(-1); } pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); ret_count=pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]); if (ret_count) { printf("ERROR; return code from pthread_create() is %d\\n", ret_count); exit(-1); } ret_count=pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]); if (ret_count) { printf("ERROR; return code from pthread_create() is %d\\n", ret_count); exit(-1); } ret_count=pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]); if (ret_count) { printf("ERROR; return code from pthread_create() is %d\\n", ret_count); exit(-1); } for (i=0; i<3; i++) { ret_count=pthread_join(threads[i], 0); if (ret_count) { printf("ERROR; return code from pthread_join() is %d\\n", ret_count); exit(-1); } } printf ("Main(): Waited on %d threads. Done.\\n", 3); ret_count=pthread_attr_destroy(&attr); if (ret_count) { printf("ERROR; return code from pthread_attr_destroy() is %d\\n", ret_count); exit(-1); } ret_count=pthread_mutex_destroy(&count_mutex); if (ret_count) { printf("ERROR; return code from pthread_mutex_destroy() is %d\\n", ret_count); exit(-1); } pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> int DPW_countack, num_ack[NUM_M]; int DPW_infly_high, DPW_infly_low; int *DPW_table4g; pthread_t DPW_recv_g_send_m_t[NUM_G], DPW_recv_m_send_g_t[NUM_M], DPW_FT_send_b_t; pthread_mutex_t ordered_mutex, ack_mutex; struct DPW_order *DPW_order_list; struct timespec DPW_DA_begin_time; struct timespec *DPW_DA_end_list, *DPW_DA_start_list; void *DPW_recv_g_send_m_task(void *arg); void *DPW_recv_m_send_g_task(void *arg); void *DPW_FT_send_b_task(void *arg); int main(int argc, char **argv) { int i, tmp_g[NUM_G], tmp_m[NUM_M], ack; int accepted; if (argc != 3) { printf("Usage: %s type infly_high\\n", argv[0]); exit(1); } me = DPW_initialize_cluster(argv[1]); printf("%d\\n", me); DPW_infly_low = DPW_infly_high = atoi(argv[2]); DPW_countack = 0; for (i = 0; i < NUM_M; i++) num_ack[i] = -1; DPW_order_list = (struct DPW_order *) malloc(BUFFER_SIZE * sizeof (struct DPW_order)); DPW_table4g = (int *) malloc(BUFFER_SIZE * sizeof (int)); DPW_DA_end_list = (struct timespec *) malloc(BUFFER_SIZE * sizeof (struct timespec)); DPW_DA_start_list = (struct timespec *) malloc(BUFFER_SIZE * sizeof (struct timespec)); pthread_mutex_init(&ordered_mutex, 0); pthread_mutex_init(&ack_mutex, 0); if (NTU_listen_unit() < 0) ERROR("listen_unit"); INFO("Start %s", get_name(me)); NTU_connect_unit(M0); NTU_connect_unit(M1); NTU_connect_unit(R); if (NTU_connect_unit(B) == B) { if (NTU_recv_unit(B, &DPW_countack, sizeof (int)) < 0) { } else INFO("Recover DPW_countack=[%d]", DPW_countack); if (NTU_recv_unit(B, &ack, sizeof (int)) < 0) { } else { INFO("Recover ack=[%d]", ack); num_ack[0] = ack; num_ack[1] = ack; } } for (i = 0; i < NUM_G; i++) { tmp_g[i] = i; while (pthread_create(&DPW_recv_g_send_m_t[i], 0, DPW_recv_g_send_m_task, (void *) &tmp_g[i]) < 0) { WARN("pthread_create m_main_t[%d]", i); } } for (i = 0; i < NUM_M; i++) { tmp_m[i] = i; while (pthread_create(&DPW_recv_m_send_g_t[i], 0, DPW_recv_m_send_g_task, (void *) &tmp_m[i]) < 0) { WARN("pthread_create m_main_t[%d]", i); } } while (pthread_create(&DPW_FT_send_b_t, 0, DPW_FT_send_b_task, 0) < 0) { WARN("pthread_create DPW_FT_send_b_t"); } while (1) { accepted = NTU_accept_unit(); if (accepted >= F0 + NUM_F) { INFO("Reconnect to %s", get_name(accepted)); while (NTU_connect_unit(accepted) < 0) { sleep(1); } } if(accepted < F0); } return 0; } void *DPW_recv_m_send_g_task(void *arg){ int w = *((int *) arg); int M = M0 + w; int ack, ok = 0, protocol, gw; while (1) { if (get_status(M) == DEAD) continue; if (num_ack[w] >= DPW_countack - 1) continue; if (NTU_recv_unit(M, &ack, sizeof (int)) < 0) { protocol = w + 3; if (NTU_send_unit(R, &protocol, sizeof (int)) < 0) { } INFO("Notify R that %s die", get_name(M)); continue; } DEBUG("Recv %s ack=[%d]", get_name(M), ack); pthread_mutex_lock(&ack_mutex); if (ack > num_ack[0] && ack > num_ack[1]) { num_ack[w] = ack; ok = 1; } pthread_mutex_unlock(&ack_mutex); if (ok == 1) { ok = 0; gw = DPW_table4g[ack % BUFFER_SIZE]; if (NTU_send_unit(gw, &ack, sizeof (int)) < 0) continue; DEBUG("Send G%d ack=[%d]", gw, ack); clock_gettime(CLOCK_REALTIME, &DPW_DA_end_list[ack % BUFFER_SIZE]); DA_data_analysis(ack, DPW_DA_start_list[ack%BUFFER_SIZE], DPW_DA_end_list[ack%BUFFER_SIZE], DPW_DA_begin_time); fflush(stdout); } if (ack > num_ack[w]) num_ack[w] = ack; } pthread_exit(0); } void *DPW_recv_g_send_m_task(void *arg) { int w = *((int *) arg); int G = G0 + w; struct DPW_order odr; int i, infly = 0; while (1) { if (get_status(G) == DEAD) continue; if (DPW_countack - (DPW_infly_high - infly) > num_ack[0] && DPW_countack - (DPW_infly_high - infly) > num_ack[1]) { infly = DPW_infly_high - DPW_infly_low; continue; } INFO("%d %d",DPW_countack - num_ack[0], DPW_countack - num_ack[1]); infly = 0; if (NTU_recv_unit(G, odr.str, DPW_order_size) < 0) continue; DEBUG("Recv %s str=[%s]", get_name(G), odr.str); if (DPW_countack < 1) clock_gettime(CLOCK_REALTIME, &DPW_DA_begin_time); clock_gettime(CLOCK_REALTIME, &DPW_DA_start_list[DPW_countack % BUFFER_SIZE]); pthread_mutex_lock(&ack_mutex); odr.id = DPW_countack; DPW_table4g[DPW_countack % BUFFER_SIZE] = w; DPW_order_list[DPW_countack % BUFFER_SIZE] = odr; for (i = 0; i < NUM_M; i++) { if (NTU_send_unit(M0 + i, &odr, DPW_order_size) < 0) { } else DEBUG("Send M%d id=[%d] str=[%s]", i, odr.id, odr.str); } pthread_mutex_unlock(&ack_mutex); if (NTU_send_unit(B, &odr, DPW_order_size) < 0) { } else DEBUG("Send B id=[%d] str=[%s]", odr.id, odr.str); DPW_countack++; } pthread_exit(0); } void *DPW_FT_send_b_task(void *arg) { struct DPW_order odr; while (1) { odr.id = -1; if (NTU_send_unit(B, &odr, DPW_order_size) < 0) { } sleep(1); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void* thread1(void*arg) { pthread_cleanup_push(pthread_mutex_unlock,&mutex); while(1) { printf("thread1 is running\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread1 applied the condition\\n"); pthread_mutex_unlock(&mutex); sleep(1); } pthread_cleanup_pop(0); } void* thread2(void *arg) { while(1) { printf("thread2 is running\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread2 applied the condition\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(int argc, char *argv[]) { pthread_t tid1; pthread_t tid2; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1,0,(void*)thread1,0); pthread_create(&tid2,0,(void*)thread2,0); do { pthread_cond_signal(&cond); }while(1); sleep(50); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; static pthread_cond_t wait = PTHREAD_COND_INITIALIZER; static void* _thread1(void *__u ) { printf("1: obtaining mutex\\n"); pthread_mutex_lock(&lock); printf("1: waiting on condition variable\\n"); pthread_cond_wait(&wait, &lock); printf("1: releasing mutex\\n"); pthread_mutex_unlock(&lock); printf("1: exiting\\n"); return 0; } static void* _thread2(void *__u ) { int cnt = 2; while(cnt--) { printf("2: obtaining mutex\\n"); pthread_mutex_lock(&lock); printf("2: signaling\\n"); pthread_cond_signal(&wait); printf("2: releasing mutex\\n"); pthread_mutex_unlock(&lock); } printf("2: exiting\\n"); return 0; } static const thread_func thread_routines[] = { &_thread1, &_thread2, }; int main(void) { pthread_t t[2]; int nn; int count = (int)(sizeof t/sizeof t[0]); for (nn = 0; nn < count; nn++) { printf("main: creating thread %d\\n", nn+1); if (pthread_create( &t[nn], 0, thread_routines[nn], 0) < 0) { printf("main: could not create thread %d: %s\\n", nn+1, strerror(errno)); return -2; } } for (nn = 0; nn < count; nn++) { printf("main: joining thread %d\\n", nn+1); if (pthread_join(t[nn], 0)) { printf("main: could not join thread %d: %s\\n", nn+1, strerror(errno)); return -2; } } return 0; }
1
#include <pthread.h> int buffer[1024]; int count=0; pthread_mutex_t mutex1; pthread_mutex_t mutex2; int flag=0; void *threadFun1(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex1); printf("Thread 1\\n"); if(0==flag) { count++; flag=1; } pthread_mutex_unlock(&mutex2); } } void *threadFun2(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex2); printf("Thread 2\\n"); if(1==flag) { printf("Get:%d\\n",count); flag = 0; } pthread_mutex_unlock(&mutex1); } } int main() { pthread_t tid[2]; int ret=0; int i; int t_value[2]; void *(*threadFun[])(void*) = {threadFun1, threadFun2}; ret = pthread_mutex_init(&mutex1,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } ret = pthread_mutex_init(&mutex2,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex2); printf("Main thread before pthread create\\n"); for(i=0; i<2; i++) { t_value[i]=i; ret=pthread_create( &(tid[i]), 0, threadFun[i], (void*)&(t_value[i])); if(ret!=0) { fprintf(stderr, "pthread create error:%s", strerror(ret)); return 1; } } printf("Main thread after pthread create\\n"); for(i=0; i<2; i++) { ret = pthread_join(tid[i],0); if(ret!=0) { fprintf(stderr, "pthread join error:%s", strerror(ret)); return 2; } } ret = pthread_mutex_destroy(&mutex1); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex2); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } printf("All threads are over!\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t empty; int ncust; void* barber(void *arg) { while(1) { pthread_mutex_lock(&mutex); if(ncust == 0) { printf("barber Sleeping\\n"); pthread_cond_wait(&empty, &mutex); } sleep(rand() % 3); printf("Cutting Done\\n"); ncust--; pthread_mutex_unlock(&mutex); } } void* customer(void *arg) { int id = *((int *)arg); pthread_mutex_lock(&mutex); if(ncust <= 5) { ncust++; printf("Customer %d sat on chair\\n", id); pthread_cond_signal(&empty); } else { printf("Customer %d left the shop\\n", id); } pthread_mutex_unlock(&mutex); sleep(rand() % 3); } int main() { int id[10]; int i; for (i = 0; i < 10; ++i) id[i] = i; pthread_mutex_init(&mutex, 0); pthread_cond_init(&empty, 0); pthread_t barber_t, customer_t[10]; pthread_create(&barber_t, 0, barber, 0); for (i = 0; i < 10; ++i) pthread_create(&customer_t[i], 0, customer, (void *)&id[i]); pthread_join(barber_t, 0); for (i = 0; i < 10; ++i) pthread_join(customer_t[i], 0); return 0; }
1
#include <pthread.h> void *thread_func(void *p) { pthread_mutex_t *mutex = (pthread_mutex_t *)p; pthread_mutex_lock(mutex); pthread_mutex_unlock(mutex); return 0; } int test_main() { pthread_t thread; pthread_mutex_t mutex; if(pthread_mutex_init(&mutex, 0)) return 1; if(pthread_mutex_lock(&mutex)) return 1; if(pthread_create(&thread, 0, &thread_func, &mutex)) return 1; usleep(500); if(pthread_mutex_unlock(&mutex)) return 1; void *res; if(pthread_join(thread, &res)) return 1; if(pthread_mutex_destroy(&mutex)) return 1; return 0; } char const test_results[] = "[1] mutex_init(1, FAST)\\n" "[1] mutex_lock(1)\\n" "[2] started\\n" "[2] mutex_lock(1) <waiting for thread 1> ...\\n" "[1] mutex_unlock(1)\\n" "[2] ... mutex_lock(1)\\n" "[2] mutex_unlock(1)\\n" "[2] finished (normal exit)\\n" "[1] mutex_destroy(1)\\n"; unsigned int const test_results_len = sizeof test_results; bool const test_result_timeout = 0;
0
#include <pthread.h> char ipaddr[]="192.168.1.57"; int ipactual=1; pthread_mutex_t p; int ping(void) { char *command = 0; char buffer[1024]; FILE *fp; int stat = 0; asprintf (&command, "%s %s", "ping", ipaddr); printf("%s\\n", command); fp = popen(command, "r"); if (fp == 0) { fprintf(stderr, "Failed to execute fping command\\n"); free(command); return -1; } while(fread(buffer, sizeof(char), 1024, fp)) { if (strstr(buffer, "1 received")) return 0; } stat = pclose(fp); free(command); return 1; } void* pingtest(void* actual){ int *ptr= (int*) actual; pthread_mutex_lock (&p); ipactual=0; int status=ping(); if (status == 0) { printf("Could ping %s successfully, status %d\\n", ipaddr, status); } else { printf("Machine not reachable, status %d\\n", status); } pthread_mutex_unlock (&p); pthread_exit(0); } int main(int argc, char *argv[]){ int i, start, tids[10]; pthread_t threads[10]; pthread_attr_t attr; pthread_mutex_init(&p, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<10; i++) { tids[i] = i; pthread_create(&threads[i], &attr, pingtest, (void *) &ipactual); } for (i=0; i<10; i++) { pthread_join(threads[i], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&p); pthread_exit (0); }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void* producer(void* ptr) { int i; for(i=0; i<=10000000000; i++) { while(buffer != 0) { } pthread_cond_wait(&condp, &the_mutex); pthread_mutex_lock(&the_mutex); buffer = i; printf("produce a number %d to buffer", buffer); pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void* consumer(void* ptr) { int i; for(i=0; i<=10000000000; i++) { while(buffer == 0) { pthread_cond_wait(&condc, &the_mutex); } pthread_mutex_lock(&the_mutex); buffer = 0; printf("consumer a number from buffer"); pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void main(int argc, char **argv) { pthread_t pro; pthread_t con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condp, 0); pthread_cond_init(&condc, 0); pthread_create(&pro, 0, producer, &pro); pthread_create(&con, 0, consumer, &con); pthread_join(&pro, 0); pthread_join(&con, 0); sleep(10); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&condp); pthread_cond_destroy(&condc); }
0
#include <pthread.h> void *multiplicar_thread(void *arg); void gerar_matrizes(); void imprimir_matriz(FILE *arquivo, int **matriz); void imprimir_matrizes(); void liberar_matrizes(); pthread_mutex_t mutex; int **matriz1; int **matriz2; int **resultado; int tamanho_matriz; int linha_atual, coluna_atual; void *multiplicar_thread(void *arg) { int i = 0; int linha_thread = 0; int coluna_thread = 0; while (linha_atual < tamanho_matriz) { pthread_mutex_lock(&mutex); linha_thread = linha_atual; coluna_thread = coluna_atual; coluna_atual += 1; if (coluna_atual >= tamanho_matriz) { coluna_atual = 0; linha_atual += 1; } pthread_mutex_unlock(&mutex); for (i = 0; i < tamanho_matriz; i++) { resultado[linha_thread][coluna_thread] += matriz1[linha_thread][i] * matriz2[i][coluna_thread]; } } } void main(int argc, char* argv[]) { if (argc < 3) { printf("Use: %s [tamanho da matriz] [threads]\\n", argv[0]); return; } printf("conter "); tamanho_matriz = atoi(argv[1]); int num_threads = atoi(argv[2]); linha_atual = 0; coluna_atual = 0; gerar_matrizes(); pthread_mutex_init(&mutex, 0); int i; pthread_t threads[num_threads]; for (i = 0; i < num_threads; i++) { pthread_create(&threads[i], 0, multiplicar_thread, (void*)&i); } for (i = 0; i < num_threads; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); imprimir_matrizes(); liberar_matrizes(); } void gerar_matrizes() { srand(time(0)); matriz1 = malloc(tamanho_matriz * sizeof(int *)); matriz2 = malloc(tamanho_matriz * sizeof(int *)); resultado = malloc(tamanho_matriz * sizeof(int *)); int i, j; for (i = 0; i < tamanho_matriz; i++) { matriz1[i] = malloc(tamanho_matriz * sizeof(int)); matriz2[i] = malloc(tamanho_matriz * sizeof(int)); resultado[i] = malloc(tamanho_matriz * sizeof(int)); for (j = 0; j < tamanho_matriz; j++) { matriz1[i][j] = rand()%10; matriz2[i][j] = rand()%10; resultado[i][j] = 0; } } } void imprimir_matriz(FILE *arquivo, int **matriz) { int i, j; for (i = 0; i < tamanho_matriz; i++) { for (j = 0; j < tamanho_matriz; j++) { fprintf(arquivo, "%d ", matriz[i][j]); } fprintf(arquivo, "\\n"); } fprintf(arquivo, "\\n"); } void imprimir_matrizes() { FILE *arquivo; arquivo = fopen("resultado.txt", "w"); if (arquivo == 0) { printf("Erro ao abrir arquivo de resultados!\\n"); exit(1); } fprintf(arquivo, "Matriz 1\\n"); imprimir_matriz(arquivo, matriz1); fprintf(arquivo, "Matriz 2\\n"); imprimir_matriz(arquivo, matriz2); fprintf(arquivo, "Resultado 2\\n"); imprimir_matriz(arquivo, resultado); fclose(arquivo); } void liberar_matrizes() { int i; for (i = 0; i < tamanho_matriz; i++) { free(matriz1[i]); free(matriz2[i]); free(resultado[i]); } free(matriz1); free(matriz2); free(resultado); }
1
#include <pthread.h> void*handler(void*num); int isPrime(int64_t n); pthread_mutex_t count_mutex; volatile int64_t count = 0; volatile int64_t numbersfound = 0; int isPrime(int64_t n) { printf("num %ld\\n", n); if( n <= 1) return 0; if( n <= 3) return 1; if( n % 2 == 0 || n % 3 == 0) return 0; int64_t i = 5; int64_t max = sqrt(n); while( i <= max) { if (n % i == 0 || n % (i+2) == 0) return 0; i += 6; } return 1; } int main( int argc, char ** argv) { int nThreads; if( argc != 1 && argc != 2) { printf("Uasge: countPrimes [nThreads]\\n"); exit(-1); } if( argc == 2) nThreads = atoi( argv[1]); if( nThreads < 1 || nThreads > 256) { printf("Bad arguments. 1 <= nThreads <= 256!\\n"); } pthread_mutex_init(&count_mutex, 0); pthread_t threads[nThreads]; printf("Counting primes using %d thread%s.\\n", nThreads, nThreads == 1 ? "" : "s"); long indexer; for(indexer =1;indexer<=nThreads;indexer++){ if( 0 != pthread_create(&threads[(indexer-1)],0,handler,(void*)indexer)){ printf("Oops, pthread_create failed.\\n"); exit(-1); }} for(indexer=1;indexer<=nThreads;indexer++){ pthread_join(threads[(indexer-1)],0);} pthread_mutex_destroy(&count_mutex); printf("Found %ld primes.\\n", count); return 0; } void*handler(void*num){ while( 1) { int64_t num; pthread_mutex_lock(&count_mutex); if( 1 != scanf("%ld", & num)) { pthread_mutex_unlock(&count_mutex); break;} pthread_mutex_unlock(&count_mutex); if( isPrime(num)) count ++; } }
0
#include <pthread.h> FILE* file; int iter =1; struct Data { int num_th; char str_find[1024]; int socket_ac; }; struct { pthread_mutex_t mutex; int buff[1000000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; void *thread_func(void* arg) { data *str_find=(data *)arg; char buf[1024]; char answer[4]; if(send(str_find->socket_ac, str_find->str_find, sizeof(str_find->str_find), MSG_WAITALL)==-1) { printf("Сервер: не отправил сообщение\\n"); } printf("Сервер: отправил строку для поиска\\n"); while(!feof(file)) { pthread_mutex_lock(&shared.mutex); fscanf(file,"%s", &buf); if(send(str_find->socket_ac, buf, sizeof(buf), MSG_WAITALL)==-1) { printf("Сервер: не отправил сообщение\\n"); } if(recv(str_find->socket_ac, answer, sizeof(answer), MSG_DONTROUTE)) { if(!strcmp(answer, "Yes")) { printf("thread№%d str№%d \\e[31m %s \\e[0m\\n", str_find->num_th, iter , buf); } } iter++; pthread_mutex_unlock(&shared.mutex); } strcpy(buf, "FEOF_END_FILE"); send(str_find->socket_ac, buf, sizeof(buf)+1, MSG_WAITALL); pthread_exit(0); } int input(int *col_thread, char *str_find, char *file_name) { printf("Введите имя файла\\n"); scanf("%s", file_name); printf("Введите строку колторую надо искать\\n"); scanf("%s", str_find); printf("Введите количество обработчиков строк\\n"); scanf("%d", col_thread); return 0; } int main(int argc, char* argv[]) { int socket1, socket_ac; struct sockaddr_in st_addr; int col_thread; int id; int error_ac=0; if((socket1 = socket(AF_INET, SOCK_STREAM, 0)) == -1) { printf("Сервер: ошибка при создании сокета\\n"); close(socket1); exit(1); } st_addr.sin_family= AF_INET; st_addr.sin_addr.s_addr=INADDR_ANY; st_addr.sin_port=htons(2524); int check = bind(socket1, (struct sockaddr *)&st_addr, sizeof(st_addr)); if(check<0) { printf("Сервер: ошибка в bind\\n"); close(socket1); exit(1); } printf("Сервер слушает сокет\\n"); char str_find[1024]; char file_name[1024]; input(&col_thread, str_find, file_name); void *status[col_thread]; data str_find_num[col_thread]; file=fopen(file_name, "r"); pthread_t *threads = (pthread_t *)malloc(sizeof(pthread_t)*col_thread); printf("%s %s %d\\n", str_find, file_name, col_thread); if(listen(socket1, 5)==-1) { printf("Ошибка в процесск прослушивания для сервера!\\n"); close(socket1); exit(1); } printf("Сервер: слушает сокет \\n"); for(int i = 0;i<col_thread; i++) { if((socket_ac = accept(socket1, 0, 0))==-1) { printf("Сервер: аксепт фэйл\\n"); error_ac++; if(error_ac==col_thread-1) { printf("Сервер: все аксепты провалены\\n"); close(socket1); exit(1); } } str_find_num[i].num_th = i; strcpy(str_find_num[i].str_find, str_find); str_find_num[i].socket_ac=socket_ac; int result=pthread_create(&threads[i], 0, thread_func, &str_find_num[i]); if(result != 0) { printf("Проблемы с трэдами\\n"); perror("Can`t creating thread\\n"); exit(1); fclose(file); } printf("Тред создан\\n"); } for(int i = 0;i < col_thread; i++) { int result=pthread_join(threads[i], &status[i]); if(result != 0) { perror("Joining thread`s"); return 1; } else { printf("square[%d]= %f\\n", i, (double*)status[i]); } free(status[i]); } close(socket1); fclose(file); exit(0); }
1
#include <pthread.h> void interrupt1() { fprintf(stdout, "Arrival thread exiting\\n"); return; } void *handler1() { struct sigaction act; sigset_t sig; act.sa_handler = interrupt1; sigaction(SIGUSR1, &act, 0); sigemptyset(&sig); sigaddset(&sig, SIGUSR1); pthread_sigmask(SIG_UNBLOCK, &sig, 0); return 0; } void* arrivalFunc(void * arg) { Packet *packet; int result; int count = 0, pack_count = 0; double inter_arrival; long int timestamp, start_time, laststart_time; FILE *fp = 0; sigset_t sig; sigemptyset(&sig); sigaddset(&sig, SIGINT); pthread_sigmask(SIG_BLOCK, &sig, 0); handler1(); fp = (FILE *)arg; laststart_time = emulationTime; start_time = emulationTime; while(1){ if(fp){ packet = getPacket(fp, &result); if(!packet) { sigHit = 1; fprintf(stdout, "\\nFile: number of inputs does not match the foresaid number of packets\\n\\n"); goto thread_exit; } } else{ packet = getPacket(0, &result); } count++; pack_count++; packet->val = pack_count; if(packet->P > packet->Bucket){ fprintf(stdout,"%012.3lfms: packet p%d arrives, needs %d tokens, dropped\\n", relativeTimeinDouble(getTime()), packet->val, packet->P); free(packet); Stat.pack_drop++; count --; Param.packet_num --; if(count == Param.packet_num){ sigHit = 1; goto thread_exit; } continue; } timestamp = packet->lambda; if(sigHit){ goto thread_exit; } timestamp = timestamp - (getTime() - start_time); if(timestamp <= 0){ fprintf(stdout, "timestamp value is going negative value, ignoring sleep\\n"); } else{ usleep(timestamp); } if(sigHit){ goto thread_exit; } start_time = getTime(); packet->start_time = start_time; inter_arrival =(double)(start_time - laststart_time)/1000.00; Stat.arrival = Stat.arrival + inter_arrival; Stat.act_pack++; fprintf(stdout,"%012.3lfms: p%d arrives, needs %d tokens, inter arrival time = %lfms\\n", relativeTimeinDouble(getTime()), packet->val, packet->P, inter_arrival); pthread_mutex_lock(&mutex); if(checkQueueEmpty(1)){ if(checkToken(packet->P)){ removeTokens(packet->P); fprintf(stdout,"%012.3lfms: p%d enters Q2\\n", relativeTimeinDouble(getTime()), packet->val); pushQueue(2, packet); packet->Q2 = getTime(); processedPacket++; if(!wakeupServer() && sigHit){ pthread_exit(0); return 0; } }else { fprintf(stdout,"%012.3lfms: p%d enters Q1\\n", relativeTimeinDouble(getTime()), packet->val); pushQueue(1, packet); packet->Q1 = getTime(); Stat.pack_Q1++; pthread_mutex_unlock(&mutex); } }else{ fprintf(stdout,"%012.3lfms: p%d enters Q1\\n", relativeTimeinDouble(getTime()), packet->val); pushQueue(1, packet); Stat.pack_Q1++; packet->Q1 = getTime(); pthread_mutex_unlock(&mutex); } if(sigHit){ goto thread_exit; } laststart_time = start_time; if(count == Param.packet_num){ break; } } pthread_exit((void *) 0); return (void *)0; thread_exit: pthread_mutex_lock(&mutex); packetCount = 0; printf("Iam here\\n"); unlinkQueue(1); unlinkQueue(2); pthread_cond_broadcast(&processQueue); pthread_mutex_unlock(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> int *mem; pthread_mutex_t mtx; void *Thread1(void *x) { pthread_mutex_lock(&mtx); free(mem); pthread_mutex_unlock(&mtx); return 0; } void *Thread2(void *x) { sleep(1); pthread_mutex_lock(&mtx); mem[0] = 42; pthread_mutex_unlock(&mtx); return 0; } int main() { mem = (int*)malloc(100); pthread_mutex_init(&mtx, 0); pthread_t t; pthread_create(&t, 0, Thread1, 0); Thread2(0); pthread_join(t, 0); pthread_mutex_destroy(&mtx); return 0; }
1
#include <pthread.h> static int __rg_quorate = 0; static int __rg_lock = 0; static int __rg_threadcnt = 0; static int __rg_initialized = 0; static int _rg_statuscnt = 0; static int _rg_statusmax = 5; static int _rg_childcnt = 0; static int _rg_childmax = 0; static pthread_cond_t unlock_cond = PTHREAD_COND_INITIALIZER; static pthread_cond_t zero_cond = PTHREAD_COND_INITIALIZER; static pthread_cond_t init_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t locks_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t _ccs_mutex = PTHREAD_MUTEX_INITIALIZER; int rg_initialized(void) { int ret; pthread_mutex_lock(&locks_mutex); ret = __rg_initialized; pthread_mutex_unlock(&locks_mutex); return ret; } int rg_set_initialized(int flag) { if (!flag) flag = ~0; pthread_mutex_lock(&locks_mutex); __rg_initialized |= flag; pthread_cond_broadcast(&init_cond); pthread_mutex_unlock(&locks_mutex); return 0; } int rg_clear_initialized(int flag) { if (!flag) flag = ~0; pthread_mutex_lock(&locks_mutex); __rg_initialized &= ~flag; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_wait_initialized(int flag) { pthread_mutex_lock(&locks_mutex); if (flag) { while ((__rg_initialized & flag) != flag) pthread_cond_wait(&init_cond, &locks_mutex); } else { while (!__rg_initialized) pthread_cond_wait(&init_cond, &locks_mutex); } pthread_mutex_unlock(&locks_mutex); return 0; } int ccs_lock(void) { int ret; pthread_mutex_lock(&_ccs_mutex); ret = ccs_connect(); if (ret < 0) { pthread_mutex_unlock(&_ccs_mutex); return -1; } return ret; } int ccs_unlock(int fd) { int ret; ret = ccs_disconnect(fd); pthread_mutex_unlock(&_ccs_mutex); if (ret < 0) { return -1; } return 0; } int rg_lockall(int flag) { pthread_mutex_lock(&locks_mutex); if (!__rg_lock) __rg_lock |= flag; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_locked(void) { int ret; pthread_mutex_lock(&locks_mutex); ret = __rg_lock; pthread_mutex_unlock(&locks_mutex); return ret; } int rg_unlockall(int flag) { pthread_mutex_lock(&locks_mutex); if (__rg_lock) __rg_lock &= ~flag; pthread_cond_broadcast(&unlock_cond); pthread_mutex_unlock(&locks_mutex); return 0; } int rg_set_quorate(void) { pthread_mutex_lock(&locks_mutex); if (!__rg_quorate) __rg_quorate = 1; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_set_inquorate(void) { pthread_mutex_lock(&locks_mutex); if (__rg_quorate) __rg_quorate = 0; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_quorate(void) { int ret; pthread_mutex_lock(&locks_mutex); ret = __rg_quorate; pthread_mutex_unlock(&locks_mutex); return ret; } int rg_inc_threads(void) { pthread_mutex_lock(&locks_mutex); ++__rg_threadcnt; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_dec_threads(void) { pthread_mutex_lock(&locks_mutex); --__rg_threadcnt; if (__rg_threadcnt <= 0) { __rg_threadcnt = 0; pthread_cond_broadcast(&zero_cond); } pthread_mutex_unlock(&locks_mutex); return 0; } int rg_set_statusmax(int max) { int old; if (max <= 3) max = 3; pthread_mutex_lock(&locks_mutex); old = _rg_statusmax; _rg_statusmax = max; pthread_mutex_unlock(&locks_mutex); return old; } int rg_inc_status(void) { pthread_mutex_lock(&locks_mutex); if (_rg_statuscnt >= _rg_statusmax) { pthread_mutex_unlock(&locks_mutex); return -1; } ++_rg_statuscnt; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_dec_status(void) { pthread_mutex_lock(&locks_mutex); --_rg_statuscnt; if (_rg_statuscnt < 0) _rg_statuscnt = 0; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_set_childmax(int max) { int old; if (max <= 1) max = 1; pthread_mutex_lock(&locks_mutex); old = _rg_childmax; _rg_childmax = max; pthread_mutex_unlock(&locks_mutex); return old; } int rg_inc_children(void) { pthread_mutex_lock(&locks_mutex); if (_rg_childmax && (_rg_childcnt >= _rg_childmax)) { pthread_mutex_unlock(&locks_mutex); return -1; } ++_rg_childcnt; pthread_mutex_unlock(&locks_mutex); return 0; } int rg_dec_children(void) { pthread_mutex_lock(&locks_mutex); --_rg_childcnt; if (_rg_childcnt < 0) { assert(0); _rg_childcnt = 0; } pthread_mutex_unlock(&locks_mutex); return 0; } int rg_wait_threads(void) { pthread_mutex_lock(&locks_mutex); if (__rg_threadcnt) pthread_cond_wait(&zero_cond, &locks_mutex); pthread_mutex_unlock(&locks_mutex); return 0; }
0
#include <pthread.h> struct send_arg { struct queue* queue; char* host; int port; }; void multi_send(char* buf, int len, char* host, int port, int num_conn); void* queue_send(void*); void fill_queue(char* buf, int len, struct queue* q); int listen_for_blocks(struct mp_writer_init* arg); int min(int n, int m); void *multiplex_writer_init(void* arg) { struct mp_writer_init* init_params = (struct mp_writer_init*) arg; listen_for_blocks(init_params); return 0; } int listen_for_blocks(struct mp_writer_init* arg) { while (1) { pthread_mutex_lock(&arg->queue->mutex); while (is_empty(arg->queue)) { pthread_cond_wait(&arg->queue->cv, &arg->queue->mutex); } char* buf; int buf_len = dequeue(arg->queue, &buf); pthread_mutex_unlock(&arg->queue->mutex); send_tcp(buf, buf_len, arg->client_fd); free(buf); } } void write_block_to_queue(struct queue* queue, char* block, int block_size) { pthread_mutex_lock(&queue->mutex); enqueue(queue, block, block_size); pthread_cond_signal(&queue->cv); pthread_mutex_unlock(&queue->mutex); } void multiplex_write_queues(struct queue** queues, int num_queues, char* buffer, int buf_len, int *next_tag) { int prev_tag = *next_tag; int tag = ++(*next_tag); struct init_block* init = (struct init_block*) malloc(sizeof(struct init_block)); init->flag = -1; init->block_size = sizeof(struct init_block); init->buffer_size = buf_len; init->tag = tag; init->prev_tag = prev_tag; init->last_block = 0; write_block_to_queue(queues[num_queues - 1], (char*) init, sizeof(struct init_block)); int unif_size; float divisor; for (divisor = 1.0; buf_len / (divisor * num_queues) > BLOCK_SIZE; divisor ++); unif_size = buf_len / (divisor * num_queues); for (int i = 0; i < buf_len; i += unif_size) { uint32_t actual_size = min(unif_size, buf_len - i); char* headered_block = (char*) malloc(sizeof(struct data_block) + actual_size); if (headered_block == 0) { fprintf(stderr, "Could not malloc new block in multiplex_writer: errno %d\\n", errno); exit(1); } struct data_block header; header.block_size = actual_size + sizeof(struct data_block); header.seq_number = i; header.tag = tag; memcpy((void*) headered_block, &header, sizeof(struct data_block)); memcpy((void*) (headered_block + sizeof(struct data_block)), (void*) &(buffer[i]), actual_size); write_block_to_queue(queues[i % num_queues], headered_block, sizeof(struct data_block) + actual_size); } } int min(int n, int m) { return n > m ? m : n; }
1
#include <pthread.h> void *thread_scheduler(void *arg) { unsigned int schedalg=*((unsigned int*)arg); int acceptfd,n; if(schedalg==0) { while(1) { if(front!=NULL) { sem_wait(&sem); pthread_mutex_lock(&sthread_mutex); pthread_mutex_lock(&qmutex); r2=extract_element(); pthread_mutex_unlock(&qmutex); pthread_cond_signal(&cond_var); free_thread--; pthread_mutex_unlock(&sthread_mutex); } else { continue; } } } else { int shortestjob_fd=0; int min; int a,b; while(1) { pthread_mutex_lock(&qmutex); temp=front; if (temp==NULL) { continue; } else if(temp->link==NULL) { shortestjob_fd=temp->r.acceptfd; } else { min=temp->r.size; while(temp->link!=NULL) { b=temp->link->r.size; if(min<=b) { shortestjob_fd=temp->r.acceptfd; } else if(min>b) { min=temp->link->r.size; shortestjob_fd=temp->link->r.acceptfd; } printf("\\n %d",a); temp=temp->link; } } pthread_mutex_lock(&sthread_mutex); r2=removesjf(shortestjob_fd); pthread_cond_signal(&cond_var); pthread_mutex_unlock(&sthread_mutex); pthread_mutex_unlock(&qmutex); } } }
0
#include <pthread.h> int main(int argc, char *argv[]){ pthread_mutex_init(&Tlock_input, 0); pthread_mutex_init(&Tlock_cubes, 0); pthread_mutex_init(&Tsync_cubes, 0); pthread_mutex_lock(&Tlock_cubes); pthread_create(&Tevent, 0, Tevent_loop, 0); pthread_create(&Tmap_sync, 0, Tsync_loop, 0); Iinit_config(&config); Iconfig(); Iinit_screen(); Iload_block_textures(); pthread_mutex_unlock(&Tlock_cubes); Tgraphic_loop(); pthread_join(Tevent, 0); pthread_join(Tmap_sync, 0); printf("\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex_s = PTHREAD_MUTEX_INITIALIZER; int suma[10000000]; int sumas = 0; FILE *fp; void * sumar(void * arg) { int tid = (int) arg; int i = 0; while (feof(fp) == 0) { pthread_mutex_lock(&mutex_s); fscanf(fp, "%d", &suma[i]); sumas += suma[i]; ++i; pthread_mutex_unlock(&mutex_s); } pthread_exit(0); } int main(int argc, const char * argv[]) { time_t start,end; double dif; fp = fopen ( "fichero1.txt", "r" ); pthread_t * tid; int nhilos; int i; nhilos = 1; tid = malloc(nhilos * sizeof(pthread_t)); time (&start); for (i = 0; i < nhilos; ++i) { pthread_create(tid + i, 0, sumar, (void *)0); } for (i = 0; i < nhilos; ++i) { pthread_join(*(tid+i), 0); } time (&end); dif = difftime (end,start); printf("Suma = %d\\n", sumas); printf ("Your calculations took %.2lf seconds to run.\\n", dif ); free(tid); return 0; }
0
#include <pthread.h> int hilos_entradaActivo; int active_work; void *KEY; int bufSize = 0; FILE *file_in; FILE *file_out; pthread_mutex_t mutexIN; pthread_mutex_t mutexWORK; pthread_mutex_t mutexOUT; char data; off_t offset; char state; } BufferItem; BufferItem *result; void thread_sleep(void); int estaELbufferVacio(); int vaciarArchivoAbuffer(); int hilosTrabajadoresSobreBuffer(); int hilosEncriptadoresSobreBuffer(); void inicializarBuffer(); void *IN_thread(void *param); void *WORK_thread(void *param); void *OUT_thread(void *param); int main(int argc, char *argv[]){ int i = 0; int nIN; int nOUT; int nWORK; pthread_mutex_init(&mutexIN, 0); pthread_mutex_init(&mutexWORK, 0); pthread_mutex_init(&mutexOUT, 0); if(strcmp(argv[1],"-e")==0) nIN = atoi(argv[2]); nWORK=nIN; KEY = "-3"; if(strcmp(argv[3],"-d")==0) nOUT = atoi(argv[4]); if(strcmp(argv[5],"-m")==0) file_in = fopen(argv[6], "r"); if(strcmp(argv[7],"-f")==0) file_out = fopen(argv[8], "w"); bufSize = 5; hilos_entradaActivo = nIN; active_work = nWORK; pthread_t INthreads[nIN]; pthread_t OUTthreads[nOUT]; pthread_t WORKthreads[nWORK]; pthread_attr_t attr; pthread_attr_init(&attr); result = (BufferItem*)malloc(sizeof(BufferItem)*bufSize); inicializarBuffer(); int keyCheck = atoi(KEY); for (i = 0; i < nIN; i++){ pthread_create(&INthreads[i], &attr, (void *) IN_thread, file_in); } for (i = 0; i < nWORK; i++){ pthread_create(&WORKthreads[i], &attr, (void *) WORK_thread, KEY); } for (i = 0; i < nOUT; i++){ pthread_create(&OUTthreads[i], &attr, (void *) OUT_thread, file_out); } for (i = 0; i < nIN; i++){ pthread_join(INthreads[i], 0); } for (i = 0; i < nWORK; i++){ pthread_join(WORKthreads[i], 0); } for (i = 0; i < nOUT; i++){ pthread_join(OUTthreads[i], 0); } pthread_mutex_destroy(&mutexIN); pthread_mutex_destroy(&mutexOUT); pthread_mutex_destroy(&mutexWORK); fclose(file_in); fclose(file_out); free(result); return 0; } void thread_sleep(void){ struct timespec t; int seed = 0; t.tv_sec = 0; t.tv_nsec = rand_r((unsigned int*)&seed)%(10000000+1); nanosleep(&t, 0); } int estaELbufferVacio(){ int i = 0; while (i < bufSize){ if (result[i].state == 'e'){ return 1; } i++; } return 0; } int vaciarArchivoAbuffer(){ int i = 0; if (estaELbufferVacio()){ while (i < bufSize){ if (result[i].state == 'e'){ return i; } i++; } } return -1; } int hilosTrabajadoresSobreBuffer(){ int i = 0; while (i < bufSize){ if (result[i].state == 'w'){ return i; } i++; } return -1; } int hilosEncriptadoresSobreBuffer(){ int i = 0; while (i < bufSize){ if (result[i].state == 'o'){ return i; } i++; } return -1; } void inicializarBuffer(){ int i = 0; while (i < bufSize){ result[i].state = 'e'; i++; } } void *IN_thread(void *param){ int index; char curr; off_t offset; thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = vaciarArchivoAbuffer(); while (index > -1){ if (estaELbufferVacio() == 1) { thread_sleep(); } pthread_mutex_lock(&mutexIN); offset = ftell(file_in); curr = fgetc(file_in); pthread_mutex_unlock(&mutexIN); if (curr == EOF){ break; } else{ result[index].offset = offset; result[index].data = curr; result[index].state = 'w'; index = vaciarArchivoAbuffer(); } } pthread_mutex_unlock(&mutexWORK); } while (!feof(file_in)); thread_sleep(); pthread_mutex_lock(&mutexWORK); hilos_entradaActivo--; pthread_mutex_unlock(&mutexWORK); return 0; } void *WORK_thread(void *param){ int index = 0; int local_active_in; char curr; int key = atoi(param); thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = hilosTrabajadoresSobreBuffer(); if (index > -1){ curr = result[index].data; if (estaELbufferVacio() == 1) { thread_sleep(); } if (curr == EOF || curr == '\\0'){ break; } if (key >= 0 && curr > 31 && curr < 127){ curr = (((int)curr-32)+2*95+key)%95+32; } else if (key < 0 && curr > 31 && curr < 127){ curr = (((int)curr-32)+2*95-(-1*key))%95+32; } result[index].data = curr; result[index].state = 'o'; } local_active_in = hilos_entradaActivo; pthread_mutex_unlock(&mutexWORK); } while (index > -1 || local_active_in > 0); thread_sleep(); pthread_mutex_lock(&mutexWORK); active_work--; pthread_mutex_unlock(&mutexWORK); return 0; } void *OUT_thread(void *param){ int index = 0; char curr; off_t offset; int local_active_work; thread_sleep(); do { pthread_mutex_lock(&mutexWORK); index = hilosEncriptadoresSobreBuffer(); if (index > -1){ offset = result[index].offset; curr = result[index].data; if (estaELbufferVacio() == 1) { thread_sleep(); } pthread_mutex_lock(&mutexOUT); if (fseek(file_out, offset, 0) == -1) { fprintf(stderr, "error %u\\n", (unsigned int) offset); exit(-1); } if (fputc(curr, file_out) == EOF) { fprintf(stderr, "error %d \\n", curr); exit(-1); } pthread_mutex_unlock(&mutexOUT); result[index].data = '\\0'; result[index].state = 'e'; result[index].offset = 0; } local_active_work = active_work; pthread_mutex_unlock(&mutexWORK); } while (index > -1 || local_active_work > 0); thread_sleep(); return 0; }
1
#include <pthread.h>void chanMsg(char *msg,char *channel,int sockfd) { char buffer[SIZE+SIZE]; sprintf(buffer,"PRIVMSG %s :%s",channel,msg); OUT(sockfd,buffer); } void OUT(int sockfd,char *message) { if(timecheck) { send(sockfd,message,strlen(message),0); timecheck=0; } send(sockfd,message,strlen(message),0); } int Send(int sockfd) { char bufz[SIZE]; char buf[SIZE]; char channel[SIZE]; strcpy(channel,defchan); int buffer[SIZE]; mainOnjoin(sockfd); int test=1; int n; while(test==1) { fgets(buf,SIZE,stdin); zap_all (buf); pthread_mutex_lock(&mutex); sprintf(buffer,"%s \\r\\n\\0",buf); outParse(buffer,sockfd,channel); pthread_mutex_unlock(&mutex); if(n<0) error("ERROR writing to socket"); } exit_flag=1; return 1; } void *Recieve(void *sock) { char buf[SIZE]; int test=1; int n; int sockfd = (int) sock; while(test==1) { if (exit_flag) { exit(0); break; } n=read(sockfd,buf,1024); if(n<0) { printf("ERROR reading from socket\\n"); exit(1); } else if (n > 0) { buf[n] = '\\0'; inParse(buf,sockfd); clearstr(buf); } } pthread_exit (NULL); } void PINGING(int sockfd) { while(1) { sleep(1); printf("%d\\n",timecheck); timecheck++; } }
0
#include <pthread.h> static pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER; void print_char(int fh, char *c) { int t=0; while (c[t]!=0) t++; write(fh,c,t); } int int2char(char* x,unsigned long i) { if (i==0) { return 0; } int k=int2char(&x[0],i/10); x[k]='0'+(i%10); x[k+1]=0; return k+1; } void print_number(int fh, long i) { char buffer[39]; if (i==0) { print_char(fh,"0"); } else { if (i<0) { buffer[0]='-'; int2char(&buffer[1],-i); } else { int2char(buffer,i); } print_char(fh,buffer); } } void sighandler(int sig) { print_char(2,"signal handler called in thread "); print_number(2,(long)pthread_self()); print_char(2," - signal "); print_number(2,sig); print_char(2,"\\n"); } void* threadstart(void* arg) { struct timespec timeout; int t; print_char(2,"thread "); print_number(2,(long)pthread_self()); print_char(2," started \\n"); while (1) { print_char(2,"getting mutex\\n"); pthread_mutex_lock(&Mutex); print_char(2,"got mutex\\n"); for (t=0;t<20;t++) { timeout.tv_sec=1; timeout.tv_nsec=0; nanosleep(&timeout,0); print_char(2,"thread "); print_number(2,(long)pthread_self()); print_char(2," still running...\\n"); } pthread_mutex_unlock(&Mutex); sleep(1); } } int main(char** argc, int argv) { pthread_t testthread1; pthread_t testthread2; struct sigaction action; print_char(2,"thread test program\\n\\n"); print_char(2,"demonstrate print function\\n"); long t=1; while (t!=0) { print_number(2,t); print_char(2," >> "); t=(t>0)?t*2:t/2; } print_number(2,t); print_char(2,"\\ndone\\n\\n"); print_char(2,"installing signal handler\\n"); action.sa_handler=sighandler; action.sa_flags=0; sigfillset( &action.sa_mask ); sigaction(SIGUSR1,&action,0); sleep(5); print_char(2,"starting thread 1\\n"); pthread_create(&testthread1,0,threadstart,0); sleep(5); print_char(2,"starting thread 2\\n"); pthread_create(&testthread2,0,threadstart,0); while (1) { sleep(5); print_char(2,"sending SIG_USR1 to thread 1\\n"); pthread_kill(testthread1,SIGUSR1); sleep(5); print_char(2,"sending SIG_USR1 to thread 2\\n"); pthread_kill(testthread2,SIGUSR1); } }
1
#include <pthread.h> int beers = 2000000; pthread_mutex_t a_lock = PTHREAD_MUTEX_INITIALIZER; void* drink_lots(void *a) { int i = 0; pthread_mutex_lock(&a_lock); for (i = 0; i < 100000; ++i) { beers -= 1; } pthread_mutex_unlock(&a_lock); printf("beers = %i\\n", beers); return 0; } int main() { pthread_t threads[20]; int t = 0; printf("%i bottles of beer on the wall \\n%ibottles of beer\\n", beers, beers); for(t = 0; t < 20; ++t) { pthread_create(&threads[t], 0, drink_lots, 0); } void *result; for(t = 0; t < 20; ++t) { pthread_join(threads[t], &result); } printf("\\n%i bottles of beer on wall left\\n", beers); return 0; }
0
#include <pthread.h> int buffer[100]; int count=0; pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t signal_c= PTHREAD_COND_INITIALIZER; pthread_cond_t signal_p= PTHREAD_COND_INITIALIZER; void printfunction(void * ptr) { if (count==0) { printf("All items produced are consumed by the consumer \\n"); } else { for (int i=0; i<=count; i=i+1) { printf("%d, \\t",buffer[i]); } printf("\\n"); } } void *producer(void *ptr) { while (count<100) { pthread_mutex_lock(&mutex); count ++; printf("Producer : %d\\n", count); pthread_cond_signal(&signal_c); if (count != 100) pthread_cond_wait(&signal_p, &mutex); pthread_mutex_unlock(&mutex); if (count == 100) { printf("Producer done.. !!\\n"); break; } } } void *consumer(void *ptr) { int printed= 0; do { while (count>0) { pthread_mutex_lock(&mutex); pthread_cond_signal(&signal_p); pthread_cond_wait(&signal_c, &mutex); printf("Consumer : %d\\n", count); pthread_mutex_unlock(&mutex); if (count == 100) { printf("Consumer done.. !!\\n"); break; } } } while(count>=0); } void main() { count= 0; pthread_t pro, con; pthread_create(&pro, 0, producer, &count); pthread_create(&con, 0, consumer, &count); pthread_join(pro, 0); pthread_join(con, 0); printfunction(&count); }
1
#include <pthread.h> COMFOME, PENSANDO, COMENDO, } Filosofo; pthread_mutex_t garfos; Filosofo *filosofos; int nfilosofo; void *ffuncao(void *f) { int fid = (int) f; while (1) { pthread_mutex_lock (&garfos); switch (filosofos[fid]) { case PENSANDO: filosofos[fid] = COMFOME; pthread_mutex_unlock(&garfos); fprintf(stdout, "F[%d]: Estou pensando...\\n", fid); sleep((random()%5)); break; case COMFOME: fprintf(stdout, "F[%d]: Estou com fome... Vou tentar pegar os garfos!\\n", fid); if (filosofos[((fid + nfilosofo - 1) % nfilosofo)] == COMENDO) { pthread_mutex_unlock(&garfos); fprintf (stdout, "\\tFilosofo %d estah comendo...\\n", ((fid + nfilosofo - 1) % nfilosofo)); } else if (filosofos[((fid + 1) % nfilosofo)] == COMENDO) { pthread_mutex_unlock(&garfos); fprintf (stdout, "\\tFilosofo %d estah comendo...\\n", ((fid + 1) % nfilosofo)); } else { filosofos[fid] = COMENDO; pthread_mutex_unlock(&garfos); fprintf (stdout, "\\tAgora sim, vou comer!\\n"); } sleep((random()%5)); break; case COMENDO: filosofos[fid] = PENSANDO; pthread_mutex_unlock(&garfos); fprintf(stdout, "F[%d]: Ja comido, voltando a pensar...\\n", fid); sleep((random()%5)); break; } } } int main (int argc, char **argv) { int i; pthread_t *t; if (argc > 1) { char **endptr = 0; nfilosofo = (int) strtol(argv[1], endptr, 10); if (endptr) { fprintf (stderr, "Argumento invalido: %s\\n", argv[1]); return 1; } } else { nfilosofo = 5; } filosofos = (Filosofo *) calloc (nfilosofo, sizeof(Filosofo)); if (!filosofos) { fprintf(stderr, "OS filosofos estao cansados. Nao querem pensar hoje...\\n"); return 1; } t = (pthread_t *) calloc (nfilosofo, sizeof(pthread_t)); if (!t) { fprintf (stderr, "Executar ou nao executar, eis a questao...\\n"); return 1; } pthread_mutex_init (&garfos, 0); for (i = 0 ; i < nfilosofo ; i++) { filosofos[i] = PENSANDO; pthread_create (&t[i], 0, ffuncao, (void *) i); } for (i = 0 ; i < nfilosofo ; i++) { pthread_join(t[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t printerMutex; void printMessage(const char* message_template, ...) { lockPrinter(); va_list arguments; __builtin_va_start((arguments)); char* message = string_from_vformat(message_template, arguments); puts(message); printf(" > "); free(message); ; unlockPrinter(); } void printNewLine() { printMessage(""); } void clearScreem() { lockPrinter(); int systemRet = system("clear"); if(systemRet != -1){ logInfo("Se ejecuto system(clear) correctamente"); }else{ logWarning("El comando system(clear) no se pudo ejecutar"); } unlockPrinter(); } void printPidNotFound(int pid) { printMessage("No se encontro un proceso con pid %d.\\n", pid); } void printFileNotFound(char* filePath) { printMessage("No se pudo acceder al archivo «%s».", filePath); } void printInvalidCommand(char* command) { if (command != 0) printMessage( "«%s» no es un comando válido.\\nSi necesita ayuda use: «%s».", command, HELP_COMMAND); } void printInvalidArguments(char* argument, char* command) { printMessage( "El argumento «%s» no es valido para el comando «%s».\\nSi necesita ayuda use: «%s».", argument, command, HELP_COMMAND); } void printInvalidOptions(char* option, char* command) { printMessage( "La opción «%s» no es valida para el comando «%s».\\nSi necesita ayuda use: «%s».", option, command, HELP_COMMAND); } void printWelcome(char* processName) { int tab = 10 - (strlen(processName) / 2); lockPrinter(); puts("__________________________________________________________"); puts("___________ Bienvenido a Esther - Los 5 Fantasticos ___________"); puts("__________________ UTN-FRBA SO 1C-2017 ___________________"); printf("______________<<< %*s%s%*s >>>_______________\\n", tab, "", processName, tab, ""); puts("__________________________________________________________"); unlockPrinter(); } void lockPrinter() { pthread_mutex_lock(&printerMutex); } void unlockPrinter() { pthread_mutex_unlock(&printerMutex); } void initPrinterMutex() { pthread_mutex_init(&printerMutex, 0); } void printerDestroy() { pthread_mutex_destroy(&printerMutex); }
1
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; char buf[32]; void *thrfun(void *data) { int id = *(int *)data; while ( 1 ) { pthread_mutex_lock(&mut); pthread_cond_wait(&cond,&mut); int val = atoi(buf); pthread_mutex_unlock(&mut); printf("Thread %d worked, answer = %d\\n",id,val*2); } } int main(int argc, char *argv []) { pthread_t th1,th2; int id1=1,id2=2; if (pthread_create(&th1,0,thrfun,&id1) ) { fprintf(stderr,"fail to create thread!\\n"); exit(1); } if (pthread_create(&th2,0,thrfun,&id2) ) { fprintf(stderr,"fail to create thread!\\n"); exit(1); } printf("Please enter a number for calculation :"); char inbuf[64]; while ( 1 ) { fgets(inbuf,64,stdin); pthread_mutex_lock(&mut); strncpy(buf,inbuf,64); pthread_mutex_unlock(&mut); pthread_cond_signal(&cond); } }
0
#include <pthread.h> struct foo{ pthread_mutex_t f_lock; struct foo *f_next; int f_count; }; struct foo *hashfoo[29L]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo *foo_alloc() { struct foo *pf; int idx; if ((pf = (struct foo *)malloc(sizeof(struct foo))) == 0) return 0; pthread_mutex_init(&pf->f_lock, 0); idx = ((unsigned long)pf % 29L); pthread_mutex_lock(&hashlock); pf->f_next = hashfoo[idx]; hashfoo[idx] = pf->f_next; pthread_mutex_unlock(&hashlock); pf->f_count = 1; return pf; } void foo_hold(struct foo *pf) { pthread_mutex_lock(&pf->f_lock); pf->f_count++; pthread_mutex_unlock(&pf->f_lock); } void foo_rele(struct foo *pf) { pthread_mutex_lock(&pf->f_lock); if (pf->f_count == 1) { pthread_mutex_unlock(&pf->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&pf->f_lock); if (--pf->f_count == 0) { pthread_mutex_unlock(&pf->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&pf->f_lock); pthread_mutex_destroy(&hashlock); free(pf); } else { pthread_mutex_unlock(&pf->f_lock); pthread_mutex_unlock(&hashlock); } } else { pf->f_count--; pthread_mutex_unlock(&pf->f_lock); } }
1
#include <pthread.h> pthread_t g_thread[2]; pthread_mutex_t g_mutex; __uint64_t g_count; pid_t gettid() { return syscall(SYS_gettid); } void *run_amuck(void *arg) { int i, j; printf("Thread %lu started.\\n", (unsigned long)gettid()); for (i = 0; i < 10000; i++) { pthread_mutex_lock(&g_mutex); for (j = 0; j < 100000; j++) { if (g_count++ == 123456789) printf("Thread %lu wins!n", (unsigned long)gettid()); } pthread_mutex_unlock(&g_mutex); } printf("Thread %lu finished!\\n", (unsigned long)gettid()); return (0); } int main(int argc, char *argv[]) { int i, threads = 2; printf("Creating %d threads...\\n", threads); pthread_mutex_init(&g_mutex, 0); for (i = 0; i < threads; i++) pthread_create(&g_thread[i], 0, run_amuck, (void *) i); for (i = 0; i < threads; i++) pthread_join(g_thread[i], 0); printf("Done.\\n"); return (0); }
0
#include <pthread.h> void sign_extend(void *not_used){ pthread_barrier_wait(&threads_creation); int i; short int imediato; int sign_extend_temp; while(1) { pthread_mutex_lock(&control_sign); if (!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait, &control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } imediato = ir & separa_imediato; sign_extend_temp = imediato & 0x0000ffff; imediato = imediato & 0x00008000; for (i = 1; i < 17; i++) sign_extend_temp = sign_extend_temp| (imediato << i); se.value = sign_extend_temp; pthread_mutex_lock(&sign_extend_mutex); se.isUpdated = 1; pthread_cond_broadcast(&sign_extend_cond); pthread_mutex_unlock(&sign_extend_mutex); pthread_barrier_wait(&current_cycle); se.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> void * wizard_func(void *wizard_descr) { struct cube* cube; struct room *newroom; struct room *oldroom; struct wizard* self; struct wizard* other; self = (struct wizard*)wizard_descr; assert(self); cube = self->cube; assert(cube); oldroom = cube->rooms[self->x][self->y]; assert(oldroom); newroom = choose_room(self); while (1) { sem_wait(&singleStepMove); if (cube->game_status == 1) { pthread_exit(0); } if (self->status == 1) { sem_post(&singleStepMove); dostuff(); continue; } printf("Wizard %c%d in room (%d,%d) wants to go to room (%d,%d)\\n", self->team, self->id, oldroom->x, oldroom->y, newroom->x, newroom->y); pthread_mutex_lock(&mutexRoom); if (try_room(self, oldroom, newroom)) { dostuff(); newroom = choose_room(self); printf("Request denied, room locked!\\n"); pthread_mutex_unlock(&mutexRoom); sem_post(&commandLineCurser); continue; } printf("Wizard %c%d in room (%d,%d) moves to room (%d,%d)\\n", self->team, self->id, oldroom->x, oldroom->y, newroom->x, newroom->y); switch_rooms(self, oldroom, newroom); other = find_opponent(self, newroom); if (other == 0) { printf("Wizard %c%d in room (%d,%d) finds nobody around\\n", self->team, self->id, newroom->x, newroom->y); } else { if (tolower(other->team) != tolower(self->team)) { if (other->status == 0) { printf("Wizard %c%d in room (%d,%d) finds active enemy\\n", self->team, self->id, newroom->x, newroom->y); fight_wizard(self, other, newroom); } else { printf("Wizard %c%d in room (%d,%d) finds enemy already frozen\\n", self->team, self->id, newroom->x, newroom->y); } } else { if (other->status == 1) { free_wizard(self, other, newroom); } } } pthread_mutex_unlock(&mutexRoom); dostuff(); oldroom = newroom; newroom = choose_room(self); sem_post(&commandLineCurser); } return 0; }
0
#include <pthread.h> struct SwarmSession { struct SessionContext* session_context; struct SwarmContext* swarm_context; }; int DEFAULT_NETWORK_TIMEOUT = 5; int libp2p_swarm_listen_and_handle(struct Stream* stream, struct Libp2pVector* protocol_handlers) { struct StreamMessage* results = 0; int retVal = 0; if (stream == 0) return -1; libp2p_logger_debug("swarm", "Attempting to get read lock.\\n"); pthread_mutex_lock(stream->socket_mutex); libp2p_logger_debug("swarm", "Got read lock.\\n"); if (!stream->read(stream->stream_context, &results, 1)) { libp2p_logger_debug("swarm", "Releasing read lock\\n"); pthread_mutex_unlock(stream->socket_mutex); if (!libp2p_stream_is_open(stream)) { libp2p_logger_error("swarm", "Attempted read on stream, but has been closed.\\n"); return -1; } libp2p_logger_error("swarm", "Unable to read from network (could just be a timeout). Exiting the read.\\n"); return retVal; } libp2p_logger_debug("swarm", "Releasing read lock.\\n"); pthread_mutex_unlock(stream->socket_mutex); if (results != 0) { libp2p_logger_debug("swarm", "Attempting to marshal %d bytes from network.\\n", results->data_size); retVal = libp2p_protocol_marshal(results, stream, protocol_handlers); libp2p_logger_debug("swarm", "The return value from the attempt to marshal %d bytes was %d.\\n", results->data_size, retVal); libp2p_stream_message_free(results); } else { libp2p_logger_debug("swarm", "Attempted read, but results were null. This is normal.\\n"); } return retVal; } void libp2p_swarm_listen(void* ctx) { struct SwarmSession* swarm_session = (struct SwarmSession*) ctx; struct SessionContext* session_context = swarm_session->session_context; int retVal = 0; for(;;) { retVal = libp2p_swarm_listen_and_handle(session_context->default_stream, swarm_session->swarm_context->protocol_handlers); if (retVal < 0) { libp2p_logger_debug("swarm", "listen: Exiting loop due to retVal being %d.\\n", retVal); break; } } if (session_context->host != 0) free(session_context->host); free(swarm_session); } int libp2p_swarm_add_peer(struct SwarmContext* context, struct Libp2pPeer* peer) { struct SwarmSession* swarm_session = (struct SwarmSession*) malloc(sizeof(struct SwarmSession)); swarm_session->session_context = peer->sessionContext; swarm_session->swarm_context = context; if (thpool_add_work(context->thread_pool, libp2p_swarm_listen, swarm_session) < 0) { libp2p_logger_error("swarm", "Unable to fire up thread for peer %s\\n", libp2p_peer_id_to_string(peer)); return 0; } libp2p_logger_info("swarm", "add_connection: added connection for peer %s.\\n", libp2p_peer_id_to_string(peer)); return 1; } int libp2p_swarm_add_connection(struct SwarmContext* context, int file_descriptor, int ip, int port ) { struct SessionContext* session = libp2p_session_context_new(); if (session == 0) { libp2p_logger_error("swarm", "Unable to allocate SessionContext. Out of memory?\\n"); return 0; } session->datastore = context->datastore; session->filestore = context->filestore; session->host = malloc(INET_ADDRSTRLEN); if (session->host == 0) { free(session->host); return 0; } if (inet_ntop(AF_INET, &ip, session->host, INET_ADDRSTRLEN) == 0) { free(session->host); session->host = 0; session->port = 0; return 0; } session->port = port; session->insecure_stream = libp2p_net_connection_new(file_descriptor, session->host, session->port, session); session->default_stream = session->insecure_stream; struct SwarmSession* swarm_session = (struct SwarmSession*) malloc(sizeof(struct SwarmSession)); swarm_session->session_context = session; swarm_session->swarm_context = context; if (thpool_add_work(context->thread_pool, libp2p_swarm_listen, swarm_session) < 0) { libp2p_logger_error("swarm", "Unable to fire up thread for connection %d\\n", file_descriptor); return 0; } libp2p_logger_info("swarm", "add_connection: added connection %d.\\n", file_descriptor); return 1; } struct SwarmContext* libp2p_swarm_new(struct Libp2pVector* protocol_handlers, struct Datastore* datastore, struct Filestore* filestore) { struct SwarmContext* context = (struct SwarmContext*) malloc(sizeof(struct SwarmContext)); if (context != 0) { context->thread_pool = thpool_init(25); context->protocol_handlers = protocol_handlers; context->datastore = datastore; context->filestore = filestore; } return context; }
1
#include <pthread.h> unsigned int TEST_VALUE_RA[2 * 8][3]; int VT_mc34704_RA_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_RA_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_test_RA(void) { int rv = TPASS, fd, i = 0, val; srand((unsigned)time(0)); fd = open(MC34704_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC34704_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } for (i = 0; i < 8; i++) { val = rand() % 2; switch (val) { case 0: TEST_VALUE_RA[i][0] = CMD_WRITE; TEST_VALUE_RA[i][1] = rand() % REG_NB; TEST_VALUE_RA[i][2] = rand() % 0xFFFFFF; TEST_VALUE_RA[8 + i][0] = CMD_READ; TEST_VALUE_RA[8 + i][1] = rand() % REG_NB; TEST_VALUE_RA[8 + i][2] = rand() % 0xFFFFFF; break; case 1: TEST_VALUE_RA[i][0] = CMD_SUB; TEST_VALUE_RA[i][1] = rand() % EVENT_NB; TEST_VALUE_RA[i][2] = 0; TEST_VALUE_RA[8 + i][0] = CMD_UNSUB; TEST_VALUE_RA[8 + i][1] = rand() % EVENT_NB; TEST_VALUE_RA[8 + i][2] = 0; break; } } for (i = 0; i < 2 * 8; i++) { if (VT_mc34704_opt (fd, TEST_VALUE_RA[i][0], TEST_VALUE_RA[i][1], &(TEST_VALUE_RA[i][2])) != TPASS) { rv = TFAIL; } } if (close(fd) < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to close file descriptor %d", fd); pthread_mutex_unlock(&mutex); return TFAIL; } return rv; }
0
#include <pthread.h> int main(int argc,char **argv){ pthread_cond_t *cond; pthread_condattr_t condattr; pthread_mutex_t m; int fd; if(argc==1){ if((fd=shm_open("/cond",O_RDWR|O_CREAT,0777))==-1){ printf("shm_open failed for /cond:%s\\n",strerror(errno)); return 0; } if(ftruncate(fd,sizeof(pthread_cond_t))==-1){ printf("ftruncate failed:%s\\n",strerror(errno)); close(fd); return 0; } printf("Doing mmap\\n"); cond=mmap(0,sizeof(pthread_cond_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); close(fd); if(cond==MAP_FAILED){ printf("mmap failed for\\n"); printf("cond with error number %d, error\\n",errno); printf("%s\\n",strerror(errno)); return 0; } memset(cond,0,sizeof(pthread_cond_t)); pthread_condattr_init(&condattr); pthread_condattr_setpshared(&condattr,PTHREAD_PROCESS_SHARED); pthread_cond_init(cond,&condattr); pthread_condattr_destroy(&condattr); pthread_mutex_init(&m,0); pthread_mutex_lock(&m); printf("Waiting\\n"); pthread_cond_wait(cond,&m); pthread_mutex_unlock(&m); printf("waited\\n"); }else{ if((fd=shm_open("/cond",O_RDWR,0777))==-1){ printf("shm_open failed for /cond:%s\\n",strerror(errno)); return 0; } printf("Doing mmap\\n"); cond=mmap(0,sizeof(pthread_cond_t),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); close(fd); if(cond==MAP_FAILED){ printf("mmap failed for\\n"); printf("cond with error number %d, error\\n",errno); printf("%s\\n",strerror(errno)); return 0; } printf("signalling\\n"); pthread_cond_signal(cond); printf("done\\n"); } return 0; }
1
#include <pthread.h> int shared_counter = 1; pthread_mutex_t mutex; pthread_t original_thread; void *thread_loop(void *arg) { long int counter_increment = (long int) arg; while (1) { pthread_mutex_lock(&mutex); if (shared_counter >= 25) { pthread_mutex_unlock(&mutex); if (pthread_self() == original_thread) break; else pthread_exit(0); } shared_counter += counter_increment; printf("Thread %d increased counter by %d, now counter = %d\\n", pthread_self(), counter_increment, shared_counter); pthread_mutex_unlock(&mutex); sleep(2); } return 0; } int main(int argc, char *argv[]) { pthread_t threads[3]; pthread_attr_t pthread_attr; long int i; pthread_mutex_init(&mutex, 0); original_thread = pthread_self(); pthread_attr_init(&pthread_attr); pthread_attr_setscope(&pthread_attr, PTHREAD_SCOPE_SYSTEM); for (i = 1; i < 3; i++) if (pthread_create(&threads[i-1], &pthread_attr, thread_loop, (void *) (i + 1))) { perror("Error while creating a thread."); exit(3); } thread_loop((void *) 1); for (i = 1; i < 3; i++) { void *thread_status; pthread_join(threads[i-1], &thread_status); printf("Exit status of thread %d was %ld\\n", threads[i-1], (long int) thread_status); } printf("All Done!\\n"); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_t thread; pthread_cond_t c1, p1; pthread_mutex_t mutex; struct node { int num; struct node *next; struct node *prev; }; int size = 0; struct node *head = 0; struct node *tail = 0; struct node *current = 0; struct node* createNode(int x){ int data; if (x == 0){ data = ((rand() % 20)) * 2; }else{ data = ((rand() % 20)) * 2 + 1; } struct node* newNode = (struct node*)malloc(sizeof(struct node)); newNode->num = data; newNode->next = 0; newNode->prev = 0; return newNode; } void printList(){ struct node* temp = head; printf("(List size = %d) ", size); while(temp != 0){ printf("%d ",temp->num); temp = temp->next; } printf("\\n"); } void add(int x){ current = head; struct node* newNode = createNode(x); if (head == 0){ head = newNode; size++; }else{ while(current->next != 0){ current = current->next; } current->next = newNode; newNode->prev = current; size++; } tail = newNode; } void delete(){ current = head; if (head == 0){ printf("The list is empty."); return; } else if (head->next == 0){ head = 0; size = 0; }else{ head->next->prev = 0; head = head->next; size--; } } void producer1(void *ptr){ while(1){ if (size >= 20){ printf("PRODUCER1: Buffer Full.\\n"); sleep(5); } pthread_mutex_lock(&mutex); while (size >= 20) pthread_cond_wait(&p1, &mutex); add(1); printf("Producer1 added a node\\n"); printList(); pthread_cond_broadcast(&c1); pthread_mutex_unlock(&mutex); sleep(1); } } void producer2(void *ptr){ while(1){ if (size >= 20){ printf("PRODUCER2: Buffer Full.\\n"); sleep(5); } pthread_mutex_lock(&mutex); while (size >= 20 ) pthread_cond_wait(&p1, &mutex); add(0); printf("Producer2 added a node\\n"); printList(); pthread_cond_broadcast(&c1); pthread_mutex_unlock(&mutex); sleep(1); } } void consumer1(void *ptr){ while(1){ if (size == 0 ){ printf("CONSUMER1: Buffer is empty.\\n"); sleep(5); }else{ pthread_mutex_lock(&mutex); while (head->num % 2 == 0) pthread_cond_wait(&c1, &mutex); delete(); printf("Consumer1 removed a node\\n"); printList(); pthread_cond_broadcast(&p1); pthread_mutex_unlock(&mutex); sleep(1); } } } void consumer2(void *ptr){ while(1){ if (size == 0 ){ printf("CONSUMER2: Buffer is empty.\\n"); sleep(5); }else{ pthread_mutex_lock(&mutex); while (head->num % 2 != 0) pthread_cond_wait(&c1, &mutex); delete(); printf("Consumer2 removed a node\\n"); printList(); pthread_cond_broadcast(&p1); pthread_mutex_unlock(&mutex); sleep (1); } } } main() { head = 0; srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_cond_init(&c1, 0); pthread_cond_init(&p1, 0); for (int i = 0; i < 3; i++){ int x = (rand() % 2); add(x); } printf("Initial List: "); printList(); pthread_t prod1, prod2, con1, con2; pthread_mutex_init(&mutex, 0); pthread_cond_init(&c1, 0); pthread_cond_init(&p1, 0); pthread_create(&con1, 0, (void *)consumer1, 0); pthread_create(&con2, 0, (void *)consumer2, 0); pthread_create(&prod1, 0, (void *)producer1, 0); pthread_create(&prod2, 0, (void *)producer2, 0); pthread_join(prod2, 0); pthread_join(prod1, 0); pthread_join(con2, 0); pthread_join(con1, 0); pthread_cond_destroy(&c1); pthread_cond_destroy(&p1); pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t C = PTHREAD_COND_INITIALIZER; void get_forks(int i) { pthread_mutex_lock(&m); pthread_mutex_unlock(&m); } void release_forks(int i) { pthread_mutex_lock(&m); pthread_mutex_unlock(&m); } void *philosopher_thread(void *context) { int philosopher_num = (int)context; return 0; } void q2(void) { } void q3(void) { }
0
#include <pthread.h> struct data { int IMAGE[1]; char mot[1*21]; int DernierThreadSurLaZone[1]; pthread_mutex_t *verrou; pthread_cond_t *condition; }data; void* Fonction1(void*); void* Fonction2(void*); void* Focntion3(void*); void* Fonction4(void*); void* Fonction5(void*); void * Fonction1(void *par){ int ma_fonction_numero = 1; struct data *mon_D1 = (struct data*)par; for(int i=0; i<1;i++){ pthread_mutex_lock(&(mon_D1->verrou[i])); mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5; strcat(mon_D1->mot,"Nique "); mon_D1->DernierThreadSurLaZone[i]=2; printf("Le thread numero %i travail sur la partie %i\\n",1,i); pthread_cond_broadcast(&(mon_D1->condition[i])); pthread_mutex_unlock(&(mon_D1->verrou[i])); } printf("Je suis %i-er le premier thread j'ai fini mon travail.\\n",ma_fonction_numero); pthread_exit(0); } void * Fonction2( void * par){ int ma_fonction_numero = 2; struct data *mon_D1 = (struct data*)par; for(int i=0;i<1;i++){ pthread_mutex_lock(&(mon_D1->verrou[i])); while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){ pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i])); } mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5; strcat(mon_D1->mot,"ta "); printf("Le thread numero %i travail sur la partie %i\\n",2,i); mon_D1->DernierThreadSurLaZone[i]++; pthread_cond_broadcast(&(mon_D1->condition[i])); pthread_mutex_unlock(&(mon_D1->verrou[i])); } printf("Je suis le second thread j'ai fini mon travail.\\n"); pthread_exit(0); } void * Fonction3(void* par){ int ma_fonction_numero = 3; struct data *mon_D1 = (struct data*)par; for(int i=0;i<1;i++){ pthread_mutex_lock(&(mon_D1->verrou[i])); while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){ pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i])); } mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5; strcat(mon_D1->mot,"mere "); printf("Le thread numero %i travail sur la partie %i\\n",3,i); mon_D1->DernierThreadSurLaZone[i]++; pthread_cond_broadcast(&(mon_D1->condition[i])); pthread_mutex_unlock(&(mon_D1->verrou[i])); } printf("Je suis le troisième thread j'ai fini mon travail.\\n"); pthread_exit(0); } void * Fonction4(void* par){ int ma_fonction_numero = 4; struct data *mon_D1 = (struct data*)par; for(int i=0;i<1;i++){ pthread_mutex_lock(&(mon_D1->verrou[i])); while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){ pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i])); } mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5; strcat(mon_D1->mot,"la "); printf("Le thread numero %i travail sur la partie %i\\n",4,i); mon_D1->DernierThreadSurLaZone[i]++; pthread_cond_broadcast(&(mon_D1->condition[i])); pthread_mutex_unlock(&(mon_D1->verrou[i])); } printf("Je suis %i le quatrième thread j'ai fini mon travail.\\n",ma_fonction_numero); pthread_exit(0); } void * Fonction5( void * par){ int ma_fonction_numero = 5; struct data *mon_D1 = (struct data*)par; for(int i=0;i<1;i++){ pthread_mutex_lock(&(mon_D1->verrou[i])); while(mon_D1->DernierThreadSurLaZone[i]!=ma_fonction_numero){ pthread_cond_wait(&(mon_D1->condition[i]),&(mon_D1->verrou[i])); } mon_D1->IMAGE[i]=mon_D1->IMAGE[i]+5; strcat(mon_D1->mot,"pute"); printf("Le thread numero %i travail sur la partie %i\\n",5,i); mon_D1->DernierThreadSurLaZone[i]++; pthread_cond_broadcast(&(mon_D1->condition[i])); pthread_mutex_unlock(&(mon_D1->verrou[i])); } printf("Je suis le second thread j'ai fini mon travail.\\n"); pthread_exit(0); } int main(){ srand(time(0)); pthread_t T1,T2,T3,T4,T5; struct data D1; for(int i=0;i<1;i++){ D1.DernierThreadSurLaZone[i]=0; D1.IMAGE[i]=0; } D1.verrou=malloc(sizeof(pthread_mutex_t)*1); D1.condition=malloc(sizeof(pthread_cond_t)*1); for(size_t i=0;i<1;i++){ pthread_mutex_init(&(D1.verrou[i]),0); pthread_cond_init(&(D1.condition[i]),0); } pthread_create(&T2,0,Fonction2,&D1); pthread_create(&T3,0,Fonction3,&D1); pthread_create(&T4,0,Fonction4,&D1); pthread_create(&T1,0,Fonction1,&D1); pthread_create(&T5,0,Fonction5,&D1); pthread_join(T1,0); pthread_join(T2,0); pthread_join(T3,0); pthread_join(T4,0); pthread_join(T5,0); printf("IMAGE("); for(int i=0;i<1 -1;i++){ printf("%i,",D1.IMAGE[i]); } printf("%i)\\n\\n\\n",D1.IMAGE[1 -1]); for(int i=0;i<1*21;i++){ printf("%c",D1.mot[i]); } printf("\\n\\n"); return 0; }
1
#include <pthread.h> const char g_wldb_file[] = "whitelist.db"; struct sDB * g_whitelist; static pthread_mutex_t whitelist_mtx; int WhiteListDatabaseInit() { int mtx = 0; mtx = pthread_mutex_init(&whitelist_mtx,0); if( 0 != mtx){ print_log(f_sysinit,"ERROR!!!pthread_mutex_init whilte list database mutex!!!"); return -1; } g_whitelist = db_open(g_wldb_file, 0); if( g_whitelist==0 ) { printf("%s not exist!!!\\n", g_wldb_file); print_log(f_sysinit,"ERROR!!! %s not exist!!!\\n",g_wldb_file); return -1; } return 0; } int RefreshWLDatabase(char *data, int count) { int i=0; int ret=0; char *ptr = data; int wl_item_size = 4+TID_LEN+CAR_NUM_LEN; char tid[20]; char priv_u[5]; int priv; char license[20]; char *sql_cmd; int sql_prefix_len = 0; int sql_cmd_len =0; int split_count = 200; sql_cmd = (char*)malloc(200*40+30); sprintf(sql_cmd, "delete from whitelist"); pthread_mutex_lock(&whitelist_mtx); ret = db_query(g_whitelist, sql_cmd); printf("Table Clear %d\\n", ret); sql_prefix_len = sprintf(sql_cmd, "insert into whitelist values "); for(i=0;i<count;i++) { ptr = data+(wl_item_size*i); if( i!=count-1) ptr[wl_item_size] = 0; memset(tid, 0x00, 20); memset(license, 0x00, 20); memset(priv_u, 0x00, 5); memcpy(tid, ptr+2, 16); memcpy(priv_u, ptr+18, 2); priv = atoi(priv_u); strcpy(license, ptr+20); sql_cmd_len += sprintf(sql_cmd+sql_prefix_len+sql_cmd_len, "('%s',%d, '%s'),", tid, priv, license); if( i%200 == 0 && i!=0 ) { sql_cmd[sql_prefix_len+sql_cmd_len-1] = 0; ret = db_query(g_whitelist, sql_cmd); if( ret==0 ) { } else { printf("sql update failed\\n"); pthread_mutex_unlock(&whitelist_mtx); free(sql_cmd); return -1; } memset(sql_cmd, 0x00, 200*40+30); sql_cmd_len =0; sql_prefix_len = sprintf(sql_cmd, "insert into whitelist values "); continue; } } if( i%200!=0 && i!=0 ) { sql_cmd[sql_prefix_len+sql_cmd_len-1] = 0; ret = db_query(g_whitelist, sql_cmd); if( ret==0 ) { } else { printf("sql update failed\\n"); pthread_mutex_unlock(&whitelist_mtx); free(sql_cmd); return -1; } } free(sql_cmd); pthread_mutex_unlock(&whitelist_mtx); return 0; } int CheckWhiteList(const char *tid,char *carnum) { char sql_cmd[1024]; struct query_result *result; int ret; if(0 == carnum){ return -1; } result = (struct query_result *)calloc(1,sizeof(struct query_result)); if( 0 == result ) { printf("calloc result is NULL!!!\\n"); return -1; } sprintf(sql_cmd, "select * from whitelist where tid='%s'", tid); pthread_mutex_lock(&whitelist_mtx); ret = db_query_call(g_whitelist, sql_cmd, result); if( ret==0 ) { struct sqlresult * temp = result->result; if( result->total == 1 ){ ret = strncmp(temp->colname[2],"license",7); if(0 == ret){ strcpy(carnum,temp->data[2]); free_result(result); pthread_mutex_unlock(&whitelist_mtx); return 0; } }else{ } } else { printf("sql exec failed\\n"); free_result(result); pthread_mutex_unlock(&whitelist_mtx); return -1; } pthread_mutex_unlock(&whitelist_mtx); free_result(result); return -1; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond_filosofos[5]; int estado_filosofo[5]; void pegar_garfos(int id); void devolver_garfos(int id); void tentar_comer(int id); void verificar_concorrencia(); void* filosofo(void* arg){ int id = *((int*) arg); while(1){ printf("filosofo %d está pensando!\\n", id); sleep(rand()%10); pegar_garfos(id); printf("filosofo %d está comendo!\\n", id); sleep(rand()%5); devolver_garfos(id); } pthread_exit(0); } void pegar_garfos(int id){ pthread_mutex_lock(&mutex); estado_filosofo[id] = 1; printf("filosofo %d está faminto!\\n", id); tentar_comer(id); while(! estado_filosofo[id] == 1 && estado_filosofo[(id+5-1)%5] != 2 && estado_filosofo[(id+1)%5] != 2) pthread_cond_wait(&cond_filosofos[id], &mutex); verificar_concorrencia(); pthread_mutex_unlock(&mutex); } void devolver_garfos(int id){ pthread_mutex_lock(&mutex); estado_filosofo[id] = 0; tentar_comer((id+5-1)%5); tentar_comer((id+1)%5); pthread_mutex_unlock(&mutex); } void tentar_comer(int id){ if(estado_filosofo[id] == 1 && estado_filosofo[(id+5-1)%5] != 2 && estado_filosofo[(id+1)%5] != 2){ estado_filosofo[id] = 2; pthread_cond_signal(&cond_filosofos[id]); } } void verificar_concorrencia(){ int i, q = 0, f[2]; for(i = 0; i < 5; i++){ if(estado_filosofo[i] == 2){ f[q] = i; q++; } } if(q == 2){ printf("os filosofos %d e %d estão comendo juntos!\\n", f[0], f[1]); } } int main(int argc, char const *argv[]) { pthread_t filosofos[5]; int i; int ids[5] = {0, 1, 2, 3, 4}; pthread_mutex_init(&mutex, 0); for(i = 0; i < 5; i++){ pthread_cond_init(&cond_filosofos[i], 0); } for(i = 0; i < 5; i++){ pthread_create(&filosofos[i], 0, filosofo, &ids[i]); } for(i = 0; i < 5; i++){ pthread_join(filosofos[i], 0); } for(i = 0; i < 5; i++){ pthread_cond_destroy(&cond_filosofos[i]); } pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error(); unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> sem_t chopstick[5]; pthread_mutex_t mutex; int food[5]; void pickup_chopsticks(int); void putdown_chopsticks(int); void philosopher(int *philosopher_info); int main(int argc, char *argv[]){ pthread_t philosophers[5]; int philosopher_info[5][1]; pthread_mutex_init(&mutex, 0); if (argc != 2){ fprintf(stderr, "Invalid Number of Arguments\\n\\tUSAGE: ./dinf foodArg\\n"); exit(0); } int foodArg = atoi(argv[1]); int i; for (i = 0; i < 5; i++){ if (sem_init(&chopstick[i], 0, 1) < 0) { fprintf(stderr, "ERROR: sem_init(&chopstick[%d], 0, 1)\\n", i); exit(1); } } for (i = 0; i < 5; i++){ philosopher_info[i][0] = i; food[i] = foodArg; pthread_create(&philosophers[i], 0, (void *(*)(void *)) &philosopher, &philosopher_info[i]); } for (i = 0; i < 5; i++){ pthread_join(philosophers[i], 0); } for (i = 0; i < 5; i++){ sem_destroy(&chopstick[i]); } return 0; } void pickup_chopsticks(int n){ if (n % 2 == 0) { pthread_mutex_lock(&mutex); sem_wait(&chopstick[(n+1) % 5]); printf("Philosopher %d waiting for left chopstick\\n", n); sem_wait(&chopstick[n]); printf("Philosopher %d waiting for right chopstick\\n", n); pthread_mutex_unlock(&mutex); }else{ pthread_mutex_lock(&mutex); sem_wait(&chopstick[n]); printf("Philosopher %d waiting for right chopstick\\n", n); sem_wait(&chopstick[(n+1) % 5]); printf("Philosopher %d waiting for left chopstick\\n", n); pthread_mutex_unlock(&mutex); } } void putdown_chopsticks(int n){ sem_post(&chopstick[n]); printf("Philosopher %d put down right chopstick\\n", n); sem_post(&chopstick[(n+1) % 5]); printf("Philosopher %d put down left chopstick\\n", n); } void philosopher(int *philosopher_info){ int n = philosopher_info[0]; while (food[n] > 0){ printf("Philosopher %d beginning to think\\n", n); sleep(rand() % 10); printf("Philosopher %d finished thinking and waiting for critical section\\n", n); pickup_chopsticks(n); printf("Philosopher %d starting to eat\\n", n); food[n] = food[n] - 1; printf("\\tPhilosopher %d has %d food left\\n", n, food[n]); putdown_chopsticks(n); } printf("Philosopher %d is done\\n", n); pthread_exit(0); }
1
#include <pthread.h> void* (*routine)(void*); void *arg; struct tpool_work *next; }tpool_work_t; int shutdown; int max_thr_num; pthread_t *thr_id; tpool_work_t *queue_head; pthread_mutex_t queue_lock; pthread_cond_t queue_ready; }tpool_t; static tpool_t *tpool = 0; static void* thread_routine(void *arg) { tpool_work_t *work; while(1) { pthread_mutex_lock(&tpool->queue_lock); while(!tpool->queue_head && !tpool->shutdown) { pthread_cond_wait(&tpool->queue_ready, &tpool->queue_lock); } if (tpool->shutdown) { pthread_mutex_unlock(&tpool->queue_lock); pthread_exit(0); } work = tpool->queue_head; tpool->queue_head = tpool->queue_head->next; pthread_mutex_unlock(&tpool->queue_lock); work->routine(work->arg); free(work); } return 0; } int tpool_create(int max_thr_num) { int i; tpool = calloc(1, sizeof(tpool_t)); if (!tpool) { printf("%s: calloc failed\\n", __FUNCTION__); exit(1); } tpool->max_thr_num = max_thr_num; tpool->shutdown = 0; tpool->queue_head = 0; if (pthread_mutex_init(&tpool->queue_lock, 0) !=0) { printf("%s: pthread_mutex_init failed, errno:%d, error:%s\\n", __FUNCTION__, errno, strerror(errno)); exit(1); } if (pthread_cond_init(&tpool->queue_ready, 0) !=0 ) { printf("%s: pthread_cond_init failed, errno:%d, error:%s\\n", __FUNCTION__, errno, strerror(errno)); exit(1); } tpool->thr_id = calloc(max_thr_num, sizeof(pthread_t)); if (!tpool->thr_id) { printf("%s: calloc failed\\n", __FUNCTION__); exit(1); } for (i = 0; i < max_thr_num; ++i) { if (pthread_create(&tpool->thr_id[i], 0, thread_routine, 0) != 0){ printf("%s:pthread_create failed, errno:%d, error:%s\\n", __FUNCTION__, errno, strerror(errno)); exit(1); } } return 0; } void tpool_destroy() { int i; tpool_work_t *member; if (tpool->shutdown) { return; } tpool->shutdown = 1; pthread_mutex_lock(&tpool->queue_lock); pthread_cond_broadcast(&tpool->queue_ready); pthread_mutex_unlock(&tpool->queue_lock); for (i = 0; i < tpool->max_thr_num; ++i) { pthread_join(tpool->thr_id[i], 0); } free(tpool->thr_id); while(tpool->queue_head) { member = tpool->queue_head; tpool->queue_head = tpool->queue_head->next; free(member); } pthread_mutex_destroy(&tpool->queue_lock); pthread_cond_destroy(&tpool->queue_ready); free(tpool); } int tpool_add_work(void*(*routine)(void*), void *arg) { tpool_work_t *work, *member; if (!routine){ printf("%s:Invalid argument\\n", __FUNCTION__); return -1; } work = malloc(sizeof(tpool_work_t)); if (!work) { printf("%s:malloc failed\\n", __FUNCTION__); return -1; } work->routine = routine; work->arg = arg; work->next = 0; pthread_mutex_lock(&tpool->queue_lock); member = tpool->queue_head; if (!member) { tpool->queue_head = work; } else { while(member->next) { member = member->next; } member->next = work; } pthread_cond_signal(&tpool->queue_ready); pthread_mutex_unlock(&tpool->queue_lock); return 0; } void *thread_read(void *args) { int fd = *(int *)args; char buff[100]; printf("thead read start\\n"); int n = read(fd, &buff, 100); printf("thead read end\\n"); if(n > 0) { write(fd, buff, n); } printf("thead close fd:%d\\n", fd); close(fd); } int main(int arg, char **argv) { int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in sa; bzero(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(8080); bind(sock, (struct sockaddr *)&sa, sizeof(sa)); if(listen(sock, 1024) < 0) { printf("listen error\\n"); return -1; } if (tpool_create(5) != 0) { printf("tpool_create failed\\n"); exit(1); } for(;;) { printf("main accept start\\n"); int fd = accept(sock, 0, 0); if(fd < 0) { printf("accept error\\n"); return -1; } printf("main accept fd:%d\\n", fd); tpool_add_work(thread_read, &fd); } tpool_destroy(); return 0; }
0
#include <pthread.h> pid_t pid; int bread_count; int box_count; pthread_mutex_t bread_mutex; sem_t box_sem; void *thread_maker(void *arg) { int usec; int id = *(int *)arg; printf("[T%d] thread started\\n", id); for(;;) { usec = random()%500000 + 500000; usleep(usec); pthread_mutex_lock(&bread_mutex); if(bread_count == 100) { pthread_mutex_unlock(&bread_mutex); printf("[T%d] thread terminated\\n", id); pthread_exit(0); } bread_count++; printf("[T%d] bread %03d\\n", id, bread_count); if(bread_count%10 == 0) { sem_post(&box_sem); } pthread_mutex_unlock(&bread_mutex); } } void *thread_boxer(void *arg) { int id = *(int *)arg; printf("[T%d] thread started\\n", id); for(;;) { sem_wait(&box_sem); usleep(5000000); box_count++; printf("[T%d] box %02d\\n", id, box_count); if(box_count == 10) break; } printf("[T%d] thread terminated\\n", id); pthread_exit(0); } void *(*thread_func[3])(void *arg) = { thread_maker, thread_maker, thread_boxer }; int thread_arg[3] = {1, 2, 3}; int main(int argc, char **argv) { pthread_t thread_id[3]; int ret; int i; printf("[%d] running %s\\n", pid = getpid(), argv[0]); ret = pthread_mutex_init(&bread_mutex, 0); if(ret != 0) { printf("[%d] error: %d (%d)\\n", pid, ret, 84); return 1; } ret = sem_init(&box_sem, 0, 0); if(ret == -1) { printf("[%d] error: %d (%d)\\n", pid, ret, 90); return 1; } printf("[%d] creating threads\\n", pid); for(i=0; i<3; i++) { ret = pthread_create(&thread_id[i], 0, thread_func[i], &thread_arg[i]); if(ret != 0) { printf("[%d] error: %d (%d)\\n", pid, ret, 98); return 1; } } printf("[%d] waiting to join with a terminated thread\\n", pid); for(i=0; i<3; i++) { ret = pthread_join(thread_id[i], 0); if(ret != 0) { printf("[%d] error: %d (%d)\\n", pid, ret, 107); return 1; } } printf("[%d] all threads terminated\\n", pid); sem_destroy(&box_sem); pthread_mutex_destroy(&bread_mutex); printf("[%d] terminted\\n", pid); return 0; }
1
#include <pthread.h> extern struct net_ops tcp_ops; static int inet_stream_connect(struct socket *sock, const struct sockaddr *addr, int addr_len, int flags); static int INET_OPS = 1; struct net_family inet = { .create = inet_create, }; static struct sock_ops inet_stream_ops = { .connect = &inet_stream_connect, .write = &inet_write, .read = &inet_read, .close = &inet_close, .free = &inet_free, .abort = &inet_abort, }; static struct sock_type inet_ops[] = { { .sock_ops = &inet_stream_ops, .net_ops = &tcp_ops, .type = SOCK_STREAM, .protocol = IPPROTO_TCP, } }; int inet_create(struct socket *sock, int protocol) { struct sock *sk; struct sock_type *skt = 0; for (int i = 0; i < INET_OPS; i++) { if (inet_ops[i].type & sock->type) { skt = &inet_ops[i]; break; } } if (!skt) { print_err("Could not find socktype for socket\\n"); return 1; } sock->ops = skt->sock_ops; sk = sk_alloc(skt->net_ops, protocol); sk->protocol = protocol; sock_init_data(sock, sk); return 0; } int inet_socket(struct socket *sock, int protol) { return 0; } int inet_connect(struct socket *sock, struct sockaddr *addr, int addr_len, int flags) { return 0; } static int inet_stream_connect(struct socket *sock, const struct sockaddr *addr, int addr_len, int flags) { struct sock *sk = sock->sk; int rc = 0; if (addr_len < sizeof(addr->sa_family)) { return -EINVAL; } if (addr->sa_family == AF_UNSPEC) { sk->ops->disconnect(sk, flags); sock->state = sk->err ? SS_DISCONNECTING : SS_UNCONNECTED; goto out; } switch (sock->state) { default: sk->err = -EINVAL; goto out; case SS_CONNECTED: sk->err = -EISCONN; goto out; case SS_CONNECTING: sk->err = -EALREADY; goto out; case SS_UNCONNECTED: sk->err = -EISCONN; if (sk->state != TCP_CLOSE) { goto out; } sk->ops->connect(sk, addr, addr_len, flags); sock->state = SS_CONNECTING; sk->err = -EINPROGRESS; if (sock->flags & O_NONBLOCK) { goto out; } wait_sleep(&sock->sleep); switch (sk->err) { case -ETIMEDOUT: case -ECONNREFUSED: goto sock_error; } if (sk->err != 0) { goto out; } sock->state = SS_CONNECTED; break; } out: return sk->err; sock_error: rc = sk->err; socket_free(sock); return rc; } int inet_write(struct socket *sock, const void *buf, int len) { struct sock *sk = sock->sk; return sk->ops->write(sk, buf, len); } int inet_read(struct socket *sock, void *buf, int len) { struct sock *sk = sock->sk; return sk->ops->read(sk, buf, len); } struct sock *inet_lookup(struct sk_buff *skb, uint16_t sport, uint16_t dport) { struct socket *sock = socket_lookup(sport, dport); if (sock == 0) return 0; return sock->sk; } int inet_close(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; if (!sock) { return 0; } if (err) { print_err("Error on socket closing\\n"); return -1; } pthread_mutex_lock(&sk->lock); sock->state = SS_DISCONNECTING; if (sock->sk->ops->close(sk) != 0) { print_err("Error on sock op close\\n"); } err = sk->err; pthread_mutex_unlock(&sk->lock); return err; } int inet_free(struct socket *sock) { struct sock *sk = sock->sk; sock_free(sk); free(sock->sk); return 0; } int inet_abort(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { sk->ops->abort(sk); } return 0; }
0
#include <pthread.h> uint64_t nb; FILE * file; char str[60]; pthread_t thread0; pthread_t thread1; pthread_mutex_t lock; void* thread_prime_factors(void * u); void print_prime_factors(uint64_t n); void* thread_prime_factors(void * u) { pthread_mutex_lock(&lock); while ( fgets(str, 60, file)!=0 ) { nb=atol(str); pthread_mutex_unlock(&lock); print_prime_factors(nb); pthread_mutex_lock(&lock); } pthread_mutex_unlock(&lock); return 0; } void print_prime_factors(uint64_t n) { printf("%ju : ", n ); uint64_t i; for( i=2; n!=1 ; i++ ) { while (n%i==0) { n=n/i; printf("%ju ", i); } } printf("\\n"); return; } int main(void) { printf("En déplaçant la boucle de lecture dans chacun des threads :\\n"); file = fopen ("fileQuestion4efficace.txt","r"); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_create(&thread0, 0, thread_prime_factors, 0); pthread_create(&thread1, 0, thread_prime_factors, 0); pthread_join(thread0, 0); pthread_join(thread1, 0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t self; int temp; struct node * next; }node_t; void performLL(node_t * node); node_t *createNode(int myTemp); void forward(node_t **currentNode); void insertEnd(node_t **head, node_t *addedNode); void insertLL(int *id); void temperature(int *id); node_t * linkedList; int NumOfLocs; int *array = 0; int completed; int main (){ linkedList = 0; int *id; completed = 0; int min = 0; printf("Number of sensor locations: "); scanf("%d", &NumOfLocs); array = malloc(sizeof(int)*NumOfLocs); int index; for(index = 0; index < NumOfLocs; index++){ array[index] = 0; } pthread_t sensors[NumOfLocs]; pthread_mutex_init(&lock, 0); pthread_cond_init(&self, 0); int count = 0; while (count < NumOfLocs){ id = (int *)malloc(sizeof(int)); *id = count; pthread_create(&(sensors[count]), 0, (void *)temperature, id); count ++; } for(count = 0; count < NumOfLocs; count++){ pthread_join(sensors[count], 0); } printf("Done!\\n"); return; } node_t *createNode(int myTemp){ node_t *p; p = (node_t *) malloc (sizeof(node_t)); p->temp = myTemp; p->next = 0; return p; } void forward(node_t **currentNode){ if((*currentNode)->next != 0){ *currentNode=(*currentNode)->next; } else { printf("Reached the end\\n"); } } void insertEnd(node_t **head, node_t *addedNode){ node_t *p; if(*head == 0) { *head = addedNode; return; } p = *head; while(p->next != 0){ p=p->next; } p->next = addedNode; return; } int findMin(int a[]){ int min = a[0]; int i; for (i = 1; i < NumOfLocs; i++){ if(a[i] < min){ min = a[i]; } } return min; } void performLL(node_t * node){ node_t *tempNode; tempNode = node; int sum = 0; if (tempNode == 0) { printf("list is empty\\n"); return; } else { while(tempNode->next != 0){ printf("Temp = %d, ", tempNode -> temp); sum = sum + (tempNode -> temp); forward(&tempNode); } printf("Temp = %d\\n", tempNode -> temp); sum = sum + (tempNode -> temp); printf("Average Temp = %f\\n\\n", (double)sum/(double)NumOfLocs); linkedList = 0; return; } } void temperature(int *id){ int count = 0; while(completed < 10){ while(count < 10){ pthread_mutex_lock(&lock); while(completed < array[*id]){ printf("%d is waiting\\n", *id); pthread_cond_wait(&self, &lock); } printf("%d is inserting\\n", *id); insertLL(id); array[*id] = (array[*id] + 1); pthread_cond_broadcast(&self); pthread_mutex_unlock(&lock); if(findMin(array) > completed) { performLL(linkedList); completed ++; } count++; } } pthread_exit(0); return; } void insertLL(int *id){ int temp; node_t *tempNode; temp = rand() % 100 - 30; tempNode = createNode(temp); insertEnd(&linkedList, tempNode); printf("sensor %d has temp %d\\n", *id, temp); return; }
0
#include <pthread.h> pthread_mutex_t ma, mb; int data1, data2; pthread_mutex_t ja, jb; int join1, join2; void * thread1(void * arg) { pthread_mutex_lock(&ma); data1++; pthread_mutex_unlock(&ma); pthread_mutex_lock(&ma); data2++; pthread_mutex_unlock(&ma); pthread_mutex_lock(&ja); join1 = 1; pthread_mutex_unlock(&ja); return 0; } void * thread2(void * arg) { pthread_mutex_lock(&ma); data1+=5; pthread_mutex_unlock(&ma); pthread_mutex_lock(&ma); data2-=6; pthread_mutex_unlock(&ma); pthread_mutex_lock(&jb); join2 = 1; pthread_mutex_unlock(&jb); return 0; } int main() { pthread_t t1, t2; int i; pthread_mutex_init(&ja, 0); pthread_mutex_init(&jb, 0); join1 = join2 = 0; pthread_mutex_init(&ma, 0); pthread_mutex_init(&mb, 0); data1 = 10; data2 = 10; pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_mutex_lock (&ja); i = join1; pthread_mutex_unlock (&ja); if (i == 0) return 0; pthread_mutex_lock (&jb); i = join2; pthread_mutex_unlock (&jb); if (i == 0) return 0; __VERIFIER_assert (data1 == 16); __VERIFIER_assert (data2 == 5); return 0; }
1
#include <pthread.h> static int ARG; int turn = 0; pthread_mutex_t lock; void *opA(void *arg) { int a = ARG; while(a > 0) { if(turn == 0) { pthread_mutex_lock(&lock); printf("Thread A executing opA\\n"); turn = 1; pthread_mutex_unlock(&lock); a--; } } return 0; } void *opB(void *arg) { int b = ARG; while(b > 0) { if(turn == 1) { pthread_mutex_lock(&lock); printf("Thread B executing opB\\n"); turn = 0; pthread_mutex_unlock(&lock); b--; } } return 0; } int main(int argc, char *argv[]) { ARG = atoi(argv[1]); if(argc != 2 || ARG <= 0) { printf("Wrong arguments, this program takes one argument that represents the number of times that thread A and thread B execute their operations\\n"); } pthread_t threadA; pthread_t threadB; if(pthread_mutex_init(&lock, 0) != 0) { printf(" mutex init failed\\n"); return 1; } if(pthread_create(&threadA, 0, opA, 0)) { fprintf(stderr,"Error while creating thread A\\n"); exit(1); } if(pthread_create(&threadB, 0, opB, 0)) { fprintf(stderr,"Error while creating thread B\\n"); exit(1); } if(pthread_join(threadA, 0)) { fprintf(stderr, "Error while waiting for thread A\\n"); exit(1); } if(pthread_join(threadB, 0)) { fprintf(stderr, "Error while waiting for thread B\\n"); exit(1); } pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *thread_function(void *arg); int run_now = 1; int main(int argc, char **argv) { int print_count1 = 0; pthread_t a_thread; if(pthread_create(&a_thread, 0, thread_function, 0) != 0 ) { perror("thread creation failed.\\n"); exit(1); } while(print_count1++ < 2) { pthread_mutex_lock(&condition_mutex); printf("main cond_mutex lock. \\n"); pthread_cond_wait(&condition_cond, &condition_mutex); pthread_mutex_unlock(&condition_mutex); printf("main cond_mutex unlock. \\n"); if(pthread_mutex_lock(&mutex) == 0) { printf("main lock. \\n"); } if(run_now == 2) { printf("main thread is run .\\n"); run_now = 1; } else { printf("main thread is sleep\\n"); usleep(10); } if(pthread_mutex_unlock(&mutex) == 0) { printf("main unlock. \\n"); } } pthread_mutex_destroy(&mutex); pthread_join(a_thread, 0); exit(0); } void *thread_function(void *arg) { int print_count2 = 0; while(print_count2++ < 3) { if(pthread_mutex_lock(&mutex) == 0) { printf("thread lock. \\n"); } if(run_now == 1) { printf("function thread is run. \\n"); run_now = 2; pthread_mutex_lock(&condition_mutex); pthread_cond_signal(&condition_cond); pthread_mutex_unlock(&condition_mutex); } else { printf("function thread is sleep:\\n"); usleep(10); } if(pthread_mutex_unlock(&mutex) == 0) { printf("thread unlock. \\n"); } } pthread_exit(0); }
1
#include <pthread.h> int ready_threads = 0; pthread_mutex_t mutex; pthread_cond_t cond; void f(void) { } void g(void) { } void barrier(void) { pthread_mutex_lock(&mutex); ready_threads++; if (ready_threads == 2) { pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } else { pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } } void set_priority(void) { int policy, err; struct sched_param param; if ((err = pthread_getschedparam(pthread_self(), &policy, &param)) != 0) { fprintf(stderr, "could not set priority: cannot retrieve thread scheduling parameters: %d\\n", err); exit(2); } param.sched_priority = 48; if ((err = pthread_setschedparam(pthread_self(), policy, &param))) { fprintf(stderr, "could not set thread priority: %d\\n", err); exit(3); } if ((err = pthread_set_fixedpriority_self())) { fprintf(stderr, "could not set thread scheduling to fixed: %d\\n", err); exit(4); } } void* first_thread(void *arg) { set_priority(); barrier(); while (1) { g(); } } void* second_thread(void *arg) { barrier(); usleep(10000); while (1) { f(); } } int main(void) { int err; pthread_t *thread = 0; if ((err = pthread_cond_init(&cond, 0)) != 0) { fprintf(stderr, "error initialising condition variable: %d\\n", err); return err; } if ((err = pthread_mutex_init(&mutex, 0)) != 0) { fprintf(stderr, "error initialising mutex: %d\\n", err); return err; } err = pthread_create(&thread, 0, first_thread, 0); if (err) { fprintf(stderr, "error starting first thread: %d\\n", err); } err = pthread_create(&thread, 0, second_thread, 0); if (err) { fprintf(stderr, "error starting second thread: %d\\n", err); } while (1) { } }
0
#include <pthread.h> volatile int varCompartilhada=0; static pthread_mutex_t mutexLock; void* incrementa_contador (void *arg) { for (unsigned int i=0; i < 10000; i++) { pthread_mutex_lock(&mutexLock); varCompartilhada++; pthread_mutex_unlock(&mutexLock); } return 0; } void* decrementa_contador (void *arg) { for (unsigned int i=0; i < 10000; i++) { pthread_mutex_lock(&mutexLock); varCompartilhada--; pthread_mutex_unlock(&mutexLock); } return 0; } int main (int argc, char** argv) { pthread_t t0; pthread_t t1; printf("Este exemplo eh igual ao anterior, exceto pelo uso de um MUTEX\\n"); printf("para evitar a concorrencia entre as threads.\\n"); printf("Execute o codigo varias vezes para ver o valor final de 'varCompartilhada'.\\n\\n"); printf("Valor inicial: %d\\n", varCompartilhada); pthread_mutex_init(&mutexLock, 0); pthread_create(&t0, 0, incrementa_contador, 0); pthread_create(&t1, 0, decrementa_contador, 0); pthread_join(t0, 0); pthread_join(t1, 0); pthread_mutex_destroy(&mutexLock); printf("Valor final: %d\\n", varCompartilhada); return 0; }
1
#include <pthread.h> struct UserThread* Iterator_next(struct UserThreadIterator*); unsigned int Iterator_hasNext(struct UserThreadIterator*); struct UserThreadIterator* new_UserThreadIterator(struct UserThreadCollection*); void dest_UserThreadIterator(struct UserThreadIterator*); static int iteratorVersion = 0; struct UserThreadIterator* new_UserThreadIterator( struct UserThreadCollection* coll) { struct UserThreadIterator* temp; pthread_mutex_lock(coll->lock); temp = malloc(sizeof(struct UserThreadIterator)); temp->collection = coll; temp->internalIndex = 0; temp->version = iteratorVersion; temp->hasNext = Iterator_hasNext; temp->next = Iterator_next; return temp; } void dest_UserThreadIterator(struct UserThreadIterator* this) { if (this == 0) return; pthread_mutex_unlock(this->collection->lock); free(this); } struct UserThread* Iterator_next(struct UserThreadIterator*this) { if (iteratorVersion != this->version) return 0; if (this->internalIndex < this->collection->numberOfUsers) { return this->collection->users[this->internalIndex++]; } return 0; } unsigned int Iterator_hasNext(struct UserThreadIterator*this) { if (iteratorVersion != this->version) return 0; if (this->internalIndex < this->collection->numberOfUsers) { return 1; } return 0; } struct UserThreadCollection* new_UserThreadCollection(); void dest_UserThreadCollection(struct UserThreadCollection*); void Collection_add(struct UserThreadCollection*, struct UserThread*); void Collection_remove(struct UserThreadCollection*, struct UserThread*); unsigned int Collection_size(struct UserThreadCollection*); unsigned int Collection_contains(struct UserThreadCollection*, char*); struct UserThread * Collection_getUser(struct UserThreadCollection*, const char*); struct UserThreadIterator* Collection_iterator(struct UserThreadCollection*); int getIndex(struct UserThreadCollection*this, struct UserThread* info); unsigned int Collection_containsByStruct(struct UserThreadCollection*this, struct UserThread* user); struct UserThreadCollection* new_UserThreadCollection() { struct UserThreadCollection* temp; int i; temp = malloc(sizeof(struct UserThreadCollection)); temp->numberAllocated = 30; temp->users = (struct UserThread**) malloc( sizeof(struct UserThread*) * 30); for (i = 0; i < 30; i++) { temp->users[i] = 0; } temp->lock = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(temp->lock, 0); temp->numberOfUsers = 0; temp->add = Collection_add; temp->contains = Collection_contains; temp->getUser = Collection_getUser; temp->iterator = Collection_iterator; temp->remove = Collection_remove; temp->size = Collection_size; return temp; } void dest_UserThreadCollection(struct UserThreadCollection*this) { int i; if (this == 0) return; for (i = 0; i < this->numberOfUsers; i++) { dest_UserThread(this->users[i]); } pthread_mutex_destroy(this->lock); free(this); } void Collection_add(struct UserThreadCollection*this, struct UserThread* toAdd) { struct UserThread *temp[this->numberAllocated]; int i; if (this->contains(this, toAdd->userName)) { return; } iteratorVersion++; pthread_mutex_lock(this->lock); if (this->numberOfUsers == this->numberAllocated) { for (i = 0; i < this->numberOfUsers; i++) { temp[i] = this->users[i]; } free(this->users); this->numberAllocated += 30; this->users = (struct UserThread**) malloc( sizeof(struct UserThread*) * this->numberAllocated); for (i = 0; i < this->numberOfUsers; i++) { this->users[i] = temp[i]; } this->users[this->numberOfUsers++] = toAdd; } else { this->users[this->numberOfUsers++] = toAdd; } pthread_mutex_unlock(this->lock); } void Collection_remove(struct UserThreadCollection*this, struct UserThread* toRemove) { int index, j; if (this->contains(this, toRemove->userName)) { pthread_mutex_lock(this->lock); index = getIndex(this, toRemove); for (j = index; j < this->numberOfUsers - 1; j++) this->users[j] = this->users[j + 1]; this->numberOfUsers--; this->users[this->numberOfUsers] = 0; iteratorVersion++; } pthread_mutex_unlock(this->lock); } unsigned int Collection_size(struct UserThreadCollection*this) { return this->numberOfUsers; } unsigned int Collection_contains(struct UserThreadCollection*this, char*name) { struct UserThread* temp = new_MockUserThread(name, 0); int rv = Collection_containsByStruct(this, temp); dest_UserThread(temp); return rv; } unsigned int Collection_containsByStruct(struct UserThreadCollection*this, struct UserThread* user) { pthread_mutex_lock(this->lock); int i = 0; for (i = 0; i < this->numberOfUsers; i++) if (this->users[i]->equals(this->users[i], user)) { pthread_mutex_unlock(this->lock); return 1; } pthread_mutex_unlock(this->lock); return 0; } struct UserThread* Collection_getUser(struct UserThreadCollection*this, const char* name) { struct UserThread* temp = new_MockUserThread(name, 0); int index = -1; pthread_mutex_lock(this->lock); index = getIndex(this, temp); dest_UserThread(temp); if (index >= 0) { pthread_mutex_unlock(this->lock); return this->users[index]; } pthread_mutex_unlock(this->lock); return 0; } struct UserThreadIterator* Collection_iterator(struct UserThreadCollection*this) { return new_UserThreadIterator(this); } int getIndex(struct UserThreadCollection*this, struct UserThread* info) { int i = -1; for (i = 0; i < this->numberOfUsers; i++) if (this->users[i]->equals(this->users[i], info)) return i; return -1; }
0
#include <pthread.h> pthread_mutex_t lock; int pos; int jointSocket[4]; void signal_callback_handler(int signum) { printf("Caught signal %d\\n", signum); exit(signum); } void *writeThread(void*); void *readThread(void*); int main(int argc, char *argv[]){ pthread_t rT, wT; int socket[4] = {4, 5, 6, 11}; int i; int id[4] = {1,2,3,4}; for(i = 0; i<argc-1; i++){ if(dxl_initialize(&jointSocket[i], socket[i], 8) == 0){ printf("Failed to open port /dev/ttyS%d\\n", socket[i]); return -1; } } for(i = 0; i <4 ; i++){ printf("%d\\n",jointSocket[i] ); } for(i = 1; i<4; i++){ dxl_write_word(jointSocket[i], id[i], 0x18, 1); } pos = -1; pthread_create(&rT, 0, readThread, 0); pthread_create(&wT, 0, writeThread, 0); sleep(10); return 0; } void *writeThread(void* n){ pthread_detach(pthread_self()); while(1){ pthread_mutex_lock(&lock); dxl_write_word(jointSocket[1], 3, 0x1E, pos); pthread_mutex_unlock(&lock); } return 0; } void *readThread(void *n){ pthread_detach(pthread_self()); while(1){ pthread_mutex_lock(&lock); pos = dxl_read_word(jointSocket[0], 1, 0x24); if(dxl_get_result() != 1) pos = -1; pthread_mutex_unlock(&lock); printf("%d\\n", pos); } return 0; }
1
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[5]; int sorted[5]; void producer () { int i, idx; for (i = 0; i < 5; i++) { idx = findmaxidx (source, 5); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 5; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 5; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0