text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct header_t { size_t size; unsigned is_free; struct header_t *next; }; struct header_t *head = 0, *tail = 0; pthread_mutex_t global_malloc_lock; struct header_t *get_free_block(size_t size) { struct header_t *curr = head; while(curr) { if (curr->is_free && curr->size >= size) return curr; curr = curr->next; } return 0; } void free(void *block) { struct header_t *header, *tmp; void *programbreak; if (!block) return; pthread_mutex_lock(&global_malloc_lock); header = (struct header_t*)block - 1; programbreak = sbrk(0); if ((char*)block + header->size == programbreak) { if (head == tail) { head = tail = 0; } else { tmp = head; while (tmp) { if(tmp->next == tail) { tmp->next = 0; tail = tmp; } tmp = tmp->next; } } sbrk(0 - header->size - sizeof(struct header_t)); pthread_mutex_unlock(&global_malloc_lock); return; } header->is_free = 1; pthread_mutex_unlock(&global_malloc_lock); } void *malloc(size_t size) { size_t total_size; void *block; struct header_t *header; if (!size) return 0; pthread_mutex_lock(&global_malloc_lock); header = get_free_block(size); if (header) { header->is_free = 0; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } total_size = sizeof(struct header_t) + size; block = sbrk(total_size); if (block == (void*) -1) { pthread_mutex_unlock(&global_malloc_lock); return 0; } header = block; header->size = size; header->is_free = 0; header->next = 0; if (!head) head = header; if (tail) tail->next = header; tail = header; pthread_mutex_unlock(&global_malloc_lock); return (void*)(header + 1); } void *calloc(size_t num, size_t nsize) { size_t size; void *block; if (!num || !nsize) return 0; size = num * nsize; if (nsize != size / num) return 0; block = malloc(size); if (!block) return 0; memset(block, 0, size); return block; } void *realloc(void *block, size_t size) { struct header_t *header; void *ret; if (!block || !size) return malloc(size); header = (struct header_t*)block - 1; if (header->size >= size) return block; ret = malloc(size); if (ret) { memcpy(ret, block, header->size); free(block); } return ret; } void print_mem_list() { struct header_t *curr = head; printf("head = %p, tail = %p \\n", (void*)head, (void*)tail); while(curr) { printf("addr = %p, size = %zu, is_free=%u, next=%p\\n", (void*)curr, curr->size, curr->is_free, (void*)curr->next); curr = curr->next; } }
1
#include <pthread.h> volatile int val = 0; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *test_thread(void*data) { pthread_mutex_lock(&mutex); val = 1; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); return 0; } int main() { int ret=0; pthread_t pt; struct timespec timeout; printf("Create thread\\n"); pthread_create(&pt, 0, test_thread, 0); pthread_detach(pt); printf("sleep 1\\n"); sleep(1); printf("cond wait, timeout time:2\\n"); pthread_mutex_lock(&mutex); clock_gettime(CLOCK_REALTIME, &timeout); timeout.tv_sec += 2; { ret = pthread_cond_timedwait(&cond, &mutex, &timeout); } pthread_mutex_unlock(&mutex); printf("ret:%d\\n", ret); if (ret != 0){ printf("time out\\n"); printf("error: %s\\n", strerror(ret)); } return 0; }
0
#include <pthread.h> int buff[10]; int buff_index; pthread_mutex_t buff_mutex; sem_t buff_sem_full; sem_t buff_sem_empty; int push_front(int val) { if(buff_index < 10) { buff[buff_index++] = val; return 0; } else return -1; } int pop_front() { if(buff_index > 0) return buff[--buff_index]; else return -1; } void* producer(void* arg) { int result; while(1) { for(int i = 0 ; i < 20 ; i++) { sem_wait(&buff_sem_empty); pthread_mutex_lock(&buff_mutex); result = push_front(i); printf("producer : %d | result = %d\\n", i, result); pthread_mutex_unlock(&buff_mutex); sem_post(&buff_sem_full); } } } void* consumer(void* arg) { int temp; while(1) { sem_wait(&buff_sem_full); pthread_mutex_lock(&buff_mutex); temp = pop_front(); printf("consumer : %d\\n", temp); pthread_mutex_unlock(&buff_mutex); sem_post(&buff_sem_empty); } } int main() { pthread_t th1, th2; pthread_mutex_init(&buff_mutex, 0); sem_init(&buff_sem_full, 0, 0); sem_init(&buff_sem_empty, 0, 10); pthread_create(&th1, 0, producer, 0); pthread_create(&th2, 0, consumer, 0); pthread_join(th1, 0); pthread_join(th2, 0); return 0; }
1
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> void search_by_thread( void* ptr); { char* start_ptr; char* end_ptr; int num; char match_str[16]; } thread_data; pthread_mutex_t mutex; int main() { FILE* fRead; char line[16]; char search_str[16]; char* array_ptr; char* temp_ptr; int i = 0; int j = 0; int fchar; int num_inputs = 0; int num_threads; int num_slices; int slice_size = 0; double time; fRead = fopen("fartico_aniketsh_input_partA.txt", "r"); Timer_start(); while(EOF != (fchar = fgetc(fRead))) {if ( fchar == '\\n'){++num_inputs;}} if ( fchar != '\\n' ){++num_inputs;} fclose(fRead); if ( num_inputs > 4 ) { num_inputs = num_inputs -3; } fRead = fopen("fartico_aniketsh_input_partA.txt", "r"); num_threads = fgetc(fRead) - 48; fgetc(fRead); num_slices = fgetc(fRead) - 48; fgetc(fRead); fgets(search_str, sizeof(search_str), fRead); array_ptr = malloc(num_inputs * sizeof(line)); temp_ptr = array_ptr; slice_size = num_inputs / num_threads; while(fgets(line, sizeof(line), fRead)) { strcpy(&temp_ptr[i*16], line); i++; } Timer_elapsedUserTime(&time); while(&temp_ptr[j*16] < &temp_ptr[i*16]) { j++; } printf("\\n\\nITEMS STORED: %d ITEMS PRINTED: %d\\n",i, j); printf("MEMORY USED: %d\\n", (&temp_ptr[i*16] - temp_ptr)); printf("TIME TO STORE: %g\\n", time); printf("\\n\\n"); printf("INPUTS: %d\\n", num_inputs); printf("THREADS: %d\\n", num_threads); printf("SLICES: %d\\n", num_slices); printf("SEARCH STR: %s\\n", search_str); printf("SIZE OF SLICES: %d\\n", slice_size); pthread_t thread_array[num_threads]; thread_data data_array[num_threads]; int k; for( k = 0; k < num_slices; ++k) { data_array[k].start_ptr = &array_ptr[k * slice_size * 16]; data_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 16]; data_array[k].num = k; strcpy(data_array[k].match_str, search_str); } pthread_mutex_init(&mutex, 0); for( k = 0; k < num_slices; ++k) { pthread_create(&thread_array[k], 0, (void *) & search_by_thread, (void *) &data_array[k]); } for( k =0; k < num_slices; ++k) { pthread_join(thread_array[k], 0); } pthread_mutex_destroy(&mutex); return 0; } void search_by_thread( void* ptr) { thread_data* data; data = (thread_data *) ptr; int i = 0; char* temp_ptr = data->start_ptr; pthread_mutex_lock(&mutex); printf("\\nTHREAD--------> %d\\n", data->num); while( &temp_ptr[i*16] < data->end_ptr) { if( strcmp(&temp_ptr[i*16], data->match_str) == 0) { printf("Matched Found\\n"); } i = i +1; } printf("Iterations: %d\\n", i); pthread_mutex_unlock(&mutex); pthread_exit(0); }
1
#include <pthread.h> static int si_init_flag = 0; static int s_conf_fd = -1; static struct sockaddr_un s_conf_addr ; static int s_buf_index = 0; static char s_conf_buf[4][(16384)]; static pthread_mutex_t s_atomic; static char CONF_LOCAL_NAME[16] = "/tmp/cfgClient"; inline int cfgSockSetLocal(const char * pLocalName) { if (pLocalName) { snprintf(CONF_LOCAL_NAME, 15, pLocalName); return 0; } else return -1; } int cfgSockInit() { if (si_init_flag) return 0; s_conf_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (s_conf_fd < 0) { return -1; } if (0 != pthread_mutex_init(&s_atomic, 0)) { close(s_conf_fd); s_conf_fd = -1; return -1; } unlink(CONF_LOCAL_NAME); bzero(&s_conf_addr , sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), CONF_LOCAL_NAME); bind(s_conf_fd, (struct sockaddr *)&s_conf_addr, sizeof(s_conf_addr)); bzero(&s_conf_addr , sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), "/tmp/cfgServer"); si_init_flag = 1; return 0; } int cfgSockUninit() { if (!si_init_flag) return 0; cfgSockSaveFiles(); if (s_conf_fd > 0) { close(s_conf_fd); } s_conf_fd = -1; unlink(CONF_LOCAL_NAME); pthread_mutex_destroy(&s_atomic); si_init_flag = 0; return 0; } static int cfgSockSend(const char *command) { int ret = -1 ; int addrlen = sizeof(s_conf_addr) ; int len = strlen(command); if (!si_init_flag) return -1; ret = sendto(s_conf_fd , command, len, 0, (struct sockaddr *)&s_conf_addr , addrlen); if (ret != len) { close(s_conf_fd) ; s_conf_fd = -1; ret = -1 ; si_init_flag = 0; syslog(LOG_ERR, "send conf message failed , ret = %d , errno %d\\n", ret, errno); } return ret ; } static int cfgSockRecv(char * buf, int len) { int ret; if (!si_init_flag) return -1; ret = recv(s_conf_fd , buf, len-1, 0); if (ret > 0) buf[ret] = '\\0'; else buf[0] = '\\0'; return ret; } static int cfgSockRequest(const char* command, char *recvbuf, int recvlen) { int ret; if (!command || !recvbuf || !recvlen) return -1; ret = cfgSockSend(command); if (ret >= 0) { ret = cfgSockRecv(recvbuf, recvlen); } return ret; } const char *cfgSockGetValue(const char *a_pSection, const char *a_pKey, const char *a_pDefault) { int nRet = -1; char *conf_buf; if (!si_init_flag || (!a_pSection && !a_pKey)) return 0; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index += 1; s_buf_index &= 3; if (a_pSection && a_pKey) { if (!a_pDefault) snprintf(conf_buf, (16384), "R %s.%s %s", a_pSection, a_pKey, "NULL"); else snprintf(conf_buf, (16384), "R %s.%s %s", a_pSection, a_pKey, a_pDefault); } else { const char *key = (a_pSection)? a_pSection : a_pKey; if (!a_pDefault) snprintf(conf_buf, (16384), "R %s %s", key, "NULL"); else snprintf(conf_buf, (16384), "R %s %s", key, a_pDefault); } cfgSockRequest(conf_buf, conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); nRet = strncmp(conf_buf, "NULL", 4); if (0 == nRet) { return a_pDefault; } return conf_buf; } int cfgSockSetValue(const char *a_pSection, const char *a_pKey, const char *a_pValue) { char *conf_buf; if (!si_init_flag || (!a_pSection && !a_pKey) || !a_pValue) return -1; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index += 1; s_buf_index &= 3; if (a_pSection && a_pKey) { snprintf(conf_buf, (16384), "W %s.%s %s", a_pSection, a_pKey, a_pValue); } else { const char *key = (a_pSection)? a_pSection : a_pKey; snprintf(conf_buf, (16384), "W %s %s", key, a_pValue); } cfgSockRequest(conf_buf, conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); return 0; } int cfgSockSaveFiles() { char *conf_buf; if (!si_init_flag) return -1; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index += 1; s_buf_index &= 3; cfgSockRequest("s", conf_buf, sizeof(conf_buf)); pthread_mutex_unlock(&s_atomic); return 0; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long) t; for (i = 0; i < 5; i++) { pthread_mutex_lock(&count_mutex); count++; if (count < 7) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long) t; printf("Starting watch_count(): thread %ld\\n", my_id); while (count < 7) { pthread_mutex_lock(&count_mutex); printf("watch_count(): thread %ld going into wait...\\n", my_id); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); } pthread_exit(0); } int main(int argc, char *argv[]) { int i; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *) t1); pthread_create(&threads[1], &attr, inc_count, (void *) t2); pthread_create(&threads[2], &attr, inc_count, (void *) t3); for (i = 1; i < 3; i++) { pthread_join(threads[i], 0); } pthread_cond_signal(&count_threshold_cv); pthread_join(threads[0],0); printf("Main(): Waited on %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> int somme_alea; int cpt; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_cpt = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_cpt = PTHREAD_COND_INITIALIZER; void* thread_rand(void * arg){ int random_val = (int) ((float) 10 * rand() /(32767 + 1.0)); printf("Mon num d'ordre : %d \\t mon tid %d \\t valeur generee : %d\\n", (*(int *)arg), (int)pthread_self(), random_val); pthread_mutex_lock(&mutex); somme_alea += random_val; pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex_cpt); cpt++; if (cpt == 5){ pthread_cond_signal(&cond_cpt); } pthread_mutex_unlock(&mutex_cpt); pthread_exit((void *)0); } void * print_thread(void * arg){ pthread_mutex_lock(&mutex_cpt); pthread_cond_wait(&cond_cpt, &mutex_cpt); pthread_mutex_unlock(&mutex_cpt); printf("La somme des valeurs generees par les threads est : %d \\n", somme_alea); pthread_exit((void *)0); } int main(int argc, char * argv[]){ int i, p,status; pthread_attr_t attr; int tab[5]; pthread_t tid[5]; pthread_t pt_print_tid; somme_alea = 0; cpt = 0; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); srand(time(0)); if (pthread_create(&pt_print_tid, 0, print_thread, 0) != 0){ perror("pthread_create"); exit(1); } for(i=0; i<5; i++){ tab[i]=i; if((p=pthread_create(&(tid[i]), &attr, thread_rand, &tab[i])) != 0){ perror("pthread_create"); exit(1); } } if(pthread_join( pt_print_tid,(void**) &status) != 0){ perror("pthread_join"); exit(1); } return 0; }
0
#include <pthread.h> double intervalWidth, mypi = 0.0; int *MyIntervals; int MyRank, Numprocs, Root = 0, MyCount = 0; pthread_mutex_t mypi_mutex = PTHREAD_MUTEX_INITIALIZER; void * MyPartOfCalc(int myID) { int myInterval; double myIntervalMidPoint; double myArea = 0.0, result; myIntervalMidPoint = ((double) MyIntervals[myID] - 0.5) * intervalWidth; myArea += (4.0 / (1.0 + myIntervalMidPoint * myIntervalMidPoint)); result = myArea * intervalWidth; pthread_mutex_lock(&mypi_mutex); mypi += result; pthread_mutex_unlock(&mypi_mutex); } double func(double x) { return (4.0 / (1.0 + x * x)); } int main(int argc, char *argv[]) { int NoInterval, interval, i; double pi, sum, h, x; double PI25DT = 3.141592653589793238462643; pthread_t *threads; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &Numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &MyRank); if (MyRank == Root) { printf("\\nEnter the number of intervals : "); scanf("%d", &NoInterval); } MPI_Bcast(&NoInterval, 1, MPI_INT, 0, MPI_COMM_WORLD); if (NoInterval <= 0) { if (MyRank == Root) printf("Invalid Value for Number of Intervals .....\\n"); MPI_Finalize(); exit(-1); } h = 1.0 / (double) NoInterval; intervalWidth = h; MyCount = 0; for (interval = MyRank + 1; interval <= NoInterval; interval += Numprocs) MyCount++; MyIntervals = (int *) malloc(sizeof(int) * MyCount); for (i = 0, interval = MyRank + 1; interval <= NoInterval; i++, interval += Numprocs) MyIntervals[i] = interval; threads = (pthread_t *) malloc(sizeof(pthread_t) * MyCount); for (interval = 0; interval < MyCount; interval++) pthread_create(&threads[interval], 0, (void *(*) (void *)) MyPartOfCalc, (void *) interval); for (interval = 0; interval < MyCount; interval++) pthread_join(threads[interval], 0); MPI_Reduce(&mypi, &pi, 1, MPI_DOUBLE, MPI_SUM, Root, MPI_COMM_WORLD); if (MyRank == Root) { printf("pi is approximately %.16f, Error is %.16f\\n", pi, fabs(pi - PI25DT)); } MPI_Finalize(); }
1
#include <pthread.h> int num = 0; pthread_mutex_t mutex; void* function1() { printf("Hello from function 1!\\n"); for (size_t i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); num++; pthread_mutex_unlock(&mutex); } return 0; } void* function2() { printf("Hello from function 2!\\n"); for (size_t i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); num--; pthread_mutex_unlock(&mutex); } return 0; } int main() { pthread_mutex_init(&mutex, 0); pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, function1, 0); pthread_create(&thread2, 0, function2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&mutex); printf("Hello from main!\\n"); printf("Value of num: %d\\n", num); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t mainThreadReady; pthread_cond_t childThreadReady; void *new_start_routine( void * arg ) { for (int i = 0; i < 10; i++) { if (i != 10 - 1) pthread_mutex_lock(&mutex); printf("CHILD\\n"); pthread_cond_signal(&childThreadReady); if (i != 10 - 1) { pthread_cond_wait(&mainThreadReady,&mutex); } else { pthread_mutex_unlock(&mutex); } } return 0; } int main( int argc, char **argv ) { pthread_t thread; pthread_mutexattr_t mutex_attr; if (0 != pthread_mutexattr_init(&mutex_attr)) { perror("Could not init mutex attributes\\n"); return 1; } if (0 != pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_ERRORCHECK)) { perror("Could not set mutex attributes type\\n"); return 1; } if (0 != pthread_mutex_init(&mutex,&mutex_attr)) { perror("Could not create mutex\\n"); return 1; } if (0 != pthread_cond_init(&mainThreadReady, 0)) { perror("Could not create condition for mutex\\n"); return 1; } if (0 != pthread_cond_init(&childThreadReady, 0)) { perror("Could not create condition for mutex\\n"); return 1; } if (0 != pthread_create(&thread, 0, new_start_routine, 0)) { perror("Could not create routine\\n"); return 1; } for (int i = 0; i < 10; i++) { if (i != 10 - 1) pthread_mutex_lock(&mutex); printf("PARENT\\n"); pthread_cond_signal(&mainThreadReady); if (i != 10 - 1) { pthread_cond_wait(&childThreadReady, &mutex); } else { pthread_mutex_unlock(&mutex); } } if (0 != pthread_join(thread,0)) { perror("Could not join the routine\\n"); return 1; } if (0 != pthread_cond_destroy(&mainThreadReady)) { perror("Could not destroy condition for mutex\\n"); return 1; } if (0 != pthread_cond_destroy(&childThreadReady)) { perror("Could not create condition for mutex\\n"); return 1; } if (0 != pthread_mutex_destroy(&mutex)) { perror("Could not destroy mutex\\n"); return 1; } if (0 != pthread_mutexattr_destroy(&mutex_attr)) { perror("Could not destroy mutex attributes\\n"); return 1; } return 0; }
1
#include <pthread.h> void *func(int n); pthread_t philosopher[15]; pthread_mutex_t chopstick[15]; int N; int main() { int i,k; void *exit_status; printf("\\nenter the no of philosohers :"); scanf("%d",&N); for(i=0;i<N;i++) { k=pthread_mutex_init(&chopstick[i],0); if(k==-1) { printf("\\nmutex failed :)"); exit(1); } } for(i=0;i<N;i++) { k=pthread_create(&philosopher[i],0,(void *)func,(int *)i); if(k!=0) { printf("\\nthread creation failed :"); exit(1); } } for(i=0;i<N;i++) { k=pthread_join(philosopher[i],&exit_status); if(k!=0) { printf("\\nmutex is still running"); exit(1); } } for(i=0;i<N;i++) { k=pthread_mutex_destroy(&chopstick[i]); if(k!=0) { printf("\\nthread destroy failed :"); exit(1); } } return 0; } void *func(int n) { printf("\\nphilosopher %d is thinking ",n+1); pthread_mutex_lock(&chopstick[n]); pthread_mutex_lock(&chopstick[(n+1)%N]); printf("\\nphilosopher %d is eating ",n+1); sleep(3); printf("\\nphilosopher %d has finished eating ",n+1); pthread_mutex_unlock(&chopstick[n]); pthread_mutex_unlock(&chopstick[(n+1)%N]); }
0
#include <pthread.h> void *hilo1(void *p); void *hilo2(void *p); int acabar; char cadena[50]; pthread_mutex_t muti = PTHREAD_MUTEX_INITIALIZER; int main(void) { pthread_t th1; pthread_t th2; int i; int res; void *result; printf("main: Comenzando la primera prueba, sin mutex\\n"); for(i=0; i<50; i++) cadena[i] = '\\0'; acabar = 0; res = pthread_create(&th1, 0, hilo1, 0); res = pthread_create(&th2, 0, hilo2, (void *)0); pthread_join(th1, &result); acabar = 1; pthread_join(th2, &result); printf("main: Comenzando la segunda prueba, con mutex\\n"); for(i=0; i<50; i++) cadena[i] = '\\0'; res = pthread_create(&th1, 0, hilo1, 0); res = pthread_create(&th2, 0, hilo2, (void *)1); pthread_join(th1, &result); acabar = 1; pthread_join(th2, &result); printf("Final del programa\\n"); } void *hilo1(void *arg) { int cnt = 10000000; char *msg1 = "ABCDEF"; char aux[50]; int nf; struct timespec tim = {0, 1000000L}; nf = 0; while(cnt--) { pthread_mutex_lock(&muti); strcpy(cadena, msg1); strcpy(aux, cadena); pthread_mutex_unlock(&muti); if(strcmp(aux, msg1) != 0) { printf("hilo1: Error; cadena encontrada: %s\\n", aux); nf++; } } printf("hilo1: %d fallos de %d iteraciones.\\n", nf, 10000000); return 0; } void *hilo2(void *arg) { char *msg1 = "hilo2 estuvo aqui"; struct timespec tim = {0, 20000000L}; while(!acabar) { if((int)arg) pthread_mutex_lock(&muti); strcpy(cadena, msg1); if((int)arg) pthread_mutex_unlock(&muti); nanosleep(&tim, 0); } }
1
#include <pthread.h> struct thread_info { pthread_t thread_id; int *forks; pthread_mutex_t *forkMutexs; int philoId; }; int forks[4] = {0,1,2,3}; pthread_mutex_t forkMutexs[4] = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER, PTHREAD_MUTEX_INITIALIZER }; static void *philo(void *arg) { struct thread_info *myInfo = arg; int philoId = myInfo->philoId; while(1) { int firstIndex, secondIndex; firstIndex = (((philoId) > (myMod(philoId-1,4))) ? (philoId) : (myMod(philoId-1,4))); pthread_mutex_lock(&forkMutexs[firstIndex]); if (firstIndex == philoId) { secondIndex = myMod(philoId-1,4); } else { secondIndex = philoId; } pthread_mutex_lock(&forkMutexs[secondIndex]); printf("Philosopher %d eating with %d and %d\\n", philoId, firstIndex, secondIndex); sleep(2); pthread_mutex_unlock(&forkMutexs[secondIndex]); pthread_mutex_unlock(&forkMutexs[firstIndex]); } pthread_exit(0); } int main() { printf("\\n\\n%d\\n\\n", -7%4); printf("Main thread id: %d\\n", (int)pthread_self()); struct thread_info thread_info_p0 = {.forks = forks, .forkMutexs = forkMutexs, .philoId = 0}; struct thread_info thread_info_p1 = {.forks = forks, .forkMutexs = forkMutexs, .philoId = 1}; struct thread_info thread_info_p2 = {.forks = forks, .forkMutexs = forkMutexs, .philoId = 2}; struct thread_info thread_info_p3 = {.forks = forks, .forkMutexs = forkMutexs, .philoId = 3}; int returnValP0 = pthread_create(&thread_info_p0.thread_id, 0, &philo, &thread_info_p0); int returnValP = pthread_create(&thread_info_p1.thread_id, 0, &philo, &thread_info_p1); int returnValP2 = pthread_create(&thread_info_p2.thread_id, 0, &philo, &thread_info_p2); int returnValP3 = pthread_create(&thread_info_p3.thread_id, 0, &philo, &thread_info_p3); while(1) {} } int myMod(int a, int b) { int ret = a % b; if (ret < 0) { return ret+b; } else { return ret; } }
0
#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/num_threads/pagea", 5, 4, 15, fetch, edge); assert(rc == 0); return compareOutput(buffer, fill, "/u/c/s/cs537-1/ta/tests/4a/tests/files/output/basic_test.out"); }
1
#include <pthread.h> pthread_attr_t attr=PTHREAD_INITIALZER; pthread_cond_t even,odd; pthread_mutex_t lock; int i=0; void func_attributes(void ) { pthread_attr_setdetachstate(&attr,PTHREAD_JOINABLE); pthread_cond_init(&even); pthread_cond_init(&odd); pthread_mutex_init(&lock,0); } void even(void* arg) { while(i<10) { pthread_mutex_lock(&lock); pthread_cond_wait(&even,&lock); printf("even_i:%d\\n",i); i++; pthread_cond_signal(&odd); pthread_mutex_unlock(&lock); } } void odd(void* arg) { pthread_cond_signal(&even); while(i<10) { pthread_mutex_lock(&lock); pthread_cond_wait(&odd,&lock); printf("odd_i:%d\\n",i); i++; pthread_cond_signal(&even); pthread_mutex_unlock(&lock); } } int main() { pthread_t even_thid,odd_thid; printf("%s_Thread_begins\\n",__func__); func_attributes(); pthread_create(&even_thid,&attr,even,0); pthread_create(&odd_thid,&attr,odd,0); pthread_join(even_thid,0); pthread_join(odd_thid,0); printf("%s_Thread_ends\\n",__func__); return 0; }
0
#include <pthread.h> void accueil() { int choix; printf("Tripote et Mascagne, bonjour : \\n \\n"); printf("Que pouvons nous faire pour vous : \\n"); printf(" 1: Des vis \\n"); printf(" 2: Des étagères \\n"); printf(" 3: Des chaises \\n"); printf(" 4: Des armoires \\n"); printf(" 5: Des pergolas \\n"); printf(" 6: Des jolis petits chalets à Courchevel \\n"); printf(" 7: Des modules lunaires \\n"); printf(" 8: Des produits encore jamais vu \\n"); printf(" 0: Vous laissez partir ... \\n"); scanf("%d",&choix); while ((choix<0)||(choix>8)) { printf("Malgrè l'étendu de nos domaines d'applications nous ne pouvons satisfaire votre demande, veuillez resaisir une réponse : \\n"); printf("Que pouvons nous faire pour vous : \\n"); printf(" 1: Des vis \\n"); printf(" 2: Des étagères \\n"); printf(" 3: Des chaises \\n"); printf(" 4: Des armoires \\n"); printf(" 5: Des pergolas \\n"); printf(" 6: Des jolis petits chalets à Courchevel \\n"); printf(" 7: Des modules lunaires \\n"); printf(" 8: Des produits encore jamais vu \\n"); printf(" 0: Vous laissez partir ... \\n"); choix=0; scanf("%d",&choix); } switch(choix) { case(1):nbPostes=2;break; case(2):nbPostes=8;break; case(3):nbPostes=15;break; case(4):nbPostes=35;break; case(5):nbPostes=100;break; case(6):nbPostes=300;break; case(7):nbPostes=800;break; case(8):printf("Combien de postes nécessite votre produit ? \\n"); scanf("%d",&nbPostes);break; case(0):printf("ben aurevoir alors \\n");exit(0);break; } printf("Combien voulez-vous de pièces ? \\n"); scanf("%d",&nbPieces); nbPiecesProduites=0; } void traitant(int num) { printf("\\nLiberation des ressources..\\n"); for(num=0;num<nbPostes+1;num++) { sem_destroy(&panneauTicket[num]); sem_destroy(&zoneCaissePleine[num]); sem_destroy(&zoneCaisseVide[num]); } free(tid); free(tid_attr); free(panneauTicket); free(zoneCaissePleine); free(zoneCaisseVide); raise(SIGSTOP); } void* creationThread(void* ID) { int i,val,timeOfProduction; i=(int)ID; srand(time(0)); timeOfProduction=rand()%5; if (i==0) { pthread_mutex_lock(&mutex); sem_getvalue(&zoneCaissePleine[i+1],&val); while((nbPiecesProduites<nbPieces) || (val<=2)) { pthread_mutex_unlock(&mutex); premierPoste(i,timeOfProduction); sem_getvalue(&panneauTicket[i],&val); } } else if (i==nbPostes-1) { sem_getvalue(&panneauTicket[i],&val); while(val>0) { dernierPoste(i,timeOfProduction); sem_getvalue(&panneauTicket[i],&val); } } else { pthread_mutex_lock(&mutex); sem_getvalue(&zoneCaissePleine[i+1],&val); while((nbPiecesProduites<nbPieces) || (val<=2)) { pthread_mutex_unlock(&mutex); posteDeTravail(i,timeOfProduction); sem_getvalue(&panneauTicket[i],&val); } } } void posteDeTravail(int ID,int timeOfProduction) { ("poste %d: j'attends le ticket\\n", ID); sem_wait(&panneauTicket[ID]); printf("oui\\nLe poste %d prend une caisse pleine et une vide \\n",ID); sem_wait(&zoneCaissePleine[ID-1]); sem_wait(&zoneCaisseVide[ID]); sem_post(&panneauTicket[ID-1]); printf("le poste %d prepare une piece...\\n", ID); sleep(timeOfProduction); printf("Le poste %d a termine \\n",ID); sem_post(&zoneCaissePleine[ID]); sem_post(&zoneCaisseVide[ID-1]); } void premierPoste(int ID, int timeOfProduction) { sem_wait(&panneauTicket[ID]); printf("Le premier poste (%d) prend une caisse vide à remplir avec la matiere premiere\\n",ID); sem_wait(&zoneCaisseVide[ID]); printf("le premier poste (%d) prepare une piece...\\n", ID); sleep(timeOfProduction); sem_post(&zoneCaissePleine[ID]); printf("Le poste %d a termine\\n",ID); } void dernierPoste(int ID, int timeOfProduction) { sem_wait(&panneauTicket[ID]); printf("le poste %d a des pieces deja pretes, il envoie au poste aval\\n", ID); sem_wait(&zoneCaissePleine[ID-1]); sem_post(&panneauTicket[ID-1]); printf("Le poste %d a termine, le %d eme produit est fini. \\n",ID, nbPiecesProduites+1); pthread_mutex_lock(&mutex); nbPiecesProduites++; pthread_mutex_unlock(&mutex); sem_post(&zoneCaisseVide[ID-1]); if(nbPieces-nbPiecesProduites==0) { sem_post(&fin); } }
1
#include <pthread.h> const int capacity = 100; const int round_max = 50000; int capacity; int size; item_t* space; pthread_mutex_t lock; pthread_cond_t some_space; pthread_cond_t some_items; } storage_t; void* produce(void* param) { storage_t* storage = (storage_t*) param; int round = 0; int notification = 0; while (round < round_max) { ++round; printf("P %d:%d: S\\n", round, notification); int error; item_t product = random(); printf("P %d:%d: %ld\\n", round, notification, product); printf("P %d:%d: L...\\n", round, notification); error = pthread_mutex_lock(&storage->lock); assert(error == 0); printf("P %d:%d: L\\n", round, notification); int put = 0; while (!put) { if (storage->size < storage->capacity) { *(storage->space + storage->size) = product; ++storage->size; if (storage->size == storage->capacity) { pthread_cond_signal(&storage->some_items); ++notification; printf("P %d:%d: consumer notified\\n", round, notification); } pthread_mutex_unlock(&storage->lock); printf("P %d:%d: notifying U\\n", round, notification); put = 1; } else { printf("P %d:%d: space L...\\n", round, notification); pthread_cond_wait(&storage->some_space, &storage->lock); printf("P %d:%d: space L\\n", round, notification); } } } pthread_mutex_lock(&storage->lock); pthread_cond_signal(&storage->some_items); pthread_mutex_unlock(&storage->lock); ++notification; printf("P %d:%d: completed\\n", round, notification); } void* consume(void* param) { storage_t* storage = (storage_t*) param; int round = 0; int notification = 0; while (round < round_max) { ++round; printf("C %d:%d: S\\n", round, notification); int error; item_t product; printf("C %d:%d: L...\\n", round, notification); error = pthread_mutex_lock(&storage->lock); assert(error == 0); printf("C %d:%d: L\\n", round, notification); int get = 0; while (!get) { if (storage->size > 0) { --storage->size; product = *(storage->space + storage->size); if (storage->size == 0) { pthread_cond_signal(&storage->some_space); ++notification; printf("C %d:%d: notifying U\\n", round, notification); } pthread_mutex_unlock(&storage->lock); get = 1; } else { printf("C %d:%d: items L...\\n", round, notification); pthread_cond_wait(&storage->some_items, &storage->lock); printf("C %d:%d: items L\\n", round, notification); } } printf("C %d:%d: %ld\\n", round, notification, product); } pthread_mutex_lock(&storage->lock); pthread_cond_signal(&storage->some_space); pthread_mutex_unlock(&storage->lock); ++notification; printf("C %d:%d: completed\\n", round, notification); } int main(int argc, char** argv) { storage_t storage; pthread_t producer; pthread_t consumer; storage.capacity = capacity; storage.size = 0; storage.space = malloc(sizeof(item_t) * capacity); pthread_mutex_init(&storage.lock, 0); pthread_cond_init(&storage.some_space, 0); pthread_cond_init(&storage.some_items, 0); pthread_create(&producer, 0, produce, &storage); pthread_create(&consumer, 0, consume, &storage); printf("Main thread waiting for producer...\\n"); pthread_join(producer, 0); printf("Main thread waiting for consumer...\\n"); pthread_join(consumer, 0); printf("Main thread exit\\n"); }
0
#include <pthread.h> int g = 0; pthread_mutex_t mutexsum; void *myThreadFun(void *vargp) { int i = (int)vargp; pthread_mutex_lock (&mutexsum); printf("%i Global: %d\\n", i, ++g); pthread_mutex_unlock (&mutexsum); } int threadCount(int num_threads) { int i; pthread_t tid; pthread_t threads[num_threads]; pthread_attr_t attr; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < num_threads; i++) pthread_create(&threads[i], &attr, myThreadFun, (void *)i); pthread_attr_destroy(&attr); for (i = 0; i < num_threads; i++) pthread_join(threads[i],0); pthread_mutex_destroy(&mutexsum); return g; pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; { int lb; int ub; int arr[100]; }param; int part(int a[],int lb,int ub) { int c,up=lb,down=ub; int x=a[lb]; while(up<down) { while(a[up]<=x && up<=down) up++; while(a[down]>x) down--; if(up<down) { c=a[up]; a[up]=a[down]; a[down]=c; } } a[lb]=a[down]; a[down]=x; return down; } void *binary(void * s) { int x; printf("Enter number to search"); scanf("%d",&x); param *p=(param*)s; if(p->lb<p->ub) return; param n1, n2; int mid = (p->lb+p->ub)/2; pthread_t tid5, tid6; if(p->arr[mid]==x) printf("Found\\n"); n1.lb = p->lb; n1.ub = mid; n2.lb = mid+1; n2.ub = p->ub; pthread_create(&tid5,0,binary,&n1); pthread_create(&tid6,0,binary,&n2); pthread_join(tid5,0); pthread_join(tid6,0); } void *quick(void *p) { pthread_mutex_lock(&mutex); param *s=(param*)p; param n1, n2; int k; if(s->lb>=s->ub) { return; } pthread_t tid1, tid2,tid3; k=part(s->arr,s->lb,s->ub); n1.lb = s->lb; n1.ub = k-1; n2.lb = k+1; n2.ub = s->ub; pthread_create(&tid1,0,quick,&n1); pthread_create(&tid2,0,quick,&n2); pthread_join(tid1,0); pthread_join(tid2,0); pthread_mutex_unlock(&mutex); } int main() { int i; param s; s.lb=0; printf("Enter the matrix size"); scanf("%d",&(s.ub)); for(i=0;i<s.ub;i++) { printf("Enter value="); scanf("%d",&(s.arr[i])); } printf("Before sorting\\n"); for(i=0;i<s.ub;i++) { printf("%d ",s.arr[i]); } pthread_t tid; pthread_create(&tid,0,quick,&s); pthread_join(tid,0); printf("\\nAfter sorting\\n"); for(i=0;i<s.ub;i++) printf("%d ",s.arr[i]); return 0; }
0
#include <pthread.h> pthread_mutex_t kran; pthread_mutex_t kufle; int l_kl, l_kf, l_kr; void * watek_klient (void * arg); int kufle_pobrane = 0; int main(){ pthread_t *tab_klient; int *tab_klient_id; int i; printf("\\nLiczba klientow: "); scanf("%d", &l_kl); printf("%d\\n",l_kl); printf("\\nLiczba kufli: "); scanf("%d", &l_kf); printf("%d\\n",l_kf); l_kr = 1; printf("Liczba kranow:\\n%d\\n",l_kr); tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t)); tab_klient_id = (int *) malloc(l_kl*sizeof(int)); for(i=0;i<l_kl;i++) tab_klient_id[i]=i; printf("Otwieramy pub (simple)!\\n"); printf("Liczba wolnych kufli %d\\n", l_kf); for(i=0;i<l_kl;i++){ pthread_create(&tab_klient[i], 0, watek_klient, &tab_klient_id[i]); } for(i=0;i<l_kl;i++){ pthread_join( tab_klient[i], 0); } printf("Zamykamy pub!\\n"); } void * watek_klient (void * arg_wsk){ int moj_id = * ((int *)arg_wsk); int i, j, result=0; int ile_musze_wypic = 2; printf("Klient %d, wchodzę do pubu\\n", moj_id); for(i=0; i<ile_musze_wypic; ){ pthread_mutex_lock(&kufle); if(kufle_pobrane<l_kf){ printf("Klient %d, wybieram kufel\\n", moj_id); kufle_pobrane++; result=1; } else{ result=0; } pthread_mutex_unlock(&kufle); j=0; if(result==1){ pthread_mutex_lock(&kran); printf("Klient %d, nalewam z kranu %d\\n", moj_id, j); usleep(300); pthread_mutex_unlock(&kran); printf("Klient %d, pije\\n", moj_id); nanosleep((struct timespec[]){{0, 500000000L}}, 0); pthread_mutex_lock(&kufle); printf("Klient %d, odkladam kufel\\n", moj_id); kufle_pobrane--; pthread_mutex_unlock(&kufle); i++; } } printf("Klient %d, wychodzę z pubu\\n", moj_id); return(0); }
1
#include <pthread.h> double start_time; double end_time; double cur_time; static enum { SIM_START, SIM_INITIALIZED, SIM_IN_PROGRESS, SIM_TERMINATED, } state; static struct cal *cal; static bool new_element_added; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; size_t get_head(void) { return cal->idx; } void del_head(void) { do { pthread_mutex_lock(&lock); if (cal) { struct cal *__tmp = cal; cal = cal->next; free(__tmp); } pthread_mutex_unlock(&lock); } while (0); } static bool process_compare(size_t new, size_t old) { if (isgreater(process_list[new].atime, process_list[old].atime) || (!islessgreater(process_list[new].atime, process_list[old].atime) && process_list[new].prio <= process_list[old].prio)) return 1; return 0; } int add_elem(size_t idx) { pthread_mutex_lock(&lock); new_element_added = 1; struct cal *new = xcalloc(1, sizeof(*new)); new->idx = idx; struct cal *prev = 0; struct cal *act = cal; while (act != 0 && process_compare(new->idx, act->idx)) { prev = act; act = act->next; if (act && new->idx == act->idx) act = act->next; } if (prev == 0) { new->next = act; cal = new; } else { prev->next = new; new->next = act; } pthread_mutex_unlock(&lock); return 0; } int Init(double t0, double t1) { if (t0 > t1 || t0 < 0.0 || t1 < 0.0) { simerr = GLOB_INVAL; return -1; } start_time = cur_time = t0; end_time = t1; state = SIM_INITIALIZED; return 0; } int Run(void) { if (state != SIM_INITIALIZED) { simerr = GLOB_NOTINIT; return -1; } struct cal *cp = cal; puts("Initial state of the calendar"); printf("top ->\\n"); for (cp = cal; cp != 0; prefetch(cp->next), cp = cp->next) { printf(" [ idx:%d atime:%g prio:%d state:%c ]\\n", cp->idx, process_list[cp->idx].atime, process_list[cp->idx].prio, TASK_STATE_TO_CHAR_STR[process_list[cp->idx].state]); } fputc_unlocked('\\n', stdout); puts("<< START OF SIMULATION >>"); cp = cal; while (cp) { int res; printf(" [ idx:%d atime:%f prio:%d state:%c ]\\n", cp->idx, process_list[cp->idx].atime, process_list[cp->idx].prio, TASK_STATE_TO_CHAR_STR[process_list[cp->idx].state]); res = pthread_mutex_lock(&process_list[cp->idx].lock); if (unlikely(res)) printf("pthread_mutex_lock: %s\\n", strerror(res)); cur_time = process_list[cp->idx].atime; if (cur_time >= end_time) goto out; if (process_list[cp->idx].state == TASK_WAKING) {; process_list[cp->idx].state = TASK_RUNNING; res = pthread_create(&process_list[cp->idx].th, 0, process_list[cp->idx].behaviour, 0); if (unlikely(res)) printf("pthread_create: %s\\n", strerror(res)); } else if (process_list[cp->idx].state == TASK_STOPPED) { process_list[cp->idx].state = TASK_RUNNING; res = pthread_cond_signal(&process_list[cp->idx].cond); if (unlikely(res)) printf("pthread_cond_signal: %s\\n", strerror(res)); } else if (process_list[cp->idx].state == TASK_DEAD) goto out; do pthread_cond_wait(&process_list[cp->idx].cond, &process_list[cp->idx].lock); while (0 && process_list[cp->idx].state == TASK_RUNNING); if (process_list[cp->idx].state == TASK_DEAD) { res = pthread_join(process_list[cp->idx].th, 0); if (unlikely(res)) printf("pthread_join: %s\\n", strerror(res)); } res = pthread_mutex_unlock(&process_list[cp->idx].lock); if (unlikely(res)) printf("pthread_mutex_unlock: %s\\n", strerror(res)); if (process_list[cp->idx].state == TASK_DEAD) destroy_process(cp->idx); if (new_element_added || process_list[cp->idx].state == TASK_DEAD) { cp = cp->next; do { pthread_mutex_lock(&lock); if (cal) { struct cal *__tmp = cal; cal = cal->next; free(__tmp); } pthread_mutex_unlock(&lock); } while (0); } } out: puts("<< END OF SIMULATION >>\\n"); return 0; }
0
#include <pthread.h> int q[4]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 4) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 4); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[7]; int sorted[7]; void producer () { int i, idx; for (i = 0; i < 7; i++) { idx = findmaxidx (source, 7); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 7; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 7); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 7; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
1
#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)); { 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)); { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr) != (-2))) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> struct kufle { pthread_mutex_t mut_kuff; int * tab_kufli; int l_kf; } kuf; pthread_mutex_t mut_kran; void * watek_klient (void * arg_wsk){ int moj_id = * ((int *)arg_wsk); int a, i, j, kufel, result; int wybralem = 0; a = 0; int ile_musze_wypic = 2; printf("Klient %d, wchodzę do pubu\\n", moj_id); for(i=0; i<ile_musze_wypic; i++){ printf("Klient %d, szuka kufla\\n", moj_id); while(1) { pthread_mutex_lock(&kuf.mut_kuff); for(a = 0; a < kuf.l_kf;a++){ if(kuf.tab_kufli[a] == 0) { kuf.tab_kufli[a] = 1; kufel = a; printf("Klient %d, wybrał kufel %d\\n",moj_id,a); wybralem = 1; break; } } pthread_mutex_unlock(&kuf.mut_kuff); if(wybralem) { break; } } j=0; printf("Klient %d, nalewam z kranu %d\\n", moj_id, j); pthread_mutex_lock(&mut_kran); usleep(300); pthread_mutex_unlock(&mut_kran); printf("Klient %d, pije\\n", moj_id); nanosleep((struct timespec[]){{0, 500000000L}}, 0); printf("Klient %d, odkladam kufel\\n", moj_id); kuf.tab_kufli[kufel] = 0; } printf("Klient %d,!wychodzi™ z pubu\\n", moj_id); return(0); } main(){ pthread_t *tab_klient; int *tab_klient_id; int *tab_kufli; int l_kl, l_kf, l_kr, i; printf("\\nLiczba klientow: "); scanf("%d", &l_kl); printf("\\nLiczba kufli: "); scanf("%d", &l_kf); l_kr = 1; tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t)); tab_klient_id = (int *) malloc(l_kl*sizeof(int)); for(i=0;i<l_kl;i++) { tab_klient_id[i]=i; } kuf.tab_kufli = (int *) malloc(l_kf * sizeof(int)); kuf.l_kf = l_kf; pthread_mutex_init(&kuf.mut_kuff, 0); for(i=0;i<l_kf;i++) { kuf.tab_kufli[i] = 0; } printf("\\nOtwieramy pub (simple)!\\n"); pthread_mutex_init(&mut_kran, 0); printf("\\nLiczba wolnych kufli %d\\n", l_kf); for(i=0;i<l_kl;i++) { pthread_create(&tab_klient[i], 0, watek_klient, &tab_klient_id[i]); } for(i=0;i<l_kl;i++) { pthread_join( tab_klient[i], 0); } printf("\\nZamykamy pub!\\n"); }
1
#include <pthread.h> int estado [(5)]; pthread_mutex_t mutex; pthread_mutex_t mux_filo [(5)]; pthread_t jantar[(5)]; void * filosofo ( void * param ); void pegar_hashi ( int id_filosofo ); void devolver_hashi ( int id_filosofo ); void intencao ( int id_filosofo ); void comer ( int id_filosofo ); void pensar ( int id_filosofo ); void * filosofo ( void * vparam ) { int * id = (int *) (vparam); printf("Filosofo %d foi criado com sucesso\\n", *(id) ); while ( 1 ) { pensar( *(id) ); pegar_hashi( *(id) ); comer( *(id) ); devolver_hashi( *(id) ); } pthread_exit( (void*) 0 ); } void pegar_hashi ( int id_filosofo ) { pthread_mutex_lock( &(mutex) ); printf("Filosofo %d esta faminto\\n", id_filosofo); estado[ id_filosofo ] = (1); intencao( id_filosofo ); pthread_mutex_unlock( &(mutex) ); pthread_mutex_lock( &(mux_filo[id_filosofo]) ); } void devolver_hashi ( int id_filosofo ) { pthread_mutex_lock ( &(mutex) ); printf("Filosofo %d esta pensando\\n", id_filosofo); estado[ id_filosofo ] = (0); intencao( (id_filosofo + (5) - 1) % (5) ); intencao( (id_filosofo + 1) % (5) ); pthread_mutex_unlock ( &(mutex) ); } void intencao ( int id_filosofo ) { printf("Filosofo %d esta com intencao de comer\\n", id_filosofo); if( (estado[id_filosofo] == (1)) && (estado[(id_filosofo + (5) - 1) % (5)] != (2)) && (estado[(id_filosofo + 1) % (5)] != (2) ) ) { printf("Filosofo %d ganhou a vez de comer\\n", id_filosofo); estado[ id_filosofo ] = (2); pthread_mutex_unlock( &(mux_filo[id_filosofo]) ); } } void pensar ( int id_filosofo ) { int r = (rand() % 10 + 1); printf("Filosofo %d pensa por %d segundos\\n", id_filosofo, r ); sleep( r ); } void comer ( int id_filosofo ) { int r = (rand() % 10 + 1); printf("Filosofo %d come por %d segundos\\n", id_filosofo, r); sleep( r ); } int main ( void ) { int cont; int status; pthread_mutex_init( &(mutex), 0); for( cont = 0 ; cont < (5) ; cont++ ) { pthread_mutex_init( &(mux_filo[cont]), 0 ); } for( cont = 0 ; cont < (5) ; cont++ ) { status = pthread_create( &(jantar[cont]), 0, filosofo, (void *) &(cont) ); if ( status ) { printf("Erro criando thread %d, retornou codigo %d\\n", cont, status ); return 1; } } pthread_mutex_destroy( &(mutex) ); for( cont = 0 ; cont < (5) ; cont++ ) { pthread_mutex_destroy( &(mux_filo[cont]) ); } pthread_exit( 0 ); return 0; }
0
#include <pthread.h> int total = 0; pthread_mutex_t mutexTotal = PTHREAD_MUTEX_INITIALIZER; pthread_t * hilos; void * suma (void * arg); clock_t begin, end; double time_spent; int fragment; int * numberArray; int inicio; int fin; }info; int main(int argc, char const *argv[]) { FILE *myFile; int numberOfElements; myFile = fopen("archivo.txt", "r"); int i; fscanf(myFile, "%d", &numberOfElements); printf("Hay %d elementos\\n", numberOfElements); numberArray = (int *)malloc(numberOfElements * sizeof(int)); for (i = 0; i < numberOfElements; i++) { fscanf(myFile, "%d", &numberArray[i]); } hilos = (pthread_t *)malloc(2 * sizeof(pthread_t)); fragment = numberOfElements/2; int actual = 0; int j; pthread_t * auxHilos = hilos; pthread_t * finHilos = hilos + 2; begin = clock(); for(; auxHilos<finHilos; ++auxHilos){ pthread_create(auxHilos,0,suma,(void *)actual); actual += fragment; } auxHilos = hilos; finHilos = hilos + 2; for (;auxHilos<finHilos;++auxHilos){ pthread_join(*auxHilos,0); } end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("El total es %d con un tiempo de %f\\n", total,time_spent); free(hilos); free(numberArray); return 0; } void * suma (void * arg){ int inicio = (int) arg; int totalLocal = 0; int * auxNumeros = numberArray + inicio; int * finNumeros = numberArray + (inicio + fragment); for (;auxNumeros<finNumeros; ++auxNumeros){ totalLocal += *auxNumeros; } pthread_mutex_lock(&mutexTotal); total += totalLocal; pthread_mutex_unlock(&mutexTotal); pthread_exit(0); }
1
#include <pthread.h> void throw_one(); void throw_two(); void determine_round_winner(); void determine_winner(); int* p_one_ptr; int* p_two_ptr; const char *rps[3]; int player_one_score; int player_two_score; pthread_t tid[2]; int choice[2]; int command[2]; pthread_mutex_t lock[2]; pthread_cond_t cond[2]; int num_rounds; int player_one_thread_id; int player_two_thread_id; int main(int argc, char** argv) { num_rounds = atoi(argv[1]); int parent_id = getpid(); pthread_mutex_init(&lock[0], 0); pthread_mutex_init(&lock[1], 0); rps[0] = "Rock"; rps[1] = "Paper"; rps[2] = "Scissors"; player_one_score = 0; player_two_score = 0; pthread_create(&tid[0], 0, throw_one, 0); pthread_create(&tid[1], 0, throw_two, 0); if(getpid() == parent_id) { printf("Child 1 tid: %d\\n", player_one_thread_id); printf("Child 2 tid: %d\\n", player_two_thread_id); printf("Beginning %d Rounds...\\n", num_rounds); printf("Fight\\n"); printf("---------------------------------------\\n"); for(int i=0; i<num_rounds; i++) { printf("Round %d:\\n", i+1); pthread_mutex_lock(&lock[0]); pthread_mutex_lock(&lock[1]); command[0] = 98; command[1] = 98; pthread_cond_signal(&cond[0]); pthread_cond_signal(&cond[1]); while(command[0] == 98 || command[1] == 98){ } pthread_mutex_unlock(&lock[0]); pthread_mutex_unlock(&lock[1]); determine_round_winner(); printf("---------------------------------------\\n"); } pthread_join(tid[0], 0); pthread_join(tid[1], 0); determine_winner(); } return 0; } void throw_one(int signum) { player_one_thread_id = syscall(SYS_gettid); for(int i=0; i<num_rounds; i++) { while(command[0] != 98) { } srand(time(0) * syscall(SYS_gettid) * (i + 100)); choice[0] = rand() % 3 + 1; command[0] = 99; } } void throw_two(int signum) { player_two_thread_id = syscall(SYS_gettid); for(int i=0; i<num_rounds; i++) { while(command[1] != 98) { } srand(time(0) * syscall(SYS_gettid) * (i + 100)); choice[1] = rand() % 3 + 1; command[1] = 99; } } void determine_round_winner() { int player_one_choice = choice[0]; int player_two_choice = choice[1]; bool player_one_win = 0; bool player_two_win = 0; if(player_one_choice != player_two_choice) { if(player_one_choice == 1 && player_two_choice == 2) { player_two_win = 1; } else if(player_one_choice == 1 && player_two_choice == 3) { player_one_win = 1; } else if(player_one_choice == 2 && player_two_choice == 1) { player_one_win = 1; } else if(player_one_choice == 2 && player_two_choice == 3) { player_two_win = 1; } else if(player_one_choice == 3 && player_two_choice == 1) { player_two_win = 1; } else { player_one_win = 1; } } printf("Child 1 throws %s!\\n", rps[player_one_choice - 1]); printf("Child 2 throws %s!\\n", rps[player_two_choice - 1]); if(player_one_win) { printf("Child 1 Wins!\\n"); player_one_score++; } else if(player_two_win) { printf("Child 2 Wins!\\n"); player_two_score++; } else { printf("Draw!\\n"); } } void determine_winner() { printf("---------------------------------------\\n"); printf("Results:\\n"); printf("Child 1: %d\\n", player_one_score); printf("Child 2: %d\\n", player_two_score); if(player_one_score > player_two_score) { printf("Child 1 Wins!\\n"); } else if(player_two_score > player_one_score) { printf("Child 2 Wins!\\n"); } else { printf("Draw!\\n"); } }
0
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number=0,i; void *thread1() { printf("thread1:i'm thread 1\\n"); for(i=0;i<10;i++) { printf("threead1:number=%d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(2); } printf("thread1:主函数在等我完成任务吗?\\n"); pthread_exit(0); } void *thread2() { printf("thread2:i'm thread2\\n"); for(i=0;i<10;i++) { printf("thread2:number=%d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(1); } printf("thread2:主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int tmp; if((tmp=pthread_create(&thread[0],0,thread1,0))!=0) printf("线程1创建失败\\n"); else printf("线程1被创建\\n"); if((tmp=pthread_create(&thread[1],0,thread2,0))!=0) printf("线程2创建失败\\n"); else printf("线程2被创建\\n"); } void thread_wait(void) { if(thread[0]!=0) { pthread_join(thread[0],0); printf("线程1已经结束\\n"); } if(thread[1]!=0) { pthread_join(thread[0],0); printf("线程2已经结束\\n"); } } void main() { pthread_mutex_init(&mut,0); printf("我是主线程,我正在创建线程\\n"); thread_create(); printf("我是主线程,我在等待线程完成任务\\n"); thread_wait(); }
1
#include <pthread.h> int NUMBER_OF_PRODUCTS; pthread_mutex_t lock; void increase_products(int i){ pthread_mutex_lock(&lock); if(NUMBER_OF_PRODUCTS < 10){ NUMBER_OF_PRODUCTS+=1; } else printf("Production limit reached.\\n\\n"); pthread_mutex_unlock(&lock); sleep(rand()%3+1); return ; } void decrease_products(int j){ pthread_mutex_lock(&lock); if(NUMBER_OF_PRODUCTS>0){ sleep(1); NUMBER_OF_PRODUCTS-=1; } else printf("No product available to consume\\n\\n"); pthread_mutex_unlock(&lock); sleep(rand()%3+1); return ; } void *produce(void *var_args){ int pid=(*(int *)var_args); int count=0; while(count++<100) increase_products(pid); return 0; } void *consume(void *var_args){ int cid=(*(int *)var_args); int count=0; while(count++<100) decrease_products(cid); return 0; } int main(){ int num_of_producer; int num_of_consumer; NUMBER_OF_PRODUCTS=0; printf("Enter the number of prodcers and the number of consumers\\n"); scanf("%d",&num_of_producer); scanf("%d",&num_of_consumer); pthread_t A[num_of_consumer]; pthread_t B[num_of_producer]; srand(time(0)); while(pthread_mutex_init(&lock,0) !=0) printf("Mutex lock creation failed,trying again\\n"); int i; int prod_id[num_of_producer]; int cons_id[num_of_consumer]; for(i=0;i<num_of_producer;i++){ prod_id[i]=i+1; } for(i=0;i<num_of_consumer;i++){ cons_id[i]=i+1; } for(i=0;i<num_of_consumer;i++) pthread_create(&A[i],0,consume,(void *)&cons_id[i]); for(i=0;i<num_of_producer;i++) pthread_create(&B[i],0,produce,(void *)&prod_id[i]); for(i=0;i<num_of_consumer;i++) pthread_join(A[i], 0); for(i=0;i<num_of_producer;i++) pthread_join(B[i], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> sem_t semEste; sem_t semOeste; pthread_mutex_t mutexEste; pthread_mutex_t mutexOeste; void* cruzarEste(void*); void* cruzarOeste(void*); int main() { sem_init(&semEste, 0, 0); sem_init(&semOeste, 0, 0); srand((int) time(0)); pthread_t* threads = (pthread_t*) malloc(10 * sizeof(pthread_t)); pthread_t* aux; int i, direccion; for (aux = threads, i = 0; aux < (threads + 10); ++aux, ++i) { direccion = rand() % 2; if (direccion) pthread_create(aux, 0, cruzarOeste, (void*) i); else pthread_create(aux, 0, cruzarEste, (void*) i); } for (aux = threads; aux < (threads + 10); ++aux) { pthread_join(*aux, 0); } sem_destroy(&semEste); sem_destroy(&semOeste); free(threads); return 0; } void* cruzarEste(void* p) { int id = (int) p; sleep(rand() % 15); int valOeste, continuar = 1; while (continuar) { pthread_mutex_lock(&mutexOeste); sem_getvalue(&semOeste, &valOeste); if (!valOeste) { while (pthread_mutex_trylock(&mutexEste)) { pthread_mutex_unlock(&mutexOeste); pthread_mutex_lock(&mutexOeste); } sem_post(&semEste); pthread_mutex_unlock(&mutexEste); continuar = 0; } pthread_mutex_unlock(&mutexOeste); } printf("Babuino %d cruzando hacia el este\\n", id); sleep(3); printf("Babuino %d llegó al este\\n", id); sem_wait(&semEste); pthread_exit(0); } void* cruzarOeste(void* p) { int id = (int) p; sleep(rand() % 15); int valEste, continuar = 1; while (continuar) { pthread_mutex_lock(&mutexEste); sem_getvalue(&semEste, &valEste); if (!valEste) { while (pthread_mutex_trylock(&mutexOeste)) { pthread_mutex_unlock(&mutexEste); pthread_mutex_lock(&mutexEste); } sem_post(&semOeste); pthread_mutex_unlock(&mutexOeste); continuar = 0; } pthread_mutex_unlock(&mutexEste); } printf("Babuino %d cruzando hacia el oeste\\n", id); sleep(3); printf("Babuino %d llegó al oeste\\n", id); sem_wait(&semOeste); pthread_exit(0); }
1
#include <pthread.h> static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t cond_mutex = PTHREAD_MUTEX_INITIALIZER; static void *doexec (void *arg); void init (void) { pthread_t thr; pthread_attr_t thread_attr; if (pthread_attr_init(&thread_attr)) do { fprintf(stderr, "Dying... %s:%d Reason: %s\\n", "cond-signal-test.c", 35, ("pthread_attr_init")); exit(1); } while(0); if (pthread_create(&thr, &thread_attr, doexec, 0)) do { fprintf(stderr, "Dying... %s:%d Reason: %s\\n", "cond-signal-test.c", 38, ("pthread_create\\n")); exit(1); } while(0); } int action = 0; int count = -1; int ready = 0; void dosignal (void) { pthread_mutex_lock (&cond_mutex); pthread_cond_signal(&cond); pthread_mutex_unlock (&cond_mutex); sched_yield(); } static void * doexec (void *arg) { pthread_mutex_lock (&cond_mutex); ready = 1; while (action != 1) { count++; pthread_cond_wait (&cond, &cond_mutex); } pthread_mutex_unlock (&cond_mutex); pthread_detach(pthread_self()); return 0; } int main (int argc, char *argv[]) { int i; init(); while (!ready) usleep(10000); for (i = 0; i < 1000; ++i) dosignal (); pthread_mutex_lock (&cond_mutex); action = 1; pthread_cond_signal(&cond); pthread_mutex_unlock (&cond_mutex); usleep(10000); fprintf(stderr, "%d\\n", count); 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; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = (struct foo*)malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_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(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--fp->f_count == 0) { idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } } void print_foo( struct foo* strf) { printf("\\n"); printf("f_cont = %d \\n", strf->f_count); printf("f_lock = %d \\n", strf->f_lock); printf("f_id = %d \\n", strf->f_id); printf("f_cont = %d \\n", strf->f_count); } int main() { struct foo * strf = foo_alloc(1); print_foo(strf); foo_hold(strf); print_foo(strf); foo_hold(strf); print_foo(strf); foo_rele(strf); print_foo(strf); foo_rele(strf); print_foo(strf); foo_rele(strf); print_foo(strf); sleep(1); int a = 1; foo_rele(strf); print_foo(strf); return 0; }
1
#include <pthread.h> void station_init(struct station *station){ station->waiting_passenger_count=0; station->available_seat_count=0; station->boarded_passenger_count=0; station->max_allowed_passengers=0; station->train_left=0; pthread_mutex_init(&station->station_key, 0); pthread_cond_init(&station->train_arrived, 0); pthread_cond_init(&station->train_loaded, 0); } void station_load_train(struct station *station, int count){ pthread_mutex_lock(&station->station_key); station->train_left=0; station->available_seat_count=count; station->boarded_passenger_count=0; station->max_allowed_passengers=count; pthread_cond_broadcast(&station->train_arrived); if(station->waiting_passenger_count==0||count==0){ station->train_left=1; pthread_mutex_unlock(&station->station_key); return; } while(1){ if((station->waiting_passenger_count==0)||(station->available_seat_count==0)){ station->train_left=1; pthread_mutex_unlock(&station->station_key); return; }else{ pthread_cond_wait(&station->train_loaded, &station->station_key); continue; } } } void station_wait_for_train(struct station *station){ pthread_mutex_lock(&station->station_key); station->waiting_passenger_count+=1; while(1){ if((station->available_seat_count<=0)||(station->train_left==1)){ pthread_cond_wait(&station->train_arrived, &station->station_key); continue; }else{ station->available_seat_count-=1; pthread_mutex_unlock(&station->station_key); return; } } } void station_on_board(struct station *station){ pthread_mutex_lock(&station->station_key); station->boarded_passenger_count+=1; station->waiting_passenger_count-=1; if((station->boarded_passenger_count==station->max_allowed_passengers)||(station->waiting_passenger_count==0)){ station->train_left=1; pthread_cond_signal(&station->train_loaded); } pthread_mutex_unlock(&station->station_key); return; }
0
#include <pthread.h> int use_mutex; pthread_mutex_t mutex; volatile int global = 0; void *compute(void *arg) { int i; for (i = 0; i < 100 * 100 * 100; i++) { if (use_mutex) { pthread_mutex_lock(&mutex); global++; pthread_mutex_unlock(&mutex); } else global++; } return 0; } void multi_thread_test() { int i; pthread_t tids[3]; global = 0; pthread_mutex_init(&mutex, 0); for (i = 0; i < 3; i++) pthread_create(&tids[i], 0, compute, 0); for (i = 0; i < 3; i++) pthread_join(tids[i], 0); printf("global = %d\\n", global); pthread_mutex_destroy(&mutex); } int main() { use_mutex = 0; multi_thread_test(); use_mutex = 1; multi_thread_test(); return 0; }
1
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=47); return 0; } void *thread2() { x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
0
#include <pthread.h> int chop = 5; struct timespec timeout; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lockp = PTHREAD_MUTEX_INITIALIZER; void *pcon(void *num) { int flag = 1; while(1) { flag =(flag ? 0:1); if(!flag) { pthread_mutex_lock(&lock); if(chop > 0) { chop--; printf("person %d is thinking...\\n",(int)num); } pthread_mutex_unlock(&lock); } else { pthread_mutex_lock(&lock); if(pthread_cond_timedwait(&cond, &lock, &timeout) == 0) { if(chop > 0) { printf("person %d begin eat food...\\n", (int)num); sleep(rand()%5); chop++; } } else { pthread_mutex_lock(&lockp); chop++; pthread_mutex_unlock(&lockp); } pthread_mutex_unlock(&lock); pthread_cond_broadcast(&cond); } usleep(100); } } int main(void) { pthread_t tid[5]; int i; timeout.tv_sec =rand()%3+1 ; timeout.tv_nsec = 0; for(i = 0; i< 5; i++) pthread_create(&tid[i], 0, pcon,(void*)i); for(i = 0; i< 5; i++) pthread_join(tid[i], 0); return 0; }
1
#include <pthread.h> int A = 0; int B = 0; pthread_mutex_t lock_A = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_B = PTHREAD_MUTEX_INITIALIZER; void * thread_a(void * para) { int i = 0; srandom(time(0L)); while(i < 100) { i++; usleep(random()%100); pthread_mutex_lock(&lock_A); A += 10; pthread_mutex_lock(&lock_B); B += 20; A += B; pthread_mutex_unlock(&lock_B); A += 30; pthread_mutex_unlock(&lock_A); usleep(random()%100); } printf("THREADA A:%d, B:%d\\n", A, B); return 0L; } void * thread_b(void * para) { int i = 0; srandom(time(0L)); while(i < 100) { i++; usleep(random()%100); pthread_mutex_lock(&lock_B); B += 10; pthread_mutex_lock(&lock_A); A += 20; A += B; pthread_mutex_unlock(&lock_A); B += 30; pthread_mutex_unlock(&lock_B); usleep(random()%100); } printf("THREADB A:%d, B:%d\\n", A, B); return 0L; } int main (int argc, char * argv[]) { pthread_t waiters[2]; int i; pthread_create (&waiters[0], 0, thread_a, 0); pthread_create (&waiters[1], 0, thread_b, 0); for (i = 0; i < 2; i++) { pthread_join (waiters[i], 0); } return 0; }
0
#include <pthread.h> static const unsigned int NUM_PHILOSOPHERS = 5; static const unsigned int NUM_CHOPSTICKS = 5; static int chopsticks[5]; static pthread_mutex_t mutex[5]; static pthread_t philosophers[5]; int isdead(){ int i; for (i = 0; i < NUM_CHOPSTICKS; i++){ if (chopsticks[i] == -1) return 0; else if (chopsticks[i] == chopsticks[(i +1) % 5]) return 0; } if (DEBUG){ printf("chopsticks = {"); for (i = 0; i < NUM_CHOPSTICKS; i++){ printf("%d ", chopsticks[i]); } printf("}\\n"); } return 1; } void* th_main( void* th_main_args ) { int i; for (i = 0; i < NUM_CHOPSTICKS; i++){ chopsticks[i] = -1; } for (i = 0; i < NUM_PHILOSOPHERS; i++){ if (pthread_create(&(philosophers[i]), 0, th_phil, (void*) i) != 0){ fprintf(stderr, "failed to create philosopher thread %d, terminating\\n", i); exit(1); } } while (1){ delay(50000); if (isdead()){ printf("deadlocked...\\n"); break; } printf("philosopher(s) "); for (i = 0; i < NUM_CHOPSTICKS; i++){ if (chopsticks[i] == chopsticks[(i + 1) % 5]) printf("%d, ", i); } printf("are eating\\n"); if (DEBUG){ printf("chopsticks = {"); for (i = 0; i < NUM_CHOPSTICKS; i++){ printf("%d ", chopsticks[i]); } printf("}\\n"); } } for (i = 0; i < NUM_PHILOSOPHERS; i++){ pthread_kill(philosophers[i], 9); } pthread_exit(0); } void* th_phil( void* th_phil_args ) { int id = (int)th_phil_args; while(1){ delay(150000); eat(id); } } void delay( long nanosec ) { struct timespec t_spec; t_spec.tv_sec = 0; t_spec.tv_nsec = nanosec; nanosleep( &t_spec, 0 ); } void eat( int phil_id ) { int left = (phil_id + 1) % 5; if (chopsticks[phil_id] != -1 && chopsticks[phil_id] != phil_id){ return; } pthread_mutex_lock(&(mutex[phil_id])); chopsticks[phil_id] = phil_id; pthread_mutex_unlock(&(mutex[phil_id])); delay(1000); if (chopsticks[left] != -1){ return; } pthread_mutex_lock(&(mutex[left])); chopsticks[left] = phil_id; pthread_mutex_unlock(&(mutex[left])); delay(100000); pthread_mutex_lock(&(mutex[left])); chopsticks[left] = -1; pthread_mutex_unlock(&(mutex[left])); delay(7500); pthread_mutex_lock(&(mutex[phil_id])); chopsticks[phil_id] = -1; pthread_mutex_unlock(&(mutex[phil_id])); }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void multiThreadCopy(char*, char*); void sectionCopy(void**); int main(int argc, char* argv[]) { if (argc < 3) { printf("Expected input and output files as parameters\\n"); return 0; } multiThreadCopy(argv[1], argv[2]); return 0; } void multiThreadCopy(char* src, char* dest) { FILE * srcFile; FILE * destFile; size_t pos = 0; srcFile = fopen(src, "r"); destFile = fopen(dest, "w"); fseek (srcFile, 0, 2); size_t size = ftell(srcFile); fseek(srcFile, 0, 0); void* args[2] = {srcFile, destFile}; for (pos = 0; pos < size; pos += 1000) { pthread_t thread; pthread_mutex_lock(&lock); pthread_create(&thread, 0, (void*)sectionCopy, args); } pthread_mutex_lock(&lock); fclose(srcFile); fclose(destFile); }; void sectionCopy(void* files[]) { FILE * srcFile = files[0]; FILE * destFile = files[1]; char currSection[1000]; int charsRead = fread(currSection, sizeof(char), 1000, srcFile); fwrite(currSection, sizeof(char), charsRead, destFile); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> void kern_mutex_init(kern_mutex_t* mtx) { pthread_mutex_init(mtx, 0); } void kern_mutex_destroy(kern_mutex_t* mtx) { pthread_mutex_destroy(mtx); } void kern_mutex_lock(kern_mutex_t* mtx) { pthread_mutex_lock(mtx); } void kern_mutex_unlock(kern_mutex_t *mtx) { pthread_mutex_unlock(mtx); } struct ls_Lock { kern_mutex_t mtx; int locked; }; struct ls_Lock* ls_lockCreate(void) { struct ls_Lock* self; size_t size = sizeof(struct ls_Lock); self = (struct ls_Lock*)calloc(size, sizeof(char)); if (0 != self) kern_mutex_init(&self->mtx); return self; } void ls_lockRelease(struct ls_Lock** self) { if (0 != *self) { if ((*self)->locked) kern_mutex_unlock(&(*self)->mtx); kern_mutex_destroy(&(*self)->mtx); free(*self); *self = 0; } } void ls_lockOn(struct ls_Lock* self) { if (0 != self && !self->locked) { kern_mutex_lock(&self->mtx); self->locked = True; } } void ls_lockOff(struct ls_Lock* self) { if (0 != self && self->locked) { kern_mutex_unlock(&self->mtx); self->locked = False; } } int ls_locked(struct ls_Lock* self) { return (0 != self ? self->locked : False); }
1
#include <pthread.h> { char buff[100]; char end; int numthr; int wtime; sem_t semaphore_io; sem_t semaphore_caps; } shared_data; int tsrandom (void); void * io (void *); void * caps (void *); int main (int argc, char * argv[]) { pthread_t tids[200]; int i, e; shared_data sd; sd.end = 0; if (argc > 1) { if (sscanf(argv[1],"%d",&sd.numthr) != 1 || sd.numthr < 1 || sd.numthr > 200) { sd.end = 1; } } else sd.numthr = 2; if (argc > 2) { if (sscanf(argv[2],"%d",&sd.wtime) != 1 || sd.wtime < 0 || sd.wtime > 1000000) { printf ("Wrong \\"microseconds\\" parameter.\\n"); sd.end = 1; } } else sd.wtime = 20; if (sd.end) { "[ microseconds ] ]\\n", argv[0]); printf ("Max. microseconds: %d\\n", 1000000); return -2; } srand ((unsigned)getpid() ^ (unsigned)time(0)); if (sem_init (&sd.semaphore_io, 0, 0) || sem_init (&sd.semaphore_caps, 0, 0)) { perror ("sem_init"); return -1; } for (i=0; i<sd.numthr; i++) if ((e=pthread_create (&tids[i], 0, caps, &sd)) != 0) { fprintf (stderr, "Error %d while " return -1; } io (&sd); for (i=0; i<sd.numthr; i++) if ((e=pthread_join (tids[i], 0)) != 0) { fprintf (stderr, "Error %d waiting for " return -2; } sem_destroy (&sd.semaphore_io); sem_destroy (&sd.semaphore_caps); return 0; } void * io (void * pv) { shared_data * sd = (shared_data *) pv; int i; printf ("Type lines of text (Ctrl+D to finish):\\n"); for (;;) { if (!fgets (sd->buff, 100, stdin)) sd->end = 1; for (i=0; i<sd->numthr; i++) sem_post (&sd->semaphore_caps); if (sd->end) return 0; for (i=0; i<sd->numthr; i++) sem_wait (&sd->semaphore_io); fputs (sd->buff, stdout); } } void * caps (void * pv) { shared_data * sd = (shared_data *) pv; int i; char c; for (;;) { sem_wait (&sd->semaphore_caps); if (sd->end) return 0; for (i=0; sd->buff[i]; i++) if (tsrandom() > 32767/2) { c = sd->buff[i]; if (c >= 'a' && c <= 'z') { if (sd->wtime) usleep (sd->wtime); sd->buff[i] -= ('a' - 'A'); } } sem_post (&sd->semaphore_io); } } int tsrandom (void) { int i; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock (&mutex); i = rand (); pthread_mutex_unlock (&mutex); return i; }
0
#include <pthread.h> void *producer(void *arg); void *consumer(void *arg); int buffer_num = 0; pthread_mutex_t mutex; int running = 1; int main(void) { pthread_t producer_pt; pthread_t consumer_pt; pthread_mutex_init(&mutex, 0); pthread_create(&producer_pt, 0, (void*)producer, 0); pthread_create(&consumer_pt, 0, (void*)consumer, 0); usleep(100); running = 0; pthread_join(consumer_pt, 0); pthread_join(producer_pt, 0); pthread_mutex_destroy(&mutex); return 0; } void *producer(void *arg) { while(running) { pthread_mutex_lock(&mutex); buffer_num++; printf("produce + buffer number: %d\\n", buffer_num); pthread_mutex_unlock(&mutex); } } void *consumer(void *arg) { while(running) { pthread_mutex_lock(&mutex); --buffer_num; printf("consume - buffer number: %d\\n", buffer_num); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> extern int errno; int gridsize = 0; int grid[10][10]; int threads_left; pthread_mutex_t lock; time_t start_t, end_t; void print_grid(int grid[10][10], int gridsize) { int i, j; for (i = 0; i < gridsize; i++) { for (j = 0; j < gridsize; j++) fprintf(stdout, "%d\\t", grid[i][j]); fprintf(stdout, "\\n"); } } void initialize_grid(int grid[10][10], int gridsize) { int i, j; for (i = 0; i < gridsize; i++) for (j = 0; j < gridsize; j++) grid[i][j] = rand() % 100; } long sum_grid(int grid[10][10], int gridsize) { int i, j; long sum = 0; for (i = 0; i < gridsize; i++) for (j = 0; j < gridsize; j++) sum += grid[i][j]; return sum; } void error(char* msg) { perror(msg); exit(1); } void* do_swaps(void *args) { int i, row1, row2, column1, column2, temp; grain_type* gain_type = (grain_type *)args; threads_left++; for (i = 0; i < 20; i++) { row1 = rand() % gridsize; column1 = rand() % gridsize; row2 = rand() % gridsize; column2 = rand() % gridsize; if (*gain_type == GRID) { pthread_mutex_lock(&lock); grid; } else if (*gain_type == ROW) { pthread_mutex_lock(&lock); grid[row1]; grid[row2]; } else if (*gain_type == CELL) { pthread_mutex_lock(&lock); } temp = grid[row1][column1]; sleep(1); grid[row1][column1] = grid[row2][column2]; grid[row2][column2] = temp; if (*gain_type == GRID) { pthread_mutex_unlock(&lock); } else if (*gain_type == ROW) { pthread_mutex_unlock(&lock); } else if (*gain_type == CELL) { pthread_mutex_unlock(&lock); } } threads_left--; if (threads_left == 0) { time(&end_t); } return 0; } int main(int argc, char** argv) { int nthreads = 0; pthread_t threads[1000]; grain_type row_granularity = NONE; long init_sum = 0; long final_sum = 0; int i; if (argc > 3) { gridsize = atoi(argv[1]); if (gridsize > 10 || gridsize < 1) error("Grid size must be between 1 to 10\\n"); nthreads = atoi(argv[2]); if (nthreads > 1000 || nthreads < 1) error("Number of threads must be between 1 to 1000\\n"); if (argv[3][0] == 'g' || argv[3][0] =='G') row_granularity = GRID; else if (argv[3][0] == 'r' || argv[3][0] == 'R') row_granularity = ROW; else if (argv[3][0] == 'c' || argv[3][0] == 'C') row_granularity = CELL; } else error("Invalid number of arguments"); printf("Initial Grid:\\n\\n"); initialize_grid(grid, gridsize); init_sum = sum_grid(grid, gridsize); print_grid(grid, gridsize); printf("\\nInitial Sum: %lu\\n", init_sum); printf("Executing threads...\\n"); srand((unsigned int)time( 0 )); pthread_mutex_init(&lock, 0); time(&start_t); for (i = 0; i < nthreads; i++) { if (pthread_create(&(threads[i]), 0, do_swaps, (void *)(&row_granularity)) != 0) error("ERROR thread creation failed"); } for (i = 0; i < nthreads; i++) pthread_detach(threads[i]); pthread_mutex_destroy(&lock); while(1) { sleep(2); if (threads_left == 0) { fprintf(stdout, "\\nFinal Grid:\\n\\n"); print_grid(grid, gridsize); final_sum = sum_grid(grid, gridsize); fprintf(stdout, "\\n\\nFinal Sum: %lu\\n", final_sum); fprintf(stdout, "Secs elapsed: %g\\n", difftime(end_t, start_t)); exit(0); } } return 0; }
0
#include <pthread.h> int g = 0; pthread_mutex_t mutexsum; void *myThreadFun(void *vargp) { int i = (int)vargp; pthread_mutex_lock (&mutexsum); printf("%i Global: %d\\n", i, ++g); pthread_mutex_unlock (&mutexsum); } int threadCount(int num_threads) { int i; pthread_t tid; pthread_t threads[num_threads]; pthread_attr_t attr; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < num_threads; i++) myThreadFun((void *)i); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutexsum); return g; pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; int buffer[5] = {0}; sem_t empty; sem_t full; void *producer(void *arg) { int in = 0; int* arr = (int*) arg; for (int i = 0; i < 10; i++) { sem_wait(&empty); pthread_mutex_lock(&mutex); buffer[in] = arr[i]; in = (in + 1) % 5; printf("Produced %d.\\n", arr[i]); pthread_mutex_unlock(&mutex); sem_post(&full); srand(time(0)); sleep(rand()%5); } return 0; } void *consumer() { int out = 0; for (int i =10; i > 0; i--) { sem_wait(&full); pthread_mutex_lock(&mutex); int temp = buffer[out]; buffer[out] = 0; out = (out + 1) % 5; printf("Consumed %d.\\n", temp); pthread_mutex_unlock(&mutex); sem_post(&empty); srand(time(0)); sleep(rand() % 5); } return 0; } int main(void) { printf("Enter ten numbers: "); int arr[10] = {0}; scanf("%d %d %d %d %d %d %d %d %d %d",&arr[0], &arr[1], &arr[2], &arr[3], &arr[4], &arr[5], &arr[6], &arr[7], &arr[8], &arr[9]); pthread_t producer_t; pthread_t consumer_t; sem_init(&empty, 0, 5); sem_init(&full, 0, 0); pthread_create(&producer_t, 0, producer, &arr); pthread_create(&consumer_t,0 , consumer, 0); pthread_join(producer_t, 0); pthread_join(consumer_t, 0); for (int i = 0; i < 5 ; i++) printf("%d ", buffer[i]); printf("\\n"); sem_destroy(&empty); sem_destroy(&full); }
0
#include <pthread.h> pthread_mutex_t mutex; int fd_gprs=0; extern struct state *g_state; int xfer_init() { if((fd_gprs=open_com_port("/dev/ttySP2"))<0) { perror("open_port lcd error"); return -1; } if(set_opt(fd_gprs,115200,8,'N',1)<0) { perror(" set_opt cap error"); close(fd_gprs); return -1; } pthread_mutex_init(&mutex, 0); return 0; } void send_web_post(char wifi,char *url,char *buf,int timeout,char **out) { char request[1024]={0}; char length_string[30]={0}; int result=0,i,ltimeout=0; char rcv[512]={0},ch; pthread_mutex_lock(&mutex); if(wifi) { sprintf(request,"JSONStr=%s",buf); printf("[UPLOAD_PROCESS]""send web %s\\n",request); *out=http_post(url,request,timeout); if(*out!=0) { printf("[UPLOAD_PROCESS]""<==%s\\n",*out); g_state->network_state=1; } else { printf("[UPLOAD_PROCESS]""<==NULL\\n"); g_state->network_state=0; } } else { char gprs_string[1024]={0}; int j=0; strcpy(gprs_string,"POST /saveData/airmessage/messMgr.do HTTP/1.1\\r\\nHOST: 101.200.182.92:8080\\r\\nAccept: */*\\r\\nContent-Type:application/x-www-form-urlencoded\\r\\n"); sprintf(length_string,"Content-Length:%d\\r\\n\\r\\nJSONStr=",strlen(buf)+8); strcat(gprs_string,length_string); strcat(gprs_string,buf); for(j=0;j<3;j++){ printf("[UPLOAD_PROCESS]""send gprs %s\\n",gprs_string); write(fd_gprs, gprs_string, strlen(gprs_string)); i=0; while(1) { if(read(fd_gprs, &ch, 1)==1) { printf("%c",ch); if(ch=='}') { rcv[i++]=ch; *out=(char *)malloc(i+1); memset(*out,'\\0',i+1); memcpy(*out,rcv,i); pthread_mutex_unlock(&mutex); g_state->network_state=1; return; } else if(ch=='{') i=0; else if(ch=='o') { if(read(fd_gprs,&ch,1)==1) if(ch=='k') { *out=(char *)malloc(3); memset(*out,'\\0',3); strcpy(*out,"ok"); memset(rcv,'\\0',512); strcpy(rcv,"ok"); pthread_mutex_unlock(&mutex); g_state->network_state=1; return; } } rcv[i]=ch; i++; } else { if(timeout!=-1) { ltimeout++; usleep(1000); if(ltimeout>=timeout*1000) { printf("gprs timeout %d\\n",j); *out=0; ltimeout=0; if(j==2) { pthread_mutex_unlock(&mutex); return; } g_state->network_state=0; break; } } } } } if(rcv!=0) printf("[UPLOAD_PROCESS]""rcv %s\\n\\n",rcv); else printf("[UPLOAD_PROCESS]""no rcv got\\n\\n"); } pthread_mutex_unlock(&mutex); return; }
1
#include <pthread.h> char buf[4]; int occupied; int nextin, nextout; pthread_mutex_t mutex; pthread_cond_t more; pthread_cond_t less; } buffer_t; buffer_t buffer; void * producer(void *); void * consumer(void *); pthread_t tid[2]; main( int argc, char *argv[] ) { int i; pthread_cond_init(&(buffer.more), 0); pthread_cond_init(&(buffer.less), 0); pthread_create(&tid[1], 0, consumer, 0); pthread_create(&tid[0], 0, producer, 0); for ( i = 0; i < 2; i++) pthread_join(tid[i], 0); printf("\\nmain() reporting that all %d threads have terminated\\n", i); } void * producer(void * parm) { char item[30]="IT'S A SMALL WORLD, AFTER ALL."; int i; printf("producer started.\\n"); for(i=0;i<30;i++) { if (item[i] == '\\0') break; pthread_mutex_lock(&(buffer.mutex)); if (buffer.occupied >= 4) printf("producer waiting.\\n"); while (buffer.occupied >= 4) pthread_cond_wait(&(buffer.less), &(buffer.mutex) ); printf("producer executing.\\n"); buffer.buf[buffer.nextin++] = item[i]; buffer.nextin %= 4; buffer.occupied++; pthread_cond_signal(&(buffer.more)); pthread_mutex_unlock(&(buffer.mutex)); } printf("producer exiting.\\n"); pthread_exit(0); } void * consumer(void * parm) { char item; int i; printf("consumer started.\\n"); for(i=0;i<30;i++){ pthread_mutex_lock(&(buffer.mutex) ); if (buffer.occupied <= 0) printf("consumer waiting.\\n"); while(buffer.occupied <= 0) pthread_cond_wait(&(buffer.more), &(buffer.mutex) ); printf("consumer executing.\\n"); item = buffer.buf[buffer.nextout++]; printf("%c\\n",item); buffer.nextout %= 4; buffer.occupied--; pthread_cond_signal(&(buffer.less)); pthread_mutex_unlock(&(buffer.mutex)); } printf("consumer exiting.\\n"); pthread_exit(0); }
0
#include <pthread.h> void* mathProf(void* t); void* csProf(void* t); void* dean(void* t); void delay(int); void shuffle(int*, int); pthread_mutex_t sherriLock; int waiting[4]; int inlounge[4]; const char* names[] = {"open", "math prof", "cs prof", "dean"}; int main(){ srand(time(0)); init(); for (int i=0; i<4; i++) { waiting[i] = 0; inlounge[i] = 0; } pthread_mutex_init(&sherriLock, 0); sign = 0; int maths = 6; int css = 7; int deans = 4; int tot = maths+css+deans; int order[tot]; int i; for (i=0; i<maths; i++) { order[i] = 1; } for (; i<maths+css; i++) { order[i] = 2; } for (; i<tot; i++) { order[i] = 3; } shuffle(order, tot); pthread_t profs[tot]; for (i=0; i<tot; i++) { if (order[i]==1) pthread_create(&profs[i], 0, mathProf, 0); else if (order[i]==2) pthread_create(&profs[i], 0, csProf, 0); else if (order[i]==3) pthread_create(&profs[i], 0, dean, 0); else printf("something went horribly wrong!!!\\n"); if (i%5==4) sleep(2); } for (i=0; i<tot; i++) { pthread_join(profs[i], 0); } return 0; } void atDoor(int prof) { waiting[prof]++; printf("%s at door, %d %ss waiting, sign=%s\\n", names[prof], waiting[prof], names[prof], names[sign]); fflush(stdout); } void entered(int prof) { waiting[prof]--; inlounge[prof]++; printf("%s enters lounge, %d %ss in lounge, sign=%s\\n", names[prof], inlounge[prof], names[prof], names[sign]); fflush(stdout); if (sign != prof) printf("*** INVALID SIGN, should be %s, instead is %s ***\\n", names[prof], names[sign]); if (inlounge[prof%3+1] > 0) printf("*** INVALID OCCUPANTS, %ss and %ss in room ***\\n", names[prof],names[prof%3+1]); if (inlounge[(prof+1)%3+1] > 0) printf("*** INVALID OCCUPANTS, %ss and %ss in room ***\\n", names[prof], names[(prof+1)%3+1]); fflush(stdout); } void left(int prof) { inlounge[prof]--; printf("%s left, %d %ss still in lounge, sign=%s\\n", names[prof], inlounge[prof], names[prof], names[sign]); fflush(stdout); if (inlounge[prof] > 0 && sign != prof) printf("*** INVALID SIGN, should be %s, instead is %s ***\\n", names[prof], names[sign]); fflush(stdout); } void* dean(void* t){ pthread_mutex_lock(&sherriLock); atDoor(3); pthread_mutex_unlock(&sherriLock); deanArrive(); pthread_mutex_lock(&sherriLock); entered(3); pthread_mutex_unlock(&sherriLock); delay(rand()%5+4); pthread_mutex_lock(&sherriLock); deanLeave(); left(3); pthread_mutex_unlock(&sherriLock); return 0; } void* csProf(void* t){ pthread_mutex_lock(&sherriLock); atDoor(2); pthread_mutex_unlock(&sherriLock); csProfArrive(); pthread_mutex_lock(&sherriLock); entered(2); pthread_mutex_unlock(&sherriLock); delay(rand()%5+4); pthread_mutex_lock(&sherriLock); csProfLeave(); left(2); pthread_mutex_unlock(&sherriLock); return 0; } void* mathProf(void* t){ pthread_mutex_lock(&sherriLock); atDoor(1); pthread_mutex_unlock(&sherriLock); mathProfArrive(); pthread_mutex_lock(&sherriLock); entered(1); pthread_mutex_unlock(&sherriLock); delay(rand()%5+4); pthread_mutex_lock(&sherriLock); mathProfLeave(); left(1); pthread_mutex_unlock(&sherriLock); return 0; } void shuffle(int* intArray, int arrayLen) { int i=0; for (i=0; i<arrayLen; i++) { int r = rand()%arrayLen; int temp = intArray[i]; intArray[i] = intArray[r]; intArray[r] = temp; } } void delay( int limit ) { int j, k; for( j=1; j < limit*1000; j++ ) { for( k=1; k < limit*1000; k++ ) { int x = j*k/(k+j); int y = x/j + k*x - (j+5)/k + (x*j*k); } } }
1
#include <pthread.h> int SharedVariable = 0; pthread_mutex_t lock_x; bool isNumber(char number[]) { int i = 0; if (number[0] == '-') return 0; for (; number[i] != 0; i++) { if (!isdigit(number[i])) return 0; } return 1; } void SimpleThread(int which) { int num, val; for(num = 0; num < 20; num++) { pthread_mutex_lock(&lock_x); if (random() > 32767 / 2) usleep(500); pthread_mutex_unlock(&lock_x); val = SharedVariable; printf("*** thread %d sees value %d\\n", which, val); SharedVariable = val + 1; } val = SharedVariable; printf("Thread %d sees final value %d\\n", which, val); } int tid; double stuff; } thread_data_t; void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; SimpleThread(data->tid); pthread_exit(0); } int main(int argc, char *argv[]) { bool isNum = 0; char *endptr; int i, rc, x; if( argc == 2 ) { printf("The argument supplied is %s\\n", argv[1]); } else { printf("One argument expected.\\n"); return 0; } isNum = isNumber(argv[1]); if(isNum){ printf("The input value is a positive number\\n"); } else { printf("The input value is not a positive number\\n"); return 0; } x = strtol(argv[1], &endptr, 10); pthread_t thr[x]; thread_data_t thr_data[x]; pthread_mutex_init(&lock_x, 0); for (i = 0; i < x; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < x; ++i) { pthread_join(thr[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t djedbozicnjak, K, godisnji; int br_sobova; int br_patuljaka; int semId; void *Djed_Bozicnjak(void) { do{ pthread_mutex_lock(&djedbozicnjak); pthread_mutex_lock(&K); if(br_sobova == 10 && br_patuljaka > 0){ pthread_mutex_unlock(&K); printf("Raznosenje poklona...\\n"); sleep(2); pthread_mutex_lock(&K); SemSetVal(2, 10); SemSetVal(0, 10); br_sobova = 0; } if(br_sobova == 10){ pthread_mutex_unlock(&K); printf("Djed hrani sobove...\\n"); sleep(2); pthread_mutex_lock(&K); } while(br_patuljaka >= 3){ pthread_mutex_unlock(&K); printf("Konzultacije kod Djeda...\\n"); sleep(2); pthread_mutex_lock(&K); SemSetVal(1, 3); br_patuljaka -= 3; } pthread_mutex_unlock(&K); }while(1); } void *patuljak(void) { pthread_mutex_lock(&K); br_patuljaka++; printf("Stvoren patuljak br. %d\\n", br_patuljaka); if(br_patuljaka == 3){ pthread_mutex_unlock(&djedbozicnjak); } pthread_mutex_unlock(&K); SemOp(1, -1); } void *sob(void) { pthread_mutex_lock(&K); br_sobova++; printf("Stvoren sob br. %d\\n", br_sobova); if(br_sobova == 10){ pthread_mutex_unlock(&djedbozicnjak); pthread_mutex_unlock(&K); SemOp(2, -1); pthread_exit(0); } pthread_mutex_unlock(&K); } int SemSetVal(int SemNum, int SemVal) { return !semctl(semId, SemNum, SETVAL, SemVal); } int SemOp(int SemNum, int SemOp) { struct sembuf SemBuf; SemBuf.sem_num = SemNum; SemBuf.sem_op = SemOp; SemBuf.sem_flg = 0; return semop(semId, &SemBuf, 1); } int main() { int i=1; float vjs, vjp; pthread_t t_id[30]; semId = semget(IPC_PRIVATE, 3, 0600); if(!SemSetVal(1, 3) || !SemSetVal(0, 10) || !SemSetVal(2, 0)){ printf("Ne mogu inicijalizirati semafor!\\n"); exit(1); } pthread_mutex_init(&djedbozicnjak, 0); pthread_mutex_init(&K, 0); pthread_create(&t_id[0], 0, (void*)Djed_Bozicnjak, 0); pthread_join(t_id[0], 0); do{ sleep(rand()%4); vjs = (rand()%6); vjp = (rand()%7); if(vjs > (6/2) && br_sobova < 10){ pthread_create(&t_id[i], 0, (void*)sob, 0); pthread_join(t_id[i], 0); i++; } if(vjp > (7/2)){ pthread_create(&t_id[i], 0, (void*)patuljak, 0); pthread_join(t_id[i], 0); i++; } }while(1); return 0; }
1
#include <pthread.h> void* ta_helping(); void* stu_listening(void *i); void srand_sleep(); sem_t *sem_stu; sem_t *sem_ta; pthread_mutex_t lock; int chair[3] = {-1,-1,-1}; int count = 0; int next_student = 0; int next_seat = 0; int student_has_teached; int main() { int number_of_student; printf("How many student? "); scanf("%d", &number_of_student); student_has_teached = number_of_student; srand(time(0)); int *studentID; pthread_t ta; pthread_t *stu; studentID = malloc(sizeof(int) * number_of_student); stu = malloc(sizeof(pthread_t) * number_of_student); for(int i = 0; i < number_of_student; ++i) {studentID[i] = i;} sem_ta = sem_open("sem_ta",O_CREAT, 0644, 1); sem_stu = sem_open("&sem_stu",O_CREAT, 0644, 0); pthread_mutex_init(&lock, 0); pthread_create(&ta, 0, ta_helping, 0); for(int i = 0; i < number_of_student; ++i) { pthread_create(&stu[i], 0, stu_listening, (void *)&studentID[i]); } pthread_join(ta, 0); for (int i = 0; i < number_of_student; ++i) { pthread_join(stu[i], 0); } return 0; } void *ta_helping() { while(1) { sem_wait(sem_stu); pthread_mutex_lock(&lock); printf("****\\n TA is teaching student %d \\n****\\n", chair[next_student]); chair[next_student] = -1; count--; next_student = (next_student + 1) % 3; printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]); srand_sleep();; pthread_mutex_unlock(&lock); sem_post(sem_ta); student_has_teached--; if(!student_has_teached) { printf("teaching finish.\\n"); return 0; } } } void *stu_listening(void *i) { int ID = *(int *) i; while(1) { srand_sleep();; pthread_mutex_lock(&lock); if(count < 3) { count++; printf("student %d is waiting\\n", ID); chair[next_seat] = ID; next_seat = (next_seat + 1) % 3; printf("waiting students : [1] %d [2] %d [3] %d\\n",chair[0],chair[1],chair[2]); pthread_mutex_unlock(&lock); sem_post(sem_stu); sem_wait(sem_ta); return 0; }else { pthread_mutex_unlock(&lock); } } } void srand_sleep() { int stime = rand() % 3 + 1; sleep(stime); }
0
#include <pthread.h> int buffer[1024]; int count=0; pthread_mutex_t mutex1; pthread_mutex_t mutex2; pthread_mutex_t mutex3; pthread_mutex_t mutex4; void *threadFun1(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); printf("Thread 1\\n"); count++; pthread_mutex_unlock(&mutex3); pthread_mutex_unlock(&mutex4); } } void *threadFun2(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex3); printf("Thread 2:%d\\n",count); pthread_mutex_unlock(&mutex1); } } void *threadFun3(void *arg) { int i; while(1) { pthread_mutex_lock(&mutex4); printf("Thread 3:%d\\n",count); pthread_mutex_unlock(&mutex2); } } int main() { pthread_t tid[3]; int ret=0; int i; int t_value[3]; void *(*threadFun[])(void*) = {threadFun1, threadFun2,threadFun3}; ret = pthread_mutex_init(&mutex1,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } ret = pthread_mutex_init(&mutex2,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } ret = pthread_mutex_init(&mutex3,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex3); ret = pthread_mutex_init(&mutex4,0); if(ret!=0) { fprintf(stderr, "pthread mutex init error:%s", strerror(ret)); return 1; } pthread_mutex_lock(&mutex4); printf("Main thread before pthread create\\n"); for(i=0; i<3; i++) { t_value[i]=i; ret=pthread_create( &(tid[i]), 0, threadFun[i], (void*)&(t_value[i])); if(ret!=0) { fprintf(stderr, "pthread create error:%s", strerror(ret)); return 1; } } printf("Main thread after pthread create\\n"); for(i=0; i<3; i++) { ret = pthread_join(tid[i],0); if(ret!=0) { fprintf(stderr, "pthread join error:%s", strerror(ret)); return 2; } } ret = pthread_mutex_destroy(&mutex1); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex2); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } ret = pthread_mutex_destroy(&mutex3); if(ret!=0) { fprintf(stderr, "pthread mutex destroy error:%s", strerror(ret)); return 1; } printf("All threads are over!\\n"); return 0; }
1
#include <pthread.h> static pthread_mutex_t *locks; static void die_with_error(char *message) { perror(message); exit(1); } static void radix_tree_init(struct radix_tree *tree, int bits, int radix) { if (radix < 1) { perror("Invalid radix\\n"); return; } if (bits < 1) { perror("Invalid number of bits\\n"); return; } unsigned long n_slots = 1L << radix; tree->radix = radix; tree->max_height = (((bits) + (radix) - 1) / (radix)); tree->node = calloc(sizeof(struct radix_node) + (n_slots * sizeof(void *)), 1); if (!tree->node) die_with_error("failed to create new node.\\n"); locks = malloc(sizeof(*locks) * tree->max_height); if (!locks) { die_with_error("failed to allocate mutexes\\n"); } else { int i; for (i = 0; i < tree->max_height; i++) pthread_mutex_init(&locks[i], 0); } } static int find_slot_index(unsigned long key, int levels_left, int radix) { return key >> ((levels_left - 1) * radix) & ((1 << radix) - 1); } static void *radix_tree_find_alloc(struct radix_tree *tree, unsigned long key, void *(*create)(unsigned long)) { int levels_left = tree->max_height; int radix = tree->radix; int n_slots = 1 << radix; int index; struct radix_node *current_node = tree->node; void **next_slot = 0; void *slot; int current_level = 0; while (levels_left) { index = find_slot_index(key, levels_left, radix); pthread_mutex_lock(&locks[current_level]); next_slot = &current_node->slots[index]; slot = *next_slot; if (slot) { current_node = slot; } else if (create) { void *new; if (levels_left != 1) new = calloc(sizeof(struct radix_node) + (n_slots * sizeof(void *)), 1); else new = create(key); if (!new) die_with_error("failed to create new node.\\n"); *next_slot = new; current_node = new; } else { pthread_mutex_unlock(&locks[current_level]); return 0; } pthread_mutex_unlock(&locks[current_level]); current_level++; levels_left--; } return *next_slot; } static void *radix_tree_find(struct radix_tree *tree, unsigned long key) { return radix_tree_find_alloc(tree, key, 0); } struct radix_tree_desc lock_level_desc = { .name = "lock_level", .init = radix_tree_init, .find_alloc = radix_tree_find_alloc, .find = radix_tree_find, };
0
#include <pthread.h> static char g_log_filename[256]; static FILE *g_log_fp = 0; static int g_log_level = 0; static pthread_mutex_t g_log_lock; static char *g_log_level_str[] = { "EMERG", "ALERT", "CRIT", "ERR", "WARNING", "NOTICE", "INFO", "DEBUG", 0 }; static void log_time(char *str, int flag_name) { struct tm *p; long ts; int year, month, day, hour, min, sec; ts = time(0); p = localtime(&ts); year = p->tm_year + 1900; month = p->tm_mon + 1; day = p->tm_mday; hour = p->tm_hour; min = p->tm_min; sec = p->tm_sec; if (flag_name == 1) sprintf(str, "%4d_%02d_%02d_%02d_%02d_%02d.log", year, month, day, hour, min, sec); else sprintf(str, "%4d-%02d-%02d %02d:%02d:%02d ", year, month, day, hour, min, sec); } static void log_print_syslog(int level, const char *format, ...) { if (level > g_log_level) return; va_list ap; __builtin_va_start((ap)); syslog(level, "%s: ", g_log_level_str[level]); vsyslog(level, format, ap); ; } static void log_print_stderr(int level, const char *format, ...) { if (level > g_log_level) return; char str_time[32] = {0}; va_list ap; __builtin_va_start((ap)); log_time(str_time, 0); fputs(str_time, stderr); fprintf(stderr, "%s: ", g_log_level_str[level]); vfprintf(stderr, format, ap); ; } static void log_print_file(int level, const char *format, ...) { if (level > g_log_level) return; pthread_mutex_lock(&g_log_lock); char str_time[32] = {0}; va_list ap; g_log_fp = fopen(g_log_filename, "a+"); if (g_log_fp == 0) { fprintf(stderr, "fopen %s failed: %s\\n", g_log_filename, strerror(errno)); goto err; } __builtin_va_start((ap)); log_time(str_time, 0); fputs(str_time, g_log_fp); fprintf(g_log_fp, "%s: ", g_log_level_str[level]); vfprintf(g_log_fp, format, ap); ; err: fclose(g_log_fp); pthread_mutex_unlock(&g_log_lock); } int log_init(int type, int level, const char *ident) { memset(g_log_filename, 0, sizeof(g_log_filename)); g_log_fp = 0; g_log_level = level; switch (type) { case LOG_STDERR: g_log_fp = stderr; g_log_print_func = &log_print_stderr; break; case LOG_FILE: if (ident == 0) { log_time(g_log_filename, 1); } else { strncpy(g_log_filename, ident, sizeof(g_log_filename)); } g_log_fp = fopen(g_log_filename, "a+"); if (g_log_fp == 0) { fprintf(stderr, "fopen %s failed: %s\\n", g_log_filename, strerror(errno)); return -1; } fprintf(stderr, "name = %s\\n", g_log_filename); g_log_print_func = &log_print_file; fclose(g_log_fp); break; case LOG_RSYSLOG: openlog(ident, LOG_CONS | LOG_PID, level); g_log_print_func = &log_print_syslog; break; default: fprintf(stderr, "unsupport log type!\\n"); return -1; break; } pthread_mutex_init(&g_log_lock, 0); return 0; }
1
#include <pthread.h> pthread_t pr[4]; pthread_mutex_t se[4]; pthread_mutex_t seEnd[4]; pthread_mutex_t seIndex; int pIndex = 0; int fIndex = 0; int mIndex = 15; int files[15] = {1,2,3,1,2,3,1,2,3,1,2,3,1,2,3}; int lockTimes[4] = {0,3,4,5}; int file; int z = 0; void * print(void *arg){ pthread_mutex_lock(&seIndex); int i = pIndex++; pthread_mutex_unlock(&seIndex); printf("Start %d \\n",i ); while(fIndex<mIndex){ pthread_mutex_lock(&se[i]); file = files[fIndex]; pthread_mutex_lock(&seIndex); fIndex++; pthread_mutex_unlock(&seIndex); printf("=> Print %d file %d, time is: %ds.\\n",i,file,lockTimes[file]*100 ); int lockTime = z+lockTimes[file]; while(z<lockTime); pthread_mutex_unlock(&se[i]); } pthread_mutex_unlock(&seEnd[i]); } int main(int argc, char const *argv[]) { pthread_mutex_lock(&seEnd[0]); pthread_mutex_lock(&seEnd[1]); pthread_mutex_lock(&seEnd[2]); pthread_mutex_lock(&seEnd[3]); pthread_create(&pr[0],0,print,0); pthread_create(&pr[1],0,print,0); pthread_create(&pr[2],0,print,0); pthread_create(&pr[3],0,print,0); while(z<1000) { z++; } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; void *another(void *arg) { printf("In child thread, lock the mutex\\n"); pthread_mutex_lock(&mutex); sleep(5); pthread_mutex_unlock(&mutex); } int main() { pthread_mutex_init(&mutex, 0); pthread_t tid; pthread_create(&tid, 0, another, 0); sleep(1); int pid = fork(); if(pid < 0) { pthread_join(tid, 0); pthread_mutex_destroy(&mutex); exit(1); } else if(pid == 0) { printf("I am in the child, want to get the lock\\n"); pthread_mutex_lock(&mutex); printf("I can't run to here, ooop...\\n"); pthread_mutex_unlock(&mutex); exit(0); } else { wait(0); } pthread_join(tid, 0); pthread_mutex_destroy(&mutex); exit(0); }
1
#include <pthread.h> struct q_log_ctx { int ql_init; int ql_fd; char *ql_file; int ql_level; pthread_mutex_t ql_mtx; }; static struct q_log_ctx log_ctx = { .ql_init = 0, .ql_fd = -1, .ql_file = Q_LOG_FILE, .ql_level = Q_LOG_LEVEL, .ql_mtx = PTHREAD_MUTEX_INITIALIZER, }; static char *lvl_str[Q_LOG_MAX] = {"D", "I", "W", "E"}; void q_log_init(void) { int fd = 0; log_ctx.ql_init = 1; fd = open(log_ctx.ql_file, O_WRONLY | O_APPEND | O_CREAT, 0644); if (fd == -1) { fprintf(stderr, "failed init log\\n"); return; } log_ctx.ql_fd = fd; log_ctx.ql_init = 2; } void q_log(int level, const char *fmt, ...) { static char log_buf[1024] = {0}; int n = 0; struct timeval tv; struct tm tm_val; va_list ap; if (level < log_ctx.ql_level || level >= Q_LOG_MAX) return; pthread_mutex_lock(&log_ctx.ql_mtx); if (unlikely(log_ctx.ql_init == 0)) q_log_init(); if (log_ctx.ql_fd < 0) goto out; gettimeofday(&tv, 0); localtime_r(&tv.tv_sec, &tm_val); n = snprintf(log_buf, sizeof(log_buf), "%04d-%02d-%02d " "%02d:%02d:%02d.%6lu [%s] ", tm_val.tm_year, tm_val.tm_mon, tm_val.tm_mday, tm_val.tm_hour, tm_val.tm_min, tm_val.tm_sec, tv.tv_usec, lvl_str[level]); if (n > 0) write(log_ctx.ql_fd, log_buf, n); __builtin_va_start((ap)); n = vsnprintf(log_buf, sizeof(log_buf) - 1, fmt, ap); ; if (n > 0) write(log_ctx.ql_fd, log_buf, n); write(log_ctx.ql_fd, "\\n", 1); out: pthread_mutex_unlock(&log_ctx.ql_mtx); }
0
#include <pthread.h> int *array; int length, count; pthread_t *ids; int length_per_thread; pthread_mutex_t ex = PTHREAD_MUTEX_INITIALIZER; void * count3s_thread(void *id){ int i; int start = length_per_thread*(int)id; int end = start + length_per_thread; for(i=start; i < end; i++){ if(array[i] == 3){ pthread_mutex_lock(&ex); count++; pthread_mutex_unlock(&ex); } } return 0; } void count3s(int nthreads){ int i; for(i=0; i < nthreads; i++){ pthread_create(&ids[i], 0, count3s_thread, (void *)i); } for(i=0; i < nthreads; i++){ pthread_join(ids[i], 0); } } int main( int argc, char *argv[]){ int i; struct timeval s,t; int n = atoi(argv[1]); ids = (pthread_t *)malloc(n*sizeof(pthread_t)); length_per_thread = 50*1024*1024 / n; printf("Using %d threads; length_per_thread = %d\\n", n, length_per_thread); array= (int *)malloc(50*1024*1024*sizeof(int)); length = 50*1024*1024; srand(0); for(i=0; i < length; i++){ array[i] = rand() % 4; } gettimeofday(&s, 0); count3s(n); gettimeofday(&t, 0); printf("Count of 3s = %d\\n", count); printf("Elapsed time (us) = %ld\\n", (t.tv_sec - s.tv_sec)*1000000 + (t.tv_usec - s.tv_usec)); return 0; }
1
#include <pthread.h> int threads=1024; int threads_max=100; int counter1=0; int counter1_start=180000; int counter1_warn=200000; int counter_de_nr=0; int koniec=0; int sleep_time=1000; int manager_cmd=0; int key=0; pthread_cond_t warunek1 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int getch (void) { int key1; struct termios oldSettings, newSettings; tcgetattr(STDIN_FILENO, &oldSettings); newSettings = oldSettings; newSettings.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newSettings); printf("getch():manager_cmd:%d\\n",manager_cmd); if (manager_cmd==1){ key1=107; } else key1 = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldSettings); return key1; } void* counter_in(void *arg) { printf("counter_in\\n"); for(;;) { pthread_mutex_lock(&mutex1); counter1++; pthread_mutex_unlock(&mutex1); usleep(sleep_time); } return 0; } void* manager(void *arg) { printf("manager\\n"); int c1=0; int c2=0; int first=0; time_t cur_time1 = time(0); time_t cur_time2; FILE *konsola = fopen("/dev/tty", "w"); for(;;) { if ( first==0 ) { cur_time1=time(0); c1=counter1; first=1; } if ( (time(0)-cur_time1) >= 10 && first==1) { c2=counter1; first=0; printf("after %d sec, c1 change: (c2-c1):%d\\tfirst:%d\\tcounter1:%d\\tcounter_de_nr:%d\\n",time(0)-cur_time1,c2-c1,first,counter1,counter_de_nr); if ((c2-c1)<-100) { manager_cmd=1; key=getch(); fprintf(konsola,"\\n"); printf("COND_WAIT\\n"); } } pthread_mutex_unlock(&mutex1); usleep(10000); } return 0; } void* counter_de(void *arg) { printf("counter_de\\n"); char t = *((int*) arg); int i; pthread_mutex_lock(&mutex2); counter_de_nr++; pthread_mutex_unlock(&mutex2); while(koniec!=t) { pthread_mutex_trylock(&mutex1); for (i=0;i<1;i++) counter1--; pthread_mutex_unlock(&mutex1); usleep(100000); } pthread_mutex_unlock(&mutex1); koniec=-1; pthread_mutex_lock(&mutex2); counter_de_nr--; pthread_mutex_unlock(&mutex2); manager_cmd=0; key=0; pthread_exit(0); return 0; } void* klawiatura1(void *workers_main) { printf("keyboard active!\\n"); pthread_t *workers_local=(pthread_t*)workers_main; int threads_names[threads_max]; int i=0; for(;;) { printf("key=%d\\n",key); key=getch(); if (key==120) { sleep_time=sleep_time-100; } if (key==115) { sleep_time=sleep_time+100; } if (key==107) { koniec=counter_de_nr; } if (key==110 && counter_de_nr<threads_max){ threads_names[counter_de_nr]=counter_de_nr+1; pthread_create(&workers_local[counter_de_nr], 0, counter_de,&threads_names[counter_de_nr]); } if (key==97) { printf("\\n\\n\\ncounter1:\\t%d\\tsleep_time:\\t%d\\n",counter1,sleep_time); } if (key==122) { printf("\\n\\n\\ncounter_de_nr:\\t%d\\n",counter_de_nr); for (i=0;i<counter_de_nr;i++) printf("%lu\\t",(unsigned long int)workers_local[i]); printf("\\n\\n"); } } } int main(int argc, char* argv[]) { printf("klawisze:a ,z ,n ,c\\n"); counter1=counter1_start; int i=0; pthread_t workers[threads_max]; for (i=0;i<threads_max;i++) workers[i]=0; pthread_t klawiatura; pthread_t counter; pthread_t manage; pthread_create(&klawiatura, 0, klawiatura1,(void*)workers); pthread_create(&counter, 0, counter_in, 0); pthread_create(&manage, 0, manager,0); sleep(1000); for (i=0;i<counter_de_nr;i++) pthread_join(workers[i], 0); return 0; }
0
#include <pthread.h> void *referee(void*); void *player(void*); void print_board(); int check_winner(); int check_horizonatal_tiles(); int check_diagonal_tiles(); int board_filled(); char board[6][7]; int play_game,game_finished; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; int main(int argc,char *argv[]) { int i,j; play_game = 1; game_finished = 0; for(i=0;i<6;i++) { for(j = 0; j < 7; j++) board[i][j]='0'; } pthread_t referee_thread, player1_thread, player2_thread; pthread_create(&referee_thread, 0, referee, 0); pthread_create(&player1_thread, 0, player,(void*) 'Y'); pthread_create(&player2_thread, 0, player,(void*) 'R'); pthread_join(referee_thread, 0); pthread_join(player1_thread, 0); pthread_join(player2_thread, 0); return(0); } void *referee(void *argument) { printf("Board is Empty and Winner is not declared.\\n\\n********************* Please Start the Game.********************\\n\\n"); print_board(); for(;;) { pthread_mutex_lock(&mutex); while (play_game == 0) pthread_cond_wait(&cond_var,&mutex); play_game = 0; if ((check_winner() == 0) && (board_filled() == 0)) pthread_cond_signal(&cond_var); else { game_finished = 1; printf("\\n****************** GAME OVER *******************\\n"); pthread_cond_signal(&cond_var); pthread_mutex_unlock(&mutex); return(0); } pthread_mutex_unlock(&mutex); } } void *player(void *tile) { char *local_tile; int i,column_no,find_new_tile; time_t tloc; local_tile = (char*)tile; srand(time(&tloc)); for(;;) { pthread_mutex_lock(&mutex); while(play_game == 1) pthread_cond_wait(&cond_var,&mutex); if(game_finished == 1) { pthread_cond_signal(&cond_var); pthread_mutex_unlock(&mutex); return(0); } else { printf("Player %c is playing..\\n",local_tile); do { sleep(1); column_no = rand()% 7 + 1; printf("\\nColumn Number Selected is:%d\\n",column_no); for(i = 6 -1; i >= 0; i--) { if(board[i][column_no-1] == '0') { board[i][column_no-1] = local_tile; print_board(); printf("Passing to Referee to Check for the winner..\\n\\n"); play_game = 1; find_new_tile = 0; pthread_cond_signal(&cond_var); break; } else find_new_tile = 1; } } while(find_new_tile == 1); } pthread_mutex_unlock(&mutex); } return(0); } void print_board() { int i,j; for(i = 0; i < 6; i++) { for(j = 0; j < 7; j++) { printf("%c\\t",board[i][j]); } printf("\\n_____________________________________________________\\n"); } } int check_winner() { if ( check_horizontal_tiles() == 1 || check_diagonal_tiles() == 1) return(1); return(0); } int check_horizontal_tiles() { int i,j; for(i = 0; i < 6;i++) { for(j = 0; j < 7; j++) { if (( board[i][j] == board[i][j+1] && j+1 < 7) && ( board[i][j] == board[i][j+2] && j+2 < 7) && ( board[i][j] == board[i][j+3] && j+3 < 7) && board[i][j] != '0') { printf("\\n***The Winner is %c with Horizontal Pattern.***\\n",board[i][j]); return(1); } } } return(0); } int check_diagonal_tiles() { int i,j; for(i = 0; i < 6;i++) { for(j = 0; j < 7; j++) { if (((( board[i][j] == board[i+1][j+1] && i+1 < 6 && j+1 < 7) && ( board[i][j] == board[i+2][j+2] && i+2 < 6 && j+2 < 7) && ( board[i][j] == board[i+3][j+3] && i+3 < 6 && j+3 < 7)) || (( board[i][j] == board[i+1][j-1] && i+1 < 6 && j-1 > -1) && ( board[i][j] == board[i+2][j-2] && i+2 < 6 && j-2 > -1) && ( board[i][j] == board[i+3][j-3] && i+3 < 6 && j-3 > -1))) && board[i][j] != '0') { printf("\\n***The Winner is %c with Diagonal Pattern.***\\n",board[i][j]); return(1); } } } return(0); } int board_filled() { int i,j; for(i = 0;i < 6; i++) { for(j = 0;j < 7; j++) { if (board[i][j] == '0') return(0); } } printf("\\nTie between the Players.\\n"); return(1); }
1
#include <pthread.h> struct foo* fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo* foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo* foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_release(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--(fp->f_count) == 0) { idx = (((unsigned long)fp)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) { tfp = tfp->f_next; } tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
0
#include <pthread.h> pthread_mutex_t semaforo; static char *path_log; void iniciarYEstablecerRutaArchivoLog(char *ruta) { path_log = strdup(ruta); pthread_mutex_init(&semaforo,0); } void borrarSemaforoLogs() { pthread_mutex_destroy(&semaforo); } void logDebug(char *mensaje) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_DEBUG); log_debug(Log,mensaje); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logConexionMarta(char *mensaje,char *ipMarta,char *puertoMarta) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,mensaje,ipMarta,puertoMarta); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logCreacionHiloMapper(char *mensaje,char *ipNodo,char *puertoNodo,char *mapper) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,mensaje,ipNodo,puertoNodo,mapper); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logCreacionHiloReducer(char *mensaje,char *ipNodo,char *puertoNodo,char *reduce,char *resultado) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,mensaje,ipNodo,puertoNodo,reduce,resultado); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logConMensaje(char *mensaje) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,mensaje); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logCabeceraEnvia(char *cabecera) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",0,LOG_LEVEL_INFO); char *mensaje=malloc(1000); strcpy(mensaje,"Se envio un mensaje con cabecera: "); strcat(mensaje,cabecera); log_info(Log,mensaje); log_destroy(Log); free(mensaje); pthread_mutex_unlock(&semaforo); } void logCabeceraRecibe(char *cabecera) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",0,LOG_LEVEL_INFO); char *mensaje=malloc(1000);; strcpy(mensaje,"Se recibio un mensaje con cabecera: "); strcat(mensaje,cabecera); log_info(Log,mensaje); log_destroy(Log); free(mensaje); pthread_mutex_unlock(&semaforo); } void logOperacion(char *mensaje,int idOp) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,mensaje,idOp); log_destroy(Log); pthread_mutex_unlock(&semaforo); } void logFinJob(char *mensaje,char *rutinaMap,char *rutinaReduce,char *resultado) { pthread_mutex_lock(&semaforo); t_log *Log; Log = log_create(path_log,"JOB",1,LOG_LEVEL_INFO); log_info(Log,rutinaMap, rutinaReduce,resultado); log_destroy(Log); pthread_mutex_unlock(&semaforo); }
1
#include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; struct tree { long data; struct tree *left; struct tree *right; }; struct tree *root = 0; struct tree *newnode(long data) { struct tree *newnode = (struct tree*)malloc(sizeof(struct tree)); newnode->data = data; newnode->left = 0; newnode->right = 0; return newnode; } void* insert(void *dat) { long data = (long)dat; printf("thread %ld is inserting a node in BST with value %ld\\n",pthread_self(),data); struct tree *newn = newnode(data); if(!(root)) { pthread_mutex_lock(&mtx); root = newn; pthread_mutex_unlock(&mtx); pthread_exit( (void*)1); } struct tree *temp = root; while(temp) { if (temp->data > data) { if(!temp->left) { pthread_mutex_lock(&mtx); temp->left = newn; pthread_mutex_unlock(&mtx); pthread_exit( (void*)1); } printf("%ld is traversing\\n",pthread_self()); temp = temp->left; } else if ( temp->data < data ) { if(!temp->right) { pthread_mutex_lock(&mtx); temp->right = newn; pthread_mutex_unlock(&mtx); pthread_exit( (void*)1); } printf("%ld is traversing\\n",pthread_self()); temp = temp->right; } else { pthread_exit( (void*)0); } } pthread_exit( (void*)0); } void inorder(struct tree *root) { if(!root) return; if(root) { inorder(root->left); printf("%ld ",root->data); inorder(root->right); } } int main () { pthread_t thread[10]; long r,t; void *status; for ( t = 0; t<10;t++) { r = pthread_create(&thread[t],0,insert,(void*)(rand()%10)); if(r) { printf("thread not created\\n"); exit(1); } } for(t=0;t<10;t++) { pthread_join(thread[t],&status); printf("%ld thread exited with status %ld\\n",t,(long)status); } printf("inorder of BST :\\n"); struct tree *temp = root; inorder(temp); pthread_exit(0); }
0
#include <pthread.h> struct job { int id; struct job *next; }; void process_job (struct job *one_job) { printf("Thread_%d is process job %d\\n", (int)pthread_self (), one_job->id); } pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; sem_t job_count; void *thread_func (void *data) { while (1) { sem_wait (&job_count); struct job *next_job; struct job **job_queue = (struct job **)data; pthread_mutex_lock (&job_queue_mutex); next_job = *job_queue; *job_queue = (*job_queue)->next; pthread_mutex_unlock (&job_queue_mutex); process_job (next_job); free (next_job); } return 0; } void enqueue_job (struct job **job_queue, struct job * new_job) { pthread_mutex_lock (&job_queue_mutex); new_job->next = *job_queue; *job_queue = new_job; pthread_mutex_unlock (&job_queue_mutex); sem_post (&job_count); } int main() { const int SIZE = 3; pthread_t threads[SIZE]; int i; struct job *job_queue = 0; sem_init (&job_count, 0, 0); for (i = 0; i < SIZE; i++) { pthread_create (&(threads[i]), 0, thread_func, &job_queue); } for (i = 0; i < 10; i++) { struct job *new_job = malloc (sizeof (struct job)); new_job->id = i; enqueue_job (&job_queue, new_job); sleep(1); } for (i = 0; i < SIZE; i++) { pthread_join (threads[i], 0); } sem_destroy (&job_count); return 0; }
1
#include <pthread.h> pthread_t stu_thread[2]; pthread_mutex_t mutex_lock; int number = 0; void * studentA() { int i = 0; for(i = 0; i < 5; i++) { pthread_mutex_lock(&mutex_lock); number++; printf("studentA has finished the work one time\\n"); pthread_mutex_unlock(&mutex_lock); sleep(1); } if(5 <= number) { printf("studentA has finished all works!!!\\n"); } pthread_exit(0); } void * studentB() { while(1) { pthread_mutex_lock(&mutex_lock); if(5 <= number) { number = 0; printf("studentB has finished his work!!!\\n"); pthread_mutex_unlock(&mutex_lock); break; } else { pthread_mutex_unlock(&mutex_lock); sleep(2); } } pthread_exit(0); } int main() { pthread_mutex_init(&mutex_lock, 0); pthread_create(&stu_thread[0], 0, studentA, 0); pthread_create(&stu_thread[1], 0, studentB, 0); pthread_join(stu_thread[0], 0); pthread_join(stu_thread[1], 0); return 0; }
0
#include <pthread.h> FILE *fp; struct userinfo { char username[100]; int socket; }u[1000]; pthread_t thread; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char buffer[256],user[100],str[100],pass[30]; struct sockaddr_in serv_addr, cli_addr; int n,nu=1,i; void error(char *msg) { perror(msg); exit(0); } void* server(void*); int main (int argc, char *argv[]) { fp=fopen("user.txt","w"); fprintf(fp,"server started\\n"); fclose(fp); int i,sockfd, newsockfd[1000], portno, clilen,no=0,n; if (argc<2) { fprintf (stderr,"ERROR! Provide A Port!\\n"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd<0) error("ERROR! Cannnot Open Socket"); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))<0) error("ERROR! On Binding"); listen(sockfd, 5); clilen = sizeof(cli_addr); while(1) { newsockfd[no] = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen); if (newsockfd<0) error("ERROR! On Accepting"); if(n<0) error("ERROR READING FROM SOCKET"); pthread_mutex_lock(&mutex); pthread_create(&thread,0,server,(void*)&newsockfd[no]); no+=1; } close(newsockfd[no]); close(sockfd); return 0; } void* server(void* sock) { int newsockfd=*((int*)sock),j=0,m; char to[100],from[100],name[100]; fp=fopen("user.txt","r+"); checking: m=1; bzero(user,100); bzero(to,100); bzero(from,100); bzero(str,100); recv(newsockfd, user,100,0); recv(newsockfd, pass,30,0); while(fscanf(fp,"%s",str)!=EOF) { n=strncmp(user,str,strlen(str)); if(n==0) { fscanf(fp,"%s",str); n=strncmp(pass,str,strlen(str)); if(n==0) { m=2; break; } else { send(newsockfd,"USERNAME EXISTS",15,0); m=0; break;} fscanf(fp,"%s",str); } } if(m==0) goto checking; if(m==1) { fclose(fp); send(newsockfd,"USER REGISTERED",15,0); bzero(u[nu].username,100); u[nu].socket=newsockfd; strncpy(u[nu].username,user,strlen(user)); nu++; } if(m==2) { fclose(fp); send(newsockfd,"USER LOGGED IN",14,0); for(i=1;i<nu;i++) if(strcmp(user,u[i].username)==0) break; u[i].socket=newsockfd; } pthread_mutex_unlock(&mutex); bzero(buffer, 256); int newsockfd1; while(1) { n = recv(newsockfd, buffer, 255, 0); if(n<0) error("ERROR! Reading From Socket"); if(strncmp(buffer,"bye",3)==0) { close(newsockfd); pthread_exit(0); } i=3; strcpy(name,buffer); while(name[i]!=':') { to[i-3]=name[i]; i++; } to[i-3]='\\0'; j=0; bzero(buffer,256); while(name[i]!='|') { buffer[j]=name[i]; i++; j++; } buffer[j]='\\0'; j=0; for(i+=1;name[i]!='\\0';i++) { from[j]=name[i]; j++; } from[j-1]='\\0'; printf("To %s From %s Message %s",to,from,buffer); for(j=1;j<nu;j++) { if((strncmp(u[j].username,to,strlen(to)))==0) { newsockfd1=u[j].socket; break; } } strcat(from,buffer); bzero(buffer,256); strcpy(buffer,"From "); strcat(buffer,from); n=send(newsockfd1,buffer,sizeof buffer,0); if(n<0) { send(newsockfd, "SENDING FAILED : USER LOGGED OUT",32,0); } else { n = send(newsockfd, "Message sent", 18, 0); if (n<0) error("ERROR! Writing To Socket");} } close(newsockfd); pthread_exit(0); }
1
#include <pthread.h> void *productor(void *); void *consumidor(void *); void yield(); struct buffer_sync_s { int buffer[16 +1]; int pr,pw; pthread_mutex_t mutex; sem_t vacios; sem_t llenos; } buffer_sync; int main(int argc, char *argv[]) { pthread_t hilo_p, hilo_c; buffer_sync.pr = buffer_sync.pw = 0; pthread_mutex_init(&buffer_sync.mutex, 0); sem_init(&buffer_sync.vacios, 0, 16); sem_init(&buffer_sync.llenos, 0, 0); pthread_create(&hilo_p, 0, productor, 0); pthread_create(&hilo_c, 0, consumidor, 0); pthread_join(hilo_p, 0); pthread_join(hilo_c, 0); sem_destroy(&buffer_sync.llenos); sem_destroy(&buffer_sync.vacios); pthread_mutex_destroy(&buffer_sync.mutex); return 0; } void yield(void) { if (rand()%2) sched_yield(); } void *productor(void *arg) { int i; for(i=0; i<20; i++) { yield(); sem_wait(&buffer_sync.vacios); yield(); pthread_mutex_lock(&buffer_sync.mutex); yield(); buffer_sync.buffer[buffer_sync.pw] = i; yield(); buffer_sync.pw = (buffer_sync.pw+1) % (16 +1); yield(); printf("< %5d\\n",i); yield(); pthread_mutex_unlock(&buffer_sync.mutex); yield(); sem_post(&buffer_sync.llenos); yield(); } pthread_exit(0); } void *consumidor(void *arg) { int i; int a; for(i=0; i<20; i++) { yield(); sem_wait(&buffer_sync.llenos); yield(); pthread_mutex_lock(&buffer_sync.mutex); yield(); a = buffer_sync.buffer[buffer_sync.pr]; yield(); buffer_sync.pr = (buffer_sync.pr+1) % (16 +1); yield(); printf("> %5d\\n",a); yield(); pthread_mutex_unlock(&buffer_sync.mutex); yield(); sem_post(&buffer_sync.vacios); yield(); } pthread_exit(0); }
0
#include <pthread.h> struct tex_circle tex_circles[TEX_CIRCLES_MAX]; unsigned int tex_circle_draw_order[TEX_CIRCLES_MAX]; struct tex_circle tex_ripples[TEX_CIRCLES_MAX]; int sizeof_tex_circles_e = sizeof(tex_circles)/sizeof(tex_circles[0]); int sizeof_tex_circles = sizeof(tex_circles); void step_tex_circle_draw_order(); struct vertex tex_circle_v[] = { {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}, }; unsigned short tex_circle_i[] = { 0, 1, 3, 2 }; int sizeof_tex_circle_v = sizeof tex_circle_v; int sizeof_tex_circle_i = sizeof tex_circle_i; void init_tex_circles() { int i; for(i=0;i<sizeof_tex_circles_e;i++) { tex_circles[i].is_alive = FALSE; tex_circles[i].tex = (textures + 10); tex_ripples[i].tex = (textures + 10); tex_ripples[i].is_alive = FALSE; tex_circle_draw_order[i] = i; (tex_circles + i)->rgb = (struct vertex_rgb*)malloc(sizeof(struct vertex_rgb*)); (tex_ripples + i)->rgb = (struct vertex_rgb*)malloc(sizeof(struct vertex_rgb*)); } } void step_tex_circle_draw_order() { int i; for(i=0;i<sizeof_tex_circles_e;i++) { if (tex_circle_draw_order[i] < sizeof_tex_circles_e) tex_circle_draw_order[i]++; if (tex_circle_draw_order[i] == sizeof_tex_circles_e) tex_circle_draw_order[i] = 0; } } void activate_tex_circle(float x, float y, struct vertex_rgb* rgb_p, float* vel) { pthread_mutex_lock(&frame_mutex); step_tex_circle_draw_order(); struct tex_circle* ts = tex_circles + (tex_circle_draw_order[sizeof_tex_circles_e -1]); ts->pos_x = ((x/(float)g_sc.width)*2)-1; ts->pos_y = ((1.0F - (y/(float)g_sc.height))*2)-1; struct vertex_rgb* rgb_c = (moods+selected_mood)->rgb_circ; struct vertex_rgb* rgb_m = (moods+selected_mood)->rgb_circ_mask; ts->rgb->r = rgb_c->r * (1.0f - (rgb_p->r*rgb_m->r)); ts->rgb->g = rgb_c->g * (1.0f - (rgb_p->g*rgb_m->g)); ts->rgb->b = rgb_c->b * (1.0f - (rgb_p->b*rgb_m->b)); LOGD("activate_tex_circle", "rgb_p->r: %f, g: %f, b: %f", rgb_p->r, rgb_p->g, rgb_p->b); ts->alpha = 0.0F; ts->scale = *vel * *vel * 1.7; ts->scale_change_rate = (0.1/(float)SEC_IN_US); ts->alpha_max = ts->scale / 2.0; ts->alpha_fade_in = (3.6/(float)SEC_IN_US); ts->alpha_fade_out = (0.205/(float)SEC_IN_US); ts->fading_in = TRUE; ts->is_alive = TRUE; struct tex_circle* tr = tex_ripples + (tex_circle_draw_order[sizeof_tex_circles_e -1]); tr->pos_x = ((x/(float)g_sc.width)*2)-1; tr->pos_y = ((1.0F - (y/(float)g_sc.height))*2)-1; tr->rgb = (moods + selected_mood)->rgb_circ; tr->alpha = 0.0F; tr->scale = *vel * *vel * 1.7; tr->scale_change_rate = (1.8/(float)SEC_IN_US); tr->alpha_max = *vel; if (tr->alpha_max >= 1.0) tr->alpha_max = 1.0; tr->alpha_fade_in = (3.6/(float)SEC_IN_US); tr->alpha_fade_out = 0.94f; tr->fading_in = TRUE; tr->is_alive = TRUE; pthread_mutex_unlock(&frame_mutex); } void activate_tex_no_ammo(float x, float y, float* vel) { pthread_mutex_lock(&frame_mutex); step_tex_circle_draw_order(); struct tex_circle* ts = tex_circles + (tex_circle_draw_order[sizeof_tex_circles_e -1]); ts->pos_x = ((x/(float)g_sc.width)*2)-1; ts->pos_y = ((1.0F - (y/(float)g_sc.height))*2)-1; struct vertex_rgb* rgb = no_ammo_touch_rgb; ts->rgb->r = rgb->r; ts->rgb->g = rgb->g; ts->rgb->b = rgb->b; LOGD("activate_touch_no_ammo", "rgb->r: %f, g: %f, b: %f", rgb->r, rgb->g, rgb->b); ts->alpha = 0.0F; ts->scale = 1.2f; ts->scale_change_rate = (3.0/(float)SEC_IN_US); ts->alpha_fade_in = (3.6/(float)SEC_IN_US); ts->alpha_fade_out = (5.0/(float)SEC_IN_US); ts->alpha_max = ts->scale / 2.0; ts->fading_in = TRUE; ts->is_alive = TRUE; pthread_mutex_unlock(&frame_mutex); } void tex_circle_alpha_size(struct tex_circle* ts) { ts->scale -= (float)frame_delta * ts->scale_change_rate; if (ts->fading_in) { ts->alpha += (float)frame_delta * ts->alpha_fade_in; if (ts->alpha >= ts->alpha_max) ts->fading_in = FALSE; } if (!ts->fading_in) { ts->alpha -= (float)frame_delta * ts->alpha_fade_out; if (ts->alpha <= 0) ts->is_alive = FALSE; } } void tex_ripple_alpha_size(struct tex_circle* tr) { tr->scale += (float)frame_delta * tr->scale_change_rate; if (tr->fading_in) { tr->alpha += (float)frame_delta * tr->alpha_fade_in; if (tr->alpha >= (tr->alpha_max * 0.95)) tr->fading_in = FALSE; } if (!tr->fading_in) { tr->alpha *= tr->alpha_fade_out; if (tr->alpha < 0.005) tr->is_alive = FALSE; } } void kill_all_tex_circles() { int i; for (i=0; i<sizeof_tex_circles_e; i++) { struct tex_circle* ts = tex_circles + i; ts->is_alive = FALSE; } } void calc_tex_circle_vertex() { float tex_h = TEX_TO_W_RATIO/g_sc.hw_ratio; float y_b = 0.0f - (tex_h/2.0f); float y_t = 0.0f + (tex_h/2.0f); float x_l = 0.0f - (TEX_TO_W_RATIO/2.0f); float x_r = 0.0f + (TEX_TO_W_RATIO/2.0f); tex_circle_v[0].x = x_l; tex_circle_v[0].y = y_b; tex_circle_v[1].x = x_r; tex_circle_v[1].y = y_b; tex_circle_v[2].x = x_r; tex_circle_v[2].y = y_t; tex_circle_v[3].x = x_l; tex_circle_v[3].y = y_t; }
1
#include <pthread.h> int buffer[100] = { 0 }; int front = 0, rear = -1; int size = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t empty_cond = PTHREAD_COND_INITIALIZER; pthread_cond_t full_cond = PTHREAD_COND_INITIALIZER; bool producer_wait = 0; bool consumer_wait = 0; void *producer(void *arg); void *consumer(void *arg); int main(int argc, char **argv) { pthread_t producer_id; pthread_t consumer_id; pthread_create(&producer_id, 0, producer, 0); pthread_create(&consumer_id, 0, consumer, 0); sleep(1); return 0; } void *producer(void *arg) { pthread_detach(pthread_self()); while (1) { pthread_mutex_lock(&mutex); if (size == 100) { printf("buffer is full. producer is waiting...\\n"); producer_wait = 1; pthread_cond_wait(&full_cond, &mutex); producer_wait = 0; } rear = (rear + 1) % 100; buffer[rear] = rand() % 100; printf("producer produces the item %d: %d\\n", rear, buffer[rear]); ++size; if (size == 1) { while (1) { if (consumer_wait) { pthread_cond_signal(&empty_cond); break; } } } pthread_mutex_unlock(&mutex); } } void *consumer(void *arg) { pthread_detach(pthread_self()); while (1) { pthread_mutex_lock(&mutex); if (size == 0) { printf("buffer is empty. consumer is waiting...\\n"); consumer_wait = 1; pthread_cond_wait(&empty_cond, &mutex); consumer_wait = 0; } printf("consumer consumes an item%d: %d\\n", front, buffer[front]); front = (front + 1) % 100; --size; if (size == 100 -1) { while (1) { if (producer_wait) { pthread_cond_signal(&full_cond); break; } } } pthread_mutex_unlock(&mutex); } }
0
#include <pthread.h> struct account{ int balance; int credits; int debits; pthread_mutex_t lock; }; struct account accounts[10]; void * transactions(void * args){ int i,v; int a1,a2; for(i=0;i<100;i++){ v = (int) random() % 100; a1 = (int) random() % 10; while((a2 = (int) random() % 10) == a1); pthread_mutex_lock(&accounts[a1].lock); pthread_mutex_lock(&accounts[a2].lock); accounts[a1].balance += v; accounts[a1].credits += v; accounts[a2].balance -= v; accounts[a2].debits += v; pthread_mutex_unlock(&accounts[a1].lock); pthread_mutex_unlock(&accounts[a2].lock); } return 0; } int main(int argc, char * argv[]){ int n_threads,i; pthread_t * threads; if(argc < 2){ fprintf(stderr, "ERROR: Require number of threads\\n"); exit(1); } n_threads = atol(argv[1]); if(n_threads <= 0){ fprintf(stderr, "ERROR: Invalivd value for number of threads\\n"); exit(1); } threads = calloc(n_threads, sizeof(pthread_t)); for(i=0;i<10;i++){ accounts[i].balance=1000; accounts[i].credits=0; accounts[i].debits=0; pthread_mutex_init(&accounts[i].lock, 0); } for(i=0;i<n_threads;i++){ pthread_create(&threads[i], 0, transactions, 0); } for(i=0;i<n_threads;i++){ pthread_join(threads[i], 0); } for(i=0;i<10;i++){ printf("ACCOUNT %d: %d (%d)\\n", i, accounts[i].balance, 1000 +accounts[i].credits-accounts[i].debits); } free(threads); for(i=0;i<10;i++){ pthread_mutex_destroy(&accounts[i].lock); } }
1
#include <pthread.h> int array[] = {1,3,2,4,5,7,6,9,10,11,12,13,0,3,7,8,1,3,5,7,9,2,4,6,8,0,1,2,3,4,5,6,7,8}; int length = sizeof(array)/sizeof(array[0]); int shared_index = 0; pthread_mutex_t shared_index_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t shared_index_cv = PTHREAD_COND_INITIALIZER; void thread_1(void *ptr) { while (1) { sleep(1); pthread_mutex_lock(&shared_index_lock); pthread_cond_signal(&shared_index_cv); pthread_cond_wait(&shared_index_cv, &shared_index_lock); while (shared_index < length && array[shared_index] % 2 == 1) { printf("Thread_name = odd_thread shared_index = %d\\n", array[shared_index]); shared_index++; } pthread_cond_signal(&shared_index_cv); pthread_mutex_unlock(&shared_index_lock); } } void thread_2(void *ptr) { while (1) { sleep(1); pthread_mutex_lock(&shared_index_lock); pthread_cond_signal(&shared_index_cv); pthread_cond_wait(&shared_index_cv, &shared_index_lock); while (shared_index < length && array[shared_index] % 2 == 0) { printf("Thread_name = even_thread shared_index = %d\\n", array[shared_index]); shared_index++; } pthread_cond_signal(&shared_index_cv); pthread_mutex_unlock(&shared_index_lock); } } int main(int argc, char **argv) { int i; int rc = (-1); pthread_t thread[2]; printf("size: %d\\n", length); pthread_create(&thread[0], 0, (void *) &thread_1, 0); pthread_create(&thread[1], 0, (void *) &thread_2, 0); for(i = 0; i < 2; i++) { pthread_join(thread[i], 0); } rc = pthread_mutex_destroy(&shared_index_lock); if (rc) { printf("Unable to destroy lock = main_thread\\n"); } rc = pthread_cond_destroy(&shared_index_cv); if (rc) { printf("Unable to destroy cv = main_thread\\n"); } return 0; }
0
#include <pthread.h> pthread_cond_t table_free_cv, sticks_cv[5]; pthread_mutex_t monitor = PTHREAD_MUTEX_INITIALIZER; int is_eating[5] = {0}; int table_free = 2, sticks[5] = {1, 1, 1, 1, 1}; void print_status () { int i; for (i=0 ; i<5 ; ++i) if (is_eating[i]) printf ("jede\\t"); else printf ("misli\\t"); printf ("\\n"); } void enter_monitor (int i) { pthread_mutex_lock (&monitor); while (table_free == 0) pthread_cond_wait (&table_free_cv, &monitor); --table_free; while (sticks[i] == 0) pthread_cond_wait (&sticks_cv[i], &monitor); --sticks[i]; while (sticks[(i + 1) % 5] == 0) pthread_cond_wait (&sticks_cv[(i + 1) % 5], &monitor); --sticks[(i + 1) % 5]; is_eating[i] = 1; pthread_mutex_unlock (&monitor); } void leave_monitor (int i) { pthread_mutex_lock (&monitor); is_eating[i] = 0; sticks[i] = sticks [(i + 1) % 5] = 1; ++table_free; pthread_cond_broadcast (&sticks_cv[i]); pthread_cond_broadcast (&sticks_cv[(i + 1) % 5]); pthread_cond_broadcast (&table_free_cv); pthread_mutex_unlock (&monitor); } void *philosoph (void *param) { int i = *((int *) param); srand ((unsigned) time (0)); while (1) { sleep (1 + rand() % 2); enter_monitor (i); print_status (); sleep (1 + rand() % 1); leave_monitor (i); } } int main () { int i, philosoph_id[5]; pthread_t thread_id[5]; pthread_cond_init (&table_free_cv, 0); for (i=0 ; i<5 ; ++i) pthread_cond_init (&sticks_cv[i], 0); printf ("----------------------------------------\\n"); for (i=0 ; i<5 ; ++i) { philosoph_id[i] = i; pthread_create (&thread_id[i], 0, philosoph, &philosoph_id[i]); } for (i=0 ; i<5 ; ++i) pthread_join (thread_id[i], 0); return 0; }
1
#include <pthread.h> int memory[(2*320+1)]; int next_alloc_idx = 1; pthread_mutex_t m; int top; int index_malloc(){ int curr_alloc_idx = -1; pthread_mutex_lock(&m); if(next_alloc_idx+2-1 > (2*320+1)){ pthread_mutex_unlock(&m); curr_alloc_idx = 0; }else{ curr_alloc_idx = next_alloc_idx; next_alloc_idx += 2; pthread_mutex_unlock(&m); } return curr_alloc_idx; } void EBStack_init(){ top = 0; } int isEmpty() { if(top == 0) return 1; else return 0; } int push(int d) { int oldTop = -1, newTop = -1; newTop = index_malloc(); if(newTop == 0){ return 0; }else{ memory[newTop+0] = d; pthread_mutex_lock(&m); oldTop = top; memory[newTop+1] = oldTop; top = newTop; pthread_mutex_unlock(&m); return 1; } } void init(){ EBStack_init(); } void __VERIFIER_atomic_assert(int r) { __atomic_begin(); assert(!r || !isEmpty()); __atomic_end(); } void push_loop(){ int r = -1; int arg = __nondet_int(); while(1){ r = push(arg); __VERIFIER_atomic_assert(r); } } pthread_mutex_t m2; int state = 0; void* thr1(void* arg) { pthread_mutex_lock(&m2); switch(state) { case 0: EBStack_init(); state = 1; case 1: pthread_mutex_unlock(&m2); push_loop(); break; } return 0; } int main() { pthread_t t1,t2; pthread_create(&t1, 0, thr1, 0); pthread_create(&t2, 0, thr1, 0); return 0; }
0
#include <pthread.h> int buffer[10]; pthread_mutex_t mutex; sem_t emptyCount; sem_t fillCount; int produceItem() { return rand(); } void putItemIntoBuffer(int item) { int pos; sem_getvalue(&fillCount, &pos); buffer[pos] = item; } int removeItemFromBuffer() { int pos; sem_getvalue(&fillCount, &pos); return buffer[pos]; } void consumeItem(int item) { } void* producer(void* t) { long tid = (long) t; while (1) { int item = produceItem(); sem_wait(&emptyCount); pthread_mutex_lock(&mutex); putItemIntoBuffer(item); pthread_mutex_unlock(&mutex); sem_post(&fillCount); printf("Producer added: %d\\n", item); } pthread_exit(0); } void* consumer(void* t) { long tid = (long) t; while (1) { sem_wait(&fillCount); pthread_mutex_lock(&mutex); int item = removeItemFromBuffer(); pthread_mutex_unlock(&mutex); sem_post(&emptyCount); consumeItem(item); printf("Consumer removed: %d\\n", item); } pthread_exit(0); } int main() { pthread_mutex_init(&mutex, 0); sem_init(&emptyCount, 0, 10); sem_init(&fillCount, 0, 0); srand(time(0)); int i; for (i = 0; i < 10; ++i) { buffer[i] = 0; } long tid_prod = 0, tid_cons = 1; pthread_t prod_thread; pthread_create(&prod_thread, 0, producer, (void*)tid_prod); pthread_t cons_thread; pthread_create(&cons_thread, 0, consumer, (void*)tid_cons); void* result; pthread_join(prod_thread, &result); pthread_join(cons_thread, &result); sem_destroy(&emptyCount); sem_destroy(&fillCount); pthread_exit(0); }
1
#include <pthread.h> int TA_Sleeping; sem_t semTA; sem_t chairs; pthread_mutex_t Helpmutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t TAcreated = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t helping = PTHREAD_MUTEX_INITIALIZER; void helpStudent(){ while(1){ int availableChairs; sem_getvalue(&chairs,&availableChairs); if(availableChairs == 3){TA_Sleeping = 1;printf("The TA is sleeping\\n");} sem_wait(&semTA); sleep(2); pthread_mutex_unlock(&helping); } } void getHelp(long studentID){ if(TA_Sleeping){ TA_Sleeping = 0; printf("Student %lu woke up the TA\\n",studentID); sem_post(&semTA); pthread_mutex_unlock(&Helpmutex); pthread_mutex_lock(&helping); } else{ int availableChairs; sem_getvalue(&chairs,&availableChairs); if(availableChairs == 3){ sem_wait(&chairs); printf("Student %lu took a seat in chair 1\\n",studentID); pthread_mutex_unlock(&Helpmutex); sem_post(&semTA); pthread_mutex_lock(&helping); printf("TA is Helping a student %lu\\n", studentID); sem_post(&chairs); printf("Chair 1 is now open\\n"); } if(availableChairs == 2){ sem_wait(&chairs); printf("Student %lu took a seat in chair 2\\n",studentID); pthread_mutex_unlock(&Helpmutex); sem_post(&semTA); pthread_mutex_lock(&helping); printf("TA is Helping a student %lu\\n", studentID); sem_post(&chairs); printf("Chair 2 is now open\\n"); } if(availableChairs == 1){ sem_wait(&chairs); printf("Student %lu took a seat in chair 3\\n",studentID); pthread_mutex_unlock(&Helpmutex); sem_post(&semTA); pthread_mutex_lock(&helping); printf("TA is Helping a student %lu\\n", studentID); sem_post(&chairs); printf("Chair 3 is now open\\n"); } if(availableChairs == 0){ printf("Student %lu went back to programming\\n",studentID); pthread_mutex_unlock(&Helpmutex);} } } void *initTA(){ sem_init(&semTA,0,0); sem_init(&chairs,0,3); TA_Sleeping = 1; pthread_mutex_unlock(&TAcreated); helpStudent(); } void *initStudent(void *t){ pthread_mutex_lock(&Helpmutex); long id = (long)t; getHelp(id); } int main(int argc,char **argv){ int n = 6; int ret; pthread_mutex_lock(&TAcreated); pthread_t TA; ret = pthread_create(&TA,0,initTA,0); pthread_mutex_lock(&TAcreated); long t; pthread_t threads[n]; for(t = 0; t<n;t++){ ret = pthread_create(&threads[t],0,initStudent,(void *)t); } for(t = 0; t<n;t++){ pthread_join(threads[t],0); } pthread_join(TA,0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex[3]; int firstIndex; int secondIndex; } Indexes; Indexes additionalThreadIndexes[3] = {{0, 1}, {2, 0}, {1, 2}}; Indexes mainThreadIndexes[3] = {{2, 0}, {1, 2}, {0, 1}}; void* doIt(void *arg) { pthread_mutex_lock(&mutex[0]); pthread_mutex_lock(&mutex[2]); for (int i = 0; i < 10; ++i) { printf("Additional Thread - %d\\n", i); pthread_mutex_unlock(&mutex[additionalThreadIndexes[i % 3].firstIndex]); pthread_mutex_lock(&mutex[additionalThreadIndexes[i % 3].secondIndex]); } pthread_exit(0); } int main() { for (int k = 0; k < 3; ++k) { pthread_mutex_init(&mutex[k], 0); } pthread_t thread; int resultOfThreadCreation = pthread_create(&thread, 0, doIt, 0); if (0 != resultOfThreadCreation) { perror("Error while cretaing thread"); exit(0); } pthread_mutex_lock(&mutex[1]); pthread_mutex_lock(&mutex[2]); usleep(1000); for (int i = 0; i < 10; ++i) { pthread_mutex_unlock(&mutex[mainThreadIndexes[i % 3].firstIndex]); pthread_mutex_lock(&mutex[mainThreadIndexes[i % 3].secondIndex]); printf("Main Thread - %d\\n", i); } for (int k = 0; k < 3; ++k) { pthread_mutex_destroy(&mutex[k]); } }
1
#include <pthread.h> int sem_post(sem_t *sem) { int result = 0; if (!sem) { result = EINVAL; } else if (!pthread_mutex_lock(&sem->mutex)) { if (++(sem->value) <= 0) { pthread_cond_signal(&(sem->cond)); } pthread_mutex_unlock(&sem->mutex); } else { result = EINVAL; } if (result) { errno = result; return -1; } return 0; }
0
#include <pthread.h> extern unsigned volatile int *lock; FILE *fileout_pbm_stringsearch; FILE *fileout_bmh_stringsearch; FILE *fileout_fft; FILE* fileout_adpcmencoder; FILE* filein_adpcmencoder; volatile int procCounter = 0; volatile int barrier_in = 0; volatile int procsFinished = 0; extern pthread_mutex_t mutex_print; extern pthread_mutex_t mutex_malloc; int NSOFTWARES = 4; void open_files(); void close_files(); int main(int argc, char *argv[]) { register int procNumber; AcquireGlobalLock(); procNumber = procCounter++; ReleaseGlobalLock(); if (procNumber == 0){ printf("\\n"); printf("--------------------------------------------------------------------\\n"); printf("------------------------- MPSoCBench -----------------------------\\n"); printf("-----------------Running: multi_office_telecomm --------------------\\n"); printf("---------PBM_stringsearch, BMH_stringsearch, FFT, ADPCM-------------\\n"); printf("--------------------------------------------------------------------\\n"); printf("\\n"); open_files(); pthread_mutex_init(&mutex_print,0); pthread_mutex_init(&mutex_malloc,0); AcquireGlobalLock(); barrier_in = 1; ReleaseGlobalLock(); main_bmh_stringsearch(); pthread_mutex_lock(&mutex_print); printf("\\nStringsearch Boyer-Moore-Horspool finished.\\n"); pthread_mutex_unlock(&mutex_print); } else if (procNumber == 1) { while(barrier_in == 0); main_pbm_stringsearch(); pthread_mutex_lock(&mutex_print); printf("\\nStringsearch Pratt-Boyer-Moore finished.\\n"); pthread_mutex_unlock(&mutex_print); } else if (procNumber == 2) { while(barrier_in == 0); main_fft(); pthread_mutex_lock(&mutex_print); printf("\\nFFT finished.\\n"); pthread_mutex_unlock(&mutex_print); } else if (procNumber == 3) { while(barrier_in == 0); main_adpcmencoder(); pthread_mutex_lock(&mutex_print); printf("\\nAdpcm Encoder finished.\\n"); pthread_mutex_unlock(&mutex_print); } else { printf("\\nERROR!\\n"); } AcquireGlobalLock(); procsFinished++; if(procsFinished == NSOFTWARES) { close_files(); } ReleaseGlobalLock(); _exit(0); return 0; } void close_files () { fclose(fileout_adpcmencoder); fclose(fileout_pbm_stringsearch); fclose(fileout_fft); fclose(fileout_bmh_stringsearch); } void open_files () { fileout_pbm_stringsearch = fopen("output_pbm_stringsearch","w"); if (fileout_pbm_stringsearch == 0){ printf("Error: fopen() fileout_pbm_stringsearch\\n"); exit(1); } fileout_bmh_stringsearch = fopen("output_bmh_stringsearch","w"); if (fileout_bmh_stringsearch == 0){ printf("Error: fopen() fileout_bmh_stringsearch\\n"); exit(1); } fileout_fft = fopen("output_fft","w"); if (fileout_fft == 0){ printf("Error: fopen() fileout_fft\\n"); exit(1); } fileout_adpcmencoder = fopen("output_adpcm","w"); if (fileout_adpcmencoder == 0){ printf("Error: fopen() fileout_adpcmencoder\\n"); exit(1); } filein_adpcmencoder = fopen("inputencoder.pcm","r"); if (filein_adpcmencoder == 0){ printf("Error: fopen() filein_adpcmencoder\\n"); exit(1); } }
1
#include <pthread.h> struct argumentos{ int *cont; pthread_mutex_t *mutex; }; void *incrementa(void *arg){ ARGS *para = (ARGS *) arg; int *p = para->cont; pthread_mutex_t *m = para->mutex; int i; for(i=0; i<100000; i++){ pthread_mutex_lock(m); (*p)++; pthread_mutex_unlock(m); } } int main(){ pthread_t tid[1]; int i, cont = 0; ARGS argumentos; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; argumentos.cont = &cont; argumentos.mutex = &mutex; for (i=0; i<1; i++){ pthread_create(&tid[i], 0, incrementa, &argumentos); } for (i=0; i<1; i++){ pthread_join(tid[i],0); } printf("Cont: %d\\n", cont); }
0
#include <pthread.h> int g_sum = 0; int g_min = 32767; int g_minX = -1; int g_minY = -1; int g_max = INT_MIN; int g_maxX = -1; int g_maxY = -1; pthread_mutex_t lock; int numWorkers; double startTime, endTime; int size, stripSize; int matrix[10000][10000]; void *Worker(void *); double readTimer(); int main(int argc, char *argv[]) { int i, j; long l; pthread_attr_t attr; pthread_t workerid[10]; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&lock, 0); size = (argc > 1)? atoi(argv[1]) : 10000; numWorkers = (argc > 2)? atoi(argv[2]) : 10; if (size > 10000) size = 10000; if (numWorkers > 10) numWorkers = 10; stripSize = size/numWorkers; for (i = 0; i < size; i++) { for (j = 0; j < size; j++) { matrix[i][j] = rand()%99; } } for (i = 0; i < size; i++) { printf("[ "); for (j = 0; j < size; j++) { printf(" %d", matrix[i][j]); } printf(" ]\\n"); } startTime = readTimer(); for (l = 0; l < numWorkers; l++) { pthread_create(&workerid[l], &attr, Worker, (void *) l); } for (l = 0; l < numWorkers; l++) { void * status; int rc = pthread_join(workerid[l], &status); if(rc) { printf("ERROR; return code from pthread_join() is %d\\n", rc); exit(-1); } printf("Main: completed join with worker %ld (pthread id %lu) having a status of %ld\\n", l, workerid[l], (long)status); } printf("The total is %d\\n", g_sum); printf("The min element is %d at (%d , %d)\\n", g_min, g_minX, g_minY); printf("The max element is %d at (%d , %d)\\n", g_max, g_maxX, g_maxY); endTime = readTimer(); printf("The execution time is %g sec\\n", endTime - startTime); return 0; } void *Worker(void *arg) { long myid = (long) arg; int total, min, minX, minY, max, maxX, maxY, i, j, first, last; printf("worker %ld (pthread id %lu) has started\\n", myid, pthread_self()); first = myid*stripSize; last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1); total = 0; min = 32767; max = INT_MIN; for (i = first; i <= last; i++) { for (j = 0; j < size; j++) { if(matrix[i][j] < min) { min = matrix[i][j]; minX = j; minY = i; } else if(matrix[i][j] > max) { max = matrix[i][j]; maxX = j; maxY = i; } total += matrix[i][j]; } } pthread_mutex_lock(&lock); if(min < g_min) { g_min = min; g_minX = minX; g_minY = minY; } if(max > g_max) { g_max = max; g_maxX = maxX; g_maxY = maxY; } g_sum += total; pthread_mutex_unlock(&lock); pthread_exit(0); } double readTimer() { static bool initialized = 0; static struct timeval start; struct timeval end; if( !initialized ) { gettimeofday( &start, 0 ); initialized = 1; } gettimeofday( &end, 0 ); return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); }
1
#include <pthread.h> int PBSD_msg_put( int c, char *jobid, int fileopt, char *msg, char *extend) { int rc = 0; int sock; struct tcp_chan *chan = 0; pthread_mutex_lock(connection[c].ch_mutex); sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_MessJob,pbs_current_user)) || (rc = encode_DIS_MessageJob(chan, jobid, fileopt, msg)) || (rc = encode_DIS_ReqExtend(chan, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return (PBSE_PROTOCOL); } pthread_mutex_unlock(connection[c].ch_mutex); if (DIS_tcp_wflush(chan)) { rc = PBSE_PROTOCOL; } DIS_tcp_cleanup(chan); return(rc); }
0
#include <pthread.h> pthread_mutex_t mutex_1; pthread_mutex_t mutex_2; void *child1(void *arg) { while (1) { pthread_mutex_lock(&mutex_1); sleep(3); pthread_mutex_lock(&mutex_2); printf("thread 1 get running\\n"); pthread_mutex_unlock(&mutex_2); pthread_mutex_unlock(&mutex_1); sleep(5); } } void *child2(void *arg) { while (1) { pthread_mutex_lock(&mutex_2); pthread_mutex_lock(&mutex_1); printf("thread 2 get running\\n"); pthread_mutex_unlock(&mutex_1); pthread_mutex_unlock(&mutex_2); sleep(5); } } int main(int argc, char *argv[]) { pthread_t tid1, tid2; pthread_mutex_init(&mutex_1, 0); pthread_mutex_init(&mutex_2, 0); pthread_create(&tid1, 0, child1, 0); pthread_create(&tid2, 0, child2, 0); if (tid1 != 0) { pthread_join(tid1, 0); printf("线程1已经结束\\n"); } if (tid2 != 0) { pthread_join(tid2, 0); printf("线程2已经结束\\n"); } printf("=================thread_wait end==================\\n"); return 0; }
1
#include <pthread.h> pthread_mutex_t the_mutex; pthread_cond_t condc, condp; int buffer = 0; void* producer(void *ptr) { int i; for (i = 1; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while (buffer != 0) pthread_cond_wait(&condp, &the_mutex); buffer = i; printf("P: buffer=%d\\n",i); pthread_cond_signal(&condc); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } void* consumer(void *ptr) { int i; for (i = 1; i <= 10; i++) { pthread_mutex_lock(&the_mutex); while (buffer == 0) pthread_cond_wait(&condc, &the_mutex); buffer = 0; printf("C: buffer=%d\\n",i); pthread_cond_signal(&condp); pthread_mutex_unlock(&the_mutex); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; pthread_mutex_init(&the_mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); pthread_create(&con, 0, consumer, 0); pthread_create(&pro, 0, producer, 0); pthread_join(con, 0); pthread_join(pro, 0); pthread_mutex_destroy(&the_mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
0
#include <pthread.h> struct node_t { int length; char data[80]; struct node_t *next; pthread_mutex_t mut; } head; void* sort_loop(void* param) { struct node_t *prev, *cur0, *cur1; int mess; while (1) { sleep(5); mess = 1; while (mess) { mess = 0; prev = &head; pthread_mutex_lock(&(prev->mut)); cur0 = head.next; if (cur0) { pthread_mutex_lock(&(cur0->mut)); cur1 = cur0->next; while (cur1) { pthread_mutex_lock(&(cur1->mut)); if (strcmp(cur1->data, cur0->data) < 0) { mess = 1; cur0->next = cur1->next; prev->next = cur1; cur1->next = cur0; cur0 = cur1; cur1 = cur0->next; } pthread_mutex_unlock(&(prev->mut)); prev = cur0; cur0 = cur1; cur1 = cur1->next; } pthread_mutex_unlock(&(cur0->mut)); } pthread_mutex_unlock(&(prev->mut)); } } return 0; } int main() { char buffer[4096]; int buflen = 0, bufpos = 0; struct node_t *cur, *pos, *prev; pthread_t sorting_thread; cur = (struct node_t*)malloc(sizeof(struct node_t)); pthread_mutex_init(&(cur->mut),0); cur->length = 0; pthread_mutex_init(&(head.mut), 0); head.next = 0; head.length = 0; pthread_create(&sorting_thread, 0, sort_loop, 0); while (1) { while (1) { if (bufpos == buflen) { buflen = read(0, buffer, 4096); if (buflen < 1) { break; } bufpos = 0; } if ((cur->data[cur->length] = buffer[bufpos++])=='\\n') break; cur->length++; if (cur->length == 80) break; } if (!cur->length) { prev = &head; pthread_mutex_lock(&(prev->mut)); pos = prev->next; while (pos) { pthread_mutex_lock(&(pos->mut)); pthread_mutex_unlock(&(prev->mut)); write(1, pos->data, pos->length); write(1, "\\n", 1); prev = pos; pos = pos->next; } pthread_mutex_unlock(&(prev->mut)); } else { pthread_mutex_lock(&(head.mut)); cur->next = head.next; head.next = cur; pthread_mutex_unlock(&(head.mut)); cur = (struct node_t*)malloc(sizeof(struct node_t)); pthread_mutex_init(&(cur->mut),0); cur->length = 0; } } return 0; }
1
#include <pthread.h> static int maxThreads; static int threadsTotal; static pthread_mutex_t fileMutex; static pthread_cond_t fileCond; void FileAccess(int n) { maxThreads = n - 1; threadsTotal = 0; pthread_mutex_init(&fileMutex, 0); pthread_cond_init(&fileCond, 0); } void* startAccess(void* obj) { pthread_mutex_lock(&fileMutex); int threadID = *(int*) obj; if(threadID > maxThreads) { printf("File Access Denied to Thread ID: %2d, ID number is too large.\\n", threadID); fflush(stdout); pthread_mutex_unlock(&fileMutex); return (void*) 0; } while((threadsTotal + threadID) > maxThreads) { pthread_cond_wait(&fileCond, &fileMutex); } threadsTotal += threadID; pthread_mutex_unlock(&fileMutex); printf("Thread ID: %2d starting file access. Sum of thread IDs: %2d.\\n", threadID, threadsTotal); fflush(stdout); endAccess(*(int*)obj); return (void*) 0; } void endAccess(int threadID) { pthread_mutex_lock(&fileMutex); threadsTotal -= threadID; printf("Thread ID: %2d ending file access. Sum of thread IDs: %2d.\\n", threadID, threadsTotal); fflush(stdout); pthread_mutex_unlock(&fileMutex); pthread_cond_signal(&fileCond); }
0
#include <pthread.h> pthread_cond_t cond_notFull = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_notEmpty = PTHREAD_COND_INITIALIZER; pthread_mutex_t bufferFull_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; int maxBufferSize = 1; int bufferSize = 0; int count = 0; void *produce(void *arg) { while (1) { pthread_mutex_lock(&bufferFull_mutex); while (bufferSize == maxBufferSize) { pthread_cond_wait(&cond_notFull, &bufferFull_mutex); } pthread_mutex_unlock(&bufferFull_mutex); pthread_mutex_lock(&count_mutex); ++count; ++bufferSize; pthread_cond_broadcast(&cond_notEmpty); if (count >= 10) { pthread_mutex_unlock(&count_mutex); break; } else { pthread_mutex_unlock(&count_mutex); } } pthread_exit(0); } void *consume(void *arg) { while (1) { pthread_mutex_lock(&bufferFull_mutex); while (bufferSize == 0) { pthread_cond_wait(&cond_notEmpty, &bufferFull_mutex); } pthread_mutex_unlock(&bufferFull_mutex); pthread_mutex_lock(&count_mutex); --bufferSize; pthread_cond_broadcast(&cond_notFull); if (count >= 10) { pthread_mutex_unlock(&count_mutex); break; } else { pthread_mutex_unlock(&count_mutex); } } pthread_exit(0); } int main(void) { int rc = 0; pthread_t producer, consumer; rc = pthread_create(&producer, 0, produce, 0); if (rc) { printf("Producer pthread_create failed with return code %d\\n", rc); exit(-1); } rc = pthread_create(&consumer, 0, consume, 0); if (rc) { printf("Consumer pthread_create failed with return code %d\\n", rc); exit(-1); } rc = pthread_join(producer, 0); if (rc) { printf("Producer pthread_join failed with return code %d\\n", rc); exit(-1); } rc= pthread_join(consumer, 0); if (rc) { printf("Consumer pthread_join failed with return code %d\\n", rc); exit(-1); } return 0; }
1
#include <pthread.h> int max(const int a, const int b) { return a > b ? a : b; } int largest = 0; pthread_mutex_t largest_mutex; void *thread_main(void *arg) { int cpu_nr = sched_getcpu(); pthread_mutex_lock(&largest_mutex); if (cpu_nr > largest) { largest = cpu_nr; } pthread_mutex_unlock(&largest_mutex); return 0; } pid_t calculate_processes(const int nr_threads) { pid_t pid = safe_fork(); if (pid == 0) { int i; pthread_t thr[nr_threads]; pthread_mutex_init(&largest_mutex, 0); for (i = 0; i < nr_threads; i++) { pthread_create(&thr[i], 0, thread_main, 0); } for (i = 0; i < nr_threads; i++) { pthread_join(thr[i], 0); } pthread_mutex_destroy(&largest_mutex); exit(largest); } return pid; } int main(int argc, char *argv[]) { int nr_threads = 25; pid_t processes[8]; while (1) { int i, previous, current; bool retry = 0; for (i = 0; i < 8; i++) { processes[i] = calculate_processes(nr_threads); } for (i = 0, previous = 0, current = 0; i < 8; i++) { waitpid(processes[i], &current, 0); current = WEXITSTATUS(current); largest = max(largest, current); if (previous && previous != current) { DEBUG_PRINT("Found different cores: %d != %d\\n", previous, current); nr_threads = (int)(nr_threads * 1.4); retry = 1; } previous = current; } if (!retry && largest >= max(current, previous)) { break; } } printf("%d\\n", largest + 1); return 0; }
0
#include <pthread.h> pthread_barrier_t barrier; pthread_mutex_t consoleMutex; struct CalculateExpArgs { double value; unsigned int maxNumberOfOperations; double result; }; void CalculateExp(struct CalculateExpArgs* args) { pthread_mutex_lock(&consoleMutex); printf("CalculateExp: argument is %f\\n", args->value); pthread_mutex_unlock(&consoleMutex); double exp = 1; double factorial = 1; double power; for (unsigned int i = 0; i < args->maxNumberOfOperations; i++) { power = i + 1; factorial *= power; exp += pow(args->value, power) / factorial; } args->result = exp; pthread_mutex_lock(&consoleMutex); printf("CalculateExp: done\\n"); pthread_mutex_unlock(&consoleMutex); pthread_barrier_wait(&barrier); } struct CalculatePiArgs { unsigned int maxNumberOfOperations; double result; }; void CalculatePi(struct CalculatePiArgs* args) { pthread_mutex_lock(&consoleMutex); printf("CalculatePi\\n"); pthread_mutex_unlock(&consoleMutex); double pi = 1.0; int numerator = 2; int denominator = 1; int numerator_counter = 0; int denominator_counter = 1; for (unsigned int i = 0; i < args->maxNumberOfOperations; i++) { if (numerator_counter == 2) { numerator_counter = 0; numerator += 2; } if (denominator_counter == 2) { denominator_counter = 0; denominator += 2; } numerator_counter++; denominator_counter++; pi *= ((double) numerator / (double) denominator); } args->result = pi; pthread_mutex_lock(&consoleMutex); printf("CalculatePi: done\\n"); pthread_mutex_unlock(&consoleMutex); pthread_barrier_wait(&barrier); } int main() { double x = 1.0; pthread_t thread_exp; pthread_t thread_pi; struct CalculateExpArgs expArgs; expArgs.value = (-pow(x,2.0)) / 2; expArgs.maxNumberOfOperations = 100000; struct CalculatePiArgs piArgs; piArgs.maxNumberOfOperations = 100000; pthread_barrier_init(&barrier, 0, 2); pthread_mutex_init(&consoleMutex, 0); if ( pthread_create(&thread_exp, 0, &CalculateExp, &expArgs) ) { pthread_mutex_lock(&consoleMutex); printf("Error launching exp thread"); pthread_mutex_unlock(&consoleMutex); return 2; } if ( pthread_create(&thread_pi, 0, &CalculatePi, &piArgs) ) { pthread_mutex_lock(&consoleMutex); printf("Error launching pi thread"); pthread_mutex_unlock(&consoleMutex); return 2; } pthread_join(thread_exp, 0); pthread_join(thread_pi, 0); pthread_barrier_destroy(&barrier); double result = expArgs.result / sqrt(2 * piArgs.result); pthread_mutex_lock(&consoleMutex); printf("Result:%f\\n", result); pthread_mutex_unlock(&consoleMutex); return 0; }
1
#include <pthread.h> extern pthread_mutex_t global_data_mutex; void update_humidity_data (int humidity_fd) { char humidity[6]; float realhumidity; int read_rc; lseek(humidity_fd,0,0); read_rc = read(humidity_fd,humidity,5); if(0 > read_rc) { close(humidity_fd); global_config.humidity_fd = -1; return; } realhumidity = atof(humidity); realhumidity -= 5.0; app_debug(debug, "Humidity:\\t%2.3f\\n",realhumidity); if ((realhumidity > (float)100) || (realhumidity < (float)0)) { app_debug(info, "Got garbage from the humidity sensor. Rejecting\\n"); } else { pthread_mutex_lock(&global_data_mutex); global_data.humidity = realhumidity; global_data.updatetime = time(0); pthread_mutex_unlock(&global_data_mutex); } }
0
#include <pthread.h> struct Message { struct Message *next; }; struct Message *work_queue; pthread_cond_t queue_ready = PTHREAD_COND_INITIALIZER; pthread_mutex_t queue_lock = PTHREAD_MUTEX_INITIALIZER; void process_message( void ) { struct Message *mp; while ( 1 ) { pthread_mutex_lock( &queue_lock ); while ( work_queue == 0 ) { pthread_cond_wait( &queue_ready, &queue_lock ); } mp = work_queue; work_queue = mp->next; pthread_mutex_unlock( &queue_lock ); } } void enqueue_message( struct Message *mp ) { pthread_mutex_lock( &queue_lock ); mp->next = work_queue; pthread_mutex_unlock( &queue_lock ); pthread_cond_signal( &queue_ready ); }
1
#include <pthread.h> extern int makethread(void *(*)(void *), void *); { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }to_info; void clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } void * timeout_helper(void *arg) { to_info *tip = 0; tip = (to_info *)arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn)(tip->to_arg); free(arg); return 0; } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; to_info *tip = 0; int err = 0; clock_gettime(0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = (to_info *)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 ; } else { free(tip); } } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err = 0; int condition = 0; int arg = 0; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) { err_exit(err, "pthread_mutexattr_init failed"); } if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) { err_exit(err, "can't set recursive type"); } if ((err = pthread_mutex_init(&mutex, &attr)) != 0) { err_exit(err, "can't create recursivek mutex"); } pthread_mutex_lock(&mutex); if (condition) { clock_gettime(0, &when); when.tv_sec += 3; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> static pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER; static int malloc_trim_count=0; static void mymalloc_install (void); static void mymalloc_uninstall (void); static void (*old_free_hook) (void *, const void *); static void myfree(void *ptr, const void *caller) { pthread_mutex_lock(&mymutex); malloc_trim_count++; if(malloc_trim_count%10000 == 0) { malloc_trim(0); } mymalloc_uninstall(); free(ptr); mymalloc_install(); pthread_mutex_unlock(&mymutex); } static void mymalloc_install (void) { old_free_hook = __free_hook; __free_hook = myfree; } static void mymalloc_uninstall (void) { __free_hook = old_free_hook; } void (*__malloc_initialize_hook) (void) = mymalloc_install;
1
#include <pthread.h> int printed_lines = 0; int lines_before[10]; int lines_after[10]; pthread_mutex_t mutex; pthread_t *threads; int n; int activated; void *send_output(void *arg) { int* idx = (int*)arg; lines_before[*idx] = printed_lines; int i; while(!activated) { usleep(500000); pthread_mutex_lock(&mutex); for (i=0; i < *idx+1; ++i) { printf("%c", 'a'+*idx); } printf("\\n"); printed_lines++; pthread_mutex_unlock(&mutex); } lines_after[*idx] = printed_lines - lines_before[*idx] - 1; pthread_exit(0); } void handler(int idx) { printf("Encerrando a aplicação. Aguardando a finalização de threads...\\n"); activated = 1; int i; for (i=0; i < n; ++i) { pthread_join(threads[i], 0); } printf("Aplicação encerrada com sucesso!\\nEstatísticas:\\n"); for (i=0; i < n; ++i) { printf("thread %d: %d linhas\\n", i+1, lines_after[i]); } } int main(int argc, char const *argv[]) { if (argc < 2) { printf("You need at least one parameter, and the first must be a number.\\n"); return 0; } else { if (!(argv[1][0]>='0' && argv[1][0]<='9')) { printf("The first argument must be a number.\\n"); return 0; } } n = atoi(argv[1]); if (n < 1) { printf("The first argument must be higher than zero.\\n"); return 0; } activated = 0; memset(lines_before, 0, sizeof lines_before); memset(lines_after, 0, sizeof lines_after); signal(SIGINT, handler); n = n > 10 ? 10 : n; threads = malloc(sizeof(pthread_t)*n); int elements[10], i; for (i=0; i < 10; ++i) { elements[i] = i; } for (i=0; i < n; ++i) { pthread_create(&threads[i], 0, send_output, &elements[i]); } while (!activated) {} free(threads); return 0; }
0
#include <pthread.h> void *lcthread(void *argv); int total_lines = 0; pthread_mutex_t total_line_lock = PTHREAD_MUTEX_INITIALIZER; main(int argc, char**argv) { pthread_t * t = malloc(500); int index_create; for(index_create = 1; index_create < argc; index_create++) { pthread_create(&t[index_create], 0, lcthread, (void *) argv[index_create]); } int index_join; for(index_join = 1; index_join < argc; index_join++) { pthread_join(t[index_join], 0); } printf("TOTAL LINES: %d\\n", total_lines); } void *lcthread(void *arg) { int fd = open((char *)arg, O_RDWR); struct stat buf; fstat(fd, &buf); int size = buf.st_size; char * loadedFileBuffer = malloc(size); read(fd, loadedFileBuffer, size); int j =0; int linecount = 0; while(1) { if(loadedFileBuffer[j] == '\\n') { linecount++; } else if(loadedFileBuffer[j] == '\\0') { printf("%d \\t\\t%s \\n", linecount, (char *)arg); break; } j++; } pthread_mutex_lock(&total_line_lock); total_lines += linecount; pthread_mutex_unlock(&total_line_lock); close(fd); }
1
#include <pthread.h> enum { NUMTHREADS = 3 }; struct bag_t_ { int threadnum; int started; }; static bag_t threadbag[NUMTHREADS + 1]; pthread_mutex_t stop_here = PTHREAD_MUTEX_INITIALIZER; void * mythread(void * arg) { bag_t * bag = (bag_t *) arg; assert(bag == &threadbag[bag->threadnum]); assert(bag->started == 0); bag->started = 1; errno = bag->threadnum; Sleep(1000); pthread_mutex_lock(&stop_here); assert(errno == bag->threadnum); pthread_mutex_unlock(&stop_here); Sleep(1000); return 0; } int main() { int failed = 0; int i; pthread_t t[NUMTHREADS + 1]; pthread_mutex_lock(&stop_here); errno = 0; assert((t[0] = pthread_self()).p != 0); for (i = 1; i <= NUMTHREADS; i++) { threadbag[i].started = 0; threadbag[i].threadnum = i; assert(pthread_create(&t[i], 0, mythread, (void *) &threadbag[i]) == 0); } Sleep(2000); pthread_mutex_unlock(&stop_here); Sleep(NUMTHREADS * 1000); for (i = 1; i <= NUMTHREADS; i++) { failed = !threadbag[i].started; if (failed) { fprintf(stderr, "Thread %d: started %d\\n", i, threadbag[i].started); } } assert(!failed); for (i = 1; i <= NUMTHREADS; i++) { } assert(!failed); return 0; }
0
#include <pthread.h> const size_t N_THREADS = 20; pthread_mutex_t mutex; struct timespec timeout; int use_timeout; void *run(void *arg) { int *argi = (int *) arg; int my_tidx = *argi; int retcode; printf("in child %d: sleeping\\n", my_tidx); sleep(2); if (use_timeout) { while (TRUE) { retcode = pthread_mutex_timedlock(&mutex, &timeout); if (retcode == 0) { break; } else if (retcode == ETIMEDOUT) { printf("timed out in child %d\\n", my_tidx); sleep(1); } else { handle_thread_error(retcode, "child failed timed lock", PROCESS_EXIT); } } } else { retcode = pthread_mutex_lock(&mutex); handle_thread_error(retcode, "child failed lock", PROCESS_EXIT); } printf("child %d got mutex\\n", my_tidx); sleep(5); printf("child %d releases mutex\\n", my_tidx); pthread_mutex_unlock(&mutex); printf("child %d released mutex\\n", my_tidx); sleep(10); printf("child %d exiting\\n", my_tidx); return 0; } void usage(char *argv0, char *msg) { printf("%s\\n\\n", msg); printf("Usage:\\n\\n%s\\n lock mutexes without lock\\n\\n%s -t <number>\\n lock mutexes with timout after given number of seconds\\n", argv0, argv0); exit(1); } int main(int argc, char *argv[]) { int retcode; use_timeout = (argc >= 2 && strcmp(argv[1], "-t") == 0); if (is_help_requested(argc, argv)) { usage(argv[0], ""); } timeout.tv_sec = (time_t) 200; timeout.tv_nsec = (long) 0; if (use_timeout && argc >= 3) { int t; sscanf(argv[2], "%d", &t); timeout.tv_sec = (time_t) t; } printf("timout(%ld sec %ld msec)\\n", (long) timeout.tv_sec, (long) timeout.tv_nsec); pthread_t thread[N_THREADS]; int tidx[N_THREADS]; for (size_t i = 0; i < N_THREADS; i++) { tidx[i] = (int) i; retcode = pthread_create(thread + i, 0, run, (void *) (tidx + i)); handle_thread_error(retcode, "creating thread failed", PROCESS_EXIT); } printf("in parent: setting up\\n"); pthread_mutex_init(&mutex, 0); sleep(2); printf("in parent: getting mutex\\n"); if (use_timeout) { while (TRUE) { retcode = pthread_mutex_timedlock(&mutex, &timeout); if (retcode == 0) { break; } else if (retcode == ETIMEDOUT) { printf("timed out in parent\\n"); sleep(1); } else { handle_thread_error(retcode, "parent failed (timed)lock", PROCESS_EXIT); } } } else { retcode = pthread_mutex_lock(&mutex); handle_thread_error(retcode, "parent failed lock", PROCESS_EXIT); } printf("parent got mutex\\n"); sleep(5); printf("parent releases mutex\\n"); pthread_mutex_unlock(&mutex); printf("parent released mutex\\n"); printf("parent waiting for child to terminate\\n"); for (size_t i = 0; i < N_THREADS; i++) { retcode = pthread_join(thread[i], 0); handle_thread_error(retcode, "join failed", PROCESS_EXIT); printf("joined thread %d\\n", (int) i); } pthread_mutex_destroy(&mutex); printf("done\\n"); exit(0); }
1
#include <pthread.h> int clientCount = 0; int byteCount = 0; pthread_mutex_t lock; struct serverParm{ int connectionfd; int clientNO; }; static int callback(void *data, int argc, char **argv, char **azColName) { int *fileDesc; fileDesc = (int *) data; int i; for (i = 0; i < argc; i++) { byteCount += write(*fileDesc, azColName[i], strlen(azColName[i])); byteCount += write(*fileDesc, " = ", 3); byteCount += write(*fileDesc, argv[i], strlen(argv[i])); byteCount += write(*fileDesc, "\\n", 1); } byteCount += write(*fileDesc, "\\n", 1); return 0; } void sqlHandler(char cmd[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char sql[1025]; int *fileDesc; fileDesc = (int *) malloc(sizeof(fileDesc)); *fileDesc = open("result.txt", O_APPEND | O_WRONLY); rc = sqlite3_open("book.db", &db); if (rc) { fprintf(stderr, "Can't open database\\n", sqlite3_errmsg(db)); exit(0); } else { } strcpy(sql, cmd); printf("Statement: %s\\n", sql); rc = sqlite3_exec(db, sql, callback, (void*)fileDesc, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\\n", zErrMsg); byteCount += write(*fileDesc, "SQL error: ", 11); byteCount += write(*fileDesc, zErrMsg, strlen(zErrMsg)); byteCount += write(*fileDesc, "\\n", 1); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Operation done successfully\\n"); } sqlite3_close(db); close(*fileDesc); free(fileDesc); } void *threadFunction(void *parmPtr){ char cmd[1025]; int cmdLen; char result[4096]; int readfd; int writefd; pthread_t tid; tid = pthread_self(); time_t curtime; struct tm *timestamp; char timeHeading[100]; printf("Connection established: %d\\n", ((struct serverParm *) parmPtr)->connectionfd); clientCount++; ((struct serverParm *) parmPtr)->clientNO = clientCount; while((cmdLen = recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0)) > 0){ pthread_mutex_lock(&lock); if(strcmp(cmd, "exit") == 0){ close(((struct serverParm *) parmPtr)->connectionfd); free(((struct serverParm *) parmPtr)); clientCount--; pthread_mutex_unlock(&lock); pthread_exit(0); } curtime = time(0); timestamp = localtime(&curtime); strftime(timeHeading, sizeof(timeHeading), "%c", timestamp); writefd = open("result.txt", O_CREAT | O_TRUNC | O_WRONLY, 0644); byteCount += write(writefd, timeHeading, strlen(timeHeading)); byteCount += write(writefd, " Thread ID: ", 12); close(writefd); FILE *file; file = fopen("result.txt", "a"); byteCount += fprintf(file, "%lu (0x%lx)\\n", (unsigned long)tid, (unsigned long)tid); fclose(file); FILE *logfile; logfile = fopen("a4p3ServerLog.txt", "a"); fclose(logfile); sqlHandler(cmd); recv(((struct serverParm *) parmPtr)->connectionfd, cmd, 1025, 0); readfd = open("result.txt", O_RDONLY); read(readfd, result, byteCount); send(((struct serverParm *) parmPtr)->connectionfd, result, strlen(result), 0); memset(&result, 0, sizeof(result)); send(((struct serverParm *) parmPtr)->connectionfd, result, 4096, 0); byteCount = 0; pthread_mutex_unlock(&lock); } close(((struct serverParm *) parmPtr)->connectionfd); free(((struct serverParm *) parmPtr)); clientCount--; pthread_exit(0); } int main(){ int listenSocket, acceptSocket, n; struct sockaddr_in cliAddr, servAddr; pthread_t threadID; struct serverParm *parmPtr; if(pthread_mutex_init(&lock, 0) != 0){ perror("Failed to initialize mutex"); exit(1); } listenSocket = socket(AF_INET, SOCK_STREAM, 0); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(6000); bind(listenSocket, (struct sockaddr *)&servAddr, sizeof(servAddr)); listen(listenSocket, 5); printf("Starts listening...\\n"); while(1){ acceptSocket = accept(listenSocket, 0, 0); printf("Client accepted!!! Assigning thread to serve client\\n"); parmPtr = (struct serverParm *) malloc(sizeof(struct serverParm)); parmPtr->connectionfd = acceptSocket; if(pthread_create(&threadID, 0, threadFunction, (void *)parmPtr) != 0){ perror("Failed to create thread"); close(acceptSocket); close(listenSocket); exit(1); } printf("Server ready for another client\\n"); } close(listenSocket); }
0
#include <pthread.h> int status; int size; struct freelist* next; }freelist; freelist* head = 0; int allocated = 0; int Mem_Init(int sizeOfRegion){ int pagesize = getpagesize(); int initsize = sizeOfRegion; if(allocated != 0 || sizeOfRegion <= 0){ fprintf(stderr, "ERROR!\\n"); return -1; } if(initsize % pagesize != 0){ initsize += (pagesize - (initsize % pagesize)); } int fd = open("/dev/zero", O_RDWR); void* allocptr = mmap(0, initsize, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0); if(allocptr == MAP_FAILED){ perror("mmap"); exit(1); } close(fd); head = (freelist*)allocptr; head->size = initsize - sizeof(freelist); head->status = 0; allocated = 1; return 0; } void* Mem_Alloc(int size){ int allocsize = size; int found = 0; int tmp; freelist* allocptr; freelist* memptr = head; if(allocsize < 0){ return 0; } if(allocsize % 8 != 0){ allocsize += (8 - (allocsize % 8)); } while(found == 0 && memptr != 0){ if(memptr->status == 0 && memptr->size >= allocsize){ found = 1; if(memptr->size > allocsize + sizeof(freelist)){ allocptr = memptr; tmp = memptr->size; memptr = (void*)memptr + sizeof(freelist) + allocsize; memptr->size = tmp - allocsize - sizeof(freelist); memptr->status = 0; memptr->next = allocptr->next; allocptr->size = allocsize; allocptr->status = 1; allocptr->next = memptr; allocptr = allocptr + 1; break; } else{ allocptr = memptr; allocptr->size = allocsize; allocptr->status = 1; allocptr = allocptr + 1; break; } } memptr = memptr->next; } if(found == 0){ return 0; } return allocptr; } int Mem_Free(void *ptr){ pthread_mutex_t lock; pthread_mutex_lock(&lock); freelist* freeptr = (freelist*)ptr - 1; freelist* memptr = head; freelist* prevptr = head; int found = 0; if(ptr == 0){ pthread_mutex_unlock(&lock); return -1; } while(found == 0 && memptr != 0){ if(memptr == freeptr && memptr->status == 1){ memptr->status = 0; found = 1; if(memptr != prevptr && prevptr->status == 0){ prevptr->size += sizeof(freelist) + memptr->size; prevptr->next = memptr->next; memptr = prevptr; } freelist* nextptr = memptr->next; if(nextptr != 0 && nextptr->status == 0){ memptr->size += sizeof(freelist) + nextptr->size; memptr->next = nextptr->next; } } prevptr = memptr; memptr = memptr->next; } pthread_mutex_unlock(&lock); if(found == 0){ return -1; } return 0; } int Mem_Available(){ freelist* memptr = head; int available = 0; while(memptr != 0){ if(memptr->size % 2 == 0){ available += memptr->size; } memptr = memptr->next; } return available; } void Mem_Dump(){ }
1
#include <pthread.h> static pthread_mutex_t cook_meal_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cook_meal_cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t deliver_meal_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t deliver_meal_cond = PTHREAD_COND_INITIALIZER; static char *meal = 0; static char *table = 0; static void *cook( void *arg ) { pthread_mutex_lock( &cook_meal_lock ); while ( meal != 0 ) { pthread_cond_wait( &cook_meal_cond, &cook_meal_lock ); } pthread_mutex_unlock( &cook_meal_lock ); meal = "Humberger"; printf( "Meal is ready to deliver\\n" ); pthread_cond_signal( &cook_meal_cond ); return (void *) 0; } static void *waitor( void *arg ) { pthread_mutex_lock( &cook_meal_lock ); while ( meal == 0 ) { pthread_cond_wait( &cook_meal_cond, &cook_meal_lock ); } pthread_mutex_unlock( &cook_meal_lock ); table = meal; printf( "Delivering meal '%s' to customer\\n", meal ); pthread_cond_signal( &deliver_meal_cond ); return (void *) 0; } static void *consumer( void *arg ) { pthread_mutex_lock( &deliver_meal_lock ); while ( table == 0 ) { pthread_cond_wait( &deliver_meal_cond, &deliver_meal_lock ); } pthread_mutex_unlock( &deliver_meal_lock ); printf( "we can enjoy '%s'\\n", table ); return (void *) 0; } int main( void ) { pthread_t cook_id, waitor_id, consumer_id; pthread_create( &consumer_id, 0, consumer, 0 ); pthread_create( &waitor_id, 0, waitor, 0 ); pthread_create( &cook_id, 0, cook, 0 ); return 0; }
0