text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static void** head = 0; static int listSize = 0; static int listCapa = 5; static pthread_mutex_t lock; void referer_init(){ if(head!= 0) return; pthread_mutex_init(&lock, 0); head = malloc(listCapa * sizeof(void*)); } int referer_add(void* addr){ pthread_mutex_lock(&lock); if(head == 0){ warn("referer not initialized\\n"); exit(1); } if(listSize == listCapa){ listCapa *= 2; head = realloc(head, listCapa * sizeof(void*)); } int i=0; for(;i<listSize; i++){ if(head[i] == 0){ head[i] = addr; break; } } if(i==listSize) head[listSize++] = addr; int ret = i; pthread_mutex_unlock(&lock); return ret; } void* referer_getAddr(int reference){ pthread_mutex_lock(&lock); if(reference>=0 && reference<listSize && head!=0){ void* ret = head[reference]; pthread_mutex_unlock(&lock); return ret; }else{ pthread_mutex_unlock(&lock); return 0; } } void referer_set(int reference, void* addr){ pthread_mutex_lock(&lock); if(reference>=0 && reference<listSize && head!=0){ head[reference] = addr; }else{ warn("referer cannot find address\\n"); } pthread_mutex_unlock(&lock); } void referer_remove(int reference){ pthread_mutex_lock(&lock); if(reference>=0 && reference<listSize && head!=0){ head[reference] = 0; }else{ warn("referer cannot find address\\n"); } pthread_mutex_unlock(&lock); } void referer_cleanup(){ if(head != 0) free(head); head = 0; listSize = 0; listCapa = 5; pthread_mutex_destroy(&lock); }
1
#include <pthread.h> static int valueget; static char nameget; struct elem{ char c; int integer; }; struct buffer{ struct elem content[16]; int readp; int writep; int counter; pthread_mutex_t bufferlocker; pthread_cond_t bufferwait; }; static struct buffer b; void buffer_init(struct buffer b) { b.readp=0; b.writep=0; b.counter=0; pthread_mutexattr_t mymutexattr1; pthread_mutexattr_init(&mymutexattr1); pthread_mutex_init(&(b.bufferlocker), &mymutexattr1); pthread_mutexattr_destroy(&mymutexattr1); pthread_condattr_t mycondattr2; pthread_condattr_init(&mycondattr2); pthread_cond_init(&(b.bufferwait), &mycondattr2); pthread_condattr_destroy(&mycondattr2); } int enqueue(char name, int value) { int fwrp=b.writep; pthread_mutex_lock(&(b.bufferlocker)); while (b.counter>=16) { pthread_cond_wait(&(b.bufferwait), &(b.bufferlocker)); } b.content[fwrp].c=name; b.content[fwrp].integer=value; b.writep++; if (b.writep>15) { b.writep=0; } b.counter++; printf("enqueue %c %d\\n",name,value); fflush(stdout); pthread_cond_broadcast(&(b.bufferwait)); pthread_mutex_unlock(&(b.bufferlocker)); return 0; } void dequeue(void) { int frdp=b.readp; pthread_mutex_lock(&(b.bufferlocker)); while (b.counter<=0) { pthread_cond_wait(&(b.bufferwait), &(b.bufferlocker)); } nameget=b.content[frdp].c; valueget=b.content[frdp].integer; b.readp++; b.counter--; if (b.readp>15) { b.readp=0; } printf("dequeue %c %d\\n",nameget,valueget); fflush(stdout); pthread_cond_broadcast(&(b.bufferwait)); pthread_mutex_unlock(&(b.bufferlocker)); } int comsumerth(void){ int i=0; char p='p'; for (i=0;i<1000;i++) { dequeue(); } return 0; } int producerth(void){ int i=0; char p='p'; for (i=0; i<1000; i++) { enqueue(p, i); fflush(stdout); } return 0; } int main() { pthread_t thread1, thread2, main_id; main_id=pthread_self(); buffer_init(b); pthread_create( &thread1, 0, &producerth, 0); pthread_create( &thread2, 0, &comsumerth, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); }
0
#include <pthread.h> int buffer[100]; int nextp, nextc; int count=0; int ProFin=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void printfunction(void * ptr) { int count = *(int *) ptr; if (count==0) { printf("All items produced are consumed by the consumer \\n"); } else { for (int i=0; i<=count; i=i+1) { printf("%d, \\t",buffer[i]); } printf("\\n"); } } void *producer(void *ptr) { int item, flag=0; int in = *(int *) ptr; do { pthread_mutex_lock(&mutex); item = (rand()%7)%10; flag=flag+1; nextp=item; buffer[in]=nextp; in=((in+1)%100); count=count+1; pthread_mutex_unlock(&mutex); } while (flag<=1000); ProFin=1; pthread_exit(0); } void *consumer(void *ptr) { int item, flag=1000; int out = *(int *) ptr; do { pthread_mutex_lock(&mutex); while (count >0) { nextc = buffer[out]; out=(out+1)%100; printf("\\t\\tCount = %d in consumer at Iteration = %d\\n", count, flag); count = count-1; flag=flag-1; } if (count <= 0 && ProFin == 0) { printf("consumer made to wait...faster than producer.\\n"); } pthread_mutex_unlock(&mutex); } while (ProFin == 0 || count > 0); pthread_exit(0); } int main(void) { int in=0, out=0; pthread_t pro, con; int rc1; int rc2; rc1 = pthread_create(&pro, 0, producer, &count); rc2 = pthread_create(&con, 0, consumer, &count); if (rc1) { printf("ERROR; return code from pthread_create() is %d\\n", rc1); exit(-1); } if (rc2) { printf("ERROR; return code from pthread_create() is %d\\n", rc2); exit(-1); } pthread_join(pro, 0); pthread_join(con, 0); printfunction(&count); }
1
#include <pthread.h> struct _int_channel{ int queue[100]; int front; int back; int MAX_SIZE; int size; bool poisoned; pthread_mutex_t lock; pthread_cond_t write_ready; pthread_cond_t read_ready; }; int _init_int_channel(struct _int_channel *channel){ if(pthread_mutex_init(&channel->lock, 0) != 0){ printf("Mutex init failed"); return 1; } if(pthread_cond_init(&channel->write_ready, 0) + pthread_cond_init(&channel->read_ready, 0 ) != 0){ printf("Cond init failed"); return 1; } channel->MAX_SIZE = 100; channel->front = 0; channel->back = 0; channel->poisoned = 0; return 0; } void _enqueue_int(int element, struct _int_channel *channel){ pthread_mutex_lock(&channel->lock); while(channel->size >= channel->MAX_SIZE) pthread_cond_wait(&channel->write_ready, &channel->lock); assert(channel->size < channel->MAX_SIZE); assert(!(channel->poisoned)); channel->queue[channel->back] = element; channel->back = (channel->back + 1) % channel->MAX_SIZE; channel->size++; pthread_cond_signal(&channel->read_ready); pthread_mutex_unlock(&channel->lock); } int _dequeue_int(struct _int_channel *channel){ pthread_mutex_lock(&channel->lock); assert(channel->size != 0); int result = channel->queue[channel->front]; channel->front = (channel->front + 1) % channel->MAX_SIZE; channel->size--; pthread_cond_signal(&channel->write_ready); pthread_mutex_unlock(&channel->lock); return result; } void _poison(struct _int_channel *channel) { pthread_mutex_lock(&channel->lock); channel->poisoned = 1; pthread_cond_signal(&channel->read_ready); pthread_mutex_unlock(&channel->lock); } bool _wait_for_more(struct _int_channel *channel) { pthread_mutex_lock(&channel->lock); while(channel->size == 0) { if(channel->poisoned){ pthread_mutex_unlock(&channel->lock); return 0; } else { pthread_cond_wait(&channel->read_ready, &channel->lock); } } pthread_mutex_unlock(&channel->lock); return 1; } struct _pthread_node{ pthread_t thread; struct _pthread_node *next; }; struct _pthread_node* _head = 0; pthread_mutex_t _thread_list_lock; pthread_t* _make_pthread_t(){ pthread_mutex_lock(&_thread_list_lock); struct _pthread_node *new_pthread = (struct _pthread_node *) malloc(sizeof(struct _pthread_node)); new_pthread->next = _head; _head = new_pthread; pthread_mutex_unlock(&_thread_list_lock); return &(new_pthread->thread); } void _wait_for_finish(){ struct _pthread_node* curr = _head; while(curr){ pthread_join(curr->thread, 0); curr = curr->next; } } struct _tokenGen_args { struct _int_channel *ochan; int input; }; void *tokenGen(void *_args) { int input = ((struct _tokenGen_args *) _args)->input; struct _int_channel *ochan = ((struct _tokenGen_args *) _args)->ochan; _enqueue_int(input, ochan); _poison(ochan); return 0; } struct _printer_args { struct _int_channel *chan; }; void *printer(void *_args) { struct _int_channel *chan = ((struct _printer_args *) _args)->chan; while (_wait_for_more(chan)) { printf("%d\\n", _dequeue_int(chan)); } return 0; } struct _interleaver_args { struct _int_channel *chan1; struct _int_channel *chan2; struct _int_channel *ochan; }; void *interleaver(void *_args) { struct _int_channel *chan1 = ((struct _interleaver_args *) _args)->chan1; struct _int_channel *chan2 = ((struct _interleaver_args *) _args)->chan2; struct _int_channel *ochan = ((struct _interleaver_args *) _args)->ochan; while(_wait_for_more(chan1) || _wait_for_more(chan2)) { if (_wait_for_more(chan1)) _enqueue_int(_dequeue_int(chan1), ochan); if (_wait_for_more(chan2)) _enqueue_int(_dequeue_int(chan2), ochan); } _poison(ochan); return 0; } int main() { pthread_mutex_init(&_thread_list_lock, 0); struct _int_channel *chan1 = (struct _int_channel *) malloc(sizeof(struct _int_channel)); _init_int_channel(chan1); struct _int_channel *chan2 = (struct _int_channel *) malloc(sizeof(struct _int_channel)); _init_int_channel(chan2); struct _int_channel *ochan = (struct _int_channel *) malloc(sizeof(struct _int_channel)); _init_int_channel(ochan); int int1 = 1; int int2 = 2; { pthread_t* _t = _make_pthread_t(); struct _tokenGen_args _args = { chan1, int1, }; pthread_create(_t, 0, tokenGen, (void *) &_args); }; { pthread_t* _t = _make_pthread_t(); struct _tokenGen_args _args = { chan2, int2, }; pthread_create(_t, 0, tokenGen, (void *) &_args); }; { pthread_t* _t = _make_pthread_t(); struct _interleaver_args _args = { chan1, chan2, ochan, }; pthread_create(_t, 0, interleaver, (void *) &_args); }; { pthread_t* _t = _make_pthread_t(); struct _printer_args _args = { ochan, }; pthread_create(_t, 0, printer, (void *) &_args); }; _wait_for_finish(); return 0; }
0
#include <pthread.h> int x, y; } my_state; my_state state; sigset_t set; pthread_mutex_t m=PTHREAD_MUTEX_INITIALIZER; void display(my_state *ptr) { printf("\\nx = %1d\\n", ptr->x); usleep(1000); printf("y = %1d\\n", ptr->y); } void *monitor(void *arg) { int sig=0; for (;;) { sigwait(&set, &sig); pthread_mutex_lock(&m); display(&state); pthread_mutex_unlock(&m); } return 0; } void update_state(my_state *ptr) { ptr->x++; usleep(100000); ptr->y++; } void compute_more() { usleep(100000); } void long_running_proc() { int i=0; for (i=0; i < 100; i++) { pthread_mutex_lock(&m); update_state(&state); pthread_mutex_unlock(&m); compute_more(); } } int main(int argc, char *argv[]) { pthread_t thr; state.x = state.y = 0; sigemptyset(&set); sigaddset(&set, SIGINT); sigprocmask(SIG_BLOCK, &set, 0); pthread_create(&thr, 0, monitor, 0); long_running_proc(); return 0; }
1
#include <pthread.h> struct Buff_List *next; char word[20]; int count; }Buff_List; char word[20]; }S_Buff; Buff_List *head; int i; FILE *fp; int start; int end; int buff_count; int n; int b; }threadPara; char S_Buffer[10][100][20]; pthread_mutex_t mutex[10]; void *mapreader(void *para); void *mapadder(void *para); int StringCompare(const void *s1, const void *s2){ Buff_List *str1 = ( Buff_List *)s1; Buff_List *str2 = ( Buff_List *)s2; return (str2->count - str1->count); } int main(int argc, char *argv[]){ struct timeval start_time; struct timeval finish_time; gettimeofday(&start_time,0); int n = atoi(argv[2]); int b = atoi(argv[3]); int p=0; pthread_t *thread_a=(pthread_t*)malloc(n*sizeof(pthread_t)); pthread_t *thread_b=(pthread_t*)malloc(n*sizeof(pthread_t)); threadPara *para=malloc(n*sizeof(threadPara)); FILE *fp = fopen(argv[1], "r"); if (fp == 0) { printf("File Open Fail!\\n"); } fseek(fp,0L,2); int FileSize = ftell(fp); for (p=0;p<n;p++){ FILE *fp = fopen(argv[1], "r"); para[p].fp = fp; para[p].i=p; para[p].start = p*FileSize/n; para[p].end = para[p].start+FileSize/n; para[p].head = (Buff_List*)malloc(sizeof(Buff_List)); para[p].n = n; para[p].b = b; pthread_mutex_init(&mutex[p],0); pthread_create(&thread_a[p],0,(void*)mapreader,&para[p]); pthread_create(&thread_b[p],0,(void*)mapadder,&para[p]); } for (p=0;p<n;p++){ pthread_join(thread_a[p],0); pthread_join(thread_b[p],0); pthread_mutex_destroy(&mutex[p]); } Buff_List *List = (Buff_List*)calloc((1000),sizeof(Buff_List)); int i; int Var = 0; for (i=0; i<n; i++) { Buff_List *loop = para[i].head; while (loop!=0 && loop->next != 0) { int distinct = 1; int q; for(q=0;q<Var;q++){ if (strcmp(List[q].word, loop->word)==0) { distinct = 0; List[q].count+=loop->count; } } if (distinct==1) { strcpy(List[Var].word, loop->word); List[Var].count = loop->count; Var++; } loop=loop->next; } } qsort(List,Var,sizeof(Buff_List),StringCompare); int word_count = 0; FILE *file = fopen("output.txt","w"); for (i=0; i<Var; i++) { word_count+= List[i].count; fprintf(file,"<%s> appear %d times.\\n", List[i].word,List[i].count); } fprintf(file,"%d total words.\\n",word_count); fprintf(file,"%d unique words.\\n", Var); fclose(file); fclose(fp); gettimeofday(&finish_time,0); double duration = 0; duration =((finish_time.tv_sec*1000000 + finish_time.tv_usec) - (start_time.tv_sec*1000000 + start_time.tv_usec))/1000000.0; printf("Running Time: %f\\n",duration); return 0; } void *mapreader(void *para){ threadPara *pm; pm =(struct threadPara*) para; char tmp[20]; int i = pm->i; int n = pm->n; int b = pm->b; fseek(pm->fp,pm->start,0); while ((ftell(pm->fp) < pm->end) && (ftell(pm->fp)!= EOF)) { fscanf(pm->fp,"%s",tmp); int l=0; int s=0; char str[20]; while (tmp[l]) { if(!ispunct(tmp[l])){ if(tmp[l] >= 'A' && tmp[l] <= 'Z'){ tmp[l]+=32; } str[s] = tmp[l]; s++; } l++; } str[s]='\\0'; while(pm->buff_count >= b); pthread_mutex_lock(&mutex[pm->i]); strcpy(S_Buffer[pm->i][pm->buff_count],str); pm->buff_count++; pthread_mutex_unlock(&mutex[pm->i]); } printf("Reader %d success!\\n",pm->i); } void *mapadder(void *para) { threadPara *pm= para; int n = pm->n; int b = pm->b; while ((ftell(pm->fp) < pm->end) && (ftell(pm->fp)!= EOF) ||( pm->buff_count)) { while (pm->buff_count == 0); pthread_mutex_lock(&mutex[pm->i]); int distinct = 1; Buff_List *temp = pm->head; if (temp == 0) { strcpy(temp->word,S_Buffer[pm->i][pm->buff_count - 1]); pm->buff_count --; temp->count = 1; temp->next = 0; distinct = 1; } else{ while (temp!=0) { if (strcmp(temp->word,S_Buffer[pm->i][pm->buff_count-1])==0) { pm->buff_count--; temp->count++; distinct = 0; break; } temp = temp->next; } if (distinct==1) { Buff_List *new=(Buff_List*)malloc(sizeof(Buff_List)); strcpy(new->word,S_Buffer[pm->i][pm->buff_count-1]); pm->buff_count--; new->count=1; new->next = pm->head; pm->head = new; } } pthread_mutex_unlock(&mutex[pm->i]); } printf("Adder %d success!\\n",pm->i); }
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) { printf("watch_count(): thread %ld Meditating on condition variable.\\n", my_id); 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> pthread_mutex_t prod_cons_mutex; pthread_cond_t prod_cons_cond; int cantProdCons = 1, buffer = 0; int generateItem(); void *producir(void *arg) { printf("Estoy en el hilo productor..\\n"); while ( 1 ) { sleep(3); if ( buffer == 100 ){ printf("Durmiendo de producir..\\n"); }else{ printf("Produciendo..\\n"); pthread_mutex_lock(&prod_cons_mutex); buffer++; pthread_mutex_unlock(&prod_cons_mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit((void*) 0); } void *consumir(void *arg) { printf("Estoy en el hilo consumidor..\\n"); while ( 1 ) { sleep(3); if ( buffer == 0 ){ printf("Durmiendo de consumir..\\n"); }else{ printf("Consumiendo..\\n"); pthread_mutex_lock(&prod_cons_mutex); buffer--; pthread_mutex_unlock(&prod_cons_mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit((void*) 0); } int main (int argc, char *argv[]) { if (argv[1]){ cantProdCons = atoi(argv[1]); } pthread_t productor, consumidor; pthread_mutex_init(&prod_cons_mutex, 0); int rp, rc; rp = pthread_create( &productor, 0, producir, 0 ); if ( rp ) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } rc = pthread_create( &consumidor, 0, consumir, 0 ); if ( rc ) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutexA; pthread_mutex_t mutexB; void* locker1(void* args) { pthread_mutex_lock(&mutexA); pthread_mutex_lock(&mutexB); pthread_mutex_unlock(&mutexB); pthread_mutex_unlock(&mutexA); return 0; } void* locker2(void* args) { pthread_mutex_lock(&mutexB); pthread_mutex_lock(&mutexA); pthread_mutex_unlock(&mutexA); pthread_mutex_unlock(&mutexB); return 0; } void* t1(void* args) { pthread_t otherHandles[(2)]; size_t i; for(i=0; i < (2); ++i) { pthread_create(&otherHandles[i], 0, locker2, 0); } for(i=0; i < (2); ++i) { pthread_join(otherHandles[i], 0); } return 0; } int main(int argc, char** argv) { pthread_mutex_init(&mutexA, 0); pthread_mutex_init(&mutexB, 0); pthread_t handle; pthread_create(&handle, 0, t1, 0); pthread_t handles[(1)]; size_t i; for(i=0; i < (1); ++i) { pthread_create(&handles[i], 0, locker1, 0); } for(i=0; i < (1); ++i) { pthread_join(handles[i], 0); } pthread_join(handle, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int data = 0; void *thread1(void *arg) { pthread_mutex_lock(&mutex); data++; printf ("t1: data %d\\n", data); pthread_mutex_unlock(&mutex); return 0; } void *thread2(void *arg) { pthread_mutex_lock(&mutex); data+=2; printf ("t2: data %d\\n", data); pthread_mutex_unlock(&mutex); return 0; } void *thread3(void *arg) { pthread_mutex_lock(&mutex); printf ("t3: data %d\\n", data); __VERIFIER_assert (0 <= data); __VERIFIER_assert (data <= 10 + 3); pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_mutex_init(&mutex, 0); pthread_t t1, t2, t3; data = __VERIFIER_nondet_int (0, 10); printf ("m: MIN %d MAX %d data %d\\n", 0, 10, data); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> struct list task_list = LIST_INITIALIZER(task_list); struct primes_list{ struct list_head list; int data; }; void log_info(const char* x){ printf("%s",x); } pthread_mutex_t task_list_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t list_av = PTHREAD_COND_INITIALIZER; int task_list_len = 0; void* thread_func_one(void *arg){ struct list_elem *e; while(1){ pthread_mutex_lock(&task_list_mutex); if(task_list_len<=0){ if(0==pthread_cond_wait(&list_av, &task_list_mutex)){ pthread_mutex_unlock(&task_list_mutex); continue; }else{ log_info("worker_thread_func:"); } } e = list_pop_front(&task_list); task_list_len--; pthread_mutex_unlock(&task_list_mutex); e_print(e); } } void thread_func_two(void *arg){ while(1){ pthread_mutex_lock(&task_list_mutex); list_push_back(&task_list, ""); pthread_mutex_unlock(&task_list_mutex); } } int main(){ pthread_t thread_one, thread_two; if(0 != pthread_create(&thread_one, 0, thread_func_one, 0)) printf("pthread created failed"); if(0 != pthread_create(&thread_two, 0, thread_func_two, 0)) printf("pthread created failed"); pthread_join(thread_one,0); pthread_join(thread_two,0); }
1
#include <pthread.h> { int MaxPost; pthread_cond_t codaA; pthread_cond_t codaB; }park_t; void *asd; park_t park; int app=0; { pthread_t macchina; int id; int Ntentativi; }Car; Car ntid[100]; pthread_mutex_t accept_car = PTHREAD_MUTEX_INITIALIZER; void *ParkA(int *id) { int tent=0; while(tent<ntid[(*id)].Ntentativi) { pthread_mutex_lock(&accept_car); while (park.MaxPost==0) { fprintf(stderr,"MAcchina %d in coda; Numero tentativo \\n: %d\\n",ntid[*id].id,ntid[*id].Ntentativi); pthread_cond_wait(&park.codaA,&accept_car); } park.MaxPost--; printf("%d\\n",park.MaxPost); pthread_mutex_unlock(&accept_car); sleep(2); pthread_mutex_lock(&accept_car); park.MaxPost++; pthread_cond_signal(&park.codaA); pthread_cond_signal(&park.codaB); pthread_mutex_unlock(&accept_car); tent++; } pthread_exit(asd); } void *ParkB(int *id) { int tent=0; while (tent<ntid[*id].Ntentativi) { pthread_mutex_lock(&accept_car); while (park.MaxPost==0) { pthread_cond_wait(&park.codaB,&accept_car); } park.MaxPost--; printf("%d\\n",park.MaxPost); pthread_mutex_unlock(&accept_car); sleep(1); pthread_mutex_lock(&accept_car); park.MaxPost++; pthread_cond_signal(&park.codaA); pthread_cond_signal(&park.codaB); pthread_mutex_unlock(&accept_car); tent++; } pthread_exit(asd); } int main() { fprintf(stderr,"/****Parcheggio Aperto*****/\\n"); park.MaxPost=10; park.codaA=(pthread_cond_t)PTHREAD_COND_INITIALIZER; park.codaB=(pthread_cond_t)PTHREAD_COND_INITIALIZER; int ingresso; srand(time(0)); int index=0; while (index<100) { ingresso= rand()%2+1; ntid[index].id=index+1; ntid[index].Ntentativi=5; if(ingresso==1) { pthread_create(&(ntid[index].macchina),0,(void*)ParkA,&ntid[index].id); } if(ingresso==2) { pthread_create(&(ntid[index].macchina),0,(void*)ParkB,&ntid[index].id); } index++; } for (index=0; index < 100; index++) pthread_join((ntid[index].macchina),asd); if(park.MaxPost!=10) fprintf(stderr,"Errore, posteggio non vuoto....!!! Impossibile chiudere il parcheggio!!Auto nel posteggio : %d\\n",30-park.MaxPost); else fprintf(stderr,"/****Parcheggio Chiuso Con Successo*****/\\n"); return 0; }
0
#include <pthread.h> const int RMAX = 1000; int thread_count; int* a; int n; int phase; int counter; pthread_mutex_t mutex; pthread_cond_t cond_var; void Usage(char* prog_name); void Get_args(int argc, char* argv[], int* n_p, char* g_i_p,int*thread_count); void Generate_list(int a[], int n); void Print_list(int a[], int n, char* title); void Read_list(int a[], int n); void* Odd_even_sort(void* rank); int main(int argc, char* argv[]) { char g_i; int i; pthread_t* thread_handles = 0; double beg,end; Get_args(argc, argv, &n, &g_i,&thread_count); a = (int*) malloc(n*sizeof(int)); if (g_i == 'g') { Generate_list(a, n); Print_list(a, n, "Before sort"); } else { Read_list(a, n); } phase = 0; counter=0; pthread_cond_init(&cond_var,0); pthread_mutex_init(&mutex,0); thread_handles = (pthread_t*)malloc(thread_count*sizeof(pthread_t)); beg = GetTickCount(); for(i=0;i<thread_count;i++) pthread_create(&thread_handles[i],0,Odd_even_sort,(void*)i); for(i=0;i<thread_count;i++) pthread_join(thread_handles[i],0); end = GetTickCount(); pthread_cond_destroy(&cond_var); pthread_mutex_destroy(&mutex); Print_list(a, n, "After sort"); printf("\\nTime: %fs\\n",(end-beg)/1000); free(a); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <n> <g|i> <c>\\n", prog_name); fprintf(stderr, " n: number of elements in list\\n"); fprintf(stderr, " 'g': generate list using a random number generator\\n"); fprintf(stderr, " 'i': user input list\\n"); fprintf(stderr, " 'c': number of threads\\n"); } void Get_args(int argc, char* argv[], int* n_p, char* g_i_p,int*thread_count) { if (argc != 4 ) { Usage(argv[0]); exit(0); } *n_p = atoi(argv[1]); *g_i_p = argv[2][0]; *thread_count = strtol(argv[3],0,10); if (*n_p <= 0 || (*g_i_p != 'g' && *g_i_p != 'i') ) { Usage(argv[0]); exit(0); } } void Generate_list(int a[], int n) { int i; srand(0); for (i = 0; i < n; i++) a[i] = rand() % RMAX; } void Print_list(int a[], int n, char* title) { int i; printf("%s:\\n", title); for (i = 0; i < n; i++) printf("%d ", a[i]); printf("\\n\\n"); } void Read_list(int a[], int n) { int i; printf("Please enter the elements of the list\\n"); for (i = 0; i < n; i++) scanf("%d", &a[i]); } void* Odd_even_sort(void* rank) { long my_rank = (long)rank; int local_a = my_rank*n/thread_count; int local_b = local_a+n/thread_count; int i, temp; if(local_a%2==0) local_a++; while(phase<n) { i = local_a; if(my_rank==thread_count-1) if(phase%2==0) local_b=n; else local_b=n-1; if (phase % 2 == 0) { if(local_b<n&&local_b%2) local_b++; for (; i < local_b; i += 2) if (a[i-1] > a[i]) { temp = a[i]; a[i] = a[i-1]; a[i-1] = temp; } } else { if(local_b<n-1&&local_b%2) local_b++; for (; i < local_b; i += 2) if (a[i] > a[i+1]) { temp = a[i]; a[i] = a[i+1]; a[i+1] = temp; } } pthread_mutex_lock(&mutex); counter++; if(counter == thread_count){ counter = 0; phase++; pthread_cond_broadcast(&cond_var); }else{ while(pthread_cond_wait(&cond_var,&mutex)!=0); } pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> int sigwaitinfo (const sigset_t *restrict set, siginfo_t *restrict info) { pthread_mutex_lock (&sig_lock); struct signal_state *ss = &_pthread_self ()->ss; pthread_mutex_lock (&ss->lock); if ((process_pending & *set) || (ss->pending & *set)) { bool local = 1; sigset_t extant = process_pending & *set; if (! extant) { local = 0; extant = ss->pending & *set; } assert (extant); int signo = vg_msb64 (extant); if (info) { if (local) *info = ss->info[signo - 1]; else *info = process_pending_info[signo - 1]; info->si_signo = signo; } sigdelset (&process_pending, signo); sigdelset (&ss->pending, signo); pthread_mutex_unlock (&ss->lock); pthread_mutex_unlock (&sig_lock); return 0; } siginfo_t i = sigwaiter_block (ss, set); assert (i.si_signo); assert ((sigmask (i.si_signo) & *set)); if (info) *info = i; return 0; }
0
#include <pthread.h> void * set_dynamixel(void * var){ while(1){ float dyna1_speed = -999.9f; float dyna2_speed = -999.9f; float dyna1_pose = -999.9f; float dyna2_pose = -999.9f; switch(commandGripper){ case 0: pthread_mutex_lock(&dynamixel_mutex); printf("Change to Joint Mode - Go to default position 0\\n"); bus.servo[0].cmd_mode = JOINT; bus.servo[0].cmd_flag = MODE; bus.servo[1].cmd_mode = JOINT; bus.servo[1].cmd_flag = MODE; pthread_mutex_unlock(&dynamixel_mutex); commandGripper = 999; break; case 1: pthread_mutex_lock(&dynamixel_mutex); printf("Claw open position. Moving to 0 degrees\\n"); bus.servo[0].cmd_angle = 0.0; bus.servo[0].cmd_speed = 0.5; bus.servo[1].cmd_angle = 0.0; bus.servo[1].cmd_speed = 0.5; bus.servo[0].cmd_flag = CMD; bus.servo[1].cmd_flag = CMD; pthread_mutex_unlock(&dynamixel_mutex); commandGripper = 999; break; case 2: pthread_mutex_lock(&dynamixel_mutex); printf("Change to Wheel Mode - Stop the Servo\\n"); bus.servo[0].cmd_mode = WHEEL; bus.servo[0].cmd_flag = MODE; bus.servo[1].cmd_mode= WHEEL; bus.servo[1].cmd_flag = MODE; pthread_mutex_unlock(&dynamixel_mutex); commandGripper = 999; break; case 3: pthread_mutex_lock(&dynamixel_mutex); printf("Closing claw. Command -0.3 speed\\n"); bus.servo[0].cmd_speed = -0.3; bus.servo[0].cmd_torque = 1.0; bus.servo[1].cmd_speed = -0.3; bus.servo[1].cmd_torque = 1.0; bus.servo[0].cmd_flag = CMD; bus.servo[1].cmd_flag = CMD; pthread_mutex_unlock(&dynamixel_mutex); commandGripper = 999; break; case 4: pthread_mutex_lock(&dynamixel_mutex); printf("Request Status:\\n"); bus.servo[0].cmd_flag = STATUS; bus.servo[1].cmd_flag = STATUS; pthread_mutex_unlock(&dynamixel_mutex); float dyna1_speed = Dynam_VelFB(&bus.servo[0]); float dyna2_speed = Dynam_VelFB(&bus.servo[1]); float dyna1_pose = Dynam_PosFB(&(bus.servo[0])); float dyna2_pose = Dynam_PosFB(&(bus.servo[1])); if(dyna1_speed > 0.01 && dyna2_speed > 0.01){ printf("Motor Moving - Vel = (%f,%f)\\n",dyna1_speed,dyna2_speed); dynam_perch_signal = 0; } else if(dyna1_pose > 65 && dyna2_pose >65){ dynam_perch_signal = 1; printf("Motor Grasped - Pose = (%f,%f)\\n",dyna1_pose,dyna2_pose); } else{ printf("Motor Missed - Pose = (%f,%f)\\n",dyna1_pose,dyna2_pose); dynam_perch_signal = -1; } printf("\\nServo 1 Angle: %f \\n",Dynam_PosFB(&(bus.servo[0]))); printf("\\nServo 2 Angle: %f \\n",Dynam_PosFB(&(bus.servo[1]))); commandGripper = 999; break; } usleep(100000); fflush(stdout); } return 0; }
1
#include <pthread.h> void *Producer(void *); void *Consumer(void *); sem_t empty; sem_t full; pthread_mutex_t mutex; int g_data[10]; int g_idx; int main(void) { pthread_t pid, cid; sem_init(&empty, 0, 10); sem_init(&full, 0, 0); pthread_mutex_init(&mutex,0); printf("main started\\n"); pthread_create(&pid, 0, Producer, 0); pthread_create(&cid, 0, Consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); printf("main done\\n"); return 0; } void *Producer(void *arg) { int i=0, j; while(i < 200) { usleep(rand()%100000); sem_wait(&empty); pthread_mutex_lock(&mutex); g_data[g_idx] = 1; g_idx++; j=0; printf("(Producer, Buffer usage is %d): ", g_idx); while(j < g_idx) { j++; printf("="); } printf("\\n"); pthread_mutex_unlock(&mutex); sem_post(&full); i++; } return 0; } void *Consumer(void *arg) { int i=0, j; while(i < 200) { usleep(rand()%100000); sem_wait(&full); pthread_mutex_lock(&mutex); g_data[g_idx-1]=0; g_idx--; j=0; printf("(Consumer, Buffer usage is %d): ", g_idx); while(j < g_idx) { j++; printf("="); } printf("\\n"); pthread_mutex_unlock(&mutex); sem_post(&empty); i++; } return 0; }
0
#include <pthread.h> pthread_mutex_t lock,agent,tobs,paps,mats;int i; void * age() {while(1) { pthread_mutex_lock(&lock); i=rand()%3; if(i==0) {printf("Agent puts tobacco on the table\\n"); printf("Agent puts paper on the table\\n"); sleep(1); pthread_mutex_unlock(&mats); } else if(i==1) {printf("Agent puts tobacco on the table\\n"); printf("Agent puts match on the table\\n"); sleep(1); pthread_mutex_unlock(&paps); } else{ printf("Agent puts paper on the table\\n"); printf("Agent puts match on the table\\n"); sleep(1); pthread_mutex_unlock(&tobs); } pthread_mutex_unlock(&lock); pthread_mutex_lock(&agent); } } void * tob() {while(1) {pthread_mutex_lock(&tobs); pthread_mutex_lock(&lock); printf("tobacco smoker picks up match\\n"); printf("tobacco smoker picks up paper\\n"); sleep(1); pthread_mutex_unlock(&agent); pthread_mutex_unlock(&lock); printf("tobacco smoker starts smoking\\n tobacco smoker ends smoking\\n"); } } void * mat() {while(1) {pthread_mutex_lock(&mats); pthread_mutex_lock(&lock); printf("match smoker picks up tobacco\\n"); printf("match smoker picks up paper\\n"); sleep(1); pthread_mutex_unlock(&agent); pthread_mutex_unlock(&lock); printf("match smoker starts smoking\\n match smoker ends smoking\\n"); } } void * pap() {while(1) {pthread_mutex_lock(&paps); pthread_mutex_lock(&lock); printf("paper smoker picks up tobacco\\n"); printf("paper smoker picks up match\\n"); sleep(1); pthread_mutex_unlock(&agent); pthread_mutex_unlock(&lock); printf("paper smoker starts smoking\\n paper smoker ends smoking\\n"); } } void main() {pthread_t tobacco,match,paper,agen; pthread_mutex_init(&lock,0); pthread_mutex_init(&mats,0); pthread_mutex_init(&paps,0); pthread_mutex_init(&tobs,0); pthread_mutex_init(&agent,0); pthread_mutex_lock(&mats); pthread_mutex_lock(&paps); pthread_mutex_lock(&tobs); pthread_mutex_lock(&agent); pthread_create(&agen,0,age,0); pthread_create(&tobacco,0,tob,0); pthread_create(&match,0,mat,0); pthread_create(&paper,0,pap,0); pthread_join(agen,0); pthread_join(tobacco,0); pthread_join(match,0); pthread_join(paper,0); }
1
#include <pthread.h> int g_itemnum; struct { pthread_mutex_t mutex; int buff[(100000)]; int nindex; int nvalue; } shared = { PTHREAD_MUTEX_INITIALIZER }; void* producer(void*); void* consumer(void*); int main(int argc, char **argv) { int i; int threadnum, threadcount[(10)]; pthread_t tid_producer[(10)], tid_consumer; if (3 != argc) { printf("usage: %s <item_num> <thread_num>\\n", argv[0]); } g_itemnum = ((atoi(argv[1])) > ((100000)) ? ((100000)) : (atoi(argv[1]))); threadnum = ((atoi(argv[2])) > ((10)) ? ((10)) : (atoi(argv[2]))); printf("item = %d, thread = %d\\n", g_itemnum, threadnum); pthread_setconcurrency(threadnum + 1); for (i = 0; i < threadnum; ++i) { threadcount[i] = 0; if (0 != pthread_create(&tid_producer[i], 0, producer, (void*)&threadcount[i])) { printf("pthread_create error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] created, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } if (0 != pthread_create(&tid_consumer, 0, consumer, 0)) { printf("pthread_create error consumer\\n"); } printf("consumer: thread[%lu] created\\n", tid_consumer); for (i = 0; i < threadnum; ++i) { if (0 != pthread_join(tid_producer[i], 0)) { printf("pthread_join error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] done, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } if (0 != pthread_join(tid_consumer, 0)) { printf("pthread_join error consumer\\n"); } printf("consumer: thread[%lu] done\\n", tid_consumer); exit(0); } void* producer(void *arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nindex >= g_itemnum) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[shared.nindex] = shared.nvalue; shared.nindex++; shared.nvalue++; pthread_mutex_unlock(&shared.mutex); *((int*)arg) += 1; } return 0; } void* consumer(void *arg) { int i; for (i = 0; i < g_itemnum; ++i) { for (;;) { pthread_mutex_lock(&shared.mutex); if (i < shared.nindex) { pthread_mutex_unlock(&shared.mutex); return 0; } pthread_mutex_unlock(&shared.mutex); } if (shared.buff[i] != i) { printf("error: buff[%d] = %d\\n", i, shared.buff[i]); } } return 0; }
0
#include <pthread.h> struct sigaction my_sig; sem_t sem1; sem_t sem2; pthread_mutex_t rsrcA; FILE *file_ptr; pthread_t tid_2; pthread_t tid_3; size_t words; size_t lines; size_t characters; }file_data; file_data statistics; void my_handler(int signum) { printf("AES\\n"); printf("Handler id is %ld\\n",pthread_self()); if (signum == SIGUSR1) { printf("Received SIGUSR1!\\n"); sem_post(&sem1); } if (signum == SIGUSR2) { printf("Received SIGUSR2!\\n"); sem_post(&sem2); } if(signum == SIGTERM) { printf("Received SIGTERM!\\n"); if(file_ptr != 0) fclose(file_ptr); pthread_kill(tid_2, SIGTERM); pthread_kill(tid_3, SIGTERM); pthread_mutex_destroy(&rsrcA); sem_destroy(&sem1); sem_destroy(&sem2); printf("Exited Normally \\n"); exit(0); } } void *thread2_fn(void *threadid) { FILE *t2_fptr; char c; printf("Thread2 waiting for semaphore 1\\n"); sem_wait(&sem1); printf("Thread2 got semaphore 1\\n"); printf("Thread2 trying to get mutex lock\\n"); pthread_mutex_lock(&rsrcA); printf("Thread2 got mutex lock\\n"); t2_fptr = fopen("multithread", "r"); printf("Data processing\\n"); if (t2_fptr) { while ((c=getc(t2_fptr)) != EOF) { if (c!= ' ' && c!= '\\n') { statistics.characters++; } if (c == ' ' || c == '\\n') { statistics.words++; } if (c == '\\n') { statistics.lines++; } } if(statistics.characters>0) statistics.lines++; statistics.words++; } else { printf("Failed to open the file\\n"); } fclose(t2_fptr); printf("Thread2 releasing mutex lock\\n"); pthread_mutex_unlock(&rsrcA); pthread_exit(0); } void *thread3_fn(void *threadid) { printf("Thread3 waiting for semaphore 2\\n"); sem_wait(&sem2); printf("Thread3 got semaphore 2\\n"); printf("Thread3 trying to get mutex lock\\n"); pthread_mutex_lock(&rsrcA); printf("Thread3 got mutex lock\\n"); printf("Lines : %ld \\n", statistics.lines); printf("Words : %ld \\n", statistics.words); printf("Characters : %ld \\n", statistics.characters); printf("Thread3 releasing mutex lock\\n"); pthread_mutex_unlock(&rsrcA); pthread_exit(0); } int main() { int rc; size_t i = 0; char str[200]; pthread_attr_t t2_attr; pthread_attr_t t3_attr; pthread_attr_init(&t2_attr); pthread_attr_init(&t3_attr); pthread_mutex_init(&rsrcA, 0); sem_init(&sem1, 0, 0); sem_init(&sem2, 0, 0); file_ptr = fopen("multithread", "a+"); printf("Enter the text\\n"); scanf("%[^\\t]%*c", str); fprintf(file_ptr, "%s", str); fclose(file_ptr); file_ptr = 0; my_sig.sa_handler = my_handler; sigaction(SIGUSR1, &my_sig, 0); sigaction(SIGUSR2, &my_sig, 0); sigaction(SIGTERM, &my_sig, 0); rc = pthread_create(&tid_2, &t2_attr, thread2_fn, 0); if (rc) { printf("ERROR; pthread_create() 2 rc is %d\\n", rc); perror(0); exit(-1); } printf("Thread 2 spawned\\n"); rc = pthread_create(&tid_3, &t3_attr, thread3_fn, 0); if (rc) { printf("ERROR; pthread_create() 3 rc is %d\\n", rc); perror(0); exit(-1); } printf("Thread 3 spawned\\n"); if(pthread_join(tid_2, 0) == 0) printf("Thread 2 done\\n"); else perror("Thread 2"); if(pthread_join(tid_3, 0) == 0) printf("Thread 3 done\\n"); else perror("Thread 3"); rc = pthread_mutex_destroy(&rsrcA); if(rc) printf("Mutex destroy error: %d\\n", rc); printf("Mutex destroyed\\n"); rc = sem_destroy(&sem1); if(rc) printf("Semaphore 1 destroy error: %d\\n", rc); printf("Semaphore 1 destroyed\\n"); rc = sem_destroy(&sem2); if(rc) printf("Semaphore 2 destroy error: %d\\n", rc); printf("Semaphore 2 destroyed\\n"); return(0); }
1
#include <pthread.h> { pthread_mutex_t mut; pthread_cond_t inserimento[2][2][2]; int coda[2][2][2]; int temperatura; int n_piastrelle; }monitor; monitor m; { int id; int t; int qta; int tipo; int temperatura; }lot; lot new_lot(int id) { lot s; s.id = id; s.t= rand()%10; s.qta = rand()%2; s.temperatura = rand()%2; return s; } void init() { pthread_mutex_init(&m.mut,0); for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { for (int k = 0; k < 2; ++k) { pthread_cond_init(&m.inserimento[i][j][k],0); m.coda[i][j][k]=0; printf("m.coda[%d][%d][%d]: %d\\n",i,j,k,m.coda[i][j][k]); } } } m.temperatura=0; printf("m.temperatura: %d\\n",m.temperatura); } void signal() { } void inT2(lot l) { pthread_mutex_lock(&m.mut); printf("lotto [%d] T2 entra \\n",l.id); while((m.temperatura!=1 && m.n_piastrelle>0) || 5 - m.n_piastrelle < l.qta ) { if (l.tipo==1) { m.coda[1][1][l.qta]++; pthread_cond_wait(&m.inserimento[1][1][l.qta],&m.mut); m.coda[1][1][l.qta]--; } else if (l.tipo==0) { m.coda[1][0][l.qta]++; pthread_cond_wait(&m.inserimento[1][0][l.qta],&m.mut); m.coda[1][0][l.qta]--; } else { printf("lotto [%d] T2 errore sul tipo di piastrella\\n",l.id); } } m.temperatura=1; m.in_piastrelle+=l.qta; pthread_mutex_unlock(&m.mut); } void outT2(lot l) { pthread_mutex_lock(&m.mut); printf("lotto [%d] T2 esce\\n",l.id); m.in_piastrelle-=l.qta; signal(); pthread_mutex_unlock(&m.mut); } void inT1(lot l) { pthread_mutex_lock(&m.mut); printf("lotto [%d] T1 entra \\n",l.id); while((m.temperatura!=0 && m.n_piastrelle>0) || 5 - m.n_piastrelle < l.qta ) { if (l.tipo==1) { m.coda[0][1][l.qta]++; pthread_cond_wait(&m.inserimento[1][1][l.qta],&m.mut); m.coda[0][1][l.qta]--; } else if (l.tipo==0) { m.coda[0][0][l.qta]++; pthread_cond_wait(&m.inserimento[1][0][l.qta],&m.mut); m.coda[0][0][l.qta]--; } else { printf("lotto [%d] T1 errore sul tipo di piastrella\\n",l.id); } } m.temperatura=0; m.in_piastrelle+=l.qta; pthread_mutex_unlock(&m.mut); } void outT1(lot l) { pthread_mutex_lock(&m.mut); printf("lotto [%d] T1 esce\\n",l.id); m.in_piastrelle-=l.qta; signal(); pthread_mutex_unlock(&m.mut); } void* lotto(void* arg) { int id = (int)arg; printf("lotto [%d] creato\\n",id); lot l; l = new_lot(id); if (l.temperatura==0) { inT1(l); sleep(l.t); outT1(l); } else if (l.temperatura==1) { inT2(l); sleep(l.t); outT2(l); } else printf("lotto [%d] errore sul tipo\\n",id); pthread_exit(0); } int main(int argc, char *argv[]) { init(); pthread_t lotti[5]; for (int i = 0; i < 5; ++i) { if(pthread_create(&lotti[i],0,lotto,(void *)i)<0) { fprintf(stderr, "errore creazione thread lotto [%d]\\n",i); exit(1); } } for (int i = 0; i < 5; ++i) { if(pthread_join(lotti[i],0)){ fprintf(stderr, "errore terminazione thread lotto [%d]\\n",i); exit(1); } else { printf("thread lotto [%d] termiato con successo\\n", i); } } return 0; }
0
#include <pthread.h> static struct netflow_cache_t nfc_instance; static struct netflow_cache_t *nfcptr = 0; static int nfc_cache_size = 0; static struct netflow_cache_data_t *netf_key = 0; static int front = 0, rear = 0; static int bufuse = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int pktbuf_num_of_buffers (void) { return nfc_cache_size; } static int pktbuf_num_of_freebuf (void) { return nfc_cache_size - bufuse; } static int pktbuf_count (void) { return bufuse; } static struct netflow_cache_data_t * request (void) { int i; if (bufuse == nfc_cache_size) return 0; i = front; front = (front + 1) % nfc_cache_size; pthread_mutex_lock (&mutex); bufuse++; pthread_mutex_unlock (&mutex); return &netf_key[i]; } static struct netflow_cache_data_t * retrieve (void) { if (bufuse == 0) return 0; if (netf_key[rear].buffer_ready == 0) return 0; return &netf_key[rear]; } static void bufready (struct netflow_cache_data_t *ptr) { ptr->buffer_ready = 1; } static void dequeue (struct netflow_cache_data_t *pkt) { int i; if (bufuse > 0) { i = rear; netf_key[i].buffer_ready = 0; rear = (rear + 1) % nfc_cache_size; pthread_mutex_lock (&mutex); bufuse--; pthread_mutex_unlock (&mutex); } } static void pfb_close (void) { int len; len = nfc_cache_size; nfc_cache_size = 0; front = rear = bufuse = 0; free (netf_key); } struct netflow_cache_t *init_netflow_cache (const int cache_size) { int i; if (nfcptr == 0) { if ((netf_key = utils_calloc (cache_size, sizeof (struct netflow_cache_data_t))) == 0) { return 0; } nfc_cache_size = cache_size; front = rear = bufuse = 0; nfcptr = &nfc_instance; for (i = 0; i < nfc_cache_size; i++) { memset (&netf_key[i], 0, sizeof (struct netflow_cache_data_t)); netf_key[i].flowkey.data = &netf_key[i].key; netf_key[i].flowkey.size = sizeof (struct netflow_key); netf_key[i].buffer_ready = 0; } nfcptr->request = request; nfcptr->ready = bufready; nfcptr->retrieve = retrieve; nfcptr->dequeue = dequeue; nfcptr->close = pfb_close; nfcptr->num_of_buffers = pktbuf_num_of_buffers; nfcptr->num_of_freebuf = pktbuf_num_of_freebuf; nfcptr->count = pktbuf_count; fprintf (logfp, "init_netflow_cache ok\\n"); } return nfcptr; }
1
#include <pthread.h> struct input { int num; int cT; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int curThread = 1; int timecount = 0; void *createThread(void *input) { struct input *in = input; int actual = in->cT; printf("Hello from thread No. %d!\\n", actual); int tcount = 0; int counter = 0; pthread_mutex_lock(&mutex2); timecount += in->num; pthread_mutex_unlock(&mutex2); pthread_t p1, p2; sleep(in->num); while(tcount < 2) { pthread_mutex_lock(&mutex); if(curThread < 10000) { curThread++; if (tcount == 0){ struct input first; first.num = ((int) rand()%10)+1; first.cT = curThread; pthread_create(&p1, 0, createThread, &first); counter++; } else { struct input sec; sec.num = ((int) rand()%10)+1; sec.cT = curThread; pthread_create(&p2, 0, createThread, &sec); counter++; } } pthread_mutex_unlock(&mutex); tcount++; } if(counter > 0) pthread_join(p1, 0); if(counter > 1) pthread_join(p2, 0); printf("Bye from thread No. %d!\\n", actual); } int main() { struct input start; start.num = 0; start.cT = curThread; createThread(&start); printf("Die Threads haben zusammen %d Sekunden gewartet.\\n", timecount); }
0
#include <pthread.h> size_t number_of_primes; size_t *arg_parse(int argc, char *argv[]) { if (argc != 4) { fprintf(stderr, "usage: %s [start] [end] [num_threads]\\n", argv[0]); exit(1); } char *endptr; long tokargs[3]; for (size_t i = 0; i < sizeof(tokargs) / sizeof(tokargs[0]); i++) { tokargs[i] = strtol(argv[i + 1], &endptr, 10); if (*endptr != '\\0') { fprintf(stderr, "Failed to convert an arugment to a long!\\n"); exit(2); } if (tokargs[i] < 1) { fprintf(stderr, "Please have all arguments be greater than or equal to 1!\\n"); exit(3); } } if (tokargs[1] < tokargs[0]) { fprintf(stderr, "Please give a valid range!\\n"); exit(4); } size_t *args = malloc(3 * sizeof(size_t)); for (size_t i = 0; i < sizeof(tokargs) / sizeof(tokargs[0]); i++) { args[i] = (size_t)tokargs[i]; } return args; } void print_result(size_t number_of_primes, size_t start, size_t end) { printf("There are %zu primes between %zu and %zu inclusive\\n", number_of_primes, start, end); } size_t start; size_t end; } ag; ag* create(size_t a, size_t b) { ag* p = malloc (sizeof (ag)); p->start = a; p->end = b; return p; } pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void* prime(void* p){ ag* q= (ag*) p; for(size_t i = q->start ; i <= q->end; i++){ double k = sqrt( (double) i ); for(size_t j=2; j<k+1; j++) { if( i % j == 0) { break; } if(i % j != 0 && j>= k ){ pthread_mutex_lock(&m); number_of_primes++; pthread_mutex_unlock(&m); } } } return 0; } int main(int argc, char *argv[]) { if (argc != 4) { fprintf(stderr, "usage: %s [start] [end] [num_threads]\\n", argv[0]); exit(1); } size_t start =(size_t)atoi(argv[1]); size_t end = (size_t )atoi(argv[2]); size_t num = (size_t )atoi(argv[3]); size_t dis = end-start; size_t unit = dis/num; if( num >= (dis+1)/2){ num = (dis+1)/2; } if(num == 0 ) num =1; ag** tuple= (ag**)malloc(num * sizeof(ag*)); if( num == 1) tuple[0] = create(start, end); else{ tuple[0] = create(start, start+unit); size_t i = 1; for(i=1; i < num-1 ; i++) { tuple[i]= create(start+i*unit+1, start+(i+1)* unit); } tuple[i] = create(start+i*unit+1, end); } pthread_t*array = (pthread_t*)malloc(num * sizeof(pthread_t)); for (size_t i = 0; i < num; i++) { pthread_create (&array[i], 0, prime, tuple[i]); } for (size_t i = 0; i < num ; i++) { pthread_join(array[i], 0); } if(start == 2 || (start == 1 && end != start)) number_of_primes ++; for(size_t i =0 ; i< num ; i++) { free(tuple [i]); } free(tuple); free (array); print_result(number_of_primes,start, end); return 0; }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks mutex @lock1 @lock2...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking mutex @lock1 @lock2...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking mutex @lock1 @lock2...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void * thr_fn(void *arg) { int err; pid_t child_proc; printf("thread start...\\n"); if((child_proc = fork()) < 0) err_quit("fork error"); else if(child_proc == 0) { err = pthread_mutex_lock(&lock1); if(err == 0) printf("lock mutex @lock1 in child proc\\n"); else err_exit(err, "cant lock mutex @lock1 in child proc"); err = pthread_mutex_unlock(&lock1); if(err == 0) printf("unlock mutex @lock1 in child proc\\n"); else err_exit(err, "cant unlock mutex @lock1 in child proc"); } else { ; } pthread_exit(0); } int main(void) { int err; pid_t pid; pthread_t tid; if((err = pthread_atfork(prepare, parent, child)) != 0) err_exit(err, "cant install fork handlers"); err = pthread_mutex_lock(&lock1); if(err == 0) printf("lock mutex @lock1 in father proc 1st-therad\\n"); else err_exit(err, "cant lock mutex"); err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0) err_exit(err, "can't create thread"); sleep(5); err = pthread_mutex_unlock(&lock1); if(err == 0) printf("unlock mutex @lock1 in father proc 1st-thread\\n"); else err_exit(err, "cant unlcok mutex"); pthread_exit(0); }
0
#include <pthread.h> extern char coup_part[13]; extern char rdy; extern pthread_mutex_t synchro_mutex; extern pthread_cond_t synchro_cv; char * send_plateau_ia() { static int first = 1; static pthread_t th; int retour = 0; if (first) { first = 0; coup_part[0] = 0; pthread_mutex_init(&synchro_mutex, 0); pthread_cond_init (&synchro_cv, 0); retour = pthread_create(&th, 0, jouer_radio_IA, 0 ); if (retour != 0) { perror(strerror(errno)); exit(1); } pthread_mutex_lock(&synchro_mutex); while (!rdy) pthread_cond_wait(&synchro_cv, &synchro_mutex); rdy = 0; pthread_mutex_unlock(&synchro_mutex); return string_plat(); } pthread_mutex_lock(&synchro_mutex); send_coup_ia(); pthread_cond_signal(&synchro_cv); rdy = 0; pthread_mutex_unlock(&synchro_mutex); pthread_mutex_lock(&synchro_mutex); while (!rdy) pthread_cond_wait(&synchro_cv, &synchro_mutex); rdy = 0; coup_part[0] = 0; pthread_mutex_unlock(&synchro_mutex); return string_plat(); } void send_coup_ia() { char * coup = get_best(); strcpy(coup_part, coup); raz_vote(); } int process_input_client_gounki_ia(char * buff, int descSock, char * address_caller) { int set = 1; setsockopt(descSock, SOL_SOCKET, 13, (void *)&set, sizeof(int)); int retour = 0; char mess[TAILLE_MAX_TCP]; if (strncmp(buff, "INFO", 4) == 0) { format_mess_desc(mess, "Un serveur de jeu Gounki communautaire ou vous affronter une IA !"); send(descSock, mess, strlen(mess), 0); send(descSock, "VOTE\\r\\n", strlen("VOTE\\r\\n"), 0); retour = send(descSock, "ENDM\\r\\n", strlen("ENDM\\r\\n"), 0); if (retour == -1) { perror(strerror(errno)); } return 1; } else if (strncmp(buff, "HELP", 4) == 0) { if (strncmp(buff + 5, "VOTE", 4) == 0) { format_mess_help(mess, "Comande pour participer au jeu VOTE suivit du coup : VOTE a1-b1", "VOTE"); retour = send(descSock, mess, strlen(mess), 0); if (retour == -1) { perror(strerror(errno)); } return 1; } } else if (strncmp(buff, "VOTE", 4) == 0) { receive_vote(buff + 5); return 1; } return 0; }
1
#include <pthread.h> int kuz; int sharmuta; pthread_mutex_t zain = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t tutzke = PTHREAD_MUTEX_INITIALIZER; void* suma(void*arg) { for(int i=0;i<10000;++i) { pthread_mutex_lock(&zain); kuz= kuz +1; pthread_mutex_lock(&tutzke); sharmuta = sharmuta + 1; pthread_mutex_unlock(&tutzke); pthread_mutex_unlock(&zain); } pthread_exit(0); } void* resta(void*arg) { for(int i=0;i<10000;++i) { while(pthread_mutex_trylock(&tutzke)); kuz= kuz-1; pthread_mutex_lock(&zain); sharmuta = sharmuta -1; pthread_mutex_unlock(&tutzke); pthread_mutex_unlock(&zain); } pthread_exit(0); } int main() { kuz =0; sharmuta = 10000; pthread_t* tids= (pthread_t*)malloc(2*sizeof(pthread_t)); pthread_create((tids),0,suma,0); pthread_create((tids+1),0,resta,1); pthread_join(*(tids),0); pthread_join(*(tids+1),0); printf("valor final de kuz:%d --valor resta: %d\\n",kuz,sharmuta); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; void * thread1(void *arg) { pthread_cleanup_push(pthread_mutex_unlock,&mutex); while(1) { printf("thread1 is runnning!\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread1 applied the condition\\n"); pthread_mutex_unlock(&mutex); sleep(4); } pthread_cleanup_pop(0); } void * thread2(void *arg) { while(1) { printf("thread2 is runnning!\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("thread2 applied the condition\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(void) { pthread_t tid1,tid2; printf("condition variable study!\\n"); pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1,0,(void *)thread1,0); pthread_create(&tid2,0,(void *)thread2,0); do { pthread_cond_signal(&cond); }while(1); sleep(50); pthread_exit(0); }
1
#include <pthread.h> void *thd_integrate(void *); struct integralApprox result; pthread_mutex_t mtx_accum; struct thd_args { double (*pFunction)(double); double interval[2]; double precision; }; struct integralApprox threaded_integrate(double *pFunction(double), double start, double end, double precision, int num_threads) { double thd_portion; int rc, i; pthread_attr_t attr; pthread_t thd_id[num_threads]; struct thd_args * args[num_threads]; thd_portion = (end - start) / (double) num_threads; pthread_mutex_init(&mtx_accum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<num_threads; i++) { args[i] = (struct thd_args *) malloc(sizeof(struct thd_args)); args[i]->interval[0] = start + i * thd_portion; args[i]->interval[1] = start + (i + 1) * thd_portion; args[i]->pFunction = pFunction; args[i]->precision = precision; if (0) { printf("In main: creating thread %d\\n", i); } rc = pthread_create(&thd_id[i], &attr, thd_integrate, (void *) args[i]); assert(0 == rc); } pthread_attr_destroy(&attr); for (i=0; i<num_threads; i++) { rc = pthread_join(thd_id[i], 0); assert(0 == rc); } for (i=0; i<num_threads; i++) { free(args[i]); } pthread_mutex_destroy(&mtx_accum); return result; } void *thd_integrate(void * vargs) { struct thd_args * argsptr; struct integralApprox thd_result; argsptr = (struct thd_args *) vargs; thd_result = integrate(argsptr->pFunction, argsptr->interval, argsptr->precision); pthread_mutex_lock(&mtx_accum); result.value += thd_result.value; result.num_strips += thd_result.num_strips; pthread_mutex_unlock(&mtx_accum); pthread_exit((void*) 0); }
0
#include <pthread.h> struct syscall_page* basepage; struct syscall_buffer* base_buffers; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int last_index = 0; void printstack(void) { int i, j, index; printf("\\n"); for (index = 0; index < NUM_THREADS; index++) { i = index % 64; j = index / 64; printf("%d ", index); printf("%d ", basepage[j].entries[i].syscall); printf("%d ", basepage[j].entries[i].num_args); printf("%d ", basepage[j].entries[i].status); printf("%ld ", basepage[j].entries[i].return_code); printf("%ld ", basepage[j].entries[i].args[0]); printf("%ld ", basepage[j].entries[i].args[1]); printf("%ld ", basepage[j].entries[i].args[2]); printf("%ld ", basepage[j].entries[i].args[3]); printf("%ld ", basepage[j].entries[i].args[4]); printf("%ld \\n", basepage[j].entries[i].args[5]); } printf("\\n"); } struct syscall_page* flexsc_register_old(void) { syscall(sys_flexsc_register); return 0; } void flexsc_register(void) { int index, i, j; int fd; unsigned char* kadr; int len = 16 * getpagesize(); syscall(sys_flexsc_register2, (void*) (NUM_THREADS * 128)); if ((fd = open("node2", O_RDWR | O_SYNC)) < 0) { perror("open"); exit(-1); } kadr = mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_LOCKED, fd, len); if (kadr == MAP_FAILED) { perror("mmap"); exit(-1); } close(fd); basepage = (struct syscall_page*) kadr; base_buffers = (struct syscall_buffer*) (kadr + 4 * 64 * 64); printf("Basepage: %ld, %p\\n", (long) basepage, basepage); for (index = 0; index < NUM_THREADS; index++) { j = index / 64; i = index % 64; basepage[j].entries[i].args[0] = 0; basepage[j].entries[i].args[1] = 0; basepage[j].entries[i].args[2] = 0; basepage[j].entries[i].args[3] = 0; basepage[j].entries[i].args[4] = 0; basepage[j].entries[i].args[5] = i + 100; basepage[j].entries[i].syscall = 0; basepage[j].entries[i].status = 0; basepage[j].entries[i].num_args = 0; basepage[j].entries[i].return_code = 0; } } void flexsc_wait(void) { long pid = (long) getpid(); long ret = syscall(sys_flexsc_wait); printf("%ld %ld\\n", pid, ret); } struct syscall_page* allocate_register(void) { return malloc(sizeof(struct syscall_page)); } int last_used = 0; struct syscall_entry* free_syscall_entry_i(int i) { return free_syscall_entry(); } struct syscall_entry* free_syscall_entry(void) { int i, j, index; struct syscall_entry* entry = 0; pthread_mutex_lock(&mutex); for (index = 0; index < NUM_THREADS; index++) { last_index = (last_index + 1) % NUM_THREADS; j = last_index / 64; i = last_index % 64; if (basepage[j].entries[i].status == _FLEX_FREE) { basepage[j].entries[i].status = _FLEX_RESERVED; entry = &basepage[j].entries[i]; break; } } pthread_mutex_unlock(&mutex); if (entry == 0) { printf("Could not find a Empty Entry, NULL\\n"); for (index = 0; index < NUM_THREADS; index++) { j = index / 64; i = index % 64; printf("Index[%d]=%d\\n", index, basepage[j].entries[i].status); } } return entry; }
1
#include <pthread.h> static int reader_count = 0; static int writer_count = 0; static pthread_mutex_t reader_count_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t new_reader_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t writer_count_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t writer_mutex = PTHREAD_MUTEX_INITIALIZER; void writer_pri_reader(int num, int duration) { pthread_mutex_lock(&new_reader_mutex); pthread_mutex_lock(&reader_count_mutex); ++reader_count; if (reader_count == 1) pthread_mutex_lock(&writer_mutex); pthread_mutex_unlock(&reader_count_mutex); pthread_mutex_unlock(&new_reader_mutex); doread(num, duration); pthread_mutex_lock(&reader_count_mutex); --reader_count; if (reader_count == 0) pthread_mutex_unlock(&writer_mutex); pthread_mutex_unlock(&reader_count_mutex); } void writer_pri_writer(int num, int duration) { pthread_mutex_lock(&writer_count_mutex); ++writer_count; if (writer_count == 1) pthread_mutex_lock(&new_reader_mutex); pthread_mutex_unlock(&writer_count_mutex); pthread_mutex_lock(&writer_mutex); dowrite(num, duration); pthread_mutex_unlock(&writer_mutex); pthread_mutex_lock(&writer_count_mutex); --writer_count; if (writer_count == 0) pthread_mutex_unlock(&new_reader_mutex); pthread_mutex_unlock(&writer_count_mutex); }
0
#include <pthread.h> int sharedCounter = 0; pthread_mutex_t lock= PTHREAD_MUTEX_INITIALIZER; void * thread_odd() { while(sharedCounter<20){ sleep(1); pthread_mutex_lock(&lock); printf("Odd acquired lock-"); if(sharedCounter%2 != 0) { printf("Odd print: %d ", sharedCounter); sharedCounter++; } pthread_mutex_unlock(&lock); printf("-Odd released lock \\n"); } } void * thread_even() { while(sharedCounter<20){ sleep(1); pthread_mutex_lock(&lock); printf("Even acquired lock-"); if(sharedCounter%2 == 0) { printf("Odd print: %d ", sharedCounter); sharedCounter++; } pthread_mutex_unlock(&lock); printf("-Even released lock \\n"); } } int main() { int status; pthread_t tid1,tid2; pthread_create(&tid1,0,&thread_odd, 0); pthread_create(&tid2,0,&thread_even,0); pthread_join(tid1,0); pthread_join(tid2,0); return 0; }
1
#include <pthread.h> buffer_item buffer[200]; int index_counter_in = 0,index_counter_out = 0; void *thread_Insert(void *arg); void *thread_Remove(void *arg); sem_t buff_sem; pthread_mutex_t mutx; char thread1[]="Producer A"; char thread2[]="Producer B"; int main(int argc, char **argv) { pthread_t t1, t2, t3; pthread_t arr_t[340]; void *thread_result; int state1, state2,i=0; char cons[340][12]; if (argc < 2) { printf("\\n Please enter argument\\n"); exit(0); } state1 = pthread_mutex_init(&mutx, 0); state2 = sem_init(&buff_sem, 0 ,0); if(state1||state2!=0) puts("Error mutex & semaphore initialization!!!"); pthread_create(&t1, 0, thread_Insert, &thread1); pthread_create(&t2, 0, thread_Insert, &thread2); for(i=0;i<atoi(argv[1]);i++) { sprintf(cons[i], "Consumer %d", i); pthread_create(&arr_t[i], 0, thread_Remove,&cons[i]); } pthread_join(t1, &thread_result); pthread_join(t2, &thread_result); for(i=0;i<atoi(argv[1]);i++) { pthread_join(arr_t[i], 0); } sem_destroy(&buff_sem); pthread_mutex_destroy(&mutx); return 0; } void *thread_Insert(void *arg) { printf("Creating Thread: %s\\n", (char*)arg); while(1) { if(index_counter_in<200) { pthread_mutex_lock(&mutx); buffer[index_counter_in] = index_counter_in; printf("%s: INSERT item to BUFFER %d\\n", (char*)arg, index_counter_in); index_counter_in++; pthread_mutex_unlock(&mutx); sem_post(&buff_sem); sleep(1); } else { index_counter_in=0; sleep(2); } } } void *thread_Remove(void *arg) { printf("Creating Thread: %s\\n", (char*)arg); while(1) { if(index_counter_out<200) { sem_wait(&buff_sem); pthread_mutex_lock(&mutx); sleep(1); buffer[index_counter_out] = 0; printf("%s: REMOVE item from BUFFER %d\\n", (char*)arg, index_counter_out); index_counter_out++; pthread_mutex_unlock(&mutx); sleep(1); } else { index_counter_out=0; sleep(2); } } }
0
#include <pthread.h> static int worms; static sem_t empty, any; static pthread_mutex_t lock; void *parent_bird(void *arg) { int i; while (1) { sem_wait(&empty); pthread_mutex_lock(&lock); worms = 13; printf(" + parent bird brings %d worms\\n\\n", worms); pthread_mutex_unlock(&lock); for (i = 0; i < 13; i++) sem_post(&any); } } void *baby_bird(void *arg) { while (1) { usleep(rand() % ((1000000*7)/13 + 1)); sem_wait(&any); pthread_mutex_lock(&lock); worms--; if (worms) { printf(" - baby bird %d eats (dish: %d worms)\\n", (int)(intptr_t)arg, worms); pthread_mutex_unlock(&lock); } else { printf(" - baby bird %d eats (dish: %d worms)" " and screams\\n\\n", (int)(intptr_t)arg, worms); pthread_mutex_unlock(&lock); sem_post(&empty); } } } int main(int argc, char *argv[]) { int i; pthread_attr_t attr; pthread_t parent_tid; pthread_t baby_tid[13]; worms = 13; printf("\\n + intitial dish: %d worms\\n\\n", worms); sem_init(&empty, 1, 0); sem_init(&any, 1, 13); pthread_mutex_init(&lock, 0); pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_create(&parent_tid, &attr, parent_bird, (void *)(intptr_t)0); for (i = 0; i < 7; i++) pthread_create(&baby_tid[i], &attr, baby_bird, (void *)(intptr_t)i); pthread_join(parent_tid, 0); for (i = 0; i < 7; i++) pthread_join(baby_tid[i], 0); pthread_exit(0); }
1
#include <pthread.h> int *a; int *b; int sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[3]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len; long offset; int 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++) { printf("\\nThread %ld x[%d]=%d y[%d]=%d\\n", offset, i, x[i], i, y[i]); mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("\\nThread %ld did %d to %d: mysum=%d global sum=%d\\n",offset,start,end-1,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i[3],j; int *a, *b; void *status; pthread_attr_t attr; srand(time(0)); a = (int*) malloc (3*3*sizeof(int)); b = (int*) malloc (3*3*sizeof(int)); for (j=0; j<3*3; j++) { a[j]=rand()%11; b[j]=rand()%11; } printf("a:\\t"); for (j=0; j<3*3; j++) printf("%d\\t", a[j]); printf("\\nb:\\t"); for (j=0; j<3*3; j++) printf("%d\\t", b[j]); dotstr.veclen = 3; 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(j=0;j<3;j++) i[j]=j; for(j=0;j<3;j++) pthread_create(&callThd[j], &attr, dotprod, (void *)&i[j]); pthread_attr_destroy(&attr); for(j=0;j<3;j++) pthread_join(callThd[j], &status); printf ("Sum = %d \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int init_function(struct vmod_priv *priv, const struct VCL_conf *conf) { return (0); } pthread_mutex_t header_mutex; static void header_init_re(struct vmod_priv *priv, const char *s) { if (priv->priv == 0) { assert(pthread_mutex_lock(&header_mutex) == 0); if (priv->priv == 0) { VRT_re_init(&priv->priv, s); priv->free = VRT_re_fini; } pthread_mutex_unlock(&header_mutex); } } void vmod_set(struct sess *sp, struct vmod_priv *priv, const char *tested, const char *regexp, const char *header_name, const char *header_value) { char *formatted_header=malloc((strlen(header_name)+3) * sizeof(char)) ; if (tested && regexp && header_name && header_value) { header_init_re(priv, regexp); if (VRT_re_match(tested,priv->priv) != 0){ sprintf(formatted_header,"%c%s:", strlen(header_name)+1,header_name); VRT_SetHdr(sp, HDR_RESP, formatted_header,header_value,vrt_magic_string_end); } } free(formatted_header); }
0
#include <pthread.h> sem_t sem_stu; sem_t sem_ta; pthread_mutex_t mutex; int chair[3]; int count = 0; int next_seat = 0; int next_teach = 0; void rand_sleep(void); void* stu_programming(void* stu_id); void* ta_teaching(); int main(int argc, char **argv){ pthread_t *students; pthread_t ta; int* student_ids; int student_num; int i; printf("How many students? "); scanf("%d", &student_num); students = (pthread_t*)malloc(sizeof(pthread_t) * student_num); student_ids = (int*)malloc(sizeof(int) * student_num); memset(student_ids, 0, student_num); sem_init(&sem_stu,0,0); sem_init(&sem_ta,0,1); srand(time(0)); pthread_mutex_init(&mutex,0); pthread_create(&ta,0,ta_teaching,0); for(i=0; i<student_num; i++) { student_ids[i] = i+1; pthread_create(&students[i], 0, stu_programming, (void*) &student_ids[i]); } pthread_join(ta, 0); for(i=0; i<student_num;i++) { pthread_join(students[i],0); } return 0; } void* stu_programming(void* stu_id) { int id = *(int*)stu_id; printf("[stu] student %d is programming\\n",id); while(1) { rand_sleep(); pthread_mutex_lock(&mutex); if(count < 3) { chair[next_seat] = id; count++; printf(" [stu] student %d is waiting\\n",id); printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]); next_seat = (next_seat+1) % 3; pthread_mutex_unlock(&mutex); sem_post(&sem_stu); sem_wait(&sem_ta); } else { pthread_mutex_unlock(&mutex); printf("[stu] no more chairs. student %d is programming\\n",id); } } } void* ta_teaching() { while(1) { sem_wait(&sem_stu); pthread_mutex_lock(&mutex); printf(" [ta] TA is teaching student %d\\n",chair[next_teach]); chair[next_teach]=0; count--; printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]); next_teach = (next_teach + 1) % 3; rand_sleep(); printf(" [ta] teaching finish.\\n"); pthread_mutex_unlock(&mutex); sem_post(&sem_ta); } } void rand_sleep(void){ int time = rand() % 5 + 1; sleep(time); }
1
#include <pthread.h> int N; pthread_mutex_t mutex; struct bufitem { int value; int readf[5]; sem_t var_stat; int status; }; struct bufitem buf[5]; int wp=0; int rp[5]={0,0,0,0,0}; void *write(); void *read(void *); int main() { N=5; int o; for(o=0;o<N;o++) { sem_init(&(buf[o].var_stat),0,0); buf[o].status=0; int p; for(p=0;p<5;p++) buf[o].readf[p]=0; } pthread_t writer; pthread_t reader[5]; pthread_create(&writer,0,&write,0); int i; int a[5]={1,2,3,4,5}; for(i=0;i<N;i++) { pthread_create(&reader[i],0,&read,&a[i]); } printf("threads created\\n"); pthread_join(writer,0); for(i=0;i<N;i++) { pthread_join(reader[i],0); } return 0; } void *write() { while(1) { int data; data=rand()%100; int y=wp%5; if(buf[y].status==0) { buf[y].value=data; printf("wrote %d to the buffer at %d(%d)th position\\n",data,y+1,wp+1); wp++; buf[y].status=1; sleep(2); } else { sem_wait(&buf[y].var_stat); pthread_mutex_lock(&mutex); buf[y].value=data; printf("overwrote %d to the buffer at %d(%d)th position\\n",data,y+1,wp+1); sleep(7); wp=wp++; buf[y].readf[0]=0; buf[y].readf[1]=0; buf[y].readf[2]=0; buf[y].readf[3]=0; buf[y].readf[4]=0; pthread_mutex_unlock(&mutex); } } } void *read(void *ii) { int i = *((int *)ii)-1,flag[5]={0,0,0,0,0}; while(1) { int x=rp[i]%5; if(buf[x].status!=0) { if(buf[x].readf[i]!=1) { printf("reader%d read %d at %dth position\\n",i+1,buf[x].value,x+1,rp[i]+1); sleep(7); buf[x].readf[i]=1; flag[x]=1; } rp[i]=rp[i]+1; int t; for(t=0;t<5;t++) { if(buf[x].readf[t]==0) break; } if(t==5 && i==1 && flag[x]) { sem_post(&buf[x].var_stat); flag[x]=0; } } } }
0
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t barrier1; int SharedVariable = 0; void *SimpleThread(void *args) { int num, val; int which = (int)args; for(num = 0; num < 20; num++){ pthread_mutex_lock(&mutex1); val = SharedVariable; printf("*** thread %d sees value %d\\n", which, val); SharedVariable = val + 1; pthread_mutex_unlock(&mutex1); } pthread_barrier_wait(&barrier1); val = SharedVariable; printf("Thread %d sees final value %d\\n", which, val); return 0; } int main (int argc, char *argv[]) { int num_threads = argc > 1 ? atoi(argv[1]) : 0; if(num_threads > 0){ pthread_t threads[num_threads]; int rc; long t; rc = pthread_barrier_init(&barrier1, 0, num_threads); if(rc) { fprintf(stderr, "pthread_barrier_init: %s\\n", strerror(rc)); exit(1); } for(t = 0; t < num_threads; t++){ printf("In main: creating thread %ld\\n", t); rc = pthread_create(&threads[t], 0, SimpleThread, (void* )t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } printf("%ld\\n", syscall(__NR_sys_pla_thornton_valdes)); for (t = 0; t<num_threads; t++){ pthread_join(threads[t], 0); } } else{ printf("ERROR: The parameter should be a valid positive number.\\n"); exit(-1); } return 0; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t monitor = PTHREAD_COND_INITIALIZER; int cond = 0; void task_cleanup(void * arg) { printf("task: clean up\\n"); pthread_mutex_unlock(&lock); } void * task(void * arg) { pthread_cleanup_push(task_cleanup, 0); pthread_mutex_lock(&lock); while (!cond) { printf("task: eseguo wait sulla var. condizione condivisa\\n"); pthread_cond_wait(&monitor, &lock); } pthread_mutex_unlock(&lock); pthread_cleanup_pop(0); return 0; } int readLine(FILE * fl, char ** strref) { int bytesRead = 0, bfsz = 8, bfactlsz = 0, unused = 0; char leave = 0, * tmp = 0; if (0 == fl || 0 == strref) { errno = EINVAL; return -1; } bfactlsz = bfsz; while (!leave) { if( 0 == (tmp = realloc(*strref, bfactlsz)) ) { free(*strref); *strref = 0; return -1; } *strref = tmp; bzero((*strref)+bfactlsz-bfsz, bfsz); fgets(*strref+bfactlsz-bfsz-unused, bfsz+unused, fl); tmp = *strref+bfactlsz-bfsz-unused; while (!leave && tmp < *strref + bfactlsz) { if ('\\n' == *tmp) { leave = 1; } else tmp++; } bfactlsz += bfsz; unused = 1; } *tmp = '\\0'; unused = (*strref)+bfactlsz-bfsz - tmp-1; if ( 0 == (tmp = realloc(*strref, bfactlsz-bfsz - unused)) ) { free(strref); *strref = 0; return -1; } return 0; } int main(void) { pthread_t t; struct timespec tosleep; char bf[8]; char * str = 0; FILE * fl; fl = fopen("DATA/userlist", "r"); readLine(fl, &str); printf("%d, >%s<\\n", strlen(str), str); free(str); fclose(fl); return 0; tosleep.tv_nsec = 0; tosleep.tv_sec = 1; printf("main: avvio l'altro thread\\n"); pthread_create(&t, 0, task, 0); nanosleep(&tosleep, 0); printf("main: ho cancellato l'altro thread\\n"); pthread_cancel(t); printf("main: aspetto la terminazione dell'altro thread\\n"); pthread_join(t, 0); return 0; }
0
#include <pthread.h> int buffer1[4]; int buffer2[4]; int in1; int out1; int in2; int out2; int buffer2_is_empty() { return in2 == out2; } int buffer2_is_full() { return (in2 + 1) % 4 == out2; } int buffer1_is_empty() { return in1 == out2; } int buffer1_is_full() { return (in1 + 1) % 4 == out1; } int get_item() { int item; item = buffer2[out2]; out2 = (out2 + 1) % 4; return item; } void put_item(int item) { buffer1[in1] = item; in1 = (in1 + 1) % 4; } int cal_get_item() { int item; item = buffer1[out1]; out1 = (out1 + 1) % 4; return item; } void cal_put_item(int item) { buffer2[in2] = item; in2 = (in2 + 1) % 4; } pthread_mutex_t mutex1; pthread_cond_t wait_empty_buffer1; pthread_cond_t wait_full_buffer1; pthread_mutex_t mutex2; pthread_cond_t wait_empty_buffer2; pthread_cond_t wait_full_buffer2; void *consume(void *arg) { int i; int item; for(i = 0; i < (4 * 8); i++){ pthread_mutex_lock(&mutex2); while(buffer2_is_empty()){ pthread_cond_wait(&wait_full_buffer2,&mutex2); } item = get_item(); printf(" consume item: %c\\n",item); sleep(1); pthread_cond_signal(&wait_empty_buffer2); pthread_mutex_unlock(&mutex2); } return 0; } void *calculate(void *arg) { int i; int item; for(i = 0; i < (4 * 8); i++){ pthread_mutex_lock(&mutex1); while(buffer1_is_empty()){ pthread_cond_wait(&wait_full_buffer1,&mutex1); } item = cal_get_item(); item += 'A' - 'a'; pthread_cond_signal(&wait_empty_buffer1); pthread_mutex_unlock(&mutex1); pthread_mutex_lock(&mutex2); while(buffer2_is_full()){ pthread_cond_wait(&wait_empty_buffer2,&mutex2); } cal_put_item(item); pthread_cond_signal(&wait_full_buffer2); pthread_mutex_unlock(&mutex2); } return 0; } void produce() { int i; int item; for(i = 0; i < (4 * 8); i++){ pthread_mutex_lock(&mutex1); while(buffer1_is_full()){ pthread_cond_wait(&wait_empty_buffer1,&mutex1); } item = i + 'a'; printf("produce item: %c\\n",item); put_item(item); sleep(1); pthread_cond_signal(&wait_full_buffer1); pthread_mutex_unlock(&mutex1); } } int main(int argc,char *argv[]) { pthread_t consumer_tid; pthread_t calculate_tid; pthread_mutex_init(&mutex1,0); pthread_cond_init(&wait_empty_buffer1,0); pthread_cond_init(&wait_full_buffer1,0); pthread_mutex_init(&mutex2,0); pthread_cond_init(&wait_empty_buffer2,0); pthread_cond_init(&wait_full_buffer2,0); pthread_create(&calculate_tid,0,calculate,0); pthread_create(&consumer_tid,0,consume,0); produce(); pthread_join(consumer_tid,0); pthread_join(calculate_tid,0); return 0; }
1
#include <pthread.h> int mediafirefs_utimens(const char *path, const struct timespec tv[2]) { printf("FUNCTION: utimens. path: %s\\n", path); time_t since_epoch; struct tm local_time; static int b_tzset = 0; char print_time[24]; bool is_file = 0; const char *key = 0; int retval; struct mediafirefs_context_private *ctx; (void)path; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); is_file = folder_tree_path_is_file(ctx->tree, ctx->conn, path); key = folder_tree_path_get_key(ctx->tree, ctx->conn, path); if (key == 0) { fprintf(stderr, "key is NULL\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOENT; } if (b_tzset != 1) { tzset(); b_tzset = 1; } memcpy(&since_epoch, &tv[1].tv_sec, sizeof(time_t)); if (localtime_r((const time_t *)&since_epoch, &local_time) == 0) { fprintf(stderr, "utimens not implemented\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -ENOSYS; } memset(print_time, 0, sizeof(print_time)); strftime(print_time, sizeof(print_time) - 1, "%F %T", &local_time); fprintf(stderr, "utimens file set: %s\\n", print_time); if (is_file) { retval = mfconn_api_file_update(ctx->conn, key, 0, print_time, 0); } else { retval = mfconn_api_folder_update(ctx->conn, key, 0, print_time); } if (retval == -1) { pthread_mutex_unlock(&(ctx->mutex)); return -ENOENT; } pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> static pthread_mutexattr_t attr; static pthread_mutex_t *pmutex; static char shared_file[] = "/tmp/shared_file.mmap"; static int fd = -1; void mutex_init(void) { if ((fd = open(shared_file, O_RDWR | O_CREAT | O_TRUNC, FILE_MODE)) < 0) err_sys("open error"); if ((pmutex = mmap(0, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0)) == 0) err_sys("mmap error"); if ((pthread_mutexattr_init(&attr)) != 0) err_sys("pthread_mutexattr_init error"); if ((pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)) != 0) { pthread_mutexattr_destroy(&attr); err_sys("pthread_mutexattr_setpshared error"); } if ((pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST)) != 0) { pthread_mutexattr_destroy(&attr); err_sys("pthread_mutexattr_setpshared error"); } if ((pthread_mutex_init(pmutex, &attr)) != 0) { pthread_mutexattr_destroy(&attr); err_sys("pthread_mutex_init error"); } pthread_mutexattr_destroy(&attr); } void mutex_wait(void) { int ret; ret = pthread_mutex_lock(pmutex); if (ret == EOWNERDEAD) { if (pthread_mutex_consistent(pmutex) != 0) { pthread_mutex_unlock(pmutex); return; } pthread_mutex_unlock(pmutex); pthread_mutex_lock(pmutex); } else if (ret == ENOTRECOVERABLE) { pthread_mutex_destroy(pmutex); munmap(pmutex, sizeof(pthread_mutex_t)); mutex_init(); ret = pthread_mutex_lock(pmutex); } if (ret != 0) { pthread_mutex_destroy(pmutex); munmap(pmutex, sizeof(pthread_mutex_t)); err_sys("pthread_mutex_lock error"); } } void mutex_signal(void) { if (pthread_mutex_unlock(pmutex) != 0) { pthread_mutex_destroy(pmutex); munmap(pmutex, sizeof(pthread_mutex_t)); err_sys("pthread_mutex_unlock error"); } }
1
#include <pthread.h> pthread_mutex_t msg = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t usuarios = PTHREAD_COND_INITIALIZER; pthread_cond_t pombo_correio = PTHREAD_COND_INITIALIZER; void* usuario(void *arg); void* pombo(void *arg); int carta = 0; int main(){ int i; int *id; pthread_t u[6]; pthread_t p; for(i = 0; i < 6; i++){ id = (int*)malloc(sizeof(int)); *id = i; pthread_create(&u[i], 0, usuario, (void*)(id)); } pthread_create(&p, 0, pombo, 0); pthread_join(u[0], 0); pthread_join(p, 0); return 0; } void* usuario(void *arg){ int i = *((int*)arg); while(1){ pthread_mutex_lock(&msg); if(carta >= 5 -1){ printf("Carga do pombo comleta: %d de %d\\n", carta+1, 5); pthread_cond_signal(&pombo_correio); } printf("%d postando carta\\n", i); carta++; while(carta >= 5 -1){ printf("Cartas sendo entregue espere pombo voltar\\n"); pthread_cond_wait(&usuarios, &msg); } pthread_mutex_unlock(&msg); printf("carta %d postada\\n", i); sleep(1); } } void* pombo(void *arg){ while(1){ pthread_mutex_lock(&msg); while(carta <= 5 -1){ printf("espere carga completa: %d carta(s) de %d\\n", carta+1, 5); pthread_cond_wait(&pombo_correio, &msg); } printf("Entregar cartas...\\n"); sleep(3); carta = 0; printf("Cartas entregues voltar para buscar mais\\n"); sleep(1); pthread_cond_broadcast(&usuarios); pthread_mutex_unlock(&msg); } }
0
#include <pthread.h> volatile int flags[10]; volatile int wait[10]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *DoWork1(void *threadid) { flags[0] = flags[0] + 1; wait[0] = 0; pthread_exit(0); } void *DoWork2(void *threadid) { pthread_mutex_lock (&mutex); flags[0] = flags[0] + 1; pthread_mutex_unlock (&mutex); pthread_exit(0); } int main( int argc, char** argv) { pthread_t threads[1]; flags[0] = 0; wait[0] = 1; __builtin_ia32_monitor ((void *)&flags, 0, 0); pthread_create(&threads[0], 0, DoWork1, 0); while(wait[0]); pthread_create(&threads[0], 0, DoWork2, 0); int mwait_cnt = 0; do { pthread_mutex_lock (&mutex); if(flags[0] != 2) { pthread_mutex_unlock (&mutex); __builtin_ia32_mwait(0, 0); } else { pthread_mutex_unlock (&mutex); } mwait_cnt++; } while(flags[0] != 2 && mwait_cnt < 1000); if(flags[0]==2) { printf("mwait regression PASSED, flags[0] = %d\\n", flags[0]); } else { printf("mwait regression FAILED, flags[0] = %d\\n", flags[0]); } return 0; }
1
#include <pthread.h> struct llist_node *ll; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;; void *build_list(void *args){ struct threads_arg *local_args; local_args = (void *)args; int factor_int = local_args->factor; int maxcnt = local_args->total_threads; char *string; printf("factor value: %d\\n", factor_int); for (int i = 0; i < maxcnt; i++) { string = malloc(80); sprintf(string, "%d", i*factor_int); pthread_mutex_lock(&mutex); llist_insert_data(i*factor_int, string, &ll); pthread_mutex_unlock(&mutex); } return 0; } int main(void) { pthread_t worker_thread1; pthread_t worker_thread2; struct threads_arg args1; struct threads_arg args2; char *string; int index; int factor1 = 2; int factor2 = 3; llist_init(&ll); args1.total_threads = 30000; args1.factor = 2; if (pthread_create(&worker_thread1, 0, build_list, (void *)&args1) != 0) { perror("pthread_create"); } args2.total_threads = 30000; args2.factor = 3; if (pthread_create(&worker_thread2, 0, build_list, (void *)&args2) != 0) { perror("pthread_create"); } pthread_join(worker_thread1, 0); pthread_join(worker_thread2, 0); if (llist_inorder(ll) != 0) { printf("ISSUE\\n"); } printf("total list counts: %d\\n", llist_count(ll)); }
0
#include <pthread.h> pthread_once_t my_init_mutex = PTHREAD_ONCE_INIT; void initialize_once_app(void) { printf("work only once\\n"); } void* EntryFunction(void* arg) { printf("Thread %d ran~\\n", (int)arg); pthread_t id = pthread_self(); printf("my id is %x\\n", (int)id); int detachid = 2; if (detachid == (int)arg) { printf("I am thread %d and I must detached bye...", detachid); pthread_detach(id); } pthread_once(&my_init_mutex, initialize_once_app); pthread_exit(arg); } int thread_create_demo() { printf("start up...\\n"); int ret; pthread_t mythread1; pthread_t mythread2; int arg1 = 1; int arg2 = 2; ret = pthread_create(&mythread1, 0, EntryFunction, (void*)arg1); printf("pthread_t is %x\\n", (int)mythread1); ret = pthread_create(&mythread2, 0, EntryFunction, (void*)arg2); if (ret!=0) { printf("Can't create pthread (%s)\\n", strerror(errno)); exit(-1); } int status = 0; printf("wait for mythread 1 working \\n"); ret = pthread_join(mythread1, (void**)&status); if (ret!=0) { printf("Error joining thread (%s)\\n", strerror(errno)); } else { printf("Thread status = %d \\n", status); } printf("mythread1 finished\\n"); return 0; } pthread_mutex_t cntr_mutex = PTHREAD_MUTEX_INITIALIZER; long countVariable = 0; void *product(void* arg) { int i, ret=0; for (int i = 0; i < 100; ++i) { ret = pthread_mutex_lock(&cntr_mutex); assert(ret == 0); countVariable++; printf("value is %ld\\n", countVariable); ret = pthread_mutex_unlock(&cntr_mutex); assert(ret == 0); } pthread_exit(0); } int thread_mutex_demo() { int i, ret; pthread_t threadIds[(10)]; for (int i = 0; i < (10); ++i) { ret = pthread_create(&threadIds[i], 0, product, 0); } for (int i = 0; i < (10); ++i) { ret = pthread_join(threadIds[i], 0); } printf("The protected value is %ld\\n", countVariable); ret = pthread_mutex_destroy(&cntr_mutex); return 0; } pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; void *producerFunc(void* arg) { int ret = 0; double result = 0.0; printf("producer started\\n"); for (int i = 0; i < 30; ++i) { ret = pthread_mutex_lock(&cond_mutex); if (ret == 0) { printf("producer create work (%d)\\n", countVariable); countVariable++; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&cond_mutex); } for (int i = 0; i < 600000; ++i) { result = result + (double)random(); } sleep(2); } printf("producer finished\\n"); pthread_exit(0); } void *consumerFunc(void* arg) { int ret; pthread_detach(pthread_self()); printf("Consumer %x: Started\\n", pthread_self() ); while(1) { assert(pthread_mutex_lock( &cond_mutex ) == 0); assert( pthread_cond_wait( &condition, &cond_mutex ) == 0); printf("Consumer %x: recv condition\\n", pthread_self()); if (countVariable) { countVariable--; printf("Consumer %x: Performed work (%d)\\n", pthread_self(), countVariable); sleep(4); } assert(pthread_mutex_unlock(&cond_mutex)==0); } printf("Consumer %x: Finished\\n", pthread_self() ); pthread_exit( 0 ); } int thread_conditon_demo() { pthread_t consumers[(10)]; pthread_t producer; for (int i = 0; i < (10); ++i) { pthread_create(&consumers[i], 0, consumerFunc, 0); } pthread_create(&producer, 0, producerFunc, 0); pthread_join(producer, 0); while((countVariable>0)); for (int i = 0; i < (10); ++i) { pthread_cancel(consumers[i]); } pthread_mutex_destroy(&cond_mutex); pthread_cond_destroy(&condition); return 0; } int main() { thread_conditon_demo(); getchar(); return 0; }
1
#include <pthread.h> pthread_t tid1,tid2; int a = 0; int n ; int buffer[n]; int counter =0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void * producer () { int nextp = 0; int in = 0; while(1){ while(counter == n) { continue; } pthread_mutex_lock(&mutex1); buffer[in] = nextp; counter += 1; in = (in+1) % n ; nextp += 1; pthread_mutex_unlock(&mutex1); } } void * consumer () { int nextc = 0; int out = 0; while(counter == 0) { while(counter == 0) { continue; } pthread_mutex_lock(&mutex1); next = buffer[out]; out = (out+1) % n; pthread_mutex_unlock(&mutex1); } } int main(){ int result ; pthread_mutex_init(&mutex1,0); result = pthread_create(&tid1, 0, producer, 0); result = pthread_create(&tid2, 0, p2, 0); pthread_join(tid1,0); printf("Thread 1 finished: %d\\n", a); pthread_join(tid2,0); printf("Thread 2 finished: %d\\n", a); return 0; }
0
#include <pthread.h> char name[256]; static int name_i = 0; static int ppi = 0; pthread_mutex_t number_mutex; pthread_mutex_t number2_mutex; void recv_user_info(int con_fd, char *info) { if(recv(con_fd, info, sizeof(info), 0) < 0) { perror("recv"); exit(1); } } void exe_in(int *con_fd) { int i,j; int flag = 1; char ret[10][256]; int s = -1; int newfd[10]; int k = -1; char quit_name[256]; s++; k++; printf("you are the %d people, con_fd:%d, name:%s\\n",ppi,*con_fd,name); strncpy(quit_name, name, 40); newfd[k] = *con_fd; fflush(stdout); memset(tmpname[name_i], 0, 40); recv(newfd[k], tmpname[name_i], 40, 0); while(flag) { recv(newfd[k], ret[s], 256, 0); printf("s = %d,*con_fd = %d\\n",s,newfd[k]); printf("服务器收到\\n"); for(i = 0; i < 10; i++) { send(people[i].confd, ret[s], strlen(ret[s]), 0); } printf("s = %d.people[i].confd = %d\\n",s,people[i].confd); printf("服务器已发送,%s\\n",people[i].name); if(strcmp(ret[s], "bye") == 0) { for(j = 0; j < 10; j++) { if(strcmp(tmpname[j], quit_name) == 0) { memset(tmpname, 0, 40); } } pthread_exit(0); } memset(ret[s], 0, 256); } } void exe_info(int *con_fd) { int i,j; int flag = 1; char ret[10][256]; int s = -1; int newfd[10]; int k = -1; char quit_name[256]; s++; k++; printf("you are the %d people, con_fd:%d, name:%s\\n",ppi,*con_fd,name); strncpy(quit_name, name, 40); newfd[k] = *con_fd; pthread_mutex_lock (&number_mutex); fflush(stdout); memset(tmpname[name_i], 0, 40); recv(newfd[k], tmpname[name_i], 40, 0); printf("接收聊天对象->tmp_name:%s\\n",tmpname[name_i]); printf("您要和%s聊天,con_fd = %d\\n",tmpname[name_i],newfd[k]); for(i = 0; i < 10; i++) { if(strcmp(tmpname[name_i], people[i].name) == 0) break; } if(i == 10) { printf("\\n抱歉!您查找的人不存在!\\n您不能和不存在的人聊天\\n请重新输入\\n"); return; } sleep(2); name_i++; pthread_mutex_unlock (&number_mutex); while(flag) { recv(newfd[k], ret[s], 256, 0); printf("s = %d,*con_fd = %d\\n",s,newfd[k]); printf("服务器收到\\n"); send(people[i].confd, ret[s], strlen(ret[s]), 0); printf("s = %d.people[i].confd = %d\\n",s,people[i].confd); printf("服务器已发送,%s\\n",people[i].name); if(strcmp(ret[s], "bye") == 0) { for(j = 0; j < 10; j++) { if(strcmp(tmpname[j], quit_name) == 0) { memset(tmpname, 0, 40); } } pthread_exit(0); } memset(ret[s], 0, 256); } } void input(char *buf) { int i= 0; char ch; while((ch = getchar()) != '\\n') { buf[i] = ch; i++; } buf[i] = '\\0'; } int main(int argc, char *argv[]) { int sock_fd, con_fd, client_len; struct sockaddr_in my_addr,client_addr; int i = 0,j; int tmp_confd; pthread_t thid; for(j = 0; j < 10; j++) { people[j].confd = -1; j++; } sock_fd = socket(AF_INET, SOCK_STREAM, 0); memset(&my_addr, 0, sizeof(my_addr)); my_addr.sin_family = AF_INET; my_addr.sin_port = htons(4057); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr_in)); if(listen(sock_fd, 10) < 0) { perror("listen"); exit(1); } client_len = sizeof(struct sockaddr_in); while(1) { con_fd = accept(sock_fd, (struct sockaddr*)&client_addr, &client_len); memset(name, 0, sizeof(name)); recv_user_info(con_fd, name); if(strcmp(name, "group") == 0) { printf("要开始群聊啦!!\\n"); pthread_create(&thid, 0, (void *)exe_in, &con_fd); } else { strcpy(people[ppi].name, name); people[ppi].confd = con_fd; ppi++; printf("%s登陆啦!!\\n",name); pthread_create(&thid, 0, (void *)exe_info, &con_fd); } } close(sock_fd); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; sem_t start0, start1, start2, start3, start4, start5, start6, start7, start8, start9; struct buffer { int idata; char cdata[100]; }buf; void *w0(void *arg) { int w0_idata = 0; char w0_cdata[100] = "0"; sem_wait(&start0); pthread_mutex_lock(&lock); buf.idata = buf.idata + w0_idata; strcat(buf.cdata, w0_cdata); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w1(void *arg) { int w1_idata = 1; char w1_cdata[100] = "1"; sem_wait(&start1); pthread_mutex_lock(&lock); buf.idata = buf.idata + w1_idata; strcat(buf.cdata, w1_cdata); sem_post(&start2); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w2(void *arg) { int w2_idata = 2; char w2_cdata[100] = "2"; sem_wait(&start2); pthread_mutex_lock(&lock); buf.idata = buf.idata * w2_idata; strcat(buf.cdata, w2_cdata); printf("t2 says: %d\\n(t2 should say 28)\\n\\n", buf.idata); sem_post(&start9); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w3(void *arg) { int semcheck; int w3_idata = 3; char w3_cdata[100] = "3"; sem_wait(&start3); pthread_mutex_lock(&lock); buf.idata = buf.idata + w3_idata; strcat(buf.cdata, w3_cdata); sem_post(&start1); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w4(void *arg) { int w4_idata = 4; char w4_cdata[100] = "4"; sem_wait(&start4); pthread_mutex_lock(&lock); buf.idata = buf.idata / w4_idata; strcat(buf.cdata, w4_cdata); sem_post(&start5); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w5(void *arg) { int w5_idata = 5; char w5_cdata[100] = "5"; sem_wait(&start5); pthread_mutex_lock(&lock); buf.idata = buf.idata + w5_idata; strcat(buf.cdata, w5_cdata); sem_post(&start0); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w6(void *arg) { int w6_idata = 6; char w6_cdata[100] = "6"; sem_wait(&start6); pthread_mutex_lock(&lock); buf.idata = buf.idata + w6_idata; strcat(buf.cdata, w6_cdata); sem_post(&start4); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w7(void *arg) { int w7_idata = 7; char w7_cdata[100] = "7"; sem_wait(&start7); pthread_mutex_lock(&lock); buf.idata = buf.idata + w7_idata; strcat(buf.cdata, w7_cdata); sem_post(&start8); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w8(void *arg) { int w8_idata = 8; char w8_cdata[100] = "8"; sem_wait(&start8); pthread_mutex_lock(&lock); buf.idata = buf.idata / w8_idata; strcat(buf.cdata, w8_cdata); sem_post(&start6); pthread_mutex_unlock(&lock); pthread_exit(0); } void *w9(void *arg) { int w9_idata = 9; char w9_cdata[100] = "9"; sem_wait(&start9); pthread_mutex_lock(&lock); buf.idata = buf.idata - 28 + w9_idata; strcat(buf.cdata, w9_cdata); sem_post(&start7); pthread_mutex_unlock(&lock); pthread_exit(0); } void main() { buf.idata = 10; strcpy(buf.cdata, "main"); pthread_t t0, t1, t2, t3, t4, t5, t6, t7, t8, t9; pthread_mutex_init(&lock, 0); sem_init(&start0, 0, 0); sem_init(&start1, 0, 0); sem_init(&start2, 0, 0); sem_init(&start3, 0, 0); sem_init(&start4, 0, 0); sem_init(&start5, 0, 0); sem_init(&start6, 0, 0); sem_init(&start7, 0, 0); sem_init(&start8, 0, 0); sem_init(&start9, 0, 0); pthread_create(&t0, 0, w0, 0); pthread_create(&t1, 0, w1, 0); pthread_create(&t2, 0, w2, 0); pthread_create(&t3, 0, w3, 0); pthread_create(&t4, 0, w4, 0); pthread_create(&t5, 0, w5, 0); pthread_create(&t6, 0, w6, 0); pthread_create(&t7, 0, w7, 0); pthread_create(&t8, 0, w8, 0); pthread_create(&t9, 0, w9, 0); sem_post(&start3); pthread_join(t0, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_join(t4, 0); pthread_join(t5, 0); pthread_join(t6, 0); pthread_join(t7, 0); pthread_join(t8, 0); pthread_join(t9, 0); printf("buf.idata = %d\\n", buf.idata); printf("buf.cdata = %s\\n", buf.cdata); if(buf.idata == 7 && strcmp(buf.cdata, "main3129786450") == 0) { printf("Synchronization successful !\\n"); } else { printf("Synchronization failed.\\n"); } pthread_exit(0); }
0
#include <pthread.h> int buffer[160]; int in = 0; int out = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait_empty_buffer; pthread_cond_t wait_full_buffer; int buffer_is_empty() { return in == out; } int buffer_is_full() { return (in + 1) % 160 == out; } int get_item() { int item; item = buffer[out]; out = (out + 1) % 160; return item; } void put_item(int item) { buffer[in] = item; in = (in + 1) % 160; } void *consumer(void *arg) { int i; int item; for (i = 0; i < (160 * 2) ; i++) { pthread_mutex_lock(&mutex); while (buffer_is_empty()) pthread_cond_wait(&wait_full_buffer, &mutex); item = get_item(); pthread_cond_signal(&wait_empty_buffer); pthread_mutex_unlock(&mutex); printf(" consume : %d\\n", item); usleep(50000); } return 0; } void producer() { int i; int item; for (i = 0; i < (160 * 2); i++) { item = i + 'a'; printf("produce : %d\\n", item); usleep(50000); pthread_mutex_lock(&mutex); while (buffer_is_full()) pthread_cond_wait(&wait_empty_buffer, &mutex); put_item(item); pthread_cond_signal(&wait_full_buffer); pthread_mutex_unlock(&mutex); } } int main() { int i; pthread_t consumer_tid; in = 0; pthread_mutex_init(&mutex, 0); pthread_cond_init(&wait_empty_buffer, 0); pthread_cond_init(&wait_full_buffer, 0); for ( i = 0; i < 1000; i++){ pthread_create(&consumer_tid, 0, consumer, 0); producer(); } return 0; }
1
#include <pthread.h> const size_t N_THREADS = 20; pthread_mutex_t mutex; struct timespec timeout; int use_timeout; void *run(void *arg) { int *argi = (int *) arg; int my_tidx = *argi; int retcode; printf("in child %d: sleeping\\n", my_tidx); sleep(2); if (use_timeout) { while (TRUE) { retcode = pthread_mutex_timedlock(&mutex, &timeout); if (retcode == 0) { break; } else if (retcode == ETIMEDOUT) { printf("timed out in child %d\\n", my_tidx); sleep(1); } else { handle_thread_error(retcode, "child failed timed lock", PROCESS_EXIT); } } } else { retcode = pthread_mutex_lock(&mutex); handle_thread_error(retcode, "child failed lock", PROCESS_EXIT); } printf("child %d got mutex\\n", my_tidx); char line[1025]; fgets(line, 1024, stdin); printf("[%d]: %s\\n", my_tidx, line); sleep(1); printf("child %d releases mutex\\n", my_tidx); pthread_mutex_unlock(&mutex); printf("child %d released mutex\\n", my_tidx); sleep(10); printf("child %d exiting\\n", my_tidx); return 0; } void usage(char *argv0, char *msg) { printf("%s\\n\\n", msg); printf("Usage:\\n\\n%s\\n lock mutexes without lock\\n\\n%s -t <number>\\n lock mutexes with timout after given number of seconds\\n", argv0, argv0); exit(1); } int main(int argc, char *argv[]) { int retcode; use_timeout = (argc >= 2 && strcmp(argv[1], "-t") == 0); if (is_help_requested(argc, argv)) { usage(argv[0], ""); } timeout.tv_sec = (time_t) 200; timeout.tv_nsec = (long) 0; if (use_timeout && argc >= 3) { int t; sscanf(argv[2], "%d", &t); timeout.tv_sec = (time_t) t; } printf("timout(%ld sec %ld msec)\\n", (long) timeout.tv_sec, (long) timeout.tv_nsec); pthread_t thread[N_THREADS]; int tidx[N_THREADS]; for (size_t i = 0; i < N_THREADS; i++) { tidx[i] = (int) i; retcode = pthread_create(thread + i, 0, run, (void *) (tidx + i)); handle_thread_error(retcode, "creating thread failed", PROCESS_EXIT); } printf("in parent: setting up\\n"); pthread_mutex_init(&mutex, 0); sleep(2); printf("in parent: getting mutex\\n"); if (use_timeout) { while (TRUE) { retcode = pthread_mutex_timedlock(&mutex, &timeout); if (retcode == 0) { break; } else if (retcode == ETIMEDOUT) { printf("timed out in parent\\n"); } else { handle_thread_error(retcode, "parent failed (timed)lock", PROCESS_EXIT); } } } else { retcode = pthread_mutex_lock(&mutex); handle_thread_error(retcode, "parent failed lock", PROCESS_EXIT); } printf("parent got mutex\\n"); sleep(5); printf("parent releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("parent released mutex\\n"); printf("parent waiting for child to terminate\\n"); for (size_t i = 0; i < N_THREADS; i++) { retcode = pthread_join(thread[i], 0); handle_thread_error(retcode, "join failed", PROCESS_EXIT); printf("joined thread %d\\n", (int) i); } pthread_mutex_destroy(&mutex); printf("done\\n"); exit(0); }
0
#include <pthread.h> pthread_mutex_t tmutex[5] = {PTHREAD_MUTEX_INITIALIZER}; pthread_t pid[5]; int mutexcount = 0; void* func(void* args) { int arc = (int*)args; srand((unsigned int)time(0)); while(1) { sleep(5); if (lockfull()) { continue; } if (arc == 0) { pthread_mutex_lock(&tmutex[4]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, 4, (long)time(0)); pthread_mutex_lock(&tmutex[0]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, 0, (long)time(0)); pthread_mutex_unlock(&tmutex[4]); mutexcount--; pthread_mutex_unlock(&tmutex[0]); mutexcount--; continue; } if (arc == 4) { pthread_mutex_lock(&tmutex[3]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, 3, (long)time(0)); pthread_mutex_lock(&tmutex[4]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, 4, (long)time(0)); pthread_mutex_unlock(&tmutex[3]); mutexcount--; pthread_mutex_unlock(&tmutex[4]); mutexcount--; continue; } pthread_mutex_lock(&tmutex[arc-1]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, arc-1, (long)time(0)); pthread_mutex_lock(&tmutex[arc]); mutexcount++; printf("I am zhexuejia: %d, I get kuaizi: %d, time is %ld.\\n", arc, arc, (long)time(0)); pthread_mutex_unlock(&tmutex[arc-1]); mutexcount--; pthread_mutex_unlock(&tmutex[arc]); mutexcount--; } } int lockfull() { return mutexcount>3 ? 1 : 0; } int main() { for (int i=0; i<5; i++) { if (pthread_create(&pid[i], 0, func, (void*)i)) { return -1; } } while(1) { sleep(10); } return 0; }
1
#include <pthread.h> void *functionC(); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main() { int rc1, rc2; pthread_t thread1, thread2; if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc1); } if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) ) { printf("Thread creation failed: %d\\n", rc2); } printf("Hello from main\\n"); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Exit from main\\n"); return 0; exit(0); } void *functionC() { pthread_mutex_lock( &mutex1 ); counter++; printf("Counter value: %d\\n",counter); pthread_mutex_unlock( &mutex1 ); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int count; } semaphore_t; void init_sem(semaphore_t *s, int i) { s->count = i; pthread_mutex_init(&(s->mutex), 0); pthread_cond_init(&(s->cond), 0); } void P(semaphore_t *sem) { pthread_mutex_lock (&(sem->mutex)); sem->count--; if (sem->count < 0) pthread_cond_wait(&(sem->cond), &(sem->mutex)); pthread_mutex_unlock (&(sem->mutex)); } void V(semaphore_t * sem) { pthread_mutex_lock (&(sem->mutex)); sem->count++; if (sem->count <= 0) { } pthread_mutex_unlock (&(sem->mutex)); pthread_yield_np(); } semaphore_t mutex; void function_1(void) { while (1){ P(&mutex); printf("Beginning of CS: func 1\\n"); sleep(1); printf("End of CCS: func 1..\\n"); sleep(1); V(&mutex); } } void function_2(void) { while (1){ P(&mutex); printf("Beginning of CS: func 2\\n"); sleep(1); printf("End of CCS: func 2..\\n"); sleep(1); V(&mutex); } } void function_3(void) { while (1){ P(&mutex); printf("Beginning of CS: func 3\\n"); sleep(1); printf("End of CCS: func 3..\\n"); sleep(1); V(&mutex); } } int main() { init_sem(&mutex, 2); start_thread(function_1, 0); start_thread(function_2, 0); start_thread(function_3, 0); while(1) sleep(1); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t full; sem_t empty; int top = 0; int bottom = 0; void *produce(void *arg) { int i; for (i = 0; i < 5 * 2; i++) { printf("producer is pushing data\\n"); sem_wait(&empty); pthread_mutex_lock(&mutex); top = (top + 1) % 5; printf("now top is %d\\n", top); pthread_mutex_unlock(&mutex); sem_post(&full); } return (void *)1; } void *consume(void *arg) { int i; for (i = 0; i < 5 * 2; i++) { printf("consumer is pulling data\\n"); sem_wait(&full); pthread_mutex_lock(&mutex); bottom = (bottom + 1) % 5; printf("now bottom is %d\\n", bottom); pthread_mutex_unlock(&mutex); sem_post(&empty); } return (void *)2; } int main(int argc, char *argv[]) { pthread_t thid1; pthread_t thid2; pthread_t thid3; pthread_t thid4; int ret1; int ret2; int ret3; int ret4; sem_init(&full, 0, 0); sem_init(&empty, 0, 5); pthread_create(&thid1, 0, produce, 0); pthread_create(&thid2, 0, consume, 0); pthread_create(&thid3, 0, produce, 0); pthread_create(&thid4, 0, consume, 0); pthread_join(thid1, (void **)&ret1); pthread_join(thid2, (void **)&ret2); pthread_join(thid3, (void **)&ret3); pthread_join(thid4, (void **)&ret4); return 0; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_nonzero; void *inc_count(void *t) { long id = (long)t; pthread_mutex_lock(&count_mutex); if (count == 0) pthread_cond_signal(&count_nonzero); count = count + 1; printf("Thread %ld updated count as %d\\n",id , count); pthread_mutex_unlock(&count_mutex); } void *dec_count(void *t) { long id = (long)t; pthread_mutex_lock(&count_mutex); if(count == 0) pthread_cond_wait(&count_nonzero, &count_mutex); count -= 1; printf("Thread %ld updated count as %d\\n",id , count); pthread_mutex_unlock(&count_mutex); } int main() { pthread_t threads[2]; int tid[2] ; tid[0] = 1; tid[1] = 2; int i ; pthread_create(&threads[0] ,0 , inc_count , (void*)tid[0]); pthread_create(&threads[1] ,0 , dec_count ,(void*)tid[1]); for( i = 0 ; i < 2 ; i++) pthread_join(threads[i] ,0); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_nonzero); pthread_exit(0); }
1
#include <pthread.h> int somme = 0; int nb_somme = 0; pthread_mutex_t mutex_somme = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_print = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_print = PTHREAD_COND_INITIALIZER; void *thread_rand(void *arg) { int* i = (int*)malloc(sizeof(int)); *i = *(int *)arg; free(arg); int random_val = (int)(10*((double)rand())/ 32767); printf("Thread num%d, tid%d, random_val%d\\n",*i, (int) pthread_self(), random_val); pthread_mutex_lock(&mutex_somme); somme += random_val; pthread_mutex_unlock(&mutex_somme); pthread_mutex_lock(&mutex_print); nb_somme++; pthread_cond_signal(&cond_print); pthread_mutex_unlock(&mutex_print); (*i) *= 2; pthread_exit((void*)i); return 0; } void *print_thread(void *arg) { pthread_mutex_lock(&mutex_print); while(nb_somme < 5) pthread_cond_wait(&cond_print, &mutex_print); pthread_mutex_unlock(&mutex_print); printf("Somme valeurs aleatoires = %d\\n", somme); pthread_exit((void *)0); return ((void *)0); } int main(int argc, char** argv) { pthread_t tid[5]; pthread_t tid_print; int *pt_ind; if ( pthread_create(&tid_print, 0, print_thread, 0)){ perror("error : pthread_create\\n"); exit(1); } int i = -1; while ( ++i < 5 ){ pt_ind = (int*) malloc(sizeof(i)); *pt_ind = i; if ( pthread_create(&(tid[i]), 0, thread_rand, (void *)pt_ind)){ perror("error : pthread_create\\n"); exit(1); } } i = -1; int* s_retour; while ( ++i < 5 ){ if ( pthread_join(tid[i], (void **)&s_retour) ){ perror("error : pthread_join\\n"); exit(1); } printf("Main : thread %d terminé, status = %d\\n",i,*s_retour); free(s_retour); } if ( pthread_join(tid_print, 0) ){ perror("error : pthread_join\\n"); exit(1); } printf("Tous les threads sont terminés\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t esperaPares; pthread_cond_t esperaImpares; int turnoImpares=1; pthread_mutex_t mtx; pthread_cond_t esperaBarrera; int hilosespera=0; void barrera(){ pthread_mutex_lock(&mtx); hilosespera++; while (hilosespera<2 ) pthread_cond_wait(&esperaBarrera, &mtx); pthread_cond_signal(&esperaBarrera); pthread_mutex_unlock(&mtx); } void *pares(void *kk) { int i; for(i=2; i <= 10; i=i+2 ) { pthread_mutex_lock(&mutex); while (turnoImpares ) pthread_cond_wait(&esperaPares, &mutex); printf ("Pares: %d\\n", i); turnoImpares=1; pthread_cond_signal(&esperaPares); pthread_mutex_unlock(&mutex); } barrera(); printf ("FIN PARES\\n"); pthread_exit(0); } void *impares(void *kk) { int i; for(i=1; i <= 10; i=i+2 ) { pthread_mutex_lock(&mutex); while (!turnoImpares) pthread_cond_wait(&esperaPares, &mutex); printf ("Impares: %d\\n", i); turnoImpares=0; pthread_cond_signal(&esperaPares); pthread_mutex_unlock(&mutex); } barrera(); printf ("FIN IMPARES\\n"); pthread_exit(0); } int main(int argc, char *argv[]){ pthread_t th1, th2; pthread_mutex_init(&mtx, 0); pthread_cond_init(&esperaBarrera, 0); pthread_mutex_init(&mutex, 0); pthread_cond_init(&esperaPares, 0); pthread_cond_init(&esperaImpares, 0); pthread_create(&th1, 0, pares, 0); pthread_create(&th2, 0, impares, 0); pthread_join(th1, 0); pthread_join(th2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&esperaPares); pthread_cond_destroy(&esperaImpares); exit(0); }
1
#include <pthread.h> int philo_states[NPHILO] = { '-' }; int philo_states_restore[NPHILO] = { 0 }; int sticks[NPHILO] = { 0 }; pthread_cond_t philo_conditions[NPHILO]; pthread_mutex_t stick_mutex; pthread_mutex_t print_mutex; pthread_barrier_t barrierSingle; pthread_barrier_t barrierAll; char philo_commands[NPHILO] = { COMMAND_EMPTY }; sem_t philo_sem[NPHILO]; int DEBUGGING = TRUE; void *philo(void *arg){ int key = *((int *) arg); pthread_barrier_wait(&barrierSingle); pthread_barrier_wait(&barrierAll); while(TRUE){ think(key); get_sticks(key); eat(key); put_sticks(key); } } void think(int key){ philo_states[key] = THINK; disp_philo_states(); int i; for( i = 0; i <= THINK_LOOP ; i++ ){ check_commands(key); if(philo_commands[key] == COMMAND_TO_PROCEED){ philo_commands[key] = COMMAND_EMPTY; } } } void get_sticks(int key){ philo_states[key] = HUNGRY; disp_philo_states(); pthread_mutex_lock(&stick_mutex); while(sticks[left_stick(key)] != FREE || sticks[right_stick(key)] != FREE ){ debugging_message("Thread will be blocked, because of at least one stick is in use.",NULLINT); pthread_cond_wait(&(philo_conditions[key]),&stick_mutex); debugging_message("Thread will be unblocked, sticks are now free.",NULLINT); } sticks[left_stick(key)] = IN_USE; sticks[right_stick(key)] = IN_USE; pthread_mutex_unlock(&stick_mutex); } void eat(int key){ philo_states[key] = EAT; disp_philo_states(); int i; for( i = 0 ; i < EAT_LOOP ; i++ ){ check_commands(key); if(philo_commands[key] == COMMAND_TO_PROCEED){ philo_commands[key] = COMMAND_EMPTY; } } } void put_sticks(int key){ pthread_mutex_lock(&stick_mutex); sticks[left_stick(key)] = FREE; sticks[right_stick(key)] = FREE; debugging_message("Informing his neighbours about the free sticks.",NULLINT); pthread_cond_signal(&philo_conditions[left_neighbor(key)]); pthread_cond_signal(&philo_conditions[right_neighbor(key)]); philo_states[key] = THINK; pthread_mutex_unlock(&stick_mutex); } void disp_philo_states(){ pthread_mutex_lock(&print_mutex); int i; for( i = 0 ; i < NPHILO ; i++ ){ printf("%i %c\\t",i,philo_states[i]); } if(neighbors_are_eating() == TRUE){ printf("\\n TAKE CARE!!! There are two neighbor philosophs eating. Check it out!\\n"); exit(1); } printf("\\n"); pthread_mutex_unlock(&print_mutex); } void check_commands(int key){ if(philo_commands[key] == COMMAND_FOR_QUIT1){ pthread_exit(0); } if(philo_commands[key] == COMMAND_TO_BLOCK){ philo_commands[key] = COMMAND_EMPTY; sem_wait(&philo_sem[key]); } } int left_stick(int key){ return key % NPHILO; } int right_stick(int key){ return (( key + DISTANCE_TO_NEXT_STICK ) % NPHILO); } int left_neighbor(int key){ return (key-1 < 0 ? NPHILO-1 : key-1); } int right_neighbor(int key){ return ((key + DISTANCE_TO_NEXT_NEIGHBOR) % NPHILO); } int neighbors_are_eating(){ int i; for( i = 0 ; i < NPHILO ; i++ ){ if( philo_states[i] == EAT && philo_states[right_neighbor(i)] == EAT ){ return TRUE; } } return FALSE; } void debugging_message(char message[],int key){ if(DEBUGGING == TRUE){ pthread_mutex_lock(&print_mutex); printf(message,key); printf("\\n"); pthread_mutex_unlock(&print_mutex); } }
0
#include <pthread.h> static pthread_mutex_t mutex; static pthread_cond_t teller_available; int id; int checked_in; int doing_service; pthread_cond_t done; pthread_t thread; struct teller_info_t *next; } *p_teller; static p_teller teller_list = 0; void teller_check_in(p_teller teller) { pthread_mutex_lock(&mutex); pthread_cond_init(&teller->done, 0); teller->checked_in = 1; teller->doing_service = 0; if (teller_list != 0) { teller->next = teller_list; teller_list = teller; } else { teller_list = teller; } pthread_cond_signal(&teller_available); pthread_mutex_unlock(&mutex); } void teller_check_out(p_teller teller) { pthread_mutex_lock(&mutex); while (teller->doing_service) { pthread_cond_wait(&teller->done, &mutex); } if (teller == teller_list) { teller_list = teller_list->next; } else { p_teller tmp = teller_list; while (tmp->next != teller) { tmp = tmp->next; } tmp->next = teller->next; } teller->checked_in = 0; pthread_mutex_unlock(&mutex); } p_teller do_banking(int customer_id) { pthread_mutex_lock(&mutex); while(teller_list == 0) { pthread_cond_wait(&teller_available, &mutex); } p_teller teller = teller_list; teller_list = teller_list->next; teller->next = 0; printf("Customer %d is served by teller %d\\n", customer_id, teller->id); teller->doing_service = 1; pthread_mutex_unlock(&mutex); return teller; } void finish_banking(int customer_id, p_teller teller) { pthread_mutex_lock(&mutex); printf("Customer %d is done with teller %d\\n", customer_id, teller->id); teller->doing_service = 0; teller->next = teller_list; teller_list = teller; pthread_cond_signal(&teller_available); pthread_cond_signal(&teller->done); pthread_mutex_unlock(&mutex); } void* teller(void *arg) { p_teller me = (p_teller) arg; teller_check_in(me); while(1) { int r = rand(); if (r < (0.05 * 32767)) { if (me->checked_in) { printf("teller %d checks out\\n", me->id); teller_check_out(me); } else { printf("teller %d checks in\\n", me->id); teller_check_in(me); } } } } void* customer(void *arg) { int id = (uintptr_t) arg; while (1) { int r = rand(); if (r < (0.1 * 32767)) { p_teller teller = do_banking(id); sleep(r % 4); finish_banking(id, teller); } } } int main(void) { srand(time(0)); struct teller_info_t tellers[3]; int i; pthread_mutex_init(&mutex, 0); pthread_cond_init(&teller_available, 0); for (i=0; i<3; i++) { tellers[i].id = i; tellers[i].next = 0; pthread_create(&tellers[i].thread, 0, teller, (void*)&tellers[i]); } pthread_t thread; for (i=0; i<5; i++) { pthread_create(&thread, 0, customer, (void*)(uintptr_t) i); } for (i=0; i<3; i++) { pthread_join(tellers[i].thread, 0); } return 0; }
1
#include <pthread.h> static pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare( void ) { printf( "preparing locks...\\n" ); pthread_mutex_lock( &lock1 ); pthread_mutex_lock( &lock2 ); } void parent( void ) { printf( "parent unlocking locks...\\n" ); pthread_mutex_unlock( &lock1 ); pthread_mutex_unlock( &lock2 ); } void child( void ) { printf( "child unlocking locks...\\n" ); pthread_mutex_unlock( &lock1 ); pthread_mutex_unlock( &lock2 ); } void *thread_run( void *arg ) { printf( "thread started...\\n" ); pause(); return (void *) 0; } int main( void ) { int err; pid_t pid; pthread_t tid; if ( (err = pthread_atfork( prepare, parent, child )) != 0 ) { err_exit( err, "cannot install fork handlers" ); } err = pthread_create( &tid, 0, thread_run, 0 ); if ( err != 0 ) { err_exit( err, "cannot create thread" ); } sleep( 2 ); printf( "parent about to fork...\\n" ); if ( (pid = fork()) < 0 ) { err_quit( "fork failed" ); } else if ( pid == 0 ) { printf( "child returned from fork\\n" ); } else { printf( "parent returned from fork\\n" ); } return 0; }
0
#include <pthread.h> int g_itemnum; struct { pthread_mutex_t mutex; int buff[(100000)]; int nindex; int nvalue; } shared = { PTHREAD_MUTEX_INITIALIZER }; void* producer(void*); void* consumer(void*); int main(int argc, char **argv) { int i; int threadnum, threadcount[(10)]; pthread_t tid_producer[(10)], tid_consumer; if (3 != argc) { printf("usage: %s <item_num> <thread_num>\\n", argv[0]); } g_itemnum = ((atoi(argv[1])) > ((100000)) ? ((100000)) : (atoi(argv[1]))); threadnum = ((atoi(argv[2])) > ((10)) ? ((10)) : (atoi(argv[2]))); printf("item = %d, thread = %d\\n", g_itemnum, threadnum); pthread_setconcurrency(threadnum); for (i = 0; i < threadnum; ++i) { threadcount[i] = 0; if (0 != pthread_create(&tid_producer[i], 0, producer, (void*)&threadcount[i])) { printf("pthread_create error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] created, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } for (i = 0; i < threadnum; ++i) { if (0 != pthread_join(tid_producer[i], 0)) { printf("pthread_join error producer %d\\n", i); exit(1); } printf("producer: thread[%lu] done, threadcount[%d] = %d\\n", tid_producer[i], i, threadcount[i]); } if (0 != pthread_create(&tid_consumer, 0, consumer, 0)) { printf("pthread_create error consumer\\n"); } printf("consumer: thread[%lu] created\\n", tid_consumer); if (0 != pthread_join(tid_consumer, 0)) { printf("pthread_join error consumer\\n"); } printf("consumer: thread[%lu] done\\n", tid_consumer); exit(0); } void* producer(void *arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nindex >= g_itemnum) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[shared.nindex] = shared.nvalue; shared.nindex++; shared.nvalue++; pthread_mutex_unlock(&shared.mutex); *((int*)arg) += 1; } return 0; } void* consumer(void *arg) { int i; for (i = 0; i < g_itemnum; ++i) { if (shared.buff[i] != i) { printf("error: buff[%d] = %d\\n", i, shared.buff[i]); } } return 0; }
1
#include <pthread.h> struct msgs{ long msgtype; char msg_text[512]; }; static int num = 2; struct prodcons { char buf[16]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; struct prodcons buffer; void init(struct prodcons * b) { pthread_mutex_init(&b->lock,0); pthread_cond_init(&b->notempty,0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct prodcons *p,void * message) { char date[512]; memset(date, 0x00, 512); memcpy(date,(char *)message, sizeof(message)); pthread_mutex_lock(&p->lock); if((p->writepos+1)%16 == p->readpos) { pthread_cond_wait(&p->notfull,&p->lock); } p->buf[p->writepos] = (void *)message; p->writepos++; if(p->writepos >= 16) p->writepos = 0; pthread_cond_signal(&p->notempty); pthread_mutex_unlock(&p->lock); } char * get(struct prodcons *b) { char date[512]; memset(date, 0x00, 512); pthread_mutex_lock(&b->lock); if(b->writepos == b->readpos) { pthread_cond_wait(&b->notempty,&b->lock); } *date = b->buf[b->readpos]; b->readpos++; if(b->readpos >=16) b->readpos = 0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return date; } void * product(void * arg) { put(&buffer,arg); } void *consumer() { char * date ; while(1) { date = get(&buffer); } } int main() { pthread_t pthread_id[num]; pthread_t pthread_id3; pthread_t pthread_id2; pthread_t pthread_id4; int ret; int i; struct msgs msg; key_t key; int pid; pid = msgget(1024,IPC_CREAT | 0666); init(&buffer); while(1) { if(msgrcv(pid,(void *)&msg, 512,0,0) < 0) { printf(" msg failed,errno=%d[%s]\\n",errno,strerror(errno)); } printf("The Key is %d\\n",pid); printf("The buf is %s\\n",msg.msg_text); } for(i = 0; i < num; i++) { ret = pthread_create(&pthread_id[i], 0, (void*)product,(void *)msg.msg_text); if(ret != 0 ) { printf("pthread_create error\\n"); return -1; } } for(i = 0; i < num ;i++) { ret = pthread_create(&pthread_id[i], 0, (void*)consumer,0); if(ret != 0 ) { printf("pthread_create error\\n"); return -1; } } for(i = 0; i < num; i++) { pthread_join(pthread_id[i], 0); } return 0; }
0
#include <pthread.h> int tid; pthread_mutex_t * p2c; pthread_mutex_t * c2p; int numVerts; int numThr; int** M_prev; int** M_curr; } pt_mat; void *Thr(void *thrargs) { struct pt_mat *mat; mat = (struct pt_mat *)thrargs; int t = (mat->tid); int i,j,k; for(k=0; k<(mat->numVerts); k++) { pthread_mutex_lock( &(mat->p2c[t]) ); for (i = t; i < (mat->numVerts); i+=(mat->numThr)) { for(j = 0; j < (mat->numVerts); j++) { if ( ( (mat->M_prev[k][j])==1 && (mat->M_prev[i][k]) ) || (mat->M_prev[i][j])==1 ) (mat->M_curr[i][j]) = 1; } } pthread_mutex_unlock(&(mat->c2p[t])); } pthread_exit (0) ; } int wtc_thr(int nThr, int nVerts, int** matrix) { struct timeval startt, endt; gettimeofday(&startt, 0 ); pthread_t* thra = (pthread_t*)malloc(sizeof(pthread_t)*nThr); int i,j; pt_mat** matsrc = (pt_mat**)malloc(sizeof(pt_mat*)*nThr); for(i=0; i<nThr; i++){ matsrc[i] = (pt_mat*)malloc(sizeof(pt_mat));; } int** cmatrix = (int**)malloc(nVerts*sizeof(int*)); for(i=0; i<nVerts; i++){ cmatrix[i] = (int*)malloc(nVerts*sizeof(int)); for(j = 0; j<nVerts; j++){ cmatrix[i][j]=0; } } pthread_mutex_t * p2c = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*nThr); pthread_mutex_t * c2p = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*nThr); int k; for(k=0; k<nThr; k++) { pthread_mutex_init(&p2c[k], 0); pthread_mutex_init(&c2p[k], 0); pthread_mutex_lock(&p2c[k]); pthread_mutex_lock(&c2p[k]); } int rc; for (k=0; k<nThr; k++) { matsrc[k]->tid = k; matsrc[k]->M_prev = matrix; matsrc[k]->M_curr = cmatrix; matsrc[k]->numVerts = nVerts; matsrc[k]->numThr = nThr; matsrc[k]->p2c = p2c; matsrc[k]->c2p = c2p; rc = pthread_create(&thra[k], 0, Thr, (void *)matsrc[k]) ; if( rc ) { exit( -1 ); } } int m,y,z; for (m=0; m<nVerts;m++) { for(k=0;k<nThr;k++){pthread_mutex_unlock(&p2c[k]);} for(k=0;k<nThr;k++){ pthread_mutex_lock(&c2p[k]); } for(y=0; y<nVerts; y++) { for(z=0; z<nVerts; z++) { matrix[y][z]=cmatrix[y][z]; } } } for (k=0; k<nThr; k++) { pthread_join( thra[k], 0 ); pthread_mutex_destroy(&p2c[k]); pthread_mutex_destroy(&c2p[k]); } free(c2p); free(p2c); free(thra); for(i=0; i<nThr; i++){ free(matsrc[i]); } free(matsrc); for(i=0; i<nVerts; i++){ free(cmatrix[i]); } free(cmatrix); printf("Output:\\n"); printMatrix(matrix, nVerts); gettimeofday(&endt, 0); int elapsedTime; elapsedTime = (endt.tv_usec - startt.tv_usec); return 0; } void *transitive_closure_thread_worker(void *); int wtc_btthr(char *argv) { struct timeval t0; struct timeval t1; int i; long elapsed; data_matrix = read_file(argv, &number_of_threads, &number_of_nodes, "wtc_btthr"); threads = (pthread_t *)malloc(sizeof(pthread_t)*number_of_threads); pthread_mutex_init(&mutexmatrix, 0); pthread_mutex_init(&mutexqueue, 0); pthread_barrier_init(&barrier, 0, number_of_threads+1); pthread_barrier_init(&kbarrier, 0, number_of_threads+1); queue = number_of_nodes; gettimeofday(&t0, 0); for(i = 0; i < number_of_threads; ++i) { pthread_create(&threads[i], 0, transitive_closure_thread_worker, 0); } for(k = 0; k < number_of_nodes;) { pthread_mutex_lock(&mutexqueue); queue = 10; pthread_mutex_unlock(&mutexqueue); pthread_barrier_wait(&kbarrier); pthread_barrier_wait(&barrier); ++k; pthread_barrier_wait(&kbarrier); } for(i = 0; i < number_of_threads; ++i) { pthread_join(threads[i], 0); } gettimeofday(&t1, 0); elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec; print_matrix(data_matrix, number_of_nodes); printf("Time: %lu us\\n", elapsed); free(data_matrix); free(threads); pthread_mutex_destroy(&mutexmatrix); pthread_mutex_destroy(&mutexqueue); pthread_barrier_destroy(&barrier); pthread_barrier_destroy(&kbarrier); return 0; } void *transitive_closure_thread_worker(void *arg) { int i; int j; int result; unsigned ik; while(k < number_of_nodes) { pthread_barrier_wait(&kbarrier); while(queue != -1) { pthread_mutex_lock(&mutexqueue); if(queue != -1) { i = queue; queue--; } pthread_mutex_unlock(&mutexqueue); ik = bit_array_get(data_matrix, i*number_of_nodes+k); for(j = 0; j < number_of_nodes; ++j) { pthread_mutex_lock(&mutexmatrix); result = (ik && bit_array_get(data_matrix, k*number_of_nodes+j)); if(result == 1) { bit_array_set(data_matrix, i*number_of_nodes+j); } pthread_mutex_unlock (&mutexmatrix); } } pthread_barrier_wait(&barrier); pthread_barrier_wait(&kbarrier); } return 0; }
1
#include <pthread.h> int n; int p; int c; int x; int p_time; int c_time; int size; int* queue; pthread_mutex_t lock; sem_t empty; sem_t full; void producer(); void consumer(); int main(int argc, char** argv) { int elapsed; int i; time_t begin; time_t end; n = atoi(argv[1]); p = atoi(argv[2]); c = atoi(argv[3]); x = atoi(argv[4]); p_time = atoi(argv[5]); c_time = atoi(argv[6]); size = 0; queue = malloc(n * sizeof(int)); pthread_t producers[p]; pthread_t consumers[c]; sem_init(&empty, 0, n); sem_init(&full, 0, 0); pthread_mutex_init(&lock, 0); begin = time(0); printf("%s\\n", asctime(localtime(&begin))); for(i = 0; i < p; i++) { pthread_create(&producers[i], 0, (void *)producer, 0); } for(i = 0; i < c; i++) { pthread_create(&consumers[i], 0, (void *)consumer, 0); } for(i = 0; i < p; i++) { pthread_join(producers[i], 0); } for(i = 0; i < c; i++) { pthread_join(consumers[i], 0); } end = time(0); elapsed = end - begin; printf("\\n%s", asctime(localtime(&end))); printf("Time elapsed: %d seconds.\\n", elapsed); free(queue); pthread_mutex_destroy(&lock); sem_destroy(&full); sem_destroy(&empty); return 0; } void producer() { int i; fprintf(stderr, "producer:> begin\\n"); do { sem_wait(&empty); pthread_mutex_lock(&lock); sleep(1); for(i = 0; i < p; i++) { if(n > size) { size += 1; queue[size-1] = rand(); fprintf(stderr, "producer:> enqueue queue[%d] = %d\\n", size, queue[size-1]); } } fprintf(stderr, "producer:> size = %d\\n", size); pthread_mutex_unlock(&lock); sem_post(&full); sleep(p_time); } while(n > size); fprintf(stderr, "producer:> end\\n"); } void consumer() { int i; fprintf(stderr, "consumer:> begin\\n"); do { sem_wait(&full); pthread_mutex_lock(&lock); sleep(1); for(i = 0; i < (int)p*(x/c); i++) { if(size > 0) { fprintf(stderr, "consumer:> dequeue queue[%d] = %d\\n", size, queue[size-1]); size -= 1; } } fprintf(stderr, "consumer:> size = %d\\n", size); pthread_mutex_unlock(&lock); sem_post(&empty); sleep(c_time); } while(size > 0); fprintf(stderr, "consumer:> end\\n"); }
0
#include <pthread.h> pthread_mutex_t sillas_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t esperando_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_sentarse = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_sentado = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_comer = PTHREAD_COND_INITIALIZER; int sillas_libres = 4; int enanos_esperando = 0; void *enano(void *arg); void *blancanieves (void *arg); void trabajar_mina(); int main(){ srand(time(0)); int i; pthread_t *enanos_t = (pthread_t*)malloc(7*sizeof(pthread_t)); pthread_t blancanieves_t; pthread_create(&blancanieves_t,0,blancanieves,0); for (i=0;i<7;++i){ pthread_create(enanos_t+i,0,enano,i); } for (i=0;i<7;++i){ pthread_join(*(enanos_t+i),0); } pthread_join(blancanieves_t,0); free(enanos_t); return 0; } void *enano(void *arg){ int id = (int)arg; while (1){ trabajar_mina(id); printf("Enano %d: me quiero sentar en la silla\\n",id); int sentado = 0; while (!sentado){ pthread_mutex_lock(&sillas_mutex); if (sillas_libres > 0){ sillas_libres--; sentado = 1; printf("Enano %d: Ya me sente\\n",id); pthread_mutex_lock(&esperando_mutex); ++enanos_esperando; pthread_mutex_unlock(&esperando_mutex); } else { printf("Enano %d: me toca esperar a que se libere una silla\\n",id); pthread_cond_wait(&cond_sentarse,&sillas_mutex); } } pthread_mutex_unlock(&sillas_mutex); pthread_cond_signal(&cond_sentado); pthread_mutex_lock(&esperando_mutex); pthread_cond_wait(&cond_comer,&esperando_mutex); pthread_mutex_unlock(&esperando_mutex); printf("Enano %d: ya estoy comiendo, a trabajar de nuevo\\n",id); sleep(4); pthread_mutex_lock(&sillas_mutex); printf("Enano %d: me pare de la silla\\n",id); sillas_libres++; pthread_mutex_unlock(&sillas_mutex); } pthread_exit(0); } void *blancanieves(void *arg){ while (1){ pthread_mutex_lock(&sillas_mutex); if (sillas_libres == 0){ printf("Me voy a dar un paseo\\n"); pthread_cond_wait(&cond_sentado,&sillas_mutex); } pthread_mutex_unlock(&sillas_mutex); pthread_mutex_lock(&esperando_mutex); if (enanos_esperando > 0){ printf("Voy a cocinar para un enanito\\n"); pthread_cond_signal(&cond_comer); --enanos_esperando; } pthread_mutex_unlock(&esperando_mutex); } pthread_exit(0); } void trabajar_mina(int i){ int tiempo_trabajo = rand() % 10; printf("Yohooo yohooo ---- Soy el enano %d y voy a trabajar %d ------ Yohoooo yohooooo\\n",i,tiempo_trabajo); sleep(tiempo_trabajo); }
1
#include <pthread.h> static int connect_downstream ( struct JH_server_worker worker [const restrict static 1] ) { struct sockaddr_un addr; const int old_errno = errno; errno = 0; if ((worker->downstream_socket = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { JH_FATAL ( stderr, "Unable to create socket: %s.", strerror(errno) ); errno = old_errno; return -1; } errno = old_errno; memset((void *) &addr, (int) 0, sizeof(addr)); addr.sun_family = AF_UNIX; strncpy ( (char *) addr.sun_path, JH_parameters_get_dest_socket_name(worker->params.server_params), (sizeof(addr.sun_path) - ((size_t) 1)) ); errno = 0; if ( connect ( worker->downstream_socket, (struct sockaddr *) &addr, sizeof(addr) ) == -1 ) { JH_FATAL ( stderr, "Unable to connect to address: %s.", strerror(errno) ); errno = old_errno; close(worker->downstream_socket); worker->downstream_socket = -1; return -1; } errno = old_errno; return 0; } static int initialize ( struct JH_server_worker worker [const restrict static 1], void * input ) { memcpy ( (void *) &(worker->params), (const void *) input, sizeof(struct JH_server_thread_parameters) ); pthread_barrier_wait(&(worker->params.thread_collection->barrier)); return connect_downstream(worker); } static void finalize ( struct JH_server_worker worker [const restrict static 1] ) { if (worker->downstream_socket != -1) { close(worker->downstream_socket); worker->downstream_socket = -1; } if (worker->params.socket != -1) { close(worker->params.socket); worker->params.socket = -1; } pthread_mutex_lock(&(worker->params.thread_collection->mutex)); worker->params.thread_collection->threads[worker->params.thread_id].state = JH_SERVER_JOINING_THREAD; pthread_mutex_unlock(&(worker->params.thread_collection->mutex)); } void * JH_server_worker_main (void * input) { int status; int timeout_count; struct JH_filter filter; struct JH_server_worker worker; initialize(&worker, input); if (JH_filter_initialize(&filter) < 0) { finalize(&worker); return 0; } timeout_count = 0; while (JH_server_is_running()) { status = JH_filter_step ( &filter, worker.params.socket, worker.downstream_socket ); if (status == 0) { timeout_count = 0; } else if (status == 1) { timeout_count += 1; if (timeout_count == 2) { break; } else { sleep(JH_SERVER_WORKER_MAX_WAITING_TIME); } } else { break; } } JH_filter_finalize(&filter); finalize(&worker); return 0; }
0
#include <pthread.h> int count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_route(void *args) { int i = 0; for (i = 0; i < (int)args; i++) { pthread_mutex_lock(&mutex); count++; printf("c: count: %d\\n", count); pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char *argv[]) { int i = 0; int loop = 1000; pthread_t tid; pthread_create(&tid, 0, thread_route, (void *)loop); for (i = 0; i < loop; i++) { pthread_mutex_lock(&mutex); count++; printf("p: count: %d\\n", count); pthread_mutex_unlock(&mutex); } pthread_join(tid, 0); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); } printf("watch_count(): thread %ld Updating the value of count...\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count= %d. Going into wait...\\n", my_id,count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id,count); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
1
#include <pthread.h> pthread_mutex_t lock1,lock2; { int val; struct node* next; }node; node *start='\\0'; node *getnode(int a) { node *temp=malloc (sizeof(node)); temp->val=a; temp->next='\\0'; return temp; } void insert(int a) { if(start=='\\0') start=getnode(a); else { node *temp=start; while(temp->next!='\\0') temp=temp->next; temp->next=getnode(a); } } void display() { node *temp=start; while(temp!='\\0') { printf("%d ",temp->val); temp=temp->next; } printf("\\n"); } void *delete() { pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); node *temp=start,*p='\\0'; int n; printf("\\nEnter value to delete "); scanf("%d",&n); if (start=='\\0') printf("Empty\\n"); else if(start->val==n) { start=start->next; temp->next='\\0'; free(temp); } else { while(temp!='\\0') { if(temp->val==n) { p->next=temp->next; temp->next='\\0'; free(temp); break; } p=temp; temp=temp->next; } } pthread_mutex_unlock(&lock2); pthread_mutex_unlock(&lock1); } int main() { int a,ex; pthread_t tid; while(1) { printf("1.Insert\\n"); printf("2.Delete\\n"); printf("3.Display\\n"); printf("4.Exit\\n"); printf("Enter: =>"); scanf("%d",&ex); switch(ex) { case 1:printf("Enter value "); scanf("%d",&a); insert(a); break; case 2: pthread_create(&tid,0,delete,0); pthread_join(tid,0); break; case 3:display(); break; case 4:exit(0); } } return 0; }
0
#include <pthread.h> struct queue { int a; int available; int arr[20]; int front; int count; int inserted; int deleted; pthread_mutex_t mutex; pthread_cond_t produce_more; pthread_cond_t consume_more; }; void do_some_work(int); int done = 0; void queue_init(queue *q) { pthread_mutex_init(&q->mutex, 0); pthread_cond_init(&q->produce_more, 0); pthread_cond_init(&q->consume_more, 0); q->front = 0; q->count = 0; q->inserted = 0; q->deleted = 0; } int is_empty(queue *q) { assert(q->count >=0 && q->count <= 20); pthread_mutex_lock(&q->mutex); int loc = q->count; pthread_mutex_unlock(&q->mutex); return(loc == 0); } int is_full(queue *q) { assert(q->count >=0 && q->count <= 20); pthread_mutex_lock(&q->mutex); int loc = q->count; pthread_mutex_unlock(&q->mutex); return(loc == 20); } int enqueue(queue *q, int a) { pthread_mutex_lock(&q->mutex); int rc = 0; while(q->count == 20 && rc == 0) { rc = pthread_cond_wait(&q->produce_more, &q->mutex); } q->arr[(q->front + q->count ) % 20] = a; q->count++; q->inserted++; assert(q->count >=0 && q->count <= 20); pthread_cond_signal(&q->consume_more); pthread_mutex_unlock(&q->mutex); return 0; } int dequeue(queue *q) { pthread_mutex_lock(&q->mutex); int rc = 0; while(q->count == 0 && rc == 0) { rc = pthread_cond_wait(&q->consume_more, &q->mutex); } int oldfront = q->front; if(++q->front == 20) q->front = 0; q->count--; q->deleted++; assert(q->count >=0 && q->count <= 20); pthread_cond_signal(&q->produce_more); pthread_mutex_unlock(&q->mutex); return q->arr[oldfront]; } void test_q(queue *q) { assert(is_empty(q) == 1); enqueue(q, 1); assert(is_empty(q) == 0); int val = dequeue(q); assert(val == 1); assert(is_empty(q) == 1); for(int i = 0; i < 1000; i++) { assert(is_empty(q) == 1); enqueue(q, i); assert(is_empty(q) == 0); int val = dequeue(q); assert(val == i); } assert(is_empty(q) == 1); for(int i = 0; i < 30; i++) { int val = enqueue(q, i); assert((i < 20 && val == 0) || (i >= 20 && val == -1)); } for(int i = 0; i < 30; i++) { int val = dequeue(q); assert((i < 20 && val == i) || (i >= 20 && val == -1)); } } void * produce_work(void * arg) { queue *q = (queue *) arg; while(!done) { int val = rand(); enqueue(q, val); } return 0; } void * consume_work(void * arg) { queue *q = (queue *) arg; while(!done) { int val = dequeue(q); do_some_work(val); } return 0; } int main() { struct timeval now; gettimeofday(&now, 0); srand(now.tv_usec); pthread_t thv[2*10]; queue q; queue_init(&q); for(int i = 0; i < 10; i++) { pthread_create(&thv[i], 0, produce_work, &q); } for(int i = 0; i < 10; i++) { pthread_create(&thv[i], 0, consume_work, &q); } for(int j = 0; j < 2*10; j++) { void *val; pthread_join(thv[j], &val); } return 0; } void do_some_work(int a) { }
1
#include <pthread.h> void * watek_klient (void * arg); int l_kr, i; int l_kl = 5; int l_kf = 3; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; main(){ pthread_t *tab_klient; int *tab_klient_id; l_kr = 1; tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t)); tab_klient_id = (int *) malloc(l_kl*sizeof(int)); for(i=0;i<l_kl;i++) tab_klient_id[i]=i; printf("Otwieramy pub (simple)!\\n"); printf("Liczba wolnych kufli %d\\n", l_kf); for(i=0;i<l_kl;i++){ pthread_create(&tab_klient[i], 0, watek_klient, &tab_klient_id[i]); } for(i=0;i<l_kl;i++){ pthread_join( tab_klient[i], 0); } printf("Zamykamy pub!\\n"); printf("Liczba wolnych kufli %d\\n", l_kf); } void * watek_klient (void * arg_wsk){ int moj_id = * ((int *)arg_wsk); int pobrano_kufel = 0; int i, j, kufel, result; int ile_musze_wypic = 2; printf("Klient %d, wchodzę do pubu\\n", moj_id); for(i=0; i<ile_musze_wypic; i++){ if(pthread_mutex_trylock(&mutex) == 0){ printf("\\nKufel zablokowany\\n", moj_id); if(l_kf>0){ printf("\\nSą wolne kufle\\n", moj_id); l_kf--; pobrano_kufel = 1; printf("\\nPodaję piwo w kuflu.\\n", moj_id); } pthread_mutex_unlock(&mutex);} else { printf("\\nNie ma kufli\\n", moj_id); } printf("Klient %d, wybieram kufel\\n", moj_id); j=0; printf("Klient %d, nalewam z kranu %d\\n", moj_id, j); usleep(300); printf("Klient %d, pije\\n", moj_id); nanosleep((struct timespec[]){{0, 500000000L}}, 0); printf("Klient %d, odkladam kufel\\n", moj_id); if(pobrano_kufel == 1){ pthread_mutex_lock(&mutex); pobrano_kufel = 0; l_kf++; printf("Klient %d zwrocił kufel. Liczba kufli: %d\\n", moj_id, l_kf); pthread_mutex_unlock(&mutex); } } printf("Klient %d, wychodzę z pubu\\n", moj_id); return(0); }
0
#include <pthread.h> int pthread_detach(pthread_t tid) { pthread_thread_t *pthread; if ((pthread = tidtothread(tid)) == NULL_THREADPTR) return EINVAL; assert_preemption_enabled(); disable_preemption(); pthread_lock(&pthread->lock); pthread->flags |= THREAD_DETACHED; pthread_unlock(&pthread->lock); pthread_mutex_lock(&pthread->mutex); if (pthread->dead) { pthread_mutex_unlock(&pthread->mutex); pthread_destroy_internal(pthread); } pthread_mutex_unlock(&pthread->mutex); enable_preemption(); return 0; }
1
#include <pthread.h> struct _dot{ double *a; double *b; double sum; int vec_len; }; dot dotstr; pthread_t call_threads[4]; pthread_mutex_t mutex; void dot_product() { int start, end, i; double mysum, *x, *y; start = 0; end = dotstr.vec_len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutex); dotstr.sum += mysum; pthread_mutex_unlock (&mutex); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { int i; int len = 1000; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*1000*sizeof(double)); b = (double*) malloc (4*1000*sizeof(double)); for (i=0; i<len; i++) { a[i]=1; b[i]=a[i]; } dotstr.vec_len = len; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<4; i++) { pthread_create(&call_threads[i], &attr, dot_product, (void *)i); } pthread_attr_destroy(&attr); for(i=0; i<4; i++) { pthread_join(call_threads[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutex); pthread_exit(0); }
0
#include <pthread.h> int estado_filosofo[5]; pthread_mutex_t palillo[5]; void *filosofo(void *num) { int fil_id = *(int *)num; while (1) { estado_filosofo[fil_id] = 0; printf("Filósofo %d pensando\\n", fil_id); sleep( (rand() % 2) + 1 ); estado_filosofo[fil_id] = 1; printf("Filósofo %d quiere comer\\n", fil_id); if ( ( *(int *)num % 2)==0 ) { pthread_mutex_lock(&palillo[fil_id%5]); pthread_mutex_lock(&palillo[(fil_id+1)%5]); } else { pthread_mutex_lock(&palillo[(fil_id+1)%5]); pthread_mutex_lock(&palillo[fil_id%5]); } estado_filosofo[fil_id] = 2; printf("Filósofo %d comiendo\\n", fil_id); sleep( (rand() % 2) + 1); if ( (*(int *)num%2)!=0 ) { pthread_mutex_unlock(&palillo[fil_id%5]); pthread_mutex_unlock(&palillo[(fil_id+1)%5]); } else { pthread_mutex_unlock(&palillo[(fil_id+1)%5]); pthread_mutex_unlock(&palillo[fil_id%5]); } } } int main(void) { pthread_t th; int i; int fil_id[5]; for(i = 0; i < 5; i++) { fil_id[i] = i; pthread_mutex_init(&palillo[i],0); pthread_create(&th,0,filosofo,(void*)&fil_id[i]); } while(1); }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for( i=0; i<((400)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_error(); } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> u64 total_pthread_count; pthread_mutex_t start_mutex; pthread_cond_t start_cond; int start; } global_state_t; global_state_t global_state; int id; } my_pthread_t; void raw__nanosleep(u64 nanoseconds) { struct timespec sleepTime; struct timespec remainingSleepTime; sleepTime.tv_sec = nanoseconds / ((u64)1000000000ull); sleepTime.tv_nsec = nanoseconds - ((nanoseconds / ((u64)1000000000ull)) * ((u64)1000000000ull)); nanosleep(&sleepTime, &remainingSleepTime); } u64 raw__nanoseconds_since_1970() { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (((u64)ts.tv_sec) * ((u64)1000000000ull)) + ((u64)ts.tv_nsec); } void* pthread_start_function(void* user_ptr) { pthread_mutex_lock(&(global_state.start_mutex)); while (global_state.start == 0) { pthread_cond_wait(&(global_state.start_cond), &(global_state.start_mutex)); } pthread_mutex_unlock(&(global_state.start_mutex)); u64 j = 0; { u64 i; for (i = 0; i < ((u64)500000000ull); i++) { j += i; } } return (void*)(j); } u64 run_test_helper(void) { pthread_t* pthread = (pthread_t*) malloc(sizeof(pthread_t) * global_state.total_pthread_count); my_pthread_t* my_pthread = (my_pthread_t*)malloc(sizeof(my_pthread_t) * global_state.total_pthread_count); pthread_mutex_init(&(global_state.start_mutex), 0); pthread_cond_init(&(global_state.start_cond), 0); global_state.start = 0; { int i; for (i = 0; i < global_state.total_pthread_count; i ++) { my_pthread[i].id = i; pthread_create(&(pthread[i]), 0, pthread_start_function, &(my_pthread[i])); } } sleep(1); pthread_mutex_lock(&(global_state.start_mutex)); global_state.start = 1; pthread_cond_broadcast(&(global_state.start_cond)); u64 start_time = raw__nanoseconds_since_1970(); pthread_mutex_unlock(&(global_state.start_mutex)); { int i; for (i = 0; i < global_state.total_pthread_count; i ++) { pthread_join(pthread[i], 0); } } u64 end_time = raw__nanoseconds_since_1970(); u64 loops_per_second = (u64)((double)global_state.total_pthread_count * (double)((u64)500000000ull) * 1000000000.0 / (double)(end_time - start_time)); printf("\\n total_loops = %llu", global_state.total_pthread_count * ((u64)500000000ull)); printf("\\n elapsed_time = %g", (end_time - start_time) / 1000000000.0); printf("\\n [%llu]: %llu\\n", global_state.total_pthread_count, loops_per_second); pthread_mutex_destroy(&(global_state.start_mutex)); pthread_cond_destroy(&(global_state.start_cond)); free(pthread); free(my_pthread); return loops_per_second; } int main(int argc, char** argv) { u64 minimum_pthread_count; u64 maximum_pthread_count; u64 total_loop_count; if (argc == 4) { minimum_pthread_count = atoi(argv[1]); maximum_pthread_count = atoi(argv[2]); total_loop_count = atoi(argv[3]); if (minimum_pthread_count > maximum_pthread_count) { printf("\\nspeed_test fatal: minimum_pthread_count must not be greater than maximum_pthread_count.\\n"); return -1; } } else { printf("\\nspeed_test <minimum-pthread-count> <maximum-pthread-count> <total-loop-count>\\n"); return -1; } { u64 i; for (i = minimum_pthread_count; i <= maximum_pthread_count; i ++) { global_state.total_pthread_count = i; u64 sum = 0; u64 j; for (j = 0; j < total_loop_count; j ++) { sum += run_test_helper(); } printf("\\nAVG [%llu]: %llu\\n", global_state.total_pthread_count, sum / total_loop_count); } } return 0; }
1
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main(int argc, char* argv[]) { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if(res != 0){ perror("pthread_mutex_init error");exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if(res != 0){ perror("pthread create error");exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit){ fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1){ pthread_mutex_lock(&work_mutex); if(work_area[0] != '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); }else{ break; } } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if(res != 0){ perror("pthread join error");exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg){ sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0){ printf("You input %d characters\\n", strlen(work_area) - 1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while(work_area[0] == '\\0'){ pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
0
#include <pthread.h> char buf[200] = {0}; pthread_mutex_t mutex; unsigned int flag = 0; void *func(void *arg) { sleep(1); while (flag == 0) { pthread_mutex_lock(&mutex); printf("本次输入了%d个字符\\n", strlen(buf)); memset(buf, 0, sizeof(buf)); pthread_mutex_unlock(&mutex); sleep(2); } pthread_exit(0); } int main(void) { int ret = -1; pthread_t th = -1; pthread_mutex_init(&mutex, 0); ret = pthread_create(&th, 0, func, 0); if (ret != 0) { printf("pthread_create error.\\n"); exit(-1); } printf("输入一个字符串,以回车结束\\n"); while (1) { pthread_mutex_lock(&mutex); scanf("%s", buf); pthread_mutex_unlock(&mutex); if (!strncmp(buf, "end", 3)) { printf("程序结束\\n"); flag = 1; break; } sleep(1); } printf("等待回收子线程\\n"); ret = pthread_join(th, 0); if (ret != 0) { printf("pthread_join error.\\n"); exit(-1); } printf("子线程回收成功\\n"); pthread_mutex_destroy(&mutex); 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); while (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); while (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> unsigned short buff = 0; unsigned short reader_count = 0; unsigned short control = 1; pthread_mutex_t rmutex, wmutex; void* thread_writer(void *arg) { puts("thread_writer created"); while (control) { pthread_mutex_lock(&wmutex); printf("writer have changed the content: %d\\n", ++buff); pthread_mutex_unlock(&wmutex); sleep(1); } return 0; } void* thread_reader(void *arg) { puts("thread_reader created"); while (control) { pthread_mutex_lock(&rmutex); if (reader_count == 0) pthread_mutex_lock(&wmutex); ++reader_count; pthread_mutex_unlock(&rmutex); printf("read content: %d, %d reader(s)\\n", buff, reader_count); pthread_mutex_lock(&rmutex); --reader_count; if (reader_count == 0) pthread_mutex_unlock(&wmutex); pthread_mutex_unlock(&rmutex); sleep(1); } return 0; } int main(int argc, char *argv[]) { long i; pthread_t tid_writer[2]; pthread_t tid_reader[2]; pthread_mutex_init(&wmutex, 0); pthread_mutex_init(&rmutex, 0); for (i=0; i<2; ++i) { pthread_create(&tid_writer[i], 0, thread_writer, (long*)i); } for (i=0; i<2; ++i) { pthread_create(&tid_reader[i], 0, thread_reader, (long*)i); } while (control) { if (getchar()) { control = 0; } } for (i=0; i<2; ++i) { pthread_join(tid_writer[i], 0); } for (i=0; i<2; ++i) { pthread_join(tid_reader[i], 0); } pthread_mutex_destroy(&wmutex); pthread_mutex_destroy(&rmutex); return 0; }
1
#include <pthread.h> int LoomSwitches[MaxNumFuncs]; struct Operation *LoomOperations[MaxNumInsts]; pthread_mutex_t Mutexes[MaxNumFilters]; void LoomSlot(unsigned SlotID) { struct Operation *Op; assert(SlotID < MaxNumInsts); for (Op = LoomOperations[SlotID]; Op; Op = Op->Next) { Op->CallBack(Op->Arg); } } int LoomSwitch(int FuncID) { return LoomSwitches[FuncID]; } void PrependOperation(struct Operation *Op, struct Operation **Pos) { Op->Next = *Pos; *Pos = Op; } int UnlinkOperation(struct Operation *Op, struct Operation **List) { if (*List == 0) return -1; if (*List == Op) { *List = Op->Next; return 0; } return UnlinkOperation(Op, &(*List)->Next); } void EnterCriticalRegion(void *Arg) { unsigned FilterID = (unsigned)Arg; pthread_mutex_lock(&Mutexes[FilterID]); } void ExitCriticalRegion(void *Arg) { unsigned FilterID = (unsigned)Arg; pthread_mutex_unlock(&Mutexes[FilterID]); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct que { int data; struct que *next; }*fr = 0, *rr = 0; struct que *create_node(int d) { struct que *new = 0; new = (struct que *)malloc(sizeof(struct que)); new->data = d; new->next = 0; return new; } void insert(int d) { struct que *new = create_node(d); if(fr == 0) fr = new; else rr->next = new; rr = new; } void rm_q() { struct que *p = fr; if(fr == 0) return; if(fr == rr) fr = rr = 0; else fr = fr->next; free(p); } void *counting_fun(void *arg) { struct que *p = fr; int offset = *(int *)arg; printf("Queue Data%d\\n",(p->data) + offset); sleep(5); rm_q(); } int main( void ) { pthread_t id1; int offset1 = 1; int data; while(1) { printf("Enter The Data:"); scanf("%d",&data); if(data == -1) break; insert(data); pthread_mutex_unlock(&mutex); pthread_create(&id1, 0, counting_fun, &offset1); } pthread_create(&id1, 0, counting_fun, &offset1); pthread_join(id1, 0); return 0; }
1
#include <pthread.h> int n,waitvar=0; int glEvmCnt=0,glVoterCnt=0 ; int boothid; int evmCnt; int evmSlot; int voterCnt; pthread_mutex_t lockevm ; pthread_mutex_t lockstruct ; pthread_mutex_t lockcast ; int waiting ; int casted; int ready; int tmp; int alloted; int waitevm; }booth ; void polling_ready_evm(booth *b, int count, int id) { printf("Evm no %d at booth no.%d ready with slots %d\\n",id,b->boothid,count); b->ready=1; while(1) { while(b->waitevm==1); b->waitevm=1; while(b->waitevm==1); if((b->casted)+(b->waiting)==(b->voterCnt) || (b->waiting)==count) break; } b->ready=0; if((b->casted)+(b->waiting)==(b->voterCnt)) { b->alloted=b->waiting; b->waiting=0; } else { b->waiting-=count; b->alloted = count ; } while(b->alloted>0); return ; } void voter_wait_for_evm(booth *b) { int count=0 ; while(b->ready!=1) count++; return; } void voter_in_slot(booth *b) { pthread_mutex_lock(&b->lockstruct); while(b->waitevm==0); (b->waiting)++; b->waitevm=0; pthread_mutex_unlock(&b->lockstruct); return; } void evm_cast_vote(booth *b) { (b->casted)++; (b->alloted)--; return ; } void vote(booth *b) { voter_wait_for_evm(b); voter_in_slot(b); printf("Voter is waiting at booth no. %d\\n",b->boothid); pthread_mutex_lock(&b->lockcast); while(b->alloted==0); evm_cast_vote(b); pthread_mutex_unlock(&b->lockcast); glVoterCnt--; printf("Voter casted his vote at booth %d and now voters left is %d\\n",b->boothid,b->voterCnt-b->casted); return ; } void control(booth *b) { int evm_id = b->tmp ; waitvar=1; while(1) { pthread_mutex_lock(&b->lockevm); if(b->casted==b->voterCnt) { pthread_mutex_unlock(&b->lockevm); break; } polling_ready_evm(b,(rand()%(b->evmSlot))+1,evm_id); pthread_mutex_unlock(&b->lockevm); } glEvmCnt--; return ; } int main() { booth b[10]; pthread_t voter[1000]; pthread_t evm[1000]; int i,j; time_t t; srand((unsigned) time(&t)); printf("Enter the number of booth : "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Allot the number of voters to booth%d : ",i); scanf("%d",&b[i].voterCnt); printf("Allot the number of evm to booth%d : ",i); scanf("%d",&b[i].evmCnt); printf("Allot the number of max Slots to this booth : "); scanf("%d",&b[i].evmSlot); b[i].boothid=i; b[i].waiting = 0; b[i].casted = 0; b[i].ready = 0; b[i].alloted = 0; b[i].waitevm=0; pthread_mutex_init(&b[i].lockevm,0); pthread_mutex_init(&b[i].lockstruct,0); pthread_mutex_init(&b[i].lockcast,0); } glEvmCnt=0;glVoterCnt=0; for(i=0;i<n;i++) { for(j=0;j<b[i].evmCnt;j++) { b[i].tmp = j; pthread_create(&evm[glEvmCnt],0,(void *)control,&b[i]); glEvmCnt++; while(waitvar==0); waitvar=0; } for(j=0;j<b[i].voterCnt;j++) { pthread_create(&voter[glVoterCnt],0,(void *)vote,&b[i]); glVoterCnt++; } } while(glEvmCnt>0 || glVoterCnt>0 ); return 0; }
0
#include <pthread.h> pthread_t callThd[4]; double *array_a; double *array_b; double big_sum; int veclen; pthread_mutex_t mutex; pthread_attr_t attr; void *dotprod(void *arg) { int i, start, end; double *x, *y; double mysum; long currThread = (long) arg; start = currThread * (veclen); end = start + (veclen); x = array_a; y = array_b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock(&mutex); big_sum += mysum; pthread_mutex_unlock(&mutex); return 0; } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; a = (double*) malloc (4*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for (i=0; i<100000*4; i++) { a[i] = 1; b[i] = a[i]; } veclen = 100000; array_a = a; array_b = b; big_sum = 0; pthread_mutex_init(&mutex, 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); } for (i=0; i < 4; i++) { pthread_join(callThd[i], 0); } printf ("Sum = %f \\n", big_sum); free (a); free (b); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); pthread_exit(0); }
1
#include <pthread.h> struct mymesg { long mtype; char mtext[512 +1]; }; struct threadinfo { int qid; int fd; int len; pthread_mutex_t mutex; pthread_cond_t ready; struct mymesg m; }; void *helper(void *arg) { int n; struct threadinfo *tip = arg; for (;;) { memset(&tip->m, 0, sizeof(struct mymesg)); if ((n = msgrcv(tip->qid, &tip->m, 512, 0, MSG_NOERROR)) == -1) { err_sys("msgrcv error"); } tip->len = n; pthread_mutex_lock(&tip->mutex); if (write(tip->fd, "a", sizeof(char)) == -1) { err_sys("write error"); } pthread_cond_wait(&tip->ready, &tip->mutex); pthread_mutex_unlock(&tip->mutex); } } int main() { char c; int i, n, err; int fd[2]; int qid[3]; struct pollfd pfd[3]; struct threadinfo ti[3]; pthread_t tid[3]; for (i = 0; i < 3; i++) { if ((qid[i] = msgget(0x123 +i, IPC_CREAT|0666)) == -1) { err_sys("msgget error"); } printf("queue ID %d is %d\\n", i, qid[i]); if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fd) == -1) { err_sys("socketpair error"); } pfd[i].fd = fd[0]; pfd[i].events = POLLIN; ti[i].qid = qid[i]; ti[i].fd = fd[1]; if (pthread_cond_init(&ti[i].ready, 0) != 0) { err_sys("pthread_cond_init error"); } if (pthread_mutex_init(&ti[i].mutex, 0) != 0) { err_sys("pthread_mutex_init error"); } if ((err = pthread_create(&tid[i], 0, helper, &ti[i])) != 0) { err_exit(err, "pthread_create errro"); } } for (;;) { if (poll(pfd, 3, -1) == -1) { err_sys("poll error"); } for (i = 0; i < 3; i++) { if (pfd[i].revents & POLLIN) { if ((n = read(pfd[i].fd, &c, sizeof(char))) == -1) { err_sys("read erorr"); } ti[i].m.mtext[ti[i].len] = '\\0'; printf("queue id %d, message %s\\n", qid[i], ti[i].m.mtext); pthread_mutex_lock(&ti[i].mutex); pthread_cond_signal(&ti[i].ready); pthread_mutex_unlock(&ti[i].mutex); } } } }
0
#include <pthread.h> char compute_gear_mode(int gear_mode) { char gear_val; switch(gear_mode) { case P: gear_val = 'P'; break; case R: gear_val = 'R'; break; case N: gear_val = 'N'; break; case D: gear_val = 'D'; break; default: break; } return gear_val; } void *create_view(void *arg) { struct car_t *c = (struct car_t *) arg; struct timespec T_input = msec_to_timespec(PERIOD_VIEW_THREAD); struct timespec t, t_next; int i; char val_gear_mode; char on_off[4]; strcpy(update_val[0], "VEHICLE STATE"); strcpy(update_val[SPEED], "Speed: 0 Km/h"); strcpy(update_val[GEAR_MODE], "Gear mode: P"); strcpy(update_val[ODOMETER], "Odometer: 0 Km"); strcpy(update_val[CRUISE_CONTROL], "Cruise control: off"); strcpy(update_val[RPM], "RPM: 0"); strcpy(update_val[CURRENT_GEAR], "Current gear: no gear"); strcpy(update_val[FUEL_LEVEL], "Fuel level: 14 gallons"); strcpy(update_val[STATE_CAR], "State car: OFF"); strcpy(update_val[THROTTLE], "THROTTLE: 0"); strcpy(update_val[BRAKE], "BRAKE: 0"); clock_gettime(CLOCK_MONOTONIC, &t); t_next = t; while(!end_simulation) { pthread_mutex_lock(&c->mutex_car); sprintf(update_val[SPEED], "Speed: %f mph", c->speed*2.237); val_gear_mode = compute_gear_mode(c->gear_mode); sprintf(update_val[GEAR_MODE], "Gear mode: %c", val_gear_mode); sprintf(update_val[ODOMETER], "Odometer: %f miles", c->position*0.000621); if(c->cruise_control == ON) { on_off[0] = 'O'; on_off[1] = 'N'; on_off[2] = '\\0'; } else { on_off[0] = 'O'; on_off[1] = 'F'; on_off[2] = 'F'; on_off[3] = '\\0'; } sprintf(update_val[CRUISE_CONTROL], "Cruise control: %s", on_off); sprintf(update_val[RPM], "RPM: %f", c->rpm); if(c->gear == NO_GEAR) { sprintf(update_val[CURRENT_GEAR], "Current gear: NO GEAR"); } else { sprintf(update_val[CURRENT_GEAR], "Current gear: %d", c->gear); } sprintf(update_val[FUEL_LEVEL], "Fuel level: %f", c->fuel_level); if(c->state_car == ON) { on_off[0] = 'O'; on_off[1] = 'N'; on_off[2] = '\\0'; } else { on_off[0] = 'O'; on_off[1] = 'F'; on_off[2] = 'F'; on_off[3] = '\\0'; } sprintf(update_val[STATE_CAR], "State car: %s", on_off); sprintf(update_val[THROTTLE], "THROTTLE: %d", c->throttle); sprintf(update_val[BRAKE], "BRAKE: %d", c->brake); pthread_mutex_unlock(&c->mutex_car); for(i = 0; i < MAX_OUTPUT; i++) { textout_ex(buf, font, update_val[i], x_pos, y_pos[i], makecol(255,0,0), -1); blit(buf, screen, x_pos, y_pos[i], x_pos, y_pos[i], MAX_LENGTH, MAX_WIDTH); } clear(buf); t_next = timespec_add(&t_next, &T_input); clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t_next, 0); } pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t servers_mutex=PTHREAD_MUTEX_INITIALIZER; static struct notifyfs_server_struct *servers=0; static struct notifyfs_server_struct local_server; struct notifyfs_server_struct *get_local_server() { return &local_server; } void add_server_to_list_unlocked(struct notifyfs_server_struct *server) { if (servers) servers->prev=server; server->next=servers; servers=server; } void add_server_to_list(struct notifyfs_server_struct *server, unsigned char locked) { if (locked==0) pthread_mutex_lock(&servers_mutex); add_server_to_list_unlocked(server); if (locked==0) pthread_mutex_unlock(&servers_mutex); } struct notifyfs_server_struct *create_notifyfs_server() { struct notifyfs_server_struct *notifyfs_server=malloc(sizeof(struct notifyfs_server_struct)); if (notifyfs_server) { notifyfs_server->owner_id=new_owner_id(); notifyfs_server->type=NOTIFYFS_SERVERTYPE_NOTSET; notifyfs_server->buffer=0; notifyfs_server->lenbuffer=0; notifyfs_server->connection=0; notifyfs_server->status=NOTIFYFS_SERVERSTATUS_NOTSET; notifyfs_server->error=0; notifyfs_server->connect_time.tv_sec=0; notifyfs_server->connect_time.tv_nsec=0; pthread_mutex_init(&notifyfs_server->mutex, 0); notifyfs_server->data=0; notifyfs_server->clientwatches=0; notifyfs_server->next=0; notifyfs_server->prev=0; } return notifyfs_server; } void init_local_server() { local_server.owner_id=new_owner_id(); local_server.type=NOTIFYFS_SERVERTYPE_LOCALHOST; local_server.status=NOTIFYFS_SERVERSTATUS_UP; local_server.buffer=0; local_server.lenbuffer=0; local_server.connection=0; local_server.error=0; local_server.connect_time.tv_sec=0; local_server.connect_time.tv_nsec=0; pthread_mutex_init(&local_server.mutex, 0); local_server.data=0; local_server.clientwatches=0; local_server.next=0; local_server.prev=0; add_server_to_list(&local_server, 0); } void change_status_server(struct notifyfs_server_struct *server, unsigned char status) { pthread_mutex_lock(&server->mutex); server->status=status; pthread_mutex_unlock(&server->mutex); }
0
#include <pthread.h> void LinuxClock_ClockImpl_OnExit(int state, struct LinuxClock_Instance *_instance); void LinuxClock_send_signal_clock_tick(struct LinuxClock_Instance *_instance); void f_LinuxClock_sleep_ms(struct LinuxClock_Instance *_instance, int timeout_ms); void f_LinuxClock_start_clock_process(struct LinuxClock_Instance *_instance); void f_LinuxClock_sleep_ms(struct LinuxClock_Instance *_instance, int timeout_ms) { { struct timeval tv; tv.tv_sec = timeout_ms/1000; tv.tv_usec = (timeout_ms%1000) * 1000; select(0, 0, 0, 0, &tv); } } struct f_LinuxClock_start_clock_process_struct { struct LinuxClock_Instance *_instance; pthread_mutex_t *lock; pthread_cond_t *cv; }; void f_LinuxClock_start_clock_process_run(struct LinuxClock_Instance *_instance) { { while(1) { f_LinuxClock_sleep_ms(_instance, _instance->Clock_period_var); LinuxClock_send_signal_clock_tick(_instance); } } } void f_LinuxClock_start_clock_process_proc(void * p) { struct f_LinuxClock_start_clock_process_struct params = *((struct f_LinuxClock_start_clock_process_struct *) p); pthread_mutex_lock(params.lock); pthread_cond_signal(params.cv); pthread_mutex_unlock(params.lock); f_LinuxClock_start_clock_process_run(params._instance); } void f_LinuxClock_start_clock_process(struct LinuxClock_Instance *_instance) { struct f_LinuxClock_start_clock_process_struct params; pthread_mutex_t lock; pthread_cond_t cv; params.lock = &lock; params.cv = &cv; params._instance = _instance; pthread_mutex_init(params.lock, 0); pthread_cond_init(params.cv, 0); pthread_mutex_lock(params.lock); pthread_t thread; pthread_create( &thread, 0, f_LinuxClock_start_clock_process_proc, (void*) &params); pthread_cond_wait(params.cv, params.lock); pthread_mutex_unlock(params.lock); } void LinuxClock_ClockImpl_OnEntry(int state, struct LinuxClock_Instance *_instance) { switch(state) { case LINUXCLOCK_CLOCKIMPL_STATE: _instance->LinuxClock_ClockImpl_State = LINUXCLOCK_CLOCKIMPL_TICKING_STATE; f_LinuxClock_start_clock_process(_instance); LinuxClock_ClockImpl_OnEntry(_instance->LinuxClock_ClockImpl_State, _instance); break; case LINUXCLOCK_CLOCKIMPL_TICKING_STATE: break; default: break; } } void LinuxClock_ClockImpl_OnExit(int state, struct LinuxClock_Instance *_instance) { switch(state) { case LINUXCLOCK_CLOCKIMPL_STATE: LinuxClock_ClockImpl_OnExit(_instance->LinuxClock_ClockImpl_State, _instance); break; case LINUXCLOCK_CLOCKIMPL_TICKING_STATE: break; default: break; } } void (*LinuxClock_send_signal_clock_tick_listener)(struct LinuxClock_Instance*)= 0x0; void register_LinuxClock_send_signal_clock_tick_listener(void (*_listener)(struct LinuxClock_Instance*)){ LinuxClock_send_signal_clock_tick_listener = _listener; } void LinuxClock_send_signal_clock_tick(struct LinuxClock_Instance *_instance){ if (LinuxClock_send_signal_clock_tick_listener != 0x0) LinuxClock_send_signal_clock_tick_listener(_instance); }
1
#include <pthread.h> static int nbfgetsInitialized = 0; static volatile int nbfgetsReady = 0; static char nbfgetsBuffer[256]; static pthread_cond_t nbfgetsCond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t nbfgetsMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_t nbfgetsThread; static void * nbfgetsThreadFunction(void *Arg) { nbfgetsBuffer[256 - 1] = 0; while (1) { if (nbfgetsBuffer != fgets(nbfgetsBuffer, 256 - 1, stdin)) { struct timespec req, rem; req.tv_sec = 0; req.tv_nsec = 10000000; nanosleep(&req, &rem); continue; } nbfgetsReady = 1; pthread_mutex_lock(&nbfgetsMutex); if (pthread_cond_wait(&nbfgetsCond, &nbfgetsMutex) != 0) { fputs("pthread error\\n", stderr); } pthread_mutex_unlock(&nbfgetsMutex); } return (0); } void nbfgets_ready(void) { pthread_mutex_lock(&nbfgetsMutex); pthread_cond_broadcast(&nbfgetsCond); pthread_mutex_unlock(&nbfgetsMutex); } char * nbfgets(char *Buffer, int Length) { if (!nbfgetsInitialized) { nbfgetsReady = 0; pthread_cond_init(&nbfgetsCond, 0); pthread_mutex_init(&nbfgetsMutex, 0); pthread_create(&nbfgetsThread, 0, nbfgetsThreadFunction, 0); nbfgetsInitialized = 1; } if (!nbfgetsReady || Length < 1) { return (0); } Length--; strncpy(Buffer, nbfgetsBuffer, Length); Buffer[Length] = 0; nbfgetsReady = 0; pthread_cond_broadcast(&nbfgetsCond); return (Buffer); }
0
#include <pthread.h> int orb =0; pthread_t tid[5]; int counter; pthread_mutex_t lock; pthread_cond_t cond; int work=0; void* doSomeThing(void *arg) { int who,tmp; int i = 0,j; counter += 1; who = counter; printf("\\n Job %d created\\n", who); for(j=0;j<5;j++){ pthread_mutex_lock(&lock); while(!work){ tmp = pthread_cond_wait(&cond, &lock); printf(" Job %d, wait\\n",who); } pthread_mutex_unlock(&lock); printf(" Job %d, orb: %d *\\n",who,orb); work = 0; printf(" Job %d started\\n", who); for(i=0; i<(100000000);i++); orb += who; pthread_mutex_lock(&lock); work =1; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } return 0; } int main(void) { int i = 0,j; int err; int tmp; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } if (pthread_cond_init(&cond, 0) != 0) { printf("\\n cond init failed\\n"); return 1; } while(i < 5) { err = pthread_create(&(tid[i-1]), 0, &doSomeThing, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); i++; } work = 1; tmp = pthread_cond_broadcast(&cond); printf("broadcast(): %d\\n",tmp); for(j=0;j<5;j++) pthread_join(tid[j], 0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> static const uint32_t S_NSECS = 1000000000UL; static const uint32_t MS_NSECS = 1000000UL; void thread_delay_ms(int ms) { time_t now; struct timespec then; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cv = PTHREAD_COND_INITIALIZER; now = time(0); uint64_t nsecs = (S_NSECS * now) + (MS_NSECS * ms); then.tv_sec = nsecs / S_NSECS; then.tv_nsec = nsecs % S_NSECS; pthread_mutex_lock(&mtx); pthread_cond_timedwait(&cv, &mtx, &then); pthread_mutex_unlock(&mtx); }
0
#include <pthread.h> pthread_mutex_t flaglock; pthread_cond_t mycond; int queue_long; int stock_time; p call; char *arg[10]; }fun_arg; fun_arg *fuar_p; struct node *next; }mytar,*mytar_p; mytar *front; mytar *rear; }queue,*listp_queue; listp_queue g_queue; listp_queue creat_queue() { listp_queue myqueue = (listp_queue)malloc(sizeof(queue)); mytar_p amytar = (mytar_p)malloc(sizeof(mytar)); amytar->next = 0; myqueue->front = myqueue->rear = amytar; return myqueue; } void destory_queue() { } int queue_in(listp_queue myqueue, fun_arg *myfun) { mytar_p newtar = (mytar_p)malloc(sizeof(mytar)); newtar->fuar_p = myfun; myqueue->rear->next = newtar; newtar->next = 0; myqueue->rear = myqueue->rear->next; queue_long++; return 0; } fun_arg *queue_out(listp_queue myqueue) { if(myqueue->front == myqueue->rear) return 0; mytar_p temp = myqueue->front; myqueue->front = myqueue->front->next; free(temp); queue_long--; return myqueue->front->fuar_p; } void myprintf(char *str[]) { int i = 0; while(str[i++]) { printf("%s ",str[i-1]); free(str[i-1]); } printf("\\n"); } void myshow(char *str[]) { int i = 0; while(str[i++]) { printf("%d:%s ++ ", i - 1, str[i-1]); free(str[i-1]); } printf("over \\n"); } void *mycall(void *arg) { fun_arg *temp; while(1){ pthread_mutex_lock(&flaglock); while(0 == (temp = queue_out(g_queue))) { pthread_cond_wait(&mycond, &flaglock); } pthread_mutex_unlock(&flaglock); if(temp) { printf("%lu,----------temp:%d\\n", pthread_self(),(unsigned int)(&temp)/8/1024/1024-330); temp->call(temp->arg); printf("queue's long is ------------->%d\\n",queue_long); sleep(1); } } } int creat_pool(int num) { g_queue = creat_queue(); int i = 0; pthread_t *mypth = (pthread_t *)malloc(sizeof(pthread_t *) * num); for(i = 0; i < num; i++) pthread_create(&mypth[i],0,mycall,0); return 0; } int poo_add_task(fun_arg *afun) { pthread_mutex_lock(&flaglock); queue_in(g_queue,afun); pthread_mutex_unlock(&flaglock); pthread_cond_broadcast(&mycond); printf("queue in a number\\n"); return 0; } int main(int argc, char *argv[]) { int i=0; char mm[8] = "Abcde"; creat_pool(40); fun_arg *a; fun_arg b[100]; while(1){ i = 100; while (i--) { b[i].call = myshow; if(mm[0]++ > 'z') mm[0] = '0'; if(mm[1]-- < '0') mm[1] = 'z'; if(0 == (b[i].arg[0] = malloc(20))) perror("malloc"); strncpy(b[i].arg[0],mm,9); if(0 == (b[i].arg[1] = malloc(20))) perror("malloc"); strncpy(b[i].arg[1],mm+1,9); b[i].arg[2] = 0; poo_add_task(&b[i]); } sleep(20); } pause(); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexsum; char char_array[8000000][16]; int char_counts[26]; char getRandomChar() { int randNum = 0; char randChar = ' '; randNum = 26 * (rand() / (32767 + 1.0)); randNum = randNum + 97; randChar = (char) randNum; return randChar; } void init_arrays() { int i, j; pthread_mutex_init(&mutexsum, 0); for ( i = 0; i < 8000000; i++) { for ( j = 0; j < 16; j++ ) { char_array[i][j] = getRandomChar(); } } for ( i = 0; i < 26; i++ ) { char_counts[i] = 0; } } void *count_array(void *myID) { char theChar; int i, j, charLoc; int local_char_count[26]; int startPos = ((int) myID) * (8000000 / 12); int endPos = startPos + (8000000 / 12); printf("myID = %d startPos = %d endPos = %d \\n", (int) myID, startPos, endPos); for ( i = 0; i < 26; i++ ) { local_char_count[i] = 0; } for ( i = startPos; i < endPos; i++) { for ( j = 0; j < 16; j++ ) { theChar = char_array[i][j]; charLoc = ((int) theChar) - 97; local_char_count[charLoc]++; } } pthread_mutex_lock (&mutexsum); for ( i = 0; i < 26; i++ ) { char_counts[i] += local_char_count[i]; } pthread_mutex_unlock (&mutexsum); pthread_exit(0); } void print_results() { int i,j, total = 0; for ( i = 0; i < 26; i++ ) { total += char_counts[i]; printf(" %c %d\\n", (char) (i + 97), char_counts[i]); } printf("\\nTotal characters: %d\\n", total); } main() { int i, rc; pthread_t threads[12]; pthread_attr_t attr; void *status; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); init_arrays(); for (i = 0; i < 12; i++ ) { rc = pthread_create(&threads[i], &attr, count_array, (void *)i); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(i=0; i<12; i++) { rc = pthread_join(threads[i], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(-1); } } print_results(); pthread_mutex_destroy(&mutexsum); printf("Main: program completed. Exiting.\\n"); pthread_exit(0); }
0
#include <pthread.h> struct timespec start_timer, end_timer; uint8_t *image; uint_t *out_mem; size_t block_size; } pthread_args; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; sem_t sem; size_t N; size_t N_THREADS; double calc_time(struct timespec start, struct timespec end) { struct timespec temp; if ((end.tv_nsec - start.tv_nsec) < 0) { temp.tv_sec = end.tv_sec - start.tv_sec - 1; temp.tv_nsec = 1e+9 + end.tv_nsec - start.tv_nsec; } else { temp.tv_sec = end.tv_sec - start.tv_sec; temp.tv_nsec = end.tv_nsec - start.tv_nsec; } return temp.tv_sec + (temp.tv_nsec * 1e-9); } uint8_t* init_image (void) { uint8_t *image = malloc(sizeof(uint8_t) * N); for (int i = 0; i < N; i++) { image[i] = rand() % 256; } return image; } uint_t* init_out_mem (void) { return malloc(sizeof(uint_t) * 256); } void phisto (uint_t *h) { for (int i = 0; i < 256; i++) printf("%d, ", h[i]); } void* sem_histogram (void *arg){ pthread_args a = *(pthread_args*) arg; for (size_t i = 0; i < a.block_size; i++) { sem_wait(&sem); a.out_mem[a.image[i]] += 1; sem_post(&sem); } return 0; } void* lock_histogram (void *arg){ pthread_args a = *(pthread_args*) arg; for (size_t i = 0; i < a.block_size; i++) { pthread_mutex_lock( &lock); a.out_mem[a.image[i]] += 1; pthread_mutex_unlock( &lock); } return 0; } void* f_histogram (void *arg){ pthread_args a = *(pthread_args*) arg; memset(a.out_mem, 0, 256 * sizeof(uint_t)); for (size_t i = 0; i < a.block_size; i++) { a.out_mem[a.image[i]] += 1; } return 0; } void* a_histogram (void *arg){ pthread_args a = *(pthread_args*) arg; for (size_t i = 0; i < a.block_size; i++) { __sync_add_and_fetch(&a.out_mem[a.image[i]], 1); } return 0; } double seq_histogram(uint8_t *image) { clock_gettime(CLOCK_MONOTONIC, &start_timer); uint_t *out_mem = init_out_mem(); memset(out_mem, 0, 256 * sizeof(uint_t)); for (size_t i = 0; i < N; i++) { out_mem[image[i]] += 1; } free(out_mem); clock_gettime(CLOCK_MONOTONIC, &end_timer); return calc_time(start_timer, end_timer); } int main(int argc, const char *argv[]) { char method = 'x'; N = 1024; N_THREADS = 8; for (size_t i = 0; i < argc; i++) { if (argv[i][1] == 'n') N = atoi(argv[i+1]); else if (argv[i][1] == 't') method = (char) argv[i+1][0]; else if (argv[i][1] == 'p') N_THREADS = atoi(argv[i+1]); } srand(3); uint8_t *image = init_image(); double seq_time = seq_histogram(image); double parallel_time; uint_t *out_mem; void* (*fptr)(void*); pthread_args args[N_THREADS]; size_t block_size = N / N_THREADS; pthread_t thread_ids[N_THREADS]; switch (method) { case 'f': out_mem = malloc(sizeof(uint_t) * N_THREADS * 256); for (size_t i = 0; i < N_THREADS; i++) { args[i].image = image + (i * block_size); args[i].out_mem = out_mem + (i * 256); args[i].block_size = block_size; } fptr = &f_histogram; clock_gettime(CLOCK_MONOTONIC, &start_timer); for (size_t i = 0; i < N_THREADS; i++) { pthread_create(&thread_ids[i], 0, fptr, &args[i]); } for (size_t i = 0; i < N_THREADS; i++) { pthread_join(thread_ids[i], 0); } uint_t histogram[256] = {0}; for (size_t i = 0; i < 256; i++) { for (size_t j = 0; j < N_THREADS; j++) { histogram[i] += out_mem[i + (256 * j)]; } } clock_gettime(CLOCK_MONOTONIC, &end_timer); parallel_time = calc_time(start_timer, end_timer); phisto(histogram); goto END; case 'l': fptr = &lock_histogram; break; case 's': sem_init(&sem, 0, 1); fptr = &sem_histogram; break; case 't': break; case 'a': fptr = &a_histogram; break; } out_mem = init_out_mem(); memset(out_mem, 0, 256 * sizeof(uint_t)); for (size_t i = 0; i < N_THREADS; i++) { args[i].image = image + (i * block_size); args[i].out_mem = out_mem; args[i].block_size = block_size; } clock_gettime(CLOCK_MONOTONIC, &start_timer); for (size_t i = 0; i < N_THREADS; i++) { pthread_create(&thread_ids[i], 0, fptr, &args[i]); } for (size_t i = 0; i < N_THREADS; i++) { pthread_join(thread_ids[i], 0); } clock_gettime(CLOCK_MONOTONIC, &end_timer); parallel_time = calc_time(start_timer, end_timer); phisto(out_mem); END: free(out_mem); free(image); printf("Size of image: %zu\\n", N); printf("Number of threads: %zu\\n", N_THREADS); printf("Seq Time: %f\\n", seq_time); double speed_up = seq_time / parallel_time; printf("Speed Up: %f\\n", speed_up); printf("Efficiency: %f\\n", speed_up / N_THREADS); return 0; }
1
#include <pthread.h> void show_errno(int err) { switch(err) { case EINVAL : do{ printf("%d--", 35); printf("[%u]-- %s", (unsigned int)pthread_self(), "EINVAL"); printf("\\n"); }while(0); break; case ETIMEDOUT : do{ printf("%d--", 38); printf("[%u]-- %s", (unsigned int)pthread_self(), "ETIMEDOUT"); printf("\\n"); }while(0); break; case EAGAIN : do{ printf("%d--", 41); printf("[%u]-- %s", (unsigned int)pthread_self(), "EAGAIN"); printf("\\n"); }while(0); break; case EDEADLK : do{ printf("%d--", 44); printf("[%u]-- %s", (unsigned int)pthread_self(), "EDEADLK"); printf("\\n"); }while(0); break; default : do{ printf("%d--", 47); printf("[%u]-- %s", (unsigned int)pthread_self(), "no such errno"); printf("\\n"); }while(0); } } pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void* start_thread(void* arg) { do{ printf("%d--", 53); printf("[%u]--get metux lock", (unsigned int)pthread_self()); printf("\\n"); }while(0); pthread_mutex_lock(&mtx); sleep(5); do{ printf("%d--", 56); printf("[%u]--unlock mutex", (unsigned int)pthread_self()); printf("\\n"); }while(0); pthread_mutex_unlock(&mtx); return 0; } int main() { pthread_t pt; pthread_create(&pt, 0, start_thread, 0); while(1) { usleep(50000); if(pthread_kill(pt, 0) == 0) { break; } } struct timespec abs_timeout; abs_timeout.tv_sec = time(0) + 2; abs_timeout.tv_nsec = 1000000; do{ printf("%d--", 75); printf("[%u]--wait lock within [%ld:%ld]", (unsigned int)pthread_self(), abs_timeout.tv_sec, abs_timeout.tv_nsec); printf("\\n"); }while(0); int err = 0; if((err = pthread_mutex_timedlock(&mtx, &abs_timeout)) != 0) { do{ printf("%d--", 78); printf("[%u]--timedlocak faild, errno = [%d]", (unsigned int)pthread_self(), err); printf("\\n"); }while(0); show_errno(err); } else { do{ printf("%d--", 81); printf("[%u]--get mutex OK", (unsigned int)pthread_self()); printf("\\n"); }while(0); } void* rt = 0; pthread_join(pt, &rt); abs_timeout.tv_sec = time(0) + 2; abs_timeout.tv_nsec = 1000000; do{ printf("%d--", 87); printf("[%u]--wait lock within [%ld:%ld]", (unsigned int)pthread_self(), abs_timeout.tv_sec, abs_timeout.tv_nsec); printf("\\n"); }while(0); if((err = pthread_mutex_timedlock(&mtx, &abs_timeout)) != 0) { do{ printf("%d--", 89); printf("[%u]--timedlocak faild, errno = [%d]", (unsigned int)pthread_self(), err); printf("\\n"); }while(0); show_errno(err); } else { do{ printf("%d--", 92); printf("[%u]--get mutex OK", (unsigned int)pthread_self()); printf("\\n"); }while(0); } return 0; }
0
#include <pthread.h> struct ryu_malloc_memories{ struct order *holder; pthread_mutex_t mutex; struct ryu_malloc_memories *next; struct ryu_malloc_using_chain *using; }; struct ryu_malloc_using_chain{ char *memory; struct ryu_malloc_using_chain *next; }; struct ryu_malloc_memories ryu_malloc_head; pthread_mutex_t ryu_malloc_chain_mutex; void _ryu_malloc_initialize(){ pthread_mutex_init(&ryu_malloc_chain_mutex,0); ryu_malloc_head.holder = 0; ryu_malloc_head.next = 0; ryu_malloc_head.using = 0; } char * ryumalloc(struct order *order,size_t size){ struct ryu_malloc_memories *current; struct ryu_malloc_memories *lastChain_orders; struct ryu_malloc_using_chain *current_using; struct ryu_malloc_using_chain *lastChain; char *val = malloc(size); if(val==0){ return 0; } pthread_mutex_lock(&ryu_malloc_chain_mutex); current = &ryu_malloc_head; lastChain_orders = current; while(current!=0){ if(current->holder==order){ pthread_mutex_lock(&current->mutex); current_using = current->using; lastChain = (struct ryu_malloc_using_chain *)malloc(sizeof(struct ryu_malloc_using_chain)); current->using = lastChain; pthread_mutex_unlock(&ryu_malloc_chain_mutex); lastChain->next = current_using; lastChain->memory = val; pthread_mutex_unlock(&current->mutex); return val; } lastChain_orders = current; current = current->next; } current = (struct ryu_malloc_memories *)malloc(sizeof(struct ryu_malloc_memories)); lastChain_orders->next = current; current->next = 0; current->using = (struct ryu_malloc_using_chain *)malloc(sizeof(struct ryu_malloc_using_chain)); current->using->next = 0; current->using->memory = val; current->holder = order; pthread_mutex_init(&lastChain_orders->next->mutex,0); pthread_mutex_unlock(&ryu_malloc_chain_mutex); return val; } int ryufree_unreachable(struct order *dead_order){ struct ryu_malloc_memories *current; struct ryu_malloc_memories *last; pthread_mutex_lock(&ryu_malloc_chain_mutex); current = &ryu_malloc_head; last = current; while(current!=0){ if(current->holder==dead_order){ last->next = current->next; pthread_mutex_unlock(&ryu_malloc_chain_mutex); int n = 0; struct ryu_malloc_using_chain *chain_current = current->using; struct ryu_malloc_using_chain *tmp; free(current); while(chain_current!=0){ tmp = chain_current; chain_current = chain_current->next; free(tmp->memory); free(tmp); n++; } return n; } last = current; current = current->next; } pthread_mutex_unlock(&ryu_malloc_chain_mutex); return 0; } void ryufree(void *ptr){ return; }
1
#include <pthread.h> pthread_mutex_t mutexid; pthread_mutex_t mutexres; int idcount = 0; pthread_mutex_t joinmutex[4]; int join[4]; int result[4]; int target; int sequence[(4 * 30)]; void *thread (void *arg) { int id, i, from, count, l_target; pthread_mutex_lock (&mutexid); l_target = target; id = idcount; idcount++; pthread_mutex_unlock (&mutexid); __VERIFIER_assert (id >= 0); __VERIFIER_assert (id <= 4); from = id * 30; count = 0; for (i = 0; i < 30; i++) { if (sequence[from + i] == l_target) { count++; } if (count > 30) { count = 30; } } printf ("t: id %d from %d count %d\\n", id, from, count); pthread_mutex_lock (&mutexres); result[id] = count; pthread_mutex_unlock (&mutexres); pthread_mutex_lock (&joinmutex[id]); join[id] = 1; pthread_mutex_unlock (&joinmutex[id]); return 0; } int main () { int i; pthread_t t[4]; int count; i = __VERIFIER_nondet_int (0, (4 * 30)-1); sequence[i] = __VERIFIER_nondet_int (0, 3); target = __VERIFIER_nondet_int (0, 3); printf ("m: target %d\\n", target); pthread_mutex_init (&mutexid, 0); pthread_mutex_init (&mutexres, 0); for (i = 0; i < 4; i++) { pthread_mutex_init (&joinmutex[i], 0); result[i] = 0; join[i] = 0; } i = 0; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; __VERIFIER_assert (i == 4); int j; i = 0; pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } if (i != 4) { return 0; } __VERIFIER_assert (i == 4); count = 0; for (i = 0; i < 4; i++) { count += result[i]; printf ("m: i %d result %d count %d\\n", i, result[i], count); } printf ("m: final count %d\\n", count); __VERIFIER_assert (count >= 0); __VERIFIER_assert (count <= (4 * 30)); return 0; }
0