text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct v { int row; int column; }; void *worker(void* coord); void *show_matrix(); pthread_t my_thread[(3*3)+1]; int A[3][2] = { {1,4}, {2,5}, {3,6} }; int B[2][3] = { {8,7,6}, {5,4,3} }; int C[3][3]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void print_matrix() { int i; int j; pthread_mutex_lock(&mutex); printf("\\n"); for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { printf(" %d ", C[i][j]); } printf("\\n"); } printf("\\n"); pthread_mutex_unlock(&mutex); } void *worker( void* coord) { int sum = 0; coordenate coords = *((coordenate*) coord); int i; pthread_mutex_lock(&mutex); printf("This thread is working in C[%d][%d]\\n",coords.row, coords.column); for (i = 0; i < 2; i++) { sum += A[coords.row][i] * B[i][coords.column]; } C[coords.row][coords.column] = sum; pthread_mutex_unlock(&mutex); } void *show_matrix() { int i; for (i = 0; i < 10; i++) { print_matrix(); sleep(1); } pthread_exit(0); } int main() { int id = 0; coordenate* coords; pthread_create(&my_thread[id], 0, show_matrix, 0); id++; for (int i = 0; i < 3; i++){ for (int j = 0; j < 3; j++){ coords = (coordenate*) malloc(sizeof(coordenate)); coords->row = i; coords->column = j; pthread_create(&my_thread[id], 0, worker, coords); id++; sleep(1); } } for (int k = 0; k < 3*3; k++) { pthread_join(my_thread[k], 0); } free(coords); printf("Let's see the final result\\n"); print_matrix(); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> static unsigned int gSharedValue = 0; static int gReaderCount = 0, gWaitingReaderCount = 0; pthread_mutex_t gSharedMemLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gReadPhase = PTHREAD_COND_INITIALIZER; pthread_cond_t gWritePhase = PTHREAD_COND_INITIALIZER; void *readerMain(void *arg); void *writerMain(void *arg); int main() { int read_threadNum[5]; int write_threadNum[5]; pthread_t read_thread[5]; pthread_t write_thread[5]; srand(time(0)); for (int i = 0; i < 5; i++) { read_threadNum[i] = i; pthread_create(&read_thread[i], 0, readerMain, &read_threadNum[i]); } for (int i = 0; i < 5; i++) { write_threadNum[i] = i; pthread_create(&write_thread[i], 0, writerMain, &write_threadNum[i]); } for (int i = 0; i < 5; i++) { pthread_join(read_thread[i], 0); } for (int i = 0; i < 5; i++) { pthread_join(write_thread[i], 0); } return 0; } static void read_lock(int *numReaders) { pthread_mutex_lock(&gSharedMemLock); gWaitingReaderCount++; while (gReaderCount == -1) pthread_cond_wait(&gReadPhase, &gSharedMemLock); gWaitingReaderCount--; *numReaders = ++gReaderCount; pthread_mutex_unlock(&gSharedMemLock); } static void read_unlock() { pthread_mutex_lock(&gSharedMemLock); gReaderCount--; if (gReaderCount == 0) pthread_cond_signal(&gWritePhase); pthread_mutex_unlock(&gSharedMemLock); } static void write_lock(int *numReaders) { pthread_mutex_lock(&gSharedMemLock); while (gReaderCount != 0) pthread_cond_wait(&gWritePhase, &gSharedMemLock); gReaderCount = -1; *numReaders = gReaderCount; pthread_mutex_unlock(&gSharedMemLock); } static void write_unlock() { pthread_mutex_lock(&gSharedMemLock); gReaderCount = 0; if (gWaitingReaderCount > 0) pthread_cond_broadcast(&gReadPhase); else pthread_cond_signal(&gWritePhase); pthread_mutex_unlock(&gSharedMemLock); } void *readerMain(void *arg) { int id = *((int *)arg); int numReaders = 0; for (int i = 0; i < 5; i++) { sleep(rand() % 5 + 5); read_lock(&numReaders); printf("ReadId: %d Value: %d ReaderCount: %d\\n", id, gSharedValue, numReaders); read_unlock(); } pthread_exit(0); } void *writerMain(void *arg) { int id = *((int *)arg); int numReaders = 0; for (int i = 0; i < 5; i++) { sleep(rand() % 5 + 5); write_lock(&numReaders); printf("WriteId: %d Value: %d ReaderCount: %d\\n", id, ++gSharedValue, numReaders); write_unlock(); } pthread_exit(0); }
0
#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[4]; int sorted[4]; void producer () { int i, idx; for (i = 0; i < 4; i++) { idx = findmaxidx (source, 4); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 4); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 4; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 4); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 4; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> int p; int n; int t; double* A; double* x; double* c; double* y; int counter = 0; pthread_mutex_t mutex; pthread_cond_t cond_var; pthread_barrier_t barrier; void Gen_matrix(double A[], int n); void Gen_vectorXC(double x[], double c[], int n); void *Pth_mat_vect(void* rank); void *Pth_mat_vectBar(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; int i, j, v; double start, finish; n = atoi(argv[1]); t = atoi(argv[2]); p = atoi(argv[3]); v = atoi(argv[4]); thread_handles = malloc(p*sizeof(pthread_t)); A = malloc(n*n*sizeof(double)); x = malloc(n*sizeof(double)); c = malloc(n*sizeof(double)); y = malloc(n*sizeof(double)); GET_TIME(start); Gen_matrix(A, n); Gen_vectorXC(x, c, n); if (v==1) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_var, 0); for (thread = 0; thread < p; thread++) { pthread_create(&thread_handles[thread], 0, Pth_mat_vect, (void*) thread); } for (thread = 0; thread < p; thread++) { pthread_join(thread_handles[thread], 0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_var); } else { pthread_barrier_init(&barrier, 0, p); for (thread = 0; thread < p; thread++) { pthread_create(&thread_handles[thread], 0, Pth_mat_vectBar, (void*) thread); } for (thread = 0; thread < p; thread++) { pthread_join(thread_handles[thread], 0); } pthread_barrier_destroy(&barrier); } if (n < 30) { for (j = 0; j < n; j++) { printf("%6.3f ",x[j]); } } else { for (j = 0; j < 30; j++) { printf("%6.3f ",x[j]); } } printf("\\n"); free(thread_handles); free(A); free(x); free(c); free(y); GET_TIME(finish); printf("Total time: %e\\n",finish-start); return 0; } void Gen_matrix(double A[], int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if (i==j) { A[i*n+j] = 0.0; } else { A[i*n+j] = -1.0/(double)n; } } } } void Gen_vectorXC(double x[], double c[], int n) { int i, j; for (i = 0; i < n; i++) { x[i] = 0.0; } for (j = 0; j < n; j++) { c[j] = (double)j/(double)n; } } void *Pth_mat_vect(void* rank) { long my_rank = (long) rank; int i; int j; int k; int l; int local_n = n/p; int my_first_row = my_rank*local_n; int my_last_row = my_first_row + local_n; for (k = 0; k < t; k++) { for (i = my_first_row; i < my_last_row; i++) { y[i] = 0.0; for (j = 0; j < n; j++) { y[i] += A[i*n+j] * x[j]; } y[i] += c[i]; } pthread_mutex_lock(&mutex); counter++; if (counter == p) { for (l = 0; l < n; l++) { x[l] = y[l]; } counter = 0; pthread_cond_broadcast(&cond_var); } else { while (pthread_cond_wait(&cond_var, &mutex) != 0); } pthread_mutex_unlock(&mutex); } return 0; } void *Pth_mat_vectBar(void* rank) { long my_rank = (long) rank; int i; int j; int k; int l; int local_n = n/p; int my_first_row = my_rank*local_n; int my_last_row = my_first_row + local_n; for (k = 0; k < t; k++) { for (i = my_first_row; i < my_last_row; i++) { y[i] = 0.0; for (j = 0; j < n; j++) { y[i] += A[i*n+j] * x[j]; } y[i] += c[i]; } pthread_barrier_wait(&barrier); if (my_rank == 0) { for (l = 0; l < n; l++) { x[l] = y[l]; } } pthread_barrier_wait(&barrier); } return 0; }
0
#include <pthread.h> static char *page; static int page_nr = 10; static int page_len; static pthread_mutex_t _syscall_mtx; void usage(const char *argv0) { exit(1); } static void recover(void) { printf("hello: recovered from pagefault\\n"); exit(0); } static void pgflt_handler(uintptr_t addr, uint64_t fec, struct dune_tf *tf) { int ret; ptent_t *pte; pthread_mutex_lock(&_syscall_mtx); ret = dune_vm_lookup(pgroot, (void *) addr, CREATE_NORMAL, &pte); assert(ret==0); long offset = 0; *pte = PTE_P | PTE_W | PTE_ADDR(dune_va_to_pa((void *) addr)); rdma_read_offset((void *)addr, (__u64)addr - (__u64) page ); pthread_mutex_unlock(&_syscall_mtx); } int main(int argc, char *argv[]) { int i,n; volatile int ret; char* val; struct timeval t0, t1, t2, t3; page_nr = atoi(argv[3]); page_len = ( 1<<12 )*page_nr; gettimeofday(&t0, 0); if (posix_memalign((void **)&page, ( 1<<12 ), page_len)) { perror("init page memory failed"); return -1; } memset( page,0, page_len); val= (char*) malloc(page_len); memcpy(val, page, page_len); if (madvise(page, page_len, MADV_DONTNEED)) { perror("madvise failed"); return -1; } gettimeofday(&t1, 0); assert(!memcmp(val, page, page_len)); gettimeofday(&t2, 0); long pagefault = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec; long total = (t2.tv_sec-t0.tv_sec)*1000000 + t2.tv_usec-t0.tv_usec; fprintf(stdout, "%ld %ld\\n", pagefault, total); return 0; }
1
#include <pthread.h> void *thread_fmain(void *); void *thread_mmain(void *); void man_leave(); void man_enter(); void woman_leave(); void woman_enter(); void use_rr(); void do_other_stuff(); int get_simple_tid(pthread_t); int maleCount = 0; int femaleCount=0; pthread_t threadIDs[2 +2]; sem_t male_semaphore; sem_t female_semaphore; pthread_mutex_t male_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t female_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t male_full = PTHREAD_COND_INITIALIZER; pthread_cond_t female_full = PTHREAD_COND_INITIALIZER; int main() { pthread_attr_t attribs; int i; int tids[2 +2]; pthread_t pthreadids[2 +2]; sem_init(&male_semaphore, 0, 2); sem_init(&female_semaphore, 0, 2); pthread_mutex_init(&male_mutex, 0); pthread_mutex_init(&female_mutex, 0); srandom(time(0) % (unsigned int) 32767); pthread_attr_init(&attribs); for (i=0; i< 2; i++) { tids[i] = i; pthread_create(&(pthreadids[i]), &attribs, thread_fmain, &(tids[i])); } for (i=0; i< 2; i++) { tids[i+2] = i+2; pthread_create(&(pthreadids[i]), &attribs, thread_mmain, &(tids[i+2])); } for (i=0; i< 2 +2; i++) pthread_join(pthreadids[i], 0); return 0; } void *thread_fmain(void * arg) { int tid = *((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); woman_enter(); use_rr(); woman_leave(); } } void *thread_mmain(void * arg) { int tid = * ((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); man_enter(); use_rr(); man_leave(); } } void woman_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread f%d trying to get in the restroom\\n", id); pthread_mutex_lock(&female_mutex); while(femaleCount == 2){ pthread_cond_wait(&female_full, &female_mutex); } sem_wait(&female_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++femaleCount; pthread_mutex_unlock(&female_mutex); printf("Thread f%d got in!\\n", id); printf("Wait time for thread f%d was %f\\n", id, waittime); } void woman_leave() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&female_mutex); sem_post(&female_semaphore); --femaleCount; pthread_cond_broadcast(&female_full); pthread_mutex_unlock(&female_mutex); printf("thread f %d left!\\n",id); } void man_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread m%d trying to get in the restroom\\n", id); pthread_mutex_lock(&male_mutex); while(maleCount == 2){ pthread_cond_wait(&male_full, &male_mutex); } sem_wait(&male_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++maleCount; pthread_mutex_unlock(&male_mutex); printf("Thread f%d got in!\\n", id); printf("Wait time for thread m%d was %f\\n", id, waittime); } void man_leave() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&male_mutex); sem_post(&male_semaphore); --maleCount; pthread_cond_broadcast(&male_full); pthread_mutex_unlock(&male_mutex); printf("Thread m%d left!\\n", id); } void use_rr() { struct timespec req, rem; double usetime; usetime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(usetime); req.tv_nsec = (unsigned int) ( (usetime - (int) floor(usetime)) * 1000000000); printf("Thread %d using restroom for %lf time\\n", get_simple_tid(pthread_self()), usetime); nanosleep(&req,&rem); } void do_other_stuff() { struct timespec req, rem; double worktime; worktime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(worktime); req.tv_nsec = (unsigned int) ( (worktime - (int) floor(worktime)) * 1000000000); printf("Thread %d working for %lf time\\n", get_simple_tid(pthread_self()), worktime); nanosleep(&req,&rem); } int get_simple_tid(pthread_t lid) { int i; for (i=0; i<2 +2; i++) if (pthread_equal(lid, threadIDs[i])) return i; printf("Oops! did not find a tid for %lu\\n", lid); _exit(-1); }
0
#include <pthread.h> int availableRooms = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* agentA(void* arg){ pthread_mutex_lock(&mutex); if(availableRooms > 0){ availableRooms -= 1; printf("Available rooms = A %d\\n", availableRooms); } pthread_mutex_unlock(&mutex); pthread_exit(0); } void* agentB(void* arg){ pthread_mutex_lock(&mutex); if(availableRooms > 0){ availableRooms -= 1; printf("Available rooms = B %d\\n", availableRooms); } pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char* argv[]){ if (argc < 2){ printf("Please enter the number of available rooms as an argument when running the program\\n"); exit(1); } availableRooms = atoi(argv[1]); pthread_t tid1; pthread_t tid2; while (availableRooms > 0){ pthread_create(&tid1, 0, agentA, 0); pthread_create(&tid2, 0, agentB, 0); } pthread_join(tid1, 0); pthread_join(tid2, 0); }
1
#include <pthread.h> struct gsm_buf_t gsm; void *thread_gsm(void *arg) { char cmd[512] = {0}; while(1) { gsm_recv(gsm_fd, "0", "1"); memset(cmd, 0, sizeof(cmd)); pthread_rwlock_rdlock(&gsmcmd_mutex); memcpy(cmd,gsm_cmd,strlen(gsm_cmd)); pthread_rwlock_unlock(&gsm_mutex); if(strncmp(cmd, "0", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '0'); pthread_mutex_unlock(&M0ctr_mutex); printf("led on\\n"); continue; } if(strncmp(cmd, "1", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '1'); pthread_mutex_unlock(&M0ctr_mutex); printf("led off\\n"); continue; } if(strncmp(cmd, "2", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '2'); pthread_mutex_unlock(&M0ctr_mutex); printf("hum on\\n"); continue; } if(strncmp(cmd, "3", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '3'); pthread_mutex_unlock(&M0ctr_mutex); printf("hum off\\n"); continue; } if(strncmp(cmd, "4", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '4'); pthread_mutex_unlock(&M0ctr_mutex); printf("fan on\\n"); continue; } if(strncmp(cmd, "5", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '5'); pthread_mutex_unlock(&M0ctr_mutex); printf("fan off\\n"); continue; } if(strncmp(cmd, "6", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '6'); pthread_mutex_unlock(&M0ctr_mutex); printf("fan off\\n"); continue; } if(strncmp(cmd, "7", 1) == 0) { pthread_mutex_lock(&M0ctr_mutex); env_send(zgb_fd, '7'); pthread_mutex_unlock(&M0ctr_mutex); printf("fan off\\n"); continue; } } printf("gsm thread exited\\n"); pthread_exit(0); }
0
#include <pthread.h> long long biggest = 100; int m; int n; pthread_t* thread_handles; int* array; } arg_struct; pthread_mutex_t mutex; void* Find_greatest(void* args) { int local_big = 100; arg_struct* t = (arg_struct*)args; int* array = t->array; for (int i = 0; i < n; i++) { if (local_big < array[i] && array[i] < 1001) { pthread_mutex_lock(&mutex); local_big = array[i]; pthread_mutex_unlock(&mutex); } } if (biggest < local_big) { pthread_mutex_lock(&mutex); biggest = local_big; pthread_mutex_unlock(&mutex); } return 0; } int main(void) { srand(time(0)); int count = 0; m = rand() % (21 - 10) + 10; n = rand() % (1001 - 100) + 100; while (n % m != 0) { n++; } int* a; a = (int*)malloc(sizeof(int) * n); for (int tt = 0; tt < n; tt++) { int r = rand() % (1001 - 100) + 100; a[tt] = r; } int** segments = malloc((m) * sizeof(int*)); for (int tt = 0; tt < m; tt++) { segments[tt] = malloc((n) * sizeof(int)); for (int i = 0; i < n; i++) { segments[tt][i] = a[count]; count++; } } pthread_mutex_init(&mutex, 0); thread_handles = malloc(m * sizeof(pthread_t)); for (int tt = 0; tt < m; tt++) { arg_struct t; t.array = segments[tt]; pthread_create(thread_handles, 0, &Find_greatest, &t); } for (int t = 0; t < m; t++) { pthread_join(thread_handles[t], 0); } pthread_mutex_destroy(&mutex); free(thread_handles); printf("%lld\\n", biggest); return 0; }
1
#include <pthread.h> pthread_mutex_t pal1, pal2, pal3, pal4, pal5; void * codigoFilos1(){ printf("Hola soy el filosofo 1 y estoy pensando\\n"); pthread_mutex_lock(&pal1); printf("Yo filos 1 voy a comer un poco\\n"); pthread_mutex_unlock(&pal1); pthread_mutex_init(&pal2, 0); } void * codigoFilos2(){ printf("Hola soy el filosofo 2 y estoy pensandon\\n"); pthread_mutex_lock(&pal2); printf("Yo filos 2 voy a comer un poco\\n"); pthread_mutex_unlock(&pal2); pthread_mutex_init(&pal3, 0); } void * codigoFilos3(){ printf("Hola soy el filosofo 3 y estoy pensando\\n"); pthread_mutex_lock(&pal3); printf("Yo filos 3 voy a comer un poco\\n"); pthread_mutex_unlock(&pal3); pthread_mutex_init(&pal4, 0); } void * codigoFilos4(){ printf("Hola soy el filosofo 4 y estoy pensando\\n"); pthread_mutex_lock(&pal4); printf("Yo filos 4 voy a comer un poco\\n"); pthread_mutex_unlock(&pal4); pthread_mutex_init(&pal5, 0); } void * codigoFilos5(){ printf("Hola soy el filosofo 5 y estoy pensando\\n"); pthread_mutex_lock(&pal5); printf("Yo filos 5 voy a comer un poco\\n"); pthread_mutex_unlock(&pal5); pthread_mutex_init(&pal1, 0); } int main(){ pthread_t filos1; pthread_t filos2; pthread_t filos3; pthread_t filos4; pthread_t filos5; pthread_mutex_init(&pal1, 0); pthread_create(&filos1, 0, codigoFilos1, 0); pthread_create(&filos2, 0, codigoFilos2, 0); pthread_create(&filos3, 0, codigoFilos3, 0); pthread_create(&filos4, 0, codigoFilos4, 0); pthread_create(&filos5, 0, codigoFilos5, 0); }
0
#include <pthread.h> extern pthread_mutex_t message_mutex; extern pthread_cond_t message_consume_cond; static pthread_t lc_threads[10]; static void* thread_message_consume(void* arg); void threadpool_message_consume_init() { int i = 0; for(i=0; i<10; i++) { Pthread_create(&lc_threads[i], 0, &thread_message_consume, 0); } } void thread_message_consume_destory() { } static void* thread_message_consume(void* arg) { bmessage_t* pMsg; while(1) { pthread_mutex_lock(&message_mutex); pthread_cond_wait(&message_consume_cond, &message_mutex); pthread_mutex_unlock(&message_mutex); pMsg = message_queue_pop(); if(pMsg != 0) { switch(pMsg->header.id) { case 10000: controller_user_login(pMsg); break; case 10001: controller_user_list(pMsg); break; case 10100: controller_hall_enter(pMsg); break; case 10101: controller_hall_sitdown(pMsg); break; default: printf("Have not controller %d!\\n", pMsg->header.id); break; } message_free(pMsg); } } return 0; }
1
#include <pthread.h> void read_from_click_thread(void *p) { struct device_data* dev = (struct device_data*)p; unsigned int ret = 0, j; unsigned char buff[4] = {0, 0, 0, 0}; unsigned long rfc_sleep_time = THREAD_SLEEP_TIME; while(1) { if(pCMDValue.exit_time>0 && pCMDValue.exit_time<time(0)) break; if(ret==0) { ret = recv_from_peer(dev->con, (char*)dev->click_read_tmp_buffer, 100); if(ret<0) ret = 0; } else { pthread_mutex_lock(&dev->click_read_mutex); if(10000-dev->click_read_buffer_length>ret ) { memcpy(dev->click_read_buffer+dev->click_read_buffer_length, dev->click_read_tmp_buffer, ret); dev->click_read_buffer_length +=ret; ret=0; rfc_sleep_time = THREAD_SLEEP_TIME; } pthread_mutex_unlock(&dev->click_read_mutex); } if(rfc_sleep_time > rfc_sleep_time) usleep( rfc_sleep_time ); if(rfc_sleep_time < THREAD_MAX_SLEEP_TIME) rfc_sleep_time += rfc_sleep_time; } printf("exit: click read\\n"); pthread_exit(p); }
0
#include <pthread.h> void *cmd_serail(void * arg) { char readbuffer[256]; int readsize, itmp; int batteryNumber = 0; int serialfd = (int) arg; int i; readsize = 0; while (1) { memset(readbuffer, 0, sizeof(char) * 100); for (i = 0; i < 3; i++) { itmp = read(serialfd, readbuffer[readsize], 100); if (itmp > 0) { readsize += itmp; i = 1; } else { i++; } } if ((readsize > 0)) { if ((strncmp(readbuffer, "s800bm", 6) != 0) && (readsize != 8)) { write(serialfd, "command formart error!", 22); } else { switch (readbuffer[6]) { case 0x01: pthread_mutex_lock(&s800bm_mutex); write(serialfd, &group_battery, sizeof(battery_pack)); pthread_mutex_unlock(&s800bm_mutex); break; case 0x02: batteryNumber = readbuffer[7]; if (batteryNumber > 0 && batteryNumber <= BATTERY_TOTAL) { pthread_mutex_lock(&s800bm_mutex); write(serialfd, &group_battery.single_bat[batteryNumber - 1], sizeof(single_battery)); pthread_mutex_unlock(&s800bm_mutex); } else { write(serialfd, "battery number error!", 21); } break; case 0x03: pthread_mutex_lock(&s800bm_mutex); write(serialfd, &group_battery.group_current, sizeof(float)); pthread_mutex_unlock(&s800bm_mutex); break; case 0x04: pthread_mutex_lock(&s800bm_mutex); write(serialfd, &group_battery.group_current, sizeof(float)); pthread_mutex_unlock(&s800bm_mutex); break; default: write(serialfd, "no such command!", 16); break; } } continue; } else { break; } } return 0; }
1
#include <pthread.h> int * enteroCompartido; pthread_mutex_t * semaforo; void * procedimiento(void * in) { int tid = (int) in, i; for(i = 0; i < 10000; i++) { pthread_mutex_lock(semaforo); enteroCompartido[0]++; if(!(i+1 < 10000)) printf("Hola soy la hebra %d y el ultimo numero que deje fue %d\\n", tid, *enteroCompartido); pthread_mutex_unlock(semaforo); } } int main(int argc, char * argv[]) { enteroCompartido = (int*) malloc(sizeof(int)); semaforo = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(semaforo, 0); int i, j = 4; pthread_t * hebra1 = (pthread_t*) malloc(sizeof(pthread_t) * 4); for(i = 0; i < j; i++) pthread_create(&hebra1[i], 0, &procedimiento, (void*) i); for(i = 0; i < j; i++) pthread_join(hebra1[i], 0); printf("Hebra padre ha terminado de esperar por sus hijas\\n"); printf("- Finalmente enteroCompartido= %d\\n", *enteroCompartido); }
0
#include <pthread.h> static uint8_t sys_irq_disable_counter; static pthread_mutexattr_t critical_mutexattr; static pthread_mutex_t critical_mutex_id; void platform_critical_init(void) { int err = pthread_mutexattr_init(&critical_mutexattr); assert(err == 0); err = pthread_mutexattr_settype(&critical_mutexattr, PTHREAD_MUTEX_RECURSIVE_NP); assert(err == 0); err = pthread_mutex_init(&critical_mutex_id, &critical_mutexattr); assert(err == 0); } void platform_critical_cleanup(void) { int err = pthread_mutex_destroy(&critical_mutex_id); assert(err == 0); err = pthread_mutexattr_destroy(&critical_mutexattr); assert(err == 0); } void platform_enter_critical(void) { pthread_mutex_lock(&critical_mutex_id); sys_irq_disable_counter++; } void platform_exit_critical(void) { --sys_irq_disable_counter; pthread_mutex_unlock(&critical_mutex_id); }
1
#include <pthread.h> static void to_worker_thread (struct job_details *job) { struct job_details *ljob; my_printf("%s: giving job %d to workers sched: %s \\n", __FUNCTION__, job->seqno, ((sched_policy == SCHED_FCFS) ? "fcfs" : "sjf")); pthread_mutex_lock(&worker_mutex); if (sched_policy == SCHED_FCFS) { if (job_head2) { job->next2 = job_head2; job_head2->prev2 = job; } job_head2 = job; if (job_tail2 == 0) { job_tail2 = job; } } if (sched_policy == SCHED_SJF) { if (!job_head2) { job_head2 = job_tail2 = job; goto done; } if (job->response_size > job_head2->response_size) { job->next2 = job_head2; job_head2->prev2 = job; job_head2 = job; goto done; } if (job_tail2->response_size > job->response_size) { job->prev2 = job_tail2; job_tail2->next2 = job; job_tail2 = job; goto done; } ljob = job_head2; while (ljob) { if (ljob->response_size < job->response_size) { break; } ljob = ljob->next2; } job->next2 = ljob; job->prev2 = ljob->prev2; ljob->prev2->next2 = job; ljob->prev2 = job; } done: sem_post(&worker_sem); pthread_cond_signal(&worker_cond_mutex); pthread_mutex_unlock(&worker_mutex); } static struct job_details * from_sched_queue (void) { struct job_details *job; sem_wait(&sched_sem); pthread_mutex_lock(&sched_mutex); job = job_tail1; job_tail1 = job->prev1; if (job_tail1) { job_tail1->next1 = 0; } if (job_head1 == job) { job_head1 = 0; } pthread_mutex_unlock(&sched_mutex); job->prev1 = job->next1 = 0; my_printf("schedular got job %d\\n", job->seqno); return job; } void * schedule_thread (void) { struct job_details *job; my_printf("%s: warming up for %d sec\\n", __FUNCTION__, warmup_time); sleep(warmup_time); my_printf("%s: ready to go \\n", __FUNCTION__); while (1) { job = from_sched_queue(); my_printf("%s: processing job %d\\n", __FUNCTION__, job->seqno); to_worker_thread(job); } pthread_exit(0); }
0
#include <pthread.h> int main() { int fd = shm_open("shm1", O_CREAT | O_RDWR, 0644); if (fd < 0) { printf("shm_open error\\n"); exit(-1); } printf("fd=%d\\n", fd); int len = sizeof(struct Test); ftruncate(fd, len); printf("ftruncate\\n"); printf("len=%d\\n", len); struct Test* p = (struct Test*)mmap(0, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); printf("mmap\\n"); close(fd); printf("close\\n"); pthread_mutexattr_t mattr; pthread_mutexattr_init(&mattr); pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&p->m1, &mattr); printf("pthread_mutex_init\\n"); pthread_mutex_init(&p->m2, &mattr); while(1) { pthread_mutex_lock(&p->m1); pthread_mutex_lock(&p->m2); printf("progress1\\n"); pthread_mutex_unlock(&p->m2); pthread_mutex_unlock(&p->m1); } pthread_mutex_destroy(&p->m1); pthread_mutex_destroy(&p->m2); return 0; }
1
#include <pthread.h> pthread_mutex_t kuaizi[5]; void *zhexuejia( void *arg ) { int i = (int) arg; int left, right; if ( i == 0 ) { left = 0; right = 5 - 1; } else { left = i; right = i - 1; } while ( 1 ) { if ( i < 5 - 1 ) { pthread_mutex_lock( &kuaizi[left] ); pthread_mutex_lock( &kuaizi[right] ); printf( "i=====%d....%lu....eating\\n", i, pthread_self() ); pthread_mutex_unlock( &kuaizi[right] ); pthread_mutex_unlock( &kuaizi[left] ); sleep( rand() % 5 ); printf( "i======%d,%lu....thinking....\\n", i, pthread_self() ); } else if ( i == 5 - 1 ) { pthread_mutex_lock( &kuaizi[right] ); pthread_mutex_lock( &kuaizi[left] ); printf( "i=====%d,%lu....eating\\n", i, pthread_self() ); pthread_mutex_unlock( &kuaizi[left] ); pthread_mutex_unlock( &kuaizi[right] ); sleep( rand() % 5 ); printf( "i=====%d,%lu....thinking....\\n", i, pthread_self() ); } } } int main() { pthread_t tid[5]; int i = 0; for ( i = 0; i < 5; i++ ) { pthread_mutex_init( &kuaizi[i], 0 ); } for ( i = 0; i < 5; i++ ) { pthread_create( &tid[i], 0, zhexuejia, (void *) i ); } for ( i = 0; i < 5; i++ ) { pthread_join( tid[i], 0 ); } return 0; }
0
#include <pthread.h> int value; pthread_mutex_t mutex; pthread_cond_t cond; }sema_t; int N=3; double sleepTime; int mailBox[2]; sema_t read_sema; sema_t write_sema; int readCount=0; int circleCount; void sema_init(sema_t *sema, int value) { sema->value = value; pthread_mutex_init(&sema->mutex, 0); pthread_cond_init(&sema->cond, 0); } void sema_wait(sema_t *sema) { pthread_mutex_lock(&sema->mutex); sema->value--; if(sema->value < 0) pthread_cond_wait(&sema->cond, &sema->mutex); pthread_mutex_unlock(&sema->mutex); } void sema_signal(sema_t *sema) { pthread_mutex_lock(&sema->mutex); ++sema->value; pthread_cond_signal(&sema->cond); pthread_mutex_unlock(&sema->mutex); } void* ring(void*arg){ int *id; int content; id=(int*)arg; char flag=0; int circle=circleCount; while(circle>0){ sema_wait(&read_sema); if(readCount==0) sema_wait(&write_sema); readCount++; sema_signal(&read_sema); if(*id==((mailBox[0]-1)%N+1)){ flag=1; content=mailBox[1]; } sema_wait(&read_sema); readCount--; if(readCount==0) sema_signal(&write_sema); sema_signal(&read_sema); if(flag==1){ sema_wait(&write_sema); mailBox[0]=*id+1; mailBox[1]=content+1; sema_signal(&write_sema); int i; assert(*id==content%N+1); flag=0; circle--; } } } int main() { pthread_t worker_id[N]; int i,j; int param[N]; sema_init(&read_sema, 1); sema_init(&write_sema, 1); struct timeval start,end; N=1; circleCount=40000; for(j=0;j<3;j++){ sleepTime=0.1*pow(0.01,j+1); mailBox[0]=1; mailBox[1]=0; gettimeofday(&start,0); for(i=0;i<N;i++){ param[i]=i+1; pthread_create(&worker_id[i],0,ring,&param[i]); } for(i=0;i<N;i++){ pthread_join(worker_id[i],0); } gettimeofday(&end,0); int timeuse=1000000*(end.tv_sec-start.tv_sec)+end.tv_usec-start.tv_usec; printf("timeuse:%d us,core number:%d,circleCount:%d,sleepTime:%.9lf\\n",timeuse,N,circleCount,sleepTime); } N=4; circleCount=10000; for(j=0;j<3;j++){ sleepTime=0.1*pow(0.01,j+1); mailBox[0]=1; mailBox[0]=1; mailBox[1]=0; gettimeofday(&start,0); for(i=0;i<N;i++){ param[i]=i+1; pthread_create(&worker_id[i],0,ring,&param[i]); } for(i=0;i<N;i++){ pthread_join(worker_id[i],0); } gettimeofday(&end,0); int timeuse=1000000*(end.tv_sec-start.tv_sec)+end.tv_usec-start.tv_usec; printf("timeuse:%d us,core number:%d,circleCount:%d,sleepTime:%.9lf\\n",timeuse,N,circleCount,sleepTime); } N=2; circleCount=20000; for(j=0;j<3;j++){ sleepTime=0.1*pow(0.01,j+1); mailBox[0]=1; mailBox[0]=1; mailBox[1]=0; gettimeofday(&start,0); for(i=0;i<N;i++){ param[i]=i+1; pthread_create(&worker_id[i],0,ring,&param[i]); } for(i=0;i<N;i++){ pthread_join(worker_id[i],0); } gettimeofday(&end,0); int timeuse=1000000*(end.tv_sec-start.tv_sec)+end.tv_usec-start.tv_usec; printf("timeuse:%d us,core number:%d,circleCount:%d,sleepTime:%.9lf\\n",timeuse,N,circleCount,sleepTime); } return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t mutex_count; pthread_cond_t cond_limit; pthread_cond_t cond_count; void *counter(void *t) { long id = (long) t; while (1) { pthread_mutex_lock(&mutex_count); if (count == 12) { printf("Thread %ld chegou ao limite - acordando o nullificador.\\n", id); pthread_cond_signal(&cond_limit); pthread_cond_wait(&cond_count, &mutex_count); } printf("Thread %ld aumentou contador de %d para %d\\n", id, count++, count+1); pthread_mutex_unlock(&mutex_count); usleep(200000); } } void *nullify(void *t) { long id = (long) t; while (1) { pthread_mutex_lock(&mutex_count); if (count < 12) { printf("Thread %ld foi escalonada mas o contador não chegou ao limite.\\n",id); pthread_cond_wait(&cond_limit, &mutex_count); } while (count > 0) { printf("Thread %ld diminuiu o contador de %d para %d\\n", id, count--, count-1); usleep(200000); } pthread_mutex_unlock(&mutex_count); pthread_cond_broadcast(&cond_count); } } int main(int argc, char** argv) { long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&mutex_count, 0); pthread_cond_init(&cond_count, 0); pthread_cond_init(&cond_limit, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, nullify, (void *) t1); pthread_create(&threads[1], &attr, counter, (void *) t2); pthread_create(&threads[2], &attr, counter, (void *) t3); pthread_mutex_init(&mutex_count, 0); pthread_cond_init(&cond_count, 0); pthread_cond_init(&cond_limit, 0); int i; for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } return (0); }
0
#include <pthread.h> int num_threads; int count; pthread_mutex_t *mutexes; none, one, two } utensil; int phil_num; int course; utensil forks; }phil_data; int *numList; phil_data *philosophers; void *eat_meal(void *ptr){ phil_data *phil_ptr = ptr; int num = phil_ptr->phil_num; int hasBothForks; int i; for (i = 0; i < 3; i++) { hasBothForks = 0; while(!hasBothForks) { if (num > 0) { if (philosophers[num-1].forks != 2) { pthread_mutex_lock(&mutexes[num]); philosophers[num].forks = 1; } } else { if (philosophers[num_threads-1].forks != 2) { pthread_mutex_lock(&mutexes[num]); philosophers[num].forks = 1; } } if (philosophers[(num+1)%num_threads].forks == 0) { pthread_mutex_lock(&mutexes[(num+1)%num_threads]); philosophers[num].forks = 2; hasBothForks = 1; } else { pthread_mutex_unlock(&mutexes[num]); philosophers[num].forks = 0; } } usleep(1); philosophers[num].course += 1; printf("Philosopher %d has just eaten the course %d meal.\\n", num, philosophers[num].course); pthread_mutex_unlock(&mutexes[num]); pthread_mutex_unlock(&mutexes[(num+1)%num_threads]); philosophers[num].forks = 0; } return 0; } int main( int argc, char **argv ){ int num_philosophers, error; if (argc < 2) { fprintf(stderr, "Format: %s <Number of philosophers>\\n", argv[0]); return 0; } num_philosophers = num_threads = atoi(argv[1]); pthread_t threads[num_threads]; philosophers = malloc(sizeof(phil_data)*num_philosophers); mutexes = malloc(sizeof(pthread_mutex_t)*num_philosophers); int i; for( i = 0; i < num_philosophers; i++ ){ philosophers[i].phil_num = i; philosophers[i].course = 0; philosophers[i].forks = none; } error = 0; int isInitialized = 0; if (error == 0) { int i; for (i = 0; i < num_threads; i++) { if ((error = pthread_mutex_init(&mutexes[i], 0)) != 0) { printf("Failing to initialize mutex!\\n"); } } isInitialized = 1; } if (error == 0) { int i; for (i = 0; i < num_threads; i++) { if ((error = pthread_create(&threads[i], 0, (void *)eat_meal, (void *)(&philosophers[i]))) !=0) { printf("Failing to create thread!\\n"); } } } if (error == 0) { int i; for (i = 0; i < num_threads; i++) { if ((error = pthread_join(threads[i], 0)) != 0) { printf("Failing to join threads!\\n"); } } } if (isInitialized == 1) { error = pthread_mutex_destroy(mutexes); } free(philosophers); free(mutexes); return 0; }
1
#include <pthread.h> int spuf = -1; pthread_mutex_t pmut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t answ = PTHREAD_COND_INITIALIZER; const char *signa = SIGNATUR; int main(int argc, char **argv) { char *ptr; int sfd, n, fda; const int on = 1; sigset_t set; pthread_t tid; struct epoll_event ev = {.events = EPOLLIN}; struct timespec tp; if (argc < 3) { fprintf(stderr, "\\nUsage in private VM: %s <Splif host:port> <Private host:port> \\nUsage in public VM: %s <Splif port> <Public port>\\n\\n", argv[0], argv[0]); exit(1); } daemonize(); if (sigemptyset(&set) < 0) { syslog(LOG_ERR, "sigemtyset: %m"); } else { if (sigaddset(&set, SIGPIPE) < 0) { syslog(LOG_ERR, "sigaddset: %m"); } else { if ( (errno = pthread_sigmask(SIG_BLOCK, &set, 0)) != 0) syslog(LOG_ERR, "sigmask: %m"); } } if ( (efd = epoll_create(EPOLLCNK)) < 0) { syslog(LOG_CRIT, "epoll create: %m"); _exit(1); } if ( (errno = pthread_create(&tid, 0, mill, 0)) != 0) { syslog(LOG_CRIT, "mill create: %m"); _exit(1); } if ( (ptr = rindex(argv[1], ':')) != 0) { s_host = argv[1]; s_port = ptr + 1; *ptr = '\\0'; if ( (ptr = rindex(argv[2], ':')) == 0) { syslog(LOG_CRIT, "Bad argument: %s", argv[2]); _exit(1); } p_host = argv[2]; p_port = ptr + 1; *ptr = '\\0'; for (;;) { while ( (sfd = tcp_connect(s_host, s_port)) < 0) sleep(PINGTIME); if (setsockopt(sfd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0) syslog(LOG_ERR, "can't set keepalive: %m"); if (send(sfd, signa, sizeof cbuf, 0) < 0) { syslog(LOG_ERR, "sigsend: %m"); conres(sfd); continue; } armed: while ( (n = recv(sfd, &cbuf, sizeof cbuf, 0)) < 0 && errno == EINTR); if (n < 0) { syslog(LOG_ERR, "prirecv from splif: %m"); conres(sfd); continue; } if (n == 0) { close(sfd); continue; } if (n != sizeof cbuf) { syslog(LOG_ERR, "prisplif inadequate input"); goto armed; } if ( (fda = tcp_connect(p_host, p_port)) < 0) { goto armed; } if ( (fdb = tcp_connect(s_host, s_port)) < 0) { conres(fda); goto armed; } if (setsockopt(fdb, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0) syslog(LOG_ERR, "keepalive on pri-to-pub: %m"); ev.data.u64 = fda; ev.data.u64 <<= 32; ev.data.u64 |= fdb; if (epoll_ctl(efd, EPOLL_CTL_ADD, fdb, &ev) < 0) { syslog(LOG_ERR, "prifdb epoll add: %m"); conres(fda); conres(fdb); goto armed; } ev.data.u64 = fdb; ev.data.u64 <<= 32; ev.data.u64 |= fda; if (epoll_ctl(efd, EPOLL_CTL_ADD, fda, &ev) < 0) { syslog(LOG_ERR, "prifda epoll add: %m"); conres(fda); conres(fdb); goto armed; } if (send(fdb, &cbuf, sizeof cbuf, 0) < 0) { syslog(LOG_ERR, "prifinal send: %m"); conres(fda); conres(fdb); } goto armed; } } else { s_port = argv[1]; p_port = argv[2]; if ( (errno = pthread_create(&tid, 0, splifguard, 0)) != 0) { syslog(LOG_CRIT, "splifguard create: %m"); _exit(1); } sfd = tcp_listen(0, p_port); for (;;) { while ( (fda = accept(sfd, 0, 0)) < 0 && errno == EINTR); if (fda < 0) { syslog(LOG_CRIT, "pubaccept: %m"); _exit(1); } if (setsockopt(fda, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on) < 0) syslog(LOG_ERR, "pubaccept - can't disable Nagle: %m"); if (setsockopt(fda, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on) < 0) syslog(LOG_ERR, "keepalive on usr-to-pub: %m"); pthread_mutex_lock(&pmut); cbuf = fda; if (send(spuf, &cbuf, sizeof cbuf, 0) != sizeof cbuf) { syslog(LOG_ERR, "fda send incomplete, %m"); pthread_mutex_unlock(&pmut); conres(fda); continue; } clock_gettime(CLOCK_REALTIME_COARSE, &tp); tp.tv_sec += XTIMEOUT; while ( (n = pthread_cond_timedwait(&answ, &pmut, &tp)) != 0 && n == EINTR); if (n != 0) { syslog(LOG_ERR, "private end timed out"); pthread_mutex_unlock(&pmut); conres(fda); continue; } ev.data.u64 = fda; ev.data.u64 <<= 32; ev.data.u64 |= fdb; if (epoll_ctl(efd, EPOLL_CTL_ADD, fdb, &ev) < 0) goto puberr; ev.data.u64 = fdb; ev.data.u64 <<= 32; ev.data.u64 |= fda; if (epoll_ctl(efd, EPOLL_CTL_ADD, fda, &ev) < 0) goto puberr; pthread_mutex_unlock(&pmut); continue; puberr: syslog(LOG_ERR, "epoll add public duo: %m"); conres(fda); conres(fdb); pthread_mutex_unlock(&pmut); } } return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[5]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 5) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 5; if (push(arr, tmp) == (-1)) error(); pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 5; i++) { __CPROVER_assume(((5 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (top > 0) { if (pop(arr) == (-2)) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> struct foo { int id; int refs; struct foo* next; pthread_mutex_t mutex; }; int hash(int id) { return id % 10; } struct foo* map[10]; pthread_mutex_t hash_lock; struct foo* alloc(int id) { struct foo* p; if ((p = (struct foo*)malloc(sizeof(struct foo))) != 0) { p->id = id; p->refs = 1; if (pthread_mutex_init(&p->mutex, 0) != 0) { free(p); return 0; } printf("pid %ld tid %ld alloc id %d\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), id); } int index = hash(id); pthread_mutex_lock(&hash_lock); p->next = map[index]; map[index] = p; pthread_mutex_unlock(&hash_lock); return p; } void hold(struct foo* p) { pthread_mutex_lock(&hash_lock); p->refs++; pthread_mutex_unlock(&hash_lock); } struct foo* find(int id) { struct foo* p; pthread_mutex_lock(&hash_lock); for (p = map[hash(id)]; p != 0; p = p->next) { if (p->id = id) { break; } } pthread_mutex_unlock(&hash_lock); return p; } void release(struct foo* p) { pthread_mutex_lock(&hash_lock); if (--p->refs == 0) { int index = hash(p->id); struct foo* f = map[index]; if (f == p) { map[index] = p->next; } else { while (f->next != p) { f = f->next; } f->next = p->next; } pthread_mutex_destroy(&p->mutex); printf("pid %ld tid %ld free id %d\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), p->id); free(p); pthread_mutex_unlock(&hash_lock); } else { pthread_mutex_unlock(&p->mutex); } } void* thread_task(void* arg) { int i; for (i = 0; i < 10; i++) { alloc(i + 1); } } int main(int argc, char* argv[]) { pthread_mutex_init(&hash_lock, 0); pthread_t tid; int err = 0; int i; err = pthread_create(&tid, 0, thread_task, 0); if (err != 0) { err_exit(err, "can't create thread"); } sleep(1); for (i = 0; i < 10; i++) { struct foo* p = find(i + 1); release(p); } pthread_join(tid, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t * mutex_current_weight; pthread_cond_t * allow_robot; void * start_shopping(void *); int * current_weight; int * max_weight; int main(){ srand(time(0)); current_weight = (int *) malloc(10 * sizeof(int)); max_weight = (int *) malloc(10 * sizeof(int)); mutex_current_weight = (pthread_mutex_t *) malloc(10 * sizeof(pthread_mutex_t)); allow_robot = (pthread_cond_t *) malloc(10 * sizeof(pthread_cond_t)); pthread_t * robots = (pthread_t *) malloc(5 * sizeof(pthread_t)); int i,j,k; for(k = 0; k < 10; ++k){ *(current_weight + k) = 0; *(max_weight + k) = rand() % 4 + 5; pthread_mutex_init(mutex_current_weight + k,0); pthread_cond_init(allow_robot + k,0); } for(i = 0; i < 5; ++i) pthread_create(robots + i,0,start_shopping,(void *) i+1); for(j = 0; j < 5; ++j) pthread_join(*(robots+j),0); free(robots); free(allow_robot); free(mutex_current_weight); free(max_weight); free(current_weight); return 0; } void * start_shopping(void * arg){ int sections = rand() % 10 + 1; int weight = rand() % 3 + 1; int i; int robotID = (int) arg; int ready; for(i = 0; i <= sections; ++i){ if(i != sections){ ready = 0; pthread_mutex_lock(mutex_current_weight+i); while(ready == 0){ if((*(current_weight + i) + weight) > *(max_weight + i)){ printf("Robot %d is waiting to enter section %d\\n",robotID,i+1); pthread_cond_wait(allow_robot + i,mutex_current_weight+i); if((*(current_weight + i) + weight) <= *(max_weight + i)){ ready = 1; } } else ready = 1; } if(i != 0){ *(current_weight + (i-1)) -= weight; pthread_cond_broadcast(allow_robot + (i-1)); printf("Robot %d left section %d \\n",robotID,i); } } if(i == sections){ pthread_mutex_lock(mutex_current_weight+(i-1)); *(current_weight + (i-1)) -= weight; pthread_mutex_unlock(mutex_current_weight+(i-1)); pthread_cond_broadcast(allow_robot + (i-1)); printf("Robot %d left section %d \\n",robotID,i); break; } printf("Robot %d entered section %d \\n",robotID,i+1); *(current_weight + i) += weight; pthread_mutex_unlock(mutex_current_weight+i); printf("Robot %d is shopping at section %d \\n",robotID,i+1); sleep(rand() % 3 + 1); } printf("------- Robot %d has finished shopping ------- \\n",robotID); pthread_exit(0); }
1
#include <pthread.h> pthread_t tid[2]; int counter; pthread_mutex_t lock; void* doSomeThing1(void *arg) { int j = 0; printf("%s entering...", __func__); fflush(stdout); while(j < 10) { pthread_mutex_lock(&lock); printf("%s done\\n", __func__); if(j == 5) { pthread_mutex_unlock(&lock); return 0; } unsigned long i = 0; counter += 1; printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j); for(i=0; i<(0xFFFFFF);i++); printf("\\n Job %d finished, tid = %ldm i = %d\\n", counter, pthread_self(), j); pthread_mutex_unlock(&lock); ++j; sleep(1); } return 0; } void* doSomeThing2(void *arg) { int j = 0; printf("%s entering...", __func__); fflush(stdout); while(j < 10) { pthread_mutex_lock(&lock); printf("%s done\\n", __func__); unsigned long i = 0; counter += 1; printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j); for(i=0; i<(0xFFFFFF);i++); printf("\\n Job %d finished, tid = %ld, i = %d\\n", counter, pthread_self(), j); pthread_mutex_unlock(&lock); ++j; sleep(1); } return 0; } int main(void) { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_create(&tid[0], 0, doSomeThing1, 0); pthread_create(&tid[1], 0, doSomeThing2, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> pthread_mutex_t lock_a = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_b = PTHREAD_MUTEX_INITIALIZER; int notify_a = 0; int notify_b = 0; void *func(void *arg) { pthread_mutex_lock(&lock_b); printf("func thread get lock_b, wanna get lock_a! \\n"); notify_b = 1; while (!notify_a) usleep(50); pthread_mutex_lock(&lock_a); printf("func thread get lock_a & lock_b! \\n"); pthread_mutex_unlock(&lock_a); pthread_mutex_unlock(&lock_b); } int main(int argc, char *argv[]) { pthread_t tid; int result = 0; if(2 != argc) { printf("usage: ./a.out <stop-positon>\\n"); return;} if(!strcmp(argv[1], "1")) { printf("stop at position 1"); sleep(1000); } pthread_mutex_init(&lock_a, 0); pthread_mutex_init(&lock_b, 0); result = pthread_create(&tid, 0, func, 0); if (0 != result) { printf("create thread error!\\n"); } printf("create thread success!\\n"); pthread_mutex_lock(&lock_a); printf("func thread get lock_b, wanna get lock_a! \\n"); notify_a = 1; while (!notify_b) usleep(50); pthread_mutex_lock(&lock_b); printf("main thread get lock_a & lock_b! \\n"); pthread_mutex_unlock(&lock_b); pthread_mutex_unlock(&lock_a); }
1
#include <pthread.h> struct prodcons { int buffer[16]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct prodcons * b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct prodcons * b, int data) { pthread_mutex_lock(&b->lock); while ((b->writepos + 1) % 16 == b->readpos) { pthread_cond_wait(&b->notfull, &b->lock); } b->buffer[b->writepos] = data; b->writepos++; if (b->writepos >= 16) b->writepos = 0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons * b) { int data; pthread_mutex_lock(&b->lock); while (b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if (b->readpos >= 16) b->readpos = 0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void * producer(void * data) { int n; for (n = 0; n < 10000; n++) { printf("%d --->\\n", n); put(&buffer, n); } put(&buffer, (-1)); return 0; } void * consumer(void * data) { int d; while (1) { d = get(&buffer); if (d == (-1)) break; printf("---> %d\\n", d); } return 0; } int main() { pthread_t th_a, th_b; void * retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); return 0; }
0
#include <pthread.h> void *Productor(void *arg); void *Consumidor(void *arg); int n_elementos; int pos_p = 0; int pos_c = 0; int buffer[3096]; void main(int argc, char *argv[]){ pthread_t th1, th2, th3, th4, th5, th6; pthread_create(&th1, 0, Consumidor, 0); pthread_create(&th2, 0, Productor, 0); pthread_create(&th3, 0, Productor, 0); pthread_create(&th4, 0, Consumidor, 0); pthread_create(&th5, 0, Consumidor, 0); pthread_create(&th6, 0, Productor, 0); pthread_exit(0); exit(0); } void *Productor(void *arg) { int i=0; int dato = 0; while (i < 40000) { pthread_mutex_lock(&cerrojoComun); if (n_elementos < 3096) { pthread_mutex_unlock(&cerrojoComun); dato=dato+1; pthread_mutex_lock(&cerrojoProd); buffer[pos_p] = dato; printf("Produce %d \\n", dato); fflush(stdout); pos_p = (pos_p + 1) % 3096; pthread_mutex_unlock(&cerrojoProd); pthread_mutex_lock(&cerrojoComun); n_elementos ++; pthread_mutex_unlock(&cerrojoComun); i++; } else pthread_mutex_unlock(&cerrojoComun); } pthread_exit(0); } void *Consumidor(void *arg) { int i=0; int dato = 0; while (i < 40000) { if (n_elementos > 0) { dato = buffer[pos_c]; pos_c = (pos_c + 1) % 3096; printf("Consume %d \\n", dato); fflush(stdout); n_elementos --; i++; } } pthread_exit(0); }
1
#include <pthread.h> const int MAX_THREADS = 1024; const int MSG_MAX = 100; void* send_msg(void* rank); void get_args(int argc, char* argv[]); void usage(char* prog_name); long thread_count; int* message_available; char** messages; pthread_mutex_t mutex; int main(int argc, char* argv[] ) { long thread; pthread_t* thread_handles; get_args(argc, argv); thread_handles = malloc(thread_count * sizeof(pthread_t) ); messages = malloc(thread_count * sizeof(char*) ); for(thread = 0; thread < thread_count; thread++) { messages[thread] = 0; } message_available = malloc(thread_count * sizeof(int) ); for(thread = 0; thread < thread_count; thread++) { message_available[thread] = 0; } pthread_mutex_init(&mutex, 0); for(thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, send_msg, (void*) thread); } for(thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } pthread_mutex_destroy(&mutex); for(thread = 0; thread < thread_count; thread++) { free(messages[thread]); } free(messages); free(thread_handles); return 0; } void* send_msg(void* rank) { long my_rank = (long) rank; long dest = (my_rank + 1) % thread_count; char* my_msg = malloc(MSG_MAX * sizeof(char) ); while(1) { pthread_mutex_lock(&mutex); if(message_available[my_rank]) { printf("CONSUMER thread %ld message: %s\\n", my_rank, messages[my_rank] ); pthread_mutex_unlock(&mutex); break; } if(message_available[dest] == 0){ sprintf(my_msg, "Message from PRODUCER thread %ld", my_rank); messages[dest] = my_msg; message_available[dest] = 1; pthread_mutex_unlock(&mutex); break; } } return 0; } void get_args(int argc, char* argv[]) { if (argc != 2) { usage(argv[0]); } thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) { usage(argv[0]); } } void usage(char* prog_name) { fprintf(stderr, "usage: %s <number of threads>\\n", prog_name); exit(0); }
0
#include <pthread.h> int id; int track; int station; int stationsN; }arg_t; pthread_mutex_t *connection_mutex, *internal_mutex[2]; int *stations, not_assigned; void select_station_and_track(int *station, int *track){ int my_station, my_track, i; my_track = rand()%2; i = rand()%not_assigned; my_station = stations[i]; stations[i] = stations[not_assigned-1]; not_assigned--; *station = my_station; *track = my_track; } void *Train(void *args); int main(int argc, char *argv[]){ int n, m, i; int station, track; pthread_t *threads; arg_t *args; if(argc < 3){ fprintf(stdout, "invalid number of parameters\\n"); return -1; } n = atoi(argv[1]); m = atoi(argv[2]); if(n < m){ fprintf(stderr, "n must be greater than m\\n"); return -1; } stations = (int*) malloc(n * sizeof(int)); not_assigned = n; for(i = 0; i < n; i++) stations[i] = i; connection_mutex = (pthread_mutex_t*) malloc(n * sizeof(pthread_mutex_t)); for(i = 0; i < 2; i++) internal_mutex[i] = (pthread_mutex_t*) malloc(n * sizeof(pthread_mutex_t)); for(i = 0; i < n; i++){ pthread_mutex_init(&connection_mutex[i], 0); pthread_mutex_init(&internal_mutex[0][i], 0); pthread_mutex_init(&internal_mutex[1][i], 0); } srand(time(0)); threads = (pthread_t*) malloc(m * sizeof(pthread_t)); args = (arg_t*) malloc(m * sizeof(arg_t)); for(i = 0; i < m; i++){ bzero(&station, sizeof(station)); bzero(&track, sizeof(track)); select_station_and_track(&station, &track); args[i].id = i; args[i].stationsN = n; args[i].station = station; args[i].track = track; pthread_mutex_lock(&internal_mutex[track][station]); pthread_create(&threads[i], 0, Train, (void*) &args[i]); } pthread_exit(0); } void *Train(void *args){ arg_t *arg = (arg_t*) args; int id = (*arg).id; int station = (*arg).station; int track = (*arg).track; int N = (*arg).stationsN; int sleep_time; char direction[50]; int next_connection, next_station; if(track == 0) sprintf(direction, "CLOCKWISE"); else sprintf(direction, "COUNTERCLOCKWISE"); while(1){ if(track = 0){ next_connection = station; next_station = station+1%N; } else{ next_station = station - 1; if(next_station < 0) next_station = N-1; next_connection = next_station; } fprintf(stdout, "Train n. %d in station %d going %s\\n", id, station, direction); srand(time(0)); sleep_time = rand()%6 + 1; sleep(sleep_time); pthread_mutex_lock(&connection_mutex[next_connection]); pthread_mutex_unlock(&internal_mutex[track][station]); fprintf(stdout, "Train n. %d travelling toward station %d\\n", id, next_station); sleep(10); pthread_mutex_lock(&internal_mutex[track][next_station]); pthread_mutex_unlock(&connection_mutex[next_connection]); fprintf(stdout, "Train n. %d arrived at station %d\\n", id, next_station); station = next_station; } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void*); void *thread2(void*); int i = 1; int main(void){ pthread_t t_a; pthread_t t_b; pthread_create(&t_a,0,thread2,(void*)0); pthread_create(&t_b,0,thread1,(void*)0); pthread_join(t_b,0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(0); } void *thread1(void *junk){ for(i = 1;i<= 9; i++){ pthread_mutex_lock(&mutex); printf("call thread1 \\n"); if(i%3 == 0) pthread_cond_signal(&cond); else printf("thread1: %d\\n",i); pthread_mutex_unlock(&mutex); sleep(1); } } void *thread2(void*junk){ while(i < 9) { pthread_mutex_lock(&mutex); printf("call thread2 \\n"); if(i%3 != 0) pthread_cond_wait(&cond,&mutex); printf("thread2: %d\\n",i); pthread_mutex_unlock(&mutex); sleep(1); } }
0
#include <pthread.h> pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; sem_t blanks; sem_t datas; int ringBuf[100] = {0}; void* productRun(void* arg) { int i = 0; while(1) { usleep(100000); sem_wait(&blanks); pthread_mutex_lock(&mylock); int data = rand()%100+1; while(ringBuf[i]!=0) { i++; } i%=100; ringBuf[i]=data; printf("I am producter:%d ,i =%d\\n",data,i); i++; i%=100; sem_post(&datas); pthread_mutex_unlock(&mylock); } } void* productRun2(void* arg) { int i = 0; while(1) { usleep(100000); sem_wait(&blanks); pthread_mutex_lock(&mylock); int data = rand()%1000+101; while(ringBuf[i]!=0) { i++; } i%=100; ringBuf[i]=data; printf("I am producter2:%d ,i =%d\\n",data,i); i++; i%=100; sem_post(&datas); pthread_mutex_unlock(&mylock); } } void* consumerRun(void* arg) { int i = 0; while(1) { usleep(100000); sem_wait(&datas); pthread_mutex_lock(&mylock); while(ringBuf[i]==0) { i++; } i%=100; int data= ringBuf[i]; ringBuf[i]=0; printf("i am consumer :%d,i=%d\\n",data,i); i++; i%=100; sem_post(&blanks); pthread_mutex_unlock(&mylock); } } void* consumerRun2(void* arg) { int i = 0; while(1) { usleep(100000); sem_wait(&datas); pthread_mutex_lock(&mylock); while(ringBuf[i]==0) { i++; } i%=100; int data= ringBuf[i]; ringBuf[i]=0; printf("i am consumer2 :%d,i = %d\\n",data,i); i++; i%=100; sem_post(&blanks); pthread_mutex_unlock(&mylock); } } int main() { sem_init(&blanks,0,100); sem_init(&datas,0,0); pthread_t product,consumer; pthread_t product2,consumer2; pthread_create(&product,0,productRun,0); pthread_create(&consumer,0,consumerRun,0); pthread_create(&product2,0,productRun2,0); pthread_create(&consumer2,0,consumerRun2,0); pthread_join(product,0); pthread_join(consumer,0); pthread_join(product2,0); pthread_join(consumer2,0); pthread_mutex_destroy(&mylock); sem_destroy(&blanks); sem_destroy(&datas); return 0; }
1
#include <pthread.h> int ismaster_guess() { if (((long)ismaster_guess) & 0x4000) return 1; return 0; } pthread_mutex_t mutex; void* receive_bit(void* unused) { if (pthread_mutex_trylock(&mutex) == 0) { pthread_mutex_unlock(&mutex); return (void*) 0; } return (void*) 1; } volatile long dummy; void* send_bit(void* b) { pthread_mutex_lock(&mutex); for (int i = 0; i < (long)b * 100000000; i++) dummy = 0; pthread_mutex_unlock(&mutex); return 0; } long do_threads(int send, long bitvalue) { pthread_t thread1, thread2; void* result_rcv = 0; if (send) { pthread_create(&thread1, 0, send_bit, (void*)bitvalue); } else { pthread_create(&thread1, 0, send_bit, 0); } for (int i = 0; i < 10000000; i++) dummy = 0; pthread_create(&thread2, 0, receive_bit, 0); pthread_join(thread1, 0); pthread_join(thread2, &result_rcv); return (long)result_rcv; } void send_pointer(void* ptr_) { uint64_t ptr = (uint64_t) ptr_; for (int i = 0; i < 64; i++) { if (ptr & (1ULL << 63)) do_threads(1, 1); else do_threads(1, 0); ptr <<= 1; } } void* receive_pointer() { uint64_t ptr = 0; for (int i = 0; i < 64; i++) { ptr <<= 1; ptr |= do_threads(0, 0); } return (void*) ptr; } void* communicate(void* input, int shouldsend) { if (shouldsend) { send_pointer(input); return input; } return receive_pointer(); } int main() { void* pointer; if (ismaster_guess() == 0) { pointer = communicate((void*)(main), 1); } else { pointer = communicate((void*)(main), 0); } printf("\\t&main() in master: %p\\n", pointer); }
0
#include <pthread.h> int NUM_FILES; int SIZE; int NUM_THREADS; char *DESTINATION_DIR; int BUF_SIZE; int COUNTER; pthread_mutex_t LOCK; void *perform_writes(void *args); void perform_write(char *path); int main(int argc, char *argv[]) { NUM_FILES = strtol(argv[1], 0, 0); SIZE = strtol(argv[2], 0, 0); NUM_THREADS = strtol(argv[3], 0, 0); DESTINATION_DIR = argv[4]; BUF_SIZE = strtol(argv[5], 0, 0); pthread_t tid[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { pthread_create(&(tid[i]), 0, &perform_writes, 0); } for (int i = 0; i < NUM_THREADS; i++) { pthread_join(tid[i], 0); } } void *perform_writes(void *args) { while (1) { int file_num; char path[100]; pthread_mutex_lock(&LOCK); file_num = COUNTER++; pthread_mutex_unlock(&LOCK); if (file_num >= NUM_FILES) pthread_exit(0); sprintf(path, "%s/%d", DESTINATION_DIR, file_num); perform_write(path); } } void perform_write(char *path) { clock_t start, end; int src, dst; char buf[BUF_SIZE]; int remaining = SIZE; int read_size; start = clock(); src = open("/dev/zero", O_RDONLY); dst = open(path, O_WRONLY | O_CREAT, 0644); while (remaining > 0) { read_size = (remaining < BUF_SIZE) ? remaining: BUF_SIZE; read(src, buf, read_size); write(dst, buf, read_size); remaining -= read_size; } close(src); close(dst); end = clock(); printf("%f\\n", (double) (end - start)); }
1
#include <pthread.h> struct lectred { pthread_mutex_t m; pthread_cond_t cl, ce; int ecriture; int nb_lecteurs, nb_lect_att, nb_ecri_att; }; struct linked_list { int nb; struct linked_list *next; }; struct linked_list_head { struct lectred sync; struct linked_list *head; }; struct linked_list_head liste; void init(struct lectred* l) { pthread_mutex_init(&(l->m), 0); pthread_cond_init(&(l->cl), 0); pthread_cond_init(&(l->ce), 0); l->ecriture = 0; l->nb_lect_att = 0; l->nb_ecri_att = 0; l->nb_lecteurs = 0; } void begin_read(struct lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1 || l->nb_ecri_att > 0){ l->nb_lect_att++; pthread_cond_wait(&(l->cl), &(l->m)); l->nb_lect_att--; } l->nb_lecteurs++; pthread_mutex_unlock(&(l->m)); } void end_read(struct lectred* l) { pthread_mutex_lock(&(l->m)); l->nb_lecteurs--; if(l->nb_lect_att == 0 && l->nb_ecri_att > 0){ pthread_cond_signal(&(l->cl)); } pthread_mutex_unlock(&(l->m)); } void begin_write(struct lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1 || l->nb_lecteurs > 0){ l->nb_ecri_att++; pthread_cond_wait(&(l->ce), &(l->m)); l->nb_ecri_att--; } l->ecriture = 1; pthread_mutex_unlock(&(l->m)); } void end_write(struct lectred* l) { pthread_mutex_lock(&(l->m)); l->ecriture = 0; if(l->nb_ecri_att > 0){ pthread_cond_signal(&(l->ce)); } else if(l->nb_lect_att > 0){ pthread_cond_broadcast(&(l->cl)); } pthread_mutex_unlock(&(l->m)); } void list_init(struct linked_list_head *list) { list->head = 0; init(&list->sync); } int exists(struct linked_list_head *list, int val) { srand(time(0)); struct linked_list *p; begin_read(&list->sync); printf("lecture\\n"); p = list->head; while(p != 0) { if (p->nb == val) { end_read(&list->sync); printf("fin lecture\\n"); return 1; } p = p->next; } end_read(&list->sync); printf("fin lecture\\n"); return 0; } void add_element(struct linked_list_head *list, struct linked_list *l) { srand(time(0)); struct linked_list **p, **prec; begin_write(&list->sync); printf("écriture\\n"); sleep(rand()%5 + 1); prec = 0; p = &list->head; while((*p) != 0) { prec = p; p = &(*p)->next; } if (prec != 0) { (*prec)->next = l; } else { list->head = l; } end_write(&list->sync); printf("fin écriture\\n"); } struct linked_list* remove_element(struct linked_list_head *list, int val) { srand(time(0)); struct linked_list **p, *ret = 0; begin_write(&list->sync); sleep(rand()%5 + 1); printf("écriture\\n"); p = &list->head; while((*p) != 0) { if ((*p)->nb == val) { ret = *p; *p = (*p)->next; break; } p = &(*p)->next; } end_write(&list->sync); printf("fin écriture\\n"); return ret; } void* lecture(void* arg) { pthread_t tid = pthread_self () ; srand ((int) tid) ; int val = rand()%2 + 1; if (exists(&liste, val)) { } else { } return 0; } void* ecriture(void* arg) { pthread_t tid = pthread_self () ; srand ((int) tid) ; int val = rand()%2; if (val) { val = rand()%2 + 1; struct linked_list *l; l = malloc(sizeof(struct linked_list)); l->nb = val; l->next = 0; add_element(&liste, l); } else { val = rand()%2 + 1; struct linked_list *l; if ((l = remove_element(&liste, val)) != 0) { free(l); } else { } } return 0; } int main (int argc, char** argv) { int i, nb_lecteur, nb_redacteur; pthread_t *tid_lecteur; pthread_t *tid_redacteur; if (argc != 3 && (atoi(argv[1]) <= 0 || atoi(argv[2]) <= 0)) { printf("usage: %s <nb_lecteur> <nd_redacteur>\\n\\t- nb_lecteur et nb_redacteur > 0\\n", argv[0]); return 0; } list_init(&liste); nb_lecteur = atoi(argv[1]); nb_redacteur = atoi(argv[2]); tid_lecteur = malloc(nb_lecteur * sizeof(pthread_t)); tid_redacteur = malloc(nb_redacteur * sizeof(pthread_t)); for(i=0; i < nb_lecteur; i++) { pthread_create(&tid_lecteur[i], 0, lecture, 0); } for(i=0; i < nb_redacteur; i++) { pthread_create(&tid_redacteur[i], 0, ecriture, 0); } for(i=0; i < nb_lecteur; i++) { pthread_join(tid_lecteur[i], 0); } for(i=0; i < nb_redacteur; i++) { pthread_join(tid_redacteur[i], 0); } free(tid_lecteur); free(tid_redacteur); return 1; }
0
#include <pthread.h> struct thr_arg { int x; int *sh_mem; }; pthread_mutex_t lock; void *thr_func(void *arg) { int i; pthread_mutex_lock(&lock); i = ((struct thr_arg *)arg)->x; ((struct thr_arg *)arg)->sh_mem[i-1] = i; pthread_mutex_unlock(&lock); return ; } int main() { pthread_t tid[50]; struct thr_arg ta[50]; int *shm; int key, shmid, i; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\nerror in mutex init"); } key = ftok("/dev/null", 0); shmid = shmget(key, sizeof(int)*50, IPC_CREAT | 0666); if (shmid < 0) { perror("shmget"); return 1; } shm = (int *)shmat(shmid, 0, 0); if (shm == 0) { perror("shmat"); return 1; } for (i = 0; i < 50; i++) { ta[i].x = i+1; ta[i].sh_mem = shm; pthread_create(&tid[i], 0, thr_func, &ta[i]); } for (i = 0; i<50; i++) { pthread_join(tid[i],0); } for(i = 0; i<50; i++) { printf("%d, ",shm[i]); } printf("\\n"); shmdt((void *)shm); shmctl(shmid, IPC_RMID,0); return 0; }
1
#include <pthread.h> int nbBonbons; pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; void sigint_handler(int s) { pthread_mutex_destroy(&mut); exit(0); } void* producteur(void* arg) { struct timespec tps; while(1) { tps.tv_sec=rand()%2; tps.tv_nsec=rand()%1000000000; nanosleep(&tps, 0); pthread_mutex_lock(&mut); if(nbBonbons<10) { nbBonbons++; printf("producer (%d) -- put a candy -- %d\\n", pthread_self(), nbBonbons); } else { printf("producer (%d) -- can't put candy\\n", pthread_self()); } pthread_mutex_unlock(&mut); } } void* consomateur(void* arg) { struct timespec tps; while(1) { tps.tv_sec=rand()%2; tps.tv_nsec=rand()%1000000000; nanosleep(&tps, 0); pthread_mutex_lock(&mut); if(nbBonbons>0) { nbBonbons--; printf(" consumer (%d) -- get a candy -- %d\\n", pthread_self(), nbBonbons); } else { printf("consumer (%d) -- can't get candy\\n", pthread_self()); } pthread_mutex_unlock(&mut); } } void main(int argc, char** argv) { struct sigaction sa; sa.sa_handler=sigint_handler; sa.sa_flags=SA_RESTART; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, 0); pthread_t th1, th2, th3; int ptid1=pthread_create(&th1, 0, producteur, 0); int ptid2=pthread_create(&th2, 0, producteur, 0); int ptid3=pthread_create(&th3, 0, consomateur, 0); pthread_join(th1, 0); exit(0); }
0
#include <pthread.h> int value; struct __node_t *next; } node_t; node_t *head; node_t *tail; pthread_mutex_t headLock; pthread_mutex_t tailLock; } queue_t; void Queue_Init(queue_t *q) { node_t *tmp = (node_t*)malloc(sizeof(node_t)); tmp->next = 0; q->head = q->tail = tmp; pthread_mutex_init(&q->headLock, 0); pthread_mutex_init(&q->tailLock, 0); } void Queue_Enqueue(queue_t *q, int value) { node_t *tmp = (node_t*)malloc(sizeof(node_t)); assert(tmp != 0); tmp->value = value; tmp->next = 0; pthread_mutex_lock(&q->tailLock); q->tail->next = tmp; q->tail = tmp; pthread_mutex_unlock(&q->tailLock); } int Queue_Dequeue(queue_t *q, int *value) { pthread_mutex_lock(&q->headLock); node_t *tmp = q->head; node_t *newHead = tmp->next; if (newHead == 0) { pthread_mutex_unlock(&q->headLock); return -1; } *value = newHead->value; q->head = newHead; pthread_mutex_unlock(&q->headLock); free(tmp); return 0; } int main() { queue_t *q = (queue_t*)malloc(sizeof(queue_t)); Queue_Init(q); int i, t; for (i = 0; i < 20; i++) { Queue_Enqueue(q, i); printf("Enqueue: %d\\n", i); } for (i = 0; i < 10; i++) { Queue_Dequeue(q, &t); printf("Dequeue: %d\\n", t); } return 0; }
1
#include <pthread.h> void *thread_shuttle(void *args); void *thread_rocket(void *args); void *thread_nasa(void *args) { pthread_detach(pthread_self()); pthread_t tid_shuttle; pthread_t tid_rocket; if (0 != pthread_create(&tid_rocket, 0, thread_rocket, 0)) { printf("nasa send rocket failed...\\n"); } else { printf("nasa send rocket to space~\\n"); } if (0 != pthread_create(&tid_shuttle, 0, thread_shuttle, 0)) { printf("nasa send shuttle failed...\\n"); } else { printf("nasa send shuttle to space~\\n"); } sleep(10); printf("nasa call back shuttle\\n"); pthread_cancel(tid_shuttle); if (pthread_join(tid_shuttle, 0)) { printf("wait shuttle back failed.\\n"); } else { printf("shuttle come back successfully.\\n"); } pthread_exit(0); } void *thread_shuttle(void *args) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); int old_cancel_type = -1; static pthread_mutex_t controller = PTHREAD_MUTEX_INITIALIZER; while(1) { printf("shuttle is flying~\\n"); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &old_cancel_type); { pthread_cleanup_push((void (*)(void *))pthread_mutex_unlock, (void *)&controller); sleep(1); pthread_mutex_lock(&controller); sleep(3); pthread_mutex_unlock(&controller); sleep(1); pthread_cleanup_pop(0); } pthread_setcanceltype(old_cancel_type, 0); } pthread_exit(0); } void *thread_rocket(void *args) { pthread_detach(pthread_self()); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); while(1) { printf("rocket is flying~\\n"); sleep(3); } pthread_exit(0); } int main() { pthread_t tid_nasa; if (0 != pthread_create(&tid_nasa, 0, thread_nasa, 0)) { printf("create thread nasa failed...\\n"); return -1; } if (pthread_join(tid_nasa, 0)) { printf("join thread_nasa failed.\\n"); } return 0; }
0
#include <pthread.h> double** matResult; double** mat1; double** mat2; int matSize1x; int matSize1y; int matSize2x; int matSize2y; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *runner(void *args) { int index = *((int *) args); double partialSum = 0; for (int j = 0; j < matSize2y; j++) { for(int i = 0; i < matSize1y; i++) { partialSum += (mat1[index][i]) * (mat2[i][j]); } pthread_mutex_lock(&mutex); matResult[index][j] = partialSum; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char **argv) { if (argc <= 2) { printf("No arguments were passed in...\\n"); exit(1); } char *fileName1 = argv[1]; char *fileName2 = argv[2]; FILE *file; FILE *file2; file=fopen(fileName1, "r"); fscanf(file, "%d", &matSize1x); fscanf(file, "%d", &matSize1y); mat1=malloc(matSize1x*sizeof(double*)); for(int i = 0; i < matSize1x; ++i) { mat1[i]=malloc(matSize1y*sizeof(double)); } for(int i = 0; i < matSize1y; i++) { for(int j = 0; j < matSize1y; j++) { if (!fscanf(file, "%lf", &mat1[i][j])) break; } } fclose(file); file2=fopen(fileName2, "r"); fscanf(file2, "%d", &matSize2x); fscanf(file2, "%d", &matSize2y); mat2=malloc(matSize2x*sizeof(double*)); if (matSize1y != matSize2x) { printf("Matrix dimensions do not match for multiplication\\n"); exit(1); } for(int i = 0; i < matSize2x; ++i) { mat2[i]=malloc(matSize2y*sizeof(double)); } for(int i = 0; i < matSize2x; i++) { for(int j = 0; j < matSize2y; j++) { if (!fscanf(file, "%lf", &mat2[i][j])) break; } } fclose(file2); pthread_t tids[matSize1x]; int indices[matSize1x]; matResult = malloc(matSize1x*sizeof(double*)); for(int i = 0; i < matSize1x; i++) { matResult[i] = malloc(matSize2y*sizeof(double)); } for(int i = 0; i < matSize1x; i++) { indices[i] = i; } for (int i = 0; i < matSize1x; i++) { pthread_create(&tids[i], 0, runner, &indices[i]); } for (int i = 0; i < matSize1x; i++) { pthread_join(tids[i], 0); } for(int i = 0; i < matSize1x; i++) { for (int j = 0; j < matSize2y; j++) { printf("%lf ", matResult[i][j]); } printf("\\n"); } return 0; }
1
#include <pthread.h> void *hello(void *arg){ static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int p; int *id=(int*)arg; int somme[5]; p=1000000*(*id); pthread_mutex_lock(& mutex); printf("%d:hello world et mon numero est %d\\n",*id,p); pthread_mutex_unlock(& mutex); somme[*id]=p; int i; int s; for(i=0;i<*id+1;i++){ s=s+somme[*id]; } printf("somme en cours:%d\\n",s/2); printf("mon pid est %d\\n",getpid()); printf("%p\\n", (void *) pthread_self()); pthread_exit(0); } int main( int argc,char *argv[]){ pthread_t thread[3]; int j=atoi(argv[1]); int i; int id[j]; for(i=0;i<j;i++){ id[i]=i; } for(i=0;i<j;i++){ printf("Cree thread %d\\n",i); pthread_create (&thread[i],0,hello,(void *)&id[i]); pthread_join(thread[i],0); } pthread_exit(0); }
0
#include <pthread.h> int max = 10 * 1000 * 1000; pthread_mutex_t mutex; pthread_cond_t cond_inc; pthread_cond_t cond_dec; int val; void * thr(void * arg) { int i; for (i = 0; i < max; i++) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } } void * thr_inc(void * arg) { int i; pthread_mutex_lock(&mutex); for (i = 0; i < max - 1; i++) { if (val > 0) { val = -1; pthread_cond_signal(&cond_dec); } else if (val == 0) break; pthread_cond_wait(&cond_inc, &mutex); } val = 0; pthread_cond_signal(&cond_dec); pthread_mutex_unlock(&mutex); } void * thr_dec(void * arg) { int i; pthread_mutex_lock(&mutex); for (i = 0; i < max; i++) { if (val < 0) { val = 1; pthread_cond_signal(&cond_inc); } else if (val == 0) break; pthread_cond_wait(&cond_dec, &mutex); } val = 0; pthread_cond_signal(&cond_inc); pthread_mutex_unlock(&mutex); } int main(int argc, char * argv[]) { pthread_t tid1, tid2; int level = 0; int i; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_inc, 0); pthread_cond_init(&cond_dec, 0); if (argc > 1) { level = atoi(argv[1]); } if (level == 0) { thr(&mutex); thr(&mutex); } if (level == 1) { pthread_create(&tid1, 0, thr, 0); pthread_create(&tid2, 0, thr, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); } if (level == 2) { val = 1; max = 1000 * 1000; pthread_create(&tid1, 0, thr_inc, 0); pthread_create(&tid2, 0, thr_dec, 0); pthread_join(tid2, 0); pthread_join(tid1, 0); } }
1
#include <pthread.h> pthread_mutex_t gm; struct foo{ int id; int arr[15]; struct foo *head; }; struct thread_data { int tid; struct foo *local_data; }; void *t(void *args){ struct thread_data *data = (struct thread_data*)args; int tid = data->tid; struct foo *tmp = data->local_data; pthread_mutex_lock(&gm); tmp->arr[7+tid] = 97+tid; printf("tid %d wrote %c at f->arr[%d]\\n", tid, tmp->arr[7+tid], 7+tid); tmp->arr[1] = '!'+tid; if (tid == 0) { tmp->arr[3] = '@'; printf("tid %d wrote %c at f->arr[3]\\n", tid, tmp->arr[3]); } printf("tid %d wrote %c at f->arr[1]\\n", tid, tmp->arr[1]); pthread_mutex_unlock(&gm); free(args); pthread_exit(0); } int main(){ pthread_mutex_init(&gm, 0); pthread_t tid[3]; printf("Checking crash status\\n"); if ( isCrashed() ) { printf("I need to recover!\\n"); struct foo *f = (struct foo*)nvmalloc(sizeof(struct foo), (char*)"f"); nvrecover(f, sizeof(struct foo), (char *)"f"); printf("f->arr[7] = %c\\n", f->arr[7]); printf("f->arr[8] = %c\\n", f->arr[8]); printf("f->arr[9] = %c\\n", f->arr[9]); printf("f->arr[1] = %c\\n", f->arr[1]); printf("f->arr[3] = %c\\n", f->arr[3]); printf("f->id = %d\\n", f->id); if(f->head) { printf("head not null\\n"); printf("f->head = %d\\n", f->head->id); } else printf("f->head = null\\n"); free(f); } else{ printf("Program did not crash before, continue normal execution.\\n"); struct foo *f = (struct foo*)nvmalloc(sizeof(struct foo), (char*)"f"); printf("finish writing to values\\n"); int i; for (i = 0; i < 3; i++) { struct thread_data *tmp = (struct thread_data*)malloc(sizeof(struct thread_data)); tmp->tid = i; tmp->local_data = f; pthread_create(&tid[i], 0, t, (void*)tmp); } pthread_mutex_lock(&gm); f->id = 12345; f->arr[0] = 10; f->arr[1] = 20; struct foo *aj = (struct foo*)nvmalloc(sizeof(struct foo), (char*)"f"); aj->id = 99; f->head = aj; printf("main wrote aj->id = 99 &f->head = aj thus f->head->id - %d\\n", f->head->id); f->arr[1] = '$'; printf("main wrote $ to f->arr[1]\\n"); pthread_mutex_unlock(&gm); pthread_mutex_lock(&gm); f->arr[1] = '$'; printf("main wrote $ to f->arr[1] again\\n"); pthread_mutex_unlock(&gm); for (i = 0; i < 3; i++) { pthread_join(tid[i], 0); } printf("f->arr[7] = %c\\n", f->arr[7]); printf("f->arr[8] = %c\\n", f->arr[8]); printf("f->arr[9] = %c\\n", f->arr[9]); printf("f->arr[1] = %c\\n", f->arr[1]); printf("f->arr[3] = %c\\n", f->arr[3]); printf("f->id = %d\\n", f->id); printf("internally abort!\\n"); abort(); } printf("-------------main exits-------------------\\n"); return 0; }
0
#include <pthread.h> void *thread_function(void *); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; int main() { pthread_t thread_id[10]; int i, j; for(i=0; i < 10; i++) { pthread_create( &thread_id[i], 0, thread_function, 0 ); } for(j=0; j < 10; j++) { pthread_join( thread_id[j], 0); } printf("Final counter value: %d\\n", counter); return 0; } void *thread_function(void *dummyPtr) { printf("Thread number %ld\\n", pthread_self()); pthread_mutex_lock( &mutex1 ); counter++; pthread_mutex_unlock( &mutex1 ); }
1
#include <pthread.h> int waiting_students; pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; void* student_thread(void* param){ int order = (int)param; int seed = (int)param*1000; int sleeptime = (rand_r(&seed)%3)+1; int helptime = 2; printf(" Student %d is programming for %d seconds.\\n", order, sleeptime); sleep(sleeptime); while(helptime > 0){ if(waiting_students < 2){ if(waiting_students==0){ pthread_mutex_lock(&mutex_lock); waiting_students++; pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sleep(sleeptime); sem_wait(&ta_sem); printf("Student %d receiving help\\n", order); helptime--; }else{ pthread_mutex_lock(&mutex_lock); waiting_students++; pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sem_wait(&ta_sem); printf("Student %d receiving help\\n", order); sleep(sleeptime); helptime--; } }else{ printf(" Student %d will try later.\\n", order); sleeptime = (rand_r(&seed)%3)+1; printf(" Student %d is programming for %d seconds.\\n", order, sleeptime); sleep(sleeptime); } } pthread_exit(0); } void* ta_thread(void* param){ while(0==0){ sem_wait(&students_sem); while(waiting_students > 0){ pthread_mutex_lock(&mutex_lock); waiting_students--; pthread_mutex_unlock(&mutex_lock); sem_post(&ta_sem); sleep(3); } } } int main(){ printf("CS149 Sleeping TA from Kim Pham\\n"); pthread_t student[4]; pthread_attr_t attr; pthread_t ta; pthread_mutex_init(&mutex_lock, 0); pthread_attr_init(&attr); sem_init(&students_sem, 0, 1); sem_init(&ta_sem, 0, 1); long seeds[4] = {1,2,3,4}; for(int i = 0; i < 4 +1; i++ ){ if(i < 4) pthread_create(&student[i], &attr, student_thread, (void*)seeds[i]); else pthread_create(&ta, &attr, ta_thread, 0); } for(int i = 0;i < 4; i++){ pthread_join(student[i], 0); } pthread_cancel(ta); printf("program terminated"); pthread_mutex_destroy(&mutex_lock); }
0
#include <pthread.h> pthread_mutex_t calculating = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t done = PTHREAD_COND_INITIALIZER; void *expensive_call(void *data) { int oldtype; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &oldtype); for ( ; ; ) { } pthread_cond_signal(&done); return 0; } int do_or_timeout(struct timespec *max_wait) { struct timespec abs_time; pthread_t tid; int err; pthread_mutex_lock(&calculating); clock_gettime(CLOCK_REALTIME, &abs_time); abs_time.tv_sec += max_wait->tv_sec; abs_time.tv_nsec += max_wait->tv_nsec; pthread_create(&tid, 0, expensive_call, 0); err = pthread_cond_timedwait(&done, &calculating, &abs_time); if (err == ETIMEDOUT) { fprintf(stderr, "%s: calculation timed out\\n", __func__); } if (!err) { pthread_mutex_unlock(&calculating); } return err; } int main() { struct timespec max_wait; memset(&max_wait, 0, sizeof(max_wait)); max_wait.tv_sec = 2; do_or_timeout(&max_wait); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[800]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 800) { 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 < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 800; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } } void *t2(void *arg) { int i; for (i = 0; i < 800; i++) { __CPROVER_assume(((800 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> struct dot_data { double *a; double *b; double sum; int veclen; }; pthread_mutex_t mutex_sum; long int sum; pthread_t threads[4]; struct dot_data dot_str; void * dot_prod(void *); int main() { int status; long int i; double * a; double * b; long int t_no; pthread_attr_t attr; a = (double *) malloc(4 * 1000 * sizeof (double)); b = (double *) malloc(4 * 1000 * sizeof (double)); for (i = 0; i < 1000 * 4; i++) { a[i] = 1.0; b[i] = a[i]; } dot_str.veclen = 1000; dot_str.a = a; dot_str.b = b; dot_str.sum = 0; pthread_mutex_init(&mutex_sum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 4; i++) { t_no = i; status = pthread_create(&threads[i], &attr, dot_prod, (void *) t_no); if (status) { printf("ERROR: Return code from pthread_create() is %d\\n", status); exit(1); } } pthread_attr_destroy(&attr); for (i = 0; i < 4; i++) { pthread_join(threads[i], 0); } printf("Sum = %f\\n", dot_str.sum); free(a); free(b); pthread_mutex_destroy(&mutex_sum); pthread_exit(0); return 0; } void * dot_prod(void * arg) { int i; int start; int end; int len; long offset; double mysum; double *x; double *y; offset = (long) arg; len = dot_str.veclen; start = offset * len; end = start + len; x = dot_str.a; y = dot_str.b; mysum = 0; for (i = start; i < end; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock(&mutex_sum); dot_str.sum += mysum; pthread_mutex_unlock(&mutex_sum); pthread_exit((void *) 0); }
1
#include <pthread.h> int glob = 0; pthread_mutex_t glob_mutex; void *odd(void *unused) { int i; int local = glob; for(i=0;i<100;i++) { if(local % 2 == 1){ printf("%d....\\n", glob); pthread_mutex_lock(&glob_mutex); glob++; pthread_mutex_unlock(&glob_mutex); sleep(1); } } pthread_exit(0); } void *even(void *unused) { int i; int local = glob; for(i=0;i<100;i++) { if(local % 2 == 0){ printf("%d....\\n", glob); pthread_mutex_lock(&glob_mutex); glob++; pthread_mutex_unlock(&glob_mutex); sleep(1); } } pthread_exit(0); } main() { pthread_t tid1, tid2; int ret; int i; pthread_mutex_init(&glob_mutex, 0); ret = pthread_create(&tid1, 0, even, 0); if(ret) { printf("pthread create failed , rc = %d\\n", ret); } ret = pthread_create(&tid2, 0, odd, 0); if(ret) { printf("pthread create failed , rc = %d\\n", ret); } pthread_mutex_destroy(&glob_mutex); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_exit(0); }
0
#include <pthread.h> int args_index_in; int args_index_out; int factors_index_in; int factors_index_out; int* args_buffer; int** factors_buffer; int g_argc; int count_down; int wait; int* factoring_func(int n) { int* factors = malloc(sizeof(int) * (16)); int i = 2; int k = 0; factors[k++] = n; while(n > 1) { while((n%i) == 0) { factors[k] = i; k++; n /= i; } i += 1; } k++; factors[k] = '\\0'; return factors; } void *producer_func(void *p) { pthread_mutex_t *pmutex = (pthread_mutex_t *)p; while(count_down != 1 || args_buffer[args_index_out] != 0) { while(factors_buffer[factors_index_in] != 0 || args_buffer[args_index_out] == 0); pthread_mutex_lock(pmutex); factors_buffer[factors_index_in++] = factoring_func(args_buffer[args_index_out]); args_buffer[args_index_out++] = 0; factors_index_in = factors_index_in % (10); args_index_out = args_index_out % (10); pthread_mutex_unlock(pmutex); } count_down--; wait--; return 0; } void *consumer_func(void *p) { pthread_mutex_t *pmutex = (pthread_mutex_t *)p; int* factor_array; while(factors_buffer[factors_index_out]!= 0 || count_down != 0) { while(factors_buffer[factors_index_out] == 0); pthread_mutex_lock(pmutex); factor_array = factors_buffer[factors_index_out]; factors_buffer[factors_index_out++] = 0; factors_index_out = factors_index_out % (10); pthread_mutex_unlock(pmutex); int k = 0; printf("%d: ", factor_array[k++]); while(factor_array[k] != '\\0') { printf("%d ", factor_array[k++]); } printf("\\n"); } wait--; return 0; } int main(int argc, char* argv[]) { args_buffer = malloc(sizeof(int) * (10)); factors_buffer = malloc(sizeof(int*) * (10)); g_argc = argc - 1; args_index_in = 0; args_index_out= 0; factors_index_in = 0; factors_index_out = 0; count_down = argc; wait = 2; int i; for(i = 0; i < (10); i++) { args_buffer[i] = 0; factors_buffer[i] = 0; } pthread_t producer_thread; pthread_t consumer_thread; pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_create(&producer_thread, 0, producer_func, &my_mutex); pthread_create(&consumer_thread, 0, consumer_func, &my_mutex); for(i = 1; i < argc; i++) { while(args_buffer[args_index_in] != 0); pthread_mutex_lock(&my_mutex); args_buffer[args_index_in++] = atoi(argv[i]); args_index_in = args_index_in % (10); pthread_mutex_unlock(&my_mutex); count_down--; } while(wait); pthread_join(producer_thread, 0); pthread_join(consumer_thread, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t *fourchettes; pthread_t *philosophes; int nombre_philosophes; void* activite_philo(void* arg) { int right=0; int left=0; int philoPos = (int)(long int)arg; int gauche = philoPos; int droite = philoPos - 1; if(droite == -1) { droite = nombre_philosophes-1; } while(1) { if(right == 0) { printf("%d: je veux ma fourchette droite: %d\\n",philoPos,droite); pthread_mutex_lock(&fourchettes[droite]); right = 1; printf("%d: j'ai ma fourchette droite: %d\\n",philoPos, droite); sleep(3); } if(left == 0) { printf("%d: je veux ma fourchette gauche: %d\\n",philoPos,gauche); int try = pthread_mutex_trylock(&fourchettes[gauche]); if(try != 0) { if (right == 1) { pthread_mutex_unlock(&fourchettes[droite]); right = 0; printf("%d: j'ai laché ma fourchette droite parce que l'autre était prise: %d\\n",philoPos, droite); sleep(3); } } else { left = 1; printf("%d: j'ai ma fourchette gauche: %d\\n",philoPos,gauche); sleep(3); } } if ((left ==1) && (right == 1)) { printf("%d: j'ai mes deux fourchettes! miam!\\n",philoPos); sleep(5); printf("%d: je lache ma fourchette droite: %d\\n",philoPos,droite); pthread_mutex_unlock(&fourchettes[droite]); right = 0; printf("%d: j'ai lache' ma fourchette droite: %d\\n",philoPos, droite); sleep(3); printf("%d: je lache ma fourchette gauche: %d\\n",philoPos,gauche); pthread_mutex_unlock(&fourchettes[gauche]); left = 0; printf("%d: j'ai lache' ma fourchette droite: %d\\n",philoPos, gauche); sleep(3); } } return 0 ; } int main() { nombre_philosophes = 5; philosophes = calloc(5, sizeof(pthread_t)); fourchettes = calloc(5,sizeof(pthread_mutex_t)); int i; for(i=0;i<5;i++) { int merror = pthread_mutex_init(&fourchettes[i],0); if(merror != 0) { printf("mutex init error %d\\n", i); } } for(i=0;i<5;i++) { int terror = pthread_create(&philosophes[i], 0,activite_philo, (void*)(long int)i); if (terror != 0) { printf ("thread create error %d\\n", i); } } for(;;); }
0
#include <pthread.h> char buffer [10]; int nextin = 0, nextout = 0; int count = 0; pthread_cond_t notfull= PTHREAD_COND_INITIALIZER; pthread_cond_t notempty= PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex =PTHREAD_MUTEX_INITIALIZER; void produce_char( void * args ){ int i; char x= 65+rand()%27; if (count == 10) pthread_cond_wait(&notfull,&mutex); pthread_mutex_lock(&mutex); buffer [nextin] = x; printf("produit %c\\n",buffer[nextin]); nextin = (nextin + 1) % 10; count ++; pthread_mutex_unlock(&mutex); pthread_cond_signal(&notempty); pthread_exit(0); } void take(void * args) { char x; if (count == 0) pthread_cond_wait(&notempty, &mutex) ; pthread_mutex_lock(&mutex); x = buffer [nextout] ; printf("consommé %c\\n", x); nextout = (nextout + 1) % 10; count --; pthread_mutex_unlock(&mutex); pthread_cond_signal(&notfull); pthread_exit(0); } int main(void){ pthread_t thread_P[10]; pthread_t thread_C[5]; int createP, createC; long i; int j; for(i=0;i<10;i++){ createP=pthread_create(&thread_P[i],0,(void *)produce_char,0); if(createP){ printf("Erreur de creation de thread %d\\n",createP); exit(-1); } } for(i=0;i<5;i++){ createC=pthread_create(&thread_C[i],0,(void *)take,0); if(createC){ printf("Erreur de creation de thread %d\\n",createC); exit(-1); } } printf("Le main attend la fin des threads producteur \\n"); for(i=0;i<10;i++){ pthread_join(thread_P[i],0); } printf("Le main attend la fin des threads consomateurs \\n"); for(j=0;j<5;j++){ pthread_join(thread_C[j],0); } pthread_cond_destroy(&notfull); pthread_cond_destroy(&notempty); pthread_mutex_destroy(&mutex); pthread_exit(0); }
1
#include <pthread.h> struct queue_root { struct queue_head *in_queue; struct queue_head *out_queue; pthread_mutex_t lock; }; struct queue_root *ALLOC_QUEUE_ROOT(void) { struct queue_root *root = malloc(sizeof(struct queue_root)); pthread_mutex_init(&root->lock, 0); root->in_queue = 0; root->out_queue = 0; return root; } void INIT_QUEUE_HEAD(struct queue_head *head) { head->next = ((void*)0xCAFEBAB5); } void queue_put(struct queue_head *new, struct queue_root *root) { struct queue_head *in_queue; while (1) { in_queue = root->in_queue; new->next = in_queue; if (__sync_bool_compare_and_swap(&root->in_queue, in_queue, new)) { break; } } } struct queue_head *queue_get(struct queue_root *root) { struct queue_head *head, *next; pthread_mutex_lock(&root->lock); if (!root->out_queue) { while (1) { head = root->in_queue; if (!head) { break; } if (__sync_bool_compare_and_swap(&root->in_queue, head, 0)) { while (head) { next = head->next; head->next = root->out_queue; root->out_queue = head; head = next; } break; } } } head = root->out_queue; if (head) { root->out_queue = head->next; } pthread_mutex_unlock(&root->lock); return head; }
0
#include <pthread.h> long balance = 1000000; long withdraw1 = 600000; long deposit = 500000; pthread_mutex_t lock; void *withdraw_func(void *val) { pthread_mutex_lock(&lock); long wd = (long)val; printf("balance before withdrawing %ld is %ld\\n",wd,balance); sleep(1); balance = balance - wd; printf("balance after withdrawing %ld is %ld\\n",wd,balance); pthread_mutex_unlock(&lock); pthread_exit(0); } void *deposit_func(void *val) { pthread_mutex_lock(&lock); long dep = (long)val; printf("balance before depositing %ld is %ld\\n",dep,balance); sleep(1); balance = balance + dep; printf("balance after depositing %ld is %ld\\n",dep,balance); pthread_mutex_unlock(&lock); pthread_exit(0); } long main() { pthread_mutex_init(&lock,0); pthread_t thread_wd, thread_dep; pthread_create(&thread_wd,0,withdraw_func,(void *)withdraw1); pthread_create(&thread_dep,0,deposit_func,(void *)deposit); pthread_join(thread_wd,0); pthread_join(thread_dep,0); printf("The total balance is %ld\\n",balance); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> const static unsigned int NUM_THREADS = 4; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; volatile int available = 1; unsigned spinLocked; unsigned spinUnlocked; volatile unsigned iterations; volatile unsigned spurious; volatile int stop = 0; void *ThreadProc(void *arg) { volatile unsigned count; while(!spinLocked && !spinUnlocked) sched_yield(); while(!stop){ pthread_mutex_lock(&mutex); while(!available){ pthread_cond_wait(&cond, &mutex); if(!available) ++spurious; } available--; iterations++; pthread_mutex_unlock(&mutex); count = spinLocked; while(count) --count; pthread_mutex_lock(&mutex); available++; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); count = spinUnlocked; while(count) --count; } return 0; } void SignalSIGALRM(int signum) { static unsigned count = 100000; signal(SIGALRM, SignalSIGALRM); if(spinLocked || spinUnlocked){ printf("%6u iterations %6u spurious\\n", iterations, spurious); if(spinLocked == count){ count /= 10; if(count < 1000) exit(0); spinLocked = 0; } else{ spinLocked += count * 25 / 100; } spinUnlocked = count - spinLocked; } else{ spinUnlocked = count; } iterations = 0; spurious = 0; printf("locked %6d unlocked %6d loop: ", spinLocked, spinUnlocked); } int main(int argn, char *argv[], char *envp[]) { pthread_t threads[NUM_THREADS]; int i; struct itimerval itimervalue; int error; void (*savedSIGALRM)(int); setvbuf(stdout, 0, _IONBF, 0); savedSIGALRM = signal(SIGALRM, SignalSIGALRM); if(savedSIGALRM == SIG_ERR) perror("signal"); spinLocked = 0; spinUnlocked = 0; printf("Starting up %d threads...\\n", (int)(sizeof(threads)/sizeof(threads[0]))); for(i=0; i<sizeof(threads)/sizeof(threads[0]); i++){ error = pthread_create(threads+i, 0, ThreadProc, 0); if(error) printf("pthread_create returned %d\\n", error); } itimervalue.it_interval.tv_sec = 0; itimervalue.it_interval.tv_usec = 100000; itimervalue.it_value.tv_sec = 0; itimervalue.it_value.tv_usec = 1; error = setitimer(ITIMER_REAL, &itimervalue, 0); if(error) perror("setitimer"); while(1) sched_yield(); for(i=0; i<sizeof(threads)/sizeof(threads[0]); i++) pthread_cancel(threads[i]); return 0; }
0
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t mysignal; int waiting=0; volatile int state=0; void barrier(){ int mystate; pthread_mutex_lock (&lock); mystate=state; waiting++; if (waiting==8){ waiting=0; state=-1; } pthread_mutex_unlock (&lock); while (mystate==state) ; } void *HelloWorld(void *arg) { long id=(long)arg; printf("Hello World! %d\\n",id); barrier(); printf("Bye Bye World! %d\\n",id); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t threads[8]; long t; pthread_cond_init(&mysignal,0); pthread_mutex_init(&lock,0); for(t=0;t<8;t++) pthread_create(&threads[t], 0, HelloWorld,(void *)t); pthread_exit(0); }
1
#include <pthread.h> void *server_process_requests(void *arg) { struct server_request *req = arg; struct server_connection *conn = req->conn; struct Message *msg = req->msg; int rc; free(req); if (msg->Type == TypeRead) { rc = conn->cbs->read_at(msg->Data, msg->DataLength, msg->Offset); } else if (msg->Type == TypeWrite) { rc = conn->cbs->write_at(msg->Data, msg->DataLength, msg->Offset); } msg->Type = TypeResponse; pthread_mutex_lock(&conn->mutex); rc = send_msg(conn->fd, msg); pthread_mutex_unlock(&conn->mutex); if (rc < 0) { fprintf(stderr, "fail to send response\\n"); } if (msg->DataLength != 0) { free(msg->Data); } free(msg); } int server_dispatch_requests(struct server_connection *conn, struct Message *msg) { int rc = 0; pthread_t pid; struct server_request *req; if (msg->Type != TypeRead && msg->Type != TypeWrite) { fprintf(stderr, "Invalid request type"); return -EINVAL; } req = malloc(sizeof(struct server_request)); req->msg = msg; req->conn = conn; rc = pthread_create(&pid, 0, server_process_requests, req); return rc; } struct server_connection *new_server_connection(char *socket_path, struct handler_callbacks *cbs) { struct sockaddr_un addr; int fd, connfd, rc = 0; struct server_connection *conn = 0; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { perror("socket error"); exit(-1); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(socket_path) >= 108) { fprintf(stderr, "socket path is too long, more than 108 characters"); exit(-EINVAL); } strncpy(addr.sun_path, socket_path, strlen(socket_path)); rc = bind(fd, (struct sockaddr*)&addr, sizeof(addr)); if (rc < 0) { perror("fail to bind server"); } rc = listen(fd, 1); connfd = accept(fd, (struct sockaddr*)0, 0); conn = malloc(sizeof(struct server_connection)); conn->fd = connfd; conn->cbs = cbs; pthread_mutex_init(&conn->mutex, 0); return conn; } int start_server(struct server_connection *conn) { int rc = 0; while (1) { struct Message *msg = malloc(sizeof(struct Message)); bzero(msg, sizeof(struct Message)); rc = receive_msg(conn->fd, msg); if (rc < 0) { fprintf(stderr, "Fail to receive request\\n"); return rc; } rc = server_dispatch_requests(conn, msg); if (rc < 0) { fprintf(stderr, "Fail to process requests\\n"); return rc; } } } void shutdown_server_connection(struct server_connection *conn) { close(conn->fd); free(conn); }
0
#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[3]; int sorted[3]; void producer () { int i, idx; for (i = 0; i < 3; i++) { idx = findmaxidx (source, 3); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 3; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 3); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 3; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#include <pthread.h> sem_t emptyPot; sem_t fullPot; void *savage (void*); void *cook (void*); static pthread_mutex_t servings_mutex; static pthread_mutex_t print_mutex; static int servings = 15; int getServingsFromPot(void) { int retVal; if (servings <= 0) { sem_post (&emptyPot); retVal = 0; } else { servings--; retVal = 1; } pthread_mutex_unlock (&servings_mutex); return retVal; } void putServingsInPot (int num) { servings += num; sem_post (&fullPot); } void *cook (void *id) { int cook_id = *(int *)id; int meals = 2; int i; while ( meals ) { sem_wait (&emptyPot); putServingsInPot (15); meals--; pthread_mutex_lock (&print_mutex); printf ("\\nCook filled pot\\n\\n"); pthread_mutex_unlock (&print_mutex); for (i=0; i<3; i++) sem_post (&fullPot); } return 0; } void *savage (void *id) { int savage_id = *(int *)id; int myServing; int meals = 11; while ( meals ) { pthread_mutex_lock (&servings_mutex); myServing = getServingsFromPot(); if (servings == 0) { sem_wait (&fullPot); myServing = getServingsFromPot(); } pthread_mutex_unlock (&servings_mutex); meals--; pthread_mutex_lock (&print_mutex); printf ("Savage: %i is eating\\n", savage_id); pthread_mutex_unlock (&print_mutex); sleep(2); pthread_mutex_lock (&print_mutex); printf ("Savage: %i is DONE eating\\n", savage_id); pthread_mutex_unlock (&print_mutex); } return 0; } int main() { int i, id[3 +1]; pthread_t tid[3 +1]; pthread_mutex_init(&servings_mutex, 0); pthread_mutex_init(&print_mutex, 0); sem_init(&emptyPot, 0, 0); sem_init(&fullPot, 0, 0); for (i=0; i<3; i++) { id[i] = i; pthread_create (&tid[i], 0, savage, (void *)&id[i]); } pthread_create (&tid[i], 0, cook, (void *)&id[i]); for (i=0; i<3; i++) { pthread_join(tid[i], 0); } }
0
#include <pthread.h> void *sum(void *p); { int id; int * myMem; } msg; unsigned long int psum[8]; 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; 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; int mySum = 0; for (i = start; i < end; i++) { mySum += 2; } pthread_mutex_lock(&mutex); sumtotal += mySum; pthread_mutex_unlock(&mutex); return 0 ; }
1
#include <pthread.h> struct protoent *getprotobynumber(int proto) { char *buf = _proto_buf(); if (!buf) return 0; return getprotobynumber_r(proto, (struct protoent *) buf, buf + sizeof(struct protoent), PROTO_BUFSIZE); } struct protoent *getprotobynumber_r(int proto, struct protoent *result, char *buf, int bufsize) { pthread_mutex_lock(&proto_iterate_lock); setprotoent(0); while ((result = getprotoent_r(result, buf, bufsize)) != 0) { if (result->p_proto == proto) break; } pthread_mutex_unlock(&proto_iterate_lock); return result; }
0
#include <pthread.h> int cine[7][20]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t kuz = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t consume_t = PTHREAD_COND_INITIALIZER; pthread_cond_t sits = PTHREAD_COND_INITIALIZER; pthread_cond_t produce_t = PTHREAD_COND_INITIALIZER; void compra(void* arg) { int sala,silla; int cont =15; while(cont>0) { sala = rand()%7; silla = rand()%20; printf("soy %d, voy a la sala %d, y a la silla %d \\n", (int)arg,sala,silla); pthread_mutex_lock(&kuz); if(cine[sala][silla]==0) { cine[sala][silla]=1; printf("soy %d, voy a la sala %d, y a la silla %d YA RESERVE\\n", (int)arg,sala,silla); cont--; } else { printf("soy %d, voy a la sala %d, y a la silla %d ESTABAN OCUPADOS\\n", (int)arg,sala,silla); } pthread_mutex_unlock(&kuz); } printf("vi %d peliculas y me voy\\n",15); } int main() { int GUESTS = 3 +2 +2; srand((int)time(0)); pthread_mutex_lock(&kuz); for(int i=0;i<7;++i) { for(int j=0; j<20;++j) { cine[i][j]=0; } } pthread_mutex_unlock(&kuz); pthread_t * compradores = (pthread_t *) malloc (sizeof(pthread_t) * GUESTS); int indice = 0; pthread_t * aux; for (aux = compradores; aux < (compradores+GUESTS); ++aux) { printf("comprador: %d \\n", ++indice); pthread_create(aux, 0, compra, (void *) indice); } for (aux = compradores; aux < (compradores+GUESTS); ++aux) { pthread_join(*aux, 0); } free(compradores); return 0; }
1
#include <pthread.h> int quitflag = 0; sigset_t mask; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thr_fn(void* arg) { int err,signo; while(1) { err = sigwait(&mask,&signo); if(err != 0) exit(-1); switch(signo) { case SIGQUIT: pthread_mutex_lock(&mutex); quitflag = 1; pthread_cond_signal(&waitloc); pthread_mutex_unlock(&mutex); return 0; case SIGINT: printf("\\ninterrupt\\n"); break; default: printf("unexpected signal %d\\n",signo); exit(1); } } } int main() { int err; sigset_t oldset; pthread_t tid; sigemptyset(&mask); sigaddset(&mask,SIGQUIT); sigaddset(&mask,SIGINT); err = pthread_sigmask(SIG_BLOCK,&mask,&oldset); err = pthread_create(&tid,0,thr_fn,0); pthread_mutex_lock(&mutex); while(quitflag == 0) pthread_cond_wait(&waitloc,&mutex); pthread_mutex_unlock(&mutex); quitflag = 0; err = pthread_sigmask(SIG_SETMASK,&oldset,0); exit(0); }
0
#include <pthread.h> pthread_mutex_t running_mutex; int running_threads = 0; int isprime(int num) { int start_check = (num/2)+1; static int prime = 1; static int notprime = 0; while( start_check > 1 ) { if( (num % start_check) == 0 ) return notprime; else start_check--; } return prime; } void CheckPrime( int num ) { int res; pthread_mutex_lock(&running_mutex); running_threads++; pthread_mutex_unlock(&running_mutex); res = isprime(num); if(res == 1) printf("%i IS prime!\\n", num); pthread_mutex_lock(&running_mutex); running_threads--; pthread_mutex_unlock(&running_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int start_num, end_num; if (argc != 3) { fprintf(stderr, "usage: %s <start_number> <end_number>\\n", argv[0]); exit(1); } sscanf(argv[1], "%i", &start_num); sscanf(argv[2], "%i", &end_num); printf("Start: %d\\tEnd: %d\\n", start_num, end_num); if(start_num <= 1 || start_num > end_num || end_num <= 1) { perror("ERROR: Invalid number range. Aborting\\n"); exit(4); } pthread_mutex_init(&running_mutex, 0); for(;start_num < end_num; start_num++) { while( running_threads > 4 ) sleep(.1); pthread_attr_t attr; pthread_attr_init(&attr); pthread_t thread; pthread_create( &thread, &attr, CheckPrime, start_num ); pthread_attr_destroy(&attr); } while(running_threads > 0) printf("Running threads: %i\\n", running_threads); sleep(.1); return 0; }
1
#include <pthread.h> int start=0; pthread_t* thread; struct buffer_struct { char buffer[100]; pthread_mutex_t lock; int rear; int front; }; struct buffer_struct* PC; struct arg_struct { pthread_t tid; struct buffer_struct* Producer; struct buffer_struct* Consumer; }; struct arg_struct * args; int main(int argc,char* argv[]) { int n; if(argc < 2) { printf("Program parameters invalid,Try './PCB 4'\\n"); } else { n=atoi(argv[1]); } int r=create_threads(n); if(r==0) { printf("Problem creating threads,existing program\\n"); exit(0); } return 0; } void printPC(struct buffer_struct* Producer,struct buffer_struct* Consumer,pid_t tid ) { printf("Thread %d\\n",tid); if(pthread_self()!=thread[0]) { printf("Producer\\n"); display_buffer(Producer); } printf("Consumer\\n"); display_buffer(Consumer); } void display_buffer(struct buffer_struct* buf) { int i; for(i=buf->front;i<= (buf->rear);i++) printf("%d\\n",buf->buffer[i]); } void * ProducerConsumer(void* arguments) { while(start!=1); struct arg_struct* arg=arguments; arg->tid=pthread_self(); int count=100; while(count>0) { count--; if(arg->tid == thread[0]) { int produced_value=rand()%100; int ret=1; do { ret=insert_into_buffer(arg->Consumer,produced_value); } while(ret==0); } else { int ret_val; do { ret_val=delete_from_buffer(arg->Producer); } while(ret_val==-1); int ret=1; do { ret=insert_into_buffer(arg->Consumer,ret_val); } while(ret==0); } } } void initialize_buffer(struct buffer_struct* buf) { buf->rear=-1; buf->front=-1; } int delete_from_buffer(struct buffer_struct * buf ) { pthread_mutex_lock(&(buf->lock)); if(buf->front==-1 && buf->rear==-1) { pthread_mutex_unlock(&(buf->lock)); return -1; } else { if(buf->front==buf->rear) { int e=buf->buffer[buf->front]; buf->front=-1; buf->rear=-1; pthread_mutex_unlock(&(buf->lock)); return e; } else { if(buf->front==100 -1 && buf->rear!=100 -1) { int e=buf->buffer[buf->front]; buf->front=0; pthread_mutex_unlock(&(buf->lock)); return e; } else { int e=buf->buffer[buf->front]; buf->front=buf->front+1; pthread_mutex_unlock(&(buf->lock)); return e; } } } } int insert_into_buffer(struct buffer_struct* buf,int value) { pthread_mutex_lock(&(buf->lock)); if(buf->rear==100 -1 && buf->front==0) { pthread_mutex_unlock(&(buf->lock)); return 0; } else { if((buf->rear + 1)== (buf->front) ) { pthread_mutex_unlock(&(buf->lock)); return 0; } else { if(buf->rear==-1 && buf->front==-1) { buf->rear=0; buf->front=0; } else { if(buf->rear==100 -1 && buf->front!=0 ) { buf->rear=0; } else buf->rear=buf->rear+1; } } } buf->buffer[buf->rear]=value; pthread_mutex_unlock(&(buf->lock)); return 1; } int create_threads(int n) { int i; thread=(pthread_t*)malloc(n*sizeof(pthread_t)); args=(struct arg_struct*)malloc(n*sizeof(struct arg_struct)); PC=(struct buffer_struct*)malloc(n*sizeof(struct buffer_struct)); for(i=0;i<n;i++) initialize_buffer(&PC[i]); start=0; for(i=0;i<n;i++) { if(i!=0) { args[i].Producer=&PC[i-1]; args[i].Consumer=&PC[i]; } else args[i].Consumer=&PC[i]; if(pthread_create(&thread[i],0,ProducerConsumer,(void*)&args[i])) { return 0; } else printf("Thread %d created with thread ID %d \\n",i,thread[i]); } start=1; for(i=0;i<n;i++) pthread_join(thread[i],0); return 1; }
0
#include <pthread.h> int x = 0; pthread_mutex_t mutex_x; pthread_t threads[5]; void *client(void *threadid) { int tid; tid = (int)threadid; pthread_mutex_lock(&mutex_x); fprintf(stdout, "TID %d: mutex_lock \\n", tid); x++; fprintf(stdout, "TID %d:mutex modifying x value: %d \\n", tid, x); pthread_mutex_unlock(&mutex_x); fprintf(stdout, "TID %d: mutex_unlock\\n",tid); pthread_exit((void*) 0); } int main(void){ int i; void *status; pthread_mutex_init(&mutex_x, 0); long t; for(i=0;i<5;i++) { pthread_create(&threads[i], 0, client, (void *)i); } for(i=0;i<5;i++) { pthread_join(threads[i], &status); } printf ("x = %d \\n", x); pthread_mutex_destroy(&mutex_x); pthread_exit(0); }
1
#include <pthread.h> int pthread_rwlock_rdlock (pthread_rwlock_t * rwlock) { int result; pthread_rwlock_t rwl; if (rwlock == 0 || *rwlock == 0) { return EINVAL; } if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) { result = pte_rwlock_check_need_init (rwlock); if (result != 0 && result != EBUSY) { return result; } } rwl = *rwlock; if (rwl->nMagic != PTE_RWLOCK_MAGIC) { return EINVAL; } if ((result = pthread_mutex_lock (&(rwl->mtxExclusiveAccess))) != 0) { return result; } if (++rwl->nSharedAccessCount == 32767) { if ((result = pthread_mutex_lock (&(rwl->mtxSharedAccessCompleted))) != 0) { (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); return result; } rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; rwl->nCompletedSharedAccessCount = 0; if ((result = pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) { (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); return result; } } return (pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))); }
0
#include <pthread.h> double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } struct list_node_s { int data; struct list_node_s* next; pthread_mutex_t mutex; }; int thread_count; struct list_node_s **head_p; pthread_mutex_t head_p_mutex; pthread_mutex_t mutex; int Member(int value) { struct list_node_s* temp_p; pthread_mutex_lock(&head_p_mutex); temp_p = *head_p; while (temp_p != 0 && temp_p->data < value) { if (temp_p->next != 0) pthread_mutex_lock(&(temp_p->next->mutex)); if (temp_p == *head_p) pthread_mutex_unlock(&head_p_mutex); pthread_mutex_unlock(&(temp_p->mutex)); temp_p = temp_p->next; } if (temp_p == 0 || temp_p->data > value) { if (temp_p == *head_p) pthread_mutex_unlock(&head_p_mutex); if (temp_p != 0) pthread_mutex_unlock(&(temp_p->mutex)); return 0; } else { if (temp_p == *head_p) pthread_mutex_unlock(&head_p_mutex); pthread_mutex_unlock(&(temp_p->mutex)); return 1; } } int Insert(int value) { struct list_node_s* curr_p = *head_p; struct list_node_s* pred_p = 0; struct list_node_s* temp_p; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p == 0 || curr_p->data > value) { temp_p = malloc(sizeof(struct list_node_s)); temp_p->data = value; temp_p->next = curr_p; if (pred_p == 0) *head_p = temp_p; else pred_p->next = temp_p; return 1; } else return 0; } int Delete(int value) { struct list_node_s* curr_p = *head_p; struct list_node_s* pred_p = 0; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p != 0 && curr_p->data == value) { if (pred_p == 0) { *head_p = curr_p->next; free(curr_p); } else { pred_p->next = curr_p->next; free(curr_p); } return 1; } else return 0; } void* Probar(void * rank) { long my_rank=(long) rank; pthread_mutex_lock(&mutex); Insert((int)my_rank); pthread_mutex_unlock(&mutex); int test=Member((int) my_rank); printf("Numero es %d\\n", test); return 0; } int main(int argc,char* argv[]) { long thread; pthread_t* thread_handles; struct list_node_s* list; list=malloc(sizeof(struct list_node_s)); list->data=0; list->next=0; head_p=&list; thread_count=strtol(argv[1],0,10); thread_handles=malloc (thread_count*sizeof(pthread_t)); struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, 0); for(thread=0;thread<thread_count;thread++) { pthread_create(&thread_handles[thread],0,Probar,(void *)thread); } for(thread=0;thread<thread_count;thread++) { pthread_join(thread_handles[thread],0); } gettimeofday(&t_fin, 0); secs = timeval_diff(&t_fin, &t_ini); printf("%.16g milliseconds\\n", secs * 1000.0); free(thread_handles); return 0; }
1
#include <pthread.h> double cur_time() { struct timespec ts[1]; clock_gettime(CLOCK_REALTIME, ts); return ts->tv_sec + ts->tv_nsec * 1.0E-9; } void think(double s) { double t0 = cur_time(); while (cur_time() - t0 < s) { } } double enter_lock_time; double return_from_lock_time; double enter_unlock_time; long x; } record; record * a; long i; long n; } record_buf; record_buf * make_record_buf(long n) { record * a = (record *)calloc(sizeof(record), n); record_buf * R = (record_buf *)malloc(sizeof(record_buf)); R->a = a; R->n = n; R->i = 0; return R; } void enter_lock(record_buf * R) { long i = R->i; assert(i < R->n); R->a[i].enter_lock_time = cur_time(); } void return_from_lock(record_buf * R) { long i = R->i; assert(i < R->n); R->a[i].return_from_lock_time = cur_time(); } void enter_unlock(record_buf * R, long x) { long i = R->i; assert(i < R->n); R->a[i].enter_unlock_time = cur_time(); R->a[i].x = x; R->i = i + 1; } int lock_vis(pthread_mutex_t * l, record_buf * R) { enter_lock(R); int r = pthread_mutex_lock(l); return_from_lock(R); return r; } int unlock_vis(pthread_mutex_t * l, record_buf * R, long x) { enter_unlock(R, x); return pthread_mutex_unlock(l); } pthread_mutex_t file_mutex[1]; void dump_record_buf(record_buf * R, int idx, FILE * wp) { long n = R->n; long i; pthread_mutex_lock(file_mutex); for (i = 0; i < n; i++) { fprintf(wp, "%ld %d enter_lock %.9f return_from_lock %.9f enter_unlock %.9f\\n", R->a[i].x, idx, R->a[i].enter_lock_time, R->a[i].return_from_lock_time, R->a[i].enter_unlock_time); } pthread_mutex_unlock(file_mutex); } pthread_t tid; int idx; long n_inc; pthread_mutex_t * m; FILE * wp; } * thread_arg_t; long g = 0; void * thread_func(void * _arg) { thread_arg_t arg = _arg; long i; long n_inc = arg->n_inc; record_buf * R = make_record_buf(n_inc); for (i = 0; i < n_inc; i++) { lock_vis(arg->m, R); long x = g++; think(1.0e-4); unlock_vis(arg->m, R, x); think(1.0e-4); } dump_record_buf(R, arg->idx, arg->wp); printf("g = %ld\\n", g); return 0; } int main(int argc, char ** argv) { if (argc <= 3) { fprintf(stderr, "usage: %s no_of_threads no_of_increments log_file\\n" "example:\\n %s 16 10000000 log.txt\\n", argv[0], argv[0]); exit(1); } int n_threads = atoi(argv[1]); long n_inc = atol(argv[2]); char * log_file = argv[3]; struct thread_arg args[n_threads]; double t0 = cur_time(); pthread_mutex_t m[1]; int i; pthread_mutex_init(m, 0); pthread_mutex_init(file_mutex, 0); FILE * wp = fopen(log_file, "wb"); if (!wp) { perror("fopen"); exit(1); } for (i = 0; i < n_threads; i++) { args[i].idx = i; args[i].n_inc = n_inc; args[i].m = m; args[i].wp = wp; pthread_create(&args[i].tid, 0, thread_func, (void *)&args[i]); } for (i = 0; i < n_threads; i++) { pthread_join(args[i].tid, 0); } double t1 = cur_time(); printf("OK: elapsed time: %f\\n", t1 - t0); fclose(wp); return 0; }
0
#include <pthread.h> void* thread_nvadata(void* arg) { while(1) { sleep(2); printf("thread_nvadata activé => tchuiiiiiiiiii pouf\\n"); } } float GetPitch() { pthread_mutex_lock(&mutex_regulation); float x_local = 0; pthread_mutex_unlock(&mutex_regulation); return x_local; } float GetRoll() { pthread_mutex_lock(&mutex_regulation); float y_local = 0; pthread_mutex_unlock(&mutex_regulation); return y_local; } float GetYaw() { pthread_mutex_lock(&mutex_regulation); float z_local = 0; pthread_mutex_unlock(&mutex_regulation); return z_local; } float GetAltitude() { pthread_mutex_lock(&mutex_regulation); float altitude_local = 0; pthread_mutex_unlock(&mutex_regulation); return altitude_local; } void Get_localization(float* x_local, float* y_local) { pthread_mutex_lock(&mutex_regulation); *x_local = 10; *y_local = 20; newCoordXY = 1; newAngle = 1; newSpeed = 1; pthread_mutex_unlock(&mutex_regulation); } void Set_nvdata(float theta, float phi, float psi, int altitude, float vx, float vy, float vz, int vbat_flying_percentage) { pthread_mutex_lock(&mutex_regulation); pthread_mutex_unlock(&mutex_regulation); }
1
#include <pthread.h> volatile unsigned char PRESSED1=0; volatile unsigned char PRESSED2=0; volatile int CLOSE[8][5]; int idx1=0; int idx2=0; extern pthread_mutex_t mIdx1; extern pthread_mutex_t mIdx2; void *serial_BUTTON(void * parm) { int fd,c, res; struct termios oldtio,newtio; unsigned char buf[255]; char cmd[2]; cmd[0]=254; cmd[1]=192; int i;int val; fd = open(MODEMDEVICE_BUTTON, O_RDWR | O_NOCTTY ); if (fd <0) {perror(MODEMDEVICE_BUTTON); printf("didn't open usb port");fflush(stdout);return; } tcgetattr(fd,&oldtio); bzero(&newtio, sizeof(newtio)); newtio.c_cflag = BAUDRATE_BUTTON | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; newtio.c_cc[VTIME] = 0; newtio.c_cc[VMIN] = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); while (TRUE) { write(fd,cmd,2); usleep(300000); res = read(fd,buf,255); buf[res]=0; if (buf[0] > 100) PRESSED1=TRUE; else PRESSED1=FALSE; if (buf[3] > 100) PRESSED2=TRUE; else PRESSED2=FALSE; } tcsetattr(fd,TCSANOW,&oldtio); } void *serial_DIST2(void * parm) { int fd,c, res; struct termios oldtio,newtio; unsigned char buf[255]; char range[5]; int sensors[3][3]; double avg;int idx=0; int cnt=0; range[0]=0x55; range[1]=0xe0; range[2]=0x00; range[3]=0x01; range[4]=80; char readrange[4]; readrange[0]=0x55; readrange[1]=0xe1; readrange[2]=0x02; readrange[3]=0x02; int i;int val;int j; fd = open(MODEMDEVICE_DIST2, O_RDWR | O_NOCTTY ); if (fd <0) {perror(MODEMDEVICE_DIST2); return;} tcgetattr(fd,&oldtio); bzero(&newtio, sizeof(newtio)); newtio.c_cflag = BAUDRATE_DIST | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; newtio.c_cc[VTIME] = 0; newtio.c_cc[VMIN] = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); while (TRUE) { for (j=0xe0;j<=0xe6;j+=2){ range[1]=j; write(fd,range,5);usleep(33000); res = read(fd,buf,255); } cnt=4; for (j=0xe1;j<=0xe7;j+=2){ readrange[1]=j; write(fd,readrange,4);usleep(33000); res = read(fd,buf,255); buf[res]=0; printf("a%d:%d ", cnt,buf[1]);fflush(stdout); CLOSE[cnt][idx2]=buf[1]; cnt++; } printf("\\n"); pthread_mutex_lock(&mIdx2); idx2=(idx2+1)%5; pthread_mutex_unlock(&mIdx2); } tcsetattr(fd,TCSANOW,&oldtio); } void *serial_DIST1(void * parm) { int fd,c, res; struct termios oldtio,newtio; unsigned char buf[255]; char range[5]; int sensors[3][3]; double avg;int idx=0; int cnt1=0; range[0]=0x55; range[1]=0xe0; range[2]=0x00; range[3]=0x01; range[4]=80; char readrange[4]; readrange[0]=0x55; readrange[1]=0xe1; readrange[2]=0x02; readrange[3]=0x02; int i;int val;int j; fd = open(MODEMDEVICE_DIST1, O_RDWR | O_NOCTTY ); if (fd <0) {perror(MODEMDEVICE_DIST1); return;} tcgetattr(fd,&oldtio); bzero(&newtio, sizeof(newtio)); newtio.c_cflag = BAUDRATE_DIST | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; newtio.c_lflag = 0; newtio.c_cc[VTIME] = 0; newtio.c_cc[VMIN] = 0; tcflush(fd, TCIFLUSH); tcsetattr(fd,TCSANOW,&newtio); while (TRUE) { for (j=0xe0;j<=0xe6;j+=2){ range[1]=j; write(fd,range,5);usleep(33000); res = read(fd,buf,255); } cnt1=0; for (j=0xe1;j<=0xe7;j+=2){ readrange[1]=j; write(fd,readrange,4);usleep(33000); res = read(fd,buf,255); buf[res]=0; printf("b%d:%d ", cnt1,buf[1]);fflush(stdout); CLOSE[cnt1][idx1]=buf[1]; cnt1++; } printf("\\n"); pthread_mutex_lock(&mIdx1); idx1=(idx1+1)%5; pthread_mutex_unlock(&mIdx1); } tcsetattr(fd,TCSANOW,&oldtio); }
0
#include <pthread.h> struct bench{ int count; pthread_mutex_t lock,barber; }*fp; void bench_init(){ if((fp=malloc(sizeof(struct bench)))!=0){ fp->count=0; if(pthread_mutex_init(&fp->lock,0)!=0){ free(fp); } } } void haircut(){ pthread_mutex_lock(&fp->barber); pthread_mutex_lock(&fp->lock); fp->count--; printf("Come on, boy, now your turn!\\n\\t%d customers is waiting\\n",fp->count); pthread_mutex_unlock(&fp->lock); sleep(rand()%3); pthread_mutex_unlock(&fp->barber); if(fp->count==0) printf("No Customer^_^~Barber is taking a nap.\\n\\nzZZ\\n"); } int seat_alloc(){ pthread_mutex_lock(&fp->lock); if(fp->count<5){ fp->count++; printf("New Customer!\\n\\tThere are %d customers waiting.\\n",fp->count); pthread_mutex_unlock(&fp->lock); return 0; } else { pthread_mutex_unlock(&fp->lock); return -1; } } void *customer(void* parm){ if(seat_alloc()!=-1) haircut(); else printf("New Customer!\\tBut no seat remained!\\n"); return 0; } int main(void){ int err; pthread_t cu[25]; bench_init(); for(int d=0;d<25;d++){ err=pthread_create(&cu[d],0,customer,0); sleep(rand()%2); } for(int d=0;d<25;d++) pthread_join(cu[d],0); pthread_mutex_destroy(&fp->lock); return 0; }
1
#include <pthread.h> struct shared_data_node { struct shared_data_t *shared_data; struct shared_data_node *next; }; struct shared_data_node *shared_data_arr; struct shared_data_node *head; int stack_size; pthread_mutex_t headlock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t stack_not_empty = PTHREAD_COND_INITIALIZER; struct shared_data_t *acquire_shared_segment() { struct shared_data_t *ret = 0; pthread_mutex_lock(&headlock); while (stack_size <= 0) { pthread_cond_wait(&stack_not_empty, &headlock); } assert(stack_size > 0); ret = head->shared_data; head = head->next; stack_size--; pthread_mutex_unlock(&headlock); return ret; } void release_shared_segment(struct shared_data_t *shared_data) { struct shared_data_node *probe; for (probe = shared_data_arr; probe->shared_data != 0; ++probe) { if (probe->shared_data == shared_data) { pthread_mutex_lock(&headlock); probe->next = head; head = probe; stack_size++; pthread_cond_broadcast(&stack_not_empty); pthread_mutex_unlock(&headlock); break; } } assert(probe->shared_data != 0); } static int create_shmem(key_t key, size_t size) { int id = shmget(key, size, IPC_CREAT | IPC_EXCL | 0666); if (id == -1) { perror("shmget"); exit(1); } return id; } static void init_storage(struct shared_data_storage *storage, size_t buf_size) { storage->buf_size = buf_size; storage->bytes_written = 0; storage->server_finished = 0; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&storage->ipc_mutex, &attr); pthread_mutexattr_destroy(&attr); pthread_condattr_t cattr; pthread_condattr_init(&cattr); pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED); pthread_cond_init(&storage->ipc_condvar, &cattr); pthread_condattr_destroy(&cattr); } void prepare_shmem_segments(int num_segments, size_t shm_buffer_size, char *path) { shared_data_arr = malloc(((num_segments + 1) * sizeof(struct shared_data_node)) + (num_segments * sizeof(struct shared_data_t))); pthread_mutex_lock(&headlock); head = shared_data_arr; stack_size = num_segments; pthread_mutex_unlock(&headlock); struct shared_data_t *d = (struct shared_data_t *) (shared_data_arr + num_segments + 1); for (int i = 0; i < num_segments; ++i) { shared_data_arr[i].shared_data = d++; shared_data_arr[i].next = &shared_data_arr[i+1]; } shared_data_arr[num_segments].shared_data = 0; shared_data_arr[num_segments].next = 0; int i, shmid; struct shared_data_storage *storage; size_t shm_size = shm_buffer_size + sizeof(struct shared_data_t); for (i = 0; i < num_segments; i++) { shmid = create_shmem(ftok(path, i), shm_size); storage = attach_shmem(shmid); init_storage(storage, shm_buffer_size); shared_data_arr[i].shared_data->data = storage; shared_data_arr[i].shared_data->shm_id = shmid; shared_data_arr[i].next = &shared_data_arr[i+1]; } shared_data_arr[num_segments - 1].next = 0; } void clear_shmem_segments(int num_segments) { int i; size_t size = (sizeof(*shared_data_arr[0].shared_data->data) + (size_t) shared_data_arr[0].shared_data->data->buf_size); for (i = 0; i < num_segments; i++) { memset(shared_data_arr[i].shared_data, 0, size); } } void detach_shmem_segments(int num_segments) { for (int i = 0; i < num_segments; ++i) { int status = shmdt(shared_data_arr[i].shared_data->data); if (status == -1) { perror("shmdt"); } } } void delete_shmem_segments(int num_segments) { for (int i = 0; i < num_segments; ++i) { int status = shmctl(shared_data_arr[i].shared_data->shm_id, IPC_RMID, 0); if (status == -1) { perror("shmctl"); } } }
0
#include <pthread.h> pthread_t *threads; pthread_mutex_t mutex; int threads_count, records_count, fd; char* word; void* thread_func(void *data){ pthread_t self; int read_count,i,j,record_id,actual_read_count,word_len; char *buf,*ptr; buf=malloc(1024*records_count); word_len=strlen(word); self=pthread_self(); read_count=1; while(read_count){ pthread_mutex_lock(&mutex); read_count=read(fd,buf,1024*records_count); pthread_mutex_unlock(&mutex); actual_read_count=read_count/1024; ptr=buf; for(i=0;i<actual_read_count;i++){ record_id=atoi(ptr); for(j=5;j<1024 -word_len;j++){ if(word_eq(ptr+j,word_len)){ printf("Znaleziono, TID - %d, rekord - %d\\n",(unsigned int)self,record_id); } } ptr+=1024; } } return 0; } bool word_eq(char* s, int word_len){ int i; char *w =word; if(!(s-1) || *(s-1)==' '){ for(i=0; i<word_len; i++){ if(s){ if(*w != *s){ return 0; } } w++; s++; } if(!(s) || *(s)==' ') return 1; } return 0; } void handler(int unused){ exit(0); } int main(int argc, char **argv){ char *file_name; int i; if(argc < 5){ printf("Needs four arguments\\n"); return -1; }else{ threads_count=atoi(argv[1]); file_name=argv[2]; records_count=atoi(argv[3]); word=argv[4]; } threads=malloc(sizeof(pthread_t)*threads_count); pthread_mutex_init(&mutex,0); fd=open(file_name,O_RDONLY); signal(SIGSEGV,handler); for(i=0; i < threads_count; i++){ pthread_create(threads+i,0,&thread_func,0); } for(i=0; i < threads_count; i++){ pthread_join(threads[i],0); } close(fd); pthread_mutex_destroy(&mutex); free(threads); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex ; void display(int n, char letter) { int i, j; for (j = 1; j < n; j++) { pthread_mutex_lock(&mutex) ; for (i = 1; i < 100000; i++); printf("%c", letter); fflush(stdout); pthread_mutex_unlock(&mutex) ; } } void *threadA(void *unused) { display(100, 65); printf("\\n End of the thread A\\n"); fflush(stdout); pthread_exit(0); } void *threadC(void *unused) { display(150, 67); printf("\\n End of the thread C\\n"); fflush(stdout); pthread_exit(0); } void *threadB(void *unused) { pthread_t thC; pthread_create(&thC, 0, threadC, 0); display(100, 66); printf("\\n Thread B is waiting for thread C\\n"); pthread_join(thC, 0); printf("\\n End of the thread B\\n"); fflush(stdout); pthread_exit(0); } int main(void) { pthread_t thA, thB; pthread_mutex_init(&mutex, 0); printf(" Creation of the thread A\\n"); pthread_create(&thA, 0, threadA, 0); printf(" Creation of the thread B\\n"); pthread_create(&thB, 0, threadB, 0); sleep(1); printf("The main thread is waiting for A and B to finish\\n"); pthread_join(thA, 0); pthread_join(thB, 0); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t prod_cv = PTHREAD_COND_INITIALIZER; pthread_cond_t cons_cv = PTHREAD_COND_INITIALIZER; int buf[50]; int current_size; int tail, head; } Q_t; Q_t g_Q; int g_counter; void enqueue(Q_t *Q, int n) { while (Q->current_size == 50) { pthread_cond_wait(&cons_cv, &mutex); } Q->buf[Q->tail] = g_counter++; Q->tail = (Q->tail + 1) % 50; Q->current_size++; if (Q->current_size == 1) { pthread_cond_broadcast(&prod_cv); } } int dequeue(Q_t *Q) { int n; while (Q->current_size == 0) { pthread_cond_wait(&prod_cv, &mutex); } n = Q->buf[Q->head]; Q->head = (Q->head + 1 ) % 50; if (Q->current_size == 50) { pthread_cond_broadcast(&cons_cv); } Q->current_size--; return n; } void *producer(void *arg) { while (1) { pthread_mutex_lock(&mutex); printf("p"); enqueue(&g_Q, g_counter); pthread_mutex_unlock(&mutex); sleep(1); } } void *consumer(void *arg) { while (1) { pthread_mutex_lock(&mutex); printf("c"); printf(" Got number %d \\n", dequeue(&g_Q)); pthread_mutex_unlock(&mutex); sleep(10); } } int main() { pthread_t tids[100 + 10]; int c = 0, i; for (i = 0; i < 100; i++) { pthread_create(&tids[c++], 0, producer, 0); } for (i = 0; i < 10; i++) { pthread_create(&tids[c++], 0, consumer, 0); } for (i = 0; i < (100 + 10); i++) { pthread_join(tids[i], 0); } }
1
#include <pthread.h> static pthread_mutex_t locka = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t lockb = PTHREAD_MUTEX_INITIALIZER; extern int errno; static void *thread_func1(void *arg) { int retcode = 0; for (;;) { pthread_mutex_lock(&lockb); printf("thread_func1 lock b get success\\n"); if ((retcode = pthread_mutex_trylock(&locka)) != 0) { if (retcode == EBUSY) { printf("lock a busy\\n"); pthread_mutex_unlock(&lockb); continue; } } printf("thread_func1 all lock get success\\n"); break; } pthread_mutex_unlock(&locka); pthread_mutex_unlock(&lockb); pthread_exit(0); } static void *thread_func2(void *arg) { int retcode = 0; for (;;) { pthread_mutex_lock(&locka); printf("thread_func2 lock a get success\\n"); if ((retcode = pthread_mutex_trylock(&lockb)) != 0) { if (retcode == EBUSY) { printf("lock b busy\\n"); pthread_mutex_unlock(&locka); continue; } } printf("thread_func2 all lock get success\\n"); break; } pthread_mutex_unlock(&lockb); pthread_mutex_unlock(&locka); pthread_exit(0); } int main(int argc, char *argv[]) { int retcode = 0; pthread_t tid1; pthread_t tid2; if ((retcode = pthread_create(&tid1, 0, thread_func1, 0)) != 0) { fprintf(stderr, "pthread_create called failure\\n"); return 1; } if ((retcode = pthread_create(&tid2, 0, thread_func2, 0)) != 0) { fprintf(stderr, "pthread_create called failure\\n"); return 1; } if (pthread_join(tid1, 0) != 0 && pthread_join(tid2, 0) != 0) { fprintf(stderr, "pthread_join failure\\n"); return 1; } return 0; }
0
#include <pthread.h> int global_int; int *dint; int *heap_int[1]; int block_write; pthread_mutex_t mlock; void *fn(void *args){ int *t = (int*)args; fprintf(stderr, "smv %d read global_int: %d\\n", *t, global_int); pthread_mutex_lock(&mlock); global_int++; printf("smv %d wrote global_int: %d\\n", *t, global_int); printf("smv %d read *dint: %d\\n", *t, *dint); *dint = global_int + 1; printf("smv %d wrote *dint: %d\\n", *t, *dint); pthread_mutex_unlock(&mlock); return 0; } int main(){ int i = 0; int *memdom_int[1024]; smv_main_init(1); pthread_mutex_init(&mlock, 0); int memdom_id = memdom_create(); smv_join_domain(memdom_id, 0); memdom_priv_add(memdom_id, 0, MEMDOM_READ | MEMDOM_WRITE); i = 0; memdom_int[i] = (int*) memdom_alloc(memdom_id, 0x50); *memdom_int[i] = i+1; printf("memdom_int[%d]: %d\\n", i, *memdom_int[i]); memdom_free(memdom_int[i]); printf("\\n"); memdom_int[i] = (int*) memdom_alloc(memdom_id, 0x20); *memdom_int[i] = i+1; printf("memdom_int[%d]: %d\\n", i, *memdom_int[i]); memdom_free(memdom_int[i]); printf("\\n"); memdom_int[i] = (int*) memdom_alloc(memdom_id, 0x50); *memdom_int[i] = i+1; printf("memdom_int[%d]: %d\\n", i, *memdom_int[i]); memdom_free(memdom_int[i]); printf("\\n"); memdom_kill(memdom_id); return 0; }
1
#include <pthread.h> uint32_t inode; uint32_t indx; uint8_t writing; uint32_t active_readers_cnt; uint32_t waiting_readers_cnt; uint32_t waiting_writers_cnt; pthread_cond_t rcond,wcond; struct chunkrec *next,**prev; } chunkrec; static pthread_mutex_t glock = PTHREAD_MUTEX_INITIALIZER; static chunkrec* hashtab[1024]; static chunkrec* freeblocks; static uint32_t freeblockscnt; void chunkrwlock_init(void) { uint32_t i; pthread_mutex_lock(&glock); for (i=0 ; i<1024 ; i++) { hashtab[i] = 0; } freeblocks=0; freeblockscnt=0; pthread_mutex_unlock(&glock); } void chunkrwlock_term(void) { uint32_t i; chunkrec *cr; pthread_mutex_lock(&glock); while (freeblocks!=0) { cr = freeblocks; zassert(pthread_cond_destroy(&(cr->rcond))); zassert(pthread_cond_destroy(&(cr->wcond))); freeblocks = cr->next; free(cr); } for (i=0 ; i<1024 ; i++) { massert(hashtab[i]==0,"chunkrwlock hashmap not empty during termination"); } pthread_mutex_unlock(&glock); } static inline chunkrec* chunkrwlock_get(uint32_t inode,uint32_t indx) { chunkrec *cr; uint32_t hash; pthread_mutex_lock(&glock); hash = ((inode * 0xF52D) + (indx ^ 0x423)) & 1023; for (cr=hashtab[hash] ; cr ; cr=cr->next) { if (cr->inode == inode && cr->indx==indx) { return cr; } } if (freeblocks==0) { cr = malloc(sizeof(chunkrec)); passert(cr); zassert(pthread_cond_init(&(cr->rcond),0)); zassert(pthread_cond_init(&(cr->wcond),0)); } else { cr = freeblocks; freeblocks = cr->next; freeblockscnt--; } cr->inode = inode; cr->indx = indx; cr->writing = 0; cr->active_readers_cnt = 0; cr->waiting_readers_cnt = 0; cr->waiting_writers_cnt = 0; cr->prev = hashtab+hash; cr->next = hashtab[hash]; if (cr->next) { cr->next->prev = &(cr->next); } hashtab[hash] = cr; return cr; } static inline void chunkrwlock_release(chunkrec *cr) { if ((cr->writing | cr->active_readers_cnt | cr->waiting_readers_cnt | cr->waiting_writers_cnt)==0) { *(cr->prev) = cr->next; if (cr->next) { cr->next->prev = cr->prev; } if (freeblockscnt>1024) { zassert(pthread_cond_destroy(&(cr->rcond))); zassert(pthread_cond_destroy(&(cr->wcond))); free(cr); } else { cr->prev = 0; cr->next = freeblocks; freeblocks = cr; freeblockscnt++; } } pthread_mutex_unlock(&glock); } void chunkrwlock_rlock(uint32_t inode,uint32_t indx) { chunkrec *cr; cr = chunkrwlock_get(inode,indx); cr->waiting_readers_cnt++; while (cr->writing | cr->waiting_writers_cnt) { zassert(pthread_cond_wait(&(cr->rcond),&glock)); } cr->waiting_readers_cnt--; cr->active_readers_cnt++; chunkrwlock_release(cr); } void chunkrwlock_runlock(uint32_t inode,uint32_t indx) { chunkrec *cr; cr = chunkrwlock_get(inode,indx); cr->active_readers_cnt--; if (cr->active_readers_cnt==0 && cr->waiting_writers_cnt) { zassert(pthread_cond_signal(&(cr->wcond))); } chunkrwlock_release(cr); } void chunkrwlock_wlock(uint32_t inode,uint32_t indx) { chunkrec *cr; cr = chunkrwlock_get(inode,indx); cr->waiting_writers_cnt++; while (cr->active_readers_cnt | cr->writing) { zassert(pthread_cond_wait(&(cr->wcond),&glock)); } cr->waiting_writers_cnt--; cr->writing = 1; chunkrwlock_release(cr); } void chunkrwlock_wunlock(uint32_t inode,uint32_t indx) { chunkrec *cr; cr = chunkrwlock_get(inode,indx); cr->writing = 0; if (cr->waiting_writers_cnt) { zassert(pthread_cond_signal(&(cr->wcond))); } else if (cr->waiting_readers_cnt) { zassert(pthread_cond_broadcast(&(cr->rcond))); } chunkrwlock_release(cr); }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond0 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; unsigned thread = 0; void fail(char *msg) { fprintf(stderr, "Error: %s\\n", msg); exit(1); } volatile int running = 1; void *thread0(void *arg) { char ** str_pt = (char **)arg; unsigned i=0; while (running) { pthread_mutex_lock(&lock); while (thread != 0) { pthread_cond_wait(&cond0, &lock); } pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); if (running) { printf("%s\\n", str_pt[i%3]); i++; } thread = 2; pthread_cond_signal(&cond2); pthread_mutex_unlock(&lock); } printf("Thread 0 total count %u\\n",i); return 0; } void *thread1(void *arg) { char ** str_pt = (char **)arg; unsigned i=0; while (running) { pthread_mutex_lock(&lock); while (thread != 1) { pthread_cond_wait(&cond1, &lock); } pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); if (running) { printf("%s\\n", str_pt[i%3]); i++; } thread = 0; pthread_cond_signal(&cond0); pthread_mutex_unlock(&lock); } printf("Thread 1 total count %u\\n",i); return 0; } void *thread2(void *arg) { char ** str_pt = (char **)arg; unsigned i=0; while (running) { pthread_mutex_lock(&lock); while (thread != 2) { pthread_cond_wait(&cond2, &lock); } pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); if (running) { printf("%s\\n", str_pt[i%3]); i++; } thread = 1; pthread_cond_signal(&cond1); pthread_mutex_unlock(&lock); } printf("Thread 2 total count %u\\n",i); return 0; } int main(int argc, char *argv[]) { char * str_array0[3] = {"alpha", "delta", "eta"}; char * str_array1[3] = {"gamma", "zeta", "iota"}; char * str_array2[3] = {"beta", "epsilon", "theta"}; pthread_t thread[3]; if (pthread_create(thread + 0, 0, thread0, str_array0) != 0) fail("Can't create thread0.\\n"); if (pthread_create(thread + 1, 0, thread1, str_array1) != 0) fail("Can't create thread1.\\n"); if (pthread_create(thread + 2, 0, thread2, str_array2) != 0) fail("Can't create thread2.\\n"); sleep(1); running = 0; int i; for (i = 0; i < 3; i++) pthread_join(thread[i], 0); return 0; }
1
#include <pthread.h> void *thread_fmain(void *); void *thread_mmain(void *); void man_leave(); void man_enter(); void woman_leave(); void woman_enter(); void use_rr(); void do_other_stuff(); int get_simple_tid(pthread_t); int maleCount = 0; int femaleCount =0; pthread_t threadIDs[2 +2]; sem_t rr_semaphore; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t full = PTHREAD_COND_INITIALIZER; int main() { pthread_attr_t attribs; int i; int tids[2 +2]; pthread_t pthreadids[2 +2]; sem_init(&rr_semaphore, 0, 2); pthread_mutex_init(&mutex, 0); srandom(time(0) % (unsigned int) 32767); pthread_attr_init(&attribs); for (i=0; i< 2; i++) { tids[i] = i; pthread_create(&(pthreadids[i]), &attribs, thread_fmain, &(tids[i])); } for (i=0; i< 2; i++) { tids[i+2] = i+2; pthread_create(&(pthreadids[i]), &attribs, thread_mmain, &(tids[i+2])); } for (i=0; i< 2 +2; i++) pthread_join(pthreadids[i], 0); return 0; } void *thread_fmain(void * arg) { int tid = *((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); woman_enter(); use_rr(); woman_leave(); } } void *thread_mmain(void * arg) { int tid = * ((int *) arg); threadIDs[tid] = pthread_self(); while(1==1) { do_other_stuff(); man_enter(); use_rr(); man_leave(); } } void woman_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread f%d trying to get in the restroom\\n", id); pthread_mutex_lock(&mutex); while(maleCount > 0 || femaleCount == 2){ pthread_cond_wait(&full, &mutex); } sem_wait(&rr_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++femaleCount; pthread_mutex_unlock(&mutex); printf("Thread f%d got in!\\n", id); printf("Wait time for thread f%d was %f\\n", id, waittime); } void woman_leave() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr_semaphore); --femaleCount; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("thread f %d left!\\n",id); } void man_enter() { clock_t start, stop; double waittime; start = clock(); int id = get_simple_tid(pthread_self()); printf("Thread m%d trying to get in the restroom\\n", id); pthread_mutex_lock(&mutex); while(femaleCount > 0 || maleCount == 2){ pthread_cond_wait(&full, &mutex); } sem_wait(&rr_semaphore); stop = clock(); waittime = (double) (stop-start)/CLOCKS_PER_SEC; ++maleCount; pthread_mutex_unlock(&mutex); printf("Thread m%d got in!\\n", id); printf("Wait time for thread m%d was %f\\n", id, waittime); } void man_leave() { int id = get_simple_tid(pthread_self()); pthread_mutex_lock(&mutex); sem_post(&rr_semaphore); --maleCount; pthread_cond_broadcast(&full); pthread_mutex_unlock(&mutex); printf("Thread m%d left!\\n", id); } void use_rr() { struct timespec req, rem; double usetime; usetime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(usetime); req.tv_nsec = (unsigned int) ( (usetime - (int) floor(usetime)) * 1000000000); printf("Thread %d using restroom for %lf time\\n", get_simple_tid(pthread_self()), usetime); nanosleep(&req,&rem); } void do_other_stuff() { struct timespec req, rem; double worktime; worktime = 10 * (random() / (1.0*(double) ((unsigned long) 32767))); req.tv_sec = (int) floor(worktime); req.tv_nsec = (unsigned int) ( (worktime - (int) floor(worktime)) * 1000000000); printf("Thread %d working for %lf time\\n", get_simple_tid(pthread_self()), worktime); nanosleep(&req,&rem); } int get_simple_tid(pthread_t lid) { int i; for (i=0; i<2 +2; i++) if (pthread_equal(lid, threadIDs[i])) return i; printf("Oops! did not find a tid for %lu\\n", lid); _exit(-1); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond_leitor; pthread_cond_t cond_escritor; int escritores = 0; int leitores = 0; int querEscrever = 0; { int contador; int idThread; }Arquivo; Arquivo arquivo; void inicializa_leitor(){ pthread_mutex_lock(&mutex); while(escritores > 0 || querEscrever > 0){ pthread_cond_wait(&cond_leitor, &mutex); } leitores++; pthread_mutex_unlock(&mutex); } void finaliza_leitor(){ pthread_mutex_lock(&mutex); leitores --; if(leitores == 0 || querEscrever > 0) pthread_cond_signal(&cond_escritor); pthread_mutex_unlock(&mutex); } void inicializa_escritor(){ pthread_mutex_lock(&mutex); querEscrever ++; while(escritores > 0){ pthread_cond_wait(&cond_escritor,&mutex); } escritores ++; pthread_mutex_unlock(&mutex); } void finaliza_escritor(){ pthread_mutex_lock(&mutex); escritores --; querEscrever --; pthread_cond_signal(&cond_escritor); if(querEscrever == 0){ pthread_cond_broadcast(&cond_leitor); } pthread_mutex_unlock(&mutex); } void * leitor(void * arg){ int* p = (int *) arg; int pid = (int) *p; Arquivo arquivoLocal; while(1){ printf("Thread Leitora[%d]\\n", pid); inicializa_leitor(); arquivoLocal.contador = arquivo.contador; arquivoLocal.idThread = arquivo.idThread; printf("Leu o contador: [%d] que foi gravado pela Thread: [%d] \\n",arquivoLocal.contador,arquivoLocal.idThread ); finaliza_leitor(); sleep(1); } pthread_exit(0); } void* escritor(void *arg){ int * p = (int *) arg; int pid = (int) *p; while(1){ printf("Thread Escritora[%d]\\n", pid); inicializa_escritor(); pthread_mutex_lock(&mutex); arquivo.contador ++; arquivo.idThread = pid; pthread_mutex_unlock(&mutex); finaliza_escritor(); sleep(1); } pthread_exit(0); } int main(int argc, char *argv[]){ int i,j; int* pid; pthread_t threads[2 +2]; for ( i = 0; i < 2; ++i) { pid = (int*) malloc(sizeof(int)); *pid = i; pthread_create(&threads[i],0, escritor,(void *) pid); } for ( j = 2; j < 2 + 2; ++j) { pid = (int*) malloc(sizeof(int)); *pid = j; pthread_create(&threads[j],0, leitor,(void *) pid); } for (i = 0; i < 2 + 2; ++i) { pthread_join(threads[i],0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_leitor); pthread_cond_destroy(&cond_escritor); free(pid); return 0; }
1
#include <pthread.h> pthread_mutex_t bd = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t cl = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t turno = PTHREAD_MUTEX_INITIALIZER; int l = 0; void* leitores(void* arg){ time_t t; int id = *((int *) arg); srand((unsigned) time(&t)); printf("Leitor %d criado.\\n",id); while(1) { pthread_mutex_lock(&turno); pthread_mutex_lock(&cl); l++; if(l==1) { pthread_mutex_lock(&bd); } pthread_mutex_unlock(&cl); pthread_mutex_unlock(&turno); printf("**Leitor %d iniciando a leitura do BD.**\\n", id); sleep(rand() % 10); printf("**Leitor %d encerrando a leitura do BD.**\\n", id); pthread_mutex_lock(&cl); l--; if(!l) { pthread_mutex_unlock(&bd); } pthread_mutex_unlock(&cl); sleep(rand() % 10); } } void* escritores(void* arg) { time_t t; int id = *((int *) arg); srand((unsigned) time(&t)); printf("Escritor %d criado.\\n",id); while(1) { sleep(rand() % 10); pthread_mutex_lock(&turno); pthread_mutex_lock(&bd); printf("--Escritor %d iniciando a escrita no BD.--\\n", id); sleep(rand() % 10); printf("--Escritor %d encerrando a escrita no BD.--\\n", id); pthread_mutex_unlock(&bd); pthread_mutex_unlock(&turno); } } int main() { pthread_t a[12]; time_t t; int i, j, k; int * id; srand((unsigned) time(&t)); j = 0; k = 0; for (i = 0; i < 12 ; i++) { id = (int *) malloc(sizeof(int)); if(rand() % 2) { *id = k; k++; pthread_create(&a[i], 0, leitores, (void *) (id)); } else { *id = j; j++; pthread_create(&a[i], 0, escritores, (void *) (id)); } } pthread_join(a[0],0); return 0; }
0
#include <pthread.h> int balance; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int rnd = 100000; void *p1(void *ptr) { for(int i=0; i<rnd; i++){ pthread_mutex_lock(&mutex); ++balance; pthread_mutex_unlock(&mutex); } return 0; } void *p2(void *ptr) { for(int i=0;i<rnd; i++){ pthread_mutex_lock(&mutex); --balance; pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char *argv[]) { if(argc >= 2){ int tmp = atoi(argv[1]); if(tmp > 100000){ rnd = tmp; } } printf("Setting round to: %d\\n", rnd); printf("Before two threads running, balance = %d\\n", balance); pthread_t threads[2] = {PTHREAD_ONCE_INIT, PTHREAD_ONCE_INIT}; pthread_create(&threads[0], 0, p1, 0); pthread_create(&threads[1], 0, p2, 0); pthread_join(threads[0], 0); pthread_join(threads[1], 0); printf("After two threads running, balance = %d\\n", balance); }
1
#include <pthread.h> struct msg { int num; struct msg *next; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_cond_t has_consume = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; void *producer(void *p) { struct msg *mp; while (1) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("Produce %d\\n",mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 3); } } void *consumer(void *p) { struct msg *mp; while (1) { pthread_mutex_lock(&lock); while (head == 0) { pthread_cond_wait(&has_product, &lock); } mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("Consume %d\\n",mp->num); free(mp); sleep(rand() % 3); } } int main(int argc, const char *argv[]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
0
#include <pthread.h> { int thread_n; }TParam,*PParam; int global_counter=1; int threads_waiting=0; pthread_mutex_t mtx1=PTHREAD_MUTEX_INITIALIZER, mtx2=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond; void* worker_thread(void *param) { PParam pp=(PParam)param; printf("thread %d started\\n",pp->thread_n); pthread_mutex_lock(&mtx1); global_counter++; pthread_mutex_unlock(&mtx1); sleep(global_counter); pthread_mutex_lock(&mtx1); threads_waiting++; pthread_mutex_unlock(&mtx1); printf("thread %d suspended\\n",pp->thread_n); if (threads_waiting>=5) { printf("last thread, global_counter=%d\\n",global_counter); pthread_cond_broadcast(&cond); } else { pthread_mutex_lock(&mtx2); pthread_cond_wait(&cond,&mtx2); pthread_mutex_unlock(&mtx2); } printf("thread %d done\\n",pp->thread_n); }; int main(int argc, char *argv[]) { pthread_t threads[5]; TParam t_param[5]; int res,i,t; pthread_cond_init(&cond,0); for(i=0;i<5;i++) { t_param[i].thread_n=i; res=pthread_create(&threads[i],0,worker_thread,(void*)&t_param[i]); if (res) { printf("Error creating thread %d\\n",i); } } for(i=0;i<5;i++) pthread_join(threads[i],0); sleep(2); }
1
#include <pthread.h> int piao = 100; pthread_mutex_t mut; void* tprocess1(void* args){ int a = 0; while(1){ pthread_mutex_lock(&mut); if(piao>0){ sleep(1); piao--; printf("xiancheng 1----------------»¹Ê£%dÕÅÆ±\\n",piao); }else{ a = 1; } pthread_mutex_unlock(&mut); sleep(1); if(a == 1) { break; } } return 0; } void* tprocess2(void* args){ int a = 0; while(1){ pthread_mutex_lock(&mut); if(piao>0){ sleep(1); piao--; printf("xiancheng 2----------------»¹Ê£%dÕÅÆ±\\n",piao); }else{ a = 1; } pthread_mutex_unlock(&mut); sleep(1); if(a == 1) { break; } } return 0; } void* tprocess3(void* args){ int a = 0; while(1){ pthread_mutex_lock(&mut); if(piao>0){ sleep(1); piao--; printf("xiancheng 3----------------»¹Ê£%dÕÅÆ±\\n",piao); }else{ a = 1; } pthread_mutex_unlock(&mut); sleep(1); if(a == 1) { break; } } return 0; } void* tprocess4(void* args){ int a = 0; while(1){ pthread_mutex_lock(&mut); if(piao>0){ sleep(1); piao--; printf("xiancheng 4----------------yu%dÕÅÆ±\\n",piao); }else{ a = 1; } pthread_mutex_unlock(&mut); sleep(1); if(a == 1) { break; } } return 0; } int main(){ pthread_mutex_init(&mut,0); pthread_t t1; pthread_t t2; pthread_t t3; pthread_t t4; pthread_create(&t4,0,tprocess4,0); pthread_create(&t1,0,tprocess1,0); pthread_create(&t2,0,tprocess2,0); pthread_create(&t3,0,tprocess3,0); printf("tony test-----end0\\n"); sleep(102); printf("tony test-----end1\\n"); return 0; }
0
#include <pthread.h> int oskit_sem_unlink(const char *name) { int i; sem_t *sem; pthread_mutex_lock(&semn_space.semn_lock); for (i = 0 ; i < semn_space.semn_arraylen ; i++) { if (semn_space.semn_array[i] && (strcmp(semn_space.semn_array[i]->sem_name, name) == 0)) { sem = semn_space.semn_array[i]; pthread_lock(&sem->sem_lock); if (sem->sem_refcount != 0) { sem->sem_flag |= SEM_UNLINK_FLAG; pthread_unlock(&sem->sem_lock); } else { sem_remove(sem); } semn_space.semn_array[i] = 0; pthread_mutex_unlock(&semn_space.semn_lock); return 0; } } pthread_mutex_unlock(&semn_space.semn_lock); return ENOENT; } void sem_remove(sem_t *sem) { if (sem->sem_name) { free(sem->sem_name); } free(sem); }
1
#include <pthread.h> static unsigned long rnd = 11; int buffer[10]; int out = 0; int in = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *producer(void *param); void *consumer(void *param); int genrnd(unsigned int n); void printbuf(); int main(int argc, const char *argv[]) { pthread_t tid1; pthread_t tid2; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid1, &attr, producer, 0); pthread_create(&tid2, &attr, consumer, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); return 0; } void *producer(void *param) { printf("start producer...\\n"); while(1){ pthread_mutex_lock(&mutex); if (((in + 1) % 10 != out)){ int d = genrnd(10); in = (in + 1) % 10; buffer[in] = d; printf("produce %d ", d); printbuf(); } pthread_mutex_unlock(&mutex); usleep(genrnd(10000)); } } void *consumer(void *param) { printf("start consumer...\\n"); while(1){ pthread_mutex_lock(&mutex); if (out != in){ out = (out + 1) % 10; int d = buffer[out]; buffer[out] = -1; printf("consume %d ", d); printbuf(); } pthread_mutex_unlock(&mutex); usleep(genrnd(10000)); } } void printbuf() { int i; for (i = 0; i < 10; i++){ usleep(100); if ((in > out && i > out && i <= in) || (in < out && (i <= in || i > out))){ printf("%d",buffer[i]); } else{ printf("-"); } } printf(" \\n"); } int genrnd(unsigned int n) { rnd = (1103515245 * rnd) % 45901 ; return (n * rnd)/45901; }
0
#include <pthread.h> struct mq_info { char *msg_ptr; size_t msg_size; volatile int was_written; pthread_mutex_t msg_snd_mutex; pthread_cond_t msg_snd_cv; pthread_mutex_t msg_rcv_mutex; pthread_cond_t msg_rcv_cv; }; static struct mq_info msg_table[MQ_MAXCOUNT]; int msg_send(int mq_id, char *msg, int size) { if (mq_id > sizeof(msg_table) / sizeof(msg_table[0])) { return -1; } pthread_mutex_lock(&msg_table[mq_id].msg_rcv_mutex); if (msg_table[mq_id].was_written) { pthread_cond_wait(&msg_table[mq_id].msg_rcv_cv, &msg_table[mq_id].msg_rcv_mutex); } msg_table[mq_id].msg_ptr = sysmalloc(size + 1); strncpy(msg_table[mq_id].msg_ptr, msg, size); msg_table[mq_id].msg_ptr[size] = '\\0'; msg_table[mq_id].msg_size = size + 1; msg_table[mq_id].was_written = 1; pthread_mutex_unlock(&msg_table[mq_id].msg_rcv_mutex); pthread_cond_broadcast(&msg_table[mq_id].msg_snd_cv); return 0; } int msg_receive(int mq_id, char *msg, int size) { if (mq_id > sizeof(msg_table) / sizeof(msg_table[0])) { return -1; } pthread_mutex_lock(&msg_table[mq_id].msg_snd_mutex); if (!msg_table[mq_id].was_written) { pthread_cond_wait(&msg_table[mq_id].msg_snd_cv, &msg_table[mq_id].msg_snd_mutex); } strncpy(msg, msg_table[mq_id].msg_ptr, size < msg_table[mq_id].msg_size ? size : msg_table[mq_id].msg_size); msg[size - 1] = '\\0'; sysfree(msg_table[mq_id].msg_ptr); msg_table[mq_id].was_written = 0; pthread_mutex_unlock(&msg_table[mq_id].msg_snd_mutex); pthread_cond_broadcast(&msg_table[mq_id].msg_rcv_cv); return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *prod_func(); void *cons_func(); int ret,fd; int main() { int ret1,ret2; pthread_t producer,consumer; ret1=pthread_create(&producer,0,&cons_func,0); ret2=pthread_create(&consumer,0,&prod_func,0); if(ret1 != 0 || ret2 != 0){perror("Error in Creating Threads"); exit(1);} pthread_join(producer,0); pthread_join(consumer,0); return 0; } void *prod_func() { char value[50]; printf("In producer\\n"); pthread_mutex_lock(&mutex1); fd = open("/dev/our_char",O_RDONLY); ret = read(fd,&value,60); write(1,&value,ret); close(fd); pthread_mutex_unlock(&mutex1); pthread_exit(0); } void *cons_func() { pthread_mutex_lock(&mutex1); printf("in consumer\\n"); char strc[60]="Success is a journey not a destination"; fd = open("/dev/our_char",O_WRONLY); ret = write(fd,&strc,60); printf("writing complete %d chars\\n",ret); close(fd); pthread_mutex_unlock(&mutex1); pthread_exit(0); }
0
#include <pthread.h> int counter; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void print_message() { pthread_mutex_lock(&mutex1); printf("thread id =%ld\\n", pthread_self()); counter++; printf("counter value is %d\\n", counter); pthread_mutex_unlock(&mutex1); } int main() { pthread_t thread[10]; char *message1 = "thread1", *message2 = "thread2"; int ret1 = 0, ret2 = 0,i; for(i = 0; i<10; i++) { if(ret1 = pthread_create(&thread[i], 0, (void *)&print_message, 0)) { printf("failed to create pthread for i = %d\\n",i); return 0; } } for(i = 0; i<10; i++) pthread_join(thread[i], 0); printf(" return values %d %d \\n", ret1, ret2); printf("counter value is %d in main\\n", counter); return 0; }
1
#include <pthread.h> struct play_t { char fname[256]; off_t flen; off_t ldlen; int pos; int fi; int fo; }; static pthread_t tid_play; static pthread_t tid_load; static volatile int playing = 0; static volatile int loading = 0; static volatile int _pause = 0; static struct play_t play; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void lock(void) { pthread_mutex_lock(&mutex); } static void unlock(void) { pthread_mutex_unlock(&mutex); } static void do_wait(int no) { while( wait(0) != -1); playing = 0; } static char *getval(int fd, char *key, char *val) { int ch; char buff[1024]; int len = strlen(key); char *ret; while(1) { read(fd, buff, len); if(strchr(buff, key[0]) == 0 ) { continue; } } return ret; } void play_cmd(char *cmd) { lock(); if(play.fi != -1) { write(play.fi, cmd, strlen(cmd)); if(strcmp(cmd, "pause\\n") == 0) { _pause = !_pause; } } unlock(); } static int buffering(struct play_t *this) { struct stat st; off_t buff_len = this->flen*2/100; off_t pos = this->pos/100.0 * this->flen; stat(this->fname, &st); this->ldlen = st.st_size; if((this->ldlen - pos < buff_len) && (this->ldlen < this->flen)) { if(this->fi != -1) { if(!_pause) play_cmd("pause\\n"); } while((this->ldlen - pos < buff_len) && (this->ldlen < this->flen)) { stat(this->fname, &st); this->ldlen = st.st_size; usleep(100 * 1000); if(playing == 0) break; } if(this->fi != -1) { if(!_pause) play_cmd("pause\\n"); } } return 0; } static void *thr_play(void *arg) { struct play_t *this = arg; int fi[2]; int fo[2]; char *p,buff[1024]; this->pos = 0; this->ldlen = 0; this->fi = -1; this->fo = -1; buffering(this); pipe(fi); pipe(fo); signal(SIGCHLD, do_wait); if(fork() == 0) { dup2(fi[0], 0); dup2(fo[1], 1); close(fi[0]); close(fi[1]); close(fo[0]); close(fo[1]); close(2); execlp("mplayer", "mplayer", "-slave", "-quiet", this->fname, 0); exit(-1); } close(fi[0]); close(fo[1]); this->fi = fi[1]; this->fo = fo[0]; while(playing) { strcpy(buff, "get_percent_pos\\n"); lock(); if(!_pause) { write(fi[1], buff, strlen(buff)); memset(buff, 0, sizeof(buff)); read(fo[0], buff, sizeof(buff)); if(!strncmp(buff, "ANS_PERCENT_POSITION=", strlen("ANS_PERCENT_POSITION=") ) ) { p = strchr(buff, '='); this->pos = atoi(p+1); } } unlock(); if(this->pos == 100) break; buffering(this); usleep(100 * 1000); } close(fi[1]); close(fo[0]); remove(play.fname); return 0; } void trim(char *s) { char *p = s + strlen(s) - 1; while(p>=s && *p == ' ') { *p = 0; p++; } p = s; while(*p == ' ') p++; strcpy(s, p); } void play_start(char *tmp_file, off_t size) { strcpy(play.fname, tmp_file); play.flen = size; playing = 1; _pause = 0; pthread_create(&tid_play, 0, thr_play, &play); } void play_stop(void) { write(play.fi, "stop\\n", 5); pthread_join(tid_play, 0); playing = 0; } static void *thr_load(void *arg) { char *file = arg; char *tmp_file = ".tmp"; struct stat st; int fd, fd_tmp; char buff[4*1024]; int len; file = strchr((char *)arg, '\\n'); if(file) *file = 0; file = arg; trim(file); fd = open(file, O_RDONLY); free(file); fd_tmp = open(tmp_file, O_WRONLY|O_CREAT|O_TRUNC, 0644); fstat(fd, &st); play_start(tmp_file, st.st_size); while( loading && (len = read(fd, buff, sizeof(buff))>0) ) { write(fd_tmp, buff, len); } close(fd); close(fd_tmp); loading = 0; return 0; } void loadfile(char *file) { char *p; printf("%d\\n", 285); if(loading) { loading = 0; pthread_join(tid_load, 0); } printf("%d\\n", 292); if(playing) { play_stop(); } printf("%d\\n", 298); p = malloc(strlen(file)+1); pthread_create(&tid_load, 0, thr_load, p); printf("%d\\n", 301); } int main(int argc, char **argv) { char cmd[100]; play_start("tmp", 1000000); while(1) { printf("$>"); fgets(cmd, sizeof(cmd), stdin); if(!strncmp(cmd, "load", 4)) { loadfile(cmd + 4); } else if(!strcmp(cmd, "stop\\n")) { play_stop(); return 0; } else play_cmd(cmd); } }
0
#include <pthread.h> pthread_mutex_t bag_mutex, sum_mutex, min_mutex, max_mutex; int numWorkers; int next_row = 0; 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); } int x, y; int value; } Pos; double start_time, end_time; int size; long sum; Pos min, max; int matrix[10000][10000]; void *Worker(void *); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_mutex_init(&bag_mutex, 0); pthread_mutex_init(&sum_mutex, 0); pthread_mutex_init(&max_mutex, 0); pthread_mutex_init(&min_mutex, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; srand(7); for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } sum = 0; min.value = matrix[0][0]; max.value = matrix[0][0]; min.x = min.y = max.x = max.y = 0; start_time = read_timer(); for (l = 0; l < numWorkers; l++) pthread_create(&workerid[l], &attr, Worker, (void *) l); for (l = 0; l < numWorkers; l++) pthread_join(workerid[l], 0); end_time = read_timer(); printf("The total is %ld, min is %d at [%d,%d], max is %d at [%d,%d]\\n", sum, min.value, min.y, min.x, max.value, max.y, max.x); printf("The execution time is %g sec\\n", end_time - start_time); pthread_exit(0); } void *Worker(void *arg) { long myid = (long) arg; long total; int row, j; while (1) { pthread_mutex_lock(&bag_mutex); row = next_row++; pthread_mutex_unlock(&bag_mutex); if (row >= size) pthread_exit(0); total = 0; for (j = 0; j < size; j++) { total += matrix[row][j]; if (min.value > matrix[row][j]) { pthread_mutex_lock(&min_mutex); if (min.value > matrix[row][j]) { min.value = matrix[row][j]; min.x = j; min.y = row; } pthread_mutex_unlock(&min_mutex); } else if (max.value < matrix[row][j]) { pthread_mutex_lock(&max_mutex); if (max.value < matrix[row][j]) { max.value = matrix[row][j]; max.x = j; max.y = row; } pthread_mutex_unlock(&max_mutex); } } pthread_mutex_lock(&sum_mutex); sum += total; pthread_mutex_unlock(&sum_mutex); } pthread_exit(0); }
1
#include <pthread.h> struct var_m { pthread_mutex_t var_mutex; }; int var; struct var_m pvar_m[1]; void var_inc(void* i); int main() { pthread_t ptchild[2]; int num[2]; num[0] = 0; num[1] = 1; int timer = 0; pthread_mutex_init(&pvar_m->var_mutex, 0); printf("timer: %d\\n", timer); timer++; pthread_create(&(ptchild[0]), 0, (void*) &var_inc, (void*) &(num[0])); sleep(1); printf("here1!!\\n"); pthread_create(&(ptchild[1]), 0, (void*) &var_inc, (void*) &(num[1])); while(1) { printf("timer: %d\\n", timer); timer++; sleep(1); } return 0; } void var_inc(void* i) { int num = *((int*)i); while(1) { printf("\\nnum:%d waiting!!\\n\\n", num); pthread_mutex_lock(&pvar_m->var_mutex); var++; printf("\\nnum:%d var:%d\\n", num, var); printf("num:%d sleep 8 secs!!\\n\\n", num); sleep(8); pthread_mutex_unlock(&pvar_m->var_mutex); sleep(2); } }
0
#include <pthread.h> int buf = 0; pthread_mutex_t mutex; void thread_func1() { while(buf < 30) { pthread_mutex_lock(&mutex); buf++; printf("thread1:%d\\n", buf); sleep(5); pthread_mutex_unlock(&mutex); sleep(2); } } void thread_func2() { while(buf < 30) { pthread_mutex_lock(&mutex); buf++; printf("thread2:%d\\n", buf); pthread_mutex_unlock(&mutex); sleep(1); } } void main(void) { pthread_t thread1, thread2; int ret1, ret2; pthread_mutex_init(&mutex, 0); ret1 = pthread_create(&thread1, 0, (void*)thread_func1, 0); if(ret1 != 0 ){ printf("Create Thread1 faild\\n"); return 1; } ret2 = pthread_create(&thread2, 0, (void*)thread_func2, 0); if(ret2 != 0 ){ printf("Create Thread2 faild\\n"); return 2; } pthread_join(thread1, 0); pthread_join(thread2, 0); }
1
#include <pthread.h> struct bhfs_open_file *bhfs_f_list; pthread_mutex_t bhfs_f_list_mutex; struct bhfs_open_file *bhfs_new_open_file() { struct bhfs_open_file *new_file; new_file = malloc(sizeof(struct bhfs_open_file)); new_file->fh = 0; new_file->size = 0; new_file->pid = 0; new_file->next = 0; return new_file; } void bhfs_free_open_file(struct bhfs_open_file *new_open_file) { free(new_open_file); } void bhfs_f_list_append(struct bhfs_open_file *new_open_file) { pthread_mutex_lock(&bhfs_f_list_mutex); new_open_file->next = bhfs_f_list; bhfs_f_list = new_open_file; pthread_mutex_unlock(&bhfs_f_list_mutex); } struct bhfs_open_file *bhfs_f_list_get(int fd) { pthread_mutex_lock(&bhfs_f_list_mutex); struct bhfs_open_file *cur_open_file; if (bhfs_f_list == 0) { pthread_mutex_unlock(&bhfs_f_list_mutex); return 0; } cur_open_file = bhfs_f_list; do { if (cur_open_file->fh == fd) { pthread_mutex_unlock(&bhfs_f_list_mutex); return cur_open_file; } cur_open_file = cur_open_file->next; } while (cur_open_file != 0); pthread_mutex_unlock(&bhfs_f_list_mutex); return 0; } void bhfs_f_list_delete(struct bhfs_open_file *open_file_to_delete) { struct bhfs_open_file *next_open_file; pthread_mutex_lock(&bhfs_f_list_mutex); if (bhfs_f_list == 0) { pthread_mutex_unlock(&bhfs_f_list_mutex); return; } next_open_file = bhfs_f_list; if (next_open_file == open_file_to_delete) { bhfs_f_list = next_open_file->next; pthread_mutex_unlock(&bhfs_f_list_mutex); return; } while (next_open_file->next != 0 && next_open_file->next != open_file_to_delete) { next_open_file = next_open_file->next; } if (next_open_file->next == open_file_to_delete) { next_open_file->next = open_file_to_delete->next; } pthread_mutex_unlock(&bhfs_f_list_mutex); return; }
0
#include <pthread.h> struct suspender { int s_sock; suspender *s_next; }; static pthread_mutex_t sus_lock = PTHREAD_MUTEX_INITIALIZER; static suspender *suspenders; void *susp_thread_main(void *closure) { while (1) { pthread_mutex_lock(&sus_lock); suspender *sp = suspenders; if (sp) suspenders = sp->s_next; else { int r = resume_daemon(); if (r) { syslog(LOG_ERR, "resume failed: %m"); exit(1); } } pthread_mutex_unlock(&sus_lock); if (!sp) break; (void)write(sp->s_sock, "OK\\n", 3); char junk[10]; for (ssize_t nr = 0; (nr = read(sp->s_sock, &junk, sizeof junk)); ) { if (nr < 0) { syslog(LOG_ERR, "suspender read: %m"); sleep(1); } } if (close(sp->s_sock)) syslog(LOG_ERR, "suspender close failed: %m"); syslog(LOG_INFO, "EOF on suspender"); free(sp); } return 0; } static int create_suspension_thread(void) { pthread_t susp_thread; int r = pthread_create(&susp_thread, 0, susp_thread_main, 0); if (r) { syslog(LOG_ERR, "Can't create thread: %m"); return r; } r = pthread_detach(susp_thread); if (r) { syslog(LOG_ERR, "Can't detach thread: %m"); return r; } return 0; } void instantiate_suspender_service(int sock) { suspender *sp = calloc(1, sizeof *sp); if (!sp) { syslog(LOG_CRIT, "out of memory: %m"); static const char oom_msg[] = "thruport daemon: out of memory\\n"; (void)write(sock, oom_msg, sizeof oom_msg - 1); exit(1); } sp->s_sock = sock; pthread_mutex_lock(&sus_lock); suspender *rest = suspenders; sp->s_next = rest; suspenders = sp; pthread_mutex_unlock(&sus_lock); if (!rest) { int r = suspend_daemon(); if (r) { syslog(LOG_CRIT, "failed to suspend daemon: %m"); static const char msg[] = "thruport: failed to suspend daemon\\n"; (void)write(sock, msg, sizeof msg - 1); exit(1); } r = create_suspension_thread(); if (r) { syslog(LOG_CRIT, "failed to suspend daemon: %m"); static const char msg[] = "thruport: failed to suspend daemon\\n"; (void)write(sock, msg, sizeof msg - 1); (void)close(sock); } } }
1
#include <pthread.h> struct jc_type_file_seq_abort { struct jc_type_file_comm_hash *comm_hash; }; static struct jc_type_file_seq_abort global_abort; static int jc_type_file_seq_abort_init( struct jc_comm *jcc ) { return global_abort.comm_hash->init(global_abort.comm_hash, jcc); } static int jc_type_file_seq_abort_execute( struct jc_comm *jcc ) { return global_abort.comm_hash->execute(global_abort.comm_hash, jcc); } static int jc_type_file_seq_abort_copy( unsigned int data_num ) { return global_abort.comm_hash->copy(global_abort.comm_hash, data_num); } static int jc_type_file_seq_abort_comm_init( struct jc_type_file_comm_node *fcn ) { return JC_OK; } static int jc_type_file_seq_abort_comm_copy( struct jc_type_file_comm_node *fcn, struct jc_type_file_comm_var_node *cvar ) { return JC_OK; } static char * jc_type_file_seq_abort_comm_execute( char separate, struct jc_type_file_comm_node *fsn, struct jc_type_file_comm_var_node *svar ) { if (svar->last_val) free(svar->last_val); pthread_mutex_lock(&svar->mutex); svar->last_val = jc_file_val_get(fsn->col_num, 0, separate, svar->cur_ptr, &svar->cur_ptr); if (!svar->last_val) svar->last_val = 0; pthread_mutex_unlock(&svar->mutex); return svar->last_val; } static int jc_type_file_seq_abort_comm_destroy( struct jc_type_file_comm_node *fcn ) { } static int jc_type_file_seq_abort_comm_var_destroy( struct jc_type_file_comm_var_node *cvar ) { } int json_type_file_seq_abort_uninit() { struct jc_type_file_manage_oper oper; struct jc_type_file_comm_hash_oper comm_oper; memset(&comm_oper, 0, sizeof(comm_oper)); comm_oper.comm_hash_execute = jc_type_file_seq_abort_comm_execute; comm_oper.comm_hash_init = jc_type_file_seq_abort_comm_init; comm_oper.comm_hash_copy = jc_type_file_seq_abort_comm_copy; comm_oper.comm_node_destroy = jc_type_file_seq_abort_comm_destroy; comm_oper.comm_var_node_destroy = jc_type_file_seq_abort_comm_var_destroy; global_abort.comm_hash = jc_type_file_comm_create(0, 0, &comm_oper); if (!global_abort.comm_hash) return JC_ERR; memset(&oper, 0, sizeof(oper)); oper.manage_init = jc_type_file_seq_abort_init; oper.manage_copy = jc_type_file_seq_abort_copy; oper.manage_execute = jc_type_file_seq_abort_execute; return jc_type_file_seq_module_add("sequence_in_a_abort", &oper); } int json_type_file_seq_abort_init() { if (global_abort.comm_hash) return jc_type_file_comm_destroy(global_abort.comm_hash); return JC_OK; }
0