text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static void * thread_fn(void * args){ printf("this a thread function\\n"); return; } int makethread(void *(*fn)(void *),void *arg){ printf("makethread runed\\n"); int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err !=0 ) return err; err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); if ( err ==0 ) err = pthread_create(&tid,&attr,fn,arg); pthread_attr_destroy(&attr); return err; } struct to_info{ void (*to_fn)(void *); void * to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg){ struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait,0); (*tip->to_fn)(tip->to_arg); return (0); } void timeout(const struct timespec *when,void (*func)(void *), void *arg){ printf("timeout runing......\\n"); struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv,0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; printf("when->tv_sec=%d;now.tv_sec=%d\\n",when->tv_sec,now.tv_sec); printf("when->tv_nsec=%lld;now.tv_nsec=%lld\\n",when->tv_nsec,now.tv_nsec); if ( (when->tv_sec > now.tv_sec ) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec) ) { tip = malloc(sizeof(struct to_info)); if ( tip != 0 ){ tip->to_fn = func; tip->to_arg =arg; tip->to_wait.tv_sec = when->tv_sec-now.tv_sec; if ( when->tv_nsec >= now.tv_nsec ){ tip->to_wait.tv_nsec = when->tv_sec -now.tv_sec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 -now.tv_nsec+when->tv_nsec; } err = makethread(timeout_helper,(void *) tip); if ( err == 0 ) return; } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry (void *arg){ pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void){ int err,condition,arg; struct timespec when; condition = 1; if ( (err = pthread_mutexattr_init(&attr)) != 0 ) printf("pthread_mutexattr_init failed %d\\n",err); if ( (err = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE_NP)) != 0 ) printf("can't set recursive tipe %d\\n",err); if ( (err = pthread_mutex_init(&mutex,&attr)) != 0 ) printf("can't create recursive mutex %d \\n",err); pthread_mutex_lock(&mutex); printf("condition =%d\\n",condition); if ( condition ){ printf("before timeout\\n"); timeout(&when,retry,(void *)arg); printf("end timeout\\n"); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> char g_data[128]; pthread_cond_t cv = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutx = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *arg) { while (1) { pthread_mutex_lock(&mutx); while (strlen(g_data) == 0) pthread_cond_wait(&cv, &mutx); printf("%s\\n", g_data); g_data[0] = 0; pthread_mutex_unlock(&mutx); } return 0; } void *producer(void *arg) { int i = 0; while (1) { sleep(1); pthread_mutex_lock(&mutx); sprintf(g_data, "Data item %d", i); pthread_mutex_unlock(&mutx); pthread_cond_signal(&cv); i++; } return 0; } int main(int argc, char *argv[]) { pthread_t producer_thread; pthread_t consumer_thread; pthread_create(&producer_thread, 0, producer, 0); pthread_create(&consumer_thread, 0, consumer, 0); pthread_join(producer_thread, 0); pthread_join(consumer_thread, 0); return 0; }
0
#include <pthread.h> float h = 0.01; static const float h_stride = 0.01; float x = 0.00; float total_area = 0.00; int thread_count; int threads_batched = 0; unsigned int usecs = 100; int threads_done = 0; pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t area_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t batch_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t batch_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t thread_end_mutex = PTHREAD_MUTEX_INITIALIZER; void *controller(){ int i; for(;;){ usleep(usecs); if(threads_batched >= (thread_count)){ threads_batched = 0; for(i=0;i<thread_count;i++) h = h + h_stride; if(pthread_cond_broadcast(&batch_cond)) printf("Error\\n"); } if(threads_done == thread_count){ printf("Calculation Done!\\n"); pthread_cond_broadcast(&batch_cond); printf("Total area: %G. Expected Area: 4.0\\n",total_area); exit(0); } } } void *auc_slice(void *ptr){ int *thread_index_ptr; thread_index_ptr = (int *) ptr; float area_to_add; int thread_id = *thread_index_ptr; pthread_mutex_unlock(&init_mutex); float my_offset = 0.00; printf("Thread %d entered\\n",thread_id); while(my_offset <= 2.0*M_PI){ my_offset = h + thread_id*h_stride; area_to_add = trap_area(h_stride,fabsf(sin(my_offset)),fabsf(sin(my_offset+h_stride))); pthread_mutex_lock(&area_mutex); total_area = total_area+area_to_add; threads_batched++; pthread_mutex_unlock(&area_mutex); pthread_cond_wait(&batch_cond,&batch_mutex); } pthread_mutex_lock(&thread_end_mutex); threads_done++; pthread_mutex_unlock(&thread_end_mutex); printf("Thread %d done\\n",thread_id); while(threads_done != thread_count){ threads_batched++; pthread_cond_wait(&batch_cond,&batch_mutex); } if(pthread_cond_broadcast(&batch_cond)) printf("Error\\n"); return(0); } float trap_area(float length,float width,float triangle_height){ triangle_height = fabsf(triangle_height-width); return (length*width)+(length*triangle_height/2.0); } struct thread_parameters{ int thread_id; float h; }; int main(int argc, char *argv[]){ if (argc != 2 && argc != 3 ) { printf("Usage: %s thread_count ?(h)\\n",argv[0]); return 1; } if (argc == 2){ printf("Assuming an h value of 0.01\\n"); } else{ h = atof(argv[2]); x = atof(argv[2]); } pthread_t control_thread; pthread_create(&control_thread,0,&controller,0); pthread_t threads[thread_count]; struct thread_parameters t_params; t_params.h = h; thread_count = atoi(argv[1]); int i; for(i=0;i<thread_count;i++){ pthread_mutex_lock(&init_mutex); t_params.thread_id = i; pthread_create(&threads[i],0,&auc_slice,(void *) &t_params); } for(i=0;i<thread_count;i++) pthread_join(threads[i],0); pthread_join(control_thread,0); printf("Approximated area: %G | Expected Area: 4.0\\n",total_area); return 0; }
1
#include <pthread.h> int data; pthread_mutex_t A; pthread_mutex_t B; pthread_mutex_t C; void * thread_routine_1(void * arg) { int tmp; pthread_mutex_lock(&A); printf("thread 1 : lock (A)\\n"); data = tmp+1; pthread_mutex_unlock(&A); printf("thread 1 : unlock (A)\\n"); return 0; } void * thread_routine_2(void * arg) { int tmp; pthread_mutex_lock(&B); printf("thread 2 : lock (B)\\n"); tmp = data; pthread_mutex_unlock(&B); printf("thread 2 : unlock (B)\\n"); return 0; } void * thread_routine_3(void * arg) { int tmp; pthread_mutex_lock(&C); printf("thread 1 : lock (A)\\n"); data = tmp+1; pthread_mutex_unlock(&C); printf("thread 1 : unlock (A)\\n"); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&A, 0); pthread_mutex_init(&B, 0); pthread_mutex_init(&C, 0); pthread_create(&t1, 0, thread_routine_1, 0); pthread_create(&t2, 0, thread_routine_2, 0); pthread_create(&t3, 0, thread_routine_3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); my_mutex_destroy(&A); my_mutex_destroy(&B); my_mutex_destroy(&C); return 0; }
0
#include <pthread.h> { int id; int noproc; int dim; } parm; { int cur_count; pthread_mutex_t barrier_mutex; pthread_cond_t barrier_cond; } barrier_t; barrier_t barrier1; double *finals; int rootn; void barrier_init (barrier_t * mybarrier) { pthread_mutexattr_t attr; pthread_mutex_init (&(mybarrier->barrier_mutex), 0); pthread_cond_init (&(mybarrier->barrier_cond), 0); mybarrier->cur_count = 0; } void barrier (int numproc, barrier_t * mybarrier) { pthread_mutex_lock (&(mybarrier->barrier_mutex)); mybarrier->cur_count++; if (mybarrier->cur_count != numproc) { pthread_cond_wait (&(mybarrier->barrier_cond), &(mybarrier->barrier_mutex)); } else { mybarrier->cur_count = 0; pthread_cond_broadcast (&(mybarrier->barrier_cond)); } pthread_mutex_unlock (&(mybarrier->barrier_mutex)); } double f (a) double a; { return (4.0 / (1.0 + a * a)); } void * cpi (void *arg) { parm *p = (parm *) arg; int myid = p->id; int numprocs = p->noproc; int i; double PI25DT = 3.141592653589793238462643; double mypi, pi, h, sum, x, a; double startwtime, endwtime; if (myid == 0) { startwtime = clock (); } barrier (numprocs, &barrier1); if (rootn == 0) finals[myid] = 0; else { h = 1.0 / (double) rootn; sum = 0.0; for (i = myid + 1; i <= rootn; i += numprocs) { x = h * ((double) i - 0.5); sum += f (x); } mypi = h * sum; } finals[myid] = mypi; barrier (numprocs, &barrier1); if (myid == 0) { pi = 0.0; for (i = 0; i < numprocs; i++) pi += finals[i]; endwtime = clock (); printf ("pi is approximately %.16f, Error is %.16f\\n", pi, fabs (pi - PI25DT)); printf ("wall clock time = %f\\n", (endwtime - startwtime) / CLOCKS_PER_SEC); } return 0; } int main (argc, argv) int argc; char *argv[]; { int done = 0, n, myid, numprocs, i, rc; double startwtime, endwtime; parm *arg; pthread_t *threads; pthread_attr_t pthread_custom_attr; if (argc != 2) { printf ("Usage: %s n\\n where n is no. of thread\\n", argv[0]); exit (1); } n = atoi (argv[1]); if ((n < 1) || (n > 1024)) { printf ("The no of thread should between 1 and %d.\\n", 1024); exit (1); } threads = (pthread_t *) malloc (n * sizeof (*threads)); pthread_attr_init (&pthread_custom_attr); barrier_init (&barrier1); finals = (double *) malloc (n * sizeof (double)); rootn = 10000000; arg = (parm *) malloc (sizeof (parm) * n); for (i = 0; i < n; i++) { arg[i].id = i; arg[i].noproc = n; pthread_create (&threads[i], &pthread_custom_attr, cpi, (void *) (arg + i)); } for (i = 0; i < n; i++) { pthread_join (threads[i], 0); } free (arg); }
1
#include <pthread.h> enum { MAX_THREADS = 3 }; enum { MAX_CYCLES = 5 }; static pthread_mutex_t mtx_waiting = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cnd_waiting = PTHREAD_COND_INITIALIZER; static int num_waiting = 0; static int cycle = -1; static float gl_rand = 0; static long gl_long = 0; static float next_iteration_random_number(int tid, int iteration) { pthread_mutex_lock(&mtx_waiting); assert(cycle == iteration || cycle == iteration - 1); num_waiting++; printf("-->> TID %d, I = %d (C = %d, W = %d)\\n", tid, iteration, cycle, num_waiting); while (cycle != iteration && num_waiting != MAX_THREADS) { assert(num_waiting > 0 && num_waiting <= MAX_THREADS); printf("-CW- TID %d, I = %d (C = %d, W = %d)\\n", tid, iteration, cycle, num_waiting); pthread_cond_wait(&cnd_waiting, &mtx_waiting); } assert(cycle == iteration || num_waiting == MAX_THREADS); printf("---- TID %d, I = %d (C = %d, W = %d)\\n", tid, iteration, cycle, num_waiting); if (cycle != iteration) { gl_long = lrand48(); gl_rand = (float)gl_long; num_waiting = 0; cycle = iteration; printf("---- TID %d generates cycle %d: L = %ld, F = %g\\n", tid, cycle, gl_long, gl_rand); pthread_cond_broadcast(&cnd_waiting); } printf("<<-- TID %d, I = %d (C = %d, W = %d) L = %ld, F = %g\\n", tid, iteration, cycle, num_waiting, gl_long, gl_rand); pthread_mutex_unlock(&mtx_waiting); return gl_rand; } static void *thread_function(void *vp) { int tid = (int)(uintptr_t)vp; for (int i = 0; i < MAX_CYCLES; i++) { float f = next_iteration_random_number(tid, i); printf("TID %d at work: I = %d, F = %g\\n", tid, i, f); fflush(stdout); struct timespec rq; rq.tv_sec = 0; rq.tv_nsec = (((gl_long & 0xFF) + (0xF * i))) % 200 * 50000000; assert(rq.tv_nsec >= 0 && rq.tv_nsec < 10000000000); nanosleep(&rq, 0); } return 0; } int main(int argc, char **argv) { err_setarg0(argv[0]); assert(argc == 1); pthread_t thread[MAX_THREADS]; for (int i = 0; i < MAX_THREADS; i++) { int rc = pthread_create(&thread[i], 0, thread_function, (void *)(uintptr_t)i); if (rc != 0) { errno = rc; err_syserr("failed to create thread %d", i); } } for (int i = 0; i < MAX_THREADS; i++) { void *vp; int rc = pthread_join(thread[i], &vp); if (rc != 0) { errno = rc; err_syserr("Failed to join TID %d", i); } printf("TID %d returned %p\\n", i, vp); } return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int queue[50]; int current = 0; void* readQueue(void* arg){ printf("THREADNUMBER is %d",(unsigned int)pthread_self()); pthread_mutex_lock(&mutex); if( 0 == queue[current]) { pthread_cond_wait(&cond,&mutex); }else{ printf("queue index %d avalid",current); current++; } pthread_mutex_unlock(&mutex); } int main() { pthread_t tid1,tid2,tid3,tid4,tid5; bzero(queue,5*sizeof(pthread_t)); int i = 0; printf("this is here\\n"); pthread_create(&tid1, 0, readQueue ,0); pthread_create(&tid2, 0, readQueue ,0); pthread_create(&tid3, 0, readQueue ,0); pthread_create(&tid4, 0, readQueue ,0); pthread_create(&tid5, 0, readQueue ,0); printf("this is here1\\n"); printf("this is here3\\n"); i = 0; while (i < 50) { queue[i] = 1; printf(" now is looping %d\\n",i); pthread_cond_broadcast(&cond); sleep(500); i++; } return 1; }
1
#include <pthread.h> int ready; int x, y, m, p, q; pthread_mutex_t l1, l2, l3; void *t0(void *args){ printf("t0\\n"); fflush(stdout); int t = 0; pthread_mutex_lock(&l1); printf("t0 locked l1\\n"); t = ready; printf("t0 unlocked l1\\n"); pthread_mutex_unlock(&l1); if ( t ) { y = x; printf("ready! y = x = %d\\n", y); } else{ printf("Not ready.. t = %d, y = %d, x = %d\\n", t, y, x); } printf("--------t0 exits-----------\\n"); pthread_exit(0); } void *t1(void *args){ printf("t1\\n"); fflush(stdout); pthread_mutex_lock(&l2); printf("t1 locked l2\\n"); p = q; printf("t1 unlocked l2\\n"); pthread_mutex_unlock(&l2); x = 1; pthread_mutex_lock(&l1); printf("t1 locked l1\\n"); ready = 1; printf("t1 unlocked l1\\n"); pthread_mutex_unlock(&l1); printf("--------t1 exits-----------\\n"); pthread_exit(0); } void *t2(void *args){ printf("t2 sleeping...\\n"); fflush(stdout); sleep(3); printf("--------t2 exits-----------\\n"); pthread_exit(0); } int main(void){ pthread_t th[3]; int i; pthread_mutex_init(&l1, 0); pthread_mutex_init(&l2, 0); pthread_mutex_init(&l3, 0); x = y = m = p = 0; pthread_create(&th[0], 0, t0, 0); pthread_create(&th[1], 0, t1, 0); pthread_create(&th[2], 0, t2, 0); for (i = 0; i < 3; i++) { pthread_join(th[i], 0); } return 0; }
0
#include <pthread.h> static pthread_t* threadID; static int activeThreadCount; static pthread_mutex_t bufferLock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t conditionLock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t exitLock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int number; static void rsleep (int t); static void init() { int i; for(i=0; i < (sizeof(buffer) / sizeof((buffer)[0])); i++) { buffer[i] = ~0; } ((buffer[0]) = (buffer[0]) & ~(((MY_TYPE) 1) << (0))); ((buffer[0]) = (buffer[0]) & ~(((MY_TYPE) 1) << (1))); for(i = (NROF_SIEVE+1)%64; i < 64; i++) { ((buffer[(sizeof(buffer) / sizeof((buffer)[0]))-1]) = (buffer[(sizeof(buffer) / sizeof((buffer)[0]))-1]) & ~(((MY_TYPE) 1) << (i))); } } static void* strike_out(void* argument) { int n = (int) argument; long long j; pthread_mutex_lock (&bufferLock); if((((buffer[n / 64]) & (((MY_TYPE) 1) << (n % 64))) == (((MY_TYPE) 1) << (n % 64)))) { for(j=n*n; j <= NROF_SIEVE; j+=n) { ((buffer[j / 64]) = (buffer[j / 64]) & ~(((MY_TYPE) 1) << (j % 64))); } } pthread_mutex_unlock (&bufferLock); pthread_mutex_lock (&exitLock); activeThreadCount--; pthread_cond_signal(&cond); pthread_mutex_unlock (&exitLock); return 0; } static void print_primes() { int n; for(n=2; n <= NROF_SIEVE; n++) { if((((buffer[n / 64]) & (((MY_TYPE) 1) << (n % 64))) == (((MY_TYPE) 1) << (n % 64)))) { printf("%d\\n", n); } } } int main (void) { init(); activeThreadCount = 0; number = 2; while(number <= sqrt(NROF_SIEVE) && activeThreadCount < NROF_THREADS) { fprintf(stderr, "Before malloc thread create\\n"); threadID = (pthread_t*) malloc(sizeof(pthread_t)); fprintf(stderr, "Before thread create\\n"); if(pthread_create(&threadID[0], 0, strike_out, &number)) { fprintf(stderr, "Error creating thread for n = %d\\n", number); return 1; } fprintf(stderr, "Thread created\\n"); pthread_detach(threadID[0]); fprintf(stderr, "Thread detached\\n"); rsleep(100); number++; activeThreadCount++; } while(number <= sqrt(NROF_SIEVE)) { pthread_mutex_lock (&conditionLock); pthread_cond_wait(&cond, &conditionLock); while(number <= sqrt(NROF_SIEVE) && activeThreadCount < NROF_THREADS) { threadID = malloc(sizeof(pthread_t)); if(pthread_create(&threadID[0], 0, strike_out, &number)) { fprintf(stderr, "Error creating thread for n = %d\\n", number); return 1; } pthread_detach(threadID[0]); number++; activeThreadCount++; } pthread_mutex_unlock (&conditionLock); } pthread_mutex_destroy(&bufferLock); pthread_mutex_destroy(&conditionLock); pthread_mutex_destroy(&exitLock); pthread_cond_destroy(&cond); print_primes(); return (0); } static void rsleep (int t) { static bool first_call = 1; if (first_call == 1) { srandom (time (0) % getpid()); first_call = 0; } usleep (random () % t); }
1
#include <pthread.h> int buffer=0; pthread_mutex_t mutex; void delay(int secs) { time_t beg = time(0), end = beg + secs; do { ; } while (time(0) < end); } void *produtor(){ int i=0,controle=0; while(controle<10){ pthread_mutex_lock(&mutex); if(buffer){ printf("Buffer cheio, produtor não pode inserir... Esperando consumidor.\\n"); delay(1); } else{ i=rand()%20+1; printf("Buffer = %d... Produtor produziu %d.\\n",buffer,i); buffer=i; delay(1); } ++controle; pthread_mutex_unlock(&mutex); delay(2); } } void *consumidor(){ int controle=0; while(controle<10){ pthread_mutex_lock(&mutex); if(buffer){ printf("Buffer = %d... Consumidor consumiu %d.\\n",buffer,buffer); buffer=0; delay(1); } else{ printf("Buffer vazio, consumidor não pode consumir... Esperando produtor. \\n"); delay(1); } ++controle; pthread_mutex_unlock(&mutex); delay(3); } } main() { int status=0; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); pthread_t ThreadProdutor, ThreadConsumidor; pthread_mutex_init(&mutex, 0); srand(time(0)); pthread_create(&ThreadProdutor,&attr, produtor, 0); pthread_create(&ThreadConsumidor,&attr, consumidor, 0); pthread_join(ThreadProdutor, (void **)&status); pthread_join(ThreadConsumidor, (void **)&status); pthread_exit(0); }
0
#include <pthread.h> void fac_constructor(struct facility_t *fac) { fac->name = 0; fac->busy = 0; fac->queue = 0; fac->idx = (ssize_t) - 1; fac->stats = xcalloc(1, sizeof(struct stat_t)); if (pthread_mutex_init(&fac->flock, 0) || pthread_cond_init(&fac->fcond, 0)) err(1, _("pthread init failed")); } void fac_clear(struct facility_t *fac) { free(fac->name); fac->name = 0; fac->busy = 0; free(fac->queue); fac->queue = 0; fac->idx = (ssize_t) - 1; } void fac_destructor(struct facility_t *fac) { free(fac->name); free(fac->queue); free(fac->stats); pthread_cond_destroy(&fac->fcond); pthread_mutex_destroy(&fac->flock); } void fac_set_name(struct facility_t *fac, const char *name) { fac->name = xrealloc(fac->name, strlen(name) + 1); memset(fac->name, 0, strlen(name) + 1); strncpy(fac->name, name, strlen(name)); } char *fac_get_name(struct facility_t *fac) { return fac->name; } void Seize(struct facility_t *fac, size_t idx) { if (!fac_busy(fac)) { pthread_mutex_lock(&fac->flock); fac->idx = idx; fac->busy = 1; } else { fac_queue_in(fac, idx); pthread_cond_signal(&process_list[idx].cond); if (fac->idx == (ssize_t) idx) return; do { pthread_cond_wait(&fac->fcond, &fac->flock); } while (fac->idx != (ssize_t) idx); } } void Release(struct facility_t *fac) { fac->idx = (ssize_t) - 1; fac->busy = 0; pthread_mutex_unlock(&fac->flock); if (!pq_empty(&fac->queue)) { pthread_mutex_lock(&fac->flock); fac->idx = pq_top(&fac->queue); pq_pop(&fac->queue); fac->busy = 1; process_list[fac->idx].atime = cur_time; add_elem(fac->idx); pthread_cond_broadcast(&fac->fcond); pthread_mutex_unlock(&fac->flock); } } bool fac_busy(struct facility_t *fac) { return fac->busy; } size_t fac_queue_len(struct facility_t * fac) { return pq_size(&fac->queue); } void fac_queue_in(struct facility_t *fac, size_t idx) { pq_push(&fac->queue, idx); }
1
#include <pthread.h> static int count=0; static pthread_mutex_t mut_count = PTHREAD_MUTEX_INITIALIZER; static void *thr_prime(void *ptr) { int mark; int i, j; i=*(int*)ptr; mark=1; for (j=2;j<i/2;++j) { if (i%j==0) { mark=0; break; } } if (mark==1) { pthread_mutex_lock(&mut_count); usleep(1); count++; pthread_mutex_unlock(&mut_count); } pthread_exit(0); } int main() { int i; int err; pthread_t tid[(30000200 -30000000 +1)]; int arg[(30000200 -30000000 +1)]; for (i=30000000;i<=30000200;++i) { arg[i-30000000] = i; err = pthread_create(tid+(i-30000000), 0, thr_prime, arg+(i-30000000)); if (err) { fprintf(stderr, "pthread_create(): %s\\n", strerror(err)); exit(1); } } for (i=30000000;i<=30000200;++i) { pthread_join(tid[i-30000000], 0); } pthread_mutex_destroy(&mut_count); printf("%d primes between %d ans %d\\n", count, 30000000, 30000200); return 0; }
0
#include <pthread.h> void *rrand(void *); pthread_mutex_t varout, out, mutexsum; double iterationLimit; int numThreads = 0; double totaloutside = 0, total =0; const double PI = 3.14159265359; unsigned seed = 300; int main(void){ printf("Enter number of iterations: \\n"); scanf("%lf", &iterationLimit); printf("Enter thread count: \\n"); scanf("%d", &numThreads); if (numThreads > 500){ printf("Too many threads"); return 0; } pthread_t threads[numThreads]; pthread_mutex_init(&varout,0); pthread_mutex_init(&out,0); pthread_mutex_init(&mutexsum,0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); int r; for (int i=0; i < numThreads; i++){ r = pthread_create(&threads[i], &attr, rrand, (void *) (intptr_t) (i + 1)); if (r){ printf("error code from pthread_create(): %d\\n", r); exit(-1); } } pthread_attr_destroy(&attr); for (int i=0; i < numThreads; i++) pthread_join(threads[i], 0); double value = 4.*((total - totaloutside)/total), error = (PI - value); printf("\\n Final estimated value of pi: %f\\n Error: %f \\n------------------------\\n", value, error); } void *rrand(void *param){ int thread = (intptr_t) param; double outside = 0; double x, y; srand(seed*thread); double count = 0; for (double n=thread; n <= iterationLimit; n+= numThreads) { count++; x = (double)rand()/32767; y = (double)rand()/32767; if ((x*x+y*y)>=1) outside++; } pthread_mutex_lock(&varout); double value = 4.*((count - outside)/count), error = (PI - value); pthread_mutex_unlock(&varout); pthread_mutex_lock(&out); printf("\\n Estimated value of pi (thread %d): %f\\n Error: %f \\n------------------------\\n", thread, value, error); pthread_mutex_unlock(&out); pthread_mutex_lock(&mutexsum); totaloutside += outside; total += count; pthread_mutex_unlock(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> double widthbase; int rectxworker; struct ij { double low; double high; }; pthread_mutex_t mutex; double total = 0; double total2= 0; void* suma_para(void *_data) { struct ij *data = (struct ij *)_data; double i=0; double resultado = 0; for (i=data->low; i<data->high;i++){ resultado +=function(widthbase*i)*(widthbase); } pthread_mutex_lock(&mutex); total = total + resultado; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char** argv) { clock_t t1,t2; int maxrect = 10000; int low_gral = 0; int high_gral = 1; int nw = 5; int j; struct ij particion[nw]; pthread_t tid[nw]; widthbase = (double)(high_gral - low_gral)/(double)maxrect; printf("Width of the base %lf\\n\\n",widthbase); printf("Number of workers %d\\n",nw); rectxworker = (int)(maxrect/nw); printf("\\tRectangles per worker %d\\n",rectxworker); t1=clock(); for (j = 0; j < nw; j++) { particion[j].low=j*rectxworker; particion[j].high=(j+1)*rectxworker; pthread_create(&tid[j],0,suma_para,&particion[j]); } for (j = 0; j < nw; j++) { pthread_join(tid[j], 0); } printf("\\tTotal Metodo Riemann: %lf\\n\\n", total); }
0
#include <pthread.h> int progress_enabled = 0; int rotate = 0; int cur_uncompressed = 0, estimated_uncompressed = 0; int columns; pthread_t progress_thread; pthread_mutex_t progress_mutex = PTHREAD_MUTEX_INITIALIZER; static void sigwinch_handler() { struct winsize winsize; if(ioctl(1, TIOCGWINSZ, &winsize) == -1) { if(isatty(STDOUT_FILENO)) printf("TIOCGWINSZ ioctl failed, defaulting to 80 " "columns\\n"); columns = 80; } else columns = winsize.ws_col; } static void sigalrm_handler() { rotate = (rotate + 1) % 4; } void inc_progress_bar() { cur_uncompressed ++; } void dec_progress_bar(int count) { cur_uncompressed -= count; } void progress_bar_size(int count) { estimated_uncompressed += count; } static void progress_bar(long long current, long long max, int columns) { char rotate_list[] = { '|', '/', '-', '\\\\' }; int max_digits, used, hashes, spaces; static int tty = -1; if(max == 0) return; max_digits = floor(log10(max)) + 1; used = max_digits * 2 + 11; hashes = (current * (columns - used)) / max; spaces = columns - used - hashes; if((current > max) || (columns - used < 0)) return; if(tty == -1) tty = isatty(STDOUT_FILENO); if(!tty) { static long long previous = -1; if((current % 100) != 0 && current != max) return; if(current == previous) return; previous = current; } printf("\\r["); while (hashes --) putchar('='); putchar(rotate_list[rotate]); while(spaces --) putchar(' '); printf("] %*lld/%*lld", max_digits, current, max_digits, max); printf(" %3lld%%", current * 100 / max); fflush(stdout); } void enable_progress_bar() { pthread_mutex_lock(&progress_mutex); progress_enabled = 1; pthread_mutex_unlock(&progress_mutex); } void disable_progress_bar() { pthread_mutex_lock(&progress_mutex); if(progress_enabled) { progress_bar(cur_uncompressed, estimated_uncompressed, columns); printf("\\n"); } progress_enabled = 0; pthread_mutex_unlock(&progress_mutex); } void *progress_thrd(void *arg) { struct timespec requested_time, remaining; struct itimerval itimerval; struct winsize winsize; if(ioctl(1, TIOCGWINSZ, &winsize) == -1) { if(isatty(STDOUT_FILENO)) printf("TIOCGWINSZ ioctl failed, defaulting to 80 " "columns\\n"); columns = 80; } else columns = winsize.ws_col; signal(SIGWINCH, sigwinch_handler); signal(SIGALRM, sigalrm_handler); itimerval.it_value.tv_sec = 0; itimerval.it_value.tv_usec = 250000; itimerval.it_interval.tv_sec = 0; itimerval.it_interval.tv_usec = 250000; setitimer(ITIMER_REAL, &itimerval, 0); requested_time.tv_sec = 0; requested_time.tv_nsec = 250000000; while(1) { int res = nanosleep(&requested_time, &remaining); if(res == -1 && errno != EINTR) BAD_ERROR("nanosleep failed in progress thread\\n"); if(progress_enabled) { pthread_mutex_lock(&progress_mutex); progress_bar(cur_uncompressed, estimated_uncompressed, columns); pthread_mutex_unlock(&progress_mutex); } } } void init_progress_bar() { pthread_create(&progress_thread, 0, progress_thrd, 0); } void progressbar_error(char *fmt, ...) { va_list ap; pthread_mutex_lock(&progress_mutex); if(progress_enabled) fprintf(stderr, "\\n"); __builtin_va_start((ap)); vfprintf(stderr, fmt, ap); ; pthread_mutex_unlock(&progress_mutex); } void progressbar_info(char *fmt, ...) { va_list ap; pthread_mutex_lock(&progress_mutex); if(progress_enabled) printf("\\n"); __builtin_va_start((ap)); vprintf(fmt, ap); ; pthread_mutex_unlock(&progress_mutex); }
1
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; sem_t sem_elfos; volatile int count_elfos; volatile int count_renas; volatile int lock; volatile int acordado; void logP(){ int i; if(!lock){ lock = 1; system("clear"); printf(" [Ajudando Elfos]\\n"); if(acordado){ printf(" ~~~~~ \\n"); printf(" o.o \\n"); printf(" \\\\___/ \\n"); } else{ printf("\\tzzzzzzzzzzzzzz\\n"); printf(" ~~~~~ \\n"); printf(" -.- \\n"); printf(" \\\\___/ \\n"); } count_elfos--; if(count_elfos==0) acordado = 0; printf("Elfos pedindo ajuda: %d\\tRenas: %d\\n", count_elfos, count_renas); printf("ELFOS: ");for(i=0; i<count_elfos; i++) printf(" & "); putchar(10);putchar(10); printf("RENAS: ");for(i=0; i<count_renas; i++) printf(" § "); putchar(10); sleep(2); lock =0; } } void logFim(){ lock = 1; system("clear"); printf(" _...\\n"); printf(" o_.-\\"` `\\n"); printf(" .--. _ `'-._.-'\\"\\"-; _\\n"); printf(" .' \\\\`_\\\\_ {_.-a\\"a-} _ / \\\\ \\n"); printf(" _/ .-' '. {c-._o_.){\\\\|` |\\n"); printf(" (@`-._ / \\\\{ ^ } \\\\\\\\ _/\\n"); printf(" `~\\\\ '-._ /'. } \\\\} .-.\\n"); printf(" |>:< '-.__/ '._,} \\\\_/ / ()) \\n "); printf(" | >:< `'---. ____'-.|(`\\"`\\n"); printf(" \\\\ >:< \\\\\\\\_\\\\\\\\_\\\\ | ;\\n"); printf(" \\\\ \\\\\\\\-{}-\\\\/ \\\\ \\n"); printf(" \\\\ '._\\\\\\\\' /)\\n"); printf(" '. /(\\n"); printf(" `-._ _____ _ _____ __.'\\\\ \\\\ \\n"); printf(" / \\\\ / \\\\ / \\\\ \\\\ \\\\ \\n"); printf(" jgs _.'/^\\\\'._.'/^\\\\'._.'/^\\\\'.__) \\\\ \\n"); printf(" ,==' `---` '---' '---' )\\n"); printf(" `\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"\\"`\\n"); getchar(); exit(0); } void logR(int id){ int i; lock = 1; system("clear"); printf(" [rena ]\\n"); if(acordado){ printf(" ~~~~~ \\n"); printf(" o o \\n"); printf(" \\\\___/ \\n"); } else{ printf("\\tzzzzzzzzzzzzzz\\n"); printf(" ~~~~~ \\n"); printf(" - - \\n"); printf(" \\\\___/ \\n"); } count_renas++; printf("Elfos pedindo ajuda: %d\\tRenas: %d\\n", count_elfos, count_renas); printf("ELFOS: ");for(i=0; i<count_elfos; i++) printf(" & "); putchar(10);putchar(10); printf("RENAS: ");for(i=0; i<count_renas; i++) printf(" § "); putchar(10); sleep(2); lock =0; } void logE(){ int i; if(!lock){ lock = 1; system("clear"); printf(" [Papai Noel dormindo]\\n"); printf("\\tzzzzzzzzzzzzzz\\n"); printf(" ~~~~~ \\n"); printf(" -.- \\n"); printf(" \\\\___/ \\n"); count_elfos++; printf("Elfos pedindo ajuda: %d\\tRenas: %d\\n", count_elfos, count_renas); printf("ELFOS: ");for(i=0; i<count_elfos; i++) printf(" & "); putchar(10);putchar(10); printf("RENAS: ");for(i=0; i<count_renas; i++) printf(" § "); putchar(10); sleep(2); lock = 0; } } void* Renas(void * v){ pthread_mutex_lock(&mutex); int id = *(int*)v; sleep(1); printf("Rena %d chegou!\\n",id); count_renas++; if(count_renas==9){ sem_post(&sem_elfos); printf("********todas as renas chegaram********\\n"); sleep(1); acordado = 1; return 0; } sleep(3); pthread_mutex_unlock(&mutex); return 0; } void * Papai_noel(void* v){ while(1){ sem_wait(&sem_elfos); if(count_renas==9){ printf("\\tPreparar treno e partir!\\n"); logFim(); return 0; }else if(count_elfos==3){ printf("Acordei! Vou ajudar os elfos!\\n"); while(count_elfos>0 && acordado){ if(count_renas==9) break; sleep(2); logP(); } } } return 0; } void * elfoo(void* v){ while(1){ if(count_renas==9) return 0; sleep(2); logE(); if(count_elfos==3){ sem_post(&sem_elfos); acordado = 1; while(count_elfos>0){ if(count_renas==9) return 0; } acordado = 0; } } } void Explicacao(){ fputs("Elfo= &\\nRena= §\\n", stdout); fputs("Papai Noel dormindo= -.-\\nPapai Noel acordado= o.o\\n\\n", stdout); fputs("Aperte uma tecla para continuar", stdout); getchar(); } int main(){ pthread_t noel; pthread_t rena[9]; pthread_t elfo; int id_rena[9]; int id_elfo = 0; int i; count_elfos=0; count_renas=0; lock = 0; acordado = 0; pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); sem_init(&sem_elfos, 0, 0); Explicacao(); pthread_create(&noel, 0, Papai_noel, 0); pthread_create(&elfo, 0, elfoo, (void*)&id_elfo); for(i=0; i<9; i++){ id_rena[i] = i; pthread_create(&rena[i], 0, Renas, (void*)&id_rena[i]); } pthread_join(noel, 0); pthread_join(elfo, 0); for(i=0; i<9; i++) pthread_join(rena[i], 0); return 0; }
0
#include <pthread.h> int _debug = -77; void debug(char *fmt, ...) { if(_debug == -77) { char *buf = getenv("EZTRACE_DEBUG"); if(buf == 0) _debug = 0; else _debug = atoi(buf); } if(_debug >= 0) { va_list va; __builtin_va_start((va)); vfprintf(stdout, fmt, va); ; } } unsigned long long tick; struct { unsigned low; unsigned high; }; } tick_t; sem_t thread_ready; sem_t sem[2]; pthread_mutex_t mutex; pthread_spinlock_t spinlock; pthread_barrier_t barrier; pthread_cond_t cond; pthread_rwlock_t rwlock; void compute(int usec) { struct timeval tv1,tv2; gettimeofday(&tv1,0); do { gettimeofday(&tv2,0); }while(((tv2.tv_sec - tv1.tv_sec) * 1000000 + (tv2.tv_usec - tv1.tv_usec)) < usec); } void* f_thread(void* arg) { uint8_t my_id=*(uint8_t*) arg; sem_post(&thread_ready); pthread_barrier_wait(&barrier); int i; for(i=0; i<10; i++){ sem_wait(&sem[my_id]); pthread_mutex_lock(&mutex); compute(5000); pthread_mutex_unlock(&mutex); compute(5000); pthread_spin_lock(&spinlock); compute(5000); pthread_spin_unlock(&spinlock); compute(5000); pthread_spin_lock(&spinlock); compute(5000); pthread_spin_unlock(&spinlock); compute(5000); pthread_rwlock_rdlock(&rwlock); compute(5000); pthread_rwlock_unlock(&rwlock); compute(5000); pthread_rwlock_wrlock(&rwlock); compute(5000); pthread_rwlock_unlock(&rwlock); compute(5000); sem_post(&sem[(my_id+1)%2]); } pthread_barrier_wait(&barrier); return 0; } int main(int argc, char**argv) { pthread_t tid[2]; int i; pthread_mutex_init(&mutex, 0); pthread_spin_init(&spinlock, 0); pthread_barrier_init(&barrier, 0, 2); pthread_cond_init(&cond, 0); pthread_rwlock_init(&rwlock, 0); sem_init(&thread_ready, 0, 0); for(i=0 ; i<2; i++) sem_init(&sem[i], 0, 0); for(i=0;i<2; i++) { pthread_create(&tid[i], 0, f_thread, &i); sem_wait(&thread_ready); } sem_post(&sem[0]); for(i=0;i<2; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); pthread_spin_destroy(&spinlock); pthread_barrier_destroy(&barrier); pthread_cond_destroy(&cond); pthread_rwlock_destroy(&rwlock); return 0; }
1
#include <pthread.h> int TcAddKeybuf (char c) { int RetVal = 1, i; pthread_mutex_lock (&TcMutex); if (TcKeybufSize < TC_KEYBUF_SIZE) { RetVal = 0; i = TcKeybufStart + TcKeybufSize; if (i >= TC_KEYBUF_SIZE) i -= TC_KEYBUF_SIZE; TcKeybuf[i] = c; TcKeybufSize++; } pthread_mutex_unlock (&TcMutex); return (RetVal); } int TcExtractKeybuf (char *c) { int RetVal = 1; pthread_mutex_lock (&TcMutex); if (TcKeybufSize > 0) { RetVal = 0; *c = TcKeybuf[TcKeybufStart]; TcKeybufSize--; TcKeybufStart++; if (TcKeybufStart >= TC_KEYBUF_SIZE) TcKeybufStart = 0; } pthread_mutex_unlock (&TcMutex); return (RetVal); } int kbhit (void) { if (TcGraphicsInitialized) { if (TcKeybufSize > 0) return (1); } if (ConioInitialized) { int KeyCode; KeyCode = getchNcurses (); if (KeyCode != ERR) { ungetchNcurses (KeyCode); return (1); } } return (0); }
0
#include <pthread.h> void *producter_f(void *arg); void *consumer_f(void *arg); int buffer_has_item = 0; pthread_mutex_t mutex; int running = 1; int main(void) { pthread_t consumer_t; pthread_t producter_t; pthread_mutex_init(&mutex, 0); pthread_create(&producter_t, 0, (void *)producter_f, 0); pthread_create(&consumer_t, 0, (void *)consumer_f, 0); usleep(1); running = 0; pthread_join(consumer_t, 0); pthread_join(producter_t, 0); pthread_mutex_destroy(&mutex); return 0; } void *producter_f(void *arg) { while(running){ pthread_mutex_lock(&mutex); buffer_has_item++; printf("生产,总数量: %d\\n", buffer_has_item); pthread_mutex_unlock(&mutex); } } void *consumer_f(void *arg) { while(running){ pthread_mutex_lock(&mutex); buffer_has_item--; printf("消费,剩余数量: %d\\n", buffer_has_item); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } struct list_node_s { int data; struct list_node_s* next; pthread_mutex_t mutex; }; int thread_count; struct list_node_s** head_pp; pthread_mutex_t mutex; pthread_mutex_t head_p_mutex; pthread_rwlock_t rwlock; int MemberP(int value) { struct list_node_s* temp_p; pthread_mutex_lock(&head_p_mutex); temp_p=*head_pp; while(temp_p != 0 && temp_p->data<value) { if (temp_p->next != 0) { pthread_mutex_lock(&(temp_p->next->mutex)); } if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); temp_p=temp_p->next; } if (temp_p == 0 || temp_p->data >value) { if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } if (temp_p != 0) { pthread_mutex_unlock(&(temp_p->mutex)); } return 0; } else { if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); return 1; } } int Member(int value) { struct list_node_s* curr_p=*head_pp; while(curr_p!=0 && curr_p->data < value) curr_p=curr_p->next; if(curr_p == 0 || curr_p->data >value) return 0; else return 1; } int Insert(int value) { struct list_node_s* curr_p= *head_pp; struct list_node_s* pred_p= 0; struct list_node_s* temp_p; while(curr_p != 0 && curr_p->data<value) { pred_p=curr_p; curr_p=curr_p->next; } if(curr_p == 0 || curr_p->data > value) { temp_p=malloc(sizeof(struct list_node_s)); temp_p->data=value; temp_p->next=curr_p; if (pred_p == 0) *head_pp=temp_p; else pred_p->next=temp_p; return 1; } else return 0; } int Delete(int value) { struct list_node_s* curr_p=*head_pp; struct list_node_s* pred_p= 0; while(curr_p != 0 && curr_p->data < value) { pred_p=curr_p; curr_p=curr_p->next; } if(curr_p != 0 && curr_p->data == value) { if(pred_p == 0) { *head_pp=curr_p->next; free(curr_p); } else { pred_p->next=curr_p->next; free(curr_p); } return 1; } else return 0; } void* LLamarFunc(void* rango) { long mi_rango=(long) rango; printf("Soy el thread %ld\\n",mi_rango); pthread_rwlock_wrlock(&rwlock); Insert((int)mi_rango); pthread_rwlock_unlock(&rwlock); pthread_rwlock_rdlock(&rwlock); int numero=Member((int)mi_rango); pthread_rwlock_unlock(&rwlock); printf("Mi numero %d\\n",numero); return 0; } int main(int argc,char* argv[]) { long thread; pthread_t* thread_handles; struct list_node_s* head; head=malloc(sizeof(struct list_node_s)); head->data=0; head->next=0; head_pp=&head; thread_count=strtol(argv[1],0,10); thread_handles=malloc (thread_count*sizeof(pthread_t)); struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, 0); for(thread=0;thread<thread_count;thread++) { pthread_create(&thread_handles[thread],0,LLamarFunc,(void *)thread); } for(thread=0;thread<thread_count;thread++) { pthread_join(thread_handles[thread],0); } gettimeofday(&t_fin, 0); secs = timeval_diff(&t_fin, &t_ini); printf("%.16g milliseconds\\n", secs * 1000.0); free(thread_handles); return 0; }
0
#include <pthread.h> struct fio_data { size_t size; }; static inline void get_mdelay_abstime(struct timespec *abstime, unsigned long ms) { struct timeval delta; gettimeofday(&delta, 0); abstime->tv_sec = delta.tv_sec + (ms/1000); abstime->tv_nsec = (delta.tv_usec + (ms%1000) * 1000) * 1000; if ( abstime->tv_nsec > 1000000000 ) { abstime->tv_sec += 1; abstime->tv_nsec -= 1000000000; } } static void *fio_write_thread(void *arg) { struct fio_info *io_info = arg; struct fio_data *data = 0; struct ft_fifo *fifo = io_info->fifo; int fd; unsigned int len; struct timespec abstime; pthread_mutex_lock(&io_info->start_write_lock); pthread_cond_wait(&io_info->start_wcond, &io_info->start_write_lock); pthread_mutex_unlock(&io_info->start_write_lock); fd = io_info->fd; while((len=ft_fifo_len(fifo)) || !(io_info->status&4)) { if(io_info->status & 2) { get_mdelay_abstime(&abstime, 30); pthread_mutex_lock(&io_info->start_write_lock); pthread_cond_timedwait(&io_info->start_wcond, &io_info->start_write_lock, &abstime); pthread_mutex_unlock(&io_info->start_write_lock); continue; } if(!len) { pthread_cond_signal(&io_info->end_wcond); get_mdelay_abstime(&abstime, 30); pthread_mutex_lock(&io_info->start_write_lock); pthread_cond_timedwait(&io_info->start_wcond, &io_info->start_write_lock, &abstime); pthread_mutex_unlock(&io_info->start_write_lock); continue; } ft_fifo_get(fifo, (unsigned char*)&data, sizeof(void*)); len = write(fd, (unsigned char*)data+sizeof(*data), data->size); free(data); }; pthread_exit(0); } void fio_wait_write_stop_and_pending(struct fio_info *io_info) { if(ft_fifo_len(io_info->fifo)) { pthread_mutex_lock(&io_info->end_write_lock); pthread_cond_wait(&io_info->end_wcond, &io_info->end_write_lock); pthread_mutex_unlock(&io_info->end_write_lock); } io_info->status = 2; } void fio_trigger_write(struct fio_info *io_info) { if(!(io_info->status&1)) io_info->status = 1; pthread_cond_signal(&io_info->start_wcond); } ssize_t fio_write(struct fio_info *io_info, const void *buf, size_t count) { struct fio_data *data; data = malloc(count+sizeof(data)); if(!data) { perror("fio_write:malloc for fio_data failed!\\n"); return 0; } data->size = count; memcpy((unsigned char*)data+sizeof(*data), buf, count); if(ft_fifo_put(io_info->fifo, (unsigned char*)&data, sizeof(void*))) { if ( pthread_cond_signal(&io_info->start_wcond) != 0 ) perror("pthread_cond_signal() failed(start_wcond)"); } else { printf("ft_fifo_put failed!"); free(data); count = 0; } return count; } struct fio_info *fio_alloc(void) { struct fio_info *io_info; int res; io_info = malloc(sizeof(struct fio_info)); if(!io_info) { perror("Memory alloc failed for fio_info."); return 0; } io_info->fifo = ft_fifo_alloc(sizeof(void*)*512); if(IS_ERR(io_info->fifo)) { free(io_info); printf("ft_fifo_alloc failed."); return 0; } io_info->status = 1; if(pthread_mutex_init(&io_info->start_write_lock, 0) != 0) { perror("Mutex initialization failed!(start_write_lock)\\n"); free(io_info); return 0; } if(pthread_mutex_init(&io_info->end_write_lock, 0) != 0) { perror("Mutex initialization failed!(end_write_lock)\\n"); free(io_info); return 0; } if (pthread_cond_init(&io_info->start_wcond, 0) < 0 ) { free(io_info); perror("pthread_cond_init() failed(start_wcond)"); return 0; } if (pthread_cond_init(&io_info->end_wcond, 0) < 0 ) { free(io_info); perror("pthread_cond_init() failed(end_wcond)"); return 0; } res = pthread_create(&io_info->thread, 0, fio_write_thread, (void*)io_info); if(res != 0) { printf("Thread creation failed."); return 0; } return io_info; } void fio_free(struct fio_info *io_info) { int res; void *thread_result; io_info->status = 4; res = pthread_join(io_info->thread, &thread_result); if(res != 0) printf("Thread join failed"); ft_fifo_free(io_info->fifo); pthread_cond_destroy(&io_info->start_wcond); pthread_cond_destroy(&io_info->end_wcond); free(io_info); }
1
#include <pthread.h> volatile int val; pthread_mutex_t me; } protected_int_t; void protected_int_init(protected_int_t *, int); protected_int_t a_done, b_done, a_cat, b_cat; volatile int n_merge; int n; int *a_array, *b_array; void *ta_work(void *arg); void *tb_work(void *arg); int main(int argc, char ** argv) { pthread_t *ta, *tb; int i, *ids; if(argc != 2) { fprintf(stderr, "Missing parameter. Usage: %s n\\n", argv[0]); return 1; } n = atoi(argv[1]); if(n == 0 || n % 2 != 0) { fprintf(stderr, "Parameter n must be a positive even number\\n"); return 2; } ta = calloc(n, sizeof(pthread_t)); tb = calloc(n, sizeof(pthread_t)); a_array = calloc(n, sizeof(int)); b_array = calloc(n, sizeof(int)); ids = calloc(n, sizeof(int)); if(!ta || !tb || !a_array || !b_array) { fprintf(stderr, "Error in allocation\\n"); return 3; } srand(time(0)); protected_int_init(&a_done, 0); protected_int_init(&b_done, 0); protected_int_init(&a_cat, 0); protected_int_init(&b_cat, 0); n_merge = 0; for(i = 0; i < n; i++) { ids[i] = i; if(pthread_create(&ta[i], 0, ta_work, &ids[i]) || pthread_create(&tb[i], 0, tb_work, &ids[i])) { fprintf(stderr, "Error creating threads\\n"); return 4; } } pthread_detach(pthread_self()); pthread_exit(0); } void *ta_work(void *arg) { int t, tmp, id; pthread_detach(pthread_self()); id = *(int *)arg; t = rand() % 4; sleep(t); pthread_mutex_lock(&a_done.me); tmp = a_done.val++; a_array[tmp] = id; pthread_mutex_unlock(&a_done.me); tmp++; if(tmp % 2 == 0) { printf("A%d cats A%d A%d\\n", a_array[tmp - 1], a_array[tmp - 2], a_array[tmp - 1]); tmp = -1; pthread_mutex_lock(&a_cat.me); pthread_mutex_lock(&b_cat.me); a_cat.val++; if((a_cat.val > n_merge) && (b_cat.val > n_merge)) { n_merge++; tmp = n_merge * 2; } pthread_mutex_unlock(&b_cat.me); pthread_mutex_unlock(&a_cat.me); if(tmp >= 0) { printf("\\t\\t\\tA%d merges A%d A%d B%d B%d\\n", a_array[tmp - 1], a_array[tmp - 2], a_array[tmp - 1], b_array[tmp - 2], b_array[tmp - 1]); } } pthread_exit(0); } void *tb_work(void *arg) { int t, tmp, id; pthread_detach(pthread_self()); id = *(int *)arg; t = rand() % 4; sleep(t); pthread_mutex_lock(&b_done.me); tmp = b_done.val++; b_array[tmp] = id; pthread_mutex_unlock(&b_done.me); tmp++; if(tmp % 2 == 0) { printf("B%d cats B%d B%d\\n", b_array[tmp - 1], b_array[tmp - 2], b_array[tmp - 1]); tmp = -1; pthread_mutex_lock(&a_cat.me); pthread_mutex_lock(&b_cat.me); b_cat.val++; if((a_cat.val > n_merge) && (b_cat.val > n_merge)) { n_merge++; tmp = n_merge * 2; } pthread_mutex_unlock(&b_cat.me); pthread_mutex_unlock(&a_cat.me); if(tmp >= 0) { printf("\\t\\t\\tB%d merges A%d A%d B%d B%d\\n", b_array[tmp - 1], a_array[tmp - 2], a_array[tmp - 1], b_array[tmp - 2], b_array[tmp - 1]); } } pthread_exit(0); } void protected_int_init(protected_int_t *pi, int val) { pthread_mutex_init(&pi->me, 0); pi->val = val; }
0
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_write = PTHREAD_COND_INITIALIZER; int common_value = 0; int readers = 0; void *readerFunc(void *param); void *writerFunc(void *param); int main(int argc, char **argv) { pthread_t treaders[5], twriters[5]; int i; for (i = 0; i < 5; i++) { if (pthread_create(&treaders[i], 0, readerFunc, 0)) { fprintf(stderr, "%s\\n", "Unalble to create reader"); exit(1); } if (pthread_create(&twriters[i], 0, writerFunc, 0)) { fprintf(stderr, "%s\\n", "Unalble to create writer"); exit(1); } } for(int i = 0; i < 5; i++) { pthread_join(treaders[i], 0); pthread_join(twriters[i], 0); } return 0; } void *readerFunc(void *params) { int read_times = 0; while(read_times < 4) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); srand(t.tv_nsec); int random_wait = rand() % 4 + 2; int start_time = time(0); sleep(random_wait); pthread_mutex_lock(&m); readers++; pthread_mutex_unlock(&m); printf("READER\\tvalue: %d, remaining readers: %d \\n", common_value, readers); fflush(stdout); pthread_mutex_lock(&m); readers--; if (readers == 0) { pthread_cond_broadcast(&c_write); } pthread_mutex_unlock(&m); read_times++; } } void *writerFunc(void *params) { int write_times = 0; while(write_times < 4) { struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t); srand(t.tv_nsec); int random_wait = rand() % 4 + 2; int start_time = time(0); sleep(random_wait); pthread_mutex_lock(&m); while(readers != 0) { pthread_cond_wait(&c_write, &m); } common_value++; printf("WRITER\\tvalue: %d, remaining readers: %d \\n", common_value, readers); fflush(stdout); pthread_cond_broadcast(&c_write); pthread_mutex_unlock(&m); write_times++; } }
1
#include <pthread.h> static pthread_cond_t runtime_init_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t runtime_init_mu = PTHREAD_MUTEX_INITIALIZER; static int runtime_init_done; static void (*cgo_context_function)(struct context_arg*); void x_cgo_sys_thread_create(void* (*func)(void*), void* arg) { pthread_t p; int err = _cgo_try_pthread_create(&p, 0, func, arg); if (err != 0) { fprintf(stderr, "pthread_create failed: %s", strerror(err)); abort(); } } uintptr_t _cgo_wait_runtime_init_done() { void (*pfn)(struct context_arg*); pthread_mutex_lock(&runtime_init_mu); while (runtime_init_done == 0) { pthread_cond_wait(&runtime_init_cond, &runtime_init_mu); } pfn = cgo_context_function; pthread_mutex_unlock(&runtime_init_mu); if (pfn != nil) { struct context_arg arg; arg.Context = 0; (*pfn)(&arg); return arg.Context; } return 0; } void x_cgo_notify_runtime_init_done(void* dummy) { pthread_mutex_lock(&runtime_init_mu); runtime_init_done = 1; pthread_cond_broadcast(&runtime_init_cond); pthread_mutex_unlock(&runtime_init_mu); } void x_cgo_set_context_function(void (*context)(struct context_arg*)) { pthread_mutex_lock(&runtime_init_mu); cgo_context_function = context; pthread_mutex_unlock(&runtime_init_mu); } void (*(_cgo_get_context_function(void)))(struct context_arg*) { void (*ret)(struct context_arg*); pthread_mutex_lock(&runtime_init_mu); ret = cgo_context_function; pthread_mutex_unlock(&runtime_init_mu); return ret; } int _cgo_try_pthread_create(pthread_t* thread, const pthread_attr_t* attr, void* (*pfn)(void*), void* arg) { int tries; int err; struct timespec ts; for (tries = 0; tries < 20; tries++) { err = pthread_create(thread, attr, pfn, arg); if (err == 0) { pthread_detach(*thread); return 0; } if (err != EAGAIN) { return err; } ts.tv_sec = 0; ts.tv_nsec = (tries + 1) * 1000 * 1000; nanosleep(&ts, nil); } return EAGAIN; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long) t; for (i = 0; i < 5; i++) { pthread_mutex_lock(&count_mutex); count++; if (count < 7) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit("someone like you"); } void *watch_count(void *t) { long my_id = (long) t; printf("Starting watch_count(): thread %ld\\n", my_id); while (count < 7) { pthread_mutex_lock(&count_mutex); printf("watch_count(): thread %ld going into wait...\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); } pthread_exit(0); } int main(int argc, char *argv[]) { int i; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *) t1); pthread_create(&threads[1], &attr, inc_count, (void *) t2); pthread_create(&threads[2], &attr, inc_count, (void *) t3); char* ret1; for (i = 1; i < 3; i++) { pthread_join(threads[i], (void**)&ret1); } pthread_cond_signal(&count_threshold_cv); pthread_join(threads[0],0); printf("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> pthread_t tid; struct job { pthread_t tid; Job next; int val; }; pthread_mutex_t q_lock = PTHREAD_MUTEX_INITIALIZER; int insert(Job head, int val, pthread_t tid) { Job p, q; p = head; if (p != 0) { while (p->next != 0) { p = p->next; } } q = (Job)malloc(sizeof(struct job)); if (q == 0) { perror("fail to malloc"); return -1; } q->next = 0; q->val = val; q->tid = tid; if (p == 0) { head = q; return 0; } p->next = q; return 0; } void get_job(Job head, Job task, int * count, pthread_t tid) { Job p, q; q = head; p = q->next; while (p != 0) { if (tid == p->tid) { q->next = p->next; p->next = 0; while (task->next != 0) { task = task->next; } task->next = p; p = q->next; ++(*count); } else { q = p; p = p->next; } } } int free_job(Job head) { Job p, q; for (p = head; p != 0; p = p->next) { q = p; free(q); } return 0; } void print(Job head) { Job p; for (p = head->next; p != 0; p = p->next) { printf("thread %u : %d\\n", (unsigned int)p->tid, p->val); } } void * tfn7(void * arg) { int count; Job task = (struct job *)malloc(sizeof(struct job)); task->next = 0; task->val = 0; task->tid = -1; pthread_t tid = pthread_self(); count = 0; while (count < 3) { if (pthread_mutex_trylock(&q_lock) == 0) { get_job(arg, task, &count, tid); pthread_mutex_unlock(&q_lock); } } print(task); if (free_job(task) == -1) { exit(1); } return (void *)0; } int main() { Job item; pthread_t tid1, tid2; int i, err; item = (struct job *)malloc(sizeof(struct job)); item->next = 0; item->val = 0; item->tid = -1; if ((err = pthread_create(&tid1, 0, tfn7, item)) == -1) { printf("fail to create thread %s\\n", strerror(err)); exit(0); } if ((err = pthread_create(&tid2, 0, tfn7, item)) == -1) { printf("fail to create thread %s\\n", strerror(err)); exit(0); } printf("===the 1st put===\\n"); pthread_mutex_lock(&q_lock); for (i = 0; i < 2; ++i) { if (insert(item, i, tid1) == -1) { exit(1); } if (insert(item, i + 1, tid2) == -1) { exit(1); } } if (insert(item, 10, tid1) == -1) { exit(1); } pthread_mutex_unlock(&q_lock); sleep(5); printf("===the 2nd put===\\n"); pthread_mutex_lock(&q_lock); if (insert(item, 9, tid2) == -1) { exit(1); } pthread_mutex_unlock(&q_lock); err = pthread_join(tid1, 0); if (err != 0) { printf("can't join thread %s\\n", strerror(err)); exit(1); } err = pthread_join(tid2, 0); if (err != 0) { printf("can't join thread %s\\n", strerror(err)); exit(1); } printf("main thread done\\n"); if (item->next == 0) { printf("No job in the queue\\n"); } free(item); return 0; }
0
#include <pthread.h> pthread_mutex_t lock; int shared_data; void mutex_cleanup(void *m) { pthread_mutex_t *p = (pthread_mutex_t *)m; printf(" Inside cancellation handler. Cleaning up elegantly...\\n"); pthread_mutex_unlock(p); } void *thread_function(void *arg) { int old_state; int old_type; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &old_state); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_type); pthread_mutex_lock(&lock); pthread_cleanup_push(mutex_cleanup, &lock); sleep(120); pthread_cleanup_pop(0); pthread_mutex_unlock(&lock); return 0; } int main(void) { pthread_t threadID; void *result; pthread_mutex_init(&lock, 0); pthread_create(&threadID, 0, thread_function, 0); printf("Subordinate thread created. Waiting...\\n"); sleep(10); printf("It's taking too long! Cancelling...\\n"); if (pthread_cancel(threadID) == ESRCH) { printf("Something went wrong... the thread appears to be already dead.\\n"); } printf("Done!\\n"); pthread_join(threadID, &result); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> static FILE *logg_file_ptr = 0; static pthread_mutex_t *logg_mutex = 0; static struct tm t; static struct timeval tval; enum LoggLevelEnum logg_level; int logg_construct() { logg_file_ptr = stderr; logg_level = get_logg_level(); if (mutex_init() != 0) { return -1; } } void logg_destruct() { logg_file_unsafe_close(); mutex_destroy(); } int logg_file_open(const char *filename) { int ret = 0; if (!logg_mutex && (mutex_init() != 0)) { fprintf(stderr, "ERROR in %s:%d init mutex err\\n", "logg.c", 28); return -1; } pthread_mutex_lock(logg_mutex); logg_file_unsafe_close(); if (!filename || !(logg_file_ptr = fopen(filename, "a"))) { fprintf(stderr, "ERROR in %s:%d open file err\\n", "logg.c", 35); ret = -1; } pthread_mutex_unlock(logg_mutex); return ret; } void logg_file_unsafe_close() { if (logg_file_ptr != stderr) fclose(logg_file_ptr); logg_file_ptr = stderr; } int mutex_init() { if (logg_mutex) { fprintf(stderr, "ERROR in %s:%d logg_mutex init already\\n", "logg.c", 51); return -1; } logg_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t *)); return pthread_mutex_init(logg_mutex, 0); } int mutex_destroy() { int ret = pthread_mutex_destroy(logg_mutex); free(logg_mutex); logg_mutex = 0; return ret; } void logg_func(const char *file, int line, const char* szFormat, ...) { pthread_mutex_lock(logg_mutex); char *szMessage; va_list vaArguments; __builtin_va_start((vaArguments)); vasprintf(&szMessage, szFormat, vaArguments); ; gettimeofday(&tval, 0); localtime_r(&tval.tv_sec, &t); fprintf(logg_file_ptr, "[P%u:T%u][%04d-%02d-%02d %02d:%02d:%02d,%03d][%s:%d]%s\\n", (unsigned int)getpid(), (unsigned int)pthread_self() ,t.tm_year + 1900, t.tm_mon + 1, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec, tval.tv_usec, file, line, szMessage); fflush(logg_file_ptr); free(szMessage); pthread_mutex_unlock(logg_mutex); } enum LoggLevelEnum get_logg_level() { enum LoggLevelEnum the_level; char *level = getenv(LOGG_ENV_LEVEL_VAL); printf("get debug level: %s\\n", level); if(level == 0){ the_level = LOGG_LEVEL_DEFAULT; }else if(strncasecmp(level, "ALL", 3) == 0){ the_level = LOGG_LEVEL_ALL; }else if(strncasecmp(level, "DEBUG", 5) == 0){ the_level = LOGG_LEVEL_DEBUG; }else if(strncasecmp(level, "INFO", 4) == 0){ the_level = LOGG_LEVEL_INFO; }else if(strncasecmp(level, "WARN", 4) == 0){ the_level = LOGG_LEVEL_WARN; }else if(strncasecmp(level, "ERROR", 5) == 0){ printf("find error\\n"); the_level = LOGG_LEVEL_ERROR; }else if(strncasecmp(level, "FATAL", 5) == 0){ the_level = LOGG_LEVEL_FATAL; }else{ the_level = LOGG_LEVEL_DEFAULT; } return the_level; } int main(int argc, char *argv[]) { logg_construct(); LOGG_DEBUG("log pure strings"); int a = 10; LOGG_DEBUG("a=%d", a); LOGG_INFO("a=%d", a); LOGG_WARN("a=%d", a); LOGG_ERROR("a=%d", a); LOGG_FATAL("a=%d", a); logg_destruct(); return 0; }
0
#include <pthread.h> void receive_external_request() { struct event_queue_node eq_node; pthread_mutex_lock(&ftl_to_nand->mutex); while (ftl_to_nand->num_of_entries != 0) { eq_node = if_dequeue(ftl_to_nand); QueryPerformanceCounter(&eq_node.time); if (eq_node.time_offset >= 0) { eq_node.time.QuadPart += eq_node.time_offset; } eq_node.dst = DS; enqueue_event_queue(eq, eq_node); } pthread_mutex_unlock(&ftl_to_nand->mutex); }
1
#include <pthread.h> int iterationsNumber = 10000; int counter = 0; void * thread_func1() { int i; int counter1 = 0; for (i = 0; counter < iterationsNumber; i++) { pthread_mutex_lock( &mutex1 ); counter++; pthread_mutex_unlock( &mutex1 ); counter1 ++; } printf("common counter is %d\\n", counter); printf("pthread counter1 is %d\\n", counter1); } void * thread_func2() { int i; int counter2 = 0; for (i = 0; counter < iterationsNumber; i++) { pthread_mutex_lock( &mutex1 ); counter++; pthread_mutex_unlock( &mutex1 ); counter2++; } printf("pthread counter2 is %d\\n", counter2); } int main(int argc, char * argv[]) { int result; pthread_t thread1, thread2; result = pthread_create(&thread1, 0, thread_func1, 0); if (result != 0) { perror("Creating the first thread"); return 1; } result = pthread_create(&thread2, 0, thread_func2, 0); if (result != 0) { perror("Creating the second thread"); return 1; } result = pthread_join(thread1, 0); if (result != 0) { perror("Joining the first thread"); return 1; } result = pthread_join(thread2, 0); if (result != 0) { perror("Joining the second thread"); return 1; } printf("Done\\n"); return 0; }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i < end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100*sizeof(double)); b = (double*) malloc (4*100*sizeof(double)); for (i=0; i < 100*4; i++) { a[i]=1.0; b[i]=a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i < 4; i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0; i<4; i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> int lock_var = 0; time_t end_time; pthread_mutex_t mutex; 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_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&mutex, &mutexattr); 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; }
0
#include <pthread.h> pthread_mutex_t db_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t op_lock = PTHREAD_MUTEX_INITIALIZER; int seats=20; int active_op; pthread_t op[3]; void *confirm_booking(); void *inizializza(); void *operatore(); void *wait_client(); int check_availability(); int ask_confirmation(); void *book_seat(); void main(int argc, char *args){ int k; inizializza(); for(k=0;k<3;k++){ pthread_join(op[k],0); } printf("Agenzia chiusa!\\n"); } void *inizializza(){ int j; for (j=0;j<3;j++){ pthread_create( &op[j],0,operatore,0 ); } } void *operatore(){ while(1){ srand(time(0)); wait_client(); pthread_mutex_lock(&op_lock); active_op++; if (active_op==1){ pthread_mutex_lock(&db_lock); } pthread_mutex_unlock(&op_lock); if (check_availability()){ pthread_mutex_lock(&op_lock); active_op--; if (active_op==0){ pthread_mutex_unlock(&db_lock); } pthread_mutex_unlock(&op_lock); if (ask_confirmation()){ pthread_mutex_lock(&db_lock); if (check_availability()){ book_seat(); pthread_mutex_unlock(&db_lock); confirm_booking(); } else { pthread_mutex_unlock(&db_lock); printf("Ci dispiace, qualcuno ha prenotato il posto prima di lei\\n"); } } else { pthread_mutex_lock(&op_lock); active_op--; if (active_op==0){ pthread_mutex_unlock(&db_lock); } pthread_mutex_unlock(&op_lock); printf("Ci dispiace che abbia cambiato idea, speriamo di rivederla al piu' presto!\\n"); } } else { pthread_mutex_lock(&op_lock); active_op--; if (active_op==0){ pthread_mutex_unlock(&db_lock); } pthread_mutex_unlock(&op_lock); printf("Ci dispiace, il viaggio che le interessa e' gia' al completo! Speriamo di rivederla presto.\\n"); break; } } } void *wait_client(){ int i; int delay; delay = rand(); for (i=0;i<delay;i++) { } } int check_availability(){ int availability = seats>0 ? 1 : 0; return availability; } int ask_confirmation(){ int confirmation = (float)((double)rand()/(double)32767)<0.75 ? 1:0; return confirmation; } void *book_seat(){ seats--; } void *confirm_booking(){ printf("L'operatore %u effettua una prenotazione!\\n",pthread_self()); }
1
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can’t set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can’t create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> void* producer1(void* pid) { int z_var = 0x60; int PID = *(int*) pid; printf("Producer 1 (%d): starte prod 1\\n", PID); while(1) { pthread_mutex_lock(&prod1_mutex); while(!is_running_prod1) { pthread_cond_wait(&cond_prod1, &prod1_mutex); pthread_mutex_unlock(&prod1_mutex); pthread_testcancel(); pthread_mutex_lock(&prod1_mutex); } pthread_mutex_unlock(&prod1_mutex); z_var++; if(z_var > 0x7A) { z_var = 0x60; } pthread_mutex_lock(&rb_mutex); while(p_rb->p_in == p_rb->p_out && p_rb->count == MAX_BUFFER_SIZE) { printf("Producer 1 (%d): Buffer ist voll.\\n", PID); pthread_cond_wait(&is_not_full, &rb_mutex); pthread_mutex_unlock(&rb_mutex); if(kill) { pthread_exit(0); } pthread_mutex_lock(&rb_mutex); } *(p_rb->p_in) = (char) z_var; printf("Producer 1 (%d): Zeichen wurde in Ringbuffer geschrieben.\\n", PID); (p_rb->p_in)++; if((p_rb->p_in) > p_end) { p_rb->p_in = p_start; } (p_rb->count)++; if(p_rb->count != 0) { printf("Producer 1 (%d): Buffer nicht leer.\\n", PID); pthread_cond_signal(&is_not_empty); } pthread_mutex_unlock(&rb_mutex); sleep(3); } printf("Producer1 beendet\\n"); return (0); }
1
#include <pthread.h> int filas_vazias = 3; int totcli; int i, t; int ncli = 0; int tem_cliente = 0; int tamfila[3]; int fila_espera = 0; int clientes = 10; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex3 = PTHREAD_MUTEX_INITIALIZER; sem_t empty; sem_t full; void NoCaixa (float delay1) { if (delay1<0.001) return; float inst1=0; float inst2=0; inst1 = (float)clock()/(float)CLOCKS_PER_SEC; while (inst2-inst1<delay1) inst2 = (float)clock()/(float)CLOCKS_PER_SEC; return; } void Chama_ListaEspera(int *tamfila){ int menorfila; int caixa; menorfila = 10; caixa = 3 + 1; for(i=0; i<3; i++){ if(tamfila[i] < menorfila){ menorfila = tamfila[i]; caixa = i; } } if(tamfila[caixa] < 10){ tamfila[caixa]++; fila_espera--; printf("INSERIRU CLIENTE NA FILA DO CAIXA: %d -> Lista_Espera %d \\n", caixa, fila_espera); tem_cliente++; } else{ printf("Todos os caixas estao cheios! fila_espera=%d\\n", fila_espera); } } void *Clientes(void *thread_id){ int menorfila; int caixa; while(ncli < 10){ menorfila = 10; caixa = 3 + 1; if(fila_espera == 0){ pthread_mutex_lock(&mutex); for(i=0; i<3; i++){ if(tamfila[i] < menorfila){ menorfila = tamfila[i]; caixa = i; } } pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if(tamfila[caixa] == 10){ printf("CAIXA %d esta com a capacidade maxima \\n", caixa); fila_espera++; } else{ tamfila[caixa]++; printf("INSERIRU CLIENTE NA FILA DO CAIXA: %d - %d\\n", caixa, ncli); tem_cliente++; ncli++; } pthread_mutex_unlock(&mutex); } else{ pthread_mutex_lock(&mutex); for(i=0; i<3; i++){ if(tamfila[i] < menorfila){ menorfila = tamfila[i]; caixa = i; } } pthread_mutex_unlock(&mutex); if(tamfila[caixa] < 10){ pthread_mutex_lock(&mutex); tamfila[caixa]++; fila_espera--; printf("INSERIRU CLIENTE NA FILA DO CAIXA: %d -> Lista_Espera %d %d\\n", caixa, fila_espera, ncli); tem_cliente++; ncli++; pthread_mutex_unlock(&mutex); } else{ printf("Todos os caixas estao cheios! fila_espera=%d\\n", fila_espera); } } } } int *Atende(void *thread_id){ int caixa; int maiorfila; int caixa_maiorfila; while (clientes > 0){ if(tem_cliente > 0){ caixa = (int)thread_id; printf("\\nclientes = %d tem_cliente=%d caixa=%d\\n", clientes, tem_cliente, caixa); maiorfila = tamfila[0]; caixa_maiorfila = 0; if(tamfila[caixa] == 0){ for(i=0; i<3; i++){ if(tamfila[i] > maiorfila){ maiorfila = tamfila[i]; caixa_maiorfila = i; } } pthread_mutex_lock(&mutex3); printf("O CAIXA %d ATENDEU CLIENTE DO CAIXA %d \\n", caixa, caixa_maiorfila); NoCaixa (2); tamfila[caixa_maiorfila] = tamfila[caixa_maiorfila] - 1; tem_cliente--; pthread_mutex_unlock(&mutex3); } else{ pthread_mutex_lock(&mutex3); printf("O CAIXA %d ATENDEU\\n", caixa); NoCaixa (2.5); tamfila[caixa] = tamfila[caixa] - 1; tem_cliente--; pthread_mutex_unlock(&mutex3); } } } } int main(){ pthread_t atendentes [3]; pthread_t gclientes; srand(time(0)); for(i=0; i<3; i++){ tamfila[i] = 0; } printf("\\nTAMANHO DA FILA INICIAL: "); for(i=0; i<3; i++){ printf("%d ", tamfila[i]); } printf("\\n\\n"); sem_init(&empty, 0, 3); sem_init(&full, 0, 0); pthread_create(&gclientes, 0, Clientes, (void*)10); for (t = 0; t<3; t++){ if (pthread_create(&atendentes[t], 0, Atende, (void*)t)) { printf("Erro criação fila %d\\n", t); } } printf("Acabou a thread\\n"); pthread_join(gclientes, 0); printf("join gclientes\\n"); for (t = 0; t < 3; t++){ pthread_join(atendentes[t], 0); } printf("join atendentes\\n"); printf("\\nnumero de cliente atendidos = %d \\nclientes para serem atendidos = %d \\n", ncli, tem_cliente); return 0; }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cvar[2] = {PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER}; int current_cars; int waiting_cars[2]; int wait_timestamp; int current_direction; char *indent = "==============="; int i; int direction; } Car; void *OneVehicle(void *arg) { Car *tmpCar = (Car *) arg; int i = tmpCar -> i; int direction = tmpCar -> direction; int rc, t; rc = pthread_mutex_lock(&lock); if (rc) { printf("Car %d: Arrive failed!\\n", i); exit(-1); } waiting_cars[direction]++; if (current_direction >= 0) { while ((current_cars != 0 && current_direction != direction) || current_cars == 3) { pthread_cond_wait(&cvar[direction], &lock); } } waiting_cars[direction]--; if (current_direction != direction) { current_direction = direction; wait_timestamp = clock(); printf("%s Now the bridge's current direction is %s %s Timestamp : %d %s \\n", indent, ((direction) ? "NORWICH" : "HANOVER"), indent, wait_timestamp, indent); } current_cars++; pthread_mutex_unlock(&lock); if (rc) { printf("Car %d: release lock failed!\\n", i); exit(-1); } for (t = 1; t <= 3; t++) { sleep(1); rc = pthread_mutex_lock(&lock); if (rc) { printf("Car %d: on bridge failed!", i); exit(-1); } printf("Car %d has been on the bridge for %d minutes.\\tThe bridge has %d %s.\\tCars waiting to NORWICH : %d\\tCars waiting to HANOVER : %d\\n", i, t, current_cars, current_cars <= 1 ? "car" : "cars", waiting_cars[1], waiting_cars[0]); rc = pthread_mutex_unlock(&lock); if (rc) { printf("Car %d: release lock failed!\\n", i); exit(-1); } } rc = pthread_mutex_lock(&lock); if (rc) { printf("Car %d: Get off failed!", i); exit(-1); } current_cars--; int waiting_time = (clock() - wait_timestamp) / 1000; if (waiting_cars[1 - direction] == 0 || waiting_time <= 2) { pthread_cond_signal(&cvar[direction]); } if (current_cars == 0) pthread_cond_broadcast(&cvar[1 - direction]); rc = pthread_mutex_unlock(&lock); if (rc) { printf("Car %d release lock failed!\\n", i); exit(-1); } return 0; } int main(int argc, char *argv[]) { pthread_t threads[30]; Car Cars[30]; int i, rc; current_direction = -1; current_cars = 0; waiting_cars[1] = 0; waiting_cars[0] = 0; for (i = 0; i < 30; i++) { Cars[i].i = i; Cars[i].direction = ((i % 2) ? 1 : 0); rc = pthread_create(&threads[i], 0, OneVehicle, (void *) &Cars[i]); if (rc) { printf("Create new thread failed!\\n"); exit(-1); } } for (i = 0; i < 30; i++) { rc = pthread_join(threads[i], 0); } return 0; }
1
#include <pthread.h> int finish = 0, mutex_enable = 1, error_enable = 0; char *cadeia[10] = {"aaaaaaaaa\\n","bbbbbbbbb\\n","ccccccccc\\n","ddddddddd\\n","eeeeeeeee\\n", "fffffffff\\n","ggggggggg\\n","hhhhhhhhh\\n","iiiiiiiii\\n","jjjjjjjjj\\n"}; pthread_mutex_t vec_mutex[N_FILES]; void usr1_handler(){ mutex_enable++; puts("Received mutex toogle!"); } void usr2_handler(){ error_enable++; puts("Received error toogle!"); } void stop_handler(){ finish = 1; puts("Writer received stop!"); } int escritor(){ int file, escolhida, id_file, k, local_enable; char filename[13]; while(1){ local_enable = mutex_enable; if(finish) return 0; strcpy(filename, "SO2014-0.txt"); id_file = rand() % N_FILES; filename[INDICE_ID_FILE] += id_file; file = open(filename, O_RDWR | O_CREAT, PERMISSION_CODE_W); if (file < 0){ perror("Open: Failed\\n"); return -1; } if(local_enable % 2){ if(flock(file, LOCK_EX) < 0){ perror("Flock on Lock: Failed.\\n"); close(file); return -1; } } if(pthread_mutex_lock(&vec_mutex[id_file]) != 0){ perror("Lock mutex: Failed"); flock(file, LOCK_UN); close(file); return -1; } escolhida = rand() % 10; if(error_enable % 2) write(file, "zzzzzzzzz\\n", 10); else write(file, cadeia[escolhida], 10); for(k = 1; k < N_LINES; k++){ if(write(file, cadeia[escolhida], 10) != 10){ perror("Write line: Failed\\n"); pthread_mutex_unlock(&vec_mutex[id_file]); flock(file, LOCK_UN); close(file); return -1; } } if(pthread_mutex_unlock(&vec_mutex[id_file]) != 0){ perror("Unlock mutex: Failed"); flock(file, LOCK_UN); close(file); return -1; } if(local_enable % 2){ if(flock(file, LOCK_UN) < 0){ perror("Flock on Lock: Failed.\\n"); close(file); return -1; } } close(file); } return 0; } int main(){ int i, j; pthread_t thread_array[N_THREAD_WRITE]; struct sigaction new_action1; struct sigaction new_action2; struct sigaction new_action3; new_action1.sa_handler = usr1_handler; sigemptyset (&new_action1.sa_mask); sigaddset(&new_action1.sa_mask, SIGUSR1); new_action1.sa_flags = 0; sigaction(SIGUSR1, &new_action1, 0); new_action2.sa_handler = usr2_handler; sigemptyset (&new_action2.sa_mask); sigaddset(&new_action2.sa_mask, SIGUSR2); new_action2.sa_flags = 0; sigaction(SIGUSR2, &new_action2, 0); new_action3.sa_handler = stop_handler; sigemptyset (&new_action3.sa_mask); sigaddset(&new_action3.sa_mask, SIGTSTP); new_action3.sa_flags = 0; sigaction(SIGTSTP, &new_action3, 0); srand(time(0)); for(i = 0; i < N_FILES; i++){ if(pthread_mutex_init(&vec_mutex[i], 0) != 0){ perror("Initialize mutex: Failed"); return -1; } } for(i = 0; i < N_THREAD_WRITE; i++){ if(pthread_create(&thread_array[i], 0, (void *) escritor, 0) != 0){ perror("Create thread: Failed"); return -1; } } for(i = 0; i < N_THREAD_WRITE; i++){ if(pthread_join(thread_array[i], 0) != 0){ perror("Join thread: Failed"); return -1; } } return 0; }
0
#include <pthread.h> pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t null_pls = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); void *function3(); int count = 0; int COUNT_DONE = 0; char * s = ""; void parseArgs(int argc, char * argv[]){ int opt; static struct option long_options[] = { {"help", 0, 0, 'h'} }; int option_index = 0; do { opt = getopt_long(argc, argv, "h", long_options, &option_index); switch(opt){ case 'h': printf("help"); break; default: break; } } while (opt != -1); if (optind < argc ){ s= argv[argc -1]; COUNT_DONE = atoi(s); printf("\\nNacital som a idem od 0 po %d \\n", COUNT_DONE); } return; } int main(int argc, char * argv[]) { parseArgs(argc, argv); pthread_t thread1, thread2, thread3; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_create( &thread3, 0, &function3, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); pthread_join( thread3, 0); exit(0); return 0; } void *functionCount1(){ while(1){ pthread_mutex_lock( &condition_mutex ); while(count % 2 == 1) pthread_cond_wait( &condition_cond, &condition_mutex ); count++; if (count <= COUNT_DONE) printf("V1 -> %d\\n",count); pthread_mutex_unlock( &condition_mutex ); if(count >= COUNT_DONE) { } } return 0; } void *functionCount2(){ while(1){ pthread_mutex_lock( &condition_mutex ); if ( count % 2 == 0 && count < COUNT_DONE ) pthread_cond_signal( &condition_cond ); else if (count >= COUNT_DONE) { pthread_mutex_unlock( &condition_mutex); pthread_cond_signal( &null_pls); } else { count++; printf ("V2 --> %d\\n",count); } pthread_mutex_unlock( &condition_mutex ); } return 0; } void *function3(){ while(1){ pthread_mutex_lock( &condition_mutex); while(count < COUNT_DONE) pthread_cond_wait( &null_pls, &condition_mutex); if (count >= COUNT_DONE) {count = 0; printf("V3 nulujem count\\n"); } pthread_mutex_unlock( &condition_mutex); } return(0); }
1
#include <pthread.h> int num_printers, num_clients, buffer_size; pthread_cond_t not_full = PTHREAD_COND_INITIALIZER; pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *buffer; int printer_index = 0; int client_index = 0; int buffer_count = 0; void* printer(void *ptr){ while(1){ pthread_mutex_lock(&mutex); long tid; tid = (long)ptr; if(buffer_count == 0){ printf("No request in buffer, Printer %ld sleeps\\n", tid); pthread_cond_wait(&not_empty, &mutex); } int pages = buffer[printer_index]; int index = printer_index; printf("Printer %ld starts printing %d pages from Buffer[%d]\\n", tid, pages, index); buffer_count--; printer_index = (printer_index + 1)%buffer_size; pthread_mutex_unlock(&mutex); pthread_cond_signal(&not_full); sleep(pages); printf("Printer %ld finishes printing %d pages from Buffer[%d]\\n", tid, pages, index); } pthread_exit(0); } void* client(void *ptr){ while(1){ pthread_mutex_lock(&mutex); long tid; tid = (long)ptr; int pages = rand() % 10 + 1; if(buffer_count == buffer_size){ printf("Client %ld has %d pages to print, buffer full, sleeps\\n", tid, pages); pthread_cond_wait(&not_full, &mutex); printf("Client %ld wakes up, puts %d pages in Buffer[%d]\\n", tid, pages, client_index); } else{ printf("Client %ld has %d pages to print, puts request in Buffer[%d]\\n", tid, pages, client_index); } buffer[client_index] = pages; buffer_count++; client_index = (client_index + 1)%buffer_size; pthread_mutex_unlock(&mutex); pthread_cond_signal(&not_empty); sleep(5); } pthread_exit(0); } int main(){ printf("Number of clients : "); scanf("%d", &num_clients); printf("Number of printers : "); scanf("%d", &num_printers); printf("Buffer size : "); scanf("%d", &buffer_size); pthread_t clients[num_clients]; pthread_t printers[num_printers]; buffer = (int *) malloc(buffer_size * sizeof(int)); int rc; long t; for(t=0; t<num_clients; t++){ rc = pthread_create(&clients[t], 0, client, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } for(t=0; t<num_printers; t++){ rc = pthread_create(&printers[t], 0, printer, (void *)t); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_exit(0); return 1; }
0
#include <pthread.h> pthread_t thread1, thread2; static pthread_mutex_t verrou1, verrou2; int var1, var2, var3; void *lire(void *nom_du_thread) { pthread_mutex_lock(&verrou1); printf("lire variable 1 = %d\\n",var1); printf("lire variable 2 = %d\\n",var2); printf("lire variable 3 = %d\\n",var3); pthread_exit(0); } void *ecrire(void *nom_du_thread) { pthread_mutex_lock(&verrou2); var1=5; var2=10; var3=15; printf("ecriture %d dans variable 1 \\n",var1); sleep(1); printf("ecriture %d dans variable 2 \\n",var2); sleep(1); printf("ecriture %d dans variable 3 \\n",var3); sleep(1); pthread_exit(0); } int main() { pthread_mutex_init(&verrou1,0); pthread_mutex_init(&verrou2,0); pthread_mutex_lock(&verrou1); pthread_mutex_lock(&verrou2); pthread_create(&thread1,0,lire,0); pthread_create(&thread2,0,ecrire,0); pthread_mutex_unlock(&verrou2); pthread_join(thread2,0); pthread_mutex_unlock(&verrou1); pthread_join(thread1,0); }
1
#include <pthread.h> sem_t maachSem; sem_t dalSem; sem_t bhaatSem; struct my_arg{ int id; int slTime; char *p; }; struct my_arg argThrd[3]; struct timeval start, stop; pthread_mutex_t mutex; pthread_t service[3]; pthread_attr_t attr[3]; static int count = 1; int breaker; void enterLog(int id, char *item1) { gettimeofday(&stop, 0); FILE *fp; fp = fopen("log.txt", "a"); fprintf(fp, "%d \\t\\t %d \\t\\t %s \\t %lu\\n", count++, id, item1, ( stop.tv_usec - start.tv_usec )); fclose(fp); } void *runService1() { while(1){ sleep( rand() % 4); pthread_mutex_lock( &mutex ); sem_wait( &maachSem ); enterLog(1, "Maach"); sem_post(&maachSem); sem_wait( &dalSem ); enterLog(1, "Dal"); sem_post(&dalSem); pthread_mutex_unlock( &mutex ); if(breaker) break; } } void *runService2() { while(1){ sleep( rand() % 4); pthread_mutex_lock( &mutex ); sem_wait( &dalSem ); enterLog(2, "Dal"); sem_post(&dalSem); sem_wait( &bhaatSem ); enterLog(2, "Bhaat"); sem_post(&bhaatSem); pthread_mutex_unlock( &mutex ); if(breaker) break; } } void *runService3() { while(1){ sleep( rand() % 4); pthread_mutex_lock( &mutex ); sem_wait( &bhaatSem ); enterLog(3, "Bhaat"); sem_post(&bhaatSem); sem_wait( &maachSem ); enterLog(3, "Maach"); sem_post(&maachSem); pthread_mutex_unlock( &mutex ); if(breaker) break; } } void *runService(void *myStruct) { int i1, slTime1; struct my_arg *data1 = (struct my_arg *)myStruct; i1 = (data1 -> id); slTime1 = (data1 -> slTime); printf("data: %d, %d \\n",i1, slTime1 ); while( 1 ){ sleep( slTime1 ); pthread_mutex_lock( &mutex ); switch( i1 ){ case 1: sem_wait( &maachSem ); enterLog(1, "Maach"); sem_post( &maachSem); sem_wait( &dalSem ); enterLog(1, "Dal"); sem_post( &dalSem); break; case 2: sem_wait( &dalSem ); enterLog(2, "Dal"); sem_post( &dalSem); sem_wait( &bhaatSem ); enterLog(2, "Bhaat"); sem_post( &bhaatSem); break; case 3: sem_wait( &bhaatSem ); enterLog(3, "Bhaat"); sem_post( &bhaatSem); sem_wait( &maachSem ); enterLog(3, "Maach"); sem_post( &maachSem); break; } pthread_mutex_unlock( &mutex ); if(breaker) break; } return 0; } void initAll() { int i; FILE *fp; fp = fopen( "log.txt", "w"); fprintf(fp, "Sl.No\\tThread No\\tITEM\\t TIME (in Microseconds)\\n"); fclose( fp ); pthread_mutex_init( &mutex, 0); sem_init( &maachSem, 0, 1); sem_init( &dalSem, 0 ,1); sem_init( &bhaatSem, 0 ,1); breaker = 0; for (i = 0; i < 3; i++){ pthread_attr_init( &attr[i]); argThrd[i].id = (i + 1); argThrd[i].slTime = 1; argThrd[i].p = "ultron"; printf("Starting %d\\n", argThrd[i].id); pthread_create( &service[i], &attr[i], runService, (argThrd+i) ); } } int main(int argc, char *argv[]) { int status; int i; gettimeofday(&start, 0); initAll(); sleep(8); breaker = 1; for (i = 0; i < 3; i++){ status = pthread_join( service[i], 0); if( status != 0) perror("pthread"); } return 0; }
0
#include <pthread.h> static pthread_mutex_t gTempdirLock = PTHREAD_MUTEX_INITIALIZER; static int gTempdirNonce = 0; int recursiveDeleteContents(const char *path) { int ret; DIR *dp; struct dirent *de; char tmp[PATH_MAX]; dp = opendir(path); if (!dp) { ret = -errno; fprintf(stderr, "recursiveDelete(%s) failed with error %d\\n", path, ret); return ret; } while (1) { de = readdir(dp); if (!de) { ret = 0; break; } if ((de->d_name[0] == '.') && (de->d_name[1] == '\\0')) continue; if ((de->d_name[0] == '.') && (de->d_name[1] == '.') && (de->d_name[2] == '\\0')) continue; snprintf(tmp, sizeof(tmp), "%s/%s", path, de->d_name); ret = recursiveDelete(tmp); if (ret) break; } if (closedir(dp)) { ret = -errno; fprintf(stderr, "recursiveDelete(%s): closedir failed with " "error %d\\n", path, ret); return ret; } return ret; } int recursiveDelete(const char *path) { int ret; struct stat stBuf; ret = stat(path, &stBuf); if (ret != 0) { ret = -errno; fprintf(stderr, "recursiveDelete(%s): stat failed with " "error %d\\n", path, ret); return ret; } if (S_ISDIR(stBuf.st_mode)) { ret = recursiveDeleteContents(path); if (ret) return ret; ret = rmdir(path); if (ret) { ret = errno; fprintf(stderr, "recursiveDelete(%s): rmdir failed with error %d\\n", path, ret); return ret; } } else { ret = unlink(path); if (ret) { ret = -errno; fprintf(stderr, "recursiveDelete(%s): unlink failed with " "error %d\\n", path, ret); return ret; } } return 0; } int createTempDir(char *tempDir, int nameMax, int mode) { char tmp[PATH_MAX]; int pid, nonce; const char *base = getenv("TMPDIR"); if (!base) base = "/tmp"; if (base[0] != '/') { if (realpath(base, tmp) == 0) { return -errno; } base = tmp; } pid = getpid(); pthread_mutex_lock(&gTempdirLock); nonce = gTempdirNonce++; pthread_mutex_unlock(&gTempdirLock); snprintf(tempDir, nameMax, "%s/temp.%08d.%08d", base, pid, nonce); if (mkdir(tempDir, mode) == -1) { int ret = errno; return -ret; } return 0; } void sleepNoSig(int sec) { int ret; struct timespec req, rem; rem.tv_sec = sec; rem.tv_nsec = 0; do { req = rem; ret = nanosleep(&req, &rem); } while ((ret == -1) && (errno == EINTR)); if (ret == -1) { ret = errno; fprintf(stderr, "nanosleep error %d (%s)\\n", ret, strerror(ret)); } }
1
#include <pthread.h> pthread_t log_thr; pthread_mutex_t logq_lock; pthread_mutex_t logev_lock; pthread_cond_t logev_cond; int logq_running; static void sigusr1 (int sig) { pthread_mutex_lock(&logq_lock); log_reset("multipathd"); pthread_mutex_unlock(&logq_lock); } void log_safe (int prio, const char * fmt, va_list ap) { sigset_t old; if (log_thr == (pthread_t)0) { syslog(prio, fmt, ap); return; } block_signal(SIGUSR1, &old); block_signal(SIGHUP, 0); pthread_mutex_lock(&logq_lock); log_enqueue(prio, fmt, ap); pthread_mutex_unlock(&logq_lock); pthread_mutex_lock(&logev_lock); pthread_cond_signal(&logev_cond); pthread_mutex_unlock(&logev_lock); pthread_sigmask(SIG_SETMASK, &old, 0); } void log_thread_flush (void) { int empty; do { pthread_mutex_lock(&logq_lock); empty = log_dequeue(la->buff); pthread_mutex_unlock(&logq_lock); if (!empty) log_syslog(la->buff); } while (empty == 0); } static void flush_logqueue (void) { int empty; do { pthread_mutex_lock(&logq_lock); empty = log_dequeue(la->buff); pthread_mutex_unlock(&logq_lock); if (!empty) log_syslog(la->buff); } while (empty == 0); } static void * log_thread (void * et) { struct sigaction sig; int running; sig.sa_handler = sigusr1; sigemptyset(&sig.sa_mask); sig.sa_flags = 0; if (sigaction(SIGUSR1, &sig, 0) < 0) logdbg(stderr, "Cannot set signal handler"); pthread_mutex_lock(&logev_lock); logq_running = 1; pthread_mutex_unlock(&logev_lock); mlockall(MCL_CURRENT | MCL_FUTURE); logdbg(stderr,"enter log_thread\\n"); while (1) { pthread_mutex_lock(&logev_lock); pthread_cond_wait(&logev_cond, &logev_lock); running = logq_running; pthread_mutex_unlock(&logev_lock); if (!running) break; log_thread_flush(); } return 0; } void log_thread_start (pthread_attr_t *attr) { logdbg(stderr,"enter log_thread_start\\n"); pthread_mutex_init(&logq_lock, 0); pthread_mutex_init(&logev_lock, 0); pthread_cond_init(&logev_cond, 0); if (log_init("multipathd", 0)) { fprintf(stderr,"can't initialize log buffer\\n"); exit(1); } if (pthread_create(&log_thr, attr, log_thread, 0)) { fprintf(stderr,"can't start log thread\\n"); exit(1); } return; } void log_thread_stop (void) { logdbg(stderr,"enter log_thread_stop\\n"); pthread_mutex_lock(&logev_lock); logq_running = 0; pthread_cond_signal(&logev_cond); pthread_mutex_unlock(&logev_lock); pthread_mutex_lock(&logq_lock); pthread_cancel(log_thr); pthread_mutex_unlock(&logq_lock); pthread_join(log_thr, 0); log_thr = (pthread_t)0; flush_logqueue(); pthread_mutex_destroy(&logq_lock); pthread_mutex_destroy(&logev_lock); pthread_cond_destroy(&logev_cond); log_close(); }
0
#include <pthread.h> struct producers { int buffer[4]; pthread_mutex_t lock; int readpos,writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct producers *b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct producers *b, int data) { pthread_mutex_lock(&b->lock); while((b->writepos + 1)%4 == b->readpos) { printf("full1\\n"); pthread_cond_wait(&b->notfull,&b->lock); printf("full2\\n"); } b->buffer[b->writepos] = data; b->writepos++; if(b->writepos >= 4) b->writepos = 0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct producers *b) { int data; pthread_mutex_lock(&b->lock); while(b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if(b->readpos >= 4) b->readpos = 0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct producers buffer; void *producer(void *data) { int n; for(n=0; n<10; n++) { printf("Producer:%d-->\\n",n); put(&buffer, n); } put(&buffer, (-1)); return 0; } void *consumer(void *data) { int d; while(1) { d = get(&buffer); if(d == (-1)) break; printf("Consumer:-->%d\\n",d); } return 0; } int main() { pthread_t tha,thb; void *retval; init(&buffer); pthread_create(&tha, 0, producer, 0); pthread_create(&thb, 0, consumer, 0); pthread_join(tha, &retval); pthread_join(thb, &retval); return 0; }
1
#include <pthread.h> static struct axis mag_min, mag_max, tilt; pthread_mutex_t tilt_axis_mutex; pthread_t head_thread_id; static bool head_track; void *head_thread(void *args) { struct axis accel, gyro, mag; head_track = 1; unsigned char st1; mag_max.x = 289; mag_min.x = -143; mag_max.y = 50; mag_min.y = -305; mag_max.z = 75; mag_min.z = -310; while(head_track) { accel_read(&accel); gyro_read(&gyro); accel.x = -accel.x; accel.y = -accel.y; accel.z = -accel.z; gyro.x = -gyro.x; gyro.y = -gyro.y; gyro.z = -gyro.z; if(sqrt(powf(accel.x,2) + powf(accel.y,2) + powf(accel.z,2)) > ACCEL_ACTIVITY_THRESHOLD) { pthread_mutex_lock(&tilt_axis_mutex); tilt.roll += gyro.roll*GYRO_PERIOD; tilt.pitch += gyro.pitch*GYRO_PERIOD; pthread_mutex_unlock(&tilt_axis_mutex); } else { pthread_mutex_lock(&tilt_axis_mutex); tilt.roll = atan(accel.y / sqrt(powf(accel.x,2) + powf(accel.z,2))); tilt.pitch = atan(-accel.x / accel.z); pthread_mutex_unlock(&tilt_axis_mutex); } if(mag_drdy()) { mag_read(&mag); mag.x = -mag.x; mag.y = -mag.y; mag.z = -mag.z; mag.x = 2 * (mag.x - mag_min.x) / (mag_max.x - mag_min.x); mag.y = 2 * (mag.y - mag_min.y) / (mag_max.y - mag_min.y); mag.z = 2 * (mag.z - mag_min.z) / (mag_max.z - mag_min.z); pthread_mutex_lock(&tilt_axis_mutex); mag.x = mag.x * cos(-tilt.pitch) + mag.y * sin(-tilt.pitch) * sin(-tilt.roll) + mag.z * sin(tilt.pitch) * cos(tilt.roll); mag.y = mag.y * cos(-tilt.roll) - mag.z * sin(tilt.roll); tilt.z = 180 * atan2(mag.y, mag.x) / M_PI; pthread_mutex_unlock(&tilt_axis_mutex); } else { pthread_mutex_lock(&tilt_axis_mutex); tilt.z += mag.yaw * (1/GYRO_PERIOD); pthread_mutex_unlock(&tilt_axis_mutex); } } return 0; } int compass_init(void) { tilt.x = tilt.y = tilt.z = 0; if(pthread_mutex_init(&tilt_axis_mutex, 0)) { return -2; } if(pthread_create(&head_thread_id, 0, head_thread, 0)) { return -3; } return 0; } double compass_read(void) { double heading; pthread_mutex_lock(&tilt_axis_mutex); heading = tilt.z; pthread_mutex_unlock(&tilt_axis_mutex); return heading; } void compass_stop(void) { head_track = 0; pthread_join(head_thread_id, 0); pthread_mutex_destroy(&tilt_axis_mutex); }
0
#include <pthread.h> int debug = 0; struct sw { int s; char *name; int sleep; }; static void * server_worker(void *v) { struct sw *sw = v; int nreq = 0; while (1) { char *rbuf; char *buf = 0; int bytes; if ((bytes = nn_recv(sw->s, &buf, NN_MSG, 0)) < 0) err(1, "nn_recv"); if (debug) printf("server %s received(%d): [%.*s]\\n", sw->name, nreq++, bytes, buf); if (sw->sleep) sleep(sw->sleep); asprintf(&rbuf, "e%.*s", bytes, buf); if (debug) printf("server %s: sending response: [%s]\\n", sw->name, rbuf); if ((bytes = nn_send(sw->s, rbuf, strlen(rbuf), 0)) != (int)strlen(rbuf)) err(1, "nn_send"); free(rbuf); nn_freemsg(buf); } nn_shutdown(sw->s, 0); return 0; } static int server(int argc, char **argv) { char *url = argv[0]; int ext_sock; int int_sock; int i; if ((ext_sock = nn_socket(AF_SP_RAW, NN_REP)) < 0) err(1, "nn_socket"); if (nn_bind(ext_sock, url) < 0) err(1, "nn_bind"); if ((int_sock = nn_socket(AF_SP_RAW, NN_REQ)) < 0) err(1, "nn_socket"); if (nn_bind(int_sock, "inproc://hej") < 0) err(1, "nn_bind"); for (i = 0; i < 5; i++) { struct sw *sw = calloc(1, sizeof(*sw)); pthread_t thr; sw->sleep = i == 0 ? 2 : 0; if ((sw->s = nn_socket(AF_SP, NN_REP)) < 0) err(1, "nn_socket"); if (nn_connect(sw->s, "inproc://hej") < 0) errx(1, "nn_connect: %d %s", nn_errno(), nn_strerror(nn_errno())); asprintf(&sw->name, "s%d", i); pthread_create(&thr, 0, server_worker, sw); } while (1) { if (debug) printf("starting device\\n"); if (nn_device(ext_sock, int_sock) < 0) errx(1, "nn_device %d %s %d %d", nn_errno(), nn_strerror(nn_errno()), int_sock, ext_sock); } return 0; } struct cw { int s; char *req; }; pthread_mutex_t count_mtx = PTHREAD_MUTEX_INITIALIZER; int slow_cnt; int fast_cnt; double slow_time; double fast_time; pthread_barrier_t thundering_herd; static void * client_worker(void *v) { struct cw *cw = v; struct timespec s, e; char *repbuf = 0; int replen; const int repeat = 1; pthread_barrier_wait(&thundering_herd); int i; for (i = 0; i < repeat; i++) { if (debug) printf("client: sending req: [%s]\\n", cw->req); clock_gettime(CLOCK_MONOTONIC, &s); if (nn_send(cw->s, cw->req, strlen(cw->req), 0) != (int)strlen(cw->req)) err(1, "nn_send"); if ((replen = nn_recv(cw->s, &repbuf, NN_MSG, 0)) < 0) err(1, "nn_recv"); clock_gettime(CLOCK_MONOTONIC, &e); e.tv_sec -= s.tv_sec; if ((e.tv_nsec -= s.tv_nsec) < 0) { e.tv_nsec += 1000000000; e.tv_sec--; } double t = ((double)e.tv_sec * 1000000000.0 + (double)e.tv_nsec) / 1000000000.0; pthread_mutex_lock(&count_mtx); if (e.tv_sec) { printf("client req took %f\\n", t); slow_time += t; slow_cnt++; } else { fast_time += t; fast_cnt++; } pthread_mutex_unlock(&count_mtx); if (debug) printf("client: received reply: [%.*s]\\n", replen, repbuf); nn_freemsg(repbuf); } nn_shutdown(cw->s, 0); return 0; } static int client(int argc, char **argv) { int cnt = 100; pthread_t thr[cnt]; int i; pthread_barrier_init(&thundering_herd, 0, cnt + 1); for (i = 0; i < cnt; i++) { struct cw *cw = calloc(1, sizeof(*cw)); if ((cw->s = nn_socket(AF_SP, NN_REQ)) < 0) err(1, "nn_socket"); if (nn_connect(cw->s, argv[0]) < 0) err(1, "nn_connect"); asprintf(&cw->req, "xx%d", i); pthread_create(&thr[i], 0, client_worker, cw); } pthread_barrier_wait(&thundering_herd); for (i = 0; i < 100; i++) { void *r; pthread_join(thr[i], &r); } printf("slow requests: %d, average time: %f, total: %f\\n", slow_cnt, slow_time / (double)slow_cnt, slow_time); printf("fast requests: %d, average time: %f, total: %f\\n", fast_cnt, fast_time / (double)fast_cnt, fast_time); return 0; } int main(int argc, char **argv) { char opt; int s,c; s = c = 0; while ((opt = getopt(argc, argv, "sc")) != -1) { switch (opt) { case 's': s = 1; break; case 'c': c = 1; break; default: goto usage; } } if (argc - optind < 1 || ((c^s) != 1)) { usage: fprintf(stderr, "Usage: %s <-s|-c> url\\n", argv[0]); exit(1); } argc -= optind; argv += optind; if (s) return server(argc, argv); return client(argc, argv); }
1
#include <pthread.h> long long MAX_LOOP; long long counter=0; long long trials_per_thread; pthread_mutex_t lock; void *Calculate_pi(void *threadid) { long tid; tid = (long)threadid; double x,y; int i; srand(time(0)); for(i=0;i<trials_per_thread;i++) { x= ((double)rand())/32767; y= ((double)rand())/32767; if( (x*x+y*y) <= 1*1) { pthread_mutex_lock(&lock); counter=counter+1; pthread_mutex_unlock(&lock); } } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t *threads; pthread_attr_t attr; int rc; long t; MAX_LOOP=atoll(argv[1]); long long NUM_THREADS; NUM_THREADS=atoll(argv[2]); void *status; threads=malloc(NUM_THREADS*sizeof(pthread_t)); clock_t tic,toc; if (threads == 0) { printf("Problem with malloc...\\n"); return 1; } if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); trials_per_thread=MAX_LOOP/NUM_THREADS; printf("Conditions:\\n%lld threads, %lld trials, %lld trials per thread\\n",NUM_THREADS,MAX_LOOP,trials_per_thread); tic=clock(); for(t=0;t<NUM_THREADS;t++) { rc = pthread_create(&threads[t], &attr, Calculate_pi, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(t=0; t<NUM_THREADS; t++) { pthread_join(threads[t], &status); } toc=clock(); printf("Time in seconds : %lf\\n",(double)(toc-tic)/(double)CLOCKS_PER_SEC); printf("Counter is %lld so pi = %lf \\n", counter, 4.0*((double)counter)/((double)MAX_LOOP)); pthread_mutex_destroy(&lock); pthread_exit(0); free (threads); }
0
#include <pthread.h> static struct _BSM *BasicSaftyMsg=0; extern int SendNetLinkData(int sockfd,int length,int pid, unsigned char *buffer); static void PutWSMReqHeader(struct _WSM_MsgReq *wsmReqMsg, char *buf) { int i; unsigned int lval; char *pval; pval = get_conf_value("WSMP_VERSION", buf); if(pval != 0){ wsmReqMsg->wsmp_ver = atoi(pval); return; } pval = get_conf_value("PSID", buf); if(pval != 0){ if(!strncmp(pval, "0x", 2)){ lval = strtoul(pval,0,16); }else{ lval = atoi(pval); } PUT_32BIT_TO_FOUR_CHARS(wsmReqMsg->psid[0], wsmReqMsg->psid[1], wsmReqMsg->psid[2], wsmReqMsg->psid[3], lval); return; } pval = get_conf_value("DST_MAC", buf); if(pval != 0){ for(i=0; i<6; i++){ if(*pval == ':') pval += 1; wsmReqMsg->dstmac[i] = (Hex(*(pval++)) << 4) | Hex(*(pval++)); } return; } pval = get_conf_value("WSMP_EXT", buf); if(pval != 0){ wsmReqMsg->ext = atoi(pval); return; } pval = get_conf_value("EXPIRY_TIME", buf); if(pval != 0){ wsmReqMsg->expirytime = atoi(pval); return; } pval = get_conf_value("USER_PRIORITY", buf); if(pval != 0){ wsmReqMsg->priority = atoi(pval); return; } if(wsmReqMsg->ext){ pval = get_conf_value("CHANNEL", buf); if(pval != 0){ wsmReqMsg->channel = atoi(pval); return; } pval = get_conf_value("DATARATE", buf); if(pval != 0){ wsmReqMsg->datarate = atoi(pval); return; } pval = get_conf_value("TRANSPOWER", buf); if(pval != 0){ wsmReqMsg->txpower = atoi(pval); return; } } pval = get_conf_value("WSMP_EID", buf); if(pval != 0){ if(!strncmp(pval, "0x", 2)){ lval = strtoul(pval,0,16); }else{ lval = atoi(pval); } wsmReqMsg->weid = lval; return; } } static int getWSMReqHeaderFromFile(char *file,struct _WSM_MsgReq *wsmReqMsg) { FILE *fp; char buff[100]={0,}; fp = fopen(file,"r"); if(fp == 0){ printf("%s file open error !!!\\n",file); return -1; } while(1){ if(fgets((char *)&buff[0], 100, fp) == 0) break; PutWSMReqHeader(wsmReqMsg,buff); } if(DebugLevel == WSMP_MSG_LEVEL){ printf("wsmReqMsg->wsmp_ver is (%d)\\n",wsmReqMsg->wsmp_ver); printf("wsmReqMsg->psid is %02x%02x%02x%02x\\n",wsmReqMsg->psid[0],wsmReqMsg->psid[1],wsmReqMsg->psid[2],wsmReqMsg->psid[3]); printf("wsmReqMsg->dstmac is (%02x:%02x:%02x:%02x:%02x:%02x)\\n",wsmReqMsg->dstmac[0],wsmReqMsg->dstmac[1],wsmReqMsg->dstmac[2], wsmReqMsg->dstmac[3],wsmReqMsg->dstmac[4],wsmReqMsg->dstmac[5]); printf("wsmReqMsg->expirytime is (%lld)\\n",wsmReqMsg->expirytime); printf("wsmReqMsg->priority is (%d)\\n",wsmReqMsg->priority); printf("wsmReqMsg->weid is (%d)\\n",wsmReqMsg->weid); if(wsmReqMsg->ext){ printf("External Field : channel(%d),datarate(%d),power(%d)\\n",wsmReqMsg->channel,wsmReqMsg->datarate,wsmReqMsg->txpower); } } fclose(fp); return 0; } void MakeWSM_request(struct rsmgmt_wave *rsmgmt, unsigned char *wsmData, unsigned short size) { struct _WSM_MsgReq *wsmReqMsg; int i,offset=0; unsigned char psidoctet[4]={0,}; unsigned char frame[WAVE_FRAME_MAX_BUF]={0,}; if((wsmReqMsg = malloc(sizeof(struct _WSM_MsgReq))) == 0){ printf ("unable to alloc memory for WSM_MsgReq !!!\\n"); return; } memset(wsmReqMsg,0,sizeof(struct _WSM_MsgReq)); if(getWSMReqHeaderFromFile("/etc/wsmreq.sch",wsmReqMsg) != -1){ PUT_16BIT_TO_TWO_CHARS(frame[offset++], frame[offset++], WSM_WAVESHORTMESSAGE_REQUEST); for(i=0 ;i<ETH_ALEN; i++){ frame[offset+i] = wsmReqMsg->dstmac[i]; } offset += (ETH_ALEN * 2); PUT_16BIT_TO_TWO_CHARS(frame[offset++], frame[offset++], IPV4_WSMP_PROTOCOL_TYPE); frame[offset++] = wsmReqMsg->wsmp_ver; offset += PUT_PSID_OCTET_STR(&frame[offset],&wsmReqMsg->psid[0]); frame[offset++] = wsmReqMsg->ext; if(wsmReqMsg->ext){ frame[offset++] = CHANNEL_NUMBER; frame[offset++] = 1; frame[offset++] = wsmReqMsg->channel; frame[offset++] = DATARATE; frame[offset++] = 1; frame[offset++] = wsmReqMsg->datarate; frame[offset++] = TRANSMIT_POWER_USED; frame[offset++] = 1; frame[offset++] = wsmReqMsg->txpower; } frame[offset++] = wsmReqMsg->weid; PUT_16BIT_TO_TWO_CHARS(frame[offset++],frame[offset++],size); memcpy(&frame[offset],wsmData,size); if(DebugLevel == WSMP_MSG_LEVEL){ printf( "frmame data size = %d\\n", (size+offset) ); for( i = 0; i < (size+offset); i++ ) { if( (i % 16) == 0 ) printf( "\\n" ); printf( "%02x ", frame[i]); } printf( "\\n" ); } SendNetLinkData(rsmgmt->socknl,(size+offset),rsmgmt->rsmgmt_pid,frame); } free(wsmReqMsg); } int GetBasicSaftyMsg(struct rsmgmt_wave *rsmgmt,struct _BSM *bsmMsg) { int result = -1; pthread_mutex_lock(&rsmgmt->bsmMsg_mutex); if(BasicSaftyMsg != 0){ result = sizeof(struct _BSM); memcpy(bsmMsg,BasicSaftyMsg,result); } pthread_mutex_unlock(&rsmgmt->bsmMsg_mutex); return result; } int BasicSaftyMsg_init(struct rsmgmt_wave *rsmgmt) { if((BasicSaftyMsg = malloc(sizeof(struct _BSM))) == 0) return -1; memset(BasicSaftyMsg,0, sizeof(struct _BSM)); return 1; } void BasicSaftyMsg_free(struct rsmgmt_wave *rsmgmt) { if(BasicSaftyMsg != 0) free(BasicSaftyMsg); }
1
#include <pthread.h> int ShareMemory[101]; int iwriteposition = 0,ireadposition = 0; int ibuffersize = 10; pthread_mutex_t pthreadmutex_lock; pthread_cond_t pthread_cond_empty; pthread_cond_t pthread_cond_full; void *sender(void) { int icount; for (icount = 0; icount < 100; icount++) { pthread_mutex_lock(&pthreadmutex_lock); if (iwriteposition - ireadposition > ibuffersize) { printf("send Waiting"); pthread_cond_wait(&pthread_cond_full, &pthreadmutex_lock); } ShareMemory[iwriteposition++] = icount; printf("send:--->%d\\n", icount); pthread_cond_signal(&pthread_cond_empty); pthread_mutex_unlock(&pthreadmutex_lock); } } void *receiver(void) { int idata; while(1) { pthread_mutex_lock(&pthreadmutex_lock); if (ireadposition == iwriteposition) { printf("receive Waiting"); pthread_cond_wait(&pthread_cond_empty,&pthreadmutex_lock); } idata = ShareMemory[ireadposition++]; if(idata != (100 - 1)) { printf("receive--->%d\\n",idata); pthread_cond_signal(&pthread_cond_full); pthread_mutex_unlock(&pthreadmutex_lock); } else { printf("receive--->%d\\n",idata); pthread_mutex_unlock(&pthreadmutex_lock); break; } } } int main() { void *recycle; memset(ShareMemory,0,sizeof(ShareMemory)); pthread_t pthread_receive,pthread_send; pthread_mutex_init(&pthreadmutex_lock,0); pthread_cond_init(&pthread_cond_full,0); pthread_cond_init(&pthread_cond_empty,0); pthread_create(&pthread_send, 0, receiver, 0); pthread_create(&pthread_receive, 0, sender, 0); printf("waiting Recive\\n"); pthread_join(pthread_receive, &recycle); printf("waiting send\\n"); pthread_join(pthread_send, &recycle); return 0; }
0
#include <pthread.h> void *print_number(void *args); int num = 0; pthread_mutex_t mutex; int main(void) { pthread_t thread; pthread_mutex_init(&mutex, 0); pthread_create(&thread, 0, print_number, 0); while(num < 100) { pthread_mutex_lock(&mutex); num++; pthread_mutex_unlock(&mutex); printf("boss thread: num = %d\\n", num); fflush(stdout); sleep(1); } return(1); } void *print_number(void *args) { while(num < 100) { pthread_mutex_lock(&mutex); num++; pthread_mutex_unlock(&mutex); printf("worker thread: num = %d\\n", num); fflush(stdout); sleep(2); } return(0); }
1
#include <pthread.h> struct buffer { int array[10]; unsigned int top; pthread_mutex_t m; }stack; pthread_cond_t stack_full = PTHREAD_COND_INITIALIZER; pthread_cond_t stack_empty = PTHREAD_COND_INITIALIZER; void *puta(void*arg) { srand(1092); int value =0; while (1) { pthread_mutex_lock(&stack.m); printf("\\n %s 0x%x Checking condition stack.top == SIZE-1 ",__func__,pthread_self()); while (stack.top == 10 -1 ) { printf("\\n %s 0x%x producer thread top %d waititng for stack to be empty",__func__,pthread_self(),(stack.top)); pthread_cond_wait(&stack_empty,&stack.m); } value =rand()%20; printf("\\n %s 0x%x going to insert at %d value %d",__func__,pthread_self(),stack.top+1, value); stack.array[(++stack.top)]=value; printf("\\n %s 0x%x sending signal stack_full ",__func__,pthread_self()); pthread_cond_signal(&stack_full); pthread_mutex_unlock(&stack.m); } return 0; } void *eata(void*arg) { int value=0; while (1) { pthread_mutex_lock(&stack.m); printf("\\n %s 0x%x Checking condition stack.top == -1 value of top =%d",__func__,pthread_self(),stack.top); while (stack.top == -1 ) { printf("\\n %s 0x%x consumer thread top %d top %d waiting for producer to fill the buffer",__func__,pthread_self(),(stack.top)%10, stack.top%10); pthread_cond_wait(&stack_full,&stack.m); } value = stack.array[stack.top--]; printf("\\n %s 0x%x going to print at %d value %d",__func__,pthread_self(),stack.top+1, value); printf("\\n %s 0x%x sending signal stack_empty",__func__,pthread_self()); pthread_cond_signal(&stack_empty); pthread_mutex_unlock(&stack.m); } return 0; } func_type_t func_arr[]={puta,eata,puta,eata}; int main() { pthread_t tid[4]; int ret=0; int i=0; pthread_mutex_init(&stack.m,0); stack.top=-1; for(i=0;i<4;i++) if( ret=pthread_create(&tid[i],0,func_arr[i],0)) { return -1; } for(i=0;i<2;i++) pthread_join(tid[i],0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_for_saveToPath = PTHREAD_MUTEX_INITIALIZER; int hxfmsg(struct htx_data *p, int err, enum sev_code sev, char *text) { char saveToPath[128]; FILE *fp; if(p == 0){ printf("%s",text); if(sev< HTX_SYS_INFO){ pthread_mutex_lock(&mutex_for_saveToPath); sprintf(saveToPath, "/tmp/htx/libsyscfg_debug.%d.txt", getpid()); fp = fopen(saveToPath, "a"); if(fp != 0){ fprintf(fp, "\\n %s", text); fclose(fp); } pthread_mutex_unlock(&mutex_for_saveToPath); } return 0; } else{ p->error_code = err; p->severity_code = sev; (void) strncpy(p->msg_text, text, MAX_TEXT_MSG); if (p->msg_text[MAX_TEXT_MSG - 1] != '\\0') p->msg_text[MAX_TEXT_MSG -1] = '\\0'; if((p->severity_code) >= HTX_SYS_INFO){ return(hxfupdate(MESSAGE, p)); } else if( (p->severity_code) < HTX_SYS_INFO) { return(hxfupdate(ERROR, p)); } } return 0; }
1
#include <pthread.h> void *producer (void *args); void *consumer (void *args); int buf[10]; long head, tail; int full, empty; pthread_mutex_t *mut; pthread_cond_t *notFull, *notEmpty; } queue; queue *queueInit (void); void queueDelete (queue *q); void queueAdd (queue *q, int in); void queueDel (queue *q, int *out); int main () { queue *fifo; pthread_t pro, con; fifo = queueInit (); if (fifo == 0) { fprintf (stderr, "main: Queue Init failed.\\n"); exit (1); } pthread_create (&pro, 0, producer, fifo); pthread_create (&con, 0, consumer, fifo); pthread_join (pro, 0); pthread_join (con, 0); queueDelete (fifo); return 0; } void *producer (void *q) { queue *fifo; int i; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); printf("producer: make %d\\n", i); usleep (100000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->full) { printf ("producer: queue FULL.\\n"); pthread_cond_wait (fifo->notFull, fifo->mut); } queueAdd (fifo, i); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notEmpty); printf("producer: make %d\\n", i); usleep (200000); } return (0); } void *consumer (void *q) { queue *fifo; int i, d; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep(200000); } for (i = 0; i < 20; i++) { pthread_mutex_lock (fifo->mut); while (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); pthread_cond_wait (fifo->notEmpty, fifo->mut); } queueDel (fifo, &d); pthread_mutex_unlock (fifo->mut); pthread_cond_signal (fifo->notFull); printf ("consumer: recieved %d.\\n", d); usleep (50000); } return (0); } queue *queueInit (void) { queue *q; q = (queue *)malloc (sizeof (queue)); if (q == 0) return (0); q->empty = 1; q->full = 0; q->head = 0; q->tail = 0; q->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t)); pthread_mutex_init (q->mut, 0); q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notFull, 0); q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t)); pthread_cond_init (q->notEmpty, 0); return (q); } void queueDelete (queue *q) { pthread_mutex_destroy (q->mut); free (q->mut); pthread_cond_destroy (q->notFull); free (q->notFull); pthread_cond_destroy (q->notEmpty); free (q->notEmpty); free (q); } void queueAdd (queue *q, int in) { q->buf[q->tail] = in; q->tail++; if (q->tail == 10) q->tail = 0; if (q->tail == q->head) q->full = 1; q->empty = 0; return; } void queueDel (queue *q, int *out) { *out = q->buf[q->head]; q->head++; if (q->head == 10) q->head = 0; if (q->head == q->tail) q->empty = 1; q->full = 0; return; }
0
#include <pthread.h> struct pids * pidmanager = 0; pthread_mutex_t alloc_mutex; int allocate_map(void){ int i; if(pidmanager!=0) return 1; pthread_mutex_init(&alloc_mutex,0); pidmanager = (struct pids *)malloc(sizeof(struct pids)); if(pidmanager){ pidmanager->last_pid = MIN_PID; for(i = 0; i < MAX_PAGE; i ++){ pidmanager->map[i].num_free = BITS_PER_PAGE; pidmanager->map[i].page = 0; } pidmanager->map[MIN_PID/BITS_PER_PAGE].num_free = BITS_PER_PAGE - MIN_PID%BITS_PER_PAGE; }else{ return -1; } return 1; } int get_next_free(void){ int page,offset, first,mask; if(pidmanager == 0) return -1; first = pidmanager->last_pid / BITS_PER_PAGE; for(page = first; page < MAX_PAGE; page++){ if(pidmanager->map[page].num_free > 0) break; } if(page == MAX_PAGE) return -1; if(first * BITS_PER_PAGE < MIN_PID) first = MIN_PID % BITS_PER_PAGE; else first = 0; for(offset = first; offset < BITS_PER_PAGE; offset++){ mask = 1 << offset; if((pidmanager->map[page].page & mask) == 0) break; } if(offset == BITS_PER_PAGE){ fprintf(stdout,"Something wrong! last pid %d page %u \\n",pidmanager->last_pid,pidmanager->map[page].page); } return page * BITS_PER_PAGE + offset; } int allocate_pid(void){ int pid = -1; int offset,page,mask; if(pidmanager == 0) return -1; pthread_mutex_lock(&alloc_mutex); pid = pidmanager->last_pid; pidmanager->last_pid++; if(pidmanager->last_pid>MAX_PID){ pthread_mutex_unlock(&alloc_mutex); return -1; } page = pid / BITS_PER_PAGE; offset = pid % BITS_PER_PAGE; mask = 1 << offset; if((pidmanager->map[page].page & mask) == 0){ pidmanager->map[page].page = pidmanager->map[page].page | mask; pidmanager->map[page].num_free--; }else{ pid = get_next_free(); page = pid / BITS_PER_PAGE; offset = pid % BITS_PER_PAGE; mask = 1 << offset; pidmanager->map[page].page = pidmanager->map[page].page | mask; pidmanager->map[page].num_free--; pidmanager->last_pid = pid + 1; } pthread_mutex_unlock(&alloc_mutex); return pid; } void release_pid(int pid){ int page,offset,mask; page = pid / BITS_PER_PAGE; offset = pid % BITS_PER_PAGE; mask = ~(1 << offset); pthread_mutex_lock(&alloc_mutex); pidmanager->map[page].page = pidmanager->map[page].page & mask; pidmanager->map[page].num_free++; if(pidmanager->last_pid > pid) pidmanager->last_pid = pid; pthread_mutex_unlock(&alloc_mutex); }
1
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo *fool_alloc(void) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return (0); } } return (fp); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } pthread_mutex_unlock(&fp->f_lock); }
0
#include <pthread.h> void *thread_cb(void *); pthread_t* threads; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; double* x; double* y; double tmp = 0; double averageX = 0; double averageY = 0; double betaTmp = 0; double beta1 = 0; double beta0 = 0; int lineNum = 0; double sumOfX = 0; double sumOfY = 0; int* argvii; int count = 0; char line[1000]; int main(int argc, char* argv[]) { int rc; int status; printf("%s %s %s \\n", argv[0], argv[1], argv[2]); int argvi = atoi(argv[2]); pthread_t threads[argvi]; printf("price = %d\\n", argvi); FILE *fp = fopen("input.txt", "r"); fgets(line, 1000, fp); while(!feof(fp)){ tmp = atof(strtok(line, " ")); sumOfX += tmp; tmp = atof(strtok(0, " ")); sumOfY += tmp; lineNum++; fgets(line, 1000, fp); } printf("%d\\n", lineNum); fclose(fp); fp = fopen("input.txt", "r"); x = (double*)malloc((lineNum * sizeof(double))); y = (double*)malloc(lineNum * sizeof(double)); int xyi = 0; fgets(line, 1000, fp); while (!feof(fp)){ x[xyi] = atof(strtok(line, " ")); y[xyi] = atof(strtok(line, " ")); xyi++; fgets(line, 1000, fp); } fclose(fp); averageX = sumOfX / lineNum; averageY = sumOfY / lineNum; argvii = (int*)malloc(sizeof(int)); argvii[0] = argvi; printf("argvii = %d\\n", argvii[0]); int passNum[argvi]; for(int gg = 0; gg < argvi; gg++) { passNum[gg] = gg; } for(int i1 = 0; i1 < argvi; i1++) { int error = pthread_create(&threads[i1], 0, &thread_cb, (void *)&passNum[i1]); printf("%d\\n", error); } printf("create end \\n"); for(int i2 = 0; i2 < argvi; i2++) { printf("join\\n"); pthread_join(threads[i2], 0); } free(x); free(y); beta1 = averageY - beta1 * averageX; beta0 = beta1/betaTmp; printf("%f %f\\n", beta0, beta1); free(argvii); } void *thread_cb(void *arg) { int number = *((int*)arg); printf("number : %d\\n", number); double beta1TMP = 0; double betaTMP2 = 0; pthread_mutex_lock(&mutex); for(int i = number; i < lineNum; i += argvii[0]) { beta1TMP += (x[i] - averageX) * (y[i] - averageY); betaTMP2 += (x[i] - averageX) * (x[i] - averageX); } beta1 += beta1TMP; betaTmp += betaTMP2; pthread_mutex_unlock(&mutex); pthread_exit((void *) 0); }
1
#include <pthread.h> pthread_cond_t is_zero; pthread_mutex_t mutex; int shared_data = 5; void *thread_function (void *arg) { pthread_mutex_lock(&mutex) ; while ( shared_data > 0) { --shared_data ; printf("Thread - Decreasing shared_data... Value:%d\\n",shared_data); sleep(1); } pthread_mutex_unlock(&mutex); printf("Thread, loop finished...\\n"); sleep(3); pthread_cond_signal (&is_zero); return 0; } int main (void) { pthread_t thread_ID1; void *exit_status; pthread_cond_init (&is_zero , 0) ; pthread_mutex_init (&mutex , 0) ; pthread_create (&thread_ID1 ,0, thread_function , 0) ; pthread_mutex_lock(&mutex ); printf("Main thread locking the mutex...\\n"); while ( shared_data != 0) { printf("I am the Main thread, shared_data is != 0. I am to sleep and unlock the mutex...\\n"); pthread_cond_wait (&is_zero, &mutex) ; } printf("Main awake - Value of shared_data: %d!!!\\n", shared_data); pthread_mutex_unlock(&mutex) ; pthread_join( thread_ID1 , 0) ; pthread_mutex_destroy(&mutex) ; pthread_cond_destroy (&is_zero) ; exit(0); }
0
#include <pthread.h> int fpthread_listen_init(struct static_val *s_val){ s_val->epoll_fd = epoll_create(epoll_max_sfd); if(s_val->epoll_fd == -1){ printf("listen pthread create epoll fail, errno: %d\\n",errno); s_val->sig_exit++; return -1; } s_val->sfd_li = cre_sock_li(srv_ip, srv_port); if(s_val->sfd_li == -1){ printf("*function inet_listen() fail, program has quit*\\n"); s_val->sig_exit++; return -1; } struct epoll_event ev; ev.events = EPOLLIN | EPOLLET ; ev.data.fd = s_val->sfd_li; if(epoll_ctl(s_val->epoll_fd, EPOLL_CTL_ADD, s_val->sfd_li, &ev) < 0){ printf("listen pthread epoll_ctl fail, add listen socket %d into epoll fail, errno: %d\\n", s_val->sfd_li, errno); s_val->sig_exit++; return -1; } printf("~.~.~.~.~.~.init listen pthread success~.~.~.~.~.~.~.\\n"); return 0; } void* fpthread_listen(struct static_val *s_val){ int tmp = fpthread_listen_init(s_val); pthread_mutex_lock(&s_val->tmp_mutex); pthread_cond_signal(&s_val->tmp_cond); pthread_mutex_unlock(&s_val->tmp_mutex); if(tmp == -1) return 0; struct as_info as; as_init(&as); s_val->cur_fds++; printf("~.~.~.~.~.~.inet tcp socket: li-pthread into loops now~.~.\\n\\n"); for(;;){ if_event(s_val,&as); if(s_val->sig_exit != 0) break; if(aq_is_empty(s_val->paq_io) == 0){ for(tmp = 0;tmp < pool_max;tmp++){ if(s_val->sig_io[tmp] == 0){ pthread_mutex_lock(&s_val->mutex_io[tmp]); pthread_cond_signal(&s_val->cond_io[tmp]); pthread_mutex_unlock(&s_val->mutex_io[tmp]); break; } } } } shutdown(s_val->sfd_li,2); close(s_val->sfd_li); s_val->sfd_li = 0; close(s_val->epoll_fd); s_val->epoll_fd = 0; printf("listen pthread has quit, clean model is good.\\n"); s_val->sig_exit++; return 0; } int start_plisten(struct static_val *s_val){ pthread_t pthread; if(pthread_create(&pthread,0,(void*)fpthread_listen,s_val) != 0){ printf("create listen pthread fail, errno: %d\\n",errno); return -1; } if(pthread_detach(pthread) != 0){ s_val->sig_exit++; return -1; } pthread_mutex_lock(&s_val->tmp_mutex); pthread_cond_wait(&s_val->tmp_cond,&s_val->tmp_mutex); pthread_mutex_unlock(&s_val->tmp_mutex); if(s_val->sig_exit != 0) if(s_val->sig_exit == 1){ shutdown(s_val->sfd_li,2); close(s_val->sfd_li); return -1; } s_val->pid_li = pthread; printf("listen pthread has started\\n\\n"); return 0; }
1
#include <pthread.h> static sem_t _sem_recv_msgs_empty; static sem_t _sem_recv_msgs_full; static char *recv_msgs[16] = { 0 }; static pthread_mutex_t _lock_read_id; pthread_mutex_t _lock_readstream; pthread_cond_t _cond_readstream; void thread_readstream_post_new_msg(char *msg) { static int pos = 0; assert(msg != 0); sem_wait(&_sem_recv_msgs_empty); recv_msgs[pos] = msg; ++pos; if (pos >= 16) pos = 0; sem_post(&_sem_recv_msgs_full); } char *thread_readstream_get_next_msg(void) { static int pos = 0; char *msg = 0; sem_wait(&_sem_recv_msgs_full); pthread_mutex_lock(&_lock_read_id); msg = recv_msgs[pos]; recv_msgs[pos] = 0; ++pos; if (pos >= 16) pos = 0; pthread_mutex_unlock(&_lock_read_id); sem_post(&_sem_recv_msgs_empty); return msg; } void thread_readstream_init(void) { if (sem_init(&_sem_recv_msgs_empty, 0, 16) != 0) perror("semaphore init failed"); if (sem_init(&_sem_recv_msgs_full, 0, 0) != 0) perror("semaphore init failed"); if (pthread_mutex_init(&_lock_readstream, 0) != 0) perror("mutex init failed"); if (pthread_cond_init(&_cond_readstream, 0) != 0) perror("cond init failed"); if (pthread_mutex_init(&_lock_read_id, 0) != 0) perror("mutex init failed"); } static void thread_readstream_close(void *vargs) { for (unsigned int i = 0; i < 16; ++i) { free(recv_msgs[i]); recv_msgs[i] = 0; } sem_destroy(&_sem_recv_msgs_empty); sem_destroy(&_sem_recv_msgs_full); pthread_mutex_destroy(&_lock_readstream); pthread_cond_destroy(&_cond_readstream); pthread_mutex_destroy(&_lock_read_id); } void *thread_readstream(void *vargs) { struct thread *t = (struct thread *) vargs; pthread_cleanup_push(thread_readstream_close, t); while (session.state != STATE_DEAD) { char *msg = 0; if (session.state != STATE_RUN) { pthread_mutex_lock(&_lock_readstream); while (session.state == STATE_TLS_INIT) pthread_cond_wait(&_cond_readstream, &_lock_readstream); if (session.state == STATE_INIT) { session.state = STATE_POLL; pthread_cond_signal(&_cond_readstream); } pthread_mutex_unlock(&_lock_readstream); msg = stream_read(session.wfs); pthread_mutex_lock(&_lock_readstream); if (session.state == STATE_POLL) { session.state = STATE_INIT; pthread_cond_signal(&_cond_readstream); } pthread_mutex_unlock(&_lock_readstream); } else { msg = stream_read(session.wfs); } if (msg == 0 || strlen(msg) <= 0) { if (session.state != STATE_DEAD) { status_set(STATUS_LEFT); } break; } { for (char *s = msg; *s; ++s) if (*s == '"') *s = '\\''; } thread_readstream_post_new_msg(msg); session.xmpp.last_query = time(0); } pthread_cleanup_pop(1); return thread_close(t); }
0
#include <pthread.h> unsigned long long int COUNTER; pthread_mutex_t LOCK = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t START = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t CONDITION = PTHREAD_COND_INITIALIZER; void * threads (void * unused) { pthread_mutex_lock(&START); pthread_mutex_unlock(&START); pthread_mutex_lock(&LOCK); if (COUNTER > 0) { pthread_cond_signal(&CONDITION); } for (;;) { COUNTER++; pthread_cond_wait(&CONDITION, &LOCK); pthread_cond_signal(&CONDITION); } pthread_mutex_unlock(&LOCK); } int main() { pthread_t t1,t2; pthread_mutex_lock(&START); COUNTER = 0; pthread_create(&t1, 0, threads, 0); pthread_create(&t2, 0, threads, 0); pthread_detach(t1); pthread_detach(t2); struct timeval start,end; pthread_mutex_unlock(&START); gettimeofday(&start,0); sleep(1); pthread_mutex_lock(&LOCK); gettimeofday(&end,0); printf("speed=%llu switches in %u second and %u microseconds\\n",COUNTER,end.tv_sec-start.tv_sec,end.tv_usec-start.tv_usec); return 0; }
1
#include <pthread.h> struct xml_cntn_fd * xml_cntn_fd_create(int *fd) { int retval; struct xml_cntn_fd *new = malloc(sizeof(*new)); assert(new); memset(new, 0, sizeof(*new)); new->fd = fd; new->run = 1; *new->fd = -1; new->ready = 0; if((retval = pthread_mutex_init(&new->mutex, 0))!=0){ PRINT_ERR("Failure in pthread_mutex_init tx_mutex_buf %p: %s ", new, strerror(retval)); return 0; } if((retval = pthread_cond_init(&new->cond, 0))!=0){ PRINT_ERR("Failure in pthread_cond_init %p: %s ", new, strerror(retval)); return 0; } return new; } void xml_cntn_fd_delete(struct xml_cntn_fd *cnfd) { pthread_mutex_lock(&cnfd->mutex); cnfd->run=0; pthread_cond_broadcast(&cnfd->cond); pthread_mutex_unlock(&cnfd->mutex); pthread_cond_destroy(&cnfd->cond); pthread_mutex_destroy(&cnfd->mutex); free(cnfd); } int xml_cntn_fd_wait(struct xml_cntn_fd *cnfd){ int retval = 0; cnfd->ready = 0; while((cnfd->ready == 0)&&(cnfd->run==1)){ if((retval = pthread_cond_wait(&cnfd->cond, &cnfd->mutex))!=0){ PRINT_ERR("ERROR-> pthread_cond_wait failed: %s (%d) in %p",strerror(retval), retval, cnfd ); return -retval; } } if(cnfd->run!=1){ retval = -1; } return retval; } int xml_cntn_fd_open(struct xml_cntn_fd *cnfd, int client_fd) { int retval = 0; pthread_mutex_lock(&cnfd->mutex); if(*cnfd->fd == -1){ *cnfd->fd = client_fd; cnfd->ready = 1; pthread_cond_broadcast(&cnfd->cond); } else { retval = -1; } pthread_mutex_unlock(&cnfd->mutex); return retval; } int xml_cntn_fd_close(struct xml_cntn_fd *cnfd) { pthread_mutex_lock(&cnfd->mutex); if(*cnfd->fd != -1) close(*cnfd->fd); *cnfd->fd = -1; pthread_mutex_unlock(&cnfd->mutex); return 0; } int xml_cntn_fd_isactive(struct xml_cntn_fd *cnfd) { int active = 0; if(pthread_mutex_trylock(&cnfd->mutex)!=0){ return 1; } if(cnfd->ready) active = 1; pthread_mutex_unlock(&cnfd->mutex); return active; }
0
#include <pthread.h> long shimid; key_t key = 66607; struct ipcstruct { int value; int size; int cachesending; int proxysending; pthread_mutex_t memMutex; pthread_cond_t cvProxyGo; pthread_cond_t cvCacheGo; }; int main(int argc, char **argv){ printf("OK\\n"); int shmd; if ( argc < 2 ) { printf("you must give a file name"); return 1; } char memName[15]; strcpy(memName, argv[1]); shmd = atoi(memName); struct ipcstruct *mystruct = (struct ipcstruct *)mmap(0, sizeof(struct ipcstruct), PROT_READ | PROT_WRITE, MAP_SHARED, shmd, 0); printf("The value is %d\\n", mystruct->value); printf("Tring to get the lock\\n"); while ( 1 ) { pthread_mutex_lock(&(mystruct->memMutex)); while ( mystruct->proxysending == 1 ) { printf("We're waiting now\\n"); pthread_cond_wait(&(mystruct->cvCacheGo), &(mystruct->memMutex) ); } mystruct->cachesending = 1; printf("We got it... doing work\\n"); sleep(5); printf("Done.. signalling\\n"); mystruct->cachesending = 0; mystruct->proxysending = 1; pthread_mutex_unlock(&(mystruct->memMutex)); pthread_cond_signal(&(mystruct->cvProxyGo)); } return 0; }
1
#include <pthread.h> struct job { struct job* next; int jid; }; struct job* job_queue; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t sem; void* thread_func (void *tid) { struct job* my_job; while (1) { sem_wait(&sem); pthread_mutex_lock(&mutex); if (job_queue == 0) { pthread_mutex_unlock(&mutex); return 0; } else { my_job = job_queue; usleep(500000); job_queue = job_queue->next; printf("%d by thread %d\\n", my_job->jid, *(int*)tid); free(my_job); pthread_mutex_unlock(&mutex); } } return 0; } void* produce(void *tid) { struct job* aux_job; struct job* new_job; int i = 0; while (1) { new_job = (struct job*) malloc (sizeof (struct job)); pthread_mutex_lock(&mutex); aux_job = job_queue; job_queue = new_job; job_queue->jid = i; job_queue->next = aux_job; pthread_mutex_unlock(&mutex); sem_post(&sem); i++; } } int main() { pthread_t my_threads[4]; sem_init(&sem, 0, 4); int tid1 = 1, tid2 = 2, tid3 = 3, tid4 = 4; pthread_create(&my_threads[0], 0, thread_func, &tid1); pthread_create(&my_threads[1], 0, thread_func, &tid2); pthread_create(&my_threads[2], 0, thread_func, &tid3); pthread_create(&my_threads[3], 0, produce, &tid4); pthread_join(my_threads[0], 0); pthread_join(my_threads[1], 0); pthread_join(my_threads[2], 0); return 0; }
0
#include <pthread.h> pthread_t tid[5]; pthread_mutex_t lock, intLock; char queue[10000] = { "\\0" }; int qLen = -1; int internal_count = 0; int flag = 0; char getCh() { pthread_mutex_lock(&lock); char ch; char temp; if (qLen == -1) { pthread_mutex_unlock(&lock); return '\\0'; } ch = queue[0]; int i; for (i = 0; i < qLen; i++) { queue[i] = queue[i + 1]; } queue[qLen--] = '\\0'; pthread_mutex_unlock(&lock); return ch; } void putCh(char ch) { pthread_mutex_lock(&lock); queue[++qLen] = ch; pthread_mutex_unlock(&lock); } void* threadFunc(void *arg) { char temp; struct timespec tim; tim.tv_sec = 0; while (1) { temp = getCh(); if (temp == '\\0' && (flag)) { pthread_mutex_lock(&intLock); printf("%d\\n", internal_count); pthread_mutex_unlock(&intLock); pthread_exit(0); } if (temp != '\\0') { switch (temp) { case '1': { tim.tv_nsec = 100000000L; nanosleep(&tim, 0); pthread_mutex_lock(&intLock); internal_count++; pthread_mutex_unlock(&intLock); break; } case '2': { tim.tv_nsec = 200000000L; nanosleep(&tim, 0); pthread_mutex_lock(&intLock); internal_count += 2; pthread_mutex_unlock(&intLock); break; } case '3': { tim.tv_nsec = 300000000L; nanosleep(&tim, 0); pthread_mutex_lock(&intLock); internal_count += 3; pthread_mutex_unlock(&intLock); break; } case '4': { tim.tv_nsec = 400000000L; nanosleep(&tim, 0); pthread_mutex_lock(&intLock); internal_count += 4; pthread_mutex_unlock(&intLock); break; } case '5': { tim.tv_nsec = 500000000L; nanosleep(&tim, 0); pthread_mutex_lock(&intLock); internal_count += 5; pthread_mutex_unlock(&intLock); break; } case '6': { pthread_mutex_lock(&intLock); printf("%d\\n", internal_count); pthread_mutex_unlock(&intLock); break; } } } } } int main(int argv, char* argc[]) { int i = 0; int err; char input; char inputArr[128] = {"\\0"}; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } if (pthread_mutex_init(&intLock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } for (i = 0; i < 5; i++) { err = pthread_create(&(tid[i]), 0, &threadFunc, 0); if (err != 0) { printf("cant create thread : [%s]", strerror(err)); } } while (1) { scanf("%s",&inputArr); input = inputArr[0]; if (input == '7') { for (i = 0; i < 5; i++) { pthread_cancel(tid[i]); } printf("%d\\n", internal_count); return 0; } if (input == '8') { flag = 1; for (i = 0; i < 5; i++) { pthread_join(tid[i], 0); } printf("%d\\n", internal_count); return 0; } putCh(input); } }
1
#include <pthread.h> int ar[21]; int front; int rear; } Quene; Quene quene; int isFull(Quene *q) { return (q->rear + 1) % 21 == q->front; } int isEmpty(Quene *q) { return q->rear == q->front; } int queneSize(Quene *q) { return (q->rear + 21 - q->front) % 21; } pthread_mutex_t mutex; pthread_cond_t cond_pro; pthread_cond_t cond_con; void cleanup_handler(void *arg) { printf("Cleanup handle of second thread\\n"); pthread_mutex_unlock(&mutex); } void *produce(void *arg) { pthread_detach(pthread_self()); pthread_cleanup_push(cleanup_handler, 0); while (1) { pthread_mutex_lock(&mutex); while (isFull(&quene)) { pthread_cond_wait(&cond_con, &mutex); } quene.rear = (quene.rear + 1) % 21; printf("produce: %d\\n", queneSize(&quene)); pthread_mutex_unlock(&mutex); if (queneSize(&quene) == 1) { pthread_cond_broadcast(&cond_pro); } sleep(rand() % 3 + 1); } pthread_exit(0); pthread_cleanup_pop(0); } void *consume(void *arg) { pthread_detach(pthread_self()); pthread_cleanup_push(cleanup_handler, 0); while (1) { pthread_mutex_lock(&mutex); while (isEmpty(&quene)) { pthread_cond_wait(&cond_pro, &mutex); } quene.front = (quene.front + 1) % 21; printf("consume: %d\\n", queneSize(&quene)); pthread_mutex_unlock(&mutex); if (queneSize(&quene) == 19) { pthread_cond_broadcast(&cond_con); } sleep(rand() % 3 + 1); } pthread_exit(0); pthread_cleanup_pop(0); } int main(int argc, char *argv[]) { if (argc != 3) { perror("argument"); exit(1); } int m = atoi(argv[1]); int n = atoi(argv[2]); quene.front = 0; quene.rear = 0; pthread_cond_init(&cond_con, 0); pthread_cond_init(&cond_pro, 0); pthread_mutex_init(&mutex, 0); srand(time(0)); pthread_t *th = (pthread_t *)calloc(m + n, sizeof(pthread_t)); int index = 0; for (index = 0; index < m; index++) { pthread_create(&th[index], 0, produce, 0); } sleep(2); for (; index < m + n; index++) { pthread_create(&th[index], 0, consume, 0); } while(1); pthread_cond_destroy(&cond_con); pthread_cond_destroy(&cond_pro); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> int multiplo(int x){ int ret; ret = ((((x - 1) >> 2) << 2) + 4); return ret; } struct cabecalho { size_t tamanho; unsigned livre; struct cabecalho *prox; }; struct cabecalho *head, *tail; pthread_mutex_t bloqueio_desbloqueio; struct cabecalho *pega_bloco_livre(size_t tamanho) { struct cabecalho *bloco = head; while(bloco) { if (bloco->livre && bloco->tamanho >= tamanho) return bloco; bloco = bloco->prox; } return 0; } void *malloc(size_t tamanho) { size_t tamanho_total; void *bloco; struct cabecalho *header; pthread_mutex_lock(&bloqueio_desbloqueio); size_t t = multiplo(tamanho); header = pega_bloco_livre(t); if (header) { header->livre = 0; pthread_mutex_unlock(&bloqueio_desbloqueio); return (void*)(header + 1); } tamanho_total = sizeof(struct cabecalho) + t; bloco = sbrk(tamanho_total); if (bloco == (void*) -1) { pthread_mutex_unlock(&bloqueio_desbloqueio); return 0; } header = bloco; header->tamanho = t; header->livre = 0; header->prox = 0; if (!head) head = header; if (tail) tail->prox = header; tail = header; pthread_mutex_unlock(&bloqueio_desbloqueio); return (void*)(header + 1); } void free(void *bloco) { struct cabecalho *header, *tmp; void *programbreak; if (!bloco) return; pthread_mutex_lock(&bloqueio_desbloqueio); header = (struct cabecalho*)bloco - 1; programbreak = sbrk(0); if ((char*)bloco + header->tamanho == programbreak) { if (head == tail) { head = tail = 0; } else { tmp = head; while (tmp) { if(tmp->prox == tail) { tmp->prox = 0; tail = tmp; } tmp = tmp->prox; } } sbrk(0 - sizeof(struct cabecalho) - header->tamanho); pthread_mutex_unlock(&bloqueio_desbloqueio); return; } header->livre = 1; pthread_mutex_unlock(&bloqueio_desbloqueio); }
1
#include <pthread.h> static int OpenSerialPortMul(const char *serpath) { int result = -1; int i=0; for (i=0; i<TRY_TIMES; i++) { result = OpenSerialPort(serpath); if (-1 != result) { break; } usleep(TRY_INTERVAL*1000); } return result; } static int SetSerialPortOptMul(int fd, int speed, int bits, int parity, int stop) { int result = -1; int i=0; for (i=0; i<TRY_TIMES; i++) { result = SetSerialPortOpt(fd, speed, bits, parity, stop); if (-1 != result) { break; } usleep(TRY_INTERVAL*1000); } return result; } static int VerifyCRC(unsigned char *pData, unsigned char dataLen) { int result = -1; unsigned short crcResult = 0; crcResult = CRC16(pData, dataLen - 2); unsigned char crc16L = crcResult & 0xff; unsigned char crc16H = (crcResult>>8) & 0xff; if (*(pData+dataLen-1) == crc16L && *(pData+dataLen-2) == crc16H) result = 0; return result; } static void DealData(unsigned char *buffer, unsigned int offset, unsigned int dataLen) { int dealResult = -1; unsigned char *pData = buffer + offset; if (0 == VerifyCRC(pData, dataLen)) { unsigned char frameType = *(pData+4) & 0x1F; if (0x2 == frameType || 0x5 == frameType) { pthread_mutex_lock(&globalVar.dataMutex); if (0x2 == frameType) { SET_BTOTVAR(globalVar.bToTVar[0], buffer, offset, dataLen); } else if (0x5 == frameType) { SET_BTOTVAR(globalVar.bToTVar[1], buffer, offset, dataLen); } pthread_mutex_unlock(&globalVar.dataMutex); SET_SEM(&globalVar.resourceSem); CLR_ERROR(ERROR_MASK_SERIAL); dealResult = 0; } } if (-1 == dealResult) { SET_ERROR(ERR_SP_FRAME_FORMAT); free(buffer); buffer = 0; } } static inline void DealErr(unsigned char *buffer, int code) { free(buffer); buffer = 0; if(0 == code) { SET_ERROR(ERR_SERIAL_TIMEOUT); } else if (-1 == code) { SET_ERROR(ERR_READ_SERIAL_PORT); } else if (-2 == code || -3 == code) { SET_ERROR(ERR_SP_FRAME_FORMAT); } else { SET_ERROR(ERR_UNKNOWN); } } void *BaseBoardThread(void *arg) { int result = -1; int serial_port_fd = -1; do { serial_port_fd = OpenSerialPortMul(SERIAL_PORT_PATH); EQUAL_SET_ERR_BREAK(serial_port_fd, -1, ERR_OPEN_SERIAL_PORT); result = SetSerialPortOptMul(serial_port_fd, SERIAL_PORT_BAUDRATE, SERIAL_PORT_DATABITS, SERIAL_PORT_CHECKBIT, SERIAL_PORT_STOPBITS); EQUAL_SET_ERR_BREAK(result, -1, ERR_SET_SERIAL_OPT); while(0 == *(int *)arg) { unsigned char *buffer = malloc(BUFFER_SIZE*sizeof(unsigned char)); unsigned int offset = 0; result = SerialPortRcvFrame(serial_port_fd, buffer, &offset, BUFFER_SIZE); if (result > 0) { SerialPortSndData(serial_port_fd, &(buffer[offset]), result - offset); DealData(buffer, offset, result - offset); } else { DealErr(buffer, result); } } } while(0); if (-1 != serial_port_fd && 0 != serial_port_fd) close(serial_port_fd); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; assiette * tampon[3]; sem_t * plein; sem_t * vide; const char* type(assiette * a) { switch (*a) { case VIDE: return "vide"; case CUPCAKE: return "cupcake"; case MUFFIN: return "muffin"; case PANCAKE: return "pancake"; default: return "truc inconnu"; } } assiette * obtenir(assiette status) { assiette * a; int i; for (i = 0; i < 3; i++) { if (tampon[i] != 0 && ((status == VIDE) == (*tampon[i] == VIDE))) { a = tampon[i]; tampon[i] = 0; return a; } } return 0; } void placer(assiette * a) { int i; for (i = 0; i < 3; i++) { if (tampon[i] == 0) { tampon[i] = a; return; } } } void consommer(assiette * a) { *a = VIDE; } void* parent (void *arg) { int id = *((int*) arg); srand(time(0)); assiette *tp; int i; for (i = 0; i < 10; i++) { printf("Le parent %d attend une assiette vide\\n", id); sem_wait(vide); pthread_mutex_lock(&mutex); tp = obtenir(VIDE); pthread_mutex_unlock(&mutex); if (tp == 0) { fprintf(stderr, "Erreur, aucune assiette disponible pour le parent %d", id); exit(1); } *tp = (rand() % (TOTAL - 1)) + 1; printf("Le parent %d a préparé un %s\\n", id, type(tp)); usleep(10000); pthread_mutex_lock(&mutex); placer(tp); pthread_mutex_unlock(&mutex); sem_post(plein); } return 0; } void* enfant (void *arg) { int id = *((int*) arg); assiette *tp; int i; for (i = 0; i < 10*3/3; i++) { printf("L'enfant %d attend une assiette pleine\\n", id); sem_wait(plein); pthread_mutex_lock(&mutex); tp = obtenir(1); pthread_mutex_unlock(&mutex); if (tp == 0) { fprintf(stderr, "Erreur, aucune assiette disponible pour l'enfant %d\\n", id); exit(1); } printf("L'enfant %d mange un %s\\n", id, type(tp)); consommer(tp); usleep(10000); pthread_mutex_lock(&mutex); placer(tp); pthread_mutex_unlock(&mutex); sem_post(vide); } return 0; } int main() { int i; pthread_t parents[3]; int parents_id[3]; pthread_t enfants[3]; int enfants_id[3]; for (i = 0; i < 3; i++) { tampon[i] = calloc(1, sizeof(assiette)); } plein = sem_open("plein", O_CREAT | O_EXCL, 755, 0); vide = sem_open("vide", O_CREAT | O_EXCL, 755, 3); if (plein == SEM_FAILED || vide == SEM_FAILED) { sem_unlink("plein"); sem_unlink("vide"); printf("semaphores existants éliminés !\\n"); return 1; } for (i = 0; i < 3; i++) { enfants_id[i] = i; pthread_create(&enfants[i], 0, enfant, (void*) &enfants_id[i]); } for (i = 0; i < 3; i++) { parents_id[i] = i; pthread_create(&parents[i], 0, parent, (void*) &parents_id[i]); } for (i = 0; i < 3; i++) { pthread_join(enfants[i], 0); } for (i = 0; i < 3; i++) { pthread_join(parents[i], 0); } for (i = 0; i < 3; i++) { free(tampon[i]); } sem_close(plein); sem_close(vide); sem_unlink("plein"); sem_unlink("vide"); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> pthread_cond_t condition_alarme = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex_alarme = PTHREAD_MUTEX_INITIALIZER; static void * thread_temperature(void * inutile); static void * thread_alarme(void * inutile); static int aleatoire(int maximum); int main(void) { pthread_t thr; pthread_create(& thr, 0, thread_temperature, 0); pthread_create(& thr, 0, thread_alarme, 0); pthread_exit(0); } static void * thread_temperature(void * inutile) { int temperature = 20; while (1) { temperature += aleatoire(5) - 2; fprintf(stdout, "Temp�rature : %d\\n", temperature); if ((temperature < 16) || (temperature > 24)) { pthread_mutex_lock(& mutex_alarme); pthread_cond_signal(& condition_alarme); pthread_mutex_unlock(& mutex_alarme); } sleep(1); } return (0); } static void * thread_alarme(void * inutile) { while (1) { pthread_mutex_lock(& mutex_alarme); pthread_cond_wait(& condition_alarme, & mutex_alarme); pthread_mutex_unlock(& mutex_alarme); fprintf(stdout, "ALARME\\n"); } return (0); } static int aleatoire(int maximum) { double d; d = (double) maximum * rand(); d = d / (32767 + 1.0); return ((int) d); }
0
#include <pthread.h> pthread_mutex_t count_lock; pthread_cond_t count_nonzero; unsigned count = 0; void *decrement_count(void *arg) { pthread_mutex_lock(&count_lock); printf("decrement_count get count_lock\\n"); while(count == 0) { printf("decrement_count count == 0 \\n"); printf("decrement_count before cond_wait \\n"); pthread_cond_wait(&count_nonzero, &count_lock); printf("decrement_count after cond_wait \\n"); } printf("tid1:count--\\n"); count = count - 1; printf("tid1:count= %d \\n", count); pthread_mutex_unlock(&count_lock); } void *increment_count(void *arg) { pthread_mutex_lock(&count_lock); printf("increment_count get count_lock \\n"); if(count == 0) { printf("increment_count before cond_signal \\n"); pthread_cond_signal(&count_nonzero); printf("increment_count after cond_signal \\n"); } printf("tid2:count++\\n"); count = count + 1; printf("tid2:count= %d \\n", count); pthread_mutex_unlock(&count_lock); } int main(void) { pthread_t tid1, tid2; pthread_mutex_init(&count_lock, 0); pthread_cond_init(&count_nonzero, 0); pthread_create(&tid1, 0, decrement_count, 0); printf("tid1 decrement is created,begin sleep 2s \\n"); sleep(2); printf("after sleep 2s, start creat tid2 increment \\n"); pthread_create(&tid2, 0, increment_count, 0); printf("after tid2 increment is created,begin sleep 10s \\n"); sleep(5); printf("after sleep 5s,begin exit!\\n"); pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_cond_t count; pthread_mutex_t count_mutex; pthread_mutex_t printie; struct parameters { int counter; int simulationtime; int I; double* old; double* current; double* next; }params; void *HelloWorld(void *args); double *simulate(const int i_max, const int t_max, const int num_threads, double *old_array, double *current_array, double *next_array) { params.counter = 0; params.simulationtime = t_max; params.I = (i_max - 2) / num_threads; params.old = old_array; params.current = current_array; params.next = next_array; pthread_t thread_ids[num_threads]; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count, 0); pthread_mutex_init(&printie, 0); for (int i = 0; i < num_threads; i++) { int point_per_thread = i * (i_max -2) / num_threads; printf("points per thread, %d ", point_per_thread); int* num = (int*) malloc( sizeof( int)); *num = point_per_thread; pthread_create( &thread_ids[i], 0 ,&HelloWorld , num); } for(int i = 0; i < t_max; i++) { while (params.counter < num_threads) { sleep(0.01); } double* temp1; temp1 = params.current; params.current = params.next; params.next = params.old; params.old = temp1; pthread_mutex_lock(&count_mutex); printf("gonna broadcast now\\n"); pthread_cond_broadcast(&count); pthread_mutex_unlock(&count_mutex); params.counter = 0; } for (int i = 0; i < num_threads; i++) { pthread_join( thread_ids[i], 0 ); } return params.current; } void *HelloWorld(void *args) { int maxi = *((int*)args); double nexti, previousi; printf( "inside hello %d ", maxi); for (int t = 0; t < params.simulationtime; t++) { const int c = 0.15; for(int i = maxi + 1; i < maxi + params.I; i++) { double eqone = 2 * params.current[i] - params.old[i]; previousi = params.current[i - 1]; nexti = params.current[i + 1]; double eqtwo = c * (previousi - (2 * params.current[i] - nexti)); params.next[i] = eqone + eqtwo; printf("%f", params.next[i]); } params.counter += 1; pthread_mutex_lock(&count_mutex); pthread_cond_wait(&count, &count_mutex); pthread_mutex_unlock(&count_mutex); } }
0
#include <pthread.h> int counter_enq = 0; int counter_deq = 0; int counter_loo = 0; int N = 100; int T = 90; struct listnode { int value; struct lisnode *next; }; struct queue { struct listnode *head; struct listnode *tail; int size; pthread_mutex_t mutex; }; struct queue *queue_create() { struct queue *q = malloc(sizeof(*q)); if (q != 0) { q->size = 0; q->head = 0; q->tail = 0; pthread_mutex_init(&q->mutex, 0); } return q; } void lock_queue(struct queue *q) { pthread_mutex_lock(&q->mutex); } void unlock_queue(struct queue *q) { pthread_mutex_unlock(&q->mutex); } struct listnode *create_node(int value) { struct listnode *new_node = malloc(sizeof(*new_node)); if (new_node != 0) { new_node->value = value; new_node->next = 0; } else { fprintf(stderr, "ERROR: can't create new node\\n"); return 0; } return new_node; } void queue_enqueue(struct queue *q, int value) { counter_enq++; struct listnode *old_tail; lock_queue(q); q->tail = create_node(value); old_tail = q->tail; if (q->head == 0) { q->head = (struct listnode*)q->tail; } else { old_tail->next = q->tail; } q->size++; unlock_queue(q); } int queue_dequeue(struct queue *q) { int value; struct listnode *node; lock_queue(q); if (q->size == 0) { unlock_queue(q); return -1; } if (!q->head) { unlock_queue(q); return -1; } value = q->head->value; node = (struct listnode*)q->head->next; if (q->head) { free(q->head); } else { fprintf(stderr, "ERROR: memory corruption\\n"); exit(1); } q->head = node; q->size--; counter_deq++; unlock_queue(q); return value; } int queue_lookup(struct queue *q, int value) { counter_loo++; struct listnode *node; lock_queue(q); if (q->size == 0) { unlock_queue(q); return -1; } node = q->head; while(node) { if (node->value = value) { unlock_queue(q); return value; } node = (struct listnode*)node->next; } unlock_queue(q); return -1; } int queue_size(struct queue *q) { return q->size; } void queue_free(struct queue *q) { while (q->size > 0) { queue_dequeue(q); } free(q); } struct task { struct queue *q; int tid; }; void *test(void *arg) { struct task *task_ = (struct task*)arg; int branch = task_->tid; if ((branch > 0) && (branch < 30)){ for(int i = 1; i <= N; i++) { queue_enqueue(task_->q, (rand() % 1000)); } } else if ((branch > 30) && (branch < 60)) { for(int i = 1; i <= N; i++) { queue_dequeue(task_->q); } } else { for(int i = 1; i <= N; i++) { queue_lookup(task_->q, (rand() % 1000)); } } } double wtime() { struct timeval t; gettimeofday(&t, 0); return (double)t.tv_sec + (double)t.tv_usec * 1E-6; } int main(int argc, char const *argv[]) { int rc; double t; struct queue *q; pthread_t thread[T]; time_t time_; srand((unsigned) time(&time_)); q = queue_create(); t = wtime(); for (int i = 0; i < T; i++) { struct task *t = malloc(sizeof(*t)); t->q = q; t->tid = rand() % 100; rc = pthread_create(&thread[i], 0, test, (void*)t); if (rc) { fprintf(stderr,"ERROR: pthread_create() return code: %d\\n", rc); exit(1); } } for (int i = 0; i < 10; i++) { pthread_join(thread[i], 0); } t = wtime() - t; printf("Queue size : %d\\n", queue_size(q)); printf("queue_enqueue: %d\\n", counter_enq); printf("queue_dequeue: %d\\n", counter_deq); printf("queue_lookup : %d\\n", counter_loo); printf("BANDWITH : %f(sec) %d(threads) %0.f(operations) %f(op/sec)\\n", t, T, ((double)T*N), ((double)T*N) / t); return 0; }
1
#include <pthread.h> void init_matrix (int *matrix, int fils, int cols) { int i, j; for (i = 0; i < fils; i++) { for (j = 0; j < cols; j++) { matrix[i * cols + j] = 1; } } } int *matrix1; int *matrix2; int *matrixR; int matrix1_fils; int matrix1_cols; int matrix2_fils; int matrix2_cols; pthread_t *thread_list; pthread_mutex_t mutex; int pending_jobs = 0; struct job { int i, j; struct job *next; }; struct job *job_list = 0; struct job *last_job = 0; void add_job(int i, int j){ struct job *job = malloc(sizeof(struct job)); job->i = i; job->j = j; job->next = 0; if(pending_jobs == 0){ job_list = job; last_job = job; } else{ last_job->next = job; last_job = job; } pending_jobs++; } struct job* get_job(){ struct job *job = 0; if(pending_jobs > 0){ job = job_list; job_list = job->next; if(job_list == 0){ last_job = 0; } pending_jobs--; } return job; } void do_job(struct job *job) { int k, acum; acum = 0; for (k = 0; k < matrix1_cols; k++) { acum += matrix1[job->i * matrix1_cols + k] * matrix2[k * matrix2_cols + job->j]; } matrixR[job->i * matrix2_cols + job->j] = acum; } void* dispatch_job () { struct job *job; while(1) { pthread_mutex_lock(&mutex); job = get_job(); pthread_mutex_unlock(&mutex); if (job) { do_job(job); free(job); } else { pthread_exit(0); } } } int main (int argc, char **argv) { if (argc > 3) { printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]); matrix1_fils = strtol(argv[1], (char **) 0, 10); matrix1_cols = strtol(argv[2], (char **) 0, 10); matrix2_fils = matrix1_cols; matrix2_cols = strtol(argv[3], (char **) 0, 10); int i,j; matrix1 = (int *) calloc(matrix1_fils * matrix1_cols, sizeof(int)); matrix2 = (int *) calloc(matrix2_fils * matrix2_cols, sizeof(int)); matrixR = (int *) malloc(matrix1_fils * matrix2_cols * sizeof(int)); init_matrix(matrix1, matrix1_fils, matrix1_cols); init_matrix(matrix2, matrix2_fils, matrix2_cols); for (i = 0; i < matrix1_fils; i++) { for (j = 0; j < matrix2_cols; j++) { add_job(i,j); } } thread_list = malloc(sizeof(int) * 3); pthread_mutex_init(&mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); for (i = 0; i < 3; i++) { pthread_create(&thread_list[i], &attr, dispatch_job, 0); } for (i = 0; i < 3; i++) { pthread_join(thread_list[i], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); free(thread_list); free(matrix1); free(matrix2); free(matrixR); return 0; } fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]); return -1; }
0
#include <pthread.h> struct prodcons { int buffer[16]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct prodcons *b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct prodcons *b, int data) { pthread_mutex_lock(&b->lock); if ((b->writepos + 1) % 16 == b->readpos) { pthread_cond_wait(&b->notfull, &b->lock); } b->buffer[b->writepos] = data; b->writepos++; if (b->writepos >= 16) { b->writepos = 0; } pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons *b) { int data; pthread_mutex_lock(&b->lock); if (b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if (b->readpos >= 16) { b->readpos = 0; } pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void *producer(void *data) { int n; for (n = 0; n < 10000; n++) { printf("%d --->\\n", n); put(&buffer, n); } put(&buffer, ( - 1)); return 0; } void *consumer(void *data) { int d; while (1) { d = get(&buffer); if (d == ( - 1)) { break; } printf("--->%d \\n", d); } return 0; } int main(void) { pthread_t th_a, th_b; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); return 0; }
1
#include <pthread.h> int port = 0; pthread_mutex_t port_mutex; int Connect(const char *hostname, int port) { int sock; struct hostent *host; struct sockaddr_in host_addr; sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { perror("socket()"); } host = gethostbyname(hostname); if (host == 0) { perror("gethostbyname()"); } host_addr.sin_family = AF_INET; host_addr.sin_port = htons(port); host_addr.sin_addr = *((struct in_addr *)host->h_addr); memset(&host_addr.sin_zero, 0, 8); int status = connect(sock, (struct sockaddr *)&host_addr, sizeof(struct sockaddr)); close(sock); if (status == 0) { return 1; } return 0; } struct Connection_t { const char *hostname; unsigned short int port; }; void *worker(void *connection) { struct Connection_t *tmp = (struct Connection_t *) connection; struct Connection_t c = *tmp; pthread_mutex_lock(&port_mutex); port++; c.port = port; pthread_mutex_unlock(&port_mutex); int connected = Connect(c.hostname, port); if (connected) { printf("Connected to %s on port %d\\n", c.hostname, c.port); } } void banner(void) { printf("Copyright (c) 2015. Al Poole <netstar@gmail.com>\\n"); printf("%s version %s\\n", "SpeedyScan", "0.0.1.1"); printf("Maximum threads: %d\\n\\n", 64); } int main(int argc, char **argv) { int max_port = 65535; int max_threads = 64; if (argc < 2) { fprintf(stderr, "%s <host> [max port]\\n", "SpeedyScan"); exit(1 << 8); } if (argc == 3) { max_port = atoi(argv[2]); } else { max_port = 65535; } if (64 < max_port) { max_threads = max_port; } char *hostname = argv[1]; pthread_t threads[max_threads]; banner(); unsigned long int time_start = time(0); while(port < max_port) { for (int y = 0; y < max_threads; y++) { struct Connection_t c; c.hostname = hostname; pthread_create(&threads[y], 0, worker, &c); } for (int y = 0; y < max_threads; y++) { pthread_join(threads[y], 0); } } unsigned long int time_end = time(0); unsigned int total_time = time_end - time_start; printf("Completed scan in %u seconds.\\n", total_time); return 0; }
0
#include <pthread.h> int in = 0; int out = 0; int buff[10] = {0}; sem_t empty_sem; sem_t full_sem; pthread_mutex_t mutex; int product_id = 0; int prochase_id = 0; void print() { int i; for(i = 0; i < 10; i++) printf("%d ", buff[i]); printf("\\n"); } void *product() { int id = ++product_id; while(1) { sleep(1); sem_wait(&empty_sem); pthread_mutex_lock(&mutex); in = in % 10; printf("product%d in %d. like: \\t", id, in); buff[in] = 1; print(); ++in; pthread_mutex_unlock(&mutex); sem_post(&full_sem); } } void *prochase() { int id = ++prochase_id; while(1) { sleep(1); sem_wait(&full_sem); pthread_mutex_lock(&mutex); out = out % 10; printf("prochase%d in %d. like: \\t", id, out); buff[out] = 0; print(); ++out; pthread_mutex_unlock(&mutex); sem_post(&empty_sem); } } int main() { pthread_t id1[2]; pthread_t id2[2]; int i; int ret[2]; int ini1 = sem_init(&empty_sem, 0, 10); int ini2 = sem_init(&full_sem, 0, 0); if(ini1 && ini2 != 0) { printf("sem init failed \\n"); exit(1); } int ini3 = pthread_mutex_init(&mutex, 0); if(ini3 != 0) { printf("mutex init failed \\n"); exit(1); } for(i = 0; i < 2; i++) { ret[i] = pthread_create(&id1[i], 0, product, (void *)(&i)); if(ret[i] != 0) { printf("product%d creation failed \\n", i); exit(1); } } for(i = 0; i < 2; i++) { ret[i] = pthread_create(&id2[i], 0, prochase, 0); if(ret[i] != 0) { printf("prochase%d creation failed \\n", i); exit(1); } } for(i = 0; i < 2; i++) { pthread_join(id1[i],0); pthread_join(id2[i],0); } exit(0); }
1
#include <pthread.h> struct message { long msg_type; char msg_text[BUFFER_SIZE]; }msgbuf; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t v = PTHREAD_COND_INITIALIZER; void *sender(void *args) { int qid = *(int *)args; while(1){ pthread_mutex_lock(&m); while(strlen(msgbuf.msg_text) == 0) pthread_cond_wait(&v, &m); Msgsnd(qid, &msgbuf, strlen(msgbuf.msg_text), 0); pthread_cond_broadcast(&v); pthread_mutex_unlock(&m); } } int main(void) { int qid; key_t key; key = Ftok(".", 'a'); qid = Msgget(key, IPC_CREAT|0666); printf("Open queue %d ",qid); printf("(\\"quit\\" to exit) "); pthread_t tid1, tid2; Pthread_create(&tid2, 0, sender, (void *)&qid); char buf4fgets[80]; while(1){ printf("Me: "); Fgets(buf4fgets, BUFFER_SIZE, stdin); pthread_mutex_lock(&m); while(strlen(msgbuf.msg_text)) pthread_cond_wait(&v, &m); strncpy(msgbuf.msg_text, buf4fgets, BUFFER_SIZE); msgbuf.msg_type = R2J; pthread_cond_broadcast(&v); pthread_mutex_unlock(&m); } exit(0); }
0
#include <pthread.h> pthread_mutex_t * mutex_fib; pthread_t * tids; int * result; size_t size; void *fib(void * arg){ size_t id = (size_t) arg; pthread_mutex_lock(&mutex_fib[id]); if (id == 0) { result[0] = 0; } else if (id == 1) { result[1] = 1; } else { result[id] = result[id - 1] + result[id - 2]; } printf("Feito pela thread %u.\\n", (size_t)pthread_self()); if (id < size - 1) { pthread_mutex_unlock(&mutex_fib[id + 1]); } pthread_exit(0); } int main(int argc, char ** argv) { size_t i = 0; sscanf(argv[1], "%d", &size); size = size+1; result = malloc(sizeof(int) * size+1); mutex_fib = malloc(sizeof(pthread_mutex_t) * size+1); tids = malloc(sizeof(pthread_t) * size+1); for (i = 0; i < size; i++) { pthread_mutex_init(&mutex_fib[i], 0); pthread_mutex_lock(&mutex_fib[i]); } for (i = 0;i < size; i++) { pthread_create(&tids[i], 0, fib, (void *) i); } pthread_mutex_unlock(&mutex_fib[0]); for (i = 0; i < size; i++) { pthread_join(tids[i], 0); } printf("Resultado : "); for (i = 0; i < size; i++){ printf("\\nfib[%d] - %d\\n",i,result[i]); } printf("\\n"); for (i = 0; i < size; i++) { pthread_mutex_destroy(&mutex_fib[i]); } free(tids); free(mutex_fib); free(result); return 0; }
1
#include <pthread.h> int buffer[16]={0}; int num_Produced; int num_Consumed; int items; pthread_mutex_t bufferLock; sem_t *fullSlots; sem_t *emptySlots; const char *full = "fullSlots"; const char *empty= "emptySlots"; void *produce(void *param); void *consume(void *param); int main(int argc, char *argv[]){ int producerNum; int consumerNum; int itemNum; int i=0; if (argc !=4){ printf("uses 3 args: log of producer, consumer, items"); return -1; } producerNum= pow(2,atoi(argv[1])); consumerNum= pow(2,atoi(argv[2])); itemNum= pow(2,atoi(argv[3])); num_Produced = itemNum/producerNum; num_Consumed = itemNum/consumerNum; printf("Producers: %d\\nConsumers: %d\\nitems:%d\\n",producerNum,consumerNum,itemNum); pthread_mutex_init(&bufferLock,0); sem_unlink(full); sem_unlink(empty); if((fullSlots = sem_open(full,O_CREAT,0644,0))==SEM_FAILED){ perror("sem_open"); exit(1); } if((emptySlots = sem_open(empty,O_CREAT,0644,16))==SEM_FAILED){ perror("sem_open"); exit(1); } items=0; pthread_t producers[producerNum]; pthread_t consumers[consumerNum]; pthread_attr_t attr; pthread_attr_init(&attr); for(i=0;i<producerNum;i++){ pthread_create(&producers[i],&attr,produce,(void*)(i)); } for(i=0;i<consumerNum;i++){ pthread_create(&consumers[i],&attr,consume,(void*)(i)); } for(i=0;i< producerNum;i++){ pthread_join(producers[i],0); } for(i=0;i< consumerNum;i++){ pthread_join(consumers[i],0); } return 0; } void *produce(void *param){ int thread_ID; int i; thread_ID = (int)param; for(i=0;i<num_Produced;i++){ sem_wait(emptySlots); pthread_mutex_lock(&bufferLock); buffer[items]= ((thread_ID * num_Produced) + i); items+=1; pthread_mutex_unlock(&bufferLock); sem_post(fullSlots); } pthread_exit(0); } void *consume(void *param){ int i; int printval; for(i=0;i<num_Consumed;i++){ sem_wait(fullSlots); pthread_mutex_lock(&bufferLock); printval=buffer[items-1]; printf("item %d from slot %d\\n",printval,(items-1)); items+=-1; pthread_mutex_unlock(&bufferLock); sem_post(emptySlots); } pthread_exit(0); }
0
#include <pthread.h> void ClockLinux_ClockImpl_OnExit(int state, struct ClockLinux_Instance *_instance); void f_ClockLinux_sleep_ms(struct ClockLinux_Instance *_instance, int timeout_ms); void f_ClockLinux_start_clock_process(struct ClockLinux_Instance *_instance); void f_ClockLinux_sleep_ms(struct ClockLinux_Instance *_instance, int timeout_ms) { struct timeval tv; tv.tv_sec = timeout_ms/1000; tv.tv_usec = (timeout_ms%1000) * 1000; select(0, 0, 0, 0, &tv); } struct f_ClockLinux_start_clock_process_struct { struct ClockLinux_Instance *_instance; pthread_mutex_t *lock; pthread_cond_t *cv; }; void f_ClockLinux_start_clock_process_run(struct ClockLinux_Instance *_instance) { while(1) { f_ClockLinux_sleep_ms(_instance, _instance->Clock_period__var); ClockLinux_send_signal_clock_tick(_instance); } } void f_ClockLinux_start_clock_process_proc(void * p) { struct f_ClockLinux_start_clock_process_struct params = *((struct f_ClockLinux_start_clock_process_struct *) p); pthread_mutex_lock(params.lock); pthread_cond_signal(params.cv); pthread_mutex_unlock(params.lock); f_ClockLinux_start_clock_process_run(params._instance); } void f_ClockLinux_start_clock_process(struct ClockLinux_Instance *_instance) { struct f_ClockLinux_start_clock_process_struct params; pthread_mutex_t lock; pthread_cond_t cv; params.lock = &lock; params.cv = &cv; params._instance = _instance; pthread_mutex_init(params.lock, 0); pthread_cond_init(params.cv, 0); pthread_mutex_lock(params.lock); pthread_t thread; pthread_create( &thread, 0, f_ClockLinux_start_clock_process_proc, (void*) &params); pthread_cond_wait(params.cv, params.lock); pthread_mutex_unlock(params.lock); } void ClockLinux_ClockImpl_OnEntry(int state, struct ClockLinux_Instance *_instance) { switch(state) { case CLOCKLINUX_CLOCKIMPL_STATE: _instance->ClockLinux_ClockImpl_State = CLOCKLINUX_CLOCKIMPL_TICKING_STATE; f_ClockLinux_start_clock_process(_instance); ClockLinux_ClockImpl_OnEntry(_instance->ClockLinux_ClockImpl_State, _instance); break; case CLOCKLINUX_CLOCKIMPL_TICKING_STATE: break; default: break; } } void ClockLinux_ClockImpl_OnExit(int state, struct ClockLinux_Instance *_instance) { switch(state) { case CLOCKLINUX_CLOCKIMPL_STATE: ClockLinux_ClockImpl_OnExit(_instance->ClockLinux_ClockImpl_State, _instance); break; case CLOCKLINUX_CLOCKIMPL_TICKING_STATE: break; default: break; } } void (*external_ClockLinux_send_signal_clock_tick_listener)(struct ClockLinux_Instance *)= 0x0; void (*ClockLinux_send_signal_clock_tick_listener)(struct ClockLinux_Instance *)= 0x0; void register_external_ClockLinux_send_signal_clock_tick_listener(void (*_listener)(struct ClockLinux_Instance *)){ external_ClockLinux_send_signal_clock_tick_listener = _listener; } void register_ClockLinux_send_signal_clock_tick_listener(void (*_listener)(struct ClockLinux_Instance *)){ ClockLinux_send_signal_clock_tick_listener = _listener; } void ClockLinux_send_signal_clock_tick(struct ClockLinux_Instance *_instance){ if (ClockLinux_send_signal_clock_tick_listener != 0x0) ClockLinux_send_signal_clock_tick_listener(_instance); if (external_ClockLinux_send_signal_clock_tick_listener != 0x0) external_ClockLinux_send_signal_clock_tick_listener(_instance); ; }
1
#include <pthread.h> int errexit(const char* format,...); struct { pthread_mutex_t st_mutex; unsigned int st_concount; unsigned int st_contotal; unsigned int st_contime; unsigned int st_bytecount; }stats; int tcp_echod(int fd) { time_t start; char buf[4096]; int cc; start=time(0); pthread_mutex_lock(&stats.st_mutex); stats.st_concount++; pthread_mutex_unlock(&stats.st_mutex); while(cc=read(fd,buf,4096)){ if(cc<0){ errexit("echo read %s\\n",strerror(errno)); } if(write(fd,buf,cc)<0){ errexit("echo write %s\\n",strerror(errno)); } pthread_mutex_lock(&stats.st_mutex); stats.st_bytecount+=cc; pthread_mutex_unlock(&stats.st_mutex); } close(fd); pthread_mutex_lock(&stats.st_mutex); stats.st_contime+=time(0)-start; stats.st_concount--; stats.st_contotal++; pthread_mutex_unlock(&stats.st_mutex); return 0; } int main(int argc,char *argv[]) { pthread_t th; pthread_attr_t ta; char* service="echo"; struct sockaddr_in fsin; unsigned int alen; unsigned short port; int msock; int ssock; if(argc!=2) errexit("usage: app [port]\\n"); switch(argc){ case 1: break; case 2: port=atoi(argv[1]); break; default: break; } msock=passiveTCP(service,32,port); pthread_attr_init(&ta); pthread_attr_setdetachstate(&ta,PTHREAD_CREATE_DETACHED); pthread_mutex_init(&stats.st_mutex,0); while(1){ alen=sizeof(fsin); ssock=accept(msock,(struct sockaddr*)&fsin,&alen); if(ssock<0){ if(errno==EINTR) continue; errexit("accept : %s\\n",strerror(errno)); } if(pthread_create(&th,&ta,(void * (*)(void*))tcp_echod,(void*)ssock)<0) errexit("pthread create:%s\\n",strerror(errno)); } }
0
#include <pthread.h> static pthread_mutex_t trigger_cmd_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t trigger_cmd = PTHREAD_COND_INITIALIZER; static int command_type = m_login; static struct commandt_data *cm_data; void send_login(int socket, uint8_t role, char *name) { int ret; struct net_login *msg; msg = (struct net_login *)alloc(sizeof(struct net_login)+strlen(name)); msg->role = role; memcpy(msg->name, name, strlen(name)); msg->header.type = m_login; msg->header.length = htons(sizeof(uint8_t) + strlen(name)); printf("Login send. Size: %li\\n", sizeof(msg)); ret = send(socket, msg, sizeof(struct net_login)+strlen(name), 0); if(ret < 0) { perror("send"); fflush(stdout); } free(msg); } void send_board_clean(int socket) { int ret; struct net_header *msg = (struct net_header *)alloc(sizeof(struct net_header)); msg->type = m_clear; msg->length = 0; printf("Board-Clear send. Size: %li\\n", sizeof(msg)); ret = send(socket, msg, sizeof(struct net_header), 0); if(ret < 0) { perror("send"); fflush(stdout); } free(msg); } void send_request(int socket, uint8_t write) { int ret; struct net_request *msg; msg = (struct net_request *)alloc(sizeof(struct net_request)); msg->header.type = m_request; msg->header.length = htons(sizeof(struct net_request)-sizeof(struct net_header)); msg->write = write; printf("Request send. Size: %li\\n", sizeof(msg)); ret = send(socket, msg, sizeof(struct net_request), 0); if(ret < 0) { perror("send"); fflush(stdout); } free(msg); } void send_reply(int socket, uint8_t write, uint16_t cid) { int ret; struct net_reply *msg; msg = (struct net_reply *)alloc(sizeof(struct net_reply)); msg->header.type = m_reply; msg->header.length = htons(sizeof(struct net_reply)-sizeof(struct net_header)); msg->write = write; msg->cid = htons(cid); printf("Reply send. Size: %li\\n", sizeof(*msg)); ret = send(socket, msg, sizeof(struct net_reply), 0); if(ret < 0) { perror("send"); fflush(stdout); } free(msg); } void send_shutdown(int socket) { int ret; struct net_header *msg; msg = (struct net_header *)alloc(sizeof(struct net_header)); msg->type = m_shutdown; msg->length = 0; printf("Shutdown send. Size: %li\\n", sizeof(*msg)); ret = send(socket, msg, sizeof(struct net_header), 0); if(ret < 0) { perror("send"); fflush(stdout); } free(msg); } void trigger_command(int type) { pthread_mutex_lock(&trigger_cmd_mutex); command_type = type; pthread_cond_signal(&trigger_cmd); pthread_mutex_unlock(&trigger_cmd_mutex); } void *command_handler(void *data) { cm_data = (struct commandt_data *)data; int socket = cm_data->socket; struct client_data *cdata = cm_data->cdata; printf("Command-Thread gestartet\\n"); fflush(stdout); cdata_lock(); send_login(socket, cdata->role, cdata->name); cdata_unlock(); pthread_mutex_lock(&trigger_cmd_mutex); while(1) { pthread_cond_wait(&trigger_cmd, &trigger_cmd_mutex); switch (command_type) { case m_login: printf("Login senden ...\\n"); fflush(stdout); cdata_lock(); send_login(socket, cdata->role, cdata->name); cdata_unlock(); break; case m_clear: printf("Clear senden ...\\n"); fflush(stdout); send_board_clean(socket); break; case m_request: printf("Request senden ...\\n"); fflush(stdout); if(cdata->role == 2) { send_request(socket, 1); } else { send_request(socket, !cdata->write); } break; case m_shutdown: printf("Shutdown senden ...\\n"); fflush(stdout); send_shutdown(socket); break; } } pthread_mutex_unlock(&trigger_cmd_mutex); pthread_exit(0); return 0; }
1
#include <pthread.h> void *pico_mutex_init(void) { pthread_mutex_t *m; m = (pthread_mutex_t *)PICO_ZALLOC(sizeof(pthread_mutex_t)); pthread_mutex_init(m, 0); log_debug("Initialized a mutex at %p",(void *)m); return (pthread_mutex_t *)m; } void pico_mutex_destroy(void *mux) { PICO_FREE(mux); mux = 0; } void pico_mutex_lock(void *mux) { if (mux == 0) return; pthread_mutex_t *m = (pthread_mutex_t *)mux; pthread_mutex_lock(m); } void pico_mutex_unlock(void *mux) { if (mux == 0) return; pthread_mutex_t *m = (pthread_mutex_t *)mux; pthread_mutex_unlock(m); } void pico_mutex_deinit(void *mux) { pico_mutex_destroy(mux); }
0
#include <pthread.h> struct arg_set{ int number; char *fname; int count; }; struct arg_set *mailbox = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; void *count_words(void *); int main(int argc, char *argv[]) { pthread_t pid_t1, pid_t2; struct arg_set args1, args2; int reports_in = 0; int total_words = 0; if (argc != 3) { err_sys("usage: %s file1 file2.\\n", argv[0]); } pthread_mutex_lock(&lock); args1.fname = argv[1]; args1.number = 1; args1.count = 0; pthread_create(&pid_t1, 0, count_words, &args1); args2.fname = argv[2]; args2.number = 2; args2.count = 0; pthread_create(&pid_t2, 0, count_words, &args2); while (reports_in < 2) { printf("MAIN : waiting for flag to go on.\\n"); pthread_cond_wait(&flag, &lock); printf("MAIN : Wow! flag was raised ,I have the lock"); printf("%7d: %s.\\n", mailbox->count, mailbox->fname); total_words += mailbox->count; if (mailbox == &args1) pthread_join(pid_t1, 0); if (mailbox == &args2) pthread_join(pid_t2, 0); mailbox = 0; pthread_cond_signal(&flag); ++reports_in; } printf("%7d: total words.\\n", total_words); exit(0); } void *count_words(void *a) { struct arg_set *args = (struct arg_set *)a; FILE *fp = 0; int c, prevc = '\\0'; if ((fp = fopen(args->fname, "r")) != 0) { while ((c = getc(fp)) != EOF) { if (!isalnum(c) && isalnum(prevc)) ++args->count; prevc = c; } fclose(fp); }else err_sys("cannot open file %s.", args->fname); printf("%d COUNT: waiting to get lock.\\n", args->number); pthread_mutex_lock(&lock); printf("%d COUNT: have lock , storing data.\\n", args->number); while (mailbox != 0) { printf("%d COUNT: oops..mailbox not empty wait for signal.\\n", args->number); pthread_cond_wait(&flag, &lock); } mailbox = args; printf("%d COUNT: raising flag.\\n", args->number); pthread_cond_signal(&flag); printf("%d COUNT: unlocking lock.\\n", args->number); pthread_mutex_unlock(&lock); return 0; }
1
#include <pthread.h> pthread_mutex_t stick[5]; void chopsticks_init(){ pthread_mutex_init(&stick[0], 0); pthread_mutex_init(&stick[1], 0); pthread_mutex_init(&stick[2], 0); pthread_mutex_init(&stick[3], 0); pthread_mutex_init(&stick[4], 0); } void chopsticks_destroy(){ pthread_mutex_destroy(&stick[0]); pthread_mutex_destroy(&stick[1]); pthread_mutex_destroy(&stick[2]); pthread_mutex_destroy(&stick[3]); pthread_mutex_destroy(&stick[4]); } void pickup_chopsticks(int phil_id){ printf("philosopher %d is hungry\\n", phil_id); if(phil_id == 4){ pthread_mutex_lock(&stick[0]); pickup_right_chopstick(phil_id); } else{ pthread_mutex_lock(&stick[phil_id]); pickup_left_chopstick(phil_id); } printf("philosopher %d gets the first chopstick\\n", phil_id); if(phil_id == 4){ pthread_mutex_lock(&stick[4]); pickup_left_chopstick(phil_id); } else{ pthread_mutex_lock(&stick[phil_id+1]); pickup_right_chopstick(phil_id); } printf("philosopher %d gets the second chopstick\\n", phil_id); printf("philosopher %d is eating\\n", phil_id); } void putdown_chopsticks(int phil_id){ printf("philosopher %d finishes eating\\n", phil_id); putdown_right_chopstick(phil_id); if(phil_id == 4) pthread_mutex_unlock(&stick[0]); else pthread_mutex_unlock(&stick[phil_id+1]); printf("philosopher %d puts down second chopstick\\n", phil_id); putdown_left_chopstick(phil_id); pthread_mutex_unlock(&stick[phil_id]); printf("philosopher %d puts down first chopstick\\n", phil_id); printf("philosopher %d is thinking\\n", phil_id); }
0
#include <pthread.h> int asciiCharacters[128]; char buffer[65536]; pthread_mutex_t lock; int partitionBounds; int threadNumber; int max_length; } thread_information; void *ascii_checker(void *t_info) { int i, threadLocation; thread_information *threadinfo = (thread_information*) t_info; threadLocation = threadinfo->threadNumber * threadinfo->partitionBounds; for(i = 0; threadLocation + i < threadinfo->max_length && i < threadinfo->partitionBounds; i++) { pthread_mutex_lock(&lock); asciiCharacters[buffer[threadLocation + i]]++; pthread_mutex_unlock(&lock); } pthread_exit(0); } double Seconds(void){ return (double)clock()/CLOCKS_PER_SEC; } int main(int argc, char* argv[]){ pthread_t threadIds[4]; thread_information t_info[4]; int i, j, sourceFile, partitions, charTotal, aThread; sourceFile = open(argv[1], O_RDONLY); if (sourceFile < 0){ fprintf(stderr, "Error opening file!\\n"); return -1; } sourceFile = read(sourceFile, buffer, 65536); partitions = (double) sourceFile / (double) 4; if(pthread_mutex_init(&lock, 0) != 0){ printf("\\n mutex init failed\\n"); return 1; } for(i = 0; i < 4; i++) { t_info[i].threadNumber = i; t_info[i].partitionBounds = partitions; t_info[i].max_length = sourceFile; aThread = pthread_create(&threadIds[i], 0, &ascii_checker, &t_info[i]); if(aThread != 0) printf("Error creating thread! %i\\n", i); } i = 0; do{ pthread_join(threadIds[i], 0); i++; } while (i < 4); for(i = 0; i < 128; i++) { printf("%i occurrences of ", asciiCharacters[i]); if(i < 33 || i == 127){ } else{ printf("%c\\n", i); } } close(sourceFile); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadFunc1(void *offset){ printf("update thread has created: %lu\\n",pthread_self()); pthread_mutex_lock(&mutex); *((int *)offset) = 10; sleep(1); *((int *)offset +1) = 20; pthread_mutex_unlock(&mutex); return 0; } void *threadFunc2(void *offset){ printf("reader thread has created: %lu\\n",pthread_self()); pthread_mutex_lock(&mutex); printf("mem1: %d\\nmem2: %d\\n",*((int *)offset),*((int *)offset +1)); pthread_mutex_unlock(&mutex); return 0; } main(){ int fd; if((fd = shm_open("/shm1",O_RDWR|O_CREAT,0664)) == -1) perror("shm_open"); if(ftruncate(fd,getpagesize())) perror("ftruncate"); void *offset = mmap(0,getpagesize(),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0); pthread_t tid1,tid2; pthread_create(&tid1,0,threadFunc1,offset); pthread_create(&tid2,0,threadFunc2,offset); pthread_join(tid1,0); pthread_join(tid2,0); }
0
#include <pthread.h> int elementos[10]; int in = 0; int out = 0; int total = 0; int producidos = 0, consumidos = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t consume_t = PTHREAD_COND_INITIALIZER; pthread_cond_t produce_t = PTHREAD_COND_INITIALIZER; void * productor(void *); void * consumidor(void *); int main(int argc, const char * argv[]) { srand((int) time(0)); int nhilos = 5 + 3; pthread_t * obreros = (pthread_t *) malloc (sizeof(pthread_t) * nhilos); int indice = 0; pthread_t * aux; for (aux = obreros; aux < (obreros+5); ++aux) { printf("--- Creando el productor %d ---\\n", ++indice); pthread_create(aux, 0, productor, (void *) indice); } indice = 0; for (; aux < (obreros+nhilos); ++aux) { printf("--- Creando el consumidor %d ---\\n", ++indice); pthread_create(aux, 0, consumidor, (void *) indice); } for (aux = obreros; aux < (obreros+nhilos); ++aux) { pthread_join(*aux, 0); } free(obreros); return 0; } void * productor(void * arg) { int id = (int) arg; while (producidos < 100) { usleep(rand() % 500); pthread_mutex_lock(&mutex); if (total < 10) { elementos[in] = producidos; printf(" +++ (Productor %d) Se produjo el elemento %d\\n", id, elementos[in]); ++producidos; ++in; in %= 10; ++total; if (total == 1) { pthread_cond_broadcast(&consume_t); } } else { printf("zzzzz (Productor %d) se va a dormir \\n", id); pthread_cond_wait(&produce_t, &mutex); printf("uuuuu (Productor %d) se despertó \\n", id); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void * consumidor(void * arg) { int id = (int) arg; while (consumidos < 100) { usleep(rand() % 500); pthread_mutex_lock(&mutex); if (total > 0) { printf(" --- (Consumidor %d) Se consumió el elemento %d\\n", id, elementos[out]); ++consumidos; ++out; out %= 10; --total; if (total == 10 -1) { pthread_cond_broadcast(&produce_t); } } else { printf("ZZZZZ (Consumidor %d) se va a dormir \\n", id); pthread_cond_wait(&consume_t, &mutex); printf("UUUUU (Consumidor %d) se despertó \\n", id); } pthread_mutex_unlock(&mutex); } pthread_exit(0); }
1
#include <pthread.h> pthread_t test_threads[2]; static pthread_mutex_t test_mutex = PTHREAD_MUTEX_INITIALIZER; int test_reg; void perror_exit(char *error_message) { printf("error: %s\\n", error_message); exit(1); } void* test_mutex_thread1(void *thread_arg) { unsigned int i; for(i = 0; i < (100000000); i++) { pthread_mutex_lock(&test_mutex); test_reg++; pthread_mutex_unlock(&test_mutex); } return 0; } void* test_mutex_thread2(void *thread_arg) { unsigned int i; for(i = 0; i < (100000000); i++) { pthread_mutex_lock(&test_mutex); test_reg--; pthread_mutex_unlock(&test_mutex); } return 0; } void* test_atomic_thread1(void *thread_arg) { unsigned int i; for(i = 0; i < (100000000); i++) { atomic_fetch_add(&test_reg, 1); } return 0; } void* test_atomic_thread2(void *thread_arg) { unsigned int i; for(i = 0; i < (100000000); i++) { atomic_fetch_sub(&test_reg, 1); } return 0; } void start_test_threads(void *(*test_thread1)(void *), void *(*test_thread2)(void *)) { if(pthread_create(&test_threads[0], 0, test_thread1, 0) != 0) perror_exit("Cant create thread1"); if(pthread_create(&test_threads[1], 0, test_thread2, 0) != 0) perror_exit("Cant create thread2"); if(pthread_join(test_threads[0], 0) != 0) perror_exit("Cant join thread1"); if(pthread_join(test_threads[1], 0) != 0) perror_exit("Cant join thread2"); } void run_test(void *(*test_thread1)(void *), void *(*test_thread2)(void *)) { unsigned int full_time; float delay, speed; static struct timespec time_start, time_end; test_reg = 0; clock_gettime(CLOCK_REALTIME, &time_start); start_test_threads(test_thread1, test_thread2); clock_gettime(CLOCK_REALTIME, &time_end); full_time = (unsigned int)(time_end.tv_sec-time_start.tv_sec); delay = (float)full_time/((100000000)*2); speed = 1.0/delay; printf("time = %u\\n", full_time); printf("delay = %e\\n", delay); printf("speed = %f\\n", speed); if(test_reg == 0) printf("Test is passed (test_reg is 0)\\n\\n"); else printf("Test is broken (test_reg must be is 0, but is %d\\n\\n", test_reg); } int main(void) { printf("run mutex test threads, wait...\\n\\n"); run_test(test_mutex_thread1, test_mutex_thread2); printf("run atomic test threads, wait...\\n\\n"); run_test(test_atomic_thread1, test_atomic_thread2); return 0; }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; { int _data; struct _node *_next; }node_t, *node_p, **node_pp; node_p head; static node_p alloc_node(int data) { node_p tmp = (node_p)malloc(sizeof(node_t)); if(!tmp) { perror("malloc"); exit(1); } tmp->_data = data; tmp->_next = 0; } void initList(node_pp _h) { *_h = alloc_node(0); } void pushFront(node_p h, int data) { node_p tmp = alloc_node(data); tmp->_next = h->_next; h->_next = tmp; } static void free_node(node_p _n) { if(_n) { free(_n); } } int isEmpty(node_p h) { return h->_next == 0 ? 1 : 0; } void popFront(node_p h, int *out) { if(!isEmpty(h)) { node_p tmp = h->_next; h->_next = tmp->_next; *out = tmp->_data; free_node(tmp); } } void showList(node_p h) { node_p start = h->_next; while(start) { printf("%d ", start->_data); start = start->_next; } printf("\\n"); } void destoryList(node_p h) { int out; while(!isEmpty(h)) { popFront(h, &out); } free_node(h); } void* product(void *arg) { while(1) { int data = rand()%1234; pthread_mutex_lock(&lock); pushFront(head, data); pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); printf("The product success:%d\\n", data); sleep(1); } } void* consume(void *arg) { while(1) { int data = -1; pthread_mutex_lock(&lock); while(isEmpty(head)) { printf("no data, The consumer wait...\\n"); pthread_cond_wait(&cond, &lock); } popFront(head, &data); pthread_mutex_unlock(&lock); printf("The consume success:%d\\n", data); } } int main() { pthread_t p; pthread_t c; pthread_create(&p, 0, product, 0); pthread_create(&c, 0, consume, 0); initList(&head); destoryList(head); pthread_join(p, 0); pthread_join(c, 0); return 0; }
1
#include <pthread.h> char *get_line (char *buf, size_t bufsize); int idle_count = 0; int update = 0; pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER; void *tenSecTillFee(void *arg) { int tries = 0; int response; while(1){ tries = 0; while(tries < 10) { sleep(1); pthread_mutex_lock(&my_mutex); if(update == 1) { tries = 0; update = 0; }else { tries++; } pthread_mutex_unlock(&my_mutex); } response = bank_do_command("withdraw",100); printf("\\nSilly you! New balance = $%d", response); printf("\\nprompt> "); fflush(stdout); } return 0; } int main(int argc, char **argv) { bank_init(0); pthread_t t1; pthread_create(&t1, 0, tenSecTillFee, 0); while (1) { char buffer[1024 +1]; printf("prompt> "); fflush(stdout); if (0 == get_line(buffer, 1024)) break; idle_count = 0; char *saveptr; char *cmd = strtok_r(buffer, " ", &saveptr); if (cmd == 0) continue; char *val = strtok_r(0, " ,\\t\\n", &saveptr); int value = (val != 0 ? atoi(val) : -1); int response; if ((response = bank_do_command(cmd,value)) != -1) { printf("Executed(%s). New balance = $%d\\n",cmd, response); pthread_mutex_lock(&my_mutex); update = 1; pthread_mutex_unlock(&my_mutex); continue; } if (strcmp(cmd, "exit") == 0) { break; } if (strcmp(cmd, "help") == 0) { printf("Help for our bank account demo.\\n" "\\tFORMAT:\\t\\tcommand [value]\\n\\n" "\\tRecognized commands:\\n" "\\tdeposit\\t\\tadd [value] dollars to the balance.\\n" "\\twithdraw\\tsubtract [value] dollars from the balance.\\n" "\\tbalance\\t\\tprint out the current balance.\\n" "\\texit\\t\\tquit the program.\\n\\n"); continue; } printf("Unrecognized command (cmd=%s, val=%d), try \\"help\\"\\n",cmd,value); } printf("Ok. we're done...\\n"); return 0; } char *get_line (char *buf, size_t bufsize) { char *p = fgets (buf, bufsize, stdin); if (p != 0) { size_t last = strlen (buf) - 1; if (buf[last] == '\\n') buf[last] = '\\0'; } return p; }
0
#include <pthread.h> 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: ; goto 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 =42%(5); if ((push(arr,tmp)==(-1))) { printf("\\033[1;31m ERROR!!! \\033[0m\\n"); } 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))) { printf("\\033[1;31m ERROR!!! \\033[0m\\n"); } } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(800)]; 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==(800)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(800); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> { 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, max = grid[j][0]; for(i=0;i<info->place;i++) { if(max < grid[j][i]) max = grid[j][i]; } pthread_mutex_lock(&themutex); if(answer < max) answer = max; pthread_mutex_unlock(&themutex); }
1
#include <pthread.h> int x[10000]; int i1,j,check=1,size; int usf[1000],usl[1000]; clock_t start, end; double time_spent; int partition(int a[], int p, int r); pthread_mutex_t lock,lock1,lock2,lock3,lock4; { int x; int counter; }t_data; void *init1 (void*arg) { int id,c; t_data *t=(t_data*)arg; id=t->x; c=t->counter; c=0; printf("\\nentering thread %d\\n",id); int f,i,l,r,c1,c2,c3,c4,c5,c6; while(check){ printf("entered the first loop in thread 1\\n"); pthread_mutex_lock(&lock1); c1=i1; c2=j; pthread_mutex_unlock(&lock1); while(c1>=0 && c2>=0){ pthread_mutex_lock(&lock2); f=usf[c1];l=usl[c2];i1=--c1;j=--c2; if((i1==-1)&&(usf[i1]>=usl[j])) check=0; pthread_mutex_unlock(&lock2); if(f<l){ r=partition(x,f,l); c++; pthread_mutex_lock(&lock3); c1=++i1;c2=++j; usf[i1]=f;usl[j]=r-1; c1=++i1;c2=++j; usf[i1]=r+1;usl[j]=l; pthread_mutex_unlock(&lock3); } } } printf("iteration of %d thread is %d",id,c); } void *init2 (void*arg) { int id,c; t_data *k=(t_data*)arg; id=k->x; c=k->counter; c=0; printf("\\nentering thread %d\\n",id); int f,i,l,r,c1,c2,c3,c4,c5,c6; usleep(200); printf("the value of check in thread 2 : %d\\n",check); while(check){ printf("\\nentering thread %d\\n",id); pthread_mutex_lock(&lock1); c1=i1; c2=j; pthread_mutex_unlock(&lock1); printf("c1 and c2 =%d %d\\n",c1,c2); while(c1>=0 && c2>=0){ pthread_mutex_lock(&lock2); f=usf[c1];l=usl[c2];i1=--c1;j=--c2; if((i1==-1)&&(usf[i1]>=usl[j])) check=0; pthread_mutex_unlock(&lock2); if(f<l){ r=partition(x,f,l); c++; pthread_mutex_lock(&lock3); c1=++i1;c2=++j; usf[i1]=f;usl[j]=r-1; c1=++i1;c2=++j; usf[i1]=r+1;usl[j]=l; pthread_mutex_unlock(&lock3); } } } printf("iteration of %d thread is %d",id,c); } main(){ int i,k1,k2,r; t_data t1[2]; for (i=0;i<2;i++){ t1[i].x=i+1;} pthread_t t[2]; srand(time(0)); printf("Enter size of the array: "); scanf("%d",&size); for(i=0;i<size;i++){ x[i]=rand() % 1000 + 1; } printf("\\nrandom numbers in random order : "); for(i=0;i<size;i++){ printf("%d ",x[i]); } pthread_mutex_init(&lock, 0); pthread_mutex_init(&lock1, 0); pthread_mutex_init(&lock2, 0); pthread_mutex_init(&lock3, 0); pthread_mutex_init(&lock4, 0); start=clock(); i1=0;j=0; usf[i1]=0; usl[j]=size-1; i1--;j--; r=partition(x,0,size-1); i1++;j++; usf[i1]=0;usl[j]=r-1; i1++;j++; usf[i1]=r+1;usl[j]=size-1; k1=pthread_create(&t[0],0,init1,(void *)&t1[0]); k2=pthread_create(&t[1],0,init2,(void *)&t1[1]); for (i = 0; i < 2; ++i) { pthread_join(t[i], 0); } printf("Sorted elements: "); for(i=0;i<size;i++) printf(" %d",x[i]); end = clock(); time_spent = (double)(end - start) / CLOCKS_PER_SEC; } int partition(int x[], int p, int r) { int i, j1, temp,p_index; p_index=p; i = p; j1 = r; while(i<j1) { while(x[i] <= x[p_index] && i<r) i++; while(x[j1] > x[p_index]) j1--; if(i < j1) { temp = x[i]; x[i] = x[j1]; x[j1] = temp; } } temp=x[p_index]; x[p_index]=x[j1]; x[j1]=temp; return j1; }
0
#include <pthread.h> static int (*old_pthread_create)(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); static unsigned long page_size; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static FILE *out_file = 0; static void * aligned(const void *p) { return (void*)((unsigned long)p & ~(page_size - 1)); } static int incore(const char *p) { unsigned char v; int ret; ret = mincore(aligned(p), 1, &v); if (ret < 0 && errno == ENOMEM) return 0; assert(ret == 0); return v & 1; } static int cmp(const void *key, const void *p) { assert(key == ((void*)0xdeadbeef)); int a = incore(p); int b = incore(p + page_size); ; if (a != b) return 0; else if (a) return -1; else return 1; } static pid_t gettid(void) { return syscall(SYS_gettid); } static void do_report(FILE *out) { pid_t tid = gettid(); char name[16+1] = {}; prctl(PR_GET_NAME, name); pthread_attr_t attr; int ret; size_t stack_size, guard_size; void *stack_addr; ret = pthread_getattr_np(pthread_self(), &attr); assert(ret == 0); ret = pthread_attr_getstack(&attr, &stack_addr, &stack_size); assert(ret == 0); ret = pthread_attr_getguardsize(&attr, &guard_size); assert(ret == 0); assert(stack_addr && stack_size); assert(!incore(stack_addr)); assert(incore(stack_addr + stack_size - page_size)); void *last_used = bsearch(((void*)0xdeadbeef), (void*)stack_addr, stack_size/page_size - 1, page_size, cmp); assert(last_used); unsigned long used = stack_addr + stack_size - last_used; fprintf(out, "tid %lu name %s stack_addr %p stack_lim %p" " guard_size %lu stack_used %lu\\n", (long)tid, name, stack_addr, stack_addr + stack_size, guard_size, used); } static void do_report_main(void) { pthread_mutex_lock(&mutex); if (out_file) { do_report(out_file); fflush(out_file); } pthread_mutex_unlock(&mutex); } static void thread_reporter(void *unused) { do_report_main(); } struct wrapper_arg { void *(*start_routine) (void *); void *arg; }; static void * start_routine_wrapper(void *arg) { struct wrapper_arg *wrapper_arg = arg; struct wrapper_arg wa = *wrapper_arg; void *rc; free(arg); pthread_cleanup_push(thread_reporter, 0); rc = wa.start_routine(wa.arg); pthread_cleanup_pop(1); return rc; } int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) { struct wrapper_arg *wrapper_arg; wrapper_arg = malloc(sizeof(*wrapper_arg)); if (!wrapper_arg) { errno = EAGAIN; return -1; } wrapper_arg->start_routine = start_routine; wrapper_arg->arg = arg; return old_pthread_create(thread, attr, start_routine_wrapper, wrapper_arg); } static void * get_sym(const char *symbol) { void *sym; char *err; sym = dlsym(RTLD_NEXT, symbol); err = dlerror(); if(err) do { do { fprintf(stderr, "error(%s:%d:%s): " "dlsym(%s) error: %s" "\\n", "stackreport.c", 211, __FUNCTION__, symbol, err); } while(0); abort(); } while(0); return sym; } void __strackreport_init(void) ; void __strackreport_init(void) { page_size = sysconf(_SC_PAGESIZE); old_pthread_create = get_sym("pthread_create"); char *out_file_name = getenv("SR_OUTPUT_FILE"); if (out_file_name) out_file = fopen(out_file_name, "w"); else out_file = stderr; atexit(do_report_main); }
1
#include <pthread.h> void *reallocf_without_thread(void *ptr, size_t size) { void *ret; t_header_block *block; if (ptr == 0) return (malloc_without_thread(size)); if (0 == (block = check_ptr_block(check_ptr_page(ptr), ptr))) return (0); else if (size == 0) { free_without_thread(ptr); return (0); } ret = malloc_without_thread(size); ft_memcpy(ret, block->ptr, block->size < size ? block->size : size); free_without_thread(ptr); return (ret); } void *reallocf(void *ptr, size_t size) { void *ret; if (!check_init()) return (0); pthread_mutex_lock(&g_malloc_lock); ret = reallocf_without_thread(ptr, size); pthread_mutex_unlock(&g_malloc_lock); return (ret); }
0
#include <pthread.h> double integral = 0.0; pthread_mutex_t lock; pthread_t threads[]; double AreaTrapezio(double dx, double h1, double h2) { double area; area = dx * (h1 + h2) / 2; return area; } double f(double x) { return (4 * sqrt(1 - x * x)); } double inferior; double superior; long n; } Limite; Limite *CriaLim(double inferior, double superior, long numero) { Limite *l = (Limite *) malloc(sizeof (Limite)); l->inferior = inferior; l->superior = superior; l->n = numero; return l; } double CalculaArea(double a, double b, int N) { int i; double area, x1, x2, f1, f2 = 0.0; double dx = (b - a) / N; for (i = 0; i < N; i++) { x1 = a + dx * i; x2 = a + dx * (i + 1); if (x1 > 1 || x2 > 1) { printf("%lf, %lf \\n", x1, x2); } f1 = f(x1); f2 = f(x2); area += AreaTrapezio(dx, f1, f2); } return area; } void *ThreadCalculaArea(double aLocal, double bLocal, int n) { double area2 = CalculaArea(aLocal, bLocal, n); pthread_mutex_lock(&lock); integral += area2; pthread_mutex_unlock(&lock); return 0; } void CriaThread(int quantThreads, long divisoes) { int i, k; Limite* l; int nProc = get_nprocs(); threads[quantThreads] = (pthread_t *) malloc(quantThreads * sizeof (pthread_t)); for (i = 0; i < quantThreads; i++) { l = CriaLim((1 / quantThreads) * i - (1 / quantThreads), (1 / quantThreads) * i, divisoes); pthread_create(&(threads[i]), 0, &ThreadCalculaArea, &l); } for (k = 0; k < quantThreads; k++) { pthread_join(threads[k], 0); } } double RankCalculaArea(double A, double B, long int nDivi, int rank, int size) { int nLocal; double larguraLocal; double aLocal; double bLocal; larguraLocal = (B - A) / size; aLocal = A + rank * larguraLocal; bLocal = aLocal + larguraLocal; nLocal = nDivi / size; int nProc = get_nprocs(); CriaThread(nProc, nLocal); double integralRank = integral; return integralRank; } int main(int argc, char **argv) { MPI_Init(&argc, &argv); long numero = 2000; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_mutex_destroy(&lock); int size, rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); double global_sum; double local_sum; local_sum = RankCalculaArea(0.0, 1.0, numero, rank, size); MPI_Reduce(&local_sum, &global_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) { printf("Total sum = %f \\n", global_sum); } MPI_Finalize(); return (0); }
1
#include <pthread.h> static const int MIN_PID = 300; static const int MAX_PID = 5000; static const int NUM_THREADS = 300; static uint8_t pidman[588]; static pthread_mutex_t mutex; static int allocate_map(void) { memset(pidman, 0x00, sizeof pidman); pthread_mutex_init(&mutex, 0); return 1; } static int allocate_pid(void) { int pid; for (pid = 0; pid <= MAX_PID - MIN_PID; pid++) { pthread_mutex_lock(&mutex); if ((pidman[pid >> 3] & (1 << (pid & 7))) == 0) { pidman[pid >> 3] |= (1 << (pid & 7)); pthread_mutex_unlock(&mutex); return MIN_PID + pid; } pthread_mutex_unlock(&mutex); } return -1; } static void release_pid(int pid) { if (MIN_PID <= pid && pid <= MAX_PID) { pid -= MIN_PID; pthread_mutex_lock(&mutex); pidman[pid >> 3] &= ~(1 << (pid & 7)); pthread_mutex_unlock(&mutex); } } static void *test_one(void *param) { int pid = allocate_pid(); printf("Got PID: %d\\n", pid); sleep(rand() % 5 + 1); release_pid(pid); pthread_exit(0); } int main(void) { pthread_attr_t tattr; pthread_t tids[NUM_THREADS]; int i; allocate_map(); srand(time(0)); pthread_attr_init(&tattr); for (i = 0; i < NUM_THREADS; i++) { pthread_create(&tids[i], &tattr, test_one, 0); } for (i = 0; i < NUM_THREADS; i++) { pthread_join(tids[i], 0); } return 0; }
0