text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> { int f_count; pthread_mutex_t f_lock; int f_id; }foo; foo *foo_alloc(int id) { foo *fp = 0; if ((fp = (foo *)malloc(sizeof(foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } } return fp; } void foo_hold(foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count--; if (fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> enum val_ty { INT, UINT, FLOAT, BOOL }; int buf[256]; long size; long n; pthread_mutex_t m; pthread_cond_t c; } stream_t; stream_t* in; stream_t* out; kernel_t c; } arg_t; int pop(stream_t* s) { pthread_mutex_lock(&(s->m)); while (s->n == -1) { pthread_cond_wait(&(s->c), &(s->m)); } int val; if (s->n == s->size) { val = s->buf[s->n--]; pthread_cond_signal(&(s->c)); } else { val = s->buf[s->n--]; } pthread_mutex_unlock(&(s->m)); return val; } void push(stream_t* s, int val) { pthread_mutex_lock(&(s->m)); while (s->n == s->size) { pthread_cond_wait(&(s->c), &(s->m)); } if (s->n == -1) { s->n++; s->buf[s->n++] = val; pthread_cond_signal(&(s->c)); } else { s->buf[s->n++] = val; } pthread_mutex_unlock(&(s->m)); } void source(stream_t* in, stream_t* out) { for (int i=0; i < 10; i++) { printf("[Source] %d\\n", i); push(out, i); } } void sink(stream_t* in, stream_t* out) { while(1) { int val = pop(in); printf("[Sink] %d\\n", val); } } void map(stream_t* in, stream_t* out) { for (int i=0; i < 10; i++) { int val = pop(in); printf("[Map] %d\\n", val); val += val+1; push(out, val); } } void* runnable(void* arg) { arg_t* args = (arg_t*) arg; kernel_t c = (kernel_t) args->c; c(args->in, args->out); return 0; } pthread_t* spawn_kernel(kernel_t c, stream_t* in, stream_t* out) { pthread_t* thr = (pthread_t*)malloc(sizeof(pthread_t)); arg_t* args = (arg_t*) malloc(sizeof(arg_t)); args->in = in; args->out = out; args->c = c; int rc = pthread_create(thr, 0, runnable, (void *) args); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(-1); } return thr; } stream_t* init_stream() { stream_t* s = (stream_t*)calloc(1, sizeof(stream_t)); pthread_mutex_init(&(s->m), 0); pthread_cond_init (&(s->c), 0); return s; } int main() { stream_t* sin = 0; stream_t* sout = init_stream(); pthread_t* t0 = spawn_kernel(source, sin, sout); sin = sout; sout = init_stream(); pthread_t* t1 = spawn_kernel(map, sin, sout); sin = sout; sout = 0; pthread_t* t2 = spawn_kernel(sink, sin, sout); pthread_join(*t0, 0); pthread_join(*t1, 0); pthread_join(*t2, 0); }
0
#include <pthread.h> int estado [(5)]; pthread_mutex_t mutex; pthread_mutex_t mux_filo [(5)]; pthread_t jantar[(5)]; void * filosofo ( void * param ); void pegar_hashi ( int id_filosofo ); void devolver_hashi ( int id_filosofo ); void intencao ( int id_filosofo ); void comer ( int id_filosofo ); void pensar ( int id_filosofo ); void * filosofo ( void * vparam ) { int * id = (int *) (vparam); printf("Filosofo %d foi criado com sucesso\\n", *(id) ); while ( 1 ) { pensar( *(id) ); pegar_hashi( *(id) ); comer( *(id) ); devolver_hashi( *(id) ); } pthread_exit( (void*) 0 ); } void pegar_hashi ( int id_filosofo ) { pthread_mutex_lock( &(mutex) ); printf("Filosofo %d esta faminto\\n", id_filosofo); estado[ id_filosofo ] = (1); intencao( id_filosofo ); pthread_mutex_unlock( &(mutex) ); pthread_mutex_lock( &(mux_filo[id_filosofo]) ); } void devolver_hashi ( int id_filosofo ) { pthread_mutex_lock ( &(mutex) ); printf("Filosofo %d esta pensando\\n", id_filosofo); estado[ id_filosofo ] = (0); intencao( (id_filosofo + (5) - 1) % (5) ); intencao( (id_filosofo + 1) % (5) ); pthread_mutex_unlock ( &(mutex) ); } void intencao ( int id_filosofo ) { printf("Filosofo %d esta com intencao de comer\\n", id_filosofo); if( (estado[id_filosofo] == (1)) && (estado[(id_filosofo + (5) - 1) % (5)] != (2)) && (estado[(id_filosofo + 1) % (5)] != (2) ) ) { printf("Filosofo %d ganhou a vez de comer\\n", id_filosofo); estado[ id_filosofo ] = (2); pthread_mutex_unlock( &(mux_filo[id_filosofo]) ); } } void pensar ( int id_filosofo ) { int r = (rand() % 10 + 1); printf("Filosofo %d pensa por %d segundos\\n", id_filosofo, r ); sleep( r ); } void comer ( int id_filosofo ) { int r = (rand() % 10 + 1); printf("Filosofo %d come por %d segundos\\n", id_filosofo, r); sleep( r ); } int main ( void ) { int cont; int status; pthread_mutex_init( &(mutex), 0); for( cont = 0 ; cont < (5) ; cont++ ) { pthread_mutex_init( &(mux_filo[cont]), 0 ); } for( cont = 0 ; cont < (5) ; cont++ ) { status = pthread_create( &(jantar[cont]), 0, filosofo, (void *) &(cont) ); if ( status ) { printf("Erro criando thread %d, retornou codigo %d\\n", cont, status ); return 1; } } pthread_mutex_destroy( &(mutex) ); for( cont = 0 ; cont < (5) ; cont++ ) { pthread_mutex_destroy( &(mux_filo[cont]) ); } pthread_exit( 0 ); return 0; }
1
#include <pthread.h> struct pending_events { struct trace_event **pending; int nr_pending; int nr_alloc; pthread_mutex_t mutex; pthread_cond_t cond; }; struct pending_events pending; static int finished = 0; static pthread_t sort_thread; static int max_pending_events = 1024; static int compare_events(const void *a, const void *b) { struct trace_event * const *A = a; struct trace_event * const *B = b; if ((*A)->ts > (*B)->ts) return 1; else if ((*A)->ts < (*B)->ts) return -1; return 0; } static void process_pending(void) { int i; qsort(pending.pending, pending.nr_pending, sizeof(*pending.pending), compare_events); for (i = 0; i < pending.nr_pending; i++) { struct trace_event *cur_pending = pending.pending[i]; int ret = cur_pending->process(cur_pending); if (ret > 1) { cur_pending->missed_count++; if (cur_pending->missed_count > 5) { cur_pending->free(cur_pending); continue; } memmove(pending.pending, pending.pending + i, sizeof(void *) * (pending.nr_pending - i)); if (cur_pending != pending.pending[0]) printf("WE FUCKED UP\\n"); break; } } pending.nr_pending -= i; } static void *thread_fn(void *unused) { while (!finished) { pthread_mutex_lock(&pending.mutex); while (pending.nr_pending < max_pending_events && !finished) pthread_cond_wait(&pending.cond, &pending.mutex); if (finished) { pthread_mutex_unlock(&pending.mutex); break; } process_pending(); pthread_mutex_unlock(&pending.mutex); } return 0; } int trace_event_add_pending(struct trace_event *event) { pthread_mutex_lock(&pending.mutex); if (pending.nr_pending == pending.nr_alloc) { pending.nr_alloc += 1024; pending.pending = realloc(pending.pending, pending.nr_alloc * sizeof(struct trace_event *)); if (!pending.pending) { pthread_mutex_unlock(&pending.mutex); return -1; } } pending.pending[pending.nr_pending++] = event; if (pending.nr_pending >= max_pending_events) pthread_cond_signal(&pending.cond); pthread_mutex_unlock(&pending.mutex); return 0; } void trace_event_process_pending(void) { pthread_mutex_lock(&pending.mutex); process_pending(); pthread_mutex_unlock(&pending.mutex); } void trace_event_drop_pending(void) { int i = 0; pthread_mutex_lock(&pending.mutex); for (i = 0; i < pending.nr_pending; i++) pending.pending[i]->free(pending.pending[i]); pending.nr_pending = 0; pthread_mutex_unlock(&pending.mutex); } void trace_event_sorter_cleanup(void) { pthread_mutex_lock(&pending.mutex); finished = 1; pthread_cond_signal(&pending.cond); pthread_mutex_unlock(&pending.mutex); pthread_join(sort_thread, 0); pthread_mutex_destroy(&pending.mutex); pthread_cond_destroy(&pending.cond); } int trace_event_sorter_init(void) { if (pthread_mutex_init(&pending.mutex, 0) || pthread_cond_init(&pending.cond, 0)) return -1; pending.pending = malloc(sizeof(void *) * 1024); if (!pending.pending) return -1; memset(pending.pending, 0, sizeof(void *) * 1024); pending.nr_alloc = 1024; pending.nr_pending = 0; if (pthread_create(&sort_thread, 0, thread_fn, 0)) { free(pending.pending); pthread_mutex_destroy(&pending.mutex); pthread_cond_destroy(&pending.cond); return -1; } return 0; }
0
#include <pthread.h> const int run_times = 50000; int testsize[7]={8,8,64,512,1024,2048,4096}; int test_MB_size; int write_mode = 0; int thread_node; int thread_send_num=1; int thread_recv_num=1; pthread_mutex_t count_mutex; int count = 0; int go = 0; pthread_mutex_t end_count_mutex; int end_count = 0; void *thread_send_lat(void *tmp) { int ret; int remote_node = thread_node; int port = *(int *)tmp; char *read = memalign(sysconf(_SC_PAGESIZE),4096*2); char *write = memalign(sysconf(_SC_PAGESIZE),4096*2); int ret_length; int i,j; struct timespec start, end; double total_lat; double *record=calloc(run_times, sizeof(double)); memset(write, 0x36, 4096); memset(read, 0, 4096); mlock(read, 4096); mlock(write, 4096); mlock(&ret_length, sizeof(int)); for(j=0;j<7;j++) { memset(read, 0, 4096); pthread_mutex_lock(&count_mutex); count++; pthread_mutex_unlock(&count_mutex); while(count<(thread_send_num+1)*(j+1)); for(i=0;i<run_times;i++) { ret = userspace_liteapi_send_reply_imm_fast(remote_node, port, write, 8, read, &ret_length, 4096); } printf("finish send %d\\n", testsize[j]); pthread_mutex_lock(&end_count_mutex); end_count++; pthread_mutex_unlock(&end_count_mutex); } return 0; } void *thread_recv(void *tmp) { int port = *(int *)tmp; uintptr_t descriptor, ret_descriptor; int i,j,k; char *read = memalign(sysconf(_SC_PAGESIZE),4096); char *write = memalign(sysconf(_SC_PAGESIZE),4096); int ret_length; int ret; int recv_num = thread_send_num/thread_recv_num; mlock(write, 4096); mlock(read, 4096); mlock(&descriptor, sizeof(uintptr_t)); mlock(&ret_length, sizeof(int)); memset(write, 0x36, 4096); memset(read, 0, 4096); for(j=0;j<7;j++) { memset(read, 0, 4096); for(i=0;i<run_times*recv_num;i++) { ret = userspace_liteapi_receive_message_fast(port, read, 4096, &descriptor, &ret_length, BLOCK_CALL); userspace_liteapi_reply_message(write, testsize[j], descriptor); } printf("finish recv %d\\n", testsize[j]); } } int init_log(int remote_node) { uint64_t xact_ID; int j, k; int *random_idx; struct timespec start, end; int temp[32]; char *read = memalign(sysconf(_SC_PAGESIZE),4096); char *write = memalign(sysconf(_SC_PAGESIZE),4096); memset(write, 0x36, 4096); memset(read, 0, 4096); if(remote_node == 0) { pthread_t threads[64]; char *name = malloc(16); int ret; sprintf(name, "test.1"); ret = userspace_liteapi_register_application(1, 4096, 16, name, strlen(name)); printf("finish registeration ret-%d\\n", ret); userspace_liteapi_dist_barrier(2); temp[0]=1; pthread_create(&threads[0], 0, thread_recv, &temp[0]); pthread_join(threads[0], 0); } else { struct timespec start, end; double total_lat[7]; pthread_t threads[64]; thread_node = remote_node; userspace_liteapi_dist_barrier(2); userspace_liteapi_query_port(remote_node,1); temp[0] = 1; pthread_create(&threads[0], 0, thread_send_lat, &temp[0]); for(j=0;j<7;j++) { pthread_mutex_lock(&count_mutex); count++; pthread_mutex_unlock(&count_mutex); } pthread_join(threads[0], 0); } return 0; } int internal_value=0; int main(int argc, char *argv[]) { if(argc!=2) { printf("./example_userspace_sr.o REMOTE_NODE\\n"); return 0; } init_log(atoi(argv[1])); return ; }
1
#include <pthread.h> struct Task; int integer; void* ptr; } TaskData; TaskData data; time_t addedTime; time_t deadline; int isRunning; void (*runnable) (TaskData); struct Task* next; struct Task* prev; } Task; int workerCount; pthread_t workers[30]; pthread_mutex_t popMutex; pthread_mutex_t pushMutex; Task* chainHead; pthread_t scheduler; pthread_cond_t emptyCond; } ThreadPool; Task* popTaskWait(ThreadPool* pool) { pthread_mutex_lock(&pool->popMutex); if(pool->chainHead == 0) { pthread_cond_wait(&pool->emptyCond, &pool->popMutex); } assert(pool->chainHead != 0); pthread_mutex_lock(&pool->pushMutex); Task* task = pool->chainHead; if(task->next == 0) { pool->chainHead = 0; } else { pool->chainHead = task->next; } task->next = 0; task->prev = 0; pthread_mutex_unlock(&pool->pushMutex); pthread_mutex_unlock(&pool->popMutex); return task; } void* singlerun(void* voidTask) { Task* task = (Task*) voidTask; task->isRunning = 1; task->runnable(task->data); } void* scheduler(void* voidPool) { ThreadPool* pool = (ThreadPool*) voidPool; int i; while(1) { time_t now = time(0); pthread_mutex_lock(&pool->pushMutex); pthread_mutex_lock(&pool->popMutex); Task* tmp = pool->chainHead; while(tmp != 0) { if(!tmp->isRunning && tmp->deadline != -1) { time_t delta = now - tmp->addedTime; if(delta >= tmp->deadline) { printf("Running task after exceeding a %d of %d seconds deadline. \\n", delta, tmp->deadline); if(tmp == pool->chainHead) { pool->chainHead = tmp->next; if(tmp->next != 0) { pool->chainHead->prev = 0; } } else { Task* parent = tmp->prev; Task* child = tmp->next; parent->next = child; if(child != 0) { child->prev = parent; } } pthread_t id; pthread_create(&id, 0, singlerun, (void*)tmp); } } tmp = tmp->next; } pthread_mutex_unlock(&pool->pushMutex); pthread_mutex_unlock(&pool->popMutex); usleep(1000000); } assert(0 == 1); } void* worker(void* voidPool) { ThreadPool* pool = (ThreadPool*) voidPool; while(1) { singlerun((void*) popTaskWait(pool)); } assert(0 == 1); } void addTask(ThreadPool* pool, Task* task) { task->next = 0; task->prev = 0; task->isRunning = 0; task->addedTime = time(0); pthread_mutex_lock(&pool->pushMutex); if(pool->chainHead == 0) { pool->chainHead = task; } else { Task* tmp = pool->chainHead; while(tmp->next != 0) { tmp = tmp->next; } tmp->next = task; task->prev = tmp; } pthread_cond_signal(&pool->emptyCond); pthread_mutex_unlock(&pool->pushMutex); } ThreadPool* createPool(const int numWorkers) { int i; ThreadPool* pool = malloc(sizeof(ThreadPool)); pool->workerCount = 0; pool->scheduler = 0; pool->chainHead = 0; pthread_mutex_init(&pool->popMutex, 0); pthread_mutex_init(&pool->pushMutex, 0); pthread_cond_init(&pool->emptyCond, 0); pthread_create(&pool->scheduler, 0, &scheduler, (void*)pool); for(i = 0; i < numWorkers; ++i) { pthread_create(&pool->workers[pool->workerCount++], 0, &worker, (void*)pool); } printf("Created a threadpool with %i workers. \\n", numWorkers); return pool; } void joinThreadPool(ThreadPool* pool) { int i; for(i = 0; i < pool->workerCount; ++i) { pthread_join(pool->workers[i], 0); } } void starve(TaskData data) { printf("Starting really long task. \\n"); sleep(10); printf("Finished really long task. \\n"); } void echoTest(TaskData data) { printf("Running a really quick task... \\n"); } int main(int argc, char** argv) { int i; ThreadPool* pool = createPool(5); Task task2[10]; for(i = 0; i < 10; ++i) { task2[i].deadline = -1; task2[i].runnable = &starve; addTask(pool, &task2[i]); } Task task[2]; for(i = 0; i < 2; ++i) { task[i].deadline = 4; task[i].runnable = &echoTest; addTask(pool, &task[i]); } joinThreadPool(pool); free(pool); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t full, empty; buffer_item buffer[5]; int counter; pthread_t tid; pthread_attr_t attr; void *producer(void *param); void *consumer(void *param); void initializeData() { pthread_mutex_init(&mutex, 0); sem_init(&full, 0, 0); sem_init(&empty, 0, 5); pthread_attr_init(&attr); counter = 0; } void *producer(void *param) { buffer_item item; while(1) { int rNum = rand() / 100000000; sleep(rNum); item = rand(); sem_wait(&empty); pthread_mutex_lock(&mutex); if(insert_item(item)) { fprintf(stderr, " Producer report error condition\\n"); } else { printf("producer produced %d\\n", item); } pthread_mutex_unlock(&mutex); sem_post(&full); } } void *consumer(void *param) { buffer_item item; while(1) { int rNum = rand() / 100000000; sleep(rNum); sem_wait(&full); pthread_mutex_lock(&mutex); if(remove_item(&item)) { fprintf(stderr, "Consumer report error condition\\n"); } else { printf("consumer consumed %d\\n", item); } pthread_mutex_unlock(&mutex); sem_post(&empty); } } int insert_item(buffer_item item) { if(counter < 5) { buffer[counter] = item; counter++; return 0; } else { return -1; } } int remove_item(buffer_item *item) { if(counter > 0) { *item = buffer[(counter-1)]; counter--; return 0; } else { return -1; } } int main(int argc, char *argv[]) { int i; if(argc != 4) { fprintf(stderr, "USAGE:./main.out <INT> <INT> <INT>\\n"); } int mainSleepTime = atoi(argv[1]); int numProd = atoi(argv[2]); int numCons = atoi(argv[3]); initializeData(); for(i = 0; i < numProd; i++) { pthread_create(&tid,&attr,producer,0); } for(i = 0; i < numCons; i++) { pthread_create(&tid,&attr,consumer,0); } sleep(mainSleepTime); printf("Exit the program\\n"); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condizione =PTHREAD_COND_INITIALIZER; int **m1=0; int **m2=0; int **m3=0; int riga; int riga2; int colonna; int colonna2; int numThread =0; void stampa(int**m,int riga,int colonna){ for (int i = 0; i < riga; ++i) { for(int j=0;j<colonna;j++){ printf("%d \\t",m[i][j] ); } printf("\\n"); } } void *funzione(void *param){ int i = *(int*)param; for (int j = 0; j < colonna2; j++) { for (int k=0;k<colonna;k++){ usleep(500); pthread_mutex_lock(&mutex); m3[i][j]=m3[i][j]+(m1[i][k]*m2[k][j]); numThread--; pthread_mutex_unlock(&mutex); } } pthread_mutex_lock(&mutex); if (numThread<=0) { pthread_cond_signal(&condizione); } pthread_mutex_unlock(&mutex); pthread_exit(0); } void *funzione2(void *param){ pthread_mutex_lock(&mutex); while(numThread>0){ pthread_cond_wait(&condizione,&mutex); } pthread_mutex_unlock(&mutex); stampa(m3,riga,colonna2); pthread_exit(0); } int main(int argc, char const *argv[]) { if (argc<3) { perror("Errore argomenti"); exit(1); } riga = atoi(argv[1]); colonna = atoi(argv[2]); riga2=atoi(argv[2]); colonna2 = atoi(argv[3]); numThread=riga; pthread_t thread[riga+1]; if (riga<riga2) { perror("Errore righe"); exit(1); } m1=(int**)malloc(sizeof(int*)*riga); for (int i = 0; i < riga;i++) { m1[i]=(int*)malloc(sizeof(int)*colonna); for (int j = 0; j < colonna; j++) { m1[i][j]=1+rand()%5; } } m2=(int**)malloc(sizeof(int*)*riga2); for (int i = 0; i < riga2;i++) { m2[i]=(int*)malloc(sizeof(int)*colonna2); for (int j = 0; j < colonna2; j++) { m2[i][j]=1+rand()%5; } } m3=(int**)malloc(sizeof(int*)*riga); for (int i = 0; i < riga;i++) { m3[i]=(int*)malloc(sizeof(int)*colonna2); for (int j = 0; j < colonna2;j++) { m3[i][j]=0; } } for (int i = 0; i < riga; i++) { int *indice=malloc(sizeof(int)); *indice=i; pthread_create(&thread[i],0,funzione,indice); } pthread_create(&thread[riga],0,funzione2,0); for (int i = 0; i <= riga; i++) { pthread_join(thread[i],0); } return 0; }
0
#include <pthread.h> int i = 0; pthread_mutex_t mutex; void* someThreadFunction1(){ int j; for (j = 0;j<1000000;j++) { pthread_mutex_lock(&mutex); i += 1; pthread_mutex_unlock(&mutex); } return 0; } void* someThreadFunction2(){ int k; for (k = 0;k<1000000;k++) { pthread_mutex_lock(&mutex); i -= 1; pthread_mutex_unlock(&mutex); } return 0; } int main(){ pthread_t someThread1; pthread_create(&someThread1, 0, &someThreadFunction1,0); pthread_t someThread2; pthread_create(&someThread2, 0, &someThreadFunction2, 0); pthread_join(someThread1, 0); pthread_join(someThread2, 0); pthread_mutex_destroy(&mutex); printf("%i\\n",i); return 0; }
1
#include <pthread.h> WAITTING, IDLE, ASSIGNED, BUSY } Thread_Status; { pthread_t tid; pthread_mutex_t mutex; pthread_cond_t cond; Thread_Status status; task_t task; void * arg; int cnt; }Thread_pool_t; void task(void * arg) { printf("I am 线程 %lu, task %d begin!\\n", pthread_self(), (int)arg); srand(pthread_self()); sleep(rand()%5 + 3); printf("task %d over!\\n", (int)arg); } static Thread_pool_t * create_pool(int num) { int i; Thread_pool_t *pools = (Thread_pool_t *)malloc(sizeof(Thread_pool_t)*num); if (!pools) { perror("malloc"); return 0; } for (i = 0; i < num; i++) { pthread_mutex_init(&pools[i].mutex, 0); pthread_cond_init(&pools[i].cond, 0); pools[i].status = WAITTING; pools[i].task = (task_t)(0); pools[i].arg = 0; pools[i].cnt = -1; } return pools; } static void set_worker_status(Thread_pool_t *worker, Thread_Status status) { worker->status = status; } static void * worker_job(void *arg) { Thread_pool_t *worker = (Thread_pool_t *)arg; pthread_mutex_t *pmutex = &worker->mutex; pthread_cond_t *pcond = &worker->cond; while (1) { pthread_mutex_lock(pmutex); if (++worker->cnt == -1) worker->cnt = 0; worker->task = (task_t)0; worker->arg = 0; set_worker_status(worker, IDLE); printf("QF:""thread %lu was ready!\\n", pthread_self()); pthread_cond_wait(pcond, pmutex); if (worker->task == (task_t)0) { pthread_mutex_unlock(pmutex); continue; } set_worker_status(worker, BUSY); pthread_mutex_unlock(pmutex); (worker->task)(worker->arg); } return 0; } static int create_threads(int num, Thread_pool_t *pools) { int i, ret; for (i = 0; i < num; i++) { ret = pthread_create(&pools[i].tid, 0, worker_job, (void *)(pools + i)); if (ret) { fprintf(stderr, "pthread_create:%s\\n", strerror(ret)); return ret; } } return ret; } static void wait_all_threads_ready(Thread_pool_t *pools, int num) { int i; for (i = 0; i < num; i++) { while (1) { pthread_mutex_lock(&pools[i].mutex); if (pools[i].status == IDLE) { pthread_mutex_unlock(&pools[i].mutex); break; } else { pthread_mutex_unlock(&pools[i].mutex); sched_yield(); } } } } Thread_pool_t * Threadpool_create_and_init(int num) { if (num <= 0) { fprintf(stderr, "Thread number invalied!\\n"); return 0; } Thread_pool_t *polls; int ret; polls = create_pool(num); if (polls == 0) return 0; ret = create_threads(num, polls); if (ret) return 0; wait_all_threads_ready(polls, num); return polls; } int threadPoll_assign_work(Thread_pool_t *pools, size_t poolnum, task_t task, void * arg) { if (!task || !pools || poolnum <= 0) { fprintf(stderr, "argument ivalied!\\n"); return -1; } int i, index = -1, cnt = -1; for (i = 0; i < poolnum; i++) { pthread_mutex_lock(&pools[i].mutex); if (pools[i].status == IDLE) { if (-1 == index) { index = i; cnt = pools[i].cnt; }else { if (cnt > pools[i].cnt) { index = i; cnt = pools[i].cnt; } } } pthread_mutex_unlock(&pools[i].mutex); } if (-1 == index) { fprintf(stderr, "All threads way busy!\\n"); return -1; }else { pthread_mutex_lock(&pools[index].mutex); pools[index].task = task; pools[index].arg = arg; set_worker_status(pools + index, ASSIGNED); pthread_cond_signal(&pools[index].cond); pthread_mutex_unlock(&pools[index].mutex); } return 0; } int main(void) { Thread_pool_t *pools; int i, ret, k; printf("请输入要创建的线程数量: "); fflush(stdout); scanf("%d", &k); pools = Threadpool_create_and_init(k); if (!pools) return -1; while (1) { printf("输入任务: "); fflush(stdout); scanf("%d", &i); ret = threadPoll_assign_work(pools, k, task, (void *)i); if (ret == -1) continue; } }
0
#include <pthread.h> pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; int buffer[1]; void * cons(void * arg) { int i = 3 * 10; while(i != 0) { pthread_mutex_lock(&mut); printf("buffer[0] = %d\\n", buffer[0]); pthread_mutex_unlock(&mut); i--; } pthread_exit(0); } void * prod(void * arg) { int i = 1 * 10; srand (time (0)); while(i != 0) { pthread_mutex_lock(&mut); buffer[0] = rand() % 100; pthread_mutex_unlock(&mut); i--; } pthread_exit(0); } int main(int argc, char * argv[]) { int i; pthread_t p[1]; pthread_t q[3]; for(i = 0 ; i < 1 ; i++) if(pthread_create(&p[i], 0, prod, 0) != 0) printf("Erreur\\n"); for(i = 0 ; i < 3 ; i++) if(pthread_create(&q[i], 0, cons, 0) != 0) printf("Erreur\\n"); for(i = 0; i < 1 ; i++) pthread_join(p[i], 0); for(i = 0; i < 3 ; i++) pthread_join(q[i], 0); return 0; }
1
#include <pthread.h> int hasPassed[4]; enum direction{ west, south, east, north } ; char * dirstr[4] = { "West", "South", "East", "North"}; struct thread_data{ int dir; int id; int order; }; struct thread_data * dataArray; pthread_cond_t queueConds[4]; pthread_cond_t firstConds[4]; pthread_mutex_t queueMutex[4]; int queueSize[4]; int isCarWaiting[4]; pthread_t * threads; pthread_attr_t attr; pthread_mutex_t printMutex; pthread_mutex_t passMutex; void print_msg(char * format, ...){ va_list list; __builtin_va_start((list)); pthread_mutex_lock(&printMutex); vprintf(format, list); pthread_mutex_unlock(&printMutex); ; return; } void debug_msg(int dir){ int i; print_msg("This is %s: ", dirstr[dir]); for( i=0; i<4; ++i){ print_msg("%s = %d, ", dirstr[i], queueSize[i]); } puts(""); } int check_deadlock(){ int i; for( i=0; i<4; ++i){ if( !isCarWaiting[i] ) return 0; } return 1; } void * queue_thread(void * data) { int dir = ((struct thread_data *)data)->dir; int id = ((struct thread_data *)data)->id; int order = ((struct thread_data *)data)->order; (&queueMutex[dir]); queueSize[dir]++; if ( hasPassed[dir] < order ) { pthread_cond_wait(&queueConds[dir], &queueMutex[dir]); } sleep(1); print_msg("car %d from %s arrives at crossing\\n", id, dirstr[dir]); pthread_mutex_unlock(&queueMutex[dir]); pthread_mutex_lock(&passMutex); if( queueSize[ (dir+1)%4 ] > 0 ){ isCarWaiting[dir] = 1; if( check_deadlock() ){ print_msg("DEADLOCK: car jam detected, signalling %s to go\\n", dirstr[dir]); }else{ pthread_cond_wait(&firstConds[dir], &passMutex); } isCarWaiting[dir] = 0; } sleep(1); print_msg("car %d from %s leaving crossing\\n", id, dirstr[dir]); pthread_cond_signal(&firstConds[ (dir+3)%4 ]); pthread_mutex_unlock(&passMutex); pthread_mutex_lock(&queueMutex[dir]); queueSize[dir]--; hasPassed[dir]++; pthread_cond_signal(&queueConds[dir]); pthread_mutex_unlock(&queueMutex[dir]); pthread_exit(0); } void init() { int i; for( i=0; i<4; ++i ){ pthread_cond_init(&queueConds[i], 0); pthread_cond_init(&firstConds[i], 0); pthread_mutex_init(&queueMutex[i], 0); queueSize[i] = 0; } pthread_mutex_init(&passMutex, 0); pthread_mutex_init(&printMutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); } void quit() { int i; pthread_attr_destroy(&attr); for( i=0; i<4; ++i ){ pthread_cond_destroy(&queueConds[i]); pthread_cond_destroy(&firstConds[i]); pthread_mutex_destroy(&queueMutex[i]); } pthread_mutex_destroy(&passMutex); pthread_mutex_destroy(&printMutex); } int main(int argc, char *argv[]) { int i, j, carnum; char * arg; int tmp[4] = {}; if( argc < 2 ){ puts("please specify the car sequence."); puts("e.g., ./os_exp1-1 nsewwewn"); exit(0); } arg = argv[1]; carnum = strlen(arg); threads = (pthread_t *)malloc(sizeof(pthread_t) * carnum); dataArray = (struct thread_data *)malloc(sizeof(struct thread_data) * carnum); init(); for( i=0; i < carnum; ++i){ switch( arg[i] ){ case 'w': j = west; break; case 'e': j = east; break; case 's': j = south; break; case 'n': j = north; break; default:printf("unknown direction: %d\\n", arg[i]); exit(0); } dataArray[i].dir = j; dataArray[i].id = i+1; dataArray[i].order = tmp[j]++; pthread_create(&threads[i], &attr, queue_thread, (void *)&dataArray[i]); } for( i=0; i<carnum; ++i){ pthread_join(threads[i], 0); } quit(); free(threads); free(dataArray); pthread_exit(0); }
0
#include <pthread.h> int completed=0; pthread_mutex_t completed_mutex; pthread_cond_t cv; void * wait_thread (void *data) { pthread_mutex_lock (&completed_mutex); while(completed==0) { printf("Conditional variable not set\\n"); pthread_cond_wait(&cv, &completed_mutex); } pthread_mutex_unlock (&completed_mutex); printf("got completed=1\\n"); } void * update_thread (void *data) { pthread_mutex_lock (&completed_mutex); printf("got mutex\\n"); completed=1; printf("update completed\\n"); printf("Relese Mutex\\n"); pthread_mutex_unlock (&completed_mutex); pthread_cond_signal(&cv); } int main(int argc, char const *argv[]) { pthread_t wait_tid, update_tid; pthread_mutex_init (&completed_mutex, 0); pthread_cond_init(&cv, 0); pthread_create(&wait_tid, 0, wait_thread, 0); pthread_create(&update_tid, 0, update_thread, 0); pthread_join(wait_tid, 0); pthread_join(update_tid, 0); pthread_mutex_destroy (&completed_mutex); pthread_cond_destroy(&cv); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thread_1(void *arg) { pthread_mutex_lock(&mutex); DPRINTF(stdout,"Thread 1 locked the mutex \\n"); pthread_exit(0); return 0; } void *thread_2(void *arg) { int state; int rc; pthread_t self = pthread_self(); int policy = SCHED_FIFO; struct sched_param param; memset(&param, 0, sizeof(param)); param.sched_priority = sched_get_priority_min(policy); rc = pthread_setschedparam(self, policy, &param); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_setschedparam %d %s", rc, strerror(rc)); exit(UNRESOLVED); } rc = pthread_mutex_lock(&mutex); if (rc != EOWNERDEAD) { EPRINTF("FAIL:pthread_mutex_lock didn't return EOWNERDEAD \\n"); exit(FAIL); } DPRINTF(stdout,"Thread 2 lock the mutex and return EOWNERDEAD \\n"); state = 1; if (pthread_mutex_setconsistency_np(&mutex, state) == 0) { pthread_mutex_unlock(&mutex); rc = pthread_mutex_lock(&mutex); if (rc != ENOTRECOVERABLE) { EPRINTF("FAIL:The mutex does not set to " "ENOTRECOVERABLE when called " "pthread_mutex_setconsistency_np successfully " "in x-mode"); pthread_mutex_unlock(&mutex); exit(FAIL); } else { DPRINTF(stdout,"PASS: The mutex is set to ENOTRECOVERABLE if " "successfully called " "pthreadmutex_setconsistency_np in x-mode\\n"); pthread_mutex_unlock(&mutex); } } else { pthread_mutex_unlock(&mutex); rc = pthread_mutex_lock(&mutex); if (rc != EOWNERDEAD) { EPRINTF("FAIL:The mutex shall not set to " "ENOTRECOVERABLE automaticly after unlock " "if can't recover it to normal state in x-mode"); pthread_mutex_unlock(&mutex); exit(FAIL); } else { DPRINTF(stdout,"PASS: The mutex remains in " "EOWNERDEAD state if the calling to " "pthread_mutex_consistency_np fails " "(Why fails?) in x-mode \\n"); pthread_mutex_unlock(&mutex); } } pthread_exit(0); return 0; } int main() { pthread_mutexattr_t attr; pthread_t threads[2]; pthread_attr_t threadattr; int rc; rc = pthread_mutexattr_init(&attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutexattr_setrobust_np(&attr, PTHREAD_MUTEX_ROBUST_NP); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutexattr_setrobust_np %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_mutex_init(&mutex, &attr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_mutex_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_attr_init(&threadattr); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_attr_init %d %s", rc, strerror(rc)); return UNRESOLVED; } rc = pthread_create(&threads[0], &threadattr, thread_1, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[0], 0); DPRINTF(stdout,"Thread 1 exit without unlock the mutex...\\n "); rc = pthread_create(&threads[1], &threadattr, thread_2, 0); if (rc != 0) { EPRINTF("UNRESOLVED: pthread_create %d %s", rc, strerror(rc)); return UNRESOLVED; } pthread_join(threads[1], 0 ); DPRINTF(stdout,"Thread 2 exit ...\\n "); DPRINTF(stdout,"PASS: Test PASSED\\n"); return PASS; }
0
#include <pthread.h> static pthread_key_t strerror_buf_key; static pthread_once_t strerror_buf_key_once = PTHREAD_ONCE_INIT; static void create_strerror_buf_key() { pthread_key_create(&strerror_buf_key, free); } static inline char *get_strerror_buf() { char *buf; pthread_once(&strerror_buf_key_once, create_strerror_buf_key); buf = pthread_getspecific(strerror_buf_key); if (!buf) { buf = malloc(256); pthread_setspecific(strerror_buf_key, buf); } return buf; } const char *strerror_safe(int errnum) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char *buf = get_strerror_buf(); pthread_mutex_lock(&mutex); strncpy(buf, strerror(errnum), 256); pthread_mutex_unlock(&mutex); buf[256 - 1] = '\\0'; return buf; }
1
#include <pthread.h> pthread_mutex_t g_mutex; int g_nflag1, g_nflag2; static pthread_cond_t g_cond1 = PTHREAD_COND_INITIALIZER; static pthread_cond_t g_cond2 = PTHREAD_COND_INITIALIZER; void suspend(int n) { pthread_mutex_lock(&g_mutex); switch (n) { case 1: g_nflag1--; break; case 2: g_nflag2--; break; default: break; } pthread_mutex_unlock(&g_mutex); } void resume(int n) { pthread_mutex_lock(&g_mutex); switch (n) { case 1: g_nflag1++; pthread_cond_signal(&g_cond1); break; case 2: g_nflag2++; pthread_cond_signal(&g_cond2); break; default: break; } pthread_mutex_unlock(&g_mutex); } void *thr_fn1(void *arg) { for (int i = 0; i< 10; i++) { sleep(1); pthread_mutex_lock(&g_mutex); while (g_nflag1 <= 0) { pthread_cond_wait(&g_cond1, &g_mutex); } pthread_mutex_unlock(&g_mutex); printf("Thread_ID: %u , i = %d\\n", (unsigned int)pthread_self(), i); } } void *thr_fn2(void *arg) { for (int i = 0; i < 10; i++) { sleep(1); pthread_mutex_lock(&g_mutex); while (g_nflag2 <= 0) { pthread_cond_wait(&g_cond2, &g_mutex); } pthread_mutex_unlock(&g_mutex); printf("Thread_ID: %u, i = %d\\n", (unsigned int)pthread_self(), i); } } int main(void) { pthread_mutex_init(&g_mutex, 0); g_nflag1 = 1; g_nflag2 = 1; pthread_t tid1,tid2; pthread_setconcurrency(3); pthread_create(&tid1, 0, &thr_fn1, 0); pthread_create(&tid2, 0, &thr_fn2, 0); sleep(2.1); suspend(2); sleep(5.1); resume(2); suspend(1); pthread_cancel(tid1); pthread_join(tid1, 0); pthread_join(tid2, 0); return 1; }
0
#include <pthread.h> struct fumador { int id; pthread_mutex_t fumando; }; pthread_mutex_t tabaco; pthread_mutex_t papel; pthread_mutex_t fosforos; fumador_t * f; void* fumar(void*); void* agente(void*); int main ( int argc, char *argv[] ){ f = (fumador_t*) malloc (3 * sizeof(fumador_t)); int i; for (i = 0; i < 3; ++i){ (f+i)->id = i; pthread_mutex_init(&(f+i)->fumando, 0); } pthread_mutex_init(&tabaco, 0); pthread_mutex_init(&papel, 0); pthread_mutex_init(&fosforos, 0); pthread_mutex_trylock(&tabaco); pthread_mutex_trylock(&papel); pthread_mutex_trylock(&fosforos); pthread_t * fumadores = (pthread_t*) malloc (3 * sizeof (pthread_t)); pthread_t ag; pthread_create(&ag, 0, &agente, 0); for (i = 0; i < 3; ++i){ pthread_create(fumadores+i, 0, &fumar, (void*)(f+i)); } pthread_join(*fumadores, 0); free(fumadores); return 0; } void* fumar(void * arg){ fumador_t * fu = (fumador_t*) arg; while(1){ pthread_mutex_lock(&tabaco); pthread_mutex_lock(&papel); pthread_mutex_lock(&fosforos); pthread_mutex_lock(&(fu->fumando)); printf("Fuamdor %d esta fumando.\\n", fu->id); sleep(10); printf("Fumador %d acabo de fumar.\\n", fu->id); pthread_mutex_unlock(&(fu->fumando)); sleep(20); } } void *agente(void* arg){ while(1){ int status; status = pthread_mutex_trylock(&(f->fumando)); if (status == 0){ pthread_mutex_unlock(&(f->fumando)); pthread_mutex_unlock(&tabaco); } status = pthread_mutex_trylock(&((f+1)->fumando)); if (status == 0){ pthread_mutex_unlock(&((f+1)->fumando)); pthread_mutex_unlock(&papel); } status = pthread_mutex_trylock(&((f+2)->fumando)); if (status == 0){ pthread_mutex_unlock(&((f+2)->fumando)); pthread_mutex_unlock(&fosforos); } sleep(15); } }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_threshold_cv = PTHREAD_COND_INITIALIZER; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); if (count < 12) { printf("watch_count(): thread %ld going into wait...\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_create(&threads[0],0, watch_count, (void *)t1); pthread_create(&threads[1],0, inc_count, (void *)t2); pthread_create(&threads[2],0, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> static void ThrObjExec(void *pArg) { struct ThrObj *pObj = pArg; while(1){ pthread_mutex_lock(&pObj->thr_mutex); pObj->thr_status = THR_STATE_FREE; printf("%s | Take a snap waiting for condtion !\\n", __func__); pthread_cond_wait(&pObj->thr_cond, &pObj->thr_mutex); pObj->thr_tsk(pObj->thr_arg); pthread_mutex_unlock(&pObj->thr_mutex); } } static int ThrObjInit(struct ThrObj *pObj, pthread_attr_t *pAttr) { int ret = 0; pthread_mutex_init(&pObj->thr_mutex, 0); pthread_cond_init(&pObj->thr_cond, 0); pObj->thr_status = THR_STATE_FREE; pObj->thr_tsk = 0; pObj->thr_arg = 0; if((ret = pthread_create(&pObj->thr_id, pAttr, (void *)ThrObjExec, (void *)pObj)) < 0){ printf("%s | Create thread Obj failed!\\n", __func__); pObj->thr_status = THR_STATE_FAIL; return -1; }else{ pthread_detach(pObj->thr_id); } return 0; } int ThrPoolHandleInit(struct ThrPoolHandle *pHdl) { struct ThrObj *pObj = 0; int i = 0; int ret = 0; pthread_attr_t attr; struct sched_param schedParam; if(pHdl == 0){ printf("Wrong arg !\\n"); return -1; } if(pHdl->thr_nums > MAX_THR_POOL_OBJS){ printf("%s | Wrong thread numbers !\\n", __func__); return -1; } if(pHdl->thr_nums <= 0){ pHdl->thr_nums = 1; } pHdl->pthr_arr = (struct ThrObj *)malloc(pHdl->thr_nums * sizeof(struct ThrObj)); pthread_attr_init(&attr); if(pHdl->thr_stkSize > 16*1024){ if((ret = pthread_attr_setstacksize(&attr, pHdl->thr_stkSize)) < 0){ printf("%s | Set thread stack size failed!\\n", __func__); return -1; } } if(pthread_attr_setschedpolicy(&attr, SCHED_RR) < 0){ printf("%s | Set thread policy failed!%d\\n", __func__, ret); return -1; } schedParam.sched_priority = pHdl->thr_stkPri <= 0 ? 98 : pHdl->thr_stkPri; if((ret = pthread_attr_setschedparam(&attr, &schedParam)) != 0){ printf("%s | Set thread priority failed!%d\\n", __func__, ret); return -1; } for(i = 0; i < pHdl->thr_nums; i++){ pObj = &pHdl->pthr_arr[i]; ThrObjInit(pObj, &attr); } return 0; } int ThrPoolHandleDeInit(struct ThrPoolHandle *pHdl) { int i = 0; struct ThrObj *pObj = 0; for(i = 0; i < pHdl->thr_nums; i++){ pObj = &pHdl->pthr_arr[i]; pthread_cancel(pObj->thr_id); pthread_mutex_destroy(&pObj->thr_mutex); pthread_cond_destroy(&pObj->thr_cond); } pHdl->thr_nums = 0; pHdl->thr_stkPri = 0; pHdl->thr_stkSize = 0; free(pHdl->pthr_arr); printf("%s | Thr Pool Deinit !\\n", __func__); return 0; } int ThrPoolObjWake(struct ThrPoolHandle *pHdl, int index, void *Tsk, void *Arg) { struct ThrObj *pObj; if(pHdl->thr_nums <= index || index < 0){ printf("%s | Wrong args !\\n", __func__); return -1; } pObj = &pHdl->pthr_arr[index]; pthread_mutex_lock(&pObj->thr_mutex); pObj->thr_tsk = Tsk; pObj->thr_arg = Arg; pObj->thr_status = THR_STATE_BUSY; pthread_mutex_unlock(&pObj->thr_mutex); pthread_cond_signal(&pObj->thr_cond); return 0; } int ThrPoolSched(struct ThrPoolHandle *pHdl) { int i = 0; struct ThrObj *pObj; for(i = 0; i < pHdl->thr_nums; i++){ pObj = &pHdl->pthr_arr[i]; if(pObj->thr_status == THR_STATE_BUSY) continue; else if(pObj->thr_status == THR_STATE_FREE) break; } return i == pHdl->thr_nums ? -1 : i; }
1
#include <pthread.h> { int data; struct node* next; }node_t,*node_p,**node_pp; node_p head=0; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; node_p AllocNode(int d,node_p node) { node_p n=(node_p)malloc(sizeof(node_t)); if(!n) { perror("malloc"); exit(1); } n->data=d; n->next=node; return n; } void InitList(node_pp _h) { *_h=AllocNode(0,0); } int IsEmpty(node_p n) { return n->next==0?1:0; } void FreeNode(node_p n) { if(n!=0) { free(n); n=0; } } void PushFront(node_p n,int d) { node_p tmp=AllocNode(d,0); tmp->next=n->next; n->next=tmp; } void PopFront(node_p n,int* out) { if(!IsEmpty(n)) { node_p tmp=n->next; n->next=tmp->next; *out=tmp->data; FreeNode(tmp); } } void ShowList(node_p n) { node_p begin=n->next; while(begin) { printf("%d ",begin->data); begin=begin->next; } printf("\\n"); } void Destory(node_p n) { int data; while(!IsEmpty(n)) { PopFront(n,&data); } FreeNode(n); } void* Consumer(void* arg) { int data=0; while(1) { pthread_mutex_lock(&lock); while(IsEmpty(head)) { pthread_cond_wait(&cond,&lock); } PopFront(head,&data); printf("consumer done: %d\\n",data); pthread_mutex_unlock(&lock); } } void* Product(void* arg) { int data=0; while(1) { pthread_mutex_lock(&lock); data=rand()%1234; PushFront(head,data); printf("productor done:%d\\n",data); pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); sleep(1); } } int main() { pthread_mutex_init(&lock,0); InitList(&head); pthread_t consumer,productor; pthread_create(&consumer,0,Consumer,0); pthread_create(&productor,0,Product,0); pthread_join(consumer,0); pthread_join(productor,0); Destory(head); pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); return 0; }
0
#include <pthread.h> pthread_mutex_t buf_lock; int start; int num_full; pthread_cond_t notfull; pthread_cond_t notempty; void *data[10]; } circ_buf_t; pthread_mutex_t lock_enq = PTHREAD_MUTEX_INITIALIZER; int data[60]; int count = 0; void circ_buf_init(circ_buf_t *cbp) { pthread_mutex_init(&cbp->buf_lock, 0); pthread_cond_init(&cbp->notfull, 0); pthread_cond_init(&cbp->notempty, 0); } void put_cb_data (circ_buf_t *cbp, void *data) { pthread_mutex_lock(&cbp->buf_lock); while (cbp->num_full == 10) pthread_cond_wait(&cbp->notfull, &cbp->buf_lock); cbp->data[(cbp->start + cbp->num_full) % 10] = data; cbp->num_full++; pthread_cond_signal(&cbp->notempty); pthread_mutex_unlock(&cbp->buf_lock); } void *get_cb_data(circ_buf_t *cbp) { void *data; pthread_mutex_lock(&cbp->buf_lock); while (cbp->num_full == 0) pthread_cond_wait(&cbp->notempty, &cbp->buf_lock); data = cbp->data[cbp->start]; cbp->start = (cbp->start + 1) % 10; cbp->num_full--; pthread_cond_signal(&cbp->notfull); pthread_mutex_unlock(&cbp->buf_lock); return data; } pid_t gettid() { return syscall(SYS_gettid); } void *enqueue(void *arg) { circ_buf_t *cbp = (circ_buf_t*)arg; for (int i = 0; i < 30; i++) { pthread_mutex_lock(&lock_enq); data[count] = count; put_cb_data(cbp, &data[count]); printf("Put(%d):%d\\n", gettid(), count); count++; pthread_mutex_unlock(&lock_enq); } } void *dequeue(void *arg) { circ_buf_t *cbp = (circ_buf_t*)arg; int *cnt; for (int i = 0; i < 10; i++) { cnt = (int*)get_cb_data(cbp); printf("Get(%d):%d\\n", gettid(), *cnt); } } int main() { pthread_t tid_enq[2], tid_deq[6]; circ_buf_t cb; circ_buf_init(&cb); for (int i = 0; i < 2; i++) { pthread_create(&tid_enq[i], 0, enqueue, &cb); } for (int i = 0; i < 6; i++) { pthread_create(&tid_deq[i], 0, dequeue, &cb); } for (int i = 0; i < 2; i++) { pthread_join(tid_enq[i], 0); } for (int i = 0; i < 6; i++) { pthread_join(tid_deq[i], 0); } return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 8; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); if (count < 12) { printf("watch_count(): thread %ld going into wait...\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutexattr_t attr; int dataItem1; int dataItem2; } DataObject; DataObject dobj = { 50, 50 }; void keepBusy( double howLongInMillisec ); void itemSwap( DataObject* dptr ); void test( DataObject* dptr ); void repeatedSwaps( DataObject* dptr ); main() { pthread_t t1, t2, t3, t4; pthread_mutexattr_init( &attr ); pthread_mutex_init( &mutex, &attr ); pthread_create(&t1, 0, (void* (*)(void*)) repeatedSwaps, &dobj); pthread_create(&t2, 0, (void* (*)(void*)) repeatedSwaps, &dobj); pthread_create(&t3, 0, (void* (*)(void*)) repeatedSwaps, &dobj); pthread_create(&t4, 0, (void* (*)(void*)) repeatedSwaps, &dobj); pthread_join( t1, 0 ); pthread_join( t2, 0); pthread_join( t3, 0); pthread_join( t4, 0); } void keepBusy( double howLongInMillisec ) { int ticksPerSec = CLOCKS_PER_SEC; int ticksPerMillisec = ticksPerSec / 1000; clock_t ct = clock(); while ( clock() < ct + howLongInMillisec * ticksPerMillisec ) ; } void itemSwap( DataObject* dptr ) { int x; pthread_mutex_lock( &mutex ); x = (int) ( -4.999999 + rand() % 10 ); dptr->dataItem1 -= x; keepBusy(10); dptr->dataItem2 += x; pthread_mutex_unlock( &mutex ); } void test( DataObject* dptr ) { int sum; pthread_mutex_lock( &mutex ); sum = dptr->dataItem1 + dptr->dataItem2; printf( "%d\\n", sum ); pthread_mutex_unlock( &mutex ); } void repeatedSwaps( DataObject* dptr ) { int i = 0; while ( i < 20000 ) { itemSwap( dptr ); if ( i % 4000 == 0 ) test( dptr ); keepBusy( 1 ); i++; } }
1
#include <pthread.h> { char tag; int buf_len; char buf[512]; struct _Log_Msg *next; }log_msg; { int log_msg_num; struct _Log_Msg *next; }log_msg_list; { int log_msg_num; pthread_mutex_t lock_list_index; struct _Log_Msg *next; }log_msg_list_index; { struct _Log_Msg_List *log_list_head ; struct _Log_Msg_List_Index *log_list_write_index; struct _Log_Msg_List_Index *log_list_add_index; }log_info; struct _Log_Msg_List *init_point_node(int num) { struct _Log_Msg_List *temp = 0; if(0 == (temp = (struct _Log_Msg_List *)malloc(sizeof(struct _Log_Msg_List)))) return 0; temp->next = 0; return temp; } struct _Log_Msg_List_Index *init_point_index_node(int num) { struct _Log_Msg_List_Index *temp = 0; if(0 == (temp = (struct _Log_Msg_List_Index *)malloc(sizeof(struct _Log_Msg_List_Index)))) return 0; pthread_mutex_init(&(temp->lock_list_index), 0); temp->next = 0; return temp; } struct _Log_Msg *init_log_msg(void) { struct _Log_Msg *temp = 0; temp = (struct _Log_Msg*)malloc(sizeof(struct _Log_Msg)); if(0 == temp) return temp; temp->next = 0; temp->buf_len = 0; temp->tag = 'F'; return temp; } int add_msg_to_list(struct _Log_Info *p_log_info_st, struct _Log_Msg *node) { node->next = p_log_info_st->log_list_head->next; p_log_info_st->log_list_head->next = node; return 0; } int init_log_list(int num, struct _Log_Info *p_log_info_st) { p_log_info_st->log_list_head = init_point_node(50); p_log_info_st->log_list_write_index = init_point_index_node(0); p_log_info_st->log_list_add_index = init_point_index_node(0); printf("%s,%d\\n", __FUNCTION__, 97); int j; struct _Log_Msg *node = 0; for(j = 0; j < num; j++) { node = init_log_msg(); add_msg_to_list(p_log_info_st, node); } p_log_info_st->log_list_write_index->next = p_log_info_st->log_list_head; p_log_info_st->log_list_add_index->next = p_log_info_st->log_list_head; if((0 == p_log_info_st->log_list_head) || (0 == p_log_info_st->log_list_write_index) ||(0 == p_log_info_st->log_list_add_index)) { printf("log链表构指向节点构造失败\\n"); return 0; } printf("%s,%d\\n", __FUNCTION__, 115); return 0; } int add_log_msg_to_list(struct _Log_Msg_List_Index *add_index, char *msg, int msg_len) { pthread_mutex_lock(&(add_index->lock_list_index)); if(0 == add_index->next->next) { printf("NULL == add_index->next->next \\n"); } else { add_index->log_msg_num++; add_index->next->tag = 'T'; add_index->next->buf_len = msg_len; printf("%s,%d\\n", __FUNCTION__, 137); strcpy(add_index->next->buf, msg); add_index->next = add_index->next->next; pthread_mutex_unlock(&(add_index->lock_list_index)); } return 0; } int write_log_msg_to_file(unsigned char *path, struct _Log_Info *log_info_st) { pthread_mutex_lock(&(log_info_st->log_list_write_index->lock_list_index)); printf("%s,%d\\n", __FUNCTION__, 153); FILE *fp = 0; extern int errno; if(0 == (fp = fopen(path, "a+"))) { printf("创建log文件失败\\n"); printf("%s \\n", strerror(errno)); } while('T' == log_info_st->log_list_write_index->next->tag) { fwrite(log_info_st->log_list_write_index->next->buf, 1, log_info_st->log_list_write_index->next->buf_len, fp); log_info_st->log_list_write_index->next->tag = 'F'; memset(log_info_st->log_list_write_index->next->buf, 0, 512); log_info_st->log_list_write_index->next = log_info_st->log_list_write_index->next->next; log_info_st->log_list_write_index->log_msg_num++; } fflush(fp); fclose(fp); pthread_mutex_unlock(&(log_info_st->log_list_write_index->lock_list_index)); return 0; } FILE *init_log_file(unsigned char *path) { FILE *fp = 0; extern int errno; if(0 == (fp = fopen(path, "a+"))) { printf("创建log文件失败\\n"); printf("%s \\n", strerror(errno)); } return fp; } int main(int argc, char **argv) { struct _Log_Msg_List *log_list_head = 0; struct _Log_Msg_List_Index *log_list_write_index = 0; struct _Log_Msg_List_Index *log_list_add_index = 0; struct _Log_Info log_info_st = {"NULL","NULL", "NULL"}; init_log_list(50, &log_info_st); int i; char temp_buf[8] = {'a', 'v', '3', '5', 'e', 't', '5', '\\n'}; for(i = 0; i < 20; i++) { add_log_msg_to_list(log_info_st.log_list_add_index, temp_buf, 8); } write_log_msg_to_file("loglog.txt", &log_info_st); printf("%s,%d\\n", __FUNCTION__, 218); return 0; }
0
#include <pthread.h> int count=1; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *counter(void *t) { long my_id=(long)t; int slp; pthread_mutex_lock(&count_mutex); count++; slp=count; while (slp=sleep(slp)); if (count == 1+3) { pthread_cond_broadcast(&count_threshold_cv); printf("signal\\n"); } pthread_cond_wait(&count_threshold_cv, &count_mutex); pthread_mutex_unlock(&count_mutex); pthread_cond_broadcast(&count_threshold_cv); pthread_exit(0); } int main (int argc, char *argv[]) { int i; int flag=1; long t; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for (i=0; i< 3; i++) { t=i; pthread_create(&threads[i], &attr, counter, (void *)t); } for(i=0; i< 3; i++) { pthread_join(threads[i], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> struct parm { int id; int ready; }; pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER; static void *syscall_setreuid(void *arg) { long int rc; uid_t ru; (void) arg; for (ru = 0; ru < 2048; ++ru) { uid_t ruid, euid, suid; rc = syscall(SYS_setreuid, -1, ru); assert_int_equal(rc, 0); ruid = getuid(); assert_int_equal(ruid, 0); euid = geteuid(); assert_int_equal(euid, ru); rc = syscall(SYS_setreuid, -1, 0); assert_int_equal(rc, 0); ruid = getuid(); assert_int_equal(ruid, 0); euid = geteuid(); assert_int_equal(euid, 0); } return 0; } static void *sync_setreuid(void *arg) { struct parm *p = (struct parm *)arg; uid_t u; syscall_setreuid(arg); p->ready = 1; pthread_mutex_lock(&msg_mutex); u = geteuid(); assert_int_equal(u, 42); pthread_mutex_unlock(&msg_mutex); return 0; } static void test_sync_setreuid(void **state) { pthread_attr_t pthread_custom_attr; pthread_t threads[10]; struct parm *p; int rc; int i; (void) state; pthread_attr_init(&pthread_custom_attr); p = malloc(10 * sizeof(struct parm)); assert_non_null(p); pthread_mutex_lock(&msg_mutex); for (i = 0; i < 10; i++) { p[i].id = i; p[i].ready = 0; pthread_create(&threads[i], &pthread_custom_attr, sync_setreuid, (void *)&p[i]); } for (i = 0; i < 10; i++) { while (p[i].ready != 1) { sleep(1); } } rc = setreuid(-1, 42); assert_int_equal(rc, 0); pthread_mutex_unlock(&msg_mutex); for (i = 0; i < 10; i++) { pthread_join(threads[i], 0); } pthread_attr_destroy(&pthread_custom_attr); free(p); } int main(void) { int rc; const struct CMUnitTest thread_tests[] = { cmocka_unit_test(test_sync_setreuid), }; rc = cmocka_run_group_tests(thread_tests, 0, 0); return rc; }
0
#include <pthread.h> pthread_mutex_t mutex_lock; pthread_mutexattr_t attr; pthread_cond_t cond_lock; struct timeval now; struct timespec outtime; int cond_counter = 0; void down(char*); void up(char *); void fork_prepare(void); void fork_parent(void); void fork_child(void); void fork_prepare(void) { int status; status = pthread_mutex_lock(&mutex_lock); if(status != 0) err_exit(status, "fork prepare handler lock error"); printf("preparing locks...\\n"); } void fork_parent(void) { int status; status = pthread_mutex_unlock(&mutex_lock); if(status != 0) err_exit(status, "fork parent handler unlock error"); printf("parent unlocks...\\n"); } void fork_child(void) { int status; status = pthread_mutex_unlock(&mutex_lock); if(status != 0) err_exit(status, "fork child handler unlock error"); printf("child unlcoks...\\n"); } void lock_init(void) { pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex_lock, &attr); pthread_cond_init(&cond_lock, 0); cond_counter = 1; } void down(char *buf) { int status; printf("DOWN: %s\\n", buf); pthread_mutex_lock(&mutex_lock); while(cond_counter == 0) { gettimeofday(&now ,0); outtime.tv_sec = now.tv_sec + 10; outtime.tv_nsec = now.tv_usec * 1000; status = pthread_cond_timedwait(&cond_lock, &mutex_lock, &outtime); if(status == ETIMEDOUT) { printf("%s condition wait TIMEOUT\\n", buf); } } cond_counter--; pthread_mutex_unlock(&mutex_lock); } void up(char *buf) { pthread_mutex_lock(&mutex_lock); printf("UP: %s\\n", buf); if(cond_counter == 0) pthread_cond_signal(&cond_lock); cond_counter++; pthread_mutex_unlock(&mutex_lock); } void down2(char * buf) { printf("DOWN: %s\\n", buf); pthread_mutex_lock(&mutex_lock); } void up2(char * buf) { pthread_mutex_unlock(&mutex_lock); printf("UP: %s\\n", buf); } void *thread_routine (void *arg) { int status; down((char *)arg); printf("%s: lock got\\n", (char *)arg); sleep(5); up((char *)arg); printf("%s: unlock\\n", (char *)arg); return 0; } int main (int argc, char *argv[]) { pthread_t thread_1_to_fork; pid_t proc_1_to_fork; int status; void *arg; lock_init(); if((status = pthread_atfork(fork_prepare, fork_parent, fork_child)) != 0) err_exit(status, "cant install fork handlers"); arg = (void *)("proc_0 | thread_1"); status = pthread_create(&thread_1_to_fork, 0, thread_routine, arg); if(status != 0) err_exit(status, "cant create new thread: thread_1"); if((proc_1_to_fork = fork()) < 0) err_sys("fork error"); else if(proc_1_to_fork == 0) { arg = (void *)("proc_1 | thread_0"); thread_routine(arg); } else { down("proc_0 | thread_0"); printf("proc_0 | thread_0: lock got\\n"); up("proc_0 | thread_0"); printf("proc_0 | thread_0: unlock\\n"); } pthread_exit(0); }
1
#include <pthread.h> int sum = 0 ; pthread_mutex_t mutex ; void *threadBody(void *id) { int i ; for (i=0; i< 100000; i++) { pthread_mutex_lock (&mutex) ; sum += 1 ; pthread_mutex_unlock (&mutex) ; } pthread_exit (0) ; } int main (int argc, char *argv[]) { struct timeval t1, t2; double elapsedTime; gettimeofday(&t1, 0); pthread_t thread [100] ; pthread_attr_t attr ; long i, status ; pthread_mutex_init (&mutex, 0) ; pthread_attr_init (&attr) ; pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE) ; for(i=0; i<100; i++) { status = pthread_create (&thread[i], &attr, threadBody, (void *) i) ; if (status) { perror ("pthread_create") ; exit (1) ; } } for (i=0; i<100; i++) { status = pthread_join (thread[i], 0) ; if (status) { perror ("pthread_join") ; exit (1) ; } } printf ("Sum should be %d and is %d\\n", 100*100000, sum) ; printf("Time Elapsed: "); gettimeofday(&t2, 0); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; printf("%f ms.\\n", elapsedTime); pthread_attr_destroy (&attr) ; pthread_exit (0) ; }
0
#include <pthread.h> pthread_mutex_t read_mutex; pthread_mutex_t write_mutex; void * writeTest(void *temp) { char *ret; FILE *file1; char *str; pthread_mutex_lock(&write_mutex); sleep(5); pthread_mutex_lock(&read_mutex); printf("\\nFile locked, please enter the message \\n"); str=(char *)malloc(10*sizeof(char)); file1=fopen("temp","w"); scanf("%s",str); fprintf(file1,"%s",str); fclose(file1); pthread_mutex_unlock(&read_mutex); pthread_mutex_unlock(&write_mutex); printf("\\nUnlocked the file you can read it now \\n"); return ret; } void * readTest(void *temp) { char *ret; FILE *file1; char *str; pthread_mutex_lock(&read_mutex); sleep(5); pthread_mutex_lock(&write_mutex); printf("\\n Opening file \\n"); file1=fopen("temp","r"); str=(char *)malloc(10*sizeof(char)); fscanf(file1,"%s",str); printf("\\n Message from file is %s \\n",str); fclose(file1); pthread_mutex_unlock(&write_mutex); pthread_mutex_unlock(&read_mutex); return ret; } int main() { pthread_t thread_id,thread_id1; pthread_attr_t attr; int ret; void *res; ret=pthread_create(&thread_id,0,&writeTest,0); ret=pthread_create(&thread_id1,0,&readTest,0); printf("\\n Created thread"); pthread_join(thread_id,&res); pthread_join(thread_id1,&res); }
1
#include <pthread.h> static inline uint32_t getchecksum(void* data, size_t datalen) { unsigned char* d = data; uint32_t sum = 0; size_t i = 0; for(i = 0; i < datalen; i++) { sum += d[i]; } return sum; } int packet_encoder_init(char* arg, void** state) { if(arg == 0 || state == 0) { return -1; } if(sodium_init() < 0) { return -1; } *state = calloc(32 + 8 + sizeof(pthread_mutex_t), 1); if(*state == 0) { return -1; } if(pthread_mutex_init((*state) + 32 + 8, 0) != 0) { free(*state); return -1; } FILE* fp = fopen(arg, "r"); if(fp == 0) { free(*state); return -1; } if(fread(*state, 32, 1, fp) != 1) { free(*state); fclose(fp); return -1; } randombytes_buf((*state) + 32, 8); fclose(fp); randombytes_close(); return 0; } int packet_encoder_deinit(void** state) { if(state == 0 || *state == 0) { return -1; } pthread_mutex_destroy((*state) + 32 + 8); sodium_memzero(*state, 32 + 8 + sizeof(pthread_mutex_t)); free(*state); *state = 0; return 0; } int packet_encode(void* eth_frame, uint16_t eth_frame_len, void* dst, size_t dst_len, int16_t id, void* state) { if(eth_frame == 0 || dst == 0 || state == 0) { return -1; } if(eth_frame_len < 1 || dst_len < 1) { return -1; } if((size_t)eth_frame_len + 24 > dst_len) { return -1; } void* key_256bit = state; uint64_t nonce_64bit = *((uint64_t*)(state + 32)); uint16_t eth_frame_len_be = htons(eth_frame_len); uint32_t frame_checksum_be = htonl(getchecksum(eth_frame, eth_frame_len)); int16_t id_be = htons(id); uint8_t nonce_dup2[16] = {0}; memcpy(nonce_dup2, &nonce_64bit, 8); memcpy(nonce_dup2 + 8, &nonce_64bit, 8); AES128_ECB_encrypt(nonce_dup2, key_256bit, nonce_dup2); memcpy(dst, &eth_frame_len_be, 2); memcpy(dst + 2, eth_frame, eth_frame_len); memcpy(dst + 2 + eth_frame_len, &frame_checksum_be, 4); memcpy(dst + 2 + eth_frame_len + 4, &id_be, 2); memcpy(dst + 2 + eth_frame_len + 4 + 2, nonce_dup2, 16); int ret = crypto_stream_chacha20_xor(dst, dst, 2 + eth_frame_len + 4 + 2, (void*)(&nonce_64bit), key_256bit); if(ret < 0) { sodium_memzero(dst, dst_len); return -1; } pthread_mutex_lock(state + 32 + 8); *((uint64_t*)(state + 32)) += 1; pthread_mutex_unlock(state + 32 + 8); return eth_frame_len + 24; } int packet_decode(void* src, size_t src_len, void* dst_eth_frame, uint16_t* dst_len, int16_t* id, void* state) { if(src == 0 || dst_eth_frame == 0 || dst_len == 0 || id == 0 || state == 0) { return -1; } if(src_len < 24 + 1 || *dst_len < 1) { return -1; } if(src_len - 24 > *dst_len) { return -1; } void* key_256bit = state; void* nonce_64bit = src + (src_len - 16); AES128_ECB_decrypt(nonce_64bit, key_256bit, nonce_64bit); int ret = crypto_stream_chacha20_xor(src, src, src_len - 16, nonce_64bit, key_256bit); if(ret < 0) { return -1; } uint16_t eth_frame_len_be; memcpy(&eth_frame_len_be, src, 2); uint16_t eth_frame_len = ntohs(eth_frame_len_be); if(2 + (size_t)eth_frame_len + 4 + 2 + 16 != src_len) { return -1; } uint32_t frame_checksum_be; memcpy(&frame_checksum_be, src + 2 + eth_frame_len, 4); uint32_t frame_checksum = ntohl(frame_checksum_be); if(frame_checksum != getchecksum(src + 2, eth_frame_len)) { return -1; } int16_t id_be; memcpy(&id_be, src + 2 + eth_frame_len + 4, 2); *id = ntohs(id_be); memcpy(dst_eth_frame, src + 2, eth_frame_len); *dst_len = eth_frame_len; return eth_frame_len; }
0
#include <pthread.h> extern char **environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, int buflen) { int i, len, olen; pthread_once(&init_done, thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen(&environ[i][len + 1]); if (olen >= buflen) { pthread_mutex_unlock(&env_mutex); return (ENOSPC); } strcpy(buf, &environ[i][len + 1]); pthread_mutex_unlock(&env_mutex); return (0); } } pthread_mutex_unlock(&env_mutex); return (ENOENT); } int main() { char buf[1<<12]; getenv_r("PATH",buf,1<<12); printf("%s\\n",buf); }
1
#include <pthread.h> static int ITEMS_SENT[1]; static int ITEMS_RECIEVED[1]; { int m_input; int m_output; int m_numberOfItems; int m_items[10]; pthread_mutex_t m_lock; } Buffer; static Buffer buffer[1]; void InitializeBuffers(void) { if (1) { printf("\\n(!) Initializing buffers..."); } int i; for (i = 0; i < 1; i++) { buffer[i].m_input = 0; buffer[i].m_output = 0; buffer[i].m_numberOfItems = 0; pthread_mutex_init(&buffer[i].m_lock, 0); } if (1) { printf(" DONE"); } } void *Producer(void *p_threadID) { int l_item = 0; int l_quit = 0; long l_threadID = (long)p_threadID; const int l_itemOffset = (10000000 / 1) * l_threadID; if (1) { printf("\\nProducer thread %lu beginning work...", l_threadID); } while (!l_quit) { pthread_mutex_lock(&buffer[l_threadID].m_lock); if (ITEMS_SENT[l_threadID] < (10000000 / 1)) { if (buffer[l_threadID].m_numberOfItems < 10) { l_item = (ITEMS_SENT[l_threadID]++) + l_itemOffset; buffer[l_threadID].m_items[buffer[l_threadID].m_input] = l_item; buffer[l_threadID].m_input = (buffer[l_threadID].m_input + 1) % 10; buffer[l_threadID].m_numberOfItems++; } } else { l_quit = 1; } pthread_mutex_unlock(&buffer[l_threadID].m_lock); } if (1) { printf("\\nProducer thread %lu completed.", l_threadID); } pthread_exit(0); } void *Consumer(void *p_threadID) { int l_item = 0; int l_quit = 0; long l_threadID = (long)p_threadID; if (1) { printf("\\nConsumer thread %lu beginning work...", l_threadID); } while (!l_quit) { pthread_mutex_lock(&buffer[l_threadID].m_lock); if (ITEMS_RECIEVED[l_threadID] < (10000000 / 1)) { if (buffer[l_threadID].m_numberOfItems > 0) { l_item = buffer[l_threadID].m_items[buffer[l_threadID].m_output]; buffer[l_threadID].m_output = (buffer[l_threadID].m_output + 1) % 10; buffer[l_threadID].m_numberOfItems--; ITEMS_RECIEVED[l_threadID]++; } } else { l_quit = 1; } pthread_mutex_unlock(&buffer[l_threadID].m_lock); } if (1) { printf("\\nConsumer thread %lu completed.", l_threadID); } pthread_exit(0); } int main(int argc, char **argv) { printf("\\nSCALING BOUNDED BUFFERS"); if (1) { printf(" (DEBUG IS ACTIVE)"); printf("\\nItems to send: %d", 10000000); printf("\\nBuffer size: %d", 10); printf("\\nProduction lines: %d", 1); printf("\\n(Thats %d items per line)", (10000000 / 1)); } InitializeBuffers(); pthread_t l_producerThreads[1]; pthread_t l_consumerThreads[1]; pthread_attr_t l_threadAttributes; pthread_attr_init(&l_threadAttributes); struct timeval l_start; struct timeval l_end; gettimeofday(&l_start, 0); if (1) { printf("\\n(!) Creating producer threads..."); } long i; for (i = 0; i < 1; i++) { pthread_create(&l_producerThreads[i], &l_threadAttributes, Producer, (void *)i); } if (1) { printf("\\nProducer threads created."); printf("\\n(!) Creating consumer threads..."); } for (i = 0; i < 1; i++) { pthread_create(&l_consumerThreads[i], &l_threadAttributes, Consumer, (void *)i); } if (1) { printf("\\nConsumer threads created."); printf("\\n(!) Waiting to join threads..."); } for (i = 0; i < 1; i++) { pthread_join(l_producerThreads[i], 0); } if (1) { printf("\\n(!) Producer threads joined."); } for (i = 0; i < 1; i++) { pthread_join(l_consumerThreads[i], 0); } if (1) { printf("\\n(!) Consumer threads joined."); int l_sumSent = 0; int l_sumRecieved = 0; for (i = 0; i < 1; i++) { l_sumSent += ITEMS_SENT[i]; l_sumRecieved += ITEMS_RECIEVED[i]; } printf("\\n%d total items sent, and %d total items recieved.", l_sumSent, l_sumRecieved); } gettimeofday(&l_end, 0); unsigned long int l_startMSec = l_start.tv_sec * 1000000 + l_start.tv_usec; unsigned long int l_endMSec = l_end.tv_sec * 1000000 + l_end.tv_usec; unsigned long int l_difference = l_endMSec - l_startMSec; double l_differenceInSeconds = l_difference / 1000000.0; printf("\\n(!) Time taken to send %d items: %f seconds.\\n", 10000000, l_differenceInSeconds); }
0
#include <pthread.h> static FILE *logfd; static pthread_mutex_t syslog_mutex = PTHREAD_MUTEX_INITIALIZER; static struct timeval start_time; static char *month[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; void rtstepper_close_log(void) { if (logfd) { fclose(logfd); logfd = 0; } pthread_mutex_destroy(&syslog_mutex); } void rtstepper_open_log(const char *ident, int logopt) { struct tm *pt; time_t t; char log_file[512], backup[512]; struct stat sb; if (logfd) return; sprintf(log_file, "%s.log", ident); if (logopt == RTSTEPPER_LOG_BACKUP && stat(log_file, &sb) == 0) { sprintf(backup, "%s.bak", ident); remove(backup); rename(log_file, backup); } logfd = fopen(log_file, "a"); gettimeofday(&start_time, 0); t = time(0); pt = localtime(&t); rtstepper_syslog("started %s %s %d %d:%d:%d\\n", log_file, month[pt->tm_mon], pt->tm_mday, pt->tm_hour, pt->tm_min, pt->tm_sec); } void rtstepper_syslog(const char *fmt, ...) { struct timeval now; va_list args; char tmp[512]; int n; if (!logfd) return; pthread_mutex_lock(&syslog_mutex); __builtin_va_start((args)); if ((n = vsnprintf(tmp, sizeof(tmp), fmt, args)) == -1) tmp[sizeof(tmp) - 1] = 0; gettimeofday(&now, 0); fprintf(logfd, "%lu.%.3lus %s", now.tv_sec & 0xfff, (unsigned long int)now.tv_usec % 1000000, tmp); fflush(logfd); ; pthread_mutex_unlock(&syslog_mutex); }
1
#include <pthread.h> struct { pthread_mutex_t mutex; pthread_cond_t cond; int buff[10]; int nitems; } shared = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; void* produce(void* arg) { for (;;) { pthread_mutex_lock(&shared.mutex); if (shared.nitems >= 50000000) { pthread_cond_broadcast(&shared.cond); pthread_mutex_unlock(&shared.mutex); return 0; } shared.buff[*((int*) arg)]++; shared.nitems++; pthread_mutex_unlock(&shared.mutex); } } void* consume(void* arg) { pthread_mutex_lock(&shared.mutex); while (shared.nitems < 50000000) { const struct timespec abstime = { time(0) + 2, 0 }; pthread_cond_timedwait(&shared.cond, &shared.mutex, &abstime); printf("timed out try one else\\n"); } pthread_mutex_unlock(&shared.mutex); int i; for (i = 0; i < 10; ++i) printf("buff[%d] = %d\\n", i, shared.buff[i]); return 0; } int main() { int i; pthread_t produce_threads[10]; pthread_t consume_thread; for (i = 0; i < 10; ++i) pthread_create(&produce_threads[i], 0, produce, &i); pthread_create(&consume_thread, 0, consume, 0); for (i = 0; i < 10; ++i) pthread_join(produce_threads[i], 0); pthread_join(consume_thread, 0); return 0; }
0
#include <pthread.h> unsigned long long calls = 0, ticks = 0; double sum = 0; pthread_mutex_t calls_lock = PTHREAD_MUTEX_INITIALIZER; static void timer_tick(union sigval _arg) { (void)_arg; unsigned long long res; pthread_mutex_lock(&calls_lock); res = calls; calls = 0; pthread_mutex_unlock(&calls_lock); double speed = (double)(res * SIZEOF_UINT64) / 1024.0; sum += speed; ticks++; double avg_speed = sum / (double)ticks; printf("Current speed: %1.3lf KiB/s\\tAverage speed: %1.3lf KiB/s\\n", speed, avg_speed); } int main(int argc, char** argv) { timer_t timer_info; struct sigevent timer_event; timer_event.sigev_notify = SIGEV_THREAD; timer_event.sigev_notify_function = timer_tick; timer_event.sigev_notify_attributes = 0; struct itimerspec timer_time; timer_time.it_interval.tv_sec = 1; timer_time.it_interval.tv_nsec = 0; timer_time.it_value.tv_sec = 1; timer_time.it_value.tv_nsec = 0; int opts; unsigned int fast = 0; struct option longopts[] = { {"fast", no_argument, 0, 'f'}, {0, 0, 0, 0} }; while ((opts = getopt_long(argc, argv, "f", longopts, 0)) != -1) switch (opts) { case 'f': fast = 1; break; default: fprintf(stderr, "Unknown option: %c\\n", opts); exit(EX_USAGE); break; } pfrng_init(); int cpus = 1; printf("Using %d thread(s)\\n", cpus); volatile uint64_t n ; timer_create(CLOCK_REALTIME, &timer_event, &timer_info); timer_settime(timer_info, 0, &timer_time, 0); while (1) { if (fast) n = pfrng_get_u64_fast(); else n = pfrng_get_u64(); pthread_mutex_lock(&calls_lock); calls++; pthread_mutex_unlock(&calls_lock); } pfrng_done(); exit(EX_OK); }
1
#include <pthread.h> int value; pthread_mutex_t mutex; } atomic_integer; void atomic_init(atomic_integer* item) { item->value = 0; pthread_mutex_init(&item->mutex, 0); } void atomic_init_and_set(atomic_integer* item, int value) { item->value = value; pthread_mutex_init(&item->mutex, 0); } void atomic_set(atomic_integer* item, int value) { pthread_mutex_lock(&item->mutex); item->value = value; pthread_mutex_unlock(&item->mutex); } int atomic_get(atomic_integer* item) { pthread_mutex_lock(&item->mutex); int value = item->value; pthread_mutex_unlock(&item->mutex); return value; } void atomic_increment(atomic_integer* item) { pthread_mutex_lock(&item->mutex); item->value++; pthread_mutex_unlock(&item->mutex); } int atomic_increment_and_get(atomic_integer* item) { pthread_mutex_lock(&item->mutex); item->value++; int value = item->value; pthread_mutex_unlock(&item->mutex); return value; } int atomic_decrement_and_get(atomic_integer* item) { pthread_mutex_lock(&item->mutex); item->value--; int value = item->value; pthread_mutex_unlock(&item->mutex); return value; } void atomic_decrement(atomic_integer* item) { pthread_mutex_lock(&item->mutex); item->value--; pthread_mutex_unlock(&item->mutex); }
0
#include <pthread.h> char** split_line(char* s){ char* p=malloc(sizeof(char)*1024); static char** ret; ret = malloc(sizeof(char*)*2); ret[0]=malloc(sizeof(char)*16); ret[1]=malloc(sizeof(char)*1024); strcpy(p,s); int i =0; p = strtok(s, " "); printf("[INPUT_POSTO] %s\\n", p); while(p != 0) { printf("%s\\n", p); if(i==0) strcpy(ret[0],p); else if(i==1) strcpy(ret[1],p); p = strtok(0, " "); i++; } return ret; } void creaFilePosti(int i, int nfile, int npostifila){ char line[1024]; FILE *f = fopen("sala.txt", "r"); if(f!=0){ if(fgets(line,sizeof(line),f)==0){ } else{ int n_file = atoi(line); printf("-%s\\n", line); printf("%d\\n", n_file); int i,j; sala.nFile = n_file; sala.file = malloc(sizeof(struct fila)*n_file); for(j=0; j<n_file; j++){ fgets(line,sizeof(line),f); int n_posti; char filara[1024]; char** ret=malloc(sizeof(char*)*2); ret[0] = malloc(sizeof(char)*16); ret[1] = malloc(sizeof(char)*1014); ret = split_line(line); printf("%s - %s\\n",ret[0],ret[1]); n_posti=20; sala.file[j].nPosti = n_posti; sala.file[j].posti = malloc(sizeof(struct posto)*n_posti); printf("OK-4\\n"); strcpy(filara, ret[1]); printf("OK-5\\n"); for(i=0; i<n_posti;i++){ printf("OK-6\\n"); sala.file[j].posti[i].codice = i; printf("OK-7\\n"); sala.file[j].posti[i].codice_fila = j; printf("OK-8\\n"); int c; if(filara[i]=='0') c=0; else c=1; sala.file[j].posti[i].prenotato = c; printf("OK-9\\n"); } sala.file[j].codice = j; sala.file[j].nPostiLiberi = npostifila; } fclose(f); } }else{ int j,k; sala.nFile = nfile; sala.file = malloc(sizeof(struct fila)*nfile); for (j = 0; j < nfile; j++){ sala.file[j].nPosti = npostifila; sala.file[j].posti = malloc(sizeof(struct posto)*npostifila); for (k = 0; k < npostifila; k++){ sala.file[j].posti[k].codice = k; sala.file[j].posti[k].codice_fila = j; sala.file[j].posti[k].prenotato = 0; } sala.file[j].codice = j; sala.file[j].nPostiLiberi = npostifila; } } } void inizializzaSala(){ int i; int nfile=9; int npostifila=20; int costoIntero=0; pthread_mutexattr_t attr; creaFilePosti(i, nfile, npostifila); sala.postiDisponibili = nfile * npostifila; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&sala.mx_aggiornamentoSala,&attr); pthread_mutexattr_destroy(&attr); pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&sala.mx_aggiornamentoFilePrenotazioni,&attr); pthread_mutexattr_destroy(&attr); char line[CODLEN]; FILE *f = fopen("codice.txt","r"); if(f!=0){ if(fgets(line,sizeof(line),f)!=0){ strcpy(COD_PREN,line); fclose(f); } } else{ strcpy(COD_PREN,"0"); } printf("<SERVER-INFO> cinema Inizializzato\\n"); } void stampaSala(struct sala_cinema s){ int j,k; pthread_mutex_lock(&(sala.mx_aggiornamentoSala)); for (j = 0; j < s.nFile; j++){ for (k = 0; k < s.file[j].nPosti; k++){ printf("%d ", s.file[j].posti[k].prenotato); } printf("\\n"); } pthread_mutex_unlock(&(sala.mx_aggiornamentoSala)); }
1
#include <pthread.h> struct JSPropertyCache { int table; int empty; }; pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; struct JSPropertyCache g_cache; void do_some_work() { int i; for(i = 0; i < 0x2000; i++) i = i * 10.0 /5 / 2; return; } void * js_FlushPropertyCache(void * pointer) { struct JSPropertyCache * cache = (struct JSPropertyCache *)pointer; int i = 0; int violated = 0; while (i++ < 10) { pthread_mutex_lock(&g_lock); cache->table = 0; pthread_mutex_unlock(&g_lock); do_some_work(); pthread_mutex_lock(&g_lock); cache->empty = 1; pthread_mutex_unlock(&g_lock); usleep(i%2); pthread_mutex_lock(&g_lock); if(cache->table != 0 && cache->empty == 0) { violated = 1; pthread_mutex_unlock(&g_lock); break; } pthread_mutex_unlock(&g_lock); } if(violated == 1) printf("atomicity violation in multivariable detected.\\n"); else printf("no violation found!\\n"); return 0L; } void * js_PropertyCacheFill(void * pointer) { int i = 0; struct JSPropertyCache * cache = (struct JSPropertyCache *)pointer; while (i++ < 10) { pthread_mutex_lock(&g_lock); cache->table = 1; pthread_mutex_unlock(&g_lock); do_some_work(); pthread_mutex_lock(&g_lock); cache->empty = 0; pthread_mutex_unlock(&g_lock); usleep(i%5); } return 0L; } int main (int argc, char * argv[]) { pthread_t waiters[2]; int i; pthread_create (&waiters[0], 0, js_FlushPropertyCache, (void *)&g_cache); pthread_create (&waiters[1], 0, js_PropertyCacheFill, (void *)&g_cache); for (i = 0; i < 2; i++) { pthread_join (waiters[i], 0); } return 0; }
0
#include <pthread.h> int total_cookies_baked = 0; int cookie_jar[5]; int number_of_cookies_in_jar = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *baker(); void *eater(); int pass = 0; int main(int argc, char *argv[]) { pthread_t thread1, thread2, thread3; char * eater1 = "Eater 1"; pthread_create( &thread1, 0, &baker, 0); pthread_create( &thread2, 0, &eater, eater1); pthread_join(thread1, 0); pthread_join(thread2, 0); return 1; } void *baker() { while(1) { pthread_mutex_lock(&count_mutex); if (total_cookies_baked == 10) { pthread_mutex_unlock( &count_mutex ); break; } while (number_of_cookies_in_jar == 5) { pthread_cond_wait(&condition_var, &count_mutex); } while(number_of_cookies_in_jar < 5 && total_cookies_baked < 10) { cookie_jar[number_of_cookies_in_jar++] = total_cookies_baked; printf("Cookie baked number %d\\n", total_cookies_baked); total_cookies_baked++; } pthread_cond_signal(&condition_var); pthread_mutex_unlock( &count_mutex ); } pthread_exit(&pass); } void *eater(void * eater_name) { char * eatername = (char *)eater_name; while (1) { pthread_mutex_lock(&count_mutex); if (total_cookies_baked == 10 && number_of_cookies_in_jar == 0) { pthread_mutex_unlock(&count_mutex); break; } while (number_of_cookies_in_jar == 0) { pthread_cond_wait(&condition_var, &count_mutex); } number_of_cookies_in_jar--; int cookie = cookie_jar[number_of_cookies_in_jar]; printf("%s ate cookie number %d\\n", eatername, cookie); pthread_cond_signal(&condition_var); pthread_mutex_unlock(&count_mutex); } pthread_exit(&pass); }
1
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; static struct foo * foo_alloc(int id) { struct foo *fp = 0; int ret = 0; fp =(struct foo *) malloc(sizeof(struct foo)); if (0 == fp) { return 0; } fp->f_id = id; fp->f_count = 1; ret = pthread_mutex_init(&fp->f_lock, 0); if (ret != 0) { free(fp); fp = 0; } return fp; } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); }
0
#include <pthread.h> static unsigned long MemoryPoolSize1=1024*1024*1; static unsigned long MemoryPoolSize2=1024*1024*32; static struct rb_root*g_table=0; static pthread_mutex_t g_ipv6status_lock; unsigned long get_ipv6_status(unsigned char*ip) { unsigned long status=0; struct my_rbnode*mynode=0; pthread_mutex_lock(&g_ipv6status_lock); mynode=hash_rbtree_search(g_table,ip); status=mynode?mynode->attr.status:multi_ntrie_get_status(ip); pthread_mutex_unlock(&g_ipv6status_lock); return status; } void get_ipv6_all(struct trans_ioctl_ipv6 *attr) { struct my_rbnode* mynode=0; pthread_mutex_lock(&g_ipv6status_lock); mynode=hash_rbtree_search(g_table,attr->net); if(mynode){ memcpy(attr, &(mynode->attr), sizeof(struct trans_ioctl_ipv6)); }else{ attr->status = multi_ntrie_get_status(attr->net); attr->lasttime_in=0; attr->lasttime_out=0; attr->bytes_in=0; attr->bytes_out=0; attr->bytesN_in=0; attr->bytesN_out=0; attr->pkts_in=0; attr->pkts_out=0; } pthread_mutex_unlock(&g_ipv6status_lock); } int set_ipv6_status(unsigned char * netprefix,unsigned long prefixlen,unsigned long status) { int ret=0; pthread_mutex_lock(&g_ipv6status_lock); if(prefixlen==128){ if(multi_ntrie_get_status(netprefix)==status){ hash_rbtree_delete(g_table,netprefix); }else{ ret=hash_rbtree_insert(g_table,netprefix,status,1 ); } } else{ ret=multi_ntrie_set_status(netprefix,prefixlen,status); } pthread_mutex_unlock(&g_ipv6status_lock); return ret; } static struct trans_ioctl_ipv6 * __get_ipv6_status_and_flow_ptr(unsigned char*ip,unsigned long *status) { struct my_rbnode* mynode=hash_rbtree_search(g_table,ip); if(mynode){ *status=mynode->attr.status; return &(mynode->attr); }else{ *status=multi_ntrie_get_status(ip); return 0; } } unsigned long transfer_test_and_merge_flow6(struct ip6_hdr *ipv6h) { struct trans_ioctl_ipv6 *sipnode=0; struct trans_ioctl_ipv6 *dipnode=0; unsigned long scntl; unsigned long dcntl; unsigned long ok_to_go; unsigned short payload_len; pthread_mutex_lock(&g_ipv6status_lock); sipnode = __get_ipv6_status_and_flow_ptr((unsigned char*)&(ipv6h->ip6_src),&scntl); dipnode = __get_ipv6_status_and_flow_ptr((unsigned char*)&(ipv6h->ip6_dst),&dcntl); ok_to_go=transfer_test_with_status(scntl, dcntl); payload_len=ntohs(ipv6h->ip6_plen); if(ok_to_go){ if(sipnode){ sipnode->pkts_out ++; sipnode->lasttime_out = time(0); if(dcntl == IPVO_FREE) sipnode->bytesN_out += payload_len; else sipnode->bytes_out += payload_len; } if(dipnode){ dipnode->pkts_in ++; dipnode->lasttime_in = time(0); if(scntl == IPVO_FREE) dipnode->bytesN_in += payload_len; else dipnode->bytes_in += payload_len; } } pthread_mutex_unlock(&g_ipv6status_lock); return ok_to_go; } int print_ipv6_memory_info(void) { pthread_mutex_lock(&g_ipv6status_lock); multi_ntrie_print_memory(); hash_rbtree_print_memory(); pthread_mutex_unlock(&g_ipv6status_lock); return 0; } int cap_ipv6_ss_init(void) { int result; pthread_mutex_init(&g_ipv6status_lock,0); result=multi_ntrie_init(MemoryPoolSize1,MemoryPoolSize2); if(result) goto error1; result=hash_rbtree_init(&g_table); if(result) goto error2; return 0; error2: hash_rbtree_free(&g_table); error1: multi_ntrie_free(); return result; } void cap_ipv6_ss_exit(void) { hash_rbtree_free(&g_table); multi_ntrie_free(); }
1
#include <pthread.h> pthread_mutex_t countAccess = PTHREAD_MUTEX_INITIALIZER; sem_t block; int count = 0; int waiting = 0; bool mustwait = 0; unsigned long rdnumber() { unsigned long number; number = genrand_int32(); return number; } void *process(int pid) { while(1) { pthread_mutex_lock(&countAccess); if(mustwait){ waiting = waiting + 1; pthread_mutex_unlock(&countAccess); sem_wait(&block); waiting = waiting - 1; } count = count + 1; printf("process %2d start (%d)\\n", pid, count); if(count == 3){ printf("wait until clear\\n"); mustwait = 1; }else{ mustwait = 0; } if(waiting >0 && !mustwait){ sem_post(&block); }else{ pthread_mutex_unlock(&countAccess); } unsigned long time; time = rdnumber()%5+1; printf("process %2d runs %lu seconds\\n", pid, time); sleep(time); pthread_mutex_lock(&countAccess); count = count-1; printf("process %2d leave (%d)\\n", pid, count); if(count == 0){ mustwait = 0; } if(waiting >0 && !mustwait){ sem_post(&block); }else{ pthread_mutex_unlock(&countAccess); } } } int main(void) { int i = 0; pthread_t processes[10]; pthread_mutex_init(&countAccess, 0); sem_init(&block, 0, 0); for(i = 0; i < 10; i++) { if(pthread_create(&processes[i], 0, process, i) !=0) { printf("error\\n"); } } for(i = 0; i < 10; i++) pthread_join(processes[i],0); return 0; }
0
#include <pthread.h> long timeval_diff(struct timeval *t2, struct timeval *t1) { long diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec); return (diff); } void error(int err, char *msg) { fprintf(stderr,"%s a retourné %d, message d'erreur : %s\\n",msg,err,strerror(errno)); exit(1); } void usage(char *arg) { printf("Usage : %s percent nthreads\\n\\n",arg); printf(" percent: 0-100 pourcentage de temps en section critique\\n"); printf(" nthreads : nombre de threads à lancer\\n"); } int percent; int nthreads; pthread_mutex_t mutex; void critique() { long j=0; for(int i=0;i<(40000*percent)/100;i++) { j+=i; } } void noncritique() { int j=0; for(int i=0;i<(40000*(100-percent))/100;i++) { j-=i; } } void *func(void * param) { for(int j=0;j<40000/nthreads;j++) { pthread_mutex_lock(&mutex); critique(); pthread_mutex_unlock(&mutex); noncritique(); } return(0); } int main (int argc, char *argv[]) { int err; struct timeval tvStart, tvEnd; long mesures[4]; long sum=0; if(argc!=3) { usage(argv[0]); return(1); } char *endptr; percent=strtol(argv[1],&endptr,10); if(percent<1 || percent >100) { usage(argv[0]); return(1); } nthreads=strtol(argv[2],&endptr,10); if(nthreads<0) { usage(argv[0]); return(1); } pthread_t thread[nthreads]; err=pthread_mutex_init( &mutex, 0); if(err!=0) error(err,"pthread_mutex_init"); for (int j=0;j<4;j++) { err=gettimeofday(&tvStart, 0); if(err!=0) exit(1); for(int i=0;i<nthreads;i++) { err=pthread_create(&(thread[i]),0,&func,0); if(err!=0) error(err,"pthread_create"); } for(int i=nthreads-1;i>=0;i--) { err=pthread_join(thread[i],0); if(err!=0) error(err,"pthread_join"); } err=gettimeofday(&tvEnd, 0); if(err!=0) exit(1); mesures[j]=timeval_diff(&tvEnd, &tvStart); sum+=mesures[j]; } printf("%d, %d, %ld\\n",nthreads,percent,sum/4); err=pthread_mutex_destroy(&mutex); if(err!=0) error(err,"pthread_destroy"); return(0); }
1
#include <pthread.h> pthread_mutex_t m; int seed = 1; void* thr1(void* arg){ int nex, nexts, casret, nex_return, nC_return; casret = 0; while(casret == 0) { pthread_mutex_lock (&m); nex = seed; pthread_mutex_unlock (&m); nC_return = __VERIFIER_nondet_int (0, 1000); while (nC_return == nex || nC_return == 0) { nC_return = __VERIFIER_nondet_int(0, 1000); } nexts = nC_return; pthread_mutex_lock (&m); if (seed == nex) { seed = nexts; casret = 1; } else { casret = 0; } pthread_mutex_unlock (&m); } if (nexts < 10) { nex_return = nexts; } else { nex_return = 10; } __VERIFIER_assert (nex_return <= 10); return 0; } int main() { pthread_t t[5]; pthread_mutex_init (&m, 0); int i = 0; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t rlock; pthread_mutex_t wlock; pthread_mutex_t slock; pthread_t tid; int readcount; void intialize(){ pthread_mutex_init(&rlock,0); pthread_mutex_init(&wlock,0); readcount=0; } void * reader (void * a){ int waittime; waittime = rand() %5 ; printf("\\nReader No_%d is trying to enter (-_-)...",a); pthread_mutex_lock(&rlock); readcount++; if(readcount==1){ pthread_mutex_lock(&wlock); } printf("\\n(^_^) Success, there is/are %d Reader inside",readcount); pthread_mutex_unlock(&rlock); Sleep(waittime); pthread_mutex_lock(&rlock); readcount--; if(readcount==0){ pthread_mutex_unlock(&wlock); } pthread_mutex_unlock(&rlock); printf("\\nReader No_%d is Leaving ~(^_^)~ ",a); } void * writer (void * a){ int waittime; waittime=rand() % 3; printf("\\nWriter No_%d is trying to enter (-_-)...",a); pthread_mutex_lock(&wlock); printf("\\n(^_^) Success,Writer No_%d has entered",a); Sleep(waittime); pthread_mutex_unlock(&wlock); printf("\\nWriter No_%d is leaving (^_^)b",a); pthread_mutex_lock(&wlock); } int main(){ int n1,n2,i; printf("Enter the number of readers: "); scanf("%d",&n1); printf("Enter the number of writers: "); scanf("%d",&n2); intialize(); for(i=0;i<n1;i++){ pthread_create(&tid,0,reader,(void*)i+1); } for(i=0;i<n2;i++){ pthread_create(&tid,0,writer,(void*)i+1); } Sleep(500*i); printf("\\nTask complete !!!"); printf("\\nPress any to end:"); scanf("%d",&n1); exit(0); }
1
#include <pthread.h> int type; int amount; } transaction; int num; transaction *t_array; } transactions; int balance; pthread_mutex_t *balance_lock; transactions *new_transactions(int num){ int i; transactions * trs = (transactions*)malloc(sizeof(transactions)); trs->num = num; trs->t_array = (transaction*)malloc(sizeof(transaction) * num); for(i = 0; i < num; i++){ int q = rand() % 100; trs->t_array[i].amount = q; trs->t_array[i].type = q % 2; } return trs; } void *deposit_repeatedly(void *np){ transactions * t; t = (transactions*)np; int i; for(i = 0; i < t->num; i++){ int q; if(t->t_array[i].type == 1){ int bal; pthread_mutex_lock(balance_lock); bal = balance; pthread_mutex_unlock(balance_lock); if(bal + t->t_array[i].amount <= 100) bal += t->t_array[i].amount; pthread_mutex_lock(balance_lock); balance = bal; pthread_mutex_unlock(balance_lock); } } } void *withdraw_repeatedly(void *np){ transactions * t; t = (transactions*)np; int i; for(i = 0; i < t->num; i++){ int q; if(t->t_array[i].type == 0){ int bal; pthread_mutex_lock(balance_lock); bal = balance; pthread_mutex_unlock(balance_lock); if(bal - t->t_array[i].amount >= 0) bal -= t->t_array[i].amount; pthread_mutex_lock(balance_lock); balance = bal; pthread_mutex_unlock(balance_lock); } } } int main(int argv, char ** argc){ transactions * trs = new_transactions(100); transactions * trs2 = new_transactions(100); balance_lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(balance_lock,0); drp_tool_cg_init(); drp_watch(&balance); pthread_t dep, wit; pthread_create(&dep,0,deposit_repeatedly,(void*)trs); pthread_create(&wit,0,withdraw_repeatedly,(void*)trs); pthread_join(dep,0); pthread_join(wit,0); }
0
#include <pthread.h> unsigned int gSharedValue = 0; pthread_mutex_t gSharedMemoryLock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gReadPhase = PTHREAD_COND_INITIALIZER; pthread_cond_t gWritePhase = PTHREAD_COND_INITIALIZER; int gWaitingReaders = 0, gReaders = 0; int main(int argc, char **argv) { int i; int readerNum[5]; int writerNum[5]; pthread_t readerThreadIDs[5]; pthread_t writerThreadIDs[5]; srandom((unsigned int)time(0)); for(i = 0; i < 5; i++) { readerNum[i] = i; pthread_create(&readerThreadIDs[i], 0, readerMain, &readerNum[i]); } for(i = 0; i < 5; i++) { writerNum[i] = i; pthread_create(&writerThreadIDs[i], 0, writerMain, &writerNum[i]); } for(i = 0; i < 5; i++) { pthread_join(readerThreadIDs[i], 0); } for(i = 0; i < 5; i++) { pthread_join(writerThreadIDs[i], 0); } return 0; } void *readerMain(void *threadArgument) { int id = *((int*)threadArgument); int i = 0, numReaders = 0; for(i = 0; i < 5; i++) { usleep(1000 * (random() % 5 + 5)); pthread_mutex_lock(&gSharedMemoryLock); gWaitingReaders++; while (gReaders == -1) { pthread_cond_wait(&gReadPhase, &gSharedMemoryLock); } gWaitingReaders--; numReaders = ++gReaders; pthread_mutex_unlock(&gSharedMemoryLock); fprintf(stdout, "[r%d] reading %u [readers: %2d]\\n", id, gSharedValue, numReaders); pthread_mutex_lock(&gSharedMemoryLock); gReaders--; if (gReaders == 0) { pthread_cond_signal(&gWritePhase); } pthread_mutex_unlock(&gSharedMemoryLock); } pthread_exit(0); } void *writerMain(void *threadArgument) { int id = *((int*)threadArgument); int i = 0, numReaders = 0; for(i = 0; i < 5; i++) { usleep(1000 * (random() % 5 + 5)); pthread_mutex_lock(&gSharedMemoryLock); while (gReaders != 0) { pthread_cond_wait(&gWritePhase, &gSharedMemoryLock); } gReaders = -1; numReaders = gReaders; pthread_mutex_unlock(&gSharedMemoryLock); fprintf(stdout, "[w%d] writing %u* [readers: %2d]\\n", id, ++gSharedValue, numReaders); pthread_mutex_lock(&gSharedMemoryLock); gReaders = 0; if (gWaitingReaders > 0) { pthread_cond_broadcast(&gReadPhase); } else { pthread_cond_signal(&gWritePhase); } pthread_mutex_unlock(&gSharedMemoryLock); } pthread_exit(0); }
1
#include <pthread.h> int philosopher_number[5]; int philosopher_state[5]; int chopstick_state[5]; pthread_mutex_t chopsticks[5]; int randomWait(int bound) { int wait = rand() % bound; sleep(wait); return wait; } void useChopstick (int chopstick) { pthread_mutex_lock(&chopsticks[chopstick]); chopstick_state[chopstick] += 1; } void putDownChopstick (int chopstick) { pthread_mutex_unlock(&chopsticks[chopstick]); chopstick_state[chopstick] -= 1; } void eat (int philosopher) { useChopstick(philosopher); useChopstick((philosopher + 1) % 5); philosopher_state[philosopher] = 1; randomWait(5); } void finishEating (int philosopher) { putDownChopstick(philosopher); putDownChopstick((philosopher + 1) % 5); philosopher_state[philosopher] = 2; } void think (int philosopher) { randomWait(5); philosopher_state[philosopher] = 0; } void* philosophize (void* philosopher) { int id = *(int*) philosopher; printPhilosophers(); while (1) { printPhilosophers(); if (philosopher_state[id] == 2) { think(id); } else if (philosopher_state[id] == 0) { eat(id); } else if (philosopher_state[id] == 1) { finishEating(id); } } } void printPhilosophers () { int i; for (i = 0; i < 5; i++) { if (philosopher_state[i] == 2) { printf(" 0_0 "); } else if (philosopher_state[i] == 0) { printf(" -.- "); } else if (philosopher_state[i] == 1) { printf(" \\\\^0^/ "); } } printf("\\n"); } int main () { int i; pthread_t philosphers[5]; for (i = 0; i < 5; i++) { philosopher_state[i] = 2; philosopher_number[i] = i; chopstick_state[i] = 0; pthread_mutex_init(&chopsticks[i], 0); pthread_create(&philosphers[i], 0, philosophize, &philosopher_number[i]); } for (i = 0; i < 5; i++) { pthread_join(philosphers[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t tlock; pthread_cond_t qempty; pthread_cond_t qfull; int queue[1000]; int head, tail; int n; int insertions, extractions; int calculate_queue_size(void) { int current_size = 0; if (head==tail && head !=-1) { current_size = 1; } else if (head==tail && head==-1) { current_size = 0; } else if (tail<head) { current_size = (tail) + 1 + (1000 - head); } else if (tail>head) { current_size = (tail-head) + 1; } return current_size; } void *consumer(void *cdata) { int extracted; int inx = *((int *)cdata); while (1) { extracted = 0; pthread_mutex_lock(&tlock); int current_size = calculate_queue_size(); while(current_size <= 1){ pthread_cond_wait(&qfull, &tlock); current_size = calculate_queue_size(); } queue[head] = -1; head = (head+1)%1000; current_size--; extracted = 1; extractions++; pthread_cond_signal(&qempty); pthread_mutex_unlock(&tlock); } } void *producer(void *pdata) { int inserted; int i = 0; int inx = *((int *)pdata); while (1) { int val = inx + (i*n); inserted = 0; pthread_mutex_lock(&tlock); int current_size = calculate_queue_size(); while(current_size == 1000){ pthread_cond_wait(&qempty, &tlock); current_size = calculate_queue_size(); } queue[(tail+1)%1000] = val; tail = (tail+1)%1000; current_size++; if(current_size == 1){ head = tail; } inserted = 1; i++; insertions++; pthread_cond_signal(&qfull); pthread_mutex_unlock(&tlock); } } int main(int argc, char *argv[]){ int i; pthread_attr_t attr; double start_time, end_time; struct timeval tz; struct timezone tx; pthread_attr_init (&attr); pthread_attr_setscope (&attr,PTHREAD_SCOPE_SYSTEM); n = atoi(argv[1]); head = -1; tail = -1; insertions = 0; extractions = 0; pthread_t c_threads[n]; pthread_t p_threads[n]; int pinx[n]; int cinx[n]; pthread_cond_init(&qfull, 0); pthread_cond_init(&qempty, 0); pthread_mutex_init(&tlock, 0); printf("Processing.....\\n"); for(i=0;i<n;i++){ pinx[i] = i+1; cinx[i] = i+1; pthread_create(&c_threads[i], &attr, consumer,(void *) &cinx[i]); pthread_create(&p_threads[i], &attr, producer,(void *) &pinx[i]); } sleep(10); for(i=0;i<n;i++){ pthread_cancel(c_threads[i]); pthread_cancel(p_threads[i]); } printf("No of insertions %d\\n", insertions); printf("No of extractions %d\\n", extractions); printf("Total %d\\n", insertions+extractions); printf("Interval %d\\n", 10); printf("Throughput %lf\\n", (insertions+extractions)/(1.0*10)); return 0; }
1
#include <pthread.h> int account; pthread_mutex_t a_lock; } account; account *Accounts; pthread_mutex_t b_lock; } theBranch; static theBranch *Bank; static int nBranches, nAccounts; void makeBank(int num_branches, int num_accounts) { nBranches = num_branches; nAccounts = num_accounts; Bank = (theBranch *)malloc(nBranches * sizeof(theBranch)); pthread_mutexattr_t attr; pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutexattr_init(&attr); for (int i = 0; i < nBranches; i++) { Bank[i].Accounts = (account *)malloc(nAccounts * sizeof(account)); pthread_mutex_init(&(Bank[i].b_lock), &attr); for (int j = 0; j < nAccounts; j++) { Bank[i].Accounts[j].account = 0; pthread_mutex_init((&(Bank[i].Accounts[j].a_lock)), &attr); } } } void deleteBank(void) { for (int i = 0; i < nBranches; i++) free(Bank[i].Accounts); free(Bank); nBranches = nAccounts = 0; } int withdraw(int branch, int account, int value) { int rv, tmp; rv = 0; tmp = Bank[branch].Accounts[account].account - value; if (tmp >= 0) { Bank[branch].Accounts[account].account = tmp; rv = value; }; return rv; } int deposit(int branch, int account, int value) { Bank[branch].Accounts[account].account += value; return 0; } void transfer(int fromB, int toB, int account, int value) { if (fromB < toB) { pthread_mutex_lock(&(Bank[fromB].b_lock)); pthread_mutex_lock(&(Bank[toB].b_lock)); } else if (fromB > toB) { pthread_mutex_lock(&(Bank[toB].b_lock)); pthread_mutex_lock(&(Bank[fromB].b_lock)); } else return; int money = withdraw(fromB, account, value); if (money > 0) deposit(toB, account, money); if (fromB < toB) { pthread_mutex_unlock(&(Bank[toB].b_lock)); pthread_mutex_unlock(&(Bank[fromB].b_lock)); } else if (fromB > toB) { pthread_mutex_unlock(&(Bank[fromB].b_lock)); pthread_mutex_unlock(&(Bank[toB].b_lock)); } } void checkAssets(void) { static long assets = 0; long sum = 0; for (int i = 0; i < nBranches; i++) { for (int j = 0; j < nAccounts; j++) { sum += (long)Bank[i].Accounts[j].account; } } if (assets == 0) { assets = sum; printf("Balance of accounts is: %ld\\n", sum); } else { if (sum != assets) { printf("Balance of accounts is: %ld ... not correct\\n", sum); } else printf("Balance of accounts is: %ld ... correct\\n", assets); } }
0
#include <pthread.h> int NumPhilosophers; char* philosopherState; pthread_cond_t* eatTurn; pthread_mutex_t chopsticksDispute; pthread_t* philosophersThreads; int* seats; void philosophize(void* ptr); void philosophersStateInit(); void printPhilosophersState(char c, int seat); void initCondTurn(); void initPhilosophers(); void joinPhilosophers(); void parse(int argc, char** argv); void pickUp(int seat); void putDown(int seat); int main(int argc, char** argv) { parse(argc, argv); philosophersStateInit(); initCondTurn(); initPhilosophers(); joinPhilosophers(); exit(0); } void philosophize(void* ptr) { int seat = *(int*)ptr; printf("Seat teken: %d \\n", seat); while (1) { pickUp(seat); sleep(rand() % 10); putDown(seat); sleep(rand() % 10); } } void pickUp(int seat) { pthread_mutex_lock(&chopsticksDispute); printPhilosophersState('H', seat); while ( (philosopherState[((seat + (NumPhilosophers - 1)) % NumPhilosophers)] == 'E') || (philosopherState[(seat + 1) % NumPhilosophers] == 'E')) { pthread_cond_wait(&eatTurn[seat], &chopsticksDispute); } printPhilosophersState('E', seat); pthread_mutex_unlock(&chopsticksDispute); } void putDown(int seat) { pthread_mutex_lock(&chopsticksDispute); printPhilosophersState('T', seat); pthread_cond_signal(&eatTurn[(seat + 1) % NumPhilosophers]); pthread_cond_signal( &eatTurn[(seat + (NumPhilosophers - 1)) % NumPhilosophers]); pthread_mutex_unlock(&chopsticksDispute); } void initPhilosophers() { int i; seats = (int*)malloc(NumPhilosophers * sizeof(int)); if (seats == 0) printf("Error while allocating memory to seat numbers!\\n"); philosophersThreads = (pthread_t*)malloc(NumPhilosophers * sizeof(pthread_t)); if (philosophersThreads == 0) printf("Error while allocating memory to the Threads!\\n"); for (i = 0; i < NumPhilosophers; i++) { seats[i] = i; int err = pthread_create(&philosophersThreads[i], 0, (void*)&philosophize, (void*)&seats[i]); if (err != 0) { printf("Error initializing the threads!\\n"); exit(1); } } } void printPhilosophersState(char c, int seat) { philosopherState[seat] = c; printf("%s\\n", philosopherState); } void initCondTurn() { int i; eatTurn = (pthread_cond_t*)malloc(NumPhilosophers * sizeof(pthread_cond_t)); if (eatTurn == 0) printf("Error while allocating memory to the chopsticks!\\n"); for (i = 0; i < NumPhilosophers; i++) { pthread_cond_init(&eatTurn[i], 0); } pthread_mutex_init(&chopsticksDispute, 0); } void joinPhilosophers() { int i; for (i = 0; i < NumPhilosophers; i++) { pthread_join(philosophersThreads[i], 0); } } void philosophersStateInit() { int i; philosopherState = (char*)malloc(NumPhilosophers * sizeof(char)); if (philosopherState == 0) printf("Error while allocating memory to the philosophersState!\\n"); for (i = 0; i < NumPhilosophers; i++) { philosopherState[i] = 'T'; } } void parse(int argc, char** argv) { if (argc != 2) { printf( "The imput format should be ./semaphores_philosophers " "NUMBER_OF_PHILOSOPHER\\n"); exit(1); } NumPhilosophers = atoi((const char*)argv[1]); if (NumPhilosophers == 0) { printf( "If tere is no philosopher to take a seat the food will get cold! " "Enter a number higher or equal to 2.\\n"); exit(1); } else if (NumPhilosophers == 1) { printf( "Philosophers are not very realistic people and they need their " "friends chopsticks to eat, only one philosopher has only it's own " "chopstick, so he would starve forever... Enter a number higher or " "equal to 2.\\n"); exit(1); } }
1
#include <pthread.h> int main(int argc, char *argv[]) { pthread_mutex_t mutex; if(argc < 2) { printf("-usage: %s [error|normal|recursive]\\n",argv[1]); exit(1); } pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); if(strcmp(argv[1], "error")) { pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_ERRORCHECK); } else if(strcmp(argv[1], "normal")) { pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_NORMAL); } else if(strcmp(argv[1], "recursive")) { pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE); } pthread_mutex_init(&mutex, &mutexattr); if(pthread_mutex_lock(&mutex)!= 0) { perror("lock failed!"); exit(1); } else { printf("lock success\\n"); } if(pthread_mutex_lock(&mutex)!= 0) { perror("lock failed!"); exit(1); } else { printf("lock success\\n"); } pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex); pthread_mutexattr_destroy(&mutexattr); pthread_mutex_destroy(&mutex); return 0; }
0
#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; }
1
#include <pthread.h> struct finalize_info final; sem_t final_sem; int finalize_init(); int finalize_destroy(); int finalize_init(){ if(final.node == 0){ final.count = 0; final.node = tableCreate(MAX_NODE_NUM, sizeof(struct finalize_node)); sem_init(&final_sem, 0, 0); } return 1; } int finalize_destroy(){ final.count = 0; sem_destroy(&final_sem); tableDestroy(final.node); return 1; } int finalize_req(){ struct request_header req; int i; struct finalize_node *get; struct request_header reply; if(g_group.node_id == g_group.coordinator.main_id){ pthread_mutex_lock(&final.lock); finalize_init(); final.count++; if(final.count == g_group.node_num){ reply.msg_type = MSG_FINALIZE_OK; for(i=0; i<final.node->use; i++){ get = (struct finalize_node*)tableGetRow(final.node, i); reply.seq_number = get->seq_number; sendTo(get->id , (void*)&reply, sizeof(struct request_header)); } finalize_destroy(); pthread_mutex_unlock(&final.lock); } else{ pthread_mutex_unlock(&final.lock); sem_wait(&final_sem); } return 1; } req.msg_type = MSG_FINALIZE; sendRecv(g_group.coordinator.main_id, (void*)&req, sizeof(struct request_header), (void*)&req, sizeof(struct request_header)); return 1; } int finalize_reply(struct request_header *request){ int i; struct finalize_node node; struct finalize_node *get; struct request_header reply; pthread_mutex_lock(&final.lock); finalize_init(); node.id = request->src_node; node.seq_number= request->src_seq_number; tableAdd(final.node, (void*)&node, final.node->use); final.count++; if(final.count == g_group.node_num){ reply.msg_type = MSG_FINALIZE_OK; for(i=0; i<final.node->use; i++){ get = (struct finalize_node*)tableGetRow(final.node, i); reply.seq_number = get->seq_number; sendTo(get->id , (void*)&reply, sizeof(struct request_header)); } sem_post(&final_sem); finalize_destroy(); } pthread_mutex_unlock(&final.lock); return 1; }
0
#include <pthread.h> int do_debug = 0; int do_thread = 0; int do_stdin = 0; int do_sleep = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t rand_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t dice_mutexes[7] = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, }; int die_sizes[7] = { 4, 6, 8, 10, 12, 20, 100 }; int threadcount = 0; struct sockets { int local; FILE *in, *out; }; struct sockets *get_sockets(int); int socket_setup(void); int debug(char *, ...); int fail(char *, ...); int warn(char *, ...); int roll_die(int); void *roll_dice(void *); void spawn(struct sockets *); int debug(char *fmt, ...) { va_list ap; int r; __builtin_va_start((ap)); if (do_debug) { r = vfprintf(stderr, fmt, ap); } else { r = 0; } ; return r; } int warn(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); ; return r; } int fail(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); exit(1); ; return r; } int roll_die(int n) { int r; pthread_mutex_lock(&rand_mutex); r = rand() % n + 1; pthread_mutex_unlock(&rand_mutex); return r; } void * roll_dice(void *v) { struct sockets *s = v; char inbuf[512]; if (!s || !s->out || !s->in) return 0; fprintf(s->out, "enter die rolls, or q to quit\\n"); while (fgets(inbuf, sizeof(inbuf), s->in) != 0) { char *str = inbuf; int dice; int size; int i; if (inbuf[0] == 'q') { fprintf(s->out, "buh-bye!\\n"); if (s->local == 0) { shutdown(fileno(s->out), SHUT_RDWR); } fclose(s->out); fclose(s->in); if (s->local == 0) { free(s); } pthread_mutex_lock(&count_mutex); --threadcount; if (threadcount == 0) exit(0); pthread_mutex_unlock(&count_mutex); return 0; } while (strlen(str)) { if (sscanf(str, "%dd%d", &dice, &size) != 2) { fprintf(s->out, "Sorry, but I couldn't understand that.\\n"); *str = '\\0'; } else { int total = 0; pthread_mutex_t *die; if (strchr(str + 1, ' ')) { str = strchr(str + 1, ' '); } else { *str = '\\0'; } for (i = 0; i < 7; ++i) { if (die_sizes[i] == size) break; } if (i == 7) { fprintf(s->out, "The only dice on the table are a d4, a d6, a d8, a d10, a d12, a d20, and a d100.\\n"); continue; } die = &dice_mutexes[i]; pthread_mutex_lock(die); for (i = 0; i < dice; ++i) { int x = roll_die(size); total += x; fprintf(s->out, "%d ", x); fflush(s->out); if (do_sleep) sleep(1); } fprintf(s->out, "= %d\\n", total); pthread_mutex_unlock(die); } } } return 0; } int main(int argc, char *argv[]) { int o; int sock; while ((o = getopt(argc, argv, "dstS")) != -1) { switch (o) { case 'S': do_sleep = 1; break; case 'd': do_debug = 1; break; case 's': do_stdin = 1; break; case 't': do_thread = 1; break; } } if (do_thread) { int i; pthread_mutex_init(&count_mutex, 0); pthread_mutex_init(&rand_mutex, 0); for (i = 0; i < 7; ++i) { pthread_mutex_init(&dice_mutexes[i], 0); } } if (do_stdin) { struct sockets s; s.local = 1; s.in = stdin; s.out = stdout; if (do_thread) { spawn(&s); } else { roll_dice(&s); exit(0); } } sock = socket_setup(); while (1) { struct sockets *s = get_sockets(sock); if (s) { if (do_thread) { spawn(s); } else { roll_dice(s); exit(0); } } } return 0; } int socket_setup(void) { struct protoent *tcp_proto; struct sockaddr_in local; int r, s, one; tcp_proto = getprotobyname("tcp"); if (!tcp_proto) { fail("Can't find TCP/IP protocol: %s\\n", strerror(errno)); } s = socket(PF_INET, SOCK_STREAM, tcp_proto->p_proto); if (s == -1) { fail("socket: %s\\n", strerror(errno)); } one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_family = AF_INET; local.sin_port = htons(6173); r = bind(s, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (r == -1) { fail("bind: %s\\n", strerror(errno)); } r = listen(s, 5); if (r == -1) { fail("listen: %s\\n", strerror(errno)); } return s; } struct sockets * get_sockets(int sock) { int conn; if ((conn = accept(sock, 0, 0)) < 0) { warn("accept: %s\\n", strerror(errno)); return 0; } else { struct sockets *s; s = malloc(sizeof(struct sockets)); if (s == 0) { warn("malloc failed.\\n"); return 0; } s->local = 0; s->in = fdopen(conn, "r"); s->out = fdopen(conn, "w"); setlinebuf(s->in); setlinebuf(s->out); return s; } } void spawn(struct sockets *s) { pthread_t p; pthread_mutex_lock(&count_mutex); pthread_create(&p, 0, roll_dice, (void *) s); ++threadcount; pthread_mutex_unlock(&count_mutex); }
1
#include <pthread.h> int cnt; pthread_mutex_t mutex; } barrier; void* thread_func(void* i); barrier b; float *v, *v1, *v2, *mat; int k; int main(int argc, char** argv) { if (argc != 2) { printf("Syntax : %s k\\n", argv[0]); return 0; } k = atoi(argv[1]); v1 = (float*) malloc(k * sizeof(float)); v2 = (float*) malloc(k * sizeof(float)); mat = (float*) malloc(k * k * sizeof(float)); srand(time(0)); for (int i = 0; i < k; i++) { v1[i] = ((float)(rand() % 100) / 100) - 0.5; } for (int i = 0; i < k; i++) { v2[i] = ((float)(rand() % 100) / 100) - 0.5; } for(int i = 0; i < k; i++) { for (int j = 0; j < k; j++) { mat[k * i + j] = ((float)(rand() % 100) / 100) - 0.5; } } pthread_mutex_lock(&b.mutex); b.cnt = k; pthread_mutex_unlock(&b.mutex); v = (float*) malloc(k * sizeof(float)); pthread_t thread; int* pi; for (int i = 0; i < k; i++) { pi = (int*)malloc(sizeof(int)); *pi = i; pthread_create(&thread, 0, thread_func, pi); } pthread_exit(0); } void* thread_func(void* arg) { int* addr = arg; int i = *addr; v[i] = 0; for (int j = 0; j < k; j++) { v[i]+= mat[k * i + j] * v2[i]; } pthread_mutex_lock(&b.mutex); b.cnt--; if (b.cnt == 0) { float result = 0; for (int i = 0; i < k; i++) { result += v1[i] * v[i]; } printf("result = %f\\n", result); } pthread_mutex_unlock(&b.mutex); return addr; }
0
#include <pthread.h> struct list { int data; struct list *next; }; pthread_mutex_t global_lock; pthread_mutex_t local_lock; struct list *shared = 0; void *run(void *arg) { struct list *cur; pthread_mutex_lock(&global_lock); for (cur = shared; cur; cur = cur->next) { int *data = &cur->data; struct list *next = cur->next; cur->next = next; pthread_mutex_unlock(&global_lock); pthread_mutex_lock(&local_lock); (*data)++; pthread_mutex_unlock(&local_lock); pthread_mutex_lock(&global_lock); } pthread_mutex_unlock(&global_lock); return 0; } int main() { pthread_t t1, t2; int i; pthread_mutex_init(&global_lock, 0); pthread_mutex_init(&local_lock, 0); for (i = 0; i < 42; i++) { struct list *new = (struct list *) malloc(sizeof(struct list)); new->data = 1; new->next = shared; shared = new; } pthread_create(&t1, 0, run, 0); pthread_create(&t2, 0, run, 0); return 1; }
1
#include <pthread.h> int number = 0; pthread_t id[2]; pthread_mutex_t mut; void thread1(void) { int i; printf("Hello, I am pthread1!\\n"); for (i = 0; i < 3; i++) { pthread_mutex_lock(&mut); number++; printf("THread1: number = %d\\n", number); pthread_mutex_unlock(&mut); sleep(1); } pthread_exit(0); } void thread2(void) { int i; printf("Hello, I am pthread2!\\n"); for (i = 0; i < 3; i++) { pthread_mutex_lock(&mut); number++; printf("THread2: number = %d\\n", number); pthread_mutex_unlock(&mut); sleep(1); } pthread_exit(0); } void thread_create(void) { int temp; memset(&id, 0, sizeof(id)); if (temp = pthread_create(&id[0], 0, (void*)thread1, 0) != 0) { printf("Thread1 fail to create!\\n"); } else { printf("Thread 1 create!\\n"); } if (temp = pthread_create(&id[1], 0, (void*)thread2, 0) != 0) { printf("Thread 2 fail to create!\\n"); } else { printf("Thread 2 create!\\n"); } } void thread_wait() { if (id[0] != 0) { pthread_join(id[0], 0); printf("Thread 1 completed!\\n"); } if (id[1] != 0) { pthread_join(id[1], 0); printf("Thread 2 completed!\\n"); } } int main(int argc, char *argv[]) { int i, ret1, ret2; pthread_mutex_init(&mut, 0); printf("Main function, creating thread...\\n"); thread_create(); printf("Main function, waiting for the pthread end!\\n"); thread_wait(); return (0); }
0
#include <pthread.h> char SPLIT_CHAR[] = {' ', '\\n', '<'}; int STRING_LENGTH = 41; FILE *fp; int sharedByteRead = 0; int sharedTotalCount = 0; pthread_mutex_t lock; void *countByte(void *param){ char *buf = param; int TARGET_SIZE = strlen(buf); int DIFF_LENGTH = TARGET_SIZE - STRING_LENGTH; for (int i = 0 ; i <= DIFF_LENGTH ; i++){ if (strncmp(&buf[i], STRING, STRING_LENGTH) == 0){ pthread_mutex_lock(&lock); sharedTotalCount++; pthread_mutex_unlock(&lock); } } return 0; } void countKUY(){ FILE *fp = fopen("./test.nt", "rb"); char buf[100000] = { 0 }; fscanf(fp, "%s", buf); int TARGET_SIZE = strlen(buf); int DIFF_LENGTH = TARGET_SIZE - STRING_LENGTH; for (int i = 0 ; i < DIFF_LENGTH ; i++){ if (strncmp(&buf[i], STRING, STRING_LENGTH) == 0){ sharedTotalCount += 1; } } } int main(){ pthread_t thread[4]; if (pthread_mutex_init(&lock, 0) != 0){ fprintf(stderr, "\\n mutex initialization failed\\n"); return 1; } fp = fopen("./test.nt", "rb"); char buf[1000 + 1]; size_t nread; int i; int err; memset(buf, 0, sizeof(buf)); if(fp){ i = 0; while( (nread = fread(buf, sizeof(char), 1000, fp)) > 0){ buf[nread] = 0; if(!feof(fp)) { while(!strchr(SPLIT_CHAR, fgetc(fp))) { buf[--nread] = '\\0'; fseek(fp, -2, 1); } fseek(fp,-1,1); } err = pthread_create(&(thread[i]), 0, &countByte, (void *) buf); if (err){ fprintf(stderr, "\\n cannot create thread[%d]: %s", i, strerror(err)); return 1; } pthread_join(thread[i], 0); i = (i + 1) % 4; } if(ferror(fp)){ fprintf(stderr, "\\n error reading file\\n"); return 1; } } fclose(fp); pthread_mutex_destroy(&lock); printf("Total count: %d", sharedTotalCount); return 0; }
1
#include <pthread.h> int fd; pthread_mutex_t mutex; uint8_t ucRev; uint8_t ucOptAv; } xChipIo; xChipIo * xChipIoOpen (const char * sI2cBus, int iSlaveAddr) { xChipIo * chip = malloc (sizeof (xChipIo) ); if (chip) { int iReg; memset (chip, 0, sizeof (xChipIo) ); chip->fd = iI2cOpen (sI2cBus, iSlaveAddr); if (chip->fd < 0) { goto open_error_exit; } pthread_mutex_init (&chip->mutex, 0); iReg = iChipIoReadReg8 (chip, eRegRev); if (iReg >= 0) { chip->ucRev = iReg; } iReg = iChipIoReadReg8 (chip, eRegOptAv); if (iReg >= 0) { chip->ucOptAv = iReg; } } return chip; open_error_exit: free (chip); return 0; } int iChipIoRevisionMajor (xChipIo * chip) { return (unsigned) chip->ucRev >> 4; } int iChipIoRevisionMinor (xChipIo * chip) { return (unsigned) chip->ucRev & 0x0F; } int iChipIoAvailableOptions (xChipIo * chip) { return (unsigned) chip->ucOptAv; } int iChipIoClose (xChipIo * chip) { if (chip) { int iRet = iI2cClose (chip->fd); free (chip); return iRet; } return 0; } int iChipIoReadReg8 (xChipIo * chip, uint8_t reg) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cReadReg8 (chip->fd, reg); pthread_mutex_unlock (&chip->mutex); return iRet; } int iChipIoReadReg16 (xChipIo * chip, uint8_t reg) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cReadReg16 (chip->fd, reg); pthread_mutex_unlock (&chip->mutex); return iRet; } int iChipIoReadRegBlock (xChipIo * chip, uint8_t reg, uint8_t * buffer, uint8_t size) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cReadRegBlock (chip->fd, reg, buffer, size); pthread_mutex_unlock (&chip->mutex); return iRet; } int iChipIoWriteReg8 (xChipIo * chip, uint8_t reg, uint8_t data) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cWriteReg8 (chip->fd, reg, data); pthread_mutex_unlock (&chip->mutex); return iRet; } int iChipIoWriteReg16 (xChipIo * chip, uint8_t reg, uint16_t data) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cWriteReg16 (chip->fd, reg, data); pthread_mutex_unlock (&chip->mutex); return iRet; } int iChipIoWriteRegBlock (xChipIo * chip, uint8_t reg, const uint8_t * buffer, uint8_t size) { int iRet; pthread_mutex_lock (&chip->mutex); iRet = iI2cWriteRegBlock (chip->fd, reg, buffer, size); pthread_mutex_unlock (&chip->mutex); return iRet; }
0
#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++) { 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++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int sem_wait(sem_t *sem) { int result = 0; if (!sem) { result = EINVAL; } else if (!pthread_mutex_lock(&sem->mutex)) { if (--(sem->value) < 0) { pthread_cond_wait(&sem->cond, &sem->mutex); } pthread_mutex_unlock(&sem->mutex); } else { result = EINVAL; } if (result) { errno = result; return -1; } return 0; }
0
#include <pthread.h> { double a[12000000/3]; double globalsum[50]; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[3]; pthread_mutex_t mutexsum; double x[12000000]; double moments[50]; void generate_data(double *destination, int n, double xmin, double xlimit, int seed){ int i; double scale; srandom(seed); scale=(xlimit-xmin)/32767; for (i=0;i<n;++i){ destination[i]= xmin+scale*random(); } } void sum_moments(double *data, int n, double *result, int m){ double term; int i,j; for (j=0;j<m;++j) result[j]=0; for (i=0;i<n;++i){ for (j=0, term=x[i]; j<m; ++j,term*=x[i]){ result[j]+= term; } } } double time_in_seconds(struct timespec *t){ return (t->tv_sec + 1.0e-9 * (t->tv_nsec)); } void *thrdcalldis(void *arg){ int i, start,end,len; long offset; double *mysum; double *anotherx; offset=(long) arg; len=dotstr.veclen; start=offset*len; end=start+len; anotherx=(double*)malloc(12000000/3*sizeof(double)); mysum = (double*)malloc(50*sizeof(double)); for(int iter=0;iter<12000000/3;iter++){ anotherx[iter]=dotstr.a[iter]; } sum_moments(anotherx,(12000000/3 -1),mysum,50); pthread_mutex_lock(&mutexsum); for(int it=0;it<50;it++){ dotstr.globalsum[it]+= mysum[it]; } pthread_mutex_unlock(&mutexsum); pthread_exit((void*)0); } int main(){ struct timespec start, finish, resolution, calculation; double calculation_time, start_time, finish_time; int err; long i; time_t startsec; err=clock_getres(CLOCK_THREAD_CPUTIME_ID,&resolution); if (err){ perror("Failed to get clock resolution"); exit(1); } printf("Main: thread clock resolution = %-16.9g seconds\\n",time_in_seconds(&resolution)); generate_data(x,12000000,0.0,2.0,123); printf("Main: generated %d data values in the range %5.3f to %5.3f, seed=%d\\n", 12000000, 0.0, 2.0, 123); err=clock_gettime(CLOCK_THREAD_CPUTIME_ID,&start); if (err){ perror("Failed to read thread_clock with error = %d\\n"); exit(1); } startsec = time(0); printf("Main: calculation start time = %-20.9g seconds\\n",time_in_seconds(&start)); double *a; void *status; pthread_attr_t attr; time_t endsec; a=(double*)malloc(12000000*sizeof(double)); for(int iterator=0;iterator<12000000;iterator++){ dotstr.a[iterator]=x[iterator]; } dotstr.veclen=12000000; for(int iterator=0;iterator<50;iterator++){ dotstr.globalsum[iterator]=0; } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); for(i=0;i<3;i++){ pthread_create(&callThd[i],&attr,thrdcalldis,(void*)i); } pthread_attr_destroy(&attr); for(i=0;i<3;i++){ pthread_join(callThd[i],&status); } for(i=0;i<50;++i){ moments[i]=dotstr.globalsum[i]; } for (i=0;i<50;++i) moments[i] /= 12000000; free(a); endsec = time(0); err=clock_gettime(CLOCK_THREAD_CPUTIME_ID,&finish); if (err){ perror("Failed to read thread_clock with error = %d\\n"); exit(1); } printf("\\n\\n Number of threads used %d \\n\\nMain: calculation finish time = %-20.9g seconds\\n",3,time_in_seconds(&start)+endsec-startsec); calculation_time = time_in_seconds(&finish)-time_in_seconds(&start); printf("Calculation elapsed time = %ld seconds\\n",endsec-startsec); printf("\\n==================== MOMENT RESULTS ======================\\n"); printf("%5s %30s %30s\\n","m","moment","Expected"); printf("%5s %30s %30s\\n","-","------","--------"); for(i=0;i<50;++i){ printf("%5d %30.16e %30.16e\\n",i+1,moments[i], 0.5*(pow(2.0,i+2)-pow(0.0,i+2))/(i+2)); } printf("\\n\\n Number of threads used %d \\n\\nMain: time elapsed = %ld seconds\\n",3,endsec-startsec); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> void* thread1(void*); void* thread2(void*); void* thread3(void*); pthread_mutex_t m; void main(){ printf("Main start..!"); pthread_t tid1,tid2,tid3; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&m,0); pthread_create(&tid1,&attr,thread1,0); pthread_create(&tid2,&attr,thread2,0); pthread_create(&tid3,&attr,thread3,0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); printf("Main end..!!"); } void* thread1(void* str){ pthread_mutex_lock(&m); printf("Start of thread 1 execution\\n"); FILE *file; file = fopen("temp.txt","w"); fprintf(file,"Contents generated by Thread 1..\\n"); for(int i=0;i<10;i++){ fprintf(file,"%d\\n",i); } fclose(file); printf("End of thread 1 execution\\n"); pthread_mutex_unlock(&m); pthread_exit(0); } void* thread2(void* str){ pthread_mutex_lock(&m); printf("Start of thread 2 execution\\n"); FILE *file; file = fopen("temp.txt","a+"); fprintf(file,"Contents generated by Thread 2..\\n"); for(int i=11;i<20;i++) { fprintf(file,"%d\\n",i); } fclose(file); printf("End of thread 2 execution\\n"); pthread_mutex_unlock(&m); pthread_exit(0); } void* thread3(void* str){ pthread_mutex_lock(&m); printf("Start of thread 3 execution\\n"); FILE *file; FILE *result; char content[20]; file = fopen("temp.txt","r"); result = fopen("result.txt","w"); while(fscanf(file,"%s",content) != EOF){ fprintf(result,"%s\\n",content); } fclose(file); fclose(result); printf("End of thread 3 execution\\n"); pthread_mutex_unlock(&m); pthread_exit(0); }
0
#include <pthread.h> sem_t empty_pot,full_pot; static pthread_mutex_t servings_mutex; static pthread_mutex_t print_mutex; static int servings=15; void *Savage(void *id) { int savage_id=*(int *)id; while(1) { pthread_mutex_lock(&servings_mutex); if(servings==0) { sem_post(&empty_pot); printf("\\nSavage %d signalled the cook\\n", savage_id); sem_wait(&full_pot); servings=15; } servings--; printf("Servings--->%d\\n", servings); pthread_mutex_lock(&print_mutex); printf("Savage %d is eating\\n", savage_id); pthread_mutex_unlock(&print_mutex); pthread_mutex_unlock(&servings_mutex); sleep(2); pthread_mutex_lock(&print_mutex); printf("Savage %d is DONE eating\\n", savage_id); pthread_mutex_unlock(&print_mutex); } pthread_exit(0); } void Cook(void *cid) { while(1) { sem_wait(&empty_pot); printf("\\nCook filled the pot\\n\\n"); sem_post(&full_pot); } pthread_exit(0); } int main(void) { int i, id[3]; pthread_t tid[3]; pthread_mutex_init(&servings_mutex,0); pthread_mutex_init(&print_mutex,0); sem_init(&empty_pot, 0, 0); sem_init(&full_pot, 0, 0); for (i = 0; i < 3; ++i) { id[i]=i; pthread_create(&tid[i],0,(void *)Savage,(void *)&id[i]); } pthread_create(&tid[i],0,(void *)Cook,(void *)&id[i]); for (i=0; i<3; i++) pthread_join(tid[i], 0); pthread_join(tid[i],0); return(0); }
1
#include <pthread.h> int sem1; int cleanup_flag; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void a_cleanup_func() { cleanup_flag=1; return; } void *a_thread_func() { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_cleanup_push(a_cleanup_func,0); sem1=1; if(pthread_mutex_lock(&mutex) != 0) { perror("Error in pthread_mutex_lock()\\n"); pthread_exit((void*)PTS_UNRESOLVED); return (void*)PTS_UNRESOLVED; } cleanup_flag=-1; pthread_cleanup_pop(0); pthread_exit(0); return 0; } int main() { pthread_t new_th; int i=0; sem1=0; cleanup_flag=0; if(pthread_mutex_lock(&mutex) != 0) { perror("Error in pthread_mutex_lock()\\n"); return PTS_UNRESOLVED; } if(pthread_create(&new_th, 0, a_thread_func, 0) != 0) { perror("Error creating thread\\n"); return PTS_UNRESOLVED; } while(sem1==0) sleep(1); if(pthread_cancel(new_th) != 0) { perror("Test FAILED: Error in pthread_cancel()\\n"); return PTS_UNRESOLVED; } while((cleanup_flag == 0) && (i != 10)) { sleep(1); i++; } pthread_mutex_unlock(&mutex); if(cleanup_flag <= 0) { printf("Test FAILED: Cancel request timed out\\n"); return PTS_FAIL; } printf("Test PASSED\\n"); return PTS_PASS; }
0
#include <pthread.h> void mux_3_pcsource(void *not_used){ pthread_barrier_wait(&threads_creation); while(1){ pthread_mutex_lock(&control_sign); if(!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } char control = (((separa_PCSource0 | separa_PCSource1) & cs.value) >> PCSource0_POS) & 0x03; if(control == 0){ pthread_mutex_lock(&alu_result_mutex); if(!alu_result.isUpdated) while(pthread_cond_wait(&alu_result_wait,&alu_result_mutex) != 0); pthread_mutex_unlock(&alu_result_mutex); mux_pcsource_buffer.value = alu_result.value; } else{ if (control == 1){ mux_pcsource_buffer.value = aluout; } else { pthread_mutex_lock(&pc_shift_left_result); if(!pc_shift_left_buffer.isUpdated) while(pthread_cond_wait(&pc_shift_left_execution_wait,&pc_shift_left_result) != 0); pthread_mutex_unlock(&pc_shift_left_result); mux_pcsource_buffer.value = pc_shift_left_buffer.value; } } pthread_mutex_lock(&mux_pcsource_result); mux_pcsource_buffer.isUpdated = 1; pthread_cond_signal(&mux_pcsource_execution_wait); pthread_mutex_unlock(&mux_pcsource_result); pthread_barrier_wait(&current_cycle); mux_pcsource_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
1
#include <pthread.h> pthread_mutex_t mutex[5]; void* philosopher(void* arg) { int *number; number=(int*) arg; while(1) { printf("philosopher %d is thinking\\n",*number ); sleep(2); pthread_mutex_lock(&mutex[*number]); printf("philosopher %d is waiting for eating(handle a chopstick)\\n",*number ); sleep(2); pthread_mutex_lock(&mutex[(*number+1)%5]); printf("philosopher %d is eating\\n",*number ); pthread_mutex_unlock(&mutex[*number]); pthread_mutex_unlock(&mutex[(*number+1)%5]); } } int main(int argc, char const *argv[]) { pthread_mutex_t mutex; pthread_mutex_init(&mutex,0); pthread_t tid1,tid2,tid3,tid4,tid5; int test1 = 0; int *attr1 = &test1; int test2 = 1; int *attr2 = &test2; int test3 = 2; int *attr3 = &test3; int test4 = 3; int *attr4 = &test4; int test5 = 4; int *attr5 = &test5; pthread_create(&tid1,0,(void*)philosopher,(void*)attr1); pthread_create(&tid2,0,(void*)philosopher,(void*)attr2); pthread_create(&tid3,0,(void*)philosopher,(void*)attr3); pthread_create(&tid4,0,(void*)philosopher,(void*)attr4); pthread_create(&tid5,0,(void*)philosopher,(void*)attr5); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); pthread_join(tid5,0); return 0; }
0
#include <pthread.h> int numCookies =10; int tid; } thread_param; pthread_mutex_t mutex; void* thread_consumer_func(void* pthread_arg) { thread_param* myParam = (thread_param*) pthread_arg; int cookiesRetrieved =0; while(cookiesRetrieved<15) { pthread_mutex_lock(&mutex); if(numCookies>0) { numCookies--; cookiesRetrieved++; } pthread_mutex_unlock(&mutex); } } void* thread_producer_func(void* pthread_arg) { int cookiesPlaced =0; while(cookiesPlaced<30) { pthread_mutex_lock(&mutex); if(numCookies<9) { numCookies+=2; cookiesPlaced+=2; } else if(numCookies ==9) { numCookies++; cookiesPlaced++; } pthread_mutex_unlock(&mutex); } } int main(void) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&mutex,0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); thread_param *thread_params = (thread_param* ) malloc(sizeof(thread_param)*3); pthread_t * threads = (pthread_t*)malloc(sizeof(pthread_t)*3); int i,rc; for(i=0; i<3; i++) { thread_param* input = &thread_params[i]; input->tid = i; if(i==0) { rc = pthread_create(&threads[i],&attr, thread_producer_func,(void*) &thread_params[i]); } else { rc = pthread_create(&threads[i],&attr, thread_consumer_func,(void*) &thread_params[i]); } if(rc!=0) { printf("creating thread failed\\n"); } } pthread_attr_destroy(&attr); for(i=0; i<3; i++) { rc = pthread_join(threads[i],0); if(rc!=0) { printf("joining thread failed\\n"); } } free(thread_params); free(threads); return 0; }
1
#include <pthread.h> static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond=PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head=0; static void cleanup_handler(void*arg) { printf("Clean up handler of second thread.\\n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node*p=0; pthread_cleanup_push(cleanup_handler,p); pthread_mutex_lock(&mtx); while(1) { while(head==0) { pthread_cond_wait(&cond,&mtx); } p=head; head=head->n_next; printf("Got%dfromfrontofqueue\\n",p->n_number); free(p); } pthread_mutex_unlock(&mtx); pthread_cleanup_pop(0); return 0; } int main(void) { pthread_t tid; int i; struct node *p; pthread_create(&tid,0,thread_func,0); for(i=0;i<10;i++) { p=(struct node*)malloc(sizeof(struct node)); p->n_number=i; pthread_mutex_lock(&mtx); p->n_next=head; head=p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread1wannaendthecancelthread2.\\n"); pthread_cancel(tid); pthread_join(tid,0); printf("Alldone--exiting\\n"); return 0; }
0
#include <pthread.h> static char envbuf[1000]; extern char **environ; char *getenv(const char *name){ int i,len; len = strlen(name); for ( i=0;environ[i] != 0; i++ ){ if ((strncmp(name,environ[i],len) == 0) && (environ[i] == '=') ){ strcpy(envbuf,&environ[i][len+1]); return envbuf; } } return 0; } pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void){ pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE_NP); pthread_mutex_init(&env_mutex,&attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf,int buflen){ int i,len,olen; pthread_once(&init_done,thread_init); len = strlen(name); pthread_mutex_lock(&env_mutex); for ( i=0;environ[i] != 0;i++) { if ( (strncmp(name,environ[i],len) == 0) && (environ[i][len] == '=') ) { olen = strlen(&environ[i][len+1]); if ( olen >= buflen ) { pthread_mutex_unlock(&env_mutex); return ENOSPC; } strcpy(buf,&environ[i][len+1]); pthread_mutex_unlock(&env_mutex); return 0; } } pthread_mutex_unlock(&env_mutex); return ENOENT; } int main(int argc,char *argv[]){ char buf[256],*temp; printf("getenv call \\n"); temp = getenv("PATH"); printf("getenv =%s\\n",temp); printf("getenv_r call \\n"); getenv_r("PATH",buf,256); printf("buf=%s\\n",buf); exit(0); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char *getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *) pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(256); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strcpy(envbuf, &environ[i][len + 1]); pthread_mutex_unlock(&env_mutex); return (envbuf); } } pthread_mutex_unlock(&env_mutex); return (0); }
0
#include <pthread.h> long mtype; char mtext[128]; } message_buf; char file[][10]={"a.txt","b.txt","c.txt","d.txt","e.txt"}; pthread_mutex_t lock; int msqid; void *send(void *name) { if ((msqid = msgget(123,IPC_CREAT|0666)) < 0) { printf("exit\\n"); exit(0); } size_t buf_length; message_buf sbuf; printf("n=%d\\n",*(int *)name ); pthread_mutex_lock(&lock); int n = *(int *)name ; sbuf.mtype = n; (void) strcpy(sbuf.mtext,file[n]); buf_length = strlen(sbuf.mtext) + 1 ; printf("%s\\n",sbuf.mtext ); if (msgsnd(msqid, &sbuf, buf_length, IPC_NOWAIT) < 0) { exit(1); } else printf("send=%s-%d\\n",file[n],n); pthread_mutex_unlock(&lock); } int main(int argc, char const *argv[]) { pthread_t p1[5]; int i=0; int a[5]={0,1,2,3,4}; for ( i = 0; i < 5; i++) { pthread_create(&p1[i],0,send,&a[i]); } for (int j = 0; j < 5; j++) { pthread_join(p1[j],0); } return 0; }
1
#include <pthread.h> pthread_mutex_t lock; struct shared { int counter; char msg[10]; }; uint64_t gettid() { pthread_t ptid = pthread_self(); return (uint64_t) ptid; } void* mythread_entry(void *args) { struct shared *SharedCounter = (struct shared*)args; for(int i=0; i<1000; i++) { pthread_mutex_lock(&lock); SharedCounter->counter += 1; pthread_mutex_unlock(&lock); } pthread_exit(0); } int main() { int i, retCode; struct shared *SharedCounter = (struct shared *)malloc(sizeof(struct shared)); retCode = pthread_mutex_init(&lock, 0); if(retCode != 0) printf("Lock failed"); pthread_t mythread[100]; for(i=0; i<100; i++) { retCode = pthread_create(&mythread[i], 0, &mythread_entry, SharedCounter); if(retCode == -1) { printf("Thread_create failed"); return -1; } } for( i=0; i<100; i++) { pthread_join(mythread[i], 0); printf("main says Running\\n"); } printf("Final SharedCounter: %d\\t Expected: %d\\n", SharedCounter->counter, 100*1000); free(SharedCounter); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; struct arg{ int i; }; void cal(int i, void* p); static void* func(void *p); int main(int argc, const char *argv[]) { int err, i; pthread_t tid[4]; for (i = 0; i < 4; i++) { err = pthread_create(tid+i, 0, func, (void*)i); if (err) { fprintf(stderr, "pthread_create():%s\\n", strerror(err)); exit(1); } } for (i = 30000000; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while (num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = i; pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while (num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num=-1; pthread_mutex_unlock(&mut_num); for (i = 0; i < 4; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mut_num); exit(0); } static void* func(void *p) { int i; while (1) { pthread_mutex_lock(&mut_num); while (num == 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } if (num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_mutex_unlock(&mut_num); cal(i, p); } pthread_exit(0); } void cal(int i, void* p) { int j,mark; mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); }
1
#include <pthread.h> int global; pthread_mutex_t glock; int local[4]; pthread_mutex_t llock[4]; int threshold; } counter_t; void init(counter_t *c, int threshold) { c->threshold = threshold; c->global = 0; pthread_mutex_init(&(c->glock), 0); int i; for (i = 0; i < 4; i++) { c->local[i] = 0; pthread_mutex_init(&c->llock[i], 0); } } void update(counter_t *c, int threadID, int amt) { int cpu = threadID % 4; pthread_mutex_lock(&c->llock[cpu]); c->local[cpu] += amt; if (c->local[cpu] >= c->threshold) { pthread_mutex_lock(&c->glock); c->global += c->local[cpu]; pthread_mutex_unlock(&c->glock); c->local[cpu] = 0; } pthread_mutex_unlock(&c->llock[cpu]); } int get(counter_t *c) { pthread_mutex_lock(&c->glock); int val = c->global; pthread_mutex_unlock(&c->glock); return val; }
0
#include <pthread.h> int nbPB; pthread_t thBus; pthread_t thPassagers [45]; pthread_mutex_t mutex_places; pthread_cond_t cond_busVide; pthread_cond_t cond_busPlein; pthread_cond_t cond_finVisite; pthread_cond_t cond_busPret; } bus_t; static bus_t bus = { .nbPB = 0, .mutex_places = PTHREAD_MUTEX_INITIALIZER, .cond_busVide = PTHREAD_COND_INITIALIZER, .cond_busPlein = PTHREAD_COND_INITIALIZER, .cond_finVisite = PTHREAD_COND_INITIALIZER, .cond_busPret = PTHREAD_COND_INITIALIZER, }; static void * fn_bus (void * p_data) { while (1) { pthread_mutex_lock (& bus.mutex_places); if (bus.nbPB < 40) { pthread_cond_wait(& bus.cond_busPlein, & bus.mutex_places); } printf ("Le bus a atteint le nombre de passagers maximum.\\n Départ imminent !\\n"); sleep(4); printf("Fin de la visite.\\n Descente des passagers...\\n"); sleep(1); pthread_cond_broadcast(& bus.cond_finVisite); pthread_cond_wait(& bus.cond_busVide, & bus.mutex_places); if( bus.nbPB == 0){ printf("Bus vide. Les prochains passagers peuvent monter.\\n"); pthread_cond_broadcast (& bus.cond_busPret); } } pthread_mutex_unlock (& bus.mutex_places); return 0; } static void * fn_passager (void * p_data) { int id = (int )(intptr_t)p_data; while (1) { pthread_mutex_lock (& bus.mutex_places); if (bus.nbPB < 40){ bus.nbPB ++; printf(" Un passager %d est monté.\\n Nombre de passagers à bord : %d \\n", id, bus.nbPB); if (bus.nbPB ==40) { pthread_cond_signal (& bus.cond_busPlein); } pthread_cond_wait (& bus.cond_finVisite, & bus.mutex_places); bus.nbPB --; printf("Un passager %d est descendu.\\n Nombre de passagers à bord : %d\\n ",id, bus.nbPB); } if (bus.nbPB == 0){ printf("Le bus est vide.\\n "); pthread_cond_broadcast (& bus.cond_busVide); pthread_cond_wait (& bus.cond_busPret, & bus.mutex_places); } pthread_mutex_unlock(& bus.mutex_places); } return 0; } int main (void) { int i = 0; int ret = 0; printf ("Creation du thread bus !\\n"); ret = pthread_create ( & bus.thBus, 0, fn_bus, 0 ); if (! ret) { printf ("Creation des threads passagers !\\n"); for (i = 0; i < 45; i++) { ret = pthread_create ( & bus.thPassagers [i], 0, fn_passager, (void *) i); if (ret) { fprintf (stderr, "%s", strerror (ret)); } } } else { fprintf (stderr, "%s", strerror (ret)); } i = 0; for (i = 0; i < 45; i++) { pthread_join (bus.thPassagers [i], 0); } pthread_join (bus.thBus, 0); return 0; }
1
#include <pthread.h> static struct packet_buffer pktbuf; static struct packet_buffer_t *full_packet = 0; static int packet_buffer_count = 0; static int front = 0, rear = 0; static int bufuse = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int pktbuf_num_of_buffers (void) { return packet_buffer_count; } static int pktbuf_num_of_freebuf (void) { return packet_buffer_count - bufuse; } static struct packet_buffer_t *request (void) { int i; if (bufuse == packet_buffer_count) return 0; i = front; front = (front + 1) % packet_buffer_count; pthread_mutex_lock (&mutex); bufuse++; pthread_mutex_unlock (&mutex); return &full_packet[i]; } static struct packet_buffer_t *retrieve (void) { if (bufuse == 0) return 0; if (full_packet[rear].buffer_ready == 0) return 0; return &full_packet[rear]; } static void bufready (struct packet_buffer_t *ptr) { ptr->buffer_ready = 1; } static void dequeue (struct packet_buffer_t *pkt) { int i; if (bufuse > 0) { i = rear; full_packet[i].buffer_ready = 0; rear = (rear + 1) % packet_buffer_count; pthread_mutex_lock (&mutex); bufuse--; pthread_mutex_unlock (&mutex); } } static void pktbuf_close (void) { int len; len = packet_buffer_count; packet_buffer_count = 0; front = rear = bufuse = 0; free (full_packet); } static int pktbuf_count (void) { return bufuse; } struct packet_buffer *init_packet_buffer_v1 (const int number_of_buffer) { int i; fprintf (stderr, "Allocate %d packet buffer ... ", number_of_buffer); if ((full_packet = utils_calloc (number_of_buffer, sizeof (struct packet_buffer_t))) == 0) { fprintf (stderr, "error\\n"); return 0; } for (i = 0; i < packet_buffer_count; i++) { full_packet[i].buffer_ready = 0; } packet_buffer_count = number_of_buffer; fprintf (stderr, "ok\\n"); front = rear = bufuse = 0; pktbuf.request = &request; pktbuf.retrieve = &retrieve; pktbuf.dequeue = &dequeue; pktbuf.ready = &bufready; pktbuf.close = &pktbuf_close; pktbuf.count = &pktbuf_count; pktbuf.num_of_buffers = &pktbuf_num_of_buffers; pktbuf.num_of_freebuf = &pktbuf_num_of_freebuf; return &pktbuf; }
0
#include <pthread.h> pthread_mutex_t bookKeeping = PTHREAD_MUTEX_INITIALIZER; pthread_t jobs[4]; float savings = 0; int numberOfJobs = 0; void LostJob() { int index; for (int i = 0; i < numberOfJobs; i++) { if (jobs[i] == pthread_self()) { index = i; } } for (int i = index + 1; i < numberOfJobs; i++) { jobs[i-1] = jobs[i]; } numberOfJobs -= 1; } void* GetAJob(void* jobTitle) { pthread_mutex_lock( &bookKeeping ); numberOfJobs += 1; pthread_mutex_unlock( &bookKeeping ); printf("I got job %s. Number of jobs: %d\\n", (char*) jobTitle, numberOfJobs); int PayPeriods = GetJobPayPeriod(); while (MaintainJob()) { Work(PayPeriods); pthread_mutex_lock( &bookKeeping ); savings += 7.25; pthread_mutex_unlock( &bookKeeping ); if (savings == 1000000) { printf("I have made enough money to retire!\\n"); return 0; } } pthread_mutex_lock( &bookKeeping ); LostJob(); pthread_mutex_unlock( &bookKeeping ); printf("I lost my job %s!\\n", (char*) jobTitle); return 0; } int main(int argc, char const *argv[]) { srand(time(0)); time_t beginWorking = time(0); char* availableJobs[] = { "JANITOR", "DUNKIN' DONUTS CREW MEMBER", "WAITRESS", "RETAILS SALES REPRESENTATIVE", }; while(1) { if (numberOfJobs == 0 || numberOfJobs < 4){ printf("Looking for a job...\\n"); int jobSearch = pthread_create( &jobs[numberOfJobs], 0, GetAJob, availableJobs[PickJob()] ); if (CouldNotFindJob(jobSearch)) { fprintf( stderr, "Could not find job! Now unemployed :( \\n" ); return 1; } } if (LifeHappens()) { int bill = rand() % 500; savings -= bill; printf("Life sucks...gotta pay $%d\\n", bill); } if (HeartAttack()) { printf("I DIED FROM OVERWORKING!\\n"); return 1; } if (savings == 1000000) { printf("HALLLUJAH I AM RETIRING! :D Age %d\\n", Age(difftime(time(0), beginWorking)) ); break; } printf("Current savings balance: $%.2f\\n", savings); ANewDay(); } for ( int i = 0 ; i < numberOfJobs ; i++ ) { pthread_join( jobs[i], 0 ); } return 0; }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo * foo_alloc(){ struct foo * fp; if((fp = malloc(sizeof(struct foo))) !=0 ){ fp->f_count = 1; if(pthread_mutex_init(&fp->f_lock , 0) != 0){ free(fp); return 0; } } return fp; } void foo_hold(struct foo * fp){ pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void * thr_fn(void * arg){ pthread_mutex_lock(&lock); int i; for(i = 0 ; i < 20; i++) printf("tid = %lu , i = %d \\n" , (unsigned long)pthread_self() , i); pthread_mutex_unlock(&lock); } int main(){ pthread_t tid1 , tid2; int err; struct foo * fp = foo_alloc(); err = pthread_create(&tid1 , 0 , thr_fn , 0); if(err !=0) err_exit(err , "can not create thread 1"); err = pthread_create(&tid2 , 0 , thr_fn , 0); if(err !=0) err_exit(err , "can not create thread 2"); sleep(5); exit(5); }
0
#include <pthread.h> void *philosopher(void *id); pthread_t philo[5]; void grab_fork(int, int, char *); void putdown_fork(int, int); pthread_mutex_t fork_lock[5]; int start = 0; int main() { int i; for (i = 0; i < 5; i++) { pthread_mutex_init (&fork_lock[i], 0); if (pthread_mutex_init(&fork_lock[i], 0) != 0) { perror("mutex initilization"); exit(0); } } for (i=0;i<5;i++){ pthread_create (&philo[i], 0, philosopher, (void *)i); } start = 1; for(i=0; i<5;i++) { pthread_join (philo[i], 0); } return 0; } void *philosopher(void *num) { int id; int left_fork, right_fork; id = (int)num; printf("philosopher %d is done thinking and wats food\\n", id); right_fork = id; left_fork = id+1; if (left_fork == 5) { left_fork = 0; } grab_fork(id, right_fork, "right "); grab_fork(id, left_fork, "left"); printf ("Philosopher %d: eating.\\n", id); putdown_fork (left_fork, right_fork); printf ("Philosopher %d is done eating.\\n", id); return (0); } void grab_fork(int phil, int c, char *hand) { pthread_mutex_lock(&fork_lock[c]); printf ("Philosopher %d: got %s fork %d\\n", phil, hand, c); } void putdown_fork(int c1, int c2) { pthread_mutex_unlock(&fork_lock[c1]); pthread_mutex_unlock(&fork_lock[c2]); }
1
#include <pthread.h> int source[30]; int minBound[3]; int maxBound[3]; int channel[3]; int th_id = 0; pthread_mutex_t mid; pthread_mutex_t ms[3]; void sort (int x, int y) { int aux = 0; for (int i = x; i < y; i++) { for (int j = i; j < y; j++) { if (source[i] > source[j]) { aux = source[i]; source[i] = source[j]; source[j] = aux; } } } } void *sort_thread (void * arg) { int id = -1; int x, y; pthread_mutex_lock (&mid); id = th_id; th_id++; pthread_mutex_unlock (&mid); x = minBound[id]; y = maxBound[id]; __VERIFIER_assert (x >= 0); __VERIFIER_assert (x < 30); __VERIFIER_assert (y >= 0); __VERIFIER_assert (y < 30); printf ("t%d: min %d max %d\\n", id, x, y); sort (x, y); pthread_mutex_lock (&ms[id]); channel[id] = 1; pthread_mutex_unlock (&ms[id]); return 0; } int main () { pthread_t t[3]; int i; __libc_init_poet (); i = __VERIFIER_nondet_int (0, 30 - 1); source[i] = __VERIFIER_nondet_int (0, 20); __VERIFIER_assert (source[i] >= 0); pthread_mutex_init (&mid, 0); int j = 0; int delta = 30/3; __VERIFIER_assert (delta >= 1); i = 0; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; __VERIFIER_assert (i == 3); int k = 0; while (k < 3) { i = 0; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++; __VERIFIER_assert (i == 3); } __VERIFIER_assert (th_id == 3); __VERIFIER_assert (k == 3); sort (0, 30); printf ("==============\\n"); for (i = 0; i < 30; i++) printf ("m: sorted[%d] = %d\\n", i, source[i]); i = 0; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; __VERIFIER_assert (i == 3); return 0; }
0
#include <pthread.h> sem_t PID_sem, signal_sem; bool stop = 0; double y = 0; struct udp_conn connection; pthread_mutex_t mutex; volatile int period_us = 5000; int udp_init_client(struct udp_conn *udp, int port, char *ip) { struct hostent *host; if ((host = gethostbyname(ip)) == 0) return -1; udp->client_len = sizeof(udp->client); memset((char *)&(udp->server), 0, sizeof(udp->server)); udp->server.sin_family = AF_INET; udp->server.sin_port = htons(port); bcopy((char *)host->h_addr, (char *)&(udp->server).sin_addr.s_addr, host->h_length); if ((udp->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) return udp->sock; return 0; } int udp_send(struct udp_conn *udp, char *buf, int len) { return sendto(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->server), sizeof(udp->server)); } int udp_receive(struct udp_conn *udp, char *buf, int len) { int res = recvfrom(udp->sock, buf, len, 0, (struct sockaddr *)&(udp->client), &(udp->client_len)); return res; } void udp_close(struct udp_conn *udp) { close(udp->sock); return; } int clock_nanosleep(struct timespec *next) { struct timespec now; struct timespec sleep; clock_gettime(CLOCK_REALTIME, &now); sleep.tv_sec = next->tv_sec - now.tv_sec; sleep.tv_nsec = next->tv_nsec - now.tv_nsec; if (sleep.tv_nsec < 0) { sleep.tv_nsec += 1000000000; sleep.tv_sec -= 1; } nanosleep(&sleep, 0); return 0; } void timespec_add_us(struct timespec *t, long us) { t->tv_nsec += us*1000; if (t->tv_nsec > 1000000000) { t->tv_nsec -= 1000000000; t->tv_sec += 1; } } void* periodic_request() { struct timespec next; clock_gettime(CLOCK_REALTIME, &next); while(1){ if (stop){ break; } pthread_mutex_lock(&mutex); if (udp_send(&connection, "GET", strlen("GET") + 1) < 0){ perror("Error in sendto()"); } pthread_mutex_unlock(&mutex); timespec_add_us(&next, period_us); clock_nanosleep(&next); } pthread_mutex_unlock(&mutex); printf("Exit periodic request\\n"); } void* udp_listener() { int bytes_received; char recvbuf[512]; char testbuf[512]; while(1){ if (stop){ break; } bytes_received = udp_receive(&connection, recvbuf, 512); if (bytes_received > 0){ memcpy(testbuf, recvbuf, strlen("GET_ACK:")); if (testbuf[0] == 'G'){ y = get_double(recvbuf); sem_post(&PID_sem); } if (testbuf[0] == 'S'){ sem_post(&signal_sem); } } } sem_post(&signal_sem); sem_post(&PID_sem); printf("Exit udp listener\\n"); } void* PID_control() { char sendbuf[64]; double error = 0.0; double reference = 1.0; double integral = 0.0; double u = 0.0; int Kp = 10; int Ki = 800; double period_s = period_us/(1000.0*1000.0); while(1){ if (stop){ break; } sem_wait(&PID_sem); error = reference - y; integral = integral + (error*period_s); u = Kp*error + Ki*integral; snprintf(sendbuf, sizeof sendbuf, "SET:%f", u); pthread_mutex_lock(&mutex); if (udp_send(&connection, sendbuf, strlen(sendbuf)+1) < 0){ perror("Error in sendto()"); } pthread_mutex_unlock(&mutex); } printf("Exit PID controller\\n"); } void* respond_to_server() { while(1){ if (stop){ break; } sem_wait(&signal_sem); pthread_mutex_lock(&mutex); if (udp_send(&connection, "SIGNAL_ACK", strlen("SIGNAL_ACK")+1) < 0){ perror("Error in sendto()"); } pthread_mutex_unlock(&mutex); } printf("Exit signal responder\\n"); } double get_double(const char *str) { while (*str && !(isdigit(*str) || ((*str == '-' || *str == '+') && isdigit(*(str + 1))))) str++; return strtod(str, 0); } int main(void){ udp_init_client(&connection, 9999, "192.168.0.1"); if (udp_send(&connection, "START", strlen("START")+1) < 0){ perror("Error in sendto()"); } if (pthread_mutex_init(&mutex, 0) != 0) { perror("mutex initialization"); } if (sem_init(&PID_sem, 0, 1) != 0) { perror("semaphore initialization"); } if (sem_init(&signal_sem, 0, 1) != 0) { perror("semaphore initialization"); } pthread_t udp_listener_thread, PID_control_thread, signal_responder_thread, periodic_request_thread; pthread_create(&udp_listener_thread, 0, udp_listener, 0); pthread_create(&PID_control_thread, 0, PID_control, 0); pthread_create(&signal_responder_thread, 0, respond_to_server, 0); pthread_create(&periodic_request_thread, 0, periodic_request, 0); usleep(500*1000); stop = 1; if (udp_send(&connection, "STOP", strlen("STOP")) < 0){ perror("Error in sendto()"); } pthread_join(periodic_request_thread, 0); pthread_join(udp_listener_thread, 0); pthread_join(PID_control_thread, 0); pthread_join(signal_responder_thread, 0); pthread_mutex_destroy(&mutex); sem_destroy(&PID_sem); sem_destroy(&signal_sem); udp_close(&connection); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thread_func1(void *p) { long int i=0; while(i<10) { i++; pthread_mutex_lock(&mutex); printf("the 1 thread %ld lock\\n",i); printf("the 1 thread %ld lock\\n",i+1); pthread_mutex_trylock(&mutex); (*(long int*)p)++; printf("p now is %ld\\n", (*(long int*)p)); pthread_mutex_unlock(&mutex); printf("the 1 thread %ld unlock\\n",i); } pthread_exit((void*)i); } void *thread_func2(void *p) { long int i=0; while(i<10) { i++; pthread_mutex_lock(&mutex); printf("the 2 thread %ld lock\\n",i); (*(long int*)p)++; pthread_mutex_unlock(&mutex); printf("the 2 thread %ld unlock\\n",i); } pthread_exit((void*)i); } int main() { pthread_t thid1,thid2; long int ret1=0,ret2=0; long int *p=(long int *)malloc(sizeof(long int)); pthread_mutexattr_t mutexattr; pthread_mutexattr_init(&mutexattr); pthread_mutexattr_settype(&mutexattr,PTHREAD_MUTEX_ERRORCHECK_NP); pthread_mutex_init(&mutex,&mutexattr); pthread_create(&thid1,0,thread_func1,p); pthread_create(&thid2,0,thread_func2,p); pthread_join(thid1,(void**)&ret1); printf("the first child thread return value is %ld\\n",ret1); pthread_join(thid2,(void**)&ret2); printf("the second child thread return value is %ld\\n",ret2); pthread_mutex_destroy(&mutex); printf("the sum=%ld\\n",*p); }
0
#include <pthread.h> struct epoll_event g_eventstack[1024]; struct epoll_event *g_eventend = g_eventstack; pthread_mutex_t g_eventstacklock; static void push_events(struct epoll_event *e, int num) { assert(num >= 0); assert(g_eventend + num < g_eventstack + 1024); pthread_mutex_lock(&g_eventstacklock); memcpy(g_eventend, e, num * sizeof(*e)); g_eventend += num; pthread_mutex_unlock(&g_eventstacklock); } static int pop_events(struct epoll_event *e, int num) { int n; assert(g_eventend >= g_eventstack); pthread_mutex_lock(&g_eventstacklock); n = g_eventend - g_eventstack; n = (n < num)?n:num; memcpy(e, g_eventend - n, n * sizeof(*e)); g_eventend -= n; pthread_mutex_unlock(&g_eventstacklock); return n; } struct es_worker { int epfd; pthread_t tid; void *data; struct epoll_event events[64]; struct epoll_event *e; int evnum; }; static void unload_events(struct es_worker *w) { push_events(w->e+1, w->events + w->evnum - w->e - 1); w->e = w->events; w->evnum = 0; } static void load_events(struct es_worker *w) { assert(w->e == w->events); assert(w->evnum == 0); w->evnum += pop_events(w->e, 64 - w->evnum); } static int g_workingnum = 0; static int g_syncnum = 0; pthread_cond_t g_synccond; pthread_mutex_t g_synclock; void es_syncworkers(int syncnum) { int i, n; assert(g_workingnum >= 0); assert(syncnum >= 0); n = g_workingnum; g_syncnum = syncnum; for (i = n; i <syncnum; ++i) { pthread_cond_signal(&g_synccond); } } static inline void checksync(struct es_worker *w) { assert(g_workingnum > 0); assert(g_syncnum >= 0); if (g_syncnum == g_workingnum) { return; } syslog(LOG_INFO, "g_syncnum, g_workingnum: %d, %d\\n", g_syncnum, g_workingnum); pthread_mutex_lock(&g_synclock); if (g_workingnum > g_syncnum) { unload_events(w); while (g_workingnum > g_syncnum) { --g_workingnum; pthread_cond_wait(&g_synccond, &g_synclock); ++g_workingnum; } } else if (g_workingnum < g_syncnum) { int i, n; n = g_workingnum; for (i = n; i < g_syncnum; ++i) { pthread_cond_signal(&g_synccond); } } else { } pthread_mutex_unlock(&g_synclock); } static pthread_key_t g_key; static pthread_once_t g_key_once = PTHREAD_ONCE_INIT; static void disable_signals() { int res; sigset_t set; sigfillset(&set); res = pthread_sigmask(SIG_BLOCK, &set, 0); assert(res == 0); } static void clear_events(struct es_worker *w) { w->e = w->events; w->evnum = 0; } static void log_exceptional_events(uint32_t events, int epfd, void *ptr) { if ((events & EPOLLERR) || (events & EPOLLHUP) || !((events & EPOLLIN) || (events & EPOLLOUT))) { if (ptr_to_service(ptr)) { syslog(LOG_ERR, "%s:%d: events = 0x%x", "epoll error on listening fd", get_service_fd(ptr_to_service(ptr)), events); } else { syslog(LOG_ERR, "%s:%d: events = 0x%x", "epoll error on working fd", get_conn_fd(ptr), events); } } } static void process_events(struct es_worker *w) { for (w->e = &w->events[0]; w->e < &w->events[w->evnum]; ++w->e) { log_exceptional_events(w->e->events, w->epfd, w->e->data.ptr); if (ptr_to_service(w->e->data.ptr)) { struct es_conn *conn; while (0 != (conn = accept_connection(ptr_to_service(w->e->data.ptr)))) { es_addconn(w->epfd, conn, 0); } } else if ((w->e->events & EPOLLIN)) { read_data(w->e->data.ptr); } else if (w->e->events & EPOLLOUT) { send_buffered_data(w->e->data.ptr, 0); } else { syslog(LOG_INFO, "%s:%d: events = 0x%x", "epoll event neither IN nor OUT", get_conn_fd(w->e->data.ptr), w->e->events); } checksync(w); if (w->evnum == 0) { break; } } clear_events(w); } static void *work(void *data) { int res; struct es_worker *w; disable_signals(); w = (struct es_worker*)data; res = pthread_setspecific(g_key, w); assert(res == 0); clear_events(w); while(1) { load_events(w); if (w->evnum == 0) { syslog(LOG_DEBUG, "Begin read poll 0x%lx: %d:", pthread_self(), w->epfd); w->evnum = epoll_wait(w->epfd, w->events, 64, -1); syslog(LOG_DEBUG, "%d events returned", w->evnum); } process_events(w); } return 0; } static void make_key() { pthread_key_create(&g_key, 0); pthread_cond_init(&g_synccond, 0); pthread_mutex_init(&g_synclock, 0); pthread_mutex_init(&g_eventstacklock, 0); } static inline void inc_workernum() { pthread_mutex_lock(&g_synclock); ++g_workingnum; ++g_syncnum; pthread_mutex_unlock(&g_synclock); } int es_getworkingnum(void) { return g_workingnum; } struct es_worker *es_newworker(int epfd, void *data) { struct es_worker *w = malloc(sizeof(struct es_worker)); inc_workernum(); w->epfd = epfd; w->data = data; pthread_once(&g_key_once, make_key); pthread_create(&w->tid, 0, work, (void*)w); syslog(LOG_DEBUG, "thread 0x%x created\\n", (unsigned int)w->tid); return w; } void *es_getworkerdata() { struct es_worker *w = pthread_getspecific(g_key); assert(w); return w->data; }
1
#include <pthread.h> struct rtpp_ttl_priv { struct rtpp_ttl pub; int max_ttl; int ttl; pthread_mutex_t lock; }; static void rtpp_ttl_dtor(struct rtpp_ttl_priv *); static void rtpp_ttl_reset(struct rtpp_ttl *); static void rtpp_ttl_reset_with(struct rtpp_ttl *, int); static int rtpp_ttl_get_remaining(struct rtpp_ttl *); static int rtpp_ttl_decr(struct rtpp_ttl *); struct rtpp_ttl * rtpp_ttl_ctor(int max_ttl) { struct rtpp_ttl_priv *pvt; struct rtpp_refcnt *rcnt; pvt = rtpp_rzmalloc(sizeof(struct rtpp_ttl_priv), &rcnt); if (pvt == 0) { goto e0; } pvt->pub.rcnt = rcnt; if (pthread_mutex_init(&pvt->lock, 0) != 0) { goto e1; } pvt->pub.reset = &rtpp_ttl_reset; pvt->pub.reset_with = &rtpp_ttl_reset_with; pvt->pub.get_remaining = &rtpp_ttl_get_remaining; pvt->pub.decr = &rtpp_ttl_decr; pvt->ttl = pvt->max_ttl = max_ttl; CALL_SMETHOD(pvt->pub.rcnt, attach, (rtpp_refcnt_dtor_t)&rtpp_ttl_dtor, pvt); return ((&pvt->pub)); e1: CALL_SMETHOD(pvt->pub.rcnt, decref); free(pvt); e0: return (0); } static void rtpp_ttl_dtor(struct rtpp_ttl_priv *pvt) { rtpp_ttl_fin(&(pvt->pub)); pthread_mutex_destroy(&pvt->lock); free(pvt); } static void rtpp_ttl_reset(struct rtpp_ttl *self) { struct rtpp_ttl_priv *pvt; pvt = ((struct rtpp_ttl_priv *)((char *)(self) - offsetof(struct rtpp_ttl_priv, pub))); pthread_mutex_lock(&pvt->lock); pvt->ttl = pvt->max_ttl; pthread_mutex_unlock(&pvt->lock); } static void rtpp_ttl_reset_with(struct rtpp_ttl *self, int max_ttl) { struct rtpp_ttl_priv *pvt; pvt = ((struct rtpp_ttl_priv *)((char *)(self) - offsetof(struct rtpp_ttl_priv, pub))); pthread_mutex_lock(&pvt->lock); pvt->ttl = max_ttl; pvt->max_ttl = max_ttl; pthread_mutex_unlock(&pvt->lock); } static int rtpp_ttl_get_remaining(struct rtpp_ttl *self) { struct rtpp_ttl_priv *pvt; int rval; pvt = ((struct rtpp_ttl_priv *)((char *)(self) - offsetof(struct rtpp_ttl_priv, pub))); pthread_mutex_lock(&pvt->lock); rval = pvt->ttl; pthread_mutex_unlock(&pvt->lock); return (rval); } static int rtpp_ttl_decr(struct rtpp_ttl *self) { struct rtpp_ttl_priv *pvt; int rval; pvt = ((struct rtpp_ttl_priv *)((char *)(self) - offsetof(struct rtpp_ttl_priv, pub))); pthread_mutex_lock(&pvt->lock); rval = pvt->ttl; if (pvt->ttl > 0) pvt->ttl--; pthread_mutex_unlock(&pvt->lock); return (rval); }
0
#include <pthread.h> void barreira_init(int n) { B.arrive = calloc(n, sizeof(int)); B.continua = calloc(n, sizeof(int)); B.final = calloc(n, sizeof(int)); B.arrive_mutex = calloc(n, sizeof(pthread_mutex_t)); B.continua_mutex = calloc(n, sizeof(pthread_mutex_t)); B.arrive_cond = calloc(n, sizeof(pthread_cond_t)); B.continua_cond = calloc(n, sizeof(pthread_cond_t)); B.size = n; B.tempo = 0; B.last = 0; int i; for (i = 0; i < n; i++) { pthread_mutex_init(&B.arrive_mutex[i], 0); pthread_mutex_init(&B.continua_mutex[i], 0); pthread_cond_init(&B.arrive_cond[i], 0); pthread_cond_init(&B.continua_cond[i], 0); } } void * barreira_coordenador() { int i, stop = 1, n = B.size; while (stop) { stop = 0; for (i = 0; i < n; i++) { if (B.final[i] == 0) { stop = 1; pthread_mutex_lock(&B.arrive_mutex[i]); while (B.arrive[i] == 0) { pthread_cond_wait(&B.arrive_cond[i], &B.arrive_mutex[i]); } B.arrive[i] = 0; pthread_mutex_unlock(&B.arrive_mutex[i]); } } if (B.last) B.tempo++; else B.tempo += 3; print_track(); for (i = 0; i < n; i++) { pthread_mutex_lock(&B.continua_mutex[i]); B.continua[i] = 1; pthread_cond_signal(&B.continua_cond[i]); pthread_mutex_unlock(&B.continua_mutex[i]); } } } void barreira_ciclista(int i) { pthread_mutex_lock(&B.arrive_mutex[i]); B.arrive[i] = 1; pthread_cond_signal(&B.arrive_cond[i]); pthread_mutex_unlock(&B.arrive_mutex[i]); pthread_mutex_lock(&B.continua_mutex[i]); while (B.continua[i] == 0) { pthread_cond_wait(&B.continua_cond[i], &B.continua_mutex[i]); } B.continua[i] = 0; pthread_mutex_unlock(&B.continua_mutex[i]); } void barreira_last() { B.last = 1; } void barreira_final(int i, int volta) { if (volta) B.final[i] = volta; else B.final[i] = B.tempo*20; pthread_mutex_lock(&B.arrive_mutex[i]); B.arrive[i] = 1; pthread_cond_signal(&B.arrive_cond[i]); pthread_mutex_unlock(&B.arrive_mutex[i]); } int * barreira_tempo() { return B.final; } void barreira_destroy() { int i, n = B.size; for (i = 0; i < n; i++) { pthread_mutex_destroy(&B.arrive_mutex[i]); pthread_mutex_destroy(&B.continua_mutex[i]); } free(B.arrive); free(B.continua); free(B.final); free(B.arrive_mutex); free(B.continua_mutex); free(B.arrive_cond); free(B.continua_cond); }
1
#include <pthread.h> void my_handler(int s) { fprintf(stderr, "exit"); exit(1); } pthread_mutex_t PrintMutex; void* print_xs (void* unused) { while (1) { usleep(3 * 1000); pthread_mutex_lock(&PrintMutex); fprintf (stderr, "123"); fprintf (stderr, "456"); fprintf (stderr, "789\\n"); pthread_mutex_unlock(&PrintMutex); } return 0; } int main () { pthread_mutex_init (&PrintMutex, 0); pthread_t thread_id; signal(SIGINT, my_handler); pthread_create (&thread_id, 0, &print_xs, 0); while (1) { pthread_mutex_lock(&PrintMutex); fprintf (stderr, "abc"); fprintf (stderr, "def"); fprintf (stderr, "ghi"); fprintf (stderr, "jkl"); fprintf (stderr, "mno"); fprintf (stderr, "pqr"); fprintf (stderr, "stu"); fprintf (stderr, "vwx"); fprintf (stderr, "yz\\n"); pthread_mutex_unlock(&PrintMutex); } return 0; }
0
#include <pthread.h> int data; struct _node *next; }node_t, *node_p, **node_pp; node_p head = 0; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static node_p alloc_node(int _d) { node_p tmp = (node_p)malloc(sizeof(node_t)); if(tmp == 0){ perror("malloc"); exit(1); } tmp->data = _d; tmp->next = 0; } static void delete_node(node_p _n) { if(_n){ free(_n); } } void initList(node_pp _h) { *_h = alloc_node(0); } void PushFront(node_p _h, int _d) { node_p tmp = alloc_node(_d); tmp->next = _h->next; _h->next = tmp; } void PopFront(node_p _h, int *_out) { if(!isEmpty(_h)){ node_p p = _h->next; _h->next = p->next; *_out = p->data; delete_node(p); } } void showList(node_p _h) { node_p start = _h->next; while(start){ printf("%d ", start->data); start = start->next; } printf("\\n"); } void destroyList(node_p _h) { int out = 0; while(!isEmpty(_h)){ PopFront(_h, &out); } delete_node(_h); } int isEmpty(node_p _h) { return _h->next == 0 ? 1 : 0; } void *_consume(void *arg) { int c; while(1){ c = -1; pthread_mutex_lock(&lock); while(isEmpty(head)){ printf("consume begin waiting...\\n"); pthread_cond_wait(&cond, &lock); } PopFront(head, &c); pthread_mutex_unlock(&lock); printf("consume done: %d\\n", c); sleep(3); } } void *_product(void *arg) { while(1){ int p = rand()%1234; pthread_mutex_lock(&lock); PushFront(head, p); pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); printf("product done: %d\\n", p); sleep(1); } } int main() { initList(&head); pthread_t consume, product; pthread_create(&consume, 0, _consume, 0); pthread_create(&product, 0, _product, 0); pthread_join(consume, 0); pthread_join(product, 0); pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); destroyList(head); return 0; }
1
#include <pthread.h> volatile int buffer[5]; volatile int cont_buffer = 0; volatile int out = 1; pthread_mutex_t mutex; pthread_cond_t cond_prod; pthread_cond_t cond_cons; int fibo (int n) { int t0 = 0, t1 = 1; for ( ; n > 0; --n) { t0 += t1; t1 ^= t0 ^= t1 ^= t0; } return t0; } int ehPrimo(long unsigned int n) { int i; if (n <= 1) return 0; if (n == 2) return 1; if ( n % 2 == 0) return 0; for (i = 3; i < sqrt(n) + 1; i += 2) { if (n % i == 0) return 0; } return 1; } void *produtor (void *args) { int i, item; for (i = 1; i <= 25; ++i) { item = fibo(i); pthread_mutex_lock(&mutex); if (cont_buffer == 5) pthread_cond_wait(&cond_prod, &mutex); buffer[i % 5] = item; cont_buffer++; pthread_cond_signal(&cond_cons); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *consumidor (void *args) { int item, fim; while (1) { pthread_mutex_lock(&mutex); fim = out > 25; if (!fim) { while (cont_buffer == 0) pthread_cond_wait(&cond_cons, &mutex); item = buffer[out++ % 5]; cont_buffer--; } pthread_mutex_unlock(&mutex); if (fim) break; printf("%2d: %5d %seh primo\\n", out-1, item, ehPrimo(item) ? "" : "nao "); } pthread_exit(0); } int main(int argc, char const *argv[]) { int i, item; pthread_t threads[3]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_prod, 0); pthread_cond_init(&cond_cons, 0); pthread_create(&threads[0], 0, produtor, 0); pthread_create(&threads[1], 0, consumidor, 0); pthread_create(&threads[2], 0, consumidor, 0); pthread_join(threads[0], 0); pthread_join(threads[1], 0); pthread_join(threads[2], 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_variable = PTHREAD_COND_INITIALIZER; int sum = 0; int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int i = 0; struct Task { int first; int last; }; void create_thread(pthread_t* thread, void* (*function)(void*), void* argument) { if (pthread_create(thread, 0, function, argument) != 0) { perror("Error creating thread"); exit(1); } } void add(struct Task* task) { int i; for (i = task->first; i < task->last; ++i) { pthread_mutex_lock(&mutex); sum += array[i]; pthread_mutex_unlock(&mutex); } } void parallel_add() { pthread_t first_thread; pthread_t second_thread; struct Task first_task = {0, 5}; struct Task second_task = {first_task.last, 10}; create_thread(&first_thread, (void*)add, &first_task); create_thread(&second_thread, (void*)add, &second_task); pthread_join(first_thread, 0); pthread_join(second_thread, 0); } void first_interleaved_half(struct Task* task) { pthread_mutex_lock(&mutex); printf("A\\n"); for (i = task->first; i < task->last; ++i) { printf("A: %d\\n", i); sum += array[i]; } pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&condition_variable); pthread_exit(0); } void second_interleaved_half(struct Task* task) { pthread_mutex_lock(&mutex); printf("B\\n"); pthread_cond_wait(&condition_variable, &mutex); for (; i < task->last; ++i) { printf("B: %d\\n", i); sum += array[i]; } pthread_mutex_unlock(&mutex); pthread_exit(0); } void interleaved_add() { pthread_t first_thread; pthread_t second_thread; struct Task first_task = {0, 5}; struct Task second_task = {5, 10}; create_thread(&first_thread, (void*)first_interleaved_half, &first_task); create_thread(&second_thread, (void*)second_interleaved_half, &second_task); pthread_join(first_thread, 0); pthread_join(second_thread, 0); } void recursive_addition(struct Task* task) { if ((task->last - task->first) <= 2) { for (; task->first < task->last; ++task->first) { pthread_mutex_lock(&mutex); sum += array[task->first]; pthread_mutex_unlock(&mutex); } } else { pthread_t thread; struct Task left_task = {task->first, task->first + (task->last - task->first) / 2}; struct Task right_task = {left_task.last, task->last}; create_thread(&thread, (void*)recursive_addition, &left_task); recursive_addition(&right_task); pthread_join(thread, 0); } } void recursive_add() { struct Task task = {0, 10}; recursive_addition(&task); } int main() { recursive_add(); printf("%d\\n", sum); return 0; }
1
#include <pthread.h> pthread_mutex_t alarm_mutex; volatile int spawnflag; void uplink_alarm_handle(int sig) { pthread_mutex_lock(&alarm_mutex); spawnflag++; pthread_mutex_unlock(&alarm_mutex); } void uplink_alarm_init(unsigned long delta) { spawnflag = 0; pthread_mutex_init(&alarm_mutex, 0); signal(SIGALRM, uplink_alarm_handle); ualarm(delta, delta); } int uplink_wait_for_alarm(void) { while (spawnflag==0) { usleep(100); } pthread_mutex_lock(&alarm_mutex); spawnflag--; pthread_mutex_unlock(&alarm_mutex); return spawnflag; }
0
#include <pthread.h> pthread_mutex_t lock; double maximum=0; double minimum=0; double total=0; double average=0; int k=0; int count=0; int flag=0; void *Add1(void *dummy) { while(1) { double num=0; if(k==1) { pthread_exit(0); return 0; } pthread_mutex_lock(&lock); if (scanf("%lf",&num)==EOF) { k=1; pthread_mutex_unlock(&lock); return 0; } else { if(flag==0) { flag=1; maximum=num; minimum=num; total+=num; count++; average=(total/count); } else { if(num>maximum) { maximum=num; } else if(num<minimum) { minimum=num; } total+=num; count++; average=(total/count); } } pthread_mutex_unlock(&lock); } return 0; } int main(int argc,char *argv[]) { pthread_t t[3]; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } int i=0; for(i;i<=2;i++) { if(pthread_create(&t[i],0,Add1,(void *)t[i])) { printf("Error message creating thread\\n"); return 1; } } while(1) { double num=0; if(k==1) { pthread_exit(0); break; } pthread_mutex_lock(&lock); if (scanf("%lf",&num)==EOF) { k=1; pthread_mutex_unlock(&lock); break; } else { if(flag==0) { flag=1; maximum=num; minimum=num; total+=num; count++; average=(total/count); } else { if(num>maximum) { maximum=num; } else if(num<minimum) { minimum=num; } total+=num; count++; average=(total/count); } } pthread_mutex_unlock(&lock); } int z=0; for (z;z<=2;z++) { pthread_join(t[z],0); } pthread_mutex_destroy(&lock); printf("max: %.0f\\n",maximum); printf("min: %.0f\\n",minimum); printf("average: %.2f",average); return 0; }
1
#include <pthread.h> static int iTThreads = 2; static int iRThreads = 1; static int data1Value = 0; static int data2Value = 0; pthread_mutex_t data1Lock; pthread_mutex_t data2Lock; void lock(pthread_mutex_t *); void unlock(pthread_mutex_t *); void *funcA(void *param) { pthread_mutex_lock(&data1Lock); data1Value = 1; pthread_mutex_unlock(&data1Lock); pthread_mutex_lock(&data2Lock); data2Value = data1Value + 1; pthread_mutex_unlock(&data2Lock); return 0; } void *funcB(void *param) { int t1 = -1; int t2 = -1; pthread_mutex_lock(&data1Lock); if (data1Value == 0) { pthread_mutex_unlock(&data1Lock); return 0; } t1 = data1Value; pthread_mutex_unlock(&data1Lock); pthread_mutex_lock(&data2Lock); t2 = data2Value; pthread_mutex_unlock(&data2Lock); assert(t2 == (t1 + 1)); return 0; } int main(int argc, char *argv[]) { int i,err; pthread_t tPool[2]; pthread_t rPool[1]; for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) { fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) { fprintf(stderr, "Error [%d] found creating read thread.\\n", err); exit(-1); } } for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_join(tPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_join(rPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } return 0; } void lock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_lock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err); exit(-1); } } void unlock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_unlock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err); exit(-1); } }
0
#include <pthread.h> int food=100; pthread_mutex_t chopstick[5]; pthread_mutex_t foodlock; void get_chopstick(int phil,int c,char hand) { pthread_mutex_lock(&chopstick[c]); printf("Philosopher %d: got %c chopstick %d\\n", phil, hand, c); } void leave_chopsticks(int phil ,int c ,char hand) { pthread_mutex_unlock(&chopstick[c]); printf("Philosopher %d: left %c chopstick %d\\n", phil, hand, c); } void * eat(void* k){ int n =(int) k; while(food >0){ get_chopstick(n,n,'R'); if(n != 4) get_chopstick(n,n+1,'L'); else get_chopstick(n,0,'L'); pthread_mutex_lock(&foodlock); food-=10; printf("phil number %d is now eating \\n", n); pthread_mutex_unlock (&foodlock); printf("phil number %d has finished eating \\n", n); leave_chopsticks(n,n,'R'); if(n != 4) leave_chopsticks(n,n+1,'L'); else leave_chopsticks(n,0,'L'); } printf("food has finished !\\n"); return 0; } int main(){ pthread_t thr[5]; for(int i=0;i<5;i++){ pthread_create(&thr[i], 0, eat, (void *)i); } for( int j=0; j<5; j++) pthread_join(thr[j], 0); return 0;}
1
#include <pthread.h> uint32_t inode[16]; uint32_t pos[16]; uint32_t time[16]; uint64_t chunkid[16]; uint32_t chunkversion[16]; uint8_t csdatasize[16]; uint8_t *csdata[16]; } hashbucket; static hashbucket *chunklochash = 0; static pthread_mutex_t clcachelock = PTHREAD_MUTEX_INITIALIZER; void chunkloc_cache_insert(uint32_t inode,uint32_t pos,uint64_t chunkid,uint32_t chunkversion,uint8_t csdatasize,const uint8_t *csdata) { uint32_t primes[4] = {1072573589U,3465827623U,2848548977U,748191707U}; hashbucket *hb,*fhb; uint8_t h,i,fi; uint32_t now; uint32_t mints; now = time(0); mints = UINT32_MAX; fi = 0; fhb = 0; pthread_mutex_lock(&clcachelock); for (h=0 ; h<4 ; h++) { hb = chunklochash + ((inode*primes[h]+pos*primes[4 -1-h])%6257); for (i=0 ; i<16 ; i++) { if (hb->inode[i]==inode && hb->pos[i]==pos) { if (hb->csdata[i]) { free(hb->csdata[i]); } hb->chunkid[i] = chunkid; hb->chunkversion[i] = chunkversion; hb->csdatasize[i] = csdatasize; if (csdatasize>0) { hb->csdata[i] = (uint8_t*)malloc(csdatasize); memcpy(hb->csdata[i],csdata,csdatasize); } else { hb->csdata[i] = 0; } hb->time[i]=now; pthread_mutex_unlock(&clcachelock); return; } if (hb->time[i]<mints) { fhb = hb; fi = i; mints = hb->time[i]; } } } if (fhb) { fhb->inode[fi] = inode; fhb->pos[fi] = pos; if (fhb->csdata[fi]) { free(fhb->csdata[fi]); } fhb->chunkid[fi] = chunkid; fhb->chunkversion[fi] = chunkversion; fhb->csdatasize[fi] = csdatasize; if (csdatasize>0) { fhb->csdata[fi] = (uint8_t*)malloc(csdatasize); memcpy(fhb->csdata[fi],csdata,csdatasize); } else { fhb->csdata[fi] = 0; } fhb->time[fi]=now; } pthread_mutex_unlock(&clcachelock); } int chunkloc_cache_search(uint32_t inode,uint32_t pos,uint64_t *chunkid,uint32_t *chunkversion,uint8_t *csdatasize,const uint8_t **csdata) { uint32_t primes[4] = {1072573589U,3465827623U,2848548977U,748191707U}; hashbucket *hb; uint8_t h,i; pthread_mutex_lock(&clcachelock); for (h=0 ; h<4 ; h++) { hb = chunklochash + ((inode*primes[h]+pos*primes[4 -1-h])%6257); for (i=0 ; i<16 ; i++) { if (hb->inode[i]==inode && hb->pos[i]==pos) { *chunkid = hb->chunkid[i]; *chunkversion = hb->chunkversion[i]; *csdatasize = hb->csdatasize[i]; *csdata = hb->csdata[i]; pthread_mutex_unlock(&clcachelock); return 1; } } } pthread_mutex_unlock(&clcachelock); return 0; } void chunkloc_cache_init(void) { chunklochash = malloc(sizeof(hashbucket)*6257); memset(chunklochash,0,sizeof(hashbucket)*6257); } void chunkloc_cache_term(void) { hashbucket *hb; uint8_t i; uint32_t hi; pthread_mutex_lock(&clcachelock); for (hi=0 ; hi<6257 ; hi++) { hb = chunklochash + hi; for (i=0 ; i<16 ; i++) { if (hb->csdata[i]) { free(hb->csdata[i]); } } } free(chunklochash); pthread_mutex_unlock(&clcachelock); }
0
#include <pthread.h> struct sockaddr; int rootwrap_bind (int, int, int, const struct sockaddr *, size_t); static int recv_fd (int p) { struct msghdr hdr; struct iovec iov; struct cmsghdr *cmsg; int val, fd; char buf[CMSG_SPACE (sizeof (fd))]; hdr.msg_name = 0; hdr.msg_namelen = 0; hdr.msg_iov = &iov; hdr.msg_iovlen = 1; hdr.msg_control = buf; hdr.msg_controllen = sizeof (buf); iov.iov_base = &val; iov.iov_len = sizeof (val); if (recvmsg (p, &hdr, 0) != sizeof (val)) return -1; for (cmsg = CMSG_FIRSTHDR (&hdr); cmsg != 0; cmsg = CMSG_NXTHDR (&hdr, cmsg)) { if ((cmsg->cmsg_level == SOL_SOCKET) && (cmsg->cmsg_type = SCM_RIGHTS) && (cmsg->cmsg_len >= CMSG_LEN (sizeof (fd)))) { memcpy (&fd, CMSG_DATA (cmsg), sizeof (fd)); return fd; } } errno = val; return -1; } int rootwrap_bind (int family, int socktype, int protocol, const struct sockaddr *addr, size_t alen) { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; struct sockaddr_storage ss; int fd, sock = -1; const char *sockenv = getenv ("VLC_ROOTWRAP_SOCK"); if (sockenv != 0) sock = atoi (sockenv); if (sock == -1) { errno = EACCES; return -1; } switch (family) { case AF_INET: if (alen < sizeof (struct sockaddr_in)) { errno = EINVAL; return -1; } break; default: errno = EAFNOSUPPORT; return -1; } if (family != addr->sa_family) { errno = EAFNOSUPPORT; return -1; } if ((socktype != SOCK_STREAM) || (protocol && (protocol != IPPROTO_TCP))) { errno = EACCES; return -1; } memset (&ss, 0, sizeof (ss)); memcpy (&ss, addr, (alen > sizeof (ss)) ? sizeof (ss) : alen); pthread_mutex_lock (&mutex); if (send (sock, &ss, sizeof (ss), 0) != sizeof (ss)) return -1; fd = recv_fd (sock); pthread_mutex_unlock (&mutex); return fd; }
1
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { return (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (top==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if ((push(arr,tmp)==(-1))) error(); pthread_mutex_unlock(&m); } return 0; } void *t2(void *arg) { int i; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); if (top>0) { if ((pop(arr)==(-2))) error(); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> unsigned short IA = 0; unsigned int int_queueing = 0; unsigned short int_queue[256]; unsigned char iq_back = 0; unsigned char iq_front = 0; void recv_int(unsigned short int_val) { static pthread_mutex_t iq_front_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&iq_front_mutex); int_queue[iq_front] = int_val; ++iq_front; pthread_mutex_unlock(&iq_front_mutex); } void trigger_interrupt(void) { if (!int_queueing && iq_front != iq_back) { if (IA) { int_queueing = 1; memory[--SP] = PC; memory[--SP] = registers[0]; PC = IA; registers[0] = int_queue[++iq_back]; } else iq_back = iq_front; } }
1
#include <pthread.h> int capacity, num_found; int *data; pthread_mutex_t lock; } PrimeList ; PrimeList * work_list; int start; int end; } ThreadWork; PrimeList *primelist_alloc(int capacity) { PrimeList *list = malloc(sizeof(PrimeList)); list->capacity = capacity; list->num_found = 0; list->data = malloc(capacity * sizeof(int)); pthread_mutex_init(&list->lock, 0); return list; } void primelist_append(PrimeList *list, int prime) { pthread_mutex_lock(&list->lock); list->data[list->num_found] = prime; ++list->num_found; pthread_mutex_unlock(&list->lock); return; } void * find_primes(void * t_arg) { ThreadWork * t_work = t_arg; for (int i = t_work->start; i < t_work->end; i++) { if (is_prime(i)) { primelist_append(t_work->work_list, i); } } pthread_exit(0); } int main(void) { int min, max; int num_threads; printf("Min: "); scanf("%i", &min); printf("Max: "); scanf("%i", &max); printf("Number of threads: "); scanf("%i", &num_threads); int est_num_primes = (int) ((max / log(max)) * 1.4); printf("Estimated number of primes is %i\\n", est_num_primes); PrimeList *list = primelist_alloc(est_num_primes); pthread_t threads[num_threads]; ThreadWork workers[num_threads]; int range = (max - min) + 1; int chunk_size = range / num_threads; int leftover = range % num_threads; for (int t = 0; t < num_threads; t++) { workers[t].work_list = list; workers[t].start = min + (t * chunk_size); workers[t].end = workers[t].start + chunk_size; if (t == num_threads - 1) { workers[t].end += leftover; } pthread_create(&threads[t], 0, find_primes, &workers[t]); } for (int t = 0; t < num_threads; t++) { pthread_join(threads[t], 0); } printf("Total primes found: %d\\n", list->num_found); for (int i = 0; i < list->num_found; i++) { printf("%d ", list->data[i]); } printf("\\n"); return 0; }
0