text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static pthread_mutex_t taskLock; static pthread_mutex_t outputLock; static sem_t taskSem; static sem_t outputSem; double compute(int x, int n); void *WorkThread(); struct node { int x; int n; double res; pthread_t tid; struct node *next; } taskQHead, outputQHead, *tmpNode; int main(int argc, char *argv[]) { int ret; double res = 0; void *status; if (argc != 7) { printf("Usage: ./mtexponential -x X -n N -t T\\n"); return 0; } int x = atoi(argv[2]); int n = atoi(argv[4]); int t = atoi(argv[6]); int i; ret = pthread_mutex_init(&taskLock, 0); ret = pthread_mutex_init(&outputLock, 0); ret = sem_init(&taskSem, 0, 0); ret = sem_init(&outputSem, 0, 0); pthread_t pool[t]; for (i = 0; i < t; i++) { ret = pthread_create(&pool[i], 0, WorkThread, 0); } for (i = 0; i <= n; i++) { pthread_mutex_lock(&taskLock); tmpNode = (struct node *)malloc(sizeof(struct node)); tmpNode->x = x; tmpNode->n = i; tmpNode->next = 0; taskQHead.next = tmpNode; pthread_mutex_unlock(&taskLock); sem_post(&taskSem); } for (i = 0; i <= n; i++) { sem_wait(&outputSem); pthread_mutex_lock(&outputLock); struct node *cOutput = outputQHead.next; outputQHead.next = outputQHead.next->next; pthread_mutex_unlock(&outputLock); res += cOutput->res; printf("%d^%d / %d! : %f. From thread %zu\\n", x, cOutput->n, cOutput->n, cOutput->res, cOutput->tid); free(cOutput); } for (i = 0; i < t; i++) { pthread_cancel(pool[i]); pthread_join(pool[i], &status); } printf("SUM(%d^n / n!) = %f\\n", x, res); pthread_exit(0); } void *WorkThread() { while(1) { sem_wait(&taskSem); pthread_mutex_lock(&taskLock); struct node *cTask = taskQHead.next; if (cTask == 0) { pthread_mutex_unlock(&taskLock); continue; } taskQHead.next = taskQHead.next->next; pthread_mutex_unlock(&taskLock); cTask->res = compute(cTask->x, cTask->n); cTask->tid = pthread_self(); pthread_mutex_lock(&outputLock); cTask->next = outputQHead.next; outputQHead.next = cTask; pthread_mutex_unlock(&outputLock); sem_post(&outputSem); } } double compute(int x, int n) { if (n == 0) return 1; int n_f = 1; int i; for (i = 1; i <= n; i++) { n_f *= i; } double res = pow(x, n) / n_f; return res; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; unsigned long tmp_start; unsigned long tmp_end; struct pthread_args { unsigned long start, end, out, chunk_size, a, b; }; void * check_is_prime(void *ptr) { struct pthread_args *arg = ptr; long N, j; unsigned long sqrRoot, endVal; int check; endVal = arg->b; arg->out = 0; if ((arg->b - arg->a) < arg->chunk_size) { arg->chunk_size = (arg->b - arg->a); } while (tmp_end <= endVal) { pthread_mutex_lock(&mutex); tmp_start = tmp_end + 1; tmp_end = tmp_start + arg->chunk_size - 1; arg->start = tmp_start; arg->end = tmp_end; pthread_mutex_unlock(&mutex); for (N = arg->start; N <= arg->end; N++) { check = 1; sqrRoot = sqrt(N) + 1; for (j = 2; j <= sqrRoot; j++) { if ((N % j) == 0) { check = 0; break; } } if (check == 1) { arg->out++; } } } return 0; } unsigned long prime_count(unsigned long a, unsigned long b, unsigned long num_threads, unsigned long chunk_size) { long j; unsigned long count = 0; tmp_start = 0; tmp_end = a; pthread_t *thread; thread = malloc(num_threads * sizeof (*thread)); struct pthread_args *thread_arg; thread_arg = malloc(num_threads * sizeof (*thread_arg)); for (j = 0; j < num_threads; j++) { thread_arg[j].a = a; thread_arg[j].b = b; thread_arg[j].chunk_size = chunk_size; } for (j = 0; j < num_threads; j++) { pthread_create(&thread[j], 0, &check_is_prime, &thread_arg[j]); } for (j = 0; j < num_threads; j++) { pthread_join(thread[j], 0); count += thread_arg[j].out; } free(thread); free(thread_arg); return count; }
0
#include <pthread.h> int stack[10][2]; int size = 0; sem_t sem; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void provide_data(void) { int i; for (i = 0; i < 10; i++) { stack[i][0] = i; stack[i][1] = i; sem_post(&sem); } } void handle_data1(void) { int i; while (pthread_mutex_lock(&mutex), ((i = size++) < 10)) { pthread_mutex_unlock(&mutex); sem_wait(&sem); printf("Plus: %d + %d = %d\\n", stack[i][0], stack[i][1], stack[i][0] + stack[i][1]); } pthread_mutex_unlock(&mutex); } void handle_data2(void) { int i; while (pthread_mutex_lock(&mutex), ((i = size++) < 10)) { pthread_mutex_unlock(&mutex); sem_wait(&sem); printf("Multiple: %d * %d = %d\\n", stack[i][0], stack[i][1], stack[i][0] * stack[i][1]); } pthread_mutex_unlock(&mutex); } int main(void) { pthread_t thrd1, thrd2, thrd3; sem_init(&sem, 0, 0); pthread_create(&thrd1, 0, (void *)handle_data1, 0); pthread_create(&thrd2, 0, (void *)handle_data2, 0); pthread_create(&thrd3, 0, (void *)provide_data, 0); pthread_join(thrd1, 0); pthread_join(thrd2, 0); pthread_join(thrd3, 0); sem_destroy(&sem); return 0; }
1
#include <pthread.h> struct item { char stuff[31337 * 1024]; struct item * next; }; struct cache_items { struct item * head; struct item * tail; pthread_mutex_t lock; } cache; void hog_memory() { struct item * thing = malloc(sizeof(struct item)); thing->next = 0; pthread_mutex_lock(&cache.lock); if (cache.tail) { cache.tail->next = thing; cache.tail = thing; } else { cache.head = thing; cache.tail = thing; } printf("program: \\tOink!\\n"); pthread_mutex_unlock(&cache.lock); usleep(200000); } int thing_count(struct item * thing) { if (0 == thing) { return 0; } return 1 + thing_count(thing->next); } extern void *osv_register_shrinker(const char *, size_t (*)(size_t, bool)); size_t shrinker_function(size_t target, bool hard) { size_t freed = 0; struct item * thing; pthread_mutex_lock(&cache.lock); if (hard == 0) { printf("shrinker:\\tSoft pressure, all done.\\n"); pthread_mutex_unlock(&cache.lock); return 0; } printf("shrinker:\\tprocessing request to free %08d bytes.\\n", target); printf("\\t\\tstarting with %d things.\\n", thing_count(cache.head)); thing = cache.head; while (thing && freed <= target) { cache.head = thing->next; free(thing); freed += sizeof(struct item); thing = cache.head; } printf("\\t\\tfinishing with %d things.\\n", thing_count(cache.head)); printf("\\t\\t%08d bytes of memory were freed!\\n", freed); sleep(2); pthread_mutex_unlock(&cache.lock); return freed; } int main (int argc, int **argv) { cache.head = 0; cache.tail = 0; pthread_mutex_init(&cache.lock, 0); printf("I'm a memory hog!\\n"); osv_register_shrinker("Example Shrinker", shrinker_function); for (;;) { hog_memory(); } }
0
#include <pthread.h> pthread_mutex_t g_mutex; int g_a = 0; int g_b = 0; int g_c = 0; double get_time_ms() { struct timeval tv; gettimeofday(&tv,0); return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; } void * use_mutex(void *arg) { double time1 = get_time_ms(); int count = *((int *)arg); while (count > 0) { pthread_mutex_lock(&g_mutex); g_a++; pthread_mutex_unlock(&g_mutex); count--; } double time2 = get_time_ms(); printf("use_mutex:time=%lfms\\n", time2-time1); return 0; } void * use_sync(void *arg) { double time1 = get_time_ms(); int count = *((int *)arg); while (count > 0) { __sync_fetch_and_add(&g_b, 1); count--; } double time2 = get_time_ms(); printf("use_sync:time=%lfms\\n", time2-time1); return 0; } void * no_lock(void *arg) { double time1 = get_time_ms(); int count = *((int *)arg); while (count > 0) { g_c++; count--; } double time2 = get_time_ms(); printf("no_lock:time=%lfms\\n", time2-time1); return 0; } int main(int argc, char **argv) { printf("hello locker\\n"); pthread_mutex_init(&g_mutex, 0); int count = 10000; { pthread_t t1, t2, t3; pthread_create(&t1, 0, use_mutex, &count); pthread_create(&t2, 0, use_mutex, &count); pthread_create(&t3, 0, use_mutex, &count); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); printf("g_a=%d\\n\\n", g_a); } { pthread_t t1, t2, t3; pthread_create(&t1, 0, use_sync, &count); pthread_create(&t2, 0, use_sync, &count); pthread_create(&t3, 0, use_sync, &count); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); printf("g_b=%d\\n\\n", g_b); } { pthread_t t1, t2, t3; pthread_create(&t1, 0, no_lock, &count); pthread_create(&t2, 0, no_lock, &count); pthread_create(&t3, 0, no_lock, &count); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); printf("g_c=%d\\n\\n", g_c); } return 0; }
1
#include <pthread.h> pthread_t student_array[4]; pthread_t ta_thread; pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; int waiting_students = 0; int thread_helped_counter[4]; unsigned int seed = 92; int sleep_time; int waiting_queue[2]; void * students(void * param); void * ta(); void create_students(); void create_ta(); void join_students(); void join_ta(); int value; int main(){ printf("%s\\n","CS149 SleepTA from Maninderpal Singh" ); sem_init(&students_sem,0,1); sem_init(&ta_sem,0,1); create_students(); create_ta(); join_students(); join_ta(); sem_destroy(&students_sem); sem_destroy(&ta_sem); } void join_ta() { if(pthread_join(ta_thread, 0)) { fprintf(stderr, "Error joining thread\\n"); } } void join_students() { int i; for(i = 0; i < 4; i++) { if(pthread_join(student_array[i], 0)) { fprintf(stderr, "Error joining thread\\n"); } } } void create_ta() { if(pthread_create(&ta_thread, 0, ta, 0)) { fprintf(stderr, "TA thread creation error\\n"); } } void create_students() { int i; for(i = 0; i < 4; i++) { int *arg = malloc(sizeof(*arg)); *arg = i; if(pthread_create(&student_array[i], 0, students, (void *)arg)) { fprintf(stderr, "Student thread creation error\\n"); } } if(pthread_create(&ta_thread, 0, ta, 0)) { fprintf(stderr, "TA thread creation error\\n"); } } void * students(void * param){ int i = *((int *)param); int sleeptime = (rand_r(&seed)% 3)+1; printf(" Student %d programming for %d seconds.\\n", i, sleeptime); sleep(sleeptime); pthread_mutex_lock(&mutex_lock); if(thread_helped_counter[i] >= 2) { pthread_mutex_unlock(&mutex_lock); return 0; } pthread_mutex_unlock(&mutex_lock); pthread_mutex_lock(&mutex_lock); sem_getvalue(&ta_sem, &value); pthread_mutex_unlock(&mutex_lock); if(value > 0) { sem_wait(&ta_sem); pthread_mutex_lock(&mutex_lock); if(waiting_students >= 0 && waiting_students < 2) { if(waiting_students == 0) { waiting_queue[0] = i; waiting_students++; } else if(waiting_students == 1) { waiting_queue[1] = i; waiting_students++; } pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sleep_time = (rand_r(&seed)% 3)+1; sleep(sleep_time); } else { printf("\\nwaiting list > 2\\n"); pthread_mutex_unlock(&mutex_lock); printf("\\t\\t\\tStudent %d will try later\\n", i); sleep((rand_r(&seed)% 3)+1); students(&i); } } else { sem_post(&students_sem); } students((void*)&i); } void * ta(){ int i,result; for(i=0;i< 4; i++){ result+=thread_helped_counter[i]; } if(result == 8){ return 0; } sem_wait(&students_sem); pthread_mutex_lock(&mutex_lock); sleep_time = (rand_r(&seed)% 3)+1; if(waiting_students == 1 && thread_helped_counter[waiting_queue[0]] < 2) { waiting_students--; printf("Student %d recieving help\\n", waiting_queue[0]); thread_helped_counter[waiting_queue[0]]++; } else if(waiting_students == 2 && thread_helped_counter[waiting_queue[1]] < 2){ waiting_students--; printf("Student %d recieving help\\n", waiting_queue[1]); thread_helped_counter[waiting_queue[1]]++; } pthread_mutex_unlock(&mutex_lock); sleep(sleep_time); sem_post(&ta_sem); ta(); }
0
#include <pthread.h> struct reg { int *inicio; int *fim; int *vet; int n; }; int somatorio[4]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * function (void *arg) { struct reg *valor; valor = (struct reg*) arg; printf("inicio %d\\n",valor->inicio[valor->n]); printf("fim %d\\n",valor->fim[valor->n]); int i; for (i = valor->inicio[valor->n]; i < valor->fim[valor->n]; i++) { pthread_mutex_lock(&mutex); somatorio[valor->n] += valor->vet[i]; pthread_mutex_unlock(&mutex); } } int* geradorDeNumeros(int M, int K){ unsigned short seed[]={12,1,2}; int i; int *vetor = malloc(sizeof(int)*M); for(i=0; i<M; i++) vetor[i] = 1 + K * erand48(seed); return vetor; } int main () { clock_t time1, time2, time_diff; int qtdnum, intervalo, *vet; struct timeval antes, depois; float delta, delta2; int K = (2048*1024); qtdnum = K; intervalo = 10000; vet = geradorDeNumeros(qtdnum, intervalo); pthread_t threads[4]; int vetFim[4]; int vetIni[4]; int result = K / 4; vetFim[0] = result; vetIni[0] = 0; int l = 1; while(l < 4) { vetIni[l] = vetFim[l-1]; vetFim[l] = vetFim[l-1] + result; l++; } struct reg x; x.inicio = vetIni; x.fim = vetFim; x.vet = vet; struct reg aux[4]; for(int i = 0; i < 4; i++) { aux[i] = x; aux[i].n = i; } int i = 0; gettimeofday (&antes, 0); for(i = 0; i < 4; i++) { pthread_create(&threads[i], 0, function, (void *)(&aux[i])); } for(i = 0; i < 4; i++) { pthread_join(threads[i], 0); } gettimeofday (&depois, 0); printf("Somatorio %d\\n",somatorio[0]); delta = (depois.tv_sec + depois.tv_usec/1000000.0) - (antes.tv_sec + antes.tv_usec /1000000.0); delta2 = ((depois.tv_sec * 1000000 + depois.tv_usec) - (antes.tv_sec * 1000000 + antes.tv_usec)); printf("Tempo de execução em segundos %f segundos & Diferenca de %f microsegundos\\n\\n", delta, delta2); exit(0); }
1
#include <pthread.h> pthread_mutex_t chops[5]; void pinit(int a, int *b,int *c) { *b=(a>0)?(a-1):5; *c=a; printf("Philosopher %d started",a+1); return; } int check_spoon(int a,int b,int c) { int sum=0; if(a&1) { ( sum=(pthread_mutex_trylock(&chops[c])))==0 ? 0:10; (sum+= ( pthread_mutex_trylock(&chops[b])))==0 ?0:1; } else { (sum= (pthread_mutex_trylock(&chops[b])))==0?0:1; (sum+=(pthread_mutex_trylock(&chops[c])))==0?0:10; } return sum; } void rel(int a,int b,int c) { if(a&1) { pthread_mutex_unlock(&chops[b]); pthread_mutex_unlock(&chops[c]); } else { pthread_mutex_unlock(&chops[c]); pthread_mutex_unlock(&chops[b]); } } void wait(int a,int b,int c,int d) { switch(a) { case 1:printf("Philosopher %d waiting: r unavailable\\n",b+1); pthread_mutex_lock(&chops[c]); break; case 10: printf("Philosopher %d waiting: l unavailable\\n",b+1); pthread_mutex_lock(&chops[d]); break; case 11: printf("philosopher %d waiting: land r unavilable\\n",b+1); pthread_mutex_lock(&chops[c]); pthread_mutex_lock(&chops[d]); break; } return; } void eat(int a) { printf("phil %d eating \\n",a+1); sleep(rand()%5); printf("phil %d finished\\n",a+1); } void *phil(void *arg){ int back,front,tmp; int id= *(int*)arg; pinit(id,&back,&front); while(1) { printf("phil %d thinking \\n",id+1); sleep(rand()%6); if((tmp=check_spoon(id,back,front))!=0) { wait(tmp,id,back,front); eat(id); rel(id,back,front); } } } int main() { pthread_t ph[5]; int *q; int i; char msg[10]; for(i=0;i<5;i++) { pthread_mutex_init(&chops[i],0); } q=(int*)malloc(5*sizeof(int)); for(i=0;i<5;i++) { q[i]=i; pthread_create(&ph[i],0,phil,(void*)&q[i]); } pthread_join(ph[0],0); }
0
#include <pthread.h> struct cleaner_entry { struct cleaner_entry* next; void (*func)(void*); void* etc; }; static struct cleaner { struct cleaner_entry* head; pthread_mutex_t mtx; } cleaner; void ws_cleaner_init(void) { cleaner.head = 0; pthread_mutex_init(&cleaner.mtx, 0); } int ws_cleaner_add( void (*cleaner_func)(void*), void* etc ) { struct cleaner_entry* e = calloc(1, sizeof(*e)); if (!e) { return -ENOMEM; } e->etc = etc; e->func = cleaner_func; pthread_mutex_lock(&cleaner.mtx); e->next = cleaner.head; cleaner.head = e; pthread_mutex_unlock(&cleaner.mtx); return 0; } bool ws_cleaner_run(void) { pthread_mutex_lock(&cleaner.mtx); struct cleaner_entry* iter = cleaner.head; struct cleaner_entry* next = iter; while (iter) { iter->func(iter->etc); next = iter->next; free(iter); iter = next; } pthread_mutex_destroy(&cleaner.mtx); return 1; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t flag; void* work(void* v) { const char* id = (const char*) v; printf("%s waiting for event\\n", id); pthread_mutex_lock(&mutex); pthread_cond_wait(&flag, &mutex); printf("\\t%s proceeding after event\\n", id); pthread_mutex_unlock(&mutex); return 0; } int main(void) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&flag, 0); pthread_t t1, t2, t3; pthread_create(&t1, 0, work, (void*) "1"); pthread_create(&t2, 0, work, (void*) "2"); pthread_create(&t3, 0, work, (void*) "3"); printf("... main waiting for 10 seconds\\n"); sleep(10); printf("... main clearing flag\\n"); pthread_cond_broadcast(&flag); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); printf("\\nEnd of main"); }
0
#include <pthread.h> pthread_mutex_t varLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t varCond = PTHREAD_COND_INITIALIZER; int data[256][8192]; int remain = 16; void *calc(void *param) { int x, y, start = 16 * (int) param; int end = start + 16; for (x = start; x < end; x++) for (y = 0; y < 8192; y++) printf("Calculando...\\n"); printf("Fim de cálculo.\\n"); pthread_mutex_lock(&varLock); remain--; if (remain == 0) { printf("Todas as threads executaram.\\n"); pthread_cond_broadcast(&varCond); } else { while (remain != 0) { printf("Ainda há threads que precisam executar.\\n"); pthread_cond_wait(&varCond, &varLock); } } pthread_mutex_unlock(&varLock); } int main(int argc, char const *argv[]) { pthread_t threads[16]; for (size_t i = 0; i < 16; i++) pthread_create(&threads[i], 0, calc, (void *) i); return 0; }
1
#include <pthread.h> static int malloc_count = 0; static int free_count = 0; static long long int malloc_size = 0; static long long int free_size = 0; static pthread_mutex_t s_regptr_mutex = PTHREAD_MUTEX_INITIALIZER; static struct { const void *ptr; const char *file; int line; size_t size; } malloc_table[5000000]; static void memfatal(const char *exec_name, const char *context, long attempted_size) { fprintf(stderr, "%s:%s: Failed to allocate %ld bytes, memory exhausted.\\n", exec_name, context, attempted_size); exit(1); } void* checking_malloc(size_t size) { void *ptr = malloc(size); if (0 == ptr) { memfatal(__FUNCTION__, "malloc", size); } return ptr; } void* checking_calloc(size_t num, size_t size) { void *ptr = calloc(num, size); if (!ptr) { memfatal(__FUNCTION__, "calloc", size); } return ptr; } char* checking_strdup(const char *s) { char *copy; copy = strdup(s); if (0 == copy) { memfatal(__FUNCTION__, "strdup", 1 + strlen(s)); } return copy; } void checking_free(void *ptr) { assert(ptr != 0); free(ptr); } static unsigned long hash_pointer(const void *ptr) { unsigned long key = (unsigned long)ptr; key += (key << 12); key ^= (key >> 22); key += (key << 4); key ^= (key >> 9); key += (key << 10); key ^= (key >> 2); key += (key << 7); key ^= (key >> 12); return key; } static inline int ptr_position(const void *ptr) { int i = hash_pointer(ptr) % 5000000; for (; 0 != malloc_table[i].ptr; i = (i + 1) % 5000000) { if (malloc_table[i].ptr == ptr) { return i; } } return i; } void xmalloc_debug_stats(void) { } static void register_ptr( const void *ptr, size_t size, const char *file, int line) { int i; if (malloc_count - free_count > 5000000) { fprintf(stderr, "Increase SZ to a larger value and recompile.\\n"); fflush(stderr); xmalloc_debug_stats(); abort(); } i = ptr_position(ptr); malloc_table[i].ptr = ptr; malloc_table[i].file = file; malloc_table[i].line = line; malloc_table[i].size = size; } static int unregister_ptr(void *ptr) { int i = ptr_position(ptr); if (0 == malloc_table[i].ptr) { return 0; } malloc_table[i].ptr = 0; free_size += malloc_table[i].size; for (i = (i + 1) % 5000000; 0 != malloc_table[i].ptr; i = (i + 1) % 5000000) { const void *ptr2 = malloc_table[i].ptr; int j = hash_pointer(ptr2) % 5000000; for (; malloc_table[j].ptr != 0; j = (j + 1) % 5000000) if (ptr2 == malloc_table[i].ptr) goto count_outer; malloc_table[j] = malloc_table[i]; malloc_table[i].ptr = 0; malloc_table[i].size = 0; count_outer: ; } return 1; } void* debugging_malloc( size_t size, const char *source_file, int source_line) { void *ptr = checking_malloc(size); pthread_mutex_lock(&s_regptr_mutex); ++malloc_count; malloc_size += size; register_ptr(ptr, size, source_file, source_line); pthread_mutex_unlock(&s_regptr_mutex); return ptr; } void *debugging_calloc(size_t numb, size_t size, const char *source_file, int source_line) { void *ptr = checking_calloc(numb, size); pthread_mutex_lock(&s_regptr_mutex); ++malloc_count; malloc_size += (numb * size); register_ptr(ptr, numb*size, source_file, source_line); pthread_mutex_unlock(&s_regptr_mutex); return ptr; } char *debugging_strdup( const char *s, const char *source_file, int source_line) { char *copy = checking_strdup(s); size_t size = strlen(copy) + 1; pthread_mutex_lock(&s_regptr_mutex); ++malloc_count; malloc_size += size; register_ptr(copy, size, source_file, source_line); pthread_mutex_unlock(&s_regptr_mutex); return copy; } void debugging_free(void *ptr, const char *source_file, int source_line) { if (0 == ptr) { fprintf(stderr, "xfree(NULL) at %s:%d\\n", source_file, source_line); fflush(stderr); abort(); } pthread_mutex_lock(&s_regptr_mutex); if (!unregister_ptr(ptr)) { fprintf(stderr, "Bad xfree() at %s:%d\\n", source_file, source_line); pthread_mutex_unlock(&s_regptr_mutex); abort(); } ++free_count; pthread_mutex_unlock(&s_regptr_mutex); checking_free(ptr); }
0
#include <pthread.h> int32_t comp_timeb(struct timeb *tpa, struct timeb *tpb) { return ((tpa->time - tpb->time) * 1000) + (tpa->millitm - tpb->millitm); } static int8_t is_leap(unsigned int y) { return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0); } time_t cs_timegm(struct tm *tm) { time_t result = 0; int32_t i; if (tm->tm_mon > 12 || tm->tm_mon < 0 || tm->tm_mday > 31 || tm->tm_min > 60 || tm->tm_sec > 60 || tm->tm_hour > 24) return 0; for (i = 70; i < tm->tm_year; ++i) { result += is_leap(i + 1900) ? 366 : 365; } for (i = 0; i < tm->tm_mon; ++i) { if(i == 0 || i == 2 || i == 4 || i == 6 || i == 7 || i == 9 || i == 11) result += 31; else if(i == 3 || i == 5 || i == 8 || i == 10) result += 30; else if(is_leap(tm->tm_year + 1900)) result += 29; else result += 28; } result += tm->tm_mday - 1; result *= 24; result += tm->tm_hour; result *= 60; result += tm->tm_min; result *= 60; result += tm->tm_sec; return result; } struct tm *cs_gmtime_r(const time_t *timep, struct tm *r) { static const int16_t daysPerMonth[13] = { 0, 31, 31 + 28, 31 + 28 + 31, 31 + 28 + 31 + 30, 31 + 28 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30, 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30 + 31 }; time_t i; time_t work =* timep % 86400; r->tm_sec = work % 60; work /= 60; r->tm_min = work % 60; r->tm_hour = work / 60; work =* timep/86400; r->tm_wday = (4 + work) % 7; for (i=1970; ; ++i) { time_t k = is_leap(i)?366:365; if (work >= k) work -= k; else break; } r->tm_year = i - 1900; r->tm_yday = work; r->tm_mday = 1; if (is_leap(i) && work > 58) { if (work == 59) r->tm_mday = 2; work -= 1; } for (i=11; i && daysPerMonth[i] > work; --i) ; r->tm_mon = i; r->tm_mday += work - daysPerMonth[i]; return r; } char *cs_ctime_r(const time_t *timep, char* buf) { struct tm t; localtime_r(timep, &t); strftime(buf, 26, "%c\\n", &t); return buf; } void cs_ftime(struct timeb *tp) { struct timeval tv; gettimeofday(&tv, 0); tp->time = tv.tv_sec; tp->millitm = tv.tv_usec / 1000; } void cs_sleepms(uint32_t msec) { struct timespec req_ts; req_ts.tv_sec = msec/1000; req_ts.tv_nsec = (msec % 1000) * 1000000L; int32_t olderrno = errno; nanosleep(&req_ts, 0); errno = olderrno; } void cs_sleepus(uint32_t usec) { struct timespec req_ts; req_ts.tv_sec = usec/1000000; req_ts.tv_nsec = (usec % 1000000) * 1000L; int32_t olderrno = errno; nanosleep (&req_ts, 0); errno = olderrno; } void add_ms_to_timespec(struct timespec *timeout, int32_t msec) { struct timeval now; gettimeofday(&now, 0); int32_t nano_secs = ((now.tv_usec * 1000) + ((msec % 1000) * 1000 * 1000)); timeout->tv_sec = now.tv_sec + (msec / 1000) + (nano_secs / 1000000000); timeout->tv_nsec = nano_secs % 1000000000; } int32_t add_ms_to_timeb(struct timeb *tb, int32_t ms) { struct timeb tb_now; tb->time += ms / 1000; tb->millitm += ms % 1000; if (tb->millitm >= 1000) { tb->millitm -= 1000; tb->time++; } cs_ftime(&tb_now); return comp_timeb(tb, &tb_now); } void sleepms_on_cond(pthread_cond_t *cond, pthread_mutex_t *mutex, uint32_t msec) { struct timespec ts; add_ms_to_timespec(&ts, msec); pthread_mutex_lock(mutex); pthread_cond_timedwait(cond, mutex, &ts); pthread_mutex_unlock(mutex); }
1
#include <pthread.h> char buf[100] = {0}; int flag = 0; pthread_mutex_t mutex; pthread_cond_t cond; void *func(void *arg) { sleep(1); while(flag == 0) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("输入了%d个字符\\n", strlen(buf)); pthread_mutex_unlock(&mutex); memset(buf, 0, sizeof(buf)); } } int main(void) { pthread_t th = -1; pthread_create(&th, 0, func, 0); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); printf("请输入字符,并以回车结束\\n"); while(1) { scanf("%s", buf); if(!strcmp("end", buf)) { printf("输入结束\\n"); flag = 1; pthread_cond_signal(&cond); break; } pthread_cond_signal(&cond); } printf("等待回收子线程\\n"); pthread_join(th, 0); printf("回收子线程成功\\n"); return 0; }
0
#include <pthread.h> int N ,T ; int v_counter = 0; int turn; pthread_mutex_t c_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_threshold_cv = PTHREAD_COND_INITIALIZER ; void *start_thread(void *thread_id) { int me,next,*ptrid, iter = 1; ptrid =(int *)thread_id; me = *ptrid; while(1) { next = (me+1)%T; pthread_mutex_lock(&c_mutex); while(turn!= me) { pthread_cond_wait(&c_threshold_cv,&c_mutex); } v_counter++; printf("\\nTHREAD %d in ITERATION %d ,COUNTER VALUE SET TO %d",me,iter,v_counter); pthread_mutex_unlock(&c_mutex); turn = next; pthread_cond_broadcast(&c_threshold_cv); if((++iter) > N) { printf("\\n EXIT THREAD:: %d\\n",me); pthread_exit(0); } } } int main(int argc, char *argv[]) { int i = 0,status = 0; N = atoi(argv[1]) ; T = atoi(argv[2]) ; pthread_t threads[T]; int thread_ids[T]; for (i = 0; i < T; i++) { thread_ids[i] = i ; status = pthread_create(&threads[i], 0, start_thread,&thread_ids[i]); if(status) printf("\\nThread couldnt be created ...."); } for (i = 0; i < T; ++i) pthread_join(threads[i], 0); return 0; }
1
#include <pthread.h> void Qaullib_Appevent_LL_Add (int event) { struct qaul_appevent_LL_item *new_item; new_item = (struct qaul_appevent_LL_item *)malloc(sizeof(struct qaul_appevent_LL_item)); new_item->event = event; new_item->next = 0; pthread_mutex_lock( &qaullib_mutex_appeventLL ); if(qaul_appevent_LL_first == 0) qaul_appevent_LL_first = new_item; else qaul_appevent_LL_last->next = new_item; qaul_appevent_LL_last = new_item; pthread_mutex_unlock( &qaullib_mutex_appeventLL ); } int Qaullib_Appevent_LL_Get () { struct qaul_appevent_LL_item *item; int event; if(qaul_appevent_LL_first == 0) event = 0; else { pthread_mutex_lock( &qaullib_mutex_appeventLL ); item = qaul_appevent_LL_first; event = item->event; qaul_appevent_LL_first = item->next; if(item->next == 0) qaul_appevent_LL_last = 0; pthread_mutex_unlock( &qaullib_mutex_appeventLL ); free(item); } return event; }
0
#include <pthread.h> struct pThreadKey { int inUse; void (*destructor)(void*); }; static struct pThreadKey pKeys[PTHREAD_KEYS_MAX]; static pthread_mutex_t pKeyMutex = PTHREAD_MUTEX_INITIALIZER; struct pthread_descr { void** specific[((PTHREAD_KEYS_MAX + 32 - 1) / 32)]; }; struct pthread_descr initial = { {0,} }; pthread_descr_t thread_self() { if (pGetCurrentThreadId() == 0) return &initial; exit(0); return 0; } int pthread_key_create(pthread_key_t* key, void (*destructor)(void*)) { int i; pthread_mutex_lock(&pKeyMutex); for (i=0; i<PTHREAD_KEYS_MAX; i++) { if (!pKeys[i].inUse) { pKeys[i].inUse = 1; pKeys[i].destructor = destructor; pthread_mutex_unlock(&pKeyMutex); *key = i; return 0; } } pthread_mutex_unlock(&pKeyMutex); return EAGAIN; } int pthread_key_delete(pthread_key_t key) { pthread_mutex_lock(&pKeyMutex); if (key >= PTHREAD_KEYS_MAX || !pKeys[key].inUse) { pthread_mutex_unlock(&pKeyMutex); return EINVAL; } pKeys[key].inUse = 0; pKeys[key].destructor = 0; pthread_mutex_unlock(&pKeyMutex); return 0; } int pthread_setspecific(pthread_key_t key,const void* value) { pthread_descr_t self; unsigned int firstLevel, secondLevel; if (key >= PTHREAD_KEYS_MAX || !pKeys[key].inUse) return EINVAL; self = thread_self(); firstLevel = key / 32; secondLevel = key % 32; if (!self->specific[firstLevel]) { self->specific[firstLevel] = calloc(32, sizeof(void*)); if (!self->specific[firstLevel]) return ENOMEM; } self->specific[firstLevel][secondLevel] = (void*)value; return 0; } void* pthread_getspecific(pthread_key_t key) { pthread_descr_t self; unsigned int firstLevel, secondLevel; if (key >= PTHREAD_KEYS_MAX) return 0; self = thread_self(); firstLevel = key / 32; secondLevel = key % 32; if (!self->specific[firstLevel] || !pKeys[key].inUse) return 0; return self->specific[firstLevel][secondLevel]; }
1
#include <pthread.h> struct aPhil { int philNum; int total; pthread_t * threads; pthread_mutex_t * forks; }typedef aPhil; void * philosopher(void * arg); void eatingBigMacs(int philNum); void philosophizing(int philNum); aPhil * createPhilosopher(int philNum); int isLastPhilosopher(aPhil * thePhilosopher); int main(int argc, char * argv[]) { aPhil * philosophers; int numEats; int numPhils; int i; int j; if(argc != 3) { printf("Please run the program as follows: ./dine <number of philosophers> <number of times they eat>\\n"); exit(1); } numPhils = atoi(argv[1]); numEats = atoi(argv[2]); if((numPhils < 3) || (numEats < 1) || (numEats > 1000)) { printf("Please ensure that the number of philosophers is greater than 2 and that the number of eats is from 1-1000\\n"); exit(1); } philosophers = createPhilosopher(numPhils); for(j = 0; j < numEats; j++) { for(i = 0; i < numPhils; i++) { philosophers->philNum = i; pthread_create(&philosophers->threads[i], 0, &philosopher, philosophers); pthread_join(philosophers->threads[i], 0); } } free(philosophers->threads); free(philosophers->forks); free(philosophers); return 0; } void philosophizing(int philNum) { printf("Philosopher %d is thinking\\n", (philNum + 1)); } void eatingBigMacs(int philNum) { printf("Philosopher %d is eating\\n", (philNum + 1)); sleep(1); } void * philosopher(void * arg) { aPhil * thePhilosopher = arg; pthread_mutex_lock(&thePhilosopher->forks[thePhilosopher->philNum]); if(isLastPhilosopher(thePhilosopher)) { pthread_mutex_lock(&thePhilosopher->forks[0]); } else { pthread_mutex_lock(&thePhilosopher->forks[thePhilosopher->philNum + 1]); } eatingBigMacs(thePhilosopher->philNum); pthread_mutex_unlock(&thePhilosopher->forks[thePhilosopher->philNum]); if(isLastPhilosopher(thePhilosopher)) { pthread_mutex_unlock(&thePhilosopher->forks[0]); } else { pthread_mutex_unlock(&thePhilosopher->forks[thePhilosopher->philNum + 1]); } philosophizing(thePhilosopher->philNum); return(0); } int isLastPhilosopher(aPhil * thePhilosopher) { if((thePhilosopher->philNum + 1) != (thePhilosopher->total)) { return 0; } return 1; } aPhil * createPhilosopher(int philNum) { int i; aPhil * new = malloc(sizeof(aPhil)); new->total = philNum; new->threads = malloc(sizeof(pthread_t) * philNum); new->forks = malloc(sizeof(pthread_mutex_t) * philNum); for (i = 0; i < philNum; i++) { philosophizing(i); pthread_mutex_init(&new->forks[i], 0); } return new; }
0
#include <pthread.h> struct control{ float period; float integral; float derivative; float error; float iMax; float iMin; float iState; float goal; }; struct control PID; pthread_mutex_t mutex; pthread_t uInput; void SetUp(){ PID.period = 1.0; PID.integral = 0.099; PID.derivative = 0.095; PID.iState=0; PID.iMin= -100.0; PID.iMax = 100.0; PID.goal= 5.0; PID.error=0.0; pthread_mutex_init(&mutex, 0); } void InitializeAD(){ uintptr_t gain_handle; uintptr_t chan_handle; gain_handle = mmap_device_io(1,0x280 +3); chan_handle = mmap_device_io(1,0x280 +2); out8(chan_handle,0x11); out8(gain_handle,0x0); } void start(){ uintptr_t write_handle; write_handle = mmap_device_io(1,0x280); out8(write_handle,0x80); } int16_t convertAD(){ uintptr_t status_handle; uintptr_t least_handle; uintptr_t most_handle; int LSB; int MSB; status_handle = mmap_device_io(1,0x280 +3); least_handle = mmap_device_io(1,0x280); most_handle = mmap_device_io(1,0x280 +1); start(); while(in8(status_handle)& 0x80){ } LSB = in8(least_handle); MSB = in8(most_handle); return MSB*256+LSB; } void convertDA(int16_t input){ uintptr_t lsb_handle; uintptr_t msb_handle; uintptr_t busy_handle; lsb_handle= mmap_device_io(1,0x280 +6); msb_handle =mmap_device_io(1,0x280 +7); busy_handle = mmap_device_io(1,0x280 +3); int8_t lsb = input&255; int8_t msb=input/256; out8(lsb_handle,lsb); out8(msb_handle,msb); while(in8(busy_handle)&0x10){ } } float compute(float error){ float pTerm, iTerm, dTerm; pthread_mutex_lock(&mutex); pTerm = PID.period * error; PID.iState+=error; if(PID.iState > PID.iMax){ PID.iState=PID.iMax; } if(PID.iState < PID.iMin){ PID.iState=PID.iMin; } iTerm= PID.integral * PID.iState; dTerm = PID.derivative +(PID.error-error); PID.error=error; pthread_mutex_unlock(&mutex); return pTerm+iTerm+dTerm; } void performMath(){ int16_t analog = 0; uint16_t convertOut = 0; float convertAnalog = 0; float out = 0.0; float error = 0.0; analog = convertAD(); convertAnalog = ((float) analog)/32768 * 10; pthread_mutex_lock(&mutex); error = PID.goal - convertAnalog; pthread_mutex_unlock(&mutex); out = compute(error); convertOut = (int)(((out/20)*2048)+2048); if(convertOut > 4095) convertOut = 4095; else if(convertOut < 0) convertOut = 0; convertDA(convertOut); } void * userControl(void * args){ float per; float inte; float der; while(1){ pthread_mutex_lock(&mutex); per = PID.period; inte=PID.integral; der=PID.derivative; pthread_mutex_unlock(&mutex); printf("Current Values- Period: %f, Integral %f, Derivative %f\\n",per, inte, der); printf("Enter Period \\n"); scanf("%f",&per); printf("Enter Integral \\n"); scanf("%f",&inte); printf("Enter Derivative \\n"); scanf("%f", &der); pthread_mutex_lock(&mutex); PID.period = per; PID.integral = inte; PID.derivative = der; pthread_mutex_unlock(&mutex); } } int main(int argc, char *argv[]) { int pid; int chid; int pulse_id = 0; struct _pulse pulse; struct _clockperiod clkper; struct sigevent event; struct itimerspec timer; timer_t timer_id; int privity_err; pthread_attr_t threadAttributes; struct sched_param parameters; int policy; pthread_attr_init(&threadAttributes); pthread_getschedparam(pthread_self(),&policy, &parameters); parameters.sched_priority--; pthread_attr_setdetachstate(&threadAttributes, PTHREAD_CREATE_JOINABLE); pthread_attr_setschedparam(&threadAttributes, &parameters); privity_err = ThreadCtl( _NTO_TCTL_IO, 0 ); if ( privity_err == -1 ) { fprintf( stderr, "can't get root permissions\\n" ); return -1; } clkper.nsec = 10000000; clkper.fract = 0; ClockPeriod(CLOCK_REALTIME, &clkper, 0, 0); chid = ChannelCreate(0); assert(chid != -1); event.sigev_notify = SIGEV_PULSE; event.sigev_coid = ConnectAttach(ND_LOCAL_NODE,0,chid,0,0); event.sigev_priority = getprio(0); event.sigev_code = 1023; event.sigev_value.sival_ptr = (void *)pulse_id; timer_create( CLOCK_REALTIME, &event, &timer_id ); timer.it_value.tv_sec = 0; timer.it_value.tv_nsec = 10000000; timer.it_interval.tv_sec = 0; timer.it_interval.tv_nsec = 10000000; timer_settime( timer_id, 0, &timer, 0 ); SetUp(); InitializeAD(); pthread_create(&uInput, &threadAttributes, &userControl, 0); while(1){ pid = MsgReceivePulse ( chid, &pulse, sizeof( pulse ), 0 ); performMath(); } return 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 () { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*10000000*sizeof(double)); b = (double*) malloc (4*10000000*sizeof(double)); for (i=0; i<10000000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 10000000; 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> static uint32_t nalloc_conn; static uint32_t nfree_conn; static struct conn_tqh free_connq; static pthread_mutex_t queue_lock; static pthread_mutex_t sum_lock; void conn_init(void) { ga_log(NOTICE, "conn size %d", sizeof(struct conn)); nfree_conn = 0; nalloc_conn = 0; TAILQ_INIT(&free_connq); pthread_mutex_init(&queue_lock, 0); pthread_mutex_init(&sum_lock, 0); } static struct conn *conn_create(void) { struct conn *conn; if (!TAILQ_EMPTY(&free_connq)) { pthread_mutex_lock(&queue_lock); conn = TAILQ_FIRST(&free_connq); nfree_conn--; TAILQ_REMOVE(&free_connq, conn, tqe); pthread_mutex_unlock(&queue_lock); } else { conn = ga_malloc(sizeof(struct conn)); if (conn == 0) return 0; pthread_mutex_lock(&sum_lock); ++nalloc_conn; pthread_mutex_unlock(&sum_lock); } return conn; } struct conn *conn_get(int sd, bool client) { struct conn *c = conn_create(); if (c == 0) return 0; c->sd = sd; c->rmsg = 0; c->smsg = 0; TAILQ_INIT(&c->omsg_q); c->recv_bytes = 0; c->send_bytes = 0; c->client = client; c->send_ready = 0; c->send_active = 0; c->recv_ready = 0; c->recv_active = 0; c->done = 0; c->err = 0; c->eof = 0; if (client) { c->recv = msg_recv; c->send = msg_send; c->close = client_close; } else { c->recv = server_recv; c->send = 0; c->close = 0; } return c; } void conn_put(struct conn *conn) { ga_log(NOTICE, "put conn %d", conn->sd); } int conn_recv(struct conn *conn, void *buf, size_t size) { ssize_t n; for (;;) { n = ga_read(conn->sd, buf, size); if (n > 0) { if (n < (ssize_t)size) { conn->recv_ready = 0; } conn->recv_bytes += (size_t)n; return n; } if (n == 0) { conn->recv_ready = 0; conn->eof = 1; return n; } if (errno == EINTR) { ga_log(ERROR, "recv on sd %d not ready - eintr", conn->sd); continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { conn->recv_ready = 0; ga_log(ERROR, "recv on sd %d not ready - eagain", conn->sd); return GA_EAGAIN; } else { conn->recv_ready = 0; conn->err = errno; ga_log(ERROR, "recv on sd %d failed: %s", conn->sd, strerror(errno)); return GA_ERR; } } return GA_ERR; } ssize_t conn_sendv(struct conn *conn, struct array *sendv, size_t nsend) { ssize_t n; for (;;) { n = ga_writev(conn->sd, sendv->elem, sendv->nelem); if (n > 0) { if (n < (ssize_t) nsend) { conn->send_ready = 0; } conn->send_bytes += (size_t)n; return n; } if (n == 0) { ga_log(NOTICE, "sendv on sd %d return zero", conn->sd); conn->send_ready = 0; return 0; } if (errno == EINTR) { ga_log(NOTICE, "sendv on sd %d not ready - eintr", conn->sd); continue; } else if (errno == EAGAIN || errno == EWOULDBLOCK) { conn->send_ready = 0; ga_log(NOTICE, "sendv on sd %d not ready - eagain", conn->sd); return GA_EAGAIN; } else { conn->send_ready = 0; conn->err = errno; ga_log(NOTICE, "sendv on sd %d failed: %s", conn->sd, strerror(errno)); return GA_ERR; } } return GA_ERR; }
1
#include <pthread.h> pthread_mutex_t help_mutex; pthread_mutex_t count_mutex; sem_t TA_sem; sem_t student_sem; int number_waiting; int go_home; long nsecSleep; int numberOfIterations; int studentNumber; } sleepAndCount; void* student(void* param); void* tA(void* param); int main(int argc, char** argv) { if (argc != 2) { printf("Usage: ./organize <number of students>\\n"); return 1; } int numberOfStudents = atoi(argv[1]); if (numberOfStudents <= 0) { printf("Error: Number of students must be a positive integer.\\n"); return 2; } sem_init(&TA_sem, 0, 1); sem_init(&student_sem, 0, 0); number_waiting = 0; go_home = 0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&help_mutex, 0); pthread_mutex_init(&count_mutex, 0); pthread_t tid_TA; pthread_create(&tid_TA, &attr, tA, 0); pthread_t* tid_students[numberOfStudents]; sleepAndCount* params[numberOfStudents]; int i; for (i = 0; i < numberOfStudents; ++i) { srand(time(0) + i); tid_students[i] = malloc(sizeof(pthread_t)); params[i] = malloc(sizeof(sleepAndCount)); params[i]->nsecSleep = (long) rand() % 1000000000; params[i]->numberOfIterations = 10; params[i]->studentNumber = i+1; pthread_create(tid_students[i], &attr, student, params[i]); } for (i = 0; i < numberOfStudents; ++i) { pthread_join(*tid_students[i], 0); free(tid_students[i]); free(params[i]); } go_home = 1; sem_post(&TA_sem); pthread_join(tid_TA, 0); pthread_attr_destroy(&attr); pthread_mutex_destroy(&help_mutex); pthread_mutex_destroy(&count_mutex); sem_destroy(&TA_sem); sem_destroy(&student_sem); return 0; } void* tA(void* param) { srand(time(0) / 2); struct timespec time; time.tv_sec = 1; time.tv_nsec = (long) rand() % 1000000000; while (1) { printf("TA sleeping, number_waiting = %d\\n",number_waiting); sem_wait(&TA_sem); if (go_home) break; printf("TA awake, number_waiting = %d\\n",number_waiting); pthread_mutex_lock(&help_mutex); sem_post(&student_sem); pthread_mutex_lock(&count_mutex); number_waiting--; pthread_mutex_unlock(&count_mutex); printf("TA helping student, number_waiting = %d\\n",number_waiting); nanosleep(&time, 0); pthread_mutex_unlock(&help_mutex); } pthread_exit(0); } void* student(void* param) { struct timespec time; time.tv_sec = 0; time.tv_nsec = ((sleepAndCount*)param)->nsecSleep; int count = ((sleepAndCount*)param)->numberOfIterations; int stuNum = ((sleepAndCount*)param)->studentNumber; int i; for (i = 0; i < count; ++i) { printf("student %d programming, number_waiting = %d\\n",stuNum,number_waiting); nanosleep(&time, 0); pthread_mutex_lock(&count_mutex); if (number_waiting >= 3) { printf("student %d waiting for chair, number_waiting = %d\\n",stuNum, number_waiting); pthread_mutex_unlock(&count_mutex); } else { number_waiting++; pthread_mutex_unlock(&count_mutex); sem_post(&TA_sem); printf("student %d waiting in chair %d, number_waiting = %d\\n",stuNum, number_waiting, number_waiting); sem_wait(&TA_sem); pthread_mutex_lock(&help_mutex); pthread_mutex_unlock(&help_mutex); } } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t p_lock; void bt_print(void* args); int s_test_1(){ printf("[+] Stress Test-1: START\\n"); struct threadpool_t *pool; int tadded = 0; if((pool = tpool_init(MAXTHREADS, MAXTASKS)) == 0){ printf(" [!] ERROR: POOL == NULL\\n"); return 1; } printf(" [*] Created threadpool_t with %d threads and queue size of %d\\n", MAXTHREADS, MAXTASKS); printf(" [*] Adding %d tasks (bt_print) to pool in sparatic intervals\\n", MAXTASKS*5); for (int i = 0; i < (MAXTASKS*5); i++){ while(add_task(pool, &bt_print, 0)){ printf("[!] QUEUE FULL\\n"); } tadded++; } sleep(5); printf(" [*] Shutting down threadpool_t with %d threads and queue size of %d\\n", MAXTHREADS, MAXTASKS); if(tpool_exit(pool)){ printf(" [!] ERROR: FREE POOL FAILURE\\n"); return 1; } printf("Added %d tasks\\n", tadded); printf("[+] Stress Test-1: SUCCESSFUL\\n"); return 0; } int main(){ if(s_test_1()){ printf("[!] Stress Test-1 failed\\n"); return 1; } return 0; } void bt_print(void* args){ pthread_mutex_lock(&p_lock); pthread_t id = pthread_self(); printf("Thread: %zu\\n", id); pthread_mutex_unlock(&p_lock); }
1
#include <pthread.h> pthread_t thr_stud[25]; pthread_t thr_dean; pthread_mutex_t stud_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dean_mutex = PTHREAD_MUTEX_INITIALIZER; int students_at_party; int dean_in_room; void test1(void); void test2(void); void break_party(void); void enter_room(void); void dbg_student(const char* message) { printf("Student %ld %s - dir=%d sap=%d\\n", pthread_self(), message, dean_in_room, students_at_party); } void dbg_dean(const char* message) { printf(">> Dean %s - dir=%d sap=%d\\n", message, dean_in_room, students_at_party); } void *stud_func(void *arg) { enter_room(); pthread_exit(0); } void *dean_func(void *arg) { break_party(); pthread_exit(0); } void start_student(int idx) { int rc; rc = pthread_create(&thr_stud[idx], 0, stud_func, 0); if (rc != 0) exit(1); } void start_dean(void) { int rc; rc = pthread_create(&thr_dean, 0, dean_func, 0); if (rc != 0) exit(1); } void party(void) { while (1) { pthread_mutex_lock(&stud_mutex); if (dean_in_room == 1) { dbg_student("will stop partying"); students_at_party--; pthread_mutex_unlock(&stud_mutex); return; } pthread_mutex_unlock(&stud_mutex); } } void enter_room(void) { pthread_mutex_lock(&stud_mutex); dbg_student("trying to..."); if (dean_in_room == 0) { dbg_student("no dean => party"); students_at_party++; pthread_mutex_unlock(&stud_mutex); party(); } else { dbg_student("silently run away"); pthread_mutex_unlock(&stud_mutex); } } void break_party(void) { while (1) { sleep(1); pthread_mutex_lock(&dean_mutex); dbg_dean("wild_party || no students_at_party"); dbg_dean("in mutex 1"); if (students_at_party >= 7 || students_at_party == 0) { dean_in_room = 1; dbg_dean("entered the room"); pthread_mutex_unlock(&dean_mutex); break; } pthread_mutex_unlock(&dean_mutex); } while (1) { sleep(1); dbg_dean("wait for everyone to leave the party"); pthread_mutex_lock(&dean_mutex); dbg_dean("in mutex 2"); if (students_at_party == 0) { dbg_dean("everyone left the party, exiting..."); dean_in_room = 0; pthread_mutex_unlock(&dean_mutex); return; } pthread_mutex_unlock(&dean_mutex); } } void wait_all(void) { int i; for (i = 0; i < 25; i++) pthread_join(thr_stud[i], 0); pthread_join(thr_dean, 0); } int main(int argc, char const *argv[]) { srand(time(0)); test1(); test2(); return 0; } void test1(void) { printf("=== TEST 1 === \\n"); int i; start_dean(); sleep(1); for (i = 0; i < 25; i++) start_student(i); wait_all(); printf("=== TEST 1 DONE === \\n"); } void test2(void) { printf("=== TEST 2 === \\n"); int i; for (i = 0; i < 25; i++) { start_student(i); if((rand() % (25 - i)) < 5) { start_dean(); break; } } for(; i < 25; i++) start_student(i); wait_all(); printf("=== TEST 2 DONE === \\n"); }
0
#include <pthread.h> struct LinkedList *createLinkedList() { struct LinkedList *list = malloc(sizeof(struct LinkedList)); list->mutex = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(list->mutex, 0); return list; } int contains(struct LinkedList *a, char *name) { pthread_mutex_lock(a->mutex); for(struct Node *current = a->head; current != 0; current = current->next) { if(!strcmp(current->name, name)){ pthread_mutex_unlock(a->mutex); return 1; } } pthread_mutex_unlock(a->mutex); return 0; } struct Node *retrieveNode(struct LinkedList *list, char *name) { pthread_mutex_lock(list->mutex); for(struct Node *current = list->head; current != 0; current = current->next) { if(!strcmp(current->name, name)){ pthread_mutex_unlock(list->mutex); return current; } } pthread_mutex_unlock(list->mutex); return 0; } int removeNode(struct LinkedList *list, char *name) { pthread_mutex_lock(list->mutex); struct Node *previous; struct Node *current; current = list->head; previous = 0; while(current->name != name) { previous = current; current = current->next; if(current == 0) { pthread_mutex_unlock(list->mutex); return 0; } } if(previous == 0) { list->head = current->next; } else { previous->next = current->next; } free(current->name); free(current); pthread_mutex_unlock(list->mutex); return 1; } void addNode(struct LinkedList *list, char *name, int value) { struct Node *current; struct Node *previous = 0; struct Node *new = (struct Node *) malloc(sizeof(struct Node)); new->name = name; new->value = value; pthread_mutex_lock(list->mutex); if(list->head == 0) { list->head = new; new->next = 0; pthread_mutex_unlock(list->mutex); return; } current = list->head; while(strcmp(current->name, name) < 0) { if(current->next == 0) { current->next = new; new->next = 0; pthread_mutex_unlock(list->mutex); return; } previous = current; current = current->next; } if(current == list->head) { new->next = current; list->head = new; } else { previous->next = new; new->next = current; } pthread_mutex_unlock(list->mutex); } void print_linked_list(struct LinkedList *list) { for(struct Node *current = list->head; current != 0; current = current->next) { fprintf(stdout, "%s:%d\\n", current->name, current->value); } fprintf(stdout, "\\n"); }
1
#include <pthread.h> long GlobalSumValues = 0; int GlobalX = 0; pthread_mutex_t mutexsum; void *Xpower2I(void *threadid) { int taskId; taskId = (int)threadid; long i=0, tmepvalue = 1; int LocalPower=0; for (i =0; i < taskId; i++) { tmepvalue *= GlobalX; } pthread_mutex_lock(&mutexsum); GlobalSumValues += tmepvalue; printf("\\ntaskId:%d ,\\tLocalSumValue = %ld,\\tGlobalSumValues = %ld ",taskId,tmepvalue, GlobalSumValues); pthread_mutex_unlock(&mutexsum); pthread_exit(0); } void main(int argc, char *argv[]) { if(argc != 3){ printf("\\nInput arrguments are not correct....\\n"); return; } GlobalX = atoi(argv[1]); int NUM_THREADS = atoi(argv[2]); pthread_t threads[NUM_THREADS]; pthread_attr_t attr; void *status; int rc, t; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t=0;t<NUM_THREADS;t++) { printf("Creating thread : %d\\n", t); rc = pthread_create(&threads[t], &attr, Xpower2I, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(t=0;t<NUM_THREADS;t++) { rc = pthread_join(threads[t], &status); if (rc){ printf("ERROR return code from pthread_join() is %d\\n", rc); exit(-1); } } printf("\\n\\n\\nGlobalSumValues = %ld \\n",GlobalSumValues); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum, mutexlvl; void *dotprod(void *thdarg) { pthread_mutex_lock (&mutexlvl); printf("Sync to start level: %ld\\n", (long)thdarg); int i, start, end, len; long offset; double mysum, *x, *y; offset = (long)thdarg; 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; pthread_mutex_unlock (&mutexsum); pthread_mutex_unlock (&mutexlvl); 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 * 100 * sizeof (double)); b = (double *) malloc(4 * 100 * sizeof (double)); for (i = 0; i < 100 * 4; ++i) { a[i] = 1.0f; b[i] = a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init (&mutexsum, 0); pthread_mutex_init (&mutexlvl, 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 (&mutexlvl); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h>void updatePortStates(int currentIndex, unsigned char rPriority, unsigned char rExtension, unsigned char *rMac, unsigned int pathCost, unsigned short age, unsigned char bPriority, unsigned char bExtension){ pthread_mutex_lock(&ifaceMutex); if(states[currentIndex] == ROOT){ if(compareBridges(rPriority, rExtension, rMac, rootPriority, rootExtension, root) != 0 || pathCost +portCost != rootPathCost){ for(int i=0; i<n; i++){ states[i] = DEDICATED; messageAge = 0; } } } if(compareBridges(rPriority, rExtension, rMac, rootPriority, rootExtension, root) < 0 || (compareBridges(rPriority, rExtension, rMac, rootPriority, rootExtension, root) == 0 && pathCost + portCost < rootPathCost)){ memcpy(root, rMac, 6); rootPriority = rPriority; rootExtension = rExtension; rootPathCost = pathCost + portCost; messageAge = age+1; for(int i=0; i<n; i++) if(states[i] == ROOT) states[i] = DEDICATED; states[currentIndex] = ROOT; sendTCN(currentIndex); } if(compareBridges(priority, extension, bridgeId, rootPriority, rootExtension, root) < 0){ memcpy(root, bridgeId, 6); rootPriority = priority; rootExtension = extension; rootPathCost = 0; for(int i=0; i<n; i++) states[i] = DEDICATED; messageAge = 0; } if(states[currentIndex] == BLOCKING){ if(compareBridges(rootPriority, rootExtension, root, rPriority, rExtension, rMac) < 0) states[currentIndex] = DEDICATED; if(compareBridges(rootPriority, rootExtension, root, rPriority, rExtension, rMac) == 0 && (rootPathCost < pathCost || (rootPathCost == pathCost && compareBridges(priority, extension, bridgeId, bPriority, bExtension, neighbours[currentIndex]) < 0))) states[currentIndex] = DEDICATED; } if(states[currentIndex] == DEDICATED){ if(compareBridges(rPriority, rExtension, rMac, rootPriority, rootExtension, root) == 0) if(rootPathCost > pathCost || (rootPathCost == pathCost && compareBridges(priority, extension, bridgeId, bPriority, bExtension, neighbours[currentIndex]) > 0)) states[currentIndex] = BLOCKING; } pthread_mutex_unlock(&ifaceMutex); }
0
#include <pthread.h> int reader_cnt = 0; pthread_mutex_t rw_mutex, read_cnt_mutex, nread_mutex; int cnt = 3; void *write_handle(void *arg); void *read_handle(void *arg); int main(void) { int type; pthread_t tid_r, tid_w; srand(getpid()); pthread_mutex_init(&rw_mutex, 0); pthread_mutex_init(&read_cnt_mutex, 0); pthread_mutex_init(&nread_mutex, 0); while(1) { type = rand(); if(type % 2 == 0) { pthread_create(&tid_w, 0, write_handle, 0); } else { pthread_create(&tid_r, 0, read_handle, 0); } sleep(1); } pthread_mutex_destroy(&read_cnt_mutex); pthread_mutex_destroy(&rw_mutex); pthread_mutex_destroy(&nread_mutex); return 0; } void *write_handle(void *arg) { pthread_detach(pthread_self()); pthread_mutex_lock(&rw_mutex); pthread_mutex_lock(&nread_mutex); printf("a writer in\\n"); ++cnt; sleep(5); printf("a writer out\\n"); pthread_mutex_unlock(&nread_mutex); pthread_mutex_unlock(&rw_mutex); } void *read_handle(void *arg) { pthread_detach(pthread_self()); pthread_mutex_lock(&rw_mutex); pthread_mutex_lock(&read_cnt_mutex); ++reader_cnt; if(reader_cnt == 1) pthread_mutex_lock(&nread_mutex); pthread_mutex_unlock(&read_cnt_mutex); pthread_mutex_unlock(&rw_mutex); printf("a reader in\\n"); printf("%d\\n", cnt); sleep(3); pthread_mutex_lock(&read_cnt_mutex); --reader_cnt; printf("a reader out\\n"); if(reader_cnt == 0) pthread_mutex_unlock(&nread_mutex); pthread_mutex_unlock(&read_cnt_mutex); }
1
#include <pthread.h> enum pt_state { SETUP, IDLE, JOB, DIE }; int task; int size; enum pt_state state; pthread_cond_t work_cond; pthread_mutex_t work_mtx; pthread_cond_t boss_cond; pthread_mutex_t boss_mtx; } pt_info; pthread_t threads[3][2]; pt_info shared_info[3][2]; void *task_type1(void *arg) { pt_info *info = (pt_info *) arg; int task = info->task; int size = 0; pthread_mutex_lock(&(info->work_mtx)); printf("<worker %i:%i> start\\n", task, 0); pthread_mutex_lock(&(info->boss_mtx)); info->state = IDLE; pthread_cond_signal(&(info->boss_cond)); pthread_mutex_unlock(&(info->boss_mtx)); while (1) { pthread_cond_wait(&(info->work_cond), &(info->work_mtx)); if (DIE == info->state) { break; } if (IDLE == info->state) { continue; } size = info->size; printf("<worker %i:%i> JOB start\\n", task, 0); usleep(size*1000000); printf("<worker %i:%i> JOB end\\n", task, 0); pthread_mutex_lock(&(info->boss_mtx)); info->state = IDLE; pthread_cond_signal(&(info->boss_cond)); pthread_mutex_unlock(&(info->boss_mtx)); } pthread_mutex_unlock(&(info->work_mtx)); pthread_exit(0); } void *task_type2(void *arg) { pt_info *info = (pt_info *) arg; int task = info->task; int size = 0; pthread_mutex_lock(&(info->work_mtx)); printf("<worker %i:%i> start\\n", task, 1); pthread_mutex_lock(&(info->boss_mtx)); info->state = IDLE; pthread_cond_signal(&(info->boss_cond)); pthread_mutex_unlock(&(info->boss_mtx)); while (1) { pthread_cond_wait(&(info->work_cond), &(info->work_mtx)); if (DIE == info->state) { break; } if (IDLE == info->state) { continue; } size = info->size; printf("<worker %i:%i> JOB start\\n", task, 1); usleep(size*1000000); printf("<worker %i:%i> JOB end\\n", task, 1); pthread_mutex_lock(&(info->boss_mtx)); info->state = IDLE; pthread_cond_signal(&(info->boss_cond)); pthread_mutex_unlock(&(info->boss_mtx)); } pthread_mutex_unlock(&(info->work_mtx)); pthread_exit(0); } void task_start(int task, int type, int size) { pt_info *info = &(shared_info[task][type]); pthread_mutex_lock(&(info->work_mtx)); info->size = size; info->state = JOB; pthread_cond_signal(&(info->work_cond)); pthread_mutex_unlock(&(info->work_mtx)); } void task_wait(int task, int type) { pt_info *info = &(shared_info[task][type]); while (1) { pthread_cond_wait(&(info->boss_cond), &(info->boss_mtx)); if (IDLE == info->state) { break; } } } void app_init() { int i; pt_info *info = 0; for (i = 0; i < 3; i++) { info = &(shared_info[i][0]); info->task = i; info->size = 0; info->state = SETUP; pthread_cond_init(&(info->work_cond), 0); pthread_mutex_init(&(info->work_mtx), 0); pthread_cond_init(&(info->boss_cond), 0); pthread_mutex_init(&(info->boss_mtx), 0); pthread_mutex_lock(&(info->boss_mtx)); pthread_create(&threads[i][0], 0, task_type1, (void *)info); task_wait(i, 0); } for (i = 0; i < 3; i++) { info = &(shared_info[i][1]); info->task = i; info->size = 0; info->state = SETUP; pthread_cond_init(&(info->work_cond), 0); pthread_mutex_init(&(info->work_mtx), 0); pthread_cond_init(&(info->boss_cond), 0); pthread_mutex_init(&(info->boss_mtx), 0); pthread_mutex_lock(&(info->boss_mtx)); pthread_create(&threads[i][1], 0, task_type2, (void *)info); task_wait(i, 1); } } void app_exit() { int i; int d; pt_info *info = 0; for (i = 0; i < 3; i++) { for (d = 0; d < 2; d++) { info = &(shared_info[i][d]); pthread_mutex_lock(&(info->work_mtx)); printf("app_exit: send DIE to <worker %i:%i>\\n", i, d); info->state = DIE; pthread_cond_signal(&(info->work_cond)); pthread_mutex_unlock(&(info->work_mtx)); pthread_join(threads[i][d], 0); pthread_mutex_destroy(&(info->work_mtx)); pthread_cond_destroy(&(info->work_cond)); pthread_mutex_unlock(&(info->boss_mtx)); pthread_mutex_destroy(&(info->boss_mtx)); pthread_cond_destroy(&(info->boss_cond)); } } } int main(int argc, char *argv[]) { app_init(); printf("Init done\\n"); task_start(0, 0, 1); task_start(1, 0, 1); task_wait(1, 0); task_wait(0, 0); task_start(0, 1, 5); task_start(0, 0, 2); task_wait(0, 1); task_wait(0, 0); app_exit(); return 0; }
0
#include <pthread.h> void * treatMsg(struct can_frame canFrame){ switch (canFrame.can_id){ case ANGLEVOLANTMESURE: if (DEBUG){ printf("%s angle volant mesure= %d\\n",TH_NAME,canFrame.data[0]); } pthread_mutex_lock(&angleVolantMesure_mutex); angleVolantMesure_c = (unsigned char)canFrame.data[0]; pthread_mutex_unlock(&angleVolantMesure_mutex); break; case BATTERIE: if(DEBUG){ printf("%s batterie= %d\\n",TH_NAME,canFrame.data[0]); } pthread_mutex_lock(&batterie_mutex); batterie_c = (unsigned char)canFrame.data[0]; pthread_mutex_unlock(&batterie_mutex); break; case VITESSEMESUREDROITE: if(DEBUG){ printf("%s vitesse mesure droite= %d\\n",TH_NAME,canFrame.data[0]); } pthread_mutex_lock(&vitesseMesureDroite_mutex); vitesseMesureDroite_c = (unsigned char)canFrame.data[0]; pthread_mutex_unlock(&vitesseMesureDroite_mutex); break; case VITESSEMESUREGAUCHE: if(DEBUG){ printf("%s vitesse mesure gauche= %d\\n",TH_NAME,canFrame.data[0]); } pthread_mutex_lock(&vitesseMesureGauche_mutex); vitesseMesureGauche_c = (unsigned char)canFrame.data[0]; pthread_mutex_unlock(&vitesseMesureGauche_mutex); break; case ULTRASONMESURE: if(DEBUG){ printf("%s mesure ultrason= %d\\n",TH_NAME,canFrame.data[0]); } pthread_mutex_lock(&ultrasonMesure_mutex); ultrasonMesure_c = (unsigned char)canFrame.data[0]; pthread_mutex_unlock(&ultrasonMesure_mutex); break; default: printf("%s Erreur variable reçue inconnue numéro = %d\\n",TH_NAME,canFrame.can_id); } } void * listenCAN (void * socketCAN){ printf("%s Starting thread\\n",TH_NAME); int *s = (int*) socketCAN; struct can_frame canFrame; printf("%s Socket number : %d\\n",TH_NAME,(*s)); int nbytes; while (1){ nbytes = read(*s,&canFrame,sizeof(struct can_frame)); if (nbytes < 0){ perror ("[Listen] can raw socket read \\n"); } if (nbytes < sizeof(struct can_frame)){ perror("[Listen] read: incomplete CAN frame"); } if(DEBUG){ printf("%s Received var number %d = %d \\n",TH_NAME,canFrame.can_id,canFrame.data[0]); } if (sizeof(canFrame.data[0])>0){ treatMsg(canFrame); } } }
1
#include <pthread.h> static void sig_catch(int); static void register_signal(void); static void buffer_idx_cntup(int *idx); static int mStopLoop = 0; static char mBuffer[2048]; static int mBufferReadIdx = 0; static int mBufferWriteIdx = 0; static FILE *mLogfd; static pthread_mutex_t mMutex; void script_loop(char *logFile) { register_signal(); mLogfd = fopen(logFile, "w"); if (mLogfd == 0) { fprintf(stderr, "Open File Failed!!\\n"); exit(1); } fprintf(mLogfd, "%d\\n", LOG_FILE_VER); memset(mBuffer, 0, 2048); while (1) { pthread_mutex_lock(&mMutex); if (mStopLoop) { if (mLogfd != 0) { fclose(mLogfd); mLogfd = 0; } exit(0); } if (mBufferReadIdx != mBufferWriteIdx) { while (mBuffer[mBufferReadIdx] != '\\n') { putc(mBuffer[mBufferReadIdx], mLogfd); buffer_idx_cntup(&mBufferReadIdx); } putc('\\n', mLogfd); buffer_idx_cntup(&mBufferReadIdx); } pthread_mutex_unlock(&mMutex); } } void stop_script_loop(int cause) { pthread_mutex_lock(&mMutex); mStopLoop = cause; pthread_mutex_unlock(&mMutex); } void write_script(char *one_line) { int i; pthread_mutex_lock(&mMutex); for (i = 0; one_line[i] != '\\n'; i++, buffer_idx_cntup(&mBufferWriteIdx)) { mBuffer[mBufferWriteIdx] = one_line[i]; if (i != 0 && mBufferWriteIdx == mBufferReadIdx) { fprintf(stderr, "oops buffer run out...\\n"); if (mLogfd != 0) { fclose(mLogfd); mLogfd = 0; } exit(1); } } mBuffer[mBufferWriteIdx] = '\\n'; buffer_idx_cntup(&mBufferWriteIdx); pthread_mutex_unlock(&mMutex); } static void buffer_idx_cntup(int *idx) { if (*idx >= 2048 - 1) { *idx = 0; } else { *idx = *idx + 1; } } static void sig_catch(int signal) { if (mLogfd != 0) { fclose(mLogfd); mLogfd = 0; } exit(0); } static void register_signal() { if (SIG_ERR == signal(SIGINT, sig_catch)) { fprintf(stderr, "Signal SIGINT set failed!!\\n"); exit(1); } if (SIG_ERR == signal(SIGTSTP, sig_catch)) { fprintf(stderr, "Signal SIGTSTP set failed!!\\n"); exit(1); } }
0
#include <pthread.h> pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; int num = 1; void * thr_func(void *arg) { int i = (int)arg; char ch = 'a' + i; for (;;) { pthread_mutex_lock(&qlock); while (num != i) { pthread_cond_wait(&qready, &qlock); } putchar(ch); if (++num > 4) num = 1; pthread_mutex_unlock(&qlock); pthread_cond_broadcast(&qready); } return ((void *)0); } int main(void) { int ret; pthread_t tid[4]; if ((ret = pthread_create(tid + 0, 0, thr_func, (void *)1)) != 0) err_exit(ret, "can't create thread 1"); if ((ret = pthread_create(tid + 1, 0, thr_func, (void *)2)) != 0) err_exit(ret, "can't create thread 2"); if ((ret = pthread_create(tid + 2, 0, thr_func, (void *)3)) != 0) err_exit(ret, "can't create thread 3"); if ((ret = pthread_create(tid + 3, 0, thr_func, (void *)4)) != 0) err_exit(ret, "can't create thread 4"); alarm(5); if ((ret = pthread_join(tid[0], 0)) != 0) err_exit(ret, "can't join with tid1"); if ((ret = pthread_join(tid[1], 0)) != 0) err_exit(ret, "can't join with tid2"); if ((ret = pthread_join(tid[2], 0)) != 0) err_exit(ret, "can't join with tid3"); if ((ret = pthread_join(tid[3], 0)) != 0) err_exit(ret, "can't join with tid4"); exit(0); }
1
#include <pthread.h> const size_t io_buffer_slot_size = 1024*16; struct io_buffer * io_buffer_new() { const unsigned int slot_count = 1024*8; size_t alloc_size = sizeof(struct io_buffer) + io_buffer_slot_size*slot_count; LOG_DEBUG("Allocating %0.2f Mbytes for IO buffer", alloc_size / 1048576.); struct io_buffer * this = malloc(alloc_size); this->slot_count = slot_count; this->free_slots_head = slot_count; this->free_slots_tail = 0; this->data = &this->free_slots[slot_count]; for (unsigned int i = 0; i < this->slot_count; i++) { this->free_slots[i] = this->data + (io_buffer_slot_size * i); } pthread_mutex_init(&this->mtx, 0); return this; } void io_buffer_delete(struct io_buffer * this) { pthread_mutex_destroy(&this->mtx); free(this); } bool io_buffer_empty(struct io_buffer * this) { return (this->free_slots_tail == this->free_slots_head); } unsigned int io_buffer_get(struct io_buffer * this, unsigned int slot_count, struct iovec * iovec) { unsigned int i; pthread_mutex_lock(&this->mtx); for (i = 0; i < slot_count; i++) { if (io_buffer_empty(this)) break; iovec[i].iov_base = this->free_slots[this->free_slots_tail]; iovec[i].iov_len = io_buffer_slot_size; this->free_slots_tail += 1; if (this->free_slots_tail == this->slot_count) this->free_slots_tail = 0; } pthread_mutex_unlock(&this->mtx); return i; } void io_buffer_put(struct io_buffer * this, unsigned int slot_count, struct iovec * iovec) { unsigned int i; pthread_mutex_lock(&this->mtx); for (i = 0; i < slot_count; i++) { this->free_slots_head += 1; if (this->free_slots_head == this->slot_count) this->free_slots_head = 0; assert(this->free_slots_head != this->free_slots_tail); this->free_slots[this->free_slots_head] = iovec[i].iov_base; } pthread_mutex_unlock(&this->mtx); }
0
#include <pthread.h> int main(int argc, char* argv[]) { int i, nthreads, count[MAXTHREADS]; pthread_t tid_produce[MAXTHREADS], tid_consume; if (argc != 3) { return -1; } nitems = ((atoi(argv[1])) > (MAXITEMS) ? (MAXITEMS) : (atoi(argv[1]))); nthreads = ((atoi(argv[2])) > (MAXTHREADS) ? (MAXTHREADS) : (atoi(argv[2]))); for (i = 0; i < nthreads; i++) { count[i] = i; if (pthread_create(&tid_produce[i], 0, produce, &count[i]) != 0) { printf("create thread error...\\n"); return(-1); } } for (i = 0; i < nthreads; i++) { if (pthread_join(tid_produce[i], 0) != 0) { printf("pthread join error...\\n"); return(-1); } printf("count[%d] = %d\\n", i, count[i]); } if (pthread_create(&tid_consume, 0, consume, 0) != 0) { printf("create consume thread error..\\n"); return -1; } if (pthread_join(tid_consume, 0) != 0) { printf("pthread join consume thread error...\\n"); return -1; } return(0); } void *produce(void* arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nputs >= nitems) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[shared.nputs] = shared.nval; shared.nputs++; shared.nval++; pthread_mutex_unlock(&shared.mutex); *((int*) arg) += 1; } return 0; } void *consume(void* arg) { int i; for (i = 0; i< nitems; i++) { if (shared.buff[i] != i) { printf("consume thread check failed: %d is an error number\\n", i); } } return 0; }
1
#include <pthread.h> size_t result = 0; pthread_mutex_t result_mutex; void *busy_work(void *data) { int i; size_t thread_num = (size_t)data; printf("Hello world! It's me - thread %zd\\n", thread_num); for (i = 0; i < 1000000; i++) { pthread_mutex_lock(&result_mutex); result++; pthread_mutex_unlock(&result_mutex); } pthread_exit(0); } int main() { size_t i; pthread_t threads[3]; pthread_mutex_init(&result_mutex, 0); for (i = 0; i < 3; i++) { printf("Creating thread %zd..\\n", i); int error = pthread_create(&threads[i], 0, busy_work, (void*)i); if (error != 0) { fprintf(stderr, "Error creating thread %zd: error: %d\\n", i, error); } } for (i = 0; i < 3; i++) { printf("Waiting for thread %ld to finish..\\n", i); int error = pthread_join(threads[i], 0); if (error != 0) { fprintf(stderr, "Error joining thread %zd: error: %d\\n", i, error); } } printf("Result: %zd\\n", result); pthread_mutex_destroy(&result_mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> static struct input_event keyqueue[2048]; static pthread_t t; static pthread_mutex_t keymutex; static pthread_mutex_t exitmutex; static int stop_flag = 0; static int sp = 0; static void (*key_handler)(int keycode); static void (*click_handler)(int x, int y); static void (*touch_handler)(int x, int y, int touch); static void *input_thread(); static void handle_key(struct input_event ev){ if (key_handler != 0) key_handler((int)(ev.code)); } static void handle_click(struct input_event ev){ if(click_handler != 0) click_handler((int)(ev.code),(int)(ev.value)); } static void handle_touch(int x, int y, int touch){ if(touch_handler != 0) touch_handler(x,y,touch); } int init_input(void (*on_key)(int keycode), void (*on_click)(int x, int y), void (*on_touch)(int x, int y, int touch)){ ev_init(); key_handler = on_key; click_handler = on_click; touch_handler = on_touch; stop_flag = 0; pthread_mutex_init(&keymutex, 0); pthread_mutex_init(&exitmutex, 0); if(pthread_create(&t, 0, input_thread, 0) != 0){ printf("ERROR: unable to create input thread\\n"); ev_exit(); return -1; }else{ printf("INFO: created the input thread\\n"); } return 0; } int kill_input(){ pthread_mutex_lock(&exitmutex); stop_flag=1; fprintf(stderr,"Stop flag is 1\\n"); pthread_mutex_unlock(&exitmutex); ev_exit(); return 0; } static void *input_thread() { int rel_sum = 0; int p_x,p_y,p_active=0,p_click=0; struct input_event ev; int key_up=0; int local_exit=0; for(;local_exit==0;) { p_active=0; p_click=0; do { ev_get(&ev, 0); switch(ev.type) { case EV_SYN: continue; case EV_ABS: if(ev.code == 0x35 ) p_x = ev.value; if(ev.code == 0x36 ) p_y = ev.value; if(ev.code == 0x30){ pthread_mutex_lock(&keymutex); handle_touch(p_x,p_y,ev.value); pthread_mutex_unlock(&keymutex); if(p_active == 0 && ev.value > 0){ p_active=1; }else if ( p_active == 1 && ev.value == 0 ){ p_click=1; p_active=0; ev.type=0x1337; ev.code=p_x; ev.value=p_y; } } break; default: rel_sum = 0; } pthread_mutex_lock(&exitmutex); local_exit=stop_flag; pthread_mutex_unlock(&exitmutex); } while( (ev.type != EV_KEY || ev.code > KEY_MAX) && p_click == 0 && local_exit == 0); rel_sum = 0; pthread_mutex_lock(&keymutex); switch(ev.type) { case(EV_KEY): if(key_up == 1) { key_up = 0; break; } key_up = 1; case(EV_REL): handle_key(ev); break; case(0x1337): handle_click(ev); break; case(EV_SYN): break; } pthread_mutex_unlock(&keymutex); } fprintf(stderr,"INFO: input thread finished\\n"); return 0; }
1
#include <pthread.h> struct rtpp_genuid_priv { struct rtpp_genuid_obj pub; uint64_t lastsuid; pthread_mutex_t lastsuid_lock; }; static void rtpp_genuid_gen(struct rtpp_genuid_obj *, uint64_t *vp); static void rtpp_genuid_dtor(struct rtpp_genuid_obj *); struct rtpp_genuid_obj * rtpp_genuid_ctor(void) { struct rtpp_genuid_priv *pvt; pvt = rtpp_zmalloc(sizeof(struct rtpp_genuid_priv)); if (pvt == 0) { return (0); } if (pthread_mutex_init(&pvt->lastsuid_lock, 0) != 0) { goto e0; } pvt->pub.dtor = &rtpp_genuid_dtor; pvt->pub.gen = &rtpp_genuid_gen; return (&pvt->pub); e0: free(pvt); return (0); } static void rtpp_genuid_dtor(struct rtpp_genuid_obj *pub) { struct rtpp_genuid_priv *pvt; pvt = ((struct rtpp_genuid_priv *)((char *)(pub) - offsetof(struct rtpp_genuid_priv, pub))); pthread_mutex_destroy(&pvt->lastsuid_lock); free(pvt); } static void rtpp_genuid_gen(struct rtpp_genuid_obj *pub, uint64_t *vp) { struct rtpp_genuid_priv *pvt; pvt = ((struct rtpp_genuid_priv *)((char *)(pub) - offsetof(struct rtpp_genuid_priv, pub))); pthread_mutex_lock(&pvt->lastsuid_lock); *vp = ++(pvt->lastsuid); pthread_mutex_unlock(&pvt->lastsuid_lock); }
0
#include <pthread.h> void mir_lock_create(struct mir_lock_t* lock) { pthread_mutex_init(&lock->m, 0); } void mir_lock_destroy(struct mir_lock_t* lock) { pthread_mutex_destroy(&lock->m); } void mir_lock_set(struct mir_lock_t* lock) { pthread_mutex_lock(&lock->m); } void mir_lock_unset(struct mir_lock_t* lock) { pthread_mutex_unlock(&lock->m); } int mir_lock_tryset(struct mir_lock_t* lock) { int retval; retval = pthread_mutex_trylock(&lock->m); return retval; }
1
#include <pthread.h> int thread_count; double a,b; int n; double h; double sum; pthread_mutex_t sum_mutex; double f(double x); void* Trap(void* rank); int main(int argc,char* argv[]) { int i; pthread_t* thread_handles = 0; double beg,end; thread_count = strtol(argv[1],0,10); printf("Enter a, b, and n\\n"); scanf("%lf", &a); scanf("%lf", &b); scanf("%d", &n); h = (b-a)/n; sum = 0; thread_handles = (pthread_t*)malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&sum_mutex,0); beg = GetTickCount(); for(i=0;i<thread_count;i++) pthread_create(&thread_handles[i],0,Trap,(void*)i); for(i=0;i<thread_count;i++) pthread_join(thread_handles[i],0); end = GetTickCount(); pthread_mutex_destroy(&sum_mutex); printf("With n = %d trapezoids, our estimate\\n", n); printf("of the integral from %f to %f = %.15f\\n", a, b, sum); printf("\\nTime: %fs\\n",(end-beg)/1000); return 0; } void* Trap(void* rank) { long my_rank = (long)rank; double local_n = n/thread_count; double local_a = a+my_rank*local_n*h; double local_b = local_a + local_n*h; if(my_rank==rank-1) local_b = n; double integral; int k; integral = (f(local_a) + f(local_b))/2.0; for (k = 1; k <= local_n-1; k++) { integral += f(local_a+k*h); } integral = integral*h; pthread_mutex_lock(&sum_mutex); sum+=integral; pthread_mutex_unlock(&sum_mutex); return 0; } double f(double x) { double return_val; return_val = x*x; return return_val; }
0
#include <pthread.h> pthread_key_t key; pthread_once_t once = PTHREAD_ONCE_INIT; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void destructor(void *ptr) { void** ptr_aux = (void**)ptr; printf("%p\\n", ptr); printf("%p\\t%p\\n", ptr_aux[0], ptr_aux[1]); free(ptr_aux[0]); free(ptr_aux[1]); free(ptr); } void init_once(void) { pthread_key_create(&key, destructor); } static void get_buf(void*** ptr) { pthread_once(&once, init_once); void** ptr_aux; if((ptr_aux = (void**)pthread_getspecific(key)) == 0) { pthread_mutex_lock(&mutex); if (0 == ptr_aux) { ptr_aux = (void**)malloc(2*sizeof(void*)); ptr_aux[0] = (void*)malloc(1024); ptr_aux[1] = (void*)malloc(1024); printf("prt_aux:%p\\n", ptr_aux); printf("%p\\t%p\\n", ptr_aux[0], ptr_aux[1]); pthread_setspecific(key, (void*)ptr_aux); } pthread_mutex_unlock(&mutex); } *ptr = ptr_aux; } static void *thread_fn(void* arg) { void** p; char* ptr[2]; int i = 0; while(i++<2) { get_buf(&p); ptr[0] = (char*)p[0]; ptr[1] = (char*)p[1]; printf("%p\\n", p); sprintf(ptr[0], "hello world"); printf("%p\\t%s\\n", ptr[0], ptr[0]); sprintf(ptr[1], ">>>>>>"); printf("%p\\t%s\\n", ptr[1], ptr[1]); } return 0; } int main() { pthread_t tid; pthread_create(&tid, 0, thread_fn, 0); pthread_join(tid, 0); return 0; }
1
#include <pthread.h> { char* bound; int index; } FARMER; int globaltime = 1; int north, south; sem_t sem; int northturn = 0; int southturn = 1; void enter_bridge(char* bound, int index); void exit_bridge(char* bound, int index); void* n_pass_bridge(void* param); void* s_pass_bridge(void* param); pthread_mutex_t lock; pthread_cond_t not_north, not_south; int ncount, scount; int main(int argc, char** argv) { north = atoi(argv[1]); south = atoi(argv[2]); FARMER northerner[north]; for(int i=0; i<north; i++) { northerner[i].bound = "North"; northerner[i].index = i+1; } FARMER southerner[south]; for(int i=0; i<south; i++) { southerner[i].bound = "South"; southerner[i].index = i+1; } printf("%d northern farmer(s) and %d southern farmer(s).\\n", north, south); sem_init(&sem, 0, 1); pthread_attr_t attr; pthread_attr_init(&attr); pthread_t *Nfarmer = malloc(north*sizeof(pthread_t)); pthread_t *Sfarmer = malloc(south*sizeof(pthread_t)); for(int i=0; i<north; i++) pthread_create(&Nfarmer[i], 0, n_pass_bridge, (void*)(intptr_t)(northerner[i].index)); for(int i=0; i<south; i++) pthread_create(&Sfarmer[i], 0, s_pass_bridge, (void*)(intptr_t)(southerner[i].index)); for(int i=0; i<north; i++) pthread_join(Nfarmer[i], 0); for(int i=0; i<south; i++) pthread_join(Sfarmer[i], 0); sem_destroy(&sem); printf("All finished!\\n"); return 0; } void enter_bridge(char* bound, int index) { sem_wait(&sem); globaltime++; int timer = rand() % 5; globaltime++; printf("M%d: %d seconds until completion...\\n", globaltime, timer); sleep(timer); } void exit_bridge(char* bound, int index) { globaltime++; sem_post(&sem); } void* n_pass_bridge(void* param) { pthread_mutex_lock(&lock); while(northturn == 0) pthread_cond_wait(&not_north, &lock); int x = (intptr_t)param; enter_bridge("North", x); exit_bridge("North", x); ncount++; if(scount < south) { northturn = 0; southturn = 1; } else { northturn = 1; southturn = 0; } pthread_cond_signal(&not_south); pthread_mutex_unlock(&lock); } void* s_pass_bridge(void* param) { pthread_mutex_lock(&lock); while(southturn == 0) pthread_cond_wait(&not_south, &lock); int x = (intptr_t)param; enter_bridge("South", x); exit_bridge("South", x); scount++; if(ncount < north) { northturn = 1; southturn = 0; } else { northturn = 0; southturn = 1; } pthread_cond_signal(&not_north); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> int VT_mc13783_OC_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc13783_OC_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc13783_test_OC(void) { int fd; fd = open(MC13783_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC13783_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } 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 TPASS; }
1
#include <pthread.h> static pthread_cond_t bcond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t bmutex = PTHREAD_MUTEX_INITIALIZER; static int count = 0; static int barrier = 0; static int limit[5]; int initbarriers(int n) { int error; int i; if (error = pthread_mutex_lock(&bmutex)) { printf("Can't lock\\n"); return -1; } if (barrier > 5) { pthread_mutex_unlock(&bmutex); return EINVAL; } limit[barrier] = n; barrier++; if (error = pthread_mutex_unlock(&bmutex)) { printf("Can't unlock\\n"); return -1; } return barrier - 1; } int waitbarriers(int barrier) { int berror = 0; int error; if (error = pthread_mutex_lock(&bmutex)) return error; if (limit[barrier] <= 0) { pthread_mutex_unlock(&bmutex); return EINVAL; } count++; while ((count < limit[barrier]) && !berror) berror = pthread_cond_wait(&bcond, &bmutex); if (!berror) berror = pthread_cond_broadcast(&bcond); error = pthread_mutex_unlock(&bmutex); if (berror) return berror; return error; }
0
#include <pthread.h> int capacidade = 5; sem_t sacola; sem_t partiu_correio; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* pombo (void* arg) { int i; time_t t; printf("POMBO CRIADO.\\n"); fflush(stdout); srand((unsigned) time(&t)); while(1) { printf("POMBO: esperando sacola ser preenchida.\\n"); fflush(stdout); for(i = 5; i > 0; i--) { sem_post(&sacola); } sem_wait(&partiu_correio); printf("POMBO: a sacola está cheia! Estou partindo para o correio.\\n"); fflush(stdout); sleep(rand() % 5); printf("POMBO: cartas entregues.\\n"); fflush(stdout); pthread_mutex_lock(&lock); capacidade = 5; pthread_mutex_unlock(&lock); } } void* usuario (void* arg) { int id = *((int*) arg); printf("USUÁRIO %d CRIADO.\\n", id); while(1) { sem_wait(&sacola); printf("USUÁRIO %d: colocando uma carta na sacola!\\n", id); fflush(stdout); pthread_mutex_lock(&lock); capacidade--; if(capacidade == 0) { printf("USUÁRIO %d: fazendo o pombo partir!\\n", id); fflush(stdout); sem_post(&partiu_correio); } pthread_mutex_unlock(&lock); sleep(3); } } int main() { pthread_t b; pthread_t a[8]; int i; int * id; sem_init(&sacola, 0, 0); sem_init(&partiu_correio, 0, 0); pthread_create(&b, 0, pombo, 0); for (i = 0; i < 8 ; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&a[i], 0, usuario, (void *) (id)); } pthread_join(b,0); return 0; }
1
#include <pthread.h> void clearscr(); static char terminf_entry[1024]; static char platz_fuer_termstrings[1024]; static char *p=platz_fuer_termstrings; static char *Cl, *Cpos, *Scroll, *SetScrollRegion; static int nrlines; static int nrcols; static int isinit; static struct termios told; static pthread_mutex_t screenmutex = PTHREAD_MUTEX_INITIALIZER; static int writebyte(int val) { char byte; byte=(char)val; write(0, &byte,1); return 0; } void exithandler() { clearscr(); tcsetattr(0, TCSAFLUSH, &told); } static void init() { struct termios t; if (isinit) return; if ( tcgetattr (0,&told) == -1 ) fprintf(stderr, "failed to init terminal\\n"), exit(1); t=told; if ( tgetent(terminf_entry, getenv("TERM"))==-1 ) fprintf(stderr, "failed to init terminaltype %s\\n", getenv("TERM")), exit(1); if (( Cl=tgetstr("cl",&p)) == 0 ) fprintf(stderr, "failed to get clear seq for terminaltype %s\\n", getenv("TERM")), exit(1); if (( Cpos=tgetstr("cm", &p)) == 0 ) fprintf(stderr, "failed to get cup seq for terminaltype %s\\n", getenv("TERM")), exit(1); if (( SetScrollRegion=tgetstr("cs", &p)) == 0 ) fprintf(stderr, "failed to get scrollreeg_seq for terminaltype %s\\n", getenv("TERM")), exit(1); if (( Scroll=tgetstr("SF", &p)) == 0 ) fprintf(stderr, "failed to get scroll seq for terminaltype %s\\n", getenv("TERM")), exit(1); if (( nrlines = tgetnum("li")) == -1) fprintf(stderr, "failed to get line-size for terminaltype %s\\n", getenv("TERM")), exit(1); if (( nrcols = tgetnum("co")) == -1) fprintf(stderr, "failed to get line-size for terminaltype %s\\n", getenv("TERM")), exit(1); atexit(exithandler); t.c_lflag &= ~ECHO; t.c_lflag &= ~ICANON; t.c_cc[VMIN] = 0; t.c_cc[VTIME] = 1; if(tcsetattr(0, TCSAFLUSH, &t) < 0) fprintf(stderr, "failed to change Terminal Interface to RAW\\n"), exit(1); ++isinit; } char *gets_raw(char *s, int maxlen, int col, int row) { char c; int i=0, rc; rc=read(0,&c,1); while ( i<maxlen-2 && c!=10 && rc!=13 && rc!='\\n' && rc!='\\r' ) { if (rc>0) { pthread_mutex_lock(&screenmutex); tputs( tgoto( Cpos, col+i, row ), 1, writebyte); write(1,&c,1); pthread_mutex_unlock(&screenmutex); s[i++]=c; } rc=read(0,&c,1); } s[i]=0; return s; } void writestr_raw(char *s, int col, int row) { pthread_mutex_lock(&screenmutex); tputs( tgoto( Cpos, col, row ), 1, writebyte); write( 0, s, strlen(s) ); pthread_mutex_unlock(&screenmutex); } void scroll_up(int from_line, int to_line) { pthread_mutex_lock(&screenmutex); tputs( tparm(SetScrollRegion,from_line,to_line), nrlines, writebyte); tputs( tparm(Scroll,1), nrlines, writebyte); tputs( tparm(SetScrollRegion,0,nrlines), nrlines, writebyte); pthread_mutex_unlock(&screenmutex); } int get_lines() { if (!isinit) init(); return nrlines; } int get_cols() { if (!isinit) init(); return nrcols; } void clearscr() { if (!isinit) init(); tputs(Cl,0,writebyte); }
0
#include <pthread.h> const int MAX_PRODUCER = 20; const int MAX_CONSUMER = 20; int head = 0; int tail = 0; int buffer[5]; pthread_mutex_t mutex; sem_t emptyBuffers; sem_t fullBuffer; void initialize_locks() { pthread_mutex_init(&mutex,0); sem_init(&emptyBuffers,0,5); sem_init(&fullBuffer,0,0); } void *producer(void *param) { int item; while(1) { item = rand(); sem_wait(&emptyBuffers); pthread_mutex_lock(&mutex); buffer[tail] = item ; tail = (tail+1) % 5; printf ("producer: inserted %d \\n", item); fflush (stdout); pthread_mutex_unlock(&mutex); sem_post(&fullBuffer); } printf ("producer quiting\\n"); fflush (stdout); } void *consumer(void *param) { int item; while (1) { sem_wait(&fullBuffer); pthread_mutex_lock(&mutex); item = buffer[head]; head = ( head + 1) % 5; printf ("consumer: removed %d \\n", item); fflush (stdout); pthread_mutex_unlock(&mutex); sem_post(&emptyBuffers); } } int main( int argc, char *argv[]) { int i, sleep_time = 100, no_of_consumer_threads = 2, no_of_producer_threads = 20; pthread_t producer_id[MAX_PRODUCER], consumer_id[MAX_CONSUMER]; initialize_locks(); for(i = 0; i < no_of_producer_threads; i++) { if (pthread_create(&producer_id[i],0,producer,0) != 0) { fprintf (stderr, "Unable to create producer thread\\n"); return -1; } } for(i = 0; i < no_of_consumer_threads; i++) { if (pthread_create(&consumer_id[i],0,consumer,0) != 0) { fprintf (stderr, "Unable to create consumer thread\\n"); } } sleep(sleep_time); return 0; }
1
#include <pthread.h> static struct timeval start_tv; static volatile struct timeval last_tv; static volatile unsigned short is_record_on = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int strcmp_wrapper(const void * str_a, const void * str_b) { return strcmp(*(const char **)str_a, *(const char **)str_b); } void ensure_free_space(void) { DIR *directory; char **filenames; struct dirent *entry; struct statvfs svfs; int i = 0, file_count = 0; if ((directory = opendir("/root/records")) == 0) return; statvfs("/", &svfs); if ((svfs.f_bfree * svfs.f_bsize / 1000000) > 500) return; while ((entry = readdir(directory)) != 0) if((entry->d_name)[0] != '.') ++file_count; if ((filenames = malloc(file_count * sizeof(const char *))) == 0) return; rewinddir(directory); while ((entry = readdir(directory)) != 0) if((entry->d_name)[0] != '.') filenames[i++] = entry->d_name; qsort(filenames, file_count, sizeof(const char *), strcmp_wrapper); i = 0; do { remove(filenames[i++]); statvfs("/", &svfs); } while (i < file_count && (svfs.f_bfree * svfs.f_bsize / 1000000) < 500); free(filenames); } void motion_handler(void) { pid_t pid; unsigned short should_record, day, hour, minute; unsigned long sleep_us; struct timeval diff_tv, used_tv; char out_filename [strlen("/root/records")+22]; char *const util_params [] = {"raspivid", "-t", "0", "-n", "-fps", "24", "-o", out_filename, 0}; gettimeofday(&used_tv, 0); last_tv = used_tv; pthread_mutex_lock(&mutex); should_record = !is_record_on; is_record_on = 1; pthread_mutex_unlock(&mutex); if (!should_record) return; pid = fork(); if (pid == 0) { timersub(&used_tv, &start_tv, &diff_tv); day = diff_tv.tv_sec / (24 * 3600); hour = (diff_tv.tv_sec / 3600) % 24; minute = (diff_tv.tv_sec / 60) % 60; sprintf(out_filename, "%s/rec_%02d_%02d-%02d-%02d.h264", "/root/records", day+1, hour, minute, diff_tv.tv_sec % 60); execv("/bin/raspivid", util_params); printf("execv error : %s\\n", strerror(errno)); } else { sleep(8); sleep_us = 0; do { usleep(sleep_us); timersub(&last_tv, &used_tv, &diff_tv); used_tv = last_tv; sleep_us = diff_tv.tv_sec * 1000000 + diff_tv.tv_usec; } while (sleep_us != 0); kill(pid, SIGINT); pthread_mutex_lock(&mutex); is_record_on = 0; pthread_mutex_unlock(&mutex); sync(); ensure_free_space(); } } int main(int argc, char **argv) { int rc; if ((rc = mkdir("/root/records", S_IRWXU|S_IRWXG|S_IRWXO)) != 0 && errno != EEXIST) return rc; gettimeofday(&start_tv, 0); wiringPiSetup(); wiringPiISR(0, INT_EDGE_RISING, &motion_handler); wiringPiISR(3, INT_EDGE_RISING, &motion_handler); wiringPiISR(4, INT_EDGE_RISING, &motion_handler); wiringPiISR(5, INT_EDGE_RISING, &motion_handler); while (1) sleep(3600); return 0; }
0
#include <pthread.h> static FILE *fp = 0; static int _log_level = SOLOG_NONE; static unsigned int log_counter = 0; static unsigned int _log_max_line = DEFAULT_LOG_LINE_LIMIT; int sopenlog(const char *filename, int log_level) { fp = fopen(filename, "a+"); if (!fp) return 1; fprintf(fp, "so_logger version:%s\\n", REL_VERSION); _log_level = log_level; return 0; } void ssetlog_option(int option, void *value) { if (!value) return ; switch (option) { case SO_OPT_SET_LEVEL: _log_level = *(int*)value & 0xff; break; case SO_OPT_SET_MAX_LOG_LINE: _log_max_line = *(unsigned int*)value; break; case SO_OPT_RESET_LOG_COUNTER: log_counter = 0; break; } } static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; char buf[2048] = {}; char buf_time[24] = {}; void slog(int level, const char *fmt, ...) { va_list ptr; time_t t = 0; struct tm *ts = 0; if (!fp || level > _log_level || log_counter > _log_max_line) return ; log_counter++; pthread_mutex_lock(&log_lock); t = time(0); ts = localtime(&t); strftime(buf_time, sizeof(buf_time)-1, "%Y-%m-%d %H:%M:%S", ts); __builtin_va_start((ptr)); vsnprintf(buf, sizeof(buf), fmt, ptr); ; fprintf(fp, "%s %s\\n", buf_time, buf); fflush(fp); pthread_mutex_unlock(&log_lock); } void scloselog(void) { if (!fp) return; fclose(fp); }
1
#include <pthread.h> int *array; int start; int end; int tid; } thread_info; int limit_threads; int shared_index; pthread_mutex_t mutex; void swap(int*, int*); void bubble_sort(int*, int); void merge_sort(int*, int, int); void *split_thread(void*); void split_main(int*, int, int); int main(void) { int limit_numbers; int input_value; scanf("%d", &limit_threads); scanf("%d", &limit_numbers); int* result_array = (int*) malloc(sizeof(int) * limit_numbers); for (int i = 0; i < limit_numbers; i++) { scanf("%d", &input_value); result_array[i] = input_value; } split_main(result_array, 0, limit_numbers - 1); int i = 0; for (i = 0; i < limit_numbers; ++i) { printf("%d\\n", result_array[i]); } free(result_array); pthread_mutex_destroy(&mutex); return 0; } void swap(int* a, int* b) { int temp = *a; *a = *b; *b = temp; } void bubble_sort(int* arr, int size) { for (int i = size; 1 < i; i--) { for (int j = 1; j < i; j++) { if (arr[j - 1] > arr[j]) swap(&arr[j - 1], &arr[j]); } } } void merge_sort(int *data, int start, int end) { int *tmpArray = (int *) malloc((end - start + 1) * sizeof(int)); int ctr = 0; int i = start; int mid = start + ((end - start) / 2); int j = mid + 1; while (i <= mid && j <= end) { if (data[i] <= data[j]) { tmpArray[ctr++] = data[i++]; } else { tmpArray[ctr++] = data[j++]; } } if (i == mid + 1) { while (j <= end) { tmpArray[ctr++] = data[j++]; } } else { while (i <= mid) { tmpArray[ctr++] = data[i++]; } } i = start; ctr = 0; while (i <= end) { data[i++] = tmpArray[ctr++]; } free(tmpArray); return; } void split_main(int *array, int start, int end) { pthread_mutex_init(&mutex, 0); shared_index = 0; thread_info info; info.array = array; info.start = start; info.end = end; info.tid = 0; pthread_t thread; pthread_create(&thread, 0, split_thread, &info); pthread_join(thread, 0); return; } void *split_thread(void *arg) { thread_info *info = (thread_info *) arg; int start = info->start; int end = info->end; int tid = info->tid; if (shared_index >= limit_threads) bubble_sort(info->array + start, end - start + 1); else { int center = start + ((end - start) / 2); thread_info thread_info_0; thread_info thread_info_1; thread_info_0.start = start; thread_info_0.end = center; thread_info_0.array = info->array; thread_info_1.start = center + 1; thread_info_1.end = end; thread_info_1.array = info->array; pthread_t thread_0; pthread_create(&thread_0, 0, split_thread, &thread_info_0); pthread_t thread_1; pthread_create(&thread_1, 0, split_thread, &thread_info_1); pthread_mutex_lock(&mutex); thread_info_0.tid = shared_index++; pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); thread_info_1.tid = shared_index++; pthread_mutex_unlock(&mutex); pthread_join(thread_0, 0); pthread_join(thread_1, 0); merge_sort(info->array, start, end); } pthread_exit(0); }
0
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static void *thr_primer(void *p); int main() { int err,i; pthread_t tid[4]; for(i = 0 ; i < 4; i++) { err = pthread_create(tid+i,0,thr_primer,(void *)i); if(err) { fprintf(stderr,"pthread_create():%s\\n",strerror(err)); exit(1); } } for(i = 30000000 ; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while(num != 0) { pthread_cond_wait(&cond, &mut_num); } num = i; pthread_cond_signal(&cond); pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while(num != 0) { pthread_cond_wait(&cond, &mut_num); } num = -1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mut_num); for(i = 0 ; i < 4; i++) pthread_join(tid[i],0); pthread_mutex_destroy(&mut_num); pthread_cond_destroy(&cond); exit(0); } static void *thr_primer(void *p) { int i,j,mark; while(1) { pthread_mutex_lock(&mut_num); while(num == 0) { pthread_cond_wait(&cond, &mut_num); } if(num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mut_num); mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); } pthread_exit(0); }
1
#include <pthread.h> pthread_cond_t prod = PTHREAD_COND_INITIALIZER, cons = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int prod_pos = 0, cons_pos = 0, stock = 0, dataProd = 0, buffer[20]; void * producer (void * arg); void * consumer (void * arg); int main (int argc, char * argv[]) { pthread_t producerThread[5], consumerThread[7]; int i = 0, * idC = 0, * idP = 0; srand (time(0)); for (i = 0; i < 5; i++) { idP = (int *) malloc (sizeof (int)); *idP = i; if (pthread_create (&producerThread[i], 0, producer, (void *) idP)) { printf ("Falha ao criar producerThread numero %d!!\\n", i); return -1; } } for (i = 0; i < 7; i++) { idC = (int *) malloc (sizeof (int)); *idC = i; if (pthread_create (&consumerThread[i], 0, consumer, (void *) idC)) { printf ("Falha ao criar consumerThread numero %d!!\\n", i); return -1; } } pthread_join (consumerThread[0], 0); pthread_join (producerThread[0], 0); return 0; } void * producer (void * arg) { int i = *((int *) arg); while (1) { printf ("Produtor %d: vou produzir um item\\n", i); sleep (2); pthread_mutex_lock (&mutex); dataProd = rand()%1000 + 1; while (stock == 20) { printf ("Produtor %d: vou esperar espaco no buffer\\n", i); pthread_cond_wait (&prod, &mutex); } printf ("Produtor %d: Produzindo item...\\n", i); sleep (2); printf ("Produtor %d: vou inserir item %d na posicao %d\\n", i, dataProd, prod_pos); buffer[prod_pos] = dataProd; prod_pos = (prod_pos + 1)%20; stock++; printf ("Dados em estoque: %d\\n\\n", stock); if (stock == 1) pthread_cond_signal (&cons); pthread_mutex_unlock (&mutex); } pthread_exit (0); } void * consumer (void * arg) { int i = *((int *) arg); int removed = 0; while (1) { pthread_mutex_lock (&mutex); while (stock == 0) { printf ("Consumidor %d: vou esperar por itens\\n", i); pthread_cond_wait (&cons, &mutex); } removed = buffer[cons_pos]; printf ("Consumidor %d:\\nDado removido da posicao %d: %d\\n", i, cons_pos, removed); cons_pos = (cons_pos + 1)%20; stock--; printf ("Dados em estoque: %d\\n\\n", stock); if (stock == (20 - 1)) pthread_cond_signal (&prod); pthread_mutex_unlock (&mutex); printf ("Consumidor %d: Consumindo dado: %d\\n", i, removed); sleep (15); } pthread_exit (0); }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t conds = PTHREAD_COND_INITIALIZER; static pthread_cond_t condr = PTHREAD_COND_INITIALIZER; void *tcons(void *param) { struct thread_param *tparam = param; cinit(param); for (;;) { bool dobreak; int v; pthread_mutex_lock(&mutex); while ( !bisset()&&!bend() ) { pthread_cond_wait(&conds,&mutex); } dobreak=bend(); if ( !dobreak ) { v=bget(); } pthread_mutex_unlock(&mutex); if ( dobreak ) { break; } consume(v); pthread_cond_signal(&condr); } return 0; } void tprod(int n,int tnum) { pinit(n,tnum); while ( !pend() ) { int v=produce(); pthread_mutex_lock(&mutex); while ( !bready() ) { pthread_cond_wait(&condr,&mutex); } bset(v); pthread_mutex_unlock(&mutex); pthread_cond_signal(&conds); } pthread_mutex_lock(&mutex); while ( !bready() ) { pthread_cond_wait(&condr,&mutex); } bclose(); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&conds); }
1
#include <pthread.h> pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t assert_mutex = PTHREAD_MUTEX_INITIALIZER; int return_code = CORRECT; const char *regression_test_name = ""; int ompt_initialized = 0; static void segv_handler(int signo) { static int reported_segv = 0; pthread_mutex_lock(&assert_mutex); if (reported_segv++ == 0) { printf(" %s: error -- failed with segmentation fault\\n", regression_test_name); } pthread_mutex_unlock(&assert_mutex); exit(MIN(return_code, FATAL)); } void serialwork(int workload) { int i = 0; for (i = 0; i < workload; i++) { usleep(500000); } for (i = 0; i < 10000; i++) { void * p = (void *) malloc(10); free(p); } } int main(int argc, char **argv) { regression_test_name = argv[0]; signal(SIGSEGV, segv_handler); openmp_init(); CHECK(ompt_initialized, FATAL, "no call to ompt_initialize. test aborted."); if (return_code == FATAL || return_code == NOT_IMPLEMENTED) { _exit(return_code); } return regression_test(argc, argv); }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t full,empty; buffer_item buffer[15]; int counter; pthread_t tid[3]; pthread_attr_t attr; void *prodcer(void *param); int insert_item(buffer_item item); int remove_item(buffer_item *item); void *consumer(void *param); void initializeData() { pthread_mutex_init(&mutex,0); sem_init(&full,0,0); sem_init(&empty,0,15); pthread_attr_init(&attr); counter=0; } void *producer(void *param) { buffer_item item=0; while(1) { sleep(2); item ++; pthread_mutex_lock(&mutex); sem_wait(&empty); if(insert_item(item)) { fprintf(stderr,"producer report error condition\\n"); } else { printf("producer produced %d\\n",item); } sem_post(&full); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *consumer(void *param) { buffer_item item; while(1) { sleep(2); pthread_mutex_lock(&mutex); sem_wait(&full); if(remove_item(&item)) { fprintf(stderr,"consumer report error condition\\n"); } else { printf("consumer consumed %d\\n",item); } sem_post(&empty); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int insert_item(buffer_item item) { if(counter<15) { buffer[counter]=item; counter++; return 0; } else { return -1; } } int remove_item(buffer_item *item) { if(counter>0) { *item=buffer[(counter-1)]; counter--; return 0; } else { return -1; } } int main(int argc,char *argv[]) { int i; pthread_t c_id; if(argc!=4) { fprintf(stderr,"USAGE:./main.out <INT> <INT> <INT>\\n"); } int mainSleepTime=atoi(argv[1]); int numProd=atoi(argv[2]); int numCons=atoi(argv[3]); initializeData(); printf("Hello---->0\\n"); pthread_create(&c_id,&attr,producer,0); pthread_join(c_id,0); printf("Hello---->1\\n"); for(i=0;i<numCons;i++) { pthread_create(&tid[i],&attr,consumer,0); pthread_join(tid[i],0); } sleep(mainSleepTime); printf("exit the program\\n"); exit(0); }
1
#include <pthread.h> int npos; pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; int buf[10000000], pos=0, val=0, v=0; void *fill(void *); void *verify(void *); int main(int argc, char *argv[]) { int k, nthr, total, count[100]; pthread_t tidf[100], tidv; if (argc != 3) { printf("Usage: %s <nr_pos> <nr_thrs>\\n", argv[0]); return 1; } npos = (atoi(argv[1]))<(10000000)?(atoi(argv[1])):(10000000); nthr = (atoi(argv[2]))<(100)?(atoi(argv[2])):(100); pthread_create(&tidv, 0, verify, 0); for (k=0; k<nthr; k++) { count[k] = 0; pthread_create(&tidf[k], 0, fill, &count[k]); } total = 0; for (k=0; k<nthr; k++) { pthread_join(tidf[k], 0); printf("count[%d] = %d\\n", k, count[k]); total += count[k]; } printf("Total filled = %d\\n", total); pthread_join(tidv, 0); printf("Verified = %d\\n", v); pthread_mutex_destroy(&mut); pthread_cond_destroy(&cond); return 0; } void *fill(void *nr) { while (1) { pthread_mutex_lock(&mut); if (pos >= npos) { pthread_mutex_unlock(&mut); return 0; } buf[pos] = val; pos++; val++; if (v < pos) pthread_cond_signal(&cond); pthread_mutex_unlock(&mut); *(int *)nr += 1; } } void *verify(void *arg) { while (1) { pthread_mutex_lock(&mut); if (v >= npos) { pthread_mutex_unlock(&mut); return 0; } while (v >= pos) pthread_cond_wait(&cond, &mut); if (buf[v] != v) printf("buf[%d] = %d\\n", v, buf[v]); v++; pthread_mutex_unlock(&mut); } }
0
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main(int argc, const char *argv[]) { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if(res != 0) { perror("Mutex initialization failed\\n"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if(res != 0) { perror("hread creation failed\\n"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit) { fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1) { pthread_mutex_lock(&work_mutex); if(work_area[0] != 0) { pthread_mutex_unlock(&work_mutex); sleep(1); }else{ break; } } } pthread_mutex_unlock(&work_mutex); printf("\\n Waiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if(res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); return 0; } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("U input %ld characters \\n", strlen(work_area) - 1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while(work_area[0] == '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
1
#include <pthread.h> sem_t semaphore; pthread_mutex_t mutex; int value; } my_struct_t; my_struct_t data; void *my_thread(void *); int main(int argc, char **argv) { pthread_t thread_id; data.value = 0; sem_init(&data.semaphore, 0, 0); pthread_mutex_init(&data.mutex, 0); pthread_create(&thread_id, 0, my_thread, 0); pthread_mutex_lock(&data.mutex); if(data.value == 0){ printf("Value of data = %d. Waiting for someone to change it and signal me. \\n", data.value); pthread_mutex_unlock(&data.mutex); sem_wait(&data.semaphore); } pthread_mutex_lock(&data.mutex); if(data.value != 0){ printf("Change in variable state was signalled. \\n"); printf("Value of data = %d. \\n", data.value); } pthread_mutex_unlock(&data.mutex); pthread_join(thread_id, 0); pthread_exit(0); } void *my_thread(void *args) { sleep(5); pthread_mutex_lock(&data.mutex); data.value = 1; pthread_mutex_unlock(&data.mutex); sem_post(&data.semaphore); pthread_exit(0); }
0
#include <pthread.h> void *malloc(size_t size) { size_t total_size; void *block; struct header_t *header; if (!size) return 0; pthread_mutex_lock(&global_malloc_lock); header = get_free_block(size); if (header) { header->is_free = 0; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } total_size = sizeof(struct header_t) + size; block = sbrk(total_size); if (block == (void*) -1) { pthread_mutex_unlock(&global_malloc_lock); return 0; } header = block; header->size = size; header->is_free = 0; header->next = 0; if (!head) head = header; if (tail) tail->next = header; tail = header; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } struct header_t *get_free_block(size_t size) { struct header_t *curr = head; while(curr) { if (curr->is_free && curr->size >= size) return curr; curr = curr->next; } return 0; }
1
#include <pthread.h> pthread_mutex_t m; int s = 0; int l = 0; void* thr1(void* arg) { pthread_mutex_lock (&m); __VERIFIER_assert (l==0 || s==1); s = 1; l = 1; pthread_mutex_unlock (&m); return 0; } int main() { s = __VERIFIER_nondet_int(0, 1000); pthread_t t[5]; pthread_mutex_init (&m, 0); int i = 0; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); return 0; }
0
#include <pthread.h> int ta = 0; int chairs[3] = {-1,-1,-1}; int chair0 = -1, chair1 = -1, chair2 = -1; int students[10] = {2,2,2,2,2,2,2,2,2,2}; pthread_mutex_t mutex[10]; pthread_mutex_t ta_mutex; pthread_mutex_t run; pthread_t students_thread[10], ta_thread; void student_state(int stdno); void ta_state(); void *ta_func(void *args); void *student_func(void *args); int main (int argc, char *argv[]){ int i; for (i = 0; i < 10; i++){ printf("initializing mutex %d\\n", i); pthread_mutex_init(&mutex[i], 0); } pthread_mutex_init(&ta_mutex, 0); pthread_mutex_init(&run, 0); pthread_create(&ta_thread, 0, ta_func, 0); for(i = 0; i < 10; i++){ pthread_t tpr = students_thread[i]; pthread_create(&tpr, 0, student_func, &i); printf("Student %d is initially programming\\n",i); } for (i = 0; i < 10; i++){ pthread_t tpr2 = students_thread[i]; pthread_join(tpr2, 0); } pthread_join(ta_thread, 0); return 0; } void student_state(int stdno){ int i = stdno; pthread_mutex_lock(&mutex[i]); switch (students[i]) { case 0: printf("student %d is with ta\\n", i); break; case 1: break; case 2: if (ta == 0){ pthread_mutex_lock(&ta_mutex); printf("student %d awakens ta\\n", i); sleep(1); ta = 1; students[i] = 0; printf("ta is helping student %d\\n", i); ta = 2; students[i] = 2; pthread_mutex_unlock(&ta_mutex); break; } if (ta == 1){ pthread_mutex_lock(&ta_mutex); if (chair0 == -1){ chair0 == stdno; sleep(1); students[i] == 1; printf("student %d sits and waits\\n", i); pthread_mutex_unlock(&ta_mutex); break; } else if (chair1 == -1){ chair1 == stdno; sleep(1); students[i] == 1; printf("student %d sits and waits\\n", i); pthread_mutex_unlock(&ta_mutex); break; } else if (chair2 == -1){ chair2 == stdno; sleep(1); students[i] == 1; printf("student %d sits and waits\\n", i); pthread_mutex_unlock(&ta_mutex); break; } } pthread_mutex_unlock(&ta_mutex); break; } pthread_mutex_unlock(&mutex[i]); } void ta_state(){ int i; switch (ta) { case 1: for (i = 0; i < 10; i++){ if (students[i] == 0){ break; } } sleep(1); students[i] = 2; ta = 2; break; case 0: break; case 2: printf("ta is checking chairs\\n"); if (chair0 != -1){ sleep(1); ta = 1; printf("ta is helping student %d\\n", chair0); pthread_mutex_lock(&mutex[chair0]); sleep(1); students[chair0] == 0; pthread_mutex_unlock(&mutex[chair0]); chair0 = -1; break; } printf("chair 0 is empty\\n"); if (chair1 != -1){ sleep(1); ta = 1; printf("ta is helping student %d\\n", chair1); pthread_mutex_lock(&mutex[chair1]); sleep(1); students[chair1] == 0; pthread_mutex_unlock(&mutex[chair1]); chair1 = -1; break; } printf("chair 1 is empty\\n"); if (chair2 != -1){ sleep(1); ta = 1; printf("ta is helping student %d\\n", chair2); pthread_mutex_lock(&mutex[chair2]); sleep(1); students[chair2] == 0; pthread_mutex_unlock(&mutex[chair2]); chair2 = -1; break; } sleep(1); ta = 0; printf("chairs are empty ta will sleep\\n"); break; } } void *student_func(void *args){ int *ptr = (int *) args; int i = *ptr; while(1){ student_state(i); } } void *ta_func(void *args){ while(1){ pthread_mutex_lock(&ta_mutex); ta_state(); pthread_mutex_unlock(&ta_mutex); } }
1
#include <pthread.h> struct rfifo *rfifo_init(unsigned int size) { struct rfifo *fifo = 0; fifo = (struct rfifo*)malloc(sizeof(struct rfifo)); if (!fifo) return 0; memset(fifo, 0,sizeof(struct rfifo)); fifo->buffer = (char *)malloc(size); if (!fifo->buffer) { free(fifo); return 0; } memset(fifo->buffer, 0, size); fifo->size = size; fifo->in = 0; fifo->out = 0; pthread_mutex_init(&fifo->lock, 0); return fifo; } void rfifo_free(struct rfifo *fifo) { if (fifo) { if (fifo->buffer) { free(fifo->buffer); fifo->buffer = 0; } free(fifo); fifo = 0; } return; } int rfifo_put(struct rfifo *fifo, char *buffer, unsigned int len) { unsigned int ret; if ((!fifo) || (!buffer)) return -1; pthread_mutex_lock(&fifo->lock); __rfifo_put(fifo, buffer, len); pthread_mutex_unlock(&fifo->lock); return ret; } __rfifo_put(struct rfifo *fifo, char *buffer, unsigned int len) { unsigned int l; len = (((len) < (fifo->size - fifo->in + fifo->out)) ? (len) : (fifo->size - fifo->in + fifo->out)); l = (((len) < (fifo->size - (fifo->in & (fifo->size - 1)))) ? (len) : (fifo->size - (fifo->in & (fifo->size - 1)))); memcpy(fifo->buffer + (fifo->in & (fifo->size - 1)), buffer, l); memcpy(fifo->buffer, buffer + l, len - l); fifo->in += len; return len; } int rfifo_get(struct rfifo *fifo, char *buffer, unsigned int len) { unsigned int ret; if ((!fifo) || (!buffer)) return -1; pthread_mutex_lock(&fifo->lock); ret = __rfifo_get(fifo, buffer, len); if (fifo->in == fifo->out) fifo->in = fifo->out = 0; pthread_mutex_unlock(&fifo->lock); return ret; } int __rfifo_get(struct rfifo *fifo, char *buffer, unsigned int len) { unsigned int l; len = (((len) < (fifo->in - fifo->out)) ? (len) : (fifo->in - fifo->out)); l = (((len) < (fifo->size - (fifo->out & (fifo->size - 1)))) ? (len) : (fifo->size - (fifo->out & (fifo->size - 1)))); memcpy(buffer, fifo->buffer + (fifo->out & (fifo->size - 1)), l); memcpy(buffer + l, fifo->buffer, len - l); fifo->out += len; return len; }
0
#include <pthread.h> int v_counter = 0; int turn = 0; pthread_mutex_t c_mutex; pthread_cond_t c_threshold_cv; void yield (void) { } void busy_wait (int me, int next) { while (1) { while (turn != me) yield(); if (v_counter >= 20) { turn = next; break; } v_counter++; printf ("T[%d] = %d.\\n",me, v_counter); turn = next; if (v_counter >= 20) break; } } void no_busy_wait (int me, int next) { while (1) { pthread_mutex_lock (&c_mutex); while (turn != me) pthread_cond_wait (&c_threshold_cv, &c_mutex); if (v_counter == 20) { turn = next; pthread_mutex_unlock (&c_mutex); pthread_cond_signal (&c_threshold_cv); break; } else { v_counter++; printf ("T[%d] = %d.\\n",me, v_counter); turn = next; pthread_mutex_unlock (&c_mutex); pthread_cond_signal (&c_threshold_cv); } } } void *working_thread(void *t) { int me = (int) t; int next = 0; if (me+1 == 3) next = 0; else next = me + 1; if (0) busy_wait(me, next); else no_busy_wait(me, next); printf ("Thread %d finished.\\n",me); return 0; } void *test_count(void *t) { return 0; } int main(int argc, char *argv[]) { int i = 0; pthread_t threads[3]; pthread_mutex_init(&c_mutex, 0); pthread_cond_init (&c_threshold_cv, 0); for (i = 0; i < 3 - 1; ++i) pthread_create(&threads[i], 0, working_thread, (void *)i); pthread_create(&threads[i], 0, working_thread, (void *)i); for (i = 0; i < 3; ++i) pthread_join(threads[i], 0); return 0; }
1
#include <pthread.h> pthread_t P1, P2, P3; int t1 = 0, t2 = 0, t3 = 0; pthread_mutex_t M; int flag; void *inc_t1(void *interval) { while(1) { sleep(2); t1 += (int)interval; printf("Counter 1: %d----------------------------------------------\\n", t1); } } void *inc_t2(void *interval) { while(1) { sleep(2); t2 += (int)interval; printf("-------------------------Counter 2: %d----------------------\\n", t2); } } void *inc_t3(void *interval) { while(1) { sleep(2); t3 += (int)interval; printf("------------------------------------------------Counter 3: %d\\n", t3); } } void *clock1(void *interval) { pthread_t id1; pthread_create(&id1, 0, inc_t1, interval); while(1) { sleep(5); pthread_mutex_lock(&M); printf("P1 received msg from P%d at interval %d\\n", flag, t1); if(flag == 2 && t2 > t1) t1 = t2 + 1; else if(flag ==3 && t3 > t1) t1 = t3 + 1; flag = 1; printf("P1 updated its count to %d\\n", t1); printf("P1 sends msg at interval %d\\n", t1); pthread_mutex_unlock(&M); } pthread_join(id1, 0); } void *clock2(void *interval) { pthread_t id2; pthread_create(&id2, 0, inc_t2, interval); while(1) { sleep(5); pthread_mutex_lock(&M); printf("P2 received msg from P%d at interval %d\\n", flag, t2); if(flag == 1 && t1 > t2) t2 = t1 + 1; else if(flag ==3 && t3 > t2) t2 = t3 + 1; flag = 2; printf("P2 updated its count to %d\\n", t2); printf("P2 sends msg at interval %d\\n", t2); pthread_mutex_unlock(&M); sleep(5); } pthread_join(id2, 0); pthread_join(P2, 0); } void *clock3(void *interval) { pthread_t id3; pthread_create(&id3, 0, inc_t3, interval); while(1) { sleep(5); pthread_mutex_lock(&M); printf("P3 received msg from P%d at interval %d\\n", flag, t3); if(flag == 2 && t2 > t3) t3 = t2 + 1; else if(flag == 1 && t1 > t3) t3 = t1 + 1; flag = 3; printf("P3 updated its count to %d\\n", t3); printf("P3 sends msg at interval %d\\n", t3); pthread_mutex_unlock(&M); sleep(3); } pthread_join(id3, 0); pthread_join(P3, 0); } int main() { pthread_mutex_init(&M, 0); int int1 = 5, int2 = 10, int3 = 8; printf("Enter start process: (1,2,3):- "); scanf("%d", &flag); pthread_create(&P1, 0, clock1, (void *)int1); pthread_create(&P2, 0, clock2, (void *)int2); pthread_create(&P3, 0, clock3, (void *)int3); pthread_join(P1, 0); return 0; }
0
#include <pthread.h> int TAM = 4; int NUM_THREAD = 1; int linha_processar = 0; long long int **A; long long int **B; long long int **C; pthread_mutex_t mutex; void *runner(void *param); void preenche_matriz(long long int **MAT); void main(int argc, char* argv[]) { int i,j, count = 0; NUM_THREAD = atoi(argv[1]); TAM = atoi(argv[2]); pthread_mutex_init(&mutex, 0); pthread_t tid[TAM]; A = (long long int**) malloc (TAM * sizeof(long long int ) ); for(i=0; i<TAM; i++) A[i]= (long long int*) malloc (TAM * sizeof(long long int ) ); B = (long long int**) malloc (TAM * sizeof(long long int ) ); for(i=0; i<TAM; i++) B[i]= (long long int*) malloc (TAM * sizeof(long long int ) ); C = (long long int**) malloc (TAM * sizeof(long long int ) ); for(i=0; i<TAM; i++) C[i]= (long long int*) malloc (TAM * sizeof(long long int ) ); preenche_matriz(A); preenche_matriz(B); for(i = 0; i < NUM_THREAD; i++) { pthread_create(&tid[i],0 ,runner, (void *)i); } for(i = 0; i< NUM_THREAD; i++){ pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); } void *runner(void *param) { int i, n, j; int id = (int)param; while(i<(TAM-NUM_THREAD)){ pthread_mutex_lock(&mutex); i = linha_processar; linha_processar++; pthread_mutex_unlock(&mutex); for(j =0; j< TAM; j++){ for(n = 0; n< TAM; n++){ C[i][j] += A[i][n] * B[n][j]; } } } } void preenche_matriz(long long int **MAT){ int i,j; srand(time(0)); for(i=0; i<TAM; i++){ for(j=0;j<TAM;j++){ MAT[i][j] = rand()/999; } } }
1
#include <pthread.h> int fifo_mut_m_spinlock; int fifo_mut_m_count; int ProgressIndicatorsMutex_m_spinlock; int ProgressIndicatorsMutex_m_count; int TerminateFlagMutex_m_spinlock; int TerminateFlagMutex_m_count; int ProducerDoneMutex_m_spinlock; int ProducerDoneMutex_m_count; int producerDone = 0; int terminateFlag = 0; void *fifo; int fifo_full; int fifo_empty; int NumBlocks, InBytesProduced, inSize; int __X__; inline int syncGetProducerDone() { int ret; pthread_mutex_lock(ProducerDoneMutex_m_spinlock, ProducerDoneMutex_m_count); ret = producerDone; pthread_mutex_unlock(ProducerDoneMutex_m_spinlock, ProducerDoneMutex_m_count); return ret; } inline int syncGetTerminateFlag() { int ret; pthread_mutex_lock(TerminateFlagMutex_m_spinlock, TerminateFlagMutex_m_count); ret = terminateFlag; pthread_mutex_unlock(TerminateFlagMutex_m_spinlock, TerminateFlagMutex_m_count); return ret; } int producer() { pthread_mutex_lock(ProgressIndicatorsMutex_m_spinlock, ProgressIndicatorsMutex_m_count); NumBlocks = 0; InBytesProduced = 0; pthread_mutex_unlock(ProgressIndicatorsMutex_m_spinlock, ProgressIndicatorsMutex_m_count); while (1) { if (syncGetTerminateFlag() != 0) { return -1; } pthread_mutex_lock(fifo_mut_m_spinlock, fifo_mut_m_count); while (fifo_full) { pthread_cond_wait(fifo_mut_m_spinlock, fifo_mut_m_count); if (syncGetTerminateFlag() != 0) { pthread_mutex_unlock(fifo_mut_m_spinlock, fifo_mut_m_count); return -1; } } __X__ = 0; assert(__X__<=0); fifo_empty = 0; pthread_cond_signal(); pthread_mutex_lock(ProgressIndicatorsMutex_m_spinlock, ProgressIndicatorsMutex_m_count); ++NumBlocks; InBytesProduced += inSize; pthread_mutex_unlock(ProgressIndicatorsMutex_m_spinlock, ProgressIndicatorsMutex_m_count); pthread_mutex_unlock(fifo_mut_m_spinlock, fifo_mut_m_count); } } void *consumer() { for (;;) { if (syncGetTerminateFlag() != 0) { return (0); } pthread_mutex_lock(fifo_mut_m_spinlock, fifo_mut_m_count); for (;;) { if (!fifo_empty) { __X__ = 1; assert(__X__>=1); fifo_full = 0;; break; } if (fifo_empty && ((syncGetProducerDone() == 1) || (syncGetTerminateFlag() != 0))) { pthread_mutex_unlock(fifo_mut_m_spinlock, fifo_mut_m_count); return (0); } pthread_cond_wait(fifo_mut_m_spinlock, fifo_mut_m_count); } pthread_cond_signal(); pthread_mutex_unlock(fifo_mut_m_spinlock, fifo_mut_m_count); } return (0); }
0
#include <pthread.h> clock_t start, finish; double timeOut; int is_data_ready = 0; int serversock, clientsock; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* streamServer(void* arg); void quit(char* msg, int retval); char attitude[3]; char attitudeBack[3]; int main(int argc, char** argv) { pthread_t thread_s; int key; fprintf(stdout, "Press 'q' to quit.\\n\\n"); if (pthread_create(&thread_s, 0, streamServer, 0)) { quit("pthread_create failed.", 1); } char buf[100]; int pitch = 0; int roll = 0; int yaw = 0; while(1) { printf("pitch:"); rewind(stdin); fgets(buf,10,stdin); sscanf(buf,"%d",&pitch); printf("roll:"); rewind(stdin); fgets(buf,10,stdin); sscanf(buf,"%d",&roll); printf("yaw:"); rewind(stdin); fgets(buf,10,stdin); sscanf(buf,"%d",&yaw); attitude[0] = (char)pitch; attitude[1] = (char)roll; attitude[2] = (char)yaw; is_data_ready = 1; printf("values received:\\n\\n"); printf("%d, %d, %d\\n",attitudeBack[0], attitudeBack[1], attitudeBack[2]); } if (pthread_cancel(thread_s)) { quit("pthread_cancel failed.", 1); } quit(0, 0); } void* streamServer(void* arg) { struct sockaddr_in server; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); if ((serversock = socket(PF_INET, SOCK_STREAM, 0)) == -1) { quit("socket() failed", 1); } printf("family : %d\\n",AF_INET); printf("PORT : %d\\n",8888); printf("addr : %d\\n",INADDR_ANY); memset(&server, 0, sizeof(server)); server.sin_family = AF_INET; server.sin_port = htons(8888); server.sin_addr.s_addr = INADDR_ANY; if (bind(serversock, (const void*)&server, sizeof(server)) == -1) { quit("bind() failed", 1); } printf("wait for client\\n"); if (listen(serversock, 10) == -1) { quit("listen() failed.", 1); } printf("client accepted\\n"); if ((clientsock = accept(serversock, 0, 0)) == -1) { quit("accept() failed", 1); } printf("after client accept\\n"); int bytes, i; while(1) { pthread_mutex_lock(&mutex); if (is_data_ready) { bytes = send(clientsock, attitude , sizeof(attitude), 0); recv(clientsock, attitudeBack, sizeof(attitudeBack), 0); is_data_ready = 0; } pthread_mutex_unlock(&mutex); if (bytes != sizeof(attitude)) { fprintf(stderr, "Connection closed.\\n"); close(clientsock); if ((clientsock = accept(serversock, 0, 0)) == -1) { quit("accept() failed", 1); } } pthread_testcancel(); } } void quit(char* msg, int retval) { if (retval == 0) { fprintf(stdout, (msg == 0 ? "" : msg)); fprintf(stdout, "\\n"); } else { fprintf(stderr, (msg == 0 ? "" : msg)); fprintf(stderr, "\\n"); } if (clientsock) close(clientsock); if (serversock) close(serversock); pthread_mutex_destroy(&mutex); exit(retval); }
1
#include <pthread.h> gf_lock_t lock; uintptr_t xl_up; uint32_t xl_up_cout; } share_data_t; void ec_mask_to_char_array (uintptr_t mask, unsigned char *array, int numsubvols) { int i = 0; for (i = 0; i < numsubvols; i++) array[i] = ((mask >> i) & 1); } uintptr_t ec_char_array_to_mask (unsigned char *array, int numsubvols) { int i = 0; uintptr_t mask = 0; for (i = 0; i < numsubvols; i++) if (array[i]) mask |= (1ULL<<i); return mask; } void *write_thread (void *data) { int ret = 0; int i = 0; int count = 0; share_data_t *share_data = data; if (!share_data) { ret = -EINVAL; printf ("arg is invalid!\\n"); goto out; } while (1) { pthread_mutex_lock (&share_data->lock); for (i = 0; i < 10; i++) { if (count % (i+1)) { share_data->xl_up ^= 1ULL << i; } else { share_data->xl_up |= 1ULL << i; } } pthread_mutex_unlock (&share_data->lock); count++; } out: return 0; } void *read_thread (void *data) { int i = 0; int ret = 0; share_data_t *share_data = data; unsigned char up_subvols[10] = {0,}; if (!share_data) { ret = -EINVAL; printf ("arg is invalid!\\n"); goto out; } while (1) { memset (up_subvols, 0, 10); ec_mask_to_char_array (share_data->xl_up, up_subvols, 10); for (i = 0; i < 10; i++) { if (up_subvols[i] < 0 || up_subvols[i] > 1) { printf ("ERROR: %d\\n", up_subvols[i]); } } } out: return 0; } int main (void) { int ret = 0; int i = 0; pthread_t threads[10]; share_data_t share_data; memset (&share_data, 0, sizeof(share_data_t)); pthread_mutex_init (&share_data.lock, 0); for (i = 0; i < 10; i++) { if (i % 2) ret = pthread_create (&threads[i], 0, write_thread, (void*)&share_data); else ret = pthread_create (&threads[i], 0, read_thread, (void*)&share_data); if (ret != 0) { printf ("ERROR: pthread_create() failed:%s\\n", strerror(errno)); break; } } printf ("Success to create %d threads\\n", i); for (i = 0; i < 10; i++) { pthread_join (threads[i], 0); } pthread_mutex_destroy (&share_data.lock); return ret; }
0
#include <pthread.h> char *ID; int N; int global_i; int procs; int Norm; volatile float A[5000][5000], B[5000], X[5000]; pthread_mutex_t global_i_lock; int NTHREADS = 4; void gauss(); unsigned int time_seed() { struct timeval t; struct timezone tzdummy; gettimeofday(&t, &tzdummy); return (unsigned int)(t.tv_usec); } void parameters(int argc, char **argv) { int submit = 0; int seed = 0; char uid[L_cuserid + 2]; if ( argc == 1 && !strcmp(argv[1], "submit") ) { submit = 1; N = 4; procs = 2; printf("\\nSubmission run for \\"%s\\".\\n", cuserid(uid)); strcpy(uid,ID); srand(4|2[uid]&3); } else { if (argc == 3) { seed = atoi(argv[3]); srand(seed); printf("Random seed = %i\\n", seed); } else { printf("Usage: %s <matrix_dimension> <num_procs> [random seed]\\n", argv[0]); printf(" %s submit\\n", argv[0]); exit(0); } } if (!submit) { N = atoi(argv[1]); if (N < 1 || N > 5000) { printf("N = %i is out of range.\\n", N); exit(0); } procs = atoi(argv[2]); if (procs < 1) { printf("Warning: Invalid number of processors = %i. Using 1.\\n", procs); procs = 1; } } printf("\\nMatrix dimension N = %i.\\n", N); printf("Number of processors = %i.\\n", procs); } void initialize_inputs() { int row, col; printf("\\nInitializing...\\n"); for (col = 0; col < N; col++) { for (row = 0; row < N; row++) { A[row][col] = (float)rand() / 32768.0; } B[col] = (float)rand() / 32768.0; X[col] = 0.0; } } void print_inputs() { int row, col; if (N < 10) { printf("\\nA =\\n\\t"); for (row = 0; row < N; row++) { for (col = 0; col < N; col++) { printf("%5.2f%s", A[row][col], (col < N-1) ? ", " : ";\\n\\t"); } } printf("\\nB = ["); for (col = 0; col < N; col++) { printf("%5.2f%s", B[col], (col < N-1) ? "; " : "]\\n"); } } } void print_X() { int row; if (N < 10) { printf("\\nX = ["); for (row = 0; row < N; row++) { printf("%5.2f%s", X[row], (row < N-1) ? "; " : "]\\n"); } } } int main(int argc, char **argv) { struct timeval etstart, etstop; struct timezone tzdummy; clock_t etstart2, etstop2; unsigned long long usecstart, usecstop; struct tms cputstart, cputstop; ID = argv[argc-1]; argc--; parameters(argc, argv); initialize_inputs(); print_inputs(); printf("\\nStarting clock.\\n"); gettimeofday(&etstart, &tzdummy); etstart2 = times(&cputstart); gauss(); gettimeofday(&etstop, &tzdummy); etstop2 = times(&cputstop); printf("Stopped clock.\\n"); usecstart = (unsigned long long)etstart.tv_sec * 1000000 + etstart.tv_usec; usecstop = (unsigned long long)etstop.tv_sec * 1000000 + etstop.tv_usec; print_X(); printf("\\nElapsed time = %g ms.\\n", (float)(usecstop - usecstart)/(float)1000); } void *computeRow(void *threadid){ long tid = (long)threadid; int i = 0; int row,col; float multiplier; while(1){ pthread_mutex_lock(&global_i_lock); i = global_i; global_i+=1; pthread_mutex_unlock(&global_i_lock); if(i>=N){ break; } multiplier = A[i][Norm]/A[Norm][Norm]; for(col = Norm;col<N;col++){ A[i][col] -= A[Norm][col]*multiplier; } B[i] -= B[Norm] * multiplier; } } void gauss() { int norm, row, col; int i; printf("Computing Parrellely.\\n"); pthread_t threads[procs]; global_i =0; pthread_mutex_init(&global_i_lock,0); for (norm = 0; norm < N - 1; norm++) { Norm = norm; global_i = norm; for(i =0;i<procs;i++){ pthread_create(&threads[i],0,&computeRow,(void *)i); } for(i = 0;i<procs;i++){ pthread_join(threads[i],0); } } pthread_mutex_destroy(&global_i_lock); for (row = N - 1; row >= 0; row--) { X[row] = B[row]; for (col = N-1; col > row; col--) { X[row] -= A[row][col] * X[col]; } X[row] /= A[row][row]; } }
1
#include <pthread.h> struct sockaddr_in addr; int connfd; int uid; char name[32]; }client_t; void handle_client(void *client); void handle_send(void *client); char *dequeue(); char *encrypt(char *msg); void queue(char *msg); void queue_add(client_t *cl); void queue_delete(int uid); extern char *encryption_1(char *msg, unsigned int msg_len); char *message_queue[5]; client_t *clients[10]; static unsigned int msg_count = 0, client_count = 0, msg_ptr = 0; static int uid = 10; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void error(char *msg){ perror(msg); exit(1); } void strip_newline(char *s){ while(*s != '\\0'){ if(*s == '\\r' || *s == '\\n'){ *s = '\\0'; } s++; } } int main(int argc, char *argv[]){ unsigned int sockfd, newsockfd, portno, clilen; pthread_t threadID; struct sockaddr_in serv_addr, cli_addr; if(argc < 2){ fprintf(stderr, "ERROR, no port provided\\n"); exit(1); } if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ error("ERROR opening socket"); } bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if(bind(sockfd, (struct sockaddr * ) & serv_addr, sizeof(serv_addr)) < 0){ error("ERROR on binding"); } listen(sockfd, 5); clilen = sizeof(cli_addr); while(1){ if((newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen)) < 0){ error("ERROR on accept"); }else{ client_t *cli = (client_t *)malloc(sizeof(client_t)); cli->addr = cli_addr; cli->connfd = newsockfd; cli->uid = uid++; sprintf(cli->name, "%d", cli->uid); queue_add(cli); pthread_create(&threadID, 0, (void *) &handle_client, cli); } } return 0; } void handle_client(void *client){ client_t *cli = (client_t *) client; int nsfd = cli->connfd; char buffer[256]; int n; bzero(buffer, 256); while(1){ if((n = read(nsfd, buffer, 255)) < 0){ error("ERROR reading from socket"); } printf("read: %s\\n", buffer); strip_newline(buffer); queue(buffer); handle_send(client); bzero(buffer, 256); } } void handle_send(void *client){ client_t *cli = (client_t *) client; char buffer[256]; int n; bzero(buffer, 256); if(msg_count > 0){ printf("DEBUG: send\\n"); char *temp = dequeue(); temp = encrypt(temp); strcat(buffer, temp); printf("DEBUG TEMP: %s\\n", temp); printf("sending: %s\\n", buffer); strip_newline(buffer); for(int i = 0; i < client_count; i++){ if(cli->uid != clients[i]->uid){ if((n = write(clients[i]->connfd, buffer, 255)) < 0){ error("ERROR writing to socket"); } } } msg_count--; msg_ptr--; bzero(buffer, 256); } } void queue(char *msg){ printf("DEBUG MSG: %s\\n", msg); if(msg_count < 5){ pthread_mutex_lock(&mtx); message_queue[msg_count] = msg; msg_count++; pthread_mutex_unlock(&mtx); printf("DEBUG QUEUED MSG: %s\\n", message_queue[msg_count - 1]); printf("DEBUG msg_count: %d\\n", msg_count); }else{ pthread_mutex_lock(&mtx); message_queue[0] = msg; msg_count = 1; msg_ptr = 0; pthread_mutex_unlock(&mtx); } } char *dequeue(){ printf("DEBUG: dequeue\\n"); char *temp = "\\0"; pthread_mutex_lock(&mtx); if(msg_count > 0){ printf("DEBUG MSG_COUNT: %d\\n", msg_count); temp = message_queue[msg_ptr]; msg_ptr++; printf("idek anymore: %s\\n", temp); } printf("DEBUG DEQUEUE MSG: %s\\n", message_queue[msg_ptr - 1]); pthread_mutex_unlock(&mtx); return temp; } void queue_add(client_t *cli){ pthread_mutex_lock(&mtx); if(client_count < 10){ clients[client_count] = cli; client_count++; } pthread_mutex_unlock(&mtx); } char *encrypt(char *msg){ unsigned int size = strlen(msg); printf("SIZE OF MSG: %d\\n", size); char* temp = "\\0"; temp = encryption_1(msg, size); printf("encrypted: %s\\n", msg); return temp; }
0
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t not_empty, not_full; int cokes = 5; void* thread_function(void* function); void refill_coke(void); void consume_coke(void); int main(int argc, const char * argv[]) { int i; pthread_t producers[10]; pthread_t consumers[3]; lock = PTHREAD_MUTEX_INITIALIZER; not_empty = PTHREAD_COND_INITIALIZER; not_full = PTHREAD_COND_INITIALIZER; for (i=0; i<3; i++) { if (pthread_create(&consumers[i],0,thread_function,&consume_coke) != 0) { perror("Thread creation failed"); exit(1); } } for (i=0; i<10; i++) { if (pthread_create(&producers[i],0,thread_function,&refill_coke) != 0) { perror("Thread creation failed"); exit(1); } } sleep(10); return 0; } void* thread_function(void* function) { int i; for (i=0; i<6; i++) { ((void (*)(void))function)(); } pthread_exit(0); } void refill_coke(void) { pthread_mutex_lock(&lock); while(cokes == 10){ printf("PP Machine is full.\\n"); pthread_cond_wait(&not_full, &lock); } cokes = 10; printf(">> Cokes refilled.\\n"); pthread_cond_signal(&not_empty); pthread_mutex_unlock(&lock); } void consume_coke(void) { pthread_mutex_lock(&lock); while(cokes == 0){ printf("CC Machine is empty.\\n"); pthread_cond_wait(&not_empty, &lock); } cokes = cokes - 1; printf("<< Coke removed. %d are left.\\n", cokes); pthread_cond_signal(&not_full); pthread_mutex_unlock(&lock); }
1
#include <pthread.h> { ElemType elem[(5 + 1)]; int head, tail; }Queue; Queue the_queue, *p_queue; pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t producer_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t consumer_cond = PTHREAD_COND_INITIALIZER; int ERROR_CODE; void init_queue(Queue *p_queue) { memset(p_queue, 0, sizeof(*p_queue)); } int is_queue_full(Queue *p_queue) { if(p_queue->head == (p_queue->tail + 1)% (5 + 1)) return 1; else return 0; } int is_queue_empty(Queue *p_queue) { if(p_queue->head == p_queue->tail) return 1; else return 0; } int get_queue_num(Queue *p_queue) { return (p_queue->tail + (5 + 1) - p_queue->head)%(5 + 1); } int insert_queue(Queue *p_queue, ElemType inserted_elem) { if(is_queue_full(p_queue)) { printf("The queue is full\\n"); ERROR_CODE = -1; return 0; } else { p_queue->tail += 1; p_queue->tail %= (5 + 1); p_queue->elem[p_queue->tail] = inserted_elem; return 1; } } int delet_queue(Queue *p_queue) { if(is_queue_empty(p_queue)) { printf("The queue is empty\\n"); ERROR_CODE = -1; return 0; } else { p_queue->head += 1; p_queue->head %= (5 + 1); return p_queue->elem[p_queue->head]; } } int get_queue_tail(Queue *p_queue) { return p_queue->tail; } int get_queue_head(Queue *p_queue) { return p_queue->head; } void * consumer_thread(void *para) { long thread_no = (long)para; while(1) { pthread_mutex_lock(&queue_lock); while(is_queue_empty(p_queue)) { pthread_cond_wait(&consumer_cond, &queue_lock); } delet_queue(p_queue); if(get_queue_num(p_queue) == 5 - 1) { pthread_cond_broadcast(&producer_cond); } printf("consumer thread[%ld] deletes queue[%d]=%d\\n", thread_no, p_queue->head, p_queue->elem[p_queue->head]); pthread_mutex_unlock(&queue_lock); sleep(rand()%3 + 1); } } void * producer_thread(void *para) { long thread_no = (long)para; int tmp; while(1) { pthread_mutex_lock(&queue_lock); while(is_queue_full(p_queue)) { pthread_cond_wait(&producer_cond, &queue_lock); } tmp = get_queue_tail(p_queue); insert_queue(p_queue, tmp); if(get_queue_num(p_queue) == 1) { pthread_cond_broadcast(&consumer_cond); } printf("producer thread[%ld] produces queue[%d]=%d\\n", thread_no, p_queue->tail, tmp ); pthread_mutex_unlock(&queue_lock); sleep(rand()%3 + 1); } } int main(int argc, char const *argv[]) { p_queue = &the_queue; pthread_t all_threads[2 + 3]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); int index; init_queue(p_queue); for (index = 0; index < 2; ++index) { pthread_create(&all_threads[index], &attr, consumer_thread, (void*)index); } sleep(2); for (index = 0; index < 3; ++index) { pthread_create(&all_threads[index + 2], &attr, producer_thread, (void*)index); } pthread_attr_destroy(&attr); while(1); return 0; }
0
#include <pthread.h> int thread_flag; pthread_mutex_t thread_flag_mutex; void initialize_flag() { pthread_mutex_init(&thread_flag_mutex, 0); thread_flag = 0; } void do_work() { printf("Thread func...\\nWe do something very important!\\n"); } void* thread_function(void* thread_arg) { while (1) { int flag_is_set; pthread_mutex_lock(&thread_flag_mutex); flag_is_set = thread_flag; pthread_mutex_unlock(&thread_flag_mutex); if (flag_is_set) do_work(); } return 0; } void set_thread_flag(int flag_value) { pthread_mutex_lock(&thread_flag_mutex); thread_flag = flag_value; pthread_mutex_unlock(&thread_flag_mutex); } int main(int argc, char** argv) { const int ciExitSuccess = 0; pthread_t thread; int inVal = 0; pthread_create(&thread, 0, thread_function, 0); while(1) { printf("Enter non zero number to start or 0 to stop.: "); scanf("%d", &inVal); set_thread_flag(inVal); } return ciExitSuccess; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t display; int oxygen = 0; int hydrogen = 0; pthread_barrier_t barrier; sem_t oxyQueue; sem_t hydroQueue; int water = 0; int building = 0; void bond(int i){ building = 1; sleep (1); } void* oxygen_thread (void *v) { pthread_mutex_lock(&mutex); oxygen += 1; sleep(random() % 3 + 1); if (hydrogen >= 2) { pthread_mutex_lock(&display); sem_post(&hydroQueue); sem_post(&hydroQueue); hydrogen -= 2; sem_post(&oxyQueue); oxygen -= 1; pthread_mutex_unlock(&display); } else pthread_mutex_unlock(&mutex); sem_wait(&oxyQueue); bond(1); pthread_barrier_wait(&barrier); water++; building = 0; pthread_mutex_unlock(&mutex); return 0; } void* hydrogen_thread (void *v) { pthread_mutex_lock(&mutex); hydrogen += 1; sleep(random() % 3); if ((hydrogen >= 2) && (oxygen >= 1)) { pthread_mutex_lock(&display); sem_post(&hydroQueue); sem_post(&hydroQueue); hydrogen -= 2; sem_post(&oxyQueue); oxygen -= 1; pthread_mutex_unlock(&display); } else pthread_mutex_unlock(&mutex); sem_wait(&hydroQueue); bond(2); pthread_barrier_wait(&barrier); return 0; } void* draw_anim(void *v) { while (1) { pthread_mutex_lock(&display); draw_screen(); pthread_mutex_unlock(&display); sleep(1); } } int main(int argv, char **argc) { pthread_t thr[3 * N], thr_draw; int h = 0, o = 0; int i = 0; int input; if (argv > 1) { input = strtol(argc[1], 0, 10); } srandom(time(0)); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&display, 0); sem_init(&oxyQueue, 0, 0); sem_init(&hydroQueue, 0, 0); pthread_barrier_init(&barrier, 0, 3); presentation(); screen_init(); N = (get_screen_column() / 6) * 3; if ((argv > 1) && (input < N)) N = input; pthread_create(&thr_draw, 0, draw_anim, 0); for (i = 0; i < N; i++) { if (random() % 3 < 2) { pthread_create(&thr[i], 0, hydrogen_thread, 0); h++; } else { pthread_create(&thr[i], 0, oxygen_thread, 0); o++; } } t_hydrogen = h; t_oxygen = o; getchar(); show_cursor(); return 0; }
0
#include <pthread.h> int count; int pending_posts; } sem_t; pthread_mutex_t mut = {0,0}; pthread_mutex_t mutp = {0,0}; void sem_init(sem_t *sem, int pshared, unsigned int value) { sem->count = value; sem->pending_posts = 0; } void sem_post(sem_t *sem) { pthread_mutex_lock(&mut); sem->count++; if (sem->count <= 0) sem->pending_posts++; pthread_mutex_unlock(&mut); } void sem_wait(sem_t *sem) { pthread_mutex_lock(&mut); int done; sem->count--; if (sem->count < 0) { pthread_mutex_unlock(&mut); sleep: while (sem->pending_posts <= 0) { usleep(1); } pthread_mutex_lock(&mutp); if (sem->pending_posts > 0) { done = 1; sem->pending_posts--; } else { done = 0; } pthread_mutex_unlock(&mutp); if (!done) { goto sleep; } pthread_mutex_lock(&mut); } pthread_mutex_unlock(&mut); } int buf[4]; int first_occupied_slot; int first_empty_slot; sem_t sem_producer; sem_t sem_consumer; pthread_mutex_t mut_buf; } queue; queue* queues[2]; queue* make_queue() { queue* que = malloc(sizeof(queue)); que->first_occupied_slot = 0; que->first_empty_slot = 0; sem_init(&que->sem_producer, 0, 4); sem_init(&que->sem_consumer, 0, 0); return que; } void push_buf(int val, queue* que) { que->buf[que->first_empty_slot] = val; que->first_empty_slot++; if (que->first_empty_slot >= 4) que->first_empty_slot = 0; } int take_from_buf(queue* que) { int val = que->buf[que->first_occupied_slot]; que->first_occupied_slot++; if (que->first_occupied_slot >= 4) que->first_occupied_slot = 0; return val; } void *producer(void *arg) { int work_item = 1; while (1) { int queue_num = rand() % 2; queue* que = queues[queue_num]; usleep( rand() % 5 ); sem_wait(&que->sem_producer); pthread_mutex_lock(&que->mut_buf); push_buf(work_item++, que); pthread_mutex_unlock(&que->mut_buf); sem_post(&que->sem_consumer); } } void *consumer(void *arg) { while (1) { int work_item; int queue_num = rand() % 2; queue* que = queues[queue_num]; usleep( rand() % 5 ); sem_wait(&que->sem_consumer); pthread_mutex_lock(&que->mut_buf); work_item = take_from_buf(que); pthread_mutex_unlock(&que->mut_buf); sem_post(&que->sem_producer); printf("%d ", work_item); fflush(stdout); } } void run_threads(int count) { while (count > 0) { count--; pthread_t pp; pthread_t cc; int perr = pthread_create(&pp, 0, &producer, 0); if (perr != 0) { printf("Failed to create producer thread\\n"); } int cerr = pthread_create(&cc, 0, &consumer, 0); if (cerr != 0) { printf("Failed to create consumer thread\\n"); } } while (1) usleep(1); } int main() { queues[0] = make_queue(); queues[1] = make_queue(); run_threads(3); return 0; }
1
#include <pthread.h> pthread_t *threads; pthread_mutex_t mutex_variable; pthread_cond_t cond_wakeup_writers; pthread_cond_t cond_wakeup_readers; int nb_readers; int nb_potential_writers; int current_writing; }struct_priority_writer; void init_priority_writer(struct_priority_writer *struct_reader_writer) { pthread_cond_init(&(struct_reader_writer->cond_wakeup_readers),0); pthread_cond_init(&(struct_reader_writer->cond_wakeup_writers),0); pthread_mutex_init(&(struct_reader_writer->mutex_variable),0); struct_reader_writer->nb_readers=0; struct_reader_writer->nb_potential_writers=0; struct_reader_writer->current_writing=0; } int hasard(int inf, int sup) { return inf + (int)((double)(sup - inf + 1) * rand() / ((double)32767 + 1)); } void writer_lock(struct_priority_writer *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); struct_priority->nb_potential_writers++; while(struct_priority->nb_readers>0||struct_priority->current_writing==1) pthread_cond_wait(&(struct_priority->cond_wakeup_writers),&(struct_priority->mutex_variable)); struct_priority->current_writing=1; pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void write_msg() { printf("%s\\n","Je suis l'écrivain." ); sleep(1); } void writer_unlock(struct_priority_writer *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); struct_priority->nb_potential_writers--; if(struct_priority->nb_potential_writers==0) pthread_cond_broadcast(&(struct_priority->cond_wakeup_readers)); else pthread_cond_signal(&(struct_priority->cond_wakeup_writers)); struct_priority->current_writing=0; pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void reader_lock(struct_priority_writer *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); if(struct_priority->nb_potential_writers>0) pthread_cond_wait(&(struct_priority->cond_wakeup_readers),&(struct_priority->mutex_variable)); struct_priority->nb_readers++; pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void read_msg() { printf("%s\\n","Je suis le lecteur." ); sleep(0.5); } void reader_unlock(struct_priority_writer *struct_priority) { pthread_mutex_lock(&(struct_priority->mutex_variable)); struct_priority->nb_readers--; if(struct_priority->nb_potential_writers==0) pthread_cond_signal(&(struct_priority->cond_wakeup_writers)); pthread_mutex_unlock(&(struct_priority->mutex_variable)); } void* thread_reader(void* data) { struct_priority_writer* struct_priority; struct_priority = (struct_priority_writer*) data; reader_lock(struct_priority); read_msg(struct_priority); reader_unlock(struct_priority); return 0; } void* thread_writer(void* data) { struct_priority_writer* struct_priority; struct_priority = (struct_priority_writer*) data; writer_lock(struct_priority); write_msg(struct_priority); writer_unlock(struct_priority); return 0; } int main(int argc, char **argv) { srand(time(0)) ; int nb_thread = 0; int idx_thread= 0; if(argc<1) { printf("%s","Merci d'entrer le nombre de thread" ); return 0; } struct_priority_writer *struct_reader_writer; struct_reader_writer= malloc(sizeof(struct_priority_writer)); init_priority_writer( struct_reader_writer); nb_thread=(int)strtol(argv[1], (char **)0, 10); threads= malloc(nb_thread*sizeof(pthread_t)); int nb_reader=0; int nb_writer=0; while(idx_thread!=nb_thread) { if(hasard(0,1)) { pthread_create(&threads[idx_thread],0,thread_reader,struct_reader_writer); nb_reader++; } else { pthread_create(&threads[idx_thread],0,thread_writer,struct_reader_writer); nb_writer++; } idx_thread++; } printf("%d%s\\n",nb_reader," lecteurs créés." ); printf("%d%s\\n",nb_writer," ecrivains créés." ); idx_thread = 0; while(idx_thread!=nb_thread) { pthread_join(threads[idx_thread],0); idx_thread++; } return 0; }
0
#include <pthread.h> int shared_variable=15; int count=0; int num; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t rea = PTHREAD_COND_INITIALIZER; pthread_cond_t writ = PTHREAD_COND_INITIALIZER; void *writePhase (void *writearg); void *readPhase (void *readarg); int main(int argc, char*argv[]){ time_t t; srand((unsigned) time(&t)); num=(rand()%10); pthread_t rthread[5]; pthread_t wthread[5]; int i,j; int rThreadid[5]; int wThreadid[5]; for(i=0;i<5;i++){ rThreadid[i]=i; pthread_create(&rthread[i],0,readPhase,&rThreadid[i]); } for(j=0;j<5;j++){ wThreadid[j]=j; pthread_create(&wthread[j],0,writePhase,&wThreadid[j]); } for(i=0;i<5;i++){ pthread_join(rthread[i],0); } for(i=0;i<5;i++){ pthread_join(wthread[i],0); } return 0; } void *writePhase (void *writearg) { sleep(num); while(count>0){ pthread_cond_wait(&writ,&m); } printf("came till here\\n"); if(count==5){ pthread_mutex_lock(&m); shared_variable+=1; printf("value written:%d\\n",shared_variable); printf("Remaining Reads:%d\\n",(5-count)); pthread_mutex_unlock(&m); pthread_cond_signal(&rea); } return 0; } void *readPhase (void *readarg) { sleep(num); while(count>4){ pthread_cond_wait(&rea,&m); } pthread_mutex_lock(&m); while(count>=0 && count<5){ printf("Remaining Reads:%d\\n",abs(5-(count+1))); if(count<5){ count=count+1; } } pthread_mutex_unlock(&m); if(count==5){ pthread_cond_signal(&writ); } return 0; }
1
#include <pthread.h> int num_threads = 30; int N = 100000; float result; pthread_mutex_t mutex; struct ThreadInput { float dx; int id; float result; }; float f(float x) { return sin(x); } void * thread_func1(void * arg_ptr); void * thread_func2(void * arg_ptr); main() { int i; pthread_t tids[num_threads]; int ids[num_threads]; struct ThreadInput thread_inputs[num_threads]; float f_val[2]; double t; float loc_vals[num_threads]; for(i = 0; i < num_threads; i++) ids[i] = i; printf("N: "); scanf("%d", &N); printf("Number of threads: "); scanf("%d", &num_threads); FILE *file = fopen("results_logs.txt", "a"); if(file == 0) { printf("Error opening file!\\n"); } printf("N: %d, l_watkow: %d:\\n", N, num_threads); fprintf(file, "N: %d, l_watkow: %d:\\n", N, num_threads); t = czas_zegara(); float a, b, x1, x2, dx; a = 0; b = 3.1415; dx = (b-a)/N; x1 = a; f_val[0] = f(x1); for(i = 0; i < N; i++) { x2 = x1 + dx; f_val[1] = f(x2); result += f_val[0] + f_val[1]; f_val[0] = f_val[1]; x1 = x2; } result *= 0.5 * dx; t = czas_zegara() - t; printf("\\tCzas zegara: %f\\n", t); printf("Wynik: %.6f\\t[Single-thread]\\n", result); fprintf(file, "\\tCzas zegara: %f\\n", t); fprintf(file, "Wynik: %.6f\\t[Single-thread]\\n", result); result = 0.0; if(pthread_mutex_init(&mutex, 0) != 0) { printf("Mutex init error\\n"); } t = czas_zegara(); for(i = 0; i < num_threads; i++) { pthread_create(&tids[i], 0, thread_func1, (void*)&ids[i]); } for(i = 0; i < num_threads; i++) { pthread_join(tids[i], 0); } result *= 0.5 * dx; t = czas_zegara() - t; printf("\\tCzas zegara: %f\\n", t); printf("Wynik: %.6f\\t[Multi-thread (4.)] \\n", result); fprintf(file, "\\tCzas zegara: %f\\n", t); fprintf(file, "Wynik: %.6f\\t[Multi-thread (4.)] \\n", result); result = 0.0; for(i = 0; i < num_threads; i++) { thread_inputs[i].dx = dx; thread_inputs[i].id = i; } t = czas_zegara(); for(i = 0; i < num_threads; i++) { pthread_create(&tids[i], 0, thread_func2, (void*)&thread_inputs[i]); } for(i = 0; i < num_threads; i++) { float *ret; pthread_join(tids[i], (void**)&ret); result += *ret; free(ret); } result *= 0.5 * dx; t = czas_zegara() - t; printf("\\tCzas zegara: %f\\n", t); printf("Wynik: %.6f\\t[Multi-thread (5.)] \\n", result); fprintf(file, "\\tCzas zegara: %f\\n", t); fprintf(file, "Wynik: %.6f\\t[Multi-thread (5.)] \\n", result); fprintf(file, "\\n-----------------\\n\\n"); fclose(file); exit(0); } void * thread_func1(void * arg_ptr) { float a, b, x1, x2, dx; float loc_result = 0; float f_val[2]; int myN, i; int id = *(int*)arg_ptr; a = 0; b = 3.1415; dx = (b-a)/N; myN = N/num_threads; x1 = id * dx * myN; f_val[0] = f(x1); for(i = 0; i < myN; i++) { x2 = x1 + dx; f_val[1] = f(x2); loc_result += f_val[0] + f_val[1]; f_val[0] = f_val[1]; x1 = x2; } pthread_mutex_lock(&mutex); result += loc_result; pthread_mutex_unlock(&mutex); return(0); } void * thread_func2(void * arg_ptr) { struct ThreadInput *t_in = (struct ThreadInput*)arg_ptr; float a, b, a_loc, b_loc, dx_loc, x1, x2; int N, i; float *loc_result = (float*)malloc(sizeof(float)); *loc_result = 0.0; float f_val[2]; int id = t_in->id; float dx = t_in->dx; a = 0; b = 3.1415; float thread_interval = (b-a) / num_threads; a_loc = a + id * thread_interval; b_loc = a + (id+1) * thread_interval; dx_loc = dx; int N_loc = (b_loc-a_loc)/dx_loc; x1 = a_loc; f_val[0] = f(x1); for(i = 0; i < N_loc; i++) { x2 = x1 + dx_loc; f_val[1] = f(x2); *loc_result += f_val[0] + f_val[1]; f_val[0] = f_val[1]; x1 = x2; } pthread_exit((void*)loc_result); }
0
#include <pthread.h> char *readline(FILE *rfile) { char buf[1000]; int len; char *result = 0; char *line = fgets(buf, 1000, rfile); if (line) { len = strnlen(buf, 1000); result = strncpy(malloc(len+1),buf,len+1); } return result; } FILE *rfile; pthread_mutex_t solock; int flag; int linenum; char *line; } so_t; long tid; so_t *soptr; } targ_t; int waittill(so_t *so, int val) { int flag; while (1) { int lw = pthread_mutex_lock(&so->solock); flag = so->flag; if (flag == val) return 1; pthread_mutex_unlock(&so->solock); } } int release(so_t *so) { return pthread_mutex_unlock(&so->solock); } void *producer(void *arg) { so_t *so = arg; int *ret = malloc(sizeof(int)); FILE *rfile = so->rfile; int i; int w = 0; char *line; for (i = 0; (line = readline(rfile)); i++) { waittill(so, 0); so->linenum = i; so->line = line; so->flag = 1; release(so); fprintf(stdout, "Prod: [%d] %s", i, line); } waittill(so, 0); so->line = 0; so->flag = 1; printf("Prod: %d lines\\n", i); release(so); *ret = i; pthread_exit(ret); } void *consumer(void *arg) { targ_t *targ = (targ_t *) arg; long tid = targ->tid; so_t *so = targ->soptr; int *ret = malloc(sizeof(int)); int i = 0;; int len; char *line; int w = 0; printf("Con %ld starting\\n",tid); while (waittill(so, 1) && (line = so->line)) { len = strlen(line); printf("Cons %ld: [%d:%d] %s", tid, i, so->linenum, line); so->flag = 0; release(so); i++; } printf("Cons %ld: %d lines\\n", tid, i); release(so); *ret = i; pthread_exit(ret); } int main (int argc, char *argv[]) { pthread_t prod; pthread_t cons[4]; targ_t carg[4]; int rc; long t; int *ret; FILE *rfile; int i; so_t *share = malloc(sizeof(so_t)); if (argc < 2) { fprintf(stderr,"Usage %s filename",argv[0]); exit(0); } rfile = fopen((char *) argv[1], "r"); if (!rfile) { printf("error opening %s\\n",argv[0]); exit(0); } share->rfile = rfile; share->line = 0; share->flag = 0; pthread_mutex_init(&share->solock, 0); pthread_create(&prod, 0, producer, share); for (i=0; i<4; i++) { carg[i].tid = i; carg[i].soptr = share; pthread_create(&cons[i], 0, consumer, &carg[i]); } printf("main continuing\\n"); rc = pthread_join(prod, (void **) &ret); printf("main: producer joined with %d\\n", *ret); for (i=0; i<4; i++) { rc = pthread_join(cons[i], (void **) &ret); printf("main: consumer %d joined with %d\\n", i, *ret); } share->flag = 0; pthread_mutex_destroy(&share->solock); pthread_exit(0); exit(0); }
1
#include <pthread.h> int counter = 0; pthread_mutex_t mutex; pthread_cond_t condvar; void *tf(void *param){ int i = 0; while (counter < 5000000) { pthread_mutex_lock(&mutex); if (counter == 5000000) pthread_cond_signal(&condvar); else counter++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(void) { int i; pthread_t ti_arr[5]; pthread_mutex_init(&mutex, 0); pthread_cond_init (&condvar, 0); for (i = 0 ; i < 5 ; i++) { if (pthread_create(ti_arr+i, 0, tf, 0) != 0) { printf("Error in creating a thread %d\\n", i); exit (0); } } pthread_mutex_lock(&mutex); while (counter < 5000000) { pthread_cond_wait(&condvar, &mutex); } pthread_mutex_unlock(&mutex); printf("Counter is after the while loop %d\\n", counter); for ( i = 0 ; i < 5 ; i++) { pthread_join(ti_arr[i], 0); } printf("Counter is when all sub threads have finnished %d\\n", counter); return 0; }
0
#include <pthread.h> int i = 0; pthread_mutex_t mutex; void* thread_function(void* j){ if (*((int*)j) == 0){ for (int k = 0; k < 1000000; k++){ pthread_mutex_lock(&mutex); i++; pthread_mutex_unlock(&mutex); } } else if (*((int*)j) == 1){ for (int k = 0; k < 1000000; k++){ pthread_mutex_lock(&mutex); i--; pthread_mutex_unlock(&mutex); } } return 0; } int main(){ pthread_mutex_init(&mutex, 0); int j = 0; pthread_t thread[2]; for (j = 0; j < 2; j++){ pthread_create(&thread[j], 0, thread_function, &j); } for (int l = 0; l < 2; l++){ pthread_join(thread[l], 0); } printf("%d\\n", i); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void enter_shared_track(void) { pthread_mutex_lock(&mutex); } void exit_shared_track(void) { pthread_mutex_unlock(&mutex); } void using_shared_track_section(char* name) { int trip_duration = rand() % 6 +1; enter_shared_track(); for(; trip_duration>0; trip_duration--){ printf("%c ",name[0]); fflush(stdout); usleep(1); } printf("\\n"); exit_shared_track(); } void* train(void* arg) { char *country=(char*) arg; int i=0; for(i=0; i<3; i++){ using_shared_track_section(country); } return 0; } int main(void) { pthread_t tids[2]; int i=0; struct timespec tt; clock_gettime(CLOCK_MONOTONIC, &tt); srand(tt.tv_sec); if(pthread_create (&tids[0], 0, train, (void*)"PERU") != 0){ fprintf(stderr,"Failed to create the peruvian thread\\n"); return 1; } if(pthread_create (&tids[1], 0, train, (void*)"BOLIVIA") != 0){ fprintf(stderr,"Failed to create the peruvian thread\\n"); return 1; } for (i = 0; i < 2; i++){ pthread_join (tids[i], 0) ; } return 0; }
0
#include <pthread.h> struct args { pthread_cond_t cond_var; pthread_mutex_t cond_lock; }; void * lazy_thread(void *arg ) { printf("thread!\\n"); struct args *t_args = (struct args *)arg; pthread_mutex_lock(&(t_args->cond_lock)); pthread_cond_wait(&(t_args->cond_var), &(t_args->cond_lock)); pthread_mutex_unlock(&(t_args->cond_lock)); return 0; } void * naughty_thread(void *arg ) { while(1) { printf("thread ...\\n"); } return 0; } int main(int argc, char **argv) { pthread_t thread_arr[128] = {0}; struct args t_args = {0}; pthread_mutex_init(&(t_args.cond_lock), 0); pthread_cond_init(&(t_args.cond_var), 0); pthread_create(&(thread_arr[0]), 0, naughty_thread, 0); for (size_t i = 1; i < 128; i++) { pthread_create(&(thread_arr[i]), 0, lazy_thread, &t_args); } pthread_join(thread_arr[1], 0); }
1
#include <pthread.h> int end = 0; int sockfd = 0; pthread_mutex_t lock; FILE * log_file; pthread_t threads[MAX_THREADS]; int threadStatus = 0; void *logPacket(void *arg) { int msg = 0; char buff[MAX_MSG_BUFF] = {0}; while(1) { if((msg = recvfrom(sockfd, buff, MAX_MSG_BUFF, 0, 0, 0)) != 0) { pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); pthread_mutex_lock(&lock); fwrite(buff, 1, msg, stdout); pthread_mutex_unlock(&lock); pthread_testcancel(); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); msg = 0; } } } void gracefulExit(int sig) { close(sockfd); int i = 0; for(i = 0; i < MAX_THREADS; i++) { pthread_cancel(threads[i]); } i = 0; for(i = 0; i < MAX_THREADS; i++) { pthread_join(threads[i], 0); } fflush(0); fclose(log_file); end = 1; } int main() { pid_t procid, sid; struct sockaddr_in my_addr; int ret = 0; int i = 0; struct stat st; struct sigaction usersig; sigset_t process_mask; sigset_t handler_mask; sigfillset(&handler_mask); memset(&usersig, 0, sizeof(struct sigaction)); usersig.sa_handler = gracefulExit; usersig.sa_mask = handler_mask; sigaction(SIGTERM, &usersig, 0); sigfillset(&process_mask); sigdelset(&process_mask, SIGTERM); sigprocmask(SIG_SETMASK, &process_mask, 0); memset( &my_addr, 0, sizeof(struct sockaddr_in) ); my_addr.sin_family = AF_INET; my_addr.sin_addr.s_addr = INADDR_ANY; my_addr.sin_port = htons(UDP_LOGGER_PORT); sockfd = socket(AF_INET,SOCK_DGRAM, 0); ret = bind(sockfd, (const struct sockaddr *) &my_addr, sizeof(my_addr)); if(ret != 0) { perror("Bind failed!"); exit(1); } if(stat("udplogd.pid", &st) == 0) { perror("PID File Found"); exit(1); } umask(0022); procid = fork(); if(procid < 0) { perror("Fork Failed!"); exit(1); } else if(procid > 0) { exit(0); } sid = setsid(); if(sid < 0) { perror("Setsid failed"); exit(1); } log_file = fopen("udplogd.log", "a"); freopen("udplogd.log", "a", stderr); freopen("udplogd.log", "a", stdout); procid = getpid(); FILE * file; file = fopen("udplogd.pid", "w"); fprintf(file, "%d", procid); fclose (file); pthread_mutex_init(&lock, 0); for(i = 0; i < MAX_THREADS; i++) { threadStatus = pthread_create(&threads[i], 0, logPacket, 0); if(threadStatus != 0) { perror("Failed to create threads"); exit(1); } } while(1) { if(end == 1) { break; } sleep(1); } return 0; }
0
#include <pthread.h> pthread_mutex_t* curl_locks = 0; void seafile_curl_locking_callback(int mode, int n, const char* file, int line) { if (mode & CRYPTO_LOCK) { pthread_mutex_lock (&curl_locks[n]); } else { pthread_mutex_unlock (&curl_locks[n]); } } void seafile_curl_init() { int i; curl_locks = malloc (sizeof(pthread_mutex_t) * CRYPTO_num_locks()); for (i = 0; i < CRYPTO_num_locks(); ++i) { pthread_mutex_init (&curl_locks[i], 0); } CRYPTO_set_id_callback (pthread_self); CRYPTO_set_locking_callback (seafile_curl_locking_callback); } void seafile_curl_deinit() { int i; CRYPTO_set_id_callback (0); CRYPTO_set_locking_callback (0); for (i = 0; i < CRYPTO_num_locks(); ++i) { pthread_mutex_destroy (&curl_locks[i]); } free (curl_locks); }
1
#include <pthread.h> void *customer(void *num); void *barber(void *); int UD(int, int); pthread_cond_t seats_available; pthread_cond_t barber_free; pthread_cond_t wake_up; pthread_cond_t done_cut; pthread_mutex_t barber_chair; pthread_mutex_t number_seats; pthread_mutex_t finished; pthread_mutex_t barber_state; int done_with_all_customers = 0; int num_waiting_chairs; int barber_sleeping = 1; int b_chair_taken = 0; int all_done = 0; int main(int argc, char **argv){ if(argc < 3){ printf("Usage: sleeping_barber <customers> <chairs> \\n"); exit(0); } int num_customers = atoi(argv[1]); num_waiting_chairs = atoi(argv[2]); srand((long)time(0)); if(num_customers > 50){ printf("Number of customers exceeds the maximum capacity of the barber \\n"); printf("Resetting the number of customers to %d \\n", (int)50); num_customers = 50; } pthread_cond_init( &seats_available, 0 ); pthread_cond_init( &barber_free, 0 ); pthread_cond_init( &wake_up, 0 ); pthread_cond_init( &done_cut, 0 ); pthread_mutex_init( &barber_chair, 0 ); pthread_mutex_init( &number_seats, 0 ); pthread_mutex_init( &finished, 0 ); pthread_mutex_init( &barber_state, 0 ); pthread_t btid; pthread_t tid[50]; pthread_create(&btid, 0, barber, 0); int customer_ID[50]; int i; for(i = 0; i < num_customers; i++){ customer_ID[i] = i; pthread_create(&tid[i], 0, customer, &customer_ID[i]); } for(i = 0; i < num_customers; i++) pthread_join(tid[i], 0); done_with_all_customers = 1; pthread_cond_signal( &wake_up ); pthread_join(btid, 0); } void *barber(void *arg){ while(!done_with_all_customers){ printf("Barber: Sleeping \\n"); pthread_mutex_lock( &barber_state ); pthread_cond_wait( &wake_up, &barber_state ); pthread_mutex_unlock( &barber_state ); if(!done_with_all_customers){ printf("Barber: Cutting hair \\n"); int waitTime = UD(4, 8); sleep(waitTime); printf("Barber: Done cut \\n"); pthread_cond_signal( &done_cut ); } else{ printf("Barber: Done for the day. Going home \\n"); } } } void *customer(void *customerNumber){ int number = *(int *)customerNumber; printf("Customer %d: Leaving for the barber shop \\n", number); int waitTime = UD(4, 8); sleep(waitTime); printf("Customer %d: Arrived at the barber shop \\n", number); pthread_mutex_lock( &number_seats ); if( num_waiting_chairs == 0 ) pthread_cond_wait( &seats_available, &number_seats); num_waiting_chairs--; pthread_mutex_unlock( &number_seats ); printf("Customer %d: Entering waiting room \\n", number); pthread_mutex_lock( &barber_chair ); if( b_chair_taken ) pthread_cond_wait( &barber_free, &barber_chair ); b_chair_taken = 1; pthread_mutex_unlock( &barber_chair ); pthread_mutex_lock( &number_seats ); num_waiting_chairs++; pthread_mutex_unlock( &number_seats ); pthread_cond_signal( &seats_available ); pthread_cond_signal( &wake_up ); printf("Customer %d: Getting cut \\n", number); pthread_mutex_lock( &finished ); if( !all_done ); pthread_cond_wait( &done_cut, &finished ); all_done = 0; pthread_mutex_unlock( &finished ); pthread_mutex_lock( &barber_chair ); b_chair_taken = 0; pthread_mutex_unlock( &barber_chair ); pthread_cond_signal( &barber_free ); printf("Customer %d: Going home \\n", number); } int UD(int min, int max){ return((int)floor((double)(min + (max - min + 1)*((float)rand()/(float)32767)))); }
0
#include <pthread.h> int arr[10]; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_barrier_t barrier; static int avail = 0; static void *producer(void *arg) { sleep(1); printf("\\n%s: Started producing..\\n", __func__); int cnt = *((int *)arg); int i, j, ret; for (j = 0; j < cnt; j++) { pthread_mutex_lock(&mtx); for (i = 0; i < 9; i++) arr[i] = 'A' + j; pthread_mutex_unlock(&mtx); printf("\\n%s: Data has produced\\n", __func__); printf("%s: Broadcasted the signal to consumers.\\n\\n", __func__); avail += 2; ret = pthread_cond_broadcast(&cond); if (ret != 0) perror("pthread_cond_signal"); pthread_barrier_wait(&barrier); } return 0; } static void *consumer1(void *arg) { int i, j, ret; printf("\\n%s: Trying to consume..\\n", __func__); for (j = 0; j < *(int *)arg; j++) { pthread_mutex_lock(&mtx); while (avail == 0) { ret = pthread_cond_wait(&cond, &mtx); if ((errno=ret) != 0) perror("pthread_cond_wait"); } printf("%s: Signal recieved.\\n", __func__); printf("Data read: "); for (i = 0; i < 9; i++) printf("%c ", arr[i]); printf("\\n"); avail--; pthread_mutex_unlock(&mtx); pthread_barrier_wait(&barrier); } } static void *consumer2(void *arg) { printf("\\n%s: Trying to consume..\\n", __func__); int i, j, ret; for (j = 0; j < *(int *)arg; j++) { pthread_mutex_lock(&mtx); while (avail == 0) { ret = pthread_cond_wait(&cond, &mtx); if ((errno=ret) != 0) perror("pthread_cond_wait"); } printf("%s: Signal recieved.\\n", __func__); printf("Data read: "); for (i = 0; i < 9; i++) printf("%c ", arr[i]); printf("\\n"); avail--; pthread_mutex_unlock(&mtx); pthread_barrier_wait(&barrier); } } int main() { pthread_t tid; int ret, j, totRequired = 20; pthread_barrier_init(&barrier, 0, 3); ret = pthread_create(&tid, 0, producer, &totRequired); if (ret != 0) { errno = ret; perror("pthread_create"); } ret = pthread_create(&tid, 0, consumer1, &totRequired); if (ret != 0) { errno = ret; perror("pthread_create"); } ret = pthread_create(&tid, 0, consumer2, &totRequired); if (ret != 0) { errno = ret; perror("pthread_create"); } pthread_exit(0); exit(0); }
1
#include <pthread.h> void *accessFile(void*); void handleSignalInterrupt(int); int threadsMade = 0; int threadsRunning = 0; int fileAccessTime = 0; pthread_mutex_t lock; int main() { signal(SIGINT, handleSignalInterrupt); char buffer[256]; srand(time(0)); if(pthread_mutex_init(&lock, 0) != 0) { printf("Error making mutex\\n"); return 1; } while (1) { pthread_t thread; int status; printf("Enter a filename: "); if (!fgets(buffer, sizeof(buffer), stdin)) { printf("fgets error\\n"); exit(1); } else { size_t ln = strlen(buffer) - 1; if (buffer[ln] == '\\n') { buffer[ln] = '\\0'; } if((status = pthread_create(&thread, 0, accessFile, buffer)) != 0) { fprintf(stderr, "thread create error %d: %s\\n", status, strerror(status)); exit(1); } printf("Thread created for file %s\\n", buffer); threadsMade++; threadsRunning++; } } } void *accessFile(void *arg) { char * fileName = (char *)malloc(sizeof(fileName)); strcpy(fileName, (char *)arg); int delay = rand() % 5; if (delay < 4) { sleep(delay = 1); } else{ delay = (rand() % 4) + 7; sleep(delay); } char * device = delay == 1 ? "cache" : "drive"; printf("Retrieved file: %s from %s in %d second(s)\\n", fileName, device, delay); pthread_mutex_lock(&lock); threadsRunning--; fileAccessTime += delay; pthread_mutex_unlock(&lock); free(fileName); return 0; } void handleSignalInterrupt(int sigNum) { signal(SIGINT, exit); if(threadsRunning > 0) { printf("\\nSHUTDOWN AFTER ALL THREADS COMPLETED\\n"); printf("\\nPRESS ^C AGAIN TO COMPLETELY TERMINATE EXECUTION\\n"); while(threadsRunning > 0); printf("Threads finished running\\n"); } printf("Threads Made: %d: \\n", threadsMade); double avgTime = fileAccessTime / (double) threadsMade; printf("Average Thread Time: %f seconds\\n", avgTime); exit(1); }
0
#include <pthread.h> static int dumperi_readq_check(struct CacheBase *cache) { pthread_mutex_lock(&cache->readq_lock); int res = (cache->readq != 0); pthread_mutex_unlock(&cache->readq_lock); return res; } int dumper_readq_enqueue(struct CacheBase *cache, struct CacheElem *elem) { pthread_mutex_lock(&cache->readq_lock); if (cache->readq == 0) { cache->readq = cache->readq_tail = elem; } else { cache->readq_tail->rq_next = elem; cache->readq_tail = elem; } pthread_mutex_unlock(&cache->readq_lock); return 0; } static int dumperi_readq_dequeue(struct CacheBase *cache) { pthread_mutex_lock(&cache->readq_lock); struct CacheElem *elem = cache->readq; if (cache->readq == 0) { } else if (cache->readq->rq_next == 0) { cache->readq = cache->readq_tail = 0; } else { cache->readq = cache->readq->next; elem->rq_next = 0; } pthread_mutex_unlock(&cache->readq_lock); return 0; } static int dumper_page_dump(struct CacheBase *cache, struct CacheElem *elem) { int retval = pool_write(cache->pool, elem->cache, cache->pool->page_size, elem->id, 0); log_info("Page %zd has been dumped", elem->id); return retval; } static int dumper_page_load(struct CacheBase *cache, struct CacheElem *elem) { int retval = pool_read(cache->pool, elem->id, elem->cache); memcpy(elem->prev, elem->cache, cache->pool->page_size); pthread_cond_signal(&elem->rw_signal); log_info("Page %zd has been loaded", elem->id); return retval; } int pthread_mutex_timedlock (pthread_mutex_t *mutex, struct timespec *timeout) { struct timeval timenow; struct timespec sleepytime; int retcode; sleepytime.tv_sec = 0; sleepytime.tv_nsec = 100000; while ((retcode = pthread_mutex_trylock (mutex)) == EBUSY) { gettimeofday (&timenow, 0); if (timenow.tv_sec >= timeout->tv_sec && (timenow.tv_usec * 1000) >= timeout->tv_nsec) { return ETIMEDOUT; } nanosleep (&sleepytime, 0); } return retcode; } void *dumper_loop(void *arg) { int *procret = calloc(1, sizeof(int)); struct timespec ts = {.tv_sec = 0, .tv_nsec = 200000}; log_info("Creating RW Thread"); struct PagePool *pp = (struct PagePool *)arg; struct CacheElem *elem_w = pp->cache->list_tail; while (pp->dumper_enable) { elem_w = elem_w->next; if (elem_w == 0) elem_w = pp->cache->list_tail; if (elem_w->flag & CACHE_DIRTY) { int retval = pthread_mutex_timedlock(&elem_w->lock, &ts); if (retval == ETIMEDOUT) continue; check(retval == 0, "Failed to lock mutex"); dumper_page_dump(pp->cache, elem_w); elem_w->flag &= (-1 - CACHE_DIRTY); pthread_mutex_unlock(&elem_w->lock); } while (dumperi_readq_check(pp->cache)) { struct CacheElem *elem_r = pp->cache->readq; pthread_mutex_lock(&elem_r->lock); dumper_page_load(pp->cache, elem_r); dumperi_readq_dequeue(pp->cache); pthread_cond_signal(&elem_r->rw_signal); pthread_mutex_unlock(&elem_r->lock); } } elem_w = pp->cache->list_tail; while (elem_w) { if (elem_w->flag & CACHE_DIRTY) { pthread_mutex_lock(&elem_w->lock); dumper_page_dump(pp->cache, elem_w); elem_w->flag &= (-1 - CACHE_DIRTY); pthread_mutex_unlock(&elem_w->lock); } elem_w = elem_w->next; } return procret; error: *procret = 1; return procret; } int dumper_init (struct DB *db, struct PagePool *pp) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pp->dumper_enable = 1; pthread_create(&pp->dumper, &attr, dumper_loop, (void *)pp); pthread_attr_destroy(&attr); return 0; } int dumper_free (struct PagePool *pp) { void *status; pthread_mutex_lock(&pp->cache->readq_lock); pp->dumper_enable = 0; pthread_mutex_unlock(&pp->cache->readq_lock); pthread_join(pp->dumper, &status); log_err("dumper_loop exited with status %d", (int )(*(int *)status)); free(status); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; extern int __VERIFIER_nondet_int(); int idx=0; int ctr1=1, ctr2=0; int readerprogress1=0; int readerprogress2=0; pthread_mutex_t mutex; void __VERIFIER_atomic_use1(int myidx) { __VERIFIER_assume(myidx <= 0 && ctr1>0); ctr1++; } void __VERIFIER_atomic_use2(int myidx) { __VERIFIER_assume(myidx >= 1 && ctr2>0); ctr2++; } void __VERIFIER_atomic_use_done(int myidx) { if (myidx <= 0) { ctr1--; } else { ctr2--; } } void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) { *readerstart1 = readerprogress1; *readerstart2 = readerprogress2; } void __VERIFIER_atomic_check_progress1(int readerstart1) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1); if (!(!(readerstart1 == 1 && readerprogress1 == 1))) ERROR: __VERIFIER_error();; } return; } void __VERIFIER_atomic_check_progress2(int readerstart2) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1); if (!(!(readerstart2 == 1 && readerprogress2 == 1))) ERROR: __VERIFIER_error();; } return; } void *qrcu_reader1() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else { } } } readerprogress1 = 1; readerprogress1 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void *qrcu_reader2() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else { } } } readerprogress2 = 1; readerprogress2 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void* qrcu_updater() { int i; int readerstart1, readerstart2; int sum; __VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2); if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; } if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; } } else { } if (sum > 1) { pthread_mutex_lock(&mutex); if (idx <= 0) { ctr2++; idx = 1; ctr1--; } else { ctr1++; idx = 0; ctr2--; } if (idx <= 0) { while (ctr1 > 0){ } } else { while (ctr2 > 0){ } } pthread_mutex_unlock(&mutex); } else { } __VERIFIER_atomic_check_progress1(readerstart1); __VERIFIER_atomic_check_progress2(readerstart2); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mutex, 0); pthread_create(&t1, 0, qrcu_reader1, 0); pthread_create(&t2, 0, qrcu_reader2, 0); pthread_create(&t3, 0, qrcu_updater, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> void* register_write(void* data) { int clock_start = 0; int new_instruction = 1; CLOCK_ZERO_READ[3] = 1; while (1) { if (STOP_THREAD == 1) { pipeline[3].instr.Itype = NO_OP; pipeline[3].instr.Ctype = NO_OP; temp_pipeline[3].instr.Itype = NO_OP; temp_pipeline[3].instr.Ctype = NO_OPERATION; CURR_INSTR[4] = pipeline[3].instr; ACTIVE_STAGE[4] = 0; regdump(); break; } pthread_mutex_lock(&CLOCK_LOCK); if (CLOCK == 1) { clock_start = 1; CLOCK_ZERO_READ[3] = 0; } if (CLOCK == 0) { clock_start = 0; new_instruction = 1; CLOCK_ZERO_READ[3] = 1; } pthread_mutex_unlock(&CLOCK_LOCK); if (clock_start && new_instruction) { temp_pipeline[3] = pipeline[3]; CURR_INSTR[4] = pipeline[3].instr; ACTIVE_STAGE[4] = 1; if (pipeline[3].instr.Itype != NO_OP) { INSTRUCTION_COUNT++; if (pipeline[3].instr.Itype == LDR_BYTE || pipeline[3].instr.Itype == LDR_WORD || pipeline[3].instr.Itype == LDR_UPPER_IMMEDIATE) { register_file[pipeline[3].instr.rt] = pipeline[3].rt_val; CONTROL_SIGN.RegW = 1; } else if (pipeline[3].instr.Itype == MULTIPLY || pipeline[3].instr.Itype == MULTIPLY_ADD) { register_file[32] = pipeline[3].LO; register_file[33] = pipeline[3].HI; CONTROL_SIGN.RegW = 1; } else if (pipeline[3].instr.Ctype == DP) { register_file[pipeline[3].instr.rd] = pipeline[3].alu_result; CONTROL_SIGN.RegW = 1; } else if (pipeline[3].instr.Itype == JUMP_LINK || pipeline[3].instr.Itype == JUMP_LINK_REGISTER) { register_file[pipeline[3].instr.rd] = pipeline[3].alu_result; CONTROL_SIGN.RegW = 1; } } else { ACTIVE_STAGE[4] = 0; } pthread_mutex_lock(&READ_LOCK); NUM_THREADS_READ++; pthread_mutex_unlock(&READ_LOCK); pthread_mutex_lock(&WRITE_LOCK); NUM_THREADS_WRITE++; pthread_mutex_unlock(&WRITE_LOCK); new_instruction = 0; } usleep(DELAY); } pthread_exit(0); }
1
#include <pthread.h> static char* output_string = 0; static pthread_mutex_t output_lock; static int initialized = 0; static pthread_t thread; static void* query_time_thread() { time_t raw; struct tm* info; if(output_string == 0) { output_string = calloc( 64, sizeof(char) ); } while( initialized ) { pthread_mutex_lock( &output_lock ); time(&raw); info = localtime(&raw); sprintf( output_string, "%s, %s %d, %d %02d:%02d:%02d", weekday( info->tm_wday ), month( info->tm_mon ), info->tm_mday, info->tm_year+1900, info->tm_hour, info->tm_min, info->tm_sec ); pthread_mutex_unlock( &output_lock ); sleep( 1 ); } free(output_string); output_string = 0; return 0; } int datetime_init() { if( initialized ) return 0; pthread_mutex_init( &output_lock, 0 ); pthread_create( &thread, 0, &query_time_thread, 0 ); initialized = 1; return 1; } int datetime_destroy() { if( !initialized ) return 0; initialized = 0; pthread_join( thread, 0 ); pthread_mutex_destroy( &output_lock ); return 1; } char* get_datetime_information() { if( !initialized ) return 0; char* datetime_string = calloc( 64, sizeof(char) ); pthread_mutex_lock( &output_lock ); if( output_string ) { strncpy( datetime_string, output_string, 64 -1 ); } pthread_mutex_unlock( &output_lock ); return datetime_string; }
0
#include <pthread.h> pthread_mutex_t tunnel; void *train(void* arg) { sleep(rand()%10); pthread_mutex_lock(&tunnel); printf("Moi, %s, j'entre dans le tunnel\\n", (char*)arg); sleep(2); pthread_mutex_unlock(&tunnel); printf("Moi, %s, je sors du tunnel\\n", (char*)arg); pthread_exit(0); } int main(int argc, char** argv) { pthread_t threads[15]; time_t t; srand((unsigned)time(&t)); pthread_mutex_init(&tunnel, 0); int i; char name[20][20]; for(i = 0; i<15; i++){ int random = rand()%4; switch(random){ case(0): sprintf(name[i], "RER B %d", i); break; case(1): sprintf(name[i], "RER D %d", i); break; case(2): sprintf(name[i], "RER E %d", i); break; case(3): sprintf(name[i], "Transilien SD %d", i); break; } pthread_create(&threads[i], 0, train, (void*)name[i]); } for(i = 0; i<15; i++){ pthread_join(threads[i], 0); } pthread_mutex_destroy(&tunnel); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int final_result = 0; struct thread_data{ int startidx; int maxidx; }; ub4 phash(ub4 val, ub2 * scramble, ub1 * tab) { ub4 a, b, rsl; b = (val >> 5) & 0x1fff; a = ((val << 22) >> 19); rsl = (a^scramble[tab[b]]); return rsl; } void *perfect_hash (void *threadarg) { int i, hash; int result=0; struct thread_data* arg = (struct thread_data*) threadarg; int startidx = arg->startidx; int maxidx = arg->maxidx; for (i=startidx; i<maxidx; i++) { hash=phash(key[i], scramble, tab); result +=(hash_table[hash] == key[i]); } pthread_mutex_lock (&mutex); final_result += result; pthread_mutex_unlock (&mutex); pthread_exit(0); } int main() { int i; pthread_t threads[6]; struct thread_data data[6]; for (i=0; i<6; i++) { data[i].startidx = i*24000/6; data[i].maxidx = (i+1)*24000/6; } for (i=0; i<6; i++) { pthread_create(&threads[i], 0, perfect_hash, (void *)&data[i]); } for (i=0; i<6; i++) { pthread_join(threads[i], 0); } printf ("Result: %d\\n", final_result); if (final_result == 24000) { printf("RESULT: PASS\\n"); } else { printf("RESULT: FAIL\\n"); } }
0
#include <pthread.h> struct node { int servico; struct node *next; }; struct node *front = 0; struct node *rear = 0; void enqueue(int idServico){ struct node *nptr = malloc(sizeof(struct node)); nptr->servico = idServico; nptr->next = 0; if (rear == 0) { front = nptr; rear = nptr; } else { rear->next = nptr; rear = rear->next; } } int dequeue(){ int serv; if(front == 0){ return -1; }else{ struct node *temp; temp = front; front = front->next; serv = temp->servico; free(temp); return serv; } } int tamanhoMatriz = 32, numThreads = 10; pthread_mutex_t lock; void mm(){ srand(time(0)); int **A, **B, **C; A = (int**) malloc(sizeof(int*) * tamanhoMatriz); B = (int**) malloc(sizeof(int*) * tamanhoMatriz); C = (int**) malloc(sizeof(int*) * tamanhoMatriz); for (int i = 0; i < tamanhoMatriz; i++) { A[i] = (int*) malloc(sizeof(int) * tamanhoMatriz); B[i] = (int*) malloc(sizeof(int) * tamanhoMatriz); C[i] = (int*) malloc(sizeof(int) * tamanhoMatriz); for (int j = 0; j < tamanhoMatriz; j++) { A[i][j] = rand() % 2; B[i][j] = rand() % 2; C[i][j] = 0; } } for (int i = 0; i < tamanhoMatriz; i++){ for (int j = 0; j < tamanhoMatriz; j++){ C[i][j] = 0; for (int k = 0; k < tamanhoMatriz; ++k){ C[i][j] += A[i][k] * B[k][j]; } } } printf("\\nAcabou multiplicação!"); } void vectorSearch(){ srand(time(0)); int *V; int buscado = rand() % 10; V = (int*) malloc(sizeof(int) *tamanhoMatriz); for(int i = 0; i < tamanhoMatriz; i++){ V[i] = rand() % 10; } for(int i = 0; i < tamanhoMatriz; i++){ if(V[i] == buscado){ printf("\\nO elemento %d existe no vetor!", buscado); break; } } } void *executaServicos(){ pthread_mutex_lock(&lock); int idService = dequeue(); pthread_mutex_unlock(&lock); if(dequeue != -1){ (*func[idService])(); } } void *atribuiServicos(){ srand(time(0)); int idServico, count = 10; pthread_t threads[numThreads]; for(int i = 0; i < numThreads; i++){ pthread_create(&threads[i], 0, executaServicos, 0); } while(count > 0){ enqueue(rand() % 2); count--; } for(int j = 0; j < numThreads; j++){ pthread_join(threads[j], 0); } } void (*func[])() = {mm, vectorSearch}; int main(){ pthread_t mainThread; pthread_create(&mainThread, 0, atribuiServicos, 0); pthread_join(mainThread, 0); return 0; }
1
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return ENOSPC; } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return ENOENT; }
0
#include <pthread.h> FILE*file; int num; }ph; ph one, two, three, four, five; pthread_mutex_t mutex; FILE*results; int process=0; void *read_thread(void *ptr); void printresults(void); int main(void) { pthread_mutex_init(&mutex, 0); FILE*file1, *file2, *file3, *file4, *file5; int end=0; file1=fopen("drive1.data", "r"); file2=fopen("drive2.data", "r"); file3=fopen("drive3.data", "r"); file4=fopen("drive4.data", "r"); file5=fopen("drive5.data", "r"); one.file=file1; two.file=file2; three.file=file3; four.file=file4; five.file=file5; one.num=0; two.num=1; three.num=2; four.num=3; five.num=4; pthread_t thread1, thread2, thread3, thread4, thread5; pthread_create(&thread1, 0, (void*)&read_thread, (void*)&one); pthread_detach(thread1); pthread_create(&thread2, 0, (void*)&read_thread, (void*)&two); pthread_detach(thread2); pthread_create(&thread3, 0, (void*)&read_thread, (void*)&three); pthread_detach(thread3); pthread_create(&thread4, 0, (void*)&read_thread, (void*)&four); pthread_detach(thread4); pthread_create(&thread5, 0, (void*)&read_thread, (void*)&five); pthread_detach(thread5); printresults(); pthread_exit(&end); fclose(file1); fclose(file2); fclose(file3); fclose(file4); fclose(file5); return 0; } void *read_thread(void *arg) { ph *point; point=((ph*)(arg)); int c; while(!feof(point->file)) { pthread_mutex_lock(&mutex); if(process%5!=point->num) { } else { pthread_mutex_unlock(&mutex); c=fgetc(point->file); results=fopen("results.txt", "a"); fputc(c, results); fclose(results); process++; } pthread_mutex_unlock(&mutex); } } void printresults(void) { FILE *fp; int c; int n = 0; fp = fopen("results.txt", "r"); do { c=fgetc(fp); if(feof(fp)) { break; } if(c>47&&c<58||c>65&&c<91||c>96&&c<123) { printf("%c", c); } }while(1); fclose(fp); fp=fopen("results.txt", "w"); fclose(fp); }
1
#include <pthread.h> extern pthread_mutex_t mutexA; extern pthread_mutex_t mutexB; pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexB = PTHREAD_MUTEX_INITIALIZER; extern int mBalance; int mBalance=0; static int modbal_armed (); static void modbal_one(); static void modbal_neg(); static void modbal_zero(); static int modbal_get(); void tpad_modbal_set_zero(){ modbal_zero();} void tpad_modbal_set_one(){ modbal_one();} void tpad_modbal_set_neg(){ modbal_neg();} int tpad_modbal_check_armed(){ return(modbal_armed());} int tpad_modbal_get(){ return(modbal_get());} static int modbal_armed () { int iRes=0; pthread_mutex_lock( &mutexA ); while ( pthread_mutex_trylock(&mutexB) ){ pthread_mutex_unlock(&mutexA); sleep(WATCH_STALL_TIME); pthread_mutex_lock(&mutexA); } if(mBalance > 0) iRes = 1; else iRes=0; pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); return(iRes); } static void modbal_zero() { pthread_mutex_lock( &mutexA ); while ( pthread_mutex_trylock(&mutexB) ){ pthread_mutex_unlock(&mutexA); sleep(WATCH_STALL_TIME); pthread_mutex_lock(&mutexA); } mBalance=0; pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); } static void modbal_one() { pthread_mutex_lock( &mutexA ); while ( pthread_mutex_trylock(&mutexB) ){ pthread_mutex_unlock(&mutexA); sleep(WATCH_STALL_TIME); pthread_mutex_lock(&mutexA); } mBalance++; pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); } static void modbal_neg() { pthread_mutex_lock( &mutexA ); while ( pthread_mutex_trylock(&mutexB) ){ pthread_mutex_unlock(&mutexA); sleep(WATCH_STALL_TIME); pthread_mutex_lock(&mutexA); } mBalance--; pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); } static int modbal_get() { int iRets=0; pthread_mutex_lock( &mutexA ); while ( pthread_mutex_trylock(&mutexB) ){ pthread_mutex_unlock(&mutexA); sleep(WATCH_STALL_TIME); pthread_mutex_lock(&mutexA); } iRets=mBalance; pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); return(iRets); }
0
#include <pthread.h> char *message = "HELLO B78! WELCOME TO THE CHAT EDGE. START CHATTING WITH YOUR FRIENDS. YOUR IP IS :"; pthread_mutex_t mutex; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct sockaddr_in sock_addr, sock_addr2; int len; int sd, fd[500], count = 0, file_d; pthread_t tid[100], tids; int shm_d; char *str, *buff, *identity; void *serve (void *fdp) { FILE *fp = 0; printf("inside serve\\n"); int i = 16; char *tmp = malloc (2024); char *str_tmp = malloc (2024); bzero(tmp, 2024); bzero(str_tmp, 2024); strcpy(tmp, identity + (16 * (count-1))); while (i--) { if (tmp[i] == 0) tmp[i] = ' '; } write (*(int *)fdp, message, strlen(message)); write (*(int *)fdp, tmp, strlen(tmp)); write (*(int *)fdp, "\\n\\n", 2); strcat(tmp, ": "); printf("connected %s\\n", tmp); while (1) { read (*(int *)fdp, tmp + 16 + 2, 2024); if (*(tmp + 16 + 2) == 0) break; pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); strcpy(buff, tmp); pthread_mutex_unlock(&mutex); *(tmp + 16 + 2) = 0; } close (*(int *)fdp); } void *sendall(void *p) { int i; while (1) { pthread_cond_wait(&cond, &mutex); if (write(file_d, buff, strlen(buff)) == -1) { perror("write"); } for (i = 0; i < count; i++) { write (fd[i], buff, strlen(buff) + 1); } pthread_mutex_unlock(&mutex); } } main () { str = malloc(1024); buff = malloc(1024); identity = malloc(2024); file_d = open("/home/sandeep/chat.log", O_APPEND | O_CREAT | O_RDWR, 0666); perror("open"); bzero(identity, 2024); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); sd = socket (AF_INET, SOCK_STREAM, 0); if (sd < 0) { perror ("socket"); exit (1); } sock_addr.sin_family = AF_INET; sock_addr.sin_port = htons(2000); sock_addr.sin_addr.s_addr = inet_addr("0.0.0.0"); if (bind(sd, (struct sockaddr *)&sock_addr, sizeof(sock_addr)) == -1) { perror ("bind"); exit (1); } if (listen(sd, 500) == -1) { perror ("listen"); exit (1); } len = sizeof (sock_addr2); if (pthread_create (&tids, 0, sendall, 0)) { printf("pthread_create fails\\n"); } while (1) { fd[count] = accept (sd, (struct sockaddr *)&sock_addr2, &len); strcpy(identity + (16 * count), (char *)inet_ntoa(sock_addr2.sin_addr)); perror ("accept"); if (pthread_create (&tid[count], 0, serve, (void *)&fd[count])) { printf("pthread_create fails\\n"); } count++; } }
1
#include <pthread.h> int i = 0; int j = 0; pthread_mutex_t m; void handle(void *d) { printf("退出后的调用!\\n"); pthread_mutex_unlock(&m); } void* pthread_add1(void *num) { while(1){ pthread_cleanup_push(handle,0 ); pthread_mutex_lock(&m); i++; j++; printf("线程one:i:%dj:%d\\n",i,j); pthread_cleanup_pop(0); pthread_mutex_unlock(&m); sleep(1); } } void* pthread_add2(void *num) { while(1){ pthread_cleanup_push(handle,0); pthread_mutex_lock(&m); i++; j++; printf("线程two:i:%dj:%d\\n",i,j); pthread_exit((void*)0); pthread_cleanup_pop(0); pthread_mutex_unlock(&m); sleep(1); } } int main() { pthread_t pfd1,pfd2; pthread_mutex_init(&m,0); pthread_create(&pfd1,0,pthread_add1,"I am one!"); pthread_create(&pfd2,0,pthread_add2,"I am two!"); pthread_join(pfd1,(void**)0); pthread_join(pfd2,(void**)0); }
0