text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int tid; double stuff; } thread_data_t; double shared_x; pthread_mutex_t lock_x; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; printf("hello from thr_func, thread id: %d\\n", data->tid); pthread_mutex_lock(&lock_x); shared_x += data->stuff; printf("x = %f\\n", shared_x); pthread_mutex_unlock(&lock_x); pthread_exit(0); } int main(int argc, char **argv) { pthread_t thr[5]; int i, rc; thread_data_t thr_data[5]; shared_x = 0; pthread_mutex_init(&lock_x, 0); for (i = 0; i < 5; ++i) { thr_data[i].tid = i; thr_data[i].stuff = (i + 1) * 5; if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < 5; ++i) { pthread_join(thr[i], 0); } return 0; }
1
#include <pthread.h> static const char* filePaths[] = { "out/1.txt", "out/2.txt", "out/3.txt", "out/4.txt", "out/5.txt" }; static const char* outputPath = "out/out.txt"; char buffer[20971520]; size_t bufsize = 0; void fileReader(pthread_mutex_t*); void* fileWriter(void*); void fileReader(pthread_mutex_t* mutex) { int fd, ret; struct aiocb aio_info = {0}; aio_info.aio_buf = &buffer; aio_info.aio_nbytes = 20971520; for (int i = 0; i < 5; ++i) { fd = open(filePaths[i], O_RDONLY); if (fd < 0) { fprintf(stderr, "Opening file %s error", filePaths[i]); exit(1); } pthread_mutex_lock(mutex); aio_info.aio_fildes = fd; ret = aio_read(&aio_info); if (ret < 0) { perror("aio_read"); close(fd); exit(1); } printf("File %s is reading.", filePaths[i]); while (aio_error( &aio_info ) == EINPROGRESS) { putchar('.'); fflush(stdout); usleep(100000); } if ((ret = aio_return(&aio_info)) < 0) { perror("aio_read"); close(fd); exit(1); } puts("Success"); bufsize = ret; pthread_mutex_unlock(mutex); close(fd); usleep(500000); } } void* fileWriter(void* mutex) { int fd, ret; struct aiocb aio_info = {0}; aio_info.aio_buf = buffer; fd = open(outputPath, O_CREAT | O_WRONLY); if (fd < 0) { fputs("Opening output file error", stderr); exit(1); } aio_info.aio_fildes = fd; while (bufsize == 0); usleep(500000); for (int i = 0; i < 5; ++i) { pthread_mutex_lock((pthread_mutex_t*)mutex); aio_info.aio_nbytes = bufsize; ret = aio_write(&aio_info); if (ret < 0) { perror("aio_write"); close(fd); exit(1); } printf("Writing to file %s.", outputPath); while (aio_error(&aio_info) == EINPROGRESS) { putchar('.'); fflush(stdout); usleep(100000); } if ((ret = aio_return(&aio_info)) < 0) { perror("aio_write"); close(fd); exit(1); } puts("Success"); pthread_mutex_unlock(mutex); aio_info.aio_offset += ret; usleep(500000); } close(fd); return 0; }
0
#include <pthread.h> int fumando[3]; int recursos[3]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* agenteT (void* a){ int enUso = 1; int i; while (1){ for (i=0;i<3; ++i){ pthread_mutex_lock(&mutex); if (!fumando[i]){ pthread_mutex_unlock(&mutex); enUso = 0; sleep(15); pthread_mutex_lock(&mutex); recursos[i]=1; if (i==0) printf("Cerillos\\n"); else if (i==1) printf("Papel\\n"); else if (i==2) printf("Cerillos\\n"); } pthread_mutex_unlock(&mutex); } if (enUso){ printf("Se va a hacer otras cosas el agente"); sleep(10); } } } void* fumador (void* a){ int id = (intptr_t) a; while (1){ pthread_mutex_lock(&mutex); if (recursos[0] && recursos[1] && recursos[2]) { recursos[0] = 0; recursos[1] = 0; recursos[2] = 0; fumando[id] = 1; printf("Fumador %d consiguio los materiales y esta fumando\\n", id); pthread_mutex_unlock(&mutex); sleep(10); printf("Fumador %d terminó de fumar\\n", id); pthread_mutex_lock(&mutex); fumando[id] = 0; pthread_mutex_unlock(&mutex); sleep(20); } else pthread_mutex_unlock(&mutex); } } int main ( int argc, char *argv[] ){ int i; pthread_t agente; pthread_create(&agente, 0, agenteT, 0); pthread_t fumadores[3]; for (i = 0; i < 3; ++i){ pthread_create(&fumadores[i], 0, fumador, (void*) (intptr_t) i); } for (i = 0; i < 3; ++i){ pthread_join(fumadores[i], 0); } pthread_join(agente, 0); return 0; }
1
#include <pthread.h> struct job { struct job* next; int job_number; }; struct job* job_queue; pthread_t thread1_id; pthread_t thread2_id; void process_job (struct job* job) { printf("%s %d\\n", "Processing job number", job->job_number); } pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_function (void* arg) { while (1) { struct job* next_job; pthread_mutex_lock (&job_queue_mutex); if (job_queue == 0) next_job = 0; else { next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock (&job_queue_mutex); if (next_job == 0) break; process_job (next_job); } return 0; } int main() { struct job sj1; struct job sj2; memset (&sj1, 0, sizeof (sj1)); memset (&sj2, 0, sizeof (sj2)); sj1.next = &sj2; sj1.job_number = 1; sj2.next = 0; sj2.job_number = 2; job_queue = &sj1; pthread_create (&thread1_id, 0, &thread_function, 0); pthread_create (&thread2_id, 0, &thread_function, 0); pthread_join (thread1_id, 0); pthread_join (thread2_id, 0); return 0; }
0
#include <pthread.h> int x; int rst[1023]; } fourKB; fourKB fourkb[256]; } BigMEMBlock; size_t MEMBLOCKSIZE = sizeof(BigMEMBlock); int numblocks = 1024 ; int numworkers = 2; int runtime = 15; int prepare = 5; BigMEMBlock *mempool; pthread_t *tid; pthread_mutex_t filelock; FILE* logfd; pthread_t timer_td; int shouldend = 0; int background = 0; int record = 0; long setmem() { int idx = rand() % numblocks; register int newvalue = rand(); register int i; struct timespec begin, end; long timediff; BigMEMBlock *source = mempool+idx; BigMEMBlock tmp; clock_gettime(CLOCK_MONOTONIC, &begin); memcpy(&tmp, source, sizeof(MEMBLOCKSIZE)); for (i = 0; i < 256; i++) { source->fourkb[i].x = newvalue; } clock_gettime(CLOCK_MONOTONIC, &end); timediff = (end.tv_sec - begin.tv_sec) * 1000000000 + (end.tv_nsec - begin.tv_nsec); return timediff; } void flushlog(long *timerecords, int size) { int i = 0; if (background) { return; } pthread_mutex_lock(&filelock); for (i = 0; i < size; i++) { fprintf(logfd, "%ld\\n", timerecords[i]); } pthread_mutex_unlock(&filelock); } void *dowork() { long timerecords[10000], timediff; int timeidx = 0; while(!shouldend) { timediff = setmem(); if (record && !background && timeidx < 10000) { timerecords[timeidx] = timediff; timeidx ++; } if (record && !background && timeidx == 10000) { flushlog(timerecords, 10000); timeidx = 0; } } if (record && !background && timeidx != 0) { flushlog(timerecords, timeidx); } return 0; } void *timerend() { int i; for (i = 0; background || i < prepare; i++) { if (!background) { printf("Prepare: %d/%d \\r", i, prepare); fflush(stdout); } sleep(1); } record = 1; for (i = 0; background || i < runtime; i++) { if (!background) { printf("Progress: %d/%d \\r", i, runtime); } fflush(stdout); sleep(1); } shouldend = 1; return 0; } int main(int argc, char** argv) { int i; mempool = (BigMEMBlock *)calloc(numblocks, sizeof(BigMEMBlock)); tid = malloc(numworkers * sizeof(pthread_t)); if (argc > 1) { background = 1; runtime += 5; } if (!background) { logfd = fopen("memaccess.log", "w"); } pthread_mutex_init(&filelock, 0); for(i = 0; i < numworkers; i ++) { pthread_create(&tid[i], 0, dowork, 0); } pthread_create(&timer_td, 0, timerend, 0); pthread_join(timer_td, 0); for (i = 0; i < numworkers; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&filelock); if (!background) { fclose(logfd); } free(mempool); free(tid); }
1
#include <pthread.h> int buffer[100]; int indice; pthread_mutex_t mutex; sem_t sem_espacios_vacios; sem_t sem_espacios_ocupados; void agregar(int n); void quitar(); void * productor() { while(1) { int n = 5 +rand()*100; agregar(n); sleep(1); } } void * consumidor() { while(1) { quitar(); sleep(1); } } void * imprimir() { while(1){ int i; printf("%d",indice); printf("\\n"); sleep(1); } } int main() { pthread_t thread_consumidor; pthread_t thread_productor1; pthread_t thread_productor2; indice = 0; pthread_mutex_init(&mutex,0); sem_init(&sem_espacios_vacios,0,100); sem_init(&sem_espacios_ocupados,0,0); pthread_create(&thread_consumidor, 0, consumidor, 0 ); pthread_create(&thread_productor1, 0, productor, 0 ); pthread_create(&thread_productor2, 0, productor, 0 ); pthread_join(thread_consumidor, 0); return 0; } void agregar(int n) { sem_wait(&sem_espacios_vacios); pthread_mutex_lock(&mutex); buffer[indice] = n; indice++; printf("%d\\n",indice); sem_post(&sem_espacios_ocupados); pthread_mutex_unlock(&mutex); } void quitar() { sem_wait(&sem_espacios_ocupados); pthread_mutex_lock(&mutex); indice--; printf("%d\\n",indice); sem_post(&sem_espacios_vacios); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> int timer = 0; pthread_mutex_t mutex_timer; pthread_cond_t timer_expired_cv; void *watch_timer(void *timer){ int waiting_time = *((int*)timer); printf("Starting watch_timer(), thread is waiting %d second(s):\\n", waiting_time); while(waiting_time > 0){ sleep(1); printf("Timer is: %d second(s).\\n", waiting_time); pthread_mutex_lock(&mutex_timer); waiting_time--; pthread_mutex_unlock(&mutex_timer); if (waiting_time == 0) { pthread_cond_signal(&timer_expired_cv); printf("Sends notification to the other thread that timer has expired.\\n"); } } pthread_exit(0); } void *timer_has_expired(void *t){ long my_thread = *(long*)t; pthread_mutex_lock(&mutex_timer); pthread_cond_wait(&timer_expired_cv, &mutex_timer); printf("Timer has expired and thread number %ld is notified. \\n", my_thread); pthread_mutex_unlock(&mutex_timer); pthread_exit(0); } void getUserInput(){ printf("Hello, please set timer limit\\n"); scanf("%d",&timer); printf("Timer limit is set too: %d\\n", timer); } int main(int argc, char *argv[]){ int i; pthread_t threads[2]; pthread_attr_t attr; long thread1=1; getUserInput(); pthread_mutex_init(&mutex_timer, 0); pthread_cond_init(&timer_expired_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_timer, (void *)&timer); pthread_create(&threads[1], &attr, timer_has_expired, (void *)&thread1); for (i = 0; i < 2; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Execution completed.\\n", 2); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex_timer); pthread_cond_destroy(&timer_expired_cv); pthread_exit(0); return 0; }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; } char do_it = 1; long long iterations = 0; void sighdl(int sig) { do { do_it = 0; } while (do_it); } pthread_once_t once_ctl; int once_chk; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void init_routine(void) { int ret = 0; ret = pthread_mutex_lock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to lock mutex in initializer"); } once_chk++; ret = pthread_mutex_unlock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to unlock mutex in initializer"); } return; } void *threaded(void *arg) { int ret = 0; ret = pthread_barrier_wait(arg); if ((ret != 0) && (ret != PTHREAD_BARRIER_SERIAL_THREAD)) { UNRESOLVED(ret, "Barrier wait failed"); } ret = pthread_once(&once_ctl, init_routine); if (ret != 0) { UNRESOLVED(ret, "pthread_once failed"); } return 0; } int main(int argc, char *argv[]) { int ret = 0, i; struct sigaction sa; pthread_barrier_t bar; pthread_t th[30]; output_init(); ret = pthread_barrier_init(&bar, 0, 30); if (ret != 0) { UNRESOLVED(ret, "Failed to init barrier"); } sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sa.sa_handler = sighdl; if ((ret = sigaction(SIGUSR1, &sa, 0))) { UNRESOLVED(ret, "Unable to register signal handler"); } if ((ret = sigaction(SIGALRM, &sa, 0))) { UNRESOLVED(ret, "Unable to register signal handler"); } while (do_it) { once_ctl = PTHREAD_ONCE_INIT; once_chk = 0; for (i = 0; i < 30; i++) { ret = pthread_create(&th[i], 0, threaded, &bar); if (ret != 0) { UNRESOLVED(ret, "Failed to create a thread"); } } for (i = 0; i < 30; i++) { ret = pthread_join(th[i], 0); if (ret != 0) { UNRESOLVED(ret, "Failed to join a thread"); } } ret = pthread_mutex_lock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to lock mutex in initializer"); } if (once_chk != 1) { output("Control: %d\\n", once_chk); FAILED("The initializer function did not execute once"); } ret = pthread_mutex_unlock(&mtx); if (ret != 0) { UNRESOLVED(ret, "Failed to unlock mutex in initializer"); } iterations++; } output("pthread_once stress test PASSED -- %llu iterations\\n", iterations); ret = pthread_barrier_destroy(&bar); if (ret != 0) { UNRESOLVED(ret, "Failed to destroy the barrier"); } PASSED; }
0
#include <pthread.h> pthread_mutex_t mutex,mutex2 ; void *my_thread_process(void *arg){ int c; for(c='a';c<='z';c++){ pthread_mutex_lock(&mutex); printf("%c\\n",c); pthread_mutex_unlock(&mutex2); } pthread_exit(0); } void *my_thread_process2(void *arg){ int c; for(c='A';c<='Z';c++){ pthread_mutex_lock(&mutex2); printf("%c\\n",c); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main (char ** argv, int argc){ pthread_t th1, th2; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutex2, 0); pthread_mutex_lock(&mutex); pthread_create(&th1, 0, my_thread_process, 0); pthread_create(&th2, 0, my_thread_process2, 0); pthread_join (th1, 0); pthread_join (th2, 0); pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutex2); }
1
#include <pthread.h> void count3s_thread(int id); pthread_t tid[8]; int t; int *my_array; int length; int count; struct padded_int { int value; char padding[60]; } private_count[8]; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void count3s() { int i; count = 0; for(i = 0; i < t; i++) { pthread_create(&tid[i], 0, count3s_thread, i); } for(i = 0; i < t; i++) { pthread_join(tid[i], 0); } } void count3s_thread(int id) { int i; int threadL = length / t; int start = id * threadL; for(i = start; i < start+threadL; i++) { if(my_array[i] == 3) { private_count[id].value++; } } pthread_mutex_lock(&m); count += private_count[id].value; pthread_mutex_unlock(&m); } int main( ) { int i; length = 5000000; t = 8; my_array = (int *)malloc(sizeof(int)*5000000); srand(12345); for(i = 0; i < length; i++) { my_array[i] = rand()% 100; } clock_t begin = clock(); count3s(); clock_t end = clock(); printf("The number of 3's is %d\\n", count); printf("\\nTime Elapsed: %f seconds\\n", (double)(end - begin) / CLOCKS_PER_SEC); return 0; }
0
#include <pthread.h> void error(char *msg) { fprintf(stderr, "%s: %s\\n", msg, strerror(errno)); exit(1); } int beers = 2000000; pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; void *drink_lots(void *a) { int i; for (i = 0; i < 100000; i++) { pthread_mutex_lock(&beers_lock); beers = beers - 1; pthread_mutex_unlock(&beers_lock); } printf("beers = %i\\n", beers); return 0; } int main() { pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers); for (t = 0; t < 20; t++) { if (pthread_create(&threads[t], 0, drink_lots, 0) == -1) error("Can't create thread"); } void *result; for (t = 0; t < 20; t++) { if (pthread_join(threads[t], &result) == -1) error("Can't join threads"); } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
1
#include <pthread.h> void Emergency_exit (int signum) { land(); close_commands_socket(); exit(signum); } void * navdata_thread() { int result = 1; printf("[NAV] Init\\n"); result = init_navdata_reception(); printf("[NAV] Init OK\\n"); if (result != 0) { printf("[NAV] Ready\\n"); while (result) { result = update_navdata(); } } printf("F*ck this, I'm outta here\\n"); return 0; } void * watchdog_thread() { while (1) { reload_watchdog(); usleep(1500000); } return 0; } int main() { signal(SIGINT, Emergency_exit); pthread_t th_navdata; pthread_t th_watchdog; initialize_connection_with_drone(); pthread_create(&th_navdata, 0, navdata_thread, 0); pthread_mutex_lock(&mutex_navdata_cond); pthread_cond_wait(&navdata_initialised, &mutex_navdata_cond); pthread_mutex_unlock(&mutex_navdata_cond); pthread_create(&th_watchdog, 0, watchdog_thread, 0); printf("It's on\\n"); sleep(2); take_off(); printf("First Altitude : %d\\n", (int) get_altitude()); sleep(2); calibrate_magnetometer(); trajectory(); land(); close_commands_socket(); return 0; }
0
#include <pthread.h> int buffer[100]; int count = 0; int in = -1, out = -1; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t buffer_has_space = PTHREAD_COND_INITIALIZER; pthread_cond_t buffer_has_data = PTHREAD_COND_INITIALIZER; void producer(void){ int i; for(i=0 ; i<1000 ; i++){ pthread_mutex_lock(&mutex); if(count==100) pthread_cond_wait(&buffer_has_space, &mutex); in++; in%=100; buffer[in] = i; count++; pthread_cond_signal(&buffer_has_data); pthread_mutex_unlock(&mutex); } } void consumer(void) { int i, data; for(i=0; i<1000; i++){ pthread_mutex_lock(&mutex); if (count ==0) pthread_cond_wait(&buffer_has_data, &mutex); out++; out %= 100; data = buffer[out]; count--; pthread_cond_signal(&buffer_has_space); pthread_mutex_unlock(&mutex); printf("data = %d\\n", data); } } int main (void) { int i ; pthread_t threads[2]; pthread_create(&threads[0], 0, (void*)producer, 0); pthread_create(&threads[1], 0, (void*)consumer, 0); for(i=0; i<2; i++) pthread_join(threads[i], 0); return 0; }
1
#include <pthread.h> static struct { int value; pthread_mutex_t mutex; pthread_cond_t cond; } money; static void *print_money(void *arg) { pthread_mutex_lock(&money.mutex); ++money.value; pthread_mutex_unlock(&money.mutex); if (0 < money.value) pthread_cond_broadcast(&money.cond); return 0; } static void *splurge(void *arg) { pthread_mutex_lock(&money.mutex); if (money.value <= 0) pthread_cond_wait(&money.cond, &money.mutex); --money.value; pthread_mutex_unlock(&money.mutex); return 0; } static void master(void) { money.value = 0; pthread_mutex_init(&money.mutex, 0); pthread_cond_init(&money.cond, 0); pthread_t gambler; pthread_t black_sheep; if (pthread_create(&gambler, 0, print_money, 0)) { abort(); } if (pthread_create(&black_sheep, 0, splurge, 0)) { abort(); } if (pthread_join(print_money, 0)) { abort(); } if (pthread_join(splurge, 0)) { abort(); } }
0
#include <pthread.h> void *threadA_main(void *arg); void *threadB_main(void *arg); static int counter=0; static pthread_mutex_t mutex; int main(int argc, char **argv) { pthread_t thread_id_1,thread_id_2; int res; pthread_mutex_init(&mutex,0); pthread_create(&thread_id_1,0,threadA_main,0); pthread_create(&thread_id_2,0,threadB_main,0); pthread_join(thread_id_1,(void **) &res); pthread_join(thread_id_2,(void **) &res); pthread_mutex_destroy(&mutex); return 0; } void *threadA_main(void *arg) { int i; for(i=0;i<10;i++) { pthread_mutex_lock(&mutex); counter+=2; printf("thread A by 2 = %d \\n",counter); pthread_mutex_unlock(&mutex); } return 0; } void *threadB_main(void *arg) { int i; for(i=0;i<10;i++) { pthread_mutex_lock(&mutex); counter+=3; printf("thread B by 3 = %d \\n",counter); pthread_mutex_unlock(&mutex); } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_empty = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_exist = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_enter = PTHREAD_COND_INITIALIZER; char text[20][10]; int val; int pro_cnt=0, cons_cnt=0; int count=0; char buf[10]; char numtoc[4]; char buffer[30]; void *Provider(void* arg) { for(pro_cnt=0; pro_cnt<100; pro_cnt++){ pthread_mutex_lock(&mutex); if(count>=20){ pthread_cond_signal(&cond_exist); pthread_cond_wait(&cond_empty, &mutex); } strcpy(buffer, "msg"); sprintf(numtoc, "%d", pro_cnt%20); strcat(buffer, numtoc); printf("Pro %s\\n", buffer); strcpy(text[pro_cnt%20], buffer); count++; pthread_mutex_unlock(&mutex); sleep(1); } } void *Cons1(void* arg) { while(cons_cnt<100){ pthread_mutex_lock(&mutex); if(count<=15){ pthread_cond_signal(&cond_empty); pthread_cond_wait(&cond_exist, &mutex); } printf("Cons1 %s(every 2 second)\\n", text[cons_cnt%20]); cons_cnt++; count--; pthread_mutex_unlock(&mutex); sleep(2); } } void *Cons2(void* arg) { while(cons_cnt<100){ pthread_mutex_lock(&mutex); pthread_cond_wait(&cond_enter, &mutex); if(count==0) pthread_cond_wait(&cond_exist, &mutex); printf("Cons2 %s(enter key)\\n", text[cons_cnt%20]); count--; cons_cnt++; if(count<=15) pthread_cond_signal(&cond_empty); pthread_mutex_unlock(&mutex); sleep(1); } } int main(void){ pthread_t thread[3]; pthread_create(&thread[0], 0, Provider, 0); pthread_create(&thread[1], 0, Cons1, 0); pthread_create(&thread[2], 0, Cons2, 0); while(cons_cnt<100){ fgets(buf, 10, stdin); if(!strcmp(buf, "\\n")){ pthread_cond_signal(&cond_enter); } } pthread_exit(0); return 0; }
0
#include <pthread.h> static void *serial_monitor(void *arg); pthread_mutex_t lock; pthread_cond_t nonfull; pthread_cond_t nonempty; int count; int last; int first; char elements[256]; } Buffer; static pthread_t pthread_receiver; static Buffer RX_buffer; static int serial_fd; void zb_transport_init() { struct termios tc; serial_fd = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY); if (serial_fd < 0) { printf("[CRITICAL] could not open serial device %s\\n", "/dev/ttyAMA0"); } fcntl(serial_fd, F_SETFL, 0); tcgetattr(serial_fd, &tc); cfsetospeed(&tc, 9600); cfsetispeed(&tc, 9600); tc.c_cflag |= (CLOCAL | CREAD); tc.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); tcsetattr(serial_fd, TCSANOW, &tc); pthread_mutex_init(&RX_buffer.lock, 0); pthread_mutex_lock(&RX_buffer.lock); pthread_cond_init(&RX_buffer.nonfull, 0); pthread_cond_init(&RX_buffer.nonempty, 0); RX_buffer.count = 0; RX_buffer.last = 0; RX_buffer.first = 0; pthread_mutex_unlock(&RX_buffer.lock); pthread_create(&pthread_receiver, 0, serial_monitor, 0); } void zb_transport_stop() { pthread_cancel(pthread_receiver); pthread_join(pthread_receiver, 0); close(serial_fd); } void zb_send(unsigned char *buf, unsigned char len) { write(serial_fd, buf, len); fsync(serial_fd); } char zb_getc() { char c; pthread_mutex_lock(&RX_buffer.lock); while (RX_buffer.count == 0) { pthread_cond_wait(&RX_buffer.nonempty, &RX_buffer.lock); } c = RX_buffer.elements[RX_buffer.first]; RX_buffer.count--; RX_buffer.first = (RX_buffer.first + 1) % 256; pthread_cond_signal(&RX_buffer.nonfull); pthread_mutex_unlock(&RX_buffer.lock); return c; } void zb_guard_delay() { usleep(1000 * 1000); } static void *serial_monitor(void *arg) { char c; printf("starting to read\\n"); while (read(serial_fd, &c, 1) > 0) { pthread_mutex_lock(&RX_buffer.lock); while (RX_buffer.count == 256) { pthread_cond_wait(&RX_buffer.nonfull, &RX_buffer.lock); } RX_buffer.elements[RX_buffer.last] = c; RX_buffer.last = (RX_buffer.last + 1) % 256; RX_buffer.count++; pthread_cond_signal(&RX_buffer.nonempty); pthread_mutex_unlock(&RX_buffer.lock); } printf("[CRITICAL] read from serial device failed.\\n"); return 0; }
1
#include <pthread.h> int reader_count = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t resource = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t service = PTHREAD_MUTEX_INITIALIZER; void *reader(void *_) { pthread_detach(pthread_self()); for (;;) { pthread_mutex_lock(&service); pthread_mutex_lock(&mutex); reader_count++; if (reader_count == 1) pthread_mutex_lock(&resource); pthread_mutex_unlock(&service); pthread_mutex_unlock(&mutex); fprintf(stderr, "reading...\\n"); pthread_mutex_lock(&mutex); reader_count--; if (reader_count == 0) pthread_mutex_unlock(&resource); pthread_mutex_unlock(&mutex); } return 0; } void *writer(void *_) { pthread_detach(pthread_self()); for (;;) { pthread_mutex_lock(&service); pthread_mutex_lock(&resource); pthread_mutex_unlock(&service); fprintf(stderr, "writing...\\n"); pthread_mutex_unlock(&resource); } return 0; } int main(void) { pthread_t id; int i; for (i = 0; i < 2; i++) { pthread_create(&id, 0, writer, 0); pthread_create(&id, 0, reader, 0); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t lock; void *system_call(void* s) { long i; int fd; char* tmp = (char*) s; if ((fd=open("write.out",O_WRONLY|O_CREAT,0644)) < 0) { fprintf(stderr,"Can't open %s. Bye.\\n","write.out"); exit(1); } for (i=0; i<50000; i++) { if (write(fd,"Y",1) < 1) { fprintf(stderr,"Can't write. Bye\\n"); exit(1); } } close(fd); pthread_mutex_lock(&lock); strcpy(tmp, "stdlibrary call thread finished first!\\n"); pthread_mutex_unlock(&lock); } void *stdlibrary_call(void* s) { long i; FILE *fp; if ((fp=fopen("fprint.out","w")) == 0) { fprintf(stderr,"Can't open %s. Bye.\\n","fprint.out"); exit(1); } for (i=0; i<400000; i++) { if (fprintf(fp,"X") < 1) { fprintf(stderr,"Can't write. Bye\\n"); exit(1); } } fclose(fp); pthread_mutex_lock(&lock); strcpy(s, "system call thread finished first!\\n"); pthread_mutex_unlock(&lock); } main() { pthread_t thread1, thread2; int ret1, ret2; char result[100]; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } ret1 = pthread_create(&thread1, 0, system_call, (void*) result); ret2 = pthread_create(&thread2, 0, stdlibrary_call, (void*) result); pthread_join(thread1, 0); pthread_join(thread2, 0); printf("%s", &result); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t cond; void * thread1(void * arg) { pthread_cleanup_push(pthread_mutex_unlock, &mutex); while(1) { pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("thread1 is appliedx the condition\\n"); pthread_mutex_unlock(&mutex); sleep(4); } pthread_cleanup_pop(0); } void * thread2(void * arg) { while(1) { printf("thread2 is running\\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond, &mutex); printf("thread2 applied the condition\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_t tid1, tid2; printf("condition variable study!\\n"); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_create(&tid1, 0, (void*)thread1, 0); pthread_create(&tid2, 0, (void*)thread2, 0); do{ pthread_cond_signal(&cond); }while(1); sleep(50); pthread_exit(0); }
0
#include <pthread.h> extern char **environ; static char envbuf[4096]; pthread_mutex_t g_env_mutex; static pthread_once_t g_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(&g_env_mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char *name, char *buf, const int buflen) { int i, len, olen; pthread_once(&g_init_done, thread_init); len = strlen(name); pthread_mutex_lock(&g_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(&g_env_mutex); return ENOSPC; } strcpy(buf, &environ[i][len+1]); pthread_mutex_unlock(&g_env_mutex); return 0; } } pthread_mutex_unlock(&g_env_mutex); return ENOENT; } void* thread_fun(void * arg) { while (1) { char buf[256] = { 0x00 }; getenv_r("PWD", buf, sizeof(buf)); printf("TID=%ul getenv_r(\\"PWD\\")=%s\\n", pthread_self(), buf); usleep(10); } return (void*)1; } int main(int argc, char* argv[]) { int ret; pthread_t t1, t2; ret = pthread_create(&t1, 0, thread_fun, 0); if (ret != 0) { printf("pthread_create() is Error t1 \\n"); exit(-1); } ret = pthread_create(&t2, 0, thread_fun, 0); if (ret != 0) { printf("pthread_create() is Error t2 \\n"); exit(-1); } while (1) { } pthread_mutex_destroy(&g_env_mutex); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t empty, full, done; int no_cycles = 2; int no_consumers = 4; int counter = 0; char *input = "Hello!"; char* buffer = '\\0'; int totalReads = 0; int totalWrites = 0; void writeToFile(int type, int num_cores, double time, int loop ){ FILE * out; out = fopen("Results_5_Raw.txt","a+"); fprintf(out,"%d,%d,%f,%d\\n",type,num_cores,time,loop); } void *producer(void *arg) { int i; for (i = 0; i < no_cycles; i++) { pthread_mutex_lock(&mutex); while (buffer != '\\0'){ pthread_cond_wait(&empty, &mutex); } buffer = input; printf("Writing new buffer.\\n"); totalWrites++; pthread_cond_signal(&full); pthread_mutex_unlock(&mutex); } } void *consumer(void *arg) { int i; for (i = 0; i < no_cycles; i++) { pthread_mutex_lock(&mutex); while (buffer == '\\0'){ pthread_cond_wait(&full, &mutex); } char* tmp = buffer; totalReads++; counter++; if(counter == no_consumers){ buffer = '\\0'; counter = 0; } pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); printf("consumer read: %s\\n", tmp); } } int main(int argc, char **argv){ char* p; if(argc >= 4){ no_cycles = strtol(argv[1], &p, 10); no_consumers = strtol(argv[2],&p,10); printf("%d %d",no_cycles, no_consumers); printf("%s is arg 3 argc %d",argv[3],argc); input = argv[3]; }else{ printf("Please pass three args: number of cycles, number of threads, and a string to write\\n"); return -1; } if(argc >= 2){ } pthread_t producert; pthread_t consumers[no_consumers]; int i = 0; pthread_cond_init(&empty,0); pthread_cond_init(&full, 0); pthread_cond_init(&done, 0); pthread_mutex_init(&mutex,0); pthread_create(&producert,0,producer,0); for(i = 0; i < no_consumers ; i++){ pthread_create(&consumers[i],0,consumer,0); pthread_join(consumers[i],0); } pthread_join(producert,0); printf("Total Reads: %d Total Writes: %d\\n",totalReads,totalWrites); }
0
#include <pthread.h> int arr[1024]; pthread_mutex_t semaphore = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t can_read = PTHREAD_COND_INITIALIZER; pthread_cond_t can_write = PTHREAD_COND_INITIALIZER; int n_reading = 0, n_writing = 0; void *escritor(void *arg){ int i; int num = *((int *)arg); for (;;) { sleep(random() % 3); pthread_mutex_lock(&semaphore); n_writing = 1; while(n_reading) pthread_cond_wait(&can_write, &semaphore); for (i = 0; i < 1024; i++) { arr[i] = num; } n_writing = 0; pthread_cond_broadcast(&can_read); pthread_mutex_unlock(&semaphore); } return 0; } void *lector(void *arg) { int v, i, err; int num = *((int *)arg); for (;;) { sleep(random() % 3); pthread_mutex_lock(&semaphore); while(n_writing) pthread_cond_wait(&can_read, &semaphore); n_reading++; pthread_mutex_unlock(&semaphore); err = 0; v = arr[0]; for (i = 1; i < 1024; i++) { if (arr[i] != v) { err = 1; break; } } if (err) printf("Lector %d, error de can_read\\n", num); else printf("Lector %d, dato %d\\n", num, v); pthread_mutex_lock(&semaphore); if(!(--n_reading)) pthread_cond_signal(&can_write); pthread_mutex_unlock(&semaphore); } return 0; } int main(){ int i; pthread_t readers[2], writers[2]; int arg[2]; for (i = 0; i < 1024; i++){ arr[i] = -1; } for (i = 0; i < 2; i++){ arg[i] = i; pthread_create(&readers[i], 0, lector, (void *)&arg[i]); pthread_create(&writers[i], 0, escritor, (void *)&arg[i]); } pthread_join(readers[0], 0); return 0; }
1
#include <pthread.h> extern struct Thread_List_Item *controlprogram_threads; extern pthread_mutex_t controlprogram_list_lock,exit_lock; extern char *controlprogram_list_lock_buffer,*exit_lock_buffer; extern int verbose; void timeout_exit(void *arg) { pthread_t tid; tid = pthread_self(); } void *timeout_handler(void *arg) { struct Thread_List_Item *thread_list,*thread_item,*thread_next; struct ControlProgram *data; struct timeval t1; long elapsed; int i,cancelled; struct ControlProgram *cprog; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0); pthread_cleanup_push(timeout_exit,0); fprintf(stdout,"Setting up thread for dead clients\\n"); fflush(stdout); while (1) { pthread_mutex_lock(&exit_lock); gettimeofday(&t1,0); if (verbose > 1 ) { fprintf(stdout,"Checking for dead clients: %d.%d\\n",(int)t1.tv_sec,(int)t1.tv_usec); fflush(stdout); fprintf(stderr,"Checking for dead clients: %d.%d\\n",(int)t1.tv_sec,(int)t1.tv_usec); fflush(stderr); } thread_list=controlprogram_threads; while(thread_list!=0){ cancelled=0; elapsed=(long)t1.tv_sec-(long)thread_list->last_seen.tv_sec; if (elapsed < 0) elapsed=0; if (verbose > 1 ) fprintf(stdout,"TIMEOUT: %p elapsed: %ld timeout: %d\\n",thread_list->data,elapsed,thread_list->timeout.tv_sec); fflush(stdout); if (elapsed > thread_list->timeout.tv_sec) { if (verbose > -1 ) fprintf(stderr,"TIMEOUT: elapsed time! %ld %d\\n",elapsed,thread_list->timeout.tv_sec); if (verbose > -1 ) fprintf(stderr," controlprogram addr: %p thread addr: %p id: %p\\n", thread_list->data,thread_list,thread_list->id); if (verbose> 0) fprintf(stderr," thread next: %p\\n",thread_list->next); if (verbose> 0) fprintf(stderr," thread prev: %p\\n",thread_list->prev); cprog=thread_list->data; if (verbose> 0) fprintf(stderr," control: %p\\n",cprog); if (cprog!=0) { if (verbose>0) fprintf(stderr," control state: %p\\n",cprog->state); if(cprog->state!=0) { cancelled=cprog->state->cancelled; if (verbose > -1) fprintf(stderr," control cancelled: %d\\n",cancelled); if (verbose > -1) fprintf(stderr,"controlprogram thread %p %p over ran timeout...trying to cancel\\n", thread_list,thread_list->id); if(cancelled==0) { pthread_mutex_unlock(&exit_lock); if (verbose > -1 ) fprintf(stderr,"TIMEOUT: Canceling client thread %p %d\\n",thread_list, thread_list->id); pthread_cancel(thread_list->id); pthread_join(thread_list->id,0); pthread_mutex_lock(&exit_lock); } else { if (verbose > -1 ) fprintf(stderr,"TIMEOUT: Client set as cancelled thread %p %d\\n",thread_list, thread_list->id); } } else { } } fflush(stderr); if (verbose> 1) fprintf(stderr," Adjusting thread list\\n"); thread_item=thread_list; thread_next=thread_item->next; thread_list=thread_item->prev; if (thread_next != 0) thread_next->prev=thread_list; else controlprogram_threads=thread_list; if (thread_list != 0) thread_list->next=thread_item->next; if (thread_item!=0) { if(thread_item->data !=0) free(thread_item->data); thread_item->data=0; free(thread_item); } thread_item=0; } else { thread_list=thread_list->prev; } } thread_list=controlprogram_threads; while(thread_list!=0){ thread_list=thread_list->prev; } pthread_mutex_unlock(&exit_lock); pthread_testcancel(); sleep(5); } if (verbose > 1 ) fprintf(stderr,"timeout handler: outside of While Loop\\n"); pthread_cleanup_pop(0); timeout_exit(0); pthread_exit(0); };
0
#include <pthread.h> pthread_mutex_t mutex; int valoresA[16], valoresB[16], separacao = 16 / 4, indiceFim; int indiceInicio = 0, sum = 0, i = 0; void *calculo(void *arg){ pthread_mutex_lock(&mutex); long int numeroThread = (long int)arg; int indiceFim = indiceInicio + separacao; if(indiceFim <= 16){ int somaParcial = 0; for(indiceInicio; indiceInicio < indiceFim; indiceInicio++){ somaParcial += valoresA[indiceInicio] * valoresB[indiceInicio]; } indiceInicio = indiceFim; printf("Thread %ld calculou de %d a %d: produto escalar parcial = %d\\n", numeroThread, indiceFim - separacao, indiceFim - 1, somaParcial); sum += somaParcial; } pthread_mutex_unlock(&mutex); } void criarEPopularVetores(){ for(i = 0; i < 16; i++){ valoresA[i] = rand()%10; valoresB[i] = rand()%10; } } void aguardarTerminoDeThreads(pthread_t thread[]){ for(i = 0; i < 4; i++){ pthread_join(thread[i], 0); } } void imprimirVetores(){ printf("\\t\\tA = "); for(i = 0; i < 16; i++){ printf("%d,", valoresA[i]); } printf("\\n"); printf("\\t\\tB = "); for(i = 0; i < 16; i++){ printf("%d,", valoresB[i]); } printf("\\n"); } int main(){ srand(time(0)); pthread_mutex_init(&mutex, 0); criarEPopularVetores(); imprimirVetores(); pthread_t vetorThreads[4]; if(!(16 < 4)){ for(i = 0; i < 4; i++){ long int numeroThread = (long int)i; pthread_create(&vetorThreads[i], 0, calculo, (void*)numeroThread); } } else { printf("O número de threads é maior que o vetor!"); return -1; } pthread_mutex_destroy(&mutex); pthread_exit(0); aguardarTerminoDeThreads(vetorThreads); printf("Produto escalar = %d\\n", sum); return 0; }
1
#include <pthread.h> pthread_t a_lock,b_lock,c_lock, d_lock; static int a; unsigned int b = 100000; unsigned int c = 200000; void *func0(void * arg,...) { unsigned int x = 100000; pthread_mutex_lock(&a_lock); pthread_mutex_lock(&a_lock); while (x--) { ++a; } pthread_mutex_unlock(&a_lock); return; } void *func1(void * arg,...) { pthread_mutex_lock(&a_lock); pthread_mutex_lock(&b_lock); while (b--) { ++a; } pthread_mutex_unlock(&b_lock); pthread_mutex_unlock(&a_lock); return; } void *func2(void * arg,...) { pthread_mutex_lock(&b_lock); pthread_mutex_lock(&a_lock); while (a--) { ++b; } pthread_mutex_unlock(&a_lock); pthread_mutex_unlock(&b_lock); return; } void *func3(void * arg,...) { pthread_mutex_lock(&a_lock); pthread_mutex_lock(&b_lock); unsigned int x = 100000; while (x--) {} pthread_mutex_unlock(&b_lock); pthread_mutex_unlock(&a_lock); return; } void *func4(void * arg,...) { pthread_mutex_lock(&b_lock); pthread_mutex_lock(&c_lock); unsigned int x = 100000; while (x--) {} pthread_mutex_unlock(&c_lock); pthread_mutex_unlock(&b_lock); return; } void *func5(void * arg,...) { pthread_mutex_lock(&c_lock); pthread_mutex_lock(&d_lock); unsigned int x = 100000; while (x--) {} pthread_mutex_unlock(&d_lock); pthread_mutex_unlock(&c_lock); return; } void *func6(void * arg,...) { pthread_mutex_lock(&d_lock); pthread_mutex_lock(&a_lock); unsigned int x = 100000; while (x--) {} pthread_mutex_unlock(&a_lock); pthread_mutex_unlock(&d_lock); return; } int main() { system("clear"); pthread_mutex_init(&a_lock, 0); pthread_mutex_init(&b_lock, 0); pthread_mutex_init(&c_lock, 0); pthread_mutex_init(&d_lock, 0); pthread_t i_thd; pthread_t j_thd, k_thd; pthread_t l_thd, m_thd, n_thd, o_thd; pthread_create(&j_thd, 0,func1, 0); pthread_create(&k_thd, 0,func2, 0); pthread_create(&l_thd, 0,func3, 0); pthread_create(&m_thd, 0,func4, 0); pthread_create(&n_thd, 0,func5, 0); pthread_create(&o_thd, 0,func6, 0); pthread_exit(0); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top = 0; static unsigned int arr[400]; pthread_mutex_t m; _Bool flag = 0; void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { top == 0 ? 1 : 0; } int push(unsigned int *stack, int x) { if (top == 400) { printf("stack overflow\\n"); return -1; } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top() == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 400; if (push(arr, tmp) == (-1)) error(); flag = 1; pthread_mutex_unlock(&m); } } } } } } void *t2(void *arg) { int i; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - 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> pthread_cond_t cond; pthread_mutex_t mutex; pthread_t thid[4]; int ocupado=1; void *t0( void *arg){ int dormir, *id; id = (int*)(arg); printf("[th %d] Inicio\\n",*id); dormir = rand()%3 + 1; printf("[th %d] Duerme %d\\n",*id,dormir); sleep(dormir); printf("[th %d] Fin\\n",*id); pthread_exit(0); } void *t1( void *arg){ int dormir, id; id = *((int*)(arg)); printf("[th %d] Inicio\\n",id); dormir = rand()%3 + 1; printf("[th %d] Duerme %d\\n",id,dormir); sleep(dormir); printf("[th %d] Fin\\n",id); pthread_exit(0); } void *t2( void *arg){ int dormir, id; pthread_mutex_lock(&mutex); id = *((int*)(arg)); pthread_cond_signal(&cond); ocupado=0; pthread_mutex_unlock(&mutex); printf("[th %d] Inicio\\n",id); dormir = rand()%3 + 1; printf("[th %d] Duerme %d\\n",id,dormir); sleep(dormir); printf("[th %d] Fin\\n",id); pthread_exit(0); } void *t3( void *arg){ int dormir, id; id = (int)(arg); printf("[th %d] Inicio\\n",id); dormir = rand()%3 + 1; printf("[th %d] Duerme %d\\n",id,dormir); sleep(dormir); printf("[th %d] Fin\\n",id); pthread_exit(0); } int main (){ int i; printf("==== [main] Inicio Test 0 Crea N t0 y espera====\\n"); for (i=0;i<4;i++) pthread_create (&thid[i], 0, t0, (void *)&i); for (i=0;i<4;i++) pthread_join(thid[i], 0); printf("==== [main] Inicio Test 1 Crea N t1 y espera====\\n"); for (i=0;i<4;i++) pthread_create (&thid[i], 0, t1, (void *)&i); for (i=0;i<4;i++) pthread_join(thid[i], 0); printf("==== [main] Inicio Test 2 Crea N bucles (t1, dormir 1 seg) y espera ====\\n"); for (i=0;i<4;i++){ pthread_create (&thid[i], 0, t1, (void *)&i); sleep(1); } for (i=0;i<4;i++) pthread_join(thid[i], 0); printf("==== [main] Inicio Test 3 Crea N bucles t2 usando mutex y variables condicion ====\\n"); ocupado = 1; pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); for (i=0;i<4;i++){ pthread_mutex_lock(&mutex); pthread_create (&thid[i], 0, t2, (void *)&i); while(ocupado){ pthread_cond_wait(&cond,&mutex); } ocupado=1; pthread_mutex_unlock(&mutex); } for (i=0;i<4;i++) pthread_join(thid[i], 0); printf("==== [main] Fin ====\\n"); }
0
#include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; char work_area[1024]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, 0); if (res != 0) { perror("Mutex initialization failed"); exit(1); } res = pthread_create(&a_thread, 0, thread_function, 0); if (res != 0) { perror("Thread creation failed"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Input some text. Enter 'end' to finish\\n"); while(!time_to_exit) { fgets(work_area, 1024, stdin); pthread_mutex_unlock(&work_mutex); while(1) { pthread_mutex_lock(&work_mutex); if (work_area[0] != '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); } else { break; } } } pthread_mutex_unlock(&work_mutex); printf("\\nWaiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); exit(0); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while(strncmp("end", work_area, 3) != 0) { printf("You input %d characters\\n", strlen(work_area) -1); work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while (work_area[0] == '\\0' ) { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; work_area[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
1
#include <pthread.h> int recordSize = 1024; int threadsNr; char *fileName; int fd; int numOfRecords; int creatingFinished = 0; char *word; int rc; int someonefound = 0; int detachedNr = 0; pthread_key_t key; pthread_t *threads; int *wasJoin; pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER; long gettid() { return syscall(SYS_gettid); } void signalHandler(int signal){ if(signal == SIGUSR1) { printf("Received SIGUSR1\\n"); } else if(signal == SIGTERM) { printf("Received SIGTERM\\n"); } printf("PID: %d TID: %ld\\n", getpid(), pthread_self()); return; } void* threadFun(void *oneArg) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); pthread_t threadHandle = pthread_self(); pthread_t threadID = gettid(); printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID); char **readRecords; readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); if(pthread_equal(threadHandle,threads[0])!=0) sleep(2); pthread_setspecific(key, readRecords); readRecords = pthread_getspecific(key); while(!creatingFinished); int finish = 0; int moreBytesToRead = 1; int numOfReadedBytes; while(!finish && moreBytesToRead) { pthread_mutex_lock(&mutexForRecords); for(int i=0;i<numOfRecords;i++) { numOfReadedBytes = read(fd, readRecords[i], 1024); if(numOfReadedBytes==-1) { perror("error while reading in threadFun"); exit(1); } if(numOfReadedBytes<1024) moreBytesToRead = 0; } pthread_mutex_unlock(&mutexForRecords); for(int i = 0; i<numOfRecords; i++) { if(strstr(readRecords[i], word) != 0) { char recID[10]; strncpy(recID, readRecords[i], 10); printf("%ld: found word in record number %d\\n", threadID, atoi(recID)); } } } if(pthread_detach(threadHandle) != 0) { perror("pthread_detach error"); exit(1); } detachedNr++; pthread_exit(0); } int openFile(char *fileName) { int fd = open(fileName, O_RDONLY); if(fd == -1) { perror("file open error"); exit(-1); } else return fd; } void createThread(pthread_t *thread) { rc = pthread_create(thread, 0, threadFun, 0); if(rc != 0) { perror("thread create error"); exit(-1); } } int main(int argc, char *argv[]) { if(argc!=6) { puts("Bad number of arguments"); puts("Appropriate arguments:"); printf("[program] [threads nr] [file] \\n"); printf("[records nr] [word to find] [test nr]"); return 1; } printf("MAIN -> PID: %d TID: %ld\\n", getpid(), pthread_self()); threadsNr = atoi(argv[1]); fileName = calloc(1,sizeof(argv[2])); fileName = argv[2]; numOfRecords = atoi(argv[3]); word = calloc(1,sizeof(argv[4])); word = argv[4]; int test = atoi(argv[5]); if(test != 1 && test != 2) { puts("wrong test number"); exit(1); } fd = openFile(fileName); char **readRecords = calloc(numOfRecords, sizeof(char*)); for(int i = 0;i<numOfRecords;i++) readRecords[i] = calloc(1024, sizeof(char)); pthread_key_create(&key, 0); threads = calloc(threadsNr, sizeof(pthread_t)); wasJoin = calloc(threadsNr, sizeof(int)); for(int i=0; i<threadsNr; i++) { createThread(&threads[i]); } creatingFinished = 1; usleep(100); if(test == 1) { puts("sending SIGUSR1 signal"); signal(SIGUSR1, signalHandler); pthread_kill(threads[0],SIGUSR1); } if(test == 2) { puts("sending SIGTERM signal"); signal(SIGTERM, signalHandler); pthread_kill(threads[0],SIGTERM); } while(detachedNr != threadsNr) { usleep(100); } printf("End of program\\n\\n"); if(close(fd)<0) { perror("close error"); return 1; } free(threads); return 0; }
0
#include <pthread.h> int buffer[10]; int bufferindicator = 0; int readbufferindex = 0; pthread_mutex_t cmutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cempty = PTHREAD_COND_INITIALIZER; pthread_cond_t cfull = PTHREAD_COND_INITIALIZER; void* writer_thread(void *arg) { int loopindex = 0; int bufferindex = 0; while(loopindex < 20) { pthread_mutex_lock(&cmutex); printf("Mutex locked by writer thread %d\\n", pthread_self() ); if (10 -1 == bufferindex) bufferindex = 0; else bufferindex++; while (bufferindicator == 10) { pthread_cond_signal(&cempty); pthread_cond_wait(&cfull,&cmutex); } buffer[bufferindex] = loopindex++; bufferindicator++; if (10 -1 == bufferindex) bufferindex = 0; else bufferindex++; pthread_cond_broadcast(&cempty); pthread_mutex_unlock(&cmutex); } return 0; } void* reader_thread(void *arg) { int loopindex = 0; while(loopindex < 20) { printf("\\nReader thread %d trying to lock mutex\\n", pthread_self()); pthread_mutex_lock(&cmutex); printf("I am going to sleeping threadid %d\\n",pthread_self()); while (bufferindicator == 0) { printf("\\nReader thread %d is waiting on condition cempty\\n", pthread_self() ); pthread_cond_wait(&cempty,&cmutex); } printf("threadid %d : buffer[%d] = %d\\n",pthread_self(), readbufferindex, buffer[readbufferindex]); bufferindicator--; if (readbufferindex == (10 -1)) readbufferindex = 0; else readbufferindex++; pthread_cond_signal(&cempty); printf("\\n Reader thread %d signalling condition cempty\\n", pthread_self() ); pthread_mutex_unlock(&cmutex); printf("I will not sleep now threadid %d\\n",pthread_self()); sleep(1); } return 0; } int main(void) { pthread_t tid1, tid2, tid3, tid4; int rv1,rv2; pthread_attr_t attr; pthread_attr_init(&attr); rv1 = pthread_create(&tid1,&attr,(void *)writer_thread,0); if(rv1 != 0) { printf("\\n Cannot create thread"); exit(0); } rv1 = pthread_create(&tid2,&attr,(void *)reader_thread,0); if(rv1 != 0) { printf("\\n Cannot create thread"); exit(0); } rv1 = pthread_create(&tid3,&attr,(void *)reader_thread,0); rv1 = pthread_create(&tid4,&attr,(void *)reader_thread,0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); return(0); }
1
#include <pthread.h> FILE *__log_out_file = 0; int __log_out_priority = 0; static int write_count = 0; static int flag_fflush = 0; static unsigned int file_max_sizes = 0; static pthread_mutex_t log_mtx = PTHREAD_MUTEX_INITIALIZER; static unsigned int threshold_switch = 10000; static unsigned int threshold_switch_size = 1024*1024; static unsigned int total_num = 0; char file_name[16][64]; static char prefix[64] = { 0 }; char LEVEL[6][16] = { {"LOG_FATAL"}, {"LOG_ERROR"}, {"LOG_WARN "}, {"LOG_INFO "}, {"LOG_DEBUG"}, {""}}; static void Log_switch() { printf("Log_switch \\n"); struct stat stat_info; sprintf(file_name[0], "%s.%d", prefix, 0); stat(file_name[0], &stat_info); printf("%s: %ld*%ld=%ld, %ld\\n", file_name[0], stat_info.st_blksize, stat_info.st_blocks, stat_info.st_blksize * stat_info.st_blocks, stat_info.st_size); if(stat_info.st_size > threshold_switch_size) { if(__log_out_file) { fclose(__log_out_file); __log_out_file = 0; } int i = total_num-1; for(;i >= 1; i--){ if(i == total_num -1){ unlink(file_name[i]); } printf("file_name[%d] = %s , file_name[%d] = %s\\n", i-1, file_name[i-1], i, file_name[i]); rename(file_name[i -1], file_name[i]); } __log_out_file = fopen(file_name[0], "w+"); } } static void Log_switch_bak() { printf("Log_switch_bak \\n"); int i = total_num-1; for(;i >= 1; i--){ if(i == total_num -1){ unlink(file_name[i]); } printf("file_name[%d] = %s , file_name[%d] = %s\\n", i-1, file_name[i-1], i, file_name[i]); rename(file_name[i -1], file_name[i]); } } int Log_init(const char *prefix_str, unsigned int log_file_num, unsigned int max_size, int priority, int buffer_flag) { if(prefix == 0 || log_file_num < 1 || log_file_num > 16) { return -1; } if(buffer_flag){ flag_fflush = 0; }else { flag_fflush = 1; } if(max_size < threshold_switch_size) file_max_sizes = threshold_switch_size; else { file_max_sizes = max_size; threshold_switch_size = max_size; } pthread_mutex_lock(&log_mtx); memset(file_name, 0x00, sizeof(file_name)); write_count = 0; total_num = log_file_num; __log_out_priority = priority; strcpy(prefix, prefix_str); int i = total_num-1; for(;i >= 0; i--){ sprintf(file_name[i], "%s.%d", prefix, i); printf("file_name[%d] = %s\\n", i, file_name[i]); } Log_switch_bak(); __log_out_file = fopen(file_name[0], "w+"); pthread_mutex_unlock(&log_mtx); return 0; } void Log_close() { __log_out_priority = 0; if(__log_out_file) { fclose(__log_out_file); __log_out_file = 0; } } inline void Log_write(int priority, const char* a_format,...) { va_list va; __builtin_va_start((va)); pthread_mutex_lock(&log_mtx); write_count++; if(write_count % threshold_switch == 0) { write_count = 0; Log_switch(); } vfprintf(__log_out_file, a_format, va); if(flag_fflush)fflush(__log_out_file); pthread_mutex_unlock(&log_mtx); ; } void *thread_write1(void *param) { int count = 0; do { LOG_ALL(LOG_INFO, "thread_write1_%d\\n", count); count++; }while(count < 500000); return 0; } void *thread_write2(void *param) { int count = 0; do { LOG_ALL(LOG_WARN, "thread_write2_%d\\n", count); count++; }while(count < 500000); return 0; } void *thread_write3(void *param) { int count = 0; do { LOG_ALL(LOG_ERROR, "thread_write2_%d\\n", count); count++; }while(count < 500000); return 0; } int main1() { Log_init("log_test", 3, 1024*1024*10, LOG_INFO, LOG_WITH_BUFFER); pthread_t pid1, pid2; struct timeval tv, tv_bak; gettimeofday(&tv_bak, 0); Log_write(1, "main start:%ld %ld\\n", tv_bak.tv_sec, tv_bak.tv_usec); pthread_create(&pid1, 0, thread_write1, 0); pthread_create(&pid2, 0, thread_write2, 0); pthread_join(pid1, 0); pthread_join(pid2, 0); gettimeofday(&tv, 0); printf("main exit:%ld %ld \\n", tv.tv_sec - tv_bak.tv_sec, tv.tv_usec - tv_bak.tv_usec); struct stat stat_info; Log_close(); char file_name[64] = { 0 }; sprintf(file_name, "%s.%d", prefix, 0); stat(file_name, &stat_info); printf("%s: %ld\\n", file_name, stat_info.st_blksize * stat_info.st_blocks); return 0; }
0
#include <pthread.h> int value; int divisors; } result_t; result_t vals[5]; int size; pthread_mutex_t mutex; pthread_cond_t cond; } stack_t; stack_t stack; int g_max; int g_next; pthread_mutex_t g_next_mtx; int num_divisors(int v) { int cnt = 0; for (int i = 1; i <= v; i++) if (v % i == 0) cnt++; return (cnt); } int inc_value() { int r; pthread_mutex_lock(&g_next_mtx); r = g_next++; pthread_mutex_unlock(&g_next_mtx); return (r); } void stack_push(stack_t *stack, result_t *value) { pthread_mutex_lock(&stack->mutex); while (stack->size == 5) pthread_cond_wait(&stack->cond, &stack->mutex); stack->vals[stack->size++] = *value; pthread_cond_signal(&stack->cond); pthread_mutex_unlock(&stack->mutex); } void stack_pop(stack_t *stack, result_t *value) { pthread_mutex_lock(&stack->mutex); while (stack->size == 0) pthread_cond_wait(&stack->cond, &stack->mutex); *value = stack->vals[--stack->size]; pthread_cond_signal(&stack->cond); pthread_mutex_unlock(&stack->mutex); } void stack_init(stack_t *stack) { bzero(stack, sizeof (stack_t)); pthread_mutex_init(&stack->mutex, 0); pthread_cond_init(&stack->cond, 0); } void stack_destroy(stack_t *stack) { pthread_cond_destroy(&stack->cond); pthread_mutex_destroy(&stack->mutex); } void *thread(void *p) { result_t res; while ((res.value = inc_value()) <= g_max) { res.divisors = num_divisors(res.value); stack_push(&stack, &res); } return (0); } int main(int argc, char *argv[]) { pthread_t thread_pool[5]; void *r; result_t res, best; if (argc < 2) { fprintf(stderr, "chybi argument\\n"); return (1); } bzero(&res, sizeof (result_t)); bzero(&best, sizeof (result_t)); g_max = atoi(argv[1]); g_next = 0; stack_init(&stack); for (int i = 0; i < 5; i++) pthread_create(&thread_pool[i], 0, thread, 0); for (int i = 0; i <= g_max; i++) { stack_pop(&stack, &res); if (res.divisors > best.divisors) { best = res; printf("\\nNovy nejlepsi vysledek [%d]: %d\\n", best.value, best.divisors); } printf("\\r%3.02f%%", 100.0f * ((float) res.value / (float) g_max)); } printf("\\nNejvice delitelu ma %d: %d\\n", best.value, best.divisors); for (int i = 0; i < 5; i++) pthread_join(thread_pool[i], &r); stack_destroy(&stack); return (0); }
1
#include <pthread.h> const char *names[5] = { "Aristoteles", "Kant", "Platon", "Marx", "Aquin" }; pthread_mutex_t forks[5]; const char *topic[5] = { "Spaghetti!", "Life", "Universe", "Everything", "Bathroom" }; void print(int y, int x, const char *fmt, ...) { static pthread_mutex_t screen = PTHREAD_MUTEX_INITIALIZER; va_list ap; __builtin_va_start((ap)); pthread_mutex_lock(&screen); printf("\\033[%d;%dH", y + 1, x), vprintf(fmt, ap); printf("\\033[%d;%dH", 5 + 1, 1), fflush(stdout); pthread_mutex_unlock(&screen); } void eat(int id) { int f[2], ration, i; f[0] = f[1] = id; f[id & 1] = (id + 1) % 5; print(id, 12, "\\033[K"); print(id, 12, "..oO (forks, need forks)"); for (i = 0; i < 2; i++) { pthread_mutex_lock(forks + f[i]); if (!i) print(id, 12, "\\033[K"); print(id, 12 + (f[i] != id) * 6, "fork%d", f[i]); sleep(1); } for (i = 0, ration = 3 + rand() % 8; i < ration; i++) print(id, 24 + i * 4, "nom"), sleep(1); for (i = 0; i < 2; i++) pthread_mutex_unlock(forks + f[i]); } void think(int id) { int i, t; char buf[64] = {0}; do { print(id, 12, "\\033[K"); sprintf(buf, "..oO (%s)", topic[t = rand() % 5]); for (i = 0; buf[i]; i++) { print(id, i+12, "%c", buf[i]); if (i < 5) usleep(200000); } usleep(500000 + rand() % 1000000); } while (t); } void* philosophize(void *a) { int id = *(int*)a; print(id, 1, "%10s", names[id]); while(1) think(id), eat(id); } int main() { int i, id[5]; pthread_t tid[5]; for (i = 0; i < 5; i++) pthread_mutex_init(forks + (id[i] = i), 0); for (i = 0; i < 5; i++) pthread_create(tid + i, 0, philosophize, id + i); return pthread_join(tid[0], 0); }
0
#include <pthread.h> void * mujer_quiere_entrar(); void * hombre_quiere_entrar(); void mujer_sale(); void hombre_sale(); pthread_mutex_t mutex_bano = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_hombres = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_mujeres = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t permitir_hombres = PTHREAD_COND_INITIALIZER; pthread_cond_t permitir_mujeres = PTHREAD_COND_INITIALIZER; int ocupado, mujeres_espera,mujeres_dentro,hombres_espera,hombres_dentro; int main(){ srand(time(0)); mujeres_espera = 0; hombres_espera = 0; mujeres_dentro = 0; hombres_dentro = 0; ocupado = 2; pthread_t * cola_entrar = (pthread_t *) malloc(20 * sizeof(pthread_t)); printf("Sanitario Vacio\\n"); int i; for(i = 0; i < 20; ++i){ sleep(rand() % 5); if(rand() % 2 == 0) pthread_create(cola_entrar+i,0,hombre_quiere_entrar,0); else pthread_create(cola_entrar+i,0,mujer_quiere_entrar,0); } int j; for(j = 0; j < 20; ++j) pthread_join(*(cola_entrar+j),0); free(cola_entrar); return 0; } void * mujer_quiere_entrar(){ pthread_mutex_lock(&mutex_mujeres); mujeres_espera++; printf("Llega una mujer (%d en espera)\\n",mujeres_espera); pthread_mutex_unlock(&mutex_mujeres); pthread_mutex_lock(&mutex_bano); if(ocupado == 0) pthread_cond_wait(&permitir_mujeres,&mutex_bano); if(ocupado == 2 || ocupado == 1){ ocupado = 1; pthread_mutex_lock(&mutex_mujeres); mujeres_espera--; mujeres_dentro++; printf("Entra una mujer (%d en espera)\\n",mujeres_espera); printf("Sanitario ocupado por mujeres\\n"); pthread_mutex_unlock(&mutex_mujeres); } pthread_mutex_unlock(&mutex_bano); sleep(rand() % 5); mujer_sale(); pthread_exit(0); } void * hombre_quiere_entrar(){ pthread_mutex_lock(&mutex_hombres); hombres_espera++; printf("Llega un hombre (%d en espera)\\n",hombres_espera); pthread_mutex_unlock(&mutex_hombres); pthread_mutex_lock(&mutex_bano); if(ocupado == 1) pthread_cond_wait(&permitir_hombres,&mutex_bano); if(ocupado == 2 || ocupado == 0){ ocupado = 0; pthread_mutex_lock(&mutex_hombres); hombres_espera--; hombres_dentro++; printf("Entra un hombre (%d en espera)\\n",hombres_espera); printf("Sanitario ocupado por hombres\\n"); pthread_mutex_unlock(&mutex_hombres); } pthread_mutex_unlock(&mutex_bano); sleep(rand() % 20); hombre_sale(); pthread_exit(0); } void mujer_sale(){ pthread_mutex_lock(&mutex_mujeres); mujeres_dentro--; printf("Sale una mujer\\n"); if(mujeres_dentro == 0){ pthread_mutex_lock(&mutex_bano); ocupado = 2; pthread_cond_broadcast(&permitir_hombres); printf("Sanitario vacio\\n"); pthread_mutex_unlock(&mutex_bano); } pthread_mutex_unlock(&mutex_mujeres); } void hombre_sale(){ pthread_mutex_lock(&mutex_hombres); hombres_dentro--; printf("Sale un hombre\\n"); if (hombres_dentro == 0){ pthread_mutex_lock(&mutex_bano); ocupado = 2; pthread_cond_broadcast(&permitir_mujeres); printf("Sanitario vacio\\n"); pthread_mutex_unlock(&mutex_bano); } pthread_mutex_unlock(&mutex_hombres); }
1
#include <pthread.h> int count = 0; int K; pthread_mutex_t my_mutex; struct timeval start, end; void error(char *msg) { perror(msg); exit(0); } void *connection_handler(void *socket_desc); int main(int argc, char *argv[]) { int i,N,global_time; void *res; count = 0; N = atoi(argv[1]); K = atoi(argv[2]); gettimeofday(&start, 0); pthread_t sniffer_thread[N]; for (i=0; i<N; i++) { if( pthread_create( &sniffer_thread[i] , 0 , connection_handler , (void*) &i) < 0) { perror("could not create thread"); return 1; } } for (i = 0; i < N; ++i) { if(pthread_join(sniffer_thread[i],&res) != 0){ perror("Error Joining\\n"); } } gettimeofday(&end, 0); global_time = (end.tv_sec * 1000000 + end.tv_usec)- (start.tv_sec * 1000000 + start.tv_usec); printf("Count -> %d\\n",count); printf("Time taken -> %d\\n", global_time); pthread_exit(0); free(res); return 0; } void *connection_handler(void *threadid){ int* threadnum = (int*)threadid; int r=0; while(r<K){ pthread_mutex_lock(&my_mutex); count = count +1; pthread_mutex_unlock(&my_mutex); r++; } return 0; }
0
#include <pthread.h> char buf[128]; size_t pos; size_t len; int write_closed; pthread_mutex_t mutex; } bbuffer; bbuffer* bbuffer_new(void) { bbuffer* bb = (bbuffer*) malloc(sizeof(bbuffer)); bb->pos = 0; bb->len = 0; bb->write_closed = 0; pthread_mutex_init(&bb->mutex, 0); return bb; } ssize_t bbuffer_write(bbuffer* bb, const char* buf, size_t sz) { size_t pos = 0; pthread_mutex_lock(&bb->mutex); assert(!bb->write_closed); while (pos < sz && bb->len < sizeof(bb->buf)) { size_t bb_index = (bb->pos + bb->len) % sizeof(bb->buf); size_t ncopy = sz - pos; if (ncopy > sizeof(bb->buf) - bb_index) { ncopy = sizeof(bb->buf) - bb_index; } if (ncopy > sizeof(bb->buf) - bb->len) { ncopy = sizeof(bb->buf) - bb->len; } memcpy(&bb->buf[bb_index], &buf[pos], ncopy); bb->len += ncopy; pos += ncopy; } pthread_mutex_unlock(&bb->mutex); if (pos == 0 && sz > 0) { return -1; } else { return pos; } } ssize_t bbuffer_read(bbuffer* bb, char* buf, size_t sz) { size_t pos = 0; pthread_mutex_lock(&bb->mutex); while (pos < sz && bb->len > 0) { size_t ncopy = sz - pos; if (ncopy > sizeof(bb->buf) - bb->pos) { ncopy = sizeof(bb->buf) - bb->pos; } if (ncopy > bb->len) { ncopy = bb->len; } memcpy(&buf[pos], &bb->buf[bb->pos], ncopy); bb->pos = (bb->pos + ncopy) % sizeof(bb->buf); bb->len -= ncopy; pos += ncopy; } int write_closed = bb->write_closed; pthread_mutex_unlock(&bb->mutex); if (pos == 0 && sz > 0 && !write_closed) { return -1; } else { return pos; } } void bbuffer_shutdown_write(bbuffer* bb) { pthread_mutex_lock(&bb->mutex); bb->write_closed = 1; pthread_mutex_unlock(&bb->mutex); } void* writer_threadfunc(void* arg) { const char message[] = "Hello world!\\n"; const size_t message_len = strlen(message); bbuffer* bb = (bbuffer*) arg; for (int i = 0; i != 1000000; ++i) { size_t pos = 0; while (pos < message_len) { ssize_t nwritten = bbuffer_write(bb, &message[pos], message_len - pos); if (nwritten > -1) { pos += nwritten; } } } bbuffer_shutdown_write(bb); return 0; } void* reader_threadfunc(void* arg) { bbuffer* bb = (bbuffer*) arg; char buf[1024]; ssize_t nread; while ((nread = bbuffer_read(bb, buf, sizeof(buf))) != 0) { if (nread > -1) { fwrite(buf, 1, nread, stdout); } } return 0; } int main() { bbuffer* bb = bbuffer_new(); pthread_t reader, writer; pthread_create(&reader, 0, reader_threadfunc, (void*) bb); pthread_create(&writer, 0, writer_threadfunc, (void*) bb); pthread_join(reader, 0); pthread_join(writer, 0); }
1
#include <pthread.h> int sum = 0; pthread_mutex_t mutex; void * func(void * n) { printf("thread %ld start\\n", pthread_self()); int *mark = (int *) n; for (int i = 0; i < 10000000; i++) { pthread_mutex_lock(&mutex); if (*mark == 1) sum++; else sum--; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char const *argv[]) { pthread_t thread1, thread2; int plus = 1; int minus = 0; pthread_mutex_init(&mutex, 0); pthread_create(&thread1, 0, func, (void *) &plus); pthread_create(&thread2, 0, func, (void *) &minus); for (int i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); sum++; pthread_mutex_unlock(&mutex); } pthread_join(thread1, 0); pthread_join(thread2, 0); printf("sum: %d\\n", sum); return 0; }
0
#include <pthread.h> char * compressMe = 0; char * finalFileName = 0; pthread_mutex_t lock; int compressT_LOLS(char * fileName, int numOutputs) { FILE * file = fopen(fileName, "r"); if(!file) { printf("The file could not be found.\\nName:\\t%s\\n", fileName); printf("The file must be in the same directory as the executable.\\n"); return 1; } int fileLen = 0; compressMe = (char *)malloc(sizeof(char)); compressMe[0] = '\\0'; char c; finalFileName = convertFileName(fileName, 'T'); do { c = fgetc(file); if(feof(file)) break; if((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) { fileLen++; } compressMe = append(compressMe, c); } while (1); compressMe = removeNonAlphaChars(compressMe); if (fileLen < numOutputs) { printf("There is a request for more outputs than characters in the file. This is not possible\\n"); fclose(file); free(compressMe); return 1; } fclose(file); int ** arguements = (int **)malloc(sizeof(int *)*numOutputs); int i; for (i = 0; i < numOutputs; i++) { arguements[i] = (int *)malloc(sizeof(int)*3); } int sizeChunks = fileLen / numOutputs; int extra = fileLen % numOutputs; int currentIndex = 0; pthread_t * tids = (pthread_t *)malloc(sizeof(pthread_t *)*numOutputs); for (i = 0; i < numOutputs; i++) { arguements[i][0] = currentIndex; arguements[i][1] = sizeChunks + extra; arguements[i][2] = i; pthread_mutex_lock(&lock); pthread_create(&tids[i], 0, threadWorker, arguements[i]); pthread_mutex_unlock(&lock); currentIndex = currentIndex + sizeChunks + extra; extra = 0; } for (i = 0; i < numOutputs; i++) { pthread_join(tids[i], 0); } pthread_mutex_destroy(&lock); free(tids); freeArgsT(arguements, numOutputs); return 0; } void * threadWorker(void * args) { int start, size, threadNum; start = (int)((int *)args)[0]; size = (int)((int *)args)[1]; threadNum = (int)((int *)args)[2]; char * compressed = (char *)malloc(sizeof(char)*(size + 1)); compressed[size] = '\\0'; int i; int j = 0; for (i = start; j < size; j++) { compressed[j] = compressMe[i]; i++; } compressed = LOLS_compress(compressed); char * threadSpecific = (char *)malloc(sizeof(finalFileName)); char * number = intToString(threadNum); char * extension = (char *)malloc(sizeof(char)*5); extension[0] = '.'; extension[1] = 't'; extension[2] = 'x'; extension[3] = 't'; extension[4] = '\\0'; number = concatenate(number, extension); strcpy(threadSpecific, finalFileName); threadSpecific = concatenate(threadSpecific, number); FILE * file = fopen(threadSpecific, "ab+"); fprintf(file, "%s", compressed); fclose(file); free(threadSpecific); free(compressed); return 0; } int freeArgsT(int ** args, int numArgs) { int i; for (i = 0; i < numArgs; i++) free(args[i]); free(args); return 0; }
1
#include <pthread.h> char* string; struct list* next; } List; pthread_mutex_t synchronzer; List* list; } headList; headList* create_list(headList* head){ head = (headList*)malloc(sizeof(headList)); pthread_mutex_init(&head->synchronzer, 0); head->list = 0; return head; } void new_node(headList* head, char* str){ if(head == 0){ printf("%s\\n", "Head isnt exist!"); return; } else if(head->list == 0){ pthread_mutex_lock(&head->synchronzer); head->list = (List*)malloc(sizeof(List)); head->list->string = (char*)malloc(strlen(str) + 1); strcpy(head->list->string, str); pthread_mutex_unlock(&head->synchronzer); } else{ pthread_mutex_lock(&head->synchronzer); List* tmp = (List*)malloc(sizeof(List)); tmp->string = (char*)malloc(strlen(str) + 1); strcpy(tmp->string, str); tmp->next = head->list; head->list = tmp; pthread_mutex_unlock(&head->synchronzer); } } void print_list(headList *head){ pthread_mutex_lock(&head->synchronzer); printf("\\nList:\\n"); List* t = 0; List* list = head->list; while(list != 0){ printf(" %s\\n", list->string); t = list->next; list = t; } pthread_mutex_unlock(&head->synchronzer); } void swap(List* a, List* b){ char* c = a->string; a->string = b->string; b->string = c; } void* sort_list(void* head){ headList* headr = (headList*)head; for(;;){ sleep(5); if(((headList*)head)->list == 0){ continue; } pthread_mutex_lock(&headr->synchronzer); for(List* i = headr->list; i != 0; i = i->next){ for(List* j = i->next; j != 0; j = j->next){ if(strcmp(i->string, j->string) > 0){ swap(i, j); } } } pthread_mutex_unlock(&headr->synchronzer); } } void freeList(headList* head){ pthread_mutex_destroy(&head->synchronzer); List* list = head->list; while(list != 0){ List* tmp = list->next; free(list); list = tmp; } free(head); } int main(){ char tmp[80]; headList *head = create_list(head); pthread_t sorter; pthread_create(&sorter, 0, sort_list, (void*)head); for(;;){ fgets(tmp, 80, stdin); tmp[strlen(tmp) - 1] = '\\0'; if(strcmp("", tmp) == 0){ print_list(head); } else if(tmp[0] == '.'){ break; } else{ new_node(head, tmp); } } pthread_cancel(sorter); pthread_join(sorter, 0); freeList(head); return 0; }
0
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(400)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(400)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (400)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (400)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (400)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(400); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(400); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR:__VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR:__VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int tasks = 0, done = 0; pthread_mutex_t lock; char localdate[9]; char locallogNo[7]; char localTime[7]; int a; }tBfans; void dummy_task(void *arg) { usleep(100); pthread_mutex_lock(&lock); tBfans *tfans; tfans = (tBfans *)arg; printf("localdate: %s\\ta: %d\\n", tfans->localdate, tfans->a); done++; pthread_mutex_unlock(&lock); } int main(int argc, char **argv) { threadpool_t *pool; int i; tBfans tb; tBfans fans[1000]; strcpy(tb.localdate, "20161103"); pthread_mutex_init(&lock, 0); assert((pool = threadpool_create(32, 256, 0)) != 0); fprintf(stderr, "Pool started with %d threads and " "queue size of %d\\n", 32, 256); for( i=0 ; i<10 ; i++ ) { tb.a = i; fans[i] = tb; if(threadpool_add(pool, &dummy_task, (void *)&fans[i], 0) == 0) { pthread_mutex_lock(&lock); tasks++; pthread_mutex_unlock(&lock); } } fprintf(stderr, "Added %d tasks\\n", tasks); assert(threadpool_destroy(pool, 1) == 0); fprintf(stderr, "Did %d tasks\\n", done); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static void *thread_func1(void *ignored_argument) { int s; s = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); if (s != 0) { perror("pthread_setcancelstate"); exit(1); } pthread_mutex_lock(&mutex); printf(" thread 1 acquire mutex \\n"); sleep(10); pthread_mutex_unlock(&mutex); printf(" thread 1 releases mutex \\n"); return 0; } static void *thread_func2(void *ignored_argument) { int s; sleep(5); pthread_mutex_lock(&mutex); printf(" thread 2 acquire mutex \\n"); pthread_mutex_unlock(&mutex); printf(" thread 2 releases mutex \\n"); return 0; } int main(void) { pthread_t thr1,thr2; void *res; int s; s = pthread_create(&thr1, 0, &thread_func1, 0); if (s != 0) { perror("pthread_create"); exit(1); } s = pthread_create(&thr2, 0, &thread_func2, 0); if (s != 0) { perror("pthread_create"); exit(1); } sleep(2); printf("main(): sending cancellation request\\n"); s = pthread_cancel(thr1); if (s != 0) { perror("pthread_cancel"); exit(1); } s = pthread_join(thr1, &res); if (s != 0) { perror("pthread_join"); exit(1); } if (res == PTHREAD_CANCELED) printf("main(): thread was canceled\\n"); else printf("main(): thread wasn't canceled\\n"); s = pthread_join(thr2, &res); if (s != 0) { perror("pthread_join"); exit(1); } exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; int shared = 0; void init() { wiringPiSetup(); pinMode(7, OUTPUT); pinMode(0, OUTPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); } void reset() { digitalWrite(7, LOW); digitalWrite(0, LOW); digitalWrite(2, LOW); digitalWrite(3, LOW); } void *dispfun() { init(); while (1) { int n = shared; printf("dispthread\\t%lu: %d\\n", pthread_self(), n); digitalWrite(7, (n >> 0) & 1); digitalWrite(0, (n >> 1) & 1); digitalWrite(2, (n >> 2) & 1); digitalWrite(3, (n >> 3) & 1); sleep(1); } reset(); return 0; } void *incfun() { pthread_mutex_lock(&mutex); int i; for (i = 0; i < 15; i++) { shared++; printf("incthread\\t%lu\\n", pthread_self()); sleep(1); } pthread_mutex_unlock(&mutex); return 0; } void *decfun() { pthread_mutex_lock(&mutex); int i; for (i = 0; i < 10; i++) { shared--; printf("decthread\\t%lu\\n", pthread_self()); sleep(1); } pthread_mutex_unlock(&mutex); return 0; } int create(pthread_t *thread, pthread_attr_t *thread_attr, void *(threadfun)(void*), char* message) { if (pthread_create(thread, thread_attr, threadfun, 0) != 0) { printf("Error creating %s\\n", message); return 1; } printf("%s id: %lu\\n", message, *thread); return 0; } int join(pthread_t thread, char* message) { if (pthread_join(thread, 0) != 0) { printf("Error joining %s\\n", message); return 1; } return 0; } int main() { pthread_mutex_init(&mutex, 0); pthread_t inc_thread; pthread_t dec_thread; pthread_t disp_thread; struct sched_param low = { 1 }; struct sched_param high = { 99 }; create(&inc_thread, 0, &incfun, "inc_thread"); pthread_setschedparam(inc_thread, SCHED_RR, &high); create(&dec_thread, 0, &decfun, "dec_thread"); pthread_setschedparam(dec_thread, SCHED_RR, &low); create(&disp_thread, 0, &dispfun, "disp_thread"); pthread_setschedparam(disp_thread, SCHED_RR, &low); join(inc_thread, "inc_thread"); join(dec_thread, "dec thread"); pthread_cancel(disp_thread); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t sum_mutex1; pthread_key_t psum_key; int a[1000], sum; void initialize_array(int *a, int n) { int i; for (i = 1; i <= n; i++) { a[i-1] = i; } } void print_partial_sum (int thread_no) { int *psum; psum = pthread_getspecific(psum_key); printf("Partial sum of thread %d is equal to %d\\n", thread_no, *psum); } void *thread_add(void *argument) { int i, thread_sum, arg; int *thread_sum_heap; thread_sum = 0; arg = *(int *)argument; for (i = ((arg-1)*(1000/4)) ; i < (arg*(1000/4)); i++) { thread_sum += a[i]; } thread_sum_heap = (int *)malloc(sizeof(int)); *thread_sum_heap = thread_sum; pthread_setspecific(psum_key, (void *)thread_sum_heap); print_partial_sum(arg); pthread_mutex_lock(&sum_mutex1); sum += thread_sum; pthread_mutex_unlock(&sum_mutex1); } void free_all(int *p) { free(p); } void initialize_keys () { pthread_key_create(&psum_key, (void *)free_all); } void print_array(int *a, int size) { int i; for(i = 0; i < size; i++) printf(" %d ", a[i]); putchar('\\n'); } int main() { int i, *range; pthread_t thread_id[4]; sum = 0; initialize_array(a, 1000); initialize_keys(); printf("Array : \\n"); print_array(a, 1000); for (i = 0; i < 4; i++) { range = (int *)malloc(sizeof(int)); *range = (i+1); if (pthread_create(&thread_id[i], 0, thread_add, (void *)range)) printf("Thread creation failed for thread num : %d\\n", *range); } for (i = 0; i < 4; i++) { pthread_join(thread_id[i], 0); } pthread_key_delete(psum_key); printf("Sum : %d\\n", sum); return 0; }
1
#include <pthread.h> struct ve_mem { struct cedrus_mem pub; struct ve_mem *next; }; struct ve_allocator { struct cedrus_allocator pub; int fd; struct ve_mem first; pthread_mutex_t lock; }; static struct cedrus_mem *cedrus_allocator_ve_mem_alloc(struct cedrus_allocator *allocator_pub, size_t size) { struct ve_allocator *allocator = (struct ve_allocator *)allocator_pub; if (pthread_mutex_lock(&allocator->lock)) return 0; void *addr = 0; struct cedrus_mem *ret = 0; struct ve_mem *c, *best_chunk = 0; for (c = &allocator->first; c != 0; c = c->next) { if(c->pub.virt == 0 && c->pub.size >= size) { if (best_chunk == 0 || c->pub.size < best_chunk->pub.size) best_chunk = c; if (c->pub.size == size) break; } } if (!best_chunk) goto out; int left_size = best_chunk->pub.size - size; addr = mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, allocator->fd, phys2bus(best_chunk->pub.phys) + (0xc0000000)); if (addr == MAP_FAILED) { ret = 0; goto out; } best_chunk->pub.virt = addr; best_chunk->pub.size = size; ret = &best_chunk->pub; if (left_size > 0) { c = calloc(1, sizeof(*c)); if (!c) goto out; c->pub.phys = best_chunk->pub.phys + size; c->pub.size = left_size; c->pub.virt = 0; c->next = best_chunk->next; best_chunk->next = c; } out: pthread_mutex_unlock(&allocator->lock); return ret; } static void cedrus_allocator_ve_mem_free(struct cedrus_allocator *allocator_pub, struct cedrus_mem *mem_pub) { struct ve_allocator *allocator = (struct ve_allocator *)allocator_pub; struct ve_mem *mem = (struct ve_mem *)mem_pub; if (pthread_mutex_lock(&allocator->lock)) return; struct ve_mem *c; for (c = &allocator->first; c != 0; c = c->next) { if (&c->pub == &mem->pub) { munmap(c->pub.virt, c->pub.size); c->pub.virt = 0; break; } } for (c = &allocator->first; c != 0; c = c->next) { if (c->pub.virt == 0) { while (c->next != 0 && c->next->pub.virt == 0) { struct ve_mem *n = c->next; c->pub.size += n->pub.size; c->next = n->next; free(n); } } } pthread_mutex_unlock(&allocator->lock); } static void cedrus_allocator_ve_mem_flush(struct cedrus_allocator *allocator_pub, struct cedrus_mem *mem_pub) { struct ve_allocator *allocator = (struct ve_allocator *)allocator_pub; struct ve_mem *mem = (struct ve_mem *)mem_pub; struct cedarv_cache_range cache_range = { .start = (long)mem->pub.virt, .end = (long)mem->pub.virt + mem->pub.size }; ioctl(allocator->fd, IOCTL_FLUSH_CACHE, &cache_range); } static void cedrus_allocator_ve_free(struct cedrus_allocator *allocator_pub) { struct ve_allocator *allocator = (struct ve_allocator *)allocator_pub; free(allocator); } struct cedrus_allocator *cedrus_allocator_ve_new(int ve_fd, const struct cedarv_env_infomation *ve_info) { if (ve_info->phymem_total_size == 0) return 0; struct ve_allocator *allocator = calloc(1, sizeof(*allocator)); if (!allocator) return 0; allocator->fd = ve_fd; allocator->first.pub.phys = bus2phys(ve_info->phymem_start - (0xc0000000)); allocator->first.pub.size = ve_info->phymem_total_size; pthread_mutex_init(&allocator->lock, 0); allocator->pub.mem_alloc = cedrus_allocator_ve_mem_alloc; allocator->pub.mem_free = cedrus_allocator_ve_mem_free; allocator->pub.mem_flush = cedrus_allocator_ve_mem_flush; allocator->pub.free = cedrus_allocator_ve_free; return &allocator->pub; }
0
#include <pthread.h> struct conduct *conduct_create(const char *name, size_t a, size_t c){ struct conduct * conduit = 0; if ( name != 0) { int fd_cond; if( access( name, F_OK ) != -1 ){ printf("[WARNING] File already exist\\n"); return 0; } if((fd_cond = open(name, O_CREAT | O_RDWR, 0666)) == -1){ printf("1° open : %s\\n", strerror(errno)); return 0; } if (ftruncate(fd_cond, sizeof(struct conduct)+c) == -1){ printf("ftruncate failed : %s\\n", strerror(errno)); return 0; } if ((conduit = (struct conduct *) mmap(0, sizeof(struct conduct)+c, PROT_WRITE | PROT_READ, MAP_SHARED, fd_cond, 0)) == (void *) -1){ printf("1° : mmap failed : %s\\n", strerror(errno)); return 0; } strncpy(conduit->name, name, 15); close(fd_cond); } else { if ((conduit = (struct conduct *) mmap(0, sizeof(struct conduct)+c, PROT_WRITE | PROT_READ, MAP_SHARED | MAP_ANONYMOUS, -1, 0)) == (void *) -1){ printf("1° : mmap failed : %s\\n", strerror(errno)); return 0; } } conduit->capacity = c; pthread_mutexattr_t mutShared; pthread_condattr_t condShared; pthread_mutexattr_init(&mutShared); pthread_mutexattr_setpshared(&mutShared,PTHREAD_PROCESS_SHARED); pthread_condattr_init(&condShared); pthread_condattr_setpshared(&condShared, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&conduit->mutex,&mutShared); pthread_cond_init(&conduit->cond,&condShared); conduit->atomic = a; conduit->lecture = 0; conduit->remplissage = 0; conduit->eof = 0; conduit->buffer_begin = sizeof(struct conduct) + 1; return conduit; } struct conduct *conduct_open(const char *name){ int fd; struct conduct * conduit; if((fd = open(name, O_RDWR,0666)) == -1){ printf("open file : failed in main"); return 0; } if ((conduit =(struct conduct *) mmap(0, sizeof(struct conduct), PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0)) == (void *) -1){ printf("mmap failed : %s\\n", strerror(errno)); return 0; } int capacity = conduit->capacity; if(munmap(conduit, sizeof(struct conduct)) == -1){ printf("munmap failed : %s\\n", strerror(errno)); return 0; } if ((conduit =(struct conduct *) mmap(0, sizeof(struct conduct)+capacity, PROT_WRITE | PROT_READ, MAP_SHARED, fd, 0)) == MAP_FAILED){ printf("mmap failed : %s\\n", strerror(errno)); return 0; } return conduit; } void conduct_close(struct conduct * conduit){ msync(conduit, sizeof(conduit), MS_SYNC); munmap(conduit, sizeof(conduit)); } int conduct_write_eof(struct conduct *conduit){ pthread_mutex_lock(&conduit->mutex); conduit->eof = 1; pthread_cond_broadcast(&conduit->cond); pthread_mutex_unlock(&conduit->mutex); return 1; } void conduct_destruct(struct conduct * conduit){ msync(conduit, sizeof(conduit), MS_SYNC); munmap(conduit, sizeof(conduit)); pthread_mutex_destroy(&conduit->mutex); unlink(conduit->name); } ssize_t conduct_read(struct conduct * conduit, void * buff, size_t count){ pthread_mutex_lock(&conduit->mutex); if(conduit->remplissage==conduit->lecture && conduit->eof) return 0; while(conduit->lecture >= conduit->remplissage) {printf("attend\\n");pthread_cond_wait(&conduit->cond,&conduit->mutex);} int lect = ((conduit->remplissage-conduit->lecture < count) ? conduit->remplissage-conduit->lecture : count); strncat(buff, (&(conduit->buffer_begin)+conduit->lecture), lect); conduit->lecture += lect; if(conduit->lecture==conduit->capacity || (conduit->lecture==conduit->remplissage && conduit->lecture > conduit->capacity- conduit->atomic)){ conduit->lecture = 0; conduit->remplissage=0; printf("avertit depassement\\n"); pthread_cond_broadcast(&conduit->cond); } pthread_mutex_unlock(&conduit->mutex); return lect; } ssize_t conduct_write(struct conduct * conduit, const void * buff, size_t count){ if(conduit->eof){ errno = EPIPE; return -1; } pthread_mutex_lock(&conduit->mutex); if(count <= conduit->atomic ){ while(conduit->remplissage +count > conduit->capacity){ printf("attend ecriture %zu",conduit->capacity); pthread_cond_wait(&conduit->cond,&conduit->mutex); if(conduit->eof){ pthread_mutex_unlock(&conduit->mutex); errno = EPIPE; return -1; } } memcpy(&(conduit->buffer_begin)+conduit->remplissage, buff, count); conduit->remplissage += count; pthread_cond_broadcast(&conduit->cond); } else{ if(conduit->remplissage+count > conduit->capacity){ count = conduit->capacity-count; } memcpy(&(conduit->buffer_begin)+conduit->remplissage, buff, count); conduit->remplissage += count; } pthread_mutex_unlock(&conduit->mutex); return count; }
1
#include <pthread.h> int xs[10][100]; int sum[10]; pthread_t threads[7]; pthread_mutex_t mutexes[10]; void *solve(void *arg) { while(1) { pthread_mutex_lock(&mutexes[5]); if(xs[5][0] >= 5) { pthread_mutex_unlock(&mutexes[5]); return 0; } pthread_mutex_unlock(&mutexes[5]); int x = rand() % 101; pthread_mutex_lock(&mutexes[x%10]); xs[x%10][++xs[x%10][0]] = x; printf("%d ", x); pthread_mutex_unlock(&mutexes[x%10]); } return 0; } int main() { srand((unsigned)time(0)^getpid()); for(int i=0; i<10; i++) pthread_mutex_init(&mutexes[i], 0); for(int i=0; i<7; i++) pthread_create(&threads[i], 0, *solve, 0); for(int i=0; i<7; i++) pthread_join(threads[i], 0); printf("\\n"); for(int s=0; s<10; s++) { int total = 0; printf("SUM[%d]=", s); for(int i=1; i<=xs[s][0]; i++) { printf("%d", xs[s][i]); if(xs[s][0] > 1) printf((i==xs[s][0]? "=":"+")); total += xs[s][i]; } if(xs[s][0] != 1) printf("%d", total); printf("\\n"); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; unsigned long long main_counter, counter[3]; void* thread_worker(void*); int main(int argc,char* argv[]) { int i, rtn, ch; pthread_t pthread_id[3] = {0}; for (i=0; i<3; i++) { pthread_create(&pthread_id[i],0,thread_worker,(void *)i); } do { unsigned long long sum = 0; for (i=0; i<3; i++) { pthread_mutex_lock(&mutex); sum += counter[i]; printf("%llu ", counter[i]); pthread_mutex_unlock(&mutex); } printf("%llu/%llu", main_counter, sum); }while ((ch = getchar()) != 'q'); return 0; } void* thread_worker(void* p) { int thread_num; thread_num = (int) p; for(;;) { pthread_mutex_lock(&mutex); counter[thread_num]++; main_counter++; pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> void * p_result(void * arg) { char * m = malloc(sizeof(char) * 3); m[0] = 'A'; m[1] = 'B'; m[2] = 'C'; return m; } void test_get_result() { pthread_t thread_id; void * exit_status ; pthread_create(&thread_id, 0, p_result, 0); pthread_join(thread_id, & exit_status); char * m = (char* ) exit_status; printf("m is %s\\n", m); free(m); } void * p_exit_result(void * arg) { printf("print before pthread_exit\\n"); pthread_exit((void *)10L); printf("print after pthread_exit\\n"); return 0; } void test_exit_result() { pthread_t thread_id; void * exit_status ; pthread_create(&thread_id, 0, p_exit_result, 0); pthread_join(thread_id, & exit_status); long m = (long ) exit_status; printf("m is %ld\\n", m); } pthread_mutex_t lock; int share_data; void * p_lock(void * arg) { int i; for(i = 0; i < 1024 * 1024; i++) { pthread_mutex_lock(&lock); share_data++; pthread_mutex_unlock(&lock); } return 0; } void test_lock() { pthread_t thread_id; void *exit_status; int i; pthread_mutex_init(&lock, 0); pthread_create(&thread_id, 0, p_lock, 0); for(i = 0; i < 10; i++) { pthread_mutex_lock(&lock); printf("Shared integer's value = %d\\n", share_data); pthread_mutex_unlock(&lock); } printf("\\n"); pthread_join(thread_id, & exit_status); pthread_mutex_destroy(&lock); } void test_lock2() { pthread_t thread_id; void *exit_status; int i; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_TIMED_NP); pthread_mutex_init(&lock, &attr); pthread_create(&thread_id, 0, p_lock, 0); for(i = 0; i < 10; i++) { pthread_mutex_lock(&lock); printf("Shared integer's value = %d\\n", share_data); pthread_mutex_unlock(&lock); } printf("\\n"); pthread_join(thread_id, & exit_status); pthread_mutexattr_destroy(&attr); pthread_mutex_destroy(&lock); } pthread_cond_t is_zero; pthread_mutex_t mutex; int con_share_data = 32767; void * p_condition(void * arg) { while(con_share_data > 0) { pthread_mutex_lock(&mutex); con_share_data--; pthread_mutex_unlock(&mutex); } pthread_cond_signal(&is_zero); } void test_condition() { pthread_t thread_id; void *exit_status; int i; pthread_cond_init(&is_zero, 0); pthread_mutex_init(&mutex, 0); pthread_create(&thread_id, 0, p_condition, 0); pthread_mutex_lock(&mutex); while(con_share_data != 0) { pthread_cond_wait(& is_zero, &mutex); } pthread_mutex_unlock(&mutex); pthread_join(thread_id, &exit_status); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&is_zero); } int sem_share_data = 0; sem_t binary_sem; void * p_sem(void * arg) { sem_wait(&binary_sem); sem_post(&binary_sem); } void test_sem() { sem_init(&binary_sem, 0, 1); sem_wait(&binary_sem); sem_post(&binary_sem); sem_destroy(&binary_sem); } pthread_rwlock_t rw_lock; void * p_rwlock(void * arg) { pthread_rwlock_rdlock(&rw_lock); pthread_rwlock_unlock(&rw_lock); } void test_rwlock() { pthread_rwlock_init(&rw_lock, 0); pthread_rwlock_wrlock(&rw_lock); pthread_rwlock_unlock(&rw_lock); pthread_rwlock_destroy(&rw_lock); } int main() { test_lock2(); return 0; }
0
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condConsumer; pthread_cond_t condProducer; int bufferSize = 2; int buffer = 0; void *producer1(void *ptr) { printf("pro1\\n"); for(int i = 0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer == bufferSize) { printf("Full! Producer1 is waiting.\\n"); pthread_cond_wait(&condProducer, &the_mutex); } buffer++; printf("Producer1 produced a toy......%d\\n", i); sleep(4); pthread_cond_broadcast(&condConsumer); pthread_cond_broadcast(&condProducer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *producer2(void *ptr) { printf("pro2\\n"); for(int i = 0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer == bufferSize) { printf("Full! Producer2 is waiting.\\n"); pthread_cond_wait(&condProducer, &the_mutex); } buffer++; printf("Producer2 produced a toy......%d\\n", i); sleep(4); pthread_cond_broadcast(&condConsumer); pthread_cond_broadcast(&condProducer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *producer3(void *ptr) { printf("pro3\\n"); for(int i = 0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer == bufferSize) { printf("Full! Producer3 is waiting.\\n"); pthread_cond_wait(&condProducer, &the_mutex); } buffer++; printf("Producer3 produced a toy......%d\\n", i); sleep(4); pthread_cond_broadcast(&condConsumer); pthread_cond_broadcast(&condProducer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer1(void *ptr) { printf("con1\\n"); for(int i =0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer == 0) { printf("Empty! Consumer1 is waiting.\\n"); pthread_cond_wait(&condConsumer, &the_mutex); } buffer--; printf("Consumer1 retrived a toy......%d\\n", i); sleep(4); pthread_cond_broadcast(&condConsumer); pthread_cond_broadcast(&condProducer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void *consumer2(void *ptr) { printf("con2\\n"); for(int i =0; i < 10; i++) { pthread_mutex_lock(&the_mutex); while(buffer == 0) { printf("Empty! Consumer2 is waiting.\\n"); pthread_cond_wait(&condConsumer, &the_mutex); } buffer--; printf("Consumer2 retrived a toy......%d\\n", i); sleep(4); pthread_cond_broadcast(&condConsumer); pthread_cond_broadcast(&condProducer); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro1, con1, pro2, con2, pro3; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condConsumer, 0); pthread_cond_init(&condProducer, 0); pthread_create(&pro3, 0, producer3, 0); printf("Have created pro3\\n"); pthread_create(&pro2, 0, producer2, 0); printf("Have created pro2\\n"); pthread_create(&pro1, 0, producer1, 0); printf("Have created pro1\\n"); pthread_create(&con2, 0, consumer2, 0); printf("Have created con2\\n"); pthread_create(&con1, 0, consumer1, 0); printf("Have created con1\\n"); pthread_join(pro1, 0); pthread_join(pro2, 0); pthread_join(con2, 0); pthread_join(con1, 0); pthread_join(pro3, 0); pthread_cond_destroy(&condConsumer); pthread_cond_destroy(&condProducer); }
1
#include <pthread.h> void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }TO_INFO; pthread_mutexattr_t attr; pthread_mutex_t mutex; void *timeout_helper(void *arg) { TO_INFO *tip; tip = (TO_INFO *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return 0; } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; TO_INFO *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(TO_INFO)); if(tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if(when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if(err ==0) return; } } (*func)(arg); } int makethread(void *(*fn)(void *), void *arg) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if(err != 0) return err; err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if(err == 0) err = pthread_create(&tid, &attr, fn, arg); pthread_attr_destroy(&attr); return err; } void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "cant set recursive type"); if((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "cant create recursive mutex"); pthread_mutex_lock(&mutex); if(condition) { timeout(&when, retry, (void*)arg); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> pthread_mutex_t midisync_lock = PTHREAD_MUTEX_INITIALIZER; static unsigned short midi_periods[4] = { 0, 0, 0, 0 }; static short next_idx = 0; static unsigned long total_time = 0; void midi_report_period(unsigned long midi_period) { pthread_mutex_lock(&midisync_lock); if (midi_period > 30000) midi_period = 30000; total_time -= midi_periods[next_idx]; total_time += midi_period; midi_periods[next_idx++] = (unsigned short) midi_period; next_idx &= 0x3; pthread_mutex_unlock(&midisync_lock); } unsigned short midi_get_bpm(void) { unsigned short average; unsigned short i; average = (unsigned short) (total_time >> 2); pthread_mutex_lock(&midisync_lock); for (i = 0; i < 4; i++) { if (average > midi_periods[i] && average - 500 > midi_periods[i]) { pthread_mutex_unlock(&midisync_lock); return 0; } else if (average < midi_periods[i] && average + 500 < midi_periods[i]) { pthread_mutex_unlock(&midisync_lock); return 0; } } pthread_mutex_unlock(&midisync_lock); if (average == 0) return 0; return (unsigned short) (((1323000L / (SPORT_DMA_LONGS / 4)) + (average / 2)) / average); }
1
#include <pthread.h> static pthread_cond_t dump_cond; static pthread_mutex_t dump_mtx; static pthread_t raw_dump_thread; unsigned char * dump_buffer; char *dump_mode; long long *dump_time; int *dump_size; char *dump_string; static volatile short new_pkt_idx=0, pkt_to_dump_idx=0; static volatile unsigned int stop_raw_dump_run = 0; unsigned short last_frame_idx =0; void dump_to_string(short idx); int raw_dump_init() { int res = 0; pthread_cond_init(&dump_cond, 0); pthread_mutex_init(&dump_mtx,0); dump_buffer= calloc(sizeof (unsigned char),MAX_FRAME_SIZE*32); dump_mode= calloc(sizeof(char), 32); dump_time= calloc(sizeof(long long), 32); dump_size= calloc(sizeof(int), 32); dump_string = calloc(sizeof(char),400); memset(dump_mode,0,32); memset(dump_time,0,32); memset(dump_size,0,32); memset(dump_string,0,32); printf("DEBUG:\\tCreating Dump Thread\\t[n_idx: %d, td_idx: %d] \\n",new_pkt_idx,pkt_to_dump_idx); res= pthread_create(&raw_dump_thread, 0, raw_dump_run, 0); return res; } void raw_dump_stop() { printf("DEBUG:\\tStopping Dump Thread \\n"); stop_raw_dump_run =1; pthread_cond_signal(&dump_cond); } void dump_raw_packet(unsigned char* frame, int read_size, char mode) { memset(dump_buffer+MAX_FRAME_SIZE*new_pkt_idx, 0, MAX_FRAME_SIZE); memcpy(&dump_buffer[MAX_FRAME_SIZE*new_pkt_idx], frame, MAX_FRAME_SIZE); dump_mode[new_pkt_idx] = mode; dump_size[new_pkt_idx] = read_size; dump_time[new_pkt_idx] = get_curr_time_in_milliseconds(); new_pkt_idx = (new_pkt_idx+1)%32; if(!stop_raw_dump_run) { pthread_mutex_lock(&dump_mtx); pthread_cond_signal(&dump_cond); pthread_mutex_unlock(&dump_mtx); } } void* raw_dump_run(void* args) { printf("DEBUG:\\tDump Thread has started\\n"); while(!stop_raw_dump_run) { pthread_mutex_lock(&dump_mtx); pthread_cond_wait(&dump_cond,&dump_mtx); pthread_mutex_unlock(&dump_mtx); if(new_pkt_idx == pkt_to_dump_idx) printf("ERROR:\\tdump-buffer overflow\\n"); while (new_pkt_idx != pkt_to_dump_idx) { dump_to_string(pkt_to_dump_idx); printf("%s",dump_string); pkt_to_dump_idx = (pkt_to_dump_idx+1)%32; } } printf("DEBUG:\\tDump Thread has ended\\n"); return 0; } void dump_to_string(short idx) { int flag =0; unsigned short curr_idx =get_unsigned_short_val(&dump_buffer[idx*MAX_FRAME_SIZE+4]); unsigned short curr_len = get_unsigned_short_val(&dump_buffer[idx*MAX_FRAME_SIZE+2]); if(dump_buffer[idx] == 0x05 && dump_size[idx] !=134) { printf("DUMP-WARNING - READ_SIZE != 134\\t read_size=%d\\n", dump_size[idx]); flag =1; } if (dump_buffer[idx] == 0x05 && (last_frame_idx+1)%65536 != curr_idx%65536) { printf("DUMP-WARNING - Frame Got Missing:\\tlast_Frame_idx: %d,\\tcurr_Frame_idx: %d\\n", last_frame_idx, curr_idx); flag=1; } if(dump_buffer[idx] == 0x05 && (130 != curr_len)) { printf("WARNING - Packet with unexpected Data-Length: \\tLEN: %d\\n", curr_len); flag=1; } if(dump_mode[idx] == 'r') { sprintf(dump_string, "-> %lld: [%03d-%03d-%d] \\t", dump_time[idx], dump_size[idx], curr_len, curr_idx); } else { sprintf(dump_string, "<- %lld: [%03d-%03d-%d] \\t", dump_time[idx], dump_size[idx], curr_len, curr_idx); } for (int i = 0; i<MAX_FRAME_SIZE; i++) { sprintf(dump_string +strlen(dump_string), "%02X", dump_buffer[idx*MAX_FRAME_SIZE + i]); if (!((i-5)%8)&& i>=5) { sprintf(dump_string +strlen(dump_string), " "); } } sprintf(dump_string + strlen(dump_string), "\\n"); last_frame_idx=curr_idx; if(flag) { printf("%s", dump_string); } } void raw_dump_join() { printf("DEBUG:\\tJoining Dump Thread \\n"); pthread_cond_destroy(&dump_cond); pthread_mutex_destroy(&dump_mtx); pthread_join(raw_dump_thread, 0); printf("DEBUG:\\tDump Thread Joined \\n"); }
0
#include <pthread.h> char* key; char* value; size_t value_len; struct hash_item** pprev; struct hash_item* next; } hash_item; hash_item* hash[1024]; pthread_mutex_t hash_mutex[1024]; hash_item* hash_get(const char* key, int create) { unsigned b = string_hash(key) % 1024; hash_item* h = hash[b]; while (h != 0 && strcmp(h->key, key) != 0) { h = h->next; } if (h == 0 && create) { h = (hash_item*) malloc(sizeof(hash_item)); h->key = strdup(key); h->value = 0; h->value_len = 0; h->pprev = &hash[b]; h->next = hash[b]; hash[b] = h; if (h->next != 0) { h->next->pprev = &h->next; } } return h; } void* connection_thread(void* arg) { int cfd = (int) (uintptr_t) arg; FILE* fin = fdopen(cfd, "r"); FILE* f = fdopen(cfd, "w"); pthread_detach(pthread_self()); char buf[1024], key[1024], key2[1024]; size_t sz; while (fgets(buf, 1024, fin)) { if (sscanf(buf, "get %s ", key) == 1) { unsigned b = string_hash(key); pthread_mutex_lock(&hash_mutex[b]); hash_item* h = hash_get(key, 0); if (h != 0) { fprintf(f, "VALUE %s %zu %p\\r\\n", key, h->value_len, h); fwrite(h->value, 1, h->value_len, f); fprintf(f, "\\r\\n"); } fprintf(f, "END\\r\\n"); fflush(f); pthread_mutex_unlock(&hash_mutex[b]); } else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) { unsigned b = string_hash(key); pthread_mutex_lock(&hash_mutex[b]); hash_item* h = hash_get(key, 1); free(h->value); h->value = (char*) malloc(sz); h->value_len = sz; fread(h->value, 1, sz, fin); fprintf(f, "STORED %p\\r\\n", h); fflush(f); pthread_mutex_unlock(&hash_mutex[b]); } else if (sscanf(buf, "delete %s ", key) == 1) { unsigned b = string_hash(key); pthread_mutex_lock(&hash_mutex[b]); hash_item* h = hash_get(key, 0); if (h != 0) { free(h->key); free(h->value); *h->pprev = h->next; if (h->next) { h->next->pprev = h->pprev; } free(h); fprintf(f, "DELETED %p\\r\\n", h); } else { fprintf(f, "NOT_FOUND\\r\\n"); } fflush(f); pthread_mutex_unlock(&hash_mutex[b]); } else if (sscanf(buf, "exch %s %s ", key, key2) == 2) { unsigned b = string_hash(key); unsigned b2 = string_hash(key2); if (b < b2) { unsigned tmp = b; b = b2; b2 = tmp; } pthread_mutex_lock(&hash_mutex[b]); if (b2 != b) { pthread_mutex_lock(&hash_mutex[b2]); } hash_item* h = hash_get(key, 0); hash_item* h2 = hash_get(key2, 0); if (h != 0 && h2 != 0) { char* tmp = h->value; h->value = h2->value; h2->value = tmp; size_t tmpsz = h->value_len; h->value_len = h2->value_len; h2->value_len = tmpsz; fprintf(f, "EXCHANGED %p %p\\r\\n", h, h2); } else { fprintf(f, "NOT_FOUND\\r\\n"); } fflush(f); pthread_mutex_unlock(&hash_mutex[b]); if (b2 != b) { pthread_mutex_unlock(&hash_mutex[b2]); } } else if (remove_trailing_whitespace(buf)) { fprintf(f, "ERROR\\r\\n"); fflush(f); } } if (ferror(fin)) { perror("read"); } fclose(fin); (void) fclose(f); return 0; } int main(int argc, char** argv) { for (int i = 0; i != 1024; ++i) { pthread_mutex_init(&hash_mutex[i], 0); } int port = 6168; if (argc >= 2) { port = strtol(argv[1], 0, 0); assert(port > 0 && port <= 65535); } int fd = open_listen_socket(port); assert(fd >= 0); while (1) { int cfd = accept(fd, 0, 0); if (cfd < 0) { perror("accept"); exit(1); } pthread_t t; int r = pthread_create(&t, 0, connection_thread, (void*) (uintptr_t) cfd); if (r != 0) { perror("pthread_create"); exit(1); } } }
1
#include <pthread.h> pthread_mutex_t lock; void alarm_handler(int arg) { pthread_mutex_lock(&lock); printf("%s, called.\\n", __func__); pthread_mutex_unlock(&lock); } int main(int argc, char *argv[]) { signal(SIGALRM, alarm_handler); alarm(1); pthread_mutex_init(&lock, 0); int num = 0; while (1) { pthread_mutex_lock(&lock); printf("\\t%d\\n", num++); sleep(3); pthread_mutex_unlock(&lock); } return 0; }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int translation_initialized = 0; void bg_translation_init() { pthread_mutex_lock(&mutex); if(!translation_initialized) { bg_bindtextdomain (PACKAGE, LOCALE_DIR); translation_initialized = 1; } pthread_mutex_unlock(&mutex); } void bg_bindtextdomain(const char * domainname, const char * dirname) { bindtextdomain(domainname, dirname); setlocale(LC_NUMERIC, "C"); }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum, mutexlvl; void *dotprod(void *thdarg) { pthread_mutex_lock (&mutexlvl); printf("Sync to start level: %ld\\n", (long)thdarg); int i, start, end, len; long offset; double mysum, *x, *y; offset = (long)thdarg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i = start; i < end; ++i) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_mutex_unlock (&mutexlvl); pthread_exit((void *)0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double *) malloc(4 * 100 * sizeof (double)); b = (double *) malloc(4 * 100 * sizeof (double)); for (i = 0; i < 100 * 4; ++i) { a[i] = 1.0f; b[i] = a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init (&mutexsum, 0); pthread_mutex_init (&mutexlvl, 0); pthread_attr_init (&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 4; ++i) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for (i = 0; i < 4; ++i) { pthread_join(callThd[i], &status); } printf("Sum = %f\\n", dotstr.sum); free(a); free(b); pthread_mutex_destroy (&mutexlvl); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutexsum; int *a, *b; long sum=0.0; void *dotprod(void *arg) { int i, start, end, offset, len; long tid; tid = (long)arg; offset = tid; len = 100000; start = offset*len; end = start + len; printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1); for (i=start; i<end ; i++) { pthread_mutex_lock(&mutexsum); sum += (a[i] * b[i]); pthread_mutex_unlock(&mutexsum); } printf("thread: %ld done. Global sum now is=%li\\n",tid,sum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; void *status; pthread_t threads[8]; pthread_attr_t attr; a = (int*) malloc (8*100000*sizeof(int)); b = (int*) malloc (8*100000*sizeof(int)); for (i=0; i<100000*8; i++) a[i]=b[i]=1; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<8;i++) pthread_create(&threads[i], &attr, dotprod, (void *)i); pthread_attr_destroy(&attr); for(i=0;i<8;i++) { pthread_join(threads[i], &status); } printf ("Final Global Sum=%li\\n",sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> int _mosquitto_log_printf(struct mosquitto *mosq, int priority, const char *fmt, ...) { va_list va; char *s; int len; assert(mosq); assert(fmt); pthread_mutex_lock(&mosq->log_callback_mutex); if(mosq->on_log){ len = strlen(fmt) + 500; s = _mosquitto_malloc(len*sizeof(char)); if(!s){ pthread_mutex_unlock(&mosq->log_callback_mutex); return MOSQ_ERR_NOMEM; } __builtin_va_start((va)); vsnprintf(s, len, fmt, va); ; s[len-1] = '\\0'; mosq->on_log(mosq, mosq->userdata, priority, s); _mosquitto_free(s); } pthread_mutex_unlock(&mosq->log_callback_mutex); return MOSQ_ERR_SUCCESS; }
0
#include <pthread.h> int x = 10; pthread_mutex_t test; void *thread1(void *arg) { pthread_mutex_lock(&test) ; int n = 100; while(n--) { x++; } printf("\\n"); pthread_mutex_unlock(&test); } void *thread2(void *arg) { pthread_mutex_lock(&test) ; int n = 100; while(n--) { x++; } pthread_mutex_unlock(&test); } int main(void) { pthread_mutex_init(&test,0); pthread_t thid1,thid2; pthread_create(&thid1 ,0,thread1,0); pthread_create(&thid2 ,0,thread1,0); sleep(5); printf("********************************************%d\\n",x); }
1
#include <pthread.h> pthread_t philosopher[5]; pthread_mutex_t chopstick[5] = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER}; struct philosopher_t { int nr; int left; int right; }; int threadError(char *msg, int nr) { printf(msg, nr); exit(1); } sem_t sem; void *philosopher_semaphore(void *p) { struct philosopher_t philosopher = *((struct philosopher_t *) (p)); while (1) { sem_wait(&sem); if (!pthread_mutex_lock(&chopstick[philosopher.left])) { printf("%d pick up's left chopstick \\n", philosopher.nr); while (1) { if (!pthread_mutex_lock(&chopstick[philosopher.right])) { printf("%d pick up's right chopstick, happy bastard, EAT \\n", philosopher.nr); pthread_mutex_unlock(&chopstick[philosopher.left]); pthread_mutex_unlock(&chopstick[philosopher.right]); break; } } } sem_post(&sem); } } int main() { sem_init(&sem, 0, 4); struct philosopher_t *p0_t, *p1_t, *p2_t, *p3_t, *p4_t; p0_t = malloc(sizeof(struct philosopher_t)); p1_t = malloc(sizeof(struct philosopher_t)); p2_t = malloc(sizeof(struct philosopher_t)); p3_t = malloc(sizeof(struct philosopher_t)); p4_t = malloc(sizeof(struct philosopher_t)); p0_t->nr = 0; p0_t->left = 0; p0_t->right = 1; p1_t->nr = 1; p1_t->left = 1; p1_t->right = 2; p2_t->nr = 2; p2_t->left = 2; p2_t->right = 3; p3_t->nr = 3; p3_t->left = 3; p3_t->right = 4; p4_t->nr = 4; p4_t->left = 4; p4_t->right = 0; if (pthread_create(&philosopher[p0_t->nr], 0, philosopher_semaphore, p0_t)) { threadError("Error while creating philosopher %d\\n", p0_t->nr); } if (pthread_create(&philosopher[p1_t->nr], 0, philosopher_semaphore, p1_t)) { threadError("Error while creating philosopher %d\\n", p1_t->nr); } if (pthread_create(&philosopher[p2_t->nr], 0, philosopher_semaphore, p2_t)) { threadError("Error while creating philosopher %d\\n", p2_t->nr); } if (pthread_create(&philosopher[p3_t->nr], 0, philosopher_semaphore, p3_t)) { threadError("Error while creating philosopher %d\\n", p4_t->nr); } if (pthread_create(&philosopher[p4_t->nr], 0, philosopher_semaphore, p4_t)) { threadError("Error while creating philosopher %d\\n", p4_t->nr); } if (pthread_join(philosopher[p0_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p0_t->nr); } if (pthread_join(philosopher[p1_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p1_t->nr); } if (pthread_join(philosopher[p2_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p2_t->nr); } if (pthread_join(philosopher[p3_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p3_t->nr); } if (pthread_join(philosopher[p4_t->nr], 0)) { threadError("Error while ending philosopher %d\\n", p4_t->nr); } return 0; }
0
#include <pthread.h> pthread_cond_t CV[6]; pthread_mutex_t M; int state[6]; int n, rounds = 0; int eat_count[6]; int update_state(int i) { if (state[i] == 2 && state[(i+6 -1)%6] != 3 && state[(i+1)%6] != 3) { state[i] = 3; pthread_cond_signal(&CV[i]); } return 0; } void chopsticks_init() { int i; pthread_mutex_init(&M, 0); for (i = 0; i < 6; i++) { pthread_cond_init (&CV[i], 0); state[i] = 1; } } void chopsticks_take(int i) { pthread_mutex_lock(&M); state[i] = 2; update_state(i); while (state[i] == 2) pthread_cond_wait (&CV[i],&M); pthread_mutex_unlock(&M); } void chopsticks_put(int i) { pthread_mutex_lock(&M); state[i] = 1; update_state ((i+6 -1)%6); update_state ((i+1)%6); pthread_mutex_unlock(&M); } void trace(int i, char *s) { if (strcmp (s, "eating") == 0) eat_count[i]++; if (n++ > rounds) { if (strcmp(s,"thinking") == 0) { pthread_exit(0); } } } void * phil_exec(void *arg) { int self = *(int *) arg; for (;;) { trace(self,"thinking"); chopsticks_take(self); trace(self,"eating"); chopsticks_put(self); } } int main(int argc, char *argv[]) { int i; int no[6]; pthread_t tid[6]; pthread_attr_t attr; if (argc < 2 || atoi(argv[1]) == 0) rounds = 4; else rounds = atoi(argv[1]); printf("Will run %d rounds\\n", rounds); for (i = 0; i < 6; i++) eat_count[i] = 0; chopsticks_init(); pthread_attr_init(&attr); pthread_setconcurrency(6); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); for (i = 0; i < 6; i++) { no[i] = i; pthread_create(&tid[i], 0, phil_exec, (int *) &no[i]); } for (i = 0; i < 6; i++) pthread_join(tid[i], 0); for (i = 0; i < 6; i++) fprintf (stdout, "philospher %d ate %d times\\n", i, eat_count [i]); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t pmutex; pthread_cond_t cond[5]; enum {THINKING, HUNGRY, EATING} state[5]; int forks[5] = {0, 0, 0, 0, 0}; void *run(void *); void pickup_forks(int); void putdown_forks(int); void test(int); int main(int argc, char *argv[]) { pthread_t tid[5]; pthread_attr_t attr[5]; int idx[5] = {0, 1, 2, 3, 4}; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&pmutex, 0); for (int i = 0; i < 5; ++i) { pthread_attr_init(&attr[i]); pthread_cond_init(&cond[i], 0); pthread_create(&tid[i], &attr[i], run, &idx[i]); state[i] = THINKING; } for (int i = 0; i < 5; ++i) pthread_join(tid[i], 0); return 0; } void *run(void *p) { int i = *((int*) p); while(1) { int dur = rand() % 3 + 1; pickup_forks(i); printf("Philo %d is eating\\n", i); sleep(dur); putdown_forks(i); printf("Philo %d is thinking...\\n", i); sleep(dur); } } void pickup_forks(int i) { pthread_mutex_lock(&mutex); state[i] = HUNGRY; pthread_mutex_lock(&pmutex); printf("Philo %d is trying to pickup fork %d\\n", i, (i + 4) % 5); printf("Philo %d is trying to pickup fork %d\\n", i, i); pthread_mutex_unlock(&pmutex); test(i); while (state[i] != EATING) pthread_cond_wait(&cond[i], &mutex); pthread_mutex_lock(&pmutex); printf("Philo %d picked up fork %d\\n", i, (i + 4) % 5); printf("Philo %d picked up fork %d\\n", i, i); pthread_mutex_unlock(&pmutex); pthread_mutex_unlock(&mutex); } void putdown_forks(int i) { pthread_mutex_lock(&mutex); state[i] = THINKING; pthread_mutex_lock(&pmutex); printf("Philo %d is putting down fork %d\\n", i, (i + 4) % 5); printf("Philo %d is putting down fork %d\\n", i, i); pthread_mutex_unlock(&pmutex); test((i + 4) % 5); test((i + 1) % 5); pthread_mutex_unlock(&mutex); } void test(int i) { if ((state[(i + 4) % 5] != EATING) && (state[i] == HUNGRY) && (state[(i + 1) % 5] != EATING)) { state[i] = EATING; pthread_cond_signal(&cond[i]); } }
0
#include <pthread.h> pthread_mutex_t sinal[10000000]; pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; int nArquivos, nThreads, nProdutos, cont = 1; int armazena[10000000]; void ler (int a){ FILE* va; int n, aux, pos; char nome[14]; int leitura; nome[10]='.'; nome[11]='i'; nome[12]='n'; nome[13]='\\0'; pos=9; n=a; while(n>0){ aux=n%10; n = n/10; nome[pos]=aux+'0'; pos--; va=fopen(nome+pos+1,"r"); while(fscanf(va,"%d", &leitura) > 0) { pthread_mutex_lock(&sinal[leitura]); armazena[leitura]++; pthread_mutex_unlock(&sinal[leitura]); } fclose(va); } return; } void * f(void * arg){ int n; pthread_mutex_lock(&mymutex); while(cont < nArquivos){ n = cont; cont++; pthread_mutex_unlock(&mymutex); ler(n); pthread_mutex_lock(&mymutex); } pthread_mutex_unlock(&mymutex); } int main(){ int i, arquivos; scanf(" %d %d %d", &arquivos, &nThreads, &nProdutos); nArquivos = arquivos; pthread_t thread[nThreads]; for(i=0; i< 10000000;i++){ pthread_mutex_init(&sinal[i], 0); } for(i=0; i<nThreads; i++) { pthread_create(&thread[i], 0, f, 0); } for(i=0; i<nThreads; i++) { pthread_join(thread[i], 0); } int sum = 0, percent = 0; for(i=0; i<=nProdutos; i++){ sum += armazena[i]; } for(i=0; i<=nProdutos; i++){ printf("%05.2lf%% (%d itens) do produto %d\\n", (armazena[i] * 100.0)/sum, armazena[i], i); } puts(""); printf("Sum: %d\\n", sum); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexmesa; pthread_t* filosofos; pthread_cond_t* cond; char* estado; } MESA; int num; MESA* mesa; void imprimeEstado(void); void *filosofo (void *); void hungry (int); void eat (int); void think (int); int main(int argc, char *argv[]) { if(argc < 2){ printf("Numero insuficiente de parametros\\n"); return -1; } num = atoi(argv[1]); if(num < 0){ printf("Erro! Número inválido de filosofos\\n"); return -1; } time_t t; srand((unsigned) time(&t)); int i; mesa = (MESA*) malloc(sizeof(MESA)); pthread_mutex_init(&mesa->mutexmesa, 0); mesa->estado = (char*) malloc(num*sizeof(char)); for (i = 0; i < num; i++) mesa->estado[i] = 'T'; imprimeEstado(); mesa->cond = (pthread_cond_t*) malloc(num*sizeof(pthread_cond_t)); for (i = 0; i < num; i++) pthread_cond_init(&mesa->cond[i], 0); mesa->filosofos = (pthread_t*) malloc(num*sizeof(pthread_t)); for (i = 0; i < num; i++) { pthread_create(&mesa->filosofos[i], 0, filosofo, (void*) &i); usleep(100); } for (i = 0; i < num; i++) pthread_join(mesa->filosofos[i], 0); return 0; } void imprimeEstado() { int i; for (i = 0; i < num; i++) printf("%c ", mesa->estado[i]); printf("\\n"); } void *filosofo (void *arg) { int fil = *(int *) arg; while(1) { hungry(fil); sleep(rand()%10+1); think(fil); sleep(rand()%10+1); } } void hungry (int filosofo) { pthread_mutex_lock(&mesa->mutexmesa); mesa->estado[filosofo] = 'H'; imprimeEstado(); eat(filosofo); if (mesa->estado[filosofo] != 'E') pthread_cond_wait(&mesa->cond[filosofo], &mesa->mutexmesa); imprimeEstado(); pthread_mutex_unlock(&mesa->mutexmesa); } void eat (int filosofo) { if (mesa->estado[(filosofo+num-1)%num] != 'E' && mesa->estado[filosofo] == 'H' && mesa->estado[(filosofo+1)%num] != 'E') { mesa->estado[filosofo] = 'E'; pthread_cond_signal(&mesa->cond[filosofo]); } } void think(int filosofo) { pthread_mutex_lock(&mesa->mutexmesa); mesa->estado[filosofo] = 'T'; imprimeEstado(); eat((filosofo+num-1)%num); eat((filosofo+1)%num); pthread_mutex_unlock(&mesa->mutexmesa); }
0
#include <pthread.h> int Number = 0; pthread_mutex_t NMutex; pthread_cond_t NCond; void *thread1(void *arg) { struct timespec waiting_time; int cond_wait_count = 0; int cond_wait_return = 0; sleep(2); pthread_mutex_lock(&NMutex); printf("Thread get lock\\n"); do { waiting_time.tv_sec = time(0) + 15; cond_wait_return = pthread_cond_timedwait(&NCond, &NMutex, &waiting_time); ++cond_wait_count; if (cond_wait_return == 0) { printf("cond_wait_return:%d\\n", cond_wait_return); } }while (Number == 0 ); Number = 0 ; printf("Number Change Thread:%d - cond_wait_count:%d\\n", Number, cond_wait_count); pthread_mutex_unlock(&NMutex); return 0; } int main(int argc, char* argv[]) { pthread_mutex_init(&NMutex, 0); pthread_cond_init(&NCond, 0); pthread_t p1; printf("Number Init:%d\\n", Number); pthread_create(&p1, 0, thread1, 0); sleep(5); pthread_mutex_lock(&NMutex); Number = 1; printf("Number Change Main:%d\\n", Number); pthread_mutex_unlock(&NMutex); pthread_cond_signal(&NCond); printf("Signal Cond, wait for thread\\n"); while (Number == 1) { sleep(1); } pthread_join(p1, 0); printf("Number End:%d\\n", Number); pthread_exit(0); return 0; }
1
#include <pthread.h> uint8_t type; uint8_t len_first_name; uint8_t len_last_name; } joker_request; uint8_t type; uint32_t len_joke; } joker_response; const short SERVER_PORT = 2345; pthread_mutex_t comm_lock; int setUpSocket(); void listenForRequests(); void error(char *msg); char * makeUpJoke(); void *HandleConnection(void *clientSocketID); int main() { int serverSocketID; serverSocketID = setUpSocket(); listenForRequests(serverSocketID); } int setUpSocket() { int serverSocketID; struct sockaddr_in serverSocketAddr; serverSocketID = socket(PF_INET, SOCK_STREAM, 0); if (serverSocketID < 0) error("ERROR opening socket"); memset(&serverSocketAddr, 0, sizeof(struct sockaddr_in)); serverSocketAddr.sin_family = AF_INET; serverSocketAddr.sin_addr.s_addr = htonl(INADDR_ANY); serverSocketAddr.sin_port = htons(SERVER_PORT); if(bind(serverSocketID, (struct sockaddr *)&serverSocketAddr, sizeof(struct sockaddr_in)) < 0) { error("ERROR binding socket"); } return serverSocketID; } void listenForRequests(int serverSocketID) { struct sockaddr_in clientSocketAddr; uint32_t addrLen = sizeof(struct sockaddr_in); pthread_t threadID; if(pthread_mutex_init(&comm_lock,0) != 0) { error("ERROR initialiazing mutex"); } if(listen(serverSocketID, 10) < 0) { error("ERROR starting to listen"); } printf("Server listening on port %d\\n", SERVER_PORT); do { int clientSocketID; clientSocketID = accept(serverSocketID,(struct sockaddr *) &clientSocketAddr, &addrLen); if (pthread_create (&threadID, 0, HandleConnection, (void *)&clientSocketID) != 0) perror("ERROR creating thread"); } while(1); } void *HandleConnection(void *arg) { int *clientSocketID = arg; int rcvCount,sentCount,totalRcvd = 0; char *first_name, *last_name, *joke; joker_request jokerRequest; joker_response jokerResponse; uint8_t buffer_size; char *buffer; printf("Connection accepted.\\n"); memset(&jokerRequest, 0, sizeof(jokerRequest)); pthread_mutex_lock(&comm_lock); if((rcvCount = recv(*clientSocketID, ((uint8_t *)&jokerRequest), sizeof(joker_request), 0)) < 0) { perror("ERROR receiving"); } pthread_mutex_unlock(&comm_lock); printf("Length of first name: %d\\n", jokerRequest.len_first_name); printf("Length of last name: %d\\n", jokerRequest.len_last_name); buffer_size = jokerRequest.len_first_name + jokerRequest.len_last_name; buffer = malloc(buffer_size); first_name = malloc(jokerRequest.len_first_name + 1); last_name = malloc(jokerRequest.len_last_name + 1); do { pthread_mutex_lock(&comm_lock); if((rcvCount = recv(*clientSocketID, buffer + totalRcvd, buffer_size - totalRcvd, 0)) < 0) { perror("ERROR receiving"); } pthread_mutex_unlock(&comm_lock); printf("Bytes received: %d\\n",rcvCount); totalRcvd += rcvCount; } while(totalRcvd < buffer_size); memcpy(first_name,buffer,jokerRequest.len_first_name); memcpy(last_name,&buffer[strlen(first_name)],jokerRequest.len_last_name); first_name[jokerRequest.len_first_name] = '\\0'; last_name[jokerRequest.len_last_name] = '\\0'; printf("First name: %s \\nLast name: %s\\n",first_name,last_name); joke = makeUpJoke(first_name,last_name); jokerResponse.type = 2; jokerResponse.len_joke = htonl(strlen(joke)); pthread_mutex_lock(&comm_lock); if((sentCount = sendto(*clientSocketID, &jokerResponse, sizeof(joker_response),0, 0, 0)) < 0) { perror("ERROR sending"); } pthread_mutex_unlock(&comm_lock); printf("Characters sent: %d\\n", sentCount); pthread_mutex_lock(&comm_lock); if((sentCount = sendto(*clientSocketID, joke, strlen(joke),0, 0, 0)) < 0) { perror("ERROR sending"); } pthread_mutex_unlock(&comm_lock); printf("Characters sent: %d\\n", sentCount); sleep(30); free(joke); free(first_name); free(last_name); free(buffer); close(*clientSocketID); printf("Connection closed.\\n"); return (0); } char * makeUpJoke(char *first_name, char *last_name) { char *buffer = malloc(strlen("Hello ")+strlen(first_name)+strlen(last_name)); sprintf(buffer,"Hello %s %s",first_name,last_name); return buffer; } void error(char *msg) { perror(msg); exit(0); }
0
#include <pthread.h> int main(int argc, char *argv[]) { if(argc!=2) { printf("Usage: %s <MSG_SIZE>\\n", argv[0]); exit(0); } int fd; size_t MSG_SIZE; void *send_buf_temp; char name[] = "/my_shmsname"; MSG_SIZE=atoi(argv[1]); printf("Size : %ld\\n", MSG_SIZE); fd = shm_open(name, O_CREAT | O_EXCL | O_RDWR, S_IRUSR | S_IWUSR); printf("SHM_OPEN : %d\\n", fd); ftruncate(fd, MSG_SIZE+1); send_buf_temp = mmap(0, MSG_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); char * send_buf = send_buf_temp; char recv_buf[MSG_SIZE+1]; close(fd); if(send_buf == MAP_FAILED) { perror("Mmap failed my_shmsname.."); return 0; } printf("Map passed\\n"); { pthread_mutex_t ipc_mutex; pthread_cond_t ipc_condvar; pthread_cond_t ipc_startvar; } shared_data_t; fd = shm_open("/my_syncname", O_CREAT|O_EXCL|O_RDWR, S_IRUSR|S_IWUSR); printf("SHM_OPEN sync : %d\\n", fd); ftruncate(fd, sizeof(shared_data_t)); shared_data_t* sdata = (shared_data_t*)mmap(0, sizeof(shared_data_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); if(send_buf == MAP_FAILED) { perror("Mmap failed my_syncname.."); return 0; } close(fd); int i; if ( fork() != 0 ) { pthread_condattr_t cond_attr; pthread_condattr_init(&cond_attr); pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED); pthread_cond_init(&sdata->ipc_condvar, &cond_attr); pthread_condattr_t cond_attr2; pthread_condattr_init(&cond_attr2); pthread_condattr_setpshared(&cond_attr2, PTHREAD_PROCESS_SHARED); pthread_cond_init(&sdata->ipc_startvar, &cond_attr2); pthread_mutexattr_t mutex_attr; pthread_mutexattr_init(&mutex_attr); pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&sdata->ipc_mutex, &mutex_attr); printf("P : initialization done\\n"); pthread_mutex_lock(&sdata->ipc_mutex); pthread_cond_wait(&sdata->ipc_startvar, &sdata->ipc_mutex); printf("P : GOT THE LOCK.. going to write\\n"); for(i = 0; i<MSG_SIZE;i++) send_buf[i] = 'A'; send_buf[MSG_SIZE] = '\\0'; printf("P: Done with writing...\\n"); pthread_cond_signal(&sdata->ipc_condvar); printf("P : Done with signalling...\\n"); pthread_mutex_unlock(&sdata->ipc_mutex); pthread_mutex_lock(&sdata->ipc_mutex); pthread_cond_wait(&sdata->ipc_startvar, &sdata->ipc_mutex); for(i=0;i<MSG_SIZE;i++) recv_buf[i] = send_buf[i]; recv_buf[MSG_SIZE] = '\\0'; printf("P : Done with read..\\n"); printf("P : reads..%ld\\n", strlen(recv_buf)); pthread_mutex_unlock(&sdata->ipc_mutex); printf("P : so longl\\n"); pthread_mutex_destroy(&sdata->ipc_mutex); pthread_cond_destroy(&sdata->ipc_startvar); pthread_cond_destroy(&sdata->ipc_condvar); printf("Both : goign to unlink guy1\\n"); shm_unlink(name); printf("Both : goign to unlink guy2\\n"); shm_unlink("/my_syncname"); printf("Both : munmap sdata\\n"); if (munmap(sdata,sizeof(shared_data_t))) perror("munmap()"); printf("Both : munmap sendbuf\\n"); if (munmap(send_buf,MSG_SIZE+1)) perror("munmap()"); } else { printf("IN THE CHILD\\n"); pthread_mutex_lock(&sdata->ipc_mutex); printf("C : GOT THE LOCK.. going to wait\\n"); pthread_cond_signal(&sdata->ipc_startvar); pthread_cond_wait(&sdata->ipc_condvar, &sdata->ipc_mutex); printf("C : Going to read..\\n"); for(i=0;i<MSG_SIZE;i++) recv_buf[i] = send_buf[i]; recv_buf[MSG_SIZE] = '\\0'; printf("C : reads..penultimate %d\\n", recv_buf[MSG_SIZE-1] ); printf("C : reads..last %d\\n", recv_buf[MSG_SIZE] ); printf("C : reads..%ld\\n", strlen(recv_buf)); printf("C : going to write.."); for(i = 0; i<MSG_SIZE;i++) send_buf[i] = 'B'; send_buf[MSG_SIZE] = '\\0'; printf("C : done with write, going to signal..\\n"); pthread_cond_signal(&sdata->ipc_startvar); pthread_mutex_unlock(&sdata->ipc_mutex); printf("C : farewell\\n"); } return 0; }
1
#include <pthread.h> void *buffer; volatile uint32_t user; volatile uint32_t server; uint32_t user_base; uint32_t server_base; uint32_t frame_count; uint32_t frame_size; pthread_mutex_t lock; pthread_cond_t cond; }buffer_cblk_t; static buffer_cblk_t g_buffer_cblk; static int g_client_runnig = 1; static void *get_user_buffer(buffer_cblk_t *pcblk) { return (int8_t *)pcblk->buffer + (pcblk->user - pcblk->user_base) * pcblk->frame_size; } static uint32_t frames_available(buffer_cblk_t *pcblk) { return (pcblk->server + pcblk->frame_count - pcblk->user); } static uint32_t frames_ready(buffer_cblk_t *pcblk) { return (pcblk->user - pcblk->server); } static uint32_t step_user(buffer_cblk_t *pcblk, uint32_t frames) { uint32_t u; uint32_t fc = pcblk->frame_count; u = pcblk->user; u += frames; if (u >= fc) { if (u - fc >= pcblk->user_base) { pcblk->user_base += fc; } } else if (u >= pcblk->user_base + fc) { pcblk->user_base += fc; } pcblk->user = u; return u; } static int step_server(buffer_cblk_t *pcblk, uint32_t frames) { uint32_t s; uint32_t fc = pcblk->frame_count; s = pcblk->server; s += frames; if (s >= fc) { if (s - fc >= pcblk->server_base ) { pcblk->server_base += fc; } } else if (s >= pcblk->server_base + fc) { pcblk->server_base += fc; } pcblk->server = s; return 0; } static void *thread_client(void *pdata) { buffer_cblk_t *pcblk = (buffer_cblk_t *)pdata; uint32_t frames_avail; uint32_t frames_req; void *ptr; while (g_client_runnig) { pthread_mutex_lock(&pcblk->lock); frames_avail = frames_available(pcblk); if (frames_avail == 0) { printf("[c]wait server\\n"); pthread_cond_wait(&pcblk->cond, &pcblk->lock); if (g_client_runnig == 0) { break; } frames_avail = frames_available(pcblk); } pthread_mutex_unlock(&pcblk->lock); frames_req = 1600; if (frames_req > frames_avail) { frames_req = frames_avail; } uint32_t u = pcblk->user; uint32_t buffer_end = pcblk->user_base + pcblk->frame_count; printf("[c]avail=0x%x u=0x%x, end=0x%x\\n", frames_avail, u, buffer_end); if (frames_req > buffer_end - u) { frames_req = buffer_end - u; } if (u < pcblk->user_base) { printf("[c] u < user_base\\n"); g_client_runnig = 0; break; } ptr = get_user_buffer(pcblk); memset(ptr, 0, frames_req*pcblk->frame_size); printf("[c]buf = 0x%x, size = 0x%x\\n", (unsigned int)ptr, frames_req*pcblk->frame_size); printf("[c]offset = %d\\n", pcblk->user - pcblk->user_base); step_user(pcblk, frames_req); usleep(20*1000); } return 0; } int main(int argc, char *argv[]) { pthread_t tid; int is_running = 1; uint32_t frames_rdy; uint32_t frames_req; buffer_cblk_t *pcblk = &g_buffer_cblk; void *ptr; uint32_t delay = -1; uint32_t cnt; if (argc > 1) { delay = atoi(argv[1]); } memset(pcblk, 0, sizeof(*pcblk)); pthread_mutex_init(&pcblk->lock, 0); pthread_cond_init(&pcblk->cond, 0); pcblk->buffer = malloc(4096*0x01); pcblk->frame_count = 4096; pcblk->frame_size = 0x01; printf("[init] buf = 0x%x, end = 0x%x\\n", (unsigned int)pcblk->buffer, (unsigned int)pcblk->buffer + 0x01*4096); pthread_create(&tid, 0, thread_client, pcblk); cnt = 0; while (is_running && g_client_runnig) { frames_rdy = frames_ready(pcblk); if (frames_rdy == 0) { usleep(100); continue; } frames_req = 2048; uint32_t s = pcblk->server; uint32_t buffer_end = pcblk->server_base + pcblk->frame_count; if (frames_req > frames_rdy) { frames_req = frames_rdy; } if (frames_req > buffer_end - s) { frames_req = buffer_end - s; } ptr = (int8_t *)pcblk->buffer + (s - pcblk->server_base) * pcblk->frame_size; memset(ptr, 0, frames_req*pcblk->frame_size); printf("[s]buf = 0x%x, size = 0x%x\\n", (unsigned int)ptr, frames_req*pcblk->frame_size); printf("[s]offset = %d\\n", pcblk->server - pcblk->server_base); pthread_mutex_lock(&pcblk->lock); step_server(pcblk, frames_req); pthread_cond_signal(&pcblk->cond); pthread_mutex_unlock(&pcblk->lock); usleep(100*1000); cnt++; if (cnt >= (1000/100)) { cnt = 0; delay--; if (delay == 0) { printf("exit main loop\\n"); is_running = 0; } } } g_client_runnig = 0; pthread_cond_signal(&pcblk->cond); pthread_join(tid, 0); pthread_cond_destroy(&pcblk->cond); pthread_mutex_destroy(&pcblk->lock); if (pcblk->buffer) { free(pcblk->buffer); pcblk->buffer = 0; } return 0; }
0
#include <pthread.h> char *level_long_str[]={ "EMERGENCY", "ALERT", "CRITICAL", "ERROR", "WARNING", "NOTICE", "INFO", "DEBUG", }; static pthread_mutex_t xlog_mutex=PTHREAD_MUTEX_INITIALIZER; int xlog_rollout(char *filename, int backup_count) { struct stat stats; char filename1[1024]; char filename2[1024]; int ret=0; int res; int count; if (stat(filename, &stats)!=0) { return ret; } for (count=backup_count; count>=0; count--) { if (count==0) strcpy(filename1, filename); else snprintf(filename1, sizeof(filename1), "%s.%d", filename, count); if (stat(filename1, &stats)==0 && S_ISREG(stats.st_mode)) { if (count==backup_count) { res=unlink(filename1); } else { snprintf(filename2, sizeof(filename2), "%s.%d", filename, count+1); res=rename(filename1, filename2); } if (res==-1) { perror(filename1); ret=1; } } } return ret; } int xlog(struct xlogger* logger, int level, const char *format, ...) { struct xloghandler* l; int ret=0; int res; if (level<0 || LOG_DEBUG<level || level>logger->level) return ret; pthread_mutex_lock(&xlog_mutex); for (l=logger->handlers; l->enable>=0; l++) { va_list args; __builtin_va_start((args)); if (l->level<0 || l->level<level) continue; if (l->filename) { if (l->file!=0) { if (l->max_bytes>0) { struct stat stats; res=fstat(fileno(l->file), &stats); if (res==-1) { ret=1; perror(l->filename); continue; } if (stats.st_size >= l->max_bytes) { res=fclose(l->file); if (res==-1) { ret=1; perror(l->filename); continue; } res=xlog_rollout(l->filename, l->backup_count); if (res) ret=1; l->file=0; } } } if (l->file==0) { if (0!=strcmp(l->mode, "a") && l->backup_count>0) { res=xlog_rollout(l->filename, l->backup_count); if (res) ret=1; } l->file=fopen(l->filename, l->mode); if (l->file==0) { ret=1; perror(l->filename); continue; } setlinebuf(l->file); } } if (format && l->time_fmt) { char timestr[1024]; time_t t; struct tm *tmp; t=time(0); tmp=localtime(&t); strftime(timestr, sizeof(timestr), l->time_fmt, tmp); char *p=strstr(timestr, "%{LEVEL}"); if (p) { memmove(p, p+5, strlen(p)-4); memcpy(p, level_long_str[level], 3); } res=fputs(timestr, l->file); if (res==EOF) { ret=1; } } if (format) { res=vfprintf(l->file, format, args); if (res<0) ret=1; } ; } pthread_mutex_unlock(&xlog_mutex); return ret; } struct xloghandler *xloghandler_init(struct xloghandler *xlh, int enable, int level, char *time_fmt, char *filename, char *alias, char *mode, int max_bytes, int backup_count, FILE *file) { xlh->enable=enable; xlh->level=level; xlh->time_fmt=time_fmt; xlh->filename=filename; xlh->alias=alias; xlh->mode=mode; xlh->max_bytes=max_bytes; xlh->backup_count=backup_count; xlh->file=file; return xlh; } struct xloghandler xlh[3]; struct xlogger logger; int xlog_main(int argc, char *argv) { int i; xloghandler_init(xlh+0, 1, LOG_ERR, "%F %T %%{LEVEL} ", "/tmp/xlog.log", "xlog.log", "a", 500, 3, 0); xloghandler_init(xlh+1, 1, LOG_DEBUG, "%T %%{LEVEL} ", 0, "stderr", 0, 0, 0, stderr); xloghandler_init(xlh+2, -1, 0, 0, 0, 0, 0, 0, 0, 0); if (xlog(&logger, LOG_EMERG, 0)) fprintf(stderr, "error initializing logging\\n"); logger.level=LOG_DEBUG; logger.handlers=xlh; for (i=0; i<20; i++) { xlog(&logger, LOG_DEBUG, "%4d DEBUG Hello World ! %s\\n", i, "go go"); xlog(&logger, LOG_INFO, "%4d INFO Hello World ! %s\\n", i, "go go"); xlog(&logger, LOG_ERR, "%4d ERROR Hello World ! %s\\n", i, "go go"); } return 0; }
1
#include <pthread.h> int socketid; char msg[35]; int S; int pid; char *queue[3]; char *seq[3]; }process; pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; char ch; void *sendMessage(void * sock); void *listenMessage(void * sock); int pid; int nprocess; process p[4]; struct hostent *server; FILE* myfile; int d=0; int main(int argc, char *argv[]) { struct sockaddr_in server_addr; int portno , i = 0,j,n; char buffer[256]; pthread_t sender,listener; int *new_sock; u_int yes=1; if(argc<4) { fprintf(stderr, "Usage client <hostname> <process> <no of processes>\\n"); exit(1); } pid=atoi(argv[2]); nprocess=atoi(argv[3]); myfile=fopen("Sample.txt","r"); if(myfile==0){ fprintf(stderr, "%d : Error opening file\\n", pid); } else{ printf("%d : File opened\\n", pid); } do{ ch=fgetc(myfile); break; }while(ch!=EOF); printf("%d : File contents %c\\n",pid,ch); rewind(myfile); fclose(myfile); portno = 8888; server = gethostbyname(argv[1]); if(server == 0) { fprintf(stderr, "No such host exists\\n"); exit(1); } int socketfd = socket(AF_INET,SOCK_STREAM, 0); if(socketfd < 0) fprintf(stderr, "%d : Error creating a socket\\n",pid); if (setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(yes)) < 0) { fprintf(stderr,"%d : Reusing ADDR failed",pid); exit(1); } if (setsockopt(socketfd,SOL_SOCKET,SO_REUSEPORT,&yes,sizeof(yes)) < 0) { fprintf(stderr,"%d : Reusing PORT failed",pid); exit(1); } server_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&server_addr.sin_addr.s_addr,server->h_length); server_addr.sin_port = htons(portno); if(connect(socketfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) { fprintf(stderr, "%d : Error connecting to sequencer\\n",pid); exit(1); } else { printf("%d : Connected to sequencer\\n",pid); } new_sock = (int *)malloc(1); *new_sock = socketfd; pthread_create(&sender,0,sendMessage,(void*)new_sock); pthread_create(&listener,0,listenMessage,(void*)new_sock); pthread_join(sender,0); pthread_join(listener,0); exit(0); } void *sendMessage(void * sock) { printf("%d : In sender thread\\n",pid); char buffer[256]; int newsocket = *(int *)sock; struct hostent *server; int i=0; bzero(buffer, 256); *(int *)buffer=pid; printf("%d : Sending to sequencer %d\\n", pid, *(int *)buffer); int n = write(newsocket, buffer, 256); if(n < 0) { fprintf(stderr, "%d : Error writing to socket\\n",pid); } else { printf("%d : Request sent to sequencer\\n",pid); } if(d==1){ printf("%d : Done with writing to file\\n", pid); bzero(buffer,256); strcpy(buffer,"DONE"); n = write(newsocket, buffer, 256); if(n < 0) { fprintf(stderr, "%d : Error writing to socket\\n",pid); } else { printf("%d : Completion msg sent to sequencer\\n",pid); d=0; } } } void *listenMessage(void * sock) { printf("%d : In receiver thread\\n",pid); int n; int newsocket = *(int *)sock; char buffer[256]; int i=0,j; FILE *file; bzero(buffer, 256); n=read(newsocket, buffer, 256); if(n<0){ fprintf(stderr, "Error reading response from sequencer\\n"); exit(1); } printf("%d : Data received : %s\\n",pid,buffer); if(strcmp(buffer,"OK")==0){ file=fopen("Sample.txt","r+"); do{ ch=fgetc(myfile); break; }while(ch!=EOF); printf("%d : New read value %c\\n", pid,ch); rewind(file); printf("%d : Acquiring lock\\n",pid); pthread_mutex_lock(&mut); fseek(file,0,0); fprintf(file, "%d\\n",((ch-'0')+1)); pthread_mutex_unlock(&mut); printf("%d : Releasing lock\\n", pid); d=1; fclose(file); pthread_yield(); } fflush(file); }
0
#include <pthread.h> pthread_t sutaziaci[5]; pthread_t gen_cisla; int cislo = 0; int gen_cislo = 0; int bignum = 0; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_gen = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_hrac = PTHREAD_COND_INITIALIZER; void * generator(void * parm) { int j=0; for(j=0;j<10;j++) { pthread_mutex_lock(&mut); sleep(1); srand ( time(0) ); cislo = rand() % 80 + 1; printf("vygenerovane cislo: %d\\n", cislo); gen_cislo = 1; pthread_cond_broadcast(&cond_gen); while(bignum < 5) { pthread_cond_wait(&cond_hrac, &mut); } bignum = 0; pthread_mutex_unlock(&mut); sched_yield(); } } void * hrac(void * param) { int k; for(k=0;k<10;k++){ pthread_mutex_lock(&mut); while (gen_cislo != 1 ) { pthread_cond_wait(&cond_gen, &mut); } printf("hrac: %d ", param); printf("precital cislo: %d\\n", cislo); bignum++; if (bignum >= 5) { gen_cislo = 0; pthread_cond_broadcast(&cond_hrac); } else pthread_cond_wait(&cond_hrac, &mut); pthread_mutex_unlock(&mut); sched_yield(); } } main( int argc, char *argv[] ) { int i=0; pthread_mutex_init(&mut,0); pthread_cond_init(&cond_hrac,0); pthread_cond_init(&cond_gen,0); pthread_create(&gen_cisla, 0, generator, 0); for (i = 1; i <= 5; i++) { pthread_create(&sutaziaci[i], 0, hrac, (void *)i); } for (i = 1; i <= 5; i++) pthread_join(sutaziaci[i], 0); pthread_join(gen_cisla, 0); pthread_mutex_destroy(&mut); pthread_cond_destroy(&cond_gen); pthread_cond_destroy(&cond_hrac); return 0; }
1
#include <pthread.h> const char year_monthdays[2][13] = { {0,31,28,31,30,31,30,31,31,30,31,30,31}, {0,31,29,31,30,31,30,31,31,30,31,30,31} }; char int2bcd(int num) { char result; result = 0xF0 & ((num/10)<<4); result += (0x0F&(num%10)); return result; } int get_rtctime(unsigned char *rx_buf) { int GiFd; unsigned int uiRet; int i; int waittime; unsigned char tx_buf[RTC_DATA_LEN]; unsigned char addr[2] ; addr[0] = 0x00; waittime = 20; while((g_sys_info.state_rtc != 1)&&(waittime--)) { sleep(1); } pthread_mutex_lock(&g_rtc_mutex); GiFd = open("/dev/i2c-1", O_RDWR); if(GiFd == -1) { return -1; perror("open rtc\\n"); } uiRet = ioctl(GiFd, I2C_SLAVE, I2C_ADDR >> 1); if (uiRet < 0) { return -1; } tx_buf[0] = addr[0]; for (i = 1; i < RTC_DATA_LEN; i++) tx_buf[i] = i; write(GiFd, addr, 1); read(GiFd, rx_buf, RTC_DATA_LEN - 1); close(GiFd); pthread_mutex_unlock(&g_rtc_mutex); return 0; } int set_rtctime(unsigned char *cst) { int GiFd; unsigned int uiRet; unsigned char tx_buf[RTC_DATA_LEN]; unsigned char addr[2]; addr[0] = 0x00; tx_buf[0] = 0x00; tx_buf[7] = int2bcd(cst[0]); tx_buf[6] = int2bcd(cst[1]); tx_buf[5] = int2bcd(cst[2]); tx_buf[4] = 0x07 & 1; tx_buf[3] = int2bcd(cst[3]); tx_buf[3] += 0x80; tx_buf[2] = int2bcd(cst[4]); tx_buf[1] = int2bcd(cst[5]); pthread_mutex_lock(&g_rtc_mutex); GiFd = open("/dev/i2c-1", O_RDWR); if(GiFd == -1) { perror("open rtc\\n"); return -1; } uiRet = ioctl(GiFd, I2C_SLAVE, I2C_ADDR >> 1); if (uiRet < 0) { return -1; } write(GiFd, tx_buf, 8); pthread_mutex_unlock(&g_rtc_mutex); return 1; } void utc2cst(unsigned char *utc,unsigned char *cst) { volatile unsigned char year,mounth,date,hour,minute,second; unsigned char isLeapYear; year = utc[0]; mounth = utc[1]; date = utc[2]; hour = utc[3]; minute = utc[4]; second = utc[5]; if(year % 4) isLeapYear = 0; else isLeapYear = 1; hour += 8; if(hour >= 24) { hour -= 24; date++; if(date > year_monthdays[isLeapYear][mounth]) { date = 1; mounth++; if(mounth > 12) { mounth = 1; year++; } } } cst[0] = year; cst[1] = mounth; cst[2] = date; cst[3] = hour; cst[4] = minute; cst[5] = second; }
0
#include <pthread.h> int volatile active = 0; int volatile error = 0; pthread_mutex_t mutex; int use_mutex = 0; long wait(int id) { long cnt = 10; cnt *= id; do{ if (active != id) { error = 1; } thread_sleep(1); cnt--; } while (cnt != 0); return cnt; } void worker(int id) { if (use_mutex) { pthread_mutex_lock(&mutex); } active = id; printf(" Started work on %d\\n",id); wait(id); printf(" Stopped work on %d\\n", id); if (use_mutex) { pthread_mutex_unlock(&mutex); } } void *run(void *arg) { int id; id = *(int *)arg; worker(id); pthread_exit(0); return 0; } int main(int argc, char *argv[]) { pthread_t t; int id1 = 4; int rc; printf("Without mutex\\n"); error = 0; rc = pthread_create(&t, 0, run, (void *)&id1); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(1); } worker(1); worker(8); thread_sleep(100); if (error == 0) { printf ("No threading\\n"); return 1; } pthread_mutex_init(&mutex, 0); use_mutex = 1; printf("With mutex\\n"); error = 0; rc = pthread_create(&t, 0, run, (void *)&id1); if (rc){ printf("ERROR; return code from pthread_create() is %d\\n", rc); exit(1); } worker(1); worker(8); thread_sleep(100); if (error != 0) { printf ("No mutex\\n"); return 1; } pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> int arr[10 * 5]; int aindex; pthread_mutex_t mutex; void *hello(void *thread_id) { int i; int *id = (int *) thread_id; for (i=1; i<=10 ; i++) { pthread_mutex_lock(&mutex); arr[aindex] = (*id)*100+ i; sleep(1); aindex = aindex + 1; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main() { pthread_t tids[5]; int ids[5] = {1, 2, 3, 4, 5}; int ret; long t; int i; pthread_mutex_init(&mutex, 0); for (i=0 ; i<5; i++) { ret = pthread_create(&tids[i], 0, hello, &ids[i]); if (ret) { printf("unable to create thread! \\n"); exit(-1); } } for (i=0 ; i<5; i++) { pthread_join(tids[i], 0); } printf("Final array : \\n"); for (i=0; i<50; i++) printf("%d ", arr[i]); printf("\\n\\n"); pthread_mutex_destroy(&mutex); pthread_exit(0); return 0; }
0
#include <pthread.h> extern int fd_hof1[2]; extern _Bool saida; extern _Bool debug; extern pthread_mutex_t all_full; extern pthread_mutex_t espera_top; extern pthread_mutex_t d_activos; extern unsigned int desafios_activos; int func_interface_serv(char *funcionalidade,char *desaf); int valida_arg_serv(char *opc,char *desaf, char *lixo2); void *interface () { char lixo[100]; char desafio[100]; char opcao[100]; char aux[100]; pthread_mutex_lock(&espera_top); pthread_mutex_lock(&espera_top); pthread_mutex_unlock(&espera_top); menu_servidor(); printf("Bem vindo ao servidor HNserv.\\n\\n Indique a sua opção:\\n"); while(saida==0){ printf("$ "); fflush(stdout); memset((void*)lixo,(int)'\\0',sizeof(lixo)); memset((void*)desafio,(int)'\\0',sizeof(desafio)); memset((void*)opcao,(int)'\\0',sizeof(opcao)); fgets(aux,100 -1,stdin); sscanf(aux,"%s %s %s",opcao,desafio,lixo); if (valida_arg_serv(opcao,desafio,lixo)==0){ func_interface_serv(opcao,desafio); } } return 0; } int valida_arg_serv(char *opc,char *desaf, char *lixo2){ if(strcmp(lixo2,"\\0")!=0){ printf("Os dados inseridos não correspondem a argumentos válidos.\\n\\n"); printf("As opções são as seguintes:\\n\\n"); printf("l - Listar desafios\\n"); printf("d - Informação sobre desafios\\n"); printf("h - HallOfFame\\n"); printf("x - Terminar o servidor.\\n\\n"); return -1; } if(strcmp(opc,"l")!=0 && strcmp(opc,"d")!=0 && strcmp(opc,"h")!=0 && strcmp(opc,"x")!=0 && strcmp(opc,"n")!=0 && strcmp(opc,"m")!=0 && strcmp(opc,"a")!=0){ printf("A opção seleccionada não é válida.\\n\\n"); printf("As opções são as seguintes:\\n\\n"); printf("l - Listar desafios\\n"); printf("d - Informação sobre desafios\\n"); printf("h - HallOfFame\\n"); printf("x - Terminar o servidor.\\n\\n"); return -1; } if(strcmp(desaf,"\\0")==0 && strcmp(opc,"d")==0){ printf("Tem de indicar o jogo a que deseja visualizar a informação\\n\\n"); printf("exemplo: d \\"nome do desafio\\"\\n"); return -1; } return 0; } int func_interface_serv(char *funcionalidade, char *desaf) { switch (*funcionalidade) { case 'l': if (strcmp(desaf,"\\0")!=0){ printf("A opção %s não necessita de argumentos adicionais.\\n\\n",funcionalidade); break; } lista_desafios(); return 0; break; case 'd': if (strcmp(desaf,"\\0")==0){ printf("A opção %s necessita de saber qual o jogo a listar a info.\\n\\n",funcionalidade); break; } mostra_desafio(desaf); return 0; break; case 'h': if (strcmp(desaf,"\\0")!=0){ printf("A opção %s não necessita de argumentos adicionais.\\n\\n",funcionalidade); break; } write(fd_hof1[WRITE], "TOP\\n\\n", 5*sizeof(char)); pthread_mutex_lock(&espera_top); pthread_mutex_lock(&espera_top); pthread_mutex_unlock(&espera_top); return 0; break; case 'm': debug=1; break; case 'n': debug=0; break; case 'a': if (strcmp(desaf,"\\0")==0){ printf("A opção %s necessita de saber qual o Jogador a listar a info.\\n\\n",funcionalidade); break; } dar_pontos(desaf); break; case 'x': if (strcmp(desaf,"\\0")!=0){ printf("A opção %s não necessita de argumentos adicionais.\\n\\n",funcionalidade); break; } pthread_mutex_lock(&d_activos); if(desafios_activos != 0){ pthread_mutex_unlock(&d_activos); printf("O servidor Nao pode terminar porque ainda existem desafios activos\\n"); break; } pthread_mutex_unlock(&d_activos); saida=1; pthread_mutex_unlock(&all_full); printf("O servidor Terminou\\n\\n"); return 2; break; default: printf("Essa opção não existe.\\n\\n"); return -1; break; } return 0; }
1
#include <pthread.h> int* find_primes(int *t); void perror_and_exit(char *msg); void usage(); int num_workers; int max_prime; int prime_count; pthread_mutex_t mtx; Boolean verbose = FALSE; int main(int argc, char **argv) { int i = 0; int c; int t = 0; double seconds; time_t start, end; num_workers = 1; max_prime = 4294967295U; while ((c = getopt(argc, argv, "c:m:v")) != -1) { switch (c) { case 'c': num_workers = atoi(optarg); break; case 'm': max_prime = atoi(optarg); break; case 'v': verbose = TRUE; break; default: usage(); exit(1); } } if (verbose == TRUE) time(&start); pthread_t *threads = (pthread_t*) malloc(num_workers * sizeof(pthread_t)); pthread_mutex_init(&mtx, 0); pthread_attr_t attr; if ( pthread_attr_init(&attr) != 0) perror_and_exit("pthread_attr_init()"); if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE) != 0) perror_and_exit("pthread_attr_setdetachstate()"); for (i = 0; i < num_workers; i++) { if (pthread_create(&threads[i], &attr, find_primes, (void *) t) != 0) perror_and_exit("pthread_create()"); t++; } for (i = 0; i < num_workers; i++) { if (pthread_join(threads[i], 0) != 0) perror_and_exit("pthread_join()"); } if (verbose == TRUE) { printf("Number of primes is %d.\\n", prime_count); time(&end); seconds = difftime(end, start); printf("%.f seconds.\\n", seconds); } if (pthread_attr_destroy(&attr) != 0) perror_and_exit("Error destroying pthread attr.\\n"); if (pthread_mutex_destroy(&mtx) != 0) perror_and_exit("Error destroying mutex.\\n"); free(threads); pthread_exit(0); return 0; } int *find_primes(int *t) { int work_done = 0; int prime_count = 0; int myid = (int) t; int i,j; int min = floor(myid * (max_prime + 1) / num_workers); printf("min = %d\\n",min); int max = floor((myid + 1) * ((max_prime + 1) / num_workers)) - 1; printf("max = %d\\n",max); if (min>=2) { for (i=min; i<=max; i++) { for (j=min; j<=i; j++) { if (i%j==0) { printf("break here.\\n"); break; } pthread_mutex_lock(&mtx); printf("found a prime.\\n\\n"); prime_count = prime_count + 1; pthread_mutex_unlock(&mtx); } if (i==j) { pthread_mutex_lock(&mtx); printf("found another prime.\\n\\n"); prime_count = prime_count + 1; printf("%d",i); pthread_mutex_unlock(&mtx); } work_done = work_done + 1; } } if (verbose == TRUE) printf ("\\nthread %d min: %d max: %d count: %d work: %d\\n", myid, min, max, prime_count, work_done); pthread_exit(0); return prime_count; } void perror_and_exit(char *msg) { perror(msg); exit(1); } void usage() { printf("%s %s", "Usage:\\n", "primePThread [-qv] [-m max_prime] [-c concurrency]\\n\\n"); printf("%s", "Options:\\n"); printf("%*s%*s\\n", 4, "-v", 23, "verbose: print timing and count"); printf("%*s%*s\\n", 4, "-m", 36, "maximum size of the prime number"); printf("%*s%*s\\n", 4, "-c", 23, "concurrency to use\\n"); }
0
#include <pthread.h> pthread_mutex_t readlock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t writelock = PTHREAD_MUTEX_INITIALIZER; void* Producteur() { int c; for(;;){ pthread_mutex_lock(&readlock); c = getchar(); if ( c == EOF ){ pthread_mutex_unlock(&readlock); return 0; } Push(c); pthread_mutex_unlock(&readlock); } return 0; } void* Consommateur() { char c; for (;;) { pthread_mutex_lock(&writelock); c = Pop(); putchar(c); fflush(stdout); pthread_mutex_unlock(&writelock); } return 0; } int main (int argc, char ** argv){ int i,nbp,nbc; if(argc < 3){ printf("usage: %s NB_PROD NB_CONS\\n", argv[0]); exit(1); } nbp = atoi(argv[1]); nbc = atoi(argv[2]); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_t prod; pthread_t cons; for(i=0;i<nbp;i++){ pthread_create(&prod, &attr, (void *(*)(void *))Producteur, 0); } for(i=0;i<nbc;i++){ pthread_create(&cons, &attr, (void *(*)(void *))Consommateur, 0); } pthread_exit(0); return 0; }
1
#include <pthread.h> char buffer[65536]; int ascii[128]; pthread_mutex_t lock; int thread_num; int bounds; } thread_info; void *thread_funct(void *thread_infos) { int threadStartPos; int i; thread_info ti = *(thread_info*) thread_infos; threadStartPos = ti.thread_num * ti.bounds; for (i = 0; i < ti.bounds && threadStartPos < 65536; i++) { pthread_mutex_lock(&lock); ascii[ buffer[threadStartPos++] ]++; pthread_mutex_unlock(&lock); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t threads[8]; thread_info ti[8]; int fd; int i, j; int bytes; int bound; if (argc != 2) { printf("Usage: ./%s <filename.txt>", argv[0]); return 1; } if ((fd = open(argv[1], O_RDONLY)) < 0) { printf("Error opening %s\\n", argv[1]); return 1; } bytes = read(fd, buffer, 65536); bound = bytes / 8; pthread_mutex_init(&lock, 0); for (i = 0; i < 8; i++) { ti[i].thread_num = i; ti[i].bounds = bound; pthread_create(&threads[i], 0, thread_funct, &ti[i]); } for (i = 0; i < 8; i++) pthread_join(threads[i], 0); for (i = 0; i <= 127; i++) { printf("\\n%d occurrences of 0x%d ", ascii[i], i); if (i >= 33 && i != 127) printf("%c", i); } printf("\\nNumber of threads used: %d\\n", 8); close(fd); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; int thread_num; int* counter; pthread_t *thread; int r[1000]; int s[1000]; int res = 0; void vector_multiply(void* arg) { printf("In thread\\n"); int i = 0; int n = *((int*) arg); for (i = n; i < 1000; i += thread_num) { pthread_mutex_lock(&mutex); res += r[i] * s[i]; pthread_mutex_unlock(&mutex); } printf("FInished thread\\n"); } void verify() { int i = 0; res = 0; for (i = 0; i < 1000; i += 1) { res += r[i] * s[i]; } printf("verified res is: %d\\n", res); } int main(int argc, char **argv) { int i = 0; if (argc == 1) { thread_num = 2; } else { if (argv[1] < 1) { printf("enter a valid thread number\\n"); return 0; } else thread_num = atoi(argv[1]); } counter = (int*)malloc(thread_num*sizeof(int)); for (i = 0; i < thread_num; ++i) counter[i] = i; thread = (pthread_t*)malloc(thread_num*sizeof(pthread_t)); for (i = 0; i < 1000; ++i) { r[i] = i; s[i] = i; } pthread_mutex_init(&mutex, 0); for (i = 0; i < thread_num; ++i) pthread_create(&thread[i], 0, &vector_multiply, &counter[i]); for (i = 0; i < thread_num; ++i) pthread_join(thread[i], 0); printf("res is: %d\\n", res); pthread_mutex_destroy(&mutex); verify(); free(thread); free(counter); return 0; }
1
#include <pthread.h> pthread_mutex_t buffer_mutex; int fill = 0; char buffer[100][50]; char *fetch(char *link) { int fd = open(link, O_RDONLY); if (fd < 0) { fprintf(stderr, "failed to open file: %s", link); return 0; } int size = lseek(fd, 0, 2); assert(size >= 0); char *buf = Malloc(size+1); buf[size] = '\\0'; assert(buf); lseek(fd, 0, 0); char *pos = buf; while(pos < buf+size) { int rv = read(fd, pos, buf+size-pos); assert(rv > 0); pos += rv; } close(fd); return buf; } void edge(char *from, char *to) { if(!from || !to) return; char temp[50]; temp[0] = '\\0'; char *fromPage = parseURL(from); char *toPage = parseURL(to); strcpy(temp, fromPage); strcat(temp, "->"); strcat(temp, toPage); strcat(temp, "\\n"); pthread_mutex_lock(&buffer_mutex); strcpy(buffer[fill++], temp); pthread_mutex_unlock(&buffer_mutex); } int main(int argc, char *argv[]) { pthread_mutex_init(&buffer_mutex, 0); int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/complex_parsing/pagea", 5, 4, 15, fetch, edge); assert(rc == 0); return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/complex_parsing.out"); }
0
#include <pthread.h> static pthread_mutex_t mutex; static void packet_receive(int sock_fd, void *eloop_ctx, void *sock_ctx) { ssize_t res; struct pkthdr pkthdr; unsigned char buf[2300]; struct smartconfig *sc = (struct smartconfig *)eloop_ctx; memset(buf, 0, sizeof(buf)); res = recv(sock_fd, buf, sizeof(buf), 0); if (res < 0) { return; } pkthdr.len = pkthdr.caplen = res; pthread_mutex_lock(&mutex); print_packet(sc, &pkthdr, buf); pthread_mutex_unlock(&mutex); } static void smartconfig_timeout_handler(void *eloop_data, void *user_ctx) { struct smartconfig *sc = (struct smartconfig *)eloop_data; if ((sc->sock_fd < 0) || (!sc->device)) { printf("%s %d device:%s\\nn", __func__, 45, sc->device); return; } iface_set_freq_1_to_14(sc->sock_fd, sc->device); eloop_register_timeout(sc->secs, sc->usecs, smartconfig_timeout_handler, sc, 0); return; } int main(int argc, char *argv[]) { int sock_fd; char *device; int protocol; struct smartconfig SC, *sc; device = argv[1]; if (!device) exit(1); pthread_mutex_init(&mutex, 0); sc = &SC; memset(sc, 0, sizeof(struct smartconfig)); protocol = htons(ETH_P_ALL); sock_fd = socket(PF_PACKET, SOCK_RAW, protocol); if (sock_fd == -1) { fprintf(stderr, "socket: %s\\n", strerror(errno)); return sock_fd; } if (iface_set_monitor_mode(sock_fd, device) < 0) { printf("can not set monitor mode"); close(sock_fd); return -1; } if (iface_socket_bind(sock_fd, device, protocol) < 0) { printf("can not bind socket fd:%d", sock_fd); close(sock_fd); return -1; } sc->sock_fd = sock_fd; sc->device = device; sc->protocol = protocol; sc->secs = 0; sc->usecs = 1000 * 300; sc->handler = smartconfig_timeout_handler; eloop_init(); eloop_register_read_sock(sock_fd, packet_receive, sc, 0); eloop_register_timeout(sc->secs, sc->usecs, smartconfig_timeout_handler, sc, 0); eloop_run(); int i; for (i = 0; i < sc->ssid_len; i++) sc->ssid[i] = sc->slm[i + 4].mcast[4]; for (i = 0; i < sc->psk_len; i++) sc->psk[i] = sc->slm[i + 4].mcast[5]; if (sc->ssid && sc->psk) printf("%s %d ssid:%s, psk:%s\\n", __func__, 113, sc->ssid, sc->psk); close(sock_fd); return 0; }
1
#include <pthread.h> int sigaltstack (const stack_t *restrict stack, stack_t *restrict old) { int err = 0; struct signal_state *ss = &_pthread_self ()->ss; pthread_mutex_lock (&ss->lock); if (old) *old = ss->stack; if (stack) { if (stack->ss_size < MINSIGSTKSZ) { err = ENOMEM; goto out; } if ((stack->ss_flags & ~(SS_DISABLE))) { err = EINVAL; goto out; } if ((ss->stack.ss_flags & SS_ONSTACK)) { err = EPERM; goto out; } ss->stack = *stack; } out: pthread_mutex_unlock (&ss->lock); if (err) { errno = err; return -1; } return 0; }
0
#include <pthread.h> struct timespec st,en; double runtime; int n,m,p; int **matrix1, **matrix2, **matrix3; int Row = 0,Col = 0; int threadCount; pthread_t * threads; pthread_mutex_t mutex_Row = PTHREAD_MUTEX_INITIALIZER; void *multiply(int d){ int i,j,myCol,myRow; while(1){ pthread_mutex_lock(&mutex_Row); if(Row>=n){ pthread_mutex_unlock(&mutex_Row); pthread_exit(0); return; } myCol = Col; myRow = Row; Col++; if(Col==p){ Col = 0; Row++; } pthread_mutex_unlock(&mutex_Row); for(i=0;i<m;i++){ matrix3[myRow][myCol] += (matrix1[myRow][i]*matrix2[i][myCol]); } } } int main() { int i,j; FILE *fptr; printf("Enter the rows and columns of matrices\\n - n,m and p\\n"); scanf("%d %d %d", &n, &m, &p); matrix1 = (int **) malloc(n * sizeof(int *)); for(i=0;i<n;i++){ matrix1[i] = (int *)malloc(m * sizeof(int)); } matrix2 = (int **) malloc(m * sizeof(int *)); for(i=0;i<m;i++){ matrix2[i] = (int *)malloc(p * sizeof(int)); } matrix3 = (int **) malloc(n * sizeof(int *)); for(i=0;i<n;i++){ matrix3[i] = (int *)malloc(p * sizeof(int)); } fptr = fopen("input1.txt", "r"); for (i=0; i<n; i++) { for (j=0; j<m; j++) { fscanf(fptr, "%d", &matrix1[i][j]); } } fclose(fptr); fptr = fopen("input2.txt", "r"); for (i=0; i<m; i++) { for (j=0; j<p; j++) { fscanf(fptr, "%d", &matrix2[i][j]); } } fclose(fptr); printf("Enter the number of threads\\n"); scanf("%d", &threadCount); threads = (pthread_t *)malloc(sizeof(pthread_t) * threadCount); clock_gettime(CLOCK_MONOTONIC,&st); for(i=0;i<threadCount;i++){ pthread_create(&threads[i], 0, (void *(*) (void *)) multiply, (void *) (i + 1)); } for (i = 0; i < threadCount; i++) { pthread_join(threads[i], 0); } clock_gettime(CLOCK_MONOTONIC,&en); runtime = en.tv_sec - st.tv_sec+(en.tv_nsec-st.tv_nsec)/(1e9); printf("With multi threading -- %f\\n", runtime); fptr=fopen("output.txt","w"); if(fptr==0){ printf("Error!"); exit(1); } for(i=0;i<n;i++){ for(j=0;j<p;j++){ fprintf(fptr,"%d ",matrix3[i][j]); } fprintf(fptr,"\\n"); } fclose(fptr); clock_gettime(CLOCK_MONOTONIC,&st); int k; int sum = 0; for(i=0;i<n;i++) { for(j=0;j<p;j++){ for(k=0;k<m;k++){ sum = sum + matrix1[i][k]*matrix2[k][j]; } sum = 0; } } clock_gettime(CLOCK_MONOTONIC,&en); runtime = en.tv_sec - st.tv_sec+(en.tv_nsec-st.tv_nsec)/(1e9); printf("Without multi threading -- %f\\n", runtime); return 0; }
1
#include <pthread.h> pthread_t tid[2]; int counter; pthread_mutex_t lock; void* doSomeThing1(void *arg) { int j = 0; printf("%s entering...", __func__); fflush(stdout); while(j < 10) { pthread_mutex_lock(&lock); printf("%s done\\n", __func__); if(j == 5) { pthread_mutex_unlock(&lock); ++j; continue; } unsigned long i = 0; counter += 1; printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j); for(i=0; i<(0xFFFFFF);i++); printf("\\n Job %d finished, tid = %ldm i = %d\\n", counter, pthread_self(), j); pthread_mutex_unlock(&lock); ++j; sleep(1); } return 0; } void* doSomeThing2(void *arg) { int j = 0; printf("%s entering...", __func__); fflush(stdout); while(j < 10) { pthread_mutex_lock(&lock); printf("%s done\\n", __func__); unsigned long i = 0; counter += 1; printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j); for(i=0; i<(0xFFFFFF);i++); printf("\\n Job %d finished, tid = %ld, i = %d\\n", counter, pthread_self(), j); pthread_mutex_unlock(&lock); ++j; sleep(1); } return 0; } int main(void) { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } pthread_create(&tid[0], 0, doSomeThing1, 0); pthread_create(&tid[1], 0, doSomeThing2, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> void *thread_function(void *); pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int counter = 0; main() { pthread_t thread_id[10]; int i, j; for(i=0; i < 10; i++) { pthread_create( &thread_id[i], 0, thread_function, 0 ); } for(j=0; j < 10; j++) { pthread_join( thread_id[j], 0); } printf("Final counter value: %d\\n", counter); } void *thread_function(void *dummyPtr) { printf("Thread number %ld\\n", pthread_self()); pthread_mutex_lock( &mutex1 ); counter++; pthread_mutex_unlock( &mutex1 ); }
1
#include <pthread.h> static pthread_mutex_t mymutex1; static pthread_mutex_t mymutex2; static int th_cnt; void *bodyA(void *arg) { int i,j,k,p,q,r; int sum; printf("%s - lock(mutex1)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_lock(&mymutex1); printf("%s - lock(mutex2)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_lock(&mymutex2); printf("%s - unlock(mutex2)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_unlock(&mymutex2); printf("%s - unlock(mutex1)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_unlock(&mymutex1); printf("%s - thread A finish\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } return 0; } void *bodyB(void *arg) { int i,j,k,p,q,r; int sum; printf("%s - lock(mutex1)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_lock(&mymutex1); printf("%s - lock(mutex2)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_lock(&mymutex2); printf("%s - unlock(mutex2)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_unlock(&mymutex2); printf("%s - unlock(mutex1)\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } pthread_mutex_unlock(&mymutex1); printf("%s - thread B finish\\n",arg); for (i=0;i<100;i++) { sum=0; for (p=0;p<1000000; p++) { sum+=p; } } return 0; } int main() { pthread_t A, B, main_id; pthread_attr_t attrA, attrB; char parameterA[]="A"; char parameterB[]="B"; main_id=pthread_self(); struct sched_param paramA; struct sched_param paramB; struct sched_param param; param.sched_priority=99; paramA.sched_priority=1; paramB.sched_priority=1; pthread_mutexattr_t mymutexattr1; pthread_mutexattr_init(&mymutexattr1); pthread_mutex_init(&mymutex1, &mymutexattr1); pthread_mutexattr_destroy(&mymutexattr1); pthread_mutexattr_t mymutexattr2; pthread_mutexattr_init(&mymutexattr2); pthread_mutex_init(&mymutex2, &mymutexattr2); pthread_mutexattr_destroy(&mymutexattr2); pthread_setschedparam(main_id, SCHED_RR, &param); pthread_attr_init(&attrA); pthread_attr_init(&attrB); pthread_attr_setinheritsched(&attrA, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&attrA, SCHED_RR); pthread_attr_setschedparam(&attrA, &paramA); pthread_attr_setinheritsched(&attrB, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&attrB, SCHED_RR); pthread_attr_setschedparam(&attrB, &paramB); pthread_create(&A, &attrA, bodyA, &parameterA); pthread_attr_destroy(&attrA); pthread_create(&B, &attrB, bodyB, &parameterB); pthread_attr_destroy(&attrB); if (pthread_join(A,0)!=0) { printf("Join thread A error!\\n"); } if (pthread_join(B,0)!=0) { printf("Join thread B error!\\n"); } return 0; }
0
#include <pthread.h> int cond; pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_pcond = PTHREAD_COND_INITIALIZER; void *t1_main(void *unused); void *t2_main(void *unused); void *t1_main(void *unused) { for (int i = 0; i < 3; i++) { cond = cond ? 0 : 1; sleep(1); if (cond) { pthread_cond_signal(&cond_pcond); } } exit(0); return 0; } void *t2_main(void *unused) { struct timespec timeToWait; struct timeval now; int ret; gettimeofday(&now, 0); time_t nowTime; nowTime = now.tv_sec; timeToWait.tv_sec = nowTime; timeToWait.tv_nsec = (now.tv_usec+1000UL*100)*1000UL; while (1) { pthread_mutex_lock(&cond_mutex); while (!cond) { ret = pthread_cond_timedwait(&cond_pcond, &cond_mutex, &timeToWait); printf("t2_main wakeup ret == %d\\n", ret); if (ret) { if (ret == ETIMEDOUT) { printf("\\tret == ETIMEDOUT\\n"); } } } printf("Timespec wait: %ld seconds %lu usec\\n", timeToWait.tv_sec, timeToWait.tv_nsec); pthread_mutex_unlock(&cond_mutex); } return 0; } void *t3_main(void *unused) { struct timespec timeToWait; struct timeval now; int ret; gettimeofday(&now, 0); time_t nowTime; nowTime = now.tv_sec; timeToWait.tv_sec = nowTime; timeToWait.tv_nsec = (now.tv_usec+1000UL*100)*1000UL; while (1) { pthread_mutex_lock(&cond_mutex); while (!cond) { ret = pthread_cond_timedwait(&cond_pcond, &cond_mutex, &timeToWait); printf("t2_main wakeup ret == %d\\n", ret); if (ret) { if (ret == ETIMEDOUT) { printf("\\tret == ETIMEDOUT\\n"); } } } printf("Timespec wait: %ld seconds %lu usec\\n", timeToWait.tv_sec, timeToWait.tv_nsec); pthread_mutex_unlock(&cond_mutex); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; pthread_create(&t1, 0, t1_main, 0); pthread_create(&t2, 0, t2_main, 0); pthread_exit((void *) 0); }
1
#include <pthread.h> NEW, PROCESSING, DONE }statuses; int duration; int id; statuses status; pthread_t worker; } task_t; pthread_mutex_t lock; task_t tasks[100]; void* my_thread(void* var){ int frag = 0, k = 0; while(k <= 100){ task_t *copy = (task_t*)var; pthread_mutex_lock(&lock); while(copy[k].status != NEW ){ k++; } copy[k].status = PROCESSING; pthread_mutex_unlock(&lock); if (k >= 100){ break; } printf("Task No %d is putting thread to sleep for %d mks\\n",copy[k].id, copy[k].duration); usleep(copy[k].duration); frag++; copy[k].status = DONE; } printf("Worker has fragged %d tasks\\n",frag); return 0; } int main(){ statuses status; pthread_t thread_id[10]; int result , i; for (i = 0; i < 100; i++){ tasks[i].id = i; tasks[i].duration = abs(random() % 1000); } for (i = 0; i < 10; i++){ pthread_create(&(thread_id[i]), 0, my_thread, (void*)(tasks)); } for(i = 0; i < 10; i++){ pthread_join(thread_id[i],0); } printf("END\\n"); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo *foo_alloc(void){ struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0){ fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0){ free(fp); return (0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp){ pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_find(int id){ struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next){ if (fp->f_id == id){ foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp){ struct foo *tfp; int idx; } int main(int argc, char *argv[]){ exit(0); }
1
#include <pthread.h> int64_t size; struct nu_free_cell* next; } nu_free_cell; static const int64_t CHUNK_SIZE = 65536; static const int64_t CELL_SIZE = (int64_t)sizeof(nu_free_cell); static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static nu_free_cell* nu_free_list = 0; void* hrealloc(void* item, int64_t size) { char* result = (char*) hmalloc(size); char* copy = (char*) item; int64_t* original_size_ptr = (item - sizeof(int64_t)); int64_t original_size = *original_size_ptr; memcpy(result, copy, original_size); hfree(item); return result; } int64_t nu_free_list_length() { int len = 0; for (nu_free_cell* pp = nu_free_list; pp != 0; pp = pp->next) { len++; } return len; } void nu_print_free_list() { nu_free_cell* pp = nu_free_list; printf("= Free list: =\\n"); for (; pp != 0; pp = pp->next) { printf("%lx: (cell %ld %lx)\\n", (int64_t) pp, pp->size, (int64_t) pp->next); } } static void nu_free_list_coalesce() { nu_free_cell* pp = nu_free_list; int free_chunk = 0; while (pp != 0 && pp->next != 0) { if (((int64_t)pp) + pp->size == ((int64_t) pp->next)) { pp->size += pp->next->size; pp->next = pp->next->next; } pp = pp->next; } } static void nu_free_list_insert(nu_free_cell* cell) { if (nu_free_list == 0 || ((uint64_t) nu_free_list) > ((uint64_t) cell)) { cell->next = nu_free_list; nu_free_list = cell; return; } nu_free_cell* pp = nu_free_list; while (pp->next != 0 && ((uint64_t)pp->next) < ((uint64_t) cell)) { pp = pp->next; } cell->next = pp->next; pp->next = cell; nu_free_list_coalesce(); } static nu_free_cell* free_list_get_cell(int64_t size) { nu_free_cell** prev = &nu_free_list; for (nu_free_cell* pp = nu_free_list; pp != 0; pp = pp->next) { if (pp->size >= size) { *prev = pp->next; return pp; } prev = &(pp->next); } return 0; } static nu_free_cell* make_cell() { void* addr = mmap(0, CHUNK_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); nu_free_cell* cell = (nu_free_cell*) addr; cell->size = CHUNK_SIZE; return cell; } void* hmalloc(size_t usize) { pthread_mutex_lock(&mutex); int64_t size = (int64_t) usize; int64_t alloc_size = size + sizeof(int64_t); if (alloc_size < CELL_SIZE) { alloc_size = CELL_SIZE; } if (alloc_size > CHUNK_SIZE) { void* addr = mmap(0, alloc_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); *((int64_t*)addr) = alloc_size; pthread_mutex_unlock(&mutex); return addr + sizeof(int64_t); } nu_free_cell* cell = free_list_get_cell(alloc_size); if (!cell) { cell = make_cell(); } int64_t rest_size = cell->size - alloc_size; if (rest_size >= CELL_SIZE) { void* addr = (void*) cell; nu_free_cell* rest = (nu_free_cell*) (addr + alloc_size); rest->size = rest_size; nu_free_list_insert(rest); } *((int64_t*)cell) = alloc_size; pthread_mutex_unlock(&mutex); return ((void*)cell) + sizeof(int64_t); } void hfree(void* addr) { nu_free_cell* cell = (nu_free_cell*)(addr - sizeof(int64_t)); int64_t size = *((int64_t*) cell); if (size > CHUNK_SIZE) { munmap((void*) cell, size); } else { cell->size = size; pthread_mutex_lock(&mutex); nu_free_list_insert(cell); pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> int sharedData = 0; pthread_mutex_t mutex; void delay(int secs) { time_t beg = time(0), end = beg + secs; do ; while (time(0) < end); } void *add1000(void *n) { pthread_mutex_lock(&mutex); int j = sharedData; delay(rand() % 6); sharedData = j + 1000; pthread_mutex_unlock(&mutex); printf("1000 added!\\n"); return n; } int main() { pthread_attr_t *attr = 0; pthread_t thrd[5]; int t; pthread_mutex_init(&mutex, 0); srand(time(0)); for (t=0; t<5; t++) pthread_create(&thrd[t], attr, add1000, 0); for (t=0; t<5; t++) pthread_join(thrd[t], 0); printf("Shared data = %d\\n", sharedData); return 0; }
1
#include <pthread.h> int q[5]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; int i = 0; printf2 ("prod: trying\\n"); while (done == 0) { i++; pthread_mutex_lock (&mq); if (qsiz < 5) { printf2 ("prod: got it! x %d qsiz %d i %d\\n", x, qsiz, i); done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x, i = 0; printf2 ("consumer: trying\\n"); while (done == 0) { i++; pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; qsiz--; x = q[qsiz]; printf2 ("consumer: got it! x %d qsiz %d i %d\\n", x, qsiz, i); } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmax (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } swap (t, mx, count-1); return t[count-1]; } int source[7]; int sorted[7]; void producer () { int i, max; for (i = 0; i < 7; i++) { max = findmax (source, 7 - i); queue_insert (max); } } void consumer () { int i, max; for (i = 0; i < 7; i++) { max = queue_extract (); sorted[i] = max; } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; __libc_init_poet (); unsigned seed = (unsigned) time (0); int i; srand (seed); printf ("Using seed %u\\n", seed); for (i = 0; i < 7; i++) { source[i] = random() % 20; assert (source[i] >= 0); printf2 ("source[%d] = %d\\n", i, source[i]); } printf2 ("==============\\n"); queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); printf2 ("==============\\n"); for (i = 0; i < 7; i++) printf2 ("sorted[%d] = %d\\n", i, sorted[i]); return 0; }
0
#include <pthread.h> FILE *fp1,*fp2; int file_size; char buf[100]; volatile char read_size=0; volatile char buf_ready =0; volatile char end_file =0; pthread_mutex_t pthread_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t pthread_cond = PTHREAD_COND_INITIALIZER; int buf_compare(char *buf1, char *buf2, int size){ int i; for(i=0;i<size;i++){ if(buf1[i] != buf2[i]){ printf("Failed \\n"); return 1; } } return 0; } int compare(FILE *file1, FILE *file2, int file_size) { printf(">>compare\\n"); int readp=0,rest = 0, nread1 =0, nread2 =0; char buf1[1024]; char buf2[1024]; while(1){ if((nread1 = fread(buf1,1,1024,file1)) !=1024){ printf("fead file1 failed\\n"); nread2 = fread(buf2,1,1024,file2); break; } if((nread2 = fread(buf2,1,1024,file2)) !=1024){ printf("fead file2 failed\\n"); break; } if( buf_compare(buf1, buf2, 1024) == 1){ printf("FAILED\\n"); return 1; } } if(feof(file1)) printf("end of file1 \\n"); if(feof(file2)) printf("end of file2 \\n"); if (nread1 != nread2){ printf("FAILED on file1 size:%d \\n",nread1); printf("FAILED on file2 size:%d \\n",nread2); printf("FAILED on file size \\n"); return 1; } if(buf_compare(buf1, buf2, nread1) == 1){ printf("FAILED\\n"); return 1; }else{ printf("PASS\\n"); } printf("<<compare\\n"); return 0; } void * thread_write(void *arg) { int rp = 0,rest,i; int nWrite =0 ; printf(">>write_thread\\n"); pthread_mutex_lock(&pthread_mutex); while(1){ while(( buf_ready == 0)){ pthread_cond_wait(&pthread_cond, &pthread_mutex); } if(buf_ready == 1){ fwrite(buf,read_size,1,fp2); nWrite += read_size; buf_ready = 0; } if(end_file == 1 ) { break; } } pthread_mutex_unlock(&pthread_mutex); printf("write_thread: total write = %d\\n",nWrite); return 0; } int main(int argc, char * argv[]) { int i,n,rest,nread=0,rp=0,status; pthread_t a_thread; pthread_t b_thread; struct stat file_stat; if((fp1 = fopen(argv[1],"r+")) == 0) perror("fopen error"); if((fp2 = fopen(argv[2],"w+")) == 0) perror("fopen error"); if(stat(argv[1],&file_stat) != 0) perror("stat error"); printf("file_size = %d\\n",file_stat.st_size); file_size = file_stat.st_size; pthread_create(&a_thread,0,thread_write,0); end_file = 0; while(1){ pthread_mutex_lock(&pthread_mutex); if(buf_ready ==0){ while((read_size = rand()%100) == 0); if((nread = fread(buf,1,read_size,fp1)) != read_size){ buf_ready = 1; break; } buf_ready = 1; rp += read_size; } pthread_cond_signal(&pthread_cond); if (status = pthread_mutex_unlock(&pthread_mutex) != 0) printf("error unlock \\n"); } printf("main_thread: near end of file1, total read size now is %d\\n", rp); read_size = nread; printf("main_thread: rest read = %d\\n", read_size); end_file = 1; pthread_cond_signal(&pthread_cond); pthread_mutex_unlock(&pthread_mutex); pthread_join(a_thread,0); rewind(fp1); rewind(fp2); if(compare(fp1, fp2, file_size)){ printf("FAILED\\n"); return 1; }else{ printf("PASS\\n"); return 0; } }
1
#include <pthread.h> long int left; long int left_updated = 0; long int right; long int right_updated = 0; pthread_mutex_t lock; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void handle_values(long int new_left, long int new_right) { if (abs(new_right) < 10000) { new_right = 0; } if (abs(new_left) < 10000) { new_left = 0; } int update_right = abs(new_right - right) > 1000; int update_left = abs(new_left - left) > 1000; pthread_mutex_lock(&lock); if (update_left) { left = new_left; left_updated = 1; } if (update_right) { right = new_right; right_updated = 1; } if (update_left || update_right) { pthread_cond_broadcast(&cond); } pthread_mutex_unlock(&lock); } void handle_input(char *line) { char *end; char *expected_end = line + strlen(line); long int new_left = strtol(line, &end, 10); end++; long int new_right = strtol(end, &end, 10); if (end != expected_end) { fprintf(stderr, "Failed to parse input line: %s\\n", line); return; } handle_values(new_left, new_right); } int read_line(char *buf, int buf_len) { int len = 0; while (1) { int c = fgetc(stdin); if(c == EOF) { fprintf(stderr, "Stdin closed\\n"); exit(1); } if (c == '\\n') { buf[len] = 0; return len; } else if (len >= buf_len - 1) { fprintf(stderr, "Stdin line too long\\n"); while (fgetc(stdin) != '\\n') ; return 0; } else { buf[len] = c; len++; } } } void *read_input_thread(void* param) { char buf[500]; while (1) { if (read_line(buf, 500) > 0) handle_input(buf); } } void set_motor(char *command, char *param, long int value) { char buf[256]; snprintf(buf, 128, "%s %s %ld", command, param, value); int ret = system(buf); if (WIFSIGNALED(ret) && (WTERMSIG(ret) == SIGINT || WTERMSIG(ret) == SIGQUIT)) exit(ret); } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: control-motors <set-motor-command>\\n"); exit(1); } char *command_name = argv[1]; pthread_t read_thread; if (pthread_create(&read_thread, 0, &read_input_thread, 0)) { fprintf(stderr, "Error creating thread\\n"); exit(1); } if (pthread_mutex_init(&lock, 0)) { fprintf(stderr, "mutex init failed\\n"); exit(1); } while (1) { pthread_mutex_lock(&lock); if (!left_updated && !right_updated) pthread_cond_wait(&cond, &lock); long int myleft = left; long int myleft_updated = left_updated; long int myright = right; long int myright_updated = right_updated; right_updated = 0; left_updated = 0; pthread_mutex_unlock(&lock); if (myright_updated) { set_motor(command_name, "-r", myright); } if (myleft_updated) { set_motor(command_name, "-l", myleft); } } }
0
#include <pthread.h> static pthread_mutex_t lock; static char *g_str = ""; static int g_length = 0; unsigned long fib(unsigned long n) { if (n == 0) return 0; if (n == 1) return 2; return fib(n-1)+fib(n-2); } void * worker1(void *v) { int input = (int)v; pthread_mutex_lock(&lock); fprintf(stderr, "[1] acquired lock\\n"); g_str = strdup("test string"); fprintf(stderr, "[1] release lock\\n"); pthread_mutex_unlock(&lock); fib(input); pthread_mutex_lock(&lock); fprintf(stderr, "[1] acquired lock\\n"); g_length = strlen(g_str); fprintf(stderr, "[1] release lock\\n"); pthread_mutex_unlock(&lock); return 0; } void * worker2(void *v) { char *tptr; int tlen; pthread_mutex_lock(&lock); fprintf(stderr, "[2] acquired lock\\n"); tptr = g_str; fprintf(stderr, "[2] release lock\\n"); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); fprintf(stderr, "[2] acquired lock\\n"); tlen = g_length; fprintf(stderr, "[2] release lock\\n"); pthread_mutex_unlock(&lock); printf("tptr = %s, tlen = %d\\n", tptr, tlen); if ( strlen(tptr) != tlen ) { printf("ERROR: mismatch\\n"); } return 0; } static void usage(char *argv[]) { printf("%s -x <x> -y <y>\\n" "-x : input for thread 1\\n" "-y : input for thread 2\\n", argv[0]); } int main(int argc, char *argv[]) { pthread_t allthr[10]; int i, ret; int x, y; x = 13; y = 0; while((i=getopt(argc, argv, "x:y:h")) != EOF) { switch(i) { case 'h': usage(argv); return 0; case 'x': x = strtol(optarg, 0, 0); break; case 'y': y = strtol(optarg, 0, 0); break; default: errx(1, "invalid option"); } } pthread_mutex_init(&lock, 0); ret = pthread_create(&allthr[0], 0, worker1, (void *)(unsigned long)x); if (ret) err(1, "pthread_create failed"); ret = pthread_create(&allthr[1], 0, worker2, (void *)(unsigned long)y); if (ret) err(1, "pthread_create failed"); pthread_join(allthr[0], 0); pthread_join(allthr[1], 0); return 0; }
1
#include <pthread.h> static unsigned char inited = 0; static unsigned char openned = 0; static pthread_mutex_t operate_lock; unsigned short BluetoothInit() { if (inited) { return 0; } system("mount -t usbdevfs none /proc/bus/usb"); if (ftdi_init()) { inited = 1; pthread_mutex_init(&operate_lock, 0); }else{ inited = 0; } } static unsigned short BluetoothCheckStat() { if (!inited) { return 1; } if (!openned) { if (ftdi_open(0x0403, 0x6001)) { openned = 1; } } if (openned) { if (!ftdi_get_state()) { openned = 0; } } if (!openned) { return 2; } return 0; } unsigned short BluetoothSend(unsigned short msgLen, unsigned char *msgBuff) { unsigned short r = 0; pthread_mutex_lock(&operate_lock); if (BluetoothCheckStat()) { r = 1; goto out; } if (ftdi_write_data(msgBuff, msgLen) < 0) { r = 2; goto out; } out: pthread_mutex_unlock(&operate_lock); return r; } unsigned short BluetoothRecv(unsigned short *msgLen, unsigned char *msgBuff) { unsigned short r = 0; pthread_mutex_lock(&operate_lock); if (BluetoothCheckStat()) { r = 1; goto out; } if ((*msgLen=ftdi_read_data(msgBuff, msgLen)) < 0) { r = 2; goto out; } out: pthread_mutex_unlock(&operate_lock); return r; } unsigned short BluetoothExit() { pthread_mutex_lock(&operate_lock); if (inited) { inited = 0; openned = 0; ftdi_close(); } pthread_mutex_unlock(&operate_lock); pthread_mutex_destory(&operate_lock); }
0
#include <pthread.h> void pks_global_init(unsigned int log_mask) { memset(&pk_state, 0, sizeof(struct pk_global_state)); pthread_mutex_init(&(pk_state.lock), 0); pthread_cond_init(&(pk_state.cond), 0); pk_state.log_ring_start = pk_state.log_ring_end = pk_state.log_ring_buffer; pk_state.log_file = stderr; pk_state.log_mask = log_mask; pk_state.bail_on_errors = 0; pk_state.conn_eviction_idle_s = 0; pk_state.socket_timeout_s = PK_DEFAULT_SOCKET_TIMEOUT; pk_state.fake_ping = 0; pk_state.ssl_ciphers = PKS_DEFAULT_CIPHERS; pk_state.ssl_cert_names = 0; pk_state.use_ipv4 = 1; pk_state.have_ssl = 0; pk_state.app_id_long = "libpagekite"; pk_state.app_id_short = PK_VERSION; pk_state.quota_days = -1; pk_state.quota_conns = -1; pk_state.quota_mb = -1; } int pks_logcopy(const char *src, size_t len) { int tmp; len += 1; if (len >= PKS_LOG_DATA_MAX) return -1; pthread_mutex_lock(&(pk_state.lock)); if (((pk_state.log_ring_end < pk_state.log_ring_start) && (pk_state.log_ring_end + len >= pk_state.log_ring_start)) || ((pk_state.log_ring_end > pk_state.log_ring_start) && (pk_state.log_ring_end + len >= pk_state.log_ring_start + PKS_LOG_DATA_MAX))) { pk_state.log_ring_start += len; if (pk_state.log_ring_start >= pk_state.log_ring_buffer+PKS_LOG_DATA_MAX) pk_state.log_ring_start -= PKS_LOG_DATA_MAX;; while ((*pk_state.log_ring_start != '\\n') && (pk_state.log_ring_start != pk_state.log_ring_end)) { pk_state.log_ring_start++; if (pk_state.log_ring_start >= pk_state.log_ring_buffer+PKS_LOG_DATA_MAX) pk_state.log_ring_start -= PKS_LOG_DATA_MAX;; } while (*pk_state.log_ring_start == '\\n') { pk_state.log_ring_start++; if (pk_state.log_ring_start >= pk_state.log_ring_buffer+PKS_LOG_DATA_MAX) pk_state.log_ring_start -= PKS_LOG_DATA_MAX;; } } len -= 1; if ((pk_state.log_ring_end > pk_state.log_ring_start) && (pk_state.log_ring_end + len >= pk_state.log_ring_buffer + PKS_LOG_DATA_MAX)) { tmp = PKS_LOG_DATA_MAX - (pk_state.log_ring_end - pk_state.log_ring_buffer); memcpy(pk_state.log_ring_end, src, tmp); memcpy(pk_state.log_ring_buffer, src + tmp, len - tmp); pk_state.log_ring_end = pk_state.log_ring_buffer + len - tmp; } else { memcpy(pk_state.log_ring_end, src, len); pk_state.log_ring_end += len; } if (pk_state.log_ring_end >= pk_state.log_ring_buffer+PKS_LOG_DATA_MAX) pk_state.log_ring_end -= PKS_LOG_DATA_MAX;; *pk_state.log_ring_end++ = '\\n'; if (pk_state.log_ring_end >= pk_state.log_ring_buffer+PKS_LOG_DATA_MAX) pk_state.log_ring_end -= PKS_LOG_DATA_MAX;; *pk_state.log_ring_end = '\\0'; pthread_cond_broadcast(&(pk_state.cond)); pthread_mutex_unlock(&(pk_state.lock)); return len; } void pks_copylog(char *dest) { pthread_mutex_lock(&(pk_state.lock)); strcpy(dest, pk_state.log_ring_start); if (pk_state.log_ring_end < pk_state.log_ring_start) strcat(dest, pk_state.log_ring_buffer); pthread_mutex_unlock(&(pk_state.lock)); } void pks_printlog(FILE* dest) { pthread_mutex_lock(&(pk_state.lock)); fprintf(dest, "%s", pk_state.log_ring_start); if (pk_state.log_ring_end < pk_state.log_ring_start) fprintf(dest, "%s", pk_state.log_ring_buffer); pthread_mutex_unlock(&(pk_state.lock)); } void pks_free_ssl_cert_names() { char** p = pk_state.ssl_cert_names; if ((p != 0) && (*p != *PAGEKITE_NET_CERT_NAMES)) { while (*p != 0) free(*p++); free(pk_state.ssl_cert_names); } pk_state.ssl_cert_names = 0; } void pks_add_ssl_cert_names(char** names) { int len_current = 0; int len_new = 0; char** p = pk_state.ssl_cert_names; while (p != 0 && *p++ != 0) len_current++; char** n = (char**) names; while (n != 0 && *n++ != 0) len_new++; if (!(len_current || len_new)) { pks_free_ssl_cert_names(); return; } char** buffer = malloc((len_current + len_new + 1) * sizeof(char*)); n = buffer; p = pk_state.ssl_cert_names; while (p && *p) { *n++ = strdup(*p++); }; p = (char**) names; while (p && *p) { *n++ = strdup(*p++); }; *n = 0; pks_free_ssl_cert_names(); pk_state.ssl_cert_names = buffer; }
1
#include <pthread.h> struct thread_data{ int shmid; pthread_mutex_t *mutex_ptr; pthread_cond_t *cond_ptr; }; void *second_thread(void *this_data) { time_t childTime; char *shm; struct thread_data *data; data = (struct thread_data *)this_data; pthread_mutex_lock(data->mutex_ptr); sleep(5); shm = (char *)shmat(data->shmid, 0, 0); if(shm == (char *)(-1)){ perror("shmat"); exit(1); } time(&childTime); sprintf(shm, ctime(&childTime)); pthread_mutex_unlock(data->mutex_ptr); pthread_cond_signal(data->cond_ptr); } int main(int argc, char const *argv[]) { int shmid; char *shm; pthread_t thid; time_t pTime; time_t start, end; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; if(pthread_mutex_init(&mutex, 0) != 0) { perror("pthread_mutex_init"); exit(1); } pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; if(pthread_cond_init(&cond_var, 0) != 0) { perror("pthread_cond_init"); exit(1); } shmid = shmget(IPC_PRIVATE, 28, IPC_CREAT | 0666); if(shmid < 0){ perror("shmget"); exit(1); } shm = (char *)shmat(shmid, 0, 0); if(shm == (char *)(-1)){ perror("shmat"); exit(1); } struct thread_data data; data.shmid = shmid; data.mutex_ptr = &mutex; data.cond_ptr = &cond_var; if(pthread_create(&thid, 0, second_thread, &data) == 0) { time(&pTime); sleep(1); time(&start); if(pthread_cond_wait(&cond_var, &mutex) == 0){ time(&end); double elapsedTime = difftime(end, start); printf("%.f seconds waited\\n", elapsedTime); printf("\\nParent process was created at: %s", ctime(&pTime)); printf("Child process was created at: %s\\n", shm); } else { perror("pthread_cond_wait"); exit(1); } shmdt(shm); } else { perror("pthread_create"); exit(1); } return 0; }
0