text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> pthread_cond_t time_to_ring = PTHREAD_COND_INITIALIZER; pthread_mutex_t time_to_ring_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t time_to_eat = PTHREAD_COND_INITIALIZER; pthread_mutex_t time_to_eat_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_master(void *args) { pthread_detach(pthread_self()); while(1) { sleep(8); printf("\\nMaster: press the ring button.\\n"); pthread_cond_signal(&time_to_ring); } pthread_exit(0); } void *thread_ring(void *args) { pthread_detach(pthread_self()); while(1) { pthread_mutex_lock(&time_to_ring_mutex); pthread_cond_wait(&time_to_ring, &time_to_ring_mutex); pthread_mutex_unlock(&time_to_ring_mutex); printf("Ring: begin ringing...\\n"); pthread_cond_broadcast(&time_to_eat); } pthread_exit(0); } void *thread_dog(void *args) { pthread_detach(pthread_self()); int i = (int)args; while(1) { printf("dog %d is hungry, wait to eat...\\n", i); pthread_mutex_lock(&time_to_eat_mutex); pthread_cond_wait(&time_to_eat, &time_to_eat_mutex); pthread_mutex_unlock(&time_to_eat_mutex); int num = random()%6 + 5; printf("dog %d hear the ring, eat %d food.\\n", i, num); sleep(num); } pthread_exit(0); } int main() { pthread_t tid_master; pthread_t tid_ring; pthread_t tid_dog[5]; if (0 != pthread_create(&tid_master, 0, thread_master, 0)) { printf("create thread master failed...\\n"); return -1; } if (0 != pthread_create(&tid_ring, 0, thread_ring, 0)) { printf("create thread ring failed...\\n"); return -1; } int i = 0; for (i = 0; i < 5; i++) { if (0 != pthread_create(&tid_dog[i], 0, thread_dog, (void *)i)) { printf("create thread dog %d failed...\\n", i); return -1; } } sleep(1000); return 0; }
1
#include <pthread.h> int rank; char finished1; pthread_mutex_t mutex1; pthread_cond_t cond1; char finished2; pthread_mutex_t mutex2; pthread_cond_t cond2; } thread_data; thread_data td[20]; void* hello_thread(void *rank) { int thread_rank = *(int *)rank; if (thread_rank > 0) { thread_data *prev = &td[thread_rank - 1]; pthread_mutex_lock(&prev->mutex1); if (!prev->finished1) pthread_cond_wait(&prev->cond1, &prev->mutex1); pthread_mutex_unlock(&prev->mutex1); } printf("Hello from thread %d\\n", thread_rank); if (thread_rank < 20 -1) { thread_data *curr = &td[thread_rank]; pthread_mutex_lock(&curr->mutex1); curr->finished1 = 1; pthread_cond_signal(&curr->cond1); pthread_mutex_unlock(&curr->mutex1); } if (thread_rank > 0) { thread_data *next = &td[20 - thread_rank]; pthread_mutex_lock(&next->mutex2); if (!next->finished2) pthread_cond_wait(&next->cond2, &next->mutex2); pthread_mutex_unlock(&next->mutex2); } printf("Sayonara from thread %d\\n", thread_rank); if (thread_rank > 0) { thread_data *curr = &td[thread_rank]; pthread_mutex_lock(&curr->mutex2); curr->finished2 = 1; pthread_cond_signal(&curr->cond2); pthread_mutex_unlock(&curr->mutex2); } return 0; } int main(void) { int rank = 0; int err; pthread_t thread_ids[20]; while(rank < 20) { td[rank].finished1 = 0; pthread_mutex_init(&td[rank].mutex2, 0); pthread_cond_init(&td[rank].cond2, 0); td[rank].finished2 = 0; pthread_mutex_init(&td[rank].mutex2, 0); pthread_cond_init(&td[rank].cond2, 0); rank++; } rank = 0; while(rank < 20) { td[rank].rank = rank; err = pthread_create(&(thread_ids[rank]), 0, hello_thread, (void*)&td[rank].rank); if (err != 0) { printf("Can't create thread error =%d\\n", err); return 1; } rank++; } rank = 0; while(rank < 20) { pthread_join(thread_ids[rank], 0); rank++; } rank = 0; while(rank < 20) { pthread_mutex_destroy(&td[rank].mutex1); pthread_cond_destroy(&td[rank].cond1); pthread_mutex_destroy(&td[rank].mutex2); pthread_cond_destroy(&td[rank].cond2); rank++; } return 0; }
0
#include <pthread.h> int available_resources = 5; int times = 100000; pthread_mutex_t mutex; sem_t semaphore; int decrease_count(int count) { pthread_mutex_lock(&mutex); if (available_resources < count) { pthread_mutex_unlock(&mutex); return -1; } else { available_resources -= count; printf("Locked %i resources, now available: %i\\n" , count , available_resources); pthread_mutex_unlock(&mutex); return 0; } } int increase_count(int count) { pthread_mutex_lock(&mutex); if (count + available_resources > 5) { pthread_mutex_unlock(&mutex); return -1; } else { available_resources += count; printf("Freed %i resources, now available: %i\\n" , count , available_resources); pthread_mutex_unlock(&mutex); return 0; } } void *runTimes(void *null) { int i = 0 , result; while (i < times) { result = -1; while (result < 0) {result = decrease_count(1);} result = -1; while (result < 0) {result = increase_count(1);} i += 1; } return 0; } int main(int argc, char *argv[]) { pthread_t thread1 , thread0; pthread_mutex_init(&mutex, 0); decrease_count(2); pthread_create(&thread0, 0, runTimes, 0); pthread_create(&thread1, 0, runTimes, 0); pthread_join(thread0, 0); pthread_join(thread1, 0); printf("Currently available resources (should be 3): %i\\n" , available_resources); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> pthread_t phil[3]; pthread_mutex_t baguette[3]; void mange(int id) { printf("Philosophe [%d] mange\\n",id); for(int i=0;i< rand(); i++) { } } void* philosophe ( void* arg ) { int *id=(int *) arg; int left = *id; int right = (left + 1) % 3; while(1) { printf("Philosophe [%d] pense\\n",*id); pthread_mutex_lock(&baguette[left]); printf("Philosophe [%d] possède baguette gauche [%d]\\n",*id,left); pthread_mutex_lock(&baguette[right]); printf("Philosophe [%d] possède baguette droite [%d]\\n",*id,right); mange(*id); pthread_mutex_unlock(&baguette[left]); printf("Philosophe [%d] a libéré baguette gauche [%d]\\n",*id,left); pthread_mutex_unlock(&baguette[right]); printf("Philosophe [%d] a libéré baguette droite [%d]\\n",*id,right); } return (0); } int main ( int argc, char *argv[]) { long i; int id[3]; srand(getpid()); for (i = 0; i < 3; i++) id[i]=i; for (i = 0; i < 3; i++) pthread_mutex_init( &baguette[i], 0); for (i = 0; i < 3; i++) pthread_create(&phil[i], 0, philosophe, (void*)&(id[i]) ); for (i = 0; i < 3; i++) pthread_join(phil[i], 0); return (0); }
0
#include <pthread.h> int s=0; sem_t full,empty; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int q[5],front=0,rear=5 -1; void *prod(void *count) { int* c = (int*)count; long int i; int j; for(i=0;i<10;i++) { sem_wait(&full); pthread_mutex_lock(&mutex); rear=(rear+1)%5; q[rear]=1; (*c)++; for(j=0;j<5;j++) { printf("%d ", q[j]); } sem_post(&empty); pthread_mutex_unlock(&mutex); } return 0; } void *cons(void *count) { int* c = (int*)count; long int i; int j; int k; for(i=0;i<10;i++) { sem_wait(&empty); pthread_mutex_lock(&mutex); (*c)--; q[front]=0; front=(front+1)%5; for(j=0;j<5;j++) { printf("%d ", q[j]); } sem_post(&full); pthread_mutex_unlock(&mutex); } return 0; } int main() { int count = 0; pthread_t producer; pthread_t consumer; sem_init(&full,0,5); sem_init(&empty,0,0); pthread_create(&producer, 0, prod, &count); pthread_create(&consumer, 0, cons, &count); pthread_join(producer, 0); pthread_join(consumer, 0); printf("Value of count is = %d\\n", count); for(int j=0;j<5;j++) { printf("%d ", q[j]); } exit(0); }
1
#include <pthread.h> double a[100000000]; int count ,num_threads,iterations; double search_no ; pthread_mutex_t count_mutex; void *find_entries(void *tid) { int i, start, *mytid, end; int local_count =0; mytid = (int *) tid; start = (*mytid * iterations); end = start + iterations; printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1); for (i=start; i < end ; i++) { if ( a[i] == search_no ) { local_count ++; } } pthread_mutex_lock (&count_mutex); count = count + local_count; pthread_mutex_unlock (&count_mutex); } int main(int argc, char *argv[]) { int i,start,ret_count; int *tids; pthread_t * threads; pthread_attr_t attr; double time_start, time_end; struct timeval tv; struct timezone tz; printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC): February-2008"); printf("\\n\\t\\t Email : RarchK"); printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Objective : Finding k matches in the given Array"); printf("\\n\\t\\t..........................................................................\\n"); for (i=0;i<100000000;i++){ a[i] = (i %10)+1.0; } if (argc != 3) { printf ("Syntax : exec <Number to be search> <Number of thread>\\n"); return ; } search_no = atoi(argv[1]); num_threads = atoi(argv[2]); if (num_threads > 8) { printf ("Number of thread should be less than or equal to 8\\n"); return ; } iterations = 100000000/num_threads; threads = (pthread_t *) malloc(sizeof(pthread_t) * num_threads); tids = (int *) malloc(sizeof(int) * num_threads); gettimeofday(&tv, &tz); time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; ret_count = pthread_mutex_init(&count_mutex, 0); if(ret_count) { printf("\\n ERROR : Return code from pthread_mutex_init() is %d ",ret_count); exit(-1); } ret_count=pthread_attr_init(&attr); if(ret_count) { printf("\\n ERROR : Return code from pthread_attr_init() is %d ",ret_count); exit(-1); } ret_count = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); if(ret_count) { printf("\\n ERROR : Return code from pthread_attr_setdetachstate() is %d ",ret_count); exit(-1); } for (i=0; i<num_threads; i++) { tids[i] = i; ret_count = pthread_create(&threads[i], &attr,find_entries, (void *) &tids[i]); if(ret_count) { printf("\\n ERROR : Return code from pthread_create() is %d ",ret_count); exit(-1); } } for (i=0; i<num_threads; i++) { ret_count = pthread_join(threads[i], 0); if(ret_count) { printf("\\n ERROR : Return code from pthread_join() is %d ",ret_count); exit(-1); } } gettimeofday(&tv, &tz); time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; printf("Number of search element found in list Count= %d\\n",count); printf("Time in Seconds (T) : %lf\\n", time_end - time_start); ret_count = pthread_attr_destroy(&attr); if(ret_count) { printf("\\n ERROR : Return code from pthread_attr_destroy() is %d ",ret_count); exit(-1); } ret_count = pthread_mutex_destroy(&count_mutex); if(ret_count) { printf("\\n ERROR : Return code from pthread_mutex_destroy() is %d ",ret_count); exit(-1); } }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); if (top>0) { if ((pop(arr)==(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int tid; double stuff; } thread_data_t; double shared_x; pthread_mutex_t lock_x; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; printf("hello from thr_func, thread id: %d\\n", data->tid); pthread_mutex_lock(&lock_x); shared_x += data->stuff; printf("x = %f\\n", shared_x); pthread_mutex_unlock(&lock_x); pthread_exit(0); } int main(int argc, char **argv) { pthread_t thr[5]; int i, rc; thread_data_t thr_data[5]; shared_x = 0; pthread_mutex_init(&lock_x, 0); for (i = 0; i < 5; ++i) { thr_data[i].tid = i; thr_data[i].stuff = (i + 1) * 5; if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < 5; ++i) { pthread_join(thr[i], 0); } printf("shared_x %lf\\n",shared_x); return 0; }
0
#include <pthread.h> int lock_var = 0; time_t end_time; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_routine1(void *arg) { int i; printf("I'am the sub thread1\\n"); while(time(0) < end_time) { pthread_mutex_lock(&mutex); for(i=0; i<3; i++) { lock_var++; sleep(1); printf("product: lock_var =%d in for loop.\\n", lock_var); } printf("product: lock_var =%d\\n", lock_var); pthread_mutex_unlock(&mutex); usleep(70000); } pthread_exit(0); return 0; } void *thread_routine2(void *arg) { printf("I'am the sub thread2\\n"); while(time(0) < end_time) { pthread_mutex_lock(&mutex); printf("customer: lock_var=%d\\n", lock_var); pthread_mutex_unlock(&mutex); usleep(10000); } pthread_exit(0); return 0; } int main(void) { pthread_t tid1, tid2; printf("Thread demo\\n"); end_time = time(0) +30; pthread_mutex_init(&mutex, 0); pthread_create(&tid1, 0, thread_routine1, 0); pthread_create(&tid2, 0, thread_routine2, 0); printf("after pthread_create()\\n"); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_mutex_destroy(&mutex); printf("after pthread_join()\\n"); return 0; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t _wait = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err, signo; for(; ;) { err = sigwait(&mask, &signo); if(err != 0) { pthread_exit((void*)0); } switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&_wait); return 0; default: printf("unexpected signal%d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { printf("sigmask error\\n"); exit(-1); } err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0) { printf("pthread create error\\n"); exit(-2); } pthread_mutex_lock(&lock); sleep(5); pthread_kill(tid, SIGINT); sleep(5); kill(getpid(), SIGQUIT); while(quitflag == 0) pthread_cond_wait(&_wait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) printf("sigpromask error\\n"); exit(0); }
0
#include <pthread.h> struct DECIMAL_COORD { int time; float latitude; float longitude; }; struct DECIMAL_COORD decimal_coord = {0, 0.0, 0.0}; struct HANDLERS handlers; void signals_handler(int signal_number) { printf("Signal catched.\\n"); hndclose(&handlers); exit(0); } float to_decimal(float value) { int deg = floor(value/100); float min = (value - deg*100)/100; return deg + min*100/60; } void *forward(void * mut) { pthread_mutex_t *mutex = (pthread_mutex_t*) mut; while(1) { pthread_mutex_lock(mutex); int time = decimal_coord.time; float latitude = decimal_coord.latitude; float longitude = decimal_coord.longitude; pthread_mutex_unlock(mutex); char message[22]; sprintf(message, "%06d/%.04f/%.04f", time, latitude, longitude); int len = sizeof(handlers.info_me); printf("sent: %s\\n", message); fflush(stdout); sleep(2); } return 0; } void *convert(void * mut) { pthread_mutex_t *mutex = (pthread_mutex_t*) mut; while(1) { sem_wait(handlers.sem); int time = handlers.shdata->time; float latitude = to_decimal(handlers.shdata->latitude); float longitude = to_decimal(handlers.shdata->longitude); sem_post(handlers.sem); pthread_mutex_lock(mutex); decimal_coord.time = time; decimal_coord.latitude = latitude; decimal_coord.longitude = longitude; pthread_mutex_unlock(mutex); usleep(500000); } } int main(int argc, char *argv []) { struct OPTS opts; if (parse_args(argc, argv, &opts) == -1) exit(1); if (hndopen(opts, &handlers) == -1) exit(1); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t thread1; if (pthread_create(&thread1, 0, convert, (void*) &mutex) != 0) exit(1); pthread_t thread2; if (pthread_create(&thread2, 0, forward, (void*) &mutex) != 0) exit(1); struct sigaction action; action.sa_handler = signals_handler; sigemptyset(& (action.sa_mask)); action.sa_flags = 0; sigaction(SIGINT, & action, 0); pthread_join(thread1, 0); hndclose(&handlers); exit(0); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char* getenv(const char *name) { int i, len; char *envbuf; pthread_onde(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(MAXSTRINGSZ); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len + 1], MAXSTRINGSZ - 1); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; }
0
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; void* p_func(void* p) { pthread_mutex_lock(&mutex); int ret; int i=(int)p; printf("I am child %d,I am here\\n",i); ret=pthread_cond_wait(&cond,&mutex); if(0!=ret) { printf("pthread_cond_wait ret=%d\\n",ret); } printf("I am child thread %d,I am wake\\n",i); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main() { int ret; ret=pthread_cond_init(&cond,0); if(0!=ret) { printf("pthread_cond_init ret=%d\\n",ret); return -1; } ret=pthread_mutex_init(&mutex,0); if(0!=ret) { printf("pthread_mutex_init ret=%d\\n",ret); return -1; } pthread_t thid[5]; int i; for(i=0;i<5;i++) { pthread_create(&thid[i],0,p_func,(void*)i); } sleep(1); pthread_cond_signal(&cond); for(i=0;i<5;i++) { ret=pthread_join(thid[i],0); if(0!=ret) { printf("pthread_join ret=%d\\n",ret); return -1; } } ret=pthread_cond_destroy(&cond); if(0!=ret) { printf("pthread_cond_destroy ret=%d\\n",ret); return -1; } pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; int g_sum = 0; void* vector_operation(void* p_param) { int* t_param = p_param; fprintf(stdout, "%d * %d\\n", t_param[0], t_param[1]); pthread_mutex_lock(&g_mutex); g_sum += t_param[0] * t_param[1]; pthread_mutex_unlock(&g_mutex); } int main() { pthread_t t_threads[3]; int t_array_a[3] = {0, 3, 6}; int t_array_b[3] = {0, 2, 5}; for(int t_index = 0; t_index < 3; t_index++) { int* t = malloc(2 * sizeof(int)); t[0] = t_array_a[t_index]; t[1] = t_array_b[t_index]; pthread_create(&t_threads[t_index], 0, vector_operation, t); } for(int t_index = 0; t_index < 3; t_index++) pthread_join(t_threads[t_index], 0); fprintf(stdout, "Produit scalaire : %d\\n", g_sum); return 0; }
0
#include <pthread.h> struct thread_args { int *counter; int rep; pthread_mutex_t *counter_mutex; pthread_mutex_t *condition_mutex; pthread_cond_t *condition; }; void* thread_function1(void *ptr) { struct thread_args *arg = (struct thread_args*) ptr; for ( ; ; ) { pthread_mutex_lock(arg->condition_mutex); while (*arg->counter >= 10 && *arg->counter <= 30) pthread_cond_wait(arg->condition, arg->condition_mutex); pthread_mutex_unlock(arg->condition_mutex); pthread_mutex_lock(arg->counter_mutex); ++*(arg->counter); printf("thread_function1: %d\\n", *arg->counter); pthread_mutex_unlock(arg->counter_mutex); if (*arg->counter >= arg->rep) return 0; } } void* thread_function2(void *ptr) { struct thread_args *arg = (struct thread_args*) ptr; for ( ; ; ) { pthread_mutex_lock(arg->condition_mutex); if (*arg->counter < 10 || *arg->counter > 30) pthread_cond_signal(arg->condition); pthread_mutex_unlock(arg->condition_mutex); pthread_mutex_lock(arg->counter_mutex); ++*(arg->counter); printf("thread_function2: %d\\n", *arg->counter); pthread_mutex_unlock(arg->counter_mutex); if (*arg->counter >= arg->rep) return 0; } } int main() { pthread_t thread1, thread2; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER, condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; int counter = 0, rep = 50; struct thread_args args = {&counter, rep, &counter_mutex, &condition_mutex, &condition}; pthread_create(&thread1, 0, thread_function1, &args); pthread_create(&thread2, 0, thread_function2, &args); pthread_join(thread1, 0); pthread_join(thread2, 0); assert(counter >= rep); return 0; }
1
#include <pthread.h> int NUM_THREADS; long int chunk_end; long int chunk_init; pthread_mutex_t lock_x; void swapM(long int* a, long int* b) { long int aux; aux = *a; *a = *b; *b = aux; } long int divideM(long int *vec, int left, int right) { int i, j; i = left; for (j = left + 1; j <= right; ++j) { if (vec[j] < vec[left]) { ++i; pthread_mutex_lock(&lock_x); swapM(&vec[i], &vec[j]); pthread_mutex_unlock(&lock_x); } } pthread_mutex_lock(&lock_x); swapM(&vec[left], &vec[i]); pthread_mutex_unlock(&lock_x); return i; } void quickSortM(long int *vec, int left, int right) { int r; if (right > left) { r = divideM(vec, left, right); quickSortM(vec, left, r - 1); quickSortM(vec, r + 1, right); } } void *th_qs(void *vect) { long int *vec = (long int *) vect; quickSortM(vec,chunk_init, chunk_end); pthread_exit(0); } int run_t(char **fname) { int i; long int num,size=0; FILE *ptr_myfile; pthread_t tid[NUM_THREADS]; void *status; char str[30]; ptr_myfile=fopen(*fname,"rb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } while(fread(&num,sizeof(long int),1,ptr_myfile)) size++; size--; long int arr[size]; fseek(ptr_myfile, sizeof(long int), 0 ); for(i=0;i<size;i++) fread(&arr[i],sizeof(long int),1,ptr_myfile); fclose(ptr_myfile); pthread_mutex_init(&lock_x, 0); for ( i = 1; i < NUM_THREADS; i++) { chunk_init = chunk_end; chunk_end = (size/NUM_THREADS)*i; pthread_create(&tid[i], 0, &th_qs, (void*)arr); } for ( i = 1; i < NUM_THREADS; i++) pthread_join(tid[i], &status); chunk_init=0; chunk_end = size; pthread_create(&tid[NUM_THREADS], 0, &th_qs, (void*)arr); pthread_join(tid[NUM_THREADS], &status); strcpy(str, *fname); strcat(str, ".out"); ptr_myfile=fopen(str,"wb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } for ( i=0; i < size; i++) fwrite(&arr[i], sizeof(long int), 1, ptr_myfile); fclose(ptr_myfile); return 0; } int run_p(char **fname){ int i,wpid,status; long int num,size=0; FILE *ptr_myfile; char str[30]; ptr_myfile=fopen(*fname,"rb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } while(fread(&num,sizeof(long int),1,ptr_myfile)) size++; size--; long int arr[size]; fseek(ptr_myfile, sizeof(long int), 0 ); for(i=0;i<size;i++) fread(&arr[i],sizeof(long int),1,ptr_myfile); fclose(ptr_myfile); for ( i = 1; i < NUM_THREADS; i++) { chunk_init = chunk_end; chunk_end = (size/NUM_THREADS)*i; if ( i==2 || i== 4 || i==6) wpid = fork(); if(wpid>0) break; quickSortM(arr,chunk_init, chunk_end); wait(&status); } quickSortM(arr,0, size); strcpy(str, *fname); strcat(str, ".out"); ptr_myfile=fopen(str,"wb"); if (!ptr_myfile) { printf("Unable to open file!"); return 1; } for ( i=0; i < size; i++) fwrite(&arr[i], sizeof(long int), 1, ptr_myfile); fclose(ptr_myfile); return 0; } void help(){ printf("\\nUsage: fqs [OPTION]... [FILE]...\\nSort with quicksort algoritm a file with random long ints, OPTION and FILE are mandatory, OPTION must be [-s/-m], a default run displays this help and exit.\\n\\t-t run with thread support\\n\\t-p run without multiprocess support\\n\\t\\t-h display this help and exit\\n\\t\\t-v output version information and exit\\n\\n"); } void vers(){ printf("\\nqs 1.30\\nCopyright (C) 2015 Free Software Foundation, Inc.\\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\\nThis is free software: you are free to change and redistribute it.\\nThere is NO WARRANTY, to the extent permitted by law.\\n\\nWritten by Gonçalo Faria, Luis Franco, and Vitor Filipe \\n\\n"); } int main (int argc, char *argv[]) { int rtn,total,opt; switch(argc){ case 2: opt = getopt(argc, argv, "v"); if(opt == 'v') { vers(); rtn=0; } else { help(); rtn=1; } break; case 4: NUM_THREADS=atoi(argv[3]); opt = getopt(argc, argv, "t:p:"); if(opt == 'p') rtn=run_p(&argv[2]); else if (opt == 't') rtn=run_t(&argv[2]); else { help(); rtn=1; } break; default: help(); rtn=1; break; } return rtn; }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer=0; void *producer(void *ptr) { int i; for (int i; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while (buffer != 0) pthread_cond_wait(&condp, &the_mutex); buffer = i; printf("producer: producing %d\\n", buffer); pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer(void *ptr) { int i; for (int i; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) pthread_cond_wait(&condc, &the_mutex); buffer = 0; printf("consumer: consuming %d\\n", buffer); pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(pro, 0); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&the_mutex); }
1
#include <pthread.h> double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void dotprod(void *data) { int i,start,end; double mysum, *x, *y; start=*((int *)data); end = start+dotstr.veclen/8; x = dotstr.a; y = dotstr.b; mysum = 0.0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock( &mutex1 ); dotstr.sum += mysum; pthread_mutex_unlock( &mutex1 ); } int main (int argc, char *argv[]) { int i,len; double *a, *b; pthread_t thread[8]; int lens[8]; len = 100000000; a = (double*) malloc (len*sizeof(double)); b = (double*) malloc (len*sizeof(double)); for (i=0; i<len; i++) { a[i]=1; b[i]=a[i]; } for(i=0;i<8;i++){ lens[i]=100000000/8*i; } dotstr.veclen = len; dotstr.a = a; dotstr.b = b; dotstr.sum=0; for(i=0;i<8;i++){ pthread_create(&thread[i],0,(void *)&dotprod,(void*)&lens[i]); } for(i=0;i<8;i++){ pthread_join(thread[i],0); } printf ("Sum = %lf \\n", dotstr.sum); free (a); free (b); return 0; }
0
#include <pthread.h> int g_done = 0; pthread_mutex_t g_mutex_launch; void *thread_main(void *null) { char line[1024]; pid_t child_pid; char *result; while (! g_done) { pthread_mutex_lock(&g_mutex_launch); if (! g_done && (result = fgets(line, 1024, stdin)) ) { if (! (child_pid = fork()) ) { system(line); exit(0); } } else g_done = 1; pthread_mutex_unlock(&g_mutex_launch); if (result) waitpid(child_pid, 0, 0); } pthread_exit(0); } void child_after_fork() { g_done = 1; } int main(int argc, const char **argv) { pthread_t *threads; int i, thread_count; if (argc < 2 || (thread_count = atoi(argv[1])) < 1) { fprintf(stderr, "Usage: parallelize {thread_count}\\n"); exit(1); } pthread_mutex_init(&g_mutex_launch, 0); pthread_atfork(0, 0, child_after_fork); threads = malloc(thread_count * sizeof(pthread_t)); for (i = 0; i < thread_count; i++) { if (pthread_create(&threads[i], 0, thread_main, 0)) { fprintf(stderr, "parallelize: cannot create thread %d\\n", i); exit(-1); } } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t lock; void *myfunc(void* myvar); int a = 0; int main() { pthread_t thread1; pthread_t thread2; int ret1, ret2; char* msg1 = "first thread"; char* msg2 = "second thread"; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } ret1 = pthread_create(&thread1, 0, (void*) &myfunc, (void*) msg1); ret2 = pthread_create(&thread2, 0, (void*) &myfunc, (void*) msg2); pthread_join(thread1, 0); pthread_join(thread2, 0); printf("Fİrst thrtead ret1 = %d\\n",ret1); printf("Fİrst thrtead ret2 = %d\\n",ret2); pthread_mutex_destroy(&lock); return 0; } void *myfunc(void* myvar) { char* msg = (char*) myvar; int i; printf("QQQQQQQ"); for(i = 0; i < 10; ++i) { printf("%s %d %d\\n",msg,i,a); pthread_mutex_lock(&lock); ++a; pthread_mutex_unlock(&lock); sleep(1); } return 0; }
0
#include <pthread.h> double a[100]; double b[100]; double c[100]; int k = 0; void fun2(int n,double money) { c[n] = 0; srand((unsigned)time(0)); for(int i = 0; i < n;i++) { a[i] = rand(); } double total = 0.0; for(int i = 0 ; i < n;i++) { total += a[i]; } for(int i = 0 ; i < n;i++) { b[i] = a[i]/total; } for(int j = 0 ; j < n -1 ; j++) { c[j] = ((int)((b[j]* 10000)))/100.0; } c[n-1] = money; for(int k = 0; k < n-1;k++) { c[n-1] -= c[k]; } } double money; pthread_t mainid; pthread_t g_id[20]; struct info{ int id; double m; int mark; char name[20]; }person[20]; pthread_mutex_t lock; void* task(void *p) { int n = (int)p; pthread_mutex_lock(&lock); if(money > 0 && person[n].mark == -1) { money = money - c[k]; printf("线程%d取走%.2lf元\\n",n,c[k]); printf("剩余%.2lf\\n",money); person[n].id = n; person[n].m = c[k]; k++; person[n].mark = 1; } pthread_mutex_unlock(&lock); } void * creat_money(void *p) { double num = *(double*)p; pthread_mutex_lock(&lock); money = num; pthread_mutex_unlock(&lock); return "红包已放入"; } void fun() { strcpy(person[0].name,"jake"); strcpy(person[1].name,"tom"); strcpy(person[2].name,"lisa"); strcpy(person[3].name,"zhangsan"); strcpy(person[4].name,"lisi"); strcpy(person[5].name,"wangwu"); strcpy(person[6].name,"xiaoliu"); strcpy(person[7].name,"qianba"); strcpy(person[8].name,"liu"); strcpy(person[9].name,"zhao"); strcpy(person[10].name,"qian"); strcpy(person[11].name,"sun"); strcpy(person[12].name,"li"); strcpy(person[13].name,"zhou"); strcpy(person[14].name,"wu"); strcpy(person[15].name,"zhen"); strcpy(person[16].name,"wang"); strcpy(person[17].name,"xing"); strcpy(person[18].name,"rou"); strcpy(person[19].name,",mercy"); } int main() { fun(); int err; for(int i = 0 ; i < 20;i++) { person[i].mark = -1; person[i].id = -1; } pthread_mutex_init(&lock,0); pthread_t tid; char *buff; double qian; int num; printf("请输入你的红包金额\\n"); scanf("%lf",&qian); printf("请输入红包个数\\n"); scanf("%d",&num); fun2(num,qian); pthread_create(&tid,0,creat_money,(void *)&qian); pthread_join(tid,(void **)&buff); printf("%s\\n",buff); sleep(1); for(int i = 0 ; i < 20;i++) { if(err = pthread_create(&g_id[i],0,task,(void *)i)!= 0) printf("error"); } for(int j = 0 ; j < 20;j++) { pthread_join(g_id[j],0); } for(int i = 0 ;i < 20;i++) { printf("name = %s\\t money = %.2lf\\n",person[i].name,person[i].m); } pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> int inc_all; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadIncrement(void *p){ int g = 0; *(int*)p = 0; for(g = 0; g<1000000; g++){ (*(int*)p)++; pthread_mutex_lock(&mutex); inc_all++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(void){ int i, j, k; pthread_t threadID[10]; int inc[10]; inc_all = 0; for(i = 0; i<10; i++){ if(pthread_create(&threadID[i], 0, threadIncrement, &inc[i]) != 0) { perror("pthread_create"); exit(1); } } for(j = 0; j<10; j++){ if(pthread_join(threadID[j], 0) != 0){ exit(1); } } for(k = 0; k<10; k++){ printf("Thread %d: %d\\n", k, inc[k]); } printf("Common increment value: %d", inc_all); return 0; }
0
#include <pthread.h> int a[16][16], b[16][16], c[16][16]; int numThreads = 1; pthread_mutex_t sumLock; int idx = 0; void init_array() { int i, j; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) { a[i][j] = i + j; b[i][j] = 16 - j; } } } void print_array() { int i, j; for (i = 0; i < 16; i++) { for (j = 0; j < 16; j++) printf("%4d ", c[i][j]); printf("\\n"); } } void slave(long tid) { int j, k, f; pthread_mutex_lock(&sumLock); f = idx++; pthread_mutex_unlock(&sumLock); while (f < 16) { for (j = 0; j < 16; j++) { c[idx][j] = 0.; for (k = 0; k < 16; k++) { c[idx][j] += a[idx][k] * b[k][j]; } } pthread_mutex_lock(&sumLock); f = idx++; pthread_mutex_unlock(&sumLock); } } int main(int argc, char **argv) { if (argc > 1) { if ((numThreads=atoi(argv[1])) < 1) { printf ("<numThreads> must be greater than 0\\n"); exit(0); } } long i; init_array(); pthread_t thread[numThreads]; pthread_mutex_init(&sumLock, 0); int nprocs = sysconf(_SC_NPROCESSORS_ONLN); for (i = 0; i <numThreads; i++) { pthread_create(&thread[i], 0, (void*)slave, (void*)i); } for (long i = 0; i < numThreads; i++) { pthread_join(thread[i], 0); } print_array(); }
1
#include <pthread.h> pthread_mutex_t mut; int pubRecord; void *thread1(void) { pid_t pid; pthread_t tid; tid = pthread_self(); pid = getpid(); int i; for (i =0; i <10; i++) { pthread_mutex_lock(&mut); pubRecord++; printf("my name is subthread1-thread = %d\\n",pubRecord); printf("there is info pid %u tid %u (0x%x)\\n", (unsigned int) pid, (unsigned int) tid, (unsigned int) tid); pthread_mutex_unlock(&mut); sleep(2); } } void *thread2(void *a) { int b; b = *(int *)a; int i; for (i =0 ; i<10; i++) { pthread_mutex_lock(&mut); pubRecord++; b++; printf("my name is subthread2-thread = %d\\n",pubRecord); printf("my name is subthread2-value a = %d\\n", b); pthread_mutex_unlock(&mut); sleep(1); } } int main(int argc, char *argv[]) { int a = 10; pthread_t ID1,ID2; int ret,i; pubRecord = 0; ret = pthread_create(&ID2, 0, (void *)thread2, (void *) &a); printf("the thread 2 id is %d", ret); if (ret !=0 ) { printf("create sub-thread2 error!\\n"); exit(1); } ret = pthread_create(&ID1, 0, (void *)thread1, 0); printf("the thread 1 id is %d", ret); if (ret !=0 ) { printf("create sub-thread1 error!\\n"); exit(2); } for (i =0; i < 10; i++) { printf("my name is main-thread\\n"); sleep(1); } pthread_join(ID1,0); pthread_join(ID2,0); return 0; }
0
#include <pthread.h> int shared = 0; pthread_mutex_t mutex_shared; void * increment(void *arg) { int i; pthread_mutex_lock(&mutex_shared); for(i=0; i<1000; i++) { shared++; } pthread_mutex_unlock(&mutex_shared); pthread_exit(0); } int main (int argc, char *argv[]) { void *status; pthread_mutex_init(&mutex_shared, 0); pthread_t threads[1000]; int i; int rc; for(i=0; i<1000; i++) { rc = pthread_create(&threads[i], 0, increment, (void *)0); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for(i=0; i<1000; i++) { pthread_join(threads[i],&status); } printf("Shared=%d\\n",shared); pthread_exit(0); }
1
#include <pthread.h> long thread_count; long long n; double sum; pthread_mutex_t mutex; void* Thread_sum(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); double Serial_pi(long long n); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish; Get_args(argc, argv); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); GET_TIME(start); sum = 0.0; for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); sum = 4.0*sum; GET_TIME(finish); printf("With n = %lld terms,\\n", n); printf(" Our estimate of pi = %.15f\\n", sum); printf("The elapsed time is %e seconds\\n", finish - start); GET_TIME(start); sum = Serial_pi(n); GET_TIME(finish); printf(" Single thread est = %.15f\\n", sum); printf("The elapsed time is %e seconds\\n", finish - start); printf(" pi = %.15f\\n", 4.0*atan(1.0)); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long i; long long my_n = n/thread_count; long long my_first_i = my_n*my_rank; long long my_last_i = my_first_i + my_n; double my_sum = 0.0; if (my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for (i = my_first_i; i < my_last_i; i++, factor = -factor) { my_sum += factor/(2*i+1); } pthread_mutex_lock(&mutex); sum += my_sum; pthread_mutex_unlock(&mutex); return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { sum += factor/(2*i+1); } return 4.0*sum; } void Get_args(int argc, char* argv[]) { thread_count = XXXX; n = YYYY; printf ("WARNING: fixing thread_count %ld and n %lld\\n", thread_count, n); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\\n"); fprintf(stderr, " n should be evenly divisible by the number of threads\\n"); exit(0); }
0
#include <pthread.h> int *all_buffers; int num_producers; int num_consumers; int num_buffers; int num_items; int num_producer_iterations; int actual_num_produced; pthread_mutex_t should_continue_producing_lock; pthread_mutex_t buffer_printer_lock; sem_t total_empty; sem_t buffer_lock; sem_t send_message_lock; int inpipe; int outpipe; bool shouldContinueProducing() { if (num_producer_iterations <= num_items) { num_producer_iterations++; return 1; } else { return 0; } } void bufferPrinter(int thread_number) { if (actual_num_produced % 1000 == 0 && actual_num_produced != 0) { printf("%d items created\\n", actual_num_produced); int i; sem_wait(&buffer_lock); for (i = 0; i < num_buffers; i++) { printf("Shared buffer %d has %d number of items\\n", i + 1, all_buffers[i]); } sem_post(&buffer_lock); } actual_num_produced++; return; } void send_message_to_consumer(int index) { int write_result = write(outpipe, &index, sizeof(int)); if(write_result < 0) printf("Producer write_result: %d, error string: %s\\n", write_result, strerror(errno)); } void *producer(void *t_number) { int thread_number = *((int *) t_number); while (1) { pthread_mutex_lock(&should_continue_producing_lock); bool shouldContinue = shouldContinueProducing(); pthread_mutex_unlock(&should_continue_producing_lock); if (shouldContinue == 0) { break; } int index_of_buffer_that_was_incremented = 0; sem_wait(&total_empty); sem_wait(&buffer_lock); int i; for (i = 0; i < num_buffers; i++) { if (all_buffers[i] < 1024) { all_buffers[i]++; index_of_buffer_that_was_incremented = i; break; } } sem_post(&buffer_lock); sem_wait(&send_message_lock); send_message_to_consumer(index_of_buffer_that_was_incremented); sem_post(&send_message_lock); pthread_mutex_lock(&buffer_printer_lock); bufferPrinter(thread_number); pthread_mutex_unlock(&buffer_printer_lock); } } void handle_received_message() { int received_messages = 0; while (received_messages <= num_items) { int index_to_decrement; if (read(inpipe, &index_to_decrement, sizeof(int)) == 0) { break; } sem_wait(&buffer_lock); all_buffers[index_to_decrement]--; sem_post(&buffer_lock); sem_post(&total_empty); received_messages++; } } void *pipereader(void *unneeded_arg) { handle_received_message(); close(inpipe); } void main (int argc, char *argv[]) { if (argc != 7) { printf("Wrong number of arguments...Exiting\\n"); return; } num_producers = atoi(argv[1]); num_consumers = atoi(argv[2]); num_buffers = atoi(argv[3]); num_items = atoi(argv[4]); inpipe = atoi(argv[5]); outpipe = atoi(argv[6]); num_producer_iterations = 0; actual_num_produced = 0; all_buffers = (int*) malloc (num_buffers * sizeof(int)); int i; for (i = 0; i < num_buffers; ++i){ all_buffers[i] = 0; } sem_init(&total_empty, 0, num_buffers * 1024); sem_init(&buffer_lock, 0, 1); sem_init(&send_message_lock, 0, 1); pthread_mutex_init(&should_continue_producing_lock, 0); pthread_mutex_init(&buffer_printer_lock, 0); pthread_t reader; pthread_create(&reader, 0, &pipereader, 0); sleep(1); printf("Num producers: %d, Num Consumers: %d," " Num Buffers: %d, Num Items: %d\\n", num_producers, num_consumers, num_buffers, num_items); pthread_t *producer_threads = (pthread_t *) malloc(num_producers * sizeof(pthread_t)); int *producer_counters = (int*) malloc (num_producers* sizeof(int)); int counter; for (counter = 0; counter < num_producers; ++counter){ producer_counters[counter] = counter; } for (counter = 0; counter < num_producers; ++counter) { printf("Creating producer thread %d\\n", counter); pthread_create(&producer_threads[counter], 0, producer, (void *) &producer_counters[counter]); } for (counter = 0; counter < num_producers; ++counter) { pthread_join(producer_threads[counter], 0); } close(outpipe); pthread_join(reader, 0); }
1
#include <pthread.h> int total_words ; pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER; int main(int ac, char *av[]) { pthread_t *thread_list; void *count_words(void *); int i; if ( ac == 1 ){ printf("usage: %s file ..\\n", av[0]); exit(1); } thread_list = (pthread_t *) malloc(ac*sizeof(pthread_t)); if ( thread_list == 0 ) { perror("malloc"); exit(1);}; total_words = 0; for(i=1; i<ac; i++) if ( pthread_create(&thread_list[i], 0, count_words, (void *) av[i]) ) { perror("pthread_create"); exit(2);}; for(i=1; i<ac; i++) pthread_join(thread_list[i], 0); printf("%5d: total words\\n", total_words); return 0; } void *count_words(void *f) { char *filename = (char *) f; FILE *fp; int c, prevc = '\\0'; if ( (fp = fopen(filename, "r")) != 0 ){ while( ( c = getc(fp)) != EOF ){ if ( !isalnum(c) && isalnum(prevc) ){ pthread_mutex_lock(&counter_lock); total_words++; pthread_mutex_unlock(&counter_lock); } prevc = c; } fclose(fp); } else perror(filename); return 0; }
0
#include <pthread.h> char *filename; struct task *next; } task; task *job_queue_head = 0; task *job_queue_tail = 0; pthread_cond_t condQueueReady = PTHREAD_COND_INITIALIZER; pthread_mutex_t qMutex = PTHREAD_MUTEX_INITIALIZER; void getfileinfo(int tid, char*filename); void *thread_pool_func(void *tid); void enqueue_task(char *fname); char * dequeue_task(); int main(int argc, char **argv) { pthread_t *pool = calloc(sizeof(pthread_t),10); for(int i=0; i < 10; i++) { int *tid = malloc(sizeof(int)); *tid = i; if (pthread_create(&(pool[i]), 0, thread_pool_func, tid) != 0) { exit(-1); } } printf("created thread pool..."); printf("Main Thread: about to start giving the thread pool tasks to work on...\\n"); fflush(stdout); while (1) { enqueue_task("./interactivebank.c"); enqueue_task("./Makefile"); enqueue_task("pthreadex.c"); enqueue_task("conditionex.c"); sleep(1); } } void *thread_pool_func(void *tid) { int thread_num = *((int*)tid); printf("Thread %d: started [%d]\\n",thread_num,(int)pthread_self()); while(1) { char *fname = dequeue_task(); getfileinfo(thread_num, fname); } } void getfileinfo(int thread_id, char *filename) { struct stat finfo; if (stat(filename, &finfo) != 0) { printf("%d: couldn't stat \\"%s\\"", thread_id, filename); } else { printf("%d: %s\\n" "\\tsize: %ld bytes\\n" "\\tblocks: %ld\\n" "\\tuser-id: %d\\n\\n", thread_id, filename, finfo.st_size, finfo.st_blocks, finfo.st_uid); } } void enqueue_task(char *fname) { task *ptask = (task*)malloc(sizeof(task)); ptask->filename = fname; ptask->next = 0; pthread_mutex_lock(&qMutex); assert(job_queue_tail != 0 || job_queue_head == 0); if (job_queue_head == 0) { job_queue_head = ptask; job_queue_tail = ptask; } else { job_queue_tail->next = ptask; job_queue_tail = ptask; } assert(job_queue_tail != 0 || job_queue_head == 0); pthread_mutex_unlock(&qMutex); } char* dequeue_task() { char* return_value; task *ptemp; pthread_mutex_lock(&qMutex); assert(job_queue_tail != 0 || job_queue_head == 0); while (job_queue_head == 0) { pthread_mutex_unlock(&qMutex); pthread_mutex_lock(&qMutex); } return_value = job_queue_head->filename; ptemp = job_queue_head; job_queue_head = job_queue_head->next; if (job_queue_tail == ptemp) job_queue_tail = 0; assert(job_queue_tail != 0 || job_queue_head == 0); pthread_mutex_unlock(&qMutex); assert (ptemp != 0); free(ptemp); return return_value; }
1
#include <pthread.h> sem_t plataforma_embarque[5]; sem_t plataforma_desembarque[5]; sem_t fila_embarque; sem_t fila_desembarque; volatile int embarcaram; volatile int desembarcaram; sem_t carro_encheu; sem_t carro_esvaziou; pthread_mutex_t trava_passageiros_embarque; pthread_mutex_t trava_passageiros_desembarque; sem_t imprime_animacao; estado_p estado_passageiros[50]; estado_c estado_carros[50]; int proximo(int id) { return ( (id+1) % 5); } void* carregar() { sleep(rand() % 3); return 0; } void* descarregar() { sleep(rand() % 3); return 0; } void* passeia() { sleep(rand() % 3); return 0; } void* Carro(void *v) { int k; int id = (int) v; while(1){ printf("Carro %d esta pronto para sair.\\n",id); sem_wait(&plataforma_embarque[id]); carregar(); printf("Carro %d esta carregando.\\n",id); for(k=0;k < 5; k++) sem_post(&fila_embarque); sem_wait(&carro_encheu); printf("Carro %d terminou de carregar.\\n",id); sem_post(&plataforma_embarque[proximo(id)]); passeia(); printf("Carro %d esta passeando.\\n",id); sem_wait(&plataforma_desembarque[id]); descarregar(); printf("Carro %d voltou para a plataforma.\\n",id); for(k=0;k < 5; k++) sem_post(&fila_desembarque); sem_wait(&carro_esvaziou); printf("Carro %d esvaziou.\\n",id); sem_post(&plataforma_desembarque[proximo(id)]); } return 0; } void* embarcar() { sleep(rand() % 3); return 0; } void* desembarcar() { sleep(rand() % 3); return 0; } void* Passageiro(void *v) { int id = (int) v; printf("Passageiro %d chegou.\\n",id); sem_wait(&fila_embarque); embarcar(); printf("Passageiro %d embarcou.\\n",id); pthread_mutex_lock(&trava_passageiros_embarque); embarcaram += 1; if (embarcaram == 5){ sem_post(&carro_encheu); embarcaram = 0; } pthread_mutex_unlock(&trava_passageiros_embarque); sem_wait(&fila_desembarque); desembarcar(); printf("Passageiro %d desembarcou.\\n",id); pthread_mutex_lock(&trava_passageiros_desembarque); desembarcaram += 1; if (desembarcaram == 5){ sem_post(&carro_esvaziou); desembarcaram = 0; } pthread_mutex_unlock(&trava_passageiros_desembarque); printf("Passageiro %d foi embora.\\n",id); return 0; } void* Animacao() { return 0; } int main() { pthread_t passageiro[50]; pthread_t carro[50]; pthread_t animacao; int i; sem_init(&fila_embarque,0,0); sem_init(&fila_desembarque,0,0); sem_init(&carro_encheu,0,0); sem_init(&carro_esvaziou,0,0); sem_init(&imprime_animacao,0,1); sem_init(&plataforma_embarque[0],0,1); for(i=1;i < 5; i++) sem_init(&plataforma_embarque[i],0,0); sem_init(&plataforma_desembarque[0],0,1); for(i=1;i < 5; i++) sem_init(&plataforma_desembarque[i],0,0); if(pthread_create(&animacao, 0, Animacao, 0)) printf("Erro ao criar a animacao!\\n"); for (i = 0; i < 5; i++) if(pthread_create(&carro[i], 0, Carro, (void*) i)) printf("Erro ao criar carro!\\n"); for (i = 0; i < 50; i++) if(pthread_create(&passageiro[i], 0, Passageiro, (void*) i)) printf("Erro ao criar passageiro!\\n"); for (i = 0; i < 50; i++) if(pthread_join(passageiro[i], 0)) printf("Erro ao esperar o passageiro!\\n"); return 0; }
0
#include <pthread.h> static char rcsId[]="$Id: ikcq.c,v 1.1 1999/12/16 22:13:40 lanzm Exp lanzm $"; int ikcq_queue_request(struct ikc_queue_head* head, struct ikc_request* req) { struct ikc_request_queue* tail; struct ikc_request_queue* new_q = (struct ikc_request_queue*) malloc(sizeof(struct ikc_request_queue)); struct ikc_request_queue** q = &(head->queue); if(new_q == 0) return -E_IKC_NOMEM; pthread_mutex_lock(head->mutex); if(*q == 0) { *q = new_q; (*q)->prev = new_q; (*q)->next = 0; (*q)->req_struct = req; } else { tail = (struct ikc_request_queue*)(*q)->prev; new_q->req_struct = req; new_q->next = tail->next; new_q->prev = tail; tail->next = new_q; (*q)->prev = new_q; } pthread_mutex_unlock(head->mutex); return 0; } int ikcq_dequeue_request(struct ikc_queue_head* head, struct ikc_request** request) { struct ikc_request_queue* q_deq; struct ikc_request_queue** q = &(head->queue); pthread_mutex_lock(head->mutex); if(*q == 0) { pthread_mutex_unlock(head->mutex); return -E_IKC_NOQUEUE; } q_deq = *q; if(q_deq == 0) { pthread_mutex_unlock(head->mutex); return -E_IKC_NOREQ; } else { if(q_deq->next != 0) q_deq->next->prev = q_deq->prev; if(q_deq != *q) q_deq->prev->next = q_deq->next; if(q_deq == (*q)->prev) (*q)->prev = q_deq->prev; if(q_deq == *q) *q = q_deq->next; if(request != 0) { *request = q_deq->req_struct; } else { __ikc_free_request(q_deq->req_struct); free(q_deq->req_struct); } free(q_deq); } pthread_mutex_unlock(head->mutex); return 0; } int ikcq_remove_request(struct ikc_queue_head* head, struct ikc_request* req) { struct ikc_request_queue* req_in_queue; struct ikc_request_queue** q = &(head->queue); pthread_mutex_lock(head->mutex); if(*q == 0) { pthread_mutex_unlock(head->mutex); return -E_IKC_NOQUEUE; } req_in_queue = *q; while(req_in_queue->req_struct != req && req_in_queue != 0) { req_in_queue = req_in_queue->next; } if(req_in_queue == 0) { pthread_mutex_unlock(head->mutex); return -E_IKC_NOREQ; } else { if(req_in_queue->next != 0) req_in_queue->next->prev = req_in_queue->prev; if(req_in_queue != *q) req_in_queue->prev->next = req_in_queue->next; if(req_in_queue == (*q)->prev) (*q)->prev = req_in_queue->prev; if(req_in_queue == *q) *q = req_in_queue->next; __ikc_free_request(req_in_queue->req_struct); free(req_in_queue); } pthread_mutex_unlock(head->mutex); return 0; }
1
#include <pthread.h> char temp[100]; int flag = 0; char flag_f = 0; int who; void *thread_recv(void *arg); void *thread_send(void *arg); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int main(void){ int socket_fd; socket_fd = socket(AF_INET, SOCK_STREAM, 0); if(socket_fd < 0){ perror("socket"); exit(1); } struct sockaddr_in serveraddr; memset(&serveraddr, 0, sizeof(struct sockaddr_in)); serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(5256); serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(socket_fd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0){ perror("bind"); exit(1); } if(listen(socket_fd, 10) < 0){ perror("listen"); exit(1); } struct sockaddr_in clientaddr; int clientlen; int connfd[10]; int j; char temp[100]; for(j = 0; j < 10; j ++){ connfd[j] = -1; } clientlen = sizeof(clientaddr); int i = 0; pthread_t tid, tid1, tid2; while(1){ connfd[i] = accept(socket_fd, (struct sockaddr *)&clientaddr, &clientlen); pthread_create(&tid, 0, thread_recv, &connfd[i]); i ++; printf("在线人数:%d", i); printf("Accepted!\\n"); pthread_create(&tid1, 0, thread_send, connfd); } } void *thread_recv(void *arg){ while(1){ int num = 0; num = recv(*((int *)arg), temp, 100, 0); if(strcmp("\\n", temp) == 0) continue; if(num > 0){ who = *((int *)arg); printf("接受客户端信息:%s\\n", temp); flag = 1; pthread_cond_signal(&cond); } } return ; } void *thread_send(void *arg){ int i; while(1){ pthread_mutex_lock(&mutex); pthread_cond_wait(&cond ,&mutex); pthread_mutex_unlock(&mutex); if(flag == 1){ for(i = 0; ((int *)arg)[i] != -1; i ++){ if(((int *)arg)[i] == who){ continue; } else send(((int *)arg)[i], temp, 100, 0); printf("消息转发成功!\\n"); } flag = 0; } } return ; }
0
#include <pthread.h> struct counter_thread { int value; pthread_mutex_t lock; }; void topup(struct counter_thread *p) { pthread_mutex_lock(&p->lock); p->value++; pthread_mutex_unlock(&p->lock); } void *the_thing(void *c) { struct counter_thread *d=(struct counter_thread*)c; long long int k=0; while(k<1000000000) { topup(d); k++; } } int main() { pthread_t thready[10]; struct counter_thread c; c.value=0; clock_t ti,t; double total=0; pthread_mutex_init(&c.lock,0); int N=2,i,j; while(N<=10) { total=0; for(j=0;j<50;++j) { c.value=0; pthread_mutex_init(&c.lock,0); ti=clock(); for(i=0;i<N;++i) { pthread_create(&thready[i],0,the_thing,(void*)(&c)); } for(i=0;i<N;++i) { pthread_join(thready[i],0); } t=clock(); total=total+((double)(t-ti)/CLOCKS_PER_SEC); } double avg=total/50; printf("%f\\n",avg ); N++; } return 0; }
1
#include <pthread.h> pthread_mutex_t mut1; int n = 0; int s = 0; void* thread_function1 (void* unused) { int i = 1; while(1) { pthread_mutex_lock (&mut1); s = s + i; pthread_mutex_unlock(&mut1); printf("s=%d, i=%d\\n", s, i); i = i + 2; if (i > n) break; } return 0; } void* thread_function2 (void* unused) { int i = 2; while(1) { pthread_mutex_lock (&mut1); s = s + i; pthread_mutex_unlock(&mut1); printf("s=%d, i=%d\\n", s, i); i = i + 2; if (i > n) break; } return 0; } int main() { pthread_t thread1; pthread_t thread2; pthread_mutex_init(&mut1, 0); printf("Enter n: "); scanf("%d", &n); pthread_create (&thread1, 0, &thread_function1, 0); pthread_create (&thread2, 0, &thread_function2, 0); pthread_join (thread1, 0); pthread_join (thread2, 0); printf("Resulting Sum = %d; n = %d\\n", s, n); return 0; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return (void *)0; default: printf("unexpected signal %d\\n", signo); return (void *)1; } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&wait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); return 0; }
1
#include <pthread.h> pthread_t tid[3]; static volatile int keepRunning = 1; pthread_mutex_t lock; sem_t countsem, spacesem; FILE *f; void *b[(50)]; int in = 0, out = 0; int biggest1=0,biggest2=0; int smallest1=1749241873,smallest2=1749241873; int bufferCount=0; void controller() { keepRunning = 0; char* str = "[aviso]: Termino solicitado. Aguardando threads...\\n"; fprintf(f, "%s", str); printf("\\n%s\\n", str); int biggestOfAll; int smallestOfAll; if(biggest2 > biggest1){ biggestOfAll = biggest2; }else{ biggestOfAll = biggest1; } if(smallest2 > smallest1) { smallestOfAll = smallest2; }else{ smallestOfAll = smallest1; } char str2[50]; sprintf(str2,"[aviso]: Maior numero gerado: %d\\n",biggestOfAll); fprintf(f, "%s", str2); printf("%s\\n",str2); char str3[50]; sprintf(str3,"[aviso]: Menor numero gerado: %d\\n",smallestOfAll); fprintf(f, "%s", str3); printf("%s\\n",str3); char str4[50]; sprintf(str4,"[aviso]: Maior ocupacao de buffer: %d\\n",bufferCount); fprintf(f, "%s", str4); printf("%s\\n",str4); char* str5 = "[aviso]: Aplicacao encerrada.\\n"; fprintf(f, "%s\\n", str5); printf("%s\\n",str5); fclose(f); } void init() { sem_init(&countsem, 0, 0); sem_init(&spacesem, 0, 50); } void enqueue(void *value){ sem_wait( &spacesem ); pthread_mutex_lock(&lock); b[ (in++) & ((50)-1) ] = value; pthread_mutex_unlock(&lock); sem_post(&countsem); int j; sem_getvalue(&countsem,&j); if(j > bufferCount){ bufferCount = j; } } void *dequeue(){ sem_wait(&countsem); pthread_mutex_lock(&lock); void *result = b[(out++) & ((50)-1)]; pthread_mutex_unlock(&lock); sem_post(&spacesem); return result; } int getRandomNumber(){ int value = rand(); int negative = rand()%2; if(negative) value*=-1; return value; } void feeder() { int i; char str[50]; while(keepRunning){ usleep(100000); int value = getRandomNumber(); sprintf(str,"[produtor]: numero gerado: %d\\n",value); fprintf(f, "%s", str); enqueue(&value); } } void eater() { int i; char str[50]; int *value; while(keepRunning){ usleep(150000); value = dequeue(); if(*value > biggest1) biggest1 = *value; if(*value < smallest1) smallest1 = *value; sprintf(str,"[consumo a]: numero lido: %d\\n",*value); fprintf(f, "%s", str); } } void eater2() { int i; char str[50]; int *value; while(keepRunning){ usleep(150000); value = dequeue(); if(*value > biggest2) biggest2 = *value; if(*value < smallest2) smallest2 = *value; sprintf(str,"[consumo b]: numero lido: %d\\n",*value); fprintf(f, "%s", str); } } void *threadSeparator(void *vargp) { pthread_t id = pthread_self(); if(pthread_equal(id,tid[0])) { feeder(); } if(pthread_equal(id,tid[1])) { eater(); } if(pthread_equal(id,tid[2])) { eater2(); } return 0; } int main(int argc, char *argv[]) { int i = 0, err; char* fileName; signal(SIGINT, controller); fileName = argv[1]; f = fopen(fileName, "w"); printf("Arquivo criando: %s\\n", fileName); init(); printf("Iniciando componentes\\n"); if (pthread_mutex_init(&lock, 0) != 0) { printf("mutex init failed\\n"); return 1; } printf("Iniciando threads\\nDigite CTRL+C para terminar\\n"); while(i < 3) { err = pthread_create(&(tid[i]), 0, &threadSeparator, 0); if (err != 0) printf("can't create thread :[%s]\\n", strerror(err)); i++; } while(keepRunning); exit(0); }
0
#include <pthread.h> static pthread_mutex_t ios_event_queue_lock = PTHREAD_MUTEX_INITIALIZER; static struct { void (*function)(void*); void* userdata; } ios_event_queue[16]; static uint32_t ios_event_queue_size; void ios_frontend_post_event(void (*fn)(void*), void* userdata) { pthread_mutex_lock(&ios_event_queue_lock); if (ios_event_queue_size < 16) { ios_event_queue[ios_event_queue_size].function = fn; ios_event_queue[ios_event_queue_size].userdata = userdata; ios_event_queue_size ++; } pthread_mutex_unlock(&ios_event_queue_lock); } static void process_events() { pthread_mutex_lock(&ios_event_queue_lock); for (int i = 0; i < ios_event_queue_size; i ++) ios_event_queue[i].function(ios_event_queue[i].userdata); ios_event_queue_size = 0; pthread_mutex_unlock(&ios_event_queue_lock); } static void ios_free_main_wrap(struct rarch_main_wrap* wrap) { if (wrap) { free((char*)wrap->libretro_path); free((char*)wrap->rom_path); free((char*)wrap->sram_path); free((char*)wrap->state_path); free((char*)wrap->config_path); } free(wrap); } void* rarch_main_ios(void* args) { struct rarch_main_wrap* argdata = (struct rarch_main_wrap*)args; int init_ret = rarch_main_init_wrap(argdata); ios_free_main_wrap(argdata); if (init_ret) { rarch_main_clear_state(); dispatch_async_f(dispatch_get_main_queue(), (void*)1, ios_rarch_exited); return 0; } while ((g_extern.is_paused && !g_extern.is_oneshot) ? rarch_main_idle_iterate() : rarch_main_iterate()); rarch_main_deinit(); rarch_deinit_msg_queue(); rarch_main_clear_state(); dispatch_async_f(dispatch_get_main_queue(), 0, ios_rarch_exited); return 0; }
1
#include <pthread.h> struct args { int index; int *counter; pthread_mutex_t *lock; }; void *incdec(void *args) { printf("thread %d starts\\n", ((struct args *)args)->index); struct args *targs = args; int *counter = targs->counter; pthread_mutex_lock(targs->lock); for(int i = 0; i < 1000000; i++) { (*counter)++; } pthread_mutex_unlock(targs->lock); pthread_mutex_lock(targs->lock); for(int i = 0; i < 1000000; i++) { (*counter)--; } pthread_mutex_unlock(targs->lock); printf("thread %d exits\\n", targs->index); return 0; } int main(int argc, char *argv[]) { int number = 200; int counter = 0; if(argc >= 2) { int num = (int)strtol(argv[1], 0, 10); number = (num >= 1) ? num : 200; } pthread_t threads[number]; pthread_mutex_t lock; struct args targs[number]; if(pthread_mutex_init(&lock, 0) != 0) { fprintf(stderr, "failed to initialise mutex"); return 1; } for(int i = 0; i < number; i++) { targs[i].index = i; targs[i].counter = &counter; targs[i].lock = &lock; } printf("creating %d threads...\\n", number); for(int i = 0; i < number; i++) { if(pthread_create(&threads[i], 0, &incdec, &targs[i]) != 0) { fprintf(stderr, "failed to create thread %d\\n", i); } } for(int i = 0; i < number; i++) { if(pthread_join(threads[i], 0) != 0) { fprintf(stderr, "failed to join thread %d\\n", i); } else { printf("thread %d joined\\n", i); } } pthread_mutex_destroy(&lock); printf("actual value of counter is %d\\n", counter); return 0; }
0
#include <pthread.h> static void *get_wqe(struct mlx4_srq *srq, int n) { return srq->buf.buf + (n << srq->wqe_shift); } void mlx4_free_srq_wqe(struct mlx4_srq *srq, int ind) { struct mlx4_wqe_srq_next_seg *next; pthread_spin_lock(&srq->lock); next = get_wqe(srq, srq->tail); next->next_wqe_index = htons(ind); srq->tail = ind; pthread_spin_unlock(&srq->lock); } int mlx4_post_srq_recv(struct ibv_srq *ibsrq, struct ibv_recv_wr *wr, struct ibv_recv_wr **bad_wr) { struct mlx4_srq *srq = to_msrq(ibsrq); struct mlx4_wqe_srq_next_seg *next; struct mlx4_wqe_data_seg *scat; int err = 0; int nreq; int i; pthread_spin_lock(&srq->lock); for (nreq = 0; wr; ++nreq, wr = wr->next) { if (wr->num_sge > srq->max_gs) { err = -1; *bad_wr = wr; break; } if (srq->head == srq->tail) { err = -1; *bad_wr = wr; break; } srq->wrid[srq->head] = wr->wr_id; next = get_wqe(srq, srq->head); srq->head = ntohs(next->next_wqe_index); scat = (struct mlx4_wqe_data_seg *) (next + 1); for (i = 0; i < wr->num_sge; ++i) { scat[i].byte_count = htonl(wr->sg_list[i].length); scat[i].lkey = htonl(wr->sg_list[i].lkey); scat[i].addr = htonll(wr->sg_list[i].addr); } if (i < srq->max_gs) { scat[i].byte_count = 0; scat[i].lkey = htonl(MLX4_INVALID_LKEY); scat[i].addr = 0; } } if (nreq) { srq->counter += nreq; wmb(); *srq->db = htonl(srq->counter); } pthread_spin_unlock(&srq->lock); return err; } int mlx4_alloc_srq_buf(struct ibv_pd *pd, struct ibv_srq_attr *attr, struct mlx4_srq *srq) { struct mlx4_wqe_srq_next_seg *next; struct mlx4_wqe_data_seg *scatter; int size; int buf_size; int i; srq->wrid = malloc(srq->max * sizeof (uint64_t)); if (!srq->wrid) return -1; size = sizeof (struct mlx4_wqe_srq_next_seg) + srq->max_gs * sizeof (struct mlx4_wqe_data_seg); for (srq->wqe_shift = 5; 1 << srq->wqe_shift < size; ++srq->wqe_shift) ; buf_size = srq->max << srq->wqe_shift; if (mlx4_alloc_buf(&srq->buf, buf_size, to_mdev(pd->context->device)->page_size)) { free(srq->wrid); return -1; } memset(srq->buf.buf, 0, buf_size); for (i = 0; i < srq->max; ++i) { next = get_wqe(srq, i); next->next_wqe_index = htons((i + 1) & (srq->max - 1)); for (scatter = (void *) (next + 1); (void *) scatter < (void *) next + (1 << srq->wqe_shift); ++scatter) scatter->lkey = htonl(MLX4_INVALID_LKEY); } srq->head = 0; srq->tail = srq->max - 1; return 0; } struct mlx4_srq *mlx4_find_xrc_srq(struct mlx4_context *ctx, uint32_t xrc_srqn) { int tind = (xrc_srqn & (ctx->num_xrc_srqs - 1)) >> ctx->xrc_srq_table_shift; if (ctx->xrc_srq_table[tind].refcnt) return ctx->xrc_srq_table[tind].table[xrc_srqn & ctx->xrc_srq_table_mask]; else return 0; } int mlx4_store_xrc_srq(struct mlx4_context *ctx, uint32_t xrc_srqn, struct mlx4_srq *srq) { int tind = (xrc_srqn & (ctx->num_xrc_srqs - 1)) >> ctx->xrc_srq_table_shift; int ret = 0; pthread_mutex_lock(&ctx->xrc_srq_table_mutex); if (!ctx->xrc_srq_table[tind].refcnt) { ctx->xrc_srq_table[tind].table = calloc(ctx->xrc_srq_table_mask + 1, sizeof(struct mlx4_srq *)); if (!ctx->xrc_srq_table[tind].table) { ret = -1; goto out; } } ++ctx->xrc_srq_table[tind].refcnt; ctx->xrc_srq_table[tind].table[xrc_srqn & ctx->xrc_srq_table_mask] = srq; out: pthread_mutex_unlock(&ctx->xrc_srq_table_mutex); return ret; } void mlx4_clear_xrc_srq(struct mlx4_context *ctx, uint32_t xrc_srqn) { int tind = (xrc_srqn & (ctx->num_xrc_srqs - 1)) >> ctx->xrc_srq_table_shift; pthread_mutex_lock(&ctx->xrc_srq_table_mutex); if (!--ctx->xrc_srq_table[tind].refcnt) free(ctx->xrc_srq_table[tind].table); else ctx->xrc_srq_table[tind].table[xrc_srqn & ctx->xrc_srq_table_mask] = 0; pthread_mutex_unlock(&ctx->xrc_srq_table_mutex); }
1
#include <pthread.h> int shouldExit = 0; sem_t empty; sem_t full; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;; buffer_item buffer[5]; void initBuffer(){ printf("Setting up buffer....\\n"); sleep(0); printf("Buffer Initialized\\n"); } int insert_item(buffer_item item,long id){ int success = 0; printf("Producer thread %lu waiting for empty spot in buffer\\n",id); sem_wait(&empty); pthread_mutex_lock(&mutex); printf("Producer thread %lu has lock on empty spot in buffer\\n",id); int emptySpots = 0; sem_getvalue(&empty,&emptySpots); buffer[emptySpots] = item; pthread_mutex_unlock(&mutex); sem_post(&full); success = 1; if(success){return 1;} else{return 0;} } int remove_item(buffer_item *item,long id){ int success = 0; printf("Consumer thread %lu waiting for production to finish\\n",id); sem_wait(&full); pthread_mutex_lock(&mutex); printf("Consumer thread %lu has a lock on an item for consumption\\n",id); int fullSpots = 0; sem_getvalue(&full,&fullSpots); *item = buffer[5 - fullSpots - 1]; buffer[5 - fullSpots-1] = 0; pthread_mutex_unlock(&mutex); sem_post(&empty); success = 1; if(success){return 1;} else{return 0;} } void *initProducer(void *t){ buffer_item item = 0; long id = (long)t; while(1){ if(shouldExit){pthread_exit(0);} sleep(rand()%3); int temp = rand(); item = temp; if(insert_item(item,id)){printf("Production Successful for thread %lu\\n\\n\\n",id);} else{printf("Error in production on thread %lu\\n",id);} } } void *initConsumer(void *t){ buffer_item item = 0; long id = (long)t; while(1){ if(shouldExit){pthread_exit(0);} sleep(rand()%3); if(remove_item(&item,id)){printf("Consumer consumed %d on thread %lu\\n\\n\\n",item,id);} else{printf("Error in consumption on thread %lu\\n",id);} } } int main(int argc,char *argv[]){ int sleepTime = atoi(argv[1]); int pThreads = atoi(argv[2]); int cThreads = atoi(argv[3]); initBuffer(); sem_init(&empty,0,5); sem_init(&full,0,0); pthread_mutex_init(&mutex,0); pthread_t consumerThreads[cThreads]; pthread_t producerThreads[pThreads]; long t; int ret; for(t = 0; t<cThreads;t++){ ret = pthread_create(&consumerThreads[t],0,initConsumer,(void *)t); } for(t = 0; t<pThreads;t++){ ret = pthread_create(&producerThreads[t],0,initProducer,(void *)t); } sleep(sleepTime); shouldExit = 1; return 0; }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void* func1(); void* func2(); int fib(int); int n = 0; int main(){ pthread_t thread1, thread2; pthread_create(&thread1, 0, &func1, 0); pthread_create(&thread2, 0, &func2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); exit(0); } int fib(int x){ static int f[100] = {0, 1}; int i; for(i=2;i<=x;i++) f[i] = f[i-1] + f[i-2]; return f[x]; } void *func1(){ while(1){ pthread_mutex_lock(&count_mutex); pthread_cond_wait(&condition_var, &count_mutex); printf("f(%d) = %d\\n", n, fib(n)); pthread_cond_signal(&condition_var); pthread_mutex_unlock(&count_mutex); if(n<=0) exit(0); } } void *func2(){ while(1){ pthread_mutex_lock(&count_mutex); printf("Input the number. (<0 to exit): "); scanf("%d", &n); if(n>=0) pthread_cond_signal(&condition_var); else exit(0); pthread_cond_wait(&condition_var, &count_mutex); pthread_mutex_unlock(&count_mutex); } }
1
#include <pthread.h> { int id, vector, place, **grid; } threadinfo; void *threadwork(void *); int answer; pthread_mutex_t themutex; int main(int argc, char **argv) { int vector = atoi(argv[1]); int place = atoi(argv[2]); int **grid = createArray(vector, place); readFile(vector, place, grid, argv[3]); answer = grid[0][0]; int j; pthread_t *threads = (pthread_t*)malloc(vector * sizeof(pthread_t)); threadinfo *info = (threadinfo*)malloc(vector * sizeof(struct threadinfo)); for(j=0;j<vector;j++) { info[j].id = j; info[j].vector = vector; info[j].place = place; info[j].grid = grid; pthread_create(&threads[j], 0, threadwork, (void*)&info[j]); } for(j=0;j<vector;j++) pthread_join(threads[j], 0); free(info); free(threads); grid[0][0] = answer; writeFile(1, 1, grid, argv[4]); freeArray(vector, place, grid); return 0; } void *threadwork(void *param) { threadinfo *info = (threadinfo*)param; int j = info->id; int **grid = info->grid; int i, min = grid[j][0]; for(i=0;i<info->place;i++) { if(min > grid[j][i]) min = grid[j][i]; } pthread_mutex_lock(&themutex); if(answer > min) answer = min; pthread_mutex_unlock(&themutex); }
0
#include <pthread.h> char *dict, *found_keys; unsigned char *ssid; int sha_len, ssid_size, n_found=0; int YEARS[] = {6, 7, 8, 9, 10, 5, 4, 3, 2, 1, 0}; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int id; int start; int end; } bf_arg; int num_threads() { int n_threads = sysconf(_SC_NPROCESSORS_ONLN); if (n_threads < 1) return 1; return n_threads; } void cleanup() { free(dict); free(ssid); if (found_keys != 0) free(found_keys); } void fill_dict(char *ab) { int i; for (i=0; i<36; i++) { if (i<10) ab[i] = i+48; else ab[i] = i+55; } } void generate_xxx(char *ab, char *xxx) { int x, y, z; for (x=35; x>=0; x--) { for (y=35; y>=0; y--) { for (z=35; z>=0; z--) { sprintf(xxx, "%.2X%.2X%.2X", ab[x], ab[y], ab[z]); xxx += 7; } } } } void brute_force(bf_arg *arg) { int year, week, i, j; char *m_number = malloc(13*sizeof(char)); m_number[12] = '\\0'; unsigned char *sha = malloc(sha_len); unsigned char *cmp_offset_ptr = sha+sha_len-ssid_size; char *iter; for (j=0; j<(sizeof(YEARS)/sizeof(int)); j++) { year = YEARS[j]; sprintf(m_number, "CP%.2d", year); for (week=(*arg).end; week>(*arg).start; week--) { iter = dict; sprintf(m_number+4, "%.2d", week); for(i=0; i<46656; i++) { memcpy(m_number+6, iter, 6); iter += 7; if (!memcmp(ssid, cmp_offset_ptr, ssid_size)) { pthread_mutex_lock(&mutex); n_found++; found_keys = realloc(found_keys, n_found*11); sprintf((n_found-1)*11+found_keys, "%.2X%.2X%.2X%.2X%.2X", sha[0], sha[1], sha[2], sha[3], sha[4]); pthread_mutex_unlock(&mutex); } } } } end: free(m_number); free(sha); } int main(int argc, char **argv) { int i; char ab[36]; dict = malloc(46656*sizeof(char)*7); sha_len = 20; ssid_size = 3*sizeof(char); ssid = malloc(ssid_size); int n_threads = num_threads() + 1; pthread_t threads[n_threads]; printf("\\n/*********************************************************/\\n/* Thomson MEO password cracker. */\\n/* Based on algorithm documented at http://fodi.me/ */\\n/* */\\n/*********************************************************/\\n\\n"); char *tmp = malloc(14*sizeof(char)); if (argc == 1) { printf("Insert SSID to crack: "); char *lele = fgets(tmp, 14, stdin); int idx = strcspn(tmp, "\\n"); tmp[idx] = '\\0'; } else if (argc != 2) { printf("Thomson MEO SSID calculator. Usage:\\n\\n\\t%s SSID\\n\\nyou can omit the \\"Thomson\\" part or include it.\\n\\nExamples:\\n\\n\\t%s ThomsonA1B2C3\\n\\t%s A1B2C3\\n\\nBoth examples are equivalent.\\n\\n\\n", argv[0], argv[0], argv[0]); cleanup(); return 0; } else { strcpy(tmp, argv[1]+(strlen(argv[1])-6)); } sscanf(tmp+(strlen(tmp)-6), "%2X%2X%2X", ssid, ssid+1, ssid+2); free(tmp); printf("\\nSearching WPA for SSID Thomson%.2X%.2X%.2X\\n", ssid[0], ssid[1], ssid[2]); fill_dict(ab); generate_xxx(ab, dict); printf("\\nFound %d CPU hw threads - Starting %d workers...\\nPlease wait a few minutes...\\n\\n", num_threads(), n_threads); pthread_mutex_init(&mutex, 0); int week_range = 52 / n_threads; int remainder = 52 % n_threads; bf_arg t_args[n_threads]; for (i=0; i<n_threads; i++) { t_args[i].id = i; t_args[i].end = i*week_range+week_range; t_args[i].start = t_args[i].end-week_range; if (i == (n_threads-1)) t_args[i].end += remainder; pthread_create(&(threads[i]), 0, &brute_force, t_args+i); } for (i=0; i<n_threads; i++) pthread_join(threads[i], 0); pthread_mutex_destroy(&mutex); if (n_found) { printf("Possible keys for this SSID:\\n\\n"); for (i=0; i<n_found; i++) printf("%s\\n", found_keys+(i*11)); } else { printf("No keys found for this SSID... :(\\n"); } printf("\\n\\n\\nPress Enter to exit..."); getchar(); cleanup(); return 0; }
1
#include <pthread.h> struct mt{ int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; }; int main(void) { int fd, i; struct mt * mm; pid_t pid; fd = open("mt_test", O_CREAT | O_RDWR, 0777); ftruncate(fd, sizeof(*mm)); mm = mmap(0, sizeof(*mm), PROT_READ | PROT_WRITE, MAP_SHARED, fd ,0); close(fd); memset(mm, 0, sizeof(*mm)); pthread_mutexattr_init(&mm->mutexattr); pthread_mutexattr_setpshared(&mm->mutexattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mm->mutex, &mm->mutexattr); pid = fork(); printf("process id=%d\\tnum=%d\\n", getpid(), mm->num); if(pid == 0){ for(i = 0; i < 10; i++){ pthread_mutex_lock(&mm->mutex); (mm->num)++; printf("in %d process,num=num+1=:%d\\n", getpid(), mm->num); pthread_mutex_unlock(&mm->mutex); sleep(1); } } else if(pid > 0){ for(i = 0; i < 10; i++){ pthread_mutex_lock(&mm->mutex); mm->num += 2;; printf("in %dprocess,num=num+2=:%d\\n", getpid(), mm->num); pthread_mutex_unlock(&mm->mutex); sleep(1); } wait(0); } pthread_mutex_destroy(&mm->mutex); pthread_mutexattr_destroy(&mm->mutexattr); munmap(mm, sizeof(*mm)); unlink("mt_test"); return 0; }
0
#include <pthread.h> volatile uint16_t *muxbus = 0; pthread_mutex_t dio_lock; void initiate_dio_mutex() { if (pthread_mutex_init(&dio_lock, 0) != 0) { syslog(LOG_ERR, "Failed to initiate dio mutex"); display_error_msg("E07:UNEXPECTED"); exit(1); } } void dio_initialize() { int mem = open("/dev/mem", O_RDWR|O_SYNC); muxbus = mmap(0, getpagesize(), PROT_READ|PROT_WRITE, MAP_SHARED, mem, 0x30000000); initiate_dio_mutex(); } void dio_destroy(){ pthread_mutex_destroy(&dio_lock); } uint16_t peek16(uint16_t addr) { return muxbus[addr/2]; } void poke16(uint16_t addr, uint16_t value) { muxbus[addr/2] = value; } void mpoke16(uint16_t addr, uint16_t value) { muxbus[(addr + 0x400)/2] = value; } uint16_t mpeek16(uint16_t addr) { return muxbus[(addr + 0x400)/2]; } void mpeekpoke16(uint16_t addr, uint16_t bitposition, int onoff) { pthread_mutex_lock(&dio_lock); int tries = 0; uint16_t value = mpeek16(addr); if (onoff) { while ( (mpeek16(addr) & bitposition) != bitposition){ if (tries++ > 20) { syslog(LOG_ERR, "Cannot write to dio addr= 0x%x", addr); display_error_msg("E07:UNEXPECTED - DIO"); exit(1); } mpoke16(addr, value | bitposition); usleep(100); }; } else { while ( (mpeek16(addr) & bitposition) != 0x0){ if (tries++ > 20) { syslog(LOG_ERR, "Cannot write to dio addr= 0x%x", addr); display_error_msg("E07:UNEXPECTED - DIO"); exit(1); } mpoke16(addr, value & ~bitposition); usleep(100); }; } pthread_mutex_unlock(&dio_lock); }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &condition_mutex ); if( count >= 3 && count <= 6 ) { pthread_cond_wait( &condition_cond, &condition_mutex ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &condition_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_cond ); } pthread_mutex_unlock( &condition_mutex ); pthread_mutex_lock( &count_mutex ); count++; printf("Counter value functionCount2: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t esperaPares; pthread_cond_t esperaImpares; int turnoPares=1; int turnoImpares=0; void *pares(void *kk) { int i; for(i=0; i <= 10; i+=2 ) { pthread_mutex_lock(&mutex); while (turnoPares == 0) pthread_cond_wait(&esperaPares, &mutex); printf ("Pares: %d\\n", i); turnoImpares=1; turnoPares=0; pthread_cond_signal(&esperaImpares); pthread_mutex_unlock(&mutex); } printf ("FIN PARES\\n"); pthread_exit(0); } void *impares(void *kk) { int i; for(i=1; i <= 10; i=i+2 ) { pthread_mutex_lock(&mutex); while (turnoImpares == 0) pthread_cond_wait(&esperaImpares, &mutex); printf ("Impares: %d\\n", i); turnoImpares=0; turnoPares=1; pthread_cond_signal(&esperaPares); pthread_mutex_unlock(&mutex); } printf ("FIN IMPARES\\n"); pthread_exit(0); } int main(int argc, char *argv[]){ pthread_t th1, th2; pthread_mutex_init(&mutex, 0); pthread_cond_init(&esperaPares, 0); pthread_cond_init(&esperaImpares, 0); pthread_create(&th1, 0, pares, 0); pthread_create(&th2, 0, impares, 0); pthread_join(th1, 0); pthread_join(th2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&esperaPares); pthread_cond_destroy(&esperaImpares); exit(0); }
1
#include <pthread.h> int SharedVariable = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t barrier; int valid(char *string){ int i; int length = strlen(string); for(i = 0; i < length; i++){ if((string[i] <48) || (string[i] > 57)) return 0; } return 1; } int getValid(){ int n; char input[200]; do{ printf("\\nEnter valid number: "); scanf("%s", &input); }while(!valid(input)); n = atoi(input); return n; } void *runSimpleThread2( void *n){ int num = (intptr_t)n; SimpleThread2(num); } void SimpleThread2(int w){ int num, value; for(num = 0; num < 20 ; num++){ if(random() > 32767 / 2) usleep(10); pthread_mutex_lock(&mutex); value = SharedVariable; printf("*** thread %d sees value %d\\n", w, value); SharedVariable = value + 1; pthread_mutex_unlock(&mutex); } pthread_barrier_wait(&barrier); pthread_mutex_lock(&mutex); value = SharedVariable; pthread_mutex_unlock(&mutex); printf("Thead %d sees final value %d\\n", w, value); } int main(int argc, char *argv[]){ int nthreads, i, c; if(argc != 2 || !valid(argv[1])) nthreads = getValid(); else nthreads = atoi(argv[1]); pthread_t threads[nthreads]; if(pthread_barrier_init(&barrier, 0, nthreads)){ printf("barrier failed\\n"); return -1; } for( i = 0; i < nthreads; i++ ){ c = pthread_create( &threads[i], 0, runSimpleThread2, (void*)(intptr_t)i ); } for( i =0; i < nthreads; ++i){ if(pthread_join(threads[i],0)){ printf("Join thread failed %d\\n", i); return -1; } } pthread_exit(0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } char *v; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread1(void * arg) { v = malloc(sizeof(char)); return 0; } void *thread2(void *arg) { pthread_mutex_lock (&m); v[0] = 'X'; pthread_mutex_unlock (&m); return 0; } void *thread3(void *arg) { pthread_mutex_lock (&m); v[0] = 'Y'; pthread_mutex_unlock (&m); return 0; } void *thread0(void *arg) { pthread_t t1, t2, t3, t4, t5; pthread_create(&t1, 0, thread1, 0); pthread_join(t1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_create(&t4, 0, thread2, 0); pthread_create(&t5, 0, thread2, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); pthread_join(t5, 0); return 0; } int main(void) { pthread_t t; pthread_create(&t, 0, thread0, 0); pthread_join(t, 0); __VERIFIER_assert(v[0] == 'X' || v[0] == 'Y'); return 0; }
1
#include <pthread.h> int nitems; int buff[MAXNITEMS]; struct { pthread_mutex_t mutex; int nput; int nval; } put = {PTHREAD_MUTEX_INITIALIZER}; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; } nready = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER}; void *produce(void *); void *consume(void *); int main(int argc, char **argv) { int i, nthreads, count[MAXNTHREADS]; pthread_t tid_produce[MAXNTHREADS], tid_consume; if (argc != 3) { exit(-1); } nitems = MIN(atoi(argv[1]), MAXNITEMS); nthreads = MIN(atoi(argv[2]), MAXNTHREADS); for (i=0; i<nthreads; i++) { count[i] = 0; pthread_create(&tid_produce[i], 0, produce, &count[i]); } pthread_create(&tid_consume, 0, consume, 0); for (i=0; i<nthreads; i++) { pthread_join(tid_produce[i], 0); printf("count[%d] = %d\\n", i, count[i]); } pthread_join(tid_consume, 0); exit(0); } void *produce(void *arg) { int dosignal = 0; for(;;) { pthread_mutex_lock(&put.mutex); if (put.nput >= nitems) { pthread_mutex_unlock(&put.mutex); return 0; } buff[put.nput] = put.nval; put.nput++; put.nval++; pthread_mutex_unlock(&put.mutex); pthread_mutex_lock(&nready.mutex); dosignal = (nready.nready == 0); nready.nready++; pthread_mutex_unlock(&nready.mutex); if (dosignal) { pthread_cond_signal(&nready.cond); } *((int *)arg) += 1; } } void *consume(void *arg) { int i; for (i=0; i<nitems; i++) { pthread_mutex_lock(&nready.mutex); while (nready.nready == 0) { pthread_cond_wait(&nready.cond, &nready.mutex); } nready.nready--; pthread_mutex_unlock(&nready.mutex); if (buff[i] != i) { printf("buff[%d] = %d\\n", i, buff[i]); } } return 0; }
0
#include <pthread.h> int make_listen(int port); void handle_connection(FILE* fin, FILE* fout); int remove_trailing_whitespace(char* buf); static pthread_mutex_t mutex; static pthread_cond_t condvar; static int n_connection_threads; void* connection_thread(void* arg) { FILE* f = (FILE*) arg; pthread_mutex_lock(&mutex); ++n_connection_threads; pthread_mutex_unlock(&mutex); pthread_detach(pthread_self()); handle_connection(f, f); fclose(f); pthread_mutex_lock(&mutex); --n_connection_threads; pthread_cond_signal(&condvar); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char** argv) { int port = 6168; if (argc >= 2) { port = strtol(argv[1], 0, 0); assert(port > 0 && port <= 65535); } int fd = make_listen(port); raise_file_limit(); pthread_mutex_init(&mutex, 0); pthread_cond_init(&condvar, 0); while (1) { int cfd = accept(fd, 0, 0); if (cfd < 0) { perror("accept"); exit(1); } while (n_connection_threads > 100) { pthread_mutex_lock(&mutex); if (n_connection_threads > 100) pthread_cond_wait(&condvar, &mutex); pthread_mutex_unlock(&mutex); } pthread_t t; FILE* f = fdopen(cfd, "a+"); setvbuf(f, 0, _IONBF, 0); int r = pthread_create(&t, 0, connection_thread, (void*) f); if (r != 0) { perror("pthread_create"); exit(1); } } } void handle_connection(FILE* fin, FILE* fout) { char buf[1024]; while (fgets(buf, 1024, fin)) if (remove_trailing_whitespace(buf)) { struct servent* service = getservbyname(buf, "tcp"); int port = service ? ntohs(service->s_port) : 0; fprintf(fout, "%s,%d\\n", buf, port); } if (ferror(fin)) perror("read"); } int make_listen(int port) { int fd = socket(AF_INET, SOCK_STREAM, 0); assert(fd >= 0); int r = fcntl(fd, F_SETFD, FD_CLOEXEC); assert(r >= 0); int yes = 1; r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); assert(r >= 0); struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = INADDR_ANY; r = bind(fd, (struct sockaddr*) &address, sizeof(address)); assert(r >= 0); r = listen(fd, 100); assert(r >= 0); return fd; } int remove_trailing_whitespace(char* buf) { int len = strlen(buf); while (len > 0 && isspace((unsigned char) buf[len - 1])) { --len; buf[len] = 0; } return len; }
1
#include <pthread.h> extern struct fs_options_struct fs_options; static struct simple_hash_s fuse_users_hash; static unsigned int calculate_uid_hash(uid_t uid) { return uid % fuse_users_hash.len; } static unsigned int uid_hashfunction(void *data) { struct fuse_user_s *user=(struct fuse_user_s *) data; return calculate_uid_hash(user->uid); } struct fuse_user_s *lookup_fuse_user(uid_t uid) { unsigned int hashvalue=calculate_uid_hash(uid); void *index=0; struct fuse_user_s *user=(struct fuse_user_s *) get_next_hashed_value(&fuse_users_hash, &index, hashvalue); while(user) { if (user->uid==uid) break; user=(struct fuse_user_s *) get_next_hashed_value(&fuse_users_hash, &index, hashvalue); } return user; } void add_fuse_user_hash(struct fuse_user_s *user) { add_data_to_hash(&fuse_users_hash, (void *) user); } void remove_fuse_user_hash(struct fuse_user_s *user) { remove_data_from_hash(&fuse_users_hash, (void *) user); } void lock_users_hash() { writelock_hashtable(&fuse_users_hash); } void unlock_users_hash() { unlock_hashtable(&fuse_users_hash); } struct fuse_user_s *get_next_fuse_user(void **index, unsigned int *hashvalue) { struct fuse_user_s *user=(struct fuse_user_s *) get_next_hashed_value(&fuse_users_hash, index, *hashvalue); while(user==0 && *hashvalue<fuse_users_hash.len) { (*hashvalue)++; user=(struct fuse_user_s *) get_next_hashed_value(&fuse_users_hash, index, *hashvalue); } return user; } static void add_workspace(struct fuse_user_s *user, struct workspace_mount_s *w) { pthread_mutex_lock(&user->mutex); add_list_element_last(&user->workspaces.head, &user->workspaces.tail, &w->list); pthread_mutex_unlock(&user->mutex); } static void remove_workspace(struct fuse_user_s *user, struct workspace_mount_s *w) { pthread_mutex_lock(&user->mutex); remove_list_element(&user->workspaces.head, &user->workspaces.tail, &w->list); pthread_mutex_unlock(&user->mutex); } struct fuse_user_s *add_fuse_user(uid_t uid, char *status, unsigned int *error) { struct fuse_user_s *user=0; struct passwd *pws=0; *error=ENOMEM; pws=getpwuid(uid); if (! pws) { *error=errno; return 0; } user=lookup_fuse_user(uid); if (user) { *error=EEXIST; return user; } user=malloc(sizeof(struct fuse_user_s)); if (user) { user->options=0; user->uid=pws->pw_uid; memset(user->status, '\\0', 32); if (status) { unsigned int len=strlen(status); if (len>FUSE_USER_STATUS_LEN - 1) len=FUSE_USER_STATUS_LEN - 1; memcpy(user->status, status, len); } user->workspaces.head=0; user->workspaces.tail=0; pthread_mutex_init(&user->mutex, 0); user->add_workspace=add_workspace; user->remove_workspace=remove_workspace; add_fuse_user_hash(user); *error=0; } else { *error=ENOMEM; } return user; } void free_fuse_user(void *data) { if (data) { struct fuse_user_s *user=(struct fuse_user_s *) data; pthread_mutex_destroy(&user->mutex); free(user); } } int initialize_fuse_users(unsigned int *error) { int result=0; result=initialize_group(&fuse_users_hash, uid_hashfunction, 32, error); if (result<0) { logoutput("initialize_fuse_users: error %i:%s initializing hashtable fuse users", *error, strerror(*error)); return -1; } return 0; } void free_fuse_users() { free_group(&fuse_users_hash, free_fuse_user); } unsigned char use_workspace_base(struct fuse_user_s *user, struct workspace_base_s *base) { unsigned char use_base=0; if ( base->ingroup>=0 && base->ingroup != (gid_t) -1) { if ( base->ingrouppolicy==WORKSPACE_RULE_POLICY_SUFFICIENT || base->ingrouppolicy==WORKSPACE_RULE_POLICY_REQUIRED ) { struct passwd *pwd=getpwuid(user->uid); int result=0; int ngroups=32; while (pwd) { gid_t groups[ngroups]; result=getgrouplist(pwd->pw_name, pwd->pw_gid, groups, &ngroups); if (result>0) { for (int i=0; i<ngroups; i++) { logoutput("use_workspace_base: found group %i user %s", (int) groups[i], pwd->pw_name); if (groups[i]==base->ingroup) { if ( base->ingrouppolicy==WORKSPACE_RULE_POLICY_SUFFICIENT ) use_base=1; if ( base->ingrouppolicy==WORKSPACE_RULE_POLICY_REQUIRED ) use_base=1; break; } } break; } } } } return use_base; } char *get_mountpoint_workspace_base(struct fuse_user_s *user, struct workspace_base_s *base, struct pathinfo_s *pathinfo) { char *mountpoint=0; if (base->mount_path_template) { mountpoint=get_path_from_template(base->mount_path_template, user, 0, 0); if (mountpoint) { pathinfo->path=mountpoint; pathinfo->len=strlen(mountpoint); pathinfo->flags=PATHINFO_FLAGS_ALLOCATED; pathinfo->refcount=1; } } return mountpoint; }
0
#include <pthread.h> pthread_mutex_t M; int DATA=0; int accessi1=0; int accessi2=0; void *thread1_process(void * arg) { int k=1; while(k) { pthread_mutex_lock(&M); accessi1++; DATA++; k=(DATA>=10?0:1); printf("accessi di T1: %d\\n", accessi1); pthread_mutex_unlock(&M); } pthread_exit(0); } void *thread2_process(void * arg) { int k=1; while(k) { pthread_mutex_lock(&M); accessi2++; DATA++; k=(DATA>=10?0:1); printf("accessi di T2: %d\\n", accessi2); pthread_mutex_unlock(&M); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t th1,th2; pthread_mutex_init(&M,0); if (pthread_create(&th1,0, thread1_process,0)<0) { fprintf(stderr, "create error for thread 1\\n"); exit(1); } if (pthread_create(&th2,0, thread2_process,0)<0) { fprintf(stderr, "create error for thread 2\\n"); exit(1); } pthread_join(th1,0); pthread_join(th2,0); }
1
#include <pthread.h> extern int identifier; extern int NUMBER_OF_ROUTERS; extern int NUMBER_OF_EDGES; extern int NUMBER_OF_NEIGHBORS; extern int* NEIGHBOR_IDS; extern struct sockaddr_in my_addr; extern int MAX_POSSIBLE_DIST; extern int** neighbor_link_details; extern int** actual_link_costs; extern int LSA_INTERVAL; extern int lsa_seq_num; extern int*** every_node_lsa_details; extern int* every_node_neighbors; extern pthread_mutex_t lock; void* lsa_packet_sender(void* param){ int i, offset, peer_id; int sock; if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("socket"); exit(1); } char send_data[1024]; struct hostent *host; host = (struct hostent *) gethostbyname("localhost"); struct sockaddr_in peer_addr; peer_addr.sin_family = AF_INET; peer_addr.sin_addr = *((struct in_addr *) host->h_addr); bzero(&(peer_addr.sin_zero), 8); while(1){ sleep(LSA_INTERVAL); strncpy(send_data, "LSA", 3); strncpy(send_data + 3, (char*)&identifier, 4); strncpy(send_data + 7, (char*)&lsa_seq_num, 4); lsa_seq_num++; strncpy(send_data + 11, (char*)&NUMBER_OF_NEIGHBORS, 4); offset = 15; pthread_mutex_lock(&lock); for(i = 0 ; i < NUMBER_OF_NEIGHBORS ; i++){ strncpy(send_data + offset, (char*)&actual_link_costs[i][0], 4); strncpy(send_data + offset + 4, (char*)&actual_link_costs[i][1], 4); offset += 8; } pthread_mutex_unlock(&lock); for(i = 0; i < NUMBER_OF_NEIGHBORS; i++){ peer_id = NEIGHBOR_IDS[i]; peer_addr.sin_port = htons(20000 + peer_id); sendto(sock, send_data, offset, 0, (struct sockaddr *) &peer_addr, sizeof (struct sockaddr)); } } }
0
#include <pthread.h> int q[2]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 2) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 2); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[6]; int sorted[6]; void producer () { int i, idx; for (i = 0; i < 6; i++) { idx = findmaxidx (source, 6); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 6; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 6; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> void quick_sort(double *vector, int a, int b); void *quick_sort_pthread(void *arg); void swap(double *vector, double temp, int i, int j); void barrier(); int dbgSorted(double* data, int len); void print_vector(double *vector, int len); int MAX_LEVEL; volatile int number_threads = 0; int number_threads_total = 0 ; pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t mysignal; { int a; int b; double* vector; int lvl; } input_args; int main(int argc, char *argv[]) { clock_t t_init, t_end; pthread_t first_thread; int i; double t_tot; double *data; int len = atoi(argv[1]); MAX_LEVEL = atoi(argv[2]); pthread_mutex_init(&mutex_lock,0); pthread_cond_init(&mysignal,0); data = (double *)malloc(len*sizeof(double)); srand(time(0)); for (i = 0; i < len; i++) { data[i] = drand48(); } t_init = clock(); input_args *arg = (input_args *)malloc(sizeof(input_args)); arg->vector = data; arg->a = 0; arg->b = len-1; arg->lvl = 0; number_threads++; number_threads_total++; pthread_create(&first_thread,0,quick_sort_pthread,(void *) arg); barrier(); t_end = clock(); t_tot = (double)(t_end - t_init) / CLOCKS_PER_SEC; printf("Time elapsed: %f \\n", t_tot); printf("Total number of threads %d \\n", number_threads_total); if (!dbgSorted(data, len)) { printf("Error not sorted \\n"); } free(arg); return 0; } void quick_sort(double *vector, int a, int b) { int i, j; double pivot; if(a < b) { pivot = vector[b]; i = a; j = b; while(i < j) { while(vector[i] < pivot) { i++; } while(vector[j] >= pivot) { j--; } if(i < j) { swap(vector, vector[i], i, j); } } swap(vector, pivot, b, i); quick_sort(vector, a, i-1); quick_sort(vector, i+1, b); } } void *quick_sort_pthread(void *input_arg) { input_args *arg = (input_args *) input_arg; int i, j; double pivot; double* vector = arg->vector; pthread_t thread; if(arg->a < arg->b) { pivot = vector[arg->b]; i = arg->a; j = arg->b; while(i < j) { while(vector[i] < pivot) { i++; } while(vector[j] >= pivot) { j--; } if(i < j) { swap(vector, vector[i], i, j); } } swap(vector, pivot, arg->b, i); if(arg->lvl < MAX_LEVEL){ input_args *a_arg = (input_args *)malloc(sizeof(input_args)); a_arg->a = arg->a; a_arg->b = i-1; a_arg->vector = vector; a_arg->lvl = arg->lvl+1; input_args *b_arg = (input_args *)malloc(sizeof(input_args)); b_arg->a = i+1; b_arg->b = arg->b; b_arg->vector = vector; b_arg->lvl = arg->lvl+1; pthread_mutex_lock(&mutex_lock); number_threads++; number_threads_total++; pthread_mutex_unlock(&mutex_lock); pthread_create(&thread, 0, quick_sort_pthread,(void *) a_arg); quick_sort_pthread((void *) b_arg); } else { quick_sort(vector, arg->a, i-1); quick_sort(vector, i+1, arg->b); } } pthread_mutex_lock(&mutex_lock); number_threads--; pthread_mutex_unlock(&mutex_lock); free(arg); pthread_exit(0); } void swap(double *vector, double temp, int i, int j) { vector[i] = vector[j]; vector[j] = temp; } void barrier() { while (number_threads > 0) { usleep(5); } } int dbgSorted(double* data, int len) { int i; for (i = 0; i < len-1; ++i) { if (data[i] > data[i+1]) { return 0; } } return 1; } void print_vector(double* vector, int len) { int i; for (i = 0; i < len; i++) { printf("%f ", vector[i]); } printf("\\n"); }
0
#include <pthread.h> void *baby( void *ptr ); int limite = 30000; int n = 2; int trovati = 0; pthread_mutex_t mutexN = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexTrovati = PTHREAD_MUTEX_INITIALIZER; void threads(int NChildren); void * baby (void * ptr); int main(int argc, char * argv[]) { int NChildren; clockid_t clk; struct timespec tpi,tpf; long nseci,nsecf; if (0>=1) printf("Argc= %d \\n",argc); if (argc>=2) { if (0>1) printf("args :: %s %s \\n",argv[0],argv[1]); NChildren=atoi(argv[1]); if (0>1) printf("in arg evaluation: NChildren= %d \\n ",NChildren); if (NChildren<1) { printf("\\nError retriving NC from arg. Set it at %d default value.\\n",2); NChildren=2; } } else { NChildren=2; } clock_gettime(clk,&tpi); nseci=tpi.tv_nsec; threads(NChildren); clock_gettime(clk,&tpf); nsecf=tpf.tv_nsec; nsecf=nsecf-nseci+1000000000*(tpf.tv_sec-tpi.tv_sec); printf("nsec passati %li usec %li msec %li \\n",nsecf,nsecf/1000,nsecf/1000000); printf("\\n\\nNumeri primi trovati: %d LIM: %d\\n", trovati,limite); exit(0); } void threads(int NChildren) { int i,irets; pthread_t threads[NChildren]; printf(" threads() :: NChildren = %i.\\n",NChildren); for (i=0;i<NChildren;i++) irets = pthread_create( &threads[i], 0, baby, (void*) &i); printf(" threads :: Waiting for babies. \\n"); for (i=0;i<NChildren;i++) pthread_join( threads[i], 0); } void * baby (void * ptr) { int cn,i,m=0; if (ptr==0) printf("Error!!! ptr ==NULL!!!!\\n"); else cn= * (int *) ptr; while(n<limite) { pthread_mutex_lock(&mutexN); m=n; n++; pthread_mutex_unlock(&mutexN); for(i=2;i<m;i++) { if(m%i==0) break; } if(i==m) { pthread_mutex_lock(&mutexTrovati); trovati++; pthread_mutex_unlock(&mutexTrovati); } } if (0==1) printf("Baby %i: i=%i \\n",cn,i); if (0==1) printf("Baby %i: Ended\\n",cn); return 0; }
1
#include <pthread.h> int pointCounter = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long thread_number, iteration_number, iterationPerThread_number; void* shoot_arrow(void *arg) { unsigned int seed; double x, y; int i, counter = 0; for (i = 0; i < iterationPerThread_number; i++) { x = rand_r(&seed) / (double)(32767); y = rand_r(&seed) / (double)(32767); if ((x*x + y*y) <= 1) { counter++; } } pthread_mutex_lock(&mutex); pointCounter += counter; pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { if (argc != 3 || strcmp(argv[1], "--help") == 0) { fprintf(stderr, "Usage: %s <iteration_number> <thread_number>\\n", argv[0]); exit(1); } iteration_number = atol(argv[1]); thread_number = atol(argv[2]); iterationPerThread_number = iteration_number/thread_number; pthread_t *threads = (pthread_t*) malloc(thread_number*sizeof(pthread_t)); int i; for (i = 0; i < thread_number; i++) { pthread_create(&threads[i], 0, shoot_arrow, 0); } for (i = 0; i < thread_number; i++) { pthread_join(threads[i], 0); } free(threads); pthread_mutex_destroy(&mutex); printf("Pi Number: %f\\n", (4 * (double)pointCounter / (double)iteration_number)); return 0; }
0
#include <pthread.h> int npos; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; int buf[10000000], pos = 0, val = 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++; pthread_mutex_unlock(&mut); *(int *)nr += 1; } } void *verify(void *arg) { int k; for(k = 0; k < npos; k++) if (buf[k] != k) printf("ERROR: buf[%d] = %d\\n", k, buf[k]); return 0; } int main(int argc, char *argv[]) { int k, nthr, count[100]; pthread_t tidf[100], tidv; int total; 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); 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 count = %d\\n",total); pthread_create(&tidv, 0, verify, 0); pthread_join(tidv, 0); return 0; }
1
#include <pthread.h> struct CTMemoryRecord { int retainCount; void (* deallocMethod)(void *address); pthread_mutex_t *memoryRecordMutex; }; void _createMemoryRecordTree(void); struct CTAVLTreeRoot *_sharedMemoryRecordTree(void); void _createMemoryRecordTreeMutex(void); pthread_mutex_t *_sharedMemoryRecordTreeMutex(void); struct CTAVLTreeRoot *__memoryRecordTree = 0; static pthread_mutex_t *__memoryRecordTreeMutex = 0; void * ctAlloc(size_t size, void (* deallocMethod)(void *address)) { void * allocedMemeory = malloc(size + sizeof(struct CTMemoryRecord) + sizeof(struct CTAVLTreeNode) + sizeof(pthread_mutex_t)); if (allocedMemeory == 0) { return 0; } struct CTMemoryRecord *memoryRecord = (struct CTMemoryRecord *)(((uint64_t)allocedMemeory) + size); memoryRecord->retainCount = 1; memoryRecord->deallocMethod = deallocMethod; memoryRecord->memoryRecordMutex = (pthread_mutex_t *)((uint64_t)memoryRecord + sizeof(struct CTMemoryRecord)); if (pthread_mutex_init(memoryRecord->memoryRecordMutex, 0)) { free(allocedMemeory); return 0; } struct CTAVLTreeNode *recordNode = (struct CTAVLTreeNode *)((uint64_t)memoryRecord + sizeof(struct CTMemoryRecord) + sizeof(pthread_mutex_t)); recordNode->key = allocedMemeory; recordNode->value = (void *)memoryRecord; struct CTAVLTreeRoot *root = _sharedMemoryRecordTree(); pthread_mutex_lock(_sharedMemoryRecordTreeMutex()); insertCTAVLTreeNode(recordNode, root); pthread_mutex_unlock(_sharedMemoryRecordTreeMutex()); return allocedMemeory; } void ctRetain(void *memory) { struct CTAVLTreeNode *node = findCTAVLTreeNode(memory, _sharedMemoryRecordTree()); struct CTMemoryRecord *memoryRecord = (struct CTMemoryRecord *)node->value; pthread_mutex_lock(memoryRecord->memoryRecordMutex); memoryRecord->retainCount++; pthread_mutex_unlock(memoryRecord->memoryRecordMutex); } void ctRelease(void *memory) { struct CTAVLTreeNode *node = findCTAVLTreeNode(memory, _sharedMemoryRecordTree()); struct CTMemoryRecord *memoryRecord = (struct CTMemoryRecord *)node->value; pthread_mutex_lock(memoryRecord->memoryRecordMutex); memoryRecord->retainCount--; pthread_mutex_unlock(memoryRecord->memoryRecordMutex); if (memoryRecord->retainCount == 0) { if (memoryRecord->deallocMethod != 0) { memoryRecord->deallocMethod(memory); } deleteCTAVLTreeNode(memory, _sharedMemoryRecordTree()); free(memory); } } void _createMemoryRecordTree() { __memoryRecordTree = (struct CTAVLTreeRoot *)malloc(sizeof(struct CTAVLTreeRoot)); __memoryRecordTree->rootNode = 0; __memoryRecordTree->compare = 0; } struct CTAVLTreeRoot *_sharedMemoryRecordTree() { if (__memoryRecordTree == 0) { static pthread_once_t onceToken = PTHREAD_ONCE_INIT; pthread_once(&onceToken, _createMemoryRecordTree); } return __memoryRecordTree; } void _createMemoryRecordTreeMutex() { pthread_mutexattr_t mutexAttr; pthread_mutexattr_init(&mutexAttr); pthread_mutexattr_settype(&mutexAttr, PTHREAD_MUTEX_RECURSIVE); __memoryRecordTreeMutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(__memoryRecordTreeMutex, &mutexAttr); pthread_mutexattr_destroy(&mutexAttr); } pthread_mutex_t *_sharedMemoryRecordTreeMutex() { if (__memoryRecordTreeMutex == 0) { static pthread_once_t onceToken = PTHREAD_ONCE_INIT; pthread_once(&onceToken, _createMemoryRecordTreeMutex); } return __memoryRecordTreeMutex; }
0
#include <pthread.h> void pager_shutdown (struct pager *p) { pager_sync (p, 1); pager_flush (p, 1); pthread_mutex_lock (&p->interlock); p->pager_state = SHUTDOWN; ports_destroy_right (p); pthread_mutex_unlock (&p->interlock); }
1
#include <pthread.h> static pthread_mutex_t lock; static pthread_cond_t data_ready, thread_idle; static int x; static int factorial(int x) { if (x == 1) return 1; return x * factorial(x - 1); } static void * thread_main(void *arg) { pthread_mutex_lock(&lock); while (x >= 0) { if (x == 0) pthread_cond_wait(&data_ready, &lock); else { printf("%d! is %d\\n", x, factorial(x)); x = 0; pthread_cond_signal(&thread_idle); } } pthread_mutex_unlock(&lock); return (0); } int main(void) { pthread_t thread; int error, y; error = pthread_mutex_init(&lock, 0); if (error) { errno = error; err(1, "pthread_mutex_init"); } error = pthread_cond_init(&data_ready, 0); if (error) { errno = error; err(1, "pthread_cond_init(data_ready)"); } error = pthread_cond_init(&thread_idle, 0); if (error) { errno = error; err(1, "pthread_cond_init(thread_idle)"); } error = pthread_create(&thread, 0, thread_main, 0); if (error) { errno = error; err(1, "pthread_create"); } while (scanf("%d", &y) == 1) { if (y <= 0) { printf("Invalid value: %d\\n", y); continue; } pthread_mutex_lock(&lock); while (x != 0) pthread_cond_wait(&thread_idle, &lock); x = y; pthread_mutex_unlock(&lock); pthread_cond_signal(&data_ready); printf("%d is ready \\n", x); } pthread_mutex_lock(&lock); while (x != 0) pthread_cond_wait(&thread_idle, &lock); x = -1; pthread_mutex_unlock(&lock); pthread_cond_signal(&data_ready); error = pthread_join(thread, 0); if (error) { errno = error; err(1, "pthread_join"); } pthread_cond_destroy(&thread_idle); pthread_cond_destroy(&data_ready); pthread_mutex_destroy(&lock); return (0); }
0
#include <pthread.h> int memory[(2*320+1)]; int next_alloc_idx = 1; pthread_mutex_t m; int top; int index_malloc(){ int curr_alloc_idx = -1; pthread_mutex_lock(&m); if(next_alloc_idx+2-1 > (2*320+1)){ pthread_mutex_unlock(&m); curr_alloc_idx = 0; }else{ curr_alloc_idx = next_alloc_idx; next_alloc_idx += 2; pthread_mutex_unlock(&m); } return curr_alloc_idx; } void EBStack_init(){ top = 0; } int isEmpty() { if(top == 0) return 1; else return 0; } int push(int d) { int oldTop = -1, newTop = -1; newTop = index_malloc(); if(newTop == 0){ return 0; }else{ memory[newTop+0] = d; while (1) { oldTop = top; memory[newTop+1] = oldTop; if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){ return 1; } } } } void __VERIFIER_atomic_assert(int r) { __atomic_begin(); assert(!r || !isEmpty()); __atomic_end(); } void push_loop(){ int r = -1; int arg = __nondet_int(); while(1){ r = push(arg); __VERIFIER_atomic_assert(r); } } pthread_mutex_t m2; int state = 0; void* thr1(void* arg) { pthread_mutex_lock(&m2); switch(state) { case 0: EBStack_init(); state = 1; case 1: pthread_mutex_unlock(&m2); push_loop(); break; } return 0; } int main() { pthread_t t1,t2; pthread_create(&t1, 0, thr1, 0); pthread_create(&t2, 0, thr1, 0); return 0; }
1
#include <pthread.h> struct pmic_data { pthread_t pmic_thread; pthread_mutex_t pmic_mutex; pthread_cond_t pmic_condition; int threshold_reached; int temp_idx; int sensor_shutdown; struct sensor_info *sensor; } pmic_data; static void *pmic_uevent(void *data) { int err = 0; struct sensor_info *sensor = (struct sensor_info *)data; struct pollfd fds; int fd; char uevent[MAX_PATH] = {0}; char buf[MAX_PATH] = {0}; struct pmic_data *pmic = 0; if (0 == sensor || 0 == sensor->data) { msg("%s: unexpected NULL", __func__); return 0; } pmic = (struct pmic_data *) sensor->data; snprintf(uevent, MAX_PATH, TZ_TYPE, pmic->sensor->tzn); fd = open(uevent, O_RDONLY); if (fd < 0) { msg("Unable to open %s to receive notifications.\\n", uevent); return 0; }; while (!pmic->sensor_shutdown) { fds.fd = fd; fds.events = POLLERR|POLLPRI; fds.revents = 0; err = poll(&fds, 1, -1); if (err == -1) { msg("Error in uevent poll.\\n"); break; } read(fd, buf, sizeof(buf)); lseek(fd, 0, 0); dbgmsg("pmic uevent :%s", buf); pthread_mutex_lock(&(pmic->pmic_mutex)); pmic->threshold_reached = 1; pthread_cond_broadcast(&(pmic->pmic_condition)); pthread_mutex_unlock(&(pmic->pmic_mutex)); } close(fd); return 0; } void pm8821_interrupt_wait(struct sensor_info *sensor) { struct pmic_data *pmic; if (0 == sensor || 0 == sensor->data) { msg("%s: unexpected NULL", __func__); return; } pmic = (struct pmic_data *) sensor->data; if (sensor->interrupt_enable) { pthread_mutex_lock(&(pmic->pmic_mutex)); while (!pmic->threshold_reached) { pthread_cond_wait(&(pmic->pmic_condition), &(pmic->pmic_mutex)); } pmic->threshold_reached = 0; pthread_mutex_unlock(&(pmic->pmic_mutex)); } } int pm8821_setup(struct sensor_info *sensor) { int fd = -1; int sensor_count = 0; int tzn = 0; char name[MAX_PATH] = {0}; struct pmic_data *pmic = 0; if (sensor == 0) { msg("pm8821_tz:unexpected NULL"); return 0; } tzn = get_tzn(sensor->name); if (tzn < 0) { msg("No thermal zone device found in the kernel for sensor %s\\n", sensor->name); return sensor_count; } sensor->tzn = tzn; pmic = (struct pmic_data *) malloc(sizeof(struct pmic_data)); if (0 == pmic) { msg("%s: malloc failed", __func__); return sensor_count; } memset(pmic, 0, sizeof(pmic_data)); sensor->data = (void *) pmic; pmic->sensor = sensor; snprintf(name, MAX_PATH, TZ_TEMP, sensor->tzn); fd = open(name, O_RDONLY); if (fd < 0) { msg("%s: Error opening %s\\n", __func__, name); free(pmic); return sensor_count; } pmic->temp_idx = fd; sensor_count++; pthread_mutex_init(&(pmic->pmic_mutex), 0); pthread_cond_init(&(pmic->pmic_condition), 0); pmic->sensor_shutdown = 0; pmic->threshold_reached = 0; if (sensor->interrupt_enable) { pthread_create(&(pmic->pmic_thread), 0, pmic_uevent, sensor); } return sensor_count; } int pm8821_get_temperature(struct sensor_info *sensor) { struct pmic_data *pmic; int temp = CONV(-273); char buf[MAX_PATH] = {0}; if (0 == sensor || 0 == sensor->data) { msg("%s: unexpected NULL", __func__); return temp; } pmic = (struct pmic_data *) sensor->data; if (read(pmic->temp_idx, buf, sizeof(buf) - 1) != -1) temp = atoi(buf); lseek(pmic->temp_idx, 0, 0); return temp; } void pm8821_shutdown(struct sensor_info *sensor) { struct pmic_data *pmic; if (0 == sensor || 0 == sensor->data) { msg("%s: unexpected NULL", __func__); return; } pmic = (struct pmic_data *) sensor->data; pmic->sensor_shutdown = 1; if (sensor->interrupt_enable) pthread_join(pmic->pmic_thread, 0); free(pmic); }
0
#include <pthread.h> struct play_t { char fname[256]; off_t flen; off_t ldlen; int pos; int fi; int fo; }; static pthread_t tid_play; static pthread_t tid_load; static volatile int playing = 0; static volatile int loading = 0; static volatile int _pause = 0; static struct play_t play; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void lock(void) { pthread_mutex_lock(&mutex); } static void unlock(void) { pthread_mutex_unlock(&mutex); } static void do_wait(int no) { while( wait(0) != -1); playing = 0; } static char *getval(int fd, char *key, char *val) { int ch; char buff[1024]; int len = strlen(key); char *ret; while(1) { read(fd, buff, len); if(strchr(buff, key[0]) == 0 ) { continue; } } return ret; } void play_cmd(char *cmd) { lock(); if(play.fi != -1) { write(play.fi, cmd, strlen(cmd)); if(strcmp(cmd, "pause\\n") == 0) { _pause = !_pause; } } unlock(); } static int buffering(struct play_t *this) { struct stat st; off_t buff_len = this->flen*2/100; off_t pos = this->pos/100.0 * this->flen; stat(this->fname, &st); this->ldlen = st.st_size; if((this->ldlen - pos < buff_len) && (this->ldlen < this->flen)) { if(this->fi != -1) { if(!_pause) play_cmd("pause\\n"); } while((this->ldlen - pos < buff_len) && (this->ldlen < this->flen)) { stat(this->fname, &st); this->ldlen = st.st_size; usleep(100 * 1000); if(playing == 0) break; } if(this->fi != -1) { if(!_pause) play_cmd("pause\\n"); } } return 0; } static void *thr_play(void *arg) { struct play_t *this = arg; int fi[2]; int fo[2]; char *p,buff[1024]; this->pos = 0; this->ldlen = 0; this->fi = -1; this->fo = -1; buffering(this); pipe(fi); pipe(fo); signal(SIGCHLD, do_wait); if(fork() == 0) { dup2(fi[0], 0); dup2(fo[1], 1); close(fi[0]); close(fi[1]); close(fo[0]); close(fo[1]); close(2); execlp("mplayer", "mplayer", "-slave", "-quiet", this->fname, 0); exit(-1); } close(fi[0]); close(fo[1]); this->fi = fi[1]; this->fo = fo[0]; while(playing) { strcpy(buff, "get_percent_pos\\n"); lock(); if(!_pause) { write(fi[1], buff, strlen(buff)); memset(buff, 0, sizeof(buff)); read(fo[0], buff, sizeof(buff)); if(!strncmp(buff, "ANS_PERCENT_POSITION=", strlen("ANS_PERCENT_POSITION=") ) ) { p = strchr(buff, '='); this->pos = atoi(p+1); } } unlock(); if(this->pos == 100) break; buffering(this); usleep(100 * 1000); } close(fi[1]); close(fo[0]); remove(play.fname); return 0; } void trim(char *s) { char *p = s + strlen(s) - 1; while(p>=s && *p == ' ') { *p = 0; p++; } p = s; while(*p == ' ') p++; strcpy(s, p); } void play_start(char *tmp_file, off_t size) { strcpy(play.fname, tmp_file); play.flen = size; playing = 1; _pause = 0; pthread_create(&tid_play, 0, thr_play, &play); } void play_stop(void) { write(play.fi, "stop\\n", 5); pthread_join(tid_play, 0); playing = 0; } static void *thr_load(void *arg) { char *file = arg; char *tmp_file = "tmp"; struct stat st; int fd, fd_tmp; char buff[4*1024]; int len; file = strchr((char *)arg, '\\n'); if(file) *file = 0; file = arg; trim(file); fd = open(file, O_RDONLY); if(fd < 0) { printf("[%s]", file); perror("open"); } free(file); fd_tmp = open(tmp_file, O_WRONLY|O_CREAT|O_TRUNC, 0644); fstat(fd, &st); play_start(tmp_file, st.st_size); loading = 1; while(loading && (len = read(fd, buff, sizeof(buff))) >0 ) { len = write(fd_tmp, buff, len); } close(fd); close(fd_tmp); loading = 0; return 0; } void loadfile(char *file) { char *p; if(loading) { loading = 0; pthread_join(tid_load, 0); } if(playing) { play_stop(); } p = malloc(strlen(file)+1); strcpy(p, file); pthread_create(&tid_load, 0, thr_load, p); } int main(int argc, char **argv) { char cmd[100]; while(1) { printf("$>"); fgets(cmd, sizeof(cmd), stdin); if(!strncmp(cmd, "load", 4)) { loadfile(cmd + 4); } else if(!strcmp(cmd, "quit\\n")) { play_stop(); return 0; } else play_cmd(cmd); } }
1
#include <pthread.h> int x; pthread_mutex_t mutex; pthread_cond_t cond; void producer(void) { while(1) { pthread_mutex_lock(&mutex); int i; for(i=0;i<3-x;i++) { x++; printf("Producing:i=%d x=%d \\n",i,x); sleep(1); } if(x>=3) { pthread_cond_signal(&cond); printf("Producing complete %d\\n",x); } pthread_mutex_unlock(&mutex); printf("producer Unlock Mutex\\n"); sleep(1); } pthread_exit(0); } void consumer(void) { while(1) { pthread_mutex_lock(&mutex); while(x<3) { pthread_cond_wait(&cond,&mutex); printf("start consuming %d\\n",x); } if(x>0) { x--; printf(" consuming %d\\n",x); sleep(1); } pthread_mutex_unlock(&mutex); printf("consumer Unlock Mutex\\n"); } pthread_exit(0); } int main() { pthread_t id1,id2; int ret; ret = pthread_mutex_init(&mutex,0); if(ret!=0) { printf("pthread_mutex_init error\\n"); exit(0); } ret=pthread_cond_init(&cond,0); if(ret!=0) { printf("pthread_cond_init error\\n"); exit(0); } printf("x=[%d]\\n",x); ret = pthread_create(&id1,0,(void *)producer,0); if(ret!=0) { printf("Create pthread producer error\\n"); exit(0); } ret = pthread_create(&id2,0,(void *)consumer,0); if(ret!=0) { printf("Create pthread consumer, error\\n"); exit(0); } pthread_join(id1,0); pthread_join(id2,0); printf("Done\\n"); return 0; }
0
#include <pthread.h> int q[3]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 3) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 3); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[5]; int sorted[5]; void producer () { int i, idx; for (i = 0; i < 5; i++) { idx = findmaxidx (source, 5); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 5; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 5; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> { int *array; int length; int sum; } MyData; MyData mData; pthread_t myThread[5]; pthread_mutex_t mutex; void *threadWork(void *arg) { int offset = (int)arg; int j, sum = 0; int start, end; start = offset*mData.length; end = start + mData.length; for( j = start; j < end; j++ ) { sum += mData.array[j]; } printf("Thread id: %d, Sum calculated: %d\\n",offset, sum); pthread_mutex_lock(&mutex); mData.sum += sum; pthread_mutex_unlock(&mutex); pthread_exit((void*) 0); } int main() { void *status; int k; int *a = (int*)malloc(sizeof(int)*20*5); for( k = 0; k < 5*20; k++ ) { a[k] = k+1; } mData.length = 20; mData.array = a; mData.sum = 0; pthread_mutex_init(&mutex, 0); for( k = 0; k < 5; k++ ) { pthread_create(&myThread[k], 0, threadWork, (void*)k ); } for( k = 0; k < 5; k++ ) { pthread_join(myThread[k], &status); } printf("Total sum from threads = %d\\n", mData.sum); free(a); pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t* Forks; int* Thinkers_hunger; int N; void get_Lfork(int name) { if (name == 0) pthread_mutex_lock(Forks + N - 1); else pthread_mutex_lock(Forks + name - 1); } void get_Rfork(int name) { pthread_mutex_lock(Forks + name); } void put_Lfork(int name) { if (name == 0) pthread_mutex_unlock(Forks + N - 1); else pthread_mutex_unlock(Forks + name - 1); } void put_Rfork(int name) { pthread_mutex_unlock(Forks + name); } void* eat0(int* pName) { int name = *pName; while (Thinkers_hunger[name] > 0){ get_Lfork(name); get_Rfork(name); Thinkers_hunger[name]--; printf("Ph %d is eating %d sec, hunger left: %d\\n", name, 3, Thinkers_hunger[name]); sleep(3); put_Lfork(name); put_Rfork(name); printf("Ph %d is thinking %d sec\\n", name, 3); sleep(3); } printf("Ph %d is fed and now will only think\\n", name); } int main() { int Hunger, algo = 0, *Nums; pthread_t* P; while (1){ printf("Please, enter count of thinkers and their hunger:\\n"); scanf("%d%d", &N, &Hunger); if (N == 0) break; Forks = (pthread_mutex_t*)malloc(N * sizeof(pthread_mutex_t)); Thinkers_hunger = (int*)malloc(N * sizeof(int)); P = (pthread_t*)malloc(N * sizeof(pthread_t)); Nums = (int*)malloc(N * sizeof(int)); int i; for (i = 0; i < N; i++){ pthread_mutex_init(Forks + i, 0); Thinkers_hunger[i] = Hunger; Nums[i] = i; } for (i = 0; i < N; i++){ if (algo == 0) pthread_create(P + i, 0, (void * (*)(void *))eat0, Nums + i); else pthread_create(P + i, 0, (void * (*)(void *))eat1, Nums + i); } for (i = 0; i < N; i++){ pthread_join(P[i], 0); } for (i = 0; i < N; i++){ pthread_mutex_destroy(Forks + i); } free(Forks); free(Thinkers_hunger); free(P); free(Nums); printf("Now all thinkers are fed. Thank you!\\n"); } exit(0); }
1
#include <pthread.h> char _buffer[50][30]; int _nbmess = 0; int _arret_lecture=0; int _arret_tot = 0; pthread_cond_t _full_buff = PTHREAD_COND_INITIALIZER; pthread_cond_t _empty_buff = PTHREAD_COND_INITIALIZER; pthread_mutex_t _mut = PTHREAD_MUTEX_INITIALIZER; void * Ecriture(void * arg) { int index_ecriture = 0; while(1) { if(_arret_tot) { printf("Fin tâche Ecriture\\n"); pthread_exit(0); } pthread_mutex_lock(&_mut); while(_nbmess == 50) { pthread_cond_wait(&_full_buff, &_mut); } if(_arret_tot) { printf("Fin tâche Ecriture\\n"); pthread_exit(0); } sprintf(_buffer[index_ecriture],"il y a %d voitures",index_ecriture); _nbmess ++; index_ecriture = (index_ecriture+1)%50; pthread_cond_signal(&_empty_buff); pthread_mutex_unlock(&_mut); sleep(3); } } void * Lecture(void * arg) { int index_lecture = 0; while(1) { if(_arret_tot && _nbmess == 0) { printf("Fin tâche Lecture\\n"); pthread_exit(0); } pthread_mutex_lock(&_mut); while((_nbmess == 0 || _arret_lecture == 1) && !_arret_tot) { pthread_cond_wait(&_empty_buff, &_mut); } if(_arret_tot && _nbmess == 0) { printf("Fin tâche Lecture\\n"); pthread_exit(0); } if( _nbmess != 0) { printf("%s\\n",_buffer[index_lecture]); index_lecture = (index_lecture+1)%50; _nbmess --; pthread_cond_signal(&_full_buff); pthread_mutex_unlock(&_mut); sleep(1); } } } void * Supervision(void * arg) { int boucle; do { int reponse; boucle=1; fflush(stdin); scanf("%d",&reponse); switch(reponse){ case 1 :_arret_lecture=1;printf("********************\\n\\n\\tPausse affichage\\n\\n********************\\n");break; case 2 :printf("********************\\n\\n\\tReprise\\n\\n********************\\n");_arret_lecture=0;break; case 0 : _arret_tot = 1; printf("Fin tâche Supervision\\n"); pthread_cond_signal(&_empty_buff); pthread_cond_signal(&_full_buff); pthread_exit(0); default :break; } reponse=0; sleep(1); }while(boucle !=0); } int main(void) { pthread_t threadEcriture, threadLecture, threadSupervision; if(pthread_create(&threadEcriture,0,Ecriture,0)!=0) { perror("creation thread entrée"); exit(1); } if(pthread_create(&threadLecture,0,Lecture,0)!=0) { perror("creation thread entrée"); exit(1); } if(pthread_create(&threadSupervision,0,Supervision,0)!=0) { perror("creation thread entrée"); exit(1); } pthread_join(threadEcriture,0); pthread_join(threadLecture,0); pthread_join(threadSupervision,0); printf("Fin Main\\n"); return 0; }
0
#include <pthread.h> void main_constructor( void ) ; void main_destructor( void ) ; void __cyg_profile_func_enter( void *, void * ) ; void __cyg_profile_func_exit( void *, void * ) ; char* join3(char *s1, char *s2); pthread_mutex_t mut; void (*callback)() = 0; double register_function( void (*in_main_func)()) { callback = in_main_func; } void function_needing_callback() { if(callback != 0) callback(); } void main_constructor( void ) { } void main_deconstructor( void ) { } void __cyg_profile_func_enter( void *this, void *callsite ) { function_needing_callback(); pthread_mutex_lock(&mut); char* filename = ""; char pid[15]; sprintf(pid, "%d", syscall(SYS_gettid)); char tid[15]; sprintf(tid, "%d", getpid()); filename = join3(filename, tid); filename = join3(filename, "_"); filename = join3(filename, "trace.txt"); FILE *fp = fopen( filename, "a" ); if (fp == 0) exit(-1); fprintf(fp, "E%p\\n", (int *)this); fclose( fp ); pthread_mutex_unlock(&mut); } void __cyg_profile_func_exit( void *this, void *callsite ) { pthread_mutex_lock(&mut); char* filename = ""; char pid[15]; sprintf(pid, "%d", syscall(SYS_gettid)); char tid[15]; sprintf(tid, "%d", getpid()); filename = join3(filename, tid); filename = join3(filename, "_"); filename = join3(filename, "trace.txt"); FILE *fp = fopen( filename, "a" ); if (fp == 0) exit(-1); fprintf(fp, "X%p\\n", (int *)this); fclose( fp ); pthread_mutex_unlock(&mut); } char* join3(char *s1, char *s2) { char *result = malloc(strlen(s1)+strlen(s2)+1); if (result == 0) exit (1); strcpy(result, s1); strcat(result, s2); return result; }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[40]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, offset, len ; double mysum, *x, *y; offset = (int)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; pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { int i; double *a, *b; int status; pthread_attr_t attr; a = (double*) malloc (40*10000*sizeof(double)); b = (double*) malloc (40*10000*sizeof(double)); for (i=0; i<10000*40; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 10000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); struct timeval t1; struct timezone t2; gettimeofday(&t1,&t2); long start_time = t1.tv_sec*1000000+t1.tv_usec;; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<40;i++) { pthread_create( &callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<40;i++) { pthread_join( callThd[i], (void **)&status); } gettimeofday(&t1,&t2); long end_time = t1.tv_sec*1000000+t1.tv_usec;; long elapsed = end_time-start_time; printf ("\\nProdotto scalare = %f \\nTempo di esecuzione = %ld\\n\\n", dotstr.sum,elapsed); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t _locker = PTHREAD_MUTEX_INITIALIZER; static int _fd = STDERR_FILENO; static char _suffix[PATH_LEN]; char *format_datetime(const struct tm *datetime, const size_t bufflen, char *buff){ size_t len = DATETIME_LEN_NOSEPY < bufflen ? DATETIME_LEN_NOSEPY : bufflen; if (0 == datetime){ time_t timep; time(&timep); struct tm *datetime_temp = localtime(&timep); snprintf(buff, len, "%04d%02d%02d%02d%02d%02d", datetime_temp->tm_year + 1900, datetime_temp->tm_mon + 1, datetime_temp->tm_mday, datetime_temp->tm_hour, datetime_temp->tm_min, datetime_temp->tm_sec); }else{ snprintf(buff, len, "%04d%02d%02d%02d%02d%02d", datetime->tm_year + 1900, datetime->tm_mon + 1, datetime->tm_mday, datetime->tm_hour, datetime->tm_min, datetime->tm_sec); } *(buff + len) = '\\0'; return buff; } static int open_logfile(const char *path){ int result = 0; char *log_filename; log_filename = (char*)malloc(PATH_LEN); if (0 == log_filename){ result = 0 == errno ? ENOMEM : errno; printf("Error!File:%s,Line:%d.malloc memory is error.Errno:%d,Info:%s.", "mq_log.c", 58, result,strerror(result)); return result; } char datetime[DATETIME_LEN_NOSEPY]; format_datetime(0, DATETIME_LEN_NOSEPY, datetime); do{ result = snprintf(log_filename, PATH_LEN, "%s%s", path, datetime); if (-1 == result || PATH_LEN <= result){ result = 0 == errno ? ENOMEM : errno; printf("Error!File:%s,Line:%d.Errno:%d,Info:%s.", "mq_log.c", 70, result,strerror(result)); break; } if (0 > (_fd = open(log_filename, O_RDWR | O_CREAT | O_APPEND | O_SYNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |S_IWOTH))){ result = errno; _fd = STDERR_FILENO; printf("Error!File:%s,Line:%d.Errno:%d,Info:%s.", "mq_log.c", 79,result, strerror(result)); break; } result = 0; } while (0); free(log_filename); log_filename=0; return result; } void logger_close(){ fsync(_fd); close(_fd); _fd = STDERR_FILENO; } static void do_log(const char *message){ int result = 0; pthread_mutex_lock(&_locker); do{ if (_linesize <= _lines){ logger_close(); if (0 != (result = open_logfile(_suffix))){ _fd = STDERR_FILENO; printf("Error!File:%s,Line:%d.Errno:%d,Info:%s.", "mq_log.c", 106, result,strerror(result)); break; } _lines = 0; } int length = strlen(message); do{ result += write(_fd, message + result, length - result); } while (length != result); _lines++; } while (0); pthread_mutex_unlock(&_locker); return; } int logger_init(const char *path, const char *prefix, const int linesize,const int level){ } void log_info_recond(const char *format, ...){ } void log_warn_recond(const char *format, ...){ } void log_error_recond(const char *format, ...){ }
1
#include <pthread.h> extern pthread_mutex_t printf_lock; extern pthread_mutex_t setup_lock; extern pthread_mutex_t chairs_lock; extern sem_t TA_ready; extern sem_t TA_done; extern sem_t Student_register; extern int setupNotDone; extern int globalSeed; extern int occupied_chairs; extern int MAX_CHAIRS; extern int chairs[]; extern int front; extern int rear; int generateSomeTime(int, unsigned int*); void* Student(void* param) { unsigned int seed = globalSeed; globalSeed++; int SID = *((int*) param); printf("SID:%d summoned.\\n", SID); pthread_mutex_unlock(&setup_lock); while(1) { int time = generateSomeTime(1, &seed); printf("SID:%d will go program for %d seconds.\\n", SID, time); sleep(time); printf("SID:%d inteds to go to TA\\n", SID); pthread_mutex_lock(&chairs_lock); if (occupied_chairs<MAX_CHAIRS) { occupied_chairs++; rear++; rear = rear % MAX_CHAIRS; chairs[rear] = SID; printf("SID:%d waiting for TA\\n", SID); sem_post(&Student_register); pthread_mutex_unlock(&chairs_lock); sem_wait(&TA_ready); sem_wait(&TA_done); } else { pthread_mutex_unlock(&chairs_lock); printf("SID:%d did not find chairs.\\n", SID); } } pthread_exit(0); }
0
#include <pthread.h> int zwierzyna; int pozywienie; pthread_mutex_t pozywienie_m; pthread_mutex_t zwierzyna_m; int millisecons_sleep = 10; int rzut_kostka() { return rand() % 6 + 1; } void *mysliwy(void *ptr) { for(int i=1; i<=365; i++) { if (rzut_kostka() > rzut_kostka()) { pthread_mutex_lock(&zwierzyna_m); zwierzyna++; pthread_mutex_unlock(&zwierzyna_m); } pthread_mutex_lock(&pozywienie_m); if(pozywienie>0) { pozywienie--; pthread_mutex_unlock(&pozywienie_m); } else { (*((int*)ptr))--; pthread_mutex_unlock(&pozywienie_m); pthread_exit(0); } usleep(millisecons_sleep*1000); } pthread_exit(0); } void *kucharz(void *ptr) { for (int i=1;i<=365;i++) { int produkowac = 1; pthread_mutex_lock(&zwierzyna_m); if (zwierzyna > 0) { zwierzyna--; } else { produkowac = 0; } pthread_mutex_unlock(&zwierzyna_m); pthread_mutex_lock(&pozywienie_m); if (produkowac==1) { pozywienie+=rzut_kostka(); } if (pozywienie>0) { pozywienie--; pthread_mutex_unlock(&pozywienie_m); } else { (*((int*)ptr))--; pthread_mutex_unlock(&pozywienie_m); pthread_exit(0); } usleep(millisecons_sleep*1000); } pthread_exit(0); } int main(int argc, char *argv[]) { srand(time(0)); if(argc < 5) pthread_exit(0); int kucharze, mysliwi; sscanf(argv[1], "%d", &mysliwi); sscanf(argv[2], "%d", &kucharze); sscanf(argv[3], "%d", &zwierzyna); sscanf(argv[4], "%d", &pozywienie); pthread_mutex_init(&pozywienie_m, 0); pthread_mutex_init(&zwierzyna_m, 0); pthread_t *kuch, *mys; kuch = (pthread_t*)malloc(sizeof(pthread_t)*kucharze); mys = (pthread_t*)malloc(sizeof(pthread_t)*mysliwi); int k = kucharze; int m = mysliwi; for (int i=0;i<kucharze;i++) { pthread_create(&kuch[i], 0, kucharz, (void*)&k); } for (int i=0;i<mysliwi;i++) { pthread_create(&mys[i], 0, mysliwy, (void*)&m); } for (int i=0;i<kucharze;i++) { pthread_join(kuch[i], 0); } for (int i=0;i<mysliwi;i++) { pthread_join(mys[i], 0); } free(kuch); free(mys); pthread_mutex_destroy(&pozywienie_m); pthread_mutex_destroy(&zwierzyna_m); printf("KONIEC\\nil mysliwych: %d\\nil kucharzy: %d\\nil pozywienia: %d\\nil zwierzyny: %d\\n", m, k, pozywienie, zwierzyna); pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t log_lock = PTHREAD_MUTEX_INITIALIZER; static int log_use_syslog = 0; static void syslog_opened(void) { pthread_mutex_lock(&log_lock); log_use_syslog = 1; pthread_mutex_unlock(&log_lock); } static int is_syslog_opened(void) { int use_syslog; pthread_mutex_lock(&log_lock); use_syslog = log_use_syslog; pthread_mutex_unlock(&log_lock); return (use_syslog); } static void logutil_vmessage(int priority, const char *format, va_list ap) { char buffer[2048]; vsnprintf(buffer, sizeof buffer, format, ap); if (is_syslog_opened()) syslog(priority, "%s", buffer); else fprintf(stderr, "%s\\n", buffer); } void logutil_message(int priority, const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(priority, format, ap); ; } void logutil_error(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_ERR, format, ap); ; } void logutil_warning(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_WARNING, format, ap); ; } void logutil_notice(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_NOTICE, format, ap); ; } void logutil_info(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_INFO, format, ap); ; } void logutil_debug(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_DEBUG, format, ap); ; } void logutil_fatal(const char *format, ...) { va_list ap; __builtin_va_start((ap)); logutil_vmessage(LOG_ERR, format, ap); ; exit(2); } void logutil_syslog_open(const char *log_identifier, int option, int facility) { openlog(log_identifier, option, facility); syslog_opened(); }
0
#include <pthread.h> extern struct connect_handle connection[]; extern struct connection svr_conn[]; int get_connection_entry( int *conn_pos) { int rc = PBSE_NONE; int pos = 0; pthread_mutex_t *tmp_mut = 0; pthread_mutexattr_t t_attr; *conn_pos = -1; pthread_mutexattr_init(&t_attr); pthread_mutexattr_settype(&t_attr, PTHREAD_MUTEX_ERRORCHECK); for (pos = 0; pos < PBS_NET_MAX_CONNECTIONS; pos++) { lock_conn_table(); if (connection[pos].ch_mutex == 0) { if ((tmp_mut = (pthread_mutex_t *)calloc(1, sizeof(pthread_mutex_t))) == 0) rc = PBSE_MEM_MALLOC; else { connection[pos].ch_mutex = tmp_mut; pthread_mutex_init(connection[pos].ch_mutex, &t_attr); } } unlock_conn_table(); if (pthread_mutex_trylock(connection[pos].ch_mutex) != 0) { continue; } if (connection[pos].ch_inuse == FALSE) { *conn_pos = pos; break; } else pthread_mutex_unlock(connection[pos].ch_mutex); } if (*conn_pos == -1) { if (rc == PBSE_NONE) rc = PBSE_NOCONNECTS; } return(rc); } int socket_to_handle( int sock, int *local_errno) { int conn_pos = 0; int rc = PBSE_NONE; if ((rc = get_connection_entry(&conn_pos)) != PBSE_NONE) { *local_errno = PBSE_NOCONNECTS; } else { connection[conn_pos].ch_stream = 0; connection[conn_pos].ch_inuse = TRUE; connection[conn_pos].ch_errno = 0; connection[conn_pos].ch_socket = sock; connection[conn_pos].ch_errtxt = 0; pthread_mutex_unlock(connection[conn_pos].ch_mutex); pthread_mutex_lock(svr_conn[sock].cn_mutex); svr_conn[sock].cn_handle = conn_pos; pthread_mutex_unlock(svr_conn[sock].cn_mutex); rc = conn_pos; } return(rc); }
1
#include <pthread.h> int data[64]; sem_t blank_sem; sem_t data_sem; pthread_mutex_t lock1=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2=PTHREAD_MUTEX_INITIALIZER; void* product(void* arg) { static int i=0; while(1) { sem_wait(&blank_sem); pthread_mutex_lock(&lock1); if(i==64) { i=i%64; } data[i]=rand()%1234; ++i; sem_post(&data_sem); sleep(1); pthread_mutex_unlock(&lock1); } return 0; } void* consume(void* arg) { static int i=0; int value=0; while(1) { sem_wait(&data_sem); pthread_mutex_lock(&lock2); if(i==64) { i=i%64; } value=data[i]; ++i; sem_post(&blank_sem); pthread_mutex_unlock(&lock2); } return 0; } int main() { sem_init(&blank_sem,0,64); sem_init(&data_sem,0,0); pthread_t consumer1,producter1; pthread_t consumer2,producter2; pthread_create(&producter1,0,product,0); pthread_create(&producter2,0,product,0); pthread_create(&consumer1,0,consume,0); pthread_create(&consumer2,0,consume,0); pthread_join(consumer1,0); pthread_join(producter1,0); pthread_join(consumer2,0); pthread_join(producter2,0); sem_destroy(&blank_sem); sem_destroy(&data_sem); pthread_mutex_destroy(&lock1); pthread_mutex_destroy(&lock2); return 0; }
0
#include <pthread.h> int main_ConditionVariable(); static void* ConditionVariable_funcThread(void* a_pArg); static void ConditionVariable_wait(int timeoutMs); static int ConditionVariable_CreateThread(); static pthread_mutex_t m_mutex; static pthread_cond_t mCondition; static pthread_t vTreadID = 0; int ConditionVariable_CreateThread() { int vRetcode = 0; PrintfLn("CreateThread"); vRetcode = pthread_create(&vTreadID,0,ConditionVariable_funcThread,0); return vRetcode; } void* ConditionVariable_funcThread(void* a_pArg) { PrintfLn("funcThread_1 "); do { PrintfLn("funcThread_2"); ConditionVariable_wait( 20 * 1000); PrintfLn("funcThread_3"); } while(1); PrintfLn("funcThread_5"); return 0; } void ConditionVariable_wait(int timeoutMs) { struct timespec absTimeToWait; struct timeval now; int status = 0; gettimeofday(&now, 0); absTimeToWait.tv_sec = now.tv_sec + (timeoutMs/1000); absTimeToWait.tv_nsec = now.tv_usec*1000L + 1000000L*(timeoutMs%1000); if (absTimeToWait.tv_nsec > 1000000000) { ++absTimeToWait.tv_sec; absTimeToWait.tv_nsec -= 1000000000; } pthread_mutex_lock(&m_mutex); PrintfLn("ConditionVariable_wait_1"); status = pthread_cond_timedwait(&mCondition, &m_mutex, &absTimeToWait); PrintfLn("ConditionVariable_wait_2"); pthread_mutex_unlock(&m_mutex); } int main_ConditionVariable() { int ii = 0; char vBuffer[1024]; pthread_mutex_init(&m_mutex, 0); ConditionVariable_CreateThread(); usleep(100*100); for(ii = 0; ii < 60 ; ii++) { sprintf(vBuffer,"ConditionVariable_main : ii = %d",ii); PrintfLn(vBuffer); sleep(1); } PrintfLn("ConditionVariable_main_1 : "); pthread_cond_signal(&mCondition); PrintfLn("ConditionVariable_main_2 : "); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t db = PTHREAD_MUTEX_INITIALIZER; int rc = 0; int reading_time = 3, writing_time = 12,using_time = 18; void read_data_base(int reader_id) { printf("number %d reader is reading data base!\\n",reader_id); sleep(reading_time * (reader_id + 1)); } void use_data_read(int reader_id) { printf(" number %d reader is using data!\\n",reader_id); sleep(using_time * (reader_id + 1)); } void write_data_base(int writer_id) { printf(" number %d writer is writing data base!\\n",writer_id); sleep(writing_time); } void think_up_data(int writer_id) { printf(" number %d writer is thinking up data!\\n",writer_id); sleep(using_time); } void reading(int *reader_id) { while(1){ pthread_mutex_lock(&mutex); rc++; if(rc == 1) pthread_mutex_lock(&db); pthread_mutex_unlock(&mutex); read_data_base(*reader_id); pthread_mutex_lock(&mutex); rc--; if(rc == 0) pthread_mutex_unlock(&db); pthread_mutex_unlock(&mutex); use_data_read(*reader_id); } } void writing(int *writer_id) { while(1){ think_up_data(*writer_id); pthread_mutex_lock(&db); write_data_base(*writer_id); pthread_mutex_unlock(&db); } } int main() { int num; pthread_t *reader = (pthread_t*)malloc(sizeof(pthread_t)*5); int *reader_id = (int*)malloc(sizeof(int)*5); for(num=0;num<5;num++){ reader_id[num] = num; pthread_create(&reader[num],0,reading,(void*)(&reader_id[num])); } pthread_t *writer = (pthread_t*)malloc(sizeof(pthread_t)*2); int *writer_id = (int*)malloc(sizeof(int)*2); for(num=0;num<2;num++){ writer_id[num] = num; pthread_create(&writer[num],0,writing,(void*)(&writer_id[num])); } for(num=0;num<5;num++){ pthread_join(reader[num],0); } for(num=0;num<2;num++){ pthread_join(writer[num],0); } return 0; }
0
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing unlocking locks...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void * thr_fn(void *arg) { printf("thread started...\\n"); pause(); return (0); } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) err_exit(err, "can't install fork handlers"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); sleep(2); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) err_quit("fork failed"); else if (pid == 0) printf("child returned from fork\\n"); else printf("parent returned from fork\\n"); exit(0); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = pthread_getspecific(key); if(envbuf == 0) { envbuf = malloc(ARG_MAX); if(envbuf == 0) { pthread_mutex_unlock(&env_mutex); return 0; } pthread_setspecific(key, envbuf); printf("thread %ld set envbuf for key %d\\n", pthread_self(), key); } len = strlen(name); for(i = 0; environ[i] != 0; ++i) { if( (strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len + 1], ARG_MAX); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; } char *pathnames[] = {"PATH", "HOME"}; void *thr_fn(void *arg) { pthread_t tid = pthread_self(); long i = (long)arg; char *name = pathnames[i % 2]; printf("thread: %ld, i: %ld, pathname: %s, env: %s\\n", tid, i, name, getenv(name)); return (void *)0; } int main(void) { long i; pthread_t tid; printf("support multi threads...\\n"); for(i = 0; i < 10; ++i) { pthread_create(&tid, 0, thr_fn, (void *)i); } while(1) sleep(1); return 0; }
0
#include <pthread.h> struct info { int * BUFFER_P; sem_t * s; pthread_mutex_t * bf_mutex; pthread_cond_t * bf_cond; int * full_P; }; void * producer_data(void * P); void * consumer_data(void * C); int fibonacci_number(int ant, int prox); int search_place_insert(int * BUFFER); int search_place_remove(int * BUFFER); void init_buffer(int * BUFFER); void is_prime(int n); int main(int argc, char * argv[]) { int * BUFFER; int full = 0; pthread_t producer_t, consumer_t; pthread_mutex_t buffer_full_mutex; pthread_cond_t buffer_full_cond = (pthread_cond_t) PTHREAD_COND_INITIALIZER; sem_t s; info_t i; BUFFER = (int*) malloc(5 * sizeof(int)); init_buffer(BUFFER); pthread_mutex_init(&buffer_full_mutex, 0); sem_init(&s, 0, 1); i.BUFFER_P = BUFFER; i.bf_mutex = &buffer_full_mutex; i.bf_cond = &buffer_full_cond; i.full_P = &full; i.s = &s; pthread_create(&producer_t, 0, producer_data, (void*) &i); pthread_create(&consumer_t, 0, consumer_data, (void*) &i); pthread_join(producer_t, 0); pthread_join(consumer_t, 0); return 0; } void * producer_data(void * P) { info_t p = *(info_t*) P; int r, ant = 0, prox = 0, place = 0, cont = 0; while(cont < 25) { pthread_mutex_lock(p.bf_mutex); if(*p.full_P == 5) pthread_cond_wait(p.bf_cond, p.bf_mutex); pthread_mutex_unlock(p.bf_mutex); r = fibonacci_number(ant, prox); ant = prox; prox = r; sem_wait(p.s); place = search_place_insert(p.BUFFER_P); if(place != -1) { p.BUFFER_P[place] = r; printf("PRODUTOR -> Produzi o numero %d.\\n", r); *p.full_P += 1; cont++; } sem_post(p.s); pthread_cond_signal(p.bf_cond); } return 0; } void * consumer_data(void * C) { info_t c = *(info_t*) C; int aux, n, cont = 0; while(cont < 25) { pthread_mutex_lock(c.bf_mutex); if(*c.full_P == 0) pthread_cond_wait(c.bf_cond, c.bf_mutex); pthread_mutex_unlock(c.bf_mutex); aux = search_place_remove(c.BUFFER_P); sem_wait(c.s); if(aux != -1) { n = c.BUFFER_P[aux]; c.BUFFER_P[aux] = -1; *c.full_P -= 1; cont++; } sem_post(c.s); pthread_cond_signal(c.bf_cond); is_prime(n); } return 0; } int fibonacci_number(int ant, int prox) { if(ant == 0 && prox == 0) return 1; else return ant + prox; } int search_place_insert(int * BUFFER) { int i; for(i = 0; i < 5; i++) if(BUFFER[i] == -1) return i; return -1; } int search_place_remove(int * BUFFER) { int i; for(i = 0; i < 5; i++) if(BUFFER[i] != -1) return i; return -1; } void init_buffer(int * BUFFER) { int i; for(i = 0; i < 5; i++) BUFFER[i] = -1; } void show_buffer(int * BUFFER) { int i; for(i = 0; i < 5; i++) printf("[ %d ] ", BUFFER[i]); printf("\\n"); } void is_prime(int n) { int cont = 0, i; for(i = 1; i <= n; i++) if(n % i == 0) cont++; if(cont == 2) printf("CONSUMIDOR -> Consumi o numero %d e ele e primo!\\n", n); else printf("CONSUMIDOR -> Consumi o numero %d e ele nao e primo!\\n", n); }
1
#include <pthread.h> void *customerMaker(); void *barberShop(); void *waitingRoom(); void checkQueue(); pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER; int returnTime=5,current=0, sleeping=0, iseed; int main(int argc, char *argv[]) { iseed=time(0); srand(iseed); pthread_t barber,customerM,timer_thread; pthread_attr_t barberAttr, timerAttr; pthread_attr_t customerMAttr; pthread_attr_init(&timerAttr); pthread_attr_init(&barberAttr); pthread_attr_init(&customerMAttr); printf("\\n"); pthread_create(&customerM,&customerMAttr,customerMaker,0); pthread_create(&barber,&barberAttr,barberShop,0); pthread_join(barber,0); pthread_join(customerM,0); return 0; } void *customerMaker() { int i=0; printf("*Customer Maker Created*\\n\\n"); fflush(stdout); pthread_t customer[6 +1]; pthread_attr_t customerAttr[6 +1]; while(i<(6 +1)) { i++; pthread_attr_init(&customerAttr[i]); while(rand()%2!=1) { sleep(1); } pthread_create(&customer[i],&customerAttr[i],waitingRoom,0); } pthread_exit(0); } void *waitingRoom() { pthread_mutex_lock(&queue_mutex); checkQueue(); sleep(returnTime); waitingRoom(); } void *barberShop() { int loop=0; printf("The barber has opened the store.\\n"); fflush(stdout); while(loop==0) { if(current==0) { printf("\\tThe shop is empty, barber is sleeping.\\n"); fflush(stdout); pthread_mutex_lock(&sleep_mutex); sleeping=1; pthread_cond_wait(&barberSleep_cond,&sleep_mutex); sleeping=0; pthread_mutex_unlock(&sleep_mutex); printf("\\t\\t\\t\\tBarber wakes up.\\n"); fflush(stdout); } else { printf("\\t\\t\\tBarber begins cutting hair.\\n"); fflush(stdout); sleep((rand()%20)/5); current--; printf("\\t\\t\\t\\tHair cut complete, customer leaving store.\\n"); pthread_cond_signal(&barberWorking_cond); } } pthread_exit(0); } void checkQueue() { current++; printf("\\tCustomer has arrived in the waiting room.\\t\\t\\t\\t\\t\\t\\t%d Customers in store.\\n",current); fflush(stdout); printf("\\t\\tCustomer checking chairs.\\n"); fflush(stdout); if(current<6) { if(sleeping==1) { printf("\\t\\t\\tBarber is sleeping, customer wakes him.\\n"); fflush(stdout); pthread_cond_signal(&barberSleep_cond); } printf("\\t\\tCustomer takes a seat.\\n"); fflush(stdout); pthread_mutex_unlock(&queue_mutex); pthread_mutex_lock(&wait_mutex); pthread_cond_wait(&barberWorking_cond,&wait_mutex); pthread_mutex_unlock(&wait_mutex); return; } if(current>=6) { printf("\\t\\tAll chairs full, leaving store.\\n"); fflush(stdout); current--; pthread_mutex_unlock(&queue_mutex); return; } }
0
#include <pthread.h> pthread_mutex_t turno; pthread_mutex_t mutex; pthread_mutex_t db; int rc = 0; void* reader(void *arg); void* writer(void *arg); void read_data_base(); void use_data_read(); void think_up_data(); void write_data_base(); int main() { pthread_mutex_init(&mutex, 0); pthread_mutex_init(&db, 0); pthread_mutex_init(&turno, 0); pthread_t r[20], w[10]; int i; int *id; for (i = 0; i < 20 ; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&r[i], 0, reader, (void *) (id)); } for (i = 0; i< 10; i++) { id = (int *) malloc(sizeof(int)); *id = i; pthread_create(&w[i], 0, writer, (void *) (id)); } pthread_join(r[0],0); return 0; } void* reader(void *arg) { int i = *((int *) arg); while(1) { pthread_mutex_lock(&turno); pthread_mutex_lock(&mutex); rc = rc + 1; if (rc == 1) { pthread_mutex_lock(&db); } pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&turno); read_data_base(i); pthread_mutex_lock(&mutex); rc = rc - 1; if (rc == 0) { pthread_mutex_unlock(&db); } pthread_mutex_unlock(&mutex); use_data_read(i); } pthread_exit(0); } void* writer(void *arg) { int i = *((int *) arg); while(1) { think_up_data(i); pthread_mutex_lock(&turno); pthread_mutex_lock(&db); write_data_base(i); pthread_mutex_unlock(&db); pthread_mutex_unlock(&turno); } pthread_exit(0); } void read_data_base(int i) { printf("Leitor %d está lendo os dados! Número de leitores = %d \\n", i,rc); sleep( rand() % 5); } void use_data_read(int i) { printf("Leitor %d está usando os dados lidos!\\n", i); sleep(rand() % 5); } void think_up_data(int i) { printf("Escritor %d está pensando no que escrever!\\n", i); sleep(rand() % 5); } void write_data_base(int i) { printf("Escritor %d está escrevendo os dados!\\n", i); sleep( rand() % 5); }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo * foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--fp->f_count == 0) { idx = (((unsigned long)fp)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
0
#include <pthread.h> char __resource[32 + 1]; unsigned long __resource_len = 0; unsigned long __reader_count = 0; pthread_mutex_t __write_mutex; pthread_mutex_t __read_mutex; void write_resource(unsigned long tid) { char ch = 'a' + __resource_len % 26; __resource[__resource_len] = ch; ++__resource_len; printf("[ Writer %lu ] Writing..., len = %lu\\n", tid, __resource_len); } void read_resource(unsigned long tid) { printf("[ Reader %lu ] %s\\n", tid, __resource); } void* writer(void* thread_id) { unsigned long tid = (unsigned long)thread_id; pthread_mutex_lock(&__write_mutex); while (__resource_len < 32) { write_resource(tid); pthread_mutex_unlock(&__write_mutex); sleep(0); pthread_mutex_lock(&__write_mutex); } pthread_mutex_unlock(&__write_mutex); pthread_exit(0); } void* reader(void* thread_id) { unsigned long tid = (unsigned long)thread_id; while (__resource_len < 32) { pthread_mutex_lock(&__read_mutex); ++__reader_count; if (__reader_count == 1) { pthread_mutex_lock(&__write_mutex); } pthread_mutex_unlock(&__read_mutex); read_resource(tid); pthread_mutex_lock(&__read_mutex); --__reader_count; if (__reader_count == 0) { pthread_mutex_unlock(&__write_mutex); } pthread_mutex_unlock(&__read_mutex); sleep(0); } pthread_exit(0); } int main() { pthread_mutex_init(&__write_mutex, 0); pthread_mutex_init(&__read_mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_t writers[4], readers[8]; for (unsigned long i = 0; i < 4; ++i) { pthread_create(&writers[i], &attr, writer, (void*)i); } for (unsigned long i = 0; i < 8; ++i) { pthread_create(&readers[i], &attr, reader, (void*)i); } for (unsigned long j = 0; j < 4; ++j) { pthread_join(writers[j], 0); } for (unsigned long k = 0; k < 8; ++k) { pthread_join(readers[k], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&__write_mutex); pthread_mutex_destroy(&__read_mutex); pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_mutex_t tenedor[5]; sem_t S; void pensar(int i) { printf("Filosofo %d pensando...\\n",i); usleep(random() % 50000); } void comer(int i) { printf("Filosofo %d comiendo...\\n",i); usleep(random() % 50000); } void tomar_tenedores(int i) { pthread_mutex_lock(&(tenedor[i])); sleep(1); pthread_mutex_lock(&(tenedor[(i+1)%5])); } void dejar_tenedores(int i) { pthread_mutex_unlock(&(tenedor[i])); pthread_mutex_unlock(&(tenedor[(i+1)%5])); } void *filosofo(void *arg) { int i = *(int*)arg; for (;;) { sem_wait(&S); tomar_tenedores(i); comer(i); dejar_tenedores(i); sem_post(&S); pensar(i); } } int main () { int args[5]; pthread_t th[5]; int i; sem_init(&S, 0, 4); for (i=0;i<5;i++) pthread_mutex_init(&tenedor[i], 0); for (i=0;i<5;i++) { args[i] = i; pthread_create(&th[i], 0, filosofo, &args[i]); } pthread_join(th[0], 0); return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex; static pthread_mutexattr_t mta; static void my_init_hook (void); static void *my_malloc_hook (size_t, const void *); static void my_free_hook (void*, const void *); static void *my_realloc_hook (void*, size_t, const void*); void (*__malloc_initialize_hook) (void) = my_init_hook; static void *old_malloc_hook; static void *old_free_hook; static void *old_realloc_hook; static FILE *log_file; static void ensure_log_file (void) { char filename[100]; if (log_file) return; snprintf (filename, sizeof (filename), "mh-%d.log", getpid()); log_file = fopen (filename, "w"); } static void my_init_hook (void) { old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; old_realloc_hook = __realloc_hook; __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; __realloc_hook = my_realloc_hook; pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init (&mutex, &mta); } static void * my_malloc_hook (size_t size, const void *caller) { void *result; pthread_mutex_lock (&mutex); __malloc_hook = old_malloc_hook; __free_hook = old_free_hook; __realloc_hook= old_realloc_hook; ensure_log_file (); fprintf(log_file, "malloc\\n"); fflush(log_file); result = malloc (size); old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; old_realloc_hook= __realloc_hook; if (result) fprintf (log_file,"%p %lu\\n", result, size); else fprintf (log_file,"%d %lu\\n", 0, size); fflush(log_file); __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; __realloc_hook= my_realloc_hook; pthread_mutex_unlock (&mutex); return result; } static void * my_realloc_hook (void *ptr, size_t size, const void *caller) { void *result; pthread_mutex_lock (&mutex); __malloc_hook = old_malloc_hook; __free_hook = old_free_hook; __realloc_hook= old_realloc_hook; ensure_log_file (); fprintf(log_file, "realloc\\n"); fflush(log_file); result = realloc (ptr, size); old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; old_realloc_hook= __realloc_hook; if (ptr && result) fprintf (log_file,"%p %p %lu\\n", ptr, result, size); else if (ptr) fprintf (log_file,"%p %d %lu\\n", ptr, 0, size); else if (result) fprintf (log_file,"%d %p %lu\\n", 0, result, size); else fprintf (log_file,"%d %d %lu\\n", 0, 0, size); fflush(log_file); __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; __realloc_hook= my_realloc_hook; pthread_mutex_unlock (&mutex); return result; } static void my_free_hook (void *ptr, const void *caller) { pthread_mutex_lock (&mutex); __malloc_hook = old_malloc_hook; __free_hook = old_free_hook; __realloc_hook= old_realloc_hook; ensure_log_file (); fprintf(log_file, "free\\n"); fflush(log_file); free (ptr); old_malloc_hook = __malloc_hook; old_free_hook = __free_hook; old_realloc_hook= __realloc_hook; if (ptr) fprintf (log_file,"%p\\n", ptr); else fprintf (log_file,"%d\\n", 0); fflush(log_file); __malloc_hook = my_malloc_hook; __free_hook = my_free_hook; __realloc_hook= my_realloc_hook; pthread_mutex_unlock (&mutex); }
1
#include <pthread.h> int auti_na_mostu = 0; int smjer_most = 2; int *smjer_auta; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t uvjet = PTHREAD_COND_INITIALIZER; void popniSeNaMost (int smjer) { pthread_mutex_lock(&m); while ((auti_na_mostu == 3) || ((auti_na_mostu > 0) && (smjer_most != smjer))) pthread_cond_wait(&uvjet, &m); auti_na_mostu++; smjer_most = smjer; pthread_mutex_unlock(&m); return; } void sidjiSaMosta (int smjer) { pthread_mutex_lock(&m); auti_na_mostu--; pthread_cond_broadcast(&uvjet); pthread_mutex_unlock(&m); return; } void *Auto (void *thread_id) { int id, moj_smjer; id = *(int *)thread_id; moj_smjer = smjer_auta[id]; if (moj_smjer == 0) printf("Auto %d čeka na prelazak preko mosta, smjer: lijevo\\n", id+1); else printf("Auto %d čeka na prelazak preko mosta, smjer: desno\\n", id+1); popniSeNaMost(moj_smjer); printf("Auto %d prelazi most\\n", id+1); sleep(1); sidjiSaMosta(moj_smjer); printf("Auto %d je prešao most.\\n", id+1); return 0; } int main (int argc, char *argv[]) { pthread_t *thread; int *thread_id; int i, koliko, x; koliko = atoi(argv[1]); printf("Broj auta: %d\\n", koliko); sleep(1); thread_id = (int *) malloc(sizeof(int)*koliko); thread = (pthread_t *) malloc(sizeof(pthread_t)*koliko); smjer_auta = (int *) malloc(sizeof(int)*koliko); srand(time(0)); for (i = 0; i < koliko; i++) { thread_id[i] = 0; x = rand() % 2; smjer_auta[i] = x; } for (i = 0; i < koliko; i++) { thread_id[i] = i; if (pthread_create(&thread[i], 0, Auto, ((void *)&thread_id[i]))) { printf("Ne može se stvoriti nova dretva\\n"); exit(1); } usleep(500000); } for (i = 0; i < koliko; i++) { pthread_join(thread[i], 0); } printf("Svi su auti prešli preko mosta, kraj programa\\n"); free(thread_id); free(thread); free(smjer_auta); return 0; }
0
#include <pthread.h> struct node { struct sockaddr_in address; long port; int del; }; struct node nodeList[10]; struct hubmsg_t { int mtype; long port; }; struct listmsg_t { int mtype; struct node nodeList[10]; }; struct listmsg_t listmsg; struct nodemsg_t { int mtype; char name[4000]; long from; }; int num = 0; char filename[128]; long from; int get; pthread_mutex_t mutexFrom = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexGet = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condGet = PTHREAD_COND_INITIALIZER; void *handleFile (void* arg) { int no = *((int *)arg); struct nodemsg_t nodemsg; struct nodemsg_t recm; int socknode, len, i, j, f; while(1) { socknode = socket(AF_INET, SOCK_STREAM, 0); if (socknode<0) { perror("[HIVE] Error creating:"); } printf("Created sock...\\n"); listmsg.nodeList[no].address.sin_port = htons(listmsg.nodeList[no].port); if (connect(socknode, (struct sockaddr*) &listmsg.nodeList[no].address, sizeof(struct sockaddr)) < 0) { printf("[HIVE] Connect error at %d, %s :: %d :\\n",no, inet_ntoa(listmsg.nodeList[no].address.sin_addr), listmsg.nodeList[no].address.sin_port); perror(":"); break; } printf("[HIVE] Connected to [%d] %s : %ld\\n", no, inet_ntoa(listmsg.nodeList[no].address.sin_addr),listmsg.nodeList[no].port); nodemsg.mtype = 4; nodemsg.from = -1; strcpy(nodemsg.name,filename); pthread_mutex_lock(&mutexFrom); if (from >= 0) { nodemsg.from = from; from = from + 100; } pthread_mutex_unlock(&mutexFrom); if (nodemsg.from < 0) { close(socknode); return; } i = send(socknode, &nodemsg, sizeof(struct nodemsg_t), 0); if (i<0) { perror("[HIVE] can't send to node :"); break; } printf("[HIVE] Sent to node.\\n"); i = recv(socknode, &recm, sizeof(struct nodemsg_t), 0); if (i<0) { printf("Error when downloading from %d. >:(\\n",i); break; } printf("[HIVE] Got from bee (node).\\n"); if (recm.from == 0) { pthread_mutex_lock(&mutexFrom); from = -1; pthread_mutex_unlock(&mutexFrom); close(socknode); return; } pthread_mutex_lock(&mutexGet); while (get > 0) pthread_cond_wait(&condGet, &mutexGet); get = 1; f = open(filename, O_WRONLY); if (f < 0) { printf("[HIVE] Cannot open file. %d\\n", no); break; } if (lseek(f, nodemsg.from, 0) < 0) { printf("[HIVE] Can't seek in file.%d\\n",no); break; } if (write(f, recm.name, recm.from) != recm.from) { printf("[HIVE] Can't write properly in file.%d\\n",no); break; } close(f); get = 0; pthread_cond_broadcast(&condGet); pthread_mutex_unlock(&mutexGet); close(socknode); sleep(1); } } int main() { struct sockaddr_in hub_addr; int sockhub; int len, i; struct hubmsg_t hubmsg; struct nodemsg_t nodemsg; sockhub = socket(AF_INET, SOCK_STREAM, 0); if (sockhub<0) { perror("[HIVE] Error creating socket:"); } hub_addr.sin_family = AF_INET; hub_addr.sin_addr.s_addr = INADDR_ANY; hub_addr.sin_port = htons(1026); if (connect(sockhub, (struct sockaddr*) &hub_addr, sizeof(struct sockaddr))<0) { perror("[HIVE] Connect error:"); } hubmsg.mtype = 2; hubmsg.port = -1; printf("[HIVE] Created request...\\n"); i = send(sockhub, &hubmsg, sizeof(struct hubmsg_t), 0); if (i<0) perror("[HIVE] can't send to hub :"); printf("[HIVE] Sent.\\n"); i = recv(sockhub, &listmsg, sizeof(struct listmsg_t), 0); if (i<0) perror("[HIVE] can't recv from hub :"); printf("[HIVE] Got message.\\n"); *((struct node*)nodeList) = *((struct node*)listmsg.nodeList); printf("[HIVE] Stored list locally.\\n"); i = 0; printf("[HIVE] List of available bees:\\n"); while (listmsg.nodeList[i].address.sin_port != 0) { printf("\\t[%d] %s : %ld\\n", i+1, inet_ntoa(listmsg.nodeList[i].address.sin_addr),listmsg.nodeList[i].port); i = i + 1; } char files[30]; strcpy(files,"ls -mB ~/Facultate/PPN/Torrent/source"); printf("[HIVE] Available files:\\n"); system(files); num = i; printf("%d Bees. \\nPlease enter the name of the file you want to download:\\n", num); gets(filename); int f; f = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0777); if (f < 0) { printf("[HIVE] Couldn't create %s\\n",filename); return 1; } close(f); struct sockaddr_in address; int sock; pthread_t thr[num]; i = 0; while (i < num && listmsg.nodeList[i].address.sin_port != 0) { if (pthread_create(&thr[i], 0, handleFile, &i) != 0) { printf("[HIVE] Error creating thread %d.\\n",i); } sleep(1); i = i + 1; } i = 0; while (i < num && listmsg.nodeList[i].address.sin_port != 0) { pthread_join(thr[i], 0); i=i + 1; } printf("Well, I tried.\\n"); char s[1]; gets(s); i = 0; close(sockhub); return 0; }
1
#include <pthread.h> static pthread_cond_t pwait = PTHREAD_COND_INITIALIZER; static pthread_mutex_t plock = PTHREAD_MUTEX_INITIALIZER; static int N; static int nsecs = 2; int *forks; int isAvailable(int i) { if(forks[i] && forks[(i+1) % N]) return 1; else return 0; } void takeFork(int i) { forks[i] = 0; forks[(i+1) % N] = 0; } void putFork(int i) { forks[i] = 1; forks[(i+1) % N] = 1; } void thinking(int i, int nsecs) { printf("philosopher %d is thinking\\n", i); sleep(nsecs); } void eating(int i, int nsecs) { printf("philosopher %d is eating\\n", i); sleep(nsecs); } void *philosopher(void *arg) { int i = (int)arg; while(1) { thinking(i, nsecs); pthread_mutex_lock(&plock); while(!isAvailable(i)){ pthread_cond_wait(&pwait, &plock); } takeFork(i); pthread_mutex_unlock(&plock); eating(i, nsecs); putFork(i); pthread_cond_broadcast(&pwait); } } int main(int argc, const char *argv[]) { int err; pthread_t tid[20]; if((argc != 2 && argc != 4) || (argc == 4 && (strcmp(argv[2], "-t") != 0))){ err_quit("usage: philosopher_th <N> [-t <time>]"); } N = atoi(argv[1]); if(N < 2 || N > 20){ err_quit("N outranged!"); } if(argc == 4){ nsecs = atoi(argv[3]); } forks = (int *)malloc(N * sizeof(int)); for(int i = 0; i < N; ++i) forks[i] = 1; for(int i = 0; i < N; ++i){ err = pthread_create(&tid[i], 0, philosopher, (void*)i); if(err != 0){ err_quit("can't create thread\\n"); } } for(int i = 0; i< N; ++i){ pthread_join(tid[i], 0); } return 0; }
0
#include <pthread.h> void *allocate_small(size_t size) { void *block; pthread_mutex_lock(&g_global_lock); if (g_book_keeper.small.head == 0) { g_book_keeper.small.head = allocate_new_zone(SMALL_MAX); divide_zone((void*)&(g_book_keeper.small.head), (void*)&(g_book_keeper.small.tail), SMALL_MAX); } block = allocate_new_block(size, &(g_book_keeper.small)); pthread_mutex_unlock(&g_global_lock); return (block); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int recordList[1000]; int result = 0; int start; int end; }t_range; void* compute_sum(void* range) { t_range r = *((t_range*) range); int i; int partialSum = 0; for (i = r.start ; i < r.end ; i++) { partialSum += recordList[i]; } pthread_mutex_lock( &mutex ); result += partialSum; pthread_mutex_unlock( &mutex ); return 0; } int main(int argc, char* argv[]) { int i; pthread_t thread1; pthread_t thread2; t_range r1 = {0, 1000/2}; t_range r2 = {1000/2, 1000}; for (i = 0 ; i < 1000 ; i++) { recordList[i] = rand() % 101 + 1; } pthread_create(&thread1, 0, compute_sum, (void*) &r1); pthread_create(&thread2, 0, compute_sum, (void*) &r2); pthread_join(thread1, 0); pthread_join(thread2, 0); result = result / 1000; printf("Result = %d\\n", result); return 0; }
0
#include <pthread.h> unsigned long long* arrayptr; int thread_no; }arg; const unsigned long long maxSize =200000; pthread_mutex_t lock; void init_emptyAry(void *ptr); void solve_problem(void *ptr); pthread_mutex_t lock; int main(){ pthread_t threadArray[16]; arg lowOrdInter[16]; unsigned long long j=0; int i= 0; int answer = 0; unsigned long long* otherarray= 0; otherarray= (unsigned long long*)malloc(maxSize * sizeof(unsigned long long)); for(i=0 ; i<16;i++){ lowOrdInter[i].thread_no = i; lowOrdInter[i].arrayptr=&otherarray[0]; } for( i=0; i<16; i++){ pthread_create(&threadArray[i], 0,(void *) &init_emptyAry, (void *) &lowOrdInter[i]); } printf("%llu \\n", otherarray[1000]); for(i = 0; i<16; i++){ pthread_join(threadArray[i], 0); } for( i=0; i<16; i++){ pthread_create(&threadArray[i], 0,(void *) &solve_problem, (void *) &lowOrdInter[i]); } for(i = 0; i<16; i++){ pthread_join(threadArray[i], 0); } FILE *ofp; char outputfilename[]="output.txt"; ofp = fopen(outputfilename,"w"); if(ofp==0){ fprintf(stderr,"can't open output file\\n"); return 1; } for (j = 0; j<(maxSize/2); j++){ fprintf(ofp, "%llu %llu \\n",j , otherarray[j]); } return 0; } void init_emptyAry(void *ptr){ arg *LOI; LOI = (arg *) ptr; int i=0; for(i=LOI->thread_no; i< maxSize; i+=16){ LOI->arrayptr[i]=0; } } void solve_problem(void* ptr){ arg *LOI; LOI = (arg *) ptr; unsigned long long i, j; unsigned long long value; for (i = 2+LOI->thread_no; i <= maxSize; i+=16){ for (j = i; j <= i*(i - 1); j++){ if ((i+j) % (i * j) == 0){ value = (i+j) / (i * j); printf("%llu %llu \\n" , value, LOI->thread_no); pthread_mutex_lock(&lock); LOI->arrayptr[value]++; pthread_mutex_unlock(&lock); if(LOI->arrayptr[value]>1000){ printf("Answer: %llu %llu \\n", value , LOI->arrayptr[value]); return; } } } } }
1
#include <pthread.h> int sockfd; int newsockfd[10]; int clients; char inputbuffer[256]; char outputbuffer[256]; int noofoutputbytes; int noofinputbytes; char newinput; char newoutput; char transclient; char recvingdata; pthread_t clithread; pthread_t inputthread; pthread_t outputthread; pthread_mutex_t mutexinput = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexoutput= PTHREAD_MUTEX_INITIALIZER; void broadcastData() { int i=0; int pid; int n; while(i< clients) { pid = fork(); if( pid == 0) { n = write(newsockfd[i] , outputbuffer , noofoutputbytes); if(n< 0) { printf("unable write"); } exit(0); } if(pid < 0) { printf("couldnot fork"); } else { i++; } } } void *acceptData(void *ptr) { int sock = *(int *)ptr; int n; int i; char tempbuff[256]; while(1) { bzero(tempbuff , 255); n = read(sock,tempbuff,255); if ( n< 0) { continue; } while(newinput !=0) { } pthread_mutex_lock(&mutexinput); newinput = 1; bcopy(tempbuff ,inputbuffer , 255); noofinputbytes = n; pthread_mutex_unlock(&mutexinput); } } void *acceptClient(void *ptr) { int clilen; int tempsock; int iret; int n; int tosend = 0; pthread_t threads[10]; struct sockaddr_in cli_addr; clilen = sizeof(cli_addr); while(1) { listen(sockfd, 5); newsockfd[clients] = accept( sockfd, (struct sockaddr *) &cli_addr, &clilen); if(newsockfd < 0) { printf("unable to accept socket"); exit(1); } else { tosend = clients +1; n = write(newsockfd[clients],&tosend,sizeof(int)); if(n<0) { printf("connection error : could to tell client his ticket\\n"); } iret = pthread_create(&threads[clients], 0, &acceptData, &newsockfd[clients]); clients++; } } } void *transmitData(void *value) { int i = transclient; int n; while(1) { if(newoutput == 1) { pthread_mutex_lock(&mutexoutput); newoutput = 0; if(transclient < 0) { broadcastData(); } else { n = write(newsockfd[i] , outputbuffer ,noofoutputbytes); if( n <0) { printf("unable to write"); } } pthread_mutex_unlock(&mutexoutput); } } } void createServer(int portno) { clients =0; int iret,iret2; struct sockaddr_in serv_addr; sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd <0) { printf("socket did not create"); } bzero((char *) &serv_addr , sizeof(serv_addr)); 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) { printf(" unable to bind"); exit(1); } iret = pthread_create(&clithread, 0, acceptClient , ""); if(iret <0) { printf("client thread did not create"); } iret2 = pthread_create(&outputthread, 0, transmitData, ""); if(iret2 <0) { printf("output thread did not create"); } iret2 = pthread_create(&inputthread, 0, acceptData, ""); if(iret2 <0) { printf("input thread did not create"); } } void createClient(int portno , char *hostname) { clients = 1; int iret; struct sockaddr_in serv_addr; struct hostent *server; newsockfd[0] = socket(AF_INET, SOCK_STREAM, 0); if(sockfd<0) { printf("socket didnot create"); } server =gethostbyname(hostname); if( server == 0) { printf(" no such host"); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr,server->h_length); serv_addr.sin_port = htons(portno); while(connect(newsockfd[0],(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) { printf(" jumping\\n"); } iret = pthread_create(&inputthread, 0, acceptData, &newsockfd[0]); iret = pthread_create(&outputthread, 0, transmitData, &newsockfd[0]); if(iret <0) { printf("output thread did not create"); } } int recieveData(void *in,int sizein) { int n; char *buffer; buffer = (char *)in; bzero(buffer,sizein); while(newinput == 0) { } if(newinput == 1) { pthread_mutex_lock(&mutexinput); newinput = 0; bcopy(inputbuffer , buffer , sizein); bzero(inputbuffer,0); pthread_mutex_unlock(&mutexinput); return noofinputbytes; } return 0; } void sendData(void *data , int noofbytes, char client) { int n; pthread_mutex_lock(&mutexoutput); bzero(outputbuffer, 256); bcopy(data , outputbuffer, noofbytes); transclient = client; noofoutputbytes=noofbytes; newoutput = 1; pthread_mutex_unlock(&mutexoutput); }
0
#include <pthread.h> pthread_mutex_t lock; void delay_in_msec(int max) { unsigned delay = (int) (rand() / (double) 32767 + 1) * max; usleep(delay); } const char* id; pthread_mutex_t* pLock; } PARAMS; void* work(void* v) { PARAMS* params = (PARAMS*) v; pthread_mutex_lock(params->pLock); for (int i = 0; i < 25; i++) { printf("%s", params->id); fflush(stdout); delay_in_msec(1000); } pthread_mutex_unlock(params->pLock); return 0; } int main(void) { pthread_t t1, t2, t3, t4; pthread_mutex_t lock1, lock2, lock3, lock4; pthread_mutex_init(&lock1, 0); pthread_mutex_init(&lock2, 0); pthread_mutex_init(&lock3, 0); pthread_mutex_init(&lock4, 0); pthread_create(&t1, 0, work, (void*) &(PARAMS){"1", &lock1}); pthread_create(&t2, 0, work, (void*) &(PARAMS){"2", &lock1}); pthread_create(&t3, 0, work, (void*) &(PARAMS){"3", &lock2}); pthread_create(&t4, 0, work, (void*) &(PARAMS){"4", &lock2}); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); }
1
#include <pthread.h> pthread_mutex_t mutex; int x; void threaddeal1(void) { while(x>0) { pthread_mutex_lock(&mutex); printf("线程1正在运行: x=%d \\n",x); x--; pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void threaddeal2(void) { while(x>0) { pthread_mutex_lock(&mutex); printf("线程2正在运行: x=%d \\n",x); x--; pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } int main(int argc,char *argv[]) { pthread_t threadid1,threadid2; int ret; ret = pthread_mutex_init(&mutex,0); if(ret != 0) { printf ("初始化互斥锁失败.\\n"); exit (1); } x = 10; ret = pthread_create(&threadid1, 0, (void *)&threaddeal1, 0); if(ret != 0) { printf ("创建线程1失败.\\n"); exit (1); } ret = pthread_create(&threadid2, 0, (void *)&threaddeal2, 0); if(ret != 0) { printf ("创建线程2失败.\\n"); exit (1); } pthread_join(threadid1, 0); pthread_join(threadid2, 0); return (0); }
0
#include <pthread.h> void *do_chat(void *); int pushClient(int); int popClient(int); pthread_t thread; pthread_mutex_t mutex; int list_c[10]; char greeting[]="Welcome to chatting room\\n"; char CODE200[]="Sorry No More Connection\\n"; main(int argc, char *argv[]) { int c_socket, s_socket; struct sockaddr_in s_addr, c_addr; int len; int i, j, n; int res; if(argc < 2) { printf("usage: %s port_number\\n", argv[0]); exit(-1); } if(pthread_mutex_init(&mutex, 0) != 0) { printf("Can not create mutex\\n"); return -1; } s_socket = socket(PF_INET, SOCK_STREAM, 0); memset(&s_addr, 0, sizeof(s_addr)); s_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(atoi(argv[1])); if(bind(s_socket, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) { printf("Can not Bind\\n"); return -1; } if(listen(s_socket, 10) == -1) { printf("listen Fail\\n"); return -1; } for(i = 0; i < 10; i++) list_c[i] = -1; while(1) { len = sizeof(c_addr); c_socket = accept(s_socket, (struct sockaddr *)&c_addr, &len); res = pushClient(c_socket); if(res < 0) { write(c_socket, CODE200, strlen(CODE200)); close(c_socket); } else { write(c_socket, greeting, strlen(greeting)); pthread_create(&thread, 0, do_chat, (void *)c_socket); } } } void *do_chat(void *arg) { int c_socket = (int)arg; char chatData[1024]; int i, n; while(1) { memset(chatData, 0, sizeof(chatData)); if((n = read(c_socket, chatData, sizeof(chatData))) != 0) { for(i = 0; i < 10; i++) if(list_c[i] != -1 && list_c[i] != c_socket) write(list_c[i], chatData, n); } else { popClient(c_socket); break; } } } int pushClient(int c_socket) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); if(list_c[i] == -1) { list_c[i] = c_socket; pthread_mutex_unlock(&mutex); return i; } pthread_mutex_unlock(&mutex); } if(i == 10) return -1; } int popClient(int s) { int i; close(s); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); if(s == list_c[i]) { list_c[i] = -1; pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> int len = 0; int front = 0; int back = 0; int size; int *arr; struct params{ int len; int size; int front; int back; int *arr; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_variable1 = PTHREAD_COND_INITIALIZER, condition_variable2 = PTHREAD_COND_INITIALIZER; void *producer(void *args){ int *thread_id = (int *)args; int i = 0; fprintf(stderr,"producer thread %d started\\n",*thread_id); while( i < 9999){ pthread_mutex_lock(&mutex); while(size == len){ pthread_cond_wait(&condition_variable1, &mutex); } fprintf(stderr,"The producer %d produced %d\\n",*thread_id,i+1); arr[front] = i+1; front = (front+1)%len; size = size+1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition_variable2); i++; } } void *consumer(void *args){ int *thread_id = (int *)args; int i = 0; fprintf(stderr,"consumer thread %d started\\n", *thread_id); while(i < 3333){ pthread_mutex_lock(&mutex); while(size == 0){ pthread_cond_wait(&condition_variable2, &mutex); } int consumed_val = arr[back]; fprintf(stderr, "consumer %d consumed %d\\n", *thread_id, consumed_val); back = (back+1)%len; size--; pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition_variable1); i++; } } int main(){ len = 5; size = 0; pthread_t threads[4]; struct params p; p.len = 5; p.size = 0; p.front = 0; p.back = 0; p.arr = (int *)malloc(sizeof(int) * len); int thread_ids[4] = {0, 1, 2, 3}; void *retval; arr = (int *)malloc(sizeof(int)*len); if( pthread_create(&threads[0],0,producer,&thread_ids[0]) != 0){ fprintf(stderr,"producer thread creation failed\\n"); exit(1); } for(int i = 1; i < 4; i++){ if(pthread_create(&threads[i], 0, consumer, &thread_ids[i]) != 0){ fprintf(stderr,"consumer thread %d creation failed\\n",thread_ids[i]); } } for(int i = 0 ; i < 4; i++){ pthread_join(threads[i],&retval); } return 0; }
0