text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> pthread_mutex_t lock; { sem_t sem; unsigned int id; int money; } bankAccount; { bankAccount *src; bankAccount *target; int numberOfMoney; } moneyTransfer; { bankAccount *target; int numberOfMoney; } addMoney; bankAccount *createAccount(int id, int money) { bankAccount *account = (bankAccount *)malloc(sizeof(bankAccount)); account->id = id; account->money = money; sem_init(&(account->sem), 0, 1); return account; } moneyTransfer *createTransfer(bankAccount *src, bankAccount *target, int numberOfMoney) { moneyTransfer *transfer = (moneyTransfer *)malloc(sizeof(moneyTransfer)); transfer->src = src; transfer->target = target; transfer->numberOfMoney = numberOfMoney; return transfer; } addMoney *createAdder(bankAccount *target, int numberOfMoney) { addMoney *add = (addMoney *)malloc(sizeof(addMoney)); add->target = target; add->numberOfMoney = numberOfMoney; return add; } void *addToAccount(void *arg) { pthread_mutex_lock(&lock); addMoney *money = (addMoney *)arg; bankAccount *target = money->target; for (int i = 0; i < 6; i++) { sem_wait(&(target->sem)); int cache = target->money; usleep(rand() % 1000); target->money = cache + money->numberOfMoney; printf("Dodaje %d pln do konta nr: %d \\nStan konta: %d \\n\\n", money->numberOfMoney, target->id, target->money); sem_post(&(target->sem)); } pthread_mutex_unlock(&lock); } void *transferMoney(void *arg) { pthread_mutex_lock(&lock); moneyTransfer *transfer = (moneyTransfer *)arg; bankAccount *src = transfer->src; bankAccount *target = transfer->target; for (int i = 0; i < 6; i++) { if (src->id < target->id) { sem_wait(&(src->sem)); sem_wait(&(target->sem)); } else { sem_wait(&(target->sem)); sem_wait(&(src->sem)); } int srcCache = src->money; int targetCache = target->money; usleep(rand() % 1000); src->money = srcCache - transfer->numberOfMoney; target->money = targetCache + transfer->numberOfMoney; printf("\\n przelew: %d \\n", transfer->numberOfMoney); printf("Z konta nr: %d --> stan konta: %d \\n", src->id, src->money); printf("Do konta nr: %d --> stan konta: %d \\n", target->id, target->money); sem_post(&(target->sem)); sem_post(&(src->sem)); } pthread_mutex_unlock(&lock); } int main() { int i; time_t t; i = time(&t); srand(i); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } int threadNumber = 5; pthread_t addFirstAccountThread[threadNumber]; pthread_t addSecondAccountThread[threadNumber]; pthread_t transferFirstThread[threadNumber]; pthread_t transferSecondThread[threadNumber]; int returnThread; bankAccount *firstAccount = createAccount(1, 0); bankAccount *secondAccount = createAccount(2, 0); addMoney *addToFirst = createAdder(firstAccount, 100); addMoney *addToSecond = createAdder(secondAccount, 100); moneyTransfer *fromFirstTransfer = createTransfer(firstAccount, secondAccount, 50); moneyTransfer *fromSecondTransfer = createTransfer(secondAccount, firstAccount, 150); for (int i = 0; i < threadNumber; i++) { pthread_create(&(addFirstAccountThread[i]), 0, addToAccount, (void *)addToFirst); pthread_create(&(addSecondAccountThread[i]), 0, addToAccount, (void *)addToSecond); pthread_create(&(transferFirstThread[i]), 0, transferMoney, (void *)fromFirstTransfer); pthread_create(&(transferSecondThread[i]), 0, transferMoney, (void *)fromSecondTransfer); } for (int i = 0; i < threadNumber; i++) { pthread_join(addFirstAccountThread[i], 0); pthread_join(addSecondAccountThread[i], 0); pthread_join(transferFirstThread[i], 0); pthread_join(transferSecondThread[i], 0); } printf("\\n====================KONIEC====================\\n"); printf("Konto nr: %d --> stan konta: %d \\n", firstAccount->id, firstAccount->money); printf("Konto nr: %d --> stan konta: %d \\n", secondAccount->id, secondAccount->money); pthread_mutex_destroy(&lock); exit(0); }
1
#include <pthread.h> sem_t forks[5]; pthread_mutex_t mutex; struct philosophor_struct{ char philosophor_name[100]; int philosophor_id; }; void eat(); void think(); void get_forks(); void put_forks(); void *doit(); void think(struct philosophor_struct *p){ int sleep_time = rand() % 20 + 1; pthread_mutex_lock(&mutex); printf("%s is hungry.\\n", p->philosophor_name); pthread_mutex_unlock(&mutex); sleep(sleep_time); } void eat(struct philosophor_struct *p){ int sleep_time = rand() % 8 + 2; pthread_mutex_lock(&mutex); printf("%s is eating noodles.\\n", p->philosophor_name); pthread_mutex_unlock(&mutex); sleep(sleep_time); } void get_forks(struct philosophor_struct *p){ int left_fork = (p->philosophor_id + 5) % 5; int right_fork = (p->philosophor_id + 1) % 5; int sem_value; int forks_check = 1; while(forks_check){ sem_getvalue(&forks[left_fork], &sem_value); if(sem_value == 1){ sem_wait(&forks[left_fork]); sem_getvalue(&forks[right_fork], &sem_value); if(sem_value == 1){ sem_wait(&forks[right_fork]); forks_check = 0; }else{ sem_post(&forks[left_fork]); } } } printf("%s get forks %d and %d.\\n", p->philosophor_name, left_fork, right_fork); } void put_forks(struct philosophor_struct *p){ int left_fork = (p->philosophor_id + 5) % 5; int right_fork = (p->philosophor_id + 1) % 5; pthread_mutex_lock(&mutex); printf("%s puts down forks %d and %d\\n", p->philosophor_name, left_fork, right_fork); pthread_mutex_unlock(&mutex); sem_post(&forks[right_fork]); sem_post(&forks[left_fork]); } void *doit(void *p){ struct philosophor_struct *philo = (struct philosophor_struct *)p; while(1){ think(philo); get_forks(philo); eat(philo); put_forks(philo); } } int main(){ int i; pthread_t p_thread[5]; struct philosophor_struct *philo; philo = malloc(sizeof(struct philosophor_struct)*5); strcpy(philo[0].philosophor_name, "Kevin"); strcpy(philo[1].philosophor_name, "Xiaoli"); strcpy(philo[2].philosophor_name, "Jaydeep"); strcpy(philo[3].philosophor_name, "Batman"); strcpy(philo[4].philosophor_name, "Ironman"); pthread_mutex_init(&mutex, 0); for(i=0;i<5;i++){ sem_init(&forks[i], 0, 1); } for(i=0;i<5;i++){ philo[i].philosophor_id = i; pthread_create(&p_thread[i], 0, doit, &philo[i]); } for(i=0;i<5;i++){ pthread_join(p_thread[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; unsigned long long main_counter,counter[3]; void* thread_work(void* ); int main(int argc, const char *argv[]) { int rtn,ch; pthread_t pthread_id[3] = {0}; pthread_mutex_init(&mutex,0); for(int i=0;i < 3; i++) { pthread_create(&pthread_id[i],0, thread_work,(void *)i); } do{ unsigned long long sum = 0; for (int i=0;i < 3; i++) { pthread_mutex_lock(&mutex); sum += counter[i]; printf("counter %d = %llu ",i,counter[i]); pthread_mutex_unlock(&mutex); } printf("main_counter %llu ",main_counter); printf("sum %llu\\n",sum); } while((ch=getchar())!='q'); pthread_mutex_destroy(&mutex); return 0; } void* thread_work(void* p) { int thread_num; thread_num = (int)p; printf("in thread %lu ,i = %d\\n",pthread_self(),thread_num); for(;;) { pthread_mutex_lock(&mutex); counter[thread_num]++; main_counter ++; pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> pthread_mutex_t lock_bd = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_cont = PTHREAD_MUTEX_INITIALIZER; int leitores_cont = 0; void * leitores (void * arg){ int i = *((int*)arg); while(1){ printf("Leitor %d - Vai ler dados\\n",i); pthread_mutex_lock(&lock_cont); leitores_cont++; if(leitores_cont == 1){ pthread_mutex_lock(&lock_bd); } pthread_mutex_unlock(&lock_cont); printf("Leitor %d - Lendo dados\\n",i); sleep(10); pthread_mutex_lock(&lock_cont); leitores_cont--; if(leitores_cont == 0){ pthread_mutex_unlock(&lock_bd); } pthread_mutex_unlock(&lock_cont); printf("Leitor %d - Processando dados lidos\\n",i); sleep(2); printf("Leitor %d - Dados processados\\n",i); } } void * escritores(void * arg){ int i = *((int*)arg); while(1){ printf("Escritor %d - Produzindo dados\\n",i); sleep(5); printf("Escritor %d - Vai escrever dados\\n",i); pthread_mutex_lock(&lock_bd); printf("Escritor %d - Escrevendo dados\\n",i); sleep(10); pthread_mutex_unlock(&lock_bd); printf("Escritor %d - Dados escritos\\n",i); } } int main(){ pthread_t l[4]; pthread_t e[2]; int i,j; int *idL,*idE; for(i = 0; i < 2; i++){ idE = (int*) malloc(sizeof(int)); *idE = i; pthread_create(&e[i], 0, escritores, (void *) (idE)); } for(j = 0; j < 4; j++){ idL = (int*) malloc(sizeof(int)); *idL = j; pthread_create(&l[j], 0, leitores, (void *) (idL)); } pthread_join(e[0],0); pthread_join(l[0],0); return 0; }
0
#include <pthread.h> int done; int totalbytes; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lockbytes = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t byteschanged = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t isbyteschanged = PTHREAD_COND_INITIALIZER; int copyfile(int infd, int outfd); struct copy_t { int infd; int outfd; int status; pthread_t tid; }; void* copyfile_thread(void* arg) { struct copy_t* args = (struct copy_t*) arg; int infd = args->infd; int outfd = args->outfd; args->status = copyfile(infd, outfd); pthread_mutex_lock(&lock); ++done; pthread_mutex_unlock(&lock); return &(args->status); } int main(int argc, char* argv[]) { if (argc != 4) { fprintf(stderr, "Usage: %s infile_basename outfile_basename copies\\n", argv[0]); return 1; } int numcopiers = atoi(argv[3]); if (numcopiers < 1) { fprintf(stderr, "Usarge: %s %d copies not allowed\\n", argv[0], numcopiers); return 1; } done = 0; totalbytes = 0; pthread_mutex_init(&lock, 0); pthread_mutex_init(&lockbytes, 0); struct copy_t* copyinfo = calloc(numcopiers, sizeof(struct copy_t)); for (int i = 0; i < numcopiers; ++i) { char filename[100]; snprintf(filename, 100, "%s.%d", argv[1], i + 1); int infd = open(filename, O_RDONLY); if (infd < 0) { perror("Input open error"); continue; } snprintf(filename, 100, "%s.%d", argv[2], i + 1); int outfd = open(filename, (O_WRONLY | O_CREAT), (S_IRUSR | S_IWUSR)); if (outfd < 0) { perror("Output open error"); continue; } copyinfo[i].infd = infd; copyinfo[i].outfd = outfd; copyinfo[i].tid = pthread_self(); pthread_create(&(copyinfo[i].tid), 0, copyfile_thread, &copyinfo[i]); } int lastdone = 0; int lasttotalbytes = 0; while (done < numcopiers) { pthread_mutex_lock(&byteschanged); if (totalbytes == lasttotalbytes) pthread_cond_wait(&isbyteschanged, &byteschanged); pthread_mutex_unlock(&byteschanged); int length = 40; int progress = length * ((double)totalbytes / (numcopiers * 57000000)); fprintf(stderr, "\\r"); for (int i = 0; i < progress; ++i) fprintf(stderr, "*"); for (int i = progress; i < length; ++i) fprintf(stderr, " "); fprintf(stderr, "%d", totalbytes); lastdone = done; lasttotalbytes = totalbytes; } fprintf(stderr, "\\n"); for (int i = 0; i < numcopiers; ++i) { if (pthread_equal(copyinfo[i].tid, pthread_self())) continue; pthread_join(copyinfo[i].tid, 0); close(copyinfo[i].infd); close(copyinfo[i].outfd); } pthread_mutex_destroy(&lock); pthread_mutex_destroy(&lockbytes); return 0; } int copyfile(int infd, int outfd) { int bytesread = 0; int byteswrote = 0; char buf[512]; int status = 1; int recordedtotalbytes = 0; for (;;) { while (((bytesread = read(infd, buf, 512)) == -1) && (errno == EINTR)) ; if (bytesread == -1) { perror("Read error"); break; } if (bytesread == 0) { status = 0; break; } while (((byteswrote = write(outfd, buf, bytesread)) == -1) && (errno == EINTR)) ; if (byteswrote == -1) { perror("Write error"); break; } recordedtotalbytes += byteswrote; int status = pthread_mutex_trylock(&lockbytes); if (status == 0) { totalbytes += recordedtotalbytes; pthread_mutex_unlock(&lockbytes); recordedtotalbytes = 0; pthread_cond_signal(&isbyteschanged); } } recordedtotalbytes += byteswrote; status = pthread_mutex_trylock(&lockbytes); if (status == 0) { totalbytes += recordedtotalbytes; pthread_mutex_unlock(&lockbytes); recordedtotalbytes = 0; pthread_cond_signal(&isbyteschanged); } return status; }
1
#include <pthread.h> pthread_mutex_t Poll_Work; sem_t Poll_IN; sem_t Poll_OUT; void* thread0(void *param) { while(1){ int rv = 0; for(int i = 0; i < 5; ++ i) while((rv = sem_wait(&Poll_IN)) != 0 && (errno == EINTR)) ; pthread_mutex_lock(&Poll_Work); (*(int*)param) += 5; printf("Thread0: %d\\n", *(int*)param); for(int i = 0; i < 5; ++ i) sem_post( &Poll_OUT); pthread_mutex_unlock(&Poll_Work); sleep(1); } return 0; } void* thread1(void *param) { while(1){ int rv = 0; for(int i = 0; i < 4; ++ i) while((rv = sem_wait(&Poll_IN)) != 0 && (errno == EINTR) ) ; pthread_mutex_lock(&Poll_Work); (*(int*)param) += 4; printf("Thread1: %d\\n", *(int*)param); for(int i = 0; i < 4; ++ i) sem_post( &Poll_OUT); pthread_mutex_unlock(&Poll_Work); sleep(1); } return 0; } void* thread2(void *param) { while(1){ int rv = 0; for(int i = 0; i < 3; ++ i) while((rv = sem_wait(&Poll_OUT)) != 0 && (errno == EINTR)) printf("xx"); pthread_mutex_lock(&Poll_Work); (*(int*)param) -= 3; printf("Thread2: %d\\n", *(int*)param); for(int i = 0; i < 3; ++ i) sem_post(&Poll_IN); pthread_mutex_unlock(&Poll_Work); sleep(1); } return 0; } int main() { int sum = 0; int i; pthread_mutex_init(&Poll_Work, 0); sem_init(&Poll_IN, 0, 100); sem_init(&Poll_OUT, 0, sum); pthread_t ths[4]; pthread_create(&ths[0], 0, thread0, (void*)&sum); pthread_create(&ths[1], 0, thread1, (void*)&sum); pthread_create(&ths[2], 0, thread2, (void*)&sum); for(i = 0; i < 3; ++ i){ pthread_join(ths[i], 0); } }
0
#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 res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if (res != 0) { perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if (res != 0) { perror("Thread creation failed"); 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("Thread join failed"); 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", (int)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); }
1
#include <pthread.h> struct data { int tid; char buffer[100]; } tdata1, tdata2; pthread_mutex_t lock; pthread_cond_t startCond; int start = 0; int totalMessageLength = 0; void *worker(void *tdata) { struct data *d = (struct data*) tdata; printf("thread %d says %s\\n", d->tid, d->buffer); pthread_mutex_lock(&lock); { printf("thread %d sleeps until we can start\\n", d->tid); pthread_cond_wait(&startCond, &lock); } totalMessageLength += strlen(d->buffer); pthread_mutex_unlock(&lock); pthread_exit(0); } int main(char *argc[], int argv) { int failed; pthread_t thread1, thread2; void *status1, *status2; pthread_mutex_init(&lock, 0); pthread_cond_init(&startCond, 0); tdata1.tid = 1; strcpy(tdata1.buffer, "hello"); failed = pthread_create(&thread1, 0, worker, (void*)&tdata1); if (failed) { printf("thread_create failed!\\n"); return -1; } tdata2.tid = 2; strcpy(tdata2.buffer, "world"); failed = pthread_create(&thread2, 0, worker, (void*)&tdata2); if (failed) { printf("thread_create failed!\\n"); return -1; } printf("Main thread is sleeping\\n"); sleep(1); printf("Main thread woke up!\\n"); pthread_cond_broadcast (&startCond); pthread_join(thread1, &status1); pthread_join(thread2, &status2); printf("Total message length %d\\n", totalMessageLength); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t mutex; static pthread_once_t once; extern char **environ; static int has_environ_malloced; size_t cur_items; size_t max_items; void *block_signal (sigset_t *oldmask) { sigset_t newmask; sigfillset(&newmask); pthread_sigmask(SIG_BLOCK, &newmask, oldmask); } void unblock_signal (sigset_t *oldmask) { pthread_sigmask(SIG_SETMASK, oldmask, 0); } void my_memcpy(void *dest, void *src, size_t n) { char *d, *s; d = dest; s = src; for (int i = 0; i < n; i++){ d[i] = s[i]; } } static int resize_environ(int first_time) { sigset_t oldmask; size_t newbuflen, newitems; char **newbuf; pthread_kill(pthread_self(), SIGQUIT); block_signal(&oldmask); pthread_kill(pthread_self(), SIGQUIT); if (cur_items != 0) newitems = cur_items << 1; else newitems = 64; newbuflen = newitems * sizeof(char*); if (first_time == 1) newbuf = malloc(newbuflen); else newbuf = realloc(environ, newbuflen); unblock_signal(&oldmask); if (newbuf == 0) return 4; else{ if (first_time == 1){ my_memcpy(newbuf, environ, cur_items * sizeof(char*)); char **tmp; tmp = environ; environ = (char**)newbuf; has_environ_malloced = 1; } max_items = newitems; return 0; } } static void init (void) { int ret; pthread_mutexattr_t attr; if (ret = pthread_mutexattr_init(&attr)){ t_err("pthread_mutexattr_init failed.", ret); exit(ret); }else if (ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)){ t_err("pthread_mutexattr_settype failed.", ret); exit(ret); }else if (ret = pthread_mutex_init(&mutex, &attr)){ t_err("pthread_mutex_init failed.", ret); exit(ret); }else if (ret = pthread_mutexattr_destroy(&attr)){ t_err("pthread_mutexattr_destroy failed.", ret); exit(ret); } } char *my_strchr (char *str, int target) { for (char *ch = str; *ch != '\\0'; ch++){ if (*ch == target) return ch; } return 0; } int my_strncmp (char *str1, char *str2, size_t num) { int i1, i2; for (i1 = 0, i2 = 0; i1 < num && i2 < num && str1[i1] != '\\0' && str2[i2] != '\\0'; i1++, i2++){ if (str1[i1] < str2[i2]) return -1; else if (str1[i1] > str2[i2]) return 1; } return 0; } int my_putenv_r (char *str) { char *equal_sign = 0; long len; int ret; if (str == 0) return 1; if ((equal_sign = my_strchr(str, '=')) == 0) return 1; if ((len = equal_sign - str) == 0) return 1; pthread_once(&once, init); if (ret = pthread_mutex_lock(&mutex)) return 3; size_t target; for (target = 0; environ[target] != 0; target++){ if (my_strncmp(str, environ[target], len) == 0){ environ[target] = str; pthread_mutex_unlock(&mutex); return 0; } } if (has_environ_malloced == 0){ for (; environ[cur_items] != 0; cur_items++) ; cur_items++; if (ret = resize_environ(1)){ pthread_mutex_unlock(&mutex); return ret; } } if (cur_items >= max_items){ if (ret = resize_environ(0)){ pthread_mutex_unlock(&mutex); return ret; } } environ[target++] = str; environ[target] = 0; cur_items++; pthread_mutex_unlock(&mutex); return 0; } void sig_handler (int signo) { int ret; write(STDOUT_FILENO, "in signal handler.\\n", sizeof("in signal handler.\\n") - 1); } void *thread (void *arg) { int ret; pthread_t *tid = (pthread_t*)arg; if (arg == (void*)0){ for (int i = 0; i < 10; i++){ char *buf; if ((buf = malloc(64)) == 0){ fprintf(stderr, "thread malloc failed.\\n"); continue; } sprintf(buf, "TTTTT%d=%d", i, i); if (ret = my_putenv_r (buf)){ fprintf(stderr, "thread put env failed.\\n"); free(buf); } } printf("thread now print environ.\\n"); for (char **ch = environ; *ch != 0; ch++){ printf("%s\\n", *ch); } return 0; } for (int i = 0; i < 20; i++){ pthread_kill(*tid, SIGQUIT); } } int main (int argc, char *argv[]) { int ret, success_items; struct sigaction act; memset(&act, 0, sizeof(act)); act.sa_handler = sig_handler; if (sigaction(SIGQUIT, &act, 0) == -1) t_err("sigaction failed.", ret); if (argc == 1) err("usage: progname environ1 environ2 ... ."); printf("main print original environ.\\n"); for (char **ch = environ; *ch != 0; ch++){ printf("%s\\n", *ch); } pthread_t tid1, tid2; if (ret = pthread_create(&tid1, 0, thread, (void*)pthread_self())) t_err("main pthread_create failed.", ret); if (ret = pthread_create(&tid2, 0, thread, (void*)0)) t_err("main pthread_create failed.", ret); for (int i = 1, success_items = 0; i < argc; i++){ if (ret = my_putenv_r (argv[i])){ printf("putenv failed, sentence: %s, errno:%d\\n", argv[i], ret); }else success_items++; } if (success_items == 0) printf("main no environ put success. exit.\\n"); for (int i = 0; i < 3; i++) printf("------------------------------------\\n"); printf("main now print environ.\\n"); for (char **ch = environ; *ch != 0; ch++){ printf("%s\\n", *ch); } if (ret = pthread_join(tid1, 0)) t_err("pthread_join failed.", ret); if (ret = pthread_join(tid2, 0)) t_err("pthread_join failed.", ret); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexes[5]; pthread_cond_t conditionVars[5]; int permits[5]; pthread_t tids[5]; int data = 0; void * Philosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[i%5]); while (permits[i%5] == 0) { pthread_cond_wait(&conditionVars[i%5],&mutexes[i%5]); } permits[i%5] = 0; pthread_mutex_unlock(&mutexes[i%5]); pthread_mutex_lock(&mutexes[(i+1)%5]); while (permits[(i+1)%5] == 0) { pthread_cond_wait(&conditionVars[(i+1)%5],&mutexes[(i+1)%5]); } permits[(i+1)%5] = 0; pthread_mutex_unlock(&mutexes[(i+1)%5]); printf("philosopher %d thinks \\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[(i+1)%5]); permits[(i+1)%5] = 1; pthread_cond_signal(&conditionVars[(i+1)%5]); pthread_mutex_unlock(&mutexes[(i+1)%5]); pthread_mutex_lock(&mutexes[i%5]); permits[i%5] = 1; pthread_cond_signal(&conditionVars[i%5]); pthread_mutex_unlock(&mutexes[i%5]); return 0; } void * OddPhilosopher(void * arg){ int i; i = (int)arg; pthread_mutex_lock(&mutexes[(i+1)%5]); while (permits[(i+1)%5] == 0) { pthread_cond_wait(&conditionVars[(i+1)%5],&mutexes[(i+1)%5]); } permits[(i+1)%5] = 0; pthread_mutex_unlock(&mutexes[(i+1)%5]); pthread_mutex_lock(&mutexes[i%5]); while (permits[i%5] == 0) { pthread_cond_wait(&conditionVars[i%5],&mutexes[i%5]); } permits[i%5] = 0; pthread_mutex_unlock(&mutexes[i%5]); printf("philosopher %d thinks\\n",i); fflush(stdout); pthread_mutex_lock(&mutexes[i%5]); permits[i%5] = 1; pthread_cond_signal(&conditionVars[i%5]); pthread_mutex_unlock(&mutexes[i%5]); pthread_mutex_lock(&mutexes[(i+1)%5]); permits[(i+1)%5] = 1; pthread_cond_signal(&conditionVars[(i+1)%5]); pthread_mutex_unlock(&mutexes[(i+1)%5]); return 0; } int main(){ int i; for (i = 0; i < 5; i++) pthread_mutex_init(&mutexes[i], 0); for (i = 0; i < 5; i++) pthread_cond_init(&conditionVars[i], 0); for (i = 0; i < 5; i++) permits[i] = 1; for (i = 0; i < 5 -1; i++){ pthread_create(&tids[i], 0, Philosopher, (void*)(i) ); } pthread_create(&tids[5 -1], 0, OddPhilosopher, (void*)(5 -1) ); for (i = 0; i < 5; i++){ pthread_join(tids[i], 0); } for (i = 0; i < 5; i++){ pthread_mutex_destroy(&mutexes[i]); } for (i = 0; i < 5; i++){ pthread_cond_destroy(&conditionVars[i]); } return 0; }
0
#include <pthread.h> static int *solution[9]; static int duplicate = 0; pthread_mutex_t lock; ROW, COLUMN, BLOCK } chk_t; void *runner(void *para); int main(int argc, const char *argv[]) { int i, j, k, l; int status; pthread_t workers[27]; if (argc < 2) { printf("no input\\n"); return 0; } for (i = 0; i < 9; i++) solution[i] = (int *)malloc(sizeof(int) * 9); FILE *file; if ((file = fopen(argv[1], "r"))) { for (i = 0; i < 9; i++) { int *ptr = solution[i]; fscanf(file, "%d %d %d %d %d %d %d %d %d", ptr, ptr+1, ptr+2, ptr+3, ptr+4, ptr+5, ptr+6, ptr+7, ptr+8); } printf("File Parsed.\\n"); fclose(file); } pthread_mutex_init(&lock, 0); for(int i=0;i<27;i++){ int thread_args[4]; int initialrow; int initialcol; chk_t chk; if (i < 9) { chk = ROW; initialrow = i; initialcol = 0; } else if (i < 18) { chk = COLUMN; initialrow = 0; initialcol = (i-9); } else { chk = BLOCK; switch(i){ case 18: initialrow = 0; initialcol = 0; break; case 19: initialrow = 0; initialcol = 3; break; case 20: initialrow = 0; initialcol = 6; break; case 21: initialrow = 3; initialcol = 0; break; case 22: initialrow = 3; initialcol = 3; break; case 23: initialrow = 3; initialcol = 6; break; case 24: initialrow = 6; initialcol = 0; break; case 25: initialrow = 6; initialcol = 3; break; case 26: initialrow = 6; initialcol = 6; break; } } thread_args[0] = chk; thread_args[1] = initialrow; thread_args[2] = initialcol; thread_args[3] = i; pthread_create(&workers[i], 0, runner, (void *)thread_args); } for (i = 0; i < 27; i++){ pthread_join(workers[i], 0); } pthread_mutex_destroy(&lock); if (duplicate == 1){ printf("Is a invalid solution\\n"); } else{ printf("Is a valid solution\\n"); } for (i = 0; i < 9; i++) free(solution[i]); return 0; } void *runner(void *para){ int *thread_params = (int *)para; chk_t type = thread_params[0]; int initialrow = thread_params[1]; int initialcol = thread_params[2]; int thread_num = thread_params[3]; int i, j, val1, val2; if (type == ROW){ for (i = 0; i < 9; i++) { val1 = solution[initialrow][i]; for (j = 0; j < 9; j++) { val2 = solution[initialrow][j]; if (val1 == val2) { if (i != j){ printf("we found duplicate in [%d][%d]-[%d][%d] in thread %d \\n", initialrow, i, initialrow, j, thread_num); pthread_mutex_lock(&lock); duplicate = 1; pthread_mutex_unlock(&lock); break; break; } } } } printf("row down %d \\n" , thread_num); } else if (type == COLUMN){ for (i = 0; i < 9; i++) { val1 = solution[i][initialcol]; for (j = 0; j < 9; j++) { val2 = solution[j][initialcol]; if (val1 == val2) { if (i != j){ printf("we found duplicate in [%d][%d]-[%d][%d] in thread %d \\n", i, initialcol, j, initialcol, thread_num); pthread_mutex_lock(&lock); duplicate = 1; pthread_mutex_unlock(&lock); break; break; } } } } printf("column down %d \\n" , thread_num); } else if (type == BLOCK) { int clonearr[9]={1,2,3,4,5,6,7,8,9}; for (i = initialrow; i < initialrow+3; i++){ for (j = initialcol; j < initialcol+3; j++){ val2=solution[i][j]; if(clonearr[val2-1] == 0){ printf("we found duplicate in [%d][%d] in thread %d \\n", i, j, thread_num); pthread_mutex_lock(&lock); duplicate = 1; pthread_mutex_unlock(&lock); break; break; } clonearr[val2-1]=0; } } printf("block down %d \\n" , thread_num); } pthread_exit(0); }
1
#include <pthread.h> struct { pthread_cond_t cond; pthread_mutex_t mutex; int num; } sync = { .cond = PTHREAD_COND_INITIALIZER, .mutex = PTHREAD_MUTEX_INITIALIZER, .num = 0, }; void * pthread_signal(void * arg) { for ( ; ; ) { pthread_mutex_lock(&sync.mutex); if (0 == sync.num) { fprintf(stdout, "producer\\n"); sync.num++; } if (0 != sync.num) pthread_cond_signal(&sync.cond); fprintf(stdout, "producer sleep 1\\n"); pthread_mutex_unlock(&sync.mutex); usleep(1); fprintf(stdout, "procucer release lock\\n"); } pthread_exit(0); } void * pthread_wait(void * arg) { for ( ; ; ) { pthread_mutex_lock(&sync.mutex); while (0 == sync.num) { fprintf(stdout, "consume wait lock\\n"); pthread_cond_wait(&sync.cond, &sync.mutex); fprintf(stdout, "consume get lock\\n"); } fprintf(stdout, "consume...\\n"); sleep(1); sync.num--; pthread_mutex_unlock(&sync.mutex); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t pt_wait; pthread_create(&pt_wait, 0, pthread_wait, 0); pthread_t pt_signal; pthread_create(&pt_signal, 0, pthread_signal, 0); pthread_join(pt_wait, 0); pthread_join(pt_signal, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t semafor = PTHREAD_MUTEX_INITIALIZER; struct wiadomosc { char tresc[50]; }; struct buforCykliczny { struct wiadomosc tablica[256]; int licznik; int we; int wy; }; int czytaj (struct buforCykliczny *bufor, struct wiadomosc *wiadCel); int zapisz (struct buforCykliczny *bufor, struct wiadomosc *wiadZrodlo); int czytajKryt (struct buforCykliczny *bufor, struct wiadomosc *wiadCel); int zapiszKryt (struct buforCykliczny *bufor, struct wiadomosc *wiadZrodlo); void* producentFunc (void *arg); void* konsumentFunc (void *arg); void *producentFunc(void *arg) { struct buforCykliczny *bufor = (struct buforCykliczny*)(arg); struct wiadomosc locWiad; int i; for (i=0; i<20; i++) { sprintf(locWiad.tresc, "Wiadomość nr %d", i); while(zapiszKryt(bufor, &locWiad)) ; sleep(1); } return 0; } void *konsumentFunc(void *arg) { struct buforCykliczny *bufor = (struct buforCykliczny*)(arg); struct wiadomosc locWiad; int i; for (i=0; i<20; i++) { while(czytajKryt(bufor, &locWiad)) ; printf("Odebrałem wiadomość %s\\n", locWiad.tresc); sleep(1); } return 0; } int main() { struct buforCykliczny buforDanych; memset(&buforDanych, 0, sizeof (struct buforCykliczny)); pthread_t konsument; pthread_t producent; if ( pthread_create(&konsument, 0, konsumentFunc, (void *)(&buforDanych))) { printf("Błąd przy tworzeniu wątku konsumenta\\n"); abort(); } if ( pthread_create(&producent, 0, producentFunc, (void *)(&buforDanych))) { printf("Błąd przy tworzeniu wątku producenta\\n"); abort(); } if ( pthread_join (konsument, 0 ) ) { printf("Błąd w kończeniu wątku konsumenta\\n"); exit(0); } if ( pthread_join (producent, 0 ) ) { printf("Błąd w kończeniu wątku producenta\\n"); exit(0); } return 0; } int czytaj(struct buforCykliczny *bufor, struct wiadomosc *wiadCel) { if (bufor->licznik == 0) return 1; struct wiadomosc *wiadZrodlo = &bufor->tablica[bufor->wy]; memcpy(wiadCel, wiadZrodlo, sizeof(struct wiadomosc)); bufor->licznik = bufor->licznik - 1; bufor->wy = (bufor->wy +1) % 256; return 0; } int zapisz(struct buforCykliczny *bufor, struct wiadomosc *wiadZrodlo) { if (bufor->licznik == 256) return 1; struct wiadomosc *wiadCel = &bufor->tablica[bufor->we]; memcpy(wiadCel, wiadZrodlo, sizeof(struct wiadomosc)); bufor->licznik = bufor->licznik + 1; bufor->we = (bufor->we +1) % 256; return 0; } int czytajKryt(struct buforCykliczny *bufor, struct wiadomosc *wiadCel) { int wynik; do { pthread_mutex_lock(&semafor); wynik = czytaj(bufor, wiadCel); pthread_mutex_unlock(&semafor); } while (wynik == 1); return wynik; } int zapiszKryt(struct buforCykliczny *bufor, struct wiadomosc *wiadZrodlo) { int wynik; do { pthread_mutex_lock(&semafor); wynik = zapisz(bufor, wiadZrodlo); pthread_mutex_unlock(&semafor); } while (wynik == 1); return wynik; }
1
#include <pthread.h> char searchWords[10000][KEYWORD_SIZE]; bool result[10000]; int searchWordCount = 0; FILE * keywordsFile = 0; FILE * searchWordsFile = 0; pthread_mutex_t search_mutex; bool readKeyWordsNBuildBST() { char word[KEYWORD_SIZE]; while (fgets(word, sizeof(word), keywordsFile)) { if(!insert(word)) return 0; } return 1; } void * readNSearch(void *arg) { pthread_mutex_lock(&search_mutex); int steps = searchWordCount / 100 ; int offset = *(int *)arg; int loc = 0; int loopCtr = 0; for(loopCtr = 0; loopCtr <= steps; loopCtr++) { loc = 100 * loopCtr + offset; if(loc < searchWordCount) { if(find(searchWords[loc])) { result[loc] = 1; } else { result[loc] = 0; } } } pthread_mutex_unlock(&search_mutex); return 0; } bool searchForWords() { pthread_t threads[100]; int count = 0; char word[KEYWORD_SIZE]; while (fgets(word, sizeof(word), searchWordsFile)) { strcpy(searchWords[searchWordCount], word); searchWordCount++; } for(count = 0; count < 100; count++) { pthread_create( &threads[count], 0, readNSearch, (void*) &count); } for(count = 0; count < 100; count++) { pthread_join(threads[count], 0); } for (count = 0; count < searchWordCount; count++) { printf("%s : %d\\n", searchWords[count], result[count]); } return 1; } int main() { keywordsFile = fopen("keywords.txt", "r"); if(0 == keywordsFile) { printf("Unable to open the keyword file ..... exiting\\n"); return -1; } searchWordsFile = fopen("searchWords.txt", "r"); if(0 == searchWordsFile) { printf("Unable to open the searchWords file ..... exiting\\n"); fclose(keywordsFile); return -1; } if(!readKeyWordsNBuildBST()) { fclose(keywordsFile); fclose(searchWordsFile); return -1; } if(!searchForWords()) { fclose(keywordsFile); fclose(searchWordsFile); return -1; } fclose(keywordsFile); fclose(searchWordsFile); return 0; }
0
#include <pthread.h> static int pixel_mode = 0; static struct console_font_op orig_font; static unsigned char orig_font_data[65536]; struct winsize size; static unsigned char *color_map; static pthread_mutex_t print_lock = PTHREAD_MUTEX_INITIALIZER; int tb_screen_init(int pixel_size) { struct console_font_op new_font; unsigned char new_font_data[256*32]; if (pixel_size < 1 || pixel_size > 8) return -1; if (!pixel_mode) { orig_font.op = KD_FONT_OP_GET; orig_font.flags = 0; orig_font.width = orig_font.height = 32; orig_font.charcount = 1024; orig_font.data = orig_font_data; FAILIF(ioctl(STDOUT_FILENO, KDFONTOP, &orig_font)); if (isatty(STDERR_FILENO)) freopen("/dev/null", "w", stderr); } if (pixel_mode != pixel_size) { memset(new_font_data + ' '*32, 0xFF, 32); new_font.op = KD_FONT_OP_SET; new_font.flags = 0; new_font.width = pixel_size; new_font.height = pixel_size; new_font.charcount = 256; new_font.data = new_font_data; FAILIF(ioctl(STDOUT_FILENO, KDFONTOP, &new_font)); pixel_mode = pixel_size; FAILIF(ioctl(STDOUT_FILENO, TIOCGWINSZ, &size)); free(color_map); color_map = calloc(sizeof(char), size.ws_col*size.ws_row); if (color_map == 0) { tb_screen_restore(); return -1; } } printf("\\x1B""c"); printf("\\x1B[?25l"); return 0; } void tb_screen_size(int *width, int *height) { *width = size.ws_col; *height = size.ws_row; } void tb_screen_color(enum tb_color color, int value) { printf("\\x1B]P%X%.6X", color, value); } int tb_screen_put(int x, int y, enum tb_color color) { static int lastx = -1, lasty = -1; if (x >= size.ws_col || y >= size.ws_row || x < 0 || y < 0) return -1; pthread_mutex_lock(&print_lock); if (color_map[x + y*size.ws_col] != color) { if (x != lastx+1 || y != lasty) printf("\\x1B[%d;%df", y+1, x+1); printf("\\x1B[%d;3%dm" "%c", (color & TB_COLOR_BOLD) != 0, color & ~TB_COLOR_BOLD, ' '); color_map[x + y*size.ws_col] = color; lastx = x; lasty = y; } pthread_mutex_unlock(&print_lock); return 0; } int tb_screen_flush(void) { return fflush(stdout); } int tb_screen_restore(void) { if (pixel_mode) { printf("\\x1B""c"); printf("\\x1B]R"); size.ws_col = size.ws_row = 0; free(color_map); orig_font.op = KD_FONT_OP_SET; FAILIF(ioctl(STDOUT_FILENO, KDFONTOP, &orig_font)); pixel_mode = 0; } return 0; }
1
#include <pthread.h> struct { pthread_mutex_t mutex; int buff[10]; int nitems; } shared = { PTHREAD_MUTEX_INITIALIZER }; void* produce(void* arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nitems >= 1000000) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[*((int*) arg)]++; shared.nitems++; pthread_mutex_unlock(&shared.mutex); } } int consume_wait() { int wait; pthread_mutex_lock(&shared.mutex); wait = shared.nitems < 1000000; pthread_mutex_unlock(&shared.mutex); return wait == 1; } void* consume(void* arg) { int i; for (;;) if (!consume_wait()) break; for (i = 0; i < 10; ++i) printf("buff[%d] = %d\\n", i, shared.buff[i]); return 0; } int main() { int i; pthread_t produce_threads[10]; pthread_t consume_thread; for (i = 0; i < 10; ++i) pthread_create(&produce_threads[i], 0, produce, &i); for (i = 0; i < 10; ++i) pthread_join(produce_threads[i], 0); pthread_create(&consume_thread, 0, consume, 0); pthread_join(consume_thread, 0); return 0; }
0
#include <pthread.h> int available[3]; int maximum[5][3]; int allocation[5][3]; int need[5][3]; pthread_mutex_t mutexavail; pthread_mutex_t mutexalloc; pthread_mutex_t mutexneed; int request_resources(int customer_num, int request[]); int release_resources(int customer_num, int request[]); void print_matrix(int M[5][3],char *name); void generate_maximum() { int ii,jj; srand(time(0)); for(ii=0;ii<5;ii++) { for(jj=0;jj<3;jj++) { maximum[ii][jj] = 10; allocation[ii][jj] = 0; } } } int request_resources(int customer_num, int request[]) { int iter,j,ii; printf("\\n %d customer request arrived ", customer_num); for(iter=0;iter<3;iter++) { if(request[iter] > need[customer_num][iter]) return -1; } for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] += request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] -= request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexneed); } printf("\\n Available Matrix \\n"); for(ii=1;ii<=3;ii++) { printf("%d ",available[ii-1]); } printf("\\n"); print_matrix(allocation,"allocation"); print_matrix(need,"need"); print_matrix(maximum,"max"); if(check_safe()<0) { for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] += request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] += request[iter]; pthread_mutex_unlock(&mutexneed); } return -1; } else printf("\\n Hurray! I am accepted %d",customer_num); return 0; } int release_resources(int customer_num, int request[]) { int iter; for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] += request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] = maximum[customer_num][iter] + allocation[customer_num][iter]; pthread_mutex_unlock(&mutexneed); } return 1; } int check_safe() { int ii,jj, work[3],finish[5]; int success_flag = 0; for(ii=0;ii<3;ii++) { work[ii] = available[ii]; } for(ii=0;ii<5;ii++) { finish[ii] = 0; } for(ii=0;ii<5;ii++) { if(finish[ii]==0) { for(jj=0;jj<3;jj++) { if(need[ii][jj] > work[jj]) return -1; } for(jj=0;jj<3;jj++) work[jj] += allocation[ii][jj]; success_flag = 1; } } return success_flag; } void *thread_create(void *cno) { int ii,j,request[3],request_flag=0; int cust_no = (int)cno; for(ii=0;ii<3;ii++) { request[ii] = rand() % available[ii]; } if(request_resources(cust_no,request)<0) { printf("\\n Customer %d ", cust_no); for(j=0;j<3;j++) printf("%d ", request[j]); printf(":Request Denied\\n"); } else { request_flag = 1; printf("\\n Customer %d ", cust_no); for(j=0;j<3;j++) printf("%d ", request[j]); printf(":Request Accepted\\n"); } sleep(rand() % 10); if(request_flag==1) { release_resources(cust_no, request); printf("\\n Customer %d released resouces", cust_no); } } void print_matrix(int M[5][3],char *name) { int i,j; printf("\\n-----%s Matrix----\\n",name); for(i=0;i<5;i++) { for(j=0;j<3;j++) printf("%d ",M[i][j]); printf("\\n"); } } int main(int argc, char **argv) { int ii,jj,kk,run_count = 1; pthread_t thread_id; if(argc==(3 +1)) { printf("\\n Available Matrix \\n"); for(ii=1;ii<=3;ii++) { available[ii-1] = abs(atoi(argv[ii])); printf("%d ",available[ii-1]); } printf("\\n"); } generate_maximum(); printf("\\n Maximum matrix is: \\n"); for(ii=0; ii<5;ii++) { for(jj=0; jj<3; jj++) { need[ii][jj] = maximum[ii][jj] - allocation[ii][jj]; printf("%d ",maximum[ii][jj]); } printf("\\n"); } printf("\\n Need Matrix\\n"); for(ii=0; ii< 5;ii++) { for(jj=0;jj<3;jj++) { printf("%d ",need[ii][jj]); } printf("\\n"); } for(ii=0;ii<run_count;ii++) { for(jj=0;jj<5;jj++) { printf("\\n creating %d",jj); pthread_create(&thread_id,0,thread_create,(void *)jj); } } printf("\\n All threads finished without any deadlocks! "); return 0; }
1
#include <pthread.h> struct task { char msg[64]; }; struct task *tp; pthread_cond_t qready = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void delay(int secs) { time_t t; for (t=time(0); t+secs>time(0); ) ; } void *process_task(void *arg) { pthread_mutex_lock(&qlock); while (tp == 0) pthread_cond_wait(&qready, &qlock); printf("Task message: %s\\n", tp -> msg); pthread_mutex_unlock(&qlock); return (void *)0; } void *enqueue_msg(void *arg) { char *msg = "Hello, there"; pthread_mutex_lock(&qlock); delay(5); tp = (struct task *)malloc(sizeof(struct task)); memcpy(tp -> msg, msg, strlen(msg)+1); pthread_mutex_unlock(&qlock); pthread_cond_signal(&qready); return (void *)0; } int main(void) { int err; pthread_t tid1, tid2; err = pthread_create(&tid1, 0, process_task, 0); if (err != 0) { fprintf(stderr, "pthread_create error: %s\\n", strerror(err)); exit(-1); } err = pthread_create(&tid2, 0, enqueue_msg, 0); if (err != 0) { fprintf(stderr, "pthread_create error: %s\\n", strerror(err)); exit(-1); } void *tret; err = pthread_join(tid1, &tret); if (err != 0) { fprintf(stderr, "pthread_join error: %s\\n", strerror(err)); exit(-1); } printf("thread1 exited with status: %ld\\n", (long)tret); err = pthread_join(tid2, &tret); if (err != 0) { fprintf(stderr, "pthread_join error: %s\\n", strerror(err)); exit(-1); } printf("thread1 exited with status: %ld\\n", (long)tret); return 0; }
0
#include <pthread.h> static int isPing = 0; static pthread_mutex_t count_mutex; static pthread_cond_t count_thresholder_cv; void *functionA(void *t) { int counter = 0; pthread_mutex_lock(&count_mutex); while(!isPing) { pthread_cond_signal(&count_thresholder_cv); if (counter == 1000) { break; } printf("ping\\n"); counter++; isPing = 1; pthread_cond_wait(&count_thresholder_cv, &count_mutex); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } void *functionB(void *t) { int counter = 0; pthread_mutex_lock(&count_mutex); while(isPing) { printf("\\tpong\\n"); counter++; isPing = 0; pthread_cond_signal(&count_thresholder_cv); if (counter == 1000) { break; } pthread_cond_wait(&count_thresholder_cv, &count_mutex); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char **argv) { pthread_t threads[2]; pthread_mutex_init(&count_mutex,0); pthread_cond_init(&count_thresholder_cv,0); int counter; pthread_create(&threads[0],0,functionA,0); pthread_create(&threads[1],0,functionB,0); for (int i=0; i<2; i++) { pthread_join(threads[i],0); } pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_thresholder_cv); pthread_exit(0); return 0; }
1
#include <pthread.h> int _debug = -77; void debug(char *fmt, ...) { if(_debug == -77) { char *buf = getenv("EZTRACE_DEBUG"); if(buf == 0) _debug = 0; else _debug = atoi(buf); } if(_debug >= 0) { va_list va; __builtin_va_start((va)); vfprintf(stdout, fmt, va); ; } } unsigned long long tick; struct { unsigned low; unsigned high; }; } tick_t; sem_t thread_ready; sem_t sem[2]; pthread_mutex_t mutex; void compute(int usec) { struct timeval tv1,tv2; gettimeofday(&tv1,0); do { gettimeofday(&tv2,0); }while(((tv2.tv_sec - tv1.tv_sec) * 1000000 + (tv2.tv_usec - tv1.tv_usec)) < usec); } void* f_thread(void* arg) { uint8_t my_id=*(uint8_t*) arg; sem_post(&thread_ready); int i; for(i=0; i<10; i++){ sem_wait(&sem[my_id]); pthread_mutex_lock(&mutex); compute(50000); pthread_mutex_unlock(&mutex); compute(50000); sem_post(&sem[(my_id+1)%2]); } return 0; } int main(int argc, char**argv) { pthread_t tid[2]; int i; pthread_mutex_init(&mutex, 0); sem_init(&thread_ready, 0, 0); for(i=0 ; i<2; i++) sem_init(&sem[i], 0, 0); for(i=0;i<2; i++) { pthread_create(&tid[i], 0, f_thread, &i); sem_wait(&thread_ready); } sem_post(&sem[0]); for(i=0;i<2; i++) { pthread_join(tid[i], 0); } return 0; }
0
#include <pthread.h> static pthread_cond_t response_cond = PTHREAD_COND_INITIALIZER; bool send_request(struct server_data* server, const char* request, int request_length) { int socket_fd = get_client_socket_fd(); char ip_address_str[INET_ADDRSTRLEN]; inet_ntop(AF_INET, &server->address.sin_addr, ip_address_str, INET_ADDRSTRLEN); int port = ntohs(server->address.sin_port); char request_type_str[MTN_REQ_TYPE_LEN + 1]; get_request_type_str(request_type_str, get_request_type(request)); if(sendto(socket_fd, request, request_length, 0, (struct sockaddr *) &(server->address), sizeof(server->address)) == -1) { error_errno("cannot send %s request to %s:%d", request_type_str, ip_address_str, port); return 0; } time_t send_time; if((send_time = time(0)) == -1) { fatal_error(1, "cannot measure time"); } info("Sending %s request to %s:%d", request_type_str, ip_address_str, port); struct timespec timeout; timeout.tv_sec = send_time + SERVER_RESPONSE_TIMEOUT; timeout.tv_nsec = 0; pthread_mutex_lock(&server->mutex); while(server->state != RESP) { if(pthread_cond_timedwait(&response_cond, &server->mutex, &timeout) == ETIMEDOUT) { info("Server %s:%d is not responding to %s request", ip_address_str, port, request_type_str); server->last_connect_attempt_time = send_time; server->not_connect_count++; if(server->not_connect_count % MAX_NOT_CONNECT_COUNT == 0) { server->state = WAIT; } pthread_mutex_unlock(&server->mutex); return 0; } } char response_type_str[MTN_RES_TYPE_LEN + 1]; get_response_type_str(response_type_str, get_response_type(server->response)); time_t connect_time; if((connect_time = time(0)) == -1) { fatal_error(1, "cannot measure time"); } info("Receiving %s response from %s:%d", response_type_str, ip_address_str, port); info("%s", server->response); server->last_connect_attempt_time = connect_time; server->not_connect_count = 0; pthread_mutex_unlock(&server->mutex); return 1; } void receive_response(const char* response, struct sockaddr_in* server_address) { struct server_map_node* node; HASH_FIND(hh, *client_server_map(), server_address, sizeof(server_map_key), node); pthread_mutex_lock(&node->data->mutex); strcpy(node->data->response, response); node->data->state = RESP; pthread_cond_broadcast(&response_cond); pthread_mutex_unlock(&node->data->mutex); }
1
#include <pthread.h> pthread_mutex_t mutex; void *thread_func1(void *p) { long int i=0; while(i<1000000) { i++; pthread_mutex_lock(&mutex); (*(long int*)p)++; pthread_mutex_unlock(&mutex); } pthread_exit((void*)i); } void *thread_func2(void *p) { long int i=0; while(i<1000000) { i++; pthread_mutex_lock(&mutex); (*(long int*)p)++; pthread_mutex_unlock(&mutex); } pthread_exit((void*)i); } int main() { pthread_t thid1,thid2; long int ret1=0,ret2=0; long int *p=(long int *)malloc(sizeof(long int)); pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&mutex,&mutexattr); pthread_create(&thid1,0,thread_func1,p); pthread_create(&thid2,0,thread_func2,p); pthread_join(thid1,(void**)&ret1); printf("the first child thread return value is %ld\\n",ret1); pthread_join(thid2,(void**)&ret2); printf("the second child thread return value is %ld\\n",ret2); pthread_mutex_destroy(&mutex); printf("the sum=%ld\\n",*p); }
0
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t cond_variable; int count; int count_limit; void * increment () { printf ("Increment thread Starts\\n"); while (1) { pthread_mutex_lock (&lock); count++; if (count == count_limit) { pthread_cond_signal (&cond_variable); printf ("Signal sent\\n"); } if (count > count_limit) { pthread_mutex_unlock (&lock); break; } pthread_mutex_unlock (&lock); } printf ("Increment thread Exits\\n"); pthread_exit (0); } void * watch () { printf ("Watching thread started\\n"); pthread_mutex_lock (&lock); if (count < count_limit) { printf ("Watching thread waiting\\n"); pthread_cond_wait (&cond_variable, &lock); } printf ("Value of count in Watch is %d\\n", count); pthread_mutex_unlock (&lock); printf ("Watching thread Exits\\n"); pthread_exit (0); } int main (int argc, char *argv[]) { if(argc != 2) { printf("Requires count threshold as argument\\n"); exit(1); } count_limit = atoi (argv[1]); count = 0; int i; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init (&lock, 0); pthread_cond_init (&cond_variable, 0); pthread_attr_init (&attr); pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE); pthread_create (&threads[0], &attr, watch, 0); pthread_create (&threads[1], &attr, increment, 0); pthread_create (&threads[2], &attr, increment, 0); pthread_attr_destroy (&attr); void *status; for (i = 0; i < 3; i++) { pthread_join (threads[i], &status); } pthread_attr_destroy (&attr); pthread_mutex_destroy (&lock); pthread_cond_destroy (&cond_variable); pthread_exit (0); }
1
#include <pthread.h> pthread_mutex_t mutex; int* vet; } Vector; Vector V; void merge(int *vet, int left, int middle, int right); void* threadedMergeSort(int* args); int main(int argc, char** argv) { int i, n; int args[2]; if (argc != 2) { fprintf (stderr, "Wrong number of arguments. Syntax: %s dimension\\n", argv[0]); return -1; } n = atoi(argv[1]); V.vet = (int*)malloc(n*sizeof(int)); pthread_mutex_init(&V.mutex, 0); srand(n); fprintf(stdout, "Array before sorting: "); pthread_mutex_lock(&V.mutex); for(i = 0; i < n; i++) { V.vet[i] = rand() % 100; fprintf(stdout, "%d ", V.vet[i]); } pthread_mutex_unlock(&V.mutex); fprintf(stdout, "\\n"); args[0] = 0; args[1] = n-1; threadedMergeSort(args); fprintf(stdout, "Array after sorting: "); pthread_mutex_lock(&V.mutex); for(i = 0; i < n; i++) { fprintf(stdout, "%d ", V.vet[i]); } pthread_mutex_unlock(&V.mutex); fprintf(stdout, "\\n"); return 0; } void* threadedMergeSort(int* args) { int* arg = args; int left, middle, right; int argsA[2], argsB[2]; pthread_t threadA, threadB; void* retValue; left = arg[0]; right = arg[1]; if (left < right) { middle = left + (right - left)/2; argsA[0] = left; argsA[1] = middle; pthread_create(&threadA, 0, (void*)threadedMergeSort, (void*)argsA); argsB[0] = middle + 1; argsB[1] = right; pthread_create(&threadB, 0, (void*)threadedMergeSort, (void*)argsB); pthread_join(threadA, &retValue); pthread_join(threadB, &retValue); pthread_mutex_lock(&V.mutex); merge(V.vet, left, middle, right); pthread_mutex_unlock(&V.mutex); } return (void*)0; } void merge(int *vet, int left, int middle, int right) { int i, j, k; int n1 = middle - left + 1; int n2 = right - middle; int L[n1], R[n2]; for (i = 0; i <= n1; i++) { L[i] = vet[left + i]; } for (j = 0; j <= n2; j++) { R[j] = vet[middle + 1 + j]; } i = 0; j = 0; k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) { vet[k++] = L[i++]; } else { vet[k++] = R[j++]; } } while (i < n1) { vet[k++] = L[i++]; } while (j < n2) { vet[k++] = R[j++]; } return; }
0
#include <pthread.h> struct prodcons { int buffer[16]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct prodcons *b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct prodcons *b, int data) { pthread_mutex_lock(&b->lock); if ((b->writepos + 1) % 16 == b->readpos) { pthread_cond_wait(&b->notfull, &b->lock); } b->buffer[b->writepos] = data; b->writepos++; if (b->writepos >= 16) b->writepos = 0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons *b) { int data; pthread_mutex_lock(&b->lock); if (b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if (b->readpos >= 16) b->readpos = 0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void *producer(void *data) { int n; for (n = 0; n < 10000; n++) { sleep(1); printf("%d --->\\n", n); put(&buffer, n); } put(&buffer, ( - 1)); return 0; } void *consumer(void *data) { int d; while (1) { d = get(&buffer); if (d == ( - 1)) break; printf("---> %d\\n", d); } return 0; } int main(void) { pthread_t th_a, th_b; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); printf("main thread end.\\n"); return 0; }
1
#include <pthread.h> { unsigned int init; char name[20]; unsigned int dt; unsigned int deadline; char prior; }trace; pthread_t threadID[100]; struct arg_struct { int delay; int id; }; trace processTable[100]; pthread_mutex_t *mutex; void showPT(trace processTable[], int size); void getTokens(char *line, trace *process); void *first_counter(void *void_delay); void *counter(void *arguments); int main(int argc, char *argv[]) { int x; int y = 0; int size = 0; char line[100]; char *token; int id; clock_t t; long now; struct arg_struct args; if (argc < 4) { printf("USAGE: ./ep1 x(1 to 6) traceFile resultFile -d(optional)\\n"); exit(0); } id = atoi(argv[1]); FILE *trace; if ((trace = fopen(argv[2],"r")) == 0) { printf("arquivo:%s nao encontrado\\n",argv[2]); exit(0); } for (x = 0; x < 100; x++) line[x] = 0; while (1) { if (fgets(line, 100, trace) == 0) break; size++; getTokens(line, &processTable[size -1]); } switch(id) { case 1: y = 0; t = clock(); while (1) { now = (long)(clock() - t) / CLOCKS_PER_SEC; if ( now == processTable[y].init && y == 0) { if (pthread_create(&threadID[y], 0, first_counter, (void *) &processTable[y].dt) != 0) { printf("ERROR\\n"); exit(0); } printf("Thread[%d] inicializada\\n",y); y++; } if ( now == processTable[y].init && y > 0) { args.delay = processTable[y].dt; args.id = (y - 1); if (pthread_create(&threadID[y], 0, counter, (void *) &args) != 0) { printf("ERROR\\n"); exit(0); } printf("Thread[%d] inicializada\\n",y); y++; } if ( y == size) { printf("Ultimo, vou esperar...\\n"); for (x = 0; x < size; x ++) pthread_join(threadID[x],0); printf(".....Vixes ja foi\\n"); break; } } break; } return (0); } void showPT(trace processTable[], int size) { printf("init | name | dt | deadline | prior |\\n"); int x = 0; for (x; x < size; x++) printf("%d | %s | %d | %d | %d |\\n",processTable[x].init,processTable[x].name,processTable[x].dt,processTable[x].deadline, processTable[x].prior ); } void getTokens(char *line, trace *process) { int x; int y; int z; char buffer[20]; for (x = 0; x < 20; x++) buffer[x] = 0; for (x = 0; line[x] != ' '; x++) buffer[x] = line[x]; process->init = atoi(buffer); x++; for (y = 0; line[x] != ' '; x++) { buffer[y] = line[x]; y++; } strcpy (process->name, buffer); x++; for (y = 0; line[x] != ' '; x++) { buffer[y] = line[x]; y++; } process->dt = atoi(buffer); x++; for (y = 0; line[x] != ' '; x++) { buffer[y] = line[x]; y++; } process->deadline = atoi(buffer); x++; for (y = 0; line[x] != '\\n' && line[x] != 0; x++) { buffer[y] = line[x]; y++; } process->prior = atoi(buffer); } void *first_counter(void *void_delay) { float delay = *((float *)(void_delay)); clock_t t,now; t = clock(); while (1) { now = (double)(clock() - t) / CLOCKS_PER_SEC; if ( now >= delay) { break; } } printf("---Thread[0] Acabou!---\\n"); return 0; } void *counter(void *arguments) { struct arg_struct *args = arguments; printf("Esperando a thread[%d] acabar...\\n", args->id); if (pthread_join(threadID[args->id],0) != 0) { printf("DEU RUIM\\n"); pthread_exit(0); } printf("Acabou\\n"); clock_t t,now; t = clock(); pthread_mutex_lock(&mutex); while (1) { now = (double)(clock() - t) / CLOCKS_PER_SEC; if ( now >= args->delay) { break; } } pthread_mutex_unlock(&mutex); printf("---Thread[%d] Acabada!---\\n",(args->id + 1)); pthread_exit(0); return 0; }
0
#include <pthread.h> static bool music_playing = 0; static pthread_mutex_t music_playing_mutex = PTHREAD_MUTEX_INITIALIZER; static int musicnum = 0; static pthread_mutex_t musicnum_mutex = PTHREAD_MUTEX_INITIALIZER; bool get_music_playing (void) { bool value; pthread_mutex_lock (&music_playing_mutex); value = music_playing; pthread_mutex_unlock (&music_playing_mutex); return value; } bool set_music_playing (bool new_value) { bool old_value; pthread_mutex_lock (&music_playing_mutex); old_value = music_playing; music_playing = new_value; pthread_mutex_unlock (&music_playing_mutex); return old_value; } int get_musicnum (void) { int value; pthread_mutex_lock (&musicnum_mutex); value = musicnum; pthread_mutex_unlock (&musicnum_mutex); return value; } int set_musicnum (int new_value) { int old_value; pthread_mutex_lock (&musicnum_mutex); old_value = musicnum; musicnum = new_value; pthread_mutex_unlock (&musicnum_mutex); return old_value; }
1
#include <pthread.h> extern int service_quit; static pthread_mutex_t active_pic_update_mutex = PTHREAD_MUTEX_INITIALIZER; struct picture_s *active_pic = 0; static int active_pic_update = 0; static int pic_shift_event_handler(int event_id, struct event_id_s event_id_table, struct picture_s *p_pic) { int ret = -1; if (event_id_table.pre_event != -1 && event_id == event_id_table.pre_event) { if (p_pic->pre_pic != 0) { printf("pre\\n"); active_pic = p_pic->pre_pic; ret = 0; } } else if (event_id_table.next_event != -1 && event_id == event_id_table.next_event) { if (p_pic->next_pic != 0) { printf("next\\n"); active_pic = p_pic->next_pic; ret = 0; } } else if (event_id_table.child_event != -1 && event_id == event_id_table.child_event) { if (p_pic->child_pic!= 0) { printf("child\\n"); active_pic = p_pic->child_pic; active_pic->parent_pic = p_pic; ret = 0; } } else if (event_id_table.parent_event != -1 && event_id == event_id_table.parent_event) { if (p_pic->parent_pic != 0) { printf("return\\n"); active_pic = p_pic->parent_pic; active_pic->child_pic = p_pic; ret = 0; } } return ret; } static int lcd_event_handler(int event_id) { int i; int j; int event_trigger = 0; if (event_id == active_pic->event_id.pre_event || event_id == active_pic->event_id.next_event || event_id == active_pic->event_id.child_event || event_id == active_pic->event_id.parent_event) { if (pic_shift_event_handler(event_id, active_pic->event_id, active_pic) == 0) { trigger_display(); return 0; } } for (i = 0; i < active_pic->windows_num; i++) { if (active_pic->p_win[i].knob_event_handler.knob_pos_event > 0 && active_pic->p_win[i].knob_event_handler.knob_pos_event == event_id) { active_pic->p_win[i].knob_event_handler.event_handler(KEY_KNOB_POS, &active_pic->p_win[i]); event_trigger = 1; } else if (active_pic->p_win[i].knob_event_handler.knob_neg_event > 0 && active_pic->p_win[i].knob_event_handler.knob_neg_event == event_id) { active_pic->p_win[i].knob_event_handler.event_handler(KEY_KNOB_NEG, &active_pic->p_win[i]); event_trigger = 1; } for (j = 0; j < 32; j++) { if (active_pic->p_win[i].misc_event_handlers[i].event_id > 0 && active_pic->p_win[i].misc_event_handlers[i].event_id == event_id) { active_pic->p_win[i].misc_event_handlers[i].event_handler(event_id, &active_pic->p_win[i]); event_trigger = 1; } } } if (event_trigger == 1) { trigger_display(); } return 0; } void lcd_display_event_handler(struct br_event_t *p_br_event) { if (p_br_event->event_id != BROADCAST_KEY_EVENT_ID) { PRINT("not key event: %d\\n", p_br_event->event_id); return; } lcd_event_handler(p_br_event->event_state); } void trigger_display() { pthread_mutex_lock(&active_pic_update_mutex); active_pic_update = 1; pthread_mutex_unlock(&active_pic_update_mutex); } void *lcd_display_loop(void *arg) { while (!service_quit) { pthread_mutex_lock(&active_pic_update_mutex); if (active_pic_update == 1) { display_picture(active_pic); active_pic_update = 0; } pthread_mutex_unlock(&active_pic_update_mutex); usleep(10*1000); } return 0; }
0
#include <pthread.h> unsigned int COUNTER; pthread_mutex_t LOCK; pthread_mutex_t START; pthread_cond_t CONDITION; void* threads (void* unused) { pthread_mutex_lock(&START); pthread_mutex_unlock(&START); pthread_mutex_lock(&LOCK); if (COUNTER > 0) { pthread_cond_signal(&CONDITION); } for (;;) { COUNTER++; pthread_cond_wait(&CONDITION, &LOCK); pthread_cond_signal(&CONDITION); } pthread_mutex_unlock(&LOCK); } void cs_speed() { pthread_t t1, t2; struct timeval ti1, ti2, tsub; unsigned int t; pthread_mutex_lock(&START); COUNTER = 0; pthread_create(&t1, 0, threads, 0); pthread_create(&t2, 0, threads, 0); pthread_detach(t1); pthread_detach(t2); gettimeofday(&ti1, 0); pthread_mutex_unlock(&START); sleep(10); pthread_mutex_lock(&LOCK); gettimeofday(&ti2, 0); timersub(&ti2, &ti1, &tsub); t = tsub.tv_sec * 1000000 + tsub.tv_usec; printf("COUNTER: %d, time: %d us, CS per us: %lf\\n", COUNTER, t, (double)COUNTER / (double)t); } int main(int lb, char** par) { cs_speed(); return 0; }
1
#include <pthread.h> sem_t fillCount; sem_t emptyCount; pthread_mutex_t thread_flag_mutex; void putInWarehouse(int item, int size, int* wh, int* itemCount); int produceItem(); void consumeItem(int size, int* wh); void initialize_flag () { pthread_mutex_init (&thread_flag_mutex, 0); } struct thread_args { int size; int* ptr_wh; int* ptr_itemCount; }; void* producer(void* arg) { struct thread_args* p = (struct thread_args*) arg; int item; while (1) { item = produceItem(); sem_wait(&emptyCount); pthread_mutex_lock (&thread_flag_mutex); putInWarehouse(item, p->size, p->ptr_wh, p->ptr_itemCount); pthread_mutex_unlock(&thread_flag_mutex); sem_post(&fillCount); } } void putInWarehouse(int item, int size, int* wh, int* itemCount) { int i; for (i = 0; i < size; ++i) { if (wh[i] == 0) { wh[i] = item; (*itemCount) += 1; printf("Produced wh[%d]: %d ItemCount: %d\\n", i, wh[i], (*itemCount)); break; } } } int produceItem() { return rand() % 100 + 1; } void consumeItem(int size, int* wh) { int i; int item; int found = 0; for (i = 0; i < size; i++) { if (wh[i] != 0) { item = wh[i]; wh[i] = 0; found = 1; break; } } if (found) printf("consumeItem: wh[%d] %d\\n", i, item); } void* consumer(void* arg) { int item; struct thread_args* p = (struct thread_args*) arg; while (1) { sem_wait(&fillCount); pthread_mutex_lock(&thread_flag_mutex); consumeItem(p->size, p->ptr_wh); pthread_mutex_unlock(&thread_flag_mutex); sem_post(&emptyCount); } } void init_warehouse(int limit, int* wh) { int i; for (i = 0; i < limit; ++i) wh[i] = 0; } int main(int argc, char* argv[]) { int size = 100; int warehouse[size]; int i; int itemCount = 0; pthread_t thread_producer1; pthread_t thread_producer2; pthread_t thread_producer3; pthread_t thread_producer4; pthread_t thread_consumer1; pthread_t thread_consumer2; pthread_t thread_consumer3; pthread_t thread_consumer4; struct thread_args pc_args; sem_init(&fillCount, 0, 0); sem_init(&emptyCount, 0, size); init_warehouse(size, warehouse); initialize_flag(); pc_args.size = size; pc_args.ptr_wh = &warehouse[0]; pc_args.ptr_itemCount = &itemCount; pthread_create (&thread_producer1, 0, &producer, &pc_args); pthread_create (&thread_producer2, 0, &producer, &pc_args); pthread_create (&thread_producer3, 0, &producer, &pc_args); pthread_create (&thread_producer4, 0, &producer, &pc_args); pthread_create (&thread_consumer1, 0, &consumer, &pc_args); pthread_create (&thread_consumer2, 0, &consumer, &pc_args); pthread_create (&thread_consumer3, 0, &consumer, &pc_args); pthread_create (&thread_consumer4, 0, &consumer, &pc_args); pthread_join (thread_producer1, 0); pthread_join (thread_producer2, 0); pthread_join (thread_producer3, 0); pthread_join (thread_producer4, 0); pthread_join (thread_consumer1, 0); pthread_join (thread_consumer2, 0); pthread_join (thread_consumer3, 0); pthread_join (thread_consumer4, 0); printf("Producer ended.\\n"); printf("Consumer ended.\\n"); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(400)]; 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==(400)) { 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<(400); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(400); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thrd_func(void *arg); int main() { pthread_t thread[3]; int no; void *tret; srand((int)time(0)); pthread_mutex_init(&mutex,0); for(no=0;no<3;no++) { if(pthread_create(&thread[no],0,thrd_func,(void*)no)!=0) { printf("create thread %d error\\n",no); exit(1); } else { printf("create thread %d succcess!\\n",no); } } for(no=0;no<3;no++) { if(pthread_join(thread[no],&tret)!=0) { printf("join thread %d error\\n",no); exit(1); } else { printf("join thread %d success\\n",no); } } pthread_mutex_destroy(&mutex); return 0; } void *thrd_func(void *arg) { int thrd_num=(void*)arg; int delay_time=0; int count=0; if(pthread_mutex_lock(&mutex)!=0) { printf("thread %d lock failed!\\n",thrd_num); pthread_exit(0); } printf("thread %d is starting\\n",thrd_num); for(count=0;count<5;count++) { delay_time=(int)(4*(rand()/(double)32767))+1; sleep(delay_time); printf("\\tthread %d:job %d delay %d.\\n",thrd_num,count,delay_time); } printf("thread %d is exiting.\\n",thrd_num); pthread_mutex_unlock(&mutex); pthread_exit(0); }
0
#include <pthread.h> int GbStop = 0; void sigaction_handle_fun(int signo, siginfo_t * siginfo, void * sigcontext) { printf("sigaction_handle_fun signo:%d\\n", signo); char* strsig = strsignal(signo); if(strsig != 0) { printf("strsig:%s\\n", strsig); } GbStop = 1; } void atexit_fun1() { printf("atexit_fun1\\n"); } void atexit_fun2() { printf("atexit_fun2\\n"); } void cleanup_fun(void* arg) { printf("cleanup_fun %s\\n", (char*)arg); } struct counter_t { pthread_mutex_t m_mutex; int m_cout; } gcounter; void * pthread_fun0(void* arg) { char* charg = (char*)arg; printf("pthread_fun0 arg:%s\\n", arg); pthread_t pthreadid = pthread_self(); printf("pthread_fun0 pthreadid:%u\\n", pthreadid); pthread_mutex_lock(&(gcounter.m_mutex)); int i=100; for(; i<113; i++) { usleep(1000); printf("%d\\n", (gcounter.m_cout+i)); } pthread_mutex_unlock(&(gcounter.m_mutex)); pthread_cleanup_push(cleanup_fun, "pthread_fun0 thread first cleanup"); pthread_cleanup_push(cleanup_fun, "pthread_fun0 thread second cleanup"); printf("pthread_fun0 cleanup_push compelete\\n"); pthread_cleanup_pop(0); pthread_cleanup_pop(0); pthread_exit((void*)0); } void * pthread_fun1(void* arg) { char* charg = (char*)arg; printf("pthread_fun1 arg:%s\\n", arg); pthread_t pthreadid = pthread_self(); printf("pthread_fun1 pthreadid:%u\\n", pthreadid); pthread_mutex_lock(&(gcounter.m_mutex)); int i=222; for(; i<230; i++) { usleep(1000); printf("%d\\n", (gcounter.m_cout+i)); } pthread_mutex_unlock(&(gcounter.m_mutex)); pthread_cleanup_push(cleanup_fun, "pthread_fun1 thread first cleanup"); pthread_cleanup_push(cleanup_fun, "pthread_fun1 thread second cleanup"); printf("pthread_fun1 cleanup_push compelete\\n"); pthread_cleanup_pop(0); pthread_cleanup_pop(0); return ((void*)1); } int main(int argc, char* argv[]) { printf("Program %s Begin\\n", argv[0]); struct tms begintime; clock_t begreal = times(&begintime); struct sigaction act, oact; sigemptyset(&act.sa_mask); act.sa_flags = SA_SIGINFO; act.sa_sigaction = sigaction_handle_fun; sigaction(SIGTERM, &act, &oact); pthread_t pthreadid = pthread_self(); printf("pthreadid:%u\\n", pthreadid); pthread_mutex_init (&(gcounter.m_mutex), 0); gcounter.m_cout = 0; pthread_attr_t pthreadattr; pthread_attr_init(&pthreadattr); size_t pthreadstacksize; pthread_attr_getstacksize(&pthreadattr, &pthreadstacksize); printf("pthreadstacksize:%u\\n", pthreadstacksize); printf("pthread_getconcurrency:%d\\n", pthread_getconcurrency()); pthread_t newpthreadid; char* charg = "000 pass to pthread"; int pcreateret = pthread_create(&newpthreadid, 0, pthread_fun0, charg); if(pcreateret != 0) { perror("pthread_create error"); } else { printf("newpthreadid:%u\\n", newpthreadid); } pthread_t newpthreadid1; char* charg1 = "100 pass to pthread"; int pcreateret1 = pthread_create(&newpthreadid1, 0, pthread_fun1, charg); if(pcreateret1 != 0) { perror("pthread_create error"); } else { printf("newpthreadid:%u\\n", newpthreadid1); } void* pret; pthread_join(newpthreadid, &pret); pthread_join(newpthreadid1, &pret); char chcwdbuf[100]; if(getcwd (chcwdbuf, 100) == 0) { perror("getcwd error"); } else { printf("getcwd %s\\n", chcwdbuf); } printf("input characters:\\n"); int c; while( (c = getc(stdin)) != EOF) { if(putc(c, stdout) == EOF) { perror("putc error"); } } time_t t = time(0); struct tm* localtm = localtime(&t); printf("Time:%s\\n", asctime(localtm)); printf("getlogin:%s\\n", getlogin()); atexit(atexit_fun1); atexit(atexit_fun2); printf("getpid():%d\\n", getpid()); pid_t pid; if( (pid = fork()) < 0) { perror("fork error\\n"); } else if(pid == 0) { printf("great this is child process created by fork \\n"); printf("getpid():%d\\n", getpid()); printf("getppid():%d\\n", getppid()); printf("getpgrp():%d\\n", getpgrp()); } else { printf("parent process is here.\\n"); } struct tms endtime; clock_t endreal = times(&endtime); printf("real:%f\\n" "user:%f\\n" "sys:%f\\n", (float)(endreal-begreal)/CLOCKS_PER_SEC, (float)(endtime.tms_utime-begintime.tms_utime)/CLOCKS_PER_SEC, (float)(endtime.tms_stime-begintime.tms_stime)/CLOCKS_PER_SEC ); return 0; }
1
#include <pthread.h> int mediafirefs_statfs(const char *path, struct statvfs *buf) { printf("FUNCTION: statfs. path: %s\\n", path); static char space_total[128]; static char space_used[128]; static uintmax_t bytes_total = 0; static uintmax_t bytes_used = 0; static uintmax_t bytes_free = 0; unsigned int state_flags = 0; (void)path; (void)buf; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); if(ctx->account == 0) { ctx->account = account_alloc(); account_add_state_flags(ctx->account, ACCOUNT_FLAG_DIRTY_SIZE); } state_flags = account_get_state_flags(ctx->account); if(state_flags & ACCOUNT_FLAG_DIRTY_SIZE) { memset(space_total, 0, sizeof(space_total)); memset(space_used, 0, sizeof(space_used)); mfconn_api_user_get_info(ctx->conn, ctx->account); account_del_state_flags(ctx->account, ACCOUNT_FLAG_DIRTY_SIZE); account_get_space_total(ctx->account, space_total, 128); account_get_space_used(ctx->account, space_used, 128); bytes_total = atoll(space_total); bytes_used = atoll(space_used); bytes_free = bytes_total - bytes_used; } if (bytes_total == 0) { pthread_mutex_unlock(&(ctx->mutex)); return -ENOSYS; } fprintf(stderr, "account size: %ju bytes\\n", bytes_total); fprintf(stderr, "account used: %ju bytes\\n", bytes_used); fprintf(stderr, "account free: %ju bytes\\n", bytes_free); buf->f_bsize = 65536; buf->f_frsize = 65536; buf->f_blocks = (bytes_total / 65535); buf->f_bfree = (bytes_free / 65536); buf->f_bavail = (bytes_free / 65536); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> int g_counter = 0; int g_stop_it = 0; pthread_mutex_t mutex_stop = PTHREAD_MUTEX_INITIALIZER; int sockaddrInit(const char *host, int port, struct sockaddr_in *peer) { int code; memset(peer, '\\0', sizeof(struct sockaddr_in)); peer->sin_family = AF_INET; peer->sin_port = htons(port); code = inet_pton(AF_INET, host, &(peer->sin_addr)); if (1 != code) { fprintf(stderr, "inet_pton failed: %s \\n", strerror(errno)); return -1; } return 0; } void generateTimeWait(struct sockaddr_in *peer) { int code; int s; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "create socket failed: %s \\n", strerror(errno)); return; } code = connect(s, (struct sockaddr *)peer, sizeof(struct sockaddr_in)); if (0 != code) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "connect socket failed: %d, %s \\n", errno, strerror(errno)); return; } pthread_mutex_lock(&mutex_stop); g_counter += 1; printf("counter: %d \\n", g_counter); pthread_mutex_unlock(&mutex_stop); } int main(int argc, char *argv[]) { int code; struct sockaddr_in peer; code = sockaddrInit("127.0.0.1", 11211, &peer); if (0 != code) { exit(1); } pthread_t tid; while (!g_stop_it) { code = pthread_create(&tid, 0, (void *)generateTimeWait, (void *)&peer); if (0 != code) { fprintf(stderr, "pthread_create failed: %s \\n", strerror(code)); } else { pthread_join(tid, 0); } } printf("counter: %d \\n", g_counter); exit(0); }
1
#include <pthread.h> int flag = 1; void uartfunction(); void txmsgfunction(); pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t empty; struct buffer { int state; char send_buf[1024]; char recv_buf[1024]; }data_buf; int main(){ data_buf.state = 1; pthread_t mythread[2]; void *retval; int j=1; int res; pthread_mutex_init(&mymutex,0); pthread_cond_init(&empty,0); pthread_create(&mythread[0],0,(void *)&uartfunction,0); pthread_create(&mythread[1],0,(void *)&txmsgfunction,0); pthread_join(mythread[0], &retval); pthread_join(mythread[1], &retval); return 0; } void uartfunction(void *arg) { while(1) { while(flag) { pthread_mutex_lock(&mymutex); data_buf.state = uart_demo(); printf("uart working... state: %d\\n",data_buf.state); sprintf(data_buf.send_buf,"%d",data_buf.state); if(data_buf.state == 0) { flag = 0; pthread_cond_signal(&empty); } pthread_mutex_unlock(&mymutex); } } pthread_exit(0) ; } void txmsgfunction(void *arg) { while(1) { while(flag == 0) { pthread_mutex_lock(&mymutex); if(data_buf.state == 1) { flag = 1; pthread_cond_wait(&empty,&mymutex); } data_buf.state = txmsg_demo(data_buf.send_buf); printf("txmsg working... state: %d\\n",data_buf.state); pthread_mutex_unlock(&mymutex); } } pthread_exit(0) ; }
0
#include <pthread.h> char *test_UID = "DRFTBHN6XXUUVM6KWTE1"; static int __start_rdt_daemon = 0; struct stRDTcnnt { char target_uid[20]; int action; int iotc_sid; int rdt_id; int tx_counter; int cnnt_state; struct st_SInfo Sinfo; }; pthread_mutex_t mutex_rdt_cnnt_array; struct stRDTcnnt __rdt_cnnt[32]; int __cnt_rdt_cnnt = 0; int init_rdt_deamon_env() { int i; __cnt_rdt_cnnt = 0; pthread_mutex_init(&mutex_rdt_cnnt_array, 0); pthread_mutex_lock(&mutex_rdt_cnnt_array); for(i=0;i<32;i++) memset(&__rdt_cnnt[i],0,sizeof(struct stRDTcnnt)); pthread_mutex_unlock(&mutex_rdt_cnnt_array); return 0; } int release_rdt_deamon_env() { int i; pthread_mutex_lock(&mutex_rdt_cnnt_array); for(i=0;i<32;i++) { if ( __rdt_cnnt[i].action > 0 ) { if ( __rdt_cnnt[i].rdt_id >= 0 ) { RDT_Destroy(__rdt_cnnt[i].rdt_id); __rdt_cnnt[i].rdt_id = -1; } if ( __rdt_cnnt[i].iotc_sid >= 0 ) { IOTC_Session_Close( __rdt_cnnt[i].iotc_sid); __rdt_cnnt[i].iotc_sid = -1; } } memset(&__rdt_cnnt[i],0,sizeof(struct stRDTcnnt)); } pthread_mutex_unlock(&mutex_rdt_cnnt_array); pthread_mutex_destroy(&mutex_rdt_cnnt_array); return 0; } int check_new_rdtcnnt_request() { int i; int ret; pthread_mutex_lock(&mutex_rdt_cnnt_array); for(i=0;i<32;i++) { if ( __rdt_cnnt[i].action == 1 ) { __rdt_cnnt[i].action = 2; __rdt_cnnt[i].iotc_sid = IOTC_Get_SessionID(); if(__rdt_cnnt[i].iotc_sid == IOTC_ER_NOT_INITIALIZED) { printf("Not Initialize!!!\\n"); } else if (__rdt_cnnt[i].iotc_sid == IOTC_ER_EXCEED_MAX_SESSION) { printf("EXCEED MAX SESSION!!!\\n"); } ret = IOTC_Connect_ByUID_Parallel(__rdt_cnnt[0].target_uid, __rdt_cnnt[i].iotc_sid); if(ret < 0) { printf("p2pAPIs_Client connect failed...!!\\n"); } else { __rdt_cnnt[i].action = 3; printf("Eddy test sid:%d \\n",__rdt_cnnt[i].iotc_sid); } } else if ( __rdt_cnnt[i].action == 3 ) { __rdt_cnnt[i].action = 4; __rdt_cnnt[i].rdt_id = RDT_Create(__rdt_cnnt[i].iotc_sid, 3000, 0); if( __rdt_cnnt[i].rdt_id < 0) { printf("RDT_Create failed[%d]!!\\n", __rdt_cnnt[i].rdt_id); IOTC_Session_Close(__rdt_cnnt[i].iotc_sid); __rdt_cnnt[i].iotc_sid = -1; __rdt_cnnt[i].action = 1; } else { __rdt_cnnt[i].action = 4; __rdt_cnnt[i].tx_counter = 0; printf("RDT_Create OK[%d]\\n", __rdt_cnnt[i].rdt_id); } } } pthread_mutex_unlock(&mutex_rdt_cnnt_array); return 0; } int start_rdt_daemon() { int i; int ret; char szBuff[4096]; if ( __start_rdt_daemon != 0 ) return 1; __start_rdt_daemon = 1; init_rdt_deamon_env(); printf("RDT Version[%X]\\n", RDT_GetRDTApiVer()); ret = IOTC_Initialize2(0); if(ret != IOTC_ER_NoERROR) { printf("IOTC_Initialize error!!\\n"); return 0; } int rdtCh = RDT_Initialize(); if(rdtCh <= 0) { printf("RDT_Initialize error!!\\n"); return 0; } pthread_mutex_lock(&mutex_rdt_cnnt_array); memcpy(__rdt_cnnt[0].target_uid,test_UID,20); __rdt_cnnt[0].action = 1; __rdt_cnnt[0].cnnt_state = 0; __rdt_cnnt[0].iotc_sid = -1; __rdt_cnnt[0].rdt_id = -1; pthread_mutex_unlock(&mutex_rdt_cnnt_array); i = 0; while(1) { check_new_rdtcnnt_request(); pthread_mutex_lock(&mutex_rdt_cnnt_array); for(i=0;i<32;i++) { if ( __rdt_cnnt[i].action == 4 ) { printf("eddy test rdt connected : [%d]:%d \\n",i,__rdt_cnnt[i].rdt_id); sprintf(szBuff,"test.json[%d]\\r\\n",__rdt_cnnt[i].tx_counter); ret = RDT_Write(__rdt_cnnt[i].rdt_id, szBuff,(int) strlen(szBuff)); __rdt_cnnt[i].tx_counter++; } } pthread_mutex_unlock(&mutex_rdt_cnnt_array); pthread_mutex_lock(&mutex_rdt_cnnt_array); for(i=0;i<32;i++) { if ( __rdt_cnnt[i].action >= 3 ) { __rdt_cnnt[i].cnnt_state = IOTC_Session_Check(__rdt_cnnt[i].iotc_sid, &__rdt_cnnt[i].Sinfo); if ( __rdt_cnnt[i].cnnt_state < 0 ) { printf("RDTcnnt[%d] err:%d \\n",i,__rdt_cnnt[i].cnnt_state); if ( __rdt_cnnt[i].rdt_id >= 0 ) { RDT_Destroy(__rdt_cnnt[i].rdt_id); __rdt_cnnt[i].rdt_id = -1; } IOTC_Session_Close(__rdt_cnnt[i].iotc_sid); __rdt_cnnt[i].iotc_sid = -1; __rdt_cnnt[i].action = 1; __rdt_cnnt[i].cnnt_state = 0; __rdt_cnnt[i].iotc_sid = -1; __rdt_cnnt[i].rdt_id = -1; } } if ( __rdt_cnnt[i].action == 4 ) { printf("eddy test rdt polling : [%d]:%d \\n",i,__rdt_cnnt[i].rdt_id); ret = RDT_Read(__rdt_cnnt[i].rdt_id, szBuff, 1024, 3000); if ( ret > 0 ) { szBuff[ret] = 0; printf("eddy test recv[%d]:\\n%s\\n",ret,szBuff); } } } pthread_mutex_unlock(&mutex_rdt_cnnt_array); usleep(1000000); } release_rdt_deamon_env(); RDT_DeInitialize(); IOTC_DeInitialize(); return 0; } int stop_rdt_daemon() { return 1; }
1
#include <pthread.h> int n = 1, xcond = 0, zcond = 0; pthread_mutex_t the_mutex; pthread_cond_t condx, condz; void x(void *argp) { pthread_mutex_lock(&the_mutex); n = n * 16; xcond = 1; pthread_cond_signal(&condx); pthread_mutex_unlock(&the_mutex); } void y(void *argp) { pthread_mutex_lock(&the_mutex); while(zcond == 0) pthread_cond_wait(&condz, &the_mutex); n = n / 7; pthread_mutex_unlock(&the_mutex); } void z(void *argp) { pthread_mutex_lock(&the_mutex); while(xcond == 0) pthread_cond_wait(&condx, &the_mutex); n = n + 40; zcond = 1; pthread_cond_signal(&condz); pthread_mutex_unlock(&the_mutex); } int main(void) { pthread_t t1, t2, t3; int rc; rc = pthread_create(&t1, 0, (void *) x, 0); if(rc == -1){ perror("Error: "); exit(-1); } rc = pthread_create(&t2, 0, (void *) y, 0); if(rc == -1){ perror("Error: "); exit(-1); } rc = pthread_create(&t3, 0, (void *) z, 0); if(rc == -1){ perror("Error: "); exit(-1); } rc = pthread_join(t1, 0); if(rc == -1){ perror("Error: "); exit(-1); } rc = pthread_join(t2, 0); if(rc == -1){ perror("Error: "); exit(-1); } rc = pthread_join(t3, 0); if(rc == -1){ perror("Error: "); exit(-1); } printf("n=%d\\n", n); return 0; }
0
#include <pthread.h> enum { kMaxNumThreads = 5 }; void create_and_join_threads(ThreadCallback *callbacks, int n) { int i; pthread_t t[kMaxNumThreads]; int ids[kMaxNumThreads]; assert(n <= kMaxNumThreads); for (i = 0; i < n; i++) { ids[i] = i; pthread_create(&t[i], 0, callbacks[i], &ids[i]); } for (i = 0; i < n; i++) { pthread_join(t[i], 0); } } void break_optimization() { volatile int foo; foo = 0; } int simple_race_obj; void simple_race_write_frame_2() { break_optimization(); simple_race_obj++; } void simple_race_write_frame_1() { break_optimization(); simple_race_write_frame_2(); break_optimization(); } void *simple_race_write(void *arg) { break_optimization(); simple_race_write_frame_1(); break_optimization(); return 0; } void positive_race_on_global_test() { ThreadCallback t[] = {simple_race_write, simple_race_write, simple_race_write}; printf("========== %s: =========\\n", __FUNCTION__); ANNOTATE_EXPECT_RACE(&simple_race_obj, "positive_race_on_global_test"); create_and_join_threads(t, 3); } int *race_on_heap_obj; void race_on_heap_frame_2() { break_optimization(); *race_on_heap_obj = 1; } void race_on_heap_frame_1() { break_optimization(); race_on_heap_frame_2(); break_optimization(); } void *race_on_heap_write(void *unused) { break_optimization(); race_on_heap_frame_1(); break_optimization(); return 0; } void positive_race_on_heap_test() { ThreadCallback t[2] = {race_on_heap_write, race_on_heap_write}; printf("========== %s: =========\\n", __FUNCTION__); race_on_heap_obj = (int*)malloc(sizeof(int)); ANNOTATE_EXPECT_RACE(race_on_heap_obj, "positive_race_on_heap_test"); create_and_join_threads(t, 2); free(race_on_heap_obj); } pthread_mutex_t wrong_lock_test_mu_1; pthread_mutex_t wrong_lock_test_mu_2; int wrong_lock_test_obj; void *wrong_lock_test_access1(void *unused) { pthread_mutex_lock(&wrong_lock_test_mu_1); wrong_lock_test_obj++; pthread_mutex_unlock(&wrong_lock_test_mu_1); return 0; } void *wrong_lock_test_access2(void *unused) { pthread_mutex_lock(&wrong_lock_test_mu_2); wrong_lock_test_obj++; pthread_mutex_unlock(&wrong_lock_test_mu_2); return 0; } void positive_wrong_lock_test() { ThreadCallback t[2] = {wrong_lock_test_access1, wrong_lock_test_access2}; pthread_mutex_init(&wrong_lock_test_mu_1, 0); pthread_mutex_init(&wrong_lock_test_mu_2, 0); printf("========== %s: =========\\n", __FUNCTION__); ANNOTATE_EXPECT_RACE(&wrong_lock_test_obj, "positive_wrong_lock_test"); create_and_join_threads(t, 2); } pthread_mutex_t locked_access_test_mu; int locked_access_test_obj; void locked_access_test_frame_2() { pthread_mutex_lock(&locked_access_test_mu); locked_access_test_obj++; pthread_mutex_unlock(&locked_access_test_mu); } void locked_access_test_frame_1() { locked_access_test_frame_2(); } void *locked_access_test_thread(void *unused) { locked_access_test_frame_1(); return 0; } void negative_locked_access_test() { ThreadCallback t[2] = {locked_access_test_thread, locked_access_test_thread}; pthread_mutex_init(&locked_access_test_mu, 0); printf("========== %s: =========\\n", __FUNCTION__); create_and_join_threads(t, 2); } int main() { if (1) positive_race_on_global_test(); if (1) positive_race_on_heap_test(); if (1) positive_wrong_lock_test(); if (1) negative_locked_access_test(); fprintf(stderr, "PASSED\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; unsigned long long switches=0; void* thread1(void *arg) { unsigned long long temp; while(1){ pthread_mutex_lock(&mutex); switches++; temp=switches; pthread_cond_signal(&cond2); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); while(temp==switches) pthread_cond_wait(&cond1,&mutex); switches++; pthread_mutex_unlock(&mutex); } return 0; } void* thread2(void *arg) { unsigned long long temp; while(1){ pthread_mutex_lock(&mutex); switches++; temp=switches; pthread_cond_signal(&cond1); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); while(temp==switches) pthread_cond_wait(&cond2,&mutex); switches++; pthread_mutex_unlock(&mutex); } return 0; } int main() { pthread_t t1,t2; struct timeval start,end; pthread_create(&t1,0,thread1,0); pthread_create(&t2,0,thread2,0); gettimeofday(&start,0); sleep(1); gettimeofday(&end,0); pthread_cancel(t1); pthread_cancel(t2); printf("switches=%llu in %u second and %u microseconds\\n",switches,end.tv_sec-start.tv_sec,end.tv_usec-start.tv_usec); return 0; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0, 1, 2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for(i = 0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if(count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, Unlocking mutex variable\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while(count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition Signal received.\\n", my_id); count+=125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(void) { 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> 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 (8 == count) { 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 < 8) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> int nitems; struct { pthread_mutex_t mutex; int buff[10000000]; int nput; int nval; int ccount; }shared={PTHREAD_MUTEX_INITIALIZER}; void *produce(void *); void *consume(void *); void printbuff() { int i; printf("\\t"); for(i=0;i<nitems;i++) printf("%4d",shared.buff[i]); } main() { int i,npthreads,ncthreads,*count,*c_count,temp1,temp2; int sum=0; pthread_t *tid_produce,*tid_consume; nitems=20; printf("\\n\\nWorking with buffer size=%d \\n",nitems); printf("\\nNo. of producer threads:"); scanf("%d",&npthreads); printf("\\nNo. of consumer threads:"); scanf("%d",&ncthreads); tid_produce=(pthread_t *)malloc(sizeof(pthread_t)*npthreads); tid_consume=(pthread_t *)malloc(sizeof(pthread_t)*ncthreads); count=(int *)malloc(npthreads*sizeof(int)); c_count=(int *)malloc(ncthreads*sizeof(int)); pthread_setconcurrency(npthreads+ncthreads); for(i=0;i<nitems;i++) shared.buff[i]=-1; for(i=0;i<npthreads;i++) { count[i]=0; pthread_create(&tid_produce[i],0,produce,&count[i]); } for(i=0;i<ncthreads;i++) { c_count[i]=0; pthread_create(&tid_consume[i],0,consume,&c_count[i]); } for(i=0;i<npthreads;i++) { pthread_join(tid_produce[i],0); } for(i=0;i<ncthreads;i++) { pthread_join(tid_consume[i],0); } printf("\\nProducers\\n---------"); for(i=0;i<npthreads;i++) printf("\\nProducer %3d = %7d",i+1,count[i]); printf("\\n\\nConsumers\\n---------"); for(i=0;i<ncthreads;i++) printf("\\nConsumer %3d = %7d",i+1,c_count[i]); printf("\\n\\nBuffer status\\n-------------"); for(i=0;i<nitems;i++) if(shared.buff[i]!=-1) sum++; printf("\\n%d remaining in buffer...\\n\\n",sum); exit(0); } void *produce(void *arg) { for(;;) { pthread_mutex_lock(&shared.mutex); if(shared.nput>=nitems) { pthread_mutex_unlock(&shared.mutex); return(0); } shared.buff[shared.nput]=shared.nval; printf("\\n%3d produced + ",shared.nput); printbuff(); shared.nput++; shared.nval++; pthread_mutex_unlock(&shared.mutex); *((int *)arg)+=1; printf("\\nProducer going to sleep..."); sleep(3); } } void *consume(void *arg) { int i; while(1){ pthread_mutex_lock(&shared.mutex); for(i=0;i<=shared.nput;i++){ if(shared.buff[i]!=-1) { printf("\\n%3d consumed - ",i); shared.buff[i]=-1; printbuff(); shared.ccount++; *((int *)arg)+=1; printf("\\nConsumer going to sleep..."); sleep(2); break; } if(shared.ccount>=nitems){ pthread_mutex_unlock(&shared.mutex); return(0); } } pthread_mutex_unlock(&shared.mutex); } }
1
#include <pthread.h> char* data; struct Node* next; } Node_t; Node_t *head; Node_t *tail; int size; } Queue_t; pthread_mutex_t linkQueueMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t linkQueueEmpty = PTHREAD_COND_INITIALIZER; pthread_cond_t linkQueueFill = PTHREAD_COND_INITIALIZER; int queue_size = 2; void Queue_init(Queue_t* q) { pthread_mutex_lock(&linkQueueMutex); q->size = 0; Node_t* temp = (Node_t*)malloc(sizeof(Node_t)); temp->next = 0; q->head = temp; q->tail = temp; pthread_mutex_unlock(&linkQueueMutex); } int Queue_enqueue(char* x, Queue_t* q) { pthread_mutex_lock(&linkQueueMutex); while (q->size == queue_size) pthread_cond_wait(&linkQueueEmpty, &linkQueueMutex); if(q->head->data == 0) { q->tail->data = x; } else{ Node_t* temp = (Node_t*)malloc(sizeof(Node_t)); temp->data = x; temp->next = 0; q->tail->next = temp; q->tail = temp; } q->size++; pthread_cond_signal(&linkQueueFill); pthread_mutex_unlock(&linkQueueMutex); return 0; } int Queue_dequeue(Queue_t *q, char** returnvalue) { pthread_mutex_lock(&linkQueueMutex); while (q->size == 0) pthread_cond_wait(&linkQueueFill, &linkQueueMutex); Node_t *tmp = q->head; *returnvalue = q->head->data; Node_t *newHead = tmp->next; if (newHead == 0) { free(q->head); q->size = 0; Node_t* temp = (Node_t*)malloc(sizeof(Node_t)); temp->next = 0; q->head = temp; q->tail = temp; return -1; } q->head = newHead; free(tmp); q->size--; pthread_cond_signal(&linkQueueEmpty); pthread_mutex_unlock(&linkQueueMutex); return 0; } Queue_t linkQueue; void* downloader(void *arg); void* parser(void *arg); int main(int argc, char* argv[]) { Queue_init(&linkQueue); char* text = "link1"; char* text2 = "link2"; Queue_enqueue(text, &linkQueue); Queue_enqueue(text2, &linkQueue); pthread_t downloadthread; pthread_t parsethread; pthread_create(&downloadthread, 0, downloader, (void *)&linkQueue); pthread_create(&parsethread, 0, parser, (void *)&linkQueue); pthread_join(downloadthread, 0); pthread_join(parsethread, 0); } void* downloader(void* q) { char* returnvalue = (char*)malloc(sizeof(char)); printf("downloading page!\\n"); Queue_dequeue(&q, &returnvalue); printf("return: %s\\n", returnvalue); return 0; } void* parser(void* arg) { printf("parsing page!\\n"); char* text3 = "link3"; Queue_enqueue(text3, &arg); return 0; }
0
#include <pthread.h> int stack_size; char pile[5]; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; void* Producteur(void* arg) { int c; int *num=(int*)arg; while ((c = getchar()) != EOF) { Push(c,*num); } } void* Consommmateur(void* arg) { sleep(1); int *num=(int*)arg; for (;;) { putchar(Pop(*num)); printf("\\n"); fflush(stdout); } } void Push(int c,int num) { pthread_mutex_lock(&mutex); if (stack_size==5 -1) { printf("Thread Producteur %d : Pile pleine, ne pouvoir plus empiler.\\n",num); pthread_cond_wait(&cond, &mutex); } else { stack_size++; pile[stack_size]=c; if (c=='\\n') c='E'; printf("Thread Producteur %d : Le caractère '%c' est empilée au sommet %d de pile, le nouveau sommet %d.\\n",num,c,stack_size,stack_size+1); pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); } int Pop(int num) { int s=0; pthread_mutex_lock(&mutex); if (stack_size==0) { printf("Thread Consommmateur %d : Pile vide, ne pouvoir plus désempiler.\\n",num); pthread_cond_wait(&cond, &mutex); } else { s=pile[stack_size]; pile[stack_size]=0; if (s=='\\n') s='E'; printf("Thread Consommmateur %d : Le caractère '%c' est désempilée depuis sommet %d de pile,le nouveau sommet %d.\\n",num,s,stack_size,stack_size-1); stack_size--; pthread_cond_signal(&cond); } pthread_mutex_unlock(&mutex); return s; } int main (int argc, char ** argv) { pthread_t prod[3],cons[5]; int status,i; int* pt_ind; stack_size=0; for (i=0;i<3;i++) { pt_ind=(int*)malloc(sizeof(i)); *pt_ind=i; if (pthread_create(&prod[i],0,Producteur,(void *)pt_ind)!=0) { printf("ERREUR:creation producteur\\n"); exit(1); } } sleep(3); for (i=0;i<5;i++) { pt_ind=(int*)malloc(sizeof(i)); *pt_ind=i; if (pthread_create(&cons[i],0,Consommmateur,(void *)pt_ind)!=0) { printf("ERREUR:creation consommateur\\n"); exit(2); } } for (i=0;i<3;i++) { if (pthread_join(prod[i],(void **)&status)!=0) { printf("ERREUR:joindre producteur\\n"); exit(3); } } for (i=0;i<5;i++) { if (pthread_join(cons[i],(void **)&status)!=0) { printf("ERREUR:joindre consommateur\\n"); exit(4); } } return 0; }
1
#include <pthread.h> void _check_dir(const char *pathname) { int i, len; char dirname[NESSDB_PATH_SIZE]; strcpy(dirname, pathname); i = strlen(dirname); len = i; if (dirname[len-1] != '/') strcat(dirname, "/"); len = strlen(dirname); for (i = 1; i < len; i++) { if (dirname[i] == '/') { dirname[i] = 0; if (access(dirname, 0) != 0) { if (mkdir(dirname, 0755) == -1) __PANIC("creta dir error, %s", dirname); } dirname[i] = '/'; } } } void _make_sstname(struct meta *meta, int lsn) { memset(meta->sst_file, 0, NESSDB_PATH_SIZE); snprintf(meta->sst_file, NESSDB_PATH_SIZE, "%s/%06d%s", meta->path, lsn, NESSDB_SST_EXT); } int _get_idx(struct meta *meta, char *key) { int cmp, i; int right = meta->size; struct meta_node *node; for (i = 0; i < right; i++) { node = &meta->nodes[i]; cmp = ness_strcmp(key, node->sst->header.max_key); if (cmp <= 0) break; } return i; } void meta_dump(struct meta *meta) { int i, j; int allc = 0; uint64_t allwasted = 0; __DEBUG("---meta(%d):", meta->size); for (i = 0; i < meta->size; i++) { int used = 0; int count = 0; int wasted = meta->nodes[i].sst->header.wasted; for (j = 0; j < MAX_LEVEL; j++) { used += meta->nodes[i].sst->header.count[j] * ITEM_SIZE; count += meta->nodes[i].sst->header.count[j]; } allc += count; allwasted += wasted; i, meta->nodes[i].lsn, meta->nodes[i].sst->header.max_key, used, wasted, count); } __DEBUG("\\t----allcount:%d, allwasted(KB):%llu", allc, allwasted/1024); } void _scryed(struct sst *sst, struct sst_item *L, int start, int c) { int i; int k = c + start; for (i = start; i < k; i++) if (L[i].opt & 1) sst_add(sst, &L[i]); } void _update(struct meta *meta, struct sst *sst, int idx) { memmove(&meta->nodes[idx + 1], &meta->nodes[idx], (meta->size - idx) * META_NODE_SIZE); memset(&meta->nodes[idx], 0, sizeof(struct meta_node)); meta->nodes[idx].sst = sst; meta->nodes[idx].lsn = meta->size; meta->size++; if (meta->size >= (int)(NESSDB_MAX_META - 1)) NESSDB_MAX_META); } void _split_sst(struct meta *meta, struct meta_node *node) { int i; int k; int split; int mod; int c = 0; int nxt_idx; struct sst_item *L; struct sst *sst; struct sst *ssts[NESSDB_SST_SEGMENT - 1]; L = sst_in_one(node->sst, &c); split = c / NESSDB_SST_SEGMENT; mod = c % NESSDB_SST_SEGMENT; k = split + mod; nxt_idx = _get_idx(meta, L[k - 1].data) + 1; for (i = 1; i < NESSDB_SST_SEGMENT; i++) { int lsn = meta->size + i; _make_sstname(meta, lsn); ssts[i - 1] = sst_new(meta->sst_file, meta->stats); _scryed(ssts[i - 1], L, mod + i*split, split); } pthread_mutex_lock(meta->r_lock); sst = node->sst; sst_truncate(sst); memcpy(node->sst->header.max_key, L[k - 1].data, strlen(L[k - 1].data)); for (i = 0; i < NESSDB_SST_SEGMENT - 1; i++) _update(meta, ssts[i], nxt_idx++); for (i = 0; i < k; i++) if (L[i].opt == 1) sst_add(sst, &L[i]); pthread_mutex_unlock(meta->r_lock); xfree(L); meta->stats->STATS_SST_SPLITS++; } void _build_meta(struct meta *meta) { int idx; int lsn; DIR *dd; struct dirent *de; struct sst *sst; char sst_name[NESSDB_PATH_SIZE]; dd = opendir(meta->path); while ((de = readdir(dd))) { if (strstr(de->d_name, NESSDB_SST_EXT)) { memset(sst_name, 0, NESSDB_PATH_SIZE); memcpy(sst_name, de->d_name, strlen(de->d_name) - 4); lsn = atoi(sst_name); _make_sstname(meta, lsn); sst = sst_new(meta->sst_file, meta->stats); idx = _get_idx(meta, sst->header.max_key); memmove(&meta->nodes[idx + 1], &meta->nodes[idx], (meta->size - idx) * META_NODE_SIZE); meta->nodes[idx].sst = sst; meta->nodes[idx].lsn = lsn; meta->size++; } } if (meta->size == 0) { _make_sstname(meta, 0); sst = sst_new(meta->sst_file, meta->stats); meta->nodes[0].sst = sst; meta->nodes[0].lsn = 0; meta->size++; } closedir(dd); meta_dump(meta); } struct meta *meta_new(const char *path, struct stats *stats) { struct meta *m = xcalloc(1, sizeof(struct meta)); m->stats = stats; memcpy(m->path, path, NESSDB_PATH_SIZE); _check_dir(path); _build_meta(m); m->r_lock = xmalloc(sizeof(pthread_mutex_t)); pthread_mutex_init(m->r_lock, 0); return m; } struct meta_node *meta_get(struct meta *meta, char *key, enum META_FLAG flag) { int i; struct meta_node *node; pthread_mutex_lock(meta->r_lock); i = _get_idx(meta, key); node = &meta->nodes[i]; if (i > 0 && i == meta->size) node = &meta->nodes[i - 1]; pthread_mutex_unlock(meta->r_lock); if ((flag == M_W) && node->sst->willfull) { _split_sst(meta, node); node = meta_get(meta, key, flag); } return node; } void meta_free(struct meta *meta) { int i; struct sst *sst; for (i = 0; i < meta->size; i++) { sst = meta->nodes[i].sst; if (sst) { if (sst->fd > 0) fsync(sst->fd); sst_free(sst); } } pthread_mutex_unlock(meta->r_lock); pthread_mutex_destroy(meta->r_lock); xfree(meta->r_lock); xfree(meta); }
0
#include <pthread.h> int item =0; int sum_r=0,sum_w=0; struct sbuf_t{ int buff[10]; int write_h; int read_h; sem_t full; sem_t empty; pthread_mutex_t mutex; }; struct sbuf_t shared; void* producer(){ for(int i=0;i<10;i++){ sem_wait(&shared.empty); pthread_mutex_lock(&shared.mutex); int k=rand()%100+1; shared.buff[shared.write_h] =k; sum_w+=k; shared.write_h = (++shared.write_h)%10; printf("Produced %d \\n",k); for(int j=0;j<10;j++){ printf("%d ",shared.buff[j]); } printf("\\n"); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.full); } return 0; } void* consumer(void* t){ for(int i=0;i<10;i++){ sem_wait(&shared.full); pthread_mutex_lock(&shared.mutex); printf("Consumed %d \\n",shared.buff[shared.read_h]); sum_r+=shared.buff[shared.read_h]; shared.buff[shared.read_h] = 0; shared.read_h = (++shared.read_h)%10; for(int j=0;j<10;j++){ printf("%d ",shared.buff[j]); } printf("\\n"); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.empty); } return 0; } int main(){ pthread_t p,c;int i=0; shared.read_h = 0; shared.write_h = 0; sem_init(&shared.full,0,0); sem_init(&shared.empty,0,10); pthread_mutex_init(&shared.mutex,0); pthread_create(&p,0,producer,0); pthread_create(&c,0,consumer,0); pthread_join(&p,0); pthread_join(&c,0); printf("%d, %d ",sum_r, sum_w); pthread_exit(0); return 0; }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv(const char *name) { int i,len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char*)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf ==0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i=0; environ[i]!=0; i++) { if ((strncmp(name, environ[i], len)==0) && (environ[i][len]=='=')) { strncpy(envbuf, &environ[i][len+1],4096 -1); pthread_mutex_unlock(&env_mutex); return (envbuf); } } pthread_mutex_unlock(&env_mutex); return (0); }
0
#include <pthread.h> int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int nondet_int(); int stored_elements[(20)]; _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 == (20)) { 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 == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(20); i++) { value = nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { goto ERROR; 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)) { goto ERROR; 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; }
1
#include <pthread.h> void chassis_term (); unsigned char convert_temperature (float temperature); unsigned char convert_pressure (float pressure); unsigned char convert_current (float current); unsigned char convert_voltage (float voltage); void * chassis (void * arg) { pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, 0); float LC, RC; float LV, RV; bool MCU_connected; bool Batt_low; pthread_cleanup_push (chassis_term, 0); pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, 0); MCU_connected = 1; Batt_low = 1; int i = 0; while ( 1 ) { i++; if (MCU_connected == 1) { Temper = convert_temperature (15); Press = convert_pressure (2); pos2volts(X, Y, Z, &LV, &RV); if (abs(LV) < 1) LV = 0; if (abs(RV) < 1) RV = 0; LVolt = convert_voltage(LV); RVolt = convert_voltage(RV); LC = LV / 12 * 2; LC = abs(LC); LCurr = convert_current(LC); RC = RV / 12 * 2; RC = abs(RC); RCurr = convert_current(RC); } else { Temper = 20; Press = 10; LVolt = 0; RVolt = 0; LCurr = 0; RCurr = 0; Batt_low = 1; } pthread_mutex_lock(&mutex1); if (MCU_connected == 1) set_bit(&Status, STATUS_MCU); else clr_bit(&Status, STATUS_MCU); if (Batt_low == 1) set_bit(&Status, STATUS_BATT); else clr_bit(&Status, STATUS_BATT); pthread_mutex_unlock (&mutex1); usleep (500); } pthread_cleanup_pop (1); pthread_exit(0); } void chassis_term() { printf ("Chassis thread stopped!\\n"); } unsigned char convert_temperature(float temperature) { return (temperature+20)/60.0 * 255; } unsigned char convert_pressure(float pressure) { return (pressure+10)/110.0 * 255; } unsigned char convert_current (float current) { return current / 2.0 * 255; } unsigned char convert_voltage (float voltage) { return (voltage+12) / 24.0 * 255; }
0
#include <pthread.h> pthread_mutex_t baglock; int numWorkers; int numArrived = 0; int row; struct ret{int sum; int max; int min; int mini; int minj; int maxi; int maxj;}; double read_timer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); } double start_time, end_time; int size; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); int total, min, max, mini, minj, maxi, maxj; total = 0; max = 0; min = 32767; for (i = 0; i < numWorkers; i++){ struct ret *retval; pthread_join(workerid[i], (void**)&retval); total += retval->sum; if(retval->max > max){ max = retval->max; maxi = retval->maxi; maxj = retval->maxj; } if(retval->min < min){ min = retval->min; mini = retval->mini; minj = retval->minj; } free(retval); } end_time = read_timer(); printf("The total is %d\\n", total); printf("Maximal element is [%d, %d] = %d\\n", maxi, maxj, max); printf("Minimum element is [%d, %d] = %d\\n", mini, minj, min); printf("The execution time is %g sec\\n", end_time - start_time); } void *Worker(void *arg) { long myid = (long) arg; int total, i, j; int min, max, mini, minj, maxi, maxj; struct ret *myret = malloc(sizeof(struct ret)); total = 0; max = 0; min = 32767; while(1){ pthread_mutex_lock(&baglock); i = row; row++; pthread_mutex_unlock(&baglock); if(row > size) break; for (j = 0; j < size; j++){ total += matrix[i][j]; if(matrix[i][j] > max){ max = matrix[i][j]; maxi = i; maxj = j; } if(matrix[i][j] < min){ min = matrix[i][j]; mini = i; minj = j; } } } myret->sum = total; myret->max = max; myret->min = min; myret->maxi = maxi; myret->maxj = maxj; myret->mini = mini; myret->minj = minj; pthread_exit((void*) myret); }
1
#include <pthread.h> int number_phils; int phil_id[10]; int phil_status[10]; pthread_mutex_t chopsticks[10]; int chopstick_status[10]; pthread_mutex_t display; int randomwait(int bound) { int wait = rand() % bound; sleep(wait); return wait; } void visualRepresentation() { pthread_mutex_lock(&display); int i; for (i = 0; i < number_phils; i++) { if (phil_status[i] == 0) { printf(" 42 "); } else if (phil_status[i] == 1) { printf(" want "); } else if (phil_status[i] == 2) { printf(" NOMNOM "); } } printf("\\n"); pthread_mutex_unlock(&display); } void pickupChopstick(int chopstick) { pthread_mutex_lock(&chopsticks[chopstick]); chopstick_status[chopstick] = 1; } void dropChopstick(int chopstick) { pthread_mutex_unlock(&chopsticks[chopstick]); chopstick_status[chopstick] = 0; } void ponderUniverse(int id) { randomwait(10); phil_status[id] = 1; } void eat(int id) { pickupChopstick(id); pickupChopstick((id+1) % number_phils); phil_status[id] = 2; randomwait(10); } void stopEating(int id) { dropChopstick(id); dropChopstick((id+1) % number_phils); phil_status[id] = 0; } void* transitioning(void* philosopher) { int id = *(int*) philosopher; while (1) { visualRepresentation(); if (phil_status[id] == 0) { ponderUniverse(id); } else if (phil_status[id] == 1) { eat(id); } else if (phil_status[id] == 2) { stopEating(id); } } } int main(int argc, char** argv) { if (argc < 2) { number_phils = 5; } else { number_phils = argv[1]; } printf("Dining Philosophers Simulation Initialized.\\n"); pthread_t phils[number_phils]; pthread_mutex_init(&display, 0); int i; for (i = 0; i < number_phils; i++) { phil_id[i] = i; pthread_mutex_init(&chopsticks[i], 0); pthread_create(&phils[i], 0, transitioning, &phil_id[i]); } for (i=0;i<number_phils;i++) { pthread_join(phils[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t a; pthread_mutex_t b; pthread_mutex_t c; int k; int j; void* fn1(void * args){ pthread_mutex_lock(&a);; if( k == 25 ){ pthread_mutex_lock(&b);; if( j ) printf("hola\\n"); else printf("adios\\n"); } else { pthread_mutex_lock(&c);; } } void* fn2(void * args){ pthread_mutex_unlock(&a);; if( k == 12 ){ j = 1; pthread_mutex_unlock(&b);; } else { j = 0; pthread_mutex_unlock(&c);; } } int main() { pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, &fn1, 0); printf("========================================================\\n"); pthread_create(&thread2, 0, &fn2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; }
1
#include <pthread.h> struct fsm_queue create_fsm_queue() { struct fsm_queue queue = { .first = 0, .last = 0, .mutex = 0, .cond = 0, }; check(pthread_mutex_init(&queue.mutex, 0) == 0, "ERROR DURING MUTEX INIT"); check(pthread_cond_init(&queue.cond, 0) == 0, "ERROR DURING CONDITION INIT"); return queue; error: exit(1); } void *fsm_queue_push_back_more( struct fsm_queue *queue, void *_value, const unsigned short size, unsigned short copy) { struct fsm_queue_elem * elem = malloc(sizeof(struct fsm_queue_elem)); if (copy) { elem->value = malloc(size); memcpy(elem->value, _value, size); }else{ elem->value = _value; } elem->next = 0; pthread_mutex_lock(&queue->mutex); elem->prev = queue->last; if (elem->prev != 0) { elem->prev->next = elem; }else{ queue->first = elem; } queue->last = elem; pthread_cond_broadcast(&queue->cond); pthread_mutex_unlock(&queue->mutex); return elem->value; } void *fsm_queue_push_back(struct fsm_queue *queue, void *_value, const unsigned short size) { return fsm_queue_push_back_more(queue, _value, size, 1); } void *fsm_queue_pop_front(struct fsm_queue *queue) { pthread_mutex_lock(&queue->mutex); if (queue->first == 0){ pthread_mutex_unlock(&queue->mutex); return 0; } void * value = queue->first->value; struct fsm_queue_elem *fsm_elem_to_free = queue->first; queue->first = queue->first->next; free(fsm_elem_to_free); if(queue->first != 0) { queue->first->prev = 0; }else{ queue->last = 0; } pthread_mutex_unlock(&queue->mutex); return value; } void fsm_queue_cleanup(struct fsm_queue *queue) { while(queue->first != 0){ free(fsm_queue_pop_front(queue)); } } struct fsm_queue *create_fsm_queue_pointer() { struct fsm_queue _q = create_fsm_queue(); struct fsm_queue * queue = malloc(sizeof(struct fsm_queue)); memcpy(queue, &_q, sizeof(struct fsm_queue)); return queue; } void fsm_queue_delete_queue_pointer(struct fsm_queue *queue) { fsm_queue_cleanup(queue); free(queue); } void *fsm_queue_get_elem(struct fsm_queue *queue, void *elem) { pthread_mutex_lock(&queue->mutex); struct fsm_queue_elem *cursor = queue->first; while(cursor != 0){ if (cursor->value == elem){ if(cursor->next == 0){ queue->last = cursor->prev; }else{ cursor->next->prev = cursor->prev; } if(cursor->prev == 0){ queue->first = cursor->next; }else{ cursor->prev->next = cursor->next; } free(cursor); pthread_mutex_unlock(&queue->mutex); return elem; } cursor = cursor->next; } pthread_mutex_unlock(&queue->mutex); return 0; } void *fsm_queue_push_top_more(struct fsm_queue *queue, void *_value, const unsigned short size, unsigned short copy) { struct fsm_queue_elem * elem = malloc(sizeof(struct fsm_queue_elem)); if (copy) { elem->value = malloc(size); memcpy(elem->value, _value, size); }else{ elem->value = _value; } elem->prev = 0; pthread_mutex_lock(&queue->mutex); elem->next = queue->first; if (elem->next != 0) { elem->next->prev = elem; }else{ queue->last = elem; } queue->first = elem; pthread_cond_broadcast(&queue->cond); pthread_mutex_unlock(&queue->mutex); return elem->value; } void *fsm_queue_push_top(struct fsm_queue *queue, void *_value, const unsigned short size) { return fsm_queue_push_top_more(queue, _value, size, 1); }
0
#include <pthread.h> pthread_mutex_t qlock; pthread_cond_t qempty; pthread_cond_t qfull; int queue[1000]; int head; int n; int insertions, extractions; void *consumer(void *cdata) { int extracted; int inx = *((int *)cdata); while (1) { extracted = 0; pthread_mutex_lock(&qlock); while(head == -1) pthread_cond_wait(&qfull, &qlock); queue[head--] = -1; extracted = 1; extractions++; pthread_cond_signal(&qempty); pthread_mutex_unlock(&qlock); } } void *producer(void *pdata) { int inserted; int i = 0; int inx = *((int *)pdata); while (1) { int val = inx + (i*n); inserted = 0; pthread_mutex_lock(&qlock); while(head == 1000 -1) pthread_cond_wait(&qempty, &qlock); queue[head+1] = val; head++; inserted = 1; i++; insertions++; pthread_cond_signal(&qfull); pthread_mutex_unlock(&qlock); } } int main(int argc, char *argv[]){ int i; pthread_attr_t attr; double start_time, end_time; struct timeval tz; struct timezone tx; pthread_attr_init (&attr); pthread_attr_setscope (&attr,PTHREAD_SCOPE_SYSTEM); n = atoi(argv[1]); head = -1; insertions = 0; extractions = 0; pthread_t c_threads[n]; pthread_t p_threads[n]; int pinx[n]; int cinx[n]; pthread_cond_init(&qfull, 0); pthread_cond_init(&qempty, 0); pthread_mutex_init(&qlock, 0); printf("Processing.....\\n"); for(i=0;i<n;i++){ pinx[i] = i+1; cinx[i] = i+1; pthread_create(&c_threads[i], &attr, consumer,(void *) &cinx[i]); pthread_create(&p_threads[i], &attr, producer,(void *) &pinx[i]); } sleep(10); for(i=0;i<n;i++){ pthread_cancel(c_threads[i]); pthread_cancel(p_threads[i]); } printf("No of insertions %d\\n", insertions); printf("No of extractions %d\\n", extractions); printf("Total %d\\n", insertions+extractions); printf("Interval %d\\n", 10); printf("Throughput %lf\\n", (insertions+extractions)/(1.0*10)); return 0; }
1
#include <pthread.h> void crut_barrier(int *counter) { static pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t my_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_lock(&my_mutex); --(*counter); if (*counter <= 0) { if (*counter < 0) { CRUT_FAIL("Barrier underflow"); } pthread_cond_broadcast(&my_cond); } else { while (*counter > 0) { pthread_cond_wait(&my_cond, &my_mutex); } } pthread_mutex_unlock(&my_mutex); } int crut_pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { pthread_attr_t my_attr, *attr_p; size_t size; int rc; if (attr) { attr_p = attr; } else { rc = pthread_attr_init(&my_attr); if (rc != 0) { CRUT_FAIL("Error calling pthread_attr_init()"); } attr_p = &my_attr; } size = 4 * 1024 * 1024; if (size < PTHREAD_STACK_MIN) size = PTHREAD_STACK_MIN; rc = pthread_attr_setstacksize(attr_p, size); if (rc != 0) { CRUT_FAIL("Error calling pthread_attr_setstacksize()"); } rc = pthread_create(thread, attr_p, start_routine, arg); if (!attr) { (void)pthread_attr_destroy(&my_attr); } return rc; } static void *crut_is_linuxthreads_aux(void *arg) { return ((int)getpid() == *(int *)arg) ? 0 : (void *)1UL; } int crut_is_linuxthreads(void) { int mypid = (int)getpid(); pthread_t th; void *join_val; if (0 != crut_pthread_create(&th, 0, &crut_is_linuxthreads_aux, (void *)(&mypid))) { CRUT_FAIL("Error calling pthread_create()"); exit(-1); } if (0 != pthread_join(th, &join_val)) { CRUT_FAIL("Error calling pthread_join()"); exit(-1); } return (join_val != 0); }
0
#include <pthread.h> void *(*process)(void *arg); void *arg; struct worker *next; } CThread_worker; pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t *threadid; int max_thread_num; int cur_queue_size; } CThread_pool; int pool_add_worker(void *(*process)(void *arg), void *arg); void *thread_routine(void *arg); static CThread_pool *pool = 0; void pool_init(int max_thread_num) { pool = (CThread_pool *)malloc(sizeof(CThread_pool)); pthread_mutex_init(&(pool->queue_lock), 0); pthread_cond_init(&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *)malloc(max_thread_num*sizeof(pthread_t)); for(int i=0; i < max_thread_num; i++){ pthread_create(&(pool->threadid[i]), 0, thread_routine, 0); } } int pool_add_worker(void *(*process)(void *arg), void *arg){ CThread_worker *newworker = (CThread_worker *)malloc(sizeof(CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock(&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if(member != 0){ while(member->next != 0) member = member->next; member->next = newworker; }else{ pool->queue_head = newworker; } assert(pool->queue_head != 0); pool->cur_queue_size++; pthread_mutex_unlock(&(pool->queue_lock)); pthread_cond_signal(&(pool->queue_ready)); return 0; } int pool_destroy(){ if(pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast(&(pool->queue_ready)); for(int i=0; i < pool->max_thread_num; i++) pthread_join(pool->threadid[i], 0); free(pool->threadid); CThread_worker *head = 0; while(pool->queue_head != 0){ head = pool->queue_head; pool->queue_head = pool->queue_head->next; free(head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free(pool); pool = 0; return 0; } void *thread_routine(void *arg){ printf("starting thread 0x%x\\n", pthread_self()); while(1){ pthread_mutex_lock(&(pool->queue_lock)); while(pool->cur_queue_size == 0 && !pool->shutdown){ printf("thread 0x%x is waiting\\n", pthread_self()); pthread_cond_wait(&(pool->queue_ready), &(pool->queue_lock)); } if(pool->shutdown){ pthread_mutex_unlock(&(pool->queue_lock)); printf("thread 0x%x will exit\\n", pthread_self()); pthread_exit(0); } printf("thread 0x%x is starting to work\\n", pthread_self()); assert(pool->cur_queue_size != 0); assert(pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock(&(pool->queue_lock)); free(worker); worker = 0; } pthread_exit(0); } void *myprocess(void *arg){ printf("threadid is 0x%x, working on task %d\\n", pthread_self(), *(int *)arg); sleep(1); return 0; } int main(int argc, char **argv){ pool_init(10); int *workingnum = (int *)malloc(sizeof(int)*10); for(int i=0; i < 10; i++){ workingnum[i] = i; pool_add_worker(myprocess, &workingnum[i]); } sleep(5); pool_destroy(); free(workingnum); return 0; }
1
#include <pthread.h> pthread_mutex_t lock_it = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t write_it = PTHREAD_COND_INITIALIZER; { char buffer[5]; int how_many; }BUFFER; BUFFER share = {"", 0}; boolean finished = FALSE; void *read_some(void *p) { int ch; printf("R %2d: Starting\\n", pthread_self()); while(!finished) { pthread_mutex_lock(&lock_it); if (share.how_many != 5) { ch = getc(stdin); if (ch == EOF) { share.buffer[share.how_many] = 0; share.how_many = 5; finished = TRUE; printf("R %2d: Signaling done\\n", pthread_self()); pthread_cond_signal(&write_it); pthread_mutex_unlock(&lock_it); break; } else { share.buffer[share.how_many++] = ch; if (share.how_many == 5) { printf("R %2d: Signaling full\\n", pthread_self()); pthread_cond_signal(&write_it); } } } pthread_mutex_unlock(&lock_it); } printf("R %2d: Exiting\\n", pthread_self()); return 0; } void *write_some(void *p) { int i; printf("W %2d: Starting \\n", pthread_self()); while(!finished) { pthread_mutex_lock(&lock_it); printf("\\nW %2d: Waiting\\n", pthread_self()); while(share.how_many != 5) { pthread_cond_wait(&write_it, &lock_it); } printf("W %2d: Writing buffer\\n", pthread_self()); for (i = 0; share.buffer && share.how_many; ++i, share.how_many--) { putchar(share.buffer[i]); } pthread_mutex_unlock(&lock_it); } printf("W %2d: Exiting\\n", pthread_self()); return 0; } int main(int argc, char**argv) { pthread_t t_read, t_write; pthread_create(&t_read, 0, read_some, 0); pthread_create(&t_write, 0, write_some, 0); pthread_join(t_write, 0); pthread_mutex_destroy(&lock_it); pthread_cond_destroy(&write_it); return 0; }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { long my_id = (long)t; while(1){ pthread_mutex_lock(&count_mutex); count++; printf("(%ld) count = %d\\n", my_id, count); if (count == 4) { pthread_cond_signal(&count_threshold_cv); printf("(%ld) condição atendida (count= %d).\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; pthread_mutex_lock(&count_mutex); while (1) { printf("(%ld) aguardando sinal.\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("(%ld) sinal recebido.\\n", my_id); count = 0; printf("(%ld) contador alterado para %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_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, watch_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> int do_debug = 0; int do_thread = 0; int do_stdin = 0; int do_sleep = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t rand_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dice_mutexes[7] = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, }; int die_sizes[7] = { 4, 6, 8, 10, 12, 20, 100 }; int threadcount = 0; struct sockets { int local; FILE *in, *out; }; struct sockets *get_sockets(int); int socket_setup(void); int debug(char *, ...); int fail(char *, ...); int warn(char *, ...); int roll_die(int); void *roll_dice(void *); void spawn(struct sockets *); int debug(char *fmt, ...) { va_list ap; int r; __builtin_va_start((ap)); if (do_debug) { r = vfprintf(stderr, fmt, ap); } else { r = 0; } ; return r; } int warn(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); ; return r; } int fail(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); exit(1); ; return r; } int roll_die(int n) { int r; pthread_mutex_lock(&rand_mutex); r = rand() % n + 1; pthread_mutex_unlock(&rand_mutex); return r; } void * roll_dice(void *v) { struct sockets *s = v; char inbuf[512]; if (!s || !s->out || !s->in) return 0; fprintf(s->out, "enter die rolls, or q to quit\\n"); while (fgets(inbuf, sizeof(inbuf), s->in) != 0) { char *str = inbuf; int dice; int size; int locked[7] = { 0, 0, 0, 0, 0, 0, 0 }; int i; if (inbuf[0] == 'q') { fprintf(s->out, "buh-bye!\\n"); if (s->local == 0) { shutdown(fileno(s->out), SHUT_RDWR); } fclose(s->out); fclose(s->in); if (s->local == 0) { free(s); } pthread_mutex_lock(&count_mutex); --threadcount; if (threadcount == 0) exit(0); pthread_mutex_unlock(&count_mutex); return 0; } while (strlen(str)) { if (sscanf(str, "%dd%d", &dice, &size) != 2) { fprintf(s->out, "Sorry, but I couldn't understand that.\\n"); *str = '\\0'; } else { int total = 0; if (strchr(str + 1, ' ')) { str = strchr(str + 1, ' '); } else { *str = '\\0'; } for (i = 0; i < 7; ++i) { if (die_sizes[i] == size) break; } if (i == 7) { fprintf(s->out, "The only dice on the table are a d4, a d6, a d8, a d10, a d12, a d20, and a d100.\\n"); continue; } if (!locked[i]) { pthread_mutex_lock(&dice_mutexes[i]); locked[i] = 1; } for (i = 0; i < dice; ++i) { int x = roll_die(size); total += x; fprintf(s->out, "%d ", x); fflush(s->out); if (do_sleep) sleep(1); } fprintf(s->out, "= %d\\n", total); } } for (i = 0; i < 7; ++i) { if (locked[i]) pthread_mutex_unlock(&dice_mutexes[i]); } } return 0; } int main(int argc, char *argv[]) { int o; int sock; while ((o = getopt(argc, argv, "dstS")) != -1) { switch (o) { case 'S': do_sleep = 1; break; case 'd': do_debug = 1; break; case 's': do_stdin = 1; break; case 't': do_thread = 1; break; } } if (do_thread) { int i; pthread_mutex_init(&count_mutex, 0); pthread_mutex_init(&rand_mutex, 0); for (i = 0; i < 7; ++i) { pthread_mutex_init(&dice_mutexes[i], 0); } } if (do_stdin) { struct sockets s; s.local = 1; s.in = stdin; s.out = stdout; if (do_thread) { spawn(&s); } else { roll_dice(&s); exit(0); } } sock = socket_setup(); while (1) { struct sockets *s = get_sockets(sock); if (s) { if (do_thread) { spawn(s); } else { roll_dice(s); exit(0); } } } return 0; } int socket_setup(void) { struct protoent *tcp_proto; struct sockaddr_in local; int r, s, one; tcp_proto = getprotobyname("tcp"); if (!tcp_proto) { fail("Can't find TCP/IP protocol: %s\\n", strerror(errno)); } s = socket(PF_INET, SOCK_STREAM, tcp_proto->p_proto); if (s == -1) { fail("socket: %s\\n", strerror(errno)); } one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_family = AF_INET; local.sin_port = htons(6173); r = bind(s, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (r == -1) { fail("bind: %s\\n", strerror(errno)); } r = listen(s, 5); if (r == -1) { fail("listen: %s\\n", strerror(errno)); } return s; } struct sockets * get_sockets(int sock) { int conn; if ((conn = accept(sock, 0, 0)) < 0) { warn("accept: %s\\n", strerror(errno)); return 0; } else { struct sockets *s; s = malloc(sizeof(struct sockets)); if (s == 0) { warn("malloc failed.\\n"); return 0; } s->local = 0; s->in = fdopen(conn, "r"); s->out = fdopen(conn, "w"); setlinebuf(s->in); setlinebuf(s->out); return s; } } void spawn(struct sockets *s) { pthread_t p; pthread_mutex_lock(&count_mutex); pthread_create(&p, 0, roll_dice, (void *) s); ++threadcount; pthread_mutex_unlock(&count_mutex); }
0
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; void functionInsideCriticalSection() { pthread_mutex_unlock(&(sip->lock)); printf("Value is currently: %i\\n", sip->value); pthread_mutex_lock(&(sip->lock)); } void *functionWithCriticalSection(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; if(sip->value = 1) { sip->value += functionInsideCriticalSection(); } pthread_mutex_unlock(&(sip->lock)); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); return sip->value-3; }
1
#include <pthread.h> pthread_t ThreadId[4]; pthread_mutex_t Mutex; int Available = 10; int Goal[4]= {6,5,4,7}; int Hold[4] = {0,0,0,0}; int Need[4]; int Request; int cusflag; int Left; int Finish[4]; void init() { cusflag = -1; int i,j; for(j=0; j<4; ++j) Finish[j] = 1; Left = Available; for(i=0; i<4; ++i) { Need[i]= Goal[i] - Hold[i]; } printf("=================================OS program3====================================\\n"); } int CheckSafty(int thr) { int i,j,k; Left = Available; for(j=0; j<4; ++j) Finish[j] = 0; int customer[4]; int cnt = 1; customer[cnt-1] = thr; int iflag = 1; Finish[thr] = 1; if(Need[thr]<=Available){ printf("Request of customer %d is safe!\\n",thr); return 1; } else{ pthread_mutex_lock(&Mutex); for(k=0; k<4; ++k) { for(i=0; i<4; ++i) { if(!Finish[i]) { if(Need[i] > Left) {iflag = 0;} if(iflag) { customer[cnt++] = i; Finish[i] = 1; Left += Hold[i]; } else iflag = 1; } } if(cnt == 4) break; } pthread_mutex_unlock(&Mutex); if(cnt != 4) return 0; printf("Request of customer %d is safe!\\nThe safe order of customers is:\\n",thr); for(i=0; i<4; ++i) printf("%d ",customer[i]); putchar('\\n'); return 1; } } void menu() { int i; printf("=================================infomation====================================\\n"); printf("Hello,I am the banker. The information has been summed up as follows:\\n"); printf("Available money: %d\\n",Available); for(i=0; i<4; ++i) printf("Customer %d holds money: %d Goal:%d Need:%d State:%d\\n",i,Hold[i],Goal[i],Need[i],Finish[i]); printf("=================================menu==========================================\\n"); printf("q -- exit r -- request\\n"); } int RequestMoney(int thr) { int j; if(Request > Need[thr]) return -1; if(Request > Available) return -2; pthread_mutex_lock(&Mutex); Available -= Request; Hold[thr] += Request; Need[thr] -= Request; pthread_mutex_unlock(&Mutex); if(0 == Need[thr]) { Available += Hold[thr]; Hold[thr] = 0; Need[thr] = 0; Finish[thr]=0; printf("The customer %d has returned money.\\n"); } if(!CheckSafty(thr)) { pthread_mutex_lock(&Mutex); Available += Request; Hold[thr] -= Request; Need[thr] += Request; pthread_mutex_unlock(&Mutex); return 1; } return 0; } void *runner(void *param) { int i,result,thr = (int)param; while(1) { sleep(1); if(cusflag == thr) { result = RequestMoney((int)param); switch(result) { case -2: printf("Request for Customer %d is not available\\n",thr); break; case -1: printf("Request for Customer %d is exceeded\\n",thr); break; case 1: printf("Request for Customer %d is not Safe!\\n",thr); break; default: break; } cusflag = -1; menu(); printf("Please input your choice:"); } } } void mainthread() { menu(); printf("Please input your choice:"); while(1) { char choice; scanf("%c",&choice); if(choice == 'q') break; if(choice == 'r'){ printf("Choose customer:"); int cus; scanf("%d",&cus); printf("Input request:"); scanf("%d",&Request); cusflag=cus; sleep(1); } else continue; } printf("The main thread ends.\\n"); } int main() { int i; init(); for(i=0; i<4; ++i) { int error; error=pthread_create(&ThreadId[i],0,runner,i); if(error) printf("Fail creating customer[i], error type:%d\\n",error); } mainthread(); for(i=0; i<4; ++i) if(ThreadId[i] !=0) { pthread_join(ThreadId[i],0); printf("Customer %d ends\\n",i); } system("pause"); return 0; }
0
#include <pthread.h> void func1(); void func2(); pthread_cond_t cond; pthread_mutex_t mutex; int food=0; int main() { pthread_t thread[2]; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); int i=0; int *status; void (*funcptr[2])(); funcptr[0]=func1; funcptr[1]=func2; for (i=0;i<2;i++) { if(pthread_create(&thread[i],0,(void *)funcptr[i],0)) { printf("thread %ld failed to create",thread[i]); } } for (i=0;i<2;i++) pthread_join(thread[i],(void*)&status); pthread_exit(0); return 0; } void func1() { while(1) { sleep(1); pthread_mutex_lock(&mutex); printf("I am producer -- food is %d\\n",++food); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } } void func2() { while(1) { sleep(1); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); printf("I am consumer- food is %d\\n",--food); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> pthread_mutex_t mutex; int counter=1; int matriz[100][10]; int somaColuna[10]; void imprime_matriz(){ int i, j; for(j=0;j<10;j++){ printf( "Soma da coluna %d (thread %d) = %d\\n", j, j, somaColuna[j]); } printf("\\n"); } void* inicializa_matriz(void *p){ int i, j, n, soma; n = (int)(size_t)p; pthread_mutex_lock(&mutex); for(j=0;j<100;j++) { matriz[j][n] = rand()%100; somaColuna[n] += matriz[j][n]; } pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char **argv) { int i; pthread_t tid[10]; pthread_mutex_init(&mutex, 0); srand(time(0)); for(i=0;i<10;i++) pthread_create(&tid[i], 0, inicializa_matriz, (void *)(size_t) i); for(i=0;i<10;i++) pthread_join(tid[i], 0); imprime_matriz(); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len+1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return(ENOSPC); } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return(0); } } pthread_mutex_unlock(&env_mutex); return(ENOENT); }
1
#include <pthread.h> static volatile int g_account; static pthread_mutex_t lock; void * Deposit(int amount) { int balance; pthread_mutex_lock(&lock); balance = g_account; pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); g_account = balance + amount; pthread_mutex_unlock(&lock); return 0; } void * Withdraw(int amount) { int balance; pthread_mutex_lock(&lock); balance = g_account; pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); g_account = balance - amount; pthread_mutex_unlock(&lock); return 0; } static void usage(char *argv[]) { printf("%s -x <x> -y <y>\\n" "-x : input for thread 1\\n" "-y : input for thread 2\\n", argv[0]); } int main(int argc, char *argv[]) { pthread_t allthr[10]; int i, ret; int x, y; x = 13; y = 0; while((i=getopt(argc, argv, "x:y:h")) != EOF) { switch(i) { case 'h': usage(argv); return 0; case 'x': x = strtol(optarg, 0, 0); break; case 'y': y = strtol(optarg, 0, 0); break; default: errx(1, "invalid option"); } } pthread_mutex_init(&lock, 0); g_account = 10; ret = pthread_create(&allthr[0], 0, Deposit, 1); if (ret) err(1, "pthread_create failed"); Withdraw(2); pthread_join(allthr[0], 0); assert( g_account == 9 ); return 0; }
0
#include <pthread.h> { char name[256]; int life; } POKEMON; static pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; static int waiting[5]; static POKEMON waitingPkmn[5][6]; static pthread_cond_t clients_waiting, client_wakeup[5]; static int client_id = 1; static int machine_id = 1; static const char* POKEMON_NAMES[] = {"Bulbasaur", "Ivysaur", "Venusaur", "Charmander", "Charmeleon", "Charizard", "Squirtle", "Wartortle", "Blastoise", "Caterpie", "Metapod", "Butterfree", "Weedle", "Kakuna", "Beedrill", "Pidgey", "Pidgeotto", "Pidgeot", "Rattata", "Raticate", "Spearow", "Fearow", "Ekans", "Arbok", "Pikachu", "Raichu", "Sandshrew", "Sandslash", "Nidoran♀", "Nidorina", "Nidoqueen", "Nidoran♂", "Nidorino", "Nidoking", "Clefairy", "Clefable", "Vulpix", "Ninetales", "Jigglypuff", "Wigglytuff", "Zubat", "Golbat", "Oddish", "Gloom", "Vileplume", "Paras", "Parasect", "Venonat", "Venomoth", "Diglett", "Dugtrio", "Meowth", "Persian", "Psyduck", "Golduck", "Mankey", "Primeape", "Growlithe", "Arcanine", "Poliwag", "Poliwhirl", "Poliwrath", "Abra", "Kadabra", "Alakazam", "Machop", "Machoke", "Machamp", "Bellsprout", "Weepinbell", "Victreebel", "Tentacool", "Tentacruel", "Geodude", "Graveler", "Golem", "Ponyta", "Rapidash", "Slowpoke", "Slowbro", "Magnemite", "Magneton", "Farfetch'd", "Doduo", "Dodrio", "Seel", "Dewgong", "Grimer", "Muk", "Shellder", "Cloyster", "Gastly", "Haunter", "Gengar", "Onix", "Drowzee", "Hypno", "Krabby", "Kingler", "Voltorb", "Electrode", "Exeggcute", "Exeggutor", "Cubone", "Marowak", "Hitmonlee", "Hitmonchan", "Lickitung", "Koffing", "Weezing", "Rhyhorn", "Rhydon", "Chansey", "Tangela", "Kangaskhan", "Horsea", "Seadra", "Goldeen", "Seaking", "Staryu", "Starmie", "Mr. Mime", "Scyther", "Jynx", "Electabuzz", "Magmar", "Pinsir", "Tauros", "Magikarp", "Gyarados", "Lapras", "Ditto", "Eevee", "Vaporeon", "Jolteon", "Flareon", "Porygon", "Omanyte", "Omastar", "Kabuto", "Kabutops", "Aerodactyl", "Snorlax", "Articuno", "Zapdos", "Moltres", "Dratini", "Dragonair", "Dragonite", "Mewtwo", "Mew"}; void generatePokemons(POKEMON pokemones[6]){ srand(time(0)); int i; int cant = rand()%3 + 4; for(i = 0; i < cant; i++){ strcpy(pokemones[i].name, POKEMON_NAMES[rand()%150]); pokemones[i].life = rand()%70 + 1; } for(i = cant; i < 6; i++){ pokemones[i].life = -1; } } void printPokemons(POKEMON pokemones[6]){ int i; int j = 1; for (i= 0; i<6 && pokemones[i].life != -1; i++){ printf(" %d) %-15s--- Life: %d%% \\n", j, pokemones[i].name, pokemones[i].life); j++; } } static int get_client(void) { int id = 0, chair = -1; int i, n; for ( i = 0 ; i < 5 ; i++ ) if ( (n = waiting[i]) && (!id || n < id) ) { id = n; chair = i; } if ( chair != -1 ) { pthread_cond_signal(&client_wakeup[chair]); waiting[chair] = 0; } return id; } static void curar_pokemones(POKEMON pokemones[6], int cant){ int i; for(i = 0; i<cant && pokemones[i].life != -1; i++){ printf("Curando a: %s\\n", pokemones[i].name ); usleep(15000* (100-pokemones[i].life)); pokemones[i].life = 100; } } static void cut_hair(int barb, int clt) { printf("Peluquero %d: atiendo cliente %d\\n", barb, clt); usleep(1000000 + rand() % 2000000); printf("Peluquero %d: cliente %d atendido\\n", barb, clt); } static void * machine(void *arg) { int id; pthread_mutex_lock(&mut); id = machine_id++; pthread_mutex_unlock(&mut); printf("Peluquero %d: creado\\n", id); while ( 1 ) { int n; pthread_mutex_lock(&mut); while ( !(n = get_client()) ) { printf("Peluquero %d: esperando cliente\\n", id); pthread_cond_wait(&clients_waiting, &mut); } pthread_mutex_unlock(&mut); cut_hair(id, n); } return 0; } static int get_chair(void) { int i; for ( i = 0 ; i < 5 ; i++ ) if ( !waiting[i] ) return i; return -1; } static void * client(void *arg) { int id, n; pthread_mutex_lock(&mut); POKEMON pkmn[6]; generatePokemons(pkmn); printPokemons(pkmn); id = client_id++; printf("Cliente %d: creado\\n", id); if ( (n = get_chair()) != -1 ) { waiting[n] = id; pthread_cond_signal(&clients_waiting); printf("Cliente %d: espero en la silla %d\\n", id, n); pthread_cond_wait(&client_wakeup[n], &mut); printf("Cliente %d: me atiende un peluquero\\n", id); } else printf("Cliente %d: no hay sillas libres\\n", id); pthread_mutex_unlock(&mut); return 0; } static void create_machines(void) { pthread_t machine_thr; pthread_create(&machine_thr, 0, machine, 0); pthread_detach(machine_thr); } static void create_client(void) { pthread_t trainer_thr; pthread_create(&trainer_thr, 0, client, 0); pthread_detach(trainer_thr); } int main(){ int c,i; for ( i = 0 ; i < 3 ; i++ ) create_machines(); while ( (c = getchar()) != EOF ){ create_client(); } }
1
#include <pthread.h> int sum_prim=0; int sum_par=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void *PrintM (void *argv) { int nr= (int) argv; pthread_mutex_lock(&mutex); if (nr % 2 == 0 ) { printf("Nr %d e par!\\n",nr); sum_par=sum_par+nr; } else{ int i; int ok=1; for(i=2;i<nr-1;++i) if (nr % i ==0 ){ ok=0; break; } if (ok) { printf("Nr %d e prim!\\n",nr); sum_prim=sum_prim+nr; } } pthread_mutex_unlock(&mutex); pthread_exit (0); } int main (int argc, char *argv[]) { pthread_t threads[5]; int rc,n; long t; for (t = 1; t < argc; t++) { n=atoi(argv[t]); rc = pthread_create (&threads[t], 0, PrintM, (void *) n); if (rc) { printf ("ERROR; codul de retur pentru pthread_create() este %d\\n", rc); exit (-1); } } for(t=1;t<argc;t++) pthread_join(threads[t],0); printf("Suma argumentelor pare: %d\\n",sum_par); printf("SUma argumentelor prime: %d\\n",sum_prim); pthread_exit (0); }
0
#include <pthread.h> const int MAX_KEY = 65535; struct list_node_s { int data; struct list_node_s* next; }; struct list_node_s* head = 0; int thread_count; int total_ops; double insert_percent; double search_percent; double delete_percent; int member_total=0, insert_total=0, delete_total=0; void Get_input(int* inserts_in_main_p); void* Thread_work(void* rank); int Insert(int value); void Print(void); int Member(int value); int Delete(int value); pthread_mutex_t mutex; pthread_mutex_t count_mutex; int main(){ int inserts_in_main,success,key; inserts_in_main=1000; total_ops=10000; insert_percent=.99; search_percent=.005; delete_percent=.005; long i; i = 0; while ( i < inserts_in_main ) { key = rand() % MAX_KEY; success = Insert(key); if (success) i++; } pthread_t* thread_handles; thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&count_mutex, 0); int start=clock(); for (i = 0; i < thread_count; i++) pthread_create(&thread_handles[i], 0, Thread_work, (void*) i); for (i = 0; i < thread_count; i++) pthread_join(thread_handles[i], 0); int finish = clock(); printf("Elapsed time = %f seconds\\n", (double)(finish - start)/ CLOCKS_PER_SEC); } void Get_input(int* inserts_in_main_p) { printf("How many keys should be inserted in the main thread?\\n"); scanf("%d", inserts_in_main_p); printf("How many total ops should be executed?\\n"); scanf("%d", &total_ops); printf("Percent of ops that should be searches? (between 0 and 1)\\n"); scanf("%lf", &search_percent); printf("Percent of ops that should be inserts? (between 0 and 1)\\n"); scanf("%lf", &insert_percent); delete_percent = 1.0 - (search_percent + insert_percent); printf("Number of Threads that should be tested?\\n"); scanf("%d", &thread_count); } void Print(void) { struct list_node_s* temp; printf("list = "); temp = head; while (temp != (struct list_node_s*) 0) { printf("%d ", temp->data); temp = temp->next; } printf("\\n"); } int Insert(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; struct list_node_s* temp; int rv = 1; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr == 0 || curr->data > value) { temp = malloc(sizeof(struct list_node_s)); temp->data = value; temp->next = curr; if (pred == 0) head = temp; else pred->next = temp; } else { rv = 0; } return rv; } void* Thread_work(void* rank) { long my_rank = (long) rank; int i, val; double which_op; unsigned seed = my_rank + 1; int my_member=0, my_insert=0, my_delete=0; int ops_per_thread = total_ops/thread_count; double choice; int memberCount=0, insertCount=0, deleteCount=0; for(i=0;i<ops_per_thread;){ choice = ((double)(rand()%10000))/10000.0; if(choice <search_percent && memberCount < ops_per_thread*search_percent){ val = rand()%MAX_KEY; pthread_mutex_lock(&mutex); Member(val); pthread_mutex_unlock(&mutex); memberCount++;i++; } else if(choice >= search_percent && choice <search_percent+insert_percent && insertCount < ops_per_thread*insert_percent){ val = rand()%MAX_KEY; pthread_mutex_lock(&mutex); Insert(val); pthread_mutex_unlock(&mutex); insertCount++;i++; } else if(choice >=search_percent+insert_percent && deleteCount < ops_per_thread*delete_percent){ val = rand()%MAX_KEY; pthread_mutex_lock(&mutex); Delete(val); pthread_mutex_unlock(&mutex); deleteCount++;i++; } } return 0; } int Member(int value) { struct list_node_s* temp; temp = head; while (temp != 0 && temp->data < value) temp = temp->next; if (temp == 0 || temp->data > value) { return 0; } else { return 1; } } int Delete(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; int rv = 1; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr != 0 && curr->data == value) { if (pred == 0) { head = curr->next; free(curr); } else { pred->next = curr->next; free(curr); } } else { rv = 0; } return rv; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cv1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cv2 = PTHREAD_COND_INITIALIZER; int cola = 0; int t_prod; int t_cons; int max; int tam_cola; int cont_p = 0; int done = 0; void *producir(void *arg) { while (1) { if (!done) { printf("IF PRODUCTOR\\n"); pthread_mutex_lock(&mutex); while (cola == tam_cola) { pthread_cond_wait(&cv1, &mutex); } sleep(t_prod); if (cont_p == max) { done = 1; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cv2); } else { cola++; printf("El hilo %lu ha producido 1 item, tamaño de la cola = %d.\\n", pthread_self(), cola); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cv2); cont_p++; printf("MAX: %d cont_p: %d\\n", max, cont_p); } } else { printf("BREAK PRODUCTOR\\n"); break; } } printf("RETORNO PRODUCTOR\\n"); return 0; } void *consumir(void *arg) { if (cola > 0) { done = 0; } while (1) { if (!done) { printf("IF CONSUMIDOR\\n"); pthread_mutex_lock(&mutex); while (cola == 0) { pthread_cond_wait(&cv2, &mutex); } sleep(t_cons); cola--; printf("El hilo %lu ha consumido 1 item, tamaño de la cola = %d.\\n", pthread_self(), cola); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cv1); if (cont_p == max && cola == 0) { done = 1; } } else { printf("BREAK CONSUMIDOR\\n"); break; } } printf("RETORNO CONSUMIDOR\\n"); return 0; } int main(int argc, char *argv[]) { if (argc != 7) { printf("USO: ./pc <num_hilos_prod> <tiempo_prod> <num_hilos_cons> <tiempo_cons> <tam_cola> <total_items>\\n"); exit(-1); } t_prod = atoi(argv[2]); t_cons = atoi(argv[4]); max = atoi(argv[6]); int num_hilos_p = atoi(argv[1]); int num_hilos_c = atoi(argv[3]); tam_cola = atoi(argv[5]); int status; pthread_t *threads_p = malloc(num_hilos_p * sizeof(pthread_t)); pthread_t *threads_c = malloc(num_hilos_c * sizeof(pthread_t)); for (int i = 0; i < num_hilos_p; i++) { status = pthread_create(&threads_p[i], 0, producir, 0); if (status != 0) { printf("Error al crear el hilo productor %d\\n.", i + 1); } } for (int i = 0; i < num_hilos_c; i++) { status = pthread_create(&threads_c[i], 0, consumir, 0); if (status != 0) { printf("Error al crear el hilo consumidor %d\\n.", i + 1); } } for (int i = 0; i < num_hilos_p; i++) { status = pthread_join(threads_p[i], 0); if (status != 0) { printf("Error al esperar por el hilo %d\\n.", i + 1); exit(-1); } } for (int i = 0; i < num_hilos_c; i++) { status = pthread_join(threads_c[i], 0); if (status != 0) { printf("Error al esperar por el hilo %d\\n.", i + 1); exit(-1); } } return 0; }
0
#include <pthread.h> void *Worker(void *); void InitializeGrids(); void Barrier(); struct tms buffer; clock_t start, finish; pthread_mutex_t barrier; pthread_cond_t go; int numArrived = 0; int gridSize, numWorkers, numIters, stripSize; double maxDiff[20]; double grid1[10000][10000]; double grid2[10000][10000]; double maxdiff; int main(int argc, char* argv[]) { pthread_t workerid[20]; pthread_attr_t attr; int i, j; long li; maxdiff = 0.001 + 1; numIters = 0; FILE *results; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&barrier, 0); pthread_cond_init(&go, 0); gridSize = atoi(argv[1]); numWorkers = atoi(argv[2]); stripSize = gridSize/numWorkers; InitializeGrids(); start = times(&buffer); printf("Create the worker threads\\n"); for (i = 0; i < numWorkers; i++) { li = i; pthread_create(&workerid[i], &attr, Worker, (void *) li); } printf("Wait for all worker threads to finish\\n"); for (i = 0; i < numWorkers; i++) pthread_join(workerid[i], 0); finish = times(&buffer); printf("number of iterations: %d\\nmaximum difference: %e\\n", numIters, maxdiff); printf("start: %ld finish: %ld\\n", start, finish); printf("elapsed time: %ld\\n", finish-start); results = fopen("results", "w"); for (i = 1; i <= gridSize; i++) { for (j = 1; j <= gridSize; j++) { fprintf(results, "%f ", grid2[i][j]); } fprintf(results, "\\n"); } } void *Worker(void *arg) { long myid =(long)arg; double localDiff, temp; int i, j; int first, last; printf("worker %ld (pthread id %lu has started\\n", myid, pthread_self()); first = myid * stripSize + 1; if(myid == numWorkers-1) last = gridSize; else last = first + stripSize - 1; while (maxdiff > 0.001) { for (i = first; i <= last; i++) { for (j = 1; j <= gridSize; j++) { grid2[i][j] = (grid1[i-1][j] + grid1[i+1][j] + grid1[i][j-1] + grid1[i][j+1]) * 0.25; } } Barrier(); localDiff = 0.0; for (i = first; i <= last; i++) { for (j = 1; j <= gridSize; j++) { grid1[i][j] = (grid2[i-1][j] + grid2[i+1][j] + grid2[i][j-1] + grid2[i][j+1]) * 0.25; temp = grid1[i][j] - grid2[i][j]; if (temp < 0) { temp *= -1; } if (localDiff < temp) { localDiff = temp; } } } maxDiff[myid] = localDiff; Barrier(); if (myid == 0) { maxdiff = 0.0; numIters++; for (i = 0; i < numWorkers; i++) { if (maxdiff < maxDiff[i]) { maxdiff = maxDiff[i]; } } } Barrier(); } return 0; } void InitializeGrids() { int i, j; for (i = 0; i <= gridSize+1; i++) for (j = 0; j <= gridSize+1; j++) { grid1[i][j] = 0.0; grid2[i][j] = 0.0; } for (i = 0; i <= gridSize+1; i++) { grid1[i][0] = 1.0; grid1[i][gridSize+1] = 1.0; grid2[i][0] = 1.0; grid2[i][gridSize+1] = 1.0; } for (j = 0; j <= gridSize+1; j++) { grid1[0][j] = 1.0; grid2[0][j] = 1.0; grid1[gridSize+1][j] = 1.0; grid2[gridSize+1][j] = 1.0; } } void Barrier() { pthread_mutex_lock(&barrier); numArrived++; if (numArrived == numWorkers) { numArrived = 0; pthread_cond_broadcast(&go); } else pthread_cond_wait(&go, &barrier); pthread_mutex_unlock(&barrier); }
1
#include <pthread.h> { void *(*routine)(void *arg); void *arg; uint64_t id; pthread_t tid; } worker_task; uint64_t bitmap; worker_task tasks[64]; uint64_t tear_down; } thread_pool; int g_flag; static thread_pool tp; static thread_pool *pool = &tp; pthread_mutex_t mutex; pthread_mutex_t pool_mutex; pthread_mutex_t io_mutex; pthread_cond_t cond; int nthread; thread_pool *pool; uint64_t id; } thread_argument; void thread_add_task(void *(*callback)(void *), void *arg) { int i; pthread_mutex_lock(&pool_mutex); for (i = 0; i < 2; ++i) { if (pool->bitmap & (1 << i)) { dprintf(INFO, "%d busy\\n", i); continue; } pool->tasks[i].routine = callback; pool->tasks[i].arg = arg; pool->bitmap |= (1 << i); assert(pool->bitmap & (1 << i)); dprintf(INFO, "%d loaded\\n", i); pthread_mutex_unlock(&pool_mutex); break; } pthread_cond_signal(&cond); } static void *thread_pool_wrapper(void *arg) { thread_pool *pool = (thread_pool *)arg; uint64_t id = __sync_fetch_and_add(&nthread, 1); dprintf(WARN, "id: %lu\\n", id); dprintf(INFO, "%lu idle: %lx\\n", id, pthread_self()); while (1) { pthread_cond_wait(&cond, &mutex); if (pool->tear_down) { pthread_mutex_unlock(&mutex); pthread_exit(0); } if (pool->tasks[id].routine) { dprintf(INFO, "%lu start\\n", id); (*(pool->tasks[id].routine))(pool->tasks[id].arg); dprintf(INFO, "%lu finish\\n", id); pthread_mutex_lock(&pool_mutex); pool->bitmap &= ~(1 << id); pool->tasks[id].routine = 0; pool->tasks[id].arg = 0; pthread_mutex_unlock(&pool_mutex); } else { pthread_t tid = pthread_self(); dprintf(INFO, "hello, I'm %x. None of my biz.\\n", tid); } } } void thread_pool_init() { uint64_t i; pool->bitmap = 0L; pool->tear_down = 0; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&pool_mutex, 0); pthread_mutex_init(&io_mutex, 0); pthread_cond_init(&cond, 0); pthread_mutex_lock(&mutex); memset(&pool->tasks, 0, 64 * sizeof(worker_task)); for (i = 0; i < 2; ++i) { pthread_create(&(pool->tasks[i].tid), 0, thread_pool_wrapper, pool); dprintf(INFO, "pthread_create: %x\\n", pool->tasks[i].tid); } pthread_mutex_unlock(&mutex); } void thread_pool_destroy() { uint8_t i; pool->tear_down = 1; pthread_cond_broadcast(&cond); for (i = 0; i < 2; ++i) { pthread_join(pool->tasks[i].tid, 0); } pthread_cond_destroy(&cond); pthread_mutex_destroy(&io_mutex); pthread_mutex_destroy(&pool_mutex); pthread_mutex_destroy(&mutex); } void *simple(void *arg) { while (g_flag == 0) {} fprintf(stdout, "easy!\\n"); return 0; } int main(int argc, char *argv[]) { g_flag = 0; thread_pool_init(); sleep(1); thread_add_task(simple, 0); thread_add_task(simple, 0); sleep(1); g_flag = 1; sleep(1); thread_pool_destroy(); fflush(stdout); return 0; }
0
#include <pthread.h> volatile struct __ptable_entry __process_table[MAX_PROCESSES]; pthread_mutex_t __process_mutex = PTHREAD_MUTEX_INITIALIZER; volatile int __ptable_initted = 0; void __init_ptable() { int i; for(i = 0;i < MAX_PROCESSES;i++) __process_table[i].in_use = 0; __ptable_initted = 1; } int start_process(void (*func)()) { int i = -1; pthread_mutex_lock(&__process_mutex); if(!__ptable_initted) __init_ptable(); while(++i < MAX_PROCESSES && __process_table[i].in_use); if(i == MAX_PROCESSES) return -1; __process_table[i].in_use = 1; if(pthread_create((pthread_t *)&(__process_table[i].thread), 0, __run_process, (void *)func)) { __process_table[i].in_use = 0; return -1; } pthread_mutex_unlock(&__process_mutex); return i; } void kill_process(int pid) { pthread_mutex_lock(&__process_mutex); if(__process_table[pid].in_use) { pthread_cancel(__process_table[pid].thread); __process_table[pid].in_use = 0; } pthread_mutex_unlock(&__process_mutex); } int is_process_running(int pid) { pthread_mutex_lock(&__process_mutex); if(pthread_kill(__process_table[pid].thread, 0)) { pthread_mutex_unlock(&__process_mutex); return 0; } pthread_mutex_unlock(&__process_mutex); return 1; } void *__run_process(void *ptr) { void (*func)() = (void (*)())ptr; func(); return 0; }
1
#include <pthread.h> int *arr; long sum=0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *gausswasbetteratthis(void *threadid) { long start = (long)threadid*10000; long end = start+10000 -1; pthread_mutex_lock(&mutex); for (long i=start; i<=end ; i++){ sum += arr[i]; } pthread_mutex_unlock(&mutex); pthread_exit((void*) 0); } int main() { long i; void* status; pthread_t threads[10]; arr = (int*) malloc (10000*10*sizeof(int)); for (i=0; i<10000*10; i++) arr[i] = i+1; for(i=0; i<10; i++) pthread_create(&threads[i], 0, gausswasbetteratthis, (void *)i); for(i=0; i<10; i++) pthread_join(threads[i], &status); printf ("Summe der ersten %d Zahlen ist %li\\n", 10*10000, sum); free (arr); pthread_exit(0); }
0
#include <pthread.h> long thread_count; int a[32768]; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; struct Thread_params { long thread; int level; }; void *Reduce(void* rank); int main(int argc, char** argv) { long thread; pthread_t* thread_handles; int i; thread_count = 32768 / 2; int depth = log (32768) / log (2); for (i=0;i<32768;i++) a[i]=i+1; struct Thread_params *params=0; thread_handles = malloc (thread_count*sizeof(pthread_t)); for (i=1; i<= depth; i++) { for (thread = 0; thread < thread_count; thread++){ params = malloc(sizeof(struct Thread_params)); params->thread = thread; params->level = i; if (pthread_create(&thread_handles[thread], 0, Reduce, (void*) params)) {printf("nooooooo!!!\\n"); return 42;} } for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); thread_count = thread_count / 2; free(params); } printf("\\nsum [1..%d]=%d\\n",32768, a[0]); free(thread_handles); pthread_mutex_destroy(&lock); return 0; } void *Reduce(void* params) { struct Thread_params* my_params = (struct Thread_params*) params; int level = my_params->level; long thread = my_params->thread; pthread_mutex_lock(&lock); a[thread*(int)(pow(2,level))] = a[thread*(int)(pow(2,level))] + a[thread*(int)(pow(2,level)) + (int)(pow(2,level-1))]; pthread_mutex_unlock(&lock); fflush(stdout); return 0; }
1
#include <pthread.h> static void process_message(struct shfs *fs, struct shfs_message *m, const char *phost, int pport) { struct shfs_file_op op_alloc; struct shfs_file_op *op = &op_alloc; memset(op, 0, sizeof(*op)); strcpy(op->host, phost); op->port = pport; if (m->type & MESSAGE_ISDIR) op->type |= FILE_OP_ISDIR; switch (m->opcode) { case MESSAGE_PING: m->opcode = MESSAGE_PONG; printf("RECV [%s:%d] got ping\\n", phost, pport); socket_sendto(fs->sock, m, sizeof(*m), fs->peer_addr); return; case MESSAGE_PONG: printf("RECV [%s:%d] got pong\\n", phost, pport); return; case MESSAGE_READ: op->type |= FILE_OP_REMOTE_READ; strcpy(op->name, m->name); op->offset = m->offset; op->length = m->length; queue_enqueue(fs->queue_fs, op); return; case MESSAGE_CREATE: op->type |= FILE_OP_REMOTE_CREATE; strcpy(op->name, m->name); op->length = m->length; queue_enqueue(fs->queue_fs, op); return; case MESSAGE_WRITE: op->type |= FILE_OP_REMOTE_WRITE; strcpy(op->name, m->name); op->count = m->count; op->offset = m->offset; op->length = m->length; op->count = m->count < sizeof(m->data) ? m->count:sizeof(m->data); memcpy(op->data, m->data, op->count); queue_enqueue(fs->queue_fs, op); return; case MESSAGE_DELETE: op->type |= FILE_OP_REMOTE_DELETE; strcpy(op->name, m->name); queue_enqueue(fs->queue_fs, op); return; case MESSAGE_RENAME: { char *t; op->type |= FILE_OP_REMOTE_RENAME; t = strchr(m->name, '|'); if (0 == t) return; *t = '\\0'; strcpy(op->name, m->name); strcpy(op->toname, t + 1); queue_enqueue(fs->queue_fs, op); return; } } } void fd_request_timeouted(struct shfs *fs) { struct shfs_message m_alloc = {0}; struct shfs_message *m = &m_alloc; size_t i; fprintf(stderr, "searching timeouts in %d files\\n", (int)fs->fdlen); pthread_mutex_lock(&fs->fdlock); for (i = 0; i < fs->fdlen; i++) { int now; int last; now = time(0); last = fs->fdlist[i].lastrecv; fprintf(stderr, "last '%s', now = %d, last = %d\\n", fs->fdlist[i].name, now, last); if (1 < (now - last)) { fprintf(stderr, "resending offset %d/%d '%s'\\n", (int)fs->fdlist[i].offset, (int)fs->fdlist[i].length, fs->fdlist[i].name); memset(m, 0, sizeof(*m)); m->id = fs->id; m->key = fs->key; m->opcode = MESSAGE_READ; m->offset = (uint32_t)fs->fdlist[i].offset; strcpy(m->name, fs->fdlist[i].name); socket_sendto(fs->sock, m, sizeof(*m), fs->group_addr); } } pthread_mutex_unlock(&fs->fdlock); } void* recv_thread(void *param) { struct shfs *fs = param; while (1) { struct shfs_message m_alloc = {0}; struct shfs_message *m = &m_alloc; char phost[46] = {0}; char shost[46] = {0}; int pport = 0; int sport = 0; int s; s = socket_recvfrom(fs->sock, m, sizeof(*m), fs->peer_addr); if (-1 == s && EAGAIN == errno) { fd_request_timeouted(fs); continue; } if (s <= 0) continue; if (m->id == fs->id) { continue; } if (m->key != fs->key) { continue; } socket_addr_get_ip(fs->peer_addr, phost, sizeof(phost)); socket_addr_get_ip(fs->self_addr, shost, sizeof(shost)); socket_addr_get_port(fs->peer_addr, &pport); socket_addr_get_port(fs->self_addr, &sport); fprintf(stderr, "RECV [%s:%d] <- [%s:%d] recv %d bytes " "(op, type) = (0x%x, 0x%x) " "(id, key) = (0x%x, 0x%x)\\n", shost, sport, phost, pport, s, m->opcode, m->type, m->id, m->key); process_message(fs, m, phost, pport); } return 0; }
0
#include <pthread.h> char Keypress=0; char Id[10]; char ServerIp[15]; char ServerPort[7]; char g_Pass[20]; char HTTPS_IP[20]; char recvbuf[(1024)]; char Sendbuf[(1024)]; struct sockaddr_in cloudaddr; struct in_addr addrKA; static char Request[700] ; extern char lat[]; extern char lon[]; extern char Location[70]; extern pthread_mutex_t LocLock; int main(){ char * p_nvr; struct hostent *hostn = 0; p_nvr=nvram_get(7,"Id"); if(p_nvr!=0){ strcpy(Id,p_nvr); } else{ printf("NVRAM corrupted \\r\\n"); } p_nvr=nvram_get(7,"serverIp"); if(p_nvr!=0){ strcpy(ServerIp,p_nvr); } else{ printf("NVRAM corrupted \\r\\n"); } p_nvr=nvram_get(7,"serverPort"); if(p_nvr!=0){ strcpy(ServerPort,p_nvr); } else{ printf("NVRAM corrupted \\r\\n"); } p_nvr=nvram_get(7,"passWord"); if(p_nvr!=0){ strcpy(g_Pass,p_nvr); } else{ printf("NVRAM corrupted \\r\\n"); } printf("DevId=%s\\r\\n",Id); printf("Server @ %s:%s\\r\\n",ServerIp,ServerPort); printf("Welcome\\r\\n"); lcd_init(); sendCommand(0x80); lcd_puts(" Welcome "); init_GPS(); init_Keypad(); sendCommand(0xc0); lcd_puts(" Loaded "); sleep(1); while(!if_check()){ printf("Waiting for Ip\\r\\n"); if(Keypress==0){ sendCommand(0xc0); lcd_puts("Waiting for IP "); } sleep(7); } const char* host_name = nvram_get(7, "HostName"); printf("Host:==> %s\\r\\n",host_name); hostn= gethostbyname(host_name); if (!hostn) { printf("hostname fetch :failed"); sleep(3); } else { strcpy(HTTPS_IP, inet_ntoa( (struct in_addr) *((struct in_addr *) hostn->h_addr_list[0]))); printf("%s is on %s \\r\\n",host_name,HTTPS_IP); } SecLayerInit(); if (cloud_inf_init(0,HTTPS_IP, &cloudaddr,0) == -1) { printf("Cloud info init error\\n"); sleep (1); } printf("SSL OK\\n"); sendCommand(0xc0); lcd_puts("Server Connected ... "); sendCommand(0x80); lcd_puts(" Welcome "); sendCommand(0xc0); lcd_puts("Enter MobNumber "); while(1){ usleep(1000*1000*17); } return 0; } float convertToMap(float rawLatLong,char dir){ static float latlong; latlong=((int)(rawLatLong / 100)) + ((rawLatLong - (((int)(rawLatLong / 100)) * 100)) / 60); if((dir=='S')||(dir=='W')){ latlong=latlong*-1; } return latlong; } void SendDataToTheServer(char *Num){ int retry=0; float latc,lonc; char dir; pthread_mutex_lock(&LocLock); pthread_mutex_unlock(&LocLock); dir=lat[10]; lat[9]=0; latc=convertToMap(atof(lat),dir); dir=lon[10]; lon[9]=0; lonc=convertToMap(atof(lon),dir); sprintf(Request,"GET https://dheauto.com/dhericknew/user/create_request?cat=3&DevId=%s&mob_number=%s&latitude=%f&longitude=%f\\r\\n\\r\\n\\r\\n\\r\\n",Id,Num,latc,lonc); retr: if (httpsGet(0, Request, recvbuf, (1024)) < 1) { sendCommand(0x80); lcd_puts("ERROR "); sendCommand(0xc0); lcd_puts("Server Error "); sleep(1); return; } sendCommand(0x80); lcd_puts(" * OK *"); sendCommand(0x80); lcd_puts(" We will "); sendCommand(0xc0); lcd_puts("Get back to you"); sleep(1); } int if_check() { int fd; char ipadd[16]; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); fd = socket(AF_INET, SOCK_DGRAM, 0); ifr.ifr_addr.sa_family = AF_INET; strncpy(ifr.ifr_name, "apcli0", IFNAMSIZ - 1); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); strcpy(ipadd, inet_ntoa(((struct sockaddr_in *) &ifr.ifr_addr)->sin_addr)); if (inet_aton(ipadd, &addrKA) == 0) { fprintf(stderr, "Invalid address\\n"); addrKA.s_addr = 0; } if (strcmp(ipadd, "0.0.0.0") == 0) return 0; else return 1; }
1
#include <pthread.h> int mediafirefs_truncate(const char *path, off_t length) { printf("FUNCTION: truncate. path: %s, length: %zd\\n", path, (size_t)length); int retval; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); if (length != 0) { fprintf(stderr, "Truncate is not defined for length other than 0\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -EINVAL; } retval = folder_tree_truncate_file(ctx->tree, ctx->conn, path); if (retval == -1) { pthread_mutex_unlock(&(ctx->mutex)); return -ENOENT; } pthread_mutex_unlock(&(ctx->mutex)); return 0; }
0
#include <pthread.h> static int count = 0; pthread_mutex_t lock; int M; int *up; int *down; int left; int right; } scalar_ctx_t; void initialization(int *up, int N, int a, int b) { srand(time(0)); for(int i = 0; i < N; i++) { up[i] = rand() % (b - a + 1) + a; } } int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } void* merge_sort(void *context) { scalar_ctx_t *ctx = context; int width = ctx->right - ctx->left + 1; if (width <= ctx->M) { qsort(ctx->up + ctx->left, width, sizeof(int), cmp); return ctx->up; } int middle = (int)((ctx->left + ctx->right) * 0.5); int *l_buff; int *r_buff; scalar_ctx_t left_ctx = { .up = ctx->up, .down = ctx->down, .left = ctx->left, .right = middle, .M = ctx->M, }; scalar_ctx_t right_ctx = { .up = ctx->up, .down = ctx->down, .left = middle + 1, .right = ctx->right, .M = ctx->M, }; int child_created = 0; pthread_t child; void *returnValue; pthread_mutex_lock(&lock); if(count - 1 > 0) { count--; child_created = 1; } pthread_mutex_unlock(&lock); if(child_created == 1) { pthread_create(&child, 0, merge_sort, &left_ctx); } else l_buff = (int*)merge_sort(&left_ctx); r_buff = (int*)merge_sort(&right_ctx); if(child_created == 1) { pthread_join(child, &returnValue); pthread_mutex_lock(&lock); count++; pthread_mutex_unlock(&lock); l_buff = (int*)returnValue; } int *target = l_buff == ctx->up ? ctx->down : ctx->up; int l_cur = ctx->left, r_cur = middle + 1; for (int i = ctx->left; i <= ctx->right; i++){ if (l_cur <= middle && r_cur <= ctx->right) { if (l_buff[l_cur] < r_buff[r_cur]){ target[i] = l_buff[l_cur]; l_cur++; } else { target[i] = r_buff[r_cur]; r_cur++; } } else if (l_cur <= middle) { target[i] = l_buff[l_cur]; l_cur++; } else { target[i] = r_buff[r_cur]; r_cur++; } } return target; } int main(int argc, char** argv) { int N = atoi(argv[1]); int M = atoi(argv[2]); int P = atoi(argv[3]); int *up = (int*)malloc(sizeof(int) * N); int *test = (int*)malloc(sizeof(int) * N); initialization(up, N, 0, 200); pthread_mutex_init(&lock, 0); count = P; FILE *data = fopen("data.txt", "w"); for (int i = 0; i < N; i++) { fprintf(data, "%d ", up[i]); test[i] = up[i]; } qsort(test, N, sizeof(int), cmp); struct timeval start, end; int *down = (int*)malloc(sizeof(int) * N); scalar_ctx_t ctx = { .up = up, .down = down, .left = 0, .right = N - 1, .M = M, }; assert(gettimeofday(&start, 0) == 0); int *res = (int*)merge_sort(&ctx); assert(gettimeofday(&end, 0) == 0); double delta = ((end.tv_sec - start.tv_sec) * 1000000u + end.tv_usec - start.tv_usec) / 1.e6; FILE *stats = fopen("stats.txt", "w"); fprintf(stats, "%.5fs %d %d %d\\n", delta, N, M, P); fclose(stats); fprintf(data, "\\n"); for (int i = 0; i < N; i++) { fprintf(data, "%d ", res[i]); } pthread_mutex_destroy(&lock); fclose(data); for (int i = 0; i < N; ++i) { if (test[i] != res[i]) { printf("error: %d \\n", i); } } printf("end\\n"); free(up); free(down); free(test); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); if (top>0) { if ((pop(arr)==(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; int p1_msg; int p2_msg; sem_t p1_has_product; sem_t p2_has_product; sem_t p1_is_empty; sem_t p2_is_empty; int cmp(int a, int b) { if (a == b) return 0; if (a - b == 1 || a - b == -2) return 1; return -1; } int judge(int father, int child) { static int fwins = 0; static int cwins = 0; fprintf(stderr, "father: %d vs child: %d\\n", father, child); if (cmp(father, child) > 0) fwins++; else if (cmp(father, child) < 0) cwins++; fprintf(stderr, "\\t\\t\\t(%d vs %d)\\n", fwins, cwins); if (fwins < 2 && cwins < 2) return 0; if (fwins == 2) fprintf(stderr, "father wins!\\n"); if (cwins == 2) fprintf(stderr, "child wins!\\n"); return 1; } void * c(void *arg) { int counter = 0; while (1) { counter++; sem_wait(&p1_has_product); sem_wait(&p2_has_product); pthread_mutex_lock(&mylock); printf("%s: %d -> %d vs %d\\n", (char *)arg, counter, p1_msg, p2_msg); pthread_mutex_unlock(&mylock); if (judge(p1_msg, p2_msg)) exit(0); sem_post(&p1_is_empty); sem_post(&p2_is_empty); } } void * p2(void *arg) { int counter = 0; while (1) { counter++; sem_wait(&p1_is_empty); pthread_mutex_lock(&mylock); p2_msg = rand() % 3; printf("%s: counter %d -> msg %d\\n", (char *)arg, counter, p2_msg); pthread_mutex_unlock(&mylock); sem_post(&p2_has_product); } return 0; } void * p1(void *arg) { int counter = 0; while (1) { counter++; sem_wait(&p2_is_empty); pthread_mutex_lock(&mylock); p1_msg = rand() % 3; printf("%s: counter %d -> msg %d\\n", (char *)arg, counter, p1_msg); pthread_mutex_unlock(&mylock); sem_post(&p1_has_product); } return 0; } pthread_t pthid1; pthread_t pthid2; pthread_t pthid3; int main(void) { srand(time(0)); sem_init(&p1_has_product, 0, 0); sem_init(&p2_has_product, 0, 0); sem_init(&p1_is_empty, 0, 1); sem_init(&p2_is_empty, 0, 1); pthread_create(&pthid1, 0, p1, "produce1"); pthread_create(&pthid2, 0, p2, "produce2"); pthread_create(&pthid3, 0, c, "consume"); pthread_join(pthid1, 0); pthread_join(pthid2, 0); pthread_join(pthid3, 0); 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...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void * thr_fn(void *arg) { printf("thread started ...\\n"); pause(); return(0); } int main(void) { int err; pid_t pid; pthread_t tid; if ((err = pthread_atfork(prepare, parent, child)) != 0) { err_exit(err, "can't install fork handlers"); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { err_exit(err, "can't create thread"); } sleep(2); printf("parent about to fork...\\n"); if ((pid = fork()) < 0) { err_quit("fork failed"); } else if (pid == 0) { printf("child returned form fork\\n"); } else { printf("parent returned from fork\\n"); } exit(0); }
0
#include <pthread.h> int thread_count; int n; double* A; double min,max; pthread_mutex_t mutex; void Usage(char* prog_name); void Gen_array(double A[], int n); void *Find_MinMax(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; if (argc != 3) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); n = strtol(argv[2], 0, 10); thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); A = malloc(n*sizeof(double)); srandom(1); Gen_array(A,n); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Find_MinMax, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); printf("Min: %f, Max: %f\\n", min, max); free(A); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void Usage (char* prog_name) { fprintf(stderr, "Usage: %s <Thread_Count> <Array_Size>\\n", prog_name); exit(0); } void Gen_array(double A[], int n) { int i; for (i = 0; i < n; i++) A[i] = random()/((double) 32767); } void* Find_MinMax(void* rank) { int i; min = A[0]; max = A[0]; for (i = 0; i < n; i++) { if (A[i] < min) { pthread_mutex_lock(&mutex); min = A[i]; pthread_mutex_unlock(&mutex); } if (A[i] > max) { pthread_mutex_lock(&mutex); max = A[i]; pthread_mutex_unlock(&mutex); } } return 0; }
1
#include <pthread.h> int somma_voti; int votanti; } Film; struct Film arrayFilm[10]; int arrayUtenti[6]; sem_t semUtenti[10]; int listaUtenti[10]; sem_t barriera; sem_t download; sem_t evento; pthread_mutex_t mutex_threads[10]; int completati=0, bestfilm, userdownloading=0; float votomediofilm = 0, bestvoto =0; void *ThreadCode(void *t) { long tid; long result = 1; int i; int voto; tid = (int)t; arrayUtenti[tid]=0; for (i = 0; i < 10; i++) { pthread_mutex_lock(&mutex_threads[i]); voto = rand() % 10 + 1; arrayFilm[i].somma_voti += voto; arrayUtenti[tid] += voto; arrayFilm[i].votanti++; completati++; printf("Utente %ld. Film %d - Voto %d\\n", tid, i, voto); pthread_mutex_unlock(&mutex_threads[i]); } arrayUtenti[tid] = arrayUtenti[tid]/10; if(completati == 10*6){ sem_post(&evento); } sem_wait(&barriera); sem_post(&barriera); if(userdownloading >= 3){ listaUtenti[arrayUtenti[tid]]++; sem_wait(&semUtenti[arrayUtenti[tid]]); } userdownloading++; printf("Utente %ld. Inizio download\\n", tid); sleep(rand() % 5 + 5); printf("Utente %ld. Termina download\\n", tid); userdownloading--; if(userdownloading < 3){ for(i=9;i>0;i--){ if(listaUtenti[i]!=0){ listaUtenti[i]--; sem_post(&semUtenti[i]); break; } } } printf("Utente %ld: guarda film %d\\n", tid, bestfilm); sleep(rand() % 5 + 5); printf("Utente %ld: finisce di guardare film %d\\n", tid, bestfilm); pthread_exit((void*) result); } int main (int argc, char *argv[]) { int i, rc, votomedioutente; long t; long result; float voto; pthread_t threads[6]; sem_init (&barriera, 0, 0); sem_init (&evento, 0, 0); for (i = 0; i < 6; i++) { sem_init (&semUtenti[i], 0, 0); listaUtenti[i]=0; } srand(time(0)); for (i = 0; i < 10; i++) { pthread_mutex_init(&mutex_threads[i], 0); arrayFilm[i] = (Film){.somma_voti = 0, .votanti = 0}; } for (t = 0; t < 6; t++) { printf("Main: Intervistato %ld.\\n", t); rc = pthread_create(&threads[t], 0, ThreadCode, (void*)t); if (rc) { printf ("ERRORE: %d\\n", rc); exit(-1); } } sem_wait(&evento); printf("\\n\\nMain: Risultati finali.\\n"); for (i = 0; i < 10; i++) { votomediofilm = arrayFilm[i].somma_voti/((double)arrayFilm[i].votanti); printf("Film %d: %f\\n", i, votomediofilm); if(votomediofilm> bestvoto) { bestvoto = votomediofilm; bestfilm=i; } } for (i = 0; i < 6; i++) { printf("Utente %d: priorita: %d\\n", i, arrayUtenti[i]); } printf("\\nMiglior film %d con voto %f\\n\\n",bestfilm,bestvoto); sem_post(&barriera); for (t = 0; t < 6; t++) { rc = pthread_join(threads[t], (void *)&result); if (rc) { printf ("ERRORE: join thread %ld codice %d.\\n", t, rc); } else { printf("Main: Finito Utente %ld.\\n", t); } } printf("Main: Termino...\\n\\n"); }
0
#include <pthread.h> int counter = 0; pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t threshold_condv = PTHREAD_COND_INITIALIZER; void *inc_counter(void *thread_id) { long th_id = (long) thread_id; for (int ii = 0; ii < 10; ii++) { pthread_mutex_lock(&counter_mutex); counter++; fprintf(stderr, "Counter thread %ld, count = %d\\n", th_id, counter); if (counter == 12) { pthread_cond_signal(&threshold_condv); fprintf(stderr, "Counter thread %ld, threshold reached\\n", th_id); } pthread_mutex_unlock(&counter_mutex); sleep(1); } return 0; } void *watch_counter(void *arg ) { fprintf(stderr, "Starting watcher thread\\n"); pthread_mutex_lock(&counter_mutex); if (counter < 12) { pthread_cond_wait(&threshold_condv, &counter_mutex); fprintf(stderr, "Watcher thread, condition signal received\\n"); counter += 125; fprintf(stderr, "Watcher thread, count now = %d.\\n", counter); } pthread_mutex_unlock(&counter_mutex); return 0; } int main(void) { pthread_t thread_ids[3]; if (pthread_create(&thread_ids[0], 0, &watch_counter, 0) != 0) { perror("pthread_create 0"); exit(1); } if (pthread_create(&thread_ids[1], 0, &inc_counter, (long *) 1) != 0) { perror("pthread_create 1"); exit(1); } if (pthread_create(&thread_ids[2], 0, &inc_counter, (long *) 2) != 0) { perror("pthread_create 2"); exit(1); } for (int ii = 0; ii < 3; ii ++) { if (pthread_join(thread_ids[ii], 0) != 0) { perror("pthread_join"); exit(1); } } exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; double sum; void *runner(void *param); int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr,"usage: <int : sumsqrt N > <int : thread count> \\n"); return (-1); } if (atoi(argv[1]) < 0) { fprintf(stderr,"%d must be >= 0 \\n",atoi(argv[1])); return (-1); } int tcount = atoi(argv[2]); int argument = atoi(argv[1])+1; int div = argument / tcount; pthread_t tids[tcount]; sum = 0.0; int i; int start = 0; int end = 0; for (i = 0; i<tcount; i++) { start = end; end += div; if (i == (tcount-1)) { end = argument; } int * data = (int*) malloc(2*sizeof(int)); data[0] = start; data[1] = end; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tids[i],&attr,runner,data); } for (i = 0; i<tcount; i++) { pthread_join(tids[i],0); } printf("sum = %G \\n",sum); } void *runner(void *param) { int start = ((int *)param)[0]; int end = ((int *)param)[1]; double tmpSum = 0; for ( ; start < end; start++) tmpSum += sqrt( ((double)start) ); pthread_mutex_lock(&mutex); sum += tmpSum; pthread_mutex_unlock(&mutex); free(param); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t glock1; pthread_mutex_t glock2; int A; int B; int B1; int X; void* thread_a(void *args) { pthread_mutex_lock(&glock1); printf("a locked glock 1\\n"); X = 0; sleep(1); pthread_mutex_lock(&glock2); printf("a locked glock 2\\n"); sleep(1); A = 2; printf("a unlocked glock 2\\n"); pthread_mutex_unlock(&glock2); X = 2; sleep(1); printf("a unlocked glock 1\\n"); pthread_mutex_unlock(&glock1); return 0; } void* thread_b(void *args) { pthread_mutex_lock(&glock2); printf("b locked glock 2\\n"); B = A; B1 = X; printf("A=%d, B1=%d\\n", A, B1); printf("b unlocked glock 2\\n"); pthread_mutex_unlock(&glock2); return 0; } int main(void) { pthread_t tid1, tid2; A = 0; B = 0; pthread_mutex_init(&glock1, 0); pthread_mutex_init(&glock2, 0); pthread_create(&tid1, 0, thread_a, 0); pthread_create(&tid2, 0, thread_b, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t cargMutex[5]; pthread_cond_t cargCv[5]; int cargas[5]; double ventas[5][31]; double totalsucursal[5]; double totalgeneral = 0; void *cargoVentas(void *p) { int tId = (int) p; int dia = 0; printf("Start cargoVentas[%d]\\n",tId); for(dia = 0 ; dia < 31 ; dia++ ){ ventas[tId][dia] = getRand(100); } printf("Listo cargoVentas[%d]\\n",tId); cargas[tId] = 1; pthread_cond_signal(&cargCv[tId]); printf("End cargoVentas[%d]\\n\\n",tId); pthread_exit(0); } void *sumoVentas(void *sucursalid) { int sucid = (int) sucursalid; printf("Start sumoVentas[%d]\\n", sucid); int dia = 0; totalsucursal[sucid] = 0; printf("Lock sumoVentas[%d]\\n", sucid); pthread_mutex_lock(&cargMutex[sucid]); if(!cargas[sucid]) pthread_cond_wait(&cargCv[sucid] , &cargMutex[sucid]); printf("Unlock sumoVentas[%d]\\n", sucid); for(dia = 0 ; dia < 31 ; dia++){ printf("sumando s: %d [%d]\\n",sucid,dia ); totalsucursal[sucid] += ventas[sucid][dia]; } totalgeneral += totalsucursal[sucid]; pthread_mutex_unlock(&cargMutex[sucid]); printf("End sumoVentas[%d] \\n\\n",sucid); pthread_exit(0); } int main(int argc, char const *argv[]){ int cantThr = 5; pthread_t arrThr[cantThr]; pthread_t arrThrSum[cantThr]; int a; for (a=0; a < 5 ;a++){ cargas[a] = 0; } printf("Creacion de hilos\\n"); int i = 0; while(i < cantThr){ printf("main(): Create cargoVentas[%d]\\n", i ); pthread_create(&arrThr[i], 0, cargoVentas, (void *) i ); printf("main(): Create sumoVentas[%d]\\n", i ); pthread_create(&arrThrSum[i], 0, sumoVentas, (void *) i ); i++; } for( i = 0 ; i < cantThr ; i++ ){ pthread_join(arrThr[i],0); pthread_join(arrThrSum[i],0); printf("Vinculo cargoVentas[%d] y sumoVentas[%d] con main.\\n",i,i ); } printf("\\nMuestro Resultados......\\n\\n"); for (i=0; i < 5; i++){ printf("Sucursal N°[%d] Sumatoria ($): %f\\n",i,totalsucursal[i]); } printf("Total General: $ %f \\n",totalgeneral); printf("main(): FIN \\n"); pthread_exit(0); }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; while(1) { err = sigwait(&mask, &signo); if(err != 0) { err_exit(err, "sigwait failed"); } switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return 0; default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main() { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while(quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); return 0; }
1
#include <pthread.h> pthread_mutex_t mutx_k; pthread_mutex_t mutx_p; pthread_mutex_t mutx_i; pthread_cond_t cond_k = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_p = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_i = PTHREAD_COND_INITIALIZER; int kosiky = 3; int pokladne = 2; int i; void *zakaznik(void *); void rndsleep(int maxdelay); int main(void) { pthread_t zak[6]; pthread_mutex_init(&mutx_k,0); pthread_mutex_init(&mutx_p,0); pthread_mutex_init(&mutx_i,0); for (i=0; i< 6; i++) { rndsleep(2000); pthread_mutex_lock(&mutx_i); if (pthread_create(&(zak[i]),0,zakaznik,0)) { pthread_mutex_unlock(&mutx_i); printf("Chyba pri tvorbe vlakna %d. zakaznika",i+1); break; } pthread_cond_wait(&cond_i, &mutx_i); pthread_mutex_unlock(&mutx_i); } for (i--; i>=0; i--) pthread_join(zak[i],0); i = 0; if (pthread_mutex_destroy(&mutx_i)) { puts("mutx_i destroy error"); i=1; } if (pthread_mutex_destroy(&mutx_k)) { puts("mutx_k destroy error"); i=1; } if (pthread_mutex_destroy(&mutx_p)) { puts("mutx_p destroy error"); i=1; } return(i); } void *zakaznik(void *param) { int poradie; pthread_mutex_lock(&mutx_i); poradie = i+1; pthread_cond_signal(&cond_i); pthread_mutex_unlock(&mutx_i); printf("z%d caka kosik\\n",poradie); pthread_mutex_lock(&mutx_k); while (kosiky == 0) pthread_cond_wait(&cond_k, &mutx_k); kosiky--; pthread_mutex_unlock(&mutx_k); printf("\\tz%d dostal kosik\\n",poradie); rndsleep(5000); printf("\\t\\tz%d caka pokl.\\n",poradie); pthread_mutex_lock(&mutx_p); while (pokladne == 0) pthread_cond_wait(&cond_p, &mutx_p); pokladne--; pthread_mutex_unlock(&mutx_p); printf("\\t\\t\\tz%d dostal pokl.\\n",poradie); rndsleep(3000); pthread_mutex_lock(&mutx_p); pokladne++; pthread_cond_signal(&cond_p); pthread_mutex_unlock(&mutx_p); pthread_mutex_lock(&mutx_k); kosiky++; pthread_cond_signal(&cond_k); pthread_mutex_unlock(&mutx_k); printf("\\t\\t\\t\\tz%d odisiel\\n",poradie); } void rndsleep(int maxdelay) { struct timespec delay; long rnd_time; rnd_time = 1 + (int) ((float)maxdelay*rand()/(32767 +1.0)); delay.tv_nsec = 1000000 * (rnd_time % 1000); delay.tv_sec = (int)(rnd_time/1000); nanosleep(&delay,0); }
0
#include <pthread.h> void codec_queue_init(struct codec_t* codec) { codec->queue_head = 0; codec->queue_tail = 0; codec->queue_count = 0; codec->is_running = 1; codec->PTS = -1; pthread_mutex_init(&codec->queue_mutex,0); pthread_cond_init(&codec->queue_count_cv,0); pthread_cond_init(&codec->resume_cv,0); pthread_mutex_init(&codec->PTS_mutex,0); pthread_mutex_init(&codec->isrunning_mutex,0); } int codec_is_running(struct codec_t* codec) { int res; pthread_mutex_lock(&codec->isrunning_mutex); res = codec->is_running; pthread_mutex_unlock(&codec->isrunning_mutex); return res; } void codec_flush_queue(struct codec_t* codec) { pthread_mutex_lock(&codec->queue_mutex); struct codec_queue_t* p = codec->queue_head; while (p) { struct codec_queue_t* tmp = p; p = p->next; codec_queue_free_item(codec,tmp); } codec->queue_count = 0; codec->queue_head = 0; codec->queue_tail = 0; pthread_mutex_unlock(&codec->queue_mutex); } void codec_stop(struct codec_t* codec) { struct codec_queue_t* new = malloc(sizeof(struct codec_queue_t)); if (new == 0) { fprintf(stderr,"FATAL ERROR: out of memory adding to queue\\n"); exit(1); } pthread_mutex_lock(&codec->queue_mutex); pthread_mutex_lock(&codec->isrunning_mutex); codec->is_running = 0; pthread_mutex_unlock(&codec->isrunning_mutex); struct codec_queue_t* p = codec->queue_head; while (p) { struct codec_queue_t* tmp = p; p = p->next; codec_queue_free_item(codec,tmp); } new->msgtype = MSG_STOP; new->data = 0; new->next = 0; new->prev = 0; codec->queue_head = new; codec->queue_tail = new; if (codec->queue_count == 0) { pthread_cond_signal(&codec->queue_count_cv); } codec->queue_count=1; codec_set_pts(codec,-1); pthread_mutex_unlock(&codec->queue_mutex); } void codec_pause(struct codec_t* codec) { struct codec_queue_t* new = malloc(sizeof(struct codec_queue_t)); if (new == 0) { fprintf(stderr,"FATAL ERROR: out of memory adding to queue\\n"); exit(1); } new->msgtype = MSG_PAUSE; new->data = 0; pthread_mutex_lock(&codec->queue_mutex); if (codec->queue_tail == 0) { new->next = 0; new->prev = 0; codec->queue_head = new; codec->queue_tail = new; pthread_cond_signal(&codec->queue_count_cv); } else { new->next = 0; new->prev = codec->queue_tail; new->prev->next = new; codec->queue_tail = new; } codec->queue_count++; pthread_mutex_unlock(&codec->queue_mutex); } void codec_resume(struct codec_t* codec) { pthread_cond_signal(&codec->resume_cv); } void codec_queue_add_item(struct codec_t* codec, struct packet_t* packet) { if (packet == 0) { fprintf(stderr,"ERROR: Adding NULL packet to queue, skipping\\n"); return; } struct codec_queue_t* new = malloc(sizeof(struct codec_queue_t)); if (new == 0) { fprintf(stderr,"FATAL ERROR: out of memory adding to queue\\n"); exit(1); } new->msgtype = MSG_PACKET; new->data = packet; pthread_mutex_lock(&codec->queue_mutex); if (codec->is_running) { if (codec->queue_head == 0) { new->next = 0; new->prev = 0; codec->queue_head = new; codec->queue_tail = new; pthread_cond_signal(&codec->queue_count_cv); } else { new->next = codec->queue_head; new->prev = 0; new->next->prev = new; codec->queue_head = new; } codec->queue_count++; } else { DEBUGF("Dropping packet - codec is stopped.\\n"); free(packet); } pthread_mutex_unlock(&codec->queue_mutex); } void codec_queue_free_item(struct codec_t* codec,struct codec_queue_t* item) { if (item == 0) return; if (item->data) { free(item->data->buf); free(item->data); } free(item); } struct codec_queue_t* codec_queue_get_next_item(struct codec_t* codec) { struct codec_queue_t* item; pthread_mutex_lock(&codec->queue_mutex); if (codec->queue_tail == 0) { pthread_cond_wait(&codec->queue_count_cv,&codec->queue_mutex); } item = codec->queue_tail; codec->queue_tail = codec->queue_tail->prev; if (codec->queue_tail == 0) { codec->queue_head = 0; } else { codec->queue_tail->next = 0; } codec->queue_count--; pthread_mutex_unlock(&codec->queue_mutex); return item; } void codec_set_pts(struct codec_t* codec, int64_t PTS) { pthread_mutex_lock(&codec->PTS_mutex); codec->PTS = PTS; pthread_mutex_unlock(&codec->PTS_mutex); } int64_t codec_get_pts(struct codec_t* codec) { int64_t PTS; pthread_mutex_lock(&codec->PTS_mutex); PTS = codec->PTS; pthread_mutex_unlock(&codec->PTS_mutex); return PTS; }
1
#include <pthread.h> char slots[3][22]; const int LUT[3][3] = { { 1, 2 , 1}, { 2, 0 , 0}, { 1, 0 , 1}}; int w= 0; int r= 1; int l= 2; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void reader_thread () { while(1) { pthread_mutex_lock(&mutex); if(l != r){ r = l; pthread_mutex_unlock(&mutex); printf ("%s", slots[r]); fflush(stdout); usleep(450000); } else { pthread_mutex_unlock(&mutex); } } } char input() { char c = getchar(); if(c==EOF) exit(0); return c; } int main () { pthread_t readerTh; pthread_create(&readerTh, 0, (void*) &reader_thread, 0); while (1) { int j = 0; while ((slots[w][j++] = input()) != '*'); slots[w][j] = 0; pthread_mutex_lock(&mutex); l = w; w = LUT[r][l]; pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int x = 0; void *thread1(void *arg){ while(1){ printf("thread1 will change ans!\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); x += 1; pthread_mutex_unlock(&mutex); sleep(4); } } void *thread2(void *arg){ while(1){ printf("thread2 will change ans!\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); x += 1; pthread_mutex_unlock(&mutex); sleep(4); } } void *thread3(void *arg){ while(1){ printf("thread3 will change ans!\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); x += 1; pthread_mutex_unlock(&mutex); sleep(4); } } int main(void){ pthread_t tid1, tid2, tid3; 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); pthread_create(&tid3, 0, (void*)thread3, 0); do{ pthread_cond_signal(&cond); printf("%d\\n", x); sleep(1); }while(1); pthread_exit(0); }
1
#include <pthread.h> sem_t ready_to_ask; pthread_mutex_t mymutex, reporter_count; pthread_cond_t cond, capacity_cond; int question_asked; int reporter_id, capacity, reporters_in, number_of_reporters; void EnterConferenceRoom(int reporter_id){ pthread_mutex_lock(&mymutex); while (reporters_in >= capacity){ pthread_cond_wait(&capacity_cond, &mymutex); } reporters_in++; number_of_reporters--; printf("Reporter %d enters the conference room\\n", reporter_id); pthread_mutex_unlock(&mymutex); } void QuestionStart(){ printf("Reporter %d asks a question\\n", reporter_id); } void QuestionDone(){ printf("Reporter %d is satisfied\\n", reporter_id); } void LeaveConferenceRoom(int reporter_id){ pthread_mutex_lock(&mymutex); reporters_in--; printf("Reporter %d leaves the conference room\\n", reporter_id); pthread_cond_signal(&capacity_cond); pthread_mutex_unlock(&mymutex); } void AnswerStart(){ printf("Speaker starts to answer question for reporter %d\\n", reporter_id); } void AnswerDone(){ printf("Speaker is done with answer for reporter %d\\n", reporter_id); } void *Speaker (){ while (reporters_in > 0){ pthread_mutex_lock(&mymutex); while (question_asked == 0){ pthread_cond_wait(&cond,&mymutex); } AnswerStart(); AnswerDone(); question_asked = 0; pthread_mutex_unlock(&mymutex); usleep(10); } pthread_exit(0); } void *Reporter (void *id){ EnterConferenceRoom((int)id); usleep(rand()%10); int questions_to_ask; questions_to_ask = ((int)id % 4) + 2; while (questions_to_ask){ sem_wait(&ready_to_ask); if (question_asked == 0){ reporter_id = (int)id; pthread_mutex_lock(&mymutex); question_asked = 1; QuestionStart(); pthread_cond_signal(&cond); pthread_mutex_unlock(&mymutex); usleep(rand()%10); QuestionDone(); questions_to_ask--; if (questions_to_ask == 0) LeaveConferenceRoom((int)id); } sem_post(&ready_to_ask); usleep(10); } pthread_exit(0); } int main (int argc, char *argv[]){ if (argc !=3){ printf("Not enough arguments\\n"); return -1; } if ( (atoi(argv[1]) == 0) || (atoi(argv[2]) == 0) ){ printf("Not a valid input\\n"); return -1; } number_of_reporters = atoi(argv[1]); capacity = atoi(argv[2]); int i; question_asked = 0; reporters_in = 0; pthread_mutex_init(&mymutex, 0); pthread_mutex_init(&reporter_count, 0); pthread_cond_init(&cond, 0); pthread_cond_init(&capacity_cond, 0); pthread_t threads[number_of_reporters+1]; if (sem_init(&ready_to_ask, 0, 1)){ printf("Could not initialize a semaphore\\n"); return -1; } if (pthread_create(&threads[0], 0, &Speaker, 0)){ printf("Could not create speaker thread\\n"); return -1; } for (i = 0; i < number_of_reporters; i++){ if (pthread_create(&threads[i+1], 0, &Reporter, (void*)(i+1))){ printf("Could not create thread %d\\n", i+1); return -1; } printf("Thread %d created\\n", i+1); } for (i = 0; i < number_of_reporters+1; i++){ if (pthread_join(threads[i], 0)){ printf("Could not join thread %d\\n", i); return -1; } } sem_destroy(&ready_to_ask); pthread_mutex_destroy(&mymutex); pthread_mutex_destroy(&reporter_count); pthread_cond_destroy(&cond); pthread_cond_destroy(&capacity_cond); pthread_exit(0); }
0
#include <pthread.h> int *all_buffers; int num_producers; int num_consumers; int num_buffers; int num_items; int num_producer_iterations; int actual_num_produced; pthread_mutex_t should_continue_producing_lock; pthread_mutex_t buffer_printer_lock; sem_t *total_empty; sem_t *total_full; sem_t *buffer_lock; bool shouldContinueProducing() { if (num_producer_iterations <= num_items) { num_producer_iterations++; return 1; } else { return 0; } } void bufferPrinter(int thread_number) { if (actual_num_produced % 1000 == 0 && actual_num_produced != 0) { printf("%d items created\\n", actual_num_produced); int i; sem_wait(buffer_lock); for (i = 0; i < num_buffers; i++) { printf("Shared buffer %d has %d number of items\\n", i + 1, all_buffers[i]); } sem_post(buffer_lock); } actual_num_produced++; return; } void *producer(void *t_number) { int thread_number = *((int *) t_number); while (1) { pthread_mutex_lock(&should_continue_producing_lock); bool shouldContinue = shouldContinueProducing(); pthread_mutex_unlock(&should_continue_producing_lock); if (shouldContinue == 0) { break; } sem_wait(total_empty); sem_wait(buffer_lock); int i; for (i = 0; i < num_buffers; i++) { if (all_buffers[i] < 1024) { all_buffers[i]++; break; } } sem_post(buffer_lock); sem_post(total_full); pthread_mutex_lock(&buffer_printer_lock); bufferPrinter(thread_number); pthread_mutex_unlock(&buffer_printer_lock); } } void main(int argc, char *argv[]) { if (argc != 5) { printf("Wrong number of arguments...Exiting\\n"); return; } num_producers = atoi(argv[1]); num_consumers = atoi(argv[2]); num_buffers = atoi(argv[3]); num_items = atoi(argv[4]); num_producer_iterations = 0; actual_num_produced = 0; key_t memory_key = ftok(".", 1337); int segment_id; int *shared_memory; int shared_segment_size = num_buffers * sizeof(int); segment_id = shmget(memory_key, shared_segment_size, 0666); if (segment_id < 0) { printf("Producer had error with shmget!"); exit(1); } shared_memory = (int *) shmat(segment_id, 0, 0); all_buffers = shared_memory; total_full = sem_open("/TeamDropTablesFullSemaphore", 0); total_empty = sem_open("/TeamDropTablesEmptySemaphore", 0); buffer_lock = sem_open("/TeamDropTablesBufferSemaphore", 0); pthread_mutex_init(&should_continue_producing_lock, 0); pthread_mutex_init(&buffer_printer_lock, 0); printf("Num producers: %d, Num Conusumers: %d," " Num Buffers: %d, Num Items: %d\\n", num_producers, num_consumers, num_buffers, num_items); pthread_t *producer_threads = (pthread_t *) malloc(num_producers * sizeof(pthread_t)); int *producer_counters = (int *) malloc(num_producers * sizeof(int)); int counter; for (counter = 0; counter < num_producers; ++counter) { producer_counters[counter] = counter; } for (counter = 0; counter < num_producers; ++counter) { printf("Creating producer thread %d\\n", counter); pthread_create(&producer_threads[counter], 0, producer, (void *) &producer_counters[counter]); } for (counter = 0; counter < num_producers; ++counter) { pthread_join(producer_threads[counter], 0); } }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione = PTHREAD_COND_INITIALIZER; int **matrice; int minimo=1000; int n=0; int *array=0; int numT=0; int i =0; void stampa (int **m,int r){ for (int i=0;i<r;i++){ for (int j=0;j<r;j++){ printf("%d\\t",m[i][j]); } printf("\\n"); } } void *determina(void *param){ int indice =*(int*)param; pthread_mutex_lock(&mutex); for (int i=0;i<n;i++){ array[i]+=matrice[indice][i]; numT--; } pthread_mutex_unlock(&mutex); if (numT<=0){ pthread_mutex_lock(&mutex); pthread_cond_signal(&condizione); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *minimoFunzione(void *param){ pthread_mutex_lock(&mutex); while (numT>0){ pthread_cond_wait(&condizione,&mutex); } pthread_mutex_unlock(&mutex); for (int i =0;i<n;i++){ printf("%d\\n",array[i]); } printf("\\nil minimo e'"); for (int i=0;i<n;i++){ if(array[i]<minimo){ minimo=array[i]; } } printf("%d\\n",minimo); pthread_exit(0); } int main(int argc,char *argv[]){ n=atoi(argv[1]); numT=n; array = malloc(n*sizeof(int)); for(int i=0;i<n;i++){ array[i]=0; } matrice=(int**)malloc(sizeof(int*)*n); for(int i=0;i<n;i++){ matrice[i]=(int*)malloc(sizeof(int)*n); for(int j=0;j<n;j++){ matrice[i][j]=1+rand()%10; } } stampa(matrice,n); printf("\\n"); pthread_t thread[n]; for (int i=0;i<n;i++){ int *indice = malloc(sizeof(int)); *indice=i; pthread_create(&thread[i],0,determina,indice); } pthread_create(&thread[n],0,minimoFunzione,0); for(int i=0;i<=n;i++){ pthread_join(thread[i],0); } return 0; }
0
#include <pthread.h> const char rtems_test_name[] = "PSXCLEANUP"; pthread_t ThreadIds[2]; pthread_mutex_t lock; pthread_cond_t rcond; pthread_cond_t wcond; int lock_count; int waiting_writers; } lock_t; volatile bool reader_cleanup_ran; volatile bool release_read_lock_ran; volatile bool writer_cleanup_ran; void waiting_reader_cleanup(void *arg); void lock_for_read(void *arg); void release_read_lock(void *arg); void waiting_writer_cleanup(void *arg); void lock_for_write(lock_t *l); void release_write_lock(void *arg); void initialize_lock_t(lock_t *l); void *ReaderThread(void *arg); void *WriterThread(void *arg); void waiting_reader_cleanup(void *arg) { lock_t *l; reader_cleanup_ran = TRUE; l = (lock_t *) arg; pthread_mutex_unlock(&l->lock); } void lock_for_read(void *arg) { lock_t *l = arg; pthread_mutex_lock(&l->lock); pthread_cleanup_push(waiting_reader_cleanup, l); while ((l->lock_count < 0) && (l->waiting_writers != 0)) pthread_cond_wait(&l->rcond, &l->lock); l->lock_count++; reader_cleanup_ran = FALSE; pthread_cleanup_pop(1); if ( reader_cleanup_ran == FALSE ) { puts( "reader cleanup did not run" ); rtems_test_exit(0); } } void release_read_lock(void *arg) { lock_t *l = arg; release_read_lock_ran = TRUE; pthread_mutex_lock(&l->lock); if (--l->lock_count == 0) pthread_cond_signal(&l->wcond); pthread_mutex_unlock(&l->lock); } void waiting_writer_cleanup(void *arg) { lock_t *l = arg; writer_cleanup_ran = TRUE; if ((--l->waiting_writers == 0) && (l->lock_count >= 0)) { pthread_cond_broadcast(&l->wcond); } pthread_mutex_unlock(&l->lock); } void lock_for_write(lock_t *l) { pthread_mutex_lock(&l->lock); l->waiting_writers++; l->lock_count = -1; pthread_cleanup_push(waiting_writer_cleanup, l); while (l->lock_count != 0) pthread_cond_wait(&l->wcond, &l->lock); l->lock_count = -1; writer_cleanup_ran = FALSE; pthread_cleanup_pop(1); if ( writer_cleanup_ran == FALSE ) { puts( "writer cleanup did not run" ); rtems_test_exit(0); } } void release_write_lock(void *arg) { lock_t *l = arg; writer_cleanup_ran = TRUE; l->lock_count = 0; if (l->waiting_writers == 0) pthread_cond_broadcast(&l->rcond); else pthread_cond_signal(&l->wcond); } void initialize_lock_t(lock_t *l) { pthread_mutexattr_t mutexattr; pthread_condattr_t condattr; if (pthread_mutexattr_init (&mutexattr) != 0) { perror ("Error in mutex attribute init\\n"); } if (pthread_mutex_init (&l->lock,&mutexattr) != 0) { perror ("Error in mutex init"); } if (pthread_condattr_init (&condattr) != 0) { perror ("Error in condition attribute init\\n"); } if (pthread_cond_init (&l->wcond,&condattr) != 0) { perror ("Error in write condition init"); } if (pthread_cond_init (&l->rcond,&condattr) != 0) { perror ("Error in read condition init"); } l->lock_count = 0; l->waiting_writers = 0; } void *ReaderThread(void *arg) { lock_t *l = arg; puts("Lock for read"); lock_for_read(l); puts("cleanup push for read"); pthread_cleanup_push(release_read_lock, &l->lock); release_read_lock_ran = FALSE; puts("cleanup pop for read"); pthread_cleanup_pop(1); if ( release_read_lock_ran == FALSE ) { puts( "release read lock did not run" ); rtems_test_exit(0); } return 0; } void *WriterThread(void *arg) { lock_t *l = arg; puts("Lock for write"); lock_for_write(l); puts("cleanup push for write"); pthread_cleanup_push(release_write_lock, &l->lock); release_write_lock(&l->lock); puts("do nothing cleanup pop for write"); pthread_cleanup_pop(0); return 0; } void *POSIX_Init( void *argument ) { pthread_attr_t attr; int status; lock_t l; TEST_BEGIN(); initialize_lock_t(&l); if (pthread_attr_init(&attr) != 0) { perror ("Error in attribute init\\n"); } status = pthread_create(&ThreadIds[0], 0, ReaderThread, &l); posix_service_failed( status, "pthread_create Reader" ); sleep(1); status = pthread_create(&ThreadIds[1], 0, WriterThread, &l); posix_service_failed( status, "pthread_create Writer" ); sleep(1); TEST_END(); rtems_test_exit(0); }
1
#include <pthread.h> static pthread_mutex_t getnetby_mutex = PTHREAD_MUTEX_INITIALIZER; static int convert (struct netent *ret, struct netent *result, char *buf, int buflen) { int len, i; if (!buf) return -1; *result = *ret; result->n_name = (char *) buf; len = strlen (ret->n_name) + 1; if (len > buflen) return -1; buflen -= len; buf += len; strcpy (result->n_name, ret->n_name); for (len = sizeof (char *), i = 0; ret->n_aliases [i]; i++) { len += strlen (ret->n_aliases [i]) + 1 + sizeof (char *); } if (len > buflen) return -1; result->n_aliases = (char **) buf; buf += (i + 1) * sizeof (char *); for (i = 0; ret->n_aliases [i]; i++) { result->n_aliases [i] = (char *) buf; strcpy (result->n_aliases [i], ret->n_aliases [i]); buf += strlen (ret->n_aliases [i]) + 1; } result->n_aliases [i] = 0; return 0; } struct netent * getnetbyaddr_r (long net, int type, struct netent *result, char *buffer, int buflen) { struct netent *ret; pthread_mutex_lock (&getnetby_mutex); ret = getnetbyaddr (net, type); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getnetby_mutex); return result; } struct netent * getnetbyname_r (const char *name, struct netent *result, char *buffer, int buflen) { struct netent *ret; pthread_mutex_lock (&getnetby_mutex); ret = getnetbyname (name); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getnetby_mutex); return result; } struct netent * getnetent_r (struct netent *result, char *buffer, int buflen) { struct netent *ret; pthread_mutex_lock (&getnetby_mutex); ret = getnetent (); if (!ret || convert (ret, result, buffer, buflen) != 0) { result = 0; } pthread_mutex_unlock (&getnetby_mutex); return result; }
0
#include <pthread.h> struct prodcons { int buffer[3]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; pthread_cond_t wait_emergency; int size; }; void init(struct prodcons *b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); pthread_cond_init(&b->wait_emergency, 0); b->readpos = 0; b->writepos = 0; b->size=0; } void put(struct prodcons *b, int data) { pthread_mutex_lock(&b->lock); if(b->size==3) { pthread_cond_wait(&b->notfull, &b->lock); } b->buffer[b->writepos] = data; b->writepos++; if (b->writepos >= 3) b->writepos = 0; b->size++; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons *b) { int data; pthread_mutex_lock(&b->lock); if(b->size==0) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if (b->readpos >= 3) b->readpos = 0; b->size--; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void *producer(void *data) { int n; for (n = 0; n < 10; n++) { printf("%d --->\\n", n); put(&buffer, n); printf("%d\\n",buffer.size); } put(&buffer, ( - 1)); return 0; } void *producer_e(void *data) { int n; for (n = 0; n < 10; n++) { printf("e %d --->\\n", n); put(&buffer, n); printf("%d\\n",buffer.size); } put(&buffer, ( - 1)); return 0; } void *consumer(void *data) { int d; int i=0; while (1) { d = get(&buffer); if (d == ( - 1)){ i++; if(i==2) break; } printf("--->%d \\n", d); printf("%d\\n",buffer.size); } return 0; } int main(void) { pthread_t th_a, th_b,th_c; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_c, 0, producer_e, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); pthread_join(th_c, &retval); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int shutdown = 0; int flag = 0; struct people { char name[10]; char sex; struct people *next; }; struct people *head = 0; void *thread_pro(void *argv) { int i = 0; for (;;) { struct people hum; if (i%2 == 0) { strcpy(hum.name, "zhangsan"); hum.sex = 'M'; } else if (i%2 == 1) { strcpy(hum.name, "lisi"); hum.sex = 'F'; } i++; struct people *temp = malloc(sizeof(hum)); assert(temp != 0); temp->sex = hum.sex; strcpy(temp->name, hum.name); temp->next = 0; pthread_mutex_lock(&mutex); if (shutdown == 1) { pthread_mutex_unlock(&mutex); return 0; } if (head == 0) head = temp; else { temp->next = head; head = temp; } pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } } void *thread_cos(void *argv) { int id = (int)argv; for (;;) { pthread_mutex_lock(&mutex); while (head == 0 && shutdown == 0) pthread_cond_wait(&cond, &mutex); if (shutdown == 1) { pthread_mutex_unlock(&mutex); return 0; } struct people hum = *head; printf("thread[%lu] name = %s, sex = %c\\n", pthread_self(), hum.name, hum.sex); struct people *temp = head; head = head->next; free(temp); pthread_mutex_unlock(&mutex); } } int main() { pthread_t pro, cos1, cos2; int ret; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); ret = pthread_create(&pro, 0, thread_pro, 0); assert(ret == 0); ret = pthread_create(&cos1, 0, thread_cos, (void *)1); assert(ret == 0); ret = pthread_create(&cos2, 0, thread_cos, (void *)2); assert(ret == 0); for (int i = 0; i < 100; i++) usleep(50); shutdown = 1; pthread_join(pro, 0); pthread_cond_broadcast(&cond); pthread_join(cos1, 0); pthread_join(cos2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
0