text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; int i = 0; printf2 ("prod: trying\\n"); while (done == 0) { i++; pthread_mutex_lock (&mq); if (qsiz < 5) { printf2 ("prod: got it! x %d qsiz %d i %d\\n", x, qsiz, i); done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x, i = 0; printf2 ("consumer: trying\\n"); while (done == 0) { i++; pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[qsiz]; qsiz--; printf2 ("consumer: got it! x %d qsiz %d i %d\\n", x, qsiz, i); } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmax (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } swap (t, mx, count-1); return t[count-1]; } int source[7]; int sorted[7]; void producer () { int i, max; for (i = 0; i < 7; i++) { max = findmax (source, 7 - i); queue_insert (max); } } void consumer () { int i, max; for (i = 0; i < 7; i++) { max = queue_extract (); sorted[i] = max; } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; __libc_init_poet (); unsigned seed = (unsigned) time (0); int i; srand (seed); printf ("Using seed %u\\n", seed); for (i = 0; i < 7; i++) { source[i] = random() % 20; assert (source[i] >= 0); printf2 ("source[%d] = %d\\n", i, source[i]); } printf2 ("==============\\n"); queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); printf2 ("==============\\n"); for (i = 0; i < 7; i++) printf2 ("sorted[%d] = %d\\n", i, sorted[i]); return 0; }
1
#include <pthread.h> int q[3]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 3) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 3); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[7]; int sorted[7]; void producer () { int i, idx; for (i = 0; i < 7; i++) { idx = findmaxidx (source, 7); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 7; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t pmutex; pthread_mutex_t gmutex; union semun { int val; struct semid_ds *buf; unsigned short *array; struct seminfo *__buf; }; int semid = -1; void getChopsticks(int num) { int left = num; int right = (num+1)%5; struct sembuf sem[2] = {{left, -1, 0} , {right, -1, 0}}; semop(semid, sem, 2); } void putChopsticks(int num) { int left = num; int right = (num+1)%5; struct sembuf sem[2] = {{left, 1, 0} , {right, 1, 0}}; semop(semid, sem, 2); } void *run(void *arg) { int num = (int)arg; while (1) { printf("第%d个哲学家正在思考...\\n", num+1); sleep(1); pthread_mutex_lock(&gmutex); getChopsticks(num); printf("第%d个哲学家获得筷子吃饭...\\n", num+1); pthread_mutex_unlock(&gmutex); sleep(1); pthread_mutex_lock(&pmutex); putChopsticks(num); printf("第%d个哲学家放下筷子...\\n", num+1); pthread_mutex_unlock(&pmutex); sleep(1); } } int main(void) { int i = 0; semid = semget(0x1024, 5, IPC_CREAT|0664); union semun sem; sem.val = 1; for (i = 0; i < 5; i++) { semctl(semid, i, SETVAL, sem); } pthread_t thr[5]; for (i=0; i<5; i++) { pthread_create(thr+i, 0, run, (void*)i); } for (i=0; i<5; i++) { pthread_join(thr[i], 0); } return 0; }
1
#include <pthread.h> static pthread_cond_t condvar; static bool child_ready; static pthread_mutex_t lock; static void handler(int sig) { print("in handler %d\\n", sig); pthread_mutex_lock(&lock); child_ready = 1; pthread_cond_signal(&condvar); pthread_mutex_unlock(&lock); } static void * thread_routine(void *arg) { int fd = (int)(long) arg; char buf[16]; signal(SIGUSR1, handler); pthread_mutex_lock(&lock); child_ready = 1; pthread_cond_signal(&condvar); pthread_mutex_unlock(&lock); int res = read(fd, buf, 2); if (res < 0) perror("error during read"); else print("got %d bytes == %d %d\\n", res, buf[0], buf[1]); close(fd); } int main(int argc, char **argv) { pthread_t thread; void *retval; int pipefd[2]; if (pipe(pipefd) == -1) { perror("pipe"); exit(1); } pthread_mutex_init(&lock, 0); pthread_cond_init(&condvar, 0); if (pthread_create(&thread, 0, thread_routine, (void *)(long)pipefd[0]) != 0) { perror("failed to create thread"); exit(1); } pthread_mutex_lock(&lock); while (!child_ready) pthread_cond_wait(&condvar, &lock); child_ready = 0; pthread_mutex_unlock(&lock); print("sending SIGURG\\n"); pthread_kill(thread, SIGURG); sleep(1); print("sending SIGUSR1\\n"); pthread_kill(thread, SIGUSR1); pthread_mutex_lock(&lock); while (!child_ready) pthread_cond_wait(&condvar, &lock); child_ready = 0; pthread_mutex_unlock(&lock); write(pipefd[1], "ab", 2); if (pthread_join(thread, &retval) != 0) perror("failed to join thread"); pthread_cond_destroy(&condvar); pthread_mutex_destroy(&lock); print("all done\\n"); return 0; }
0
#include <pthread.h> int GlobalGeneratedValues[10*10]; pthread_mutex_t mutexsum; void *GenerateValues(void *threadid) { int taskId; taskId = (int)threadid; int i=0, tmepvalue; int LocalThreadGeneratedValues[10]; for (i =0; i <= 10; i++) { tmepvalue = rand() % 11; while (tmepvalue == 0 ) tmepvalue = rand() % 11; LocalThreadGeneratedValues[i] = tmepvalue; } int SegmentNo = (10*taskId); pthread_mutex_lock (&mutexsum); for(i=0; i < 10; i++) { GlobalGeneratedValues[SegmentNo + i] = LocalThreadGeneratedValues[i]; printf("\\ntaskId:%d , GlobalGeneratedValues[%d] = %d \\t",taskId,i, LocalThreadGeneratedValues[i]); } pthread_mutex_unlock (&mutexsum); pthread_exit(0); } void main(int argc, char *argv[]) { pthread_t threads[10]; pthread_attr_t attr; void *status; int rc, t; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(t=0;t<10;t++) { printf("Creating thread : %d\\n", t); rc = pthread_create(&threads[t], &attr, GenerateValues, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for(t=0;t<10;t++) { rc = pthread_join(threads[t], &status); if (rc){ printf("ERROR return code from pthread_join() is %d\\n", rc); exit(-1); } } int sum = 0; for(int i=0; i<10*10; i++) { printf("\\nGlobalGeneratedValues[%d] = %d \\t Sum = %d",i, GlobalGeneratedValues[i], sum); sum += GlobalGeneratedValues[i]; } printf("\\n\\n\\n\\n The sum of all generated value numbers by threads is : %d",sum); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> volatile int myInt = 1; pthread_mutex_t myLock; void *readInt(void *numberOfLoops) { int i=0; int localInt = 0; for (i=0; i<*((int*)numberOfLoops); i++) { pthread_mutex_lock(&myLock); localInt = myInt; pthread_mutex_unlock(&myLock); } pthread_exit(0); } void *incInt(void *numberOfLoops) { int i=0; for (i=0; i<*((int*)numberOfLoops); i++) { pthread_mutex_lock(&myLock); myInt = myInt + 1; pthread_mutex_unlock(&myLock); } pthread_exit(0); } int main(int argc, char** argv) { pthread_t threads[32]; int error = pthread_mutex_init(&myLock,0); if (error) { printf("Error initializing lock\\n"); return(1); } char *tempString = 0; int t = 0; int threadIndexMax = 0; int numberOfLoops = 0; int numberOfReads = 0; int processorCount = 0; int localInt = 0; for (t=0; t<argc; t++) { tempString = argv[t]; if (tempString[0]=='-') { if (tempString[1]=='p') { processorCount = atoi(tempString+2); } else if (tempString[1]=='n') { numberOfReads = atoi(tempString+2); } } } if (!processorCount || !numberOfReads) { printf("Usage: readtest -p[number of processors] -n[number of reads]\\n"); pthread_exit(0); } threadIndexMax = processorCount - 2; threadIndexMax = threadIndexMax / 2; numberOfLoops = numberOfReads / processorCount; printf("numberOfLoops=%d\\n", numberOfLoops); t = 0; while (1) { printf("Creating write thread %d\\n", t); pthread_create(&threads[t], 0, incInt, &numberOfLoops); t++; if (t >= processorCount-1) { break; } printf("Creating read thread %d\\n", t); pthread_create(&threads[t], 0, readInt, &numberOfLoops); t++; } printf("Creating read thread %d\\n", t); for (t=0; t<numberOfLoops; t++) { pthread_mutex_lock(&myLock); localInt = myInt; pthread_mutex_unlock(&myLock); } for (t=0; t<processorCount-2; t++) { pthread_join(threads[t], 0); pthread_exit(0); } }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; }thread,*pthread; void *threadfunc(void *p) { int ret; pthread id=(pthread)p; printf("process id:%d,chlid pthread id:%lu be waiting!\\n",getpid(),pthread_self()); pthread_mutex_lock(&id->mutex); ret=pthread_cond_wait(&id->cond,&id->mutex); if(ret!=0) { printf("pthread_cond_wait=%d\\n",ret); return (void*)-1; } printf("process id:%d,chlid pthread id:%lu signal coming!\\n",getpid(),pthread_self()); pthread_mutex_unlock(&id->mutex); printf("process id:%d,chlid pthread id:%lu is wakeup!\\n",getpid(),pthread_self()); pthread_exit(0); } int main(void) { thread id; int i,ret; ret=pthread_mutex_init(&id.mutex,0); if(ret!=0) { printf("pthread_mutex_init=%d\\n",ret); return -1; } ret=pthread_cond_init(&id.cond,0); if(ret!=0) { printf("pthread_cond_init=%d\\n",ret); return -1; } pthread_t num[5]; for(i=0;i<5;i++) { pthread_create(&num[i],0,threadfunc,&id); if(ret!=0) { printf("pthread_cond_init=%d\\n",ret); return -1; } printf("%dth pthread create success,process!\\n",i+1); } sleep(1); pthread_cond_broadcast(&id.cond); for(i=0;i<5;i++) pthread_join(num[i],0); pthread_mutex_destroy(&id.mutex); return 0; }
1
#include <pthread.h> char wkeyerbuffer[400] = ""; int data_ready = 0; pthread_mutex_t keybuffer_mutex = PTHREAD_MUTEX_INITIALIZER; void keyer_append(const char *string) { pthread_mutex_lock( &keybuffer_mutex ); g_strlcat(wkeyerbuffer, string, sizeof(wkeyerbuffer)); data_ready = 1; pthread_mutex_unlock( &keybuffer_mutex ); } void keyer_flush() { pthread_mutex_lock( &keybuffer_mutex ); wkeyerbuffer[0] = '\\0'; data_ready = 0; pthread_mutex_unlock( &keybuffer_mutex ); } int write_keyer(void) { extern int trxmode; extern int cwkeyer; extern int digikeyer; extern char controllerport[]; extern char rttyoutput[]; FILE *bfp = 0; int rc; char outstring[420] = ""; char *tosend = 0; if (trxmode != CWMODE && trxmode != DIGIMODE) return (1); pthread_mutex_lock( &keybuffer_mutex ); if (data_ready == 1) { tosend = g_strdup(wkeyerbuffer); wkeyerbuffer[0] = '\\0'; data_ready = 0; } pthread_mutex_unlock( &keybuffer_mutex ); if (tosend != 0) { if (digikeyer == FLDIGI && trxmode == DIGIMODE) { fldigi_send_text(tosend); } else if (cwkeyer == NET_KEYER) { netkeyer(K_MESSAGE, tosend); } else if (cwkeyer == MFJ1278_KEYER || digikeyer == MFJ1278_KEYER) { if ((bfp = fopen(controllerport, "a")) == 0) { mvprintw(24, 0, "1278 not active. Switching to SSB mode."); sleep(1); trxmode = SSBMODE; clear_display(); } else { fputs(tosend, bfp); fclose(bfp); } } else if (digikeyer == GMFSK) { if (strlen(rttyoutput) < 2) { mvprintw(24, 0, "No modem file specified!"); } if (tosend[strlen(tosend)-1] == '\\n') { tosend[strlen(tosend)-1] = '\\0'; } sprintf(outstring, "echo -n \\"\\n%s\\" >> %s", tosend, rttyoutput); rc = system(outstring); } g_free (tosend); tosend = 0; } return (0); }
0
#include <pthread.h> struct zc_queue create_queue() { struct zc_queue queue = { .first = 0, .last = 0, .mutex = 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 *queue_push_back_more( struct zc_queue *queue, void *_value, const unsigned short size, unsigned short copy) { struct zc_queue_elem * elem = malloc(sizeof(struct zc_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 *queue_push_back(struct zc_queue *queue, void *_value, const unsigned short size) { return queue_push_back_more(queue, _value, size, 1); } void *queue_pop_front(struct zc_queue *queue) { pthread_mutex_lock(&queue->mutex); if (queue->first == 0){ pthread_mutex_unlock(&queue->mutex); return 0; } void * value = queue->first->value; struct zc_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 queue_cleanup(struct zc_queue *queue) { while(queue->first != 0){ free(queue_pop_front(queue)); } } struct zc_queue *create_queue_pointer() { struct zc_queue _q = create_queue(); struct zc_queue * queue = malloc(sizeof(struct zc_queue)); memcpy(queue, &_q, sizeof(struct zc_queue)); return queue; } void queue_delete_queue_pointer(struct zc_queue *queue) { queue_cleanup(queue); free(queue); } void *queue_get_elem(struct zc_queue *queue, void *elem) { pthread_mutex_lock(&queue->mutex); struct zc_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 *queue_push_top_more(struct zc_queue *queue, void *_value, const unsigned short size, unsigned short copy) { struct zc_queue_elem * elem = malloc(sizeof(struct zc_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 *queue_push_top(struct zc_queue *queue, void *_value, const unsigned short size) { return queue_push_top_more(queue, _value, size, 1); }
1
#include <pthread.h> const int nr_threads = 4; int port; char* data; int size; int nr_requests; pthread_mutex_t lock; unsigned long total = 0; int nr_accepted = 0; const char* HOST = 0; void* worker(void* arg) { int i; for (i = 0; i < nr_requests / nr_threads; ++i) { int sfd; int ret; u32 usecs; do { struct timeval __beg, __end; gettimeofday(&__beg, 0); do { { sfd = get_conn_to_host(HOST, port, SOCK_STREAM); ret = write(sfd, data, size); ret += read(sfd, data, size); evt_close(sfd); } } while (0); gettimeofday(&__end, 0); u32 __end_us = (__end.tv_sec * 1000000) + __end.tv_usec; u32 __beg_us = (__beg.tv_sec * 1000000) + __beg.tv_usec; usecs = __end_us - __beg_us; } while(0); ; pthread_mutex_lock(&lock); total += usecs; if (ret == 2 * size) ++nr_accepted; pthread_mutex_unlock(&lock); } return arg; } int main(int argc, char** argv) { puts("Usage: ./flooder [port] [nr_conns]"); assert(argc == 3); port = atoi(argv[1]); nr_requests = atoi(argv[2]); size = 512; int pad = nr_requests % nr_threads; nr_requests += nr_threads - pad; data = malloc(size); pthread_t pool[nr_threads]; pthread_mutex_init(&lock, 0); evt_server_init(port, SOCK_STREAM); int i; for (i = 0; i < nr_threads; ++i) { pthread_create(&pool[i], 0, worker, 0); } pthread_join(pool[nr_threads - 1], 0); fflush(stdout); double avg = ((double) total) / ((double) nr_requests); printf ("nr_accepted = %d\\n" "nr_requests = %d\\n" "total time (microseconds) = %lu\\n" "avg. time per req (microseconds) = %f\\n" , nr_accepted, nr_requests, total, avg); return 0; }
0
#include <pthread.h> int main(int argc, char *argv[]) { int num_mutexes = 5; if (argc > 1) num_mutexes = atoi(argv[1]); pthread_mutex_t m[num_mutexes]; for (int i = 0; i < num_mutexes; ++i) pthread_mutex_init(&m[i], 0); for (int i = 0; i < num_mutexes - 1; ++i) { pthread_mutex_lock(&m[i]); pthread_mutex_lock(&m[i + 1]); pthread_mutex_unlock(&m[i]); pthread_mutex_unlock(&m[i + 1]); } pthread_mutex_lock(&m[num_mutexes - 1]); pthread_mutex_lock(&m[0]); pthread_mutex_unlock(&m[num_mutexes - 1]); pthread_mutex_unlock(&m[0]); for (int i = 0; i < num_mutexes; ++i) pthread_mutex_destroy(&m[i]); fprintf(stderr, "PASS\\n"); }
1
#include <pthread.h> int pthread_getschedparam (pthread_t thread_id, int *policy, struct sched_param *param) { int ret = 0; posix_thread_t *thread; pthread_mutex_lock(&_posix_threads_mutex); thread = posix_get_thread(thread_id); if( thread == 0 ) { ret = ESRCH; } else { if( policy != 0 ) { *policy = thread->schedpolicy; } if( param != 0 ) { *param = thread->schedparam; } } pthread_mutex_unlock(&_posix_threads_mutex); return 0; }
0
#include <pthread.h> volatile int tab[5]; pthread_mutex_t mutex; void * lire (void *arg) { int i; pthread_mutex_lock (&mutex); for (i = 0; i != 5; i++) printf ("Thread lecture: tab[%d] vaut %d\\n", i, tab[i]); pthread_mutex_unlock (&mutex); pthread_exit (0); } void * ecrire (void *arg) { int i; pthread_mutex_lock (&mutex); for (i = 0; i != 5; i++) { tab[i] = 2 * i; printf ("Thread ecriture: tab[%d] vaut %d\\n", i, tab[i]); usleep (500000); } pthread_mutex_unlock (&mutex); pthread_exit (0); } int main (void) { pthread_t th1, th2; void *ret; pthread_mutex_init (&mutex, 0); if (pthread_create (&th1, 0, ecrire, 0) < 0) { perror ("Thread ecrire (pthread_create)"); exit (-1); } if (pthread_create (&th2, 0, lire, 0) < 0) { perror ("Thread lire (pthread_create)"); exit (-1); } (void) pthread_join (th1, &ret); (void) pthread_join (th2, &ret); }
1
#include <pthread.h> static int classificacao = 1; static pthread_mutex_t lock; static void* Correr(void* sapo); int main() { classificacao = 1; pthread_t threads[5]; int t; printf("Corrida iniciada...\\n"); for(t = 0; t < 5; t++) { pthread_create(&threads[t], 0, Correr, (void *)t); } for(t = 0; t < 5; t++) { pthread_join(threads[t], 0); } printf("\\nAcabou!!\\n"); pthread_exit(0); return 0; } void* Correr(void* sapo) { int pulos = 0; int distanciaJaCorrida = 0; while(distanciaJaCorrida <= 100) { int pulo = rand() % 100; distanciaJaCorrida += pulo; pulos++; printf("Sapo %d pulou\\n", (int)sapo); int descanso = rand() % 1; sleep(descanso); } pthread_mutex_lock(&lock); printf("Sapo %d chegou na posicao %d com %d pulos!\\n", (int)sapo, classificacao, pulos); classificacao++; pthread_mutex_unlock(&lock); pthread_exit(0); }
0
#include <pthread.h> int end; int p,q; char buffer[5]; pthread_mutex_t mutex; pthread_cond_t empty,full; int thread_no; int partial_count; } thdata; void producer_func(FILE *fp){ char s1; s1 = fgetc(fp); while(1){ pthread_mutex_lock(&mutex); buffer[p] = s1; p = (p+1)%5; if((p-1)%5 == q){ pthread_cond_signal(&empty); } if(p == q){ pthread_cond_wait(&full, &mutex); } pthread_mutex_unlock(&mutex); s1=fgetc(fp); if(feof(fp)){ pthread_mutex_lock(&mutex); end = 1; pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); break; } } } void consumer_func(void *ptr){ while(1){ pthread_mutex_lock(&mutex); if(p == q){ if(end) break; else{ pthread_cond_wait(&empty, &mutex); if(p == q && end) break; } } printf("%c",buffer[q]); q = (q+1)%5; if(p == (q-1)%5){ pthread_cond_signal(&full); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char *argv[]){ pthread_t producer, consumer; FILE *fp; p = 0; q = 0; if((fp=fopen("messages.txt", "r"))==0){ printf("ERROR: can't open string.txt!\\n"); return -1; } pthread_mutex_init(&mutex, 0); pthread_cond_init (&empty, 0); pthread_cond_init (&full, 0); end = 0; pthread_create (&producer, 0, (void *) &producer_func, (FILE *) fp); pthread_create (&consumer, 0, (void *) &consumer_func, 0); pthread_join(producer, 0); pthread_join(consumer, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&empty); pthread_cond_destroy(&full); return 1; }
1
#include <pthread.h> int bitmap[5000]; int init; int num_alloc; pthread_mutex_t lock; } pid_table; pid_table ptable; int allocate_map(void) { int i; if (ptable.init) { return 1; } for (i = 0; i < 5000; i++) { ptable.bitmap[i] = 0; } ptable.init = 1; ptable.num_alloc = 0; return 0; } int allocate_pid(void) { int i; pthread_mutex_lock(&(ptable.lock)); if (!ptable.init || ptable.num_alloc == 5000 - 1) { pthread_mutex_unlock(&(ptable.lock)); return 1; } pthread_mutex_unlock(&(ptable.lock)); for (i = 0; i < 5000; i++) { pthread_mutex_lock(&(ptable.lock)); if (ptable.bitmap[i] == 0 && i != 1) { ptable.bitmap[i] = 1; ++ptable.num_alloc; break; } pthread_mutex_unlock(&(ptable.lock)); } return i; } int release_pid(int pid) { pthread_mutex_lock(&(ptable.lock)); if (ptable.init && pid >= 0 && pid < 5000) { ptable.bitmap[pid] = 0; --ptable.num_alloc; pthread_mutex_unlock(&(ptable.lock)); return 0; } else { pthread_mutex_unlock(&(ptable.lock)); return 1; } }
0
#include <pthread.h> struct gw { void *thingplus; char *id; bool connected; int nr_sensor; struct sensor *sensor; timer_t timer_id; pthread_mutex_t wait_thingplus_done_mutex; pthread_cond_t wait_thingplus_done; }; static struct gw *gw = 0; static unsigned long long _now_ms(void) { struct timeval tv; unsigned long long now; gettimeofday(&tv, 0); now = (unsigned long long)(tv.tv_sec) * 1000 + (unsigned long long)(tv.tv_usec) / 1000; return now; } static void _thingplus_done(struct gw *g) { pthread_mutex_lock(&g->wait_thingplus_done_mutex); pthread_cond_signal(&g->wait_thingplus_done); pthread_mutex_unlock(&g->wait_thingplus_done_mutex); } static void _thingplus_wait(struct gw *g) { pthread_mutex_lock(&g->wait_thingplus_done_mutex); pthread_cond_wait(&g->wait_thingplus_done, &gw->wait_thingplus_done_mutex); pthread_mutex_unlock(&g->wait_thingplus_done_mutex); } static void _status_publish(union sigval sigval) { struct gw *g = (struct gw*)sigval.sival_ptr; struct thingplus_status s[2]; int i=0; for (i=0; i<g->nr_sensor; i++) { s[i].id = g->sensor[i].id; s[i].timeout_ms = (60 * 2) * 1000; if (g->sensor[i].ops.on) s[i].status = g->sensor[i].ops.on() ? 0 : 1 ; else s[i].status = 1; } s[i].id = g->id; s[i].status = 0; s[i].timeout_ms = (60 * 2) * 1000; thingplus_status_publish(g->thingplus, 0, sizeof(s)/sizeof(s[0]), s); } static void _status_publish_timer_start(struct gw *g) { struct itimerspec its; bzero(&its, sizeof(its)); its.it_interval.tv_sec = 60; its.it_interval.tv_nsec = 0; its.it_value.tv_sec = 1; its.it_value.tv_nsec = 0; struct sigevent sev; bzero(&sev, sizeof(sev)); sev.sigev_notify = SIGEV_THREAD; sev.sigev_signo = SIGUSR1; sev.sigev_value.sival_ptr = g; sev.sigev_notify_function = _status_publish; sev.sigev_notify_attributes = 0; if (timer_create(CLOCK_REALTIME, &sev, &g->timer_id) < 0) { fprintf(stderr, "timer_create failed\\n"); return; } timer_settime(g->timer_id, 0, &its, 0); } static void _status_publish_timer_stop(struct gw *g) { if (g->timer_id) timer_delete(g->timer_id); } static void _connected(void *arg, enum thingplus_error error) { struct gw* g = (struct gw*)arg; g->connected = 1; _status_publish_timer_start(g); _thingplus_done((struct gw*)arg); } int gw_event_value_publish(char *id, char *value) { if (!gw) return -1; struct thingplus_value v; v.id = id; v.value = value; v.time_ms = _now_ms(); return thingplus_value_publish(gw->thingplus, 0, 1, &v); } int gw_connect(char *ca_cert) { if (!gw) return -1; if (gw->connected) return 1; if (!ca_cert) { printf("[ERR] Invalid Argument\\n"); return -1; } thingplus_connect(gw->thingplus, 8883, ca_cert, 60); _thingplus_wait(gw); return 0; } void gw_disconnect(void) { if (!gw) return; _status_publish_timer_stop(gw); } int gw_init(char *gw_id, char *apikey, int nr_sensor, struct sensor *s) { if (gw) { printf("[WARN gw_connect is already called\\n"); return -1; } if (!gw_id || !apikey) { printf("[ERR] Invalid Argument\\n"); return -1; } gw = (struct gw*)calloc(1, sizeof(struct gw)); if (gw == 0) { return -1; } pthread_mutex_init(&gw->wait_thingplus_done_mutex, 0); pthread_cond_init(&gw->wait_thingplus_done, 0); gw->id = (char*)malloc(strlen(gw_id) + 1); if (!gw->id) goto err_gw_id_dump; strcpy(gw->id, gw_id); gw->nr_sensor = nr_sensor; gw->sensor = calloc(nr_sensor, sizeof(struct sensor)); if (!gw->sensor) { goto err_sensor_malloc; } memcpy(gw->sensor, s, nr_sensor * sizeof(struct sensor)); gw->thingplus = thingplus_init(gw_id, apikey, "mqtt.thingplus.net", "https://api.thingplus.net"); if (!gw->thingplus) { goto err_thingplus_init; } struct thingplus_callback cb; bzero(&cb, sizeof(struct thingplus_callback)); cb.connected = _connected; thingplus_callback_set(gw->thingplus, &cb, gw); return 0; err_thingplus_init: free(gw->sensor); err_sensor_malloc: free(gw->id); err_gw_id_dump: pthread_cond_destroy(&gw->wait_thingplus_done); pthread_mutex_destroy(&gw->wait_thingplus_done_mutex); free(gw); gw = 0; return -1; } void gw_cleanup(void) { if (!gw) return; gw_disconnect(); if (gw->thingplus) thingplus_cleanup(gw->thingplus); if (gw->sensor) free(gw->sensor); if (gw->id) free(gw->id); pthread_cond_destroy(&gw->wait_thingplus_done); pthread_mutex_destroy(&gw->wait_thingplus_done_mutex); free(gw); gw = 0; }
1
#include <pthread.h> struct file_path { int tag; char path[1024]; int flag; int fd; }; struct thread_arg { int fd; char *data; uint64_t size; int id; }; struct file_path fp[(1000)]; char cpath[(1000)][1024]; int fp_flag[(1000)]; pthread_t writer_thread[(1000)]; struct thread_arg writer_args[(1000)]; double start[(1000)]; double end[(1000)]; pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER; int thread_count = 0; static int get_index(uint64_t id); static int hash(uint64_t id); void RDMA_transfer_recv(void); void *writer(void *args); int main(int argc, char **argv) { RDMA_transfer_recv(); return 0; } int count = 1; void RDMA_transfer_recv(void) { struct RDMA_communicator comm; char* data; char* path; uint64_t size; int ctl_tag; int file_tag; int id; int i; char log[1024]; RDMA_Passive_Init(&comm); for (i = 0; i < (1000); i++) { fp[i].flag = 0; fp_flag[i] = 0; } int a = 0; double s; double data_out_count = 0; while (1) { int retry = 1000; RDMA_Recvr(&data, &size, &ctl_tag, &comm); data_out_count += size; debug(fprintf(stderr, "RDMA lib: RECV: %s: Time= %f , out_count= %f \\n", get_ip_addr("ib0"), get_dtime(), data_out_count), 2); if (a == 0) { s = get_dtime(); a = 1; } if (ctl_tag == TRANSFER_INIT) { sprintf(log, "ACT lib: RECV: INI: %s\\n", data); file_tag = atoi(strtok(data, "\\t")); id = get_index(file_tag); fp[id].tag = file_tag; path = strtok(0, "\\t"); sprintf(cpath[id],"%s",path); while ((fp[id].fd = open(path, O_WRONLY | O_CREAT, 0660)) < 0) { if (retry < 0) { fprintf(stderr, "ACT lib: RECV: ERROR: failed to open file= %s\\n", cpath[id]); exit(1); } fprintf(stderr, "ACT lib: RECV: failed to open file= %s: retry=%d\\n", cpath[id], retry); usleep(1 * 1000 * 1000); retry--; } printf("ACT lib: RECV: fd= %d opened: file= %s \\n", fp[id].fd, cpath[id]); fp[id].flag = 1; start[id] = get_dtime(); } else if (ctl_tag == TRANSFER_FIN) { file_tag = atoi(strtok(data, "\\t")); id = get_index(file_tag); while (fp_flag[id] != 0) { usleep(1 * 1000); } while (close(fp[id].fd) < 0) { fprintf(stderr, "ACT lib: RECV: ERROR: failed to close file= %d\\n", fp[id].fd); exit(1); } printf("ACT lib: RECV: fd= %d closed\\n", fp[id].fd); end[id] = get_dtime(); count++; debug(printf("ACT lib: Recv: FIN: Time stamp= %f\\n", get_dtime() - s), 1); RDMA_show_buffer(); } else { id = get_index(ctl_tag); while (fp_flag[id] != 0) { usleep(1); } fp_flag[id] = 1; writer_args[id].id = id; writer_args[id].fd = fp[id].fd; printf("ACT lib: RECV: fd= %d write\\n", fp[id].fd); writer_args[id].data = data; writer_args[id].size = size; while (thread_count >= (10)) { usleep(10); } pthread_mutex_lock(&fastmutex); thread_count++; pthread_mutex_unlock(&fastmutex); pthread_create(&writer_thread[id], 0, writer, &writer_args[id]); } } return ; } void *writer(void *args) { struct thread_arg *wargs; int fd; int id; char* data; uint64_t size; double ws, we; int n_write = 0; int n_write_sum = 0; wargs = (struct thread_arg *)args; id = wargs->id; fd = wargs->fd; data = wargs->data; size = wargs->size; ws = get_dtime(); do { n_write = write(fd, data, size); if(n_write < 0) { perror("ACT lib: RECV: ERROR: Write error"); fprintf(stderr, "ACT lib: RECV: ERROR: Write error: fd=%d\\n", fd); exit(1); } n_write_sum = n_write_sum + n_write; if(n_write_sum >= size) { break; } fprintf(stderr, "ACT lib: RECV: partial write %d / %lu \\n", n_write, size); } while( n_write > 0); fsync(fd); we = get_dtime(); printf("ACT lib: RECV: writer ends: %d : write time = %f secs, write size= %f MB , throughput= %f MB/s\\n", fd, we - ws, size/1000000.0, size/(we - ws)/1000000.0); fp_flag[id] = 0; free(data); pthread_mutex_lock(&fastmutex); thread_count--; pthread_mutex_unlock(&fastmutex); return 0; } static int get_index(uint64_t id) { int i; int index; int offset = 0; index = hash(id + offset); i = 0; for (i = 0; i < (1000); i++) { if (fp[index].flag == 0) { return index; } else if (fp[index].tag == id) { return index; } index = (index + 1) % (1000); } printf("Error:Hashtable: Enough size of hashtable needed\\n"); exit(0); return 0; } static int hash(uint64_t id) { unsigned int b = 378551; unsigned int a = 63689; unsigned int hash = 0; unsigned int i = 0; unsigned int l = 3; for(i = 0; i < l; i++) { hash = hash * a + id; a = a * b; } return hash % (1000); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutexattr_t mutex_attrs; pthread_t thread_A, thread_B; int global_var; void *thread_func_A(void *arg) { char *message = arg; int ret; printf("%s \\n", message); pthread_mutex_lock(&mutex); global_var = 5; pthread_mutex_unlock(&mutex); return arg; } void *thread_func_B(void *arg) { char *message = arg; int ret; printf("%s \\n", message); ret = pthread_mutex_unlock(&mutex); if (ret != 0) { printf("Thread B failed to unlock mutex acquired by thread A \\n"); } pthread_mutex_lock(&mutex); global_var = 10; pthread_mutex_unlock(&mutex); return arg; } int main(int argc, char *argv[]) { int ret; pthread_mutexattr_init(&mutex_attrs); pthread_mutexattr_settype(&mutex_attrs, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &mutex_attrs); ret = pthread_create(&thread_A, 0 , thread_func_A , "This is thread A"); assert(ret == 0); ret = pthread_create(&thread_B, 0 , thread_func_B , "This is thread B"); assert(ret == 0); ret = pthread_join(thread_A, 0 ); assert(ret == 0); ret = pthread_join(thread_B, 0); assert(ret == 0); printf("Value of global variable: %d \\n", global_var); pthread_mutexattr_destroy(&mutex_attrs); pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> int thread_count; char theArray[1024][1000]; int* seed; pthread_mutex_t mutex; void *Operate(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; int i; double start, finish, elapsed; thread_count = strtol(argv[1], 0, 10); seed = malloc(thread_count*sizeof(int)); for (i = 0; i < thread_count; i++) seed[i] = i; for (i = 0; i < 1024; i ++) { sprintf(theArray[i], "theArray[%d]: initial value", i); printf("%s\\n\\n", theArray[i]); } thread_handles = malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); GET_TIME(start); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Operate, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); GET_TIME(finish); elapsed = finish - start; printf("The elapsed time is %e seconds\\n", elapsed); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; } void *Operate(void* rank) { long my_rank = (long) rank; printf("%p\\n", &seed[my_rank]); int pos = rand_r(&seed[my_rank]) % 1024; int randNum = rand_r(&seed[my_rank]) % 10; printf("pos: %i\\n", pos); pthread_mutex_lock(&mutex); if (randNum >= 9) sprintf(theArray[pos], "theArray[%i] modified by thread %ld", pos, my_rank); printf("Thread %ld: randNum = %i\\n", my_rank, randNum); printf("%s\\n\\n", theArray[pos]); pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> void *sum(void *p); unsigned long int psum[8 * 64]; unsigned long int sumtotal = 0; unsigned long int n; int numthreads; pthread_mutex_t mutex; int main(int argc, char **argv) { pthread_t tid[8]; int i, myid[8]; struct timeval start, end; gettimeofday(&start, 0); scanf("%lu %d", &n, &numthreads); for (i = 0; i < numthreads; i++) { myid[i] = i; psum[i * 64] = 0.0; pthread_create(&tid[i], 0, sum, &myid[i]); } for (i = 0; i < numthreads; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); long spent = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec); printf("%lu\\n%ld\\n", sumtotal, spent); return 0; } void *sum(void *p) { int myid = *((int *) p); unsigned long int start = (myid * (unsigned long int) n) / numthreads; unsigned long int end = ((myid + 1) * (unsigned long int) n) / numthreads; unsigned long int i; for (i = start; i < end; i++) { psum[myid * 64] += 2; } pthread_mutex_lock(&mutex); sumtotal += psum[myid * 64]; pthread_mutex_unlock(&mutex); return 0 ; }
1
#include <pthread.h> sem_t *sem_consume; sem_t *sem_produce; pthread_mutex_t mutex; buffer_item buffer[5]; int head = 0; int tail = 0; int count = 0; void sleep_rand() { sleep(rand() % 5 + 1); } int insert_item(buffer_item item) { sem_wait(sem_produce); pthread_mutex_lock(&mutex); if (count == 5) return -1; buffer[tail] = item; tail = (tail + 1) % 5; count++; pthread_mutex_unlock(&mutex); sem_post(sem_consume); return 0; } int remove_item(buffer_item *item) { sem_wait(sem_consume); pthread_mutex_lock(&mutex); if (count == 0) return -1; *item = buffer[head]; head = (head + 1) % 5; count--; pthread_mutex_unlock(&mutex); sem_post(sem_produce); return 0; } void *producer(void *param) { buffer_item item; while (1) { sleep_rand(); item = rand(); if (insert_item(item)) { fprintf(stderr, "report error condition\\n"); } else { printf("producer produced %d\\n", item); } } } void *consumer(void *param) { buffer_item item; while (1) { sleep_rand(); if (remove_item(&item)) { fprintf(stderr, "report error condition\\n"); } else { printf("consumer consumed %d\\n", item); } } } int main(int argc, char *argv[]) { if (argc != 4) { fprintf(stderr, "Should have 3 args:\\n[1] The sleep time before terminate.\\n[2] The number of producer threads.\\n[3] The number of consumer threads.\\n"); return 1; } srand(time(0)); int sleep_time = atoi(argv[1]); int producer_count = atoi(argv[2]); int consumer_count = atoi(argv[3]); pthread_t *producer_threads = (pthread_t *) malloc(sizeof(pthread_t) * producer_count); pthread_t *consumer_threads = (pthread_t *) malloc(sizeof(pthread_t) * consumer_count); pthread_attr_t attr; pthread_attr_init(&attr); if ((sem_produce = sem_open("/semaphore1", O_CREAT, 0644, 5)) == SEM_FAILED || (sem_consume = sem_open("/semaphore2", O_CREAT, 0644, 0)) == SEM_FAILED) { fprintf(stderr, "Error opening semaphore\\n"); return 2; } pthread_mutex_init(&mutex, 0); int i; for (i = 0; i < producer_count; i++) { pthread_create(&producer_threads[i], &attr, producer, 0); } for (i = 0; i < consumer_count; i++) { pthread_create(&consumer_threads[i], &attr, consumer, 0); } sleep(sleep_time); if (sem_close(sem_produce) == -1 || sem_close(sem_consume) == -1) { fprintf(stderr, "Error closing semaphore\\n"); return 3; } if (sem_unlink("/semaphore1") == -1 || sem_unlink("/semaphore2") == -1) { fprintf(stderr, "Error unlinking semaphore\\n"); return 4; } free(producer_threads); free(consumer_threads); printf("Done!\\n"); return 0; }
0
#include <pthread.h> double start_time, end_time; pthread_mutex_t palindromicsMutex; pthread_mutex_t wordsMutex; struct thread_data { long noPalindromes; FILE* wordsfd; FILE* palindromicsfd; }; 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); } void reverseStr(char* str) { if(str) { int i, length, last_pos; length = strlen(str); last_pos = length - 1; for(i=0; i<length/2; i++) { char tmp = str[i]; str[i] = str[last_pos - i]; str[last_pos - i] = tmp; } } } void* work(void *threadarg) { struct thread_data* my_data; my_data = (struct thread_data *) threadarg; FILE* fd = fopen("words","r"); if (!fd) { perror("Error opening file in thread: "); pthread_exit(0); } while(1) { ssize_t read, read2; char* line = 0; char* line2 = 0; size_t len = 0; size_t len2 = 0; pthread_mutex_lock (&wordsMutex); read = getline(&line, &len, my_data->wordsfd); pthread_mutex_unlock (&wordsMutex); if (read == -1) { fclose(fd); pthread_exit(0); } line[read-1] = 0; reverseStr(line); while ((read2 = getline(&line2, &len2, fd)) != -1) { line2[read2-1] = 0; if (!strcasecmp(line, line2)) { my_data->noPalindromes += 1; reverseStr(line); pthread_mutex_lock (&palindromicsMutex); fprintf(my_data->palindromicsfd, "%s\\n", line); pthread_mutex_unlock (&palindromicsMutex); rewind(fd); break; } free(line2); line2 = 0; len2 = 0; } rewind(fd); free(line); } } int main(int argc, char* argv[]) { if (argc != 2) { printf("Usage: %s <number of worker processes>\\n", argv[0]); exit(0); } int noThreads = atoi(argv[1]); pthread_t threads[noThreads]; pthread_attr_t attr; struct thread_data thread_data_array[noThreads]; int i, rc; void *status; FILE* fd = fopen("palindromics", "w"); if(!fd) { perror("Error opening palindromics file in master: "); exit(-1); } FILE* wordsFile = fopen("words", "r"); if(!wordsFile) { perror("Error opening words file in master: "); exit(-1); } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); start_time = read_timer(); for (i=0; i<noThreads; i++) { thread_data_array[i].noPalindromes = 0; thread_data_array[i].wordsfd = wordsFile; thread_data_array[i].palindromicsfd = fd; rc = pthread_create(&threads[i], &attr, work, (void *)&thread_data_array[i]); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); long noPalindromics = 0; for(i=0; i<noThreads; i++) { rc = pthread_join(threads[i], &status); if (rc) { printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(-1); } printf("Main: thread %d found %ld palindromics\\n",i,thread_data_array[i].noPalindromes); noPalindromics += thread_data_array[i].noPalindromes; } end_time = read_timer(); fclose(wordsFile); fclose(fd); printf("Found total of %ld palindromics\\n", noPalindromics); printf("The execution time is %g sec\\n", end_time - start_time); exit(0); }
1
#include <pthread.h> int id; int lap; int v; int broken; int d; int track; int points; int step; } cyclist; int d, n, v; int debug; pthread_t* t; cyclist** comp; int** velodrome; int readyCount; pthread_mutex_t readyMutex; pthread_cond_t allReady; pthread_mutex_t** mutex; pthread_mutex_t* cyclistMutex; void print_velodrome () { for (int i = 0; i < 10; i++){ printf ("%d: ", i); for (int j = 0; j < d; j++) printf ("%d ", velodrome[i][j]); printf ("\\n"); } printf ("\\n"); } void* run (void* cthread) { int i, j, aux; cyclist* c = (cyclist*)(cthread); i = 0; j = d - 1; aux = 1; while (1){ while (aux && i < 10){ if (!(aux = pthread_mutex_trylock(&(mutex[i][j])))) break; i++; } if (i == 10) i = 0; if (j < 0) j += d; if (!aux) break; if(--j < 0) j += d; } velodrome[i][j] = c->id; pthread_mutex_lock (&readyMutex); readyCount++; if (readyCount == n){ readyCount = 0; pthread_cond_broadcast (&allReady); if (debug) print_velodrome(); } else pthread_cond_wait (&allReady, &readyMutex); pthread_mutex_unlock (&readyMutex); for (c->d = j, c->lap = -1; c->lap < v;){ if (!(pthread_mutex_trylock (&(mutex[i][(c->d + 1)%d])))){ pthread_mutex_lock (&(cyclistMutex[c->id])); velodrome[i][c->d] = -1; if (++(c->d) >= d) c->d -= d; velodrome[i][c->d] = c->id; if (debug) print_velodrome(); c->step++; pthread_mutex_unlock (&(mutex[i][c->d - 1])); pthread_mutex_unlock (&(cyclistMutex[c->id])); } pthread_mutex_lock (&readyMutex); readyCount++; if (readyCount == n){ readyCount = 0; pthread_cond_broadcast (&allReady); } else pthread_cond_wait (&allReady, &readyMutex); pthread_mutex_unlock (&readyMutex); if (c->d >= d){ c->d -= d; c->lap++; } } pthread_exit (0); return 0; } int main (int argc, char** argv) { int i, j, k, l, m, p, o, q; d = atoi (argv[1]); n = atoi (argv[2]); v = atoi (argv[3]); if (argc == 5) debug = 1; else debug = 0; t = malloc (n*sizeof (pthread_t)); pthread_mutex_init (&readyMutex, 0); pthread_cond_init (&allReady, 0); cyclistMutex = malloc (n*sizeof (pthread_mutex_t)); for (q = 0; q < n; q++) pthread_mutex_init (&(cyclistMutex[q]), 0); mutex = malloc (10*sizeof (pthread_mutex_t*)); for (m = 0; m < 10; m++) mutex[m] = malloc (d*sizeof (pthread_mutex_t)); for (p = 0; p < 10; p++) for (o = 0; o < d; o++) pthread_mutex_init (&mutex[p][o], 0); velodrome = malloc (10*sizeof (int*)); for (l = 0; l < 10; l++) velodrome[l] = malloc (d*sizeof (int)); for (i = 0; i < 10; i++) for (j = 0; j < d; j++) velodrome[i][j] = -1; if (debug) print_velodrome(); readyCount = 0; comp = malloc (n*sizeof (cyclist*)); for (k = 0; k < n; k++){ comp[k] = malloc (sizeof (cyclist)); comp[k]->id = k; pthread_create (&t[k], 0, run, (void*)comp[k]); } for (k--; k >= 0; k--) pthread_join (t[k], 0); return 0; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; for (;;) { 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(void) { 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); printf("1\\n"); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); printf("2\\n"); exit(0); }
1
#include <pthread.h> double estimatePi(int, int); void * monteCarlo(void *); int circleCount = 0; pthread_mutex_t count_mutex; time_t seed; int main(int argc, char *argv[]) { int i; pthread_t threads[10]; pthread_mutex_init(&count_mutex, 0); seed = time(0); for(i = 0; i < 10; ++i) { int *arg = malloc(sizeof(*arg)); *arg = i; if(pthread_create(&threads[i], 0, monteCarlo, arg)) { perror("pthread create: "); exit(1); } } for(i=0; i < 10; ++i) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&count_mutex); printf("In the parent thread, estimated value of pi is: "); estimatePi(circleCount, (10*1000000)); return 0; } double estimatePi(int points, int totalPoints) { double pi = 4 * (((double)points) / (double)totalPoints); printf("%lf\\n", pi); return pi; } void * monteCarlo(void *arg) { int thread = *((int*) arg); free(arg); double x, y; double min = -1.0; double max = 1.0; double range = (max - min); double divisor = 32767 / range; int counter = 0; long i; unsigned int threadSeed = seed + thread; for (i=0; i < 1000000; i++) { x= min + ((double)rand_r(&threadSeed)/ divisor) ; y= min + ((double)rand_r(&threadSeed)/ divisor) ; if ((x*x + y*y) <= 1) { counter++; } } printf("In thead %d Estimated value of pi is: ", thread); estimatePi(counter, 1000000); pthread_mutex_lock(&count_mutex); circleCount += counter; pthread_mutex_unlock(&count_mutex); pthread_exit(0); }
0
#include <pthread.h> struct AutoFreePool_callback { void (* callback)(void * context); void * context; }; struct AutoFreePool { unsigned int numberOfAddresses; unsigned int addressListSize; void ** addresses; unsigned int numberOfCallbacks; unsigned int callbackListSize; struct AutoFreePool_callback * callbacks; }; static struct AutoFreePool poolStack[16]; static int poolStackDepth = -1; static bool mutexInited = 0; static pthread_mutex_t mutex; void AutoFreePool_initMutex() { pthread_mutex_init(&mutex, 0); mutexInited = 1; } void AutoFreePool_push() { if (mutexInited) { pthread_mutex_lock(&mutex); } if (poolStackDepth >= 16 - 1) { fprintf(stderr, "Warning: AutoFreePool maximum stack depth (%d) exceeded; couldn't push another pool as requested\\n", 16); if (mutexInited) { pthread_mutex_unlock(&mutex); } return; } poolStackDepth++; poolStack[poolStackDepth].addresses = 0; poolStack[poolStackDepth].callbacks = 0; if (mutexInited) { pthread_mutex_unlock(&mutex); } } void AutoFreePool_pop() { if (mutexInited) { pthread_mutex_lock(&mutex); } if (poolStackDepth < 0) { fprintf(stderr, "Warning: AutoFreePool stack underflow; you've popped more times than you've pushed\\n"); if (mutexInited) { pthread_mutex_unlock(&mutex); } return; } AutoFreePool_empty(); free(poolStack[poolStackDepth].addresses); free(poolStack[poolStackDepth].callbacks); poolStackDepth--; } void * AutoFreePool_add(void * address) { if (mutexInited) { pthread_mutex_lock(&mutex); } if (poolStackDepth == -1) { AutoFreePool_push(); } if (poolStack[poolStackDepth].addresses == 0) { poolStack[poolStackDepth].numberOfAddresses = 0; poolStack[poolStackDepth].addressListSize = 1; poolStack[poolStackDepth].addresses = malloc(sizeof(void *) * poolStack[poolStackDepth].addressListSize); } else if (poolStack[poolStackDepth].numberOfAddresses >= poolStack[poolStackDepth].addressListSize) { poolStack[poolStackDepth].addressListSize *= 2; poolStack[poolStackDepth].addresses = realloc(poolStack[poolStackDepth].addresses, sizeof(void *) * poolStack[poolStackDepth].addressListSize); } poolStack[poolStackDepth].addresses[poolStack[poolStackDepth].numberOfAddresses++] = address; return address; } void AutoFreePool_addCallback(void (* callback)(void * context), void * context) { if (mutexInited) { pthread_mutex_lock(&mutex); } if (poolStackDepth == -1) { AutoFreePool_push(); } if (poolStack[poolStackDepth].callbacks == 0) { poolStack[poolStackDepth].numberOfCallbacks = 0; poolStack[poolStackDepth].callbackListSize = 1; poolStack[poolStackDepth].callbacks = malloc(sizeof(struct AutoFreePool_callback) * poolStack[poolStackDepth].callbackListSize); } else if (poolStack[poolStackDepth].numberOfCallbacks >= poolStack[poolStackDepth].callbackListSize) { poolStack[poolStackDepth].callbackListSize *= 2; poolStack[poolStackDepth].callbacks = realloc(poolStack[poolStackDepth].callbacks, sizeof(struct AutoFreePool_callback) * poolStack[poolStackDepth].callbackListSize); } poolStack[poolStackDepth].callbacks[poolStack[poolStackDepth].numberOfCallbacks].callback = callback; poolStack[poolStackDepth].callbacks[poolStack[poolStackDepth].numberOfCallbacks].context = context; poolStack[poolStackDepth].numberOfCallbacks++; } void AutoFreePool_empty() { if (mutexInited) { pthread_mutex_lock(&mutex); } if (poolStackDepth == -1) { if (mutexInited) { pthread_mutex_unlock(&mutex); } return; } if (poolStack[poolStackDepth].addresses != 0) { unsigned int addressIndex; for (addressIndex = 0; addressIndex < poolStack[poolStackDepth].numberOfAddresses; addressIndex++) { free(poolStack[poolStackDepth].addresses[addressIndex]); } poolStack[poolStackDepth].numberOfAddresses = 0; } if (poolStack[poolStackDepth].callbacks != 0) { unsigned int callbackIndex; for (callbackIndex = 0; callbackIndex < poolStack[poolStackDepth].numberOfCallbacks; callbackIndex++) { poolStack[poolStackDepth].callbacks[callbackIndex].callback(poolStack[poolStackDepth].callbacks[callbackIndex].context); } poolStack[poolStackDepth].numberOfCallbacks = 0; } }
1
#include <pthread.h> pthread_t *consumitors; pthread_t productor; sem_t prod_sem, cons_sem; int productor_pointer, consumitor_pointer, prod_end; char **thread_buffer; int thread_buffer_size; int thread_consumitors_num; char * (*productor_extract_data) (void); int (*productor_continue) (void); pthread_mutex_t readBuffer; void (*consumitor_work) ( char * ); void threadCreate__ ( pthread_t * pt, void * (*f) (void *) ) { if ( (pthread_create (pt, 0, f, 0)) ) { printf ("Error, pthread_create\\n"); exit(1); } } void initThread ( void * (*prod_fun)(void *), void * (*cons_fun)(void *) ) { int i; threadCreate__ ( &productor, prod_fun); consumitors = malloc ( thread_consumitors_num * sizeof (pthread_t) ); if ( consumitors == 0 ) { printf ("Error, malloc for thread\\n"); exit (1); } for ( i = 0; i < thread_consumitors_num; i++ ) threadCreate__ ( consumitors +i, cons_fun); pthread_join (productor, 0); for ( i = 0; i < thread_consumitors_num; i++ ) pthread_join ( consumitors[i], 0 ); free (consumitors); } void * productor_function ( void * n) { char * pointer; while ( 1 ) { pointer = productor_extract_data (); if ( productor_continue () ) { prod_end = 1; sem_post (&cons_sem); return 0; } sem_wait (&prod_sem); thread_buffer[productor_pointer] = pointer; productor_pointer = (1+productor_pointer) % thread_buffer_size; sem_post (&cons_sem); } return 0; } void * consumitor_function ( void * n ) { char * pointer; while ( 1 ) { sem_wait (&cons_sem); pthread_mutex_lock(&readBuffer); if ( prod_end ) { if ( productor_pointer == consumitor_pointer ) { pthread_mutex_unlock(&readBuffer); sem_post (&cons_sem); return 0; } } pointer = thread_buffer[consumitor_pointer]; consumitor_pointer = (1+consumitor_pointer) % thread_buffer_size; pthread_mutex_unlock(&readBuffer); sem_post (&prod_sem); consumitor_work (pointer); } return 0; } void thread_init ( int sizeBuffer, int threadsConsumitor, char * (*ped) (void), int (*pc) (void), void (*cw) (char *) ) { thread_buffer_size = sizeBuffer; thread_consumitors_num = threadsConsumitor; productor_extract_data = ped; productor_continue = pc; consumitor_work = cw; } void thread_execute () { sem_init ( &prod_sem, 0, sizeBuffer); sem_init ( &cons_sem, 0, 0); productor_pointer = 0; prod_end = 0; consumitor_pointer = 0; initThread ( productor_function, consumitor_function ); }
0
#include <pthread.h> pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; int isRed1 (int s) { return s == 2; } int isRed2 (int s) { return s == 2; } void * signal1(void* d) { int status = 0; b1: printf("1 -> GREEN\\n"); sleep(2); status = 1; printf("1 -> ORANGE\\n"); sleep(1); status = 2; printf("1 -> RED\\n"); pthread_mutex_unlock(&m1); pthread_mutex_lock(&m2); status = 0; printf("1 -> GREEN\\n"); sleep(2); status = 1; printf("1 -> ORANGE\\n"); sleep(1); status = 2; printf("1 -> RED\\n"); pthread_mutex_unlock(&m1); e1: pthread_exit(0); } void * signal2(void* d) { int status = 2; printf("2 -> RED\\n"); b2: pthread_mutex_lock(&m1); status = 0; printf("2 -> GREEN\\n"); sleep(2); status = 1; printf("2 -> ORANGE\\n"); sleep(1); status = 2; printf("2 -> RED\\n"); pthread_mutex_unlock(&m2); e2: pthread_exit(0); } int main() { pthread_t t1, t2; printf("Start\\n"); pthread_mutex_lock(&m1); pthread_mutex_lock(&m2); printf("Create\\n"); pthread_create(&t1, 0, signal1, 0); pthread_create(&t2, 0, signal2, 0); printf("Join\\n"); pthread_join(t1, 0); pthread_join(t2, 0); printf("End\\n"); return 0; }
1
#include <pthread.h> void * theif (void * param) { int balance; int stolen = 0; pthread_mutex_t * mutex = (pthread_mutex_t *) param; while ( 1 ) { pthread_mutex_lock(mutex); FILE * file = fopen ("account.txt", "r"); fscanf ( file, "%d", &balance); fclose(file); if ( balance == 0 ) { printf("Theif stole total of %d\\n", stolen); pthread_mutex_unlock(mutex); pthread_exit(0); } if ( balance >= 2 ) { stolen += balance / 2; balance -= balance / 2; } else { stolen += 1; balance = 0; } file = fopen ("account.txt", "w"); fprintf(file, "%d", balance); fclose(file); pthread_mutex_unlock(mutex); } } int main() { pthread_t tid1, tid2, tid3, tid4; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_create(&tid1, &attr, theif, &mutex); pthread_create(&tid2, &attr, theif, &mutex); pthread_create(&tid3, &attr, theif, &mutex); pthread_create(&tid4, &attr, theif, &mutex); pthread_join ( tid1, 0); pthread_join ( tid2, 0); pthread_join ( tid3, 0); pthread_join ( tid4, 0); pthread_mutex_destroy(&mutex); FILE * file = fopen ("account.txt", "w"); fprintf(file, "1000"); fclose(file); }
0
#include <pthread.h> pthread_mutex_t prod_cons_mutex; pthread_cond_t prod_cons_cond; int cantProdCons = 1, buffer = 0; int generateItem(); void *producir(void *index) { int fibIndex = (int) index; printf("Estoy en el hilo productor Nª %d..\\n", fibIndex); while ( 1 ) { sleep(1); if ( buffer == 100 ){ printf("Durmiendo de producir..\\n"); }else{ printf("Produciendo..\\n"); pthread_mutex_lock(&prod_cons_mutex); buffer++; pthread_mutex_unlock(&prod_cons_mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit((void*) 0); } void *consumir(void *index) { int fibIndex = (int) index; printf("Estoy en el hilo consumidor Nª %d..\\n", fibIndex); while ( 1 ) { sleep(5); if ( buffer == 0 ){ printf("Durmiendo de consumir..\\n"); }else{ printf("Consumiendo..\\n"); pthread_mutex_lock(&prod_cons_mutex); buffer--; pthread_mutex_unlock(&prod_cons_mutex); printf("Buffer: %d\\n", buffer); } } pthread_exit((void*) 0); } int main (int argc, char *argv[]) { if (argv[1]){ cantProdCons = atoi(argv[1]); } pthread_t productor, consumidor; pthread_mutex_init(&prod_cons_mutex, 0); int rp, rc; for (int i = 0; i < cantProdCons; i++) { rp = pthread_create( &productor, 0, producir, (void *)i ); if ( rp ) { printf("ERROR; return code from pthread_create() is %d\\n", rp); exit(-1); } } for (int i = 0; i < cantProdCons; i++) { rc = pthread_create( &consumidor, 0, consumir, (void *)i ); if ( rc ) { printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } } pthread_exit(0); return 0; }
1
#include <pthread.h> int sum = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_function(void *arg) { int index; pthread_mutex_lock(&mutex); for(index=1;index<6;index++) { sum += index; printf("Thread : %d is running : sum : %d index : %d\\n",*((unsigned int *)arg),sum,index ); sleep(1); } pthread_mutex_unlock(&mutex); } int main() { pthread_t tid[3]; int index = 0; unsigned int thread_num[3] ; for(index=0;index<3;index++) thread_num[index] = index+1; for(index=0;index<3;index++) { if( pthread_create(&tid[index],0,thread_function,&thread_num[index]) < 0 ) { printf("\\nThread %d is not created\\n",(index+1) ); exit(-1); } } for(index=0;index<3;index++) pthread_join(tid[index], 0); printf("Total = %d\\n",sum); return 0; }
0
#include <pthread.h> pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t datosLeidos_lock = PTHREAD_MUTEX_INITIALIZER; sem_t hay_datos; sem_t hay_sitio; int Nhilos, Nnumeros, Tambuffer; int datosLeidos = 0; int *buffer; int in = 0; int out = 0; int esPrimo(int n){ int a = 0, i; for( i = 1; i < (n + 1); i++){ if(n % i == 0){ a++; } } if(a != 2){ return 0; }else{ return 1; } } void meteNumero(int value){ pthread_mutex_lock(&buffer_lock); buffer[in] = value; in = (in + 1) % Tambuffer; pthread_mutex_unlock(&buffer_lock); } void sacaNumero(int *value){ pthread_mutex_lock(&buffer_lock); *value = buffer[out]; out = (out + 1) % Tambuffer; pthread_mutex_unlock(&buffer_lock); } int quedanDatos(int *dato){ int a = 0; if (datosLeidos < Nnumeros){ a = 1; pthread_mutex_lock(&datosLeidos_lock); *dato = datosLeidos; datosLeidos++; pthread_mutex_unlock(&datosLeidos_lock); } return a; } void *productor(void *arg1){ srand ( time(0) ); int i; for (i = 0; i < Nnumeros; i++) { sem_wait(&hay_sitio); meteNumero(rand() % 9999); sem_post(&hay_datos); } pthread_exit(0); } void *consumidor(void* arg2){ int *idHilo = (int *) arg2; int num, idDato; char primo[3]; while (quedanDatos(&idDato)){ sem_wait(&hay_datos); sacaNumero(&num); sem_post(&hay_sitio); if (esPrimo(num)){ strcpy(primo, "si"); } else{ strcpy(primo, "no"); } printf("Hilo numero %d : Ha sido consumido el %d valor generado. El numero %d %s es primo. \\n", *idHilo+1, idDato+1,num, primo); } pthread_exit(0); } int main(int argc, char *argv[]){ if(argc != 4){ printf("Error: numero de argumentos invalido.\\n"); return 1; } if ( (Nhilos = atoi(argv[1]) ) <= 0) { printf("Error: el numero de hilos debe ser mayor que cero.\\n"); return 1; } if ( (Nnumeros = atoi(argv[2]) ) <= 0) { printf("Error: la cantidad de numeros para analizar debe ser mayor que cero.\\n"); return 1; } if ( (Tambuffer = atoi(argv[3]) ) <= 0) { printf("Error el tamano del buffer debe ser mayor que cero.\\n"); return 1; } if (Tambuffer > (Nnumeros / 2)){ printf("Error: el tamano del buffer es demasiado grande.\\n"); return 1; } if ( (buffer=(int*)malloc(Tambuffer * sizeof(int))) == 0) { printf("ERROR al reservar memoria\\n"); return 1; } pthread_t producer, consumer[Nhilos]; sem_init(&hay_datos, 0, 0); sem_init(&hay_sitio, 0, Tambuffer); pthread_create(&producer, 0, productor,(void *) 0); int i; int id[Nhilos]; for (i = 0; i < Nhilos; i++){ id[i] = i; pthread_create(&consumer[i], 0, consumidor,(void*) &id[i]); } pthread_join(producer, 0); for (i = 0 ; i< Nhilos; i++){ pthread_join(consumer[i], 0); } }
1
#include <pthread.h> pthread_mutex_t atomic64; pthread_mutex_t atomic32; int64_t atomicRead64(int64_t* i) { pthread_mutex_lock(&atomic64); int64_t r = *i; pthread_mutex_unlock(&atomic64); return r; } void atomicWrite64(int64_t* i, int64_t v) { pthread_mutex_lock(&atomic64); *i = v; pthread_mutex_unlock(&atomic64); return; } int64_t atomicAdd64(int64_t* i, int64_t v) { pthread_mutex_lock(&atomic64); *i += v; int64_t r = *i; pthread_mutex_unlock(&atomic64); return r; } void atomicSafeUnlock64() { if (pthread_mutex_trylock(&atomic64) > 0) pthread_mutex_unlock(&atomic64); } int32_t atomicRead32(int32_t* i) { pthread_mutex_lock(&atomic32); int64_t r = *i; pthread_mutex_unlock(&atomic32); return r; } void atomicWrite32(int32_t* i, int32_t v) { pthread_mutex_lock(&atomic32); *i = v; pthread_mutex_unlock(&atomic32); return; } int32_t atomicAdd32(int32_t* i, int32_t v) { pthread_mutex_lock(&atomic32); *i += v; int32_t r = *i; pthread_mutex_unlock(&atomic32); return r; } void atomicSafeUnlock32() { if (pthread_mutex_trylock(&atomic32) > 0) pthread_mutex_unlock(&atomic32); }
0
#include <pthread.h> pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; const char * function3(int *test){ static char strBuff[16]; sprintf(strBuff, "%d", *test); printf("%s", strBuff); return strBuff; } void *function1(void *arg){ pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); function3((int *)arg); pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } void *function2(void *arg){ pthread_mutex_lock(&mutex2); pthread_mutex_lock(&mutex1); function3((int *)arg); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); } int main(int argc, char *argv[]){ int i=0,childpid=0; pthread_t a_thread; pthread_attr_t attr; pthread_attr_init(&attr); for(i=0;i<10;){ pthread_create(&a_thread, &attr, function1, (void *)&i); pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); i++; pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } for(i=10;i<20;i++){ pthread_create(&a_thread, &attr, function2, (void *)&i); } if((childpid = fork()) < 0) exit(-1); else if(childpid == 0){ pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); printf("%s", "abcdef"); pthread_mutex_unlock(&mutex1); pthread_mutex_unlock(&mutex2); sleep(10); exit(0); } else{ waitpid(childpid, 0, 0); return 0; } } int proc_wrap_up(){}
1
#include <pthread.h> int mutex_set_int(pthread_mutex_t *mutex, int *i, int value) { pthread_mutex_lock(mutex); *i = value; pthread_mutex_unlock(mutex); return (0); }
0
#include <pthread.h> void InitLock(void *pv_lock) { pthread_mutex_t *p_lock = (pthread_mutex_t *)pv_lock; pthread_mutex_init(p_lock, 0); } void EnterLock(void *pv_lock) { pthread_mutex_t *p_lock = (pthread_mutex_t *)pv_lock; pthread_mutex_lock(p_lock); } void LeaveLock(void *pv_lock) { pthread_mutex_t *p_lock = (pthread_mutex_t *)pv_lock; pthread_mutex_unlock(p_lock); } void UninitLock(void *pv_lock) { pthread_mutex_t *p_lock = (pthread_mutex_t *)pv_lock; pthread_mutex_destroy(p_lock); }
1
#include <pthread.h> int buffer[10]; int rear = 0; int front = -1; int count = 0; int resourceAccess = 0; int readerPriorityFlag = 0; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cons_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t prod_cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mtxData = PTHREAD_MUTEX_INITIALIZER; void *writer(void* param); void *reader(void* param); int main(int argc, char *argv[]) { srand(time(0)); pthread_t thId[10]; int idx; for (idx = 0; idx < 10 / 2; ++idx) { if(pthread_create(&thId[idx], 0, writer, 0) != 0) { fprintf(stderr, "Unable to create writer thread\\n"); exit(1); } if(pthread_create(&thId[idx + 10/2], 0, reader, 0) != 0) { fprintf(stderr, "Unable to create reader thread\\n"); exit(1); } } for (idx = 0; idx < 10; ++idx) { pthread_join(thId[idx], 0); } fprintf(stdout, "Parent thread quitting\\n"); return 0; } void *writer(void* param) { int r = rand() % 500; usleep(r); pthread_mutex_lock(&mtx); while(resourceAccess > 0 || readerPriorityFlag == 1) pthread_cond_wait(&prod_cond,&mtx); --resourceAccess; pthread_mutex_unlock(&mtx); unsigned int tid = (unsigned int)pthread_self(); pthread_mutex_lock(&mtxData); if (front != rear) { int newVal = rand() % 300; buffer[rear] = newVal; rear = (rear + 1) % 10; int readersCount = resourceAccess < 0 ? 0 : resourceAccess; fprintf(stdout, "Data written by thread %u is %d with readers %d\\n", tid, newVal, readersCount); } pthread_mutex_unlock(&mtxData); pthread_mutex_lock(&mtx); ++resourceAccess; pthread_cond_broadcast(&cons_cond); pthread_cond_broadcast(&prod_cond); pthread_mutex_unlock(&mtx); } void *reader(void* param) { int r = rand()%(500); usleep(r); pthread_mutex_lock(&mtx); if(resourceAccess < 0) { readerPriorityFlag = 1; } else { ++resourceAccess; } pthread_mutex_unlock(&mtx); pthread_mutex_lock(&mtxData); if ((front + 1) % 10 != rear) { front = (front + 1) % 10; int val = buffer[front]; unsigned int tid = (unsigned int)pthread_self(); fprintf(stdout, "Data read by thread %u\\n is %d readers %d\\n", tid, val, resourceAccess); } pthread_mutex_unlock(&mtxData); pthread_mutex_lock(&mtx); --resourceAccess; readerPriorityFlag = 0; pthread_cond_broadcast(&cons_cond); pthread_cond_broadcast(&prod_cond); pthread_mutex_unlock(&mtx); }
0
#include <pthread.h> int tickets=10; pthread_mutex_t mutex; pthread_cond_t cond; void* s_func(void* p) { int i=(int)p; while(1) { pthread_mutex_lock(&mutex); if(tickets >0) { printf("I am windows %d,tickets=%d\\n",i,tickets); tickets--; if(0==tickets) pthread_cond_signal(&cond); printf("I am windows %d,sale finish,tickets=%d\\n",i,tickets); }else{ pthread_mutex_unlock(&mutex); pthread_exit(0); } pthread_mutex_unlock(&mutex); sleep(1); } } void* set_func(void* p) { pthread_mutex_lock(&mutex); if(tickets >0) pthread_cond_wait(&cond,&mutex); tickets=10; pthread_mutex_unlock(&mutex); sleep(1); pthread_exit(0); } int main() { pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_t sale[2],setticket; int i; for(i=0;i<2;i++) { pthread_create(&sale[i],0,s_func,(void*)i); } pthread_create(&setticket,0,set_func,0); for(i=0;i<2;i++) { pthread_join(sale[i],0); } pthread_join(setticket,0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> pthread_mutex_t mutex ; pthread_cond_t cond_pro, cond_con ; void* handle(void* arg) { int* pt = (int*)arg ; int soldn = 0 ; int tmp ; while(1) { pthread_mutex_lock(&mutex); while( *pt == 0) { printf("no tickets!\\n"); pthread_cond_signal(&cond_pro); pthread_cond_wait(&cond_con, &mutex); } tmp = *pt ; tmp -- ; *pt = tmp ; soldn ++ ; printf("%u: sold a ticket, %d, left: %d\\n", pthread_self(),soldn, *pt); pthread_mutex_unlock(&mutex); sleep(1); } pthread_mutex_unlock(&mutex); pthread_exit((void*)soldn); } void* handle1(void* arg) { int* pt = (int*)arg ; while(1) { pthread_mutex_lock(&mutex); while(*pt > 0) pthread_cond_wait(&cond_pro, &mutex); *pt = rand() % 20 + 1 ; printf("new tickets: %d\\n", *pt); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond_con); } } int main(int argc, char* argv[]) { int nthds = atoi(argv[1]); int ntickets = atoi(argv[2]); int total = ntickets; pthread_t thd_bak; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_pro, 0); pthread_cond_init(&cond_con, 0); pthread_t* thd_arr = (pthread_t*)calloc(nthds, sizeof(pthread_t)); int* thd_tickets = (int*)calloc(nthds, sizeof(int)); int i ; for(i = 0; i < nthds; i ++) { pthread_create( thd_arr + i, 0, handle, (void*)&ntickets ); } pthread_create(&thd_bak, 0, handle1, (void*)&ntickets ); for(i = 0; i < nthds; i ++) { pthread_join(thd_arr[i], (void*)(thd_tickets + i)); } int sum ; for(sum = 0, i = 0; i < nthds; i ++) { sum += thd_tickets[i] ; } printf("sold: %d, total: %d, current: %d\\n", sum,total, ntickets); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_pro); pthread_cond_destroy(&cond_con); }
1
#include <pthread.h> char* outboard; char* inboard; int nrows; int ncols; int gens_max; pthread_mutex_t lock; } arguments; arguments * struct_alloc_initialize(); void struct_alloc_set_fields(arguments * args, char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max); const pthread_mutex_t init = PTHREAD_MUTEX_INITIALIZER; void *thread_start_routine(void *pthreadId); char* sequential_game_of_life (char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max) { arguments *args; args=struct_alloc_initialize(); struct_alloc_set_fields(args,outboard,inboard,nrows,ncols,gens_max); pthread_t pool_wkthreads[1]; int tc; long i; for(i=0; i< 1; i++) { tc = pthread_create(&pool_wkthreads[i], 0,thread_start_routine, (void *)args); if (tc) { printf("ERROR; return code from pthread_create() is %d\\n", tc); exit(-1); } } for (i = 0; i < 1; ++i) { pthread_join( pool_wkthreads[i], 0); } return args->inboard; } arguments * struct_alloc_initialize() { arguments *args= malloc (sizeof (arguments)); if (args == 0){ printf("ERROR when trying to allocate struct!\\n"); exit(1); } args->outboard=0; args->inboard=0; args->nrows=0; args->ncols=0; args->gens_max=0; args->lock= init; return args; } void struct_alloc_set_fields(arguments * args, char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max) { args->outboard=outboard; args->inboard=inboard; args->nrows=nrows; args->ncols=ncols; args->gens_max=gens_max; } void *thread_start_routine(void *myargs) { arguments *args = (arguments *) myargs; pthread_mutex_lock(&args->lock); const int LDA = args->nrows; int curgen, i, j; for (curgen = 0; curgen < args->gens_max; curgen++) { for (i = 0; i < args->nrows; i++) { for (j = 0; j < args->ncols; j++) { const int inorth = mod (i-1, args->nrows); const int isouth = mod (i+1, args->nrows); const int jwest = mod (j-1, args->ncols); const int jeast = mod (j+1, args->ncols); const char neighbor_count = (args->inboard[(inorth) + LDA*(jwest)]) + (args->inboard[(inorth) + LDA*(j)]) + (args->inboard[(inorth) + LDA*(jeast)]) + (args->inboard[(i) + LDA*(jwest)]) + (args->inboard[(i) + LDA*(jeast)]) + (args->inboard[(isouth) + LDA*(jwest)]) + (args->inboard[(isouth) + LDA*(j)]) + (args->inboard[(isouth) + LDA*(jeast)]); (args->outboard[(i) + LDA*(j)]) = alivep (neighbor_count, (args->inboard[(i) + LDA*(j)])); } } do { char* temp = args->outboard; args->outboard = args->inboard; args->inboard = temp; } while(0); } pthread_mutex_unlock(&args->lock); }
0
#include <pthread.h> void *do_image(void *); void *do_chat(void *); int pushClient(int); int popClient(int); int pushClientImage(int); int popClientImage(int); pthread_t thread; pthread_mutex_t mutex; pthread_mutex_t mutex_image; int list_c[10]; int list_c_i[10]; char greeting[]="Welcome to chatting room\\n"; char CODE200[]="Sorry No More Connection\\n"; main(int argc, char *argv[]) { int c_socket, c_socket_i, s_socket, s_socket_i; struct sockaddr_in s_addr, s_addr_i, c_addr, c_addr_i; int len; int i, j, n; int res; if(argc < 2) { printf("usage: %s port_number\\n", argv[0]); exit(-1); } if(pthread_mutex_init(&mutex, 0) != 0) { printf("Can not create mutex\\n"); return -1; } if(pthread_mutex_init(&mutex_image, 0) != 0) { printf("Can not create mutex\\n"); return -1; } s_socket = socket(PF_INET, SOCK_STREAM, 0); memset(&s_addr, 0, sizeof(s_addr)); s_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(atoi(argv[1])); if(bind(s_socket, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) { printf("Can not Bind\\n"); return -1; } if(listen(s_socket, 10) == -1) { printf("listen Fail\\n"); return -1; } s_socket_i = socket(PF_INET, SOCK_STREAM, 0); memset(&s_addr, 0, sizeof(s_addr)); s_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(atoi(argv[1])+1); if(bind(s_socket_i, (struct sockaddr *)&s_addr, sizeof(s_addr)) == -1) { printf("Can not Bind\\n"); return -1; } if(listen(s_socket_i, 10) == -1) { printf("listen Fail\\n"); return -1; } for(i = 0; i < 10; i++){ list_c[i] = -1; list_c_i[i] = -1; } while(1) { len = sizeof(c_addr); c_socket = accept(s_socket, (struct sockaddr *)&c_addr, &len); res = pushClient(c_socket); if(res < 0) { write(c_socket, CODE200, strlen(CODE200)); close(c_socket); } else { len = sizeof(c_addr_i); c_socket_i = accept(s_socket_i, (struct sockaddr *)&c_addr_i, &len); res = pushClientImage(c_socket_i); if(res < 0){ write(c_socket, CODE200, strlen(CODE200)); close(c_socket_i); close(c_socket); }else{ write(c_socket, greeting, strlen(greeting)); pthread_create(&thread, 0, do_chat, (void *)c_socket); pthread_create(&thread, 0, do_image, (void *)c_socket_i); } } } } void *do_image(void *arg){ int c_socket = (int)arg; char chatData[1024]; int i, n; while(1) { memset(chatData, 0, sizeof(chatData)); if((n = read(c_socket, chatData, sizeof(chatData))) > 0) { printf("%d\\n", n); for(i = 0; i < 10; i++) if(list_c_i[i] != -1 && list_c_i[i] != c_socket) write(list_c_i[i], chatData, n); } else { popClient(c_socket); break; } } } void *do_chat(void *arg) { int c_socket = (int)arg; char chatData[1024]; int i, n; while(1) { memset(chatData, 0, sizeof(chatData)); if((n = read(c_socket, chatData, sizeof(chatData))) != 0) { for(i = 0; i < 10; i++) if(list_c[i] != -1 && list_c[i] != c_socket) write(list_c[i], chatData, n); } else { popClient(c_socket); break; } } } int pushClient(int c_socket) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); if(list_c[i] == -1) { list_c[i] = c_socket; pthread_mutex_unlock(&mutex); return i; } pthread_mutex_unlock(&mutex); } if(i == 10) return -1; } int popClient(int s) { int i; close(s); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); if(s == list_c[i]) { list_c[i] = -1; pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); } return 0; } int pushClientImage(int c_socket) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex_image); if(list_c_i[i] == -1) { list_c_i[i] = c_socket; pthread_mutex_unlock(&mutex_image); return i; } pthread_mutex_unlock(&mutex_image); } if(i == 10) return -1; } int popClientImage(int s) { int i; close(s); for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex_image); if(s == list_c_i[i]) { list_c_i[i] = -1; pthread_mutex_unlock(&mutex_image); break; } pthread_mutex_unlock(&mutex_image); } return 0; }
1
#include <pthread.h> extern int _shutdown; extern struct s_conf conf; struct gps_data_t *gpsd_data = 0, *gpsd_data_new = 0; pthread_t t_gps_update; pthread_mutex_t mutex_gps; double db_interval = 5.0f; double db_last = 0.0f; static void *gpsd_update_thread(void *arg) { logger("GPS: Update thread initialized"); int gps_fix = 0; while(!_shutdown) { if(gps_waiting(gpsd_data)) { pthread_mutex_lock(&mutex_gps); gps_poll(gpsd_data); pthread_mutex_unlock(&mutex_gps); if(get_timestamp_double() >= (db_last + db_interval)) { db_last = get_timestamp_double(); switch(gpsd_data->fix.mode) { case MODE_NOT_SEEN: case MODE_NO_FIX: gps_fix = 0; break; case MODE_2D: gps_fix = 1; break; case MODE_3D: gps_fix = 2; break; } sqlite_add_gps( gpsd_data->fix.latitude, gpsd_data->fix.longitude, gpsd_data->fix.altitude, gpsd_data->fix.speed * 3.6f, gpsd_data->fix.track, gpsd_data->satellites_used, gps_fix); } } usleep(100000); } pthread_exit(0); } void gpsd_init(void) { gpsd_data = gps_open(conf.gpsd_host, conf.gpsd_port); gpsd_data_new = malloc(sizeof(struct gps_data_t)); if(gpsd_data == 0) { logger("GPS: Unable to connect to GPS daemon, location data will be unavailable"); return; } else { logger("GPS: Connection to GPS daemon established"); } gps_stream(gpsd_data, WATCH_NEWSTYLE, 0); gpsd_data_new = malloc(sizeof(struct gps_data_t)); pthread_mutex_init(&mutex_gps, 0); pthread_create(&t_gps_update, 0, gpsd_update_thread, 0); } struct gps_data_t *gpsd_update(void) { if(gpsd_data == 0) { return 0; } pthread_mutex_lock(&mutex_gps); memcpy(gpsd_data_new, gpsd_data, sizeof(struct gps_data_t)); pthread_mutex_unlock(&mutex_gps); return gpsd_data_new; } void gpsd_uninit(void) { if(gpsd_data != 0) { pthread_cancel(t_gps_update); pthread_join(t_gps_update, 0); gps_close(gpsd_data); logger("GPS: Disconnected"); } }
0
#include <pthread.h> int port, portlow, porthigh; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *scan(void *arg) { int sd; struct sockaddr_in servaddr; struct servent *srvport; struct hostent* hp; char *argv1 = (char*)arg; hp = gethostbyname(argv1); if (hp == 0) { herror("gethostbyname() failed"); exit(-1); } bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr = *((struct in_addr *)hp->h_addr); while (port < porthigh) { if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("socket() failed"); exit(-1); } pthread_mutex_lock(&lock); servaddr.sin_port = htons(port); if (connect(sd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == 0) { srvport = getservbyport(htons(port), "tcp"); if (srvport == 0) printf("Open: %d (unknown)\\n", port); else printf("Open: %d (%s)\\n", port, srvport->s_name); fflush(stdout); } port++; close(sd); pthread_mutex_unlock(&lock); } } int main(int argc, char *argv[]) { pthread_t threads[255]; int thread_num; int i; if (argc != 5) { fprintf(stderr, "Usage: %s <address> <portlow> <porthigh> <num threads>\\n", argv[0]); exit(-1); } thread_num = atoi(argv[4]); if (thread_num > 255) fprintf(stderr, "too many threads requested"); portlow = atoi(argv[2]); porthigh = atoi(argv[3]); port = portlow; fprintf(stderr, "Running scan...\\n"); for (i = 0; i < thread_num; i++) if (pthread_create(&threads[i], 0, scan, argv[1]) != 0) fprintf(stderr, "error creating thread"); for (i = 0; i < thread_num; i++) pthread_join(threads[i], 0); return 0; }
1
#include <pthread.h> int randomNum, divisor=2; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; void *send_random(void *lfdInput){ int parameter, checkPrime=0; memcpy(&parameter,(int *)lfdInput,sizeof(int)); int cfd=0; char sBuffer[1044], rBuffer[1044]; memset(sBuffer, '0', sizeof(sBuffer)); memset(rBuffer, '0', sizeof(rBuffer)); while(divisor!=sqrt(randomNum)){ cfd=accept(parameter, (struct sockaddr*)0, 0); snprintf(sBuffer, sizeof(sBuffer), "%d", randomNum); write(cfd, sBuffer, strlen(sBuffer)); snprintf(sBuffer, sizeof(sBuffer), "%d", divisor); write(cfd, sBuffer, strlen(sBuffer)); pthread_mutex_lock(&count_mutex); divisor++; pthread_mutex_unlock(&count_mutex); checkPrime=recv(cfd, rBuffer, strlen(rBuffer), 0); if(checkPrime==1){ printf("%d is not a prime number!", randomNum); return 0; } } close(cfd); sleep(1); } int main(int argc, char *argv[]){ randomNum=rand()%(32767 -1)+(32767 -1000000); randomNum=randomNum/(-10); int lfd=0, threadNum=0, i=0; struct sockaddr_in servAdd; lfd=socket(AF_INET, SOCK_STREAM, 0); memset(&servAdd, '0', sizeof(servAdd)); servAdd.sin_addr.s_addr=inet_addr("192.168.1.100"); servAdd.sin_port=htons(4488); servAdd.sin_family=AF_INET; bind(lfd, (struct sockaddr*)&servAdd, sizeof(servAdd)); listen(lfd, 5); pthread_t threadPool[5]; for(threadNum=0; threadNum < 5; threadNum++){ fflush(stdout); int Error = pthread_create(&threadPool[threadNum],0,send_random,(void *)&lfd); if (Error) { printf("Error: creating threads... program exited."); return -1; } } for(i=0; i < 5; i++){ pthread_join(threadPool[i],(void **)0); } printf("%d is a prime number!", randomNum); return 0; }
0
#include <pthread.h> { int Buffer; sem_t Bloqueado; }Tarjeta_Red; pthread_mutex_t Mutex_Requerido = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t Cond_Tarjeta_Disponible = PTHREAD_COND_INITIALIZER; void Inicio(Tarjeta_Red *TR); void Envio_Recepcion_Datos(Tarjeta_Red *TR, int IRQ); void Cierre_Envio_Recepcion_Tarjeta_Red(Tarjeta_Red *TR); void Habilitacion_Envio_Recepcion_Tarjeta_Red(Tarjeta_Red *TR); void *Recepcion_Peticion(Tarjeta_Red *TR); void Insertar_Peticion_Buffer(Tarjeta_Red *TR); void *Envio_Peticion(Tarjeta_Red *TR); void Eliminar_Peticion_Buffer(Tarjeta_Red *TR); int main() { Tarjeta_Red TR; TR.Buffer = 0; sem_init(&TR.Bloqueado, 0, 1); Inicio(&TR); return 0; } void Inicio(Tarjeta_Red *TR) { int Num; srand(time(0)); while(1) { Num = (rand() % 2); Cierre_Envio_Recepcion_Tarjeta_Red(TR); Habilitacion_Envio_Recepcion_Tarjeta_Red(TR); Envio_Recepcion_Datos(TR, Num); } } void Envio_Recepcion_Datos(Tarjeta_Red *TR, int IRQ) { int Valor; pthread_t P1, P2; pthread_mutex_lock(&Mutex_Requerido); if((sem_getvalue(&TR->Bloqueado, &Valor) == 0) && (Valor == 1)) { if(IRQ == 0) { Recepcion_Peticion(TR); }else{ Envio_Peticion(TR); } pthread_mutex_unlock(&Mutex_Requerido); pthread_cond_signal(&Cond_Tarjeta_Disponible); }else{ printf("\\nFirewall Bloqueo el Envio y Recepcion de Datos...\\n"); system("sleep 2.0"); } } void Cierre_Envio_Recepcion_Tarjeta_Red(Tarjeta_Red *TR) { sem_wait(&TR->Bloqueado); } void Habilitacion_Envio_Recepcion_Tarjeta_Red(Tarjeta_Red *TR) { sem_post(&TR->Bloqueado); } void *Recepcion_Peticion(Tarjeta_Red *TR) { if(TR->Buffer < 21) { Insertar_Peticion_Buffer(TR); }else{ printf("\\nBuffer LLeno...\\n"); system("sleep 2.0"); } } void Insertar_Peticion_Buffer(Tarjeta_Red *TR) { TR->Buffer = (TR->Buffer + 1); printf("\\nNuevo Paquete, para enviar...\\n"); printf("Capacidad Buffer ->: %d\\n", TR->Buffer); system("sleep 1.0"); } void *Envio_Peticion(Tarjeta_Red *TR) { if(TR->Buffer > 0) { Eliminar_Peticion_Buffer(TR); }else{ printf("\\nBuffer Vacio...\\n"); system("sleep 2.0"); } } void Eliminar_Peticion_Buffer(Tarjeta_Red *TR) { TR->Buffer = (TR->Buffer - 1); printf("\\nPaquete, enviado...\\n"); printf("Capacidad Buffer ->: %d\\n", TR->Buffer); system("sleep 1.0"); }
1
#include <pthread.h> struct s { int datum; struct s *next; }; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = 0; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } pthread_mutex_t mutex[10]; struct s *slot[10]; void *t_fun(void *arg) { int i; for (i=0; i<10; i++) { pthread_mutex_lock(&mutex[i]); list_add(new(10 +i), slot[i]); pthread_mutex_unlock(&mutex[i]); } return 0; } int main () { int j; struct s *p; pthread_t t1; for (j=0; j<10; j++) { pthread_mutex_init(&mutex[j],0); slot[j] = new(0); } pthread_create(&t1, 0, t_fun, 0); for (j=0; j<10; j++) { pthread_mutex_lock(&mutex[j]); list_add(new(j), slot[j]); p = slot[j]->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&mutex[j]); } return 0; }
0
#include <pthread.h> { void * (*start_routine)(void *); void * arg; pthread_mutex_t lock; pthread_cond_t wait; struct itimerval itimer; } wrapper_t; static void * wrapper_routine(void *); int gprof_pthread_create(pthread_t * thread, pthread_attr_t * attr, void * (*start_routine)(void *), void * arg) { wrapper_t wrapper_data; int i_return; wrapper_data.start_routine = start_routine; wrapper_data.arg = arg; getitimer(ITIMER_PROF, &wrapper_data.itimer); pthread_cond_init(&wrapper_data.wait, 0); pthread_mutex_init(&wrapper_data.lock, 0); pthread_mutex_lock(&wrapper_data.lock); i_return = pthread_create(thread, attr, &wrapper_routine, &wrapper_data); if(i_return == 0) { pthread_cond_wait(&wrapper_data.wait, &wrapper_data.lock); } pthread_mutex_unlock(&wrapper_data.lock); pthread_mutex_destroy(&wrapper_data.lock); pthread_cond_destroy(&wrapper_data.wait); return i_return; } static void * wrapper_routine(void * data) { void * (*start_routine)(void *) = ((wrapper_t*)data)->start_routine; void * arg = ((wrapper_t*)data)->arg; setitimer(ITIMER_PROF, &((wrapper_t*)data)->itimer, 0); pthread_mutex_lock(&((wrapper_t*)data)->lock); pthread_cond_signal(&((wrapper_t*)data)->wait); pthread_mutex_unlock(&((wrapper_t*)data)->lock); return start_routine(arg); }
1
#include <pthread.h> int addLobby(char *nazev); int removeLobby(int index); int addPlayer(int indexHrac, int indexLobby); int removePlayer(int indexHrac, int indexLobby); struct Lobby* boostLobby(); struct Lobby* reduceLobby(int index); int initLobby(); int uvolniLobby(); struct Lobby *lobbies; int length_lobbies = 0; int id_plus_lobby = 1; pthread_mutex_t lockLobby = PTHREAD_MUTEX_INITIALIZER; int initLobby() { pthread_mutex_lock(&lockLobby); lobbies = (struct Lobby*)malloc(sizeof(struct Lobby) * (length_lobbies + 1)); memset(&lobbies[0].hraciLobby, -1, sizeof(int) * 4); strcpy(lobbies[0].lobbyName, "default"); lobbies[0].pocetHracu = 0; lobbies[0].idLobby = id_plus_lobby++; length_lobbies += 1; pthread_mutex_unlock(&lockLobby); } int addLobby(char *nazev) { for(int i = 0; i < length_lobbies; i++) { if(strcmp(lobbies[i].lobbyName, nazev) == 0) { return 1; } } pthread_mutex_lock(&lockLobby); lobbies = boostLobby(); memset(&lobbies[length_lobbies - 1].hraciLobby, -1, sizeof(int) * 4); memset(&lobbies[length_lobbies - 1].lobbyName, 0, sizeof(lobbies[length_lobbies - 1].lobbyName)); memcpy(lobbies[length_lobbies - 1].lobbyName, nazev, sizeof(nazev)); pthread_mutex_unlock(&lockLobby); return 0; } int removeLobby(int index) { if(index < 0 || index >= length_lobbies) { printf("Zadany index %d je mimo ramec lobbies!\\n", index); return 1; } pthread_mutex_lock(&lockLobby); lobbies = reduceLobby(index); pthread_mutex_unlock(&lockLobby); return 0; } struct Lobby* boostLobby() { struct Lobby *moreLobbies; moreLobbies = (struct Lobby*)malloc(sizeof(struct Lobby) * (length_lobbies + 1)); for(int i = 0; i < length_lobbies; i++) { memcpy(moreLobbies[i].hraciLobby, lobbies[i].hraciLobby, sizeof(lobbies[i].hraciLobby)); strcpy(moreLobbies[i].lobbyName, lobbies[i].lobbyName); moreLobbies[i].idLobby = lobbies[i].idLobby; moreLobbies[i].pocetHracu = lobbies[i].pocetHracu; moreLobbies[i].idLobby = lobbies[i].idLobby; } moreLobbies[length_lobbies].pocetHracu = 0; moreLobbies[length_lobbies].idLobby = id_plus_lobby++; free(lobbies); length_lobbies += 1; return moreLobbies; } struct Lobby* reduceLobby(int index) { struct Lobby *lessLobbies; lessLobbies = (struct Lobby*)malloc(sizeof(struct Lobby) * (length_lobbies - 1)); int j = 0; for(int i = 0; i < length_lobbies; i++) { if(i != index) { memcpy(lessLobbies[j].hraciLobby, lobbies[i].hraciLobby, sizeof(lobbies[i].hraciLobby)); strcpy(lessLobbies[j].lobbyName, lobbies[i].lobbyName); lessLobbies[j].idLobby = lobbies[i].idLobby; lessLobbies[j].pocetHracu = lobbies[i].pocetHracu; lessLobbies[j].idLobby = lobbies[i].idLobby; j++; } } free(lobbies); length_lobbies -= 1; return lessLobbies; } int addPlayer(int indexHrac, int indexLobby) { if(indexHrac < 0 || indexHrac >= length_hraci) { printf("[ADD]Index hrace %d neni ve stanovenych mezich!", indexHrac); return 1; } if(indexLobby < 0 || indexLobby >= length_lobbies) { printf("[ADD]Index lobby %d neni ve stanovenych mezich!", indexHrac); return 1; } int ind = -1; if(hraci[indexHrac].init == 0) { printf("[ADD]Na zadanem indexu %d neni zadny hrac!", indexHrac); return 2; } pthread_mutex_lock(&lockLobby); int nasel = 0; for(int i = 0; i < 4; i++) { if(lobbies[indexLobby].hraciLobby[i] == -1) { nasel = 1; lobbies[indexLobby].hraciLobby[i] = indexHrac; break; } } if(nasel == 0) { pthread_mutex_unlock(&lockLobby); printf("[ADD]Neni jiz misto v lobby s indexem %d!\\n", indexLobby); return 3; } lobbies[indexLobby].pocetHracu += 1; pthread_mutex_unlock(&lockLobby); return 0; } int removePlayer(int indexHrac, int indexLobby) { if(indexHrac < 0 || indexHrac >= length_hraci) { printf("[RM]Index hrace %d neni ve stanovenych mezich!", indexHrac); return 1; } if(indexLobby < 0 || indexLobby >= length_lobbies) { printf("[RM]Index lobby %d neni ve stanovenych mezich!", indexHrac); return 1; } int ind = -1; if(hraci[indexHrac].init == 0) { printf("[RM]Na zadanem indexu %d neni zadny hrac!", indexHrac); return 2; } pthread_mutex_lock(&lockLobby); int nasel = 0; for(int i = 0; i < 4; i++) { if(lobbies[indexLobby].hraciLobby[i] == indexHrac) { nasel = 1; lobbies[indexLobby].hraciLobby[i] = -1; break; } } if(nasel == 0) { pthread_mutex_unlock(&lockLobby); printf("[RM]Nenasel se hrac v lobby %d s indexem %d!\\n", indexLobby, indexHrac); return 3; } lobbies[indexLobby].pocetHracu -= 1; pthread_mutex_unlock(&lockLobby); return 0; } int uvolniLobby() { free(lobbies); }
0
#include <pthread.h> double res = .0, a = .0, b = 2 * atan(1.0), h; int n = 100000, loc_n; pthread_mutex_t mut; int thread_count; void parsearg(int, char **); double f(double); void * func(void *); double integate(double, double); int main(int argc, char ** argv) { parsearg(argc, argv); int s; h = (b - a) / n; loc_n = n / thread_count; pthread_t * arr = malloc(thread_count * sizeof(pthread_t)); s = pthread_mutex_init(&mut, 0); if(s) do { errno = s; perror("main(): pthread_mutex_init"); exit(1); } while (0); for(int i = 0; i < thread_count; i++) { s = pthread_create(&arr[i], 0, func, (void*) i); if(s) do { errno = s; perror("main(): pthread_create"); exit(1); } while (0); } for(int i = 0; i < thread_count; i++) { s = pthread_join(arr[i], 0); if(s) do { errno = s; perror("main(): pthread_join"); exit(1); } while (0); } fprintf(stdout, "INTEGRAL: %g\\n", res); pthread_mutex_destroy(&mut); free(arr); return 0; } double f(double x) { return cos(x); } void * func(void * arg) { double loc_a, loc_b, ans; int my_rank = (int) arg; loc_a = a + my_rank * loc_n * h; loc_b = loc_a + loc_n * h; ans = integate(loc_a, loc_b); pthread_mutex_lock(&mut); res += ans; pthread_mutex_unlock(&mut); fprintf(stdout, "%lu:\\t%g\\n", pthread_self(), ans); return 0; } double integate(double loc_a, double loc_b) { double integ = (f(loc_a) + f(loc_b)) * 0.5, x = loc_a; for (int i = 1; i <= loc_n - 1; ++i) { x = loc_a + i * h; integ += f(x); } integ = integ * h; return integ; } void parsearg(int argc, char ** argv) { int res, ind; const char * short_opt = "hp:"; const struct option long_opt[] = { {"help", no_argument, 0, 'h'}, {"pthread",required_argument, 0, 'p'}, {0, 0, 0, 0} }; while((res = getopt_long(argc, argv, short_opt, long_opt, &ind)) != -1) { switch(res) { case 'h': fprintf(stdout, "-p | --ptherad [int]\\tthread_count\\n"); exit(-1); break; case 'p': thread_count = atoi(optarg); break; case '?': break; default: break; } } }
1
#include <pthread.h> int B[4]; int in_ptr, out_ptr; int count; pthread_cond_t full, empty; pthread_mutex_t lock; void *thread_A(void *arg) { int i, data; for (i = 0; i < 20; i++) { data = i; pthread_mutex_lock(&lock); while (count >= 4) pthread_cond_wait(&full, &lock); count++; B[in_ptr++] = data; printf("thread_A(): put(%d)\\n", data); if (in_ptr >= 4) in_ptr = 0; pthread_mutex_unlock(&lock); pthread_cond_broadcast(&empty); } pthread_exit(0); } void *thread_B(void *arg) { int i, data; for (i = 0; i < 20; i++) { sleep(1); pthread_mutex_lock(&lock); while (count == 0) pthread_cond_wait(&empty, &lock); count--; data = B[out_ptr++]; printf("thread_B(): get() %d.\\n", data); if (out_ptr >= 4) out_ptr = 0; pthread_mutex_unlock(&lock); pthread_cond_broadcast(&full); } pthread_exit(0); } int main() { pthread_t t1; pthread_t t2; in_ptr = 0; out_ptr = 0; count = 0; pthread_mutex_init(&lock, 0); pthread_cond_init(&full, 0); pthread_cond_init(&empty, 0); pthread_setconcurrency(2); pthread_create(&t1, 0, (void *)thread_A, 0); pthread_create(&t2, 0, (void *)thread_B, 0); pthread_join(t1, 0); pthread_join(t2, 0); }
0
#include <pthread.h> char buf[1024]; int occupied; int nextin; int nextout; pthread_mutex_t lock; pthread_cond_t more; pthread_cond_t less; } buffer_t; void buffer_init(buffer_t *); void buffer_free(buffer_t *); void producer(buffer_t *, char); char consumer(buffer_t *); void producer_driver(buffer_t *); void consumer_driver(buffer_t *); int main() { int zfd; pid_t pid; buffer_t *buf; zfd = open("/dev/zero", O_RDWR); buf = (buffer_t *)mmap(0, sizeof(buffer_t), PROT_READ | PROT_WRITE, MAP_SHARED, zfd, 0); close(zfd); buffer_init(buf); if ((pid = fork()) == 0) { printf("input something:\\n"); producer_driver(buf); exit(0); } else { consumer_driver(buf); waitpid(pid, 0, 0); buffer_free(buf); munmap(buf, sizeof(buffer_t)); return 0; } } void buffer_init(buffer_t *b) { pthread_mutexattr_t mattr; pthread_condattr_t cattr; if (b == 0) return; bzero(b->buf, 1024); b->occupied = b->nextin = b->nextout = 0; pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&b->lock, &mattr); pthread_mutexattr_destroy(&mattr); pthread_condattr_init(&cattr); pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); pthread_cond_init(&b->more, &cattr); pthread_cond_init(&b->less, &cattr); pthread_condattr_destroy(&cattr); } void buffer_free(buffer_t *b) { if (b == 0) return; bzero(b->buf, 1024); b->occupied = b->nextin = b->nextout = 0; pthread_mutex_destroy(&b->lock); pthread_cond_destroy(&b->more); pthread_cond_destroy(&b->less); } void producer(buffer_t *b, char item) { pthread_mutex_lock(&b->lock); while (b->occupied >= 1024) pthread_cond_wait(&b->less, &b->lock); assert(b->occupied < 1024); b->buf[b->nextin++] = item; b->nextin %= 1024; b->occupied++; pthread_cond_signal(&b->more); pthread_mutex_unlock(&b->lock); } char consumer(buffer_t *b) { char item; pthread_mutex_lock(&b->lock); while (b->occupied <= 0) pthread_cond_wait(&b->more, &b->lock); assert(b->occupied > 0); item = b->buf[b->nextout++]; b->nextout %= 1024; b->occupied--; pthread_cond_signal(&b->less); pthread_mutex_unlock(&b->lock); return item; } void producer_driver(buffer_t *b) { int item; for (;;) { item = getchar(); if (item == EOF) { producer(b, '\\0'); break; } producer(b, (char)item); } } void consumer_driver(buffer_t *b) { char item; for (;;) { if ((item = consumer(b)) == '\\0') break; putchar(item); } }
1
#include <pthread.h> int num=0; pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t qready=PTHREAD_COND_INITIALIZER; void* thread_func(void *arg) { int param=(int)arg; int count=1; while(1) { pthread_mutex_lock(&mylock); while(param!=num) pthread_cond_wait(&qready,&mylock); printf("%c\\n",param+'A'); num=(num+1)%3; pthread_mutex_unlock(&mylock); pthread_cond_broadcast(&qready); } } int main() { int ret=0; int i=0; pthread_t tid[3]; for(i=0;i<3;i++) pthread_create(&tid[i],0,thread_func,(void *)i); getchar(); return 0; }
0
#include <pthread.h> int ncount; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* do_loop(void *data) { int i; pthread_mutex_lock(&mutex); for (i = 0; i < 10; i++) { printf("loop1 : %d\\n", ncount); ncount ++; sleep(1); } pthread_mutex_unlock(&mutex); } void* do_loop2(void *data) { int i; pthread_mutex_lock(&mutex); for (i = 0; i < 10; i++) { printf("loop2 : %d\\n", ncount); ncount ++; sleep(1); } pthread_mutex_unlock(&mutex); } int main() { int thr_id; pthread_t p_thread[2]; int status; int a = 1; ncount = 0; thr_id = pthread_create(&p_thread[0], 0, do_loop, (void *)&a); sleep(1); thr_id = pthread_create(&p_thread[1], 0, do_loop2, (void *)&a); pthread_join(p_thread[0], (void *) &status); pthread_join(p_thread[1], (void *) &status); status = pthread_mutex_destroy(&mutex); printf("code = %d \\n", status); printf("programing is end\\n"); return 0; }
1
#include <pthread.h> int SharedVariable = 0; pthread_mutex_t lock_x; static pthread_barrier_t barrier; bool isPositiveNumber(char number[]) { int i = 0; if (number[0] == '-') return 0; for (; number[i] != 0; i++) { if (!isdigit(number[i])) return 0; } return 1; } void SimpleThread(int which) { int num, val, z; for(num = 0; num < 20; num++) { pthread_mutex_lock(&lock_x); if (random() > 32767 / 2) usleep(500); pthread_mutex_unlock(&lock_x); val = SharedVariable; printf("*** thread %d sees value %d\\n", which, val); SharedVariable = val + 1; z = pthread_barrier_wait(&barrier); if(z!=0 && z != PTHREAD_BARRIER_SERIAL_THREAD){ fprintf(stderr, "error: pthread_barrier_wait, z: %d\\n", z); } } val = SharedVariable; printf("Thread %d sees final value %d\\n", which, val); } int tid; double stuff; } thread_data_t; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; SimpleThread(data->tid); pthread_exit(0); } int main(int argc, char *argv[]) { bool isNum = 0; char *endptr; int i, rc, x, s; if( argc == 2 ) { printf("The argument supplied is %s\\n", argv[1]); } else { printf("One argument expected.\\n"); return 0; } isNum = isPositiveNumber(argv[1]); if(isNum){ printf("The input value is a positive number\\n"); } else { printf("The input value is not a positive number\\n"); return 0; } x = strtol(argv[1], &endptr, 10); pthread_t thr[x]; thread_data_t thr_data[x]; pthread_mutex_init(&lock_x, 0); s = pthread_barrier_init(&barrier, 0, x); if(s!=0){ fprintf(stderr, "error: pthread_barrier_init, s: %d\\n", s); return 1; } for (i = 0; i < x; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < x; ++i) { pthread_join(thr[i], 0); } return 0; }
0
#include <pthread.h> int main() { pthread_mutex_t m; pthread_cond_t c; pthread_condattr_t at; struct timespec ts0, ts1, ts2; int res; u64 sleep; pthread_mutex_init(&m, 0); pthread_condattr_init(&at); pthread_condattr_setclock(&at, CLOCK_MONOTONIC); pthread_cond_init(&c, &at); clock_gettime(CLOCK_MONOTONIC, &ts0); ts1 = ts0; ts1.tv_sec += 2; pthread_mutex_lock(&m); do { res = pthread_cond_timedwait(&c, &m, &ts1); } while (res == 0); pthread_mutex_unlock(&m); clock_gettime(CLOCK_MONOTONIC, &ts2); sleep = (u64)ts2.tv_sec * 1000000000 + ts2.tv_nsec - ((u64)ts0.tv_sec * 1000000000 + ts0.tv_nsec); if (res != ETIMEDOUT) exit(printf("bad return value %d, want %d\\n", res, ETIMEDOUT)); if (sleep < 1000000000) exit(printf("bad sleep duration %lluns, want %dns\\n", sleep, 1000000000)); fprintf(stderr, "OK\\n"); }
1
#include <pthread.h> buffer_t buffer[5]; int buffer_index; pthread_mutex_t buffer_mutex; sem_t full_sem; sem_t empty_sem; void insertbuffer(buffer_t value) { if (buffer_index < 5) { buffer[buffer_index++] = value; } else { printf("Buffer overflow\\n"); } } buffer_t dequeuebuffer() { if (buffer_index > 0) { return buffer[--buffer_index]; } else { printf("Buffer underflow\\n"); } return 0; } void *producer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { value = rand() % 100; sem_wait(&full_sem); pthread_mutex_lock(&buffer_mutex); insertbuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&empty_sem); printf("Producer %d added %d to buffer\\n", thread_numb, value); } pthread_exit(0); } void *consumer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { sem_wait(&empty_sem); pthread_mutex_lock(&buffer_mutex); value = dequeuebuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&full_sem); printf("Consumer %d dequeue %d from buffer\\n", thread_numb, value); } pthread_exit(0); } int main(int argc, int **argv) { buffer_index = 0; pthread_mutex_init(&buffer_mutex, 0); sem_init(&full_sem, 0, 5); sem_init(&empty_sem, 0, 0); pthread_t thread[6]; int thread_numb[6]; int i; for (i = 0; i < 6; ) { thread_numb[i] = i; pthread_create(thread + i, 0, producer, thread_numb + i); i++; thread_numb[i] = i; pthread_create(&thread[i], 0, consumer, &thread_numb[i]); i++; } for (i = 0; i < 6; i++) pthread_join(thread[i], 0); pthread_mutex_destroy(&buffer_mutex); sem_destroy(&full_sem); sem_destroy(&empty_sem); return 0; }
0
#include <pthread.h> pthread_t thread[11]; pthread_mutex_t mut; int data[9][9]; int a = 0, b = 0, i = 0, j = 0, k = 0, m = 0, err = 0, err1 = 0; void read_data() { FILE *fp = fopen("sudoku.txt", "r"); if(fp == 0) { printf("cannot open the file\\n"); exit(0); } for(i = 0; i < 9; i++) { for(j = 0; j < 9; j++) { fscanf(fp, "%d", &data[i][j]); } } printf("\\n"); fclose(fp); fp = 0; } void *thread1() { for(a = 0; a < 9; a++) { pthread_mutex_lock(&mut); err = 0; int flag[10] = {0,0,0,0,0,0,0,0,0,0}; for(j = 0; j < 9; j++) { flag[data[a][j]] = 1; } for(k = 1; k < 10; k++) { if(flag[k] == 0) { err++; if(err == 1) { printf("row = %d, Missing digit = ", a+1); } printf("%d ", k); } } if(err != 0) { printf("\\n"); err1++; } pthread_mutex_unlock(&mut); } pthread_exit(0); } void *thread2() { for(b = 0; b < 9; b++) { pthread_mutex_lock(&mut); err = 0; int flag[10] = {0,0,0,0,0,0,0,0,0,0}; for(j = 0; j < 9; j++) { flag[data[j][b]] = 1; } for(k = 1; k < 10; k++) { if(flag[k] == 0) { err++; if(err == 1) { printf("column = %d, Missing digit = ", b+1); } printf("%d ", k); } } if(err != 0) { printf("\\n"); err1++; } pthread_mutex_unlock(&mut); } pthread_exit(0); } void checksquare(int row, int column) { i = 0, j =0, k = 0, m = 0; err = 0; int flag[10] = {0,0,0,0,0,0,0,0,0,0}; for(i = row; i < row + 3; i++) { for(j = column; j < column + 3; j++) { flag[data[i][j]] = 1; } } for(k = 1; k < 10; k++) { if(flag[k] == 0) { err++; if(err == 1) { printf("3x3 subgrid of row %d..%d and column %d..%d, Missing digit = ", row + 1, row + 3, column + 1, column + 3); } printf("%d ", k); } } if(err != 0) { printf("\\n"); err1++; } } void *thread3() { pthread_mutex_lock(&mut); checksquare(0, 0); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread4() { pthread_mutex_lock(&mut); checksquare(0, 3); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread5() { pthread_mutex_lock(&mut); checksquare(0, 6); pthread_mutex_unlock(&mut); pthread_exit(0); } void thread6() { pthread_mutex_lock(&mut); checksquare(3, 0); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread7() { pthread_mutex_lock(&mut); checksquare(3, 3); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread8() { pthread_mutex_lock(&mut); checksquare(3, 6); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread9() { pthread_mutex_lock(&mut); checksquare(6, 0); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread10() { pthread_mutex_lock(&mut); checksquare(6, 3); pthread_mutex_unlock(&mut); pthread_exit(0); } void *thread11() { pthread_mutex_lock(&mut); checksquare(6, 6); pthread_mutex_unlock(&mut); pthread_exit(0); } void create_thread(void) { int i = 0; int symbol[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; memset(&thread, 0, sizeof(thread)); symbol[0] = pthread_create(&thread[0], 0,(void *) thread1, 0); symbol[1] = pthread_create(&thread[1], 0,(void *) thread2, 0); symbol[2] = pthread_create(&thread[2], 0,(void *) thread3, 0); symbol[3] = pthread_create(&thread[3], 0,(void *) thread4, 0); symbol[4] = pthread_create(&thread[4], 0,(void *) thread5, 0); symbol[5] = pthread_create(&thread[5], 0,(void *) thread6, 0); symbol[6] = pthread_create(&thread[6], 0,(void *) thread7, 0); symbol[7] = pthread_create(&thread[7], 0,(void *) thread8, 0); symbol[8] = pthread_create(&thread[8], 0,(void *) thread9, 0); symbol[9] = pthread_create(&thread[9], 0,(void *) thread10, 0); symbol[10] = pthread_create(&thread[10], 0,(void *) thread11, 0); for(i = 1; i < 11; i++) { if(symbol[i] != 0) { printf("Failure: create thread 1\\n");printf("%d\\n", symbol[i]); } } } void wait_thread() { int i = 0; for(i = 0; i < 11; i++) { if(thread[i] != 0) { pthread_join(thread[i], 0); } } } void main() { int i =0, j =0; pthread_mutex_init(&mut, 0); read_data(); create_thread(); wait_thread(); if(err1 == 0) { printf("The Sudoku puzzle is valid\\n"); } }
1
#include <pthread.h> void *Worker(void *); void InitializeGrids(); void Barrier(); pthread_mutex_t barrier; pthread_cond_t go; int numArrived = 0; int gridSize, numWorkers, numIters, stripSize; double grid1[258], grid2[258]; int main(int argc, char *argv[]) { pthread_t workerid[16]; pthread_attr_t attr; int i; 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]); numIters = atoi(argv[3]); stripSize = gridSize/numWorkers; InitializeGrids(); for (i = 0; i < numWorkers; i++) pthread_create(&workerid[i], &attr, Worker, (void *) i); for (i = 0; i < numWorkers; i++) pthread_join(workerid[i], 0); results = fopen("results", "w"); fprintf(results, "number of iterations: %d\\n",numIters); for (i = 0; i <= gridSize+1; i++) { fprintf(results, "%f ", grid1[i]); } fprintf(results, "\\n"); } void *Worker(void *arg) { int myid = (int) arg; int i, iters; int first, last; printf("worker %d (pthread id %d) has started\\n", myid, pthread_self()); first = myid*stripSize + 1; last = first + stripSize - 1; for (iters = 1; iters <= numIters; iters++) { for (i = first; i <= last; i++) { grid2[i] = (grid1[i-1] + grid1[i] + grid1[i+1]) / 3; } Barrier(); for (i = first; i <= last; i++) { grid1[i] = grid2[i]; } Barrier(); } } void InitializeGrids() { int i; grid1[0] = 1.0; for (i = 1; i <= gridSize; i++) { grid1[i] = 0.0; } grid1[gridSize+1] = 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); }
0
#include <pthread.h> { struct LinkTableNode * pNext; }tLinkTableNode; { tLinkTableNode *pHead; tLinkTableNode *pTail; int SumOfNode; pthread_mutex_t mutex; }tLinkTable; tLinkTable * CreateLinkTable() { tLinkTable *pLinkTable = (tLinkTable*)malloc(sizeof(tLinkTable)); if(pLinkTable == 0) { return 0; } pLinkTable->pHead = 0; pLinkTable->pTail = 0; pLinkTable->SumOfNode = 0; pthread_mutex_init(&(pLinkTable->mutex),0); return pLinkTable; } int DeleteLinkTable(tLinkTable *pLinkTable) { if(pLinkTable==0) { return FAILURE; } while(pLinkTable->pHead != 0) { tLinkTableNode *p =pLinkTable->pHead; pthread_mutex_lock(&(pLinkTable->mutex)); pLinkTable->pHead = pLinkTable->pHead->pNext; pLinkTable->SumOfNode -= 1; pthread_mutex_unlock(&(pLinkTable->mutex)); free(p); } pLinkTable->pHead = 0; pLinkTable->pTail = 0; pLinkTable->SumOfNode = 0; pthread_mutex_destroy(&(pLinkTable->mutex)); free(pLinkTable); return SUCCESS; } int AddLinkTableNode(tLinkTable *pLinkTable, tLinkTableNode *pNode) { if (pLinkTable == 0 || pNode == 0) return FAILURE; if (pLinkTable->pHead == 0) { pLinkTable->pHead = pNode; pLinkTable->pTail = pNode; pLinkTable->SumOfNode = 1; } else { pLinkTable->pTail->pNext = pNode; pLinkTable->pTail = pNode; pLinkTable->SumOfNode++; } return SUCCESS; } int DeleteLinkTableNode(tLinkTable *pLinkTable,tLinkTableNode * pNode) { if(pLinkTable->pHead == 0 || pNode == 0) { return FAILURE; } pthread_mutex_lock(&(pLinkTable->mutex)); if(pLinkTable->pHead == pNode) { pLinkTable->pHead = pLinkTable->pHead->pNext; pLinkTable->SumOfNode -= 1; if(pLinkTable->SumOfNode = 0) { pLinkTable->pTail = 0; } pthread_mutex_unlock(&(pLinkTable->mutex)); return SUCCESS; } tLinkTableNode * pTempNode = pLinkTable->pHead; while(pTempNode != 0) { if(pTempNode->pNext == pNode) { pTempNode->pNext = pTempNode->pNext->pNext; pLinkTable->SumOfNode -= 1; if(pLinkTable->SumOfNode = 0) { pLinkTable->pTail = 0; } pthread_mutex_unlock(&(pLinkTable->mutex)); return SUCCESS; } pTempNode = pTempNode->pNext; } pthread_mutex_unlock(&(pLinkTable->mutex)); return FAILURE; } tLinkTableNode *SearchLinkTableNode(tLinkTable *pLinkTable,int Condition(tLinkTableNode * pNode, void * args),void *args) { if(pLinkTable == 0) { return 0; } tLinkTableNode *tmp = pLinkTable->pHead; while(tmp != 0) { if(Condition(tmp,args) == 1) { return tmp; } tmp = tmp->pNext; } return 0; } tLinkTableNode * GetLinkTableHead(tLinkTable *pLinkTable) { if(pLinkTable == 0) { return 0; } return pLinkTable->pHead; } tLinkTableNode * GetNextLinkTableNode(tLinkTable *pLinkTable,tLinkTableNode * pNode) { if(pLinkTable == 0 || pNode == 0) { return 0; } tLinkTableNode * pTempNode = pLinkTable->pHead; while(pTempNode != 0) { if(pTempNode == pNode) { return pTempNode->pNext; } pTempNode = pTempNode->pNext; } return 0; }
1
#include <pthread.h> void* thread1(void* pParam); void* thread2(void* pParam); int count1=0; int count2; int count3; int i,j; int n=10000; pthread_mutex_t mutex; int main(int argc, char *argv[]){ pthread_t tid1, tid2; clock_t start, end; start = clock(); pthread_mutex_init(&mutex, 0); pthread_create(&tid1, 0, thread1, 0); pthread_create(&tid2, 0, thread2, 0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_mutex_destroy(&mutex); count3 = count1; printf("total = %d",count3); end = clock(); printf("\\ntime: %fs\\n", (double)(end - start) / CLOCKS_PER_SEC); return 0; } void* thread1(void* pParam) { pthread_mutex_lock(&mutex); for(i=0;i<n/2;i++){ count1 = count1 + i; } printf("\\n"); pthread_mutex_unlock(&mutex); return 0; } void* thread2(void* pParam) { pthread_mutex_lock(&mutex); for(j=n/2;j<n;j++){ count1 = count1 + j; } pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> int quitflag = 0; 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; for (;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (signo) { case SIGINT: printf("\\nSIGINT caught\\n"); break; case SIGQUIT: printf("SIGQUIT caught\\n"); pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexpected signla %d\\n", signo); exit(1); } } } int main(void) { 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"); exit(0); }
1
#include <pthread.h> void *dosomething(void *threadnum ){ int *num = threadnum; for(int i=0; i<100; i++){ printf("this is thread %d : task [%d]\\n", *num, i ); } return 0; } int buff[8] = {0}; sem_t *full; sem_t *empty; void *writer(){ for(int i=0 ; i < 100 ; i++){ sem_wait(full); buff[i%8]=i; sem_post(empty); } buff[100%8] = -1; sem_post(empty); return 0; } void *reader(){ int c=0; int count=0; while(1) { sem_wait(empty); c=buff[(count++)%8]; if(c==-1) break; printf("%d|", c); sleep(1); fflush(stdout); sem_post(full); } return 0; } int multithreadingT(){ empty = sem_open("empty", O_CREAT, 0644 ,0); full = sem_open("full", O_CREAT, 0644, 8); pthread_t theads[2]; pthread_create(&theads[0], 0, writer, 0); pthread_create(&theads[1], 0, reader, 0); for(int i=0; i<2; i++) pthread_join(theads[i],0); sem_close(full); sem_close(empty); return 0; } void *dothework(void *(*fn)(void *), void *args){ (*fn)(args); return 0; } void *p1(void *args){ int *c = (int*) args; printf("thread ID is %u | argu is %d\\n", (unsigned int)pthread_self(), *c); return 0; } Function func; void* args; struct thread_works_s *next; } thread_cell; pthread_t *threads; pthread_mutex_t pool_lock; pthread_cond_t pool_cond; int threads_num; int current_work; int pool_join; thread_cell *head; } thread_pool; void *pool_routine(void *args){ thread_pool *Pool = args; while(1){ pthread_mutex_lock(&(Pool->pool_lock)); while(Pool->current_work==0&&Pool->pool_join==0){ pthread_cond_wait(&(Pool->pool_cond), &(Pool->pool_lock)); } while(Pool->current_work==0 && Pool->pool_join==1){ pthread_mutex_unlock(&(Pool->pool_lock)); pthread_exit(0); } assert(Pool->current_work!=0); assert(Pool->head!=0); Pool->current_work--; thread_cell *Target = Pool->head; Pool->head=Pool->head->next; pthread_mutex_unlock(&(Pool->pool_lock)); (Target->func)(Target->args); free(Target); Target=0; } pthread_exit(0); } int pool_prepare(thread_pool *Pool, int threads_num){ pthread_mutex_init(&(Pool->pool_lock),0); pthread_cond_init(&(Pool->pool_cond),0); Pool->threads_num=threads_num; Pool->current_work=0; Pool->pool_join = 0; Pool->threads=malloc(threads_num*sizeof(pthread_t)); for(int i=0; i<Pool->threads_num ;i++){ pthread_create(&(Pool->threads[i]), 0, pool_routine, Pool); } return 0; } int pool_add(thread_pool *Pool, Function func, void *args){ thread_cell *new_work = (thread_cell *)malloc(sizeof(thread_cell)); new_work->func = func; new_work->args = args; new_work->next = 0; pthread_mutex_lock(&(Pool->pool_lock)); thread_cell *tail = Pool->head; if(Pool->head!=0){ while(tail->next!=0) tail = tail->next; tail->next = new_work; } else Pool->head = new_work; assert(Pool->head!=0); Pool->current_work++; pthread_mutex_unlock(&(Pool->pool_lock)); pthread_cond_signal(&(Pool->pool_cond)); return 0; } int pool_join(thread_pool *Pool){ Pool->pool_join = 1; pthread_cond_broadcast(&(Pool->pool_cond)); for(int i = 0; i<Pool->threads_num ; i++){ pthread_join((Pool->threads[i]), 0); } thread_cell *cell=0; while(Pool->head!=0){ cell = Pool->head; Pool->head = Pool->head->next; free(cell); } pthread_mutex_destroy(&(Pool->pool_lock)); pthread_cond_destroy(&(Pool->pool_cond)); free(Pool); Pool=0; return 0; } int main(){ int *task; task = malloc(100*sizeof(int)); for(int i=0; i< 100 ;i++) task[i] = i+1; thread_pool *Pool = malloc(sizeof(thread_pool)); pool_prepare(Pool, 4); for(int i =0; i< 100; i++) pool_add(Pool, p1, &task[i]); pool_join(Pool); }
0
#include <pthread.h> int num_people = 0; int on_car = 0; int next_car = 0; bool can_board = 1; pthread_mutex_t conductor_mutex; pthread_cond_t begin_loading, begin_unloading, enter_car, leave_car, car_empty; void conductor_take_ride() { pthread_mutex_lock(&conductor_mutex); num_people += 1; printf("Passenger %u has arrived for a ride.\\n", (unsigned int)pthread_self()); if(num_people >= 5 && can_board) { can_board = 0; pthread_cond_broadcast(&begin_loading); } pthread_cond_wait(&enter_car, &conductor_mutex); on_car += 1; if(on_car == 5) { pthread_cond_signal(&begin_unloading); } pthread_cond_wait(&leave_car, &conductor_mutex); on_car -= 1; num_people -= 1; if(on_car == 0) { pthread_cond_signal(&car_empty); } pthread_mutex_unlock(&conductor_mutex); } void conductor_load(int car_number) { pthread_mutex_lock(&conductor_mutex); while(num_people < 5 || next_car != car_number) { pthread_cond_wait(&begin_loading, &conductor_mutex); } printf("num people %d\\n", num_people); for(int i = 0; i < 5; i++) { pthread_cond_signal(&enter_car); } pthread_mutex_unlock(&conductor_mutex); } void conductor_unload(int car_number) { pthread_mutex_lock(&conductor_mutex); if(on_car < 5) { pthread_cond_wait(&begin_unloading, &conductor_mutex); } printf("Car %d ran with %d passengers. Now unloading.\\n", car_number, on_car); for(int i = 0; i < 5; i++) { pthread_cond_signal(&leave_car); } if(on_car > 0) { pthread_cond_wait(&car_empty, &conductor_mutex); } can_board = 1; next_car = (next_car + 1) % 3; printf("Car %d has unloaded.\\n", car_number); pthread_cond_broadcast(&begin_loading); pthread_mutex_unlock(&conductor_mutex); } void* car(void* arg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); int car_number = *((int *)arg); while(1) { conductor_load(car_number); conductor_unload(car_number); } return 0; } void* passenger() { if(1) { conductor_take_ride(); } return 0; } int main() { srand(time(0)); pthread_t passengers[15]; pthread_t cars[3]; int car_numbers[3]; if(pthread_mutex_init(&conductor_mutex, 0) != 0) { printf("pthread_mutex_init error\\n"); exit(1); } if(pthread_cond_init(&begin_loading, 0) != 0) { printf("pthread_cond_init error\\n"); exit(1); } if(pthread_cond_init(&begin_unloading, 0) != 0) { printf("pthread_cond_init error\\n"); exit(1); } if(pthread_cond_init(&enter_car, 0) != 0) { printf("pthread_cond_init error\\n"); exit(1); } if(pthread_cond_init(&leave_car, 0) != 0) { printf("pthread_cond_init error\\n"); exit(1); } if(pthread_cond_init(&car_empty, 0) != 0) { printf("pthread_cond_init error\\n"); exit(1); } for(int i = 0; i < 15; i++) { pthread_create(&passengers[i], 0, passenger, 0); } for(int i = 0; i < 3; i++) { car_numbers[i] = i; pthread_create(&cars[i], 0, car, (void *)(&car_numbers[i])); } for(int i = 0; i < 15; i++) { pthread_join(passengers[i], 0); } printf("All passenger threads joined.\\n"); for(int i = 0; i < 3; i++) { pthread_cancel(cars[i]); } printf("All car threads terminated.\\n"); pthread_mutex_destroy(&conductor_mutex); pthread_cond_destroy(&begin_loading); pthread_cond_destroy(&begin_unloading); pthread_cond_destroy(&enter_car); pthread_cond_destroy(&leave_car); pthread_cond_destroy(&car_empty); return 0; }
1
#include <pthread.h> int proximo = -1, i = 0; int nFatoracoes = 100; pthread_mutex_t mutex; pthread_cond_t condM; pthread_cond_t condE; struct strDivisores { int *lista; int tamanho; int nDivisores; }; struct strDivisores encontraDivisores (int n) { struct strDivisores div; div.tamanho = (int) ceilf ( log2f( (float)n ) ); div.lista = (int *) malloc ( div.tamanho * sizeof(int) ); div.nDivisores = 0; int i; for (i=2; i <= n; i++) { if ( n % i == 0 ) { while ( n % i == 0 && n != 1 ) { div.lista[ div.nDivisores ] = i; n = n/i; } div.nDivisores++; } } return div; } void *mestre(void *param) { int nMin = 100000000; int nMax = 1000000000; int i; for (i=0; i<nFatoracoes; i++) { pthread_mutex_lock(&mutex); proximo = (int) floor ( (double) rand() * (nMax - nMin) / 32767 ) + nMin; pthread_cond_signal(&condE); pthread_cond_wait(&condM, &mutex); pthread_mutex_unlock(&mutex); } } void *escravo(void *param) { int k; while (1) { pthread_mutex_lock(&mutex); if (i >= nFatoracoes) { pthread_mutex_unlock(&mutex); pthread_exit(0); } int i_local = ++i; if(proximo==-1) pthread_cond_wait(&condE, &mutex); int n = proximo; proximo = -1; pthread_cond_signal(&condM); pthread_mutex_unlock(&mutex); struct strDivisores div = encontraDivisores (n); printf("[%3d] %10d: ", i_local,n); for (k=0; k<div.nDivisores; k++) printf("%10d ", div.lista[k]); printf("\\n"); free (div.lista); } } int main (int argc, char *argv[]) { srand(1); int i; pthread_t mestre_t; pthread_t escravo_t[4]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&condE, 0); pthread_cond_init(&condM, 0); pthread_create(&mestre_t, 0, mestre, 0); for (i=0; i<4; i++) pthread_create(&escravo_t[i], 0, escravo, 0); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t lock; int jump; struct list{ int id; int lower_bound; int upper_bound; }; int is_prime(int n){ int i; if(n%2==0 && n!=2) return 0; for(i=3;i*i<n;i+=2){ if(n%i==0) return 0; } return 1; } void* print(void *arg){ pthread_mutex_lock(&lock); struct list *prime=arg; int iter; for(iter=prime->lower_bound;iter<=prime->upper_bound;iter++){ if(is_prime(iter)) printf("THREAD %d => %d\\n",prime->id,iter); } pthread_mutex_unlock(&lock); } int main(){ int n,t,i;scanf("%d %d",&n,&t); jump=n/t; pthread_t tid[t]; struct list prime[t]; prime[0].id=0; prime[0].lower_bound=2; prime[0].upper_bound=jump; for(i=1;i<t;i++){ prime[i].id=i; prime[i].lower_bound=prime[i-1].upper_bound+1; prime[i].upper_bound=prime[i].lower_bound+jump-1; } for(int i=0;i<t;i++){ pthread_create( &(tid[i]),0,&print,(void*)&prime[i]); printf("\\n"); } for(int i=0;i<t;i++){ pthread_join(tid[i],0); } return 0; }
1
#include <pthread.h> pthread_mutex_t sum_mutex1; int a[1000], sum; void initialize_array(int *a, int n) { int i; for (i = 1; i <= n; i++) { a[i-1] = i; } } void *thread_add(void *argument) { int i, thread_sum, arg; thread_sum = 0; arg = *(int *)argument; for (i = ((arg-1)*(1000/4)) ; i < (arg*(1000/4)); i++) { thread_sum += a[i]; } printf("Thread : %d : Sum : %d\\n", arg, thread_sum); pthread_mutex_lock(&sum_mutex1); sum += thread_sum; pthread_mutex_unlock(&sum_mutex1); } void print_array(int *a, int size) { int i; for(i = 0; i < size; i++) printf(" %d ", a[i]); putchar('\\n'); } int main() { int i, *range; pthread_t thread_id[4]; pthread_attr_t custom_sched_attr; int fifo_max_prio, fifo_min_prio, fifo_mid_prio; struct sched_param fifo_param; sum = 0; initialize_array(a, 1000); pthread_attr_init(&custom_sched_attr); pthread_attr_setscope(&custom_sched_attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_init(&custom_sched_attr); pthread_attr_setinheritsched(&custom_sched_attr, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&custom_sched_attr, SCHED_FIFO); fifo_max_prio = sched_get_priority_max(SCHED_FIFO); fifo_min_prio = sched_get_priority_min(SCHED_FIFO); fifo_mid_prio = (fifo_min_prio + fifo_max_prio)/2; fifo_param.sched_priority = fifo_max_prio; pthread_attr_setschedparam(&custom_sched_attr, &fifo_param); printf("Array : \\n"); print_array(a, 1000); for (i = 0; i < 4; i++) { range = (int *)malloc(sizeof(int)); *range = (i+1); if (pthread_create(&thread_id[i], 0, thread_add, (void *)range)) printf("Thread creation failed for thread num : %d\\n", *range); } for (i = 0; i < 4; i++) { pthread_join(thread_id[i], 0); } printf("Sum : %d\\n", sum); pthread_attr_destroy(&custom_sched_attr); return 0; }
0
#include <pthread.h> static int camera_stop_flag = 0; static int take_picture =0; static pthread_t read_thread; static char filename[64]; static int count = 0; pthread_mutex_t lock; static struct fb_info *fb_info; struct display_info disp_info; static int fd = -1; static int start_ms = 0; void process_frame(const char *filename, void *frame, struct display_info *dis) { FILE *file; int width = dis->width; int height = dis->height; unsigned char *rgb_frame = 0; file = fopen(filename, "w"); if (!file) { fprintf(stderr, "--%s() L%d: open %s failed!!!\\n", __func__, 41, filename); return; } rgb_frame = (unsigned char *)malloc(width * height * 3); if (rgb_frame == 0) { fprintf(stderr, "-->%s() L%d: malloc failed!\\n", __func__, 46); return; } convert_yuv_to_rgb24(frame, rgb_frame, dis); save_bgr_to_bmp(rgb_frame, dis, file); free(rgb_frame); fclose(file); } static int handle_bufs(void *tmp_buf) { struct timeval t_end; int end_ms; iq_lcd_display_frame(tmp_buf,&disp_info,fb_info); if(take_picture){ sprintf(filename,"/mnt/sdcard/test%d.bmp",count); process_frame(filename, tmp_buf, &disp_info); gettimeofday(&t_end,0); end_ms = ((long long) t_end.tv_sec) * 1000 + (long long) t_end.tv_usec / 1000; if((end_ms - start_ms) > 500){ mozart_play_key("take_picture"); count++; if(count > 200) count = 0; camera_stop_flag = 1; } } return 0; } static void * camera_read_frame(void *arg) { while(!camera_stop_flag){ pthread_mutex_lock(&lock); iq_camera_get_frames(); pthread_mutex_unlock(&lock); } pthread_exit(0); } int mozart_start_camera() { int width = 320; int height = 240; int bpp = 16; int ret = -1; disp_info.width = width; disp_info.height = height; disp_info.bpp = bpp; take_picture = 0; if(fd >= 0) mozart_stop_camera(); pthread_mutex_init(&lock, 0); camera_stop_flag = 0; iq_camera_init_disp_info(&disp_info); fb_info = iq_lcd_init("/dev/fb0"); fd = iq_camera_open("/dev/video0"); if(fd < 0){ fprintf(stderr,"open camera failed!!!"); return -1; } iq_camera_start(&disp_info,handle_bufs); ret = pthread_create(&read_thread,0,camera_read_frame,0); if(ret != 0){ fprintf(stderr,"create pthread failed!!!\\n"); return -1; } return 0; } static void stop_camera() { void *pret = 0; pthread_join(read_thread,&pret); iq_camera_stop(&disp_info); iq_camera_close(fd); iq_lcd_deinit(fb_info); pthread_mutex_destroy(&lock); fd = -1; } void mozart_stop_camera() { camera_stop_flag = 1; stop_camera(); } void mozart_take_picture() { struct timeval t_start; take_picture = 1; gettimeofday(&t_start,0); start_ms = ((long long) t_start.tv_sec) * 1000 + (long long) t_start.tv_usec / 1000; stop_camera(); printf("finish %s\\n",__func__); }
1
#include <pthread.h> long long int value; pthread_mutex_t mutex1; }count; void init(count *c) { c->value=0; c->mutex1=(pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER; } void *increment(void *c) { while(((count *)c)->value<1000000000) { pthread_mutex_lock(&(((count *)c)->mutex1)); if(((count *)c)->value<1000000000) ((count *)c)->value++; pthread_mutex_unlock(&(((count *)c)->mutex1)); } pthread_exit(0); return 0; } long long int get(count *c) { pthread_mutex_lock(&(((count *)c)->mutex1)); long long int rc=c->value; pthread_mutex_unlock(&(((count *)c)->mutex1)); return rc; } int main(int argc, char *argv[]) { pthread_t t1; count c; init(&c); int rc; rc=pthread_create(&t1, 0, increment, &c); assert(rc==0); pthread_join(t1, 0); printf("counter value is :%lld\\n",get(&c)); return 0; }
0
#include <pthread.h> extern int makethread (void* (*) (void*), void*); struct to_info { void (*to_fn) (void*); void* to_arg; struct timespec to_wait; }; void clock_gettime (int id, struct timespec* tsp) { struct timeval tv; gettimeofday (&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void* timeout_helper (void* arg) { struct to_info* tip; tip = (struct to_info*) arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn) (tip->to_arg); free (arg); return (0); } void timeout (const struct timespec* when, void (*func) (void*), void* arg) { struct timespec now; struct to_info* tip; int err; clock_gettime (0, &now); if ( (when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc (sizeof (struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread (timeout_helper, (void*) tip); if (err == 0) { return; } else { free (tip); } } } (*func) (arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry (void* arg) { pthread_mutex_lock (&mutex); pthread_mutex_unlock (&mutex); } int main (void) { int err, condition, arg; struct timespec when; if ( (err = pthread_mutexattr_init (&attr)) != 0) { err_exit (err, "pthread_mutexattr_init failed"); } if ( (err = pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) { err_exit (err, "can't set recursive type"); } if ( (err = pthread_mutex_init (&mutex, &attr)) != 0) { err_exit (err, "can't create recursive mutex"); } pthread_mutex_lock (&mutex); if (condition) { clock_gettime (0, &when); when.tv_sec += 10; timeout (&when, retry, (void*) ( (unsigned long) arg)); } pthread_mutex_unlock (&mutex); exit (0); }
1
#include <pthread.h> pthread_cond_t found; pthread_mutex_t mutexi; pthread_barrier_t barreira; int resultados; int num_equipes, num_membros; int print =0; int equipes[100][100][2]; int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); } void* doIt(void* team){ int *equipi = (int*)team; int equipe = (*equipi); int i =0; for(i =0;i<num_membros;i++){ int result = gcd(equipes[equipe][i][0],equipes[equipe][i][1]); pthread_mutex_lock(&mutexi); resultados +=result; pthread_mutex_unlock(&mutexi); pthread_barrier_wait(&barreira); pthread_mutex_lock(&mutexi); if(print==0){ printf("Resultado turno %d: %d\\n",(i+1),resultados); resultados=0; print = 1; } pthread_mutex_unlock(&mutexi); pthread_barrier_wait(&barreira); print = 0; } } int main(int argc, char *argv[]) { scanf("%d%d",&num_equipes,&num_membros); pthread_t ids_threads[num_equipes]; int ids[num_equipes]; pthread_barrier_init(&barreira, 0, num_equipes); int i=0 ,j=0; resultados = 0; for (i = 0; i < num_equipes; ++i) { ids[i] =i; for (j = 0; j < num_membros; ++j) { int a,b; scanf("%d%d",&a,&b); equipes[i][j][0] = a; equipes[i][j][1] = b; } } for (i = 0; i < num_equipes; ++i){ int status = pthread_create(&ids_threads[i],0,doIt,(void*)(&ids[i])); if(status != 0) { printf("Error ao criar Thread - %d, error code = %d", i, status); exit(-1); } } for (i = 0; i < num_equipes; ++i){ pthread_join(ids_threads[i],0); } }
0
#include <pthread.h> struct job { struct job* next; }; struct job* job_queue; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_function (void* arg) { while (1) { struct job* next_job; pthread_mutex_lock (&job_queue_mutex); if (job_queue == 0) next_job = 0; else { next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0) break; process_job (next_job); free (next_job); } return 0; }
1
#include <pthread.h> struct setNode* next; pthread_mutex_t* mutex; void* data; }setNode_t; setNode_t* head; int (*compare)(void* , void* ); }set_t; static setNode_t* setNode_new(void* data, setNode_t* next) { setNode_t* new = malloc(sizeof(setNode_t)); if (new == 0){ fprintf(stderr, "%s\\n","Malloc setNode_t"); return 0; } new->mutex = malloc(sizeof(pthread_mutex_t)); if(new->mutex == 0){ fprintf(stderr, "%s\\n","Malloc mutex_t"); return 0; } pthread_mutex_init(new->mutex,0); new->data = data; new->next = next; return new; } set_t* set_new(int (*compare)(void* , void* )) { if(compare == 0){ fprintf(stderr, "%s\\n", "Input type can be anything but compare function required."); return 0; } set_t* setHead = malloc(sizeof(set_t)); if (setHead == 0){ fprintf(stderr, "%s\\n","Malloc set_t"); return 0; } setHead->compare = compare; setHead->head = setNode_new(0,0); return setHead; } bool set_contains(set_t* set, void* data) { setNode_t* elem = set->head; pthread_mutex_lock(elem->mutex); if (elem->next == 0){ pthread_mutex_unlock(elem->mutex); return 0; } setNode_t* prev = elem; while (elem->next != 0 && set->compare(elem->next->data,data) <= 0){ if(set->compare(elem->next->data,data) == 0){ pthread_mutex_unlock(elem->mutex); return 1; } prev = elem; elem = elem->next; pthread_mutex_lock(elem->mutex); pthread_mutex_unlock(prev->mutex); } if(set->compare(elem->data,data) == 0){ pthread_mutex_unlock(elem->mutex); return 1; } pthread_mutex_unlock(elem->mutex); return 0; } bool set_add(set_t* set, void* data) { setNode_t* elem = set->head; pthread_mutex_lock(elem->mutex); if (elem->next == 0){ setNode_t *newElem = setNode_new(data,0); elem->next = newElem; pthread_mutex_unlock(elem->mutex); return 1; } setNode_t* prev = elem; while (elem->next != 0 && set->compare(elem->next->data,data) <= 0){ if(set->compare(elem->next->data,data) == 0){ pthread_mutex_unlock(elem->mutex); return 0; } prev = elem; elem = elem->next; pthread_mutex_lock(elem->mutex); pthread_mutex_unlock(prev->mutex); } if (elem->data == data){ pthread_mutex_unlock(elem->mutex); return 0; } setNode_t *newElem = setNode_new(data, elem->next); elem->next = newElem; pthread_mutex_unlock(elem->mutex); return 1; } bool set_del(set_t* set, void* val) { setNode_t* prev = set->head; pthread_mutex_lock(prev->mutex); if (prev->next == 0){ pthread_mutex_unlock(prev->mutex); return 0; } setNode_t* elem = prev->next; pthread_mutex_lock(elem->mutex); while (elem->next != 0 && set->compare(elem->data,val) <= 0){ if (set->compare(elem->data,val) == 0){ prev->next = elem->next; pthread_mutex_unlock(elem->mutex); free(elem->mutex); free(elem); pthread_mutex_unlock(prev->mutex); return 1; } pthread_mutex_unlock(prev->mutex); prev = elem; elem = elem->next; pthread_mutex_lock(elem->mutex); } if (set->compare(elem->data,val) == 0){ prev->next = elem->next; pthread_mutex_unlock(elem->mutex); free(elem->mutex); free(elem); pthread_mutex_unlock(prev->mutex); return 1; } pthread_mutex_unlock(elem->mutex); pthread_mutex_unlock(prev->mutex); return 0; }
0
#include <pthread.h> unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: ; goto ERROR; return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for(i=0; i<(5); i++) { 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> void *resourceRequest(void *i); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int **alloc,**need,**maxClaim; int *maxRes,*resVector,*complete; int *executionOrder; int order=0; int nr,np; char space; int count=0; int main(int argc , char *argv[]) { int rc[100]; int i,j,sum,k=0,turn=0; FILE *fptr; char msg[150]; pthread_t *thread; if(argc < 2 ) { printf("Please Enter the filename using command Line argument."); return 0; } if((fptr=fopen(argv[1],"r"))== 0) { printf("Error occur in file opening\\n"); return 0; } if(!fscanf(fptr,"%d",&nr)){ printf("File is not formated \\n"); return 0; } printf("Number of resource %d\\n",nr); complete = (int *)malloc(sizeof(int)*np); for(i=0;i<np;i++) { complete[i] = 0; } executionOrder = (int *)malloc(sizeof(int)*np); for(i=1;i<=np;i++) { executionOrder[i] = 0; } printf("max resource\\n"); maxRes =(int *) malloc(sizeof(int)*nr); if(maxRes == 0) { printf("Memory in not sufficient\\n"); return 0; } for(i=0;i<nr;i++) { fscanf(fptr,"%d",&maxRes[i]); fscanf(fptr,"%c",&space); printf("%d\\t",maxRes[i]); } resVector =(int *) malloc(sizeof(int)*nr); if(resVector == 0) { printf("Memory in not sufficient\\n"); return 0; } printf("\\nAvailable Resource\\n"); for(i=0;i<nr;i++) { fscanf(fptr,"%d",&resVector[i]); fscanf(fptr,"%c",&space); printf("%d\\t",resVector[i]); } printf("\\n"); if(!fscanf(fptr,"%d",&np)){ printf("File is not formated \\n"); return 0; } printf("Number of process %d\\n",np); alloc = (int **)malloc(sizeof(int)*nr*np); if(alloc == 0) { printf("Mermory is not sufficient\\n"); } printf("Allocation matrix\\n"); for(i=0;i<np;i++) { alloc[i] = (int *)malloc(sizeof(int)*nr); for(j=0;j<nr;j++) { fscanf(fptr,"%d",&alloc[i][j]); printf("%d\\t",alloc[i][j]); } printf("\\n"); } maxClaim = (int **)malloc(sizeof(int)*nr*np); if(maxClaim == 0) { printf("Mermory is not sufficient\\n"); } printf("Maximum resource claim matrix\\n"); for(i=0;i<np;i++) { maxClaim[i] = (int *)malloc(sizeof(int)*nr); for(j=0;j<nr;j++) { fscanf(fptr,"%d",&maxClaim[i][j]); printf("%d\\t",maxClaim[i][j]); } printf("\\n"); } fclose(fptr); need = (int **)malloc(sizeof(int)*nr*np); if(need == 0) { printf("Mermory is not sufficient\\n"); } printf(" resource need matrix\\n"); for(i=0;i<np;i++) { sum = 0; need[i] = (int *)malloc(sizeof(int)*nr); for(j=0;j<nr;j++) { need[i][j] = maxClaim[i][j]-alloc[i][j]; printf("%d\\t",need[i][j]); } printf("\\n"); } thread = (pthread_t *)malloc(sizeof(pthread_t)*np); if(thread == 0) { printf("Memory is insufficient\\n"); return 0; } next: for(i=0;i<np;i++) { if(complete[i] == 0) { if(rc[i]=pthread_create( &thread[i], 0, resourceRequest,(void *) &i)) { printf("Thread creation failed: %d\\n", rc[i]); } } } for(i=0;i<np;i++) { pthread_join(thread[i],0); turn++; } k=0; for(i=0;i<np;i++) { if(complete[i] == 1) { k++; } else if(complete[i]==0 && (turn==(np*np))) { printf("The process is not in safe state\\n"); strcpy(msg,"The process is not in safe state"); printf("Complete vector\\n"); for(i=0;i<np;i++) { printf("%d\\t",complete[i]); } fptr= fopen("output.txt","w"); if(fptr==0) { printf("Error in file opening in output.txt\\n"); } fprintf(fptr,"%d\\n",nr); fprintf(fptr,"%d\\n",np); fprintf(fptr,"%s\\n",msg); for(i=0;i<np;i++) { if(executionOrder[i] == 0) { fprintf(fptr,"P%s\\t","x"); } else { fprintf(fptr,"P%d\\t",executionOrder[i]); } } printf("\\n"); printf("Output is written in output.txt successfuly\\n"); fclose(fptr); return 0; } else { goto next; } } if(k==np) { printf("The process is in safe state\\n"); strcpy(msg,"The process is in safe state"); } printf("Order of execution\\n"); for(i=0;i<np;i++) { printf("P%d\\t",executionOrder[i]); } printf("\\n"); fptr= fopen("output.txt","w"); if(fptr==0) { printf("Error in file opening in output.txt\\n"); } fprintf(fptr,"%d\\n",nr); fprintf(fptr,"%d\\n",np); fprintf(fptr,"%s\\n",msg); for(i=0;i<np;i++) { fprintf(fptr,"P%d\\t",executionOrder[i]); } printf("Complete vector\\n"); for(i=0;i<np;i++) { printf("%d\\t",complete[i]); } printf("\\n"); printf("Output is written in output.txt successfuly\\n"); fclose(fptr); free(alloc); free(need); free(maxClaim); free(maxRes); free(resVector); free(complete); free(executionOrder); return 0; } void *resourceRequest(void *li) { int l,m,counter; int pi; pi = *(int *)li; pthread_mutex_lock( &mutex1 ); counter=0; if(complete[pi] == 1) { goto Relese; } for(l=0;l<nr;l++) { if(need[pi][l]>resVector[l]) { count++; complete[pi] = 0; break; } else if(need[pi][l] <= resVector[l]){ counter++; } } if(counter == nr) { complete[pi] = 1; executionOrder[order++] = pi+1; for(l=0;l<nr;l++) { resVector[l] = resVector[l] + alloc[pi][l]; } } Relese: ; pthread_mutex_unlock( &mutex1 ); pthread_exit((void *)"threadexit"); }
0
#include <pthread.h> void shift_left_after_se(void *not_used){ pthread_barrier_wait(&threads_creation); while(1) { pthread_mutex_lock(&control_sign); if (!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait, &control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } pthread_mutex_lock(&sign_extend_mutex); if (!se.isUpdated) while(pthread_cond_wait(&sign_extend_cond, &sign_extend_mutex) != 0); pthread_mutex_unlock(&sign_extend_mutex); shift_left.value = se.value << 2; pthread_mutex_lock(&shift_left_mutex); shift_left.isUpdated = 1; pthread_cond_signal(&shift_left_cond); pthread_mutex_unlock(&shift_left_mutex); pthread_barrier_wait(&current_cycle); shift_left.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> pthread_mutex_t mutex; double target; void* opponent(void *arg) { int i ; for(i = 0; i < 100000; ++i) { pthread_mutex_lock(&mutex); target -= i ; pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char **argv) { pthread_t other; int rv; target = 5.0; if(pthread_mutex_init(&mutex, 0)) { printf("Unable to initialize a mutex\\n"); return -1; } if(pthread_create(&other, 0, &opponent, 0)) { printf("Unable to spawn thread\\n"); return -1; } int i; for(i = 0; i < 100000; ++i) { pthread_mutex_lock(&mutex); target += i ; pthread_mutex_unlock(&mutex); } if(rv = pthread_join(other, 0)) { printf("Could not join thread - %d\\n", rv); return -1; } pthread_mutex_destroy(&mutex); printf("Result: %f\\n", target); return 0; }
0
#include <pthread.h> struct options { char* mnt_point; int mnt_point_set; }; static struct options* parse_args(int argc, char* argv[]); static void usage(int argc, char** argv); static struct options* user_opts = 0; int main(int argc, char **argv) { int ret = -1; int counter = 5; user_opts = parse_args(argc, argv); if(!user_opts) { fprintf(stderr, "Error: failed to parse command line arguments.\\n"); usage(argc, argv); return(-1); } ret = pvfs2_vis_start(user_opts->mnt_point, 1000); if(ret < 0) { PVFS_perror("pvfs2_vis_start", ret); return(-1); } while(counter--) { pthread_mutex_lock(&pint_vis_mutex); pthread_cond_wait(&pint_vis_cond, &pint_vis_mutex); if(pint_vis_error) { return(-1); } printf("%lld\\n", lld(pint_vis_shared.io_perf_matrix[0][pint_vis_shared.io_depth-1].read)); pthread_mutex_unlock(&pint_vis_mutex); } pvfs2_vis_stop(); return(0); } static struct options* parse_args(int argc, char* argv[]) { char flags[] = "vm:"; int one_opt = 0; int len = 0; struct options* tmp_opts = 0; int ret = -1; tmp_opts = (struct options*)malloc(sizeof(struct options)); if(!tmp_opts){ return(0); } memset(tmp_opts, 0, sizeof(struct options)); while((one_opt = getopt(argc, argv, flags)) != EOF){ switch(one_opt) { case('v'): printf("%s\\n", "Unknown"); exit(0); case('m'): len = strlen(optarg)+1; tmp_opts->mnt_point = (char*)malloc(len+1); if(!tmp_opts->mnt_point) { free(tmp_opts); return(0); } memset(tmp_opts->mnt_point, 0, len+1); ret = sscanf(optarg, "%s", tmp_opts->mnt_point); if(ret < 1){ free(tmp_opts); return(0); } strcat(tmp_opts->mnt_point, "/"); tmp_opts->mnt_point_set = 1; break; case('?'): usage(argc, argv); exit(1); } } if(!tmp_opts->mnt_point_set) { free(tmp_opts); return(0); } return(tmp_opts); } static void usage(int argc, char** argv) { fprintf(stderr, "\\n"); fprintf(stderr, "Usage : %s -m [fs_mount_point]\\n", argv[0]); fprintf(stderr, "Example: %s -m /mnt/pvfs2\\n", argv[0]); return; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long) id) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long) id) % 29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long) fp->f_id) % 29); tfp = fh[idx]; if (tfp == fp) fh[idx] = fp->f_next; else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> void *v2(void *path){ if (start_time.tv_sec == 0 && start_time.tv_usec == 0) { if (gettimeofday(&start_time, 0)) { fprintf(stderr, "Failed to run Variant 2: unable to get current time\\n"); exit(1); } } char *file, new_path[1000]; pthread_t thread, thread_png, thread_jpg, thread_gif, thread_bmp; DIR *inDir; struct dirent *inDirent; struct stat st; inDir = opendir(path); if (!inDir) { fprintf(stderr, "Error encountered in Variant 2: invalid input path.\\n"); fprintf(stderr, " Unable to open directory at %s\\n", (char *) path); exit(1); } pthread_mutex_lock(&log_mutex); num_dir++; num_threads += 5; pthread_mutex_unlock(&log_mutex); pthread_create(&thread_png, 0, find_png, path); pthread_join(thread_png, 0); pthread_create(&thread_jpg, 0, find_jpg, path); pthread_join(thread_jpg, 0); pthread_create(&thread_gif, 0, find_gif, path); pthread_join(thread_gif, 0); pthread_create(&thread_bmp, 0, find_bmp, path); pthread_join(thread_bmp, 0); while ( (inDirent = readdir(inDir)) ) { file = inDirent->d_name; strcpy(new_path, path); strcat(new_path, "/"); strcat(new_path, file); if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store")) { continue; } stat(new_path, &st); if (S_ISDIR(st.st_mode)) { pthread_create(&thread, 0, v2, new_path); pthread_join(thread, 0); continue; } pthread_mutex_lock(&log_mutex); num_files++; pthread_mutex_unlock(&log_mutex); } pthread_mutex_lock(&time_mutex); if (gettimeofday(&end_time, 0)) { fprintf(stderr, "Failed to run Variant 2: unable to get current time\\n"); exit(1); } pthread_mutex_unlock(&time_mutex); closedir(inDir); pthread_exit(0); }
1
#include <pthread.h> pthread_cond_t cond; pthread_mutex_t mutex; void* p_func(void* p) { struct timespec ts; struct timeval now; bzero(&ts,sizeof( ts)); int ret; gettimeofday(&now,0); ts.tv_sec=now.tv_sec+5; pthread_mutex_lock(&mutex); printf(" i am child ,this is wait entrance\\n" ); ret=pthread_cond_timedwait(&cond,&mutex,&ts); if(0!=ret) { printf("pthread_cond_timewait ret is %d\\n" ,ret); } printf(" i am child thread,i am wake\\n" ); pthread_mutex_unlock(&mutex); pthread_exit( 0); } int main( ) { int ret; ret=pthread_cond_init(&cond,0); if( 0!=ret) { printf("pthread_cond_init ret is %d\\n" ,ret); return -1; } ret=pthread_mutex_init(&mutex,0); if( 0!=ret) { printf("pthread_mutex_init ret is %d\\n" ,ret); return -1; } pthread_t thid; pthread_create( &thid,0,p_func,0); sleep( 1); ret=pthread_join(thid,0); if( 0!=ret) { printf("pthread_join ret is %d\\n" ,ret); return -1; } ret=pthread_cond_destroy(&cond); if( 0!=ret) { printf("pthread_cond_destroy ret is %d\\n" ,ret); return -1; } ret=pthread_mutex_destroy(&mutex); if( 0!=ret) { printf("pthread_mutex_destroy ret is %d\\n" ,ret); return -1; } return 0; }
0
#include <pthread.h> void *matrix(void *); void *display(void *); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t t[5]; int C[4], A[8], B[8]; int main(int argc, char *argv[]) { if (argc == 17) { if (datavalidation(argc, argv)) { int i; for (i = 0; i < 8; i++) A[i] = atoi(argv[i+1]); for (i = 0; i < 8; i++) B[i] = atoi(argv[i+9]); for (i = 0; i < 4; i++) { printf("Thread (%d) being created\\n", i); pthread_create(&t[i], 0, matrix, (void *) i); } printf("Thread (%d) being created\\n", i); pthread_create(&t[4], 0, display, (void *) i); printf("%s\\n", "Waiting for Display thread to finish if it hasnt already..."); pthread_join(t[4], 0); pthread_exit(0); } } else { printf("%s\\n", "Incorrect number of input or incorrect type of input"); return 0; } return 0; } void *display(void *i) { int x = (int)i; int j; printf("Thread ID (%u)\\n", pthread_self()); printf("%s\\n", "Waiting for matrix calculation threads to finish if they havent already..."); for (j = 0; j < 4; j++) pthread_join(t[j], 0); pthread_mutex_lock(&mutex); printf("The first row the resulting matrix is %d %d\\n", C[0], C[1]); printf("The second row of the resulting matrix is %d %d\\n", C[2], C[3]); pthread_mutex_unlock(&mutex); printf("%s%d%s\\n", "Thread ", x, " exiting"); pthread_exit(0); } void *matrix(void *num) { int x = (int)num; printf("Thread ID (%u)\\n", pthread_self()); pthread_mutex_lock(&mutex); switch (x) { case 0: C[0] = (A[0]*B[0]) + (A[1]*B[2]) + (A[2]*B[4]) + (A[3]*B[6]); printf("C[0]=%d\\n", C[0]); break; case 1: C[1] = (A[0]*B[1]) + (A[1]*B[3]) + (A[2]*B[5]) + (A[3]*B[7]); printf("C[1]=%d\\n", C[1]); break; case 2: C[2] = (A[4]*B[0]) + (A[5]*B[2]) + (A[6]*B[4]) + (A[7]*B[6]); printf("C[2]=%d\\n", C[2]); break; case 3: C[3] = (A[4]*B[1]) + (A[5]*B[3]) + (A[6]*B[5]) + (A[7]*B[7]); printf("C[3]=%d\\n", C[3]); break; } pthread_mutex_unlock(&mutex); printf("%s%d%s\\n", "Thread ", x, " exiting"); pthread_exit(0); } int datavalidation(int c, char *a[]) { int i; for (i = 1; i < c; i++) { if (isvalid(a[i]) == 0) return 0; } return 1; } int isvalid(char a[]) { int i; if ((a[0] == '+') || (a[0] == '-')) { i = 1; while (a[i] != '\\0') { if (isdigit(a[i]) != 0) { } else { printf("%s\\n", "Incorrect type of input\\nError code: 1A"); return 0; } i++; } } else { i = 0; while (a[i] != '\\0') { if (isdigit(a[i]) != 0) { } else { printf("%s\\n", "Incorrect type of input\\nError code: 1B"); return 0; } i++; } } return 1; }
1
#include <pthread.h> void insert_end( char * ); void delete_beginning( void ); void delete_position( int pos ); struct node { int sec; int lost_sec; char info[64]; struct node *link; }; pthread_mutex_t mutex; pthread_cond_t cond1; pthread_cond_t cond2; struct node * head; } my_struct_t; my_struct_t data = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, PTHREAD_COND_INITIALIZER, 0}; struct node *p, *temp; int count ; int pos ; int n ; void *alrm(void *line) { time_t instance; while ( 1 ) { while (data.head == 0) { sleep(1); } while (data.head != 0) { sleep( (data.head -> sec) - time(0)); printf("(%d) %s\\n", data.head -> sec, data.head -> info); pthread_mutex_lock(&data.mutex); delete_beginning(); pthread_mutex_unlock(&data.mutex); } } pthread_exit(0); } int main( void ) { pthread_t th_id; char line[128]; int status; if( 0 != pthread_create(&th_id, 0, &alrm, 0)) { err_abort(status,"failed pthread craete"); pthread_exit(0); } while (1) { printf("Alarm > "); if(fgets (line, sizeof(line), stdin) == 0) exit(0); if(strlen (line) <= 1) continue; pthread_mutex_lock(&data.mutex); insert_end( line ); pthread_mutex_unlock(&data.mutex); } return 0; } void insert_end( char * buffer) { time_t instance; int seconds; char message[64]; int num; temp = ((struct node *) malloc ( sizeof(struct node ))); if(sscanf(buffer, "%d %64[^\\n]", &seconds, message) < 2) { fprintf(stderr, "Bad command\\n"); } num = seconds; temp -> sec = seconds + time( 0 ); strcpy(temp -> info, message); temp -> link = 0; if (0 == data.head){ data.head = temp; } else { p = data.head; while ( p->link != 0 ){ p = p->link; } p -> link = temp; } count++; return; } void delete_beginning( void ) { struct node *p = data.head; data.head = data.head -> link; count --; free( p ); }
0
#include <pthread.h> int N=100; int T=4; pthread_mutex_t count_lock; pthread_cond_t ok_to_proceed; int count; } barrier; double escalar; barrier *barrera; double max, min, suma; double *R; double* M[8]; pthread_mutex_t mutexMax; pthread_mutex_t mutexMin; pthread_mutex_t mutexAvg; void printMatrix(double* M, char* c, int ord){ int i,j; printf("Matriz %s:\\n", c); if(ord==1){ for (i=0;i<N;i++){ for(j=0;j<N;j++){ printf("%f ",M[i+j*N]); } printf("\\n"); } } else { for (i=0;i<N;i++){ for(j=0;j<N;j++){ printf("%f ",M[i*N+j]); } printf("\\n"); } } } double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *hilar(void *s){ int i,k,j,c; int tid = *((int*)s); int cant=0; int inicio=tid*(N/T); int fin=inicio+N/T; double minLocal, maxLocal, sumaLocal; minLocal=9999; maxLocal=-999; sumaLocal=0; for(k=0;k<8;++k){ for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j]; if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j]; sumaLocal+=M[k][i*N+j]; } } } pthread_mutex_lock(&mutexMax); if(maxLocal>max) max=maxLocal; pthread_mutex_unlock(&mutexMax); pthread_mutex_lock(&mutexMin); if(minLocal<min) min=minLocal; pthread_mutex_unlock(&mutexMin); pthread_mutex_lock(&mutexAvg); suma+=sumaLocal; pthread_mutex_unlock(&mutexAvg); pthread_mutex_lock(&(barrera -> count_lock)); barrera -> count ++; if (barrera -> count == T){ barrera -> count = 0; escalar=(max-min)/(suma/(N*N*8)); pthread_cond_broadcast(&(barrera -> ok_to_proceed)); }else{ pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock)); } pthread_mutex_unlock(&(barrera -> count_lock)); for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ M[0][i*N+j] = M[0][i*N+j] * escalar; } } for(k=1;k<8;++k){ for(i=0;i<N;++i){ for(j=inicio;j<fin;++j){ M[k][i+j*N] = M[k][i+j*N] * escalar; } } } pthread_mutex_lock(&(barrera -> count_lock)); barrera -> count ++; if (barrera -> count == T){ barrera -> count = 0; pthread_cond_broadcast(&(barrera -> ok_to_proceed)); }else{ pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock)); } pthread_mutex_unlock(&(barrera -> count_lock)); for(k=1;k<8;++k){ if(k%2==1){ for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ R[i*N+j]=0; for(c=0;c<N;++c){ R[i*N+j]+=M[0][i*N+c]*M[k][c+j*N]; } } } } else { for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ M[0][i*N+j]=0; for(c=0;c<N;++c){ M[0][i*N+j]+=R[i*N+c]*M[k][c+j*N]; } } } } } } int main(int argc,char*argv[]){ int i,j,k; double timetick; if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[2])) <= 0)) { printf("\\nUsar: %s n t\\n n: Dimension de la matriz (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]); exit(1); } R=(double*)malloc(sizeof(double)*N*N); for(i=0;i<8;i++){ M[i]=(double*)malloc(sizeof(double)*N*N); } for(k=0;k<8;++k){ for(i=0;i<N;++i){ for(j=0;j<N;++j){ M[k][i*N+j] = (double) (rand() % 1000000000); } } } pthread_t p_threads[T]; pthread_attr_t attr; pthread_attr_init (&attr); int id[T]; pthread_mutex_init(&mutexMax, 0); pthread_mutex_init(&mutexMin, 0); pthread_mutex_init(&mutexAvg, 0); barrera = (barrier*)malloc(sizeof(barrier)); barrera -> count = 0; pthread_mutex_init(&(barrera -> count_lock), 0); pthread_cond_init(&(barrera -> ok_to_proceed), 0); min=9999; max=-999; suma=0; timetick = dwalltime(); for(i=0;i<T;i++){ id[i]=i; pthread_create(&p_threads[i], &attr, hilar, (void *) &id[i]); } for(i=0;i<T;i++){ pthread_join(p_threads[i],0); } printf("\\nTiempo en segundos %f\\n", dwalltime() - timetick); if(8%2 == 1){ free(R); R=M[0]; } free(barrera); free(R); for(i=1;i<8;i++){ free(M[i]); } return(0); }
1
#include <pthread.h> main() { int semId,semval,fd,i,j; struct sembuf v1,v2; pthread_t tid1,tid2; char rdbuf1[20],rdbuf2[20]; pthread_mutex_t m1,m2; if(fork()==0) { printf("In child process %d\\n",getpid()); printf("Enter message\\n"); scanf("%s",rdbuf1); for(i=0;rdbuf1[i];i++) { pthread_mutex_lock(&m2); write(fd,&rdbuf1[i],1); printf("%c\\n",rdbuf1[i]); pthread_mutex_unlock(&m1); } } else { printf("In Parent process\\n"); printf("Enter message2\\n"); scanf("%s",rdbuf2); for(j=0;rdbuf2[j];j++) { pthread_mutex_lock(&m1); write(fd,&rdbuf2[j],1); printf("%c\\n",rdbuf1[j]); pthread_mutex_unlock(&m2); } } close(fd); }
0
#include <pthread.h> uint64_t nb; FILE * file; char str[60]; pthread_t thread0; pthread_t thread1; pthread_mutex_t lock; void* thread_prime_factors(void * u); void print_prime_factors(uint64_t n); void* thread_prime_factors(void * u) { pthread_mutex_lock(&lock); while ( fgets(str, 60, file)!=0 ) { nb=atol(str); pthread_mutex_unlock(&lock); print_prime_factors(nb); pthread_mutex_lock(&lock); } pthread_mutex_unlock(&lock); return 0; } void print_prime_factors(uint64_t n) { printf("%ju : ", n ); uint64_t i; for( i=2; n!=1 ; i++ ) { while (n%i==0) { n=n/i; printf("%ju ", i); } } printf("\\n"); return; } int main(void) { printf("En déplaçant la boucle de lecture dans chacun des threads :\\n"); file = fopen ("fileQuestion4pasEfficace.txt","r"); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_create(&thread0, 0, thread_prime_factors, 0); pthread_create(&thread1, 0, thread_prime_factors, 0); pthread_join(thread0, 0); pthread_join(thread1, 0); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> struct common_ctx_t_ { uint8_t printer_tid; uint8_t cur_count; bool cur_count_handled; uint8_t total_count; bool do_debug; pthread_mutex_t mtx; pthread_cond_t cv; }; struct thread_ctx_t_ { uint8_t thread_id; common_ctx_t *common_ctx; }; static void * counting_fn(void *arg) { thread_ctx_t *thread_ctx = (thread_ctx_t *) arg; common_ctx_t *ctx = thread_ctx->common_ctx; const uint8_t id = thread_ctx->thread_id; if (ctx->do_debug) { printf("%s: starting thread %u\\n", __func__, id); } pthread_mutex_lock(&(ctx->mtx)); while (1) { if (id == ctx->printer_tid) { printf("%s: (thread %u) cur_count=%u\\n", __func__, id, ctx->cur_count); ctx->cur_count_handled = 1; pthread_cond_broadcast(&(ctx->cv)); } if (ctx->cur_count >= ctx->total_count) { break; } pthread_cond_wait(&(ctx->cv), &(ctx->mtx)); } pthread_mutex_unlock(&(ctx->mtx)); if (ctx->do_debug) { printf("%s: finishing thread %u\\n", __func__, id); } pthread_exit(0); } int main(int argc, char **argv) { static const uint8_t THREAD_COUNT = 5; static const uint8_t TOTAL_COUNT = 50; static const bool DO_DEBUG = 0; common_ctx_t ctx = {0}; pthread_t threads[THREAD_COUNT]; thread_ctx_t *thread_ctx[THREAD_COUNT] = {0}; uint8_t *tid; uint8_t i; ctx.total_count = TOTAL_COUNT; ctx.do_debug = DO_DEBUG; pthread_mutex_init(&(ctx.mtx), 0); pthread_cond_init(&(ctx.cv), 0); for (i = 0; i < THREAD_COUNT; ++i) { thread_ctx[i] = malloc(sizeof(*thread_ctx[i])); if (0 == thread_ctx[i]) { printf("%s: allocation failure\\n", __func__); goto done; } thread_ctx[i]->thread_id = (i + 1); thread_ctx[i]->common_ctx = &ctx; pthread_create(&threads[i], 0, counting_fn, thread_ctx[i]); } tid = &(ctx.printer_tid); pthread_mutex_lock(&(ctx.mtx)); *tid = 0; for (ctx.cur_count = 1; ctx.cur_count <= ctx.total_count; ++(ctx.cur_count)) { *tid = (*tid >= THREAD_COUNT) ? 1 : (*tid + 1); ctx.cur_count_handled = 0; printf("%s: cur_count=%u\\n", __func__, ctx.cur_count); pthread_cond_broadcast(&(ctx.cv)); while (!ctx.cur_count_handled) { pthread_cond_wait(&(ctx.cv), &(ctx.mtx)); } } pthread_mutex_unlock(&(ctx.mtx)); done: for (i = 0; i < THREAD_COUNT; ++i) { if (0 != thread_ctx[i]) { pthread_join(threads[i], 0); free(thread_ctx[i]); thread_ctx[i] = 0; } } printf("%s: %u threads finished\\n", __func__, THREAD_COUNT); pthread_mutex_destroy(&(ctx.mtx)); pthread_cond_destroy(&(ctx.cv)); return 0; }
0
#include <pthread.h> sem_t dataBaseController; pthread_mutex_t mutex; pthread_t writters[1], readers[5]; int rc = 0, n; int data[1]; int dataBase[6]; void readDataBase(int i){ printf("O leitor %d leu a informacao %d do banco de dados\\n", i, dataBase[rand()%6]); usleep(500000); } void useDataRead(int i){ printf("O leitor %d utilizou o dado lido\\n", i); usleep(500000); } void thinkUpData(int i){ data[i]=rand()%100; Sleep(4); printf("O escritor %d produziu nova informacao\\n",i); } void initiateDataBaseVector(){ for(n=0;n<6;n++) dataBase[n] = 0; } void reader(int i) { while(1) { pthread_mutex_lock(&mutex); rc = rc + 1; if (rc == 1) sem_wait(&dataBaseController); pthread_mutex_unlock(&mutex); readDataBase(i); pthread_mutex_lock(&mutex); rc = rc - 1; if (rc == 0) sem_post(&dataBaseController); pthread_mutex_unlock(&mutex); useDataRead(i); } } void writeDataBase(int i){ printf("O escritor %d esta escrevendo a informacao %d no banco de dados\\n", i, data[i]); Sleep(4); dataBase[rand()%6] = data[i]; } void writer(int i) { while(1) { thinkUpData(i); sem_wait(&dataBaseController); writeDataBase(i); sem_post(&dataBaseController); } } void createWritersThreads(){ for(n=0;n<1;n++) pthread_create(&writters[n], 0, (void *)writer, (int *)n); } void createReadersThreads(){ for(n=0;n<5;n++) pthread_create(&readers[n], 0, (void *)reader, (int *)n); } int main(){ initiateDataBaseVector(); sem_init(&dataBaseController,0,1); pthread_mutex_init(&mutex, 0); createWritersThreads(); createReadersThreads(); getchar(); pthread_join(writters[0],0); exit((0)); }
1
#include <pthread.h> int g_wpmsg_num = 0; struct wpmsglist *g_wpmsg_list = 0; pthread_mutex_t g_wpmsglist_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t g_wpd_mutex = PTHREAD_MUTEX_INITIALIZER; struct wpmsg { int len; unsigned char *data; }; struct wpmsglist { struct wpmsglist *next; struct wpmsg *wpmsg; }; struct wpmsg *init_wpmsg() { struct wpmsg *wpmsg = (struct wpmsg *)calloc(1, sizeof(struct wpmsg)); return wpmsg; } static int inline get_wpmsg(struct wpmsglist **wpmsg_list, struct wpmsg **wpmsg) { struct wpmsglist *current = *wpmsg_list; if (current == 0) return 0; current = current->next; *wpmsg = (*wpmsg_list)->wpmsg; free(*wpmsg_list); (*wpmsg_list) = current; return 1; } struct wpmsg *create_wpmsg(unsigned char **buf, int len) { struct wpmsg *one = 0; if (buf == 0 || len < 0) return 0; one = init_wpmsg(); one->len = len; one->data = *buf; return one; } void destroy_wpmsg(struct wpmsg **wpmsg) { if ((wpmsg != 0 && (*wpmsg) != 0)) { if((*wpmsg )->data != 0) { free((*wpmsg )->data); ((*wpmsg)->data) = 0; } free(*wpmsg); (*wpmsg) = 0; } } void destroy_wpmsg_list(struct wpmsglist **wpmsg_list) { struct wpmsglist *current = *wpmsg_list; if(current == 0) { printf("[%s %d][WARNING] Asked to delete empty list!\\n", __FUNCTION__, 75); return; } while(current != 0) { current = current->next; free((*wpmsg_list)->wpmsg->data); free((*wpmsg_list)->wpmsg); free(*wpmsg_list); (*wpmsg_list) = current; } } void add_wpmsg(struct wpmsg* wpmsg, struct wpmsglist **wpmsg_list) { struct wpmsglist *tail = 0; struct wpmsglist *tmp = *wpmsg_list; if (!wpmsg) { printf("[%s %d] pointer wpmsg is NULL, no add and return \\n", __FUNCTION__, 94); return; } tail = (struct wpmsglist*)calloc(1, sizeof(struct wpmsglist)); tail->wpmsg = wpmsg; tail->next = 0; if ((*wpmsg_list) == 0) { (*wpmsg_list) = tail; } else { while (tmp->next != 0) tmp = tmp->next; tmp->next = tail; } } int main(int argc, char **argv) { struct wpmsg *pwpmsg = 0; unsigned char *pmsg; int buflen = 10000; int i = 0; for (i = 0; i < 100; ++i) { pmsg = (unsigned char*)calloc(1, buflen); struct wpmsg *tmp = create_wpmsg(&pmsg, buflen); pthread_mutex_lock(&g_wpmsglist_mutex); if (tmp && g_wpmsg_num < 1000) { add_wpmsg(tmp, &g_wpmsg_list); g_wpmsg_num++; printf("len %d, add to list number %d\\n", buflen, g_wpmsg_num); } else { free(pmsg); pmsg = 0; } pthread_mutex_unlock(&g_wpmsglist_mutex); } while (g_wpmsg_num) { pthread_mutex_lock(&g_wpmsglist_mutex); if (g_wpmsg_num > 0) { if (get_wpmsg(&g_wpmsg_list, &pwpmsg)) { g_wpmsg_num--; printf("len %d, DEL list number %d\\n", pwpmsg->len, g_wpmsg_num); } } pthread_mutex_unlock(&g_wpmsglist_mutex); if (pwpmsg) { destroy_wpmsg(&pwpmsg); pwpmsg = 0; } } }
0
#include <pthread.h> void hashpipe_thread_args_init(struct hashpipe_thread_args *a) { a->thread_desc=0; a->instance_id=0; a->cpu_mask=0; a->finished=0; pthread_cond_init(&a->finished_c,0); pthread_mutex_init(&a->finished_m,0); memset(&a->st, 0, sizeof(hashpipe_status_t)); a->ibuf = 0; a->obuf = 0; } void hashpipe_thread_args_destroy(struct hashpipe_thread_args *a) { a->finished=1; pthread_cond_destroy(&a->finished_c); pthread_mutex_destroy(&a->finished_m); } void hashpipe_thread_set_finished(struct hashpipe_thread_args *a) { pthread_mutex_lock(&a->finished_m); a->finished=1; pthread_cond_broadcast(&a->finished_c); pthread_mutex_unlock(&a->finished_m); } int hashpipe_thread_finished(struct hashpipe_thread_args *a, float timeout_sec) { struct timeval now; struct timespec twait; int rv; pthread_mutex_lock(&a->finished_m); gettimeofday(&now,0); twait.tv_sec = now.tv_sec + (int)timeout_sec; twait.tv_nsec = now.tv_usec * 1000 + (int)(1e9*(timeout_sec-floor(timeout_sec))); if (a->finished==0) rv = pthread_cond_timedwait(&a->finished_c, &a->finished_m, &twait); rv = a->finished; pthread_mutex_unlock(&a->finished_m); return(rv); }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; enum BUS_STATUS { BUS_ON_BUSY =0, BUS_OFF_BUSY =1, BUS_ON_LOCK =2, BUS_OFF_LOCK =3, }; enum BUS_ADDR_MAP { BUS_SLAVE_1_ST = 0x00000100, BUS_SLAVE_1_ED = 0x000001ff, BUS_SLAVE_2_ST = 0x00000200, BUS_SLAVE_2_ED = 0x000002ff, BUS_MASTER_1_ST = 0x00000300, BUS_MASTER_1_ED = 0x000003ff, }; int FmAddr; int ToAddr; int Data[4]; int Busy; int Lock; } Bus_Buf; Bus_Buf BusPtr; int TEST_COT=0; void Bus_Initial(){ BusPtr.Busy = BUS_OFF_BUSY; BusPtr.Lock = BUS_OFF_LOCK; } void *MASTER_1_Transmitter(void *t){ long my_id = (long)t; while( TEST_COT < 3 ){ int cot =10; while( BusPtr.Busy == BUS_ON_BUSY ){ sleep(1); if( cot==0 ){ printf("Out-of-Time-Wait M1 Transmitter retry...\\n"); break; } cot--; } if( cot>0 ){ printf("M1 Transmitter @ %d\\n", TEST_COT); pthread_mutex_lock(&count_mutex); BusPtr.FmAddr = BUS_MASTER_1_ST; BusPtr.ToAddr = ( TEST_COT%2==0 )? BUS_SLAVE_1_ST: BUS_SLAVE_2_ST; BusPtr.Busy = BUS_ON_BUSY; pthread_mutex_unlock(&count_mutex); } else { sleep(2); } sleep(3); } pthread_exit(0); } void *MASTER_1_Receiver(void *t){ long my_id = (long)t; int cot =10; while( TEST_COT < 3 ){ while( BusPtr.Busy == BUS_ON_BUSY && BusPtr.Lock == BUS_OFF_LOCK ){ sleep(1); if( cot==0 ){ printf("Out-of-Time wait M1 Receiver retry...\\n"); break; } cot--; } int i; if( cot>0 && BUS_MASTER_1_ST <= BusPtr.FmAddr && BusPtr.FmAddr <= BUS_MASTER_1_ED ){ pthread_mutex_lock(&count_mutex); BusPtr.Busy = BUS_OFF_BUSY; BusPtr.Lock = BUS_OFF_LOCK; for(i=0; i<4; i++){ printf("M1 Receive Fm %d,%d,%d\\n",BusPtr.ToAddr,i,BusPtr.Data[i]); } printf("M1 Reveive Done @ %d\\n",TEST_COT); printf("\\n"); TEST_COT++; pthread_mutex_unlock(&count_mutex); } else { sleep(2); } sleep(3); } pthread_exit(0); } void *SLAVE_1_DO(void *t){ long my_id = (long)t; while( TEST_COT < 3 ){ while( BusPtr.Busy == BUS_OFF_BUSY ){ sleep(1); } int i; if( BUS_SLAVE_1_ST <= BusPtr.ToAddr && BusPtr.ToAddr <= BUS_SLAVE_1_ED ){ pthread_mutex_lock(&count_mutex); BusPtr.Lock = BUS_ON_LOCK; for(i=0; i<4; i++){ BusPtr.Data[i] = i+10; } pthread_mutex_unlock(&count_mutex); } else { sleep(3); } sleep(3); } pthread_exit(0); } void *SLAVE_2_DO(void *t){ long my_id = (long)t; while( TEST_COT < 3 ){ while( BusPtr.Busy == BUS_OFF_BUSY ){ sleep(1); } int i; if( BUS_SLAVE_2_ST <= BusPtr.ToAddr && BusPtr.ToAddr <= BUS_SLAVE_2_ED ){ pthread_mutex_lock(&count_mutex); BusPtr.Lock = BUS_ON_LOCK; for(i=0; i<4; i++){ BusPtr.Data[i] = i+100; } pthread_mutex_unlock(&count_mutex); } else { sleep(3); } sleep(3); } pthread_exit(0); } int main(int argc,char* argv[]){ Bus_Initial(); pthread_t thread[4]; pthread_create( &thread[0],0, MASTER_1_Transmitter, 0); pthread_create( &thread[1],0, MASTER_1_Receiver, 0); pthread_create( &thread[2],0, SLAVE_1_DO, 0); pthread_create( &thread[3],0, SLAVE_2_DO, 0); pthread_join( thread[0],0); pthread_join( thread[1],0); pthread_join( thread[2],0); pthread_join( thread[3],0); pthread_exit(0); return 0; }
0
#include <pthread.h> int count[5]={0}; int inputs[10000]={0}; void *job(void *); pthread_mutex_t mutexprotect; int main(){ pthread_t t[5]; int tstatus[5]; int i=0,j=0; time_t tim; srand((int) tim); for(j=0;j<10000;j++){ inputs[j]=(rand()%5); printf("%d",inputs[j],"\\n"); } for(i=0;i<5;i++){ tstatus[i]=pthread_create(&t[i],0,job,(void*) i); printf("Thread Started =%d \\n",i); } for(i=0;i<5;i++) pthread_join(t[i],0); int total=0; for(i=0;i<5;i++){ printf("\\nCount of %d=%d",i,count[i],"\\n"); total=total+count[i]; } printf("\\nTotal=%d",total); } void *job(void *i){ int j=0; j=(int) i; int k=0; k=j; while(k<10000){ pthread_mutex_lock(&mutexprotect); switch (inputs[k]){ case 0: count[0]++; break; case 1: count[1]++; break; case 2: count[2]++; break; case 3: count[3]++; break; case 4: count[4]++; break; } pthread_mutex_unlock(&mutexprotect); k=k+5; } pthread_exit((void*) 0); }
1
#include <pthread.h> int data[50]; int occupied; int nextin; int nextout; pthread_mutex_t *buflock; pthread_cond_t *objects; pthread_cond_t *room; } Buffer; void *prime_thread(void *args); int main(){ Buffer *buffer1; int val = 2; buffer1 = malloc(sizeof(Buffer)); buffer1->occupied = 0; buffer1->nextin = 0; buffer1->nextout = 0; pthread_t next_thread; pthread_mutex_t block = PTHREAD_MUTEX_INITIALIZER; buffer1->buflock = &block; pthread_cond_t objects = PTHREAD_COND_INITIALIZER; buffer1->objects = &objects; pthread_cond_t room = PTHREAD_COND_INITIALIZER; buffer1->room = &room; pthread_create(&next_thread, 0, prime_thread, (void *)buffer1); do{ pthread_mutex_lock(buffer1->buflock); while(buffer1->occupied == 50){ pthread_cond_wait(buffer1->room, buffer1->buflock); } buffer1->data[buffer1->nextin] = val; buffer1->nextin = (buffer1->nextin + 1) % 50; buffer1->occupied = buffer1->occupied +1; pthread_mutex_unlock(buffer1->buflock); pthread_cond_signal(buffer1->objects); val = val + 1; }while(1); return 0; } void *prime_thread(void *args) { int prime = 0; int next = 0; pthread_t next_thread; Buffer *buffer1, *buffer2; buffer1 = malloc(sizeof(Buffer)); buffer2 = (Buffer *) args; buffer1 = malloc(sizeof(Buffer)); pthread_mutex_t block = PTHREAD_MUTEX_INITIALIZER; buffer1->buflock = &block; pthread_cond_t objects = PTHREAD_COND_INITIALIZER; buffer1->objects = &objects; pthread_cond_t room = PTHREAD_COND_INITIALIZER; buffer1->room = &room; do{ int number; pthread_mutex_lock(buffer2->buflock); while(buffer2->occupied == 0){ pthread_cond_wait(buffer2->objects, buffer2->buflock); } if(prime == 0){ prime = buffer2->data[buffer2->nextout]; buffer2->nextout = (buffer2->nextout + 1) % 50; buffer2->occupied = buffer2->occupied - 1; printf("[%d]", prime); pthread_cond_signal(buffer2->room); pthread_mutex_unlock(buffer2->buflock); continue; } number = buffer2->data[buffer2->nextout]; buffer2->nextout = (buffer2->nextout + 1) % 50; buffer2->occupied = buffer2->occupied - 1; pthread_cond_signal(buffer2->room); pthread_mutex_unlock(buffer2->buflock); if(number % prime == 0){ continue; } if(next == 0){ pthread_create(&next_thread, 0, &prime_thread, (void *)buffer1); next = 1; } pthread_mutex_lock(buffer1->buflock); while(buffer1->occupied == 50){ pthread_cond_wait(buffer1->room, buffer1->buflock); } buffer1->data[buffer1->nextin] = number; buffer1->nextin = (buffer1->nextin + 1) % 50; buffer1->occupied = buffer1->occupied +1; pthread_cond_signal(buffer1->objects); pthread_mutex_unlock(buffer1->buflock); }while(1); }
0
#include <pthread.h> int elementos[10]; int in = 0; int out = 0; int total = 0; int producidos = 0, consumidos = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t consume_t = PTHREAD_COND_INITIALIZER; pthread_cond_t produce_t = PTHREAD_COND_INITIALIZER; void * productor(void *); void * consumidor(void *); int main(int argc, const char * argv[]) { srand((int) time(0)); int nhilos = 5 + 3; pthread_t * obreros = (pthread_t *) malloc (sizeof(pthread_t) * nhilos); int indice = 0; pthread_t * aux; for (aux = obreros; aux < (obreros+5); ++aux) { printf("--- Creando el productor %d ---\\n", ++indice); pthread_create(aux, 0, productor, (void *) indice); } indice = 0; for (; aux < (obreros+nhilos); ++aux) { printf("--- Creando el consumidor %d ---\\n", ++indice); pthread_create(aux, 0, consumidor, (void *) indice); } for (aux = obreros; aux < (obreros+nhilos); ++aux) { pthread_join(*aux, 0); } free(obreros); return 0; } void * productor(void * arg) { int id = (int) arg; while (producidos < 100) { usleep(rand() % 500); pthread_mutex_lock(&mutex); if (total < 10) { elementos[in] = producidos; printf(" +++ (Productor %d) Se produjo el elemento %d\\n", id, elementos[in]); ++producidos; ++in; in %= 10; ++total; if (total == 1) { pthread_cond_broadcast(&consume_t); } } else { printf("zzzzz (Productor %d) se va a dormir \\n", id); pthread_cond_wait(&produce_t, &mutex); printf("uuuuu (Productor %d) se despertó \\n", id); } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void * consumidor(void * arg) { int id = (int) arg; while (consumidos < 100) { usleep(rand() % 500); pthread_mutex_lock(&mutex); if (total > 0) { printf(" --- (Consumidor %d) Se consumió el elemento %d\\n", id, elementos[out]); ++consumidos; ++out; out %= 10; --total; if (total == 10 -1) { pthread_cond_broadcast(&produce_t); } } else { printf("ZZZZZ (Consumidor %d) se va a dormir \\n", id); pthread_cond_wait(&consume_t, &mutex); printf("UUUUU (Consumidor %d) se despertó \\n", id); } pthread_mutex_unlock(&mutex); } pthread_exit(0); }
1
#include <pthread.h> struct UpdateThreadParams { int min; int max; }; void* gridUpdateThread(void* param); void finishTick(); void finishCount(); void finishTickInit(); int threadCount = 0; int threadsDone = 0; bool ticksPaused = 0; pthread_cond_t pauseCond; pthread_cond_t unpauseCond; pthread_mutex_t threadsDoneMutex; pthread_cond_t threadsDoneCond; int countsDone = 0; pthread_mutex_t countsDoneMutex; pthread_cond_t countsDoneCond; int initsDone = 0; pthread_mutex_t initsDoneMutex; pthread_cond_t initsDoneCond; pthread_mutex_t swapGridsMutex; time_t lastTick; float tpsArray[20]; int tpsArrayPos = 0; float tpsAverage; void startGridUpdater(int threads) { for (int i = 0; i < 20; i++) tpsArray[i] = 0; threadCount = threads; int rangeSize = GRID_W / threads; for (int i = 0; i < threads; i++) { struct UpdateThreadParams *params = malloc(sizeof(struct UpdateThreadParams)); params->min = i * rangeSize; params->max = params->min + rangeSize; printf("Starting thread %i, rendering %i-%i\\n", i, params->min, params->max); pthread_attr_t* attrs = malloc(sizeof(pthread_attr_t)); pthread_attr_init(attrs); pthread_t* thread = malloc(sizeof(pthread_t)); pthread_create(thread, attrs, gridUpdateThread, params); } } void* gridUpdateThread(void* p) { struct UpdateThreadParams *params = (struct UpdateThreadParams*)p; while (1) { for (int y = 0; y < GRID_H; y++) { for (int x = params->min; x < params->max; x++) { updateNeighbors(x, y); } } finishCount(); for (int y = 0; y < GRID_H; y++) { for (int x = params->min; x < params->max; x++) { if (nGrid[x][y] & 0b00100000) updateLife(x, y); } } finishTick(); for (int y = 0; y < GRID_H; y++) { for (int x = params->min; x < params->max; x++) { nGrid[x][y] = cGrid[x][y]; } } finishTickInit(); } } void finishTickInit() { pthread_mutex_lock(&initsDoneMutex); initsDone++; if (initsDone >= threadCount) { pthread_cond_broadcast(&initsDoneCond); initsDone = 0; } else { pthread_cond_wait(&initsDoneCond, &initsDoneMutex); } pthread_mutex_unlock(&initsDoneMutex); } void finishCount() { pthread_mutex_lock(&countsDoneMutex); countsDone++; if (countsDone >= threadCount) { pthread_cond_broadcast(&countsDoneCond); countsDone = 0; } else { pthread_cond_wait(&countsDoneCond, &countsDoneMutex); } pthread_mutex_unlock(&countsDoneMutex); } void finishTick() { pthread_mutex_lock(&threadsDoneMutex); threadsDone++; if (threadsDone >= threadCount) { if (ticksPaused) { pthread_cond_signal(&pauseCond); pthread_cond_wait(&unpauseCond, &threadsDoneMutex); } pthread_cond_broadcast(&threadsDoneCond); struct timespec now; clock_gettime(CLOCK_MONOTONIC_COARSE, &now); float cTps = 1000000000 / (float)(now.tv_nsec - lastTick); tpsArray[tpsArrayPos] = cTps; tpsArrayPos++; if (tpsArrayPos >= 20) tpsArrayPos = 0; float avgTotal = 0; for (int i = 0; i < 20; i++) avgTotal += tpsArray[i]; tpsAverage = avgTotal / (float)20; lastTick = now.tv_nsec; threadsDone = 0; swapGrids(); } else { pthread_cond_wait(&threadsDoneCond, &threadsDoneMutex); } pthread_mutex_unlock(&threadsDoneMutex); } void awaitTick() { pthread_mutex_lock(&threadsDoneMutex); pthread_cond_wait(&threadsDoneCond, &threadsDoneMutex); pthread_mutex_unlock(&threadsDoneMutex); } void lockTick() { pthread_mutex_lock(&threadsDoneMutex); ticksPaused = 1; pthread_cond_wait(&pauseCond, &threadsDoneMutex); pthread_mutex_unlock(&threadsDoneMutex); } void unlockTick() { pthread_mutex_lock(&threadsDoneMutex); ticksPaused = 0; pthread_cond_broadcast(&unpauseCond); pthread_mutex_unlock(&threadsDoneMutex); } void swapGrids() { lockSwapGrids(); char (*tGrid)[GRID_W][GRID_H] = currentGrid; currentGrid = newGrid; newGrid = tGrid; unlockSwapGrids(); } void lockSwapGrids() { pthread_mutex_lock(&swapGridsMutex); } void unlockSwapGrids() { pthread_mutex_unlock(&swapGridsMutex); }
0
#include <pthread.h> int allocate_map(); int allocate_pid(); int release_pid(int pid); void* test_method(void *p); unsigned int *pidMap; pthread_mutex_t *locks; int mapSize; int allocate_map() { if (pidMap != 0) { free(pidMap); } mapSize = ceil((5000 -300)/32.0); pidMap = (unsigned int*)malloc(mapSize * sizeof(int)); locks = (pthread_mutex_t*)malloc(mapSize * sizeof(int)); sleep(2); int success = 0; if (pidMap != 0) { for(int x = 0; x++; x < mapSize) { pidMap[x] = 0; pthread_mutex_init(&locks[x], 0); } success = 1; } return success; } int allocate_pid() { int pid = -1; for(int x = 0; x < mapSize; x++) { pthread_mutex_lock(&locks[x]); if (pidMap[x] != ~0) { int y = ffs(~pidMap[x]); pidMap[x] |= 1 << (y - 1); pid = 300 + x * 32 + (32 - y); pthread_mutex_unlock(&locks[x]); break; } pthread_mutex_unlock(&locks[x]); } if(pid > 5000) pid = -1; return pid; } int release_pid(int pid) { pid -= 300; int block = pid / 32; int spot = pid % 32; pthread_mutex_lock(&locks[block]); int bitSelector = (1 << (31 - spot)); int ret = pidMap[block] & bitSelector; pidMap[block] &= ~bitSelector; pthread_mutex_unlock(&locks[block]); return !!ret; } int main(){ pthread_t *threads = (pthread_t*)malloc(sizeof(pthread_t) * 100); allocate_map(); for(int t = 0; t < 100; t++) { fflush(stdout); int ret; while (ret = pthread_create(&threads[t], 0, &test_method,(void*)t)) { if(ret == EAGAIN || errno == EAGAIN) printf("Can't create more threads.\\n"); } } printf("All threads allocated\\n"); for(int t = 0; t < 100; t++){ void *end; pthread_join(threads[t], &end); } int sum = 0; for(int t = 0; t < mapSize; t++) { sum += pidMap[t]; } if(sum) printf("Not all threads were freed appropriately.\\n"); } void *test_method(void *threadid) { int pid = allocate_pid(); int sec = rand() % 3; sleep(sec); int ret = release_pid(pid); if(!ret) printf("Thread %d was freed inappropriately.\\n", pid); fflush(stdout); pthread_exit(0); }
1
#include <pthread.h> static int cant_hilos; static int resto; static pthread_mutex_t lock; static int tarea = -1; static int A[4000][4000], B[4000][4000], C[4000][4000]; struct indices { int i, j; }; void cargarMatrices(); void realizarTarea(indice indiceGral); void *mapearTarea(void *); indice getIndice(int); double getTime(); void imprimirMatrices(); int main(int argc, char *argv[]){ int i, j, k, token; pthread_t *hilos; double t1, t2; if (argc!=2) { fprintf(stderr, "Modo de uso: ./mm1d <cantidad_de_hilos>\\n"); return -1; } cant_hilos=atoi(argv[1]); hilos = (pthread_t *)malloc(sizeof(pthread_t) * (cant_hilos-1)); pthread_mutex_init(&lock, 0); cargarMatrices(); printf("Ok!!\\n\\n"); printf("Multiplicacion ...\\n"); pthread_setconcurrency(cant_hilos); t1=getTime(); for (i=0; i < cant_hilos-1; i++) pthread_create(hilos+i, 0, mapearTarea, 0); mapearTarea(0); for (i=0; i < cant_hilos-1; i++) pthread_join(hilos[i], 0); t2=getTime(); if (4000 <= 10 && 4000 <= 10 && 4000 <= 10){ imprimirMatrices(); } printf("\\n\\nDuracion total de la multilplicacion de matrices %4f segundos\\n", t2-t1); } void cargarMatrices(){ int i, j = 0; for (i=0; i < 4000; i++) for (j=0; j < 4000; j++) A[i][j] = (j+3) * (i+1); for (i=0; i < 4000; i++) for (j=0; j < 4000; j++) B[i][j] = i+j; for (i=0; i < 4000; i++) for (j=0; j < 4000; j++) C[i][j] = 0; } void realizarTarea(indice indiceGral) { int k,j; for(j=0;j<4000;j++){ for (k=0; k < 4000; k++) C[indiceGral.i][j] += A[indiceGral.i][k] * B[k][j]; } } void *mapearTarea(void *arg) { while (1) { pthread_mutex_lock(&lock); tarea++; pthread_mutex_unlock(&lock); if ( tarea >= 4000) return 0; indice indiceGral = getIndice(tarea); realizarTarea(indiceGral); } } indice getIndice(int tarea) { indice indiceGral; indiceGral.i = tarea % 4000; return indiceGral; } double getTime() { struct timeval t; gettimeofday(&t, 0); return (double)t.tv_sec+t.tv_usec*0.000001; } void imprimirMatrices() { int i, j = 0; printf("Imprimimos matrices...\\n"); printf("Matriz A\\n"); for (i=0; i < 4000; i++) { printf("\\n\\t| "); for (j=0; j < 4000; j++) printf("%d ", A[i][j]); printf("|"); } printf("\\n"); printf("Matriz B\\n"); for (i=0; i < 4000; i++) { printf("\\n\\t| "); for (j=0; j < 4000; j++) printf("%d ", B[i][j]); printf("|"); } printf("\\n"); printf("Matriz C\\n"); for (i=0; i < 4000; i++) { printf("\\n\\t| "); for (j=0; j < 4000; j++) printf("%d ", C[i][j]); printf("|"); } printf("\\n"); }
0
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct list { struct list *next; int exiting; enum eid_vwr_state_event e; void* data; void (*free)(void*); void (*done)(void*); } *cmdlist = 0; static void* thread_main(void* val) { int rv; if((rv = pthread_mutex_lock(&mutex)) != 0) { be_log(EID_VWR_LOG_COARSE, TEXT("Could not lock mutex: %s"), strerror(rv)); } for(;;) { while(cmdlist != 0) { struct list *tmp = cmdlist; if(cmdlist->exiting != 0) { goto exit; } cmdlist = cmdlist->next; pthread_mutex_unlock(&mutex); sm_handle_event_onthread(tmp->e, tmp->data); if(tmp->done != 0) { tmp->done(tmp->data); } pthread_mutex_lock(&mutex); if(tmp->free != 0) { tmp->free(tmp->data); } free(tmp); } pthread_cond_wait(&cond, &mutex); } exit: pthread_mutex_unlock(&mutex); return 0; } static void add_item(struct list* item) { struct list **ptr; pthread_mutex_lock(&mutex); ptr = &cmdlist; while(*ptr != 0) { ptr = &((*ptr)->next); } *ptr = item; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } void sm_stop_thread() { struct list *item = (struct list *)calloc(sizeof(struct list), 1); item->exiting = 1; add_item(item); } void sm_start_thread() { pthread_t thread; pthread_create(&thread, 0, thread_main, 0); } void sm_handle_event(enum eid_vwr_state_event e, void* data, void(*freefunc)(void*), void(*donefunc)(void*)) { struct list *item = (struct list *)calloc(sizeof(struct list), 1); item->e = e; item->data = data; item->free = freefunc; add_item(item); }
1
#include <pthread.h> struct mytask { char c; }; void showtask(struct mytask *p) { printf("%c\\n",p->c); sleep(1); } int quit; void * start(void * arg) { struct myqueue *myq = arg; struct mytask *p = 0; while(1) { pthread_mutex_lock(&myq->lock); while(myq->empty(myq)) { if(1 == quit) { pthread_mutex_unlock(&myq->lock); goto end; } pthread_cond_wait(&myq->cond,&myq->lock); } p = myq->get(myq); pthread_mutex_unlock(&myq->lock); showtask(p); free(p); } end: return 0; } int main() { int i; pthread_t pt[10]; int n; struct myqueue myq; init_myqueue(&myq); struct mytask *myt = 0; int flag; int pid = open("fifo",O_RDONLY); if(pid == -1) { fprintf(stderr,"can't open the file\\n"); return -1; } n = pthread_create(&pt[0],0,start,&myq); n = pthread_create(&pt[1],0,start,&myq); n = pthread_create(&pt[2],0,start,&myq); if(n != 0) { close(pid); fprintf(stderr,"can't create\\n"); return -1; } while(1) { myt = malloc(sizeof(struct mytask)); n = read(pid,myt,sizeof(struct mytask)); if(n == 0) { quit = 1; pthread_cond_broadcast(&myq.cond); close(pid); break; } pthread_mutex_lock(&myq.lock); flag = myq.empty(&myq); myq.put(&myq,myt); pthread_mutex_unlock(&myq.lock); if(flag) { pthread_cond_broadcast(&myq.cond); } } while(i<10) { pthread_join(pt[i],0); i++; } close(pid); return 0; }
0