text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct msg { struct msg *m_next; char *data; }; struct msg *workq; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void process_msg(int thread) { struct msg *mp; for (;;) { pthread_mutex_lock(&qlock); while (workq == 0) pthread_cond_wait(&qready, &qlock); mp = workq; workq = mp->m_next; pthread_mutex_unlock(&qlock); printf("thread %u message:%s \\n",thread,mp->data); free(mp); } } void enqueue_msg(struct msg *mp) { pthread_mutex_lock(&qlock); mp->m_next = workq; workq = mp; pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); } pthread_t ntid[2]; struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo * foo_alloc(void) { struct foo *fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void printids(const char *s) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf("%s pid %u tid %u (0x%x)\\n", s, (unsigned int)pid, (unsigned int)tid, (unsigned int)tid); } void cleanup(void *arg) { printf("cleanup: %s\\n", (char *)arg); } void * thr_func1(void *arg) { struct foo* fp=(struct foo*)arg; pthread_cleanup_push(cleanup,"thread 1 cleanup"); printids("new thread: "); pthread_cleanup_pop(0); process_msg(1); return((void *)2); } void * thr_func2(void *arg) { struct foo* fp=(struct foo*)arg; pthread_cleanup_push(cleanup,"thread 2 cleanup"); printids("new thread: "); pthread_cleanup_pop(0); process_msg(2); pthread_exit((void *)1); } int main(void) { int err; void * ret; struct foo *fp=foo_alloc(); char message[][5]={"1111", "2222", "3333", "4444", "5555", "6666", "7777", "8888", "9999", "000" }; int loop=0; err = pthread_create(&ntid[0], 0, thr_func1, fp); if (err != 0){ exit(0); } err = pthread_create(&ntid[1], 0, thr_func2, fp); if (err != 0){ exit(0); } sleep(1); for(loop ; loop<10 ; loop++ ){ struct msg * f=malloc(sizeof(struct msg)); f->data=message[loop]; enqueue_msg(f); } sleep(1); err = pthread_join(ntid[0], &ret); printf("thread 1 exit code %u\\n",(int)ret); err = pthread_join(ntid[1], &ret); printf("thread 2 exit code %u\\n",(int)ret); printids("main thread:"); exit(0); }
1
#include <pthread.h> char** field; char** new_field; int n, m; int total_number_of_threads; int total_number_of_iterations; struct segment_t* segments; pthread_t* threads; char* finished_treads; int number_of_finished_treads; pthread_mutex_t mutex; pthread_cond_t conditional; int number_of_active_threads; char broadcasted; char stop_immediately; struct segment_t { int l, r; }; void* life_computator(void* arg) { int i, j, step; struct segment_t borders = *((struct segment_t*)arg); for (step = 0; step < total_number_of_iterations; step++) { for (i = borders.l; i<= borders.r; i++) { for (j = 0; j < m; j++) { recalculate_on_coordinate(field, new_field, n, m, i, j); } } pthread_mutex_lock(&mutex); number_of_active_threads--; if (number_of_active_threads > 0) { pthread_cond_wait(&conditional, &mutex); } else { number_of_active_threads = total_number_of_threads; two_dimentional_array_swap(&field, &new_field); if (stop_immediately) { total_number_of_iterations = step; } pthread_cond_broadcast(&conditional); } pthread_mutex_unlock(&mutex); } return 0; } void distribute_segments(struct segment_t* segments) { int i; int k = n / total_number_of_threads; int border = n % total_number_of_threads; int last = 0; for (i = 0; i < total_number_of_threads; i++) { segments[i].l = last; segments[i].r = last + k - 1; if (border) { segments[i].r++; border--; } last = segments[i].r + 1; } } void init_parallel_mode() { pthread_mutex_init(&mutex, 0); pthread_cond_init(&conditional, 0); number_of_finished_treads = 0; stop_immediately = 0; number_of_active_threads = total_number_of_threads; allocate_two_dimentional_array(&new_field, n, m); segments = (struct segment_t*) malloc(total_number_of_threads * sizeof(struct segment_t)); threads = (pthread_t*)malloc(total_number_of_threads * sizeof(pthread_t)); finished_treads = (char*)calloc(sizeof(char), total_number_of_threads); } void run_parallel(int number_of_threads, int number_of_iterations, char** passed_field, int passed_n, int passed_m) { int i; n = passed_n; m = passed_m; if (number_of_threads > n) number_of_threads = n; field = passed_field; total_number_of_threads = number_of_threads; total_number_of_iterations = number_of_iterations; init_parallel_mode(); distribute_segments(segments); for (i = 0; i < number_of_threads; i++) { pthread_create(&threads[i], 0, life_computator, &segments[i]); } } void finalize() { if (total_number_of_iterations % 2 == 1) { two_dimentional_array_swap(&field, &new_field); copy_two_dimentional_array(new_field, field, n, m); } dispose_two_dimentional_array(new_field, n); free(segments); free(threads); free(finished_treads); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&conditional); } int try_join() { int i; for (i = 0; i < total_number_of_threads; i++) { if (finished_treads[i] == 0 && pthread_tryjoin_np(threads[i], 0) == 0) { finished_treads[i] = 1; number_of_finished_treads++; } } if (number_of_finished_treads == total_number_of_threads) { finalize(); return 1; } else { return 0; } } void completely_join() { int i; for (i = 0; i < total_number_of_threads; i++) { pthread_join(threads[i], 0); } finalize(); } int stop() { stop_immediately = 1; completely_join(); return total_number_of_iterations; }
0
#include <pthread.h> struct ID_object{ int objID; struct position *pos; }; pthread_mutex_t obj_lock; static struct ID_object *obj_list; void set_num_obj(int num){ if (pthread_mutex_init(&obj_lock, 0) != 0){ pexit("Mutex init failed: "); } if ((obj_list = calloc(num ,sizeof(struct ID_object))) == 0){ pexit("Callocing failed: "); } obj_list[0].objID = -1; } void set_obj(int objID, struct position *pos){ pthread_mutex_lock(&obj_lock); obj_list[objID].objID = objID; obj_list[objID].pos = pos; pthread_mutex_unlock(&obj_lock); } void set_pos(int objID, int posx, int posy){ pthread_mutex_lock(&obj_lock); obj_list[objID].pos->x = posx; obj_list[objID].pos->y = posy; pthread_mutex_unlock(&obj_lock); } void get_pos(int objID, int *posx, int *posy){ pthread_mutex_lock(&obj_lock); *posx = obj_list[objID].pos->x; *posy = obj_list[objID].pos->y; pthread_mutex_unlock(&obj_lock); } int obj_exists(int objID){ if(obj_list[objID].objID == objID){ return 1; }else{ return 0; } } void free_list(){ pthread_mutex_destroy(&obj_lock); free(obj_list); }
1
#include <pthread.h> pthread_mutex_t lock; long long int *MatrixA,*MatrixB,i,j,k,nRows,nThread,offset; long long int sum=0; void * multiply(void *arg) { long long int row=*(long long int*)arg; long long int mysum=0; int i; for(i=0;i<offset;i++) mysum=mysum+MatrixA[row*offset+i]*MatrixB[row*offset+i]; pthread_mutex_lock(&lock); sum=mysum+sum; printf("\\n Row is %d\\n",row); pthread_mutex_unlock(&lock); pthread_exit(0); } void fillMatrix(long long int *a,long long int b) { for(i=0;i<nRows;i++) a[i]=b; } int main(int argc,char *argv[]) { pthread_mutex_init(&lock,0); if(argc!=3) { printf("\\n Pleas Enter The size of The Vector and No Of Thread \\n");exit(1); } nRows=atoi(argv[1]); nThread=atoi(argv[2]); pthread_t *t; MatrixA=(long long int *)malloc(8*nRows); MatrixB=(long long int *)malloc(8*nRows); fillMatrix(MatrixA,1); fillMatrix(MatrixB,2); t=(pthread_t*)malloc(sizeof(pthread_t)*nThread); offset=nRows/nThread; struct timeval tv_start,tv_end; gettimeofday(&tv_start,0); for(i=0;i<nThread;i++) { pthread_create(&t[i],0,multiply,&i); } for(i=0;i<nThread;i++) { pthread_join(t[i],0); } gettimeofday(&tv_end,0); printf("\\n\\nThe Result Is :: %d\\n",sum); printf(" \\n\\nTime Taken in Parallel Code is %f\\n",(double)(tv_end.tv_sec-tv_start.tv_sec)+(tv_end.tv_usec-tv_start.tv_usec)/1000000); sum=0; gettimeofday(&tv_start,0); for(i=0;i<nRows;i++) sum+=MatrixA[i]*MatrixB[i]; gettimeofday(&tv_end,0); printf("\\n\\nThe Result Is :: %d\\n",sum); printf(" \\n\\nTime Taken in Serial Code is %f\\n",(double)(tv_end.tv_sec-tv_start.tv_sec)+(tv_end.tv_usec-tv_start.tv_usec)/1000000); return 0; }
0
#include <pthread.h> static char encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'}; static char *decoding_table = 0; static int mod_table[] = {0, 2, 1}; pthread_mutex_t mutex_base64; void build_decoding_table() { int i; pthread_mutex_lock(&global.mutex_formatos); if (decoding_table != 0) return; decoding_table = malloc(256); for (i = 0; i < 64; i++) decoding_table[(unsigned char) encoding_table[i]] = i; pthread_mutex_unlock(&global.mutex_formatos); } char *base64_encode(const unsigned char *data, size_t input_length, size_t *output_length) { int i,j; *output_length = 4 * ((input_length + 2) / 3); char *encoded_data = malloc(*output_length+1); if (encoded_data == 0) return 0; for (i = 0, j = 0; i < input_length;) { uint32_t octet_a = i < input_length ? data[i++] : 0; uint32_t octet_b = i < input_length ? data[i++] : 0; uint32_t octet_c = i < input_length ? data[i++] : 0; uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c; encoded_data[j++] = encoding_table[(triple >> 3 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 2 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 1 * 6) & 0x3F]; encoded_data[j++] = encoding_table[(triple >> 0 * 6) & 0x3F]; } encoded_data[j++]=0; for (i = 0; i < mod_table[input_length % 3]; i++) { encoded_data[*output_length - 1 - i] = '='; } return encoded_data; } unsigned char *base64_decode(const char *data, size_t input_length, size_t *output_length) { int i,j; if (decoding_table == 0) build_decoding_table(); if (input_length % 4 != 0) return 0; *output_length = input_length / 4 * 3; if (data[input_length - 1] == '=') (*output_length)--; if (data[input_length - 2] == '=') (*output_length)--; unsigned char *decoded_data = malloc(*output_length+1); if (decoded_data == 0) return 0; for (i = 0, j = 0; i < input_length;) { uint32_t sextet_a = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_b = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_c = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t sextet_d = data[i] == '=' ? 0 & i++ : decoding_table[data[i++]]; uint32_t triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6); if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF; if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF; } decoded_data[j++]=0; return decoded_data; } void base64_cleanup() { free(decoding_table); }
1
#include <pthread.h> struct arg_set{ char *fname; int count; }; struct arg_set * mailbox; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; int main(int argc, char *argv[]) { pthread_t t1, t2; struct arg_set args1, args2; void *count_words(void *); int reports_in = 0; int total_words = 0; if( argc!= 3){ printf("usage: %s file1 file2\\n", argv[0]); exit(1); } pthread_mutex_lock(&lock); args1.count = 0; args1.fname = argv[1]; pthread_create(&t1, 0, count_words, (void*)&args1); args2.fname = argv[2]; args2.count = 0; pthread_create(&t2, 0, count_words, (void *)&args2); while( reports_in < 2 ) { printf("MAIN: Waiting for flag to go up\\n"); pthread_cond_wait(&flag, &lock); printf("MAIN: WOw! flag was raised, i have the lock\\n"); printf(" %d : %s\\n", mailbox->count, mailbox->fname); total_words +=mailbox->count; if( mailbox == &args1 ) pthread_join(t1, 0); if( mailbox == &args2) pthread_join(t2, 0); mailbox = 0; pthread_cond_signal(&flag); reports_in++; } printf("%7d: total_words\\n",total_words); return 0; } void *count_words(void *a) { struct arg_set * args = a; FILE * fp; int c, prevc = '\\0'; if( (fp = fopen(args->fname, "r")) != 0 ) { while( (c =getc(fp)) != EOF){ if( !isalnum(c) && isalnum(prevc) ) args->count++; prevc = c; } fclose(fp); } else perror(args->fname); printf("COUNT: Waiting to get lock\\n"); pthread_mutex_lock(&lock); printf("COUNT: have lock, storing data\\n"); if( mailbox != 0 ) pthread_cond_wait(&flag, &lock); mailbox = args; printf("COUNT: raitsing flag\\n"); pthread_cond_signal(&flag); printf("COUNT: unlocking box\\n"); pthread_mutex_unlock(&lock); return 0; }
0
#include <pthread.h> struct fuse_session *fuse_session_new(void) { struct fuse_session *se = (struct fuse_session *) malloc(sizeof(*se)); if (se == 0) { fprintf(stderr, "fuse: failed to allocate session\\n"); return 0; } memset(se, 0, sizeof(*se)); return se; } void fuse_session_add_chan(struct fuse_session *se, struct fuse_chan *ch) { assert(se->ch == 0); assert(ch->se == 0); se->ch = ch; ch->se = se; } void fuse_session_remove_chan(struct fuse_chan *ch) { struct fuse_session *se = ch->se; if (se) { assert(se->ch == ch); se->ch = 0; ch->se = 0; } } struct fuse_chan *fuse_session_chan(struct fuse_session *se) { return se->ch; } int fuse_chan_clearfd(struct fuse_chan *ch) { int fd = ch->fd; ch->fd = -1; return fd; } void fuse_session_exit(struct fuse_session *se) { se->exited = 1; } void fuse_session_reset(struct fuse_session *se) { se->exited = 0; } int fuse_session_exited(struct fuse_session *se) { return se->exited; } struct fuse_chan *fuse_chan_new(int fd) { struct fuse_chan *ch = (struct fuse_chan *) malloc(sizeof(*ch)); if (ch == 0) { fprintf(stderr, "fuse: failed to allocate channel\\n"); return 0; } memset(ch, 0, sizeof(*ch)); ch->fd = fd; ch->ctr = 1; fuse_mutex_init(&ch->lock); return ch; } int fuse_chan_fd(struct fuse_chan *ch) { return ch->fd; } struct fuse_session *fuse_chan_session(struct fuse_chan *ch) { return ch->se; } struct fuse_chan *fuse_chan_get(struct fuse_chan *ch) { assert(ch->ctr > 0); pthread_mutex_lock(&ch->lock); ch->ctr++; pthread_mutex_unlock(&ch->lock); return ch; } void fuse_chan_put(struct fuse_chan *ch) { if (ch) { pthread_mutex_lock(&ch->lock); ch->ctr--; if (!ch->ctr) { pthread_mutex_unlock(&ch->lock); fuse_session_remove_chan(ch); fuse_chan_close(ch); pthread_mutex_destroy(&ch->lock); free(ch); } else { pthread_mutex_unlock(&ch->lock); } } }
1
#include <pthread.h> static pthread_mutex_t mallocMutex; void initMeMalloc() { pthread_mutex_init(&mallocMutex, 0); } void deinitMeMalloc() { pthread_mutex_destroy(&mallocMutex); } void *MeAlloc( long nbytes, const char *file, int line ) { void *ptr = ( void * )malloc( nbytes ); if ( ptr == 0 ) Printf( "Malloc Memory Failed, file: %s, line: %d !\\r\\n", file, line ); return ptr; } void *MeCalloc( long count, long nbytes, const char *file, int line ) { void *ptr = ( void * )calloc( count, nbytes ); if ( ptr == 0 ) Printf( "Calloc Memory Failed, file: %s, line: %d !\\r\\n", file, line ); return ptr; } void MeFree( void *ptr, const char *file, int line ) { if ( ptr != 0 ) free( ptr ); } void *MeRealloc( void *ptr, long nbytes, const char *file, int line ) { ptr = ( void * )realloc( ptr, nbytes ); if ( ptr == 0 ) Printf( "Realloc Memory Failed, file: %s, line: %d !\\r\\n", file, line ); return ptr; } void *ShareMeAlloc( long nbytes, const char *file, int line ) { long size = nbytes + sizeof(long)*2; long *ptr = ( long * )malloc( size ); if ( ptr == 0 ) { Printf( "Malloc Share Memory Failed, file: %s, line: %d !\\r\\n", file, line ); } else { *ptr = 0xCCBB2828; *(ptr + 1) = 1; } return (void *)(ptr + 2); } void *ShareMeCalloc( long count, long nbytes, const char *file, int line ) { long size = nbytes + sizeof(long)*2; long *ptr = ( long * )calloc( count, size ); if ( ptr == 0 ) { Printf( "Calloc Share Memory Failed, file: %s, line: %d !\\r\\n", file, line ); } else { *ptr = 0xCCBB2828; *(ptr + 1) = 1; } return (void *)(ptr + 2); } void ShareMeFree( void *ptr, const char *file, int line ) { if ( ptr != 0 ) { long *pmem = (long *)ptr - 2; if ( *pmem == (long)0xCCBB2828 ) { pthread_mutex_lock(&mallocMutex); *(pmem + 1) -= 1; if ( *(pmem + 1) == 0 ) { free( pmem ); } pthread_mutex_unlock(&mallocMutex); } else { Printf( "Free Share Memory Failed, file: %s, line: %d !\\r\\n", file, line ); } } } void *ShareMeCopy( void *ptr, const char *file, int line ) { if ( ptr == 0 ) { return 0; } long *pmem = (long *)ptr - 2; if ( *pmem == (long)0xCCBB2828 ) { pthread_mutex_lock(&mallocMutex); *(pmem + 1) += 1; pthread_mutex_unlock(&mallocMutex); return ptr; } else { Printf( "Copy Share Memory Failed, Copy Error ptr; " "file: %s, line: %d !\\r\\n", file, line ); } return 0; } void FreeMs( void *ptr, int bShareMem ) { if( PDATA_FROM_SHAREMALLOC == bShareMem ) { ShareFree( ptr ); } else { Free( ptr ); } }
0
#include <pthread.h> { void *(*process) (void *arg); void *arg; struct worker *next; } CThread_worker; { pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t *threadid; int max_thread_num; int cur_queue_size; } CThread_pool; int pool_add_worker (void *(*process) (void *arg), void *arg); void *thread_routine (void *arg); static CThread_pool *pool = 0; void pool_init (int max_thread_num) { pool = (CThread_pool *) malloc (sizeof (CThread_pool)); pthread_mutex_init (&(pool->queue_lock), 0); pthread_cond_init (&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); int i = 0; for (i = 0; i < max_thread_num; i++) { pthread_create (&(pool->threadid[i]), 0, thread_routine, 0); } } int pool_add_worker (void *(*process) (void *arg), void *arg) { CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock (&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if (member != 0) { while (member->next != 0) member = member->next; member->next = newworker; } else { pool->queue_head = newworker; } assert (pool->queue_head != 0); pool->cur_queue_size++; pthread_mutex_unlock (&(pool->queue_lock)); pthread_cond_signal (&(pool->queue_ready)); return 0; } int pool_destroy () { if (pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast (&(pool->queue_ready)); int i; for (i = 0; i < pool->max_thread_num; i++) pthread_join (pool->threadid[i], 0); free (pool->threadid); CThread_worker *head = 0; while (pool->queue_head != 0) { head = pool->queue_head; pool->queue_head = pool->queue_head->next; free (head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free (pool); pool=0; return 0; } void * thread_routine (void *arg) { printf ("starting thread 0x%x\\n", pthread_self ()); while (1) { pthread_mutex_lock (&(pool->queue_lock)); while (pool->cur_queue_size == 0 && !pool->shutdown) { printf ("thread 0x%x is waiting\\n", pthread_self ()); pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); } if (pool->shutdown) { pthread_mutex_unlock (&(pool->queue_lock)); printf ("thread 0x%x will exit\\n", pthread_self ()); pthread_exit (0); } printf ("thread 0x%x is starting to work\\n", pthread_self ()); assert (pool->cur_queue_size != 0); assert (pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock (&(pool->queue_lock)); (*(worker->process)) (worker->arg); free (worker); worker = 0; } pthread_exit (0); } void * myprocess (void *arg) { printf ("threadid is 0x%x, working on task %d\\n", pthread_self (),*(int *) arg); sleep (1); return 0; } int main (int argc, char **argv) { pool_init (3); int *workingnum = (int *) malloc (sizeof (int) * 10); int i; for (i = 0; i < 10; i++) { workingnum[i] = i; pool_add_worker (myprocess, &workingnum[i]); } sleep (5); pool_destroy (); free (workingnum); return 0; }
1
#include <pthread.h> int array[4]; int array_index = 0; pthread_mutex_t mutex; void *thread(void * arg) { pthread_mutex_lock(&mutex); array[array_index] = 1; pthread_mutex_unlock(&mutex); return 0; } void *main_continuation (void *arg); pthread_t t[4]; int main() { int i; pthread_t t[4]; pthread_mutex_init(&mutex, 0); i = 0; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); i++; __VERIFIER_assert (i == 4); __VERIFIER_assert (array_index < 4); pthread_t tt; pthread_create(&tt, 0, main_continuation, 0); pthread_join (tt, 0); return 0; } void *main_continuation (void *arg) { int i, sum; i = 0; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; __VERIFIER_assert (i == 4); sum = 0; i = 0; sum += array[i]; i++; sum += array[i]; i++; sum += array[i]; i++; sum += array[i]; i++; __VERIFIER_assert (i == 4); printf ("m: sum %d SIGMA %d\\n", sum, 4); __VERIFIER_assert (sum == 4); return 0; }
0
#include <pthread.h> void *fetch_data(void *filename); void exit_handler (int sigNum); int file_request_count; float file_access_time; pthread_mutex_t count_lock; pthread_mutex_t avg_lock; int main() { pthread_t thread1; int status; char cmd[80]; srand(time(0)); signal (SIGINT, exit_handler); while(1) { fprintf(stdout, "Enter Filename: \\n"); fgets(cmd, 80, stdin); cmd[strcspn(cmd, "\\n")] = 0; status = pthread_create (&thread1, 0, fetch_data, &cmd); if (status != 0) { fprintf (stderr, "Thread spawn error %d: %s\\n", status, strerror(status)); exit (1); } else { pthread_mutex_lock(&count_lock); file_request_count++; pthread_mutex_unlock(&count_lock); } status = pthread_detach (thread1); if (status != 0) { fprintf (stderr, "Detach error %d: %s\\n", status, strerror(status)); exit (1); } } return 0; } void *fetch_data(void *filename) { char *fname = (char*) filename; char *name = (char *) malloc((sizeof(char) * 80)); strcpy(name, fname); *name = *fname; int wait_time = (rand()%10) + 1; int sleep_time = 0; if (wait_time <= 2) { sleep_time = 10 - (rand()%4); pthread_mutex_lock(&avg_lock); file_access_time += sleep_time; pthread_mutex_unlock(&avg_lock); sleep(sleep_time); } else { sleep_time = 1; pthread_mutex_lock(&avg_lock); file_access_time += sleep_time; pthread_mutex_unlock(&avg_lock); sleep(sleep_time); } fprintf(stdout, "\\nFile \\"%s\\" located after %d seconds\\n", name, sleep_time); return 0; } void exit_handler (int sigNum) { fprintf(stdout, " received. That's shutting down...\\n"); fprintf(stdout, "Files Requested: %d\\n", file_request_count); fprintf(stdout, "Average File Request Time: %f seconds\\n", (float)(file_access_time/file_request_count)); exit(0); }
1
#include <pthread.h> { struct node *next; } node; { node *head; node *tail; pthread_mutex_t GlobalLock; } queue; void Queue_Init(struct queue *q); void Queue_Enqueue(struct queue *q); int Queue_Dequeue( struct queue *q); void* Thread_Enqueue(void *q); void* Thread_Dequeue(void *q); int main(){ struct queue MainQueue; Queue_Init(&MainQueue); int i = 0; for(i = 0; i< 100; i++){ Queue_Enqueue(&MainQueue); } pthread_t enQ; pthread_t deQ; pthread_create(&enQ, 0, Thread_Enqueue, (void*) &MainQueue); pthread_create(&deQ, 0, Thread_Dequeue, (void*) &MainQueue); pthread_join(enQ, 0); pthread_join(deQ, 0); isEmpty(&MainQueue); } void Queue_Init(struct queue *q){ struct node *tmp = malloc(sizeof(node)); tmp->next = 0; q->head = tmp; q->tail = tmp; pthread_mutex_init(&q->GlobalLock, 0); } void isEmpty(struct queue *q){ struct node *tmp = q->head; struct node *newHead = tmp->next; if(newHead == 0){ printf("Queue is Empty"); }else{ printf("Queue is NOT Empty"); } } void Queue_Enqueue(struct queue *q){ struct node *tmp = malloc(sizeof(node)); assert(tmp != 0); tmp->next = 0; pthread_mutex_lock(&q->GlobalLock); q->tail->next = tmp; q->tail = tmp; pthread_mutex_unlock(&q->GlobalLock); } int Queue_Dequeue(struct queue *q){ pthread_mutex_lock(&q->GlobalLock); struct node *tmp = q->head; struct node *newHead = tmp->next; if(newHead == 0){ pthread_mutex_unlock(&q->GlobalLock); return -1; } q->head = newHead; pthread_mutex_unlock(&q->GlobalLock); free(tmp); return 0; } void *Thread_Enqueue(void* q){ struct queue *PassedQueue = (struct queue *)q; int i = 0; for(i = 0; i< 1000000; i++){ Queue_Enqueue(PassedQueue); } } void *Thread_Dequeue(void* q){ struct queue *PassedQueue = (struct queue *)q; while(Queue_Dequeue(PassedQueue) == 0); }
0
#include <pthread.h> char buf[1] = {0}; pthread_mutex_t rlock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t wlock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t can_read = PTHREAD_COND_INITIALIZER; pthread_cond_t can_write = PTHREAD_COND_INITIALIZER; void* write_buf(void * p) { char c; int i = 0; char arr[52]; for (c = 'a'; c <= 'z'; c++, i++) arr[i] = c; for (c = 'A'; c <= 'Z'; c++, i++) arr[i] = c; i = 0; for (i = 0; i < 52; i++) { pthread_mutex_lock(&wlock); if (buf[0] != 0) pthread_cond_wait(&can_write, &wlock); buf[0] = arr[i]; printf("write: %c\\n", buf[0]); fflush(stdout); sleep(2); pthread_cond_signal(&can_read); pthread_mutex_unlock(&wlock); } } void* read_buf(void *p) { int i = 0; char c; for (i = 0; i < 52; i++) { pthread_mutex_lock(&rlock); if (buf[0] == 0) pthread_cond_wait(&can_read, &rlock); printf("read: %c\\n", buf[0]); fflush(stdout); buf[0] = 0; sleep(1); pthread_cond_signal(&can_write); pthread_mutex_unlock(&rlock); } } int main() { pthread_t a_thread; pthread_t b_thread; pthread_create(&b_thread, 0, write_buf, 0); pthread_create(&a_thread, 0, read_buf, 0); pthread_join(b_thread, 0); pthread_join(a_thread, 0); return 0; }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PHTREAD_MUTEX_INITIALLIZER; extern char **environ; static void thread_init() { pthread_key_create(&key, free); } char *getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if(envbuf == 0) { envbuf = malloc(ARG_MAX); if(envbuf == 0) { pthread_mutex_unlock(&env_mutex); return 0; } pthread_setspecific(key, envbuf); } len = strlen(name); for(i = 0; environ[i] != 0; i++) { if((strncmp(name, environ[i], len) == 0) && environ[i][len] == '=') { strcpy(envbuf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; }
0
#include <pthread.h> pthread_t philosopher[5]; pthread_mutex_t chopstick[5] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}; struct philosopher_t { int nr; int left; int right; }; int threadError(char *msg, int nr) { printf(msg, nr); exit(1); } void *philosopher_deadlock(void *p) { struct philosopher_t philosopher = *((struct philosopher_t *) (p)); while (1) { if (!pthread_mutex_lock(&chopstick[philosopher.left])) { printf("%d pick up's left chopstick \\n", philosopher.nr); while (1) { if (!pthread_mutex_lock(&chopstick[philosopher.right])) { printf("%d pick up's right chopstick, happy bastard, EAT \\n", philosopher.nr); pthread_mutex_unlock(&chopstick[philosopher.left]); pthread_mutex_unlock(&chopstick[philosopher.right]); break; } } } } } int main() { struct philosopher_t *p0_t, *p1_t, *p2_t, *p3_t, *p4_t; p0_t = malloc(sizeof(struct philosopher_t)); p1_t = malloc(sizeof(struct philosopher_t)); p2_t = malloc(sizeof(struct philosopher_t)); p3_t = malloc(sizeof(struct philosopher_t)); p4_t = malloc(sizeof(struct philosopher_t)); p0_t->nr = 0; p0_t->left = 1; p0_t->right = 0; p1_t->nr = 1; p1_t->left = 1; p1_t->right = 2; p2_t->nr = 2; p2_t->left = 3; p2_t->right = 2; p3_t->nr = 3; p3_t->left = 3; p3_t->right = 4; p4_t->nr = 4; p4_t->left = 4; p4_t->right = 0; if (pthread_create(&philosopher[p0_t->nr], 0, philosopher_deadlock, p0_t)) { threadError("Error while creating philosopher %d\\n", p0_t->nr); } if (pthread_create(&philosopher[p1_t->nr], 0, philosopher_deadlock, p1_t)) { threadError("Error while creating philosopher %d\\n", p1_t->nr); } if (pthread_create(&philosopher[p2_t->nr], 0, philosopher_deadlock, p2_t)) { threadError("Error while creating philosopher %d\\n", p2_t->nr); } if (pthread_create(&philosopher[p3_t->nr], 0, philosopher_deadlock, p3_t)) { threadError("Error while creating philosopher %d\\n", p4_t->nr); } if (pthread_create(&philosopher[p4_t->nr], 0, philosopher_deadlock, p4_t)) { threadError("Error while creating philosopher %d\\n", p4_t->nr); } if (pthread_join(philosopher[p0_t->nr], 0)) { threadError("Error while ending asymmetric philosopher %d\\n", p0_t->nr); } if (pthread_join(philosopher[p1_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p1_t->nr); } if (pthread_join(philosopher[p2_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p2_t->nr); } if (pthread_join(philosopher[p3_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p3_t->nr); } if (pthread_join(philosopher[p4_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p4_t->nr); } return 0; }
1
#include <pthread.h> static inline struct msglist *get_msglist(struct threadqueue *queue) { struct msglist *tmp; if(queue->msgpool != 0) { tmp = queue->msgpool; queue->msgpool = tmp->next; queue->msgpool_length--; } else { tmp = (struct msglist *)malloc(sizeof *tmp); } return tmp; } static inline void release_msglist(struct threadqueue *queue,struct msglist *node) { if(queue->msgpool_length > ( queue->length/8 + MSGPOOL_SIZE)) { free(node); } else { node->msg.data = 0; node->msg.msgtype = 0; node->next = queue->msgpool; queue->msgpool = node; queue->msgpool_length++; } if(queue->msgpool_length > (queue->length/4 + MSGPOOL_SIZE*10)) { struct msglist *tmp = queue->msgpool; queue->msgpool = tmp->next; free(tmp); queue->msgpool_length--; } } int thread_queue_init(struct threadqueue *queue) { int ret = 0; if (queue == 0) { return EINVAL; } memset(queue, 0, sizeof(struct threadqueue)); ret = pthread_cond_init(&queue->cond, 0); if (ret != 0) { return ret; } ret = pthread_mutex_init(&queue->mutex, 0); if (ret != 0) { pthread_cond_destroy(&queue->cond); return ret; } return 0; } int thread_queue_add(struct threadqueue *queue, void *data, long msgtype) { struct msglist *newmsg; pthread_mutex_lock(&queue->mutex); newmsg = get_msglist(queue); if (newmsg == 0) { pthread_mutex_unlock(&queue->mutex); return ENOMEM; } newmsg->msg.data = data; newmsg->msg.msgtype = msgtype; newmsg->next = 0; if (queue->last == 0) { queue->last = newmsg; queue->first = newmsg; } else { queue->last->next = newmsg; queue->last = newmsg; } if(queue->length == 0) pthread_cond_broadcast(&queue->cond); queue->length++; pthread_mutex_unlock(&queue->mutex); return 0; } int thread_queue_get(struct threadqueue *queue, const struct timespec *timeout, struct threadmsg *msg) { struct msglist *firstrec; int ret = 0; struct timespec abstimeout; if (queue == 0 || msg == 0) { return EINVAL; } if (timeout) { struct timeval now; gettimeofday(&now, 0); abstimeout.tv_sec = now.tv_sec + timeout->tv_sec; abstimeout.tv_nsec = (now.tv_usec * 1000) + timeout->tv_nsec; if (abstimeout.tv_nsec >= 1000000000) { abstimeout.tv_sec++; abstimeout.tv_nsec -= 1000000000; } } pthread_mutex_lock(&queue->mutex); while (queue->first == 0 && ret != ETIMEDOUT) { if (timeout) { ret = pthread_cond_timedwait(&queue->cond, &queue->mutex, &abstimeout); } else { pthread_cond_wait(&queue->cond, &queue->mutex); } } if (ret == ETIMEDOUT) { pthread_mutex_unlock(&queue->mutex); return ret; } firstrec = queue->first; queue->first = queue->first->next; queue->length--; if (queue->first == 0) { queue->last = 0; queue->length = 0; } msg->data = firstrec->msg.data; msg->msgtype = firstrec->msg.msgtype; msg->qlength = queue->length; release_msglist(queue,firstrec); pthread_mutex_unlock(&queue->mutex); return 0; } int thread_queue_cleanup(struct threadqueue *queue, int freedata) { struct msglist *rec; struct msglist *next; struct msglist *recs[2]; int ret,i; if (queue == 0) { return EINVAL; } pthread_mutex_lock(&queue->mutex); recs[0] = queue->first; recs[1] = queue->msgpool; for(i = 0; i < 2 ; i++) { rec = recs[i]; while (rec) { next = rec->next; if (freedata) { free(rec->msg.data); } free(rec); rec = next; } } pthread_mutex_unlock(&queue->mutex); ret = pthread_mutex_destroy(&queue->mutex); pthread_cond_destroy(&queue->cond); return ret; } long thread_queue_length(struct threadqueue *queue) { long counter; pthread_mutex_lock(&queue->mutex); counter = queue->length; pthread_mutex_unlock(&queue->mutex); return counter; }
0
#include <pthread.h> struct signal { int active; pthread_mutex_t mutex; sem_t semaphore; }; static struct signal sig; void* thread (void* param) { sleep(5); pthread_mutex_lock(&sig.mutex); sig.active = 1; pthread_mutex_unlock(&sig.mutex); sem_post(&sig.semaphore); printf("Signal Thread -- upped semaphore\\n"); pthread_exit(0); } int main (int argc, char** argv) { pthread_t tid; sig.active = 0; pthread_mutex_init(&sig.mutex, 0); sem_init(&sig.semaphore, 0, 0); pthread_create(&tid, 0, thread, 0); pthread_mutex_lock(&sig.mutex); while (!sig.active) { printf("Main Thread -- waiting for signal\\n"); pthread_mutex_unlock(&sig.mutex); sem_wait(&sig.semaphore); pthread_mutex_lock(&sig.mutex); printf ("Main Thread -- received signal via binary semaphore\\n"); } printf ("Main Thread -- are we active? "); if (sig.active) printf("YES!\\n"); else printf("NO?! (oops, that shouldn't happen!)\\n"); pthread_mutex_unlock(&sig.mutex); pthread_join(tid, 0); return 0; }
1
#include <pthread.h> void *hit(void *); float elapsed_time_msec(struct timespec *, struct timespec *, long *, long *); long num_hits=0, num_threads=0; pthread_mutex_t mutex; int main (int argc, char *argv[]) { float pi; pthread_t tid[32]; int i, myid[32]; struct timespec t0, t1; unsigned long sec, nsec; float comp_time; if (argc != 2) { printf("Usage: %s <num_threads>\\n", argv[0]); exit(0); } num_threads = atoi(argv[1]); if (num_threads > 32) { printf("num_threads > MAXTHREADS (%d)\\n", 32); exit(0); } ; if (clock_gettime(CLOCK_MONOTONIC, &(t0)) < 0) { perror("clock_gettime( ):"); exit(1); }; pthread_mutex_init(&mutex, 0); for (i = 0; i < num_threads; i++) { myid[i] = i; pthread_create(&tid[i], 0, hit, &myid[i]); } for (i = 0; i < num_threads; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); pi = 4.0 * num_hits / (100*1000*1000); ; if (clock_gettime(CLOCK_MONOTONIC, &(t1)) < 0) { perror("clock_gettime( ):"); exit(1); }; comp_time = elapsed_time_msec(&t0, &t1, &sec, &nsec); num_threads, pi, (long) (100*1000*1000), comp_time); pthread_exit(0); } void *hit(void * tid) { int myid = *((int *)tid); long start = (myid * (long)(100*1000*1000))/num_threads; long end = ((myid+1) * (long)(100*1000*1000)) /num_threads; long i, my_hits=0; double x, y; for (i=start; i < end; i++) { x = ((double) random())/ 32767; y = ((double) random())/ 32767; if (x*x + y*y < 1.0) my_hits++; } pthread_mutex_lock (&mutex); num_hits += my_hits; pthread_mutex_unlock (&mutex); pthread_exit(0); } float elapsed_time_msec(struct timespec *begin, struct timespec *end, long *sec, long *nsec) { if (end->tv_nsec < begin->tv_nsec) { *nsec = 1000000000 - (begin->tv_nsec - end->tv_nsec); *sec = end->tv_sec - begin->tv_sec -1; } else { *nsec = end->tv_nsec - begin->tv_nsec; *sec = end->tv_sec - begin->tv_sec; } return (float) (*sec) * 1000 + ((float) (*nsec)) / 1000000; }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t full; sem_t empty; char bufferpool[5][100]; int in = 0; int out = 0; pthread_t producers[3]; pthread_t consumers[4]; void* produce(void* args); void* consume(void* args); FILE* file; int t[4]={1,2,3,4}; int main(){ pthread_mutex_init(&mutex,0); int ret1=sem_init(&full,0,0); int ret2=sem_init(&empty,0,5); if(ret1!=ret2) printf("sem init failed\\n"); if((file=fopen("resource.txt","r"))==0){ printf("File open failed...\\n"); return 1; } int i; for(i = 0; i <= 2; i++){ int ret=pthread_create(&producers[i],0,produce,&t[i]); if(ret != 0) printf("Failed to create producer %d \\n",t[i]); } for(i = 0; i <= 3; i++){ int ret=pthread_create(&consumers[i],0,consume,&t[i]); if(ret != 0) printf("Failed to create consumer %d \\n",t[i]); } for(i = 0;i < 3;i++ ){ pthread_join(producers[i],0); } for(i = 0;i < 4;i++ ){ pthread_join(consumers[i],0); } fclose(file); return 0; } void* produce(void* args){ int id = *(int*) args; char product[50]={0}; while(1){ sem_wait(&empty); pthread_mutex_lock(&mutex); if(fgets(product,50,file)){ strcpy(bufferpool[in],product); in = (in + 1) % 5; printf("A product has been product by producer%d\\n",id); } else if(ferror(file)){ printf("Error uccured when producer %d reading the file!\\n",id); pthread_mutex_unlock(&mutex); pthread_exit(0); } else if(feof(file)){ printf("The producers finished producing.\\n"); pthread_mutex_unlock(&mutex); pthread_exit(0); } sleep(2); pthread_mutex_unlock(&mutex); sem_post(&full); } return ((void*)0); } void* consume(void* args){ int id = *(int*) args; char product[50]={0}; while(1){ sem_wait(&full); pthread_mutex_lock(&mutex); if(strcpy(product,bufferpool[out])){ printf(">***>Consumer %d has consumed an item, the item is::: %s\\n",id,product); out = (out + 1) % 5; } else{ printf("The consumer %d is out of work.\\n",id); } pthread_mutex_unlock(&mutex); sem_post(&empty); } return ((void*)0); }
1
#include <pthread.h> struct pair_count { short pair; int count; }; pthread_mutex_t mutex; struct pair_count pc[100000]; int pair_num = 0; int find_pair(short* pair) { int i; for (i = 0; i < pair_num; i++) { if (pc[i].pair == pair) return i; } return -1; } void add_pair(short* pair) { pthread_mutex_lock (&mutex); int ret = find_pair(pair); if (ret != -1) (pc[ret].count)++; else { pc[pair_num].pair = pair; (pc[pair_num].count)++; pair_num++; } pthread_mutex_unlock (&mutex); } void read_pairs() { int i; for (i = 0; i < pair_num; i++) { printf("Short: %hd\\n", pc[i].pair); printf("Count: %i\\n", pc[i].count); } } void *file_read(void *filename) { FILE *fp; fp = fopen(filename, "r"); if (fp == 0) { printf("ERROR, while opening the file %s\\n", filename); pthread_exit(0); } short x; while (fread(&x, sizeof x, 1, fp) != 0) add_pair(x); pthread_exit(0); } int main(int argc, char const *argv[]) { int i; int rc; pthread_t thread[50]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&mutex, 0); for (i = 1; i < argc; ++i) { rc = pthread_create(&thread[i-1], &attr, file_read, (void *)argv[i]); if (rc) { printf("ERROR, return code from pthread_create() is %d\\n", rc); exit (-1); } } pthread_attr_destroy(&attr); for (i = 1; i < argc; ++i) { rc = pthread_join(thread[i-1], 0); if (rc) { printf("ERROR, return code from pthread_join() is %d\\n", rc); exit(-1); } } read_pairs(); pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> long long sum; pthread_mutex_t sumLock; int gcd(int a, int b) { return a < b ? gcd(b, a) : b == 0 ? a : gcd(b, a % b); } int phi(int n) { int i, r = 0; for( i=1; i<n; i++ ) if ( gcd(n, i) == 1 ) r++; return r; } void* threadRoutine(void* arg) { pair p = *((pair*)arg); int n; for( n=p.first; n<=p.last; n++ ) { pthread_mutex_lock(&sumLock); sum += phi(n); pthread_mutex_unlock(&sumLock); } } int main() { pthread_t tid[8]; pair intervals[8]; int low = 2; int high = 30000; int job_size = (high - low + 1) / 8; int remaining = (high - low + 1) % 8; int i, first = low, last; for( i=0; i<8; i++ ) { intervals[i].first = first; intervals[i].last = first + job_size - 1; if ( remaining > 0 ) { intervals[i].last++; remaining--; } first = intervals[i].last + 1; } sum = 0; pthread_mutex_init(&sumLock, 0); for( i=0; i<8; i++ ) { pthread_create(&tid[i], 0, threadRoutine, &intervals[i]); } for( i=0; i<8; i++ ) pthread_join(tid[i], 0); printf("%lld\\n", sum); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *producer(void *arg) { long int i; long int loops = (long int)arg; for (i=0; i<loops; i++) { pthread_mutex_lock(&mutex); if (buffer_is_full()) pthread_cond_wait(&cond, &mutex); buffer_put(i); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } return 0; } void *consumer(void *arg) { long int i; long int loops = (long int)arg; for (i=0; i<loops; i++) { pthread_mutex_lock(&mutex); if (buffer_is_empty()) pthread_cond_wait(&cond, &mutex); int tmp = buffer_get(); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); fprintf(stdout, "%d\\n", tmp); } return 0; } int main(int argc, char *argv[]) { int i; pthread_t *thread_handles; struct timeval start, end; float elapsed_time; long int num_producers, num_consumers, items; if (argc <= 3) { exit(-1); } num_producers = strtol(argv[1], 0, 10); num_consumers = strtol(argv[2], 0, 10); items = strtol(argv[3], 0, 10); thread_handles = malloc((num_producers+num_consumers)*sizeof(pthread_t)); fprintf(stdout, "Number of producers = %ld\\n", num_producers); fprintf(stdout, "Number of consumers = %ld\\n", num_consumers); fprintf(stdout, "Number of items = %ld\\n", items); gettimeofday(&start, 0); for (i=0; i<num_producers; i++) if (pthread_create(&thread_handles[i], 0, producer, (void *) (items/num_producers))) { fprintf(stderr, "Error spawning thread\\n"); exit(-1); } for (i=num_producers; i<num_producers+num_consumers; i++) if (pthread_create(&thread_handles[i], 0, consumer, (void *) (items/num_consumers))) { fprintf(stderr, "Error spawning thread\\n"); exit(-1); } for (i=0; i<num_producers+num_consumers; i++) { pthread_join(thread_handles[i], 0); } gettimeofday(&end, 0); elapsed_time = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000000.0; fprintf(stdout, "Elapsed time: %g s\\n", elapsed_time); free(thread_handles); return 0; }
0
#include <pthread.h> pthread_mutex_t stats_lock = PTHREAD_MUTEX_INITIALIZER; int mean, samples, total; void *report_stats(void *p) { int caught; sigset_t sigs_to_catch; printf("\\nreport_stats() started.\\n"); sigemptyset(&sigs_to_catch); sigaddset(&sigs_to_catch, SIGUSR1); for (;;) { sigwait(&sigs_to_catch, &caught); pthread_mutex_lock(&stats_lock); mean = total/samples; printf("\\nreport_stats(): mean = %d, samples = %d\\n", mean, samples); pthread_mutex_unlock(&stats_lock); } return 0; } void *worker_thread(void *p) { int item; time_t now; int *amtp=(int *)p; for (;;) { sleep((*amtp)*9); now = time(0); pthread_mutex_lock(&stats_lock); total+=((int)now)%60; samples++; pthread_mutex_unlock(&stats_lock); } return 0; } extern int main(void) { int i; pthread_t threads[10]; int num_threads = 0; sigset_t sigs_to_block; struct sigaction action; printf("main() running in thread 0x%x\\n", pthread_self()); sigemptyset(&sigs_to_block); sigaddset(&sigs_to_block, SIGUSR1); pthread_sigmask(SIG_BLOCK, &sigs_to_block, 0); pthread_create(&threads[num_threads++], 0, report_stats, 0); for (i=num_threads; i<10; i++) { pthread_create(&threads[num_threads++], 0, worker_thread, &i); } printf("main()\\t\\t\\t\\t%d threads created\\n",num_threads); for (i = 0; i < num_threads; i++) { pthread_join(threads[i], 0); printf("main()\\t\\tjoined to thread %d \\n", i); } printf("main()\\t\\tall %d threads have finished. \\n", num_threads); return 0; }
1
#include <pthread.h> struct list_head { struct list_head *next ; struct list_head *prev ; }; struct s { int datum ; struct list_head list ; }; struct cache { struct list_head slot[10] ; pthread_mutex_t slots_mutex[10] ; }; struct cache c ; static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; INIT_LIST_HEAD(&p->list); return p; } static inline void list_add(struct list_head *new, struct list_head *head) { struct list_head *next = head->next; next->prev = new; new->next = next; new->prev = head; head->next = new; } inline static struct list_head *lookup (int d) { int hvalue; struct list_head *p; p = c.slot[hvalue].next; return p; } void *f(void *arg) { struct s *pos ; int j; struct list_head const *p ; struct list_head const *q ; while (j < 10) { pthread_mutex_lock(&c.slots_mutex[j]); p = c.slot[j].next; pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list)); while (& pos->list != & c.slot[j]) { pos->datum++; q = pos->list.next; pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list)); } pthread_mutex_unlock(&c.slots_mutex[j]); j ++; } return 0; } int main() { struct list_head *p1, *p2; pthread_t t1, t2; for (int i = 0; i < 10; i++) { INIT_LIST_HEAD(&c.slot[i]); pthread_mutex_init(&c.slots_mutex[i], 0); for (int j = 0; j < 30; j++) list_add(&new(j*i)->list, &c.slot[i]); } p1 = lookup(1); p2 = lookup(2); p1->next = p2->next; pthread_create(&t1, 0, f, 0); pthread_create(&t2, 0, f, 0); return 0; }
0
#include <pthread.h> pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex; int num_str=1, flag=0; void* thread_func_writer(void * arg){ char str[30]; time_t cur_time; struct tm * tv; int i, try_lock, fd; int len_str; if ((fd = open("./File.txt", O_RDWR | O_CREAT, 0744)) == -1){ printf("Ошибка открытия файла\\n"); exit(0); } while(1){ pthread_mutex_lock(&mutex); cur_time = time(0); tv = localtime(&cur_time); len_str = sprintf (str, "%d\\t %s", num_str, asctime(tv)); write(fd, str, len_str); flag = 1; num_str++; pthread_cond_signal(&cond_var); pthread_mutex_unlock(&mutex); sleep(1); } close(fd); pthread_exit(0); } void* thread_func_reader(void* arg){ int fd, buffer_read=0, buffer_written=0, i; char buffer[30]; if ((fd = open("./File.txt", O_CREAT|O_RDONLY, 0744)) == -1){ printf("Ошибка открытия файла\\n"); exit(0); } while(1){ pthread_mutex_lock(&mutex); while (flag != 1){ pthread_cond_wait(&cond_var, &mutex); } printf("Thread: %lx:\\n", pthread_self()); while ((buffer_read = read(fd, buffer, 30)) > 0){ buffer_written = write(1, buffer, buffer_read); if (buffer_written != buffer_read) printf("Ошибка чтения"); } flag = 0; pthread_mutex_unlock(&mutex); sleep(5); } close(fd); pthread_exit(0); } int main() { int i; pthread_t thread_writer; pthread_t thread_reader[10]; if(pthread_create(&thread_writer, 0, thread_func_writer, 0)<0) printf("Ошибка создания писателя\\n"); for(i=0; i<10; i++){ if(pthread_create(&thread_reader[i], 0, thread_func_reader, 0)<0) printf("Ошибка создания читателя\\n"); } pthread_join(thread_writer, 0); for(i=0; i<10;i++){ pthread_join(thread_reader[i], 0); } return 0; }
1
#include <pthread.h> struct cycle_buf_t { uint32_t size; uint32_t in; uint32_t out; uint8_t *buf; pthread_mutex_t rw_lock; }; static struct cycle_buf_t* cycle_init(void) { struct cycle_buf_t* cycle_p; cycle_p = calloc( 1, sizeof(*cycle_p) ); if ( !cycle_p ) { exit( 1 ); } cycle_p->buf = calloc( 1, (1024 * 1024) ); if ( !cycle_p->buf ) { free( cycle_p ); exit( 1 ); } cycle_p->size = (1024 * 1024); cycle_p->in = cycle_p->out = 0; pthread_mutex_init( &cycle_p->rw_lock, 0 ); return(cycle_p); } static int32_t in_buf( struct cycle_buf_t* cycle_p, uint8_t *date, uint32_t lenth ) { int32_t ret = -1; uint32_t re_len, w_len; if ( !cycle_p ) return(ret); re_len = ( (lenth) < ((cycle_p->size - (cycle_p->in + cycle_p->out))) ? (lenth): ((cycle_p->size - (cycle_p->in + cycle_p->out))) ); w_len = ( (re_len) < ((cycle_p->size - ((cycle_p->size - 1) & cycle_p->in) )) ? (re_len): ((cycle_p->size - ((cycle_p->size - 1) & cycle_p->in) )) ); printf("w_len: %d\\n",w_len); memcpy( cycle_p->buf + ((cycle_p->size - 1) & cycle_p->in), date, w_len ); memcpy( cycle_p->buf, date + 1, lenth-w_len); cycle_p->in += lenth; return(lenth); } static int32_t out_buf( struct cycle_buf_t* cycle_p, uint8_t *date, uint32_t lenth ) { int32_t ret = -1; uint32_t re_len, r_len; if ( !cycle_p ) return(ret); re_len = ( (lenth) < ((cycle_p->in - cycle_p->out)) ? (lenth): ((cycle_p->in - cycle_p->out)) ); printf("in: %d out :%d re_len:%d \\n",cycle_p->in,cycle_p->out,re_len); r_len = ( (re_len) < ((cycle_p->size - ((cycle_p->size - 1) & cycle_p->out))) ? (re_len): ((cycle_p->size - ((cycle_p->size - 1) & cycle_p->out))) ); printf("r_len: %d\\n",r_len); memcpy( date, cycle_p->buf + ((cycle_p->size - 1) & cycle_p->out), r_len ); memcpy( date +1, cycle_p->buf, lenth-r_len); cycle_p->out += r_len; return(r_len); } static void * start_write( void *agrv ) { pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, 0 ); struct cycle_buf_t* cycle_p = (struct cycle_buf_t *)agrv; uint8_t *buf = "test cycle buffer"; pthread_detach(pthread_self()); while ( 1 ) { pthread_mutex_lock(&cycle_p->rw_lock); in_buf(cycle_p, buf, strlen((char *)buf) ); printf("----\\n"); pthread_mutex_unlock(&cycle_p->rw_lock); usleep( 50000 ); } return 0; } static void * start_read( void *agrv ) { uint8_t buf[1024]; int count,i =0; struct cycle_buf_t* cycle_p = (struct cycle_buf_t *)agrv; pthread_detach(pthread_self()); while ( 1 ) { pthread_mutex_lock(&cycle_p->rw_lock); count = out_buf(cycle_p, buf, sizeof(buf) ); pthread_mutex_unlock(&cycle_p->rw_lock); printf("\\n"); write(1,buf,count); printf("%d \\n",i++); usleep( 50000 ); } return 0; } int main( void ) { int result; pthread_t pthr1, pthr2; struct cycle_buf_t* cyle_p = cycle_init(); if(!cyle_p) return -1; result = pthread_create( &pthr1, 0, start_write, cyle_p ); if ( result < 0 ) { fprintf( stderr, "pthread_create() %s", strerror( errno ) ); exit( 1 ); } result = pthread_create( &pthr2, 0, start_read, cyle_p ); if ( result < 0 ) { fprintf( stderr, "pthread_create() %s", strerror( errno ) ); pthread_cancel( pthr1 ); exit( 1 ); } pthread_mutex_destroy(&cyle_p->rw_lock); while(1); exit( 0 ); }
0
#include <pthread.h> int id, eat_count; pthread_t thread; struct fork *right_neighbor, *left_neighbor; }ph; int num; pthread_mutex_t mutex; }fr; void* ph_life(ph* p){ srand(time(0)); int i = 0; for(i = 0; i < p -> eat_count; ++i){ printf("philosopher %d is sleep \\n", p->id); sleep(rand() % 20); if(( p -> id) % 2 ){ pthread_mutex_lock(&p -> left_neighbor -> mutex); pthread_mutex_lock(&p -> right_neighbor -> mutex); } else{ pthread_mutex_lock(&p -> right_neighbor -> mutex); pthread_mutex_lock(&p -> left_neighbor -> mutex); } printf("philosopher %d eat \\n", p->id); if( (p -> id) % 2){ pthread_mutex_unlock(&p -> right_neighbor -> mutex); pthread_mutex_unlock(&p -> left_neighbor -> mutex); } else{ pthread_mutex_unlock(&p -> left_neighbor -> mutex); pthread_mutex_unlock(&p -> right_neighbor -> mutex); } } pthread_exit(0); } int main(int argc, char **argv){ if (argc != 3){ printf("Error\\n"); return 0; } int count_of_philosophers = 0, eat_count = 0; sscanf(argv[1], "%d", &count_of_philosophers); sscanf(argv[2], "%d", &eat_count); fr forks[count_of_philosophers]; int i; for(i = 0; i < count_of_philosophers; ++i){ forks[i].num = i; if(pthread_mutex_init(&forks[i].mutex, 0)){ fprintf(stderr, "ERROR\\n"); } } ph philosophers[count_of_philosophers]; for(i = 0; i < count_of_philosophers; ++i){ philosophers[i].id = i; philosophers[i].eat_count = eat_count; philosophers[i].right_neighbor = &forks[i + 1]; philosophers[i].left_neighbor = &forks[i]; } philosophers[count_of_philosophers - 1].right_neighbor = &forks[0]; for(i = 0; i < count_of_philosophers; ++i){ pthread_create(&philosophers[i].thread, 0, (void* (*) (void*))ph_life, &philosophers[i]); } for(i = 0; i < count_of_philosophers; ++i){ void *res; pthread_join(philosophers[i].thread, &res); } for(i = 0; i < count_of_philosophers; ++i){ pthread_mutex_destroy(&forks[i].mutex); } return 0; }
1
#include <pthread.h> int balance = 1000; int credits = 0; int debits = 0; pthread_mutex_t lock; void * transactions(void * args){ int i,v; for(i=0;i<100;i++){ pthread_mutex_lock(&lock); v = (int) random() % 100; if( random()% 2){ balance = balance + v; credits = credits + v; }else{ balance = balance - v; debits = debits + v; } pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char * argv[]){ int n_threads,i; pthread_t * threads; if(argc < 2){ fprintf(stderr, "ERROR: Require number of threads\\n"); exit(1); } n_threads = atol(argv[1]); if(n_threads <= 0){ fprintf(stderr, "ERROR: Invalivd value for number of threads\\n"); exit(1); } threads = calloc(n_threads, sizeof(pthread_t)); pthread_mutex_init(&lock, 0); for(i=0;i<n_threads;i++){ pthread_create(&threads[i], 0, transactions, 0); } for(i=0;i<n_threads;i++){ pthread_join(threads[i], 0); } printf("\\tCredits:\\t%d\\n", credits); printf("\\t Debits:\\t%d\\n\\n", debits); printf("%d+%d-%d= \\t%d\\n", 1000,credits,debits, 1000 +credits-debits); printf("\\t Balance:\\t%d\\n", balance); free(threads); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> { int count; int *array; }arr_num; double shared_x; pthread_mutex_t lock_x; void swap(int* a, int* b) { int aux; aux = *a; *a = *b; *b = aux; } int divide(int *vec, int left, int right) { int i, j; i = left; for (j = left + 1; j <= right; ++j) { if (vec[j] < vec[left]) { ++i; swap(&vec[i], &vec[j]); } } swap(&vec[left], &vec[i]); return i; } void quickSort(int *vec, int left, int right) { int r; if (right > left) { r = divide(vec, left, right); quickSort(vec, left, r - 1); quickSort(vec, r + 1, right); } } void quick_sort (int *a, int n) { int i, j, p, t; if (n < 2) return; p = a[n / 2]; for (i = 0, j = n - 1;; i++, j--) { while (a[i] < p) i++; while (p < a[j]) j--; if (i >= j) break; t = a[i]; a[i] = a[j]; a[j] = t; } quick_sort(a, i); quick_sort(a + i, n - i); } void* quick_sort_m (void* parameters) { struct arr_num* arr = (struct arr_num*) parameters; int i,j,p,t,th_num; pthread_t thread[25000]; if (arr->count < 2) return; p=arr->array[arr->count/2]; for(i = 0,j=arr->count-1;; i++,j++) { while(arr->array[i]<p) i++; while (p<arr->array[j]) j--; if (i >= j) break; t = arr->array[i]; arr->array[i] = arr->array[j]; arr->array[j] = t; } pthread_mutex_lock(&lock_x); th_num++; pthread_create (&thread[th_num], 0, &quick_sort_m,&arr); pthread_join (thread[th_num], 0); pthread_mutex_unlock(&lock_x); pthread_mutex_lock(&lock_x); th_num++; arr->array=arr->array+i; arr->count=arr->count-i; pthread_create (&thread[th_num], 0, &quick_sort_m,&arr); pthread_join (thread[th_num], 0); pthread_mutex_unlock(&lock_x); } int run_s(int num){ int a[num],i,n; n = sizeof a / sizeof a[0]; for (i=0;i<num;i++) a[i]=rand() % num + 1; for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\\n" : " "); printf("\\n----------- sorted -----------\\n"); quickSort(a,0, n); for (i = 0; i < n; i++) printf("%d%s", a[i], i == n - 1 ? "\\n" : " "); return 0; } int run_m(int num){ struct arr_num an; int r,j; pthread_t thread[25000]; pthread_mutex_init(&lock_x, 0); an.count=num; an.array= malloc(sizeof(int) * an.count); for (r=0;r<an.count;r++) { an.array[r]=rand() % num - 1; printf(" -- %d - %d -- \\n",r,an.array[r]); } pthread_create (&thread[0], 0, &quick_sort_m,&an); pthread_join (thread[0], 0); printf("\\n----------- sorted -----------\\n"); for (j=0;j<an.count;j++) printf(" -- %d - %d --\\n",j,an.array[j]); return 0; } void help(){ printf("\\nUsage: qs [OPTION]... [SIZE]...\\nSort with quicksort algoritm a random array of SIZE, SIZE and OPTION are mandatory,SIZE must be a integer, OPTION must be [-s/-m], a default run displays this help and exit.\\n\\nMandatory arguments to long options are mandatory for short options too.\\n\\t-m run with multiprocess support\\n\\t-s run without multiprocess support\\n\\t\\t-h display this help and exit\\n\\t\\t-v output version information and exit\\n\\n"); } void vers(){ printf("\\nqs 1.02\\nCopyright (C) 2014 Free Software Foundation, Inc.\\nLicense GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\\nThis is free software: you are free to change and redistribute it.\\nThere is NO WARRANTY, to the extent permitted by law.\\n\\nWritten by Gonçalo Faria, Luis Franco, and Vitor Filipe \\n\\n"); } int main (int argc, char *argv[]) { int rtn,total,opt; switch(argc){ case 2: opt = getopt(argc, argv, "v"); if(opt == 'v') { vers(); rtn=0; } else { help(); rtn=1; } break; case 3: opt = getopt(argc, argv, "s:m:"); if(opt == 's') { total=atoi(argv[2]); rtn=run_s(total); } else if (opt == 'm') { printf("2do\\n"); total=atoi(argv[2]); rtn=run_m(total); } else { help(); rtn=1; } break; default: help(); rtn=1; break; } return rtn; }
1
#include <pthread.h> pthread_mutex_t mutex; int counter = 0; void* justAnotherFunction(void* arg) { long threadID = (long) arg; pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); pthread_exit((void*) threadID); } int main() { long tID; int ret; void* status; pthread_t thread[10]; pthread_attr_t attr; pthread_mutex_init(&mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(tID = 0 ; tID < 10 ; tID++) { if((ret = pthread_create( &thread[tID], &attr, justAnotherFunction, (void*) tID)) > 0) { printf( tID, ret); exit(1); } } pthread_attr_destroy(&attr); for(tID = 0 ; tID < 10 ; tID++) { if((ret = pthread_join(thread[tID], &status)) > 0) { printf( tID, ret); exit(1); } } pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err = 0; int signo = 0; while(1) { err = sigwait(&mask, &signo); if (err != 0) { err_exit(err, "sigwait failed"); } printf("signo = %d\\n", signo); switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return 0; default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(void) { int err = 0; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { err_exit(err, "pthread_sigmask SIG_BLOCK error"); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { err_exit(err, "can't create thread"); } pthread_mutex_lock(&lock); while(quitflag == 0) { pthread_cond_wait(&waitloc, &lock); } pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { err_sys("SIG_SETMASK error"); } exit(0); }
1
#include <pthread.h> static char Message_Buffer[10000]; static pthread_mutex_t Si_Ui_Mutex; static int Message_Pos; static char Message_String[SI_UI_MAX_MESSAGE_SIZE]; static char Command_Delim; void si_ui_init(void) { Command_Delim = ';'; si_comm_open(); pthread_mutex_init(&Si_Ui_Mutex, 0); Message_Pos = 0; } static void remove_trailing_command_delim(char buffer []) { int len; len = strlen(buffer); if (buffer[len-1] == Command_Delim) { buffer[len-1] = '\\0'; } } static void send_buffer(void) { int si_comm_return_value; int n_tries; const int max_n_tries = 10000; const int delay_ms_between_tries = 100; remove_trailing_command_delim(Message_Buffer); n_tries = 0; do { si_comm_return_value = si_comm_write(Message_Buffer); n_tries++; if (si_comm_return_value != SI_COMM_OK) { pthread_mutex_unlock(&Si_Ui_Mutex); usleep(delay_ms_between_tries * 1000); pthread_mutex_lock(&Si_Ui_Mutex); } } while (n_tries < max_n_tries && si_comm_return_value != SI_COMM_OK); if (si_comm_return_value != SI_COMM_OK) { printf("si_ui: NOTE: communication problem - number of write tries: %d", n_tries); } } static void append_to_buffer(char message[]) { size_t i; int buffer_full = 0; for (i = 0; i < strlen(message) && !buffer_full; i++) { Message_Buffer[Message_Pos] = message[i]; Message_Pos++; if (Message_Pos >= 10000 - 1) { printf("NOTE: message buffer OVERFLOW\\n"); Message_Buffer[Message_Pos] = '\\0'; buffer_full = 1; Message_Pos = 0; } } if (!buffer_full) { Message_Buffer[Message_Pos] = Command_Delim; Message_Pos++; Message_Buffer[Message_Pos] = '\\0'; } } void si_ui_draw_begin(void) { pthread_mutex_lock(&Si_Ui_Mutex); Message_Pos = 0; append_to_buffer("draw_begin"); pthread_mutex_unlock(&Si_Ui_Mutex); } void si_ui_draw_end(void) { pthread_mutex_lock(&Si_Ui_Mutex); append_to_buffer("draw_end"); append_to_buffer("\\n"); send_buffer(); pthread_mutex_unlock(&Si_Ui_Mutex); } void si_ui_draw_string(char string[], int x_coord, int y_coord) { pthread_mutex_lock(&Si_Ui_Mutex); sprintf(Message_String, "draw_string:%08X:%08X:%s", x_coord, y_coord, string); append_to_buffer(Message_String); pthread_mutex_unlock(&Si_Ui_Mutex); } void si_ui_draw_image(char image_name[], int x_coord, int y_coord) { pthread_mutex_lock(&Si_Ui_Mutex); sprintf(Message_String, "draw_image:%s:%08X:%08X", image_name, x_coord, y_coord); append_to_buffer(Message_String); pthread_mutex_unlock(&Si_Ui_Mutex); } void si_ui_show_error(char message[]) { si_ui_draw_begin(); pthread_mutex_lock(&Si_Ui_Mutex); sprintf(Message_String, "show_error:%s", message); append_to_buffer(Message_String); pthread_mutex_unlock(&Si_Ui_Mutex); si_ui_draw_end(); } void si_ui_set_size(int x_size, int y_size) { si_ui_draw_begin(); pthread_mutex_lock(&Si_Ui_Mutex); sprintf(Message_String, "set_size:%08X:%08X", x_size, y_size); append_to_buffer(Message_String); pthread_mutex_unlock(&Si_Ui_Mutex); si_ui_draw_end(); } void si_ui_receive(char message[]) { int si_comm_return_value; int n_tries; const int max_n_tries = 10000; const int delay_ms_between_tries = 250; n_tries = 0; pthread_mutex_lock(&Si_Ui_Mutex); do { si_comm_return_value = si_comm_read(message, SI_UI_MAX_MESSAGE_SIZE); n_tries++; if (si_comm_return_value != SI_COMM_OK) { pthread_mutex_unlock(&Si_Ui_Mutex); usleep(delay_ms_between_tries * 1000); pthread_mutex_lock(&Si_Ui_Mutex); } } while (n_tries < max_n_tries && si_comm_return_value != SI_COMM_OK); if (si_comm_return_value != SI_COMM_OK) { printf("si_ui: NOTE: communication problem - number of read tries %d", n_tries); } pthread_mutex_unlock(&Si_Ui_Mutex); } void si_ui_close(void) { si_comm_close(); }
0
#include <pthread.h> int rbuf_writeto(struct io_params *iop) { struct rbuf_entry *w_ptr; int i, r; w_ptr = iop->rbuf_p; if (pthread_mutex_lock(&w_ptr->lock) != 0) log_die("pthread_mutex_lock locking error %d"); pthread_mutex_lock(&iop->listlock); *iop->listready = 1; pthread_mutex_unlock(&iop->listlock); pthread_cond_signal(&iop->readable); for (;;) { printf("w_ptr id: %d\\n", w_ptr->id); if ((i = readv(iop->io_fd, w_ptr->iov, 1)) > 0) { printf("w_ptr read %d bytes from %d into ringbuff\\n", i, iop->io_fd); w_ptr->iov[0].iov_len = i; if (pthread_mutex_lock(&w_ptr->next->lock) < 0) log_die("pthread_mutex_lock locking error: %d"); if (pthread_mutex_unlock(&w_ptr->lock) < 0) printf("pthread_mutex_unlock unlocking error"); w_ptr = w_ptr->next; } else if (i == 0) { sleep(2); continue; } else { if (errno == EPIPE || errno == ENETDOWN || errno == EDESTADDRREQ) log_msg("readv error - read end closed\\n"); return -1; } sleep(2); } } int rbuf_readfrom(struct io_params *iop) { struct rbuf_entry *r_ptr; int r; r_ptr = iop->rbuf_p; pthread_mutex_lock(&iop->listlock); while (*iop->listready == 0) pthread_cond_wait(&iop->readable, &iop->listlock); pthread_mutex_unlock(&iop->listlock); if (pthread_mutex_lock(&r_ptr->lock) != 0 ) printf("W.1.1: Failed to get lock for %d\\n", r_ptr->id); for (;;) { printf("r_ptr id: %d\\n", r_ptr->id); if ( (r = writev(iop->io_fd, r_ptr->iov, 1)) < 0) { log_ret("writev error: %d", errno); pthread_mutex_unlock(&r_ptr->lock); pthread_exit(0); } else if (r == 0) { printf("writev(2) returned 0\\n"); sleep(2); continue; } else { printf("\\nW: WROTE %d bytes from ringbuff to %d\\n", iop->io_fd); } r_ptr->iov[0].iov_len = BUFF_SIZE; if (pthread_mutex_lock(&r_ptr->next->lock) != 0 ) log_syserr("pthread_mutex_lock error: %d %s\\n", errno, strerror(errno)); if (pthread_mutex_unlock(&r_ptr->lock) < 0) printf("W.3.1: failed to unlock %d %s\\n", r_ptr->id); r_ptr = r_ptr->next; } } struct rbuf_entry *new_rbuf(void) { int i; struct rbuf_entry *e, *prev_ptr, *head; pthread_mutexattr_t attrs; prev_ptr = 0; pthread_mutexattr_init(&attrs); for (i = 64; i >= 1; i--) { if ((e = malloc(sizeof(struct rbuf_entry))) == 0) log_syserr("rbuf malloc error"); e->id = i; e->iov[0].iov_len = BUFF_SIZE; e->iov[0].iov_base = e->line; pthread_mutex_init(&e->lock, &attrs); if ( prev_ptr != 0 ) { prev_ptr->next = e; } else { head = e; } prev_ptr = e; } e->next = head; rb = head; return head; } void free_rbuf(struct rbuf_entry *rbuf) { int i; struct rbuf_entry *rb, *rb_nxt; rb = rbuf; for (i = 1; i < 65; i++) { rb_nxt = rb->next; free(rb); rb = rb_nxt; } }
1
#include <pthread.h> pthread_mutex_t barrier; pthread_mutex_t minBarrier; pthread_mutex_t maxBarrier; pthread_mutex_t rowBarrier; int numWorkers; int sum; int nextRow = 0; int value; int xIndex; int yIndex; } MINMAX; MINMAX min; MINMAX max; 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); } double start_time, end_time; int size, stripSize; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_mutex_init(&minBarrier,0); pthread_mutex_init(&maxBarrier,0); pthread_mutex_init(&rowBarrier,0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } min.value = matrix[0][0]; max.value = matrix[0][0]; start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); for(l= 0; l< numWorkers; l++) pthread_join(workerid[l],0); end_time = read_timer(); printf("The sum is %d\\n", sum); printf("Max value : %d\\n", max.value); printf("Max x position %d\\n", max.xIndex); printf("Max y position %d\\n", max.yIndex); printf("Min value : %d\\n", min.value); printf("Min x position %d\\n", min.xIndex); printf("Min y position %d\\n", min.yIndex); printf("The execution time is %g sec\\n", end_time - start_time); } int getNewRow(){ pthread_mutex_lock(&rowBarrier); int row = nextRow++; pthread_mutex_unlock(&rowBarrier); return row; } void * Worker(void *arg) { long myid = (long) arg; int j; int row = 0; int localSum; while (row < size) { row = getNewRow(); if(row >= size) break; for (j = 0; j < size; j++) { if(matrix[row][j] > max.value) { pthread_mutex_lock(&minBarrier); if(matrix[row][j] > max.value) { max.value = matrix[row][j]; max.yIndex = row; max.xIndex = j; } pthread_mutex_unlock(&minBarrier); } if(matrix[row][j] < min.value) { pthread_mutex_lock(&maxBarrier); if(matrix[row][j] < min.value){ min.value = matrix[row][j]; min.yIndex = row; min.xIndex = j; } pthread_mutex_unlock(&maxBarrier); } localSum += matrix[row][j]; } pthread_mutex_lock(&barrier); sum += localSum; pthread_mutex_unlock(&barrier); } }
0
#include <pthread.h> struct data { int *a; int *b; int len; int offset; int sliceSt; int sliceEnd; long *myList; }; pthread_t threads[1]; pthread_mutex_t mutex_sum; double sum; void *dot(void *arg) { int i; int start; int end; struct data *d = (struct data*) arg; pthread_mutex_lock(&mutex_sum); for(i = 0; i < 8; i++){ } printf("%d start: \\n", d->sliceSt); printf("%d end: \\n", d->sliceEnd); for(i = d->sliceSt; i < d->sliceEnd; i++); { printf("%d prime: \\n\\n", (int) d->myList[i]); } pthread_mutex_unlock(&mutex_sum); pthread_exit((void*) 0); } int main(int argc, char **argv) { int *a = (int*)malloc(1 * 1000000 * sizeof(int)); int *b = (int*)malloc(1 * 1000000 * sizeof(int)); int i; int Inpt= 0; int rem = 0; struct data d[1]; struct primeArr *primeArray; pthread_attr_t attr; printf("Please enter the max integer to search through for primes: ----> "); scanf("%d",&Inpt); primeArray = crinit_primeArr(Inpt); IgnorePts(primeArray); p_primeArr(primeArray); for(i=0; i<1; ++i) { d[i].myList = primeArray->list; } for(i = 0; i < primeArray->num_of_primes; i++){ } printf("\\n\\n\\n\\n%d <-----NUMBER OF PRIMES \\n\\n", primeArray->num_of_primes); rem = primeArray->num_of_primes % 1; Inpt = primeArray->num_of_primes / 1; for(i=0; i<1000000 * 1; ++i) { a[i] = 1.0; b[i] = 1.0; } sum = 0.0; pthread_mutex_init(&mutex_sum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); printf(" ERROR? \\n\\n"); for(i=0; i<1; ++i) { d[i].a = a; d[i].b = b; d[i].len = 1000000; d[i].offset = i; d[i].sliceSt = (Inpt * i); d[i].sliceEnd = Inpt * (i + 1); if(i == 1 - 1) { d[i].sliceEnd = d[i].sliceEnd + rem; } pthread_create(&threads[i], &attr, dot, (void*)&d[i]); } for(i=0; i<10; i++) { } pthread_attr_destroy(&attr); for(i=0; i<1; ++i) { pthread_join(threads[i], 0); } printf("Sum is %f\\n", sum); free(a); free(b); pthread_mutex_destroy(&mutex_sum); return 0; }
1
#include <pthread.h> static int next_rank = 0, next_tid = 0; static pthread_key_t datakey; static pthread_t tids[P5_MAX_THREADS]; static pthread_mutex_t dprintf_lock; static void freedata(void *); static void freedata(void *p) { free(p); } void p5_init(int flag) { int *p; if (flag) { pthread_key_create(&datakey,freedata); pthread_mutex_init(&dprintf_lock,0); } p = (int *) malloc(sizeof(int)); *p = next_rank++; pthread_setspecific(datakey,(void *)p); } int p5_rank() { int *p; p = (int *) pthread_getspecific(datakey); return *p; } void p5_dprintf(char *fmt, ...) { int rank; va_list ap; rank = *( (int *)pthread_getspecific(datakey) ); pthread_mutex_lock(&dprintf_lock); __builtin_va_start((ap)); printf("%d: ",rank); vprintf(fmt, ap); ; fflush(stdout); pthread_mutex_unlock(&dprintf_lock); } void p5_tcreate( void *(*sub)(void *), void *arg) { pthread_create(&tids[next_tid++], 0, sub, arg); } void p5_finalize() { int i; for (i=0; i < next_tid; i++) pthread_join(tids[i],0); } void askfor_init(struct askfor_monitor *afm, int nthreads) { afm->prob_done = 0; afm->qsize = 0; afm->nthreads = nthreads; pthread_mutex_init(&(afm->mon_lock),0); pthread_cond_init(&(afm->queue_cv),0); } int askfor(struct askfor_monitor *afm, int (*getprob_fxn)(void *), void *problem) { int rc, work_found; pthread_mutex_lock(&(afm->mon_lock)); work_found = 0; while ( ! work_found && ! afm->prob_done) { rc = (*getprob_fxn)(problem); if (rc == 0) { work_found = 1; } else if (afm->qsize == afm->nthreads-1) { afm->prob_done = 1; } else { afm->qsize++; pthread_cond_wait( &(afm->queue_cv), &(afm->mon_lock) ); afm->qsize--; } } if (afm->qsize > 0) pthread_cond_signal(&(afm->queue_cv)); pthread_mutex_unlock(&(afm->mon_lock)); if (afm->prob_done) rc = afm->prob_done; else rc = 0; return rc; } void askfor_update(struct askfor_monitor *afm, int (*putprob_fxn)(void *), void *problem) { pthread_mutex_lock(&(afm->mon_lock)); if (putprob_fxn(problem)) { pthread_cond_signal(&(afm->queue_cv)); } pthread_mutex_unlock(&(afm->mon_lock)); } void askfor_probend(struct askfor_monitor *afm, int code) { pthread_mutex_lock(&(afm->mon_lock)); afm->prob_done = code; pthread_mutex_unlock(&(afm->mon_lock)); }
0
#include <pthread.h> double mivta[5][31]; double totalgral=0.0; double totalsuc[5]; void *sumoVentas(void *sucursalid); void *cargoVentas(void *); pthread_mutex_t cargada_mutex1; pthread_mutex_t cargada_mutex[5]; int cargadas[5]; pthread_cond_t sucursales[5]; int main (int argc, char *argv[]){ int a = 0; int rc, t, status; memset(&mivta,0,sizeof(double)*5*31); memset(&totalsuc,0,sizeof(double)*5); pthread_t thread_cargo; pthread_t threads[5]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&cargada_mutex1, 0); for (a=0; a<5; a++){ pthread_mutex_init(&cargada_mutex[a], 0); } pthread_create(&thread_cargo,0,cargoVentas,0); for(t=0; t<5; t++){ pthread_create(&threads[t], &attr, sumoVentas, (void *) t); } pthread_attr_destroy(&attr); for(t=0; t<5; t++){ rc = pthread_join(threads[t],0); if (rc){ printf("main(): Error, pthread_join() retorna %d\\n", rc); exit(-3); } } for(t=0; t<5; t++) totalgral+=totalsuc[t]; printf("main():Total Gral $ %d\\n",totalgral); pthread_mutex_destroy(&cargada_mutex1); printf("fin main():1\\n"); pthread_exit(0); } void *sumoVentas(void *sucursalid) { int sucid; sucid = (int) sucursalid; printf("thread %d esperando carga de sucursal %d \\n", sucid,sucid); pthread_mutex_lock(&cargada_mutex[sucid]); if ( cargadas[sucid] == 0 ) { printf("thread %d esperando condicion de cargada para sucursal %d \\n", sucid,sucid); pthread_cond_wait(&sucursales[sucid], &cargada_mutex[sucid]); } else { printf("thread %d sumoVentas sucursal %d \\n", sucid,sucid); totalsuc[sucid]=0.0; int d; for(d=0;d<31;d++) { totalsuc[sucid]+=mivta[sucid][d]; } printf("fin thread %d sumatoria de sucursal %d : %d $\\n",sucid,sucid,totalsuc[sucid]); pthread_mutex_unlock(&cargada_mutex[sucid]); } pthread_exit( 0); } void *cargoVentas(void *p) { int s,d; pthread_mutex_lock(&cargada_mutex1); for(s=0;s<5;s++) { for(d=0;d<31;d++) { mivta[s][d] = ((double) random())/10000000.0; cargadas[s] = 1; pthread_cond_signal(&sucursales[s]); } printf("Termine de cargar sucursal %i\\n", s); sleep(4); } pthread_mutex_unlock(&cargada_mutex1); printf("fin thread cargoVentas\\n"); pthread_exit(0); }
1
#include <pthread.h> pthread_t tid[2]; int counter; pthread_mutex_t lock; void *doSomeThing(void *arg) { pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf("\\n Job %d started\\n", counter); for(i=0; i<(0xFFFFFFFF); i++); printf("\\n Job %d finished\\n", counter); pthread_mutex_unlock(&lock); return 0; } int main(int argc, char *argv[]) { int i=0; int err; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } while(i<2) { err = pthread_create(&(tid[i]), 0, &doSomeThing, 0); if (err != 0) printf("\\ncan't create thread[%s]\\n", strerror(err)); i++; } pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv_(const char *name) { char *envbuf; int len; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return 0; } pthread_setspecific(key, envbuf); } len = strlen(name); for (int i=0; environ[i] != 0; i++) { if (strncmp(name, environ[i], len) == 0 && environ[i][len] == '=') { strncpy(envbuf, &environ[i][len+1], 4096 - 1); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return 0; }
1
#include <pthread.h> static char db_root[256]; static char homedir[256]; static char import_root[256]; static char import_homedir[256]; static volatile bool stop = 0; static volatile bool exec = 0; static volatile bool quit = 0; static volatile bool timeout_enable = 1; pthread_mutex_t mutex; int timeout = 0; void progress_callback (int value, int max) { static int last = 0; static time_t lasttime = 0; int now = (value*100)/max; if (now != last && lasttime != time (0)) { lasttime = time (0); interactive_send_int (ACTION_PROGRESS, now); last = now; } } void url_callback (char *url) { interactive_send_text (ACTION_URL, url); } void file_callback (char *file) { interactive_send_text (ACTION_FILE, file); } void *import (void *args) { interactive_send (ACTION_START); interactive_send_text (ACTION_PROGRESS, "ON"); importer_parse_directory (import_root, db_root, progress_callback, url_callback, file_callback, &stop); importer_parse_directory (import_homedir, db_root, progress_callback, url_callback, file_callback, &stop); exec = 0; interactive_send_text (ACTION_PROGRESS, "OFF"); interactive_send (ACTION_END); return 0; } void *interactive (void *args) { char buffer[4096], byte; bool run = 1; pthread_t thread; interactive_send (ACTION_READY); while (run) { int i = 0, size = 0; memset (buffer, '\\0', 4096); while ((size = fread (&byte, 1, 1, stdin))) { if (byte == '\\n') break; buffer[i] = byte; i++; } if (memcmp (buffer, CMD_QUIT, strlen (CMD_QUIT)) == 0 || quit || size == 0) { run = 0; stop = 1; } else if (memcmp (buffer, CMD_IMPORT, strlen (CMD_IMPORT)) == 0) { if (!exec) { stop = 0; exec = 1; pthread_create (&thread, 0, import, 0); } else interactive_send_text (ACTION_ERROR, "cannot do it... other operations in background"); timeout_enable = 1; } else if (memcmp (buffer, CMD_WAIT, strlen (CMD_WAIT)) == 0) { timeout_enable = 0; } else if (memcmp (buffer, CMD_SAVE, strlen (CMD_SAVE)) == 0) { if (!exec) { timeout_enable = 0; interactive_send (ACTION_START); interactive_send_text (ACTION_PROGRESS, "ON"); if (!epgdb_save (progress_callback)) interactive_send_text (ACTION_ERROR, "cannot save data"); interactive_send (ACTION_END); interactive_send_text (ACTION_PROGRESS, "OFF"); } else interactive_send_text (ACTION_ERROR, "cannot do it... other operations in background"); timeout_enable = 1; } else if (memcmp (buffer, CMD_STOP, strlen (CMD_STOP)) == 0) { stop = 1; timeout_enable = 1; } else { interactive_send_text (ACTION_ERROR, "unknow command"); timeout_enable = 1; } pthread_mutex_lock (&mutex); timeout = 0; pthread_mutex_unlock (&mutex); } quit = 1; if (exec) pthread_join (thread, 0); return 0; } void interactive_manager () { pthread_t thread; quit = 0; exec = 0; pthread_mutex_init (&mutex, 0); pthread_create (&thread, 0, interactive, 0); while (1) { pthread_mutex_lock (&mutex); if (exec || !timeout_enable) timeout = 0; else timeout++; if (timeout > 200) { pthread_kill (thread, SIGQUIT); quit = 1; } pthread_mutex_unlock (&mutex); if (quit) break; usleep (100000); } pthread_join (thread, 0); } int main (int argc, char **argv) { int c, i; opterr = 0; bool iactive = 0; strcpy (homedir, argv[0]); for (i = strlen (homedir)-1; i >= 0; i--) { bool ended = 0; if (homedir[i] == '/') ended = 1; homedir[i] = '\\0'; if (ended) break; } sprintf (db_root, DEFAULT_DB_ROOT); sprintf (import_root, DEFAULT_IMPORT_ROOT); while ((c = getopt (argc, argv, "d:i:l:k:r")) != -1) { switch (c) { case 'd': strcpy (db_root, optarg); break; case 'l': strcpy (homedir, optarg); break; case 'i': strcpy (import_root, optarg); break; case 'k': nice (atoi(optarg)); break; case 'r': log_disable (); interactive_enable (); iactive = 1; break; case '?': printf ("Usage:\\n"); printf (" ./crossepg_importer [options]\\n"); printf ("Options:\\n"); printf (" -d db_root crossepg db root folder\\n"); printf (" default: %s\\n", db_root); printf (" -l homedir home directory\\n"); printf (" default: %s\\n", homedir); printf (" -i import_root import root folder\\n"); printf (" default: %s\\n", import_root); printf (" -k nice see \\"man nice\\"\\n"); printf (" -r interactive mode\\n"); printf (" -h show this help\\n"); return 0; } } while (homedir[strlen (homedir) - 1] == '/') homedir[strlen (homedir) - 1] = '\\0'; while (db_root[strlen (db_root) - 1] == '/') db_root[strlen (db_root) - 1] = '\\0'; while (import_root[strlen (import_root) - 1] == '/') import_root[strlen (import_root) - 1] = '\\0'; log_open (db_root); log_banner ("CrossEPG Importer"); sprintf (import_homedir, "%s/import/", homedir); if (epgdb_open (db_root)) log_add ("EPGDB opened"); else { log_add ("Error opening EPGDB"); epgdb_close (); log_close (); return 0; } epgdb_load (); aliases_make (homedir); if (iactive) interactive_manager (); else { volatile bool useless = 0; importer_parse_directory (import_root, db_root, 0, 0, 0, &useless); importer_parse_directory (import_homedir, db_root, 0, 0, 0, &useless); log_add ("Saving data..."); if (epgdb_save (0)) log_add ("Data saved"); else log_add ("Error saving data"); } epgdb_clean (); memory_stats (); log_close (); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; void err_thread(int ret, char *str) { if (ret != 0) { fprintf(stderr, "%s:%s\\n", str, strerror(ret)); pthread_exit(0); } } void *tfn(void *arg) { srand(time(0)); int ret; while (1) { if((ret=pthread_mutex_lock(&mutex))!=0) { printf("ret:%d\\n",ret); } printf("hello "); sleep(rand() % 3); printf("world\\n"); pthread_mutex_unlock(&mutex); sleep(rand() % 3); } return 0; } int main(void) { int flag = 5; pthread_t tid; srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_create(&tid, 0, tfn, 0); while (flag--) { pthread_mutex_lock(&mutex); printf("HELLO "); sleep(rand() % 3); printf("WORLD\\n"); pthread_mutex_unlock(&mutex); sleep(rand() % 3); } pthread_cancel(tid); pthread_join(tid, 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> struct process_fcgs { char * name; int line; int (*func) (void *); void * arg; double init; struct process_fcgs * next; }; static ProcessFCFS head; static int init = 0; static int running = 0; static pthread_mutex_t head_lock; static pthread_mutex_t file_lock; static FILE *log; static int output_info; static int output_line; void fcfs_exec(char *name, int line, double remaining, int (*func) (void *), void *arg) { ProcessFCFS tmp, novo; if (init) pthread_mutex_lock(&head_lock); tmp = head; if (line >= 0 && output_info == 100) { fprintf(stderr, " NEW '%s' (%d)\\n", name, line); } else if (output_info == 99) { fprintf(stderr, "%.3f\\t NEW '%s'\\n", time2(), name); } while (tmp != 0 && tmp->next != 0) tmp = tmp->next; novo = malloc2(sizeof(struct process_fcgs)); novo->name = name; novo->line = line; novo->func = func; novo->arg = arg; novo->next = 0; novo->init = time2(); if (head == 0) head = novo; else tmp->next = novo; if (init) pthread_mutex_unlock(&head_lock); } static void * escalona (void * n) { ProcessFCFS atual; int *number; int flag; double tf; number = (int *)n; while (1) { pthread_mutex_lock(&head_lock); if (head != 0) { atual = head; head = head->next; running++; pthread_mutex_unlock(&head_lock); if (atual->line >= 0 && output_info == 100) { fprintf(stderr, "%d) IN '%s' (%d)\\n", *number, atual->name, atual->line); } else if (output_info == 99) { fprintf(stderr, "%.3f\\t %3d > START '%s'\\n", time2(), *number, atual->name); } atual->func(atual->arg); pthread_mutex_lock(&head_lock); running--; pthread_mutex_unlock(&head_lock); if (atual->line >= 0) { tf = time2(); pthread_mutex_lock(&file_lock); fprintf(log, "%s %.5f %.5f\\n", atual->name, tf, tf-atual->init); output_line++; pthread_mutex_unlock(&file_lock); } if (atual->line >= 0 && output_info == 100) { fprintf(stderr, "%d) END '%s' (%d)\\n", *number, atual->name, output_line-1); } else if (output_info == 99) { fprintf(stderr, "%.3f\\t %3d > END '%s'\\n", time2(), *number, atual->name); } } else { flag = (running == 0 && head == 0); pthread_mutex_unlock(&head_lock); if (flag) { if (output_info == 99) fprintf(stderr, "%.3f\\t %3d > OFF\\n", time2(), *number); return 0; } sleep2 (0.05); } } } void fcfs_init(char *log_file, int output) { pthread_t *threads_ids; int i, threads; int *cpu_n; threads = sysconf(_SC_NPROCESSORS_ONLN); log = fopen(log_file, "w"); output_info = output; output_line = 0; threads_ids = malloc2(sizeof(pthread_t) * threads); cpu_n = malloc2(sizeof(int) * threads); if (pthread_mutex_init(&head_lock, 0) != 0 && pthread_mutex_init(&file_lock, 0) != 0) { fprintf(stderr, "Erro ao criar mutex!\\n"); } else { init = 1; for (i = 0; i < threads; ++i) { cpu_n[i] = i; pthread_create(&threads_ids[i], 0, escalona, &cpu_n[i]); } for (i = 0; i < threads; ++i) { pthread_join(threads_ids[i], 0); } pthread_mutex_destroy(&head_lock); pthread_mutex_destroy(&file_lock); } if (output_info == 100) fprintf(stderr, " MC 0\\n"); fprintf(log, "0\\n"); fclose(log); } int fcfs_run() { return 0; }
0
#include <pthread.h> buffer_item buffer[10]; int insertnum,removenum,all; pthread_mutex_t mutex; sem_t mo1,mo2; sem_t empty; sem_t full; int cnt; void *monitoring(void *para) { while(1) { sem_wait(&mo2); printf("Acknowledge no : %d -> count==:%d\\n",++all,cnt); sem_post(&mo1); } } int insert_item(buffer_item item) { if(sem_wait(&empty)!=0) return -1; pthread_mutex_lock(&mutex); buffer[insertnum]=item; insertnum=(insertnum+1)%10; printf("insert : %d\\n",++cnt); sem_post(&mo2); sem_wait(&mo1); pthread_mutex_unlock(&mutex); sem_post(&full); return 0; } int remove_item(buffer_item *item) { if(sem_wait(&full)!=0) return -1; pthread_mutex_lock(&mutex); *item=buffer[removenum]; buffer[removenum]=0; removenum=(removenum+1)%10; printf("remove : %d\\n",--cnt); sem_post(&mo2); sem_wait(&mo1); pthread_mutex_unlock(&mutex); sem_post(&empty); } void *producer(void *para) { buffer_item item; while(1) { sleep(rand()%5); item=rand(); if(insert_item(item)) printf("report error condition"); else printf("producer produced %d\\n", item); } } void *consumer(void *para) { buffer_item item; while(1) { sleep(rand()%3); if(remove_item(&item)) printf("report error condition"); else printf("consumer consumed %d\\n", item); } } int main(int argc,char *argv[]) { int produce_num=atoi(argv[2]); int consume_num=atoi(argv[3]); int i=0; sem_init(&empty, 0, 10); sem_init(&full, 0, 0); pthread_mutex_init(&mutex,0); sem_init(&mo1, 0, 0); sem_init(&mo2, 0, 0); pthread_t producer_thread; pthread_t consumer_thread; pthread_t monitoring_thread; for(i=0;i<produce_num;i++) pthread_create(&producer_thread,0,producer,0); pthread_create(&monitoring_thread,0,monitoring,0); for(i=0;i<consume_num;i++) pthread_create(&consumer_thread,0,consumer,0); sleep(atoi(argv[1])); return 0; }
1
#include <pthread.h> char * TimeStr[4] = {"2/4", "3/4", "4/4", "6/8"}; int main(void) { char c; int success; run = False; keepgoing = 1; success = init_LED (); if (success == -1) return -1; init_KEY (); status = 3; location = 0; tempo = 90; run = False; printf (" Default: TimeSig %s, Tempo %d, Run %d\\n", TimeStr[status], tempo, run); while (keepgoing) { c = getch(); pthread_mutex_lock (&mutex_lock); switch (c) { case 'q' : printf (" q: Quit!\\n"); break; case 'z' : status = (status + 1) % 4; break; case 'c' : if (tempo == 30) tempo = 30; else tempo -= 5; break; case 'b' : if (tempo == 200) tempo = 200; else tempo += 5; break; case 'm' : if (run == True) run = False; else run = True; } location = 0; if (c == 'q') { pthread_mutex_unlock (&mutex_lock); break; } printf (" Key %c: TimeSig %s, Tempo %d, Run %d\\n", c, TimeStr[status], tempo, run); fflush(stdout); pthread_mutex_unlock (&mutex_lock); } fflush(stdout); exit_KEY (); exit_LED (); return 0; }
0
#include <pthread.h> pthread_once_t once = PTHREAD_ONCE_INIT; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void ofunc(void); void* threadfunc(void *); void cleanup(void *); void handler(int, siginfo_t *, void *); int main(int argc, char *argv[]) { pthread_t thread; struct sigaction act; struct itimerval it; printf("Test 3 of pthread_once() (test versus cancellation)\\n"); act.sa_sigaction = handler; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; sigaction(SIGALRM, &act, 0); timerclear(&it.it_value); it.it_value.tv_usec = 500000; timerclear(&it.it_interval); setitimer(ITIMER_REAL, &it, 0); pthread_mutex_lock(&mutex); pthread_create(&thread, 0, threadfunc, 0); pthread_cancel(thread); pthread_mutex_unlock(&mutex); pthread_join(thread, 0); pthread_once(&once, ofunc); timerclear(&it.it_value); setitimer(ITIMER_REAL, &it, 0); printf("Test succeeded\\n"); return 0; } void cleanup(void *m) { pthread_mutex_t *mu = m; pthread_mutex_unlock(mu); } void ofunc(void) { pthread_testcancel(); } void * threadfunc(void *arg) { pthread_mutex_lock(&mutex); pthread_cleanup_push(cleanup, &mutex); pthread_once(&once, ofunc); pthread_cleanup_pop(1); return 0; } void handler(int sig, siginfo_t *info, void *ctx) { printf("Signal handler was called; main thread deadlocked in " "pthread_once().\\n" "Test failed.\\n"); exit(1); }
1
#include <pthread.h> int ** bigmatrix; int r = 5; int c = 5; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int ** AllocMatrix(int r, int c) { int ** a; int i; a = (int**) malloc(sizeof(int *) * r); assert(a != 0); for (i = 0; i < r; i++) { a[i] = (int *) malloc(c * sizeof(int)); assert(a[i] != 0); } return a; } void FreeMatrix(int ** a, int r, int c) { int i; for (i=0; i<r; i++) { free(a[i]); } free(a); } void GenMatrix(int ** matrix, const int height, const int width) { int i, j; for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { int * mm = matrix[i]; mm[j] = rand() % 10; } } } int AvgElement(int ** matrix, const int height, const int width) { int x=0; int y=0; int ele=0; int i, j; for (i=0; i<height; i++) for (j=0; j<width; j++) { int *mm = matrix[i]; y=mm[j]; x=x+y; ele++; } printf("x=%d ele=%d\\n",x,ele); return x / ele; } void *worker(void *arg) { int *loops = (int *) &arg; int i; for (i=0; i<*loops; i++) { pthread_mutex_lock(&mutex); bigmatrix = AllocMatrix(r,c); GenMatrix(bigmatrix, r, c); pthread_cond_signal(&cond); pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); FreeMatrix(bigmatrix, r, c); } return 0; } int main (int argc, char * argv[]) { pthread_t p1; printf("main: begin \\n"); int loops = 10000; int i; pthread_create(&p1, 0, worker, loops); for(i=0;i<loops;i++) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); int avgele = AvgElement(bigmatrix, r, c); printf("Avg array=%d value=%d\\n",i,avgele); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } pthread_join(p1, 0); return 0; }
0
#include <pthread.h> int process_var3(char* input_path, char* output_path) { struct sigaction sa; memset (&sa, 0, sizeof(sa)); sa.sa_handler = &timer_handler; sigaction (SIGALRM, &sa, 0); struct itimerval timer; timer.it_value.tv_sec = 0; timer.it_value.tv_usec = 1000; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = 1000; setitimer (ITIMER_REAL, &timer, 0); pthread_t tid; int retval; pid_t tid2 = syscall(__NR_gettid); fprintf(log_file, "Starting Variant 3 \\n"); if(pthread_create(&tid, 0, read_dir3, (void*)input_path)) { fprintf(log_file, "FAILED to create thread\\n"); exit(1); } num_threads = num_threads + 1; fprintf(log_file, "Created Thread: %s\\n", input_path); pthread_join(tid, retval); return 0; } void process_file3(void* fullpath) { int error; if(error = pthread_mutex_lock(&lock)) { perror(error); } fullpath = (char*)fullpath; file_traversed = file_traversed + 1; pid_t curthread = syscall(__NR_gettid); struct stat sb; if (stat(fullpath, &sb) == -1) { perror("stat"); exit(1); } time_t t = sb.st_mtime; struct tm lt; localtime_r(&t, &lt); char timbuf[80]; strftime(timbuf, sizeof(timbuf), "%c", &lt); char* temp = malloc(200); strcpy(temp, ""); strcat(temp, fullpath); fprintf(html_file, "<a href='%s'><img src='%s' width=100 height=100/></a>\\n", temp, temp); fprintf(html_file, "<p align='left'> iNode: %d, Type: %d, Size: %ld bytes, Last Modified: %s, Thread Id: %ld</p>\\n", (int)sb.st_ino, (int)sb.st_mode, (long)sb.st_size, timbuf, (long)curthread); fprintf(log_file,"Process file: %s tid: %ld\\n", fullpath, (long) curthread); pthread_mutex_unlock(&lock); } void *read_dir3(void *path) { dir_traversed = dir_traversed+1; DIR* FD; struct dirent* in_file; if (0 == (FD = opendir ((char *) path))) { perror("Error - Failed to open input directory"); exit(1); } char* files[MAXFILES]; char* directories[MAXFILES]; int num_files = 0; int num_dirs = 0; int i; while ((in_file = readdir(FD))) { if (!strcmp (in_file->d_name, ".")) continue; if (!strcmp (in_file->d_name, "..")) continue; char fullpath[300]; strcpy(fullpath, (char *) path); strcat(fullpath, "/"); strcat(fullpath, in_file->d_name); if(in_file->d_type == DT_DIR) { directories[num_dirs] = malloc(256); strcpy(directories[num_dirs], fullpath); num_dirs++; } else { files[num_files] = malloc(256); strcpy(files[num_files], fullpath); num_files++; } } closedir(FD); for(i = 0; i < num_files; i++) { char *extn = strrchr(files[i], '.'); if(strcmp(extn, ".jpg") != 0 && strcmp(extn, ".png") != 0 && strcmp(extn, ".bmp") != 0 && strcmp(extn, ".gif") != 0) { continue; } if(strcmp(extn, ".jpg") == 0) { jpg_file = jpg_file + 1; } if(strcmp(extn, ".bmp") == 0) { bmp_file = bmp_file + 1; } if(strcmp(extn, ".png") == 0) { png_file = png_file + 1; } if(strcmp(extn, ".gif") == 0) { gif_file = gif_file + 1; } pthread_t file_tid; if(pthread_create(&file_tid, 0, process_file3, (void*)files[i])) { fprintf(log_file, "FAILED to create thread\\n"); exit(1); } num_threads = num_threads + 1; pthread_join(file_tid, 0); } pthread_t tids[num_dirs]; for(i = 0; i < num_dirs; i++) { if(pthread_create(&tids[i], 0, read_dir3, (void*)directories[i])) { fprintf(log_file, "FAILED to create thread\\n"); exit(1); } num_threads = num_threads + 1; printf("Created Thread: %s\\n", directories[i]); fprintf(log_file, "Created Thread: %s\\n", directories[i]); } for(i = 0; i < num_dirs; i++) { pthread_join(tids[i], 0); } }
1
#include <pthread.h> sem_t wrt; int read_cnt = 0; pthread_mutex_t mutex; FILE * Wp; struct file_id { FILE *Rp; }; struct file_id * file_array; void * writer(void *param){ char c[2]; while(1){ c[0] = rand()%94+32; c[1] = '\\0'; sem_wait(&wrt); fwrite(c,sizeof(char),1,Wp); printf("Write into: %s\\n\\n",c); sem_post(&wrt); } } void * reader(void *param){ int Num = *((int*)param); char buff[1024]; while(1){ file_array[Num].Rp = fopen("RW.txt","rb"); pthread_mutex_lock(&mutex); read_cnt = read_cnt + 1; if(read_cnt == 1)sem_wait(&wrt); pthread_mutex_unlock(&mutex); fread(buff,sizeof(char),1024,file_array[Num].Rp); printf("[%d] Read from file :%s\\n\\n",Num,buff); pthread_mutex_lock(&mutex); read_cnt = read_cnt-1; if(read_cnt == 0)sem_post(&wrt); pthread_mutex_unlock(&mutex); fclose(file_array[Num].Rp); } } int main(int argc,char * argv[]){ if(argc!=3){ return -1; } int i; int Writer_Num = atoi(argv[1]); int Reader_Num = atoi(argv[2]); pthread_t Writer_Handles[Writer_Num]; pthread_t Reader_Handles[Reader_Num]; file_array = (struct file_id*)malloc(sizeof(struct file_id)*Reader_Num); sem_init(&wrt,0,1); pthread_mutex_init(&mutex,0); Wp = fopen("RW.txt","wb"); srand(time(0)); for(i = 0; i < Writer_Num; i++){ pthread_create(&Writer_Handles[i],0,writer,0); } for(i = 0; i < Reader_Num; i++){ int * tNum = (int*)malloc(sizeof(int)); *tNum = i; pthread_create(&Reader_Handles[i],0,reader,tNum); } sleep(10); fclose(Wp); 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; pthread_mutex_unlock(&mutexsum); pthread_exit((void*)0); } int main(int argc, char const *argv[]) { long i; double *a, *b; void* status; pthread_attr_t attr; a = (double*)malloc(4*100*sizeof(double)); b = (double*)malloc(4*100*sizeof(double)); for (i = 0; i < 100*4; ++i) { a[i] = 1; b[i] = a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 4; ++i) { pthread_create(&callThd[i], &attr, dotprod, (void*)i); } pthread_attr_destroy(&attr); for (i = 0; i < 4; ++i) { pthread_join(callThd[i], &status); } printf("Sum = %f \\n", dotstr.sum); free(a); free(b); pthread_exit(0); return 0; }
1
#include <pthread.h> void initLoadAdaptation() { pthread_mutex_init(&ionum_mutex, 0); pthread_mutex_init(&worknum_mutex, 0); pthread_mutex_init(&clientsconn_mutex, 0); pthread_mutex_init(&inputworks_mutex, 0); clients_connected = 0; input_works = 0; iothreads_num = 0; workerthreads_num = 0; } void loadAdaptation() { pthread_t thread_id; pthread_mutex_lock(&ionum_mutex); pthread_mutex_lock(&worknum_mutex); pthread_mutex_lock(&clientsconn_mutex); pthread_mutex_lock(&inputworks_mutex); if (clients_connected > 0) { if ( iothreads_num < IOTHREADS_MAX && (float)iothreads_num/(float)clients_connected < 0.05 ) { pthread_create(&thread_id, 0, IOThread, 0); pthread_mutex_lock(&reg_mutex); sem_post(&reg_semaphore); iothreads_num++; pthread_mutex_unlock(&reg_mutex); } else if ( iothreads_num > IOTHREADS_MIN && (float)iothreads_num/(float)clients_connected > 1 ) { kill(getpid(),SIGUSR1); } } if (input_works > 0) { if ( workerthreads_num < WORKER_THREADS_MAX && (float) workerthreads_num/(float)input_works < 0.05 ) { pthread_create(&thread_id, 0, workerThread, 0); addSlot(); } else if ( workerthreads_num > WORKER_THREADS_MIN && (float) workerthreads_num/(float)input_works > 1 ) { kill(getpid(), SIGUSR2); } } pthread_mutex_unlock(&ionum_mutex); pthread_mutex_unlock(&worknum_mutex); pthread_mutex_unlock(&clientsconn_mutex); pthread_mutex_unlock(&inputworks_mutex); }
0
#include <pthread.h> pthread_mutex_t mcount; pthread_cond_t mcount_threshold; void get_memory_from_pool ( void *ptr ); void put_memory_into_pool ( void *ptr ); { int thread_no; int mem_count; } meminfo; void init_mem_info(struct mem_info * m) { m->mem_count = 100 ; } int main() { pthread_t maint, swapt; meminfo mems; pthread_mutex_init(&mcount, 0); pthread_cond_init (&mcount_threshold, 0); init_mem_info(&mems); pthread_create (&maint, 0, (void *) &get_memory_from_pool, (void *) &mems); pthread_create (&swapt, 0, (void *) &put_memory_into_pool, (void *) &mems); pthread_join(maint, 0); pthread_join(swapt, 0); pthread_mutex_destroy(&mcount); pthread_cond_destroy(&mcount_threshold); exit(0); } void get_memory_from_pool ( void *ptr ) { meminfo *get_mem; get_mem = (meminfo *) ptr; while (get_mem ->mem_count > 20 ) { pthread_mutex_lock (&mcount); get_mem->mem_count--; if(get_mem->mem_count == 20 ){ pthread_cond_signal(&mcount_threshold); } pthread_mutex_unlock (&mcount); } printf("%s(): Thread %d says %d \\n", __func__, get_mem->thread_no, get_mem->mem_count); pthread_exit(0); } void put_memory_into_pool ( void *ptr ) { meminfo *get_mem; get_mem = (meminfo *) ptr; pthread_mutex_lock (&mcount); while (get_mem->mem_count > 20 ){ pthread_cond_wait(&mcount_threshold, &mcount); } get_mem->mem_count = get_mem->mem_count+5; pthread_mutex_unlock (&mcount); printf("%s(): Thread %d says %d \\n", __func__, get_mem->thread_no, get_mem->mem_count); pthread_exit(0); }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } 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); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, 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 on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t blanks; sem_t datas; int ringBuf[30]; void *productRun(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product is done... data is: %d\\n",data); sem_post(&datas); } } void *productRun2(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product2 is done... data is: %d\\n",data); sem_post(&datas); } } void *consumerRun(void *arg) { int i = 0; while(1) { usleep(1456); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer is done... data is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } void *consumerRun2(void *arg) { int i = 0; while(1) { usleep(1234); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer2 is done...data2 is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } int main() { sem_init(&blanks, 0, 30); sem_init(&datas, 0, 0); pthread_t tid1,tid2,tid3,tid4; pthread_create(&tid1, 0, productRun, 0); pthread_create(&tid4, 0, productRun2, 0); pthread_create(&tid2, 0, consumerRun, 0); pthread_create(&tid3, 0, consumerRun2, 0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); sem_destroy(&blanks); sem_destroy(&datas); return 0; } int sem_ID; int customers_count=0; int eflag=fflag=0; void barber() { printf("barber started\\n"); while(1) { sem_change(sem_ID, 0, -1); if(customers_count==0) { printf("barber sleeping\\n"); eflag=1; sem_change(sem_ID, 0, 1); sem_change(sem_ID, 1, -1); sem_change(sem_ID, 0, -1); } customers_count--; sem_change(sem_ID, 0, 1); sem_change(sem_ID, 3, 1); sem_change(sem_ID, 4, -1); } } void customer(void *arg) { sem_change(sem_ID, 0, -1); if(customers_count==5) { int *ptr=(int*)arg; *ptr=0; printf("No place for customer %d so leaving\\n", pthread_self()); sem_change(sem_ID, 0, 1); return; } customers_count++; if(customers_count==1 && eflag==1) { sem_change(sem_ID, 1, 1); eflag=0; } sem_change(sem_ID, 0, 1); printf("Customer %d got a place\\n", pthread_self()); sem_change(sem_ID, 3, -1); printf("Cutting for %d customer\\n", pthread_self()); sleep(rand()%5+4); sem_change(sem_ID, 4, 1); int *ptr=(int*)arg; *ptr=0; } int main(int argc, char* argv[]) { pthread_t barber_thread; int live_threads[5 +2]; pthread_t customer_thread[5 +2]; for(int i=0; i<5 +2; i++) live_threads[i]=0; int array[]={1, 0, 5, 0, 0}; sem_ID=sem_init_diff_val(5,array); pthread_create(&barber_thread, 0, (void*)&barber, 0); sleep(2); while(1) { for(int i=0; i<5 +2; i++) { if(live_threads[i]==0) { live_threads[i]=1; pthread_create(&customer_thread[i], 0, (void*)&customer, (void*)&live_threads[i]); sleep(rand()%4); } } } exit(0); }
1
#include <pthread.h> int counter; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; void *doit( void * ); int main( int argc, char **argv ) { pthread_t tidA, tidB; pthread_create( &tidA, 0, doit, 0 ); pthread_create( &tidB, 0, doit, 0 ); pthread_join( tidA, 0 ); pthread_join( tidB, 0 ); return 0; } void *doit( void *vptr ) { int i, val; for( i = 0; i < 5000; i++ ) { pthread_mutex_lock( &counter_mutex ); val = counter; printf( "%x: %d\\n", (unsigned int)pthread_self( ), val + 1 ); counter = val + 1; pthread_mutex_unlock( &counter_mutex ); } return 0; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } 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); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, 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 on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> struct list_head { struct list_head *next ; struct list_head *prev ; }; struct s { int datum ; struct list_head list ; }; struct cache { struct list_head slot[10] ; pthread_mutex_t slots_mutex[10] ; }; struct cache c ; static inline void INIT_LIST_HEAD(struct list_head *list) { list->next = list; list->prev = list; } struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; INIT_LIST_HEAD(&p->list); return p; } static inline void list_add(struct list_head *new, struct list_head *head) { struct list_head *next = head->next; next->prev = new; new->next = next; new->prev = head; head->next = new; } void *f(void *arg) { struct s *pos ; int j; struct list_head const *p ; struct list_head const *q ; while (j < 10) { pthread_mutex_lock(&c.slots_mutex[j]); p = c.slot[j].next; pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list)); while (& pos->list != & c.slot[j]) { pos->datum++; q = pos->list.next; pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list)); } pthread_mutex_unlock(&c.slots_mutex[j]); j ++; } return 0; } void *g(void *arg) { struct s *pos ; int j; struct list_head const *p ; struct list_head const *q ; while (j < 10) { pthread_mutex_lock(&c.slots_mutex[j+1]); p = c.slot[j].next; pos = (struct s *)((char *)p - (size_t)(& ((struct s *)0)->list)); while (& pos->list != & c.slot[j]) { pos->datum++; q = pos->list.next; pos = (struct s *)((char *)q - (size_t)(& ((struct s *)0)->list)); } pthread_mutex_unlock(&c.slots_mutex[j+1]); j ++; } return 0; } int main() { pthread_t t1, t2; for (int i = 0; i < 10; i++) { INIT_LIST_HEAD(&c.slot[i]); pthread_mutex_init(&c.slots_mutex[i], 0); for (int j = 0; j < 30; j++) list_add(&new(j*i)->list, &c.slot[i]); } pthread_create(&t1, 0, f, 0); pthread_create(&t2, 0, g, 0); return 0; }
0
#include <pthread.h> static struct usb_device *current_device = 0; static char hidraw_path[20]; static int hidraw_fd = -1; static pthread_mutex_t device_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t device_cond = PTHREAD_COND_INITIALIZER; static int usbdevice_added(const char *dev) { struct usb_device *device = 0; uint16_t vendor_id=0, product_id=0; device = usb_device_open(dev); if (!device) { printf("%s: usb_device_open failed\\n",__func__); return 0; } vendor_id = usb_device_get_vendor_id(device); product_id = usb_device_get_product_id(device); if(!current_device && (vendor_id==0x0483 && product_id==0x5750)) { pthread_mutex_lock(&device_mutex); current_device = device; printf("%s: dev_name=%s\\n", __func__,usb_device_get_name(current_device)); pthread_cond_broadcast(&device_cond); pthread_mutex_unlock(&device_mutex); } else { usb_device_close(device); } return 0; } static int usbdevice_removed(const char *dev) { pthread_mutex_lock(&device_mutex); if (current_device && !strcmp(usb_device_get_name(current_device), dev)) { fprintf(stderr, "current device disconnected\\n"); usb_device_close(current_device); current_device = 0; } pthread_mutex_unlock(&device_mutex); return 0; } struct usb_device* usb_wait_for_device() { struct usb_device* device = 0; pthread_mutex_lock(&device_mutex); while (!current_device) pthread_cond_wait(&device_cond, &device_mutex); device = current_device; pthread_mutex_unlock(&device_mutex); return device; } static void* hid_thread(void) { char buffer[11]; int ret=-1; int i=0; printf("%s: waiting for device fd: %d\\n", __func__, hidraw_fd); usb_wait_for_device(); printf("%s: read fd: %d\\n", __func__, hidraw_fd); while (1) { ret = read(hidraw_fd, buffer, sizeof(buffer)); if (ret < 0) { printf("%s: read failed, errno: %d, fd: %d\\n", __func__, errno, hidraw_fd); close(hidraw_fd); unlink(hidraw_path); hidraw_fd = -1; memset(hidraw_path, 0x0, 20); break; }else{ for(i=0; i<ret; i++) printf("0x%x ", buffer[i]); printf("\\n"); } } printf("%s: hid thread exiting\\n", __func__); return 0; } static int open_hid(const char* name) { int fd; char path[20]; pthread_t th; snprintf(path, sizeof(path), "/dev/%s", name); fd = open(path, O_RDONLY); if (fd < 0) return -1; hidraw_fd = fd; memcpy(hidraw_path, path, 20); printf("%s: opened %s\\n", __func__, hidraw_path); pthread_create(&th, 0, hid_thread, 0); return 0; } static void* inotify_thread(void) { int i=0; char name[10]; for(i=0; i<10; i++) { snprintf(name, sizeof(name), "hidraw%d", i); if(!open_hid(name)) break; } int inotify_fd = inotify_init(); inotify_add_watch(inotify_fd, "/dev", IN_DELETE | IN_CREATE); while (1) { char event_buf[512]; struct inotify_event *event; int event_pos = 0; int event_size; int count = read(inotify_fd, event_buf, sizeof(event_buf)); if (count < (int)sizeof(*event)) { if(errno == EINTR) continue; printf("%s: could not get event, %s\\n", __func__, strerror(errno)); break; } while (count >= (int)sizeof(*event)) { event = (struct inotify_event *)(event_buf + event_pos); if (event->len && !strncmp(event->name, "hidraw", 6)) { if(event->mask & IN_CREATE) { printf("%s: created %s\\n", __func__, event->name); open_hid(event->name); } else { printf("%s: lost %s\\n", __func__, event->name); } } event_size = sizeof(*event) + event->len; count -= event_size; event_pos += event_size; } } close(inotify_fd); return 0; } static void init_hid() { pthread_t th; pthread_create(&th, 0, inotify_thread, 0); } int main(int argc, char *argv[]) { struct usb_host_context *ctx; ctx = usb_host_init(); if (!ctx) { printf("%s:USB host init error\\n",__func__); return 1; } init_hid(); while(1){ usb_host_run(ctx, usbdevice_added, usbdevice_removed, 0, 0); } return 0; }
1
#include <pthread.h> static unsigned int avail = 0; static int work_pipe[2]; static pthread_mutex_t mtx_work = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static unsigned int producers = 10000; unsigned int random_uint(unsigned int max) { float tmp = (float)rand()/(float)32767 * (float)max; return (unsigned int)ceilf(tmp); } void* producer (void* param) { int ret; unsigned int* thread_num = (unsigned int*)param; unsigned int result; unsigned int pipe_ready = 1; result = *thread_num; do { sleep(random_uint(2)); pthread_mutex_lock(&mtx_work); ret = write(work_pipe[1], &result, sizeof(unsigned int)); if (ret <= 0) { pipe_ready = 0; pthread_mutex_unlock(&mtx_work); fprintf (stderr, "producer -- pipe was full!\\n"); continue; } avail++; producers--; pthread_mutex_unlock(&mtx_work); } while (!pipe_ready); pthread_cond_signal(&cond); } void main (int argc, char** argv) { unsigned int i, ret; unsigned int work_unit; unsigned int finished = 0; pthread_t thread_id[10000]; unsigned int thread_num[10000]; unsigned int processed = 0; int sum = 0; pipe(work_pipe); fcntl(work_pipe[0], F_SETFL, O_NONBLOCK); fcntl(work_pipe[1], F_SETFL, O_NONBLOCK); for (i=0; i<10000; i++) { thread_num[i] = i; pthread_create(&thread_id[i], 0, producer, &thread_num[i]); pthread_detach(thread_id[i]); } while (!finished) { processed = 0; pthread_mutex_lock(&mtx_work); while (!avail) { pthread_cond_wait (&cond, &mtx_work); } while (avail > 0) { ret = read(work_pipe[0], &work_unit, sizeof(unsigned int)); if (ret > 0) { sum += work_unit; avail--; processed++; } else { fprintf (stderr, "consumer -- tried to read from empty pipe!\\n"); } if (producers == 0) { finished = 1; } } pthread_mutex_unlock(&mtx_work); if (processed) printf ("consumer -- processed %u work units\\n", processed); } printf ("-------------------\\n"); printf (" Work unit sum: %u\\n", sum); sum = 0; for (i=0; i<10000; i++) { sum += i; } printf ("Expected result: %u\\n", sum); }
0
#include <pthread.h> int n=0; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; void* thread_func(void* arg) { int param = (int) arg; char c='A'+param; int ret, i=0; for(; i < 10; i++) { pthread_mutex_lock(&mylock); printf("thread %d get the lock\\n", param); while(param != n) { printf("thread %d waiting\\n", param); ret = pthread_cond_wait(&qready, &mylock); if(ret == 0) { printf("thread %d wait success\\n", param); } else { printf("thread %d wait failed: %s\\n", param, strerror(ret)); } } printf("%c ",c); n = (n+1)%3; pthread_mutex_unlock(&mylock); printf("thread %d release the lock\\n", param); pthread_cond_broadcast(&qready); } return (void*) 0; } int main( int argc, char** argv) { int i =0, err; pthread_t tid[3]; void* tret; for(; i<3; i++) { err = pthread_create(&tid[i], 0, thread_func, (void*)i); if(err != 0) { printf("thread_create error:%s\\n", strerror(err)); exit(-1); } } for(i=0; i < 3; i++) { err = pthread_join(tid[i], &tret); if(err != 0) { printf("can not join with thread %d:%s\\n", i, strerror(err)); exit(-1); } } printf("\\n"); return 0; }
1
#include <pthread.h> void *snapshot_fun() { int cmd; while(1) { pthread_mutex_lock(&mutex_snapshot); pthread_cond_wait(&cond_snapshot,&mutex_snapshot); cmd = msg.cmd; pthread_mutex_unlock(&mutex_snapshot); switch(cmd) { case SNAPSHOT_ON: system("killall mjpg_streamer"); usleep(500); system("killall ffmpeg"); usleep(500); system("mjpg_streamer -i \\"/mjpg/input_uvc.so -y\\" -o \\"/mjpg/output_http.so –w /www\\" -o \\"/mjpg/output_file.so -f /var/www/motion/photo -d 1000\\" &"); break; case SNAPSHOT_OFF: system("killall mjpg_streamer"); usleep(500); system("killall ffmpeg"); usleep(1000000); system("mjpg_streamer -i \\"/mjpg/input_uvc.so -y\\" -o \\"/mjpg/output_http.so -w /www\\" &"); break; case SNAPSHOT_DEL: system("rm -rf /var/www/motion/photo/*.jpg"); break; default: break; } } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t monitor; pthread_cond_t red[5]; int fork[5]={1,1,1,1,1}; char philosophers[5]={'O','O','O','O'}; void think() { sleep(3); } void eat (int n){ int i; pthread_mutex_lock(&monitor); philosophers[n]='o'; while (fork[n]==0 || fork[(n+1)%5]==0){ pthread_cond_wait(&red[n],&monitor); } fork[n]=fork[(n+1)%5]=0; philosophers[n]='X'; for(i=0;i<5;i++){ printf("%c ",philosophers[i]); } printf(" (%d)\\n",(n+1)); pthread_mutex_unlock(&monitor); sleep(2); pthread_mutex_lock(&monitor); philosophers[n]='O'; fork[n]=fork[(n+1)%5]=1; pthread_cond_signal(&red[(n-1)%5]); pthread_cond_signal(&red[(n+1)%5]); for(i=0;i<5;i++){ printf("%c ",philosophers[i]); } printf(" (%d)\\n",(n+1)); pthread_mutex_unlock(&monitor); } void *philosopher(void *i){ int j; j=*((int *)i); while(1){ think(); eat(j); } } int main(int argc, char *argv[]){ int i; int *br; pthread_mutex_init (&monitor,0); pthread_cond_init (red,0); pthread_t *t; t=(pthread_t *)malloc(5*sizeof(pthread_t)); br=(int *)malloc(5*sizeof(int)); for (i=0;i<5;i++){ br[i]=i; if(pthread_create(&t[i],0,philosopher,((void *)&br[i]))){ printf("Can't create new thread! \\n"); exit(1); } } for (i=0;i<5;i++){ pthread_join(t[i],0); } free(t); free(br); system("PAUSE"); return 0; }
1
#include <pthread.h> int g_buff[3]; int g_write_index = 0; int g_read_index = 0; pthread_mutex_t lock; pthread_cond_t consume_cond, produce_cond; void* produce(void *ptr){ int idx = *(int*)ptr; printf("in produce %d %d %d\\n",idx, g_write_index, g_read_index); while(1){ pthread_mutex_lock(&lock); while((g_write_index + 1) % 3 == g_read_index) pthread_cond_wait(&produce_cond, &lock); g_buff[g_write_index] = idx; g_write_index = (g_write_index + 1) % 3; pthread_cond_signal(&consume_cond); pthread_mutex_unlock(&lock); } return 0; } void* consume(void *ptr){ while(1){ pthread_mutex_lock(&lock); while(g_read_index == g_write_index) pthread_cond_wait(&consume_cond, &lock); int data = g_buff[g_read_index]; g_buff[g_read_index] = -1; g_read_index = (g_read_index + 1) % 3; printf("consume %d\\n", data); pthread_cond_signal(&produce_cond); pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char * argv[]){ pthread_t con; pthread_t pros[5]; srand((unsigned)time(0)); pthread_mutex_init(&lock, 0); pthread_cond_init(&consume_cond,0); pthread_cond_init(&produce_cond,0); pthread_create(&con, 0, consume, 0); int thread_args[5]; for(int i = 0; i < 5; i++){ thread_args[i] = i + 1; pthread_create(&pros[i], 0, produce, (thread_args + i)); } pthread_join(con,0); for(int i = 0; i < 5; i++) pthread_join(pros[i],0); pthread_mutex_destroy(&lock); pthread_cond_destroy(&consume_cond); pthread_cond_destroy(&produce_cond); return 0; }
0
#include <pthread.h> pthread_mutex_t finish_mutex; pthread_cond_t finish_condvar; int pool = 1; int arsize = 10000; void* single (void*); int rs = 0; int bs = 0; int main (int argc, char** argv) { int i, sum1, sum2; struct sync_queue_t queue; struct params *stp; counter = 0; if (argc > 1) { for (i = 2; i < argc; i++) { if (argv[i - 1][1] == 'p') { pool = atoi(argv[i]); } else if (argv[i - 1][1] == 'a') { arsize = atoi(argv[i]); } else if (argv[i - 1][1] == 'r') { rs = atoi(argv[i]); } else if (argv[i -1][1] == 'b'){ bs = atoi(argv[i]); } } } pthread_t mythreads[pool]; int ar[arsize]; for (i = 0; i < arsize; i++) { ar[i] = rand() % 100; } sum1 = ar[0]; for (i = 1; i < arsize; i++) { sum1 += ar[i]; } stp = malloc(sizeof(struct params)); stp->p = &ar[0]; stp->size = arsize; sync_queue_init(&queue, 10*(arsize + pool)); for (i = 0; i < pool; i++) { pthread_create(&mythreads[i], 0, single, &queue); } pthread_mutex_lock(&finish_mutex); counter++; pthread_mutex_unlock(&finish_mutex); sync_queue_enqueue(&queue, stp); pthread_mutex_lock(&finish_mutex); if (counter != 0) { pthread_cond_wait(&finish_condvar, &finish_mutex); } pthread_mutex_unlock(&finish_mutex); for (i = 0; i < pool; i++) { sync_queue_enqueue(&queue, 0); } for (i = 0; i < pool; i++) { pthread_join(mythreads[i], 0); } queue_collapse(&queue.sp); sum2 = ar[0]; for (i = 1; i < arsize; i++) { sum2 += ar[i]; } for (i = 1; i < arsize; i++) { if ((ar[i] < ar[i - 1]) || (sum1 != sum2)) { } } return 0; } void* single (void* param) { while (1) { struct params* temp = sync_queue_dequeue(param); if (!temp) { break; } quicksort(param, temp, 0); } return 0; }
1
#include <pthread.h> void *philosopher (void *id); int food_on_table (); pthread_mutex_t chopstick[5]; pthread_mutex_t food_lock; pthread_t philo[5]; int sleep_seconds = 0; int main (int argn, char **argv) { long i; if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&food_lock, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&chopstick[i], 0); for (i = 0; i < 5; i++) pthread_create (&philo[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (philo[i], 0); return 0; } void * philosopher (void *num) { long id = (long)num; long i, left_chopstick, right_chopstick, f; left_chopstick = id; right_chopstick = (id + 1)%5; while (f = food_on_table ()) { if (id==0) sleep (rand()%10); pthread_mutex_lock (&chopstick[left_chopstick]); printf ("Philosopher %ld: got left chopstick %ld\\n", id, left_chopstick); pthread_mutex_lock (&chopstick[right_chopstick]); printf ("Philosopher %ld: got right chopstick %ld\\n", id, right_chopstick); printf ("Philosopher %ld: eating -- food %ld.\\n", id, f); sleep (rand()%5); pthread_mutex_unlock (&chopstick[left_chopstick]); pthread_mutex_unlock (&chopstick[right_chopstick]); int thinking_time=rand()%10; printf ("Philosopher %ld is done eating and is now thinking for %d secs.\\n", id, thinking_time); sleep (thinking_time); } return (0); } int food_on_table () { static int food = 15; int myfood; pthread_mutex_lock (&food_lock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&food_lock); return myfood; }
0
#include <pthread.h> struct thread_args { int tid; int inc; int loop; }; int count = 0; pthread_mutex_t count_mutex; void *inc_count(void *arg) { int i,loc; struct thread_args *my_args = (struct thread_args*) arg; loc = 0; { for (i = 0; i < my_args->loop; i++) { pthread_mutex_lock(&count_mutex); count = count + my_args->inc; pthread_mutex_unlock(&count_mutex); loc = loc + my_args->inc; } } printf("Thread: %d finished. Counted: %d\\n", my_args->tid, loc); free(my_args); pthread_exit(0); } int main(int argc, char *argv[]) { int i, loop, inc; struct thread_args *targs; pthread_t threads[3]; pthread_attr_t attr; if (argc != 3) { printf("Usage: PTCOUNT LOOP_BOUND INCREMENT\\n"); exit(0); } loop = atoi(argv[1]); inc = atoi(argv[2]); pthread_mutex_init(&count_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 3; i++) { targs = malloc(sizeof(targs)); targs->tid = i; targs->loop = loop; targs->inc = inc; pthread_create(&threads[i], &attr, inc_count, targs); } for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_exit (0); }
1
#include <pthread.h> void *area_thread ( void *arg ); double integral ( double h ); double ntr; double nt; double area = 0.0; double ls = 4.0; double li = 0.0; pthread_mutex_t *flag_mutex; int main ( int argc, char **argv ) { ntr = atoi ( argv[1] ); nt = atoi ( argv[2] ); pthread_t *thread_ids = (pthread_t*) malloc (nt*sizeof(pthread_t)); flag_mutex = (pthread_mutex_t*) malloc (sizeof(pthread_mutex_t)); pthread_mutex_init ( flag_mutex, 0 ); int i; int *thread_number = (int*) malloc (nt*sizeof(int)); for ( i = 0; i < nt; i ++ ) { thread_number[i] = i; pthread_create ( &thread_ids[i], 0, area_thread, &thread_number[i] ); } for ( i = 0; i < nt; i ++ ) pthread_join ( thread_ids[i], 0 ); free ( thread_ids ); pthread_mutex_destroy ( flag_mutex ); printf ( "Area/Integral aproximada: %lf\\n", area ); return 0; } void *area_thread ( void *arg ) { double bma; double bme; double h = (ls - li) / ntr; int id = *((int*)arg); double t_fim = ntr / nt; double t_inicio = li + (id * t_fim * h); double aux = t_inicio; int i; double soma = 0.0; for ( i = 0; i < t_fim; i ++ ) { bma = integral (aux); bme = integral (aux + h); soma += ( (bma+bme)*h ) / 2; aux += h; } pthread_mutex_lock ( flag_mutex ); area += soma; pthread_mutex_unlock ( flag_mutex ); } double integral ( double h ) { return h*h; }
0
#include <pthread.h> struct thread_info{ int id; int reader_or_writer; int resource_id; int arrive_t; int burst_t; }; struct thread_pool{ int value; pthread_mutex_t wl; pthread_mutex_t rl; pthread_mutex_t can_read; pthread_mutex_t can_write; int w_number; int r_number; }; int number; int writer_number = 0, reader_number = 0; int compare(const void *a, const void *b){ struct thread_info *aa = (struct thread_info*)a; struct thread_info *bb = (struct thread_info*)b; return aa->arrive_t - bb->arrive_t; } static void *reader_thread(void *a){ struct thread_pool *p = a; pthread_mutex_lock(&p->can_read); pthread_mutex_lock(&p->rl); p->r_number = p->r_number + 1; if(p->r_number == 1){ pthread_mutex_lock(&p->can_write); } pthread_mutex_unlock(&p->rl); pthread_mutex_unlock(&p->can_read); printf("reader read %d seconds and ", p -> value); sleep(p -> value); time_t t = time(0); printf("current time %ld\\n", t); pthread_mutex_lock(&p->rl); p->r_number = p->r_number - 1; if(p->r_number == 0){ pthread_mutex_unlock(&p->can_write); } pthread_mutex_unlock(&p->rl); return 0; } static void *writer_thread(void *a){ struct thread_pool *p = a; pthread_mutex_lock(&p->wl); p->w_number = p->w_number + 1; if(p->w_number == 1){ pthread_mutex_lock(&p->can_read); } pthread_mutex_unlock(&p->wl); pthread_mutex_lock(&p->can_write); printf("writerer write %d seconds and ", p -> value); sleep(p -> value); time_t t1 = time(0); printf("current time %ld\\n", t1); pthread_mutex_unlock(&p->can_write); pthread_mutex_lock(&p->wl); p->w_number = p->w_number - 1; if(p->w_number == 0){ pthread_mutex_unlock(&p->can_read); } pthread_mutex_unlock(&p->wl); return 0; } static inline void init_thread_pool(struct thread_pool *p){ p -> value = 0; p -> r_number = 0; p -> w_number = 0; pthread_mutex_init(&p->wl, 0); pthread_mutex_init(&p->rl, 0); pthread_mutex_init(&p->can_read, 0); pthread_mutex_init(&p->can_write, 0); } static inline void update_thread_pool(struct thread_pool *p, int time){ p -> value = time; } void empty_array_row(int i, struct thread_info a[]){ a[i].id = a[i].resource_id = a[i].reader_or_writer = a[i].arrive_t = a[i].burst_t = 0; } int sum_array_row(int i, struct thread_info a[]){ if(a[i].id+a[i].resource_id+a[i].reader_or_writer+a[i].arrive_t+a[i].burst_t == 0) return 0; else return 1; } int main(){ FILE *fin; if((fin = fopen("input.2", "r")) == 0){ printf("read input file failed, please modify you input as input.1 format and name\\n"); exit(0); } fscanf(fin, "%d", &number); struct thread_info a[number]; for(int i = 0; i < number; i++){ a[i].id = a[i].resource_id = a[i].reader_or_writer = a[i].arrive_t = a[i].burst_t = 0; } for(int i = 0; i < number; i++){ fscanf(fin, "%d %d %d %d %d\\n", &a[i].id, &a[i].reader_or_writer, &a[i].resource_id, &a[i].arrive_t, &a[i].burst_t); if(a[i].reader_or_writer == 2){ ++reader_number; }else if(a[i].reader_or_writer == 1){ ++writer_number; } } struct thread_info writer[writer_number]; struct thread_info reader[reader_number]; for(int i = 0; i < writer_number; i++){ writer[i].id = writer[i].resource_id = writer[i].reader_or_writer = writer[i].arrive_t = writer[i].burst_t = 0; } for(int i = 0; i < reader_number; i++){ reader[i].id = reader[i].resource_id = reader[i].reader_or_writer = reader[i].arrive_t = reader[i].burst_t = 0; } int ri = 0, wi = 0; for(int i = 0; i < number; i++){ if(a[i].reader_or_writer == 2){ reader[ri].id = a[i].id; reader[ri].resource_id = a[i].resource_id; reader[ri].reader_or_writer = a[i].reader_or_writer; reader[ri].arrive_t = a[i].arrive_t; reader[ri].burst_t = a[i].burst_t; ri++; } if(a[i].reader_or_writer == 1){ writer[wi].id = a[i].id; writer[wi].resource_id = a[i].resource_id; writer[wi].reader_or_writer = a[i].reader_or_writer; writer[wi].arrive_t = a[i].arrive_t; writer[wi].burst_t = a[i].burst_t; wi++; } } fclose(fin); FILE *fout = fopen("processevent.log", "w"); fprintf(fout, "processID Resource arrival-time start-time end-time\\n"); qsort(reader, reader_number, sizeof(struct thread_info), compare); qsort(writer, writer_number, sizeof(struct thread_info), compare); pthread_t pid[number]; struct thread_pool pool; init_thread_pool(&pool); time_t t1 = time(0); printf("current time %ld\\n", t1); int total_time = 0; int all_exec = 0; while(1){ if(all_exec >= number){ break; } int flag = 1; int start_t = 0; int temp_id, temp_resourceid, temp_arrivet; for(int i = 0; i < writer_number; i++){ if(sum_array_row(i, writer) != 0){ if(writer[i].arrive_t <= total_time){ update_thread_pool(&pool, writer[i].burst_t); pthread_create(&pid[writer[i].id], 0, writer_thread, &pool); all_exec++; pthread_join(pid[writer[i].id], 0); temp_id = writer[i].id; temp_resourceid = writer[i].resource_id; temp_arrivet = writer[i].arrive_t; start_t = total_time; total_time = total_time + writer[i].burst_t; empty_array_row(i, writer); fprintf(fout, "%d %d %d %d %d\\n", temp_id , temp_resourceid, temp_arrivet, start_t, total_time); flag = 0; break; }else{ break; } }else{ continue; } } if(flag == 1){ for(int i = 0; i < reader_number; i++){ if(sum_array_row(i, reader) != 0){ if(reader[i].arrive_t <= total_time){ update_thread_pool(&pool, reader[i].burst_t); pthread_create(&pid[reader[i].id], 0, reader_thread, &pool); all_exec++; pthread_join(pid[reader[i].id], 0); temp_id = reader[i].id; temp_resourceid = reader[i].resource_id; temp_arrivet = reader[i].arrive_t; start_t = total_time; total_time += reader[i].burst_t; empty_array_row(i, reader); fprintf(fout, "%d %d %d %d %d\\n", temp_id , temp_resourceid, temp_arrivet, start_t, total_time); break; }else{ break; } }else{ continue; } } } } return 0; }
1
#include <pthread.h> int g_num = 0; int nNum = 0; int nLoop = 0; { int numID; }threadID; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *pthread_routine(void *arg) { threadID tmp = *(threadID *)arg; pthread_mutex_lock(&mutex); ++g_num; printf("tid = %d, g_num = %d, tmp.numID = %d\\n", (int)pthread_self(), g_num, tmp.numID); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(void) { int ret = 0; int i = 0; pthread_t tidArray[1024 * 6]; threadID tmp; threadID tmparr[2048]; printf("请输入线程的数量: "); scanf("%d", &nNum); printf("请输入线程循环的个数: "); scanf("%d", &nLoop); for (i = 0; i < nNum; i++) { tmparr[i].numID = i + 1; ret = pthread_create(&tidArray[i], 0, pthread_routine, &tmparr[i]); if (ret != 0) { ret = -1; printf("func err pthread_create ... \\n"); return ret; } } for (i = 0; i < nNum; i++) { pthread_join(tidArray[i], 0); } printf("父进程结束\\n"); return 0; }
0
#include <pthread.h> static pthread_mutex_t getservby_mutex = PTHREAD_MUTEX_INITIALIZER; static int convert (struct servent *ret, struct servent *result, char *buf, int buflen) { int len, i; if (!buf) return -1; *result = *ret; len = strlen (ret->s_name) + 1; if (len > buflen) return -1; buflen -= len; result->s_name = (char *) buf; buf += len; strcpy (result->s_name, ret->s_name); for (len = sizeof (char *), i = 0; ret->s_aliases [i]; i++) { len += strlen (ret->s_aliases [i]) + 1 + sizeof (char *); } if (len > buflen) return -1; buflen -= len; result->s_aliases = (char **) buf; buf += (i + 1) * sizeof (char *); for (i = 0; ret->s_aliases [i]; i++) { result->s_aliases [i] = (char *) buf; strcpy (result->s_aliases [i], ret->s_aliases [i]); buf += strlen (ret->s_aliases [i]) + 1; } result->s_aliases [i] = 0; len = strlen (ret->s_proto) + 1; if (len > buflen) return -1; buf += len; result->s_proto = (char *) buf; strcpy (result->s_proto, ret->s_proto); return 0; } struct servent * getservbyport_r (int port, const char *proto, struct servent *result, char *buffer, int buflen) { struct servent *ret; pthread_mutex_lock (&getservby_mutex); ret = getservbyport (port, proto); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getservby_mutex); return result; } struct servent * getservbyname_r (const char *name, const char *proto, struct servent *result, char *buffer, int buflen) { struct servent *ret; pthread_mutex_lock (&getservby_mutex); ret = getservbyname (name, proto); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getservby_mutex); return result; } struct servent * getservent_r (struct servent *result, char *buffer, int buflen) { struct servent *ret; pthread_mutex_lock (&getservby_mutex); ret = getservent (); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getservby_mutex); return result; }
1
#include <pthread.h> pthread_mutex_t barrier_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t barrier_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t alive_mutex = PTHREAD_MUTEX_INITIALIZER; int barrier_count = 0; int barrier_id = 0; pthread_t *threads; int nb_threads; int threads_per_row; int threads_per_col; int col_block_size; int row_block_size; void barrier() { int id; pthread_mutex_lock(&barrier_mutex); id = barrier_id; barrier_count++; if (barrier_count == nb_threads) { barrier_count = 0; barrier_id++; pthread_cond_broadcast(&barrier_cond); } while (id == barrier_id) pthread_cond_wait(&barrier_cond, &barrier_mutex); pthread_mutex_unlock(&barrier_mutex); } void* start_work(void *param) { int loop, i, j, thread_id = (int)param, count, local_alive; int istart = (thread_id / threads_per_row) * col_block_size + 1; int iend = ((thread_id / threads_per_row) + 1) * col_block_size; int jstart = (thread_id % threads_per_row) * row_block_size + 1; int jend = ((thread_id % threads_per_row) + 1) * row_block_size; int end_num = BS; for (loop = 1; loop <= maxloop; loop++) { if (istart == 1) { if (jstart == 1) cell(end_num+1, end_num+1) = cell(1, 1); else if (jend == end_num) cell(end_num+1, 0) = cell(1, end_num); for (j = jstart; j <= jend; j++) { cell(end_num+1, j) = cell(1, j); } } else if (iend == end_num) { if (jstart == 1) cell(0, end_num+1) = cell(end_num, 1); else if (jend == end_num) cell(0, 0) = cell(end_num, end_num); for (j = jstart; j <= jend; j++) { cell(0, j) = cell(end_num, j); } } if (jstart == 1) { for (i = istart; i <= iend; i++) cell(i, end_num+1) = cell(i, 1); } else if (jend == end_num) { for (i = istart; i <= iend; i++) cell(i, 0) = cell(i, end_num); } barrier(); for (j = jstart; j <= jend; j++) { for (i = istart; i <= iend; i++) { ngb( i, j ) = cell( i-1, j-1 ) + cell( i, j-1 ) + cell( i+1, j-1 ) + cell( i-1, j ) + cell( i+1, j ) + cell( i-1, j+1 ) + cell( i, j+1 ) + cell( i+1, j+1 ); } } num_alive = 0; barrier(); local_alive = 0; for (j = jstart; j <= jend; j++) { for (i = istart; i <= iend; i++) { if ( (ngb( i, j ) < 2) || (ngb( i, j ) > 3) ) { cell(i, j) = 0; } else { if ((ngb( i, j )) == 3) cell(i, j) = 1; } if (cell(i, j) == 1) { local_alive ++; } } } pthread_mutex_lock(&alive_mutex); num_alive += local_alive; pthread_mutex_unlock(&alive_mutex); } return 0; } int main(int argc, char* argv[]) { int i, j; double t1, t2; double temps; get_arg(argc,argv,0,0); init(); threads_per_row = 2; nb_threads = n; threads_per_col = nb_threads / threads_per_row; if (print) output_board( BS, &(cell(1, 1)), ldboard, maxloop); printf("Starting number of living cells = %d\\n", num_alive); t1 = mytimer(); threads = malloc(nb_threads * sizeof(pthread_t)); row_block_size = BS / threads_per_row; col_block_size = BS / threads_per_col; for (i = 0; i < nb_threads; i++) { pthread_create(&threads[i], 0, start_work, (void*)i); } for (i = 0; i < nb_threads; i++) { pthread_join(threads[i], 0); } t2 = mytimer(); temps = t2 - t1; printf("Final number of living cells = %d\\n", num_alive); printf("time=%.2lf ms\\n",(double)temps * 1.e3); if (print) { output_board( BS, &(cell(1, 1)), ldboard, maxloop); printf("----------------------------\\n"); output_board( BS+2, &(cell(0, 0)), ldboard, maxloop); } pthread_mutex_destroy(&barrier_mutex); pthread_mutex_destroy(&alive_mutex); pthread_cond_destroy(&barrier_cond); free(threads); free(board); free(nbngb); return 0; }
0
#include <pthread.h> static pthread_t thread; static pthread_cond_t r_cond; static pthread_mutex_t r_mutex; struct ring_buffer { int buffer[8]; int head; int tail; }; void put_value(rbuf *r, int *value) { int align = sizeof(r->buffer) / sizeof(int); r->head = r->head % align; r->buffer[r->head] = *value; r->head++; } void get_value(rbuf *r, int *value) { int align = sizeof(r->buffer) / sizeof(int); r->tail = r->tail % align; if (r->tail == r->head) return; *value = r->buffer[r->tail]; r->tail++; } static void *thr_fn(void *arg) { int value; int factor = 1000; rbuf *p = (rbuf *)arg; srand(time(0)); while (1) { value = rand() % factor; pthread_mutex_lock(&r_mutex); put_value(p, &value); pthread_mutex_unlock(&r_mutex); } } void init_ring_buffer(rbuf *r) { memset(r, 0, sizeof(rbuf)); r->tail = r->head = 0; } int main(int argc, char *argv[]) { rbuf r; init_ring_buffer(&r); pthread_mutex_init(&r_mutex, 0); pthread_cond_init(&r_cond, 0); if (pthread_create(&thread, 0, thr_fn, (void *)&r) != 0) { printf("ring buffer: error when create pthread, %d\\n", errno); return 1; } usleep(100000); while (1) { int value; pthread_mutex_lock(&r_mutex); get_value(&r, &value); pthread_mutex_unlock(&r_mutex); } pthread_join(thread, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t my_mutex; int my_count; void *thread_function(void *ptr ); void my_increment_count_function() { pthread_mutex_lock(&my_mutex); my_count = my_count + 1; pthread_mutex_unlock(&my_mutex); } int my_fetch_count_function() { int count; count = my_count; return (count); } int main(int argc, char **argv) { pthread_t thread1, thread2; const char *name1 = "Inside Thread 1"; const char *name2 = "Inside Thread 2"; int my_ret_1, my_ret_2; my_ret_1 = pthread_create(&thread1, 0, thread_function, (void*) name1); if(my_ret_1) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",my_ret_1); exit(1); } my_ret_2 = pthread_create( &thread2, 0, thread_function, (void*) name2); if(my_ret_2) { fprintf(stderr,"Error - pthread_create() return code: %d\\n",my_ret_2); exit(1); } printf("pthread_create() for thread 1 returns: %d\\n",my_ret_1); printf("pthread_create() for thread 2 returns: %d\\n",my_ret_2); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *thread_function( void *ptr ) { char *name; int loopvar=0; name = (char *) ptr; printf("%s \\n", name); fflush(stdout); for(loopvar=0; loopvar<100000; loopvar++) { my_count = my_count+1; printf("Thread %s prints %d\\n", name, my_fetch_count_function()); } return 0; }
0
#include <pthread.h> static pthread_mutex_t logLock; int bhdapp_logging_init(void) { int rv = 0; FILE *fp; rv = pthread_mutex_init(&logLock, 0); _BHDAPP_ASSERT_NET_ERROR( (rv == 0), "BHDAPP : Error creating logging mutex \\n"); fp = fopen(BHDAPP_COMMUNICATION_LOG_FILE_NEW, "w"); if (fp != 0) { fclose(fp); } fp = fopen(BHDAPP_COMMUNICATION_LOG_FILE_OLD, "w"); if (fp != 0) { fclose(fp); } return 0; } int bhdapp_message_log(char *message, int length, bool isFromAgent) { FILE *fp = 0; char timeString[BHDAPP_MAX_STRING_LENGTH] = { 0 }; time_t logtime; struct tm *timeinfo; int i = 0; struct stat fileStat; time(&logtime); timeinfo = localtime(&logtime); strftime(timeString, BHDAPP_MAX_STRING_LENGTH, "%Y-%m-%d %H:%M:%S ", timeinfo); pthread_mutex_lock(&logLock); fp = fopen(BHDAPP_COMMUNICATION_LOG_FILE_NEW, "a"); if (fp == 0) { _BHDAPP_LOG(_BHDAPP_DEBUG_ERROR, "Log : Unable to open file for logging [%d:%s] \\n", errno, strerror(errno)); pthread_mutex_unlock(&logLock); return -1; } fputs(timeString, fp); if (isFromAgent) { fputs("Message from Agent \\n", fp); } else { fputs("Message to Agent \\n", fp); } for (i = 0; i < length; i++) { fputc(message[i], fp); } fputs("\\n", fp); fclose(fp); if (stat(BHDAPP_COMMUNICATION_LOG_FILE_NEW, &fileStat) == 0) { if (BHDAPP_COMMUNICATION_LOG_MAX_FILE_SIZE <= fileStat.st_size) { if (0 > remove(BHDAPP_COMMUNICATION_LOG_FILE_OLD)) { _BHDAPP_LOG(_BHDAPP_DEBUG_ERROR, "Log : Unable to remove old file for logging [%d:%s] \\n", errno, strerror(errno)); } if (0 > rename(BHDAPP_COMMUNICATION_LOG_FILE_NEW, BHDAPP_COMMUNICATION_LOG_FILE_OLD)) { _BHDAPP_LOG(_BHDAPP_DEBUG_ERROR, "Log : Unable to rename new file to old file for logging [%d:%s] \\n", errno, strerror(errno)); } } } pthread_mutex_unlock(&logLock); return 0; }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; pthread_mutex_t mutexsum; DOTDATA dotstr; 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[]) { char *p; char *q; int num; long arg1 = strtol(argv[1], &p, 10); long arg2 = strtol(argv[2], &q, 10); int NUMTHRDS = arg1; int VECLEN = arg2; pthread_t callThd[NUMTHRDS]; long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double)); for (i=0; i<VECLEN*NUMTHRDS; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = VECLEN; 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<NUMTHRDS;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<NUMTHRDS;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> double* x; double* c; double** A; double* y; int n; int t; int threadCount; int type; int barrierCount = 0; pthread_mutex_t lock; pthread_cond_t cond; pthread_barrier_t barrier; int* getRange(int myrank, int n, int p) { int quotient = n / p; int remainder = n % p; int myCount; int* range = malloc(2 * sizeof(int)); if (myrank < remainder) { myCount = quotient + 1; range[0] = myrank * myCount; } else { myCount = quotient; range[0] = myrank * myCount + remainder; } range[1] = range[0] + myCount; return range; } double calculateDotProduct(double* a, double* b) { double total = 0; int i; for (i = 0; i < n; i++) { total += (a[i] * b[i]); } return total; } void conditionalBarrier() { pthread_mutex_lock(&lock); if ((barrierCount + 1) == threadCount) { while (barrierCount > 0) { pthread_cond_signal(&cond); barrierCount--; } } else { barrierCount++; pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); } void* threadFunction(void* me) { int id = (int) me; int* range = getRange(id, n, threadCount); int start = range[0]; int finish = range[1]; free(range); int i, j; for (i = start; i < finish; i++) { A[i] = malloc(n * sizeof(double)); for (j = 0; j < n; j++) { if (i == j) { A[i][j] = 0; } else { A[i][j] = -1/(double)n; } } } int currentInteration = 0; for (currentInteration = 0; currentInteration < t; currentInteration++) { for (i = start; i < finish; i++) { y[i] = calculateDotProduct(A[i], x) + c[i]; } if (type == 1) { conditionalBarrier(); } else { pthread_barrier_wait(&barrier); } for (i = start; i < finish; i++) { x[i] = y[i]; } if (type == 1) { conditionalBarrier(); } else { pthread_barrier_wait(&barrier); } } return 0; } int main() { double start, finish, elapsed; pthread_t* threads; printf("Enter problem size (n):\\n"); scanf("%d", &n); printf("Enter iterations (t):\\n"); scanf("%d", &t); printf("Enter thread count:\\n"); scanf("%d", &threadCount); printf("Enter synchronization type (1 = cond, 2 = barrier):\\n"); scanf("%d", &type); GET_TIME(start); x = malloc(n * sizeof(double)); c = malloc(n * sizeof(double)); A = malloc(n * sizeof(double*)); y = malloc(n * sizeof(double)); if (type == 1) { pthread_mutex_init(&lock, 0); pthread_cond_init(&cond, 0); } else { pthread_barrier_init(&barrier, 0, threadCount); } int i; for (i = 0; i < n; i++) { x[i] = 0; } for (i = 0; i < n; i++) { c[i] = (double)i / (double)n; } threads = malloc(threadCount * sizeof(pthread_t)); for (i = 0; i < threadCount; i++) { pthread_create(&threads[i], 0, threadFunction, (void*) i); } for (i = 0; i < threadCount; i++) { pthread_join(threads[i], 0); } GET_TIME(finish); elapsed = finish - start; printf("Time to complete: %.2f seconds.\\n", elapsed); printf("Up to first 30 elements in x:\\n"); for (i = 0; i < n && i < 30; i++) { printf("%f\\n", x[i]); } free(x); free(c); for (i = 0; i < n; i++) { free(A[i]); } free(A); free(y); if (type == 1) { pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); } else { pthread_barrier_destroy(&barrier); } return 0; }
1
#include <pthread.h> pthread_mutex_t locka, lockb, lockc, lockd, locke, lockf, lockg, lockh, locki; sem_t semi,sema,semb,semc,semd,semef,semg,semh,semi; void *fa(void *arg){ pthread_mutex_lock(&locka); fprintf(stdout,"a"); pthread_mutex_unlock(&lockb); pthread_mutex_unlock(&lockc); pthread_mutex_unlock(&lockd); } void *fb(void *arg){ pthread_mutex_lock(&lockb); fprintf(stdout,"b"); sem_post(&semi); } void *fc(void *arg){ pthread_mutex_lock(&lockc); fprintf(stdout,"c"); sem_post(&semef); sem_post(&semef); } void *fd(void *arg){ pthread_mutex_lock(&lockd); fprintf(stdout,"d"); pthread_mutex_unlock(&lockh); } void *fe(void *arg){ sem_wait(&semef); fprintf(stdout,"e"); sem_post(&semg); } void *ff(void *arg){ sem_wait(&semef); fprintf(stdout,"f"); sem_post(&semg); } void *fg(void *arg){ sem_wait(&semg); sem_wait(&semg); fprintf(stdout,"g"); sem_post(&semi); } void *fh(void *arg){ pthread_mutex_lock(&lockh); fprintf(stdout,"h"); sem_post(&semi); } void *fi(void *arg){ sem_wait(&semi); sem_wait(&semi); sem_wait(&semi); fprintf(stdout,"i"); exit(0); } int main(){ pthread_t ta,tb,tc,td,te,tf,tg,th,ti; sem_init(&sema,0,0); sem_init(&semb,0,0); sem_init(&semc,0,0); sem_init(&semd,0,0); sem_init(&semef,0,0); sem_init(&semg,0,0); sem_init(&semh,0,0); sem_init(&semi,0,0); pthread_mutex_init(&locka,0); pthread_mutex_init(&lockb,0); pthread_mutex_init(&lockc,0); pthread_mutex_init(&lockd,0); pthread_mutex_init(&locke,0); pthread_mutex_init(&lockf,0); pthread_mutex_init(&lockg,0); pthread_mutex_init(&lockh,0); pthread_mutex_init(&locki,0); pthread_mutex_lock(&locka); pthread_mutex_lock(&lockb); pthread_mutex_lock(&lockc); pthread_mutex_lock(&lockd); pthread_mutex_lock(&locke); pthread_mutex_lock(&lockf); pthread_mutex_lock(&lockg); pthread_mutex_lock(&lockh); pthread_mutex_lock(&locki); pthread_create(&ta,0,&fa,(void*)0); pthread_create(&tb,0,&fb,(void*)0); pthread_create(&tc,0,&fc,(void*)0); pthread_create(&td,0,&fd,(void*)0); pthread_create(&te,0,&fe,(void*)0); pthread_create(&tf,0,&ff,(void*)0); pthread_create(&tg,0,&fg,(void*)0); pthread_create(&th,0,&fh,(void*)0); pthread_create(&ti,0,&fi,(void*)0); pthread_mutex_unlock(&locka); pthread_join(ti,0); }
0
#include <pthread.h> pthread_mutex_t forks[5]; sem_t philosopherGoEat[5]; pthread_mutex_t fork_status; bool fork_available[5]; bool canEat(bool fork1_available, bool fork2_available){ if(fork1_available ==1 && fork2_available == 1){ fork1_available = 0; fork2_available = 0; return 1; } return 0; } void *waiter(){ int i; while(1){ for(i = 0;i<5;i++){ bool philCanEat = 0; pthread_mutex_lock(&fork_status); if(i == 0){ philCanEat = canEat(fork_available[0], fork_available[4]); } else { philCanEat = canEat(fork_available[i], fork_available[i - 1]); } pthread_mutex_unlock(&fork_status); if(philCanEat){ sem_post(&philosopherGoEat[i]); } } usleep(1000*100); } } void *philosopher(void* philo_id){ int *id = (int*) philo_id; while(1){ if(*id == 0){ sem_wait(&philosopherGoEat[*id]); pthread_mutex_lock(&forks[0]); pthread_mutex_lock(&forks[4]); printf("Philosopher %d is ready to eat now \\n", *id); sleep(1); pthread_mutex_unlock(&forks[4]); pthread_mutex_unlock(&forks[0]); pthread_mutex_lock(&fork_status); fork_available[0] = 1; fork_available[4] = 1; pthread_mutex_unlock(&fork_status); printf("Philosopher %d has finished his turn\\n",*id); }else { sem_wait(&philosopherGoEat[*id]); pthread_mutex_lock(&forks[*id]); pthread_mutex_lock(&forks[*id -1]); printf("Philosopher %d is ready to eat now \\n", *id); sleep(1); pthread_mutex_unlock(&forks[*id-1]); pthread_mutex_unlock(&forks[*id]); pthread_mutex_lock(&fork_status); fork_available[*id-1] = 1; fork_available[*id] = 1; pthread_mutex_unlock(&fork_status); printf("Philosopher %d has finished his turn\\n",*id); } usleep(1000*100); } } int main(){ int i; pthread_mutex_init(&fork_status,0); for(i = 0; i<5;i++){ pthread_mutex_init(&forks[i],0); sem_init(&philosopherGoEat[i],0,1); fork_available[i] = 1; } pthread_t thread1,thread2,thread3,thread4,thread5,thread6; int philosopher_id[5] = {0,1,2,3,4}; pthread_create(&thread6,0,waiter,0); pthread_create(&thread1,0,philosopher,&philosopher_id[0]); pthread_create(&thread2,0,philosopher,&philosopher_id[1]); pthread_create(&thread3,0,philosopher,&philosopher_id[2]); pthread_create(&thread4,0,philosopher,&philosopher_id[3]); pthread_create(&thread5,0,philosopher,&philosopher_id[4]); pthread_join(thread1,0); return 0; }
1
#include <pthread.h> pthread_cond_t conditionVar; pthread_mutex_t mutex; void *thread1CallBack(void *arg) { pthread_mutex_lock(&mutex); printf("hello\\n"); pthread_cond_wait(&conditionVar, &mutex); int *tmp = (int *)arg; printf("thread 1 is runing\\n"); printf("thread 1 get var is %d\\n", *tmp); (*tmp)++; pthread_mutex_unlock(&mutex); } void *thread2CallBack(void *arg) { sleep(2); pthread_mutex_lock(&mutex); int *tmp = (int *)arg; printf("thread 2 is runing\\n" "thread 2 get var is %d\\n", *tmp); (*tmp)++; pthread_cond_signal(&conditionVar); pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { assert (pthread_cond_init(&conditionVar, 0) == 0); assert (pthread_mutex_init(&mutex, 0) == 0); pthread_t thread1, thread2; int comVar = 0; assert (pthread_create(&thread1, 0, thread1CallBack, &comVar) == 0); assert (pthread_create(&thread2, 0, thread2CallBack, &comVar) == 0); assert (pthread_join(thread1, 0) == 0); assert (pthread_join(thread2, 0) == 0); printf("main function get var is %d\\n", comVar); pthread_cond_destroy(&conditionVar); return 0; }
0
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 5) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 5); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[5]; int sorted[5]; void producer () { int i, idx; for (i = 0; i < 5; i++) { idx = findmaxidx (source, 5); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 5; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 5); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 5; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> int thread_count; pthread_mutex_t mutex; double sum = 0; int n = 1024; void * threadSum (void * rank){ long my_rank = (long) rank; double factor; long long i; long long myN = n/thread_count; long long myFirstI = myN * my_rank; long long myLastI = myFirstI + myN; double mySum = 0; if(myFirstI & 1){ factor = -1; } else{ factor = 1; } for(i = myFirstI; i < myLastI; i++, factor = -factor){ mySum += factor/(2*i + 1); } pthread_mutex_lock(&mutex); sum += mySum; pthread_mutex_unlock(&mutex); return 0; } int main (int arc, char* argv[]){ long thread; pthread_t* thread_handles; thread_count = strtol(argv[1], 0, 10); thread_handles = malloc (thread_count * sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); for(long i = 0; i < thread_count; i++){ pthread_create(thread_handles + i, 0, threadSum, (void*) i); } for(long i = 0; i < thread_count; i++){ pthread_join(thread_handles[i], 0); } pthread_mutex_destroy(&mutex); printf("%f\\n", 4*sum); return 0; }
0
#include <pthread.h> static int glob = 0; static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER; static void * threadFunc1(void *arg) { int loop = (int)(*((int*)arg)); while(loop-- >0){ pthread_mutex_lock(&mtx1); pthread_mutex_lock(&mtx2); glob += 1; printf("in t1 glob = %d\\n", glob); pthread_mutex_unlock(&mtx2); pthread_mutex_unlock(&mtx1); } return 0; } static void * threadFunc2(void *arg) { int loop = (int)(*((int*)arg)); while(loop-- > 0){ pthread_mutex_lock(&mtx2); pthread_mutex_lock(&mtx1); glob += 1; printf("in t2 glob = %d\\n", glob); pthread_mutex_unlock(&mtx1); pthread_mutex_unlock(&mtx2); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int loops,s; loops = 10000; s = pthread_create(&t1, 0, threadFunc1, &loops); s = pthread_create(&t2, 0, threadFunc2, &loops); s = pthread_join(t1, 0); s = pthread_join(t2, 0); printf("glob = %d\\n", glob); return 0; }
1
#include <pthread.h> int global_int; pthread_mutex_t lock; pthread_cond_t cond; void *fn_1(void *args){ pthread_mutex_lock(&lock); while(global_int != 999) pthread_cond_wait(&cond, &lock); printf("fn1: read global_int: %d\\n", global_int); global_int++; printf("fn1: updated global_int: %d\\n", global_int); pthread_mutex_unlock(&lock); return 0; } void *fn_2(void *args){ sleep(3); pthread_mutex_lock(&lock); global_int = 999; printf("fn2: signal\\n"); pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); return 0; } int main(){ int smv_id; pthread_t tid[2]; global_int = 0; smv_main_init(1); pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&lock, &attr); pthread_condattr_t cattr; pthread_condattr_init(&cattr); pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); pthread_cond_init(&cond, &cattr); pthread_create(&tid[0], 0, fn_2, 0); smv_id = smv_create(); smvthread_create(smv_id, &tid[1], fn_1, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); printf("global_int: %d\\n", global_int); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t blanks; sem_t datas; int ringBuf[30]; void *productRun(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product is done... data is: %d\\n",data); sem_post(&datas); } } void *productRun2(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product2 is done... data is: %d\\n",data); sem_post(&datas); } } void *consumerRun(void *arg) { int i = 0; while(1) { usleep(1456); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer is done... data is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } void *consumerRun2(void *arg) { int i = 0; while(1) { usleep(1234); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer2 is done...data2 is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } int main() { sem_init(&blanks, 0, 30); sem_init(&datas, 0, 0); pthread_t tid1,tid2,tid3,tid4; pthread_create(&tid1, 0, productRun, 0); pthread_create(&tid4, 0, productRun2, 0); pthread_create(&tid2, 0, consumerRun, 0); pthread_create(&tid3, 0, consumerRun2, 0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); sem_destroy(&blanks); sem_destroy(&datas); return 0; } int sem_ID; int customers_count=5; int eflag=0,fflag=0; void barber() { printf("barber started\\n"); while(1) { sem_change(sem_ID, 2, -1);printf("A\\n"); sem_change(sem_ID, 1, 1);printf("B\\n"); customers_count++; sem_change(sem_ID, 0, 1);printf("C\\n"); sem_change(sem_ID, 1, -1);printf("D\\n"); printf("CUT HAIR\\n"); sleep(2); } } void customer(void *arg) { printf("CUSTOMER CAME %d\\n",pthread_self()); sem_change(sem_ID, 1, 1);printf("E\\n"); if(customers_count>0) {customers_count--; sem_change(sem_ID, 2, 1);printf("F\\n"); sem_change(sem_ID, 1, -1);printf("G\\n"); sem_change(sem_ID, 0, -1);printf("I\\n"); printf("GET CUTTING %d\\n",pthread_self()); } else {sem_change(sem_ID, 1, -1);printf("J\\n"); printf("LEAVE WITHOUT CUT\\n"); } int *ptr=(int*)arg; *ptr=0; } int main(int argc, char* argv[]) { pthread_t barber_thread; int live_threads[5 +2]; pthread_t customer_thread[5 +2]; int i; for(i=0; i<5 +2; i++) live_threads[i]=0; int array[]={0, 0, 0, 0, 0}; sem_ID=sem_init_diff_val(5,array); pthread_create(&barber_thread, 0, (void*)&barber, 0); sleep(2); while(1) {int i; for(i=0; i<5 +2; i++) { if(live_threads[i]==0) { live_threads[i]=1; pthread_create(&customer_thread[i], 0, (void*)&customer, (void*)&live_threads[i]); sleep(rand()%2); } } } exit(0); }
1
#include <pthread.h> PROCESS process; void* arg; struct worker *next; }CThread_worker; pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker * queue_head; pthread_t *threadid; int max_threads; int cur_queue_len; int shutdown; }CThread_pool; static CThread_pool * pool; void* worker_routine(void * arg){ while(1){ pthread_mutex_lock(&pool->queue_lock); while(pool->cur_queue_len==0&&pool->shutdown==0){ printf("no work need to do,thread =%d\\n\\n",pthread_self()); pthread_cond_wait(&pool->queue_ready,&pool->queue_lock); } if(pool->shutdown){ pthread_mutex_unlock(&pool->queue_lock); printf("thread = %d, will exit\\n",pthread_self()); pthread_exit(0); } CThread_worker * worker=pool->queue_head; pool->queue_head=pool->queue_head->next; pool->cur_queue_len--; pthread_mutex_unlock(&pool->queue_lock); printf("this is thread %d, i will work\\n\\n",pthread_self()); worker->process(*(int*)(worker->arg)); free(worker); } } void pool_init(int max_worker){ assert(max_worker>=0); pool=(CThread_pool*)malloc(sizeof(CThread_pool)); pool->queue_head=0; pthread_mutex_init(&pool->queue_lock,0); pthread_cond_init(&pool->queue_ready,0); pool->max_threads=max_worker; pool->cur_queue_len=0; pool->shutdown=0; pool->threadid=(pthread_t*)malloc(max_worker*(sizeof(pthread_t))); for(int i=0;i<max_worker;i++){ pthread_create(pool->threadid+i,0,worker_routine,0); } } void pool_add_worker(PROCESS process,void * arg){ assert(process); CThread_worker * newwork=(CThread_worker*)malloc(sizeof(CThread_worker)); newwork->process=process; newwork->arg=arg; pthread_mutex_lock(&pool->queue_lock); if(pool->shutdown){ free(newwork); pthread_mutex_unlock(&pool->queue_lock); return ; } if(pool->queue_head!=0){ CThread_worker * tmpworker=pool->queue_head; while(tmpworker->next){ tmpworker=tmpworker->next; } tmpworker->next=newwork; }else{ pool->queue_head=newwork; } pool->cur_queue_len++; pthread_mutex_unlock(&pool->queue_lock); pthread_cond_signal(&pool->queue_ready); } void pool_destroy(){ if(pool->shutdown){ return ; } pthread_mutex_lock(&(pool->queue_lock)); printf("set shuddown\\n\\n"); pool->shutdown=1; pthread_mutex_unlock(&(pool->queue_lock)); printf("cond_broadcast\\n"); pthread_cond_broadcast(&pool->queue_ready); for(int i=0;i<pool->max_threads;i++){ pthread_join(pool->threadid[i],0); } pthread_mutex_destroy(&pool->queue_lock); pthread_cond_destroy(&pool->queue_ready); CThread_worker * tmpworker=pool->queue_head; while(pool->queue_head){ tmpworker=pool->queue_head; pool->queue_head=pool->queue_head->next; free(tmpworker); } free(pool->threadid); free(pool); } void* myfunc(int num){ printf("myfunc -------%d\\n",num); sleep(1); } void main(){ pool_init(3); int a[10]; for(int i=0;i<10;i++ ){ a[i]=i; pool_add_worker(myfunc,&a[i]); } printf("after pool_join \\n"); sleep(10); printf("before pool_destroy \\n"); pool_destroy(); }
0
#include <pthread.h> static volatile int run_flag = 1; pthread_mutex_t m ; pthread_cond_t c = PTHREAD_COND_INITIALIZER; pthread_cond_t w = PTHREAD_COND_INITIALIZER; int done=0; int sent=1; float pitch_buffer[151]; float roll_buffer[151]; float avg_val[2]={0,0}; void do_when_interrupted() { run_flag = 0; } double timestamp() { struct timeval tv; double sec_since_epoch; gettimeofday(&tv, 0); sec_since_epoch = (double) tv.tv_sec + (double) tv.tv_usec/1000000.0; return sec_since_epoch; } void* read_data(void *arg) { NINEDOF *ninedof; mraa_init(); ninedof = ninedof_init(A_SCALE_4G, G_SCALE_245DPS, M_SCALE_2GS); float *pitch, *roll; printf("collecting data in 9DOF thread\\n"); while(run_flag) { float pitch_avg_local=0; float roll_avg_local=0; pitch=calloc(151,sizeof(float)); roll=calloc(151,sizeof(float)); pitch[0]=0; roll[0]=1; ninedof_read(ninedof,(pitch),(roll)); int i=0; pthread_mutex_lock(&m); while(sent==0) pthread_cond_wait(&w, &m); for (i = 0; i < 151; i++) { pitch_avg_local=pitch_avg_local + pitch[i]; roll_avg_local=roll_avg_local + roll[i]; } avg_val[0] = pitch_avg_local/150; avg_val[1]=roll_avg_local/150; printf("done collecting in 9DOF thread\\n"); sent=0; done =1; pthread_cond_signal(&c); printf("pthread signal\\n"); pthread_mutex_unlock(&m); printf("done with this iteration in 9DOF thread\\n"); free(pitch); free(roll); } } void* client_handle_connection(void *arg) { printf("in client \\n"); int n; int rc; char buffer[256]; char ready_buf[10]; double sec_since_epoch; int i; int client; int server_signal; client = *(int *)arg; ioctl(client, FIONBIO, 0); sprintf(ready_buf, "ready"); ready_buf[strlen(ready_buf)] = '\\0'; while (run_flag) { memset(buffer, 0, 256); sec_since_epoch = timestamp(); int i; printf("waiting\\n"); rc=pthread_mutex_lock(&m); if(rc==EBUSY) { printf("lock busy\\n"); continue; } while (done==0) pthread_cond_wait(&c, &m); n = write(client, ready_buf, sizeof(ready_buf)); printf("Pitch Data: \\n"); n = read(client, buffer, sizeof(buffer)); buffer[strlen(buffer)] = '\\0'; printf("read from server(pitch): %s\\n", buffer); if (n > 0 && strcmp(buffer, "pitch")==0) { printf("writing pitch buffer to server\\n"); n = write(client, avg_val, 8); if (n < 0) { client_error("ERROR writing to socket"); } printf("sent pitch buffer\\n"); } done=0; sent = 1; pthread_cond_signal(&w); pthread_mutex_unlock(&m); printf("exited from client\\n"); usleep(10000); } close(client); } int main(int argc, char *argv[]) { int client_socket_fd; signal(SIGINT, do_when_interrupted); int *client; (client_socket_fd) = client_init(argc, argv); client=&client_socket_fd; if (client_socket_fd < 0) { return -1; } pthread_t manage_9dof_tid, manage_client_tid; int rc; rc = pthread_create(&manage_9dof_tid, 0, read_data, 0); if (rc != 0) { fprintf(stderr, "Failed to create manage_9dof thread. Exiting Program.\\n"); exit(0); } rc = pthread_create(&manage_client_tid, 0, client_handle_connection, (void*)client); if (rc != 0) { fprintf(stderr, "Failed to create thread. Exiting program.\\n"); exit(0); } pthread_join(manage_9dof_tid, 0); pthread_join(manage_client_tid, 0); printf("\\n...cleanup operations complete. Exiting main.\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int sum=0; void* p_func(void* p) { int i; pthread_mutex_lock(&mutex); pthread_mutex_lock(&mutex); printf("I am child\\n"); pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main() { int ret; pthread_mutexattr_t attr; int i; i=PTHREAD_MUTEX_RECURSIVE_NP; memcpy(&attr,&i,4); ret=pthread_mutex_init(&mutex,&attr); if(0!=ret) { printf("pthread_mutex_init ret=%d\\n",ret); return -1; } pthread_t pthid; pthread_create(&pthid,0,p_func,0); ret=pthread_join(pthid,0); if(0!=ret) { printf("pthread_join ret=%d\\n",ret); return -1; } ret=pthread_mutex_destroy(&mutex); if(0!=ret) { printf("pthread_mutex_destroy ret=%d\\n",ret); return -1; } return 0; }
0
#include <pthread.h> int CADEIRAS; int TIMEWAIT_MAX; volatile int running = 1; pensar, fome, comer, } Filosofos; void rel(int filosofo, int comeu,int pensou,int tentou); int Filosofos_esquerda(int filo_n); int Filosofos_direita(int filo_n); void *Filosofos_checkin(void *filo); pthread_mutex_t forks; Filosofos *FilosofosN; int main(int argc, char **argv){ int shmid; key_t key; char *shm, *s; key = 5678; int i; pthread_t *thread; CADEIRAS = atoi(argv[1]); TIMEWAIT_MAX = atoi(argv[2]); FilosofosN = (Filosofos *) calloc(CADEIRAS, sizeof(Filosofos)); if(FilosofosN == 0){ printf("\\nErro ao alocar os filosofos!\\n"); return -1; } thread = (pthread_t *) calloc(CADEIRAS, sizeof(pthread_t)); if(thread == 0){ printf("\\nErro ao alocar as threads!\\n"); return -1; } pthread_mutex_init(&forks, 0); for(i = 0; i<CADEIRAS; i++){ FilosofosN[i] = pensar; pthread_create(&thread[i], 0, Filosofos_checkin, (void *) i); } sleep(TIMEWAIT_MAX); running = 0; for(int n = 0; n<CADEIRAS; n++){ if(pthread_join(thread[n], 0)) { fprintf(stderr, "Error joining thread\\n"); return 1; } } pthread_mutex_destroy(&forks); free(FilosofosN); printf("Termino da execução... \\n"); return 0; if ((shmid = shmget(key, 27, 0666)) < 0) { perror("shmget"); exit(1); } if ((shm = shmat(shmid, 0, 0)) == (char *) -1) { perror("shmat"); exit(1); } for (s = shm; *s != 0; s++) putchar(*s); putchar('\\n'); *shm = '*'; } int Filosofos_esquerda(int filo_n){ return (filo_n + CADEIRAS - 1) % CADEIRAS; } int Filosofos_direita(int filo_n){ return (filo_n + 1) % CADEIRAS; } void *Filosofos_checkin(void *filo){ int filo_n = (int*)filo; int comeu, tentou, pensou; comeu = 0; tentou = 0; pensou = 0; while(running){ pthread_mutex_lock(&forks); switch(FilosofosN[filo_n]){ case pensar: FilosofosN[filo_n] = fome; pthread_mutex_unlock(&forks); pensou ++; sleep(5); break; case comer: FilosofosN[filo_n] = pensar; pthread_mutex_unlock(&forks); comeu ++; usleep(2000); break; case fome: if(FilosofosN[Filosofos_esquerda(filo_n)] == comer){ pthread_mutex_unlock(&forks); tentou ++; } else if(FilosofosN[Filosofos_direita(filo_n)] == comer){ pthread_mutex_unlock(&forks); tentou ++; }else{ FilosofosN[filo_n] = comer; pthread_mutex_unlock(&forks); } sleep(random() % 3); break; } } rel(filo_n, comeu, pensou, tentou); return 0; } void rel(int filosofo, int comeu,int pensou,int tentou){ printf("Filosofo [%d] - Pensou %d: - Comeu %d: - Tentou %d:\\n",filosofo ,comeu ,pensou, tentou); }
1
#include <pthread.h> static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER; static int num = 0; static int next(int a) { if (a + 1 == 4) return 0; return a + 1; } void *thr_func(void *arg) { int i = (int)arg; char ch = i + 'a'; while (1) { pthread_mutex_lock(&mut_num); while (num != i) { pthread_cond_wait(&cond_num, &mut_num); } putchar(ch); num = next(num); pthread_cond_broadcast(&cond_num); pthread_mutex_unlock(&mut_num); } pthread_exit((void *)0); } int main() { int i, err; pthread_t tid[4]; for (i = 0; i < 4; i++) { err = pthread_create(tid + i, 0, thr_func, (void *)i); if (err) { fprintf(stderr, "pthread_create(): %s\\n", strerror(err)); exit(1); } } alarm(5); for (i = 0; i < 4; i++) pthread_join(tid[i], 0); exit(0); }
0
#include <pthread.h> int somme_val=0; int nbre_thread=0; int signal_envoye=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; void *print_thread(){ pthread_mutex_lock(&mutex); if(signal_envoye==0){ pthread_cond_wait(&cond, &mutex); } printf("La valeur générée est %d\\n", somme_val); pthread_mutex_unlock(&mutex); pthread_exit(0); } void *thread_rand(void *arg) { int *pt=(int*)arg; int random_val; random_val=(int) (10*((double)rand())/32767); *pt=*pt*2; pthread_mutex_lock(&mutex); somme_val+=random_val; nbre_thread++; printf("Argument recu : %d, thread_id : %d, random_val : %d\\n", *pt, (int)pthread_self(), random_val); if(nbre_thread==10){ pthread_cond_signal(&cond); signal_envoye++; } pthread_mutex_unlock(&mutex); pthread_exit(pt); } int main(int argc, char ** argv){ pthread_t tid[10 +1]; pthread_attr_t attr; int i; int* status; int* pt_ind; if(pthread_create(&(tid[0]), 0, print_thread, 0)){ printf("pthread_create\\n"); exit(1); } for (i=1;i<10 +1;i++) { pt_ind=(int*)malloc(sizeof(i)); *pt_ind=i; if (pthread_create(&tid[i],0,thread_rand,(void *)pt_ind)!=0) { printf("ERREUR:creation\\n"); exit(1); } pthread_detach(tid[i]); } if(pthread_join(tid[0], (void**)&status)!=0){ printf("pthread_join");exit(1); } else{ printf("Thread %d fini\\n", i); } printf("La somme est %d\\n",somme_val); return 0; }
1
#include <pthread.h> struct socket_context* incoming_queue; struct socket_context* output_list; struct socket_context* storage_cache; int add(struct socket_context* storage, struct socket_context* sc); struct socket_context* find(struct socket_context* storage, int sock); pthread_mutex_t inqueue_mutex; pthread_cond_t empty_inqueue_cv; pthread_mutex_t outqueue_mutex; pthread_cond_t empty_outqueue_cv; int init_storage() { struct socket_context *cs; for (int i = 0; i < 32; i++) { cs = storage_cache; storage_cache = malloc(sizeof(struct socket_context)); if (storage_cache == 0) { return -1; } storage_cache->request = malloc(MAX_PACKET_SIZE + 1); if (storage_cache->request == 0) { free(storage_cache); return 0; } storage_cache->next = cs; } pthread_mutex_init(&inqueue_mutex, 0); pthread_cond_init(&empty_inqueue_cv, 0); pthread_mutex_init(&outqueue_mutex, 0); pthread_cond_init(&empty_outqueue_cv, 0); return 0; } int cleanup_storage() { pthread_mutex_destroy(&inqueue_mutex); pthread_cond_destroy(&empty_inqueue_cv); pthread_mutex_destroy(&outqueue_mutex); pthread_cond_destroy(&empty_outqueue_cv); return 0; } struct socket_context* create_socket_context(int client_socket, char* buffer) { struct socket_context* sc; if (storage_cache == 0) { sc = malloc(sizeof(struct socket_context)); sc->request = malloc(MAX_PACKET_SIZE + 1); if (sc->request == 0) { free(sc); return 0; } } else { sc = storage_cache; storage_cache = sc->next; sc->next = 0; } if (sc != 0) { sc->client_socket = client_socket; strcpy(sc->request, buffer); sc->response = 0; sc->close_after_response = 0; } return sc; } void destroy_socket_context(struct socket_context* sc) { sc->next = storage_cache; storage_cache = sc; if (sc->response) { free(sc->response); } } int add_input(struct socket_context* sc) { pthread_mutex_lock(&inqueue_mutex); int result = 0; if (incoming_queue == 0) { incoming_queue = sc; } else { result = add(incoming_queue, sc); } if (result != -1) { pthread_cond_broadcast(&empty_inqueue_cv); } pthread_mutex_unlock(&inqueue_mutex); return result; } int add_output(struct socket_context* sc) { pthread_mutex_lock(&outqueue_mutex); int result = 0; if (output_list == 0) { output_list = sc; } else { result = add(output_list, sc); } if (result != -1) { pthread_cond_broadcast(&empty_outqueue_cv); } pthread_mutex_unlock(&outqueue_mutex); return result; } struct socket_context* poll_first_input() { pthread_mutex_lock(&inqueue_mutex); while (incoming_queue == 0) { pthread_cond_wait(&empty_inqueue_cv, &inqueue_mutex); } struct socket_context* sc = incoming_queue; incoming_queue = sc->next; pthread_mutex_unlock(&inqueue_mutex); return sc; } struct socket_context* get_output(int client_socket) { pthread_mutex_lock(&outqueue_mutex); struct socket_context* sc = find(output_list, client_socket); if (sc != 0) { output_list = sc->next; } pthread_mutex_unlock(&outqueue_mutex); return sc; } int add(struct socket_context* storage, struct socket_context* sc) { struct socket_context* existing = find(storage, sc->client_socket); if (existing == 0) { struct socket_context* tp = storage; while (tp->next != 0) { tp = tp->next; } tp->next = sc; sc->next = 0; return 0; } fprintf(stderr, "[error] Socket Context already exists: socket=%d.\\n", sc->client_socket); return -1; } struct socket_context* find(struct socket_context* storage, int sock) { struct socket_context* tp = storage; while (tp) { if (tp->client_socket == sock) { return tp; } tp = tp->next; } return 0; }
0
#include <pthread.h> pthread_cond_t sem; pthread_mutex_t read; pthread_mutex_t write; pthread_mutex_t count; int sem_count = 0; int sem_b = 0; int isWriteReady = 0; int data = 1; void CreateSemaphore() { if(pthread_cond_init(&sem, 0) != 0) { printf("Semaphore creation failed\\n"); exit(0); } if(pthread_mutex_init(&read, 0) != 0) { printf("Semaphore Creation failed\\n"); exit(0); } if(pthread_mutex_init(&count, 0) != 0) { printf("Semaphore Creation failed\\n"); exit(0); } if(pthread_mutex_init(&write, 0) != 0) { printf("Semaphore Creation failed\\n"); exit(0); } } int isReading() { if(sem_count != 0) return 1; else return 0; } void FinishRead() { isWriteReady = 1; while(isReading()); } void ResumeRead() { isWriteReady = 0; } void WriteLock() { if(pthread_mutex_lock(&write) == 0) { printf("Write Lock acquired\\n"); FinishRead(); } } void WriteUnlock() { if(pthread_mutex_unlock(&write) == 0) { printf("Write Lock released\\n"); ResumeRead(); } isWriteReady = 0; } int ReadLock() { if(isWriteReady == 1) { printf("writer wants to write, no new reads allowed\\n"); return -1; } int ret = pthread_mutex_trylock(&read) ; if(ret == 0) { pthread_mutex_lock(&count); if(sem_count < 5) { sem_count++; } else { printf("No more read locks available\\n"); return -1; } pthread_mutex_unlock(&count); return 0; } else if(ret == EBUSY) { pthread_mutex_lock(&count); if(sem_count < 5) { sem_count++; pthread_mutex_unlock(&count); printf("we already have a read lock\\n"); return 0; } else { printf("No more read locks available\\n"); pthread_mutex_unlock(&count); return -1; } } else { printf("Read mutex lock failed Lets try again\\n"); return -1; } } int ReadUnlock() { if(pthread_mutex_trylock(&read) == EBUSY) { pthread_mutex_lock(&count); sem_count--; if(sem_count == 0 ) { pthread_mutex_unlock(&read); } pthread_mutex_unlock(&count); } else return -1; } void* Reader(void *param) { printf("Reader %d: executing\\n", *((int *)param)); if(ReadLock() == 0) { usleep(200); printf("Data read %d\\n", data); if(ReadUnlock() != 0) printf("Error Unlocking\\n"); } else printf("Reader %d: No lock\\n", *((int *)param)); printf("Reader %d: done\\n\\n", *((int *)param)); return 0; } void *Writer(void * param) { printf("Writer %d: executing\\n", *((int *)param)); WriteLock(); data += 12; WriteUnlock(); sleep(2); printf("Writer %d: done\\n\\n", *((int *)param)); return 0; } int main() { pthread_t writer[3]; pthread_t reader[20]; int i = 0; int arr[20]; int arrW[3]; for(i = 0; i < 20; ++i) arr[i] = i; for(i = 0; i < 3; ++i) arrW[i] = i; CreateSemaphore(); for(i = 0; i < 20; ++i) { int j= 0 ; j = i; pthread_create(&reader[i], 0, Reader, (void *)&arr[i]); if(i < 3) { pthread_create(&writer[i], 0, Writer, (void *)&arrW[i]); } } for(i = 0; i < 20; ++i) { pthread_join(reader[i], 0); if(i < 3) pthread_join(writer[i], 0); } printf("main exiting\\n"); }
1
#include <pthread.h> struct msg{ char *str; int row; int delay; int dir; }; pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER; int setup(int strnum, char *strings[], struct msg msgs[]) { int i; int num_msg = (strnum > 10 ? 10 : strnum); for(i = 0; i < strnum; i++){ msgs[i].str = strings[i]; msgs[i].row = i; msgs[i].delay = 1 + (rand() % 10); msgs[i].dir = ((rand() % 2) ? 1 : -1); } initscr(); crmode(); noecho(); clear(); mvprintw(LINES - 1, 0, "'Q' to quit, '0'...'%d' to bounce", num_msg - 1); return num_msg; } void *movestr(void *arg) { struct msg *info = arg; int len = strlen(info->str) + 2; int col = rand() % (COLS - len - 3); while(1){ usleep(info->delay * 20000); pthread_mutex_lock(&mx); move(info->row, col); addch(' '); addstr(info->str); addch(' '); move(LINES-1, COLS-1); refresh(); pthread_mutex_unlock(&mx); col += info->dir; if(col <= 0 && info->dir == -1) info->dir = 1; else if(col + len >= COLS && info->dir == 1) info->dir = -1; } } int main(int argc, char *argv[]) { int msg_num; int c; pthread_t thrds[10]; struct msg msgs[10]; int i; if(argc == 1){ printf("usage: string ...\\n"); exit(1); } msg_num = setup(argc-1, argv+1, msgs); for(i = 0; i < msg_num; i++){ if(pthread_create(&thrds[i], 0, movestr, &msgs[i])){ fprintf(stderr, "error creating thread"); endwin(); exit(0); } } while(1){ c = getch(); if(c == 'Q') break; if(c == ' '){ for(i = 0; i < msg_num; i++) msgs[i].dir = -msgs[i].dir; } if(c >= '0' && c <= '9'){ i = c - '0'; if(i < msg_num) msgs[i].dir = -msgs[i].dir; } } pthread_mutex_lock(&mx); for(i = 0; i < msg_num; i++) pthread_cancel(thrds[i]); endwin(); return 0; }
0
#include <pthread.h> struct iSharePrivate { unsigned char destroy; pthread_mutex_t token; char * shm_pointer; }; int iShare_Init(struct iShare * iShare) { key_t key; int shmflg; int shmid; int size; char * shm; struct iSharePrivate * private_struct; key = iShareGetSHMKey(*iShare); shmflg = IPC_CREAT | 0666; size = ISHARE_MEM_SIZE; if ((shmid = shmget(key, size, shmflg)) < 0) { printf("shmget error.\\n"); return -1; } if ((shm = shmat(shmid, 0, 0)) == (char *) -1) { printf("shmat error"); return -1; } private_struct = (struct iSharePrivate *)iShare->p; private_struct->destroy = 0; pthread_mutex_init(&private_struct->token, 0); private_struct->shm_pointer = shm; return (int) key; } int iShare_DeInit(struct iShare * iShare) { struct iSharePrivate * pri = (struct iSharePrivate *)iShare->p; pthread_mutex_t * mutex = &pri->token; pthread_mutex_lock(mutex); pri->destroy = 1; pthread_mutex_unlock(mutex); return 0; } int iShareGetSHMKey(struct iShare ishare) { return ishare.SensorType * 100 + ishare.SensorNumber; } int iShareGetSavedFilename(struct iShare ishare, char * filename_buffer) { char filename[30]; memset(filename, 0, 30); sprintf(filename, "RaspiDo_%d_%d.tqk", ishare.SensorType, ishare.SensorNumber); strcpy(filename_buffer, filename); return 0; } int iShare_SaveToDisk(struct SharedMemoryData * ishare_data, const char * filename) { struct iSharePrivate * pri; FILE * fp = fopen(filename, "w+"); if (fp == 0) { printf("Cannot open file: %s.\\n", filename); return -1; } fclose(fp); return 0; } int iShare_RestoreFromDisk(struct SharedMemoryData * ishare_data, const char * filename) { FILE * fp = fopen(filename, "r+"); if (fp == 0) { printf("Cannot open file: %s.\\n", filename); return -1; } fclose(fp); return 0; } void * iShareThread(void * handle_obj) { pthread_exit(0); }
1
#include <pthread.h> int eye_update_interval = 50; int smallest_head; float smallest_val; bool eye_terminate = 0; bool ball_inside = 0; pthread_mutex_t nav_mutex; pthread_t eye_tid; void reset_value(){ smallest_head = 0; smallest_val = 9999.0; } void * eye_check(){ int detected_color; float ball_distance; while(!eye_terminate){ detected_color = (int) sn_get_color_val(); ball_distance = sn_get_sonar_val(); if (ball_distance < US_THRESHOLD && ball_distance <= smallest_val){ pthread_mutex_lock(&nav_mutex); smallest_val = ball_distance; smallest_head = get_heading(); pthread_mutex_unlock(&nav_mutex); printf("EYE_V: %f\\t%d\\n",smallest_val, smallest_head); } if (detected_color == 5) { stop_turn = 1; close_ball(); ball_inside = 1; return 0; } usleep(( eye_update_interval ) * 1000 ); } return 0; } void eye_start(){ reset_value(); eye_terminate = 0; pthread_mutex_init(&nav_mutex, 0); printf("Creating THE EYE threat... "); pthread_create(&eye_tid, 0, eye_check, 0); printf("Done\\n"); } bool obstacle_detected(float *val, int *head){ pthread_mutex_lock(&nav_mutex); if(smallest_val<US_THRESHOLD){ *val = smallest_val; *head = smallest_head; reset_value(); pthread_mutex_unlock(&nav_mutex); printf("EYE: Value: %f, Heading: %d\\n", *val, *head); return 1; } else{ reset_value(); pthread_mutex_unlock(&nav_mutex); return 0; } } void eye_stop(){ printf("Waiting for THE EYE thread to terminate...\\n"); eye_terminate = 1; pthread_join(eye_tid, 0); printf("Done\\n"); }
0
#include <pthread.h> int server_running; pthread_t *ping_threads; pthread_t serverthread; char *dev; void *ping_thread(void *arg) { if (arg != 0) { struct cfgData *data = (struct cfgData *)arg; if (data->status == tUp) { if (ping(&data->ip) != 0) { pthread_mutex_lock(&data->accessmutex); ifup(dev,data); debug_printf("Device is down, should going up\\n"); data->status=tDown; pthread_mutex_unlock(&data->accessmutex); } } else if (data->status == tGoingUp) { debug_printf("Going up\\n"); if (ping(&data->ip) == 0) { debug_printf("Going up id UP\\n"); pthread_mutex_lock(&data->accessmutex); data->status=tUp; pthread_mutex_unlock(&data->accessmutex); } } else if (data->status==tUnknown) { debug_printf("Unknown status of device\\n"); if (ping(&data->ip) == 0) { pthread_mutex_lock(&data->accessmutex); data->status=tUp; pthread_mutex_unlock(&data->accessmutex); } else { pthread_mutex_lock(&data->accessmutex); ifup(dev,data); data->status=tDown; pthread_mutex_unlock(&data->accessmutex); } } } return (0); } void *server_thread(void *arg) { int i; while (server_running==0) { struct hostData *tmp = hostBuffer; for(i=0;i<get_configsize();i++) { debug_printf("New ping cycle %i\\n",get_configsize()); pthread_create(&ping_threads[i],0,ping_thread,(void *)&tmp->data); pthread_join(ping_threads[i], 0); tmp = tmp->next; } sleep(5); } return 0; } int init_server(char *pdev) { dev=pdev; int err; ping_threads = (pthread_t*)malloc(get_configsize()*sizeof(pthread_t)); server_running=0; err = pthread_create(&serverthread, 0, &server_thread, 0); if (err != 0) { return ERR_THREAD_CREATE; } return 0; }
1
#include <pthread.h> void* task(void* argument); int var=0; int max= -2147483647; int min= +2147483647; pthread_mutex_t lock; int main(void) { pthread_mutex_init(&lock,0); pthread_t threads[8]; int threadArgs[8]; int t; for(t=0; t<8; t++ ){ threadArgs[t]= t; printf("main: Creating thread %d\\n", t); int ok= pthread_create(&threads[t],0,task,(void*)&threadArgs[t]); if( ok!=0 ){ printf("main: could not create thread %d\\n",t); return 1; } } for (t=0; t<8; t++ ){ int ok= pthread_join(threads[t],0); if( ok!=0 ){ printf("main: Could not JOIN thread %d\\n",t); return 1; } printf("Main: Thread %d complete\\n",t); } printf("After all, var= %d\\n",var); printf("min= %d\\n",min); printf("max= %d\\n",max); printf("main: Completed\\n"); return 0; } void* task(void* arg) { int myId; myId= *((int*)arg); printf(" thread %d: Started\\n",myId); int incDec= +1; if(myId%2==1 ){ incDec=-1; } int i; for( i=0; i<10000; i++ ){ pthread_mutex_lock(&lock); var=var+incDec; if( var> max ){ max= var; } if( var< min ){ min= var; } pthread_mutex_unlock(&lock); } printf(" thread %d: var= %d\\n",myId,var); printf(" thread %d: Ending\\n",myId); return 0; }
0
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; int count = 0; int task[3]; void *consumer(void *arg) { for (;;) { int num; pthread_mutex_lock(&mutex); if (count > 0) { count--; num = task[count]; printf("Consumer processed item: %d\\n", num); } pthread_mutex_unlock(&mutex); if(num == 3) break; } return 0 ; } void *producer(void *arg) { unsigned short int xsubi[3] = {3, 7, 11}; int num = 0; for (;;) { double sleep_time = 1.0 + erand48(xsubi); if (num == 2) usleep(1000000 * sleep_time); pthread_mutex_lock(&mutex); task[count] = num; count++; printf("Producer slept for %lf seconds created item: %d\\n",sleep_time, num); pthread_mutex_unlock(&mutex); if(num == 3) break; num++; } return 0 ; } int main() { pthread_t prod, cons; pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); pthread_create(&cons, 0, &consumer, 0); pthread_create(&prod, 0, &producer, 0); pthread_join(prod, 0); pthread_join(cons, 0); return 0; }
1
#include <pthread.h> int n, C, T, N; FILE* fout; char* out; pthread_t car; pthread_t passenger[10]; pthread_mutex_t mutex; int passenger_time[10] = {0}; int car_time = 0; int on_board[10] = {0}; int on_board_count = 0; int ending = 0; sem_t queue, checkin, boarding, riding, unloading; void* PassengerThread(void* argv) { int passenger_id = *(int*)argv; while (!ending) { pthread_mutex_lock(&mutex); fprintf(fout, "Passenger %d wanders around the park.\\n", passenger_id); pthread_mutex_unlock(&mutex); usleep(passenger_id * 1000); passenger_time[passenger_id - 1] += passenger_id; pthread_mutex_lock(&mutex); fprintf(fout, "Passenger %d returns for another ride at %d millisec.\\n", passenger_id, passenger_time[passenger_id - 1]); pthread_mutex_unlock(&mutex); sem_wait(&queue); sem_wait(&checkin); on_board[on_board_count] = passenger_id; on_board_count++; if (on_board_count == C) sem_post(&boarding); sem_post(&checkin); sem_wait(&riding); sem_post(&unloading); } pthread_exit(0); } void* CarThread() { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < C; j++) { sem_post(&queue); } sem_wait(&boarding); if (car_time < passenger_time[on_board[C - 1] - 1]) car_time = passenger_time[on_board[C - 1] - 1]; pthread_mutex_lock(&mutex); fprintf(fout, "Car departures at %d millisec. Passengers ", car_time); for (j = 0; j < C; j++) fprintf(fout, "%d ", on_board[j]); fprintf(fout, "are in the car.\\n"); pthread_mutex_unlock(&mutex); usleep(T * 1000); car_time += T; for (j = 0; j < C; j++) passenger_time[on_board[j] - 1] = car_time; pthread_mutex_lock(&mutex); fprintf(fout, "Car arrives at %d millisec. Passengers ", car_time); for (j = 0; j < C; j++) fprintf(fout, "%d ", on_board[j]); fprintf(fout, "get off the car.\\n"); pthread_mutex_unlock(&mutex); if (i == N - 1) { ending = 1; for (j = 0; j < n; j++) { sem_post(&queue); sem_post(&checkin); sem_post(&riding); } } else { on_board_count = 0; for (j = 0; j < C; j++) { sem_post(&riding); sem_wait(&unloading); } } } pthread_exit(0); } int main(int argc, char** argv) { n = atoi(argv[1]), C = atoi(argv[2]), T = atoi(argv[3]), N = atoi(argv[4]), out = argv[5]; sem_init(&queue, 0, 0); sem_init(&checkin, 0, 1); sem_init(&boarding, 0, 0); sem_init(&riding, 0, 0); sem_init(&unloading, 0, 0); pthread_mutex_init(&mutex, 0); fout = fopen(out, "w"); fprintf(fout, "%d %d %d %d\\n", n, C, T, N); int id[n]; int i; pthread_create(&car, 0, &CarThread, 0); for (i = 0; i < n; i++) { id[i] = i + 1; pthread_create(&passenger[i], 0, &PassengerThread, (void*)&id[i]); } pthread_join(car, 0); for (i = 0; i < n; i++) pthread_join(passenger[i], 0); fclose(fout); pthread_mutex_destroy(&mutex); sem_destroy(&queue), sem_destroy(&checkin), sem_destroy(&boarding), sem_destroy(&riding), sem_destroy(&unloading); pthread_exit(0); return 0; }
0
#include <pthread.h> extern pthread_mutex_t __sfp_mutex; extern pthread_cond_t __sfp_cond; extern int __sfp_state; int __swalk_sflush() { register FILE *fp, *savefp; register int n, ret, saven; register struct glue *g, *saveg; pthread_mutex_lock(&__sfp_mutex); __sfp_state++; pthread_mutex_unlock(&__sfp_mutex); ret = 0; saven = 0; saveg = 0; savefp = 0; for (g = &__sglue; g != 0; g = g->next) { for (fp = g->iobs, n = g->niobs; --n >= 0; fp++) { if (fp->_flags != 0) { if (fp->_bf._base && (fp->_bf._base - fp->_p)) { if (ftrylockfile(fp)) { if (!saven) { saven = n; saveg = g; savefp = fp; continue; } } else { ret |= __sflush(fp); funlockfile(fp); } } } } } if (savefp) { for (g = saveg; g != 0; g = g->next) { for (fp = savefp, n = saven + 1; --n >= 0; fp++) { if (fp->_flags != 0) { while (fp->_bf._base && (fp->_bf._base - fp->_p)) { flockfile(fp); ret |= __sflush(fp); funlockfile(fp); } } } } } pthread_mutex_lock(&__sfp_mutex); if (! (--__sfp_state)) { pthread_cond_signal(&__sfp_cond); } pthread_mutex_unlock(&__sfp_mutex); return (ret); }
1
#include <pthread.h> int fin_fd; size_t entry_count; int fin_new(char* filename){ mode_t mode=S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH; int fd=open(filename,O_RDWR|O_CREAT|O_EXCL,mode); if (fd==-1){ perror("create fin:"); return -1; } fin_fd=fd; entry_count=0; return fd; } int fin_end(){ lseek(fin_fd,0,0); struct fin_header header; header.entry_count=entry_count; write(fin_fd,&header,sizeof(struct fin_header)); close(fin_fd); printf("file closed,written %d entries\\n",entry_count); return 0; } int fin_app(struct fin_entry* this_entry){ size_t written=write(fin_fd,this_entry,sizeof(struct fin_entry)); fin_flush(); if(written!=sizeof(struct fin_entry)){ printf("error in writing\\n"); return -1; } else { printf("added one entry successfully!\\n"); return 0; } } int fin_load(char* path){ fin_fd=open(path,O_RDONLY); if(fin_fd==-1){ perror("read fin file"); return -1; } struct fin_header header; read(fin_fd,&header,sizeof(struct fin_header)); entry_count=header.entry_count; return 0; } int fin_flush(){ int rval=fsync(fin_fd); if (rval!=0){ perror("fin_flush"); return rval; } else { return 0; } } off_t fin_get_entry(int num){ return sizeof(struct fin_header)+sizeof(struct fin_entry)*num; } off_t fin_get_record(int num,int subno){ return fin_get_entry(num)+2+subno*sizeof(struct fin_record); } int rssi_table_to_fin_record(struct fin_record* dest,struct rssi_table* from){ dest->used=1; memcpy(dest->bssid,from->bssid,6); float calced=0.0; int i; for(i=0;i<10;i++){ calced+=from->rssi[i]; } calced/=10; dest->rssi=calced; return 0; } int cmp_rssi(const void* c1,const void* c2){ struct rssi_table* a1=(struct rssi_table*)c1; struct rssi_table* a2=(struct rssi_table*)c2; if ( get_rssi_raw(a1)>get_rssi_raw(a2) ){ return 1; } else { return -1; } } int table_to_fin_entry(struct fin_entry* dest){ printf("trying to lock table\\n"); pthread_mutex_lock(&table_mutex); printf("sorting...\\n"); qsort(table,MAX_ENTRY,sizeof(struct rssi_table),cmp_rssi); int i; printf("copying data\\n"); for (i=0;i<REC_NUM;i++){ dest->records[i].used=table[i].used; if(dest->records[i].used==0){break;} memcpy(dest->records[i].bssid,table[i].bssid,6); dest->records[i].rssi=get_rssi_index(i); } pthread_mutex_unlock(&table_mutex); printf("fin_entry created successfully\\n"); return 0; } int table_to_file(){ int rval=0; printf("stopping listening...\\n"); getter_stop(); printf("creating entry..\\n"); struct fin_entry thisEntry; thisEntry.number=entry_count++; table_to_fin_entry(&thisEntry); printf("writing to file...\\n"); fin_app(&thisEntry); rval=fin_flush(); if(rval!=0){return -1;} printf("resume listening...\\n"); getter_id=getter_listen(); return 0; } float fin_score(struct fin_entry* src,int index){ float score=0.0; struct fin_entry retrieved; lseek(fin_fd,sizeof(struct fin_header)+index*sizeof(struct fin_entry),0); read(fin_fd,&retrieved,sizeof(struct fin_entry)); int i,j; for(i=0;i<REC_NUM;i++){ for(j=0;j<REC_NUM;j++){ if(retrieved.records[i].used==1){ if(memcmp(retrieved.records[i].bssid,src->records[j].bssid,6)==0){ score+=abs(retrieved.records[i].rssi-src->records[j].rssi); break; } } } score+=10; } return score; } int locate(struct fin_entry* sig){ float* scores=malloc(sizeof(float)*entry_count); int i=0; for(i=0;i<entry_count;i++){ scores[i]=fin_score(sig,i); } float min=scores[0]; int min_index=0; for(i=1;i<entry_count;i++){ if(scores[i]<min){ min_index=i; min=scores[i]; } } return min_index; }
0