text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> void signal_handler(int); clock_t program_time(); double ptime(); void add_line(const char*); void print_lines(); char* buffer[11]; int frnt = 0, back = 0; pthread_mutex_t buffer_lock; struct sigaction act; int main(void) { if (pthread_mutex_init(&buffer_lock, 0) != 0) { fprintf(stderr, "Could not create mutex...exiting\\n"); exit(1); } sigemptyset(&act.sa_mask); sigaddset(&act.sa_mask, SIGTSTP); sigaddset(&act.sa_mask, SIGALRM); act.sa_handler = signal_handler; act.sa_flags = SA_RESTART; sigaction(SIGALRM, &act, 0); sigaction(SIGINT, &act, 0); sigaction(SIGTERM, &act, 0); sigaction(SIGTSTP, &act, 0); struct itimerval timer; timer.it_interval.tv_sec = 10; timer.it_interval.tv_usec = 1; timer.it_value = timer.it_interval; setitimer(ITIMER_REAL, &timer, 0); while(1) { char* line = 0; size_t len = 0; ssize_t linelen; if ((linelen = getline(&line, &len, stdin)) != -1) { printf("%s\\n", line); pthread_mutex_lock(&buffer_lock); line[linelen-1] = '\\0'; if (back < frnt) free(buffer[back]); buffer[back] = line; back = (back + 1) % 11; if (back == frnt) frnt = (frnt + 1) % 11; pthread_mutex_unlock(&buffer_lock); } } } void signal_handler(int status) { static int count = 0; switch (status) { case SIGALRM: printf("tick %d...\\n", count); count+=10; break; case SIGINT: printf("Program time: %f\\n", ptime()); break; case SIGTSTP: print_lines(); break; case SIGTERM: printf("Program time: %f\\nCleaning up...\\n", ptime()); for (; frnt != back; frnt = (frnt + 1) % 11) free(buffer[frnt]); exit(0); } } void print_lines() { int i; pthread_mutex_lock(&buffer_lock); for (i = frnt; i != back; i = (i + 1) % 11) { printf(" %s\\n", buffer[i]); } pthread_mutex_unlock(&buffer_lock); } double ptime() { struct rusage usage; getrusage(RUSAGE_SELF, &usage); return usage.ru_utime.tv_sec + (usage.ru_utime.tv_usec / 1000.) + usage.ru_stime.tv_sec + (usage.ru_stime.tv_usec / 1000.); }
1
#include <pthread.h>extern int __VERIFIER_nondet_int(); int idx=0; int ctr1=1, ctr2=0; int readerprogress1=0, readerprogress2=0; pthread_mutex_t mutex; void __VERIFIER_atomic_use1(int myidx) { __VERIFIER_assume(myidx <= 0 && ctr1>0); ctr1++; } void __VERIFIER_atomic_use2(int myidx) { __VERIFIER_assume(myidx >= 1 && ctr2>0); ctr2++; } void __VERIFIER_atomic_use_done(int myidx) { if (myidx <= 0) { ctr1--; } else { ctr2--; } } void __VERIFIER_atomic_take_snapshot(int readerstart1, int readerstart2) { readerstart1 = readerprogress1; readerstart2 = readerprogress2; } void __VERIFIER_atomic_check_progress1(int readerstart1) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1); if (!(0)) ERROR: goto ERROR;; } return; } void __VERIFIER_atomic_check_progress2(int readerstart2) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1); if (!(0)) ERROR: goto ERROR;; } return; } void *qrcu_reader1() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress1 = 1; readerprogress1 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void *qrcu_reader2() { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress2 = 1; readerprogress2 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void* qrcu_updater() { int i; int readerstart1, readerstart2; int sum; __VERIFIER_atomic_take_snapshot(readerstart1, readerstart2); if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; } else {} if (sum > 1) { pthread_mutex_lock(&mutex); if (idx <= 0) { ctr2++; idx = 1; ctr1--; } else { ctr1++; idx = 0; ctr2--; } if (idx <= 0) { while (ctr1 > 0); } else { while (ctr2 > 0); } pthread_mutex_unlock(&mutex); } else {} __VERIFIER_atomic_check_progress1(readerstart1); __VERIFIER_atomic_check_progress2(readerstart2); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mutex, 0); pthread_create(&t1, 0, qrcu_reader1, 0); pthread_create(&t2, 0, qrcu_reader2, 0); pthread_create(&t3, 0, qrcu_updater, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_t tid[8]; pthread_mutex_t mutex; int *array; float arraytime[8]; int length = 1000000000; int count = 0; int double_count = 0; int t = 8; int max_threads = 0; void *count3s_thread(void *arg) { int i; clock_t t1th, t2th; int length_per_thread = length/max_threads; int id = (int)arg; int start = id * length_per_thread; printf("\\tThread [%d] starts [%d] length [%d]\\n",id, start, length_per_thread); t1th=clock(); for (i = start; i < start + length_per_thread; i++) { if (array[i] == 3) { pthread_mutex_lock(&mutex); count++; pthread_mutex_unlock(&mutex); } } t2th=clock(); arraytime[id]=(((float)t2th - (float)t1th) / 1000000.0F ) * 1000; } void initialize_vector() { int i = 0; array = (int*) malloc(sizeof(int) * 1000000000); if (array == 0) { printf("Allocation memory failed!\\n"); exit(-1); } for (; i < 1000000000; i++) { array[i] = rand() % 20; if (array[i] == 3) double_count++; } } int main(int argc, char* argv[]) { int i = 0; int err; clock_t t1, t2 , t1ini, t2ini; if (argc == 2) { max_threads = atoi(argv[1]); if (max_threads > 8) max_threads = 8; } else { max_threads = 8; } printf("[3s-04] Using %d threads\\n",max_threads); srand(time(0)); printf("*** 3s-04 ***\\n"); printf("Initializing vector... "); fflush(stdout); t1ini= clock(); initialize_vector(); t2ini= clock(); printf("Vector initialized!\\n"); fflush(stdout); t1 = clock(); pthread_mutex_init(&mutex,0); while (i < max_threads) { err = pthread_create(&tid[i], 0, &count3s_thread, (void*)i); if (err != 0) printf("[3s-04] Can't create a thread: [%d]\\n", i); else printf("[3s-04] Thread created!\\n"); i++; } i = 0; for (; i < max_threads; i++) { void *status; int rc; rc = pthread_join(tid[i], &status); if (rc) { printf("ERROR; retrun code from pthread_join() is %d\\n", rc); exit(-1); } else { printf("Thread [%d] exited with status [%ld]\\n", i, (long)status); } } t2 = clock(); printf("[3s-04] Count by threads %d\\n", count); printf("[3s-04] Double check %d\\n", double_count); pthread_mutex_destroy(&mutex); printf("[[3s-04] Initializing time %f\\n", (((float)t2ini - (float)t1ini) / 1000000.0F ) * 1000); printf("[[3s-04] Elapsed time %f\\n", (((float)t2 - (float)t1) / 1000000.0F ) * 1000); for(i=0; i<8; i++){ printf("[[3s-04] Elapsed time thread [%d] = %f\\n",i, arraytime[i]); } pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int *value; int shmid; void init() { shmid = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0700); value = (int*) shmat(shmid, 0, 0); *value = 1000; } void terminate() { pthread_mutex_destroy(&mutex); if (shmid > 0) { shmctl(shmid, IPC_RMID, 0); } } void *worker(void *id) { int r; int aux = *((int*) id); int my_id = aux; srand(time(0)); r = rand() % 2 + 1; sleep(r); pthread_mutex_lock(&mutex); *value += 1; printf("Thread with id == %d incremented value by 1\\n", my_id); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main() { int i; init(); pthread_t threads; int id[100]; for (i = 0; i < 100; i++) { id[i] = i; pthread_create(&threads, 0, worker, &id[i]); } for (i = 0; i < 100; i++) { pthread_join(threads, 0); } printf("The final value is %d\\n", *value); terminate(); }
0
#include <pthread.h> pthread_mutex_t mut1=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut2=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut3=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void sigint_handler(int s) { pthread_mutex_destroy(&mut1); pthread_mutex_destroy(&mut2); pthread_mutex_destroy(&mut3); exit(0); } void* f(void* arg) { while(1) { pthread_mutex_lock(&mut1); printf("first\\n"); pthread_mutex_unlock(&mut2); } } void* s(void* arg) { while(1) { pthread_mutex_lock(&mut2); printf("second\\n"); pthread_mutex_unlock(&mut3); } } void* t(void* arg) { while(1) { pthread_mutex_lock(&mut3); printf("third\\n"); pthread_mutex_unlock(&mut1); } } int main (void) { struct sigaction sa; sa.sa_handler=sigint_handler; sa.sa_flags=SA_RESTART; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); pthread_t th1, th2, th3; pthread_mutex_lock(&mut3); pthread_mutex_lock(&mut2); int ptid1=pthread_create(&th1, 0, f, 0); int ptid2=pthread_create(&th2, 0, s, 0); int ptid3=pthread_create(&th3, 0, t, 0); pthread_join(th1, 0); pthread_join(th2, 0); pthread_join(th3, 0); exit(0); }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_hit_threshold; void *inc_count( void *idp ) { while(1){ pthread_mutex_lock( &count_lock ); count++; printf( "inc_count: %d\\n", count ); if(count == 4 ){ pthread_cond_broadcast( &count_hit_threshold ); } if( count == 10 ){ pthread_mutex_unlock( &count_lock ); break; } else { pthread_mutex_unlock( &count_lock ); } } } void *watch_count( void *idp ) { pthread_mutex_lock( &count_lock ); while( count < 4 ){ gprintf( "fucking wait\\n"); pthread_cond_wait( &count_hit_threshold, &count_lock ); } printf( "watch_count: %d\\n", count ); pthread_mutex_unlock( &count_lock ); return 0; } main() { int i; pthread_t threads[3]; pthread_cond_init( &count_hit_threshold , 0 ); pthread_create( &threads[0] , 0 , inc_count, (void*)0 ); pthread_create( &threads[1] , 0 , watch_count, (void*)0 ); pthread_join( threads[0] , 0 ); pthread_join( threads[1] , 0 ); }
0
#include <pthread.h> static pthread_mutex_t testlock; static void *Func(void *arg) { pthread_mutex_lock(&testlock); char *s = (char *)arg; printf("%s\\n", s); pthread_mutex_unlock(&testlock); return (void *)strlen(s); } int main(int argc, char *argv[]) { pthread_t thread; void *res; int s; pthread_mutex_init(&testlock, 0); pthread_mutex_lock(&testlock); s = pthread_create(&thread, 0, Func, "hello world\\n"); if (s != 0) { } printf("pthread Main()\\n"); pthread_mutex_unlock(&testlock); s = pthread_join(thread, &res); if (s != 0) { } printf("pthread join\\n"); return 0; }
1
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static unsigned int seed0; static unsigned int seed1; static int have_init = 0; static int read_dev_random (void *buffer, size_t buffer_size) { int fd; ssize_t status = 0; char *buffer_position; size_t yet_to_read; fd = open ("/dev/urandom", O_RDONLY); if (fd < 0) { perror ("open"); return (-1); } buffer_position = (char *) buffer; yet_to_read = buffer_size; while (yet_to_read > 0) { status = read (fd, (void *) buffer_position, yet_to_read); if (status < 0) { if (errno == EINTR) continue; fprintf (stderr, "read_dev_random: read failed.\\n"); break; } buffer_position += status; yet_to_read -= (size_t) status; } close (fd); if (status < 0) return (-1); return (0); } static void do_init (void) { if (have_init) return; read_dev_random (&seed0, sizeof (seed0)); read_dev_random (&seed1, sizeof (seed1)); have_init = 1; } int sn_random_init (void) { have_init = 0; do_init (); return (0); } int sn_random (void) { int r0; int r1; pthread_mutex_lock (&lock); do_init (); r0 = rand_r (&seed0); r1 = rand_r (&seed1); pthread_mutex_unlock (&lock); return (r0 ^ r1); } int sn_true_random (void) { int ret = 0; int status; status = read_dev_random (&ret, sizeof (ret)); if (status != 0) return (sn_random ()); return (ret); } int sn_bounded_random (int min, int max) { int range; int rand; if (min == max) return (min); else if (min > max) { range = min; min = max; max = range; } range = 1 + max - min; rand = min + (int) (((double) range) * (((double) sn_random ()) / (((double) 32767) + 1.0))); assert (rand >= min); assert (rand <= max); return (rand); } double sn_double_random (void) { return (((double) sn_random ()) / (((double) 32767) + 1.0)); } pthread_mutex_t lock; pthread_mutex_t lock2; pthread_cond_t empty; pthread_cond_t full; struct item{ int val; int sleeptime; }; struct item * buffer; void * consumer(void *dummy) { pthread_mutex_lock(&lock2); int * curitem = (int *)(dummy); pid_t x = syscall(__NR_gettid); pthread_mutex_unlock(&lock2); while(1) { pthread_mutex_lock(&lock); fflush(stdout); while(*curitem < 0){ pthread_cond_wait(&empty, &lock); } sleep(buffer[*curitem].sleeptime); printf("(CONSUMER) My ID is %d and I ate the number %d in %d seconds\\n\\n",x,buffer[*curitem].val, buffer[*curitem].sleeptime); buffer[*curitem].val = 0; buffer[*curitem].sleeptime = 0; *curitem = *curitem - 1; pthread_mutex_unlock(&lock); if(*curitem == 30){ pthread_cond_signal(&full); } } return 0; } void * producer(void *dummy) { pthread_mutex_lock(&lock2); int * curitem = (int *)(dummy); pid_t x = syscall(__NR_gettid); pthread_mutex_unlock(&lock2); int i = 0; while(1) { sleep(generate_rand(3,7)); fflush(stdout); pthread_mutex_lock(&lock); while(*curitem > 30){ pthread_cond_wait(&full, &lock); } *curitem = *curitem + 1; i = (int)generate_rand(0,10); printf("(PRODUCER) My ID is %d and I created the value %d\\n\\n",x,i); buffer[*curitem].val = i; i = (int)generate_rand(2,9); buffer[*curitem].sleeptime = i; if(*curitem == 0){ pthread_cond_signal(&empty); } pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char **argv) { int * curitem = malloc(sizeof(int)); int curthread = 0; buffer = malloc(sizeof(struct item)*32); *curitem = -1; pthread_mutex_init(&lock, 0); pthread_mutex_init(&lock2, 0); pthread_cond_init(&full, 0); pthread_cond_init(&empty, 0); int threadcap = atoi(argv[1]); pthread_t conthreads[threadcap]; pthread_t prod; pthread_create(&prod, 0, producer, (void*)curitem); for(; curthread < threadcap; curthread++) pthread_create(&conthreads[curthread], 0, consumer, (void*)curitem); pthread_join(prod, 0); for(curthread = 0; curthread < threadcap; curthread++) pthread_join(conthreads[curthread], 0); return 0; }
0
#include <pthread.h> static struct option gLongOptions[] = { {"server", required_argument, 0, 's'}, {"port", required_argument, 0, 'p'}, {"workload-path", required_argument, 0, 'w'}, {"nthreads", required_argument, 0, 't'}, {"nrequests", required_argument, 0, 'n'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* worker(void*); char *server2; unsigned short port2; static void Usage() { fprintf(stdout, "%s", "usage:\\n" " webclient [options]\\n" "options:\\n" " -s [server_addr] Server address (Default: 0.0.0.0)\\n" " -p [server_port] Server port (Default: 8888)\\n" " -w [workload_path] Path to workload file (Default: workload.txt)\\n" " -t [nthreads] Number of threads (Default 1)\\n" " -n [num_requests] Requests download per thread (Default: 1)\\n" " -h Show this help message\\n"); } static void localPath(char *req_path, char *local_path){ static int counter = 0; sprintf(local_path, "%s-%06d", &req_path[1], counter++); } static FILE* openFile(char *path){ char *cur, *prev; FILE *ans; prev = path; while(0 != (cur = strchr(prev+1, '/'))){ *cur = '\\0'; if (0 > mkdir(&path[0], S_IRWXU)){ if (errno != EEXIST){ perror("Unable to create directory"); exit(1); } } *cur = '/'; prev = cur; } if( 0 == (ans = fopen(&path[0], "w"))){ perror("Unable to open file"); exit(1); } return ans; } static void writecb(void* data, size_t data_len, void *arg){ FILE *file = (FILE*) arg; fwrite(data, 1, data_len, file); } int main(int argc, char **argv) { char *server = "localhost"; unsigned short port = 8888; char *workload_path = "workload.txt"; int i; int option_char = 0; int nrequests = 1; int nthreads = 1; while ((option_char = getopt_long(argc, argv, "s:p:w:n:t:h", gLongOptions, 0)) != -1) { switch (option_char) { case 's': server = optarg; break; case 'p': port = atoi(optarg); break; case 'w': workload_path = optarg; break; case 'n': nrequests = atoi(optarg); break; case 't': nthreads = atoi(optarg); break; case 'h': Usage(); exit(0); break; default: Usage(); exit(1); } } if( 0 != workload_init(workload_path)){ fprintf(stderr, "Unable to load workload file %s.\\n", workload_path); exit(1); } server2 =server; port2 = port; gfc_global_init(); pthread_t workers[nthreads]; pthread_attr_t attr; pthread_attr_init(&attr); for(i = 0; i < nthreads; i++) pthread_create(&workers[i], &attr, worker, &nrequests); pthread_attr_destroy(&attr); for(i = 0; i < nthreads; i++) pthread_join(workers[i], 0); gfc_global_cleanup(); return 0; } void *worker(void* requests) { int* nrequests = (int*)requests; gfcrequest_t *gfr; char local_path[256];; char* req_path; FILE* file; int j = 0; int returncode; while(j < *nrequests) { j++; pthread_mutex_lock(&lock); req_path = workload_get_path(); if(strlen(req_path) > 256){ fprintf(stderr, "Request path exceeded maximum of 256 characters\\n."); continue; } localPath(req_path, local_path); file = openFile(local_path); pthread_mutex_unlock(&lock); gfr = gfc_create(); gfc_set_server(gfr, server2); gfc_set_path(gfr, req_path); gfc_set_port(gfr, port2); gfc_set_writefunc(gfr, writecb); gfc_set_writearg(gfr, file); fprintf(stdout, "Requesting %s%s\\n", server2, req_path); if ( 0 > (returncode = gfc_perform(gfr))){ fprintf(stdout, "gfc_perform returned an error %d\\n", returncode); fclose(file); if ( 0 > unlink(local_path)) fprintf(stderr, "unlink failed on %s\\n", local_path); } else { fclose(file); } if ( gfc_get_status(gfr) != GF_OK){ if ( 0 > unlink(local_path)) fprintf(stderr, "unlink failed on %s\\n", local_path); } fprintf(stdout, "Status: %s\\n", gfc_strstatus(gfc_get_status(gfr))); fprintf(stdout, "Received %zu of %zu bytes\\n", gfc_get_bytesreceived(gfr), gfc_get_filelen(gfr)); } }
1
#include <pthread.h> struct job { int id; struct job *next; }; void process_job (struct job *one_job) { printf("Thread_%d is process job %d\\n", (int)pthread_self (), one_job->id); } pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void init_flag () { pthread_mutex_init (&thread_flag_mutex, 0); pthread_cond_init (&thread_flag_cv, 0); thread_flag = 0; } void *thread_func (void *data) { while (1) { struct job *next_job; struct job **job_queue = (struct job **)data; pthread_mutex_lock (&thread_flag_mutex); while (thread_flag == 0) { pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); } pthread_mutex_unlock (&thread_flag_mutex); pthread_mutex_lock (&job_queue_mutex); if ( *job_queue == 0){ pthread_mutex_unlock (&job_queue_mutex); break; } next_job = *job_queue; *job_queue = (*job_queue)->next; pthread_mutex_unlock (&job_queue_mutex); process_job (next_job); free (next_job); } return 0; } void set_thread_flag (int flag) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag; pthread_cond_broadcast (&thread_flag_cv); pthread_mutex_unlock (&thread_flag_mutex); } void enqueue_job (struct job **job_queue, struct job * new_job) { pthread_mutex_lock (&job_queue_mutex); new_job->next = *job_queue; *job_queue = new_job; pthread_mutex_unlock (&job_queue_mutex); } int main() { const int SIZE = 3; pthread_t threads[SIZE]; int i; struct job *job_queue = 0; init_flag(); for (i = 0; i < SIZE; i++) { pthread_create (&(threads[i]), 0, thread_func, &job_queue); } for (i = 0; i < 10; i++) { struct job *new_job = malloc (sizeof (struct job)); new_job->id = i; enqueue_job (&job_queue, new_job); } set_thread_flag(1); for (i = 0; i < SIZE; i++) { pthread_join (threads[i], 0); } return 0; }
0
#include <pthread.h> struct GlobalMemory { int id; pthread_mutex_t id_lock; pthread_barrier_t barrier_rank; } *global; struct GlobalPrivate { int *rank_ff; } gp[(1024)]; int p; int radix; int max_key; int **rank_me; int max_num_digits; int log2_radix; void *slave_sort(void *arg) { int local_id; int *rank_me_mynum; int *rank_ff_mynum; int loopnum; int i; pthread_mutex_lock(&global->id_lock); local_id = global->id; ++global->id; pthread_mutex_unlock(&global->id_lock); rank_me_mynum = rank_me[local_id]; rank_ff_mynum = gp[local_id].rank_ff; for (i = 0; i < radix; ++i) rank_ff_mynum[i] = 0; for (loopnum = 0; loopnum < max_num_digits; ++loopnum) { int shiftnum; int bb; int my_key; shiftnum = loopnum * log2_radix; bb = (radix - 1) << shiftnum; pthread_barrier_wait(&global->barrier_rank); my_key = rand() & bb; my_key = my_key >> shiftnum; printf("loopnum = %d; my_key = %d\\n", loopnum, my_key); rank_me_mynum[my_key]++; } return 0; } int get_max_digits(int max_key) { int done = 0; int temp = 1; int key_val; key_val = max_key; while (!done) { key_val = key_val / radix; if (key_val == 0) { done = 1; } else { temp ++; } } return temp; } long log_2(long number) { long cumulative = 1; long out = 0; long done = 0; while ((cumulative < number) && (!done) && (out < 50)) { if (cumulative == number) { done = 1; } else { cumulative = cumulative * 2; out ++; } } if (cumulative == number) { return(out); } else { return(-1); } } int main(int argc, char *argv[]) { int i; int size; int **temp; int **temp2; int *a; int rem; pthread_t children[(1024)]; if (argc < 4) { return 1; } p = atoi(argv[1]); radix = atoi(argv[2]); max_key = atoi(argv[3]); log2_radix = log_2(radix); max_num_digits = get_max_digits(max_key); if (radix < 1 || radix > (4096)) exit(-1); if (max_key < 1 || max_key > (524288)) exit(-1); if (log2_radix < 0 || radix != (1 << log2_radix)) exit(-1); rem = (max_key >> ((max_num_digits - 1) * log2_radix)); if (max_num_digits <= 0 || max_num_digits >= 32 || rem <= 0 || rem >= radix) exit(-1); global = (struct GlobalMemory *)valloc(sizeof(struct GlobalMemory)); pthread_mutex_init(&global->id_lock, 0); pthread_barrier_init(&global->barrier_rank, 0, p); global->id = 0; size = p * (radix * sizeof(int) + sizeof(int *)); rank_me = (int **)valloc(size); for (i = 0; i < p; ++i) gp[i].rank_ff = (int *)valloc(radix * sizeof(int) + (4096)); temp = rank_me; temp2 = temp + p; a = (int *)temp2; for (i = 0; i < p; ++i) { *temp = (int *)a; ++temp; a += radix; } for (i = 0; i < p - 1; ++i) pthread_create(&children[i], 0, slave_sort, 0); slave_sort(0); for (i = 0; i < p - 1; ++i) pthread_join(children[i], 0); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_cv; void *child (void *args) { int tid; tid = (int) ((long) args); pthread_mutex_lock (&count_mutex); count++; if (count == 4) pthread_cond_signal (&count_cv); pthread_mutex_unlock (&count_mutex); printf ("Thread %d just got it done\\n", tid); pthread_exit (0); } int main (int argc, char *argv[]) { int rc, i; pthread_t threads[4]; pthread_mutex_init (&count_mutex, 0); pthread_cond_init (&count_cv, 0); for (i = 0; i < 4; i++) { long tid = (long) i; rc = pthread_create (&threads[i], 0, child, (void *) tid); if (rc) { printf ("ERROR: code = %d\\n", rc); exit (-1); } } pthread_mutex_lock (&count_mutex); while (count < 4) pthread_cond_wait (&count_cv, &count_mutex); pthread_mutex_unlock (&count_mutex); printf ("Parent is done!\\n"); pthread_mutex_destroy (&count_mutex); pthread_cond_destroy (&count_cv); pthread_exit (0); }
0
#include <pthread.h> enum fstat { FSTAT_EMPTY, FSTAT_USED, FSTAT_CLOSED, FSTAT_NUM }; struct fd_entry { time_t access_time; enum fstat fstat; pthread_mutex_t lock; }; extern int loglevel; extern FILE *debugfp; static inline void debug_log(const char *action, int fd) { if (loglevel > 0 ) { char name[17] = ""; prctl(PR_GET_NAME, name); fprintf(debugfp, "[pid %d %s] %s %s (%d)\\n", getpid(), name, __FUNCTION__, action, fd); } } struct fd_entry fd_entry[2048]; void mgmt_create_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("create", fd); fde->fstat = FSTAT_USED; fde->access_time = time(0); pthread_mutex_unlock(&fde->lock); } void mgmt_close_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("close", fd); if (fde->fstat != FSTAT_USED) { fprintf(debugfp, "[pid %d] fd %d is in %d stated\\n", getpid(), fd, fde->fstat); abort(); } fde->fstat = FSTAT_CLOSED; pthread_mutex_unlock(&fde->lock); } void mgmt_access_fd(int fd) { struct fd_entry *fde = &fd_entry[fd]; pthread_mutex_lock(&fde->lock); debug_log("access", fd); if (fde->fstat != FSTAT_USED) { fprintf(debugfp, "[pid %d] fd %d is in %d state(not used)\\n", getpid(), fd, fde->fstat); abort(); } fde->access_time = time(0); pthread_mutex_unlock(&fde->lock); } int (*__read)(int fd, char *buf, size_t len); static void init_all_fds() ; static void init_all_fds() { int i; struct fd_entry *fde; struct stat buf; for (i = 0, fde = &fd_entry[0]; i < 2048; ++i, ++fde) { if (fstat(i, &buf) == -1 && errno == EBADF) { fde->fstat = FSTAT_EMPTY; } else { fde->fstat = FSTAT_USED; debug_log("In Used", i); } pthread_mutex_init(&fde->lock, 0); fde->access_time = 0; } }
1
#include <pthread.h> pthread_mutex_t lock_mutex = PTHREAD_MUTEX_INITIALIZER; int agent_s, smokerPaper_s, smokerTobacco_s, smokerMatches_s; void *chooseIngredients(); void *smokePaper(); void *smokeTobacco(); void *smokeMatches(); int count = 0; int randNum; main() { pthread_t agent_t, smokerPaper_t, smokerTobacco_t, smokerMatches_t; int rc1, rc2, rc3, rc4; if((agent_s=semget(IPC_PRIVATE,1,0666 | IPC_CREAT)) == -1) { printf("\\n can't create agent semaphore"); exit(1); } if((smokerPaper_s=semget(IPC_PRIVATE,1,0666 | IPC_CREAT)) == -1) { printf("\\n can't create smokerPaper_s semaphore"); exit(1); } if((smokerTobacco_s=semget(IPC_PRIVATE,1,0666 | IPC_CREAT)) == -1) { printf("\\n can't create smokerTobacco_s semaphore"); exit(1); } if((smokerMatches_s=semget(IPC_PRIVATE,1,0666 | IPC_CREAT)) == -1) { printf("\\n can't create smokerMatches_s semaphore"); exit(1); } sem_create(agent_s, 1); sem_create(smokerPaper_s, 0); sem_create(smokerTobacco_s, 0); sem_create(smokerMatches_s, 0); if (rc1 = pthread_create(&agent_t, 0, &chooseIngredients, 0)) { printf("Thread creation failed: %d\\n", rc1); } if (rc2 = pthread_create(&smokerPaper_t, 0, &smokePaper, 0)) { printf("Thread creation failed: %d\\n", rc2); } if (rc3 = pthread_create(&smokerTobacco_t, 0, &smokeTobacco, 0)) { printf("Thread creation failed: %d\\n", rc3); } if (rc4 = pthread_create(&smokerMatches_t, 0, &smokeMatches, 0)) { printf("Thread creation failed: %d\\n", rc4); } pthread_join(agent_t, 0); pthread_join(smokerPaper_t, 0); pthread_join(smokerMatches_t, 0); pthread_join(smokerTobacco_t, 0); exit(0); } void *chooseIngredients(void *ptr) { while (1) { pthread_mutex_lock(&lock_mutex); randNum = rand()%3 + 1; if (randNum == 1) { V(smokerMatches_s); } else if (randNum == 2) { V(smokerPaper_s); } else { V(smokerTobacco_s); } pthread_mutex_unlock(&lock_mutex); P(agent_s); } } void *smokePaper(void *ptr) { while (1) { P(smokerPaper_s); pthread_mutex_lock(&lock_mutex); V(agent_s); printf("Smoker with paper made a cigar\\n"); pthread_mutex_unlock(&lock_mutex); } } void *smokeTobacco(void *ptr) { while (1) { P(smokerTobacco_s); pthread_mutex_lock(&lock_mutex); V(agent_s); printf("Smoker with tobacco made a cigar\\n"); pthread_mutex_unlock(&lock_mutex); } } void *smokeMatches(void *ptr) { while (1) { P(smokerMatches_s); pthread_mutex_lock(&lock_mutex); V(agent_s); printf("Smoker with matches made a cigar\\n"); pthread_mutex_unlock(&lock_mutex); } }
0
#include <pthread.h> int *array; int l; int r; int id; } arg_t; pthread_mutex_t lock; int count; } Counter; sem_t barrier, barrier1; Counter count; int nthreads, swapped = 1, regionsize, n; static int comp_integers(const void *p1, const void *p2){ int *x = (int*) p1; int *y = (int*) p2; int a = *x; int b = *y; return (*x) - (*y); } static void* Th_func(void *args){ arg_t *arg = (arg_t*) args; int *array = (*arg).array; int left = (*arg).l; int right = (*arg).r; int i, l, r, tmp; int id = (*arg).id; pthread_detach(pthread_self()); while(1){ sem_wait(&barrier1); if(swapped == 0){ break; } pthread_mutex_lock(&count.lock); count.count++; if(count.count == nthreads){ for(i = 0; i < nthreads; i++) sem_post(&barrier); } pthread_mutex_unlock(&count.lock); int dim = right - left; qsort(&array[left], right - left +1, sizeof(int), comp_integers); sem_wait(&barrier); pthread_mutex_lock(&count.lock); count.count--; if(count.count == 0){ l = regionsize-1; r = l+1; swapped = 0; for(i = 0; i < nthreads - 1; i++){ if(array[l] > array[r]){ tmp = array[l]; array[l] = array[r]; array[r] = tmp; swapped = 1; } l = l + regionsize; r = l+1; } for(i = 0; i < nthreads; i++) sem_post(&barrier1); } pthread_mutex_unlock(&count.lock); } pthread_exit(0); } int main(int argc, char* argv[]){ int fd, *array, filesize, i, limitsN; struct stat buf; pthread_t *tid; arg_t *arguments; if(argc < 3){ fprintf(stderr, "invalid number of parameters\\n"); return -1; } n = atoi(argv[1]); array = (int*) malloc(n *sizeof(int)); fd = open(argv[2], O_RDWR); array = mmap((caddr_t) 0, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); pthread_mutex_init(&count.lock, 0); count.count = 0; nthreads = ceil(log10(n)); regionsize = n / nthreads; sem_init(&barrier, 0, 0); sem_init(&barrier1, 0, nthreads); tid = (pthread_t*) malloc(nthreads * sizeof(pthread_t)); arguments = (arg_t*) malloc(nthreads * sizeof(arg_t)); int l; int r; l = 0; r = regionsize - 1; for(i = 0; i < nthreads; i++){ arguments[i].l = l; arguments[i].r = r; arguments[i].array = array; arguments[i].id = i; pthread_create(&tid[i], 0, Th_func, (void*) &arguments[i]); l += regionsize; if(i + 1 == nthreads-1) r = n; else r += regionsize; } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int numSortedArr = 0; int arrLength = 150; int* globArray; void createArray(int length) { int *arr = (int*)malloc(sizeof(int)*length); for(int i= 0; i < length; i++) { arr[i] = i; } permutation(arr, length); bubbleSort(arr, length); numSortedArr++; } void permutation(int *arr, int arrSize) { for(int i = 0; i < arrSize; i++){ swap(arr, i, randomizer(arrSize)); } } int randomizer(int arrSize) { int randNum = rand() % arrSize; return randNum; } void swap(int* arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } void bubbleSort(int* arr, int arrSize) { for(int i = 0; i < arrSize; i++) { for(int j=0; j < arrSize - 1; j++) { if(arr[j] > arr[j+1]) { swap(arr, j, j+1); } globArray = arr; } } } void* sorter_startSorting(void* arg) { printf("Started Sorting\\n"); char stopSort = ' '; while(stopSort == ' ') { pthread_mutex_lock(&mutex); createArray(arrLength); free(globArray); pthread_mutex_unlock(&mutex); } printf("Exited sorter\\n"); pthread_exit(0); } void printArr(int *arr, int arrLength, int space) { for(int i = 0; i < arrLength; i++) { if(((i % space) == 0) && (i != 0)) { printf("\\n"); } if(i == arrLength - 1) { printf("%d\\n", arr[i]); } else { printf("%d, \\t", arr[i]); } } }
0
#include <pthread.h> pthread_mutex_t mutex; void *thread_1(void *arg) { pthread_mutex_lock(&mutex); DPRINTF(stdout,"Thread 1 lock the mutex\\n"); pthread_exit(0); return 0; } void *thread_2(void *arg) { pthread_t self = pthread_self(); int policy = SCHED_FIFO; struct sched_param param; param.sched_priority = sched_get_priority_min(policy); int rc; rc = pthread_setschedparam(self, policy, &param); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_setschedparam: %d %s", rc, strerror(rc)); exit(UNRESOLVED); } if (pthread_mutex_lock(&mutex) != EOWNERDEAD) { EPRINTF("FAIL:pthread_mutex_lock didn't return EOWNERDEAD"); exit(FAIL); } DPRINTF(stdout,"Thread 2 locked the mutex and return EOWNERDEAD\\n"); if (pthread_mutex_consistent_np(&mutex) == 0) { pthread_mutex_unlock(&mutex); if (pthread_mutex_lock(&mutex) != 0) { EPRINTF("FAIL: The mutex didn't transit to normal state" " when calling to pthread_mutex_consistent_np" " successfully in Sun Compability mode"); pthread_mutex_unlock(&mutex); exit(FAIL); } else { DPRINTF(stdout,"PASS: The mutex transitted to normal state " "when calling to pthread_mutex_consistent_np " "successfully in Sun compability mode\\n"); pthread_mutex_unlock(&mutex); } } else { pthread_mutex_unlock(&mutex); if (pthread_mutex_lock(&mutex) != ENOTRECOVERABLE) { EPRINTF("FAIL:The mutex should remain as EOWNERDEAD " "if call pthread_mutex_consistent_np fails, " "so the mutex will transit to ENOTRECOVERABLE " "when unlocked in Sun compatibility mode"); pthread_mutex_unlock(&mutex); exit(FAIL); } else { DPRINTF(stdout,"PASS: The mutex transitted to ENOTRECOVERABLE " "state when pthread_mutex_consistent_np fails " "in Sun compatibility mode (why fails?)\\n"); pthread_mutex_unlock(&mutex); } } pthread_exit(0); return 0; } int main() { pthread_mutexattr_t attr; pthread_t threads[2]; pthread_attr_t threadattr; int rc; rc = pthread_mutexattr_init(&attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_SUN_NP); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_setrobust_np %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutex_init(&mutex, &attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutex_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_attr_init(&threadattr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_attr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_create(&threads[0], &threadattr, thread_1, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[0], 0); DPRINTF(stdout,"Thread 1 exited without unlock...\\n"); rc = pthread_create(&threads[1], &threadattr, thread_2, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[1], 0); DPRINTF(stdout,"Thread 2 exited ...\\n"); DPRINTF(stdout,"PASS: Test PASSED\\n"); return PASS; }
1
#include <pthread.h> pthread_mutex_t forks[3]; pthread_mutex_t fork1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork3 = PTHREAD_MUTEX_INITIALIZER; static void *philosopher(void *seat) { printf("seat: %d\\n", seat); int f_left = seat; int f_right = seat+1; if (f_right == 3) f_right = 0; if (seat == 0) { pthread_mutex_lock(&forks[f_left]); printf("P%d picked up left fork\\n", seat); pthread_mutex_lock(&forks[f_right]); printf("P%d picked up right fork\\n", seat); printf("P%d eating...\\n", seat); usleep(10000); printf("P%d returning left fork\\n", seat); pthread_mutex_unlock(&forks[f_left]); printf("P%d returning right fork\\n", seat); pthread_mutex_unlock(&forks[f_right]); } else { pthread_mutex_lock(&forks[f_right]); printf("P%d picked up right fork\\n", seat); pthread_mutex_lock(&forks[f_left]); printf("P%d picked up left fork\\n", seat); printf("P%d eating...\\n", seat); usleep(10000); printf("P%d returning right fork\\n", seat); pthread_mutex_unlock(&forks[f_right]); printf("P%d returning left fork\\n", seat); pthread_mutex_unlock(&forks[f_left]); } return 0; } int main() { forks[0] = fork1; forks[1] = fork2; forks[2] = fork3; pthread_t p0, p1, p2; while(1) { pthread_create(&p0, 0, philosopher, 0); pthread_create(&p1, 0, philosopher, 1); pthread_create(&p2, 0, philosopher, 2); pthread_join(p0, 0); pthread_join(p1, 0); pthread_join(p2, 0); } return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } char *v; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread1(void * arg) { v = malloc(sizeof(char)); return 0; } void *thread2(void *arg) { pthread_mutex_lock (&m); v[0] = 'X'; pthread_mutex_unlock (&m); return 0; } void *thread3(void *arg) { pthread_mutex_lock (&m); v[0] = 'Y'; pthread_mutex_unlock (&m); return 0; } void *thread0(void *arg) { pthread_t t1, t2, t3, t4, t5; pthread_create(&t1, 0, thread1, 0); pthread_join(t1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_create(&t4, 0, thread2, 0); pthread_create(&t5, 0, thread2, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); pthread_join(t5, 0); return 0; } int main(void) { pthread_t t; pthread_create(&t, 0, thread0, 0); pthread_join(t, 0); __VERIFIER_assert(v[0] == 'X'); return 0; }
1
#include <pthread.h> int arr[1000][1000]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void initArray() { int i = 0; int j = 0; for (i = 0; i < 1000; i++) { for (j = 0; j < 1000; j++) { srand(time(0)); arr[i][j] = rand() % 100 + 100; } } } int main() { initArray(); int globalmax = arr[0][0]; omp_set_num_threads(10); int id; int localmax; int startr; int finishr; int i; int j; { id = omp_get_thread_num(); localmax = 0; startr = id * 100; finishr = startr + 100; for (i = startr; i < finishr; i++) { for (j = 0; j < 1000; j++) { if (localmax < arr[i][j]) localmax = arr[i][j]; } } pthread_mutex_lock(&mutex); if (globalmax < localmax) globalmax = localmax; pthread_mutex_unlock(&mutex); } printf("%d", globalmax); }
0
#include <pthread.h> void *sense(void* arg); void *stateOutput(void* arg); void *userInterface(void* arg); short isRealState(char s); char state; short changed; pthread_cond_t stateCond; pthread_mutex_t stateMutex; int main(int argc, char *argv[]) { printf("Hello World!\\n"); state = 'N'; pthread_cond_init(&stateCond, 0); pthread_mutex_init(&stateMutex, 0); pthread_t sensorThread; pthread_t stateOutputThread; pthread_t userThread; pthread_create(&sensorThread, 0, sense, 0); pthread_create(&stateOutputThread, 0, stateOutput, 0); pthread_create(&userThread, 0, userInterface, 0); pause(); printf("Goodbye World!\\n"); return 0; } void *sense(void* arg) { char prevState = ' '; while (1) { char tempState; scanf("%c", &tempState); delay(10); pthread_mutex_lock(&stateMutex); if (isRealState(tempState)) state = tempState; if (prevState != state && prevState != (state ^ ' ')) { changed = 1; pthread_cond_signal(&stateCond); } prevState = state; pthread_mutex_unlock(&stateMutex); } return 0; } short isRealState(char s) { short real = 0; if (s == 'R' || s == 'r') real = 1; else if (s == 'N' || s == 'n') real = 1; else if (s == 'D' || s == 'd') real = 1; return real; } void *stateOutput(void* arg) { changed = 0; while (1) { pthread_mutex_lock(&stateMutex); while (!changed) { pthread_cond_wait(&stateCond, &stateMutex); } printf("The state has changed! It is now in "); if (state == 'n' || state == 'N') printf("Not Ready State\\n"); else if (state == 'r' || state == 'R') printf("Ready State\\n"); else if (state == 'd' || state == 'D') printf("Dance Mode\\n"); changed = 0; pthread_mutex_unlock(&stateMutex); } return 0; } void *userInterface(void* arg) { while (1) { if (state == 'n' || state == 'N') printf("___________________________________________________\\n"); else if (state == 'r' || state == 'R') printf("!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!_!\\n"); else if (state == 'd' || state == 'D') printf("/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\_/-\\\\\\n"); delay(1000); } return 0; }
1
#include <pthread.h> struct _qsd_pool { qsd_pool *next; qsd_pool *prev; }; static qsd_pool *pool_list_head = 0; static pthread_mutex_t pool_list_lock; qsd_pool *get_new_pool () { qsd_pool *new_pool; new_pool = (qsd_pool *) malloc(sizeof(qsd_pool)); new_pool->prev = 0; pthread_mutex_lock (&pool_list_lock); if (!pool_list_head) { pool_list_head = new_pool; new_pool->next = 0; } else { pool_list_head->prev = new_pool; new_pool->next = pool_list_head; pool_list_head = new_pool; } pthread_mutex_unlock (&pool_list_lock); return new_pool; } void *go1(void *x) { qsd_pool *p = get_new_pool(); } int main() { pthread_t t1,t2; pthread_mutex_init(&pool_list_lock,0); pthread_create(&t1, 0, go1, 0); pthread_create(&t1, 0, go1, 0); }
0
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; void *consumer(void *p) { struct msg *mp; for (;;){ pthread_mutex_lock(&lock); while (head == 0) pthread_cond_wait(&has_product, &lock); mp = head; head = head->next; pthread_mutex_unlock(&lock); printf("Consume %d\\n", mp->num); free(mp); sleep(rand() % 5); } } void *producer(void *p) { struct msg *mp; for (;;) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("Produce %d\\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(int argc, char *argv[]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
1
#include <pthread.h> double start_time, end_time; double read_timer(); void *findPalin(void*); int main(int argc, char *argv[]); pthread_mutex_t mutex; int chunkSize; int numWorkers; int numberOfPalinFound[10]; char wordArray[(25143)][(40)]; char line[(40)]; int len; FILE *outFile; int main(int argc, char *argv[]) { int i, j, a; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&mutex, 0); numWorkers = (argc > 1)? atoi(argv[1]) : 10; if (numWorkers > 10){ numWorkers = 10; } FILE *file = fopen("words", "r"); if (file == 0) { fprintf(stderr, "Failed to open file!\\n"); exit(1); } while (fgets(line, sizeof(line), file)) { len = strlen(line); if (line[len - 1] == '\\n'){ line[len - 1] = '\\0'; } strcpy(wordArray[i],line); i++; } fclose(file); chunkSize = ceil((25143)/numWorkers); start_time = read_timer(); outFile = fopen("out", "w"); if (outFile == 0) { fprintf(stderr, "Failed to create file\\n"); exit(1); } for (i = 0; i < numWorkers; i++) { pthread_create(&workerid[i], &attr, findPalin, (void *) i); } for(j = 0; j < numWorkers; j++){ pthread_join(workerid[j], 0); } fclose(outFile); end_time = read_timer(); int sumOfFound = 0; for (i = 0; i < numWorkers; ++i){ printf("Thread %d found: %d number of palindromes!\\n", i, numberOfPalinFound[i]); sumOfFound += numberOfPalinFound[i]; } printf("Total found: %d\\n", sumOfFound); printf("\\nThe execution time is %g sec\\n", end_time - start_time); pthread_exit(0); return 0; } void *findPalin(void *arg){ long myid = (long) arg; int i, j, a; char myWord[(40)]; char myWordReverse[(40)]; int stringLen; int counter = 0; int myStartIndex = myid * (chunkSize + 1); int myEndIndex = myStartIndex + chunkSize; if (myEndIndex > (25143)) { myEndIndex = (25143); } for (i = myStartIndex; i < myEndIndex; ++i) { strcpy(myWord, wordArray[i]); stringLen = strlen(myWord); for (a = stringLen -1, j = 0; a >= 0; a--, j++) { myWordReverse[j] = myWord[a]; } if (strcmp(myWord, myWordReverse) == 0) { counter++; numberOfPalinFound[myid] = counter; pthread_mutex_lock(&mutex); fprintf(outFile, "%s\\n", myWord); pthread_mutex_unlock(&mutex); } memset(myWordReverse, 0, sizeof myWordReverse); } } double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); }
0
#include <pthread.h> extern int keepRunning; extern pthread_mutex_t compute_pos_mux; extern pthread_mutex_t track_pos_mux; void intHandlerThread3(int sig){ keepRunning=0; printf("CTRL+C signal in track_position\\n"); } void print_position(void) { time_t rawtime; struct tm * timeinfo; char buffer [80]; time (&rawtime); timeinfo = localtime (&rawtime); strftime (buffer, 80, "%X", timeinfo); if(pos.signalDetected) printf("%s > Angle : %d - Distance : %d \\n", buffer, pos.angle, pos.distance); else printf("%s > No signal\\n", buffer); } void * track_position(void * arg){ struct timeval old_tv = {0}; struct timeval tv = {0}; long unsigned int elapsed_time = 0; char message [512]; int tps = 1; int wait =1; struct sigaction act; memset(&act,0,sizeof(act)); act.sa_handler = intHandlerThread3; sigaction(SIGINT, &act, 0); gettimeofday(&old_tv, 0); if (init_socket() != 0) { printf("[FAILED] Socket initialization failed\\n"); } else { sleep(1); printf("Drone starts flying...\\n"); set_trim(message, wait); printf("Taking off...\\n"); while(tps < 167) { take_off(message, wait); tps++; } wait = 0; printf("Going up...\\n"); gettimeofday(&old_tv, 0); elapsed_time = 0; while(elapsed_time < 2) { set_simple_move(message, UP, 1, wait); gettimeofday(&tv, 0); elapsed_time = (tv.tv_sec-old_tv.tv_sec); } set_simple_move(message, UP, 0.0, wait); elapsed_time = 35000; while(keepRunning){ while (elapsed_time < 35000) { gettimeofday(&tv, 0); elapsed_time = (tv.tv_sec-old_tv.tv_sec)*1000000 + (tv.tv_usec-old_tv.tv_usec); } pthread_mutex_lock(&track_pos_mux); print_position(); reset_com(message, wait); if(!pos.signalDetected) { set_simple_move(message, FRONT, 0, wait); } else { if(pos.angle >= -ANGLE_PRECISION/2 && pos.angle <= ANGLE_PRECISION/2) { set_simple_move(message, FRONT, 0.05, wait); } else if (pos.angle > ANGLE_PRECISION/2) set_simple_move(message, CLKWISE, 0.5, wait); else set_simple_move(message, ANTI_CLKWISE, 0.5,wait); } pthread_mutex_unlock(&compute_pos_mux); gettimeofday(&old_tv, 0); elapsed_time=0; } landing(message, wait); sleep(1); } pthread_exit(0); }
1
#include <pthread.h> static bool wait; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void* thread_timedwait (void* arg) { (void)arg; pthread_mutex_lock(&mutex); wait = 1; struct timespec ts; spec_gettimeout(&ts, 500); do { if (ETIMEDOUT == pthread_cond_timedwait(&cond, &mutex, &ts)) { if (!wait) { printf("signal\\n"); } wait = 0; printf("ETIMEDOUT\\n"); } } while (wait); pthread_mutex_unlock(&mutex); pthread_exit(0); return 0; } int main(int argc, char *argv[]) { (void)argc; (void)argv; pthread_t tid; pthread_create(&tid, 0, thread_timedwait, 0); usleep(50 * 1000); pthread_mutex_lock(&mutex); usleep(800 * 1000); wait = 0; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); pthread_join(tid, 0); return 0; }
0
#include <pthread.h> void process_reader(FILE *trace_file) { int trace_line = 1; char my_line[128]; float arrival_time; time_current(); while(fgets(my_line, 128, trace_file) != 0) { pthread_mutex_lock(&mutex_ptable); if (p_table.first_free >= p_table.size) realloc_table(2); pthread_mutex_unlock(&mutex_ptable); arrival_time = get_t0(my_line); while(time_current() < arrival_time) { my_sleep(0.1); } pthread_mutex_lock(&mutex_ptable); line_to_process(&(p_table.table[p_table.first_free]), my_line); if (d) { fprintf(stderr, "DEBUG: The process '%s' from trace line %d arrived in the system\\n", p_table.table[p_table.first_free].trace_name, trace_line++); } p_table.first_free++; pthread_mutex_unlock(&mutex_ptable); } }
1
#include <pthread.h> int result[8]={0, 0, 0, 0, 0, 0, 0, 0}; pthread_mutex_t my_mutex; int share=100; int thread_args[8]={0, 1, 2, 3, 4, 5, 6, 7}; void *TaskCode(void *argument) { int tid; tid = *((int *) argument); result[tid] = tid; pthread_mutex_lock( &my_mutex ); printf("Exec thread = %d\\n", tid); share=share - tid; pthread_mutex_unlock( &my_mutex ); pthread_exit( 0 ); return (0); } int main (int argc, char *argv[]) { pthread_t threads[7]; pthread_attr_t attr; int rc, i; int tmp; tmp = pthread_mutex_init( &my_mutex, 0 ); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); printf("On commence à creer les threads \\n"); for (i=0; i < 7; i++) { thread_args[i] = i; pthread_mutex_lock( &my_mutex ); printf("creer thread no %d \\n", i); pthread_mutex_unlock( &my_mutex ); rc = pthread_create(&threads[i], 0, TaskCode, (void *) &thread_args[i]); assert(0 == rc); } pthread_mutex_lock( &my_mutex ); printf("Attente la fin des threads \\n"); pthread_mutex_unlock( &my_mutex ); for (i=0; i< 7; i++) { rc = pthread_join(threads[i], 0); assert(0 == rc); } pthread_attr_destroy(&attr); for (i=0; i< 7; i++) { printf("resultat = %d \\n", result[i]); } printf("share=%d \\n", share); exit(0); }
0
#include <pthread.h> void mylib_init_barrier(struct barrier_node *b) { b -> count = 0; pthread_mutex_init(&(b -> count_lock), 0); pthread_cond_init(&(b -> ok_to_proceed), 0); } void mylib_barrier(struct barrier_node *b, int num_threads) { pthread_mutex_lock(&(b -> count_lock)); b -> count ++; if (b -> count == num_threads) { b -> count = 0; int *sortedNByPSquareElements = (int*)malloc(sizeof(int)*num_threads*num_threads); int i = 0 , totalElement= 0, k=0; int pivotIndexFactor = num_threads/2 - 1; int pivotIndex = 0; for(;i<num_threads;i++) { k=0; for(;k < customArray[i].elementCount; k++) { sortedNByPSquareElements[totalElement++] = customArray[i].beginPtr[k]; } } qsort(sortedNByPSquareElements,totalElement,sizeof(int),compare_int_keys); pivotsArray = (int*)malloc(sizeof(int) * (num_threads - 1)); for(i = 1;i < num_threads;i++) { pivotIndex = i*num_threads + pivotIndexFactor; if(pivotIndex >= totalElement) { break; } if(!pivotsCount ||( pivotsArray[pivotsCount - 1] != sortedNByPSquareElements[pivotIndex])) { pivotsArray[pivotsCount++] = sortedNByPSquareElements[pivotIndex]; } } pthread_cond_broadcast(&(b -> ok_to_proceed)); } else{ while (pthread_cond_wait(&(b -> ok_to_proceed), &(b -> count_lock)) != 0); } pthread_mutex_unlock(&(b -> count_lock)); } void mylib_barrier_second(struct barrier_node *b, int num_threads) { pthread_mutex_lock(&(b -> count_lock)); b -> count ++; if (b -> count == num_threads) { b -> count = 0; pthread_cond_broadcast(&(b -> ok_to_proceed)); } else while (pthread_cond_wait(&(b -> ok_to_proceed), &(b -> count_lock)) != 0); pthread_mutex_unlock(&(b -> count_lock)); } void computePrefixSum(int num_threads, int thread_id) { int i = 0; int neighbourNode = 0; for(; i < logThreadNum; i++) { neighbourNode = thread_id ^ (1<<i); if((neighbourNode < num_threads) && (neighbourNode > thread_id)) { prefixSumPacketInfoList[neighbourNode].prefixSumPacket += prefixSumPacketInfoList[thread_id].prefixSumPacket; prefixSumPacketInfoList[neighbourNode].prefixSum += prefixSumPacketInfoList[thread_id].prefixSumPacket; prefixSumPacketInfoList[thread_id].prefixSumPacket = prefixSumPacketInfoList[neighbourNode].prefixSumPacket; } mylib_barrier_second(barrierAttrSecond,num_threads); } }
1
#include <pthread.h> extern void do_work (); int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void initialize_flag () { pthread_mutex_init (&thread_flag_mutex, 0); pthread_cond_init (&thread_flag_cv, 0); thread_flag = 0; } void* thread_function (void* thread_arg) { while (1) { pthread_mutex_lock (&thread_flag_mutex); while (!thread_flag) pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); pthread_mutex_unlock (&thread_flag_mutex); do_work (); } return 0; } void set_thread_flag (int flag_value) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_cond_signal (&thread_flag_cv); pthread_mutex_unlock (&thread_flag_mutex); }
0
#include <pthread.h> int M, N, posInicial, posfinal; int *vetorPrefixos; pthread_mutex_t mutex; void *somaPrefixos(void *threadid) { int i; for (i = posInicial; i < posfinal; ++i) { pthread_mutex_lock(&mutex); vetorPrefixos[i] = vetorPrefixos[i - 1] + vetorPrefixos[i]; pthread_mutex_unlock(&mutex); } } void popularVetor(int n) { int i; for (i = 0; i < n; ++i) { vetorPrefixos[i] = i + 1; } } void imprimirVetor() { int i; for (i = 0; i < N; ++i) { if(i == N-1) printf("%d", vetorPrefixos[i]); else printf("%d, ", vetorPrefixos[i]); } } int main(int argc, char *argv[]){ printf("Digite o numero de threads M: ");scanf("%d", &M); printf("\\nDigite o numero de elementos N: ");scanf("%d", &N); pthread_t tid[M]; int t, *id; double start, finish, elapsed; pthread_mutex_init(&mutex, 0); GET_TIME(start); vetorPrefixos = malloc(N * sizeof(int)); popularVetor(N); printf("\\nVetor antes da soma: "); imprimirVetor(); for(t = 0; t < M; t++){ if ((id = malloc(sizeof(int))) == 0) { pthread_exit(0); return 1; } *id=t; posInicial = t*(N/M); posfinal = (t+1)*(N/M); if(posfinal >= M) posfinal = posfinal - 1; printf("--Posição inicial da thread %d\\n", posInicial); printf("--Posição final da thread %d\\n", posfinal); printf("--Cria a thread %d\\n", t); if (pthread_create(&tid[t], 0, somaPrefixos, (void *)id)) { printf("--ERRO: pthread_create()\\n"); exit(-1); } } for (t = 0; t < M; t++) { if (pthread_join(tid[t], 0)) { printf("--ERRO: pthread_join() \\n"); exit(-1); } } printf("\\nVetor depois da soma: "); imprimirVetor(); GET_TIME(finish); elapsed = finish - start; printf("TEMPO GASTO: %lf segundos\\n", elapsed); pthread_exit(0); }
1
#include <pthread.h> struct udt_pipe_struct { struct udt_pipe_struct *up, *down; int sock_udt, sock_sys; pthread_t thread_up, thread_down; int running_count; pthread_mutex_t running_mutex; }; static void *thread_udtpipe (void *arg) { struct udt_pipe_struct *udt_pipe = *(struct udt_pipe_struct **)arg; int isup; unsigned char buff[2000]; assert(&udt_pipe->up == (struct udt_pipe_struct **)arg || &udt_pipe->down == (struct udt_pipe_struct **)arg); isup = &udt_pipe->up == (struct udt_pipe_struct **)arg; printf("thread_udtpipe start, isup=%d\\n", isup); while (1) { int sent = 0; ssize_t len = isup ? recv(udt_pipe->sock_sys, buff, sizeof(buff), 0) : udt_recv(udt_pipe->sock_udt, (char *)buff, sizeof(buff), 0); if (len <= 0) { if (isup) perror("thread_udtpipe() recv failed"); else printf("thread_udtpipe() recv failed udt_lasterror=%d\\n", udt_getlasterror()); break; } while (sent < len) { int len1 = isup ? udt_send(udt_pipe->sock_udt, (char *)buff+sent, len-sent, 0) : send(udt_pipe->sock_sys, buff+sent, len-sent, 0); if (len1 <= 0) { if (isup) printf("thread_udtpipe() send failed udt_lasterror=%d\\n", udt_getlasterror()); else perror("thread_udtpipe() send failed"); break; } sent += len1; } if (sent < len) break; } printf("thread_udtpipe end, isup=%d\\n", isup); pthread_mutex_lock(&udt_pipe->running_mutex); if (udt_pipe->running_count == 2) { close(udt_pipe->sock_sys); udt_close(udt_pipe->sock_udt); udt_pipe->running_count --; pthread_mutex_unlock(&udt_pipe->running_mutex); } else { pthread_mutex_unlock(&udt_pipe->running_mutex); free(udt_pipe); } return 0; } int punch_udt (const struct punch_local_param *local, const struct punch_param *peer) { int sock = -1, spair[2]; struct sockaddr_in addr; struct udt_pipe_struct *udt_pipe; sock = udt_socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); assert(sock >= 0); assert(udt_setsockopt_rendezvous(sock, 1) == 0); memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(local->udt.localport); if (udt_bind(sock, (const struct sockaddr *)&addr, sizeof(addr))) { printf("bind to port %d failed\\n", local->udt.localport); goto errout; } printf("try to udt_connect()\\n"); if (udt_connect(sock, (const struct sockaddr *)&peer->udt.addr, sizeof(struct sockaddr_in)) != 0) { printf("failed to udt_connect\\n"); goto errout; } printf("succeed udt_connect()\\n"); assert(socketpair(AF_UNIX, SOCK_STREAM, 0, spair) == 0); udt_pipe = (struct udt_pipe_struct *)malloc(sizeof(struct udt_pipe_struct)); udt_pipe->up = udt_pipe->down = udt_pipe; udt_pipe->sock_sys = spair[0]; udt_pipe->sock_udt = sock; udt_pipe->running_count = 2; pthread_mutex_init(&udt_pipe->running_mutex, 0); assert(pthread_create(&udt_pipe->thread_up, 0, thread_udtpipe, &udt_pipe->up) == 0); assert(pthread_create(&udt_pipe->thread_down, 0, thread_udtpipe, &udt_pipe->down) == 0); return spair[1]; errout: udt_close(sock); return -1; } int punch_udt_param_init (struct punch_local_param *local, struct punch_param *peer, int haslocal) { if (!haslocal) memset(local, 0, sizeof(struct punch_local_param)); memset(peer, 0, sizeof(struct punch_param)); local->type = peer->type = PT_UDT; return do_stun(0, haslocal ? 0 : 1, &local->udt.localport, &peer->udt.addr); }
0
#include <pthread.h> int out_max,in_max; int prod_number=0; int cons_number=0; pthread_mutex_t mu= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t sig_consumer= PTHREAD_COND_INITIALIZER; pthread_cond_t sig_producer= PTHREAD_COND_INITIALIZER; void cpu_eat(int count){ unsigned long loop; int k; loop=1; for (k=0; k<count; k++){ loop = loop+3; } } long com_counter=10; void *consumer(void *dummy) { int printed= 0; int consumes=0; " now\\"\\n", pthread_self()); while (1) { pthread_mutex_lock(&mu); cpu_eat(in_max); consumes++; if (cons_number< prod_number){ cons_number++; com_counter = com_counter - 2; } pthread_mutex_unlock(&mu); cpu_eat(in_max/2); if (cons_number == out_max) { printf("New Consumer done! :%d consumes:%d cons_number:%d cc:%d\\n",out_max,consumes,cons_number,com_counter); cpu_eat(in_max*10); break; } } } void *producer(void *dummy) { " now\\"\\n", pthread_self()); int number =0; while (1) { pthread_mutex_lock(&mu); if (cons_number == prod_number){ prod_number++; com_counter = com_counter +2; } number ++; cpu_eat(in_max); pthread_mutex_unlock(&mu); cpu_eat(in_max/2); if (prod_number == out_max) { printf("New Producer done.. :%d produced:%d prod_number:%d cc:%d\\n",out_max,number,prod_number,com_counter); cpu_eat(in_max*10); break; } } } unsigned char stack[4001]; void main(int argc, char *argv[] ) { int rc, i; pthread_t t[2]; if (argc != 3) { printf("./sem <out_loop> <in_loop> \\n"); return 1; } out_max = atoi(argv[1]); in_max = atoi(argv[2]); if (in_max ==0){ in_max = 200000; } clone((void *) &consumer, &stack[4000], 9000, 0, 0); producer(0); printf("Done..\\n"); }
1
#include <pthread.h> pthread_t gl_thread; volatile int die = 0; int g_argc; char **g_argv; int window; pthread_mutex_t gl_backbuf_mutex = PTHREAD_MUTEX_INITIALIZER; uint8_t gl_depth_front[640*480*4]; uint8_t gl_depth_back[640*480*4]; uint8_t gl_rgb_front[640*480*4]; uint8_t gl_rgb_back[640*480*4]; int gl_depth_tex; int gl_rgb_tex; pthread_cond_t gl_frame_cond = PTHREAD_COND_INITIALIZER; int got_frames = 0; void DrawGLScene() { static int fcnt = 0; pthread_mutex_lock(&gl_backbuf_mutex); while (got_frames < 2) { pthread_cond_wait(&gl_frame_cond, &gl_backbuf_mutex); } memcpy(gl_depth_front, gl_depth_back, sizeof(gl_depth_back)); memcpy(gl_rgb_front, gl_rgb_back, sizeof(gl_rgb_back)); got_frames = 0; pthread_mutex_unlock(&gl_backbuf_mutex); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, gl_depth_tex); glTexImage2D(GL_TEXTURE_2D, 0, 3, 640, 480, 0, GL_RGB, GL_UNSIGNED_BYTE, gl_depth_front); glBegin(GL_TRIANGLE_FAN); glColor4f(255.0f, 255.0f, 255.0f, 255.0f); glTexCoord2f(0, 0); glVertex3f(0,0,0); glTexCoord2f(1, 0); glVertex3f(640,0,0); glTexCoord2f(1, 1); glVertex3f(640,480,0); glTexCoord2f(0, 1); glVertex3f(0,480,0); glEnd(); glBindTexture(GL_TEXTURE_2D, gl_rgb_tex); glTexImage2D(GL_TEXTURE_2D, 0, 3, 640, 480, 0, GL_RGB, GL_UNSIGNED_BYTE, gl_rgb_front); glBegin(GL_TRIANGLE_FAN); glColor4f(255.0f, 255.0f, 255.0f, 255.0f); glTexCoord2f(0, 0); glVertex3f(640,0,0); glTexCoord2f(1, 0); glVertex3f(1280,0,0); glTexCoord2f(1, 1); glVertex3f(1280,480,0); glTexCoord2f(0, 1); glVertex3f(640,480,0); glEnd(); glutSwapBuffers(); printf("Frame %d\\n", fcnt++); } void keyPressed(unsigned char key, int x, int y) { if (key == 27) { die = 1; glutDestroyWindow(window); pthread_exit(0); } } void ReSizeGLScene(int Width, int Height) { glViewport(0,0,Width,Height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho (0, 1280, 480, 0, -1.0f, 1.0f); glMatrixMode(GL_MODELVIEW); } void InitGL(int Width, int Height) { glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glClearDepth(1.0); glDepthFunc(GL_LESS); glDisable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glShadeModel(GL_SMOOTH); glGenTextures(1, &gl_depth_tex); glBindTexture(GL_TEXTURE_2D, gl_depth_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenTextures(1, &gl_rgb_tex); glBindTexture(GL_TEXTURE_2D, gl_rgb_tex); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); ReSizeGLScene(Width, Height); } void *gl_threadfunc(void *arg) { printf("GL thread\\n"); glutInit(&g_argc, g_argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH); glutInitWindowSize(1280, 480); glutInitWindowPosition(0, 0); window = glutCreateWindow("LibFreenect"); glutDisplayFunc(&DrawGLScene); glutIdleFunc(&DrawGLScene); glutReshapeFunc(&ReSizeGLScene); glutKeyboardFunc(&keyPressed); InitGL(1280, 480); glutMainLoop(); pthread_exit(0); return 0; } uint16_t t_gamma[2048]; void depthimg(uint16_t *buf, int width, int height) { int i; pthread_mutex_lock(&gl_backbuf_mutex); for (i=0; i<640*480; i++) { int pval = t_gamma[buf[i]]; int lb = pval & 0xff; switch (pval>>8) { case 0: gl_depth_back[3*i+0] = 255; gl_depth_back[3*i+1] = 255-lb; gl_depth_back[3*i+2] = 255-lb; break; case 1: gl_depth_back[3*i+0] = 255; gl_depth_back[3*i+1] = lb; gl_depth_back[3*i+2] = 0; break; case 2: gl_depth_back[3*i+0] = 255-lb; gl_depth_back[3*i+1] = 255; gl_depth_back[3*i+2] = 0; break; case 3: gl_depth_back[3*i+0] = 0; gl_depth_back[3*i+1] = 255; gl_depth_back[3*i+2] = lb; break; case 4: gl_depth_back[3*i+0] = 0; gl_depth_back[3*i+1] = 255-lb; gl_depth_back[3*i+2] = 255; break; case 5: gl_depth_back[3*i+0] = 0; gl_depth_back[3*i+1] = 0; gl_depth_back[3*i+2] = 255-lb; break; default: gl_depth_back[3*i+0] = 0; gl_depth_back[3*i+1] = 0; gl_depth_back[3*i+2] = 0; break; } } got_frames++; pthread_cond_signal(&gl_frame_cond); pthread_mutex_unlock(&gl_backbuf_mutex); } void rgbimg(uint8_t *buf, int width, int height) { int i; pthread_mutex_lock(&gl_backbuf_mutex); memcpy(gl_rgb_back, buf, width*height*3); got_frames++; pthread_cond_signal(&gl_frame_cond); pthread_mutex_unlock(&gl_backbuf_mutex); } int main(int argc, char **argv) { int res; libusb_device_handle *dev; printf("Kinect camera test\\n"); int i; for (i=0; i<2048; i++) { float v = i/2048.0; v = powf(v, 3)* 6; t_gamma[i] = v*6*256; } g_argc = argc; g_argv = argv; libusb_init(0); dev = libusb_open_device_with_vid_pid(0, 0x45e, 0x2ae); if (!dev) { printf("Could not open device\\n"); return 1; } res = pthread_create(&gl_thread, 0, gl_threadfunc, 0); if (res) { printf("pthread_create failed\\n"); return 1; } cams_init(dev, depthimg, rgbimg); while(!die && libusb_handle_events(0) == 0); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t condc, condp; int buffer = 0; void* produtor(void *ptr) { int i; for (i = 1; i <= 100000000; i++) { pthread_mutex_lock(&mutex); while (buffer != 0) { printf("PRODUTOR: Buffer CHEIO. Indo dormir\\n"); pthread_cond_wait(&condp, &mutex); } printf("PRODUTOR: Acordado! Produzindo...\\n"); buffer = i; pthread_cond_signal(&condc); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void* consumidor(void *ptr) { int i; for (i = 1; i <= 100000000; i++) { pthread_mutex_lock(&mutex); while (buffer == 0){ printf("CONSUMIDOR: Buffer VAZIO. Indo dormir\\n"); pthread_cond_wait(&condc, &mutex); } printf("CONSUMIDOR: Acordado! Consumindo...\\n"); buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumidor, 0); pthread_create(&pro, 0, produtor, 0); pthread_join(con, 0); pthread_join(pro, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
1
#include <pthread.h> struct random_src { pthread_mutex_t lock; unsigned int rand_state; }; struct random_src *random_src_alloc(struct htrace_log *lg) { struct random_src *rnd; int ret; rnd = calloc(1, sizeof(*rnd)); if (!rnd) { htrace_log(lg, "random_src_alloc: OOM\\n"); return 0; } ret = pthread_mutex_init(&rnd->lock, 0); if (ret) { htrace_log(lg, "random_src_alloc: pthread_mutex_create " "failed: error %d (%s)\\n", ret, terror(ret)); free(rnd); return 0; } return rnd; } void random_src_free(struct random_src *rnd) { if (!rnd) { return; } pthread_mutex_destroy(&rnd->lock); free(rnd); } uint32_t random_u32(struct random_src *rnd) { uint32_t val = 0; pthread_mutex_lock(&rnd->lock); val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; pthread_mutex_unlock(&rnd->lock); return val; } uint64_t random_u64(struct random_src *rnd) { uint64_t val = 0; pthread_mutex_lock(&rnd->lock); val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; val ^= rand_r(&rnd->rand_state); val <<= 15; pthread_mutex_unlock(&rnd->lock); return val; }
0
#include <pthread.h> struct args { pthread_cond_t cond_var; pthread_mutex_t cond_lock; }; void * lazy_thread(void *arg ) { printf("thread!\\n"); struct args *t_args = (struct args *)arg; pthread_mutex_lock(&(t_args->cond_lock)); pthread_cond_wait(&(t_args->cond_var), &(t_args->cond_lock)); pthread_mutex_unlock(&(t_args->cond_lock)); return 0; } void * naughty_thread(void *arg ) { while(1) { printf("thread ...\\n"); } return 0; } int main(int argc, char **argv) { pthread_t thread_arr[128] = {0}; struct args t_args = {0}; pthread_mutex_init(&(t_args.cond_lock), 0); pthread_cond_init(&(t_args.cond_var), 0); pthread_create(&(thread_arr[0]), 0, naughty_thread, 0); for (size_t i = 1; i < 128; i++) { pthread_create(&(thread_arr[i]), 0, lazy_thread, &t_args); } pthread_join(thread_arr[1], 0); }
1
#include <pthread.h> pthread_t tid[8]; pthread_mutex_t mutex; int *array; int length = 1000000000; int count = 0; int double_count = 0; int t = 8; int max_threads = 0; void *count3s_thread(void *arg) { int i; int length_per_thread = length / max_threads; int id = (int) arg; int start = id * length_per_thread; printf("\\tThread [%d] starts [%d] length [%d]\\n", id, start, length_per_thread); pthread_mutex_lock(&mutex); for (i = start; i < start + length_per_thread; i++) { if (array[i] == 3) { count++; } } pthread_mutex_unlock(&mutex); } void initialize_vector() { int i = 0; array = (int*) malloc(sizeof (int) * 1000000000); if (array == 0) { printf("Allocation memory failed!\\n"); exit(-1); } for (; i < 1000000000; i++) { array[i] = rand() % 20; if (array[i] == 3) double_count++; } } int main(int argc, char* argv[]) { int i = 0; int err; clock_t t1, t2; clock_t clocks[8]; if (argc == 2) { max_threads = atoi(argv[1]); if (max_threads > 8) max_threads = 8; } else { max_threads = 8; } printf("[3s-03] Using %d threads\\n", max_threads); srand(time(0)); printf("*** 3s-03 ***\\n"); printf("Initializing vector... "); fflush(stdout); initialize_vector(); printf("Vector initialized!\\n"); fflush(stdout); t1 = clock(); pthread_mutex_init(&mutex, 0); while (i < max_threads) { err = pthread_create(&tid[i], 0, &count3s_thread, (void*) i); if (err != 0) printf("[3s-03] Can't create a thread: [%d]\\n", i); else printf("[3s-03] Thread created!\\n"); i++; } i = 0; for (; i < max_threads; i++) { void *status; int rc; rc = pthread_join(tid[i], &status); if (rc) { printf("ERROR; retrun code from pthread_join() is %d\\n", rc); exit(-1); } else { clocks[i] = clock(); printf("Thread [%d] exited with status [%ld], time [%f]\\n", i, (long) status, (((float) clocks[i] - (float) t1) / 1000000.0F) * 1000); } } t2 = clock(); printf("[3s-03] Count by threads %d\\n", count); printf("[3s-03] Double check %d\\n", double_count); pthread_mutex_destroy(&mutex); printf("[[3s-03] Elapsed time %f\\n", (((float) t2 - (float) t1) / 1000000.0F) * 1000); pthread_exit(0); return 0; }
0
#include <pthread.h> int _mosquitto_handle_connack(struct mosquitto *mosq) { uint8_t byte; uint8_t result; int rc; assert(mosq); _mosquitto_log_printf(mosq, MOSQ_LOG_DEBUG, "Client %s received CONNACK", mosq->id); rc = _mosquitto_read_byte(&mosq->in_packet, &byte); if(rc) return rc; rc = _mosquitto_read_byte(&mosq->in_packet, &result); if(rc) return rc; pthread_mutex_lock(&mosq->callback_mutex); if(mosq->on_connect){ mosq->in_callback = 1; mosq->on_connect(mosq, mosq->userdata, result); mosq->in_callback = 0; } pthread_mutex_unlock(&mosq->callback_mutex); switch(result){ case 0: mosq->state = mosq_cs_connected; return MOSQ_ERR_SUCCESS; case 1: case 2: case 3: case 4: case 5: return MOSQ_ERR_CONN_REFUSED; default: return MOSQ_ERR_PROTOCOL; } }
1
#include <pthread.h> int *nVal; int nSize; int *dVal; int dSize; float result=1; float numer=1; float denom=1; void *nFunc(void *arg); void *dFunc(void *arg); int count; pthread_mutex_t lock; sem_t bar; }Barrier; Barrier b; int main(int argc, char *argv[]){ if(argc != 3){ printf("Usage %s: <n> <k>\\n",argv[0]); return -1; } pthread_t numerator,denominator; int n; int i; int k; int diff; int val; n = atoi(argv[1]); k = atoi(argv[2]); if(k > n){ printf("Error: n should be >= k\\n"); return -1; } if(n == 0 || k == 0){ printf("Result = 1\\n"); return -1; } diff = n-k; nSize = n-diff; dSize = k; nVal = (int *)malloc((n - diff) * sizeof(int)); dVal = (int *)malloc(k * sizeof(int)); val = n; for(i=0; i < (n-diff); i++){ nVal[i] = val; val--; } val = k; for(i=0; i < k; i++){ dVal[i] = val; val--; } b.count = 0; sem_init(&b.bar, 0 ,0); pthread_mutex_init(&b.lock, 0); pthread_create(&numerator, 0, nFunc, 0); pthread_create(&denominator, 0, dFunc, 0); pthread_join(numerator, 0); pthread_join(denominator, 0); printf("Result = %.2f\\n", result); return 0; } void *nFunc(void *arg){ int i =0; int first; int second; int last = 0; while(1){ first = nVal[i]; i++; if(i >= nSize){ second = 1; last = 1; } else{ second = nVal[i]; i++; if(i >= nSize) last = 1; } numer *= first; numer *= second; pthread_mutex_lock(&b.lock); b.count++; if(b.count == 2){ result *= (numer/denom); numer = 1; denom = 1; b.count = 0; sem_post(&b.bar); sem_post(&b.bar); } pthread_mutex_unlock(&b.lock); if(last == 1) break; sem_wait(&b.bar); } pthread_exit(0); } void *dFunc(void *arg){ int i =0; int first; int second; int last = 0; while(1){ first = dVal[i]; i++; if(i >= dSize){ second = 1; last = 1; } else{ second = dVal[i]; i++; if(i >= dSize) last = 1; } denom *= first; denom *= second; pthread_mutex_lock(&b.lock); b.count++; if(b.count == 2){ result *= (numer/denom); numer = 1; denom = 1; b.count = 0; sem_post(&b.bar); sem_post(&b.bar); } pthread_mutex_unlock(&b.lock); if(last == 1) break; sem_wait(&b.bar); } pthread_exit(0); }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if((fp = (struct foo *)malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)id) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->f_next) { if(fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id) % 29); tfp = fh[idx]; if(tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> void *thread1(void *); void *thread2(void *); pthread_cond_t cond; pthread_mutex_t mutex; int i; int main(void) { pthread_t t1,t2; pthread_cond_init(&cond,0); pthread_mutex_init(&mutex,0); pthread_create(&t1,0,thread1,0); pthread_create(&t2,0,thread2,0); pthread_join(t1,0); pthread_join(t2,0); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex); exit(0); } void *thread1(void *arg) { for(i=1;i<6;i++) { pthread_mutex_lock(&mutex); printf("xiyoulinux\\n"); if(i==3) { pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); sleep(1); } } void *thread2(void *arg) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("motian\\n"); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> char buffer[256],employ[100],str[100],pass[30]; struct sockaddr_in serv_addr, cli_addr; int n,nu=1,i; FILE *fp; struct userinfo { char username[100]; int socket; }u[1000]; pthread_t thread; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void error(char *msg) { perror(msg); exit(0); } void* server(void*); int main (int argc, char *argv[]) { int i,sockfd, newsockfd[1000], portno, clilen,no=0,n; try: fp=fopen("employ.txt","w"); printf("server started\\n"); fclose(fp); if (argc<2) { fprintf (stderr,"ERROR! Provide A Port!\\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd<0) error("ERROR! Cannnot Open Socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))<0) error("ERROR! On Binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); while(1) { newsockfd[no] = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd<0) error("ERROR! On Accepting"); pthread_mutex_lock(&mutex); pthread_create(&thread,0,server,(void*)&newsockfd[no]); no+=1; } close(newsockfd[no]); close(sockfd); goto try; return 0; } void* server(void* sock) { char to[100],from[100],name[100]; int newsockfd=*((int*)sock),j=0,m; fp=fopen("employ.txt","r+"); checking: m=1; bzero(employ,100); bzero(to,100); bzero(from,100); bzero(str,100); recv(newsockfd, employ,100,0); recv(newsockfd, pass,30,0); while(fscanf(fp,"%s",str)!=EOF) { n=strncmp(employ,str,strlen(str)); if(n==0) { fscanf(fp,"%s",str); n=strncmp(pass,str,strlen(str)); if(n==0) { m=2; break; } else { send(newsockfd,"USERNAME EXISTS",15,0); m=0; break;} fscanf(fp,"%s",str); } } if(m==0) goto checking; if(m==1) { fclose(fp); send(newsockfd,"server accepted your credentials",15,0); printf("Entered as client:"); printf("%s ",employ); bzero(u[nu].username,100); u[nu].socket=newsockfd; strncpy(u[nu].username,employ,strlen(employ)); nu++; } if(m==2) { fclose(fp); send(newsockfd,"USER LOGGED IN",14,0); for(i=1;i<nu;i++) if(strcmp(employ,u[i].username)==0) break; u[i].socket=newsockfd; } pthread_mutex_unlock(&mutex); bzero(buffer, 256); int newsockfd1; while(1) { n = recv(newsockfd, buffer, 255, 0); if(n<0) error("ERROR! Reading From Socket"); if(strncmp(buffer,"bye",3)==0) { close(newsockfd); pthread_exit(0); } i=3; strcpy(name,buffer); while(name[i]!=':') { to[i-3]=name[i]; i++; } to[i-3]='\\0'; j=0; bzero(buffer,256); while(name[i]!='|') { buffer[j]=name[i]; i++; j++; } buffer[j]='\\0'; j=0; for(i+=1;name[i]!='\\0';i++) { from[j]=name[i]; j++; } from[j-1]='\\0'; printf("To %s From %s Message %s",to,from,buffer); for(j=1;j<nu;j++) { if((strncmp(u[j].username,to,strlen(to)))==0) { newsockfd1=u[j].socket; break; } } strcat(from,buffer); bzero(buffer,256); strcpy(buffer,"From "); strcat(buffer,from); n=send(newsockfd1,buffer,sizeof buffer,0); if(n<0) { send(newsockfd, "SENDING FAILED : employ LOGGED OUT",32,0); } else { n = send(newsockfd, "Message sent", 18, 0); if (n<0) error("ERROR! Writing To Socket");} } close(newsockfd); pthread_exit(0); }
1
#include <pthread.h> char buffer[100]; int indice; pthread_mutex_t mutex; sem_t sem_espacios_vacios; sem_t sem_espacios_ocupados; void agregar(char c); void quitar(); void * productor() { while(1) { char c = 'a' + rand()%24; agregar(c); sleep(1); } } void * consumidor() { while(1) { quitar(); sleep(1); } } void * imprimir() { while(1){ int i; printf("%d",indice); printf("\\n"); sleep(1); } } int main() { pthread_t thread_consumidor; pthread_t thread_productor1; pthread_t thread_productor2; indice = 0; pthread_mutex_init(&mutex, 0); sem_init(&sem_espacios_vacios,0,100); sem_init(&sem_espacios_ocupados,0,0); pthread_create(&thread_consumidor, 0, consumidor, 0 ); pthread_create(&thread_productor1, 0, productor, 0 ); pthread_create(&thread_productor2, 0, productor, 0 ); pthread_join(thread_consumidor, 0); return 0; } void agregar(char c) { sem_wait(&sem_espacios_vacios); pthread_mutex_lock(&mutex); buffer[indice] = c; indice++; printf("%d\\n",indice); sem_post(&sem_espacios_ocupados); pthread_mutex_unlock(&mutex); } void quitar() { sem_wait(&sem_espacios_ocupados); pthread_mutex_lock(&mutex); indice--; printf("%d\\n",indice); sem_post(&sem_espacios_vacios); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> int bfr_net_listener_init() { return 0; } void bfr_net_listener_close() { } void * bfr_net_listener_service(void * arg) { prctl(PR_SET_NAME, "bfr_net", 0, 0, 0); struct listener_args * net_args = arg; log_print(g_log, "bfr_net_listener_service: listening..."); struct bfr_msg * msg; int rcvd; struct net_buffer buf; net_buffer_init(BFR_MAX_PACKET_SIZE, &buf); while (1) { net_buffer_reset(&buf); rcvd = recvfrom(g_sockfd, buf.buf, buf.size, 0, 0, 0); struct ether_header eh; net_buffer_copyFrom(&buf, &eh, sizeof(eh)); log_debug(g_log, "bfr_net_listener_service: rcvd %d bytes from %02x:%02x:%02x:%02x:%02x:%02x", rcvd, eh.ether_shost[0], eh.ether_shost[1], eh.ether_shost[2], eh.ether_shost[3], eh.ether_shost[4], eh.ether_shost[5]); if (rcvd <= 0) { log_error(g_log, "bfr_net_listener_service: recv failed -- trying to stay alive!"); sleep(1); continue; } msg = (struct bfr_msg *) malloc(sizeof(struct bfr_msg)); msg->hdr.type = net_buffer_getByte(&buf); msg->hdr.nodeId = net_buffer_getInt(&buf); msg->hdr.payload_size = net_buffer_getInt(&buf); msg->payload.data = malloc(msg->hdr.payload_size); net_buffer_copyFrom(&buf, msg->payload.data, msg->hdr.payload_size); synch_enqueue(net_args->queue, (void * ) msg); pthread_mutex_lock(net_args->lock); pthread_cond_signal(net_args->cond); pthread_mutex_unlock(net_args->lock); } pthread_exit(0); }
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, "cant' 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> const int primes[] = { 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, }; char **sa; int sasize; int sacnt; struct timespec sts; struct timespec ets; pthread_barrier_t barrier; pthread_mutex_t lock; volatile sig_atomic_t stop; double nlookups; double ideal; static void makelist(void) { char buf[MAXPATHLEN], *p; size_t l; FILE *fp; fp = popen("/usr/bin/locate x", "r"); if (fp == 0) { perror("popen"); exit(1); } while (fgets(buf, sizeof(buf), fp) != 0) { l = strlen(buf) + 1; p = malloc(l); if (p == 0) { perror("malloc"); exit(1); } strcpy(p, buf); p[l - 2] = '\\0'; if (sacnt == sasize) { sasize += 256; sa = realloc(sa, sizeof(*sa) * sasize); if (sa == 0) { perror("realloc"); exit(1); } } sa[sacnt++] = p; if (sacnt == 4096) { break; } } fclose(fp); } static void lookups(int idx) { unsigned int p, c; for (c = 0, p = 0; !stop; c++) { p += primes[idx]; if (p >= sacnt) { p %= sacnt; } (void)access(sa[p], F_OK); } pthread_mutex_lock(&lock); nlookups += c; pthread_mutex_unlock(&lock); } static void start(void) { (void)pthread_barrier_wait(&barrier); if (clock_gettime(CLOCK_MONOTONIC, &sts)) { perror("clock_gettime"); exit(1); } } static void end(void) { if (clock_gettime(CLOCK_MONOTONIC, &ets)) { perror("clock_gettime"); exit(1); } (void)pthread_barrier_wait(&barrier); } static void * thread(void *cookie) { start(); lookups((int)(uintptr_t)cookie); end(); return 0; } static void sigalrm(int junk) { stop = (sig_atomic_t)1; } static void run(int nt) { pthread_t pt; double c; int i; long us; if (pthread_barrier_init(&barrier, 0, nt + 1)) { fprintf(stderr, "pthread_barrier_init\\n"); exit(1); } nlookups = 0; stop = 0; for (i = 0; i < nt; i++) { if (pthread_create(&pt, 0, thread, (void *)(uintptr_t)i)) { fprintf(stderr, "pthread_create\\n"); exit(1); } } start(); alarm(10); end(); us = (long)(ets.tv_sec * (uint64_t)1000000 + ets.tv_nsec / 1000); us -= (long)(sts.tv_sec * (uint64_t)1000000 + sts.tv_nsec / 1000); c = nlookups * 1000000.0 / us; if (ideal == 0) { ideal = c; } printf("%d\\t%d\\t%.0f\\t%.0f\\n", sacnt, nt, c, ideal * nt); if (pthread_barrier_destroy(&barrier)) { fprintf(stderr, "pthread_barrier_destroy\\n"); exit(1); } } int main(int argc, char **argv) { int i, mt; (void)setvbuf(stdout, 0, _IOLBF, 1024); if (argc < 2) { mt = sysconf(_SC_NPROCESSORS_ONLN); } else { mt = atoi(argv[1]); if (mt < 1) { mt = 1; } } if (pthread_mutex_init(&lock, 0)) { fprintf(stderr, "pthread_mutex_init\\n"); exit(1); } makelist(); (void)signal(SIGALRM, sigalrm); for (i = 1; i <= mt; i++) { run(i); } exit(0); }
1
#include <pthread.h> int *m1[1025]; int *m2[1025]; int *res1[1025]; int *res2[1025]; int *res3[1025]; int *res4[1025]; pthread_mutex_t mutex; int m1rows, m1cols, m2rows, m2cols, resrows, rescols; long int row_matrix_mult() { int i, j, k; struct timeval ti, tf; gettimeofday(&ti, 0); for ( i = 0; i < m1rows; i++ ) for ( j = 0; j < m2cols; j++ ) for ( k = 0; k < m1cols; k++ ) { res1[i][j] += m1[i][k] * m2[k][j]; } gettimeofday(&tf, 0); return (long int)((tf.tv_sec - ti.tv_sec) * 1000000L + tf.tv_usec - ti.tv_usec); } long int col_matrix_mult() { int i, j, k; struct timeval ti, tf; gettimeofday(&ti, 0); for ( k = 0; k < m1cols; k++ ) for ( i = 0; i < m1rows; i++ ) for ( j = 0; j < m2cols; j++ ) { res4[i][j] += m1[i][k] * m2[k][j]; } gettimeofday(&tf, 0); return (long int)((tf.tv_sec - ti.tv_sec) * 1000000L + tf.tv_usec - ti.tv_usec); } void *row_mult(void *tid) { int j, k, i = (int)tid; for ( j = 0; j < m2cols; j++ ) for ( k = 0; k < m1cols; k++ ) res2[i][j] += m1[i][k] * m2[k][j]; pthread_exit(0); } void *col_mult(void *tid) { pthread_mutex_lock( &mutex ); int i, j, k = (int)tid; for ( i = 0; i < m1rows; i++ ) for ( j = 0; j < m2cols; j++ ) res3[i][j] += m1[i][k] * m2[k][j]; pthread_mutex_unlock( &mutex ); pthread_exit(0); } long int prll_row_matrix_mult() { pthread_t threads[m1rows]; int status, i; struct timeval ti, tf; gettimeofday(&ti, 0); for ( i = 0; i < m1rows; i++) { status = pthread_create(&threads[i], 0, row_mult, (void *)i); if (status != 0) { printf("Oops. pthread_create returned error code %d\\n", status); } } for (int i = 0; i < m1rows; i++) pthread_join(threads[i], 0); gettimeofday(&tf, 0); return (long int)((tf.tv_sec - ti.tv_sec) * 1000000L + tf.tv_usec - ti.tv_usec); } long int prll_col_matrix_mult() { pthread_t threads[m1cols]; int status, k; struct timeval ti, tf; gettimeofday(&ti, 0); pthread_mutex_init( &mutex, 0 ); for ( k = 0; k < m1cols; k++) { status = pthread_create(&threads[k], 0, col_mult, (void *)k); if (status != 0) { printf("Oops. pthread_create returned error code %d\\n", status); } } for (int k = 0; k < m1cols; k++) pthread_join(threads[k], 0); pthread_mutex_destroy( &mutex ); gettimeofday(&tf, 0); return (long int)((tf.tv_sec - ti.tv_sec) * 1000000L + tf.tv_usec - ti.tv_usec); } void read_matrix( char* filename, int **m, int *mrows, int *mcols) { FILE* fp = fopen(filename, "r"); char s[2050 + 1]; *mrows = 0; while ( fgets(s, 2050, fp) != 0 && *mrows < 1025 ) { char *token; *mcols = 0; m[*mrows] = (int *) malloc( 2050/2 * sizeof(int) ); token = strtok(s, " "); while( token != 0 && *mcols < 2050/2 && (int)token[0] != 10 ) { m[*mrows][*mcols] = atoi(token); (*mcols)++; token = strtok(0, " "); } (*mrows)++; } fclose(fp); } int main( int argc, char **argv ) { if ( argc != 3 ) { printf( "Usage: mm matrix1 matrix2\\n" ); exit(-1); } read_matrix( argv[1], m1, &m1rows, &m1cols ); read_matrix( argv[2], m2, &m2rows, &m2cols ); if ( m1cols != m2rows ) { printf( "Cannot multiply these matrices: %dX%d * %dX%d\\n", m1rows, m1cols, m2rows, m2cols ); exit(-1); } resrows = m1rows; rescols = m2cols; int i, j, k; for ( i = 0; i < resrows; i++ ) { res1[i] = (int *) malloc( rescols * sizeof(int) ); res2[i] = (int *) malloc( rescols * sizeof(int) ); res3[i] = (int *) malloc( rescols * sizeof(int) ); res4[i] = (int *) malloc( rescols * sizeof(int) ); for ( j = 0; j < rescols; j++ ) res1[i][j] = res2[i][j] = res3[i][j] = res4[i][j] = 0; } long int t1, t2, t3, t4; t1 = row_matrix_mult(); t2 = prll_row_matrix_mult(); t3 = prll_col_matrix_mult(); t4 = col_matrix_mult(); for ( i = 0; i < resrows; i++ ) { for ( j = 0; j < rescols; j++ ) { printf("%d ", res4[i][j]); } printf("\\n"); } return 0; }
0
#include <pthread.h> void * escritor(void *); void * lector(void *); int dato = 5; int n_lectores = 0; pthread_mutex_t mutex; pthread_mutex_t mutex_lectores; main(int argc, char *argv[]) { pthread_t th1, th2, th3, th4; pthread_mutex_init(&mutex, 0); pthread_create(&th1, 0, (void *) lector, 0); pthread_create(&th2, 0, (void *) escritor, 0); pthread_create(&th3, 0, (void *) lector, 0); pthread_create(&th4, 0, (void *) escritor, 0); pthread_join(th1, 0); pthread_join(th2, 0); pthread_join(th3, 0); pthread_join(th4, 0); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex_lectores); exit(0); } void * escritor(void *argv) { int i; for(i=0; i<5; i++) { int aux; pthread_mutex_lock(&mutex); aux = dato; dato = dato + 2; printf("Escritor %lu modificando dato %d->%d\\n",(unsigned long int) pthread_self(),aux,dato); pthread_mutex_unlock(&mutex); usleep(random()%2000); } pthread_exit(0); } void * lector(void *argv) { int i; for(i=0; i<5; i++) { pthread_mutex_lock(&mutex_lectores); n_lectores++; if (n_lectores == 1) pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex_lectores); printf("Lector %lu leyedo dato: %d\\n",(unsigned long int) pthread_self(), dato); pthread_mutex_lock(&mutex_lectores); n_lectores--; if (n_lectores == 0) pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex_lectores); usleep(random()%2000); } pthread_exit(0); }
1
#include <pthread.h> pthread_t pthreads[8]; int aantal_tickets = 1000; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *ticket_broker(void * args){ int aantal_verkocht=0; int brokernum = *((int *)args); time_t rawtime; struct tm * timeinfo; while(1){ sleep(rand()%3); pthread_mutex_lock(&lock); if(aantal_tickets>0){ time(&rawtime); timeinfo = localtime(&rawtime); printf("[%.24s] Broker %d sold 1 ticket. (only %d tickets left now)\\n",asctime(timeinfo),brokernum,aantal_tickets); aantal_tickets--; aantal_verkocht++; } else{ pthread_mutex_unlock(&lock); printf("======================\\nBroker %d sold %d tickets.\\n==========================\\n",brokernum,aantal_verkocht); return 0; } pthread_mutex_unlock(&lock); } } int main(int argc, char *argv[]) { int i=0,brokernum[8]; for(i=0;i<8;i++){ brokernum[i] = i; pthread_create(&pthreads[i],0,ticket_broker,&brokernum[i]); } for(i=0;i<8;i++){ pthread_join(pthreads[i],0); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int count = 0; void *func(void *argv) { int *a = (int *)argv; printf(" Thread%d start!\\n", *a); int i; for (i = 0; i < 10; i++) { printf(" Thread%d running...%d\\n", *a, count); sleep(1); pthread_mutex_lock(&mutex); count++; pthread_mutex_unlock(&mutex); } printf(" Thread%d end.\\n", *a); pthread_exit(0); } int main(int argc, char const *argv[]) { printf("Main Start!\\n"); pthread_t thrd1, thrd2; int i[2]; i[0] = 1; i[1] = 2; if (pthread_create(&thrd1, 0, func, &i[0]) != 0) { printf("Error in pthread_create. %s\\n", strerror(errno)); return -1; } if (pthread_create(&thrd2, 0, func, &i[1]) != 0) { printf("Error in pthread_create. %s\\n", strerror(errno)); return -1; } pthread_join(thrd1, 0); pthread_join(thrd2, 0); printf("Main End!\\n"); return 0; }
1
#include <pthread.h> int *a, *b; long sum=0; pthread_mutex_t mymutex; void *dotprod(void *arg) { int i, start, end, offset, len; long tid = (long)arg; long tempsum; offset = tid; len = 100000; start = offset*len; end = start + len; tempsum = 0; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++) tempsum += (a[i] * b[i]); pthread_mutex_lock(&mymutex); sum += tempsum; pthread_mutex_unlock(&mymutex); printf("thread: %ld done. Global sum now is=%li\\n",tid,sum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; void *status; pthread_t threads[8]; pthread_attr_t attr; a = (int*) malloc (8*100000*sizeof(int)); b = (int*) malloc (8*100000*sizeof(int)); for (i=0; i<100000*8; i++) a[i]= b[i]=1; pthread_attr_init(&attr); pthread_mutex_init(&mymutex, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<8; i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_attr_destroy(&attr); for(i=0; i<8; i++) pthread_join(threads[i], &status); printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_mutex_destroy(&mymutex); pthread_exit(0); }
0
#include <pthread.h> int globalCounter=0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; struct params { int maxCount; int threadId; }; void *Contador(void *arg) { struct params *p = (struct params *)arg; printf("Thread %i. Counting until %i\\n",(*p).threadId,(*p).maxCount); int i; for(i=0;i<(*p).maxCount;i++) { pthread_mutex_lock(&mutex1); globalCounter++; pthread_mutex_unlock(&mutex1); } printf("Thread %i. End\\n",(*p).threadId); return 0; } int main(void) { const int maxThreads = 4; pthread_t threads[maxThreads]; struct params p[maxThreads]; int errorCode; int t; for(t=0;t<maxThreads;t++) { p[t].maxCount = 1000000; p[t].threadId = t+1; errorCode = pthread_create(&threads[t],0,&Contador,(void *)&p[t]); if (errorCode) printf("Error %i al crear el thread %i\\n",errorCode,p[t].threadId); } printf("Waiting...\\n"); sleep(3); printf("End. globalCounter=%i\\n",globalCounter); return 0; }
1
#include <pthread.h> uint8_t mem[((1<<12) * (20 - (20 % 8)))]; int counter=0; int failures=0; pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; void do_work(size_t id){ for (int i=0;i<(20 - (20 % 8));++i){ mem[(i*(1<<12))+id]++; } } int count_array(){ int count=0; for (int i=0;i<((1<<12) * (20 - (20 % 8)));++i){ count+=mem[i]; } return count; } void validate(int counter){ int count = counter*(20 - (20 % 8)); int real_count = count_array(); if (count!=real_count){ failures++; printf("failed, count: %d, real_count: %d, counter: %d\\n", count, real_count, counter); } } void * child_thread(void * data) { int id=*((int *)data); for (int i=0;i<150;++i){ do_work(id); pthread_mutex_lock(&g_lock); ++counter; pthread_mutex_unlock(&g_lock); } return 0; } int main(int argc,char**argv) { pthread_t waiters[8]; int thread_id[8]; int i; memset(mem, 0, ((1<<12) * (20 - (20 % 8)))); for(i = 0; i < 8; i++){ thread_id[i]=i; pthread_create (&waiters[i], 0, child_thread, (void *)&(thread_id[i])); } for(i = 0; i < 8; i++) pthread_join (waiters[i], 0); validate(counter); if (counter==150*8 && failures==0){ fprintf(stderr, "lockuse: SUCCEEDED\\n"); } else{ fprintf(stderr, "lockuse: FAILED, failures %d, counter %d expected %d\\n", failures, counter, 150*8); } return 0; }
0
#include <pthread.h> char documentRoot[] = "/usr/local/apache/htdocs"; void *do_web(void *); void web_log(int, char[], char[], int); pthread_t tid; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int log_fd; int main(int argc, char *argv[]) { struct sockaddr_in s_addr, c_addr; int s_sock, c_sock; int len, len_out; unsigned short port; int status; struct rlimit resourceLimit; int i, res; int pid; if(argc != 2) { printf("Usage: webServer_thread port_number\\n"); return -1; } if(fork() != 0) return 0; (void)signal(SIGCHLD, SIG_IGN); (void)signal(SIGHUP, SIG_IGN); resourceLimit.rlim_max = 0; status = getrlimit(RLIMIT_NOFILE, &resourceLimit); for(i = 0; i < resourceLimit.rlim_max; i++) { close(i); } web_log(100, "STATUS", "web server start", getpid()); if((s_sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { web_log(200, "SYSCALL", "web server listen socket open error", s_sock); } port = atoi(argv[1]); if(port > 60000) web_log(200, "ERROR", "invalid port number", port); memset(&s_addr, 0, sizeof(s_addr)); s_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(port); if(bind(s_sock, (struct sockaddr *)&s_addr, sizeof(s_addr) < 0)) { web_log(200, "ERROR", "server cannot bind", 0); } listen(s_sock, 10); while(1) { len = sizeof(c_addr); if((c_sock = accept(s_sock, (struct sockaddr *)&c_addr, &len)) < 0) web_log(200, "ERROR", "server accept error", 0); res = pthread_create(&tid, 0, do_web, (void *)c_sock); } } void * do_web(void *arg) { int c_sock = (int)arg; char sndBuf[1024 +1], rcvBuf[1024 +1]; char uri[100], c_type[20]; int len; int len_out; int n, i; char *p; char method[10], f_name[20]; char phrase[20] = "OK"; int code = 200; int fd; char file_name[20]; char ext[20]; struct stat sbuf; struct { char *ext; char *filetype; } extensions [] = { {"gif", "image/gif"}, {"jpg", "image/jpg"}, {"jpeg", "image/jpeg"}, {"png", "image/png"}, {"zip", "image/zip"}, {"gz", "image/gz"}, {"tar", "image/tar"}, {"htm", "text/html"}, {"html", "text/html"}, {0,0} }; memset(rcvBuf, 0, sizeof(rcvBuf)); if((n = read(c_sock, rcvBuf, 1024)) <= 0) web_log(200, "ERROR", "can not receive data from web browser", n); web_log(100, "REQUEST", rcvBuf, n); p = strtok(rcvBuf, " "); if(strcmp(p, "GET") && strcmp(p, "get")) web_log(200, "ERROR", "only get method can supoort", 0); p = strtok(0, " "); if(!strcmp(p, "/")) sprintf(uri, "%s/index.html", documentRoot); else sprintf(uri, "%s%s", documentRoot, p); strcpy(c_type, "text/plain"); for(i=0; extensions[i].ext != 0; i++) { len = strlen(extensions[i].ext); if(!strncmp(uri+strlen(uri)-len, extensions[i].ext, len)) { strcpy(c_type, extensions[i].filetype); break; } } if((fd = open(uri, O_RDONLY)) < 0) { code = 404; strcpy(phrase, "FILE NOT FOUND"); } p = strtok(0, "\\r\\n "); sprintf(sndBuf, "HTTP/1.0 %d %s \\r\\n", code, phrase); n = write(c_sock, sndBuf, strlen(sndBuf)); web_log(100, "RESPONSE", sndBuf, getpid()); sprintf(sndBuf, "content-type: %s\\r\\n\\r\\n", c_type); n = write(c_sock, sndBuf, strlen(sndBuf)); web_log(100, "RESPONSE", sndBuf, getpid()); if(fd >= 0) { while(( n = read(fd, rcvBuf, 1024)) > 0) { write(c_sock, rcvBuf, n); } } close(c_sock); exit(-1); } void web_log(int type, char s1[], char s2[], int n) { int log_fd; char buf[1024]; if(type == 100) { sprintf(buf, "STATUS %s %s %d\\n", s1, s2, n); } else if(type == 200) { sprintf(buf, "ERROR %s %s %d\\n", s1, s2, n); } pthread_mutex_lock(&mutex); if((log_fd = open("web.log", O_CREAT|O_WRONLY|O_APPEND, 0644)) >= 0) { write(log_fd, buf, strlen(buf)); close(log_fd); } pthread_mutex_unlock(&mutex); if(type == 200) exit(-1); }
1
#include <pthread.h> void program_counter(void *not_used){ pthread_barrier_wait(&threads_creation); while(1){ pthread_mutex_lock(&control_sign); if(!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait, &control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } pthread_mutex_lock(&or_result_mutex); if(!or_result.isUpdated) while(pthread_cond_wait(&or_result_wait, &or_result_mutex) != 0); pthread_mutex_unlock(&or_result_mutex); pthread_mutex_lock(&mux_pcsource_result); if(!mux_pcsource_buffer.isUpdated) while(pthread_cond_wait(&mux_pcsource_execution_wait, &mux_pcsource_result) != 0); pthread_mutex_unlock(&mux_pcsource_result); pthread_barrier_wait(&current_cycle); if(or_result.value) pc = mux_pcsource_buffer.value; pthread_barrier_wait(&update_registers); } }
0
#include <pthread.h> int contador; pthread_mutex_t mutex; void agregar(char c); void quitar(); void * productor() { while(1) { char c = 'a' + rand()%24; agregar(c); usleep(1000); } } void * consumidor() { while(1) { quitar(); usleep(1000); } } void * imprimir() { while(1){ int i; printf("%d",contador); printf("\\n"); usleep(1000); } } int main() { pthread_t thread_consumidor; pthread_t thread_productor; contador = 0; pthread_mutex_init(&mutex, 0); pthread_create(&thread_consumidor, 0, consumidor, 0 ); pthread_create(&thread_productor, 0, productor, 0 ); pthread_join(thread_consumidor, 0); return 0; } void agregar(char c) { if(contador<100){ pthread_mutex_lock(&mutex); contador++; printf("%d\\n",contador); pthread_mutex_unlock(&mutex); } } void quitar() { if(contador>0) { pthread_mutex_lock(&mutex); contador--; printf("%d\\n",contador); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> static int glob = 0; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void *thread_func(void *arg) { int ii; for (ii = 0; ii < 100000; ii++) { pthread_mutex_lock(&mtx); glob++; pthread_mutex_unlock(&mtx); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int s; s = pthread_create(&t1, 0, thread_func, 0); if (s != 0) { do { errno = s; perror("pthread_create"); exit(1); } while(0); } s = pthread_create(&t2, 0, thread_func, 0); if (s != 0) { do { errno = s; perror("pthread_create"); exit(1); } while(0); } s = pthread_join(t1, 0); if (s != 0) { do { errno = s; perror("pthread_join"); exit(1); } while(0); } s = pthread_join(t2, 0); if (s != 0) { do { errno = s; perror("pthread_join"); exit(1); } while(0); } printf("glob = %d\\n", glob); exit(0); }
0
#include <pthread.h> pthread_t jsthread; pthread_mutex_t js_lock = PTHREAD_MUTEX_INITIALIZER; volatile struct js_state js_state = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; struct thread_data { char *path; void (*update)(struct js_event); }; float deadzone(float in) { if (fabs(in) <= .09) return 0; return in; } struct js_state get_js_state() { return js_state; } void js_update(struct js_event event) { pthread_mutex_lock(&js_lock); if (event.type > 2) { event.type -= 0x80; } if (event.type == 1) { if (event.number == 0) js_state.btn_a = event.value; else if (event.number == 1) js_state.btn_b = event.value; else if (event.number == 2) js_state.btn_x = event.value; else if (event.number == 3) js_state.btn_y = event.value; else if (event.number == 4) js_state.btn_left_shoulder = event.value; else if (event.number == 5) js_state.btn_right_shoulder = event.value; else if (event.number == 6) js_state.btn_back = event.value; else if (event.number == 7) js_state.btn_start = event.value; else if (event.number == 8) js_state.btn_guide = event.value; else if (event.number == 9) js_state.btn_left_stick = event.value; else if (event.number == 10) js_state.btn_right_stick = event.value; else { slog(200, SLOG_ERROR, "Unknown js type 1 event %d", event.number); } } else if (event.type == 2) { if (event.number == 0) js_state.axis_left_x = deadzone(-((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 1) js_state.axis_left_y = deadzone(((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 2) js_state.axis_left_trigger = deadzone(((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 3) js_state.axis_right_x = deadzone(-((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 4) js_state.axis_right_y = deadzone(((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 5) js_state.axis_right_trigger = deadzone(((float)event.value) / ((float)SHRT_MIN)); else if (event.number == 6) js_state.axis_dpad_x = -((float)event.value) / ((float)SHRT_MIN); else if (event.number == 7) js_state.axis_dpad_y = ((float)event.value) / ((float)SHRT_MIN); else { slog(200, SLOG_ERROR, "Unknown js type 2 event %d", event.number); } } else { slog(100, SLOG_FATAL, "Unknown event type %d", event.type); screen_close(); exit(1); } pthread_mutex_unlock(&js_lock); } void *js_loop(void *p) { struct thread_data *td = (struct thread_data *)p; int fd = open(td->path, O_RDONLY); while (1) { struct js_event event; int ret = read(fd, &event, sizeof(event)); if (ret == 0) { } td->update(event); } close(fd); free(p); pthread_exit(0); } bool js_connect(char *path) { pthread_mutex_lock(&js_lock); struct thread_data *td = malloc(sizeof(struct thread_data)); td->path = path; td->update = js_update; int stat = pthread_create(&jsthread, 0, js_loop, (void *)td); if (stat) { slog(100, SLOG_FATAL, "Can't create js thread"); exit(1); } pthread_mutex_unlock(&js_lock); return 1; }
1
#include <pthread.h> pthread_mutex_t mutex; sem_t lock1, unlock1; sem_t full, empty; int stack[3]; int cnt; pthread_t pid,cid; pthread_attr_t attr; void *producer(void *param); void *consumer(void *param); void initializeData() { pthread_mutex_init(&mutex, 0); sem_init(&full, 0, 0); sem_init(&empty, 0, 3 -1); cnt = 0; } void *producer(void *param) { int item; while(1) { int rNum = 1; sleep(rNum); item = 10; pthread_mutex_lock(&mutex); if(push(item)) { printf("\\n Stack Full so producer has to wait.........!!"); } else printf("\\nproducer produced : %d\\n", item); pthread_mutex_unlock(&mutex); } } void *consumer(void *param) { int item; while(1) { int rNum =2; sleep(rNum); item = 10; pthread_mutex_lock(&mutex); if(pop(&item)) { sem_wait(&full); printf(" \\n Stack Empty......!!!"); } else printf("Consumer consumed : %d\\n", item); pthread_mutex_unlock(&mutex); } } int push(int item) { if(cnt < 3) { stack[cnt] = item; cnt++; return 0; } else return 1; } int pop(int *item) { if(cnt > 0) { *item = stack[(cnt-1)]; cnt--; return 0; } else return 1; } int main() { initializeData(); sem_init(&lock1,0,0); sem_init(&unlock1,0,0); pthread_create(&pid,0,producer,0); pthread_create(&cid,0,consumer,0); pthread_join(pid,0); pthread_join(cid,0); exit(0); }
0
#include <pthread.h> double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start+len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock(&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n", offset, start, end, mysum, dotstr.sum); pthread_mutex_unlock(&mutexsum); pthread_exit((void *)0); } int main(int argc, char **argv) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double *)malloc(4 * 100000 * sizeof(double)); b = (double *)malloc(4 * 100000 * sizeof(double)); for (i=0; i<100000*4; i++) { a[i] = 1; b[i] = a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<4; i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for (i=0; i<4; i++) { pthread_join(callThd[i], &status); } printf("Sum = %f\\n", dotstr.sum); free(a); free(b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); return 0; }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
0
#include <pthread.h> static FILE *fz; pthread_mutex_t fz_mutex = PTHREAD_MUTEX_INITIALIZER; static void open_file(const char* file) { fz = fopen(file, "w+"); if (fz == 0) { printf("Konnte Datei %s nicht öffnen\\n", file); exit(1); } } static void thread_schreiben(void* name) { (void)name; char string[255]; pthread_mutex_lock(&fz_mutex); printf("Bitte Eingabe machen: "); fgets(string, 255, stdin); fputs(string, fz); fflush(fz); for (int i=0; i<(10 * 1000 * 1000); ++i); pthread_mutex_unlock(&fz_mutex); pthread_exit((void*)pthread_self()); } static void thread_lesen(void* name) { (void)name; char string[255]; pthread_mutex_lock(&fz_mutex); rewind(fz); fgets(string, 255, fz); printf("Ausgabe Thread %ld: ", (long)pthread_self()); fputs(string, stdout); fflush(stdout); pthread_mutex_unlock(&fz_mutex); pthread_exit((void*)pthread_self()); } int main(void) { int i; static int ret[2]; static pthread_t thread[2]; printf("\\n-> Main-Thread gestartet (ID:%ld)\\n", (long)pthread_self()); open_file("testfile"); if (pthread_create(&thread[0], 0, (void*)&thread_schreiben, 0) != 0) { fprintf(stderr, "Konnte Thread nicht erzeugen ...!\\n"); exit(1); } if (pthread_create(&thread[1], 0, (void*)&thread_lesen, 0) != 0) { fprintf(stderr, "Konnte Thread nicht erzeugen ...!\\n"); exit(1); } for (i=0; i< 2; ++i) { pthread_join(thread[i], (void*)(&ret[i])); } for (i=0; i< 2; ++i) { printf("\\t<-Thread %ld fertig\\n", (long)thread[i]); } printf("<- Main-Thread beendet (ID:%ld)\\n", (long)pthread_self()); return 0; }
1
#include <pthread.h> struct product_cons { int buffer[5]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }buffer; void init(struct product_cons *p) { pthread_mutex_init(&p->lock, 0); pthread_cond_init(&p->notempty, 0); pthread_cond_init(&p->notfull, 0); p->readpos = 0; p->writepos = 0; } void finish(struct product_cons *p) { pthread_mutex_destroy(&p->lock); pthread_cond_destroy(&p->notempty); pthread_cond_destroy(&p->notfull); p->readpos = 0; p->writepos = 0; } void put(struct product_cons *p, int data) { pthread_mutex_lock(&p->lock); if((p->writepos+1)%5 == p->readpos) { printf("producer wait for not full\\n"); pthread_cond_wait(&p->notfull, &p->lock); } p->buffer[p->writepos] = data; p->writepos ++; if(p->writepos >= 5) p->writepos = 0; pthread_cond_signal(&p->notempty); pthread_mutex_unlock(&p->lock); } int get(struct product_cons *p) { int data; pthread_mutex_lock(&p->lock); if(p->readpos == p->writepos) { printf("consumer wait for not empty\\n"); pthread_cond_wait(&p->notempty, &p->lock); } data = p->buffer[p->readpos]; p->readpos++; if(p->readpos >= 5) p->readpos = 0; pthread_cond_signal(&p->notfull); pthread_mutex_unlock(&p->lock); return data; } void *producer(void *data) { int n; for(n = 1; n <= 50; ++n) { sleep(1); printf("put the %d product ...\\n", n); put(&buffer,n); printf("put the %d product success\\n", n); } printf("producer stopped\\n"); return 0; } void *consumer(void *data) { static int cnt = 0; int num; while(1) { sleep(2); printf("get product ...\\n"); num = get(&buffer); printf("get the %d product success\\n", num); if(++cnt == 30) break; } printf("consumer stopped\\n"); return 0; } int main(int argc, char *argv[]) { 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); finish(&buffer); return 0; }
0
#include <pthread.h> extern char **environ; static pthread_mutex_t env_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void init_mutex( void ) { pthread_mutexattr_t attr; pthread_mutexattr_init( &attr ); pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( &env_lock, &attr ); pthread_mutexattr_destroy( &attr ); } extern int putenv_r( char *env_str ) { char *env_name = env_str; char *env_value = strchr( env_str, '=' ); if ( env_value == 0 ) { return -1; } *env_value = '\\0'; env_value++; pthread_once( &init_done, init_mutex ); int i; int len = strlen( env_name ); pthread_mutex_lock( &env_lock ); for ( i = 0; environ[ i ] != 0; i++ ) { if ( strncmp( environ[ i ], env_name, len ) == 0 && environ[ i ][ len ] == '=' ) { strcpy( &environ[ i ][ len ], env_value ); pthread_mutex_unlock( &env_lock ); return 0; } } pthread_mutex_unlock( &env_lock ); return -1; }
1
#include <pthread.h> pid_t pid; bool has_done; pthread_mutex_t mutex; void kill_child(int); void *read_output(void *); void *read_output(void *arg) { int fd = *((int *)arg); free(arg); int ret = 0; char buffer[1024]; do { ret = read(fd, buffer, 1024); pthread_mutex_lock(&mutex); if (has_done) { pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); printf("%s", buffer); } while(ret >= 0); return 0; } void kill_child(int sig) { kill(pid, sig); } int main(int argc, char **argv) { int status; int fds[2]; if (argc < 2) { fprintf(stderr, "usage: ./monitor-process <program> [args]\\n"); exit(1); } pipe(fds); pid = fork(); if (pid == 0) { dup2(fds[1], 1); dup2(fds[1], 2); execvp(argv[1], argv + 1); fprintf(stderr, "error: unable to exec process: %s\\n", strerror(errno)); exit(1); } else if (pid > 0) { signal(SIGTERM, (void (*)(int)) kill_child); signal(SIGHUP, (void (*)(int)) kill_child); signal(SIGUSR1, (void (*)(int)) kill_child); signal(SIGINT, (void (*)(int)) kill_child); signal(SIGQUIT, (void (*)(int)) kill_child); pthread_mutex_init(&mutex, 0); pthread_mutex_lock(&mutex); has_done = 0; pthread_mutex_unlock(&mutex); int *fd_arg = malloc(sizeof(*fd_arg)); *fd_arg = fds[0]; pthread_t read_thread; pthread_create(&read_thread, 0, read_output, (void *)fd_arg); pthread_detach(read_thread); if (wait(&status) < 0) { fprintf(stderr, "error: unable to wait: %s\\n", strerror(errno)); exit(1); } pthread_mutex_lock(&mutex); has_done = 1; pthread_mutex_unlock(&mutex); close(fds[1]); close(fds[0]); int exit_code; if (WIFEXITED(status)) { exit_code = WEXITSTATUS(status); printf("\\nexited with status code of %d\\n", exit_code); } else if (WIFSIGNALED(status)) { exit_code = WTERMSIG(status); printf("\\nexited with signal of %d\\n", exit_code); } else { printf("\\nexited without status code or signal\\n"); } } else { fprintf(stderr, "error: unable to fork process: %s\\n", strerror(errno)); exit(1); } pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> int ready; sig_atomic_t sigusr1_received; sig_atomic_t sigusr2_received; sig_atomic_t sigabrt_received; int thread_count; pthread_mutex_t thread_count_mutex; pthread_cond_t thread_count_condvar; static void incr_thread_count (void) { pthread_mutex_lock (&thread_count_mutex); ++thread_count; pthread_cond_signal (&thread_count_condvar); pthread_mutex_unlock (&thread_count_mutex); } static void sigusr1_handler (int sig) { sigusr1_received = 1; } static void sigusr2_handler (int sig) { sigusr2_received = 1; } static void sigabrt_handler (int sig) { sigabrt_received = 1; } static void * sigusr1_thread_function (void *unused) { incr_thread_count (); while (!ready) usleep (100); pthread_kill (pthread_self (), SIGUSR1); } static void * sigusr2_thread_function (void *unused) { incr_thread_count (); while (!ready) usleep (100); } static void wait_all_threads_running (int nr_threads) { pthread_mutex_lock (&thread_count_mutex); while (1) { if (thread_count == nr_threads) { pthread_mutex_unlock (&thread_count_mutex); return; } pthread_cond_wait (&thread_count_condvar, &thread_count_mutex); } } static void all_threads_running (void) { while (!ready) usleep (100); } static void all_threads_done (void) { } int main () { pthread_t sigusr1_thread, sigusr2_thread; alarm (60); signal (SIGUSR1, sigusr1_handler); signal (SIGUSR2, sigusr2_handler); signal (SIGABRT, sigabrt_handler); ready = 0; pthread_mutex_init (&thread_count_mutex, 0); pthread_cond_init (&thread_count_condvar, 0); pthread_create (&sigusr1_thread, 0, sigusr1_thread_function, 0); pthread_create (&sigusr2_thread, 0, sigusr2_thread_function, 0); wait_all_threads_running (2); all_threads_running (); pthread_kill (pthread_self (), SIGABRT); pthread_join (sigusr1_thread, 0); pthread_join (sigusr2_thread, 0); all_threads_done (); return 0; }
1
#include <pthread.h> int inCircle = 0; int point = 0; int count = 0; pthread_mutex_t mutex; int i; int thread[10]; void help() { printf("\\n-----------------------------------------------------------\\n"); printf("| usage: ./OShw3_3 [sample points number] [thread number] |\\n"); printf("| [sample points number] must be a positive number (>0) |\\n"); printf("| [thread number] must be a positive number (>0) |\\n"); printf("-----------------------------------------------------------\\n\\n"); } void *runner(void *param) { int t = *(int*)param; while(count<point){ double x = (double)(rand()%2000-1000)/1000; double y = (double)(rand()%2000-1000)/1000; double dis = sqrt(x*x + y*y); pthread_mutex_lock(&mutex); thread[t]++; count++; if(dis<1) inCircle++; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char* argv[]) { help(); if(argc!=3){ printf("ERROR: command error\\n"); return -1; } point = atoi(argv[1]); int threadNum = atoi(argv[2]); if(point<=0 || threadNum<=0){ printf("ERROR: input must be positive\\n"); return -1; } pthread_mutex_init(&mutex, 0); pthread_t tid[threadNum]; pthread_attr_t attr[threadNum]; int param[threadNum]; for(i=0; i<threadNum; i++) param[i] = i; for(i=0; i<threadNum; i++){ pthread_attr_init(&attr[i]); pthread_create(&tid[i], &attr[i], runner, &param[i]); } for(i=0; i<threadNum; i++) pthread_join(tid[i], 0); for(i=0; i<threadNum; i++) printf("Thread %d: %d\\n", i, thread[i]); double pi = 4 * ((double)inCircle/(double)count); printf("Sample points = %d\\n", count); printf("In circle points = %d\\n", inCircle); printf("PI = %f\\n", pi); return 0; }
0
#include <pthread.h> int num_threads; pthread_mutex_t * mutexes; none, one, two } utensil; int phil_num; int course; utensil forks; }phil_data; void * eat_meal(void * args){ phil_data * phil = (phil_data *) args; phil->course += 1; sleep(1); return 0; } void run(phil_data * philos, int length) { char buf[512 * length]; sprintf(buf, "%-20s %-s\\n", "Philosopher", "Courses Eaten"); printf(buf); for (int i = 0; i < length; i++) { printf("%-20d %-d\\n", philos[i].phil_num, philos[i].course); } return; } int main( int argc, char ** argv ){ int num_philosophers; if (argc < 2) { fprintf(stderr, "Format: %s <Number of philosophers>\\n", argv[0]); return 0; } num_philosophers = num_threads = atoi(argv[1]); pthread_t threads[num_threads]; phil_data philosophers[num_philosophers]; mutexes = malloc(sizeof(pthread_mutex_t)*num_philosophers); pthread_cond_t cond_var[num_threads]; for (int i = 0; i < num_threads; i++) { pthread_cond_init(&cond_var[i], 0); pthread_mutex_init(&mutexes[i], 0); } for( int i = 0; i < num_philosophers; i++ ){ philosophers[i].phil_num = i; philosophers[i].course = 0; philosophers[i].forks = none; } int total_courses = num_philosophers * 3; int eaten_courses = 0; while (eaten_courses < total_courses) { for (int i = 0; i < num_philosophers; i++) { pthread_mutex_lock(&mutexes[i]); if (philosophers[i].course < 3 && philosophers[i].forks == none) { philosophers[i].forks = one; if (i == num_philosophers - 1) { pthread_mutex_lock(&mutexes[0]); if (philosophers[0].forks == none) { philosophers[i].forks = two; pthread_create(&threads[i], 0, &eat_meal, &philosophers[i]); } pthread_mutex_unlock(&mutexes[0]); } else { pthread_mutex_lock(&mutexes[i+1]); if (philosophers[i+1].forks == none) { philosophers[i].forks = two; pthread_create(&threads[i], 0, &eat_meal, &philosophers[i]); } pthread_mutex_unlock(&mutexes[i+1]); } if (philosophers[i].course == 3) { eaten_courses += 3; } philosophers[i].forks = none; } pthread_mutex_unlock(&mutexes[i]); } } for (int i = 0; i < num_philosophers; i++) { pthread_join(threads[i], 0); pthread_cond_destroy(&cond_var[i]); pthread_mutex_destroy(&mutexes[i]); } run(philosophers, num_philosophers); return 0; }
1
#include <pthread.h> sem_t customers; sem_t barbers; pthread_mutex_t mutex; int waiting = 0; void barber(void); void customer(void); void cut_hair(void); int main(void) { pthread_t tid_b, tid_c; int i = 0; sem_init(&customers, 0, 0); sem_init(&barbers, 0, 1); pthread_create(&tid_b, 0, barber, 0); while (1) { sleep(1); pthread_create(&tid_c, 0, customer, 0); } } void barber(void) { while(1) { sem_wait(&customers); pthread_mutex_lock(&mutex); waiting = waiting -1; sem_post(&barbers); pthread_mutex_unlock(&mutex); cut_hair(); } } void cut_hair(void) { printf(" Barber: I am cutting the customer's hair...\\n"); sleep(1); printf(" Barber: done.\\n"); } void customer(void) { pthread_mutex_lock(&mutex); if (waiting < 5) { printf("add customer.\\n"); waiting += 1; sem_post(&customers); pthread_mutex_unlock(&mutex); sem_wait(&barbers); } else { printf("Too many wait.\\n"); pthread_mutex_unlock(&mutex); } return ; }
0
#include <pthread.h> int i = 4; pthread_mutex_t mutex; pthread_cond_t cond; void* Thread1(void* arg) { printf("Thread1 called \\n"); pthread_mutex_lock(&mutex); printf("Thread1 mutex taken\\n"); if (i != 10) { printf("Thread1 cond wait\\n"); pthread_cond_wait(&cond, &mutex); } printf("Thread1 signalled and about to unlock\\n"); pthread_mutex_unlock(&mutex); printf("Thread1 unlocked\\n"); printf("Thread1 finished, i: %d \\n", i); pthread_exit(&i); } void* Thread2(void* arg) { printf("Thread2 called \\n"); pthread_mutex_lock(&mutex); printf("Thread2 mutex taken\\n"); i = 10; printf("Thread2 about to signal\\n"); pthread_cond_signal(&cond); printf("Thread2 about to unlock\\n"); sleep(2); pthread_mutex_unlock(&mutex); printf("Thread2 unlocked\\n"); sleep(2); printf("Thread2 finished \\n"); } int main() { pthread_t t1; pthread_t t2; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_create(&t1, 0, Thread1, 0); sleep(2); pthread_create(&t2, 0, Thread2, 0); int* j; pthread_join(t1, (void**)&j); pthread_join(t2, 0); printf("j: %d \\n", *j); return 0; }
1
#include <pthread.h> static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head = 0; static void cleanup_handler(void *arg) { printf("Cleanup handler of second thread./n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node *p = 0; pthread_cleanup_push(cleanup_handler, p); while (1) { pthread_mutex_lock(&mtx); while (head == 0) { pthread_cond_wait(&cond, &mtx); } p = head; head = head->n_next; printf("Got %d from front of queue/n", p->n_number); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); return 0; } int main(void) { pthread_t tid; int i; struct node *p; pthread_create(&tid, 0, thread_func, 0); for (i = 0; i < 10; i++) { p = malloc(sizeof(struct node)); p->n_number = i; pthread_mutex_lock(&mtx); p->n_next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread 1 wanna end the line.So cancel thread 2./n"); pthread_cancel(tid); pthread_join(tid, 0); printf("All done -- exiting/n"); return 0; }
0
#include <pthread.h> int MyTurn = 0; { pthread_mutex_t *lock; pthread_cond_t *wait; int id; int size; int iterations; char *s; int nthreads; } Thread_struct; void *infloop(void *x) { int i, j, k; Thread_struct *t; t = (Thread_struct *) x; for (i = 0; i < t->iterations; i++) { pthread_mutex_lock(t->lock); while((MyTurn % t->nthreads) != t->id) { pthread_cond_signal(t->wait); pthread_cond_wait(t->wait,t->lock); } for (j = 0; j < t->size-1; j++) { t->s[j] = 'A'+t->id; for(k=0; k < 50000; k++); } t->s[j] = '\\0'; printf("Thread %d: %s\\n", t->id, t->s); MyTurn++; pthread_cond_signal(t->wait); pthread_mutex_unlock(t->lock); } return(0); } int main(int argc, char **argv) { pthread_mutex_t lock; pthread_cond_t wait; pthread_t *tid; pthread_attr_t *attr; Thread_struct *t; void *retval; int nthreads, size, iterations, i; char *s; if (argc != 4) { fprintf(stderr, "usage: race nthreads stringsize iterations\\n"); exit(1); } pthread_mutex_init(&lock, 0); pthread_cond_init(&wait, 0); nthreads = atoi(argv[1]); size = atoi(argv[2]); iterations = atoi(argv[3]); tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads); attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * nthreads); t = (Thread_struct *) malloc(sizeof(Thread_struct) * nthreads); s = (char *) malloc(sizeof(char *) * size); for (i = 0; i < nthreads; i++) { t[i].nthreads = nthreads; t[i].id = i; t[i].size = size; t[i].iterations = iterations; t[i].s = s; t[i].lock = &lock; t[i].wait = &wait; pthread_attr_init(&(attr[i])); pthread_attr_setscope(&(attr[i]), PTHREAD_SCOPE_SYSTEM); pthread_create(&(tid[i]), &(attr[i]), infloop, (void *)&(t[i])); } for (i = 0; i < nthreads; i++) { pthread_join(tid[i], &retval); } return(0); }
1
#include <pthread.h> pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_nonzero = PTHREAD_COND_INITIALIZER; unsigned count = 4; void *decrement_count(void *arg) { while(1) { pthread_mutex_lock(&count_lock); printf("desc locked\\n"); while (count == 0){ printf("desc cond wait\\n"); pthread_cond_wait(&count_nonzero, &count_lock); } sleep(1); count = count - 1; printf("desc unlock %d \\n", count); pthread_mutex_unlock(&count_lock); } } void *increment_count(void *arg) { while(1) { sleep(1); pthread_mutex_lock(&count_lock); printf("inc locked\\n"); if (count == 0) { printf("inc cond signal\\n"); pthread_cond_signal(&count_nonzero); } count = count + 1; printf("inc unlock %d \\n", count); pthread_mutex_unlock(&count_lock); } } pthread_t threadid[2]; int main( void ) { pthread_create( &threadid[0], 0, &increment_count, 0 ); pthread_create( &threadid[1], 0, &decrement_count, 0 ); sleep( 10 ); pthread_join(threadid[0], 0); pthread_join(threadid[1], 0); pthread_mutex_destroy(&count_lock); pthread_cond_destroy(&count_nonzero); printf("Main program completed\\n"); return 0; }
0
#include <pthread.h> int mesa[4]; int sentados=0; int platos=0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t kuz = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t consume_t = PTHREAD_COND_INITIALIZER; pthread_cond_t sits = PTHREAD_COND_INITIALIZER; pthread_cond_t produce_t = PTHREAD_COND_INITIALIZER; void * blancanieves(void * arg) { while(1){ pthread_cond_wait(&produce_t, &mutex); pthread_mutex_lock(&mutex); platos++; printf("un enano me pidio de comer\\n"); pthread_mutex_unlock(&mutex); pthread_cond_signal(&consume_t); } pthread_exit(0); } void * enanitos(void * arg) { while(1) { usleep(rand() % 500); pthread_mutex_lock(&kuz); if(sentados<4) { sentados++; pthread_cond_signal(&produce_t); printf("me sente y pedi de comer\\n"); }else{ printf("esperando a que se pare un enano\\n"); pthread_cond_wait(&sits, &kuz); pthread_cond_signal(&produce_t); printf("me sente (despues de eperar) y pedi de comer\\n"); sentados++; } pthread_mutex_unlock(&kuz); pthread_cond_wait(&consume_t, &mutex); pthread_mutex_lock(&mutex); platos--; sentados--; printf("comi me voy a trabajar\\n"); pthread_mutex_unlock(&mutex); pthread_cond_signal(&sits); } } int main(int argc, const char * argv[]) { int nhilos = 7 + 1; pthread_t * obreros = (pthread_t *) malloc (sizeof(pthread_t) * nhilos); int indice = 0; pthread_t * aux; for (aux = obreros; aux < (obreros+7); ++aux) { printf("--- Creando el enano %d ---\\n", ++indice); pthread_create(aux, 0, enanitos, (void *) indice); } printf("--- Creando blancanieves ---\\n"); ++indice; pthread_create(aux, 0, blancanieves, (void *) indice); for (aux = obreros; aux < (obreros+nhilos); ++aux) { pthread_join(*aux, 0); } free(obreros); return 0; }
1
#include <pthread.h> struct propset { char *str; int row; int col; int delay; int dir; int vert; int prevr; }; pthread_mutex_t myLock = PTHREAD_MUTEX_INITIALIZER; int main(int argc, const char *argv[]) { void *animate(void *); int setup(int, char **, struct propset *); int ch; int numMsg; pthread_t thrds[10]; struct propset props[10]; numMsg = setup(argc - 1, argv + 1, props); for (int i = 0; i < numMsg; ++i) { pthread_create(&thrds[i], 0, animate, (void *)&props[i]); } while (1) { ch = getch(); if (ch == 'q') break; if (ch == ' ') { for (int i = 0; i < numMsg; ++i) { props[i].dir = -props[i].dir; } } if (ch >= '0' && ch <= '9') { if ( ch - '0' < numMsg) props[ch - '0'].dir = -props[ch - '0'].dir; } } for (int i = 0; i < numMsg; ++i) { pthread_cancel(thrds[i]); } endwin(); return 0; } int setup(int numOfStr, char *mStr[], struct propset props[]) { int numOfMsg = numOfStr > 10 ? 10 : numOfStr; initscr(); srand(getpid()); for (int i = 0; i < numOfMsg; ++i) { props[i].str = mStr[i]; props[i].row = i; props[i].col = rand() % (LINES - strlen(mStr[i]) - 2); props[i].delay = 100 + (rand() % 100); props[i].dir = ((rand() % 2) ? 1 : -1); props[i].prevr = -1; props[i].vert = 1; } crmode(); noecho(); clear(); mvprintw(LINES - 1, 0, "'q' to quit, '0'..'%d' to bounce", numOfMsg - 1); return numOfMsg; } void *animate(void *arg) { struct propset *info = arg; int len = strlen(info->str)+2; while( 1 ) { usleep(info->delay*1000); pthread_mutex_lock(&myLock); if ( info->vert ){ if ( info->prevr != -1 ){ move( info->prevr, info->col ); printw("%*s", strlen(info->str), ""); } move( info->row, info->col ); addstr( info->str ); info->prevr = info->row; } else { move( info->row, info->col ); addch(' '); addstr( info->str ); addch(' '); } move(LINES-1,COLS-1); refresh(); pthread_mutex_unlock(&myLock); if ( info->vert ){ info->row += info->dir; if ( info->row <= 0 && info->dir == -1 ) info->dir = 1; else if ( info->row >= LINES-2 && info->dir == 1 ) info->dir = -1; } else { info->col += info->dir; if ( info->col <= 0 && info->dir == -1 ) info->dir = 1; else if ( info->col+len >= COLS && info->dir == 1 ) info->dir = -1; } } }
0
#include <pthread.h> static struct { struct dht22 dht_street; struct dht22 dht_room; struct dht22 dht_veranda; struct dht22 dht_2nd; float street_temp; float street_hum; float room_temp; float room_hum; float second_temp; float second_hum; float veranda_temp; float veranda_hum; pthread_t sens_th; pthread_mutex_t *mutex; uint8_t tm; } meteo = { .tm = 0, .street_temp = -2000.0f, .street_hum = -2000.0f, .room_temp = -2000.0f, .room_hum = -2000.0f, .second_temp = -2000.0f, .second_hum = -2000.0f, .veranda_temp = -2000.0f, .veranda_hum = -2000.0f }; static bool sensor_read_data(struct dht22 *dht, float *temp, float *hum) { uint8_t ret = 0; for (uint8_t i = 0; i < 20; i++) { ret = dht22_read_data(dht, temp, hum); if (ret == DHT_OK) return 1; struct timeval tv = {1, 0}; if (select(0, 0, 0, 0, &tv) == -1) if (EINTR == errno) continue; } *temp = -2000.0f; *hum = -2000.0f; return 0; } static void* timer_thread(void *data) { for (;;) { if (!sensor_read_data(&meteo.dht_street, &meteo.street_temp, &meteo.street_hum)) { pthread_mutex_lock(meteo.mutex); log_local("Fail reading street sensor", LOG_WARNING); pthread_mutex_unlock(meteo.mutex); } if (!sensor_read_data(&meteo.dht_room, &meteo.room_temp, &meteo.room_hum)) { pthread_mutex_lock(meteo.mutex); log_local("Fail reading room sensor", LOG_WARNING); pthread_mutex_unlock(meteo.mutex); } if (!sensor_read_data(&meteo.dht_veranda, &meteo.veranda_temp, &meteo.veranda_hum)) { pthread_mutex_lock(meteo.mutex); log_local("Fail reading veranda sensor", LOG_WARNING); pthread_mutex_unlock(meteo.mutex); } if (!sensor_read_data(&meteo.dht_2nd, &meteo.second_temp, &meteo.second_hum)) { pthread_mutex_lock(meteo.mutex); log_local("Fail reading 2nd sensor", LOG_WARNING); pthread_mutex_unlock(meteo.mutex); } struct timeval tv = {10, 0}; if (select(0, 0, 0, 0, &tv) == -1) if (EINTR == errno) continue; meteo.tm++; if (meteo.tm == 60) { struct database meteo_db; meteo.tm = 0; if (!database_load(&meteo_db, PATH_METEO)) { log_local("Fail loading Meteo database.", LOG_WARNING); continue; } if (!database_add_meteo(&meteo_db, meteo.street_temp, meteo.street_hum, DB_STREET)) log_local("Fail adding street data to DB.", LOG_WARNING); if (!database_add_meteo(&meteo_db, meteo.room_temp, meteo.room_hum, DB_MAIN_ROOM)) log_local("Fail adding room data to DB.", LOG_WARNING); database_close(&meteo_db); } } return 0; } bool meteo_sensors_init(void) { const struct meteo_cfg *mc = configs_get_meteo(); if (!gpio_init()) return 0; dht22_init(&meteo.dht_street, mc->street); dht22_init(&meteo.dht_room, mc->room); dht22_init(&meteo.dht_veranda, mc->veranda); dht22_init(&meteo.dht_2nd, mc->second); return 1; } void meteo_sensors_start_timer(pthread_mutex_t *mutex) { meteo.mutex = mutex; pthread_create(&meteo.sens_th, 0, &timer_thread, 0); pthread_detach(meteo.sens_th); puts("Starting meteo server..."); } void meteo_get_street_data(float *temp, float *hum) { *temp = meteo.street_temp; *hum = meteo.street_hum; } void meteo_get_room_data(float *temp, float *hum) { *temp = meteo.room_temp; *hum = meteo.room_hum; } void meteo_get_2nd_data(float *temp, float *hum) { *temp = meteo.second_temp; *hum = meteo.second_hum; } void meteo_get_veranda_data(float *temp, float *hum) { *temp = meteo.veranda_temp; *hum = meteo.veranda_hum; }
1
#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 < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { 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(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); if (count<12) { while (count != 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); } printf("watch_count(): thread %ld Count= %d. Updating the value of count...\\n", my_id,count); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; 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); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %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); }
0
#include <pthread.h> time_t time; int roomNumber; } WakeUpCall; int size; WakeUpCall *alarm; } AlarmHeap; pthread_mutex_t lock; pthread_cond_t cond; AlarmHeap* heap=0; static void AlarmGeneratorExit() { printf("\\ncleaning memory up"); free(heap->alarm); printf("\\nGoodbye from AlarmGenerator Thread\\n"); } static void GuestNotifyExit() { printf("Goodbye from GuestNotify Thread\\n"); } void SortInsert(int index) { int parentIndex; WakeUpCall tmp; while(index>0) { parentIndex = (index - 1) / 2; if(heap->alarm[parentIndex].time > heap->alarm[index].time) { tmp = heap->alarm[parentIndex]; heap->alarm[parentIndex] = heap->alarm[index]; heap->alarm[index] = tmp; } index=parentIndex; } } void SortRemove(int index) { int lChild, rChild, minIndex; WakeUpCall tmp; while(1) { lChild=index*2; rChild=index*2+1; if(lChild>heap->size) { break; } minIndex=lChild; if(rChild<=heap->size && heap->alarm[rChild].time < heap->alarm[lChild].time) { minIndex = rChild; } if(heap->alarm[index].time > heap->alarm[minIndex].time) { tmp = heap->alarm[minIndex]; heap->alarm[minIndex] = heap->alarm[index]; heap->alarm[index] = tmp; index=minIndex; } else { break; } } } static void * GuestNotify(void *heaper){ pthread_cleanup_push(GuestNotifyExit, 0); AlarmHeap *tempHeap = (AlarmHeap *)heaper; int expired,error = 0; struct timespec check; time_t currentTime; while(1){ if(tempHeap->size>0) { pthread_mutex_lock(&lock); WakeUpCall test=tempHeap->alarm[0]; check.tv_sec = test.time; check.tv_nsec = 0; error = pthread_cond_timedwait(&cond, &lock, &check); if(error == 110) { tempHeap->alarm[0] = tempHeap->alarm[tempHeap->size-1]; tempHeap->size--; tempHeap->alarm= realloc(tempHeap->alarm, (tempHeap->size*sizeof(WakeUpCall))); heap=tempHeap; SortRemove(0); expired += 1; printf("\\nWake up! %i %s \\n", test.roomNumber, ctime(&test.time)); printf("Expired Alarms: %i\\n", expired); printf("Pending Alarms: %i\\n", tempHeap->size); } pthread_mutex_unlock(&lock); } } pthread_cleanup_pop(1); } static void * AlarmGenerator(void *heaper){ pthread_cleanup_push(AlarmGeneratorExit, 0); srand(time(0)); AlarmHeap *tempHeap = (AlarmHeap *)heaper; while(1){ sleep(rand()%(5-1)+1); time_t waketime; WakeUpCall call; call.roomNumber = rand()%(1-10000)+1; waketime = time(0) + rand()%(1-100)+1; call.time = waketime; pthread_mutex_lock(&lock); tempHeap->size++; tempHeap->alarm = realloc(tempHeap->alarm, (tempHeap->size*sizeof(WakeUpCall))); tempHeap->alarm[tempHeap->size-1] = call; heap=tempHeap; SortInsert(heap->size-1); printf("\\nRegistering: %i %s \\n", call.roomNumber, ctime(&waketime)); pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); } pthread_cleanup_pop(1); } int main(int argc, char *argv[]){ pthread_t create,check; AlarmHeap heap; heap.alarm = 0; heap.size = 0; heap.alarm = malloc( heap.size*sizeof(heap.alarm) ); pthread_create(&create, 0, AlarmGenerator, &heap); pthread_create(&check, 0, GuestNotify, &heap); sigset_t listen_sigs; sigemptyset(&listen_sigs); sigaddset(&listen_sigs, SIGINT); int listen_sig_r; pthread_sigmask(SIG_BLOCK, &listen_sigs, 0); sigwait(&listen_sigs, &listen_sig_r); pthread_cancel(create); pthread_cancel(check); pthread_join(create,0); pthread_join(check,0); pthread_mutex_destroy(&lock); pthread_cond_destroy (&cond); return 0; }
1
#include <pthread.h> int c[10]; pthread_mutex_t mut[10]; void enter_critical(int i, int j){ pthread_mutex_lock (&mut[(i<j)?i:j]); pthread_mutex_lock (&mut[(i<j)?j:i]); } void exit_critical(int i, int j){ pthread_mutex_unlock (&mut[i]); pthread_mutex_unlock (&mut[j]); } void init_mutexes(){ int j; for(j=0;j<10;j++) pthread_mutex_init (&mut[j], 0); } void destroy_mutexes(){ int j; for(j=0;j<10;j++) pthread_mutex_destroy (&mut[j]); } int randpos() { return (rand() % 10); } void atomic_swap(int i, int j){ enter_critical(i, j); int t = c[i]; c[i] = c[j]; c[j] = t; exit_critical(i, j); } void *threadfun(void *arg) { int n; for(n=0;n<1000000;n++){ int i = randpos(); int j = randpos(); if (i!=j) atomic_swap(i,j); } printf("Fin %s\\n",(char *)arg); return 0; } int main(int argc, char **argv){ pthread_t t1,t2; srand(time(0)); int i; for(i=0;i<10;i++) c[i] = i; init_mutexes(); pthread_create(&t1,0,threadfun,"thread 1"); pthread_create(&t2,0,threadfun,"thread 2"); pthread_join(t1,0); pthread_join(t2,0); destroy_mutexes(); for(i=0;i<10;i++) printf("c[%d] = %d\\n",i,c[i]); printf("Fin main.\\n"); }
0
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks ...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks ...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks ...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started ...\\n"); pause(); return (0); } int main(void) { int err; pid_t pid; pthread_t tid; printf("main process: %d\\n",getpid()); if((err = pthread_atfork(prepare, parent, child)) != 0){ err_exit(err, "can't install fork handlers"); } err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0){ err_exit(err, "can't create thread"); } sleep(2); printf("parent about to fork ...\\n"); if((pid = fork()) < 0){ err_quit("fork failed"); } else if(pid == 0){ printf("child returned from fork\\n"); } else { printf("parent returned from fork\\n"); } exit(0); }
1
#include <pthread.h> extern char **environ; static pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init( void ) { pthread_mutexattr_t attr; pthread_mutexattr_init( &attr ); pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE ); pthread_mutex_init( &env_mutex, &attr ); pthread_mutexattr_destroy( &attr ); } int getenv_r( const char *env_name, char *env_value, int env_value_len_limit ) { int i, len, old_len; pthread_once( &init_done, thread_init ); len = strlen( env_name ); pthread_mutex_lock( &env_mutex ); for ( i = 0; environ[i] != 0; i++ ) { if ( (strncmp( env_name, environ[i], len ) == 0) && (environ[i][len] == '=') ) { old_len = strlen( &environ[ i ][ len+1 ] ); if ( old_len >= buflen ) { pthread_mutex_unlock( &env_mutex ); return ENOSPC; } strcpy( env_value, &environ[ i ][ len+1 ] ); pthread_mutex_unlock( &env_mutex ); return 0; } } pthread_mutex_unlock( &env_mutex ); return ENOENT; } int main( void ) { return 0; }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void pthread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int putenv_r(char *envbuf) { int i; int len; pthread_once(&init_done, pthread_init); for (i = 0; envbuf[i] != '\\0'; i++) { if (envbuf[i] == '=') break; } if (envbuf[i] == '\\0') { return 1; } pthread_mutex_lock(&env_mutex); len = i; for (i = 0; environ[i] != 0; i++) { if ((strncmp(envbuf, environ[i], len) == 0) && (environ[i][len] == '=')) { if (strcmp(&envbuf[len+1], &environ[i][len+1]) == 0) { return 0; } environ[i] = envbuf; return 0; } } if (environ[i] == 0) { environ[i] = envbuf; environ[i+1] = 0; } pthread_mutex_unlock(&env_mutex); return 0; } void *thd(void *arg) { putenv_r((char *)arg); pthread_exit((void *)0); } int main(void) { pthread_t tid1, tid2, tid3, tid4; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_create(&tid1, &attr, thd, (void *)"SHELL=/bin/sh"); pthread_create(&tid2, &attr, thd, (void *)"SHELL=/bin/bash"); pthread_create(&tid3, &attr, thd, (void *)"SHELL=/usr/bin/rsh"); pthread_create(&tid4, &attr, thd, (void *)"SHELL=/bin/ksh"); sleep(2); pthread_attr_destroy(&attr); pthread_mutex_destroy(&env_mutex); printf("SHELL = %s\\n", getenv("SHELL")); return 0; }
1
#include <pthread.h> struct timespec start,finish; double elapsed; pthread_mutex_t forks; pthread_cond_t freed[50]; int NoPhil; int *timed; char *fork_state; int display(); int pickup_fork(int phil); int return_fork(int phil); void *activity(int phil); int main() { char choice='Y'; int err_mutex,err_cond,err_thread; printf("Enter the number of philosophers :"); scanf("%d",&NoPhil); pthread_t philosopher[NoPhil]; fork_state=malloc(NoPhil*sizeof(char)); timed=malloc(NoPhil*sizeof(int)); while(choice=='Y') { for(int i=0;i<NoPhil;i++) { err_cond=pthread_cond_init(&freed[i],0); if(err_cond) { printf("Condition initialization failed\\n"); } } err_mutex=pthread_mutex_init(&forks,0); if(err_mutex) { printf("Mutex initialization failed\\n"); } clock_gettime(CLOCK_MONOTONIC, &start); for(int i=0;i<NoPhil;i++) { fork_state[i]='F'; err_thread=pthread_create(&philosopher[i],0,(void*)activity,(int*)i); if(err_thread) { printf("Thread creation failed\\n"); } } for(int i=0;i<NoPhil;i++) { pthread_join(philosopher[i],0); } clock_gettime(CLOCK_MONOTONIC, &finish); elapsed+=(finish.tv_sec-start.tv_sec); printf("Do you want to continue(Y/N):"); scanf(" %c",&choice); } printf(" --Summary--\\n"); display(); return 0; } void *activity(int phil) { int k; printf("Philosopher[%d] -> Thinking\\n",phil); sleep(2); pickup_fork(phil); printf("Philosopher[%d] -> Eating\\n",phil); k=rand()%3+1; sleep(k); timed[phil]=timed[phil]+k; return_fork(phil); printf("Philosopher[%d] -> Thinking\\n",phil); } int pickup_fork(int phil) { pthread_mutex_lock(&forks); printf("Philosopher[%d] -> Hungry\\n",phil); while(fork_state[(phil)%NoPhil]!='F') { pthread_cond_wait(&freed[(phil)%NoPhil],&forks); } fork_state[phil%NoPhil]='U'; while(fork_state[(phil+1)%NoPhil]!='F') { pthread_cond_wait(&freed[(phil+1)%NoPhil],&forks); } fork_state[(phil+1)%NoPhil]='U'; printf("Philosopher[%d] has taken fork[%d] and fork[%d]\\n",phil,(phil+1)%NoPhil,(phil)%NoPhil); pthread_mutex_unlock(&forks); return 0; } int return_fork(int phil) { pthread_mutex_lock(&forks); fork_state[phil%NoPhil]='F'; pthread_cond_signal(&freed[(phil)%NoPhil]); fork_state[(phil+1)%NoPhil]='F'; pthread_cond_signal(&freed[(phil+1)%NoPhil]); printf("Philosopher[%d] has put down fork[%d] and fork[%d]\\n",phil,(phil+1)%NoPhil,(phil)%NoPhil); pthread_mutex_unlock(&forks); return 0; } int display() { printf("No of Philosophers = %d\\n",NoPhil); for(int i=0;i<NoPhil;i++) { printf("Total time Philosopher[%d] has eaten =%d seconds\\n",i,timed[i]); } printf("Total time taken = %f seconds\\n",elapsed); return 0; }
0
#include <pthread.h> static struct psample_context *context; static const char *my_addr = "127.0.0.1"; static int port = 6666; static int srv_port; static const char *srv_ip; static char *fprefix; static pthread_mutex_t neigh_lock; static void cmdline_parse(int argc, char *argv[]) { int o; while ((o = getopt(argc, argv, "s:p:i:P:I:")) != -1) { switch(o) { case 'p': srv_port = atoi(optarg); break; case 'i': srv_ip = strdup(optarg); break; case 'P': port = atoi(optarg); break; case 'I': my_addr = iface_addr(optarg); break; case 's': fprefix = strdup(optarg); break; default: fprintf(stderr, "Error: unknown option %c\\n", o); exit(-1); } } } static struct nodeID *init(void) { struct nodeID *myID; myID = net_helper_init(my_addr, port, ""); if (myID == 0) { fprintf(stderr, "Error creating my socket (%s:%d)!\\n", my_addr, port); return 0; } context = psample_init(myID, 0, 0, "protocol=cyclon"); return myID; } static void *cycle_loop(void *p) { int done = 0; int cnt = 0; while (!done) { const int tout = 1; pthread_mutex_lock(&neigh_lock); psample_parse_data(context, 0, 0); pthread_mutex_unlock(&neigh_lock); if (cnt % 10 == 0) { const struct nodeID **neighbours; int n, i; pthread_mutex_lock(&neigh_lock); neighbours = psample_get_cache(context, &n); printf("I have %d neighbours:\\n", n); for (i = 0; i < n; i++) { printf("\\t%d: %s\\n", i, node_addr(neighbours[i])); } fflush(stdout); if (fprefix) { FILE *f; char fname[64]; sprintf(fname, "%s-%d.txt", fprefix, port); f = fopen(fname, "w"); for (i = 0; i < n; i++) { if (f) fprintf(f, "%d\\t\\t%d\\t%s\\n", port, i, node_addr(neighbours[i])); } fclose(f); } pthread_mutex_unlock(&neigh_lock); } cnt++; sleep(tout); } return 0; } static void *recv_loop(void *p) { struct nodeID *s = p; int done = 0; static uint8_t buff[1024]; while (!done) { int len; struct nodeID *remote; len = recv_from_peer(s, &remote, buff, 1024); pthread_mutex_lock(&neigh_lock); psample_parse_data(context, buff, len); pthread_mutex_unlock(&neigh_lock); nodeid_free(remote); } return 0; } int main(int argc, char *argv[]) { struct nodeID *my_sock; pthread_t cycle_id, recv_id; cmdline_parse(argc, argv); my_sock = init(); if (my_sock == 0) { return -1; } if (srv_port != 0) { struct nodeID *knownHost; knownHost = create_node(srv_ip, srv_port); if (knownHost == 0) { fprintf(stderr, "Error creating knownHost socket (%s:%d)!\\n", srv_ip, srv_port); return -1; } psample_add_peer(context, knownHost, 0, 0); } pthread_mutex_init(&neigh_lock, 0); pthread_create(&recv_id, 0, recv_loop, my_sock); pthread_create(&cycle_id, 0, cycle_loop, my_sock); pthread_join(recv_id, 0); pthread_join(cycle_id, 0); return 0; }
1
#include <pthread.h> sem_t sem; int semVal; pthread_mutex_t mut; pthread_cond_t condC; pthread_cond_t condA; void utiliserPont(int type){ if (type == 1){ sem_wait(&sem); sem_getvalue(&sem, &semVal); } else{ int i = 0; for(i=0; i<3; i++){ sem_wait(&sem); sem_getvalue(&sem, &semVal); } } } void libererPont(int type){ if (type == 1){ sem_post(&sem); sem_getvalue(&sem, &semVal); } else{ int i = 0; for(i=0; i<3; i++){ sem_post(&sem); sem_getvalue(&sem, &semVal); } } } void* voiture(void* arg){ printf("Voiture %d en attente d'un coté du pont !\\n", (int)pthread_self()); sleep(1); pthread_mutex_lock(&mut); if (semVal != 0){ pthread_cond_wait(&condA, &mut); pthread_mutex_unlock(&mut); utiliserPont(1); printf("Voiture %d utilise le pont !\\n", (int)pthread_self()); sleep(3); libererPont(1); } if (semVal == 3) pthread_cond_broadcast(&condC); printf("Voiture %d a fini d'utiliser le pont !\\n\\n", (int)pthread_self()); sleep(1); pthread_exit(0); } void* camion(void* arg){ printf("Camion %d en attente d'un coté du pont !\\n", (int)pthread_self()); sleep(1); pthread_mutex_lock(&mut); if(semVal != 0){ pthread_cond_wait(&condC, &mut); utiliserPont(2); printf("Camion %d utilise le pont !\\n", (int)pthread_self()); sleep(3); libererPont(2); } pthread_mutex_unlock(&mut); if (semVal == 3) pthread_cond_broadcast(&condA); printf("Camion %d a fini d'utiliser le pont !\\n\\n", (int)pthread_self()); sleep(1); pthread_exit(0); } int main(){ pthread_t v1, v2, v3, v4; pthread_t c1, c2, c3, c4; sem_init(&sem, 0, 3); sem_getvalue(&sem, &semVal); pthread_mutex_init(&mut, 0); pthread_cond_init(&condC, 0); pthread_cond_init(&condA, 0); pthread_create(&v1, 0, voiture, 0); pthread_create(&v2, 0, voiture, 0); pthread_create(&v3, 0, voiture, 0); pthread_create(&v4, 0, voiture, 0); pthread_create(&c1, 0, camion, 0); pthread_create(&c2, 0, camion, 0); pthread_create(&c3, 0, camion, 0); pthread_create(&c4, 0, camion, 0); sleep(3); pthread_cond_broadcast(&condC); pthread_join(v1, 0); pthread_join(v2, 0); pthread_join(v3, 0); pthread_join(v4, 0); pthread_join(c1, 0); pthread_join(c2, 0); pthread_join(c3, 0); pthread_join(c4, 0); printf("fin main\\n"); pthread_exit(0); }
0
#include <pthread.h> static char wbuff[P4_NET_SERVER_BUFFER_SIZE_WRITE]; pthread_mutex_t wbuffmutex; int server_net_game_curplay(struct p4_server_game *game) { static int start = 1; struct p4_net_protocol_match *proto; char *ptr; int rbufflen; if (start) { pthread_mutex_init(&wbuffmutex,0); start = 0; } if ((rbufflen = read(game->pcur->sockfd,game->rbuff,sizeof(game->rbuff))) <= 0) goto err; game->rbuff[rbufflen] = 0; if (P4_NET_PROTO_CHECK(game->rbuff,ptr,proto,P4_NET_PROTO_COUP_COL)) { if (P4_NET_PROTO_CHECK(game->rbuff,ptr,proto,P4_NET_PROTO_QUITTE)) { WRITES(game->pcur->sockfd,"error: COUP COL expected\\n"); fprintf(stderr,"error: COUP COL\\n"); goto err; } else { if (game->pcur == game->pred) { fprintf(stdout,"client %s leaved the challenge\\n", game->pblack->nick); write(game->pblack->sockfd,game->rbuff,rbufflen); } else { fprintf(stdout,"client %s leaved the challenge\\n", game->pred->nick); write(game->pred->sockfd,game->rbuff,rbufflen); } return -2; } } goto out; err: return -1; out: return atoi(ptr); } int server_net_game_notify_play( struct p4_server_game *g, int x, int y) { struct p4_net_protocol_match *proto; char *ptr; pthread_mutex_lock(&wbuffmutex); ptr = wbuff; proto = net_proto_get_proto_id(P4_NET_PROTO_UPDATE_PION); ptr += sprintf(ptr,"%s %c %d %d", proto->name, token_get_char_value(g->pcur->color),x,y); *ptr++ = 0; write(g->pred->sockfd,wbuff,ptr - wbuff); write(g->pblack->sockfd,wbuff,ptr - wbuff); pthread_mutex_unlock(&wbuffmutex); return 0; } int server_net_game_notify_curinval(struct p4_server_game *g) { struct p4_net_protocol_match *proto; char *ptr; pthread_mutex_lock(&wbuffmutex); ptr = wbuff; proto = net_proto_get_proto_id(P4_NET_PROTO_UPDATE_COUP_INVALIDE); ptr += sprintf(ptr,"%s", proto->name); *ptr++ = 0; write(g->pcur->sockfd,wbuff,ptr - wbuff); pthread_mutex_unlock(&wbuffmutex); return 0; } int server_net_game_notify_drawn(struct p4_server_game *g) { struct p4_net_protocol_match *proto; char *ptr; pthread_mutex_lock(&wbuffmutex); ptr = wbuff; proto = net_proto_get_proto_id(P4_NET_PROTO_UPDATE_NUL); ptr += sprintf(ptr,"%s", proto->name); *ptr++ = 0; write(g->pred->sockfd,ptr,wbuff - ptr); write(g->pblack->sockfd,ptr,wbuff - ptr); pthread_mutex_unlock(&wbuffmutex); return 0; } int server_net_game_notify_win( struct p4_server_game *g, int x, int y, enum p4_game_win_dir dir) { struct p4_net_protocol_match *proto; char *ptr; pthread_mutex_lock(&wbuffmutex); ptr = wbuff; proto = net_proto_get_proto_id(P4_NET_PROTO_UPDATE_GAGNE); ptr += sprintf(ptr,"%s %c %d %d %c", proto->name, token_get_char_value(g->pcur->color),x,y, p4_get_win_dir_char_value(dir)); *ptr++ = 0; write(g->pred->sockfd,wbuff,ptr - wbuff); write(g->pblack->sockfd,wbuff,ptr - wbuff); pthread_mutex_unlock(&wbuffmutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cnd = PTHREAD_COND_INITIALIZER; int toexit = 0; void * start_thread(void * arg) { pthread_mutex_lock(&mtx); while(0 == toexit) { do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("wait..."); printf("\\n"); }while(0); pthread_cond_wait(&cnd, &mtx); } pthread_mutex_unlock(&mtx); do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("get toexit, and exit"); printf("\\n"); }while(0); return 0; } int main(int argc, char * argv[]) { pthread_t pt; int i = 0; for(i = 0; i < 5; i++) { if(0 != pthread_create(&pt, 0, start_thread, 0)) { do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("create thread faild"); printf("\\n"); }while(0); return -1; } } while(1) { if(0 != pthread_kill(pt, 0)) { do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("thread [%ld] not exist any more", pt); printf("\\n"); }while(0); break; } do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("\\033[0;32mEnter to continue, 'q' or 'Q' to quit :\\033[0m "); printf("\\n"); }while(0); char c = getchar(); pthread_mutex_lock(&mtx); if('Q' == c || 'q' == c) { toexit = 1; do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("set toexit"); printf("\\n"); }while(0); } pthread_mutex_unlock(&mtx); int err = 0; err = pthread_cond_broadcast(&cnd); if(0 != err) { do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("send broadcast faild"); printf("\\n"); }while(0); } else { do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("send broadcast success"); printf("\\n"); }while(0); } usleep(10000); } void * st = 0; pthread_join(pt, &st); do{ printf("ptid [%ld] -- ", (long int)pthread_self()); printf("main over"); printf("\\n"); }while(0); return 0; }
0
#include <pthread.h> { int sfd; struct wait_queue_struct *pnext; }wait_queue,*p_wait_queue; { int sfd; struct ready_queue_struct *pnext; }ready_queue,*p_ready_queue; p_wait_queue wait_phead; p_wait_queue wait_ptail; p_ready_queue ready_phead; p_ready_queue ready_ptail; pthread_mutex_t mutex; pthread_mutex_t mutex_epoll_wait; pthread_cond_t cond; int sfd; int new_fd; int epfd_accept; int epfd_ready; int epfd_wait; pthread_t pthid[5]; void epoll_add(int epfd,int fd) { struct epoll_event event; event.events=EPOLLIN; event.data.fd=fd; epoll_ctl(epfd,EPOLL_CTL_ADD,sfd,&event); printf("epoll_add success!\\n"); } void epoll_delete(int epfd,int fd) { struct epoll_event event; event.events=EPOLLIN; event.data.fd=fd; epoll_ctl(epfd,EPOLL_CTL_DEL,sfd,&event); printf("epoll_delete success!\\n"); } void queue_init() { ready_phead=(p_ready_queue)calloc(0,sizeof(ready_queue)); ready_ptail=ready_phead; wait_phead=(p_wait_queue)calloc(0,sizeof(wait_queue)); wait_ptail=wait_phead; printf("queue_init success!\\n"); } void ready_enqueue(int fd) { p_ready_queue p; p=(p_ready_queue)calloc(0,sizeof(ready_queue)); p->sfd=fd; p->pnext=ready_ptail->pnext; ready_ptail->pnext=p; ready_ptail=p; pthread_cond_signal(&cond); } void ready_dequeue(int *fd) { p_ready_queue p; p=ready_phead->pnext; if(0==p) { printf("empty queue\\n"); return ; } ready_phead->pnext=p->pnext; *fd=p->sfd; if(p==ready_ptail) { ready_ptail=ready_phead; } free(p); } void ready_queue_delete(p_ready_queue *p,p_ready_queue q) { q->pnext=(*p)->pnext; free (*p); (*p)=q->pnext; if((*p)==ready_ptail) { ready_ptail=q; } } void wait_enqueue(int fd) { p_wait_queue p; p=(p_wait_queue)calloc(0,sizeof(wait_queue)); p->sfd=fd; p->pnext=wait_ptail->pnext; wait_ptail->pnext=p; wait_ptail=p; } void wait_dequeue(int *fd) { p_wait_queue p; p=wait_phead->pnext; if(0==p) { printf("empty queue\\n"); return ; } wait_phead->pnext=p->pnext; *fd=p->sfd; if(wait_ptail==p) { wait_ptail=wait_phead; } free(p); } void wait_queue_delete(p_wait_queue *p,p_wait_queue q) { q->pnext=(*p)->pnext; free (*p); (*p)=q->pnext; if((*p)==wait_ptail) { wait_ptail=q; } } void *ticket_server(void *v) { while(1){} lable_begin: pthread_mutex_lock(&mutex); if(0==ready_phead->pnext) { pthread_cond_wait(&cond,&mutex); } int new_fd; ready_dequeue(&new_fd); pthread_mutex_unlock(&mutex); int buf; buf=0; int ret; ret=send(new_fd,(void*)&buf,sizeof(buf),0); if(-1==ret) { goto lable_begin; } printf("new_fd=%d login\\n",new_fd); sleep(10); printf("new_fd=%d logout\\n",new_fd); goto lable_begin; } void *ticket_ready(void *v) { p_ready_queue p; p_ready_queue q; int ret; int i; while(1) { p=ready_phead->pnext; q=ready_phead; i=1; while(p) { printf("temp:\\n"); ret=send(p->sfd,(void*)&i,sizeof(i),0); printf("ret=%d i=%d\\n",ret,i); if(-1==ret) { ready_queue_delete(&p,q); continue; } p=p->pnext; q=q->pnext; i++; } sleep(1); } } void *ticket_wait(void *v) { int fd; struct epoll_event event; int event_len; int ret; int temp; while(1) { event_len=sizeof(event); memset(&event,0,event_len); pthread_mutex_lock(&mutex_epoll_wait); printf("lock mmm\\n"); ret=epoll_wait(epfd_wait,&event,event_len,1000); pthread_mutex_unlock(&mutex_epoll_wait); if(ret==0) { continue; } fd=event.data.fd; recv(fd,(void*)&temp,sizeof(temp),0); printf("recv=%d\\n",temp); wait_dequeue(&fd); ready_enqueue(fd); epoll_add(epfd_ready,fd); epoll_delete(epfd_wait,fd); } } void pthread_init() { int ret; ret=pthread_mutex_init(&mutex,0); if(0!=ret) { printf("pthread_mutex_init errno=%d\\n",ret); exit(-1); } ret=pthread_mutex_init(&mutex_epoll_wait,0); if(0!=ret) { printf("pthread_mutex_init mutex_epoll_wait errno=%d\\n",ret); exit(-1); } ret=pthread_cond_init(&cond,0); if(0!=ret) { printf("pthread_cond_init errno=%d\\n",ret); exit(-1); } pthread_t pthid_ready; ret=pthread_create(&pthid_ready,0,ticket_ready,0); if(-1==ret) { printf("pthread_create pthid_ready errno=%d\\n",ret); exit(-1); } pthread_t pthid_wait; ret=pthread_create(&pthid_wait,0,ticket_wait,0); if(-1==ret) { printf("pthread_create pthid_wait errno=%d\\n",ret); exit(-1); } int i; for(i=0;i<5;i++) { ret=pthread_create(&pthid[i],0,ticket_server,0); if(0!=ret) { printf("pthread_create pthin[%d] errno=%d\\n",i,ret); exit(-1); } } printf("pthread_init success!\\n"); } void tcp_init() { sfd=socket(AF_INET,SOCK_STREAM,0); if(-1==sfd) { perror("socket"); exit(-1); } int ret; struct sockaddr_in addr; addr.sin_family=AF_INET; addr.sin_addr.s_addr=inet_addr("192.168.1.114"); addr.sin_port=htons(2000); ret=bind(sfd,(struct sockaddr*)&addr,sizeof(struct sockaddr)); if(-1==ret) { perror("bind"); exit(-1); } ret=listen(sfd,100); if(-1==ret) { perror("listen"); exit(-1); } printf("tcp_init success!\\n"); } void epoll_init() { epfd_accept=epoll_create(1); epoll_add(epfd_accept,sfd); epfd_wait=epoll_create(1); epfd_ready=epoll_create(1); } int main() { signal(SIGPIPE,SIG_IGN); queue_init(); pthread_init(); tcp_init(); epoll_init(); int ret; struct epoll_event event; int event_len; struct sockaddr_in addr; int addr_len; int i=0; while(1) { event_len=sizeof(event); memset(&event,0,event_len); addr_len=sizeof(addr); memset(&addr,0,addr_len); ret=epoll_wait(epfd_accept,&event,event_len,-1); if(ret>0) { new_fd=accept(sfd,(struct sockaddr*)&addr,&addr_len); if(-1==new_fd) { perror("accept"); exit(-1); } printf("new login\\n"); wait_enqueue(new_fd); printf("wait_queue\\n"); pthread_mutex_lock(&mutex_epoll_wait); printf("lock mu\\n"); epoll_add(epfd_wait,new_fd); pthread_mutex_unlock(&mutex_epoll_wait); } } }
1
#include <pthread.h> static struct logdb_queue_node* logdb_queue_node_new(void* value); static int logdb_queue_node_destroy(struct logdb_queue_node** p_node); static struct logdb_queue_node* logdb_queue_node_new(void* value){ struct logdb_queue_node* new_node = (struct logdb_queue_node *) malloc(sizeof(*new_node)); if (0 == new_node){ printf("malloc new_node failed in logdb_queue_node_new\\n"); return 0; } new_node->value = value; new_node->next_node = 0; return new_node; } static int logdb_queue_node_destroy(struct logdb_queue_node** p_node){ if (0 == p_node){ printf("p_node is NULL in logdb_queue_node_destroy\\n"); return -1; } struct logdb_queue_node* node = *p_node; if (0 == node){ printf("node is NULL in logdb_queue_node_destroy\\n"); return -1; } node->value = 0; node->next_node = 0; free(node); *p_node = 0; return 0; } struct logdb_queue* logdb_queue_new(char* name){ struct logdb_queue* new_queue = (struct logdb_queue*) malloc(sizeof(*new_queue)); if (0 == new_queue){ printf("malloc new_queue failed in logdb_queue_new\\n"); return 0; } strncpy(new_queue->name, name, strlen(name)); pthread_mutex_init(&new_queue->mutex, 0); new_queue->head = 0; new_queue->tail = 0; new_queue->size = 0; return new_queue; } int logdb_queue_destroy(struct logdb_queue** p_queue){ if (0 == p_queue){ printf("p_queue is NULL in logdb_queue_destory\\n"); return -1; } struct logdb_queue* queue = *p_queue; if (0 == queue){ printf("queue is NULL in logdb_queue_destory\\n"); return -1; } while (queue->head != 0) logdb_queue_pop(queue); free(queue); *p_queue = 0; return 0; } int logdb_queue_is_empty(struct logdb_queue* queue){ if (0 == queue){ printf("queue is NULL in logdb_queue_is_empty\\n"); return -1; } if (0 == queue->size) return 1; else return 0; } int logdb_queue_push(struct logdb_queue* queue, void* value){ if (0 == queue){ printf("queue is NULL in logdb_queue_push\\n"); return -1; } if (0 == value){ printf("value is NULL in logdb_queue_push\\n"); return -1; } struct logdb_queue_node* new_node = logdb_queue_node_new(value); if (0 == new_node){ printf("logdb_queue_node_new failed\\n"); return -1; } pthread_mutex_lock(&queue->mutex); if (0 == queue->head){ queue->head = new_node; queue->tail = new_node; queue->size++; } else { queue->tail->next_node = new_node; queue->tail = new_node; queue->size++; } pthread_mutex_unlock(&queue->mutex); return 0; } void* logdb_queue_pop(struct logdb_queue* queue){ if (0 == queue){ printf("queue is NULL in logdb_queue_pop\\n"); return 0; } void* value = 0; if (0 == queue->size){ } else { pthread_mutex_lock(&queue->mutex); struct logdb_queue_node *dead_node = queue->head; queue->head = queue->head->next_node; if (0 == queue->head) queue->tail = 0; queue->size--; pthread_mutex_unlock(&queue->mutex); value = dead_node->value; logdb_queue_node_destroy(&dead_node); } return value; }
0
#include <pthread.h> extern pthread_mutex_t httpd_mutex; extern int created_httpd_threads; extern int current_httpd_threads; void thread_httpd(void *args) { void **params; httpd *webserver; request *r; int serialnum; pthread_mutex_lock(&httpd_mutex); current_httpd_threads++; pthread_mutex_unlock(&httpd_mutex); params = (void **)args; webserver = *params; r = *(params + 1); serialnum = *((int *)*(params + 2)); free(*(params + 2)); free(params); if (httpdReadRequest(webserver, r) == 0) { debug(LOG_DEBUG, "Thread %d calling httpdProcessRequest() for %s", serialnum, r->clientAddr); httpdProcessRequest(webserver, r); debug(LOG_DEBUG, "Thread %d returned from httpdProcessRequest() for %s", serialnum, r->clientAddr); } else { debug(LOG_DEBUG, "Thread %d: No valid request received from %s", serialnum, r->clientAddr); } debug(LOG_DEBUG, "Thread %d ended request from %s", serialnum, r->clientAddr); httpdEndRequest(r); pthread_mutex_lock(&httpd_mutex); current_httpd_threads--; pthread_mutex_unlock(&httpd_mutex); }
1
#include <pthread.h> int brashno = 1000; int masa[4]; pthread_mutex_t lock; void* Mama(){ int position = 0; while(brashno) { int mama_get_brashno = rand() % 100 + 1; if(mama_get_brashno > brashno){ mama_get_brashno = brashno; } brashno -= mama_get_brashno; while(masa[position] == 1){ int wtime = rand() % 100 + 1; usleep(wtime*1000); } printf("MAMA PRAI PASTI4KA!\\n"); usleep(mama_get_brashno*1000); pthread_mutex_lock(&lock); masa[position] = 1; pthread_mutex_unlock(&lock); if(position == 3) { position = 0; } else { position++; } } } void* Ivan(){ int position = 0; while(brashno){ while(masa[position] == 0) { int wtime = rand() % 100 + 1; usleep(wtime*1000); } pthread_mutex_lock(&lock); masa[position] =0; pthread_mutex_unlock(&lock); printf("IVAN4O LAPA PASTI4KAAA!\\n"); if(position == 3) { position = 0; } else { position++; } } } int main(){ pthread_mutex_init(&lock,0); pthread_t thread[2]; pthread_create(&thread[0],0,Mama,0); pthread_create(&thread[1],0,Ivan,0); pthread_join(thread[1],0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> enum pipe_funcs { ADD1, MUL2, READER, WRITER, FREER, }; struct stage { struct stage *next; pthread_cond_t *cv; pthread_mutex_t *mut; char *data; unsigned int size; int func; int last; }; unsigned int do_work(char *data, unsigned int size, int func); void *thr_func(struct stage *S) { unsigned int size = 0; int last = 0; unsigned int ret; char *data = 0; while (!last) { pthread_mutex_lock(S->mut); while (!S->data) pthread_cond_wait(S->cv,S->mut); size = S->size; data = S->data; last = S->last; S->data = 0; S->size = 0; pthread_cond_signal(S->cv); pthread_mutex_unlock(S->mut); if ((ret = do_work(data,size,S->func)) < size) { size = ret; pthread_mutex_lock(S->mut); last = S->last = 1; pthread_mutex_unlock(S->mut); } if (S->next) { pthread_mutex_lock(S->next->mut); while (S->next->data) pthread_cond_wait(S->next->cv,S->next->mut); S->next->size = size; S->next->data = data; S->next->last = last; pthread_cond_signal(S->next->cv); pthread_mutex_unlock(S->next->mut); } } pthread_mutex_lock(S->mut); S->data = 0; S->size = 0; pthread_cond_signal(S->cv); pthread_mutex_unlock(S->mut); return 0; } FILE *inFile; FILE *outFile; unsigned int do_work(char *data, unsigned int size, int func) { unsigned int ret; int i; switch(func) { case ADD1: for (i = 0; i < size; i++) data[i] = data[i] + 1; ret = size; break; case MUL2: for (i = 0; i < size; i++) data[i] = data[i] * 2; ret = size; break; case READER: ret = fread(data,sizeof(char),size,inFile); break; case WRITER: if (size) fwrite(data,sizeof(char),size,outFile); ret = size; break; case FREER: if (data) free(data); ret = size; break; default: ret = size; break; } return ret; } struct stage *make_stage(struct stage *next, int func) { struct stage *new = malloc(sizeof(struct stage)); new->next = next; new->cv = malloc(sizeof(pthread_cond_t)); new->mut = malloc(sizeof(pthread_mutex_t)); new->data = 0; new->size = 0; new->func = func; new->last = 0; pthread_mutex_init(new->mut,0); pthread_cond_init(new->cv,0); return new; } int main() { pthread_t tid[5]; int i; struct stage *freestage = make_stage(0,FREER); struct stage *writestage = make_stage(freestage,WRITER); struct stage *add1stage = make_stage(writestage,ADD1); struct stage *mul2stage = make_stage(add1stage,MUL2); struct stage *readstage = make_stage(mul2stage,READER); inFile = fopen("inFile.txt","r"); outFile = fopen("outFile.txt","w"); pthread_create(&tid[0],0,thr_func,readstage); pthread_create(&tid[1],0,thr_func,mul2stage); pthread_create(&tid[2],0,thr_func,add1stage); pthread_create(&tid[3],0,thr_func,writestage); pthread_create(&tid[4],0,thr_func,freestage); while (1) { pthread_mutex_lock(readstage->mut); while (readstage->data) pthread_cond_wait(readstage->cv,readstage->mut); if (readstage->last) { pthread_mutex_unlock(readstage->mut); break; } readstage->size = 10000; readstage->data = malloc(10000 * sizeof(char)); pthread_cond_signal(readstage->cv); pthread_mutex_unlock(readstage->mut); } for(i = 0; i < 5; i++) { if (pthread_join(tid[i],0) != 0) printf("joining on %d failed.\\n", i); } return 0; }
1
#include <pthread.h> struct philosopher { pthread_t threadHandle; pthread_mutex_t *leftFork; pthread_mutex_t *rightFork; int threadResponse; char name[15]; }; void *supper(void * args) { struct philosopher* philo = (struct philosopher*)args; int response = 0; int action = 0; int tries; int justAte = 1; while(1) { if(justAte) { action = 1 + rand() % 20; printf("%s is thinking for %d seconds.\\n", philo->name, action); sleep(action); justAte = 0; } response = pthread_mutex_lock(philo->leftFork); tries = 2; while(1) { if(tries > 0) { response = pthread_mutex_trylock(philo->rightFork); tries--; } else { pthread_mutex_unlock(philo->leftFork); break; } if(!response) { action = 2 + rand() % 8; printf("%s has grabbed two forks and is eatting for %d seconds.\\n", philo->name, action); sleep(action); pthread_mutex_unlock(philo->leftFork); pthread_mutex_unlock(philo->rightFork); printf("%s has returned the forks.\\n", philo->name); tries = 2; justAte = 1; break; } } } return 0; } void setup() { int i, response; pthread_mutex_t forks[5]; struct philosopher philosophers[5]; for(i = 0; i < 5; i++) { response = pthread_mutex_init(&forks[i], 0); if(response) { printf("Failed to create mutex. Exiting...."); exit(1); } } strcpy(philosophers[0].name, "Abe"); strcpy(philosophers[1].name,"Bob"); strcpy(philosophers[2].name, "Carly"); strcpy(philosophers[3].name, "Daruma"); strcpy(philosophers[4].name,"Flume"); for(i = 0; i < 5; i++) { philosophers[i].leftFork = &forks[i]; philosophers[i].rightFork = &forks[(i + 1) % 5]; pthread_attr_t attr; pthread_attr_init (&attr); philosophers[i].threadResponse = pthread_create(&philosophers[i].threadHandle, &attr, supper, &philosophers[i]); } for(i = 0; i < 5; i++) { if(!philosophers[i].threadResponse && pthread_join(philosophers[i].threadHandle, 0)) { printf("Failed to join thread for %s. Exiting...", philosophers[i].name); exit(1); } } } int main(int argc, char** argv) { setup(); return 0; }
0
#include <pthread.h> struct threadpool* threadpool_init(int thread_num, int queue_max_num) { struct threadpool *pool = 0; do { pool = (struct threadpool *)malloc(sizeof(struct threadpool)); if (0 == pool) { printf("failed to malloc threadpool!\\n"); break; } pool->thread_num = thread_num; pool->queue_max_num = queue_max_num; pool->queue_cur_num = 0; pool->head = 0; pool->tail = 0; if (pthread_mutex_init(&(pool->mutex), 0)) { printf("failed to init mutex!\\n"); break; } if (pthread_cond_init(&(pool->queue_empty), 0)) { printf("failed to init queue_empty!\\n"); break; } if (pthread_cond_init(&(pool->queue_not_empty), 0)) { printf("failed to init queue_not_empty!\\n"); break; } if (pthread_cond_init(&(pool->queue_not_full), 0)) { printf("failed to init queue_not_full!\\n"); break; } pool->pthreads = (pthread_t *)malloc(sizeof(pthread_t) * thread_num); if (0 == pool->pthreads) { printf("failed to malloc pthreads!\\n"); break; } pool->queue_close = 0; pool->pool_close = 0; int i; for (i = 0; i < pool->thread_num; ++i) { pthread_create(&(pool->pthreads[i]), 0, threadpool_function, (void *)pool); } return pool; } while (0); return 0; } int threadpool_add_job(struct threadpool* pool, void* (*callback_function)(void *arg), void *arg) { assert(pool != 0); assert(callback_function != 0); assert(arg != 0); pthread_mutex_lock(&(pool->mutex)); while ((pool->queue_cur_num == pool->queue_max_num) && !(pool->queue_close || pool->pool_close)) { pthread_cond_wait(&(pool->queue_not_full), &(pool->mutex)); } if (pool->queue_close || pool->pool_close) { pthread_mutex_unlock(&(pool->mutex)); return -1; } struct job *pjob =(struct job*) malloc(sizeof(struct job)); if (0 == pjob) { pthread_mutex_unlock(&(pool->mutex)); return -1; } pjob->callback_function = callback_function; pjob->arg = arg; pjob->next = 0; if (pool->head == 0) { pool->head = pool->tail = pjob; pthread_cond_broadcast(&(pool->queue_not_empty)); } else { pool->tail->next = pjob; pool->tail = pjob; } pool->queue_cur_num++; pthread_mutex_unlock(&(pool->mutex)); return 0; } void* threadpool_function(void* arg) { struct threadpool *pool = (struct threadpool*)arg; struct job *pjob = 0; while (1) { pthread_mutex_lock(&(pool->mutex)); while ((pool->queue_cur_num == 0) && !pool->pool_close) { pthread_cond_wait(&(pool->queue_not_empty), &(pool->mutex)); } if (pool->pool_close) { pthread_mutex_unlock(&(pool->mutex)); pthread_exit(0); } pool->queue_cur_num--; pjob = pool->head; if (pool->queue_cur_num == 0) { pool->head = pool->tail = 0; } else { pool->head = pjob->next; } if (pool->queue_cur_num == 0) { pthread_cond_signal(&(pool->queue_empty)); } if (pool->queue_cur_num == pool->queue_max_num - 1) { pthread_cond_broadcast(&(pool->queue_not_full)); } pthread_mutex_unlock(&(pool->mutex)); (*(pjob->callback_function))(pjob->arg); free(pjob); pjob = 0; } } int threadpool_destroy(struct threadpool *pool) { assert(pool != 0); pthread_mutex_lock(&(pool->mutex)); if (pool->queue_close || pool->pool_close) { pthread_mutex_unlock(&(pool->mutex)); return -1; } pool->queue_close = 1; while (pool->queue_cur_num != 0) { pthread_cond_wait(&(pool->queue_empty), &(pool->mutex)); } pool->pool_close = 1; pthread_mutex_unlock(&(pool->mutex)); pthread_cond_broadcast(&(pool->queue_not_empty)); pthread_cond_broadcast(&(pool->queue_not_full)); int i; for (i = 0; i < pool->thread_num; ++i) { pthread_join(pool->pthreads[i], 0); } pthread_mutex_destroy(&(pool->mutex)); pthread_cond_destroy(&(pool->queue_empty)); pthread_cond_destroy(&(pool->queue_not_empty)); pthread_cond_destroy(&(pool->queue_not_full)); free(pool->pthreads); struct job *p; while (pool->head != 0) { p = pool->head; pool->head = p->next; free(p); } free(pool); return 0; }
1
#include <pthread.h> static FILE *writefp; static pthread_mutex_t mem_handle; { void *address; unsigned long size; }memInfo; { memInfo mem_info; struct _memLeak *next; }memLeak; static memLeak *mem_start; static memLeak *mem_end; void add_meminfo(void *alloc, unsigned long size); void rem_meminfo(void *alloc); void add(memInfo mem_alloc); void rem(void *memAddr); int init_leakcheck() { pthread_mutex_init(&mem_handle, 0); } void* lc_malloc(unsigned long size) { void* alloc = malloc(size); if (alloc != 0) { add_meminfo(alloc, size); } return alloc; } void * lc_calloc(unsigned long count, unsigned long size) { unsigned long totalSize; void *memPtr = calloc(count, size); if (memPtr != 0) { totalSize = count * size; add_meminfo(memPtr, totalSize); } return memPtr; } void * lc_realloc(void *addr, unsigned long size) { void *memPtr; memPtr = realloc(addr, size); if (memPtr != 0) { if (addr == 0) { add_meminfo(memPtr, size); } else { rem_meminfo(addr); add_meminfo(memPtr, size); } } return memPtr; } char * lc_strdup(const char *str) { char *ret_str; unsigned long str_size = strlen(str) + 1; ret_str = strdup(str); if (ret_str != 0) { add_meminfo(ret_str, str_size); } return ret_str; } void lc_free(void *addr) { rem_meminfo(addr); free(addr); } void add_meminfo(void *alloc, unsigned long size) { memInfo mem_alloc; memset(&mem_alloc, 0, sizeof(mem_alloc)); mem_alloc.address = alloc; mem_alloc.size = size; pthread_mutex_lock(&mem_handle); add(mem_alloc); pthread_mutex_unlock(&mem_handle); } void rem_meminfo(void *alloc) { if (alloc == 0) return; pthread_mutex_lock(&mem_handle); rem(alloc); pthread_mutex_unlock(&mem_handle); } void add(memInfo mem_alloc) { memLeak *mem_leak_info = 0; mem_leak_info = malloc( sizeof(memLeak)); if (mem_leak_info == 0) { perror("malloc"); exit(-1); } mem_leak_info->mem_info.size = mem_alloc.size; mem_leak_info->mem_info.address = mem_alloc.address; mem_leak_info->next = 0; if (mem_start == 0) { mem_start = mem_leak_info; mem_end = mem_start; } else { mem_end->next = mem_leak_info; mem_end = mem_leak_info; } } void rem(void *memAddr) { memLeak *delnode, *prev; memLeak *memlist_ptr = mem_start; if (memlist_ptr->mem_info.address == memAddr ) { mem_start = memlist_ptr->next; delnode = memlist_ptr; free(delnode); return; } prev = memlist_ptr; memlist_ptr = memlist_ptr -> next; while (memlist_ptr != 0) { if (memlist_ptr->mem_info.address == memAddr) { delnode = memlist_ptr; prev->next = memlist_ptr->next; free(delnode); return; } else { prev = prev->next; memlist_ptr = memlist_ptr->next; } } } void display_leakinfo() { memLeak *memlist = mem_start; printf("-----------------------------MEMORY LEAK----------------------------------------\\n"); while(memlist != 0) { printf("Address : %p size : %ld bytes\\n", memlist->mem_info.address, memlist->mem_info.size); memlist = memlist->next; } printf("---------------------------------------------------------------------------------\\n"); pthread_mutex_destroy(&mem_handle); }
0
#include <pthread.h> struct thread_data { int t_index; }; int k,n,x,thread_count=0,col_count=0,status1=0,status2=0; int **arr; pthread_t thread_id[5]; pthread_mutex_t cnt_mutex; pthread_cond_t *cnt_cond; void row_swap(int tid) { int i,j; for(i = tid * (n/x) ;i<(tid+1)*(n/x);i++) { int tmp = arr[i][0]; for(j=0;j<n-1;j++) { arr[i][j] = arr[i][j+1]; } arr[i][n-1] = tmp; } } void col_swap(int tid) { int i,j; for(i = tid * (n/x);i<(tid+1)*(n/x) ;i++) { int tmp = arr[n-1][i]; for(j=n-2;j>=0;j--) { arr[j+1][i] = arr[j][i]; } arr[0][i] = tmp; } } void *start_routine(void *param) { struct thread_data *t_param = (struct thread_data *) param; int tid = (*t_param).t_index; int i,j,c; pthread_mutex_lock(&cnt_mutex); sleep(1); for(c=0;c<k;c++) { pthread_cond_wait(cnt_cond+tid, &cnt_mutex); if(tid!=x-1) row_swap(tid); else { for(i = tid * (n/x) ;i<n;i++) { int tmp = arr[i][0]; for(j=0;j<n-1;j++) { arr[i][j] = arr[i][j+1]; } arr[i][n-1] = tmp; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d ",arr[i][j]); } printf("\\n"); } printf("\\n"); if(tid != x-1) pthread_cond_signal(cnt_cond+tid+1); else pthread_cond_signal(cnt_cond); pthread_cond_wait(cnt_cond+tid, &cnt_mutex); if(tid!=x-1) col_swap(tid); else { for(i = tid * (n/x);i<n ;i++) { int tmp = arr[n-1][i]; for(j=n-2;j>=0;j--) { arr[j+1][i] = arr[j][i]; } arr[0][i] = tmp; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d ",arr[i][j]); } printf("\\n"); } printf("\\n"); if(tid!=x-1) pthread_cond_signal(cnt_cond+tid+1); else pthread_cond_signal(cnt_cond); pthread_mutex_unlock(&cnt_mutex); } pthread_exit(0); } int main() { int i,j; scanf("%d %d %d",&n,&k,&x); arr = (int **)malloc(sizeof(int *)*n); pthread_mutex_init(&cnt_mutex, 0); cnt_cond = (pthread_cond_t *)malloc(sizeof(pthread_cond_t )*x); for(i = 0;i < x;i++) { pthread_cond_init(cnt_cond+i, 0); } for(i = 0;i < n;i++) arr[i]=(int *)malloc(sizeof(int)*n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { scanf("%d",&arr[i][j]); } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d ",arr[i][j]); } printf("\\n"); } printf("\\n"); struct thread_data param[x]; for(i=0; i<x; i++) { param[i].t_index = i; pthread_create(&thread_id[i], 0, start_routine, (void *) &param[i]); } sleep(3); pthread_cond_signal(cnt_cond); for(i=0; i<x; i++) { pthread_join(thread_id[i], 0); } pthread_mutex_destroy(&cnt_mutex); for(i = 0;i < x;i++) { pthread_cond_destroy(cnt_cond+i); } }
1
#include <pthread.h> int thisCount; int blockSize; int offsetLow; } read_data; pthread_mutex_t lock; void* countWords(void*); int ourFile; int main(){ read_data data_array[16]; if((ourFile = open("Assign3.txt",O_RDONLY))< -1) return 1; pthread_t threads[16]; int count = lseek(ourFile,0,2); int i; for (i = 0; i < 16; i++){ data_array[i].blockSize = (count / 16) +1; data_array[i].offsetLow = data_array[i].blockSize*i; data_array[i].thisCount = 0; } for(i = 0; i < 16; i++){ pthread_create(&threads[i], 0, countWords, (void*)&data_array[i]); } int finalCount = 0; for(i=0; i < 16; i++){ pthread_join(threads[i], 0); } for(i=0; i < 16; i++){ finalCount = data_array[i].thisCount + finalCount; } printf("The total words in the file are: %d\\n",finalCount); exit(0); } void *countWords(void* args){ struct read_data* our_data; our_data = (struct read_data*)args; pthread_mutex_lock(&lock); char buffer[our_data->blockSize]; lseek(ourFile,our_data->offsetLow,0); read(ourFile,buffer,our_data->blockSize); pthread_mutex_unlock(&lock); int i = 0; our_data->thisCount=0; for(i = 0; i<our_data->blockSize;i++){ if(buffer[i] == ' '){ our_data->thisCount++; }} printf(" Counted words in this thread:%d\\n",our_data->thisCount); pthread_exit(0); return 0; }
0
#include <pthread.h> extern void do_work (); int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void initialize_flag () { pthread_mutex_init (&thread_flag_mutex, 0); pthread_cond_init (&thread_flag_cv, 0); thread_flag = 0; } void* thread_function (void* thread_arg) { while (1) { pthread_mutex_lock (&thread_flag_mutex); while (!thread_flag) pthread_cond_wait (&thread_flag_cv, &thread_flag_mutex); pthread_mutex_unlock (&thread_flag_mutex); do_work (); } return 0; } void set_thread_flag (int flag_value) { pthread_mutex_lock (&thread_flag_mutex); thread_flag = flag_value; pthread_cond_signal (&thread_flag_cv); pthread_mutex_unlock (&thread_flag_mutex); } void* flag_manager(void* arg){ while(1){ set_thread_flag(1); sleep(2); set_thread_flag(0); sleep(5); } } void do_work(){ printf("%s\\n", "Haciendo algo"); } int main(){ initialize_flag(); pthread_t thread_fm; pthread_create(&thread_fm,0,&flag_manager,0); int tamanho = 5; pthread_t threads[tamanho]; for(int i = 0 ; i < tamanho ; i++) pthread_create(&(threads[i]),0,&thread_function,0); pthread_join(thread_fm,0); for(int i = 0 ; i < tamanho ; i++) pthread_join(threads[i],0); return 0; }
1
#include <pthread.h> void* threadFunc(void* rank); int driverParallel(int start, int stop); int mergeParallel(int start, int middle, int stop); int binSearch(int arr[], int a, int b, int x); void printParallel(int start, int stop); int validateParallel(); int combine(long myRank); void barrier(); extern int threadCount; extern long n; extern int *vecSerial; extern int *vecParallel; extern int *temp; pthread_t *threads; int level; extern int threads_ready; extern pthread_cond_t ready_cv; extern pthread_mutex_t lock; int mergeSortParallel() { threads = malloc(threadCount*sizeof(pthread_t)); level = 1; int i; for(i = 0; i < threadCount; i++){ long rank = (long)i; pthread_create(&threads[i], 0, threadFunc, (void*)rank); } for(i = 0; i < threadCount; i++){ pthread_join(threads[i], 0); } return 0; } void* threadFunc(void* rank){ long myRank = (long) rank; long quotient = n / threadCount; long remainder = n % threadCount; long myCount; long myFirsti, myFirstj, mySecondi, mySecondj; if (myRank < remainder) { myCount = quotient + 1; myFirsti = myRank * myCount; } else { myCount = quotient; myFirsti = myRank * myCount + remainder; } myFirstj = myFirsti + myCount; driverParallel(myFirsti, myFirstj-1); int team_size, num_teams, chunk_size, block_size, team, offset, a, b; barrier(); while(pow(2, level) <= threadCount) { if(myRank == 0){ printf("LEVEL %d\\n", level); } barrier(); team_size = pow(2, level); num_teams = threadCount / team_size; chunk_size = n / (num_teams * 2); block_size = chunk_size / team_size; team = myRank / team_size; offset = team * chunk_size; myFirsti = offset + (myRank * block_size); myFirstj = myFirsti + block_size; a = (chunk_size * 2 * (team+1))- chunk_size; b = a + chunk_size; if((level % 2) == 0){ mySecondi = binSearch(vecParallel, a, b, vecParallel[myFirsti-1]); mySecondj = binSearch(vecParallel, a, b, vecParallel[myFirstj]); } else{ mySecondi = binSearch(temp, a, b, temp[myFirsti-1]); mySecondj = binSearch(temp, a, b, temp[myFirstj]); } printf("Thread %ld first: %ld --> %ld\\n", myRank, myFirsti, myFirstj); printf("Thread %ld second: %ld --> %ld\\n", myRank, mySecondi, mySecondj); barrier(); if(myRank == 0){ level++; } barrier(); } barrier(); return 0; } int binSearch(int arr[], int a, int b, int x){ if (b >= a){ int mid = a + (b - a)/2; if (arr[mid] == x){ return mid;} if(arr[mid] > x){ return binSearch(arr, a, mid-1, x);} return binSearch(arr, mid+1, b, x); } return a; } void barrier(){ pthread_mutex_lock(&lock); threads_ready++; if(threads_ready == threadCount){ threads_ready = 0; pthread_cond_broadcast(&ready_cv); } else{ while(pthread_cond_wait(&ready_cv, &lock) != 0); } pthread_mutex_unlock(&lock); } int validateParallel(){ int i; for(i = 0; i < n-1; i++){ if(vecParallel[i] != vecSerial[i]){ printf("Parallel sort unsuccesful.\\n"); return 1; } } return 0; } int driverParallel(int start, int stop){ if(start >= stop){ return 0; } int middle = ((stop + start) / 2); driverParallel(start, middle); driverParallel(middle+1, stop); mergeParallel(start, middle, stop); return 0; } int mergeParallel(int start, int middle, int stop){ int first = start; int second = middle+1; int tempIndex = start; while(first <= middle && second <= stop){ if(vecParallel[first] < vecParallel[second]){ temp[tempIndex] = vecParallel[first]; first++; tempIndex++; } else { temp[tempIndex] = vecParallel[second]; second++; tempIndex++; } } while(first <= middle){ temp[tempIndex] = vecParallel[first]; first++; tempIndex++; } while(second <= stop){ temp[tempIndex] = vecParallel[second]; second++; tempIndex++; } int i; for(i = start; i <= stop; i++){ vecParallel[i] = temp[i]; } return 0; } void printParallel(int start, int stop){ int i; for(i = start; i < stop; i++){ printf("%d\\t", vecParallel[i]); } printf("\\n"); return; }
0