text
stringlengths
192
6.24k
label
int64
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; int out = 0; char q[10]; void *inc_count(void *t) { int i; long my_id = (long)t; while(!out){ fprintf(stdout,"Enter q to quit: "); fscanf(stdin,"%s",q); if (strstr(q,"q")) { out = 1; fprintf(stdout,"Tin hieu out: %i\\n", out); } else { fprintf(stdout,"Khong phai tin hieu out\\n"); } } fprintf(stdout,"break thanh cong tin hieu\\n"); pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); while (!out) { pthread_mutex_lock(&count_mutex); count += 1; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); usleep(250000); } fprintf(stdout,"break thanh cong thread\\n"); 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, inc_count, (void *)t1); pthread_create(&threads[1], &attr, watch_count, (void *)t2); pthread_create(&threads[2], &attr, watch_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); printf("Last count: %i\\n",count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t fillmore; pthread_cond_t macchina; int tank = 4; int i, j, ii = 0; void *prepare(void *a) { while(ii < (15/4)){ pthread_mutex_lock(&mutex); if (tank != 0) printf("(P)I'm resting\\n"); while (tank != 0){ pthread_cond_wait(&fillmore, &mutex); } tank = 4; printf("(P)Fuel is ready!\\n"); ii++; for (j=0; j<4; j++){ printf("(P)Unlock a car\\n"); pthread_cond_signal(&macchina); } printf("(P)I go to sleep\\n"); pthread_mutex_unlock(&mutex); } printf("(P)I'm out of business!\\n"); pthread_exit(0); } void *take(void *b) { pthread_mutex_lock(&mutex); while (tank == 0){ printf("(C)I'm waiting a tank\\n"); pthread_cond_wait(&macchina, &mutex); } printf("(C)Thank you for the fuel!\\n"); tank --; if (tank == 0){ printf("(C)I took the last tank, I call Fillmore\\n"); pthread_cond_signal(&fillmore); } pthread_mutex_unlock(&mutex); printf("(C)See you next time!\\n"); pthread_exit(0); } int main(void) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&fillmore, 0); pthread_cond_init(&macchina, 0); pthread_t tid[15 +1]; if (pthread_create(&tid[0],0,prepare,0)) perror("Error create"); for(i=1; i < (15 +1); i++){ if (pthread_create(&tid[i],0,take,0)) perror("Error create"); } for (i=0;i<(15 +1);i++) if (pthread_join(tid[i], 0)) perror("Error Join"); printf("Everything went smoothly!\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t condA; pthread_cond_t condB; sem_t sem1; sem_t sem2; int contadorA; int contadorB; void * imprimirA() { while(1) { pthread_mutex_lock(&mutex); if(contadorA == 2) pthread_cond_wait(&condA, &mutex); printf("A\\n"); contadorA++; if(contadorA == 2) { contadorB = 0; pthread_cond_signal(&condB); } pthread_mutex_unlock(&mutex); } } void * imprimirB() { while(1) { pthread_mutex_lock(&mutex); if(contadorB == 1) pthread_cond_wait(&condB, &mutex); printf("B\\n"); contadorB++; contadorA = 0; pthread_cond_signal(&condA); pthread_mutex_unlock(&mutex); } } int main() { pthread_t thread_impA; pthread_t thread_impB; pthread_t thread_impC; pthread_mutex_init(&mutex, 0); sem_init(&sem1, 0, 1); sem_init(&sem2, 0, 2); contadorA = 0; contadorB = 0; pthread_create(&thread_impA, 0, imprimirA, 0 ); pthread_create(&thread_impC, 0, imprimirA, 0 ); pthread_create(&thread_impB, 0, imprimirB, 0 ); pthread_join(thread_impA, 0); return 0; }
1
#include <pthread.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static volatile int counter = 0; static volatile int exiting = 0; void *decrementer (void *arg) { int counterVal; for (;;) { pthread_mutex_lock (&lock); while (!exiting && (counter <= 0)) { pthread_cond_wait (&cond, &lock); } if (exiting) { pthread_mutex_unlock (&lock); pthread_exit (0); } counterVal = --counter; pthread_mutex_unlock (&lock); printf ("Thread %ld decrementing to %d.\\n", pthread_self (), counterVal); sleep (1); } } int main (int argc, char *argv[]) { pthread_t threads[3]; int i, val; for (i = 0; i < 3; ++i) { pthread_create (&threads[i], 0, decrementer, 0); } for (;;) { switch (scanf ("%d", &val)) { case 1: pthread_mutex_lock (&lock); counter += val; pthread_cond_broadcast (&cond); pthread_mutex_unlock (&lock); break; case EOF: pthread_mutex_lock (&lock); exiting = 1; pthread_cond_broadcast (&cond); pthread_mutex_unlock (&lock); for (i = 0; i < 3; ++i) { pthread_join (threads[i], 0); } exit (0); default: fprintf (stderr, "You must enter numbers or EOF to end the program.\\n"); exit (1); } } }
0
#include <pthread.h> const int MAX_THREADS = 5; long tid; char name[20]; unsigned int age; } tls_t; static pthread_mutex_t lock; static pthread_key_t key_tls; static pthread_once_t once = PTHREAD_ONCE_INIT; static void make_key(){ pthread_key_create(&key_tls, 0); } static void * thread_setup_tls(long tid) { pthread_once(&once, make_key); tls_t *tls; tls = pthread_getspecific(key_tls); if( tls==0 ){ tls = (tls_t *)malloc(sizeof(tls_t)); pthread_setspecific(key_tls, (void *)tls); } tls->tid = tid; tls->age = 100; return tls; } static void dump_thread_tls(tls_t * tls) { pthread_mutex_lock(&lock); printf(" Dumping thread TLS %p:\\n", tls); if(tls!=0) { printf(" tid = %ld\\n", tls->tid); printf(" name = %s\\n", tls->name); printf(" age = %d\\n", tls->age); } else printf(" !EMPTY!\\n"); pthread_mutex_unlock(&lock); } void* run(void * arg){ long tid = (long)arg; tls_t *tls = 0; printf(" Thread %ld start\\n", tid); if (tid%2 == 0) { printf(" Thread %ld setting up tls\\n", tid); tls = thread_setup_tls(tid); } sleep(1); tls = pthread_getspecific(key_tls); dump_thread_tls(tls); printf(" Thread %ld exit\\n", tid); pthread_exit((void *)tid); } int main(){ printf("Main Thread start\\n"); pthread_t threads[MAX_THREADS]; int rc; int i; pthread_mutex_init(&lock, 0); pthread_attr_t thread_attr; pthread_attr_init(&thread_attr); pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<MAX_THREADS; i++){ rc = pthread_create(&threads[i], &thread_attr, run, (void *)(long)i); if (rc) { printf("Error: pthread_create rc=%d\\n", rc); exit(-1); } } printf("Thread main: created threads\\n"); void * status; for (i=0; i<MAX_THREADS; i++) { rc = pthread_join(threads[i], &status); if (rc) { printf("Error: pthread_join rc=%d\\n", rc); exit(-1); } printf("Thread main: joined thread: %ld\\n", (long) status); } pthread_attr_destroy(&thread_attr); pthread_mutex_destroy(&lock); printf("Thread main exit\\n"); pthread_exit(0); }
1
#include <pthread.h> int cond =0; pthread_cond_t condthread = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int max = 0; void* thread_func(void* arg) { int i, nb; int *param; int *lvl = (int*)arg; pthread_t *tid; nb = (*lvl)+1; pthread_mutex_lock(&mutex); while (!cond) { pthread_cond_wait(&condthread, &mutex); } cond = 0; pthread_mutex_unlock(&mutex); if (*lvl < max) { param = (int*)malloc(sizeof(int)); *param = nb; tid = calloc(nb, sizeof(pthread_t)); printf("%d cree %d fils\\n", (int)pthread_self(), nb); pthread_mutex_lock(&mutex); for (i = 0; i < nb; i++) { pthread_create((tid+i), 0, thread_func, param); } pthread_cond_broadcast(&condthread); pthread_mutex_unlock(&mutex); cond = 1; for (i = 0; i < nb; i++) pthread_join(tid[i], 0); } if (*lvl > 1) pthread_exit ( (void*)0); return (void*)0; } int main(int argc, char *argv[]) { if(argc<2) return 1; max = atoi(argv[1]); printf("Passage\\n"); int *pi = 0; int i = 1; pi = malloc(sizeof(int)); *pi = i; pthread_t pthread; printf("Passage\\n"); pthread_mutex_lock(&mutex); pthread_create(&pthread, 0, thread_func,(void*)pi ); pthread_cond_broadcast(&condthread); cond = 1; pthread_mutex_unlock(&mutex); pthread_join(pthread, 0); }
0
#include <pthread.h> void iOsalTimespecPlusMs (struct timespec *pTS, unsigned int millisecond) { struct timeval tv; struct timespec ts; gettimeofday (&tv, 0); ts.tv_sec = tv.tv_sec; ts.tv_nsec = tv.tv_usec * 1000; ts.tv_sec += (millisecond / 1000); ts.tv_nsec += (millisecond % 1000) * 1000000; if (ts.tv_nsec >= 1000000000) { ts.tv_nsec -= 1000000000; ts.tv_sec += 1; } *pTS = ts; } static void pthread_delay (int millisecond) { pthread_mutex_t mutex; pthread_cond_t cond; struct timespec ts; iOsalTimespecPlusMs (&ts, millisecond); pthread_mutex_init (&mutex, 0); pthread_cond_init (&cond, 0); pthread_mutex_lock (&mutex); pthread_cond_timedwait (&cond, &mutex, &ts); pthread_mutex_unlock (&mutex); pthread_cond_destroy (&cond); pthread_mutex_destroy (&mutex); } void Thread1 () { int i, j; int policy; struct sched_param param; pthread_getschedparam (pthread_self (), &policy, &param); if (policy == SCHED_OTHER) printf ("SCHED_OTHER 1\\n"); if (policy == SCHED_RR) printf ("SCHED_RR 1 \\n"); if (policy == SCHED_FIFO) printf ("SCHED_FIFO 1\\n"); printf ("thread 1 param.sched_priority = %d\\n", param.sched_priority); for (i = 1; i < 10; i++) { pthread_delay (50); printf ("thread 1\\n"); } printf ("Pthread 1 exit\\n"); } void Thread2 () { int i, j, m; int policy; struct sched_param param; pthread_getschedparam (pthread_self (), &policy, &param); if (policy == SCHED_OTHER) printf ("SCHED_OTHER 2\\n"); if (policy == SCHED_RR) printf ("SCHED_RR 2\\n"); if (policy == SCHED_FIFO) printf ("SCHED_FIFO 2\\n"); printf ("thread 2 param.sched_priority = %d\\n", param.sched_priority); for (i = 1; i < 10; i++) { pthread_delay (50); printf ("thread 2\\n"); } printf ("Pthread 2 exit\\n"); } void Thread3 () { int i, j; int policy; struct sched_param param; pthread_getschedparam (pthread_self (), &policy, &param); if (policy == SCHED_OTHER) printf ("SCHED_OTHER 3\\n"); if (policy == SCHED_RR) printf ("SCHED_RR 3\\n"); if (policy == SCHED_FIFO) printf ("SCHED_FIFO 3\\n"); printf ("thread 3 param.sched_priority = %d\\n", param.sched_priority); for (i = 1; i < 10; i++) { pthread_delay (50); printf ("thread 3\\n"); } printf ("Pthread 3 exit\\n"); } int main () { int i; i = getuid (); if (i == 0) printf ("The current user is root\\n"); else printf ("The current user is not root\\n"); pthread_t ppid1, ppid2, ppid3; struct sched_param param; pthread_attr_t attr, attr1, attr2; pthread_attr_init (&attr1); pthread_attr_init (&attr); pthread_attr_init (&attr2); param.sched_priority = 51; pthread_attr_setschedpolicy (&attr2, SCHED_FIFO); pthread_attr_setschedparam (&attr2, &param); pthread_attr_setinheritsched (&attr2, PTHREAD_EXPLICIT_SCHED); param.sched_priority = 21; pthread_attr_setschedpolicy (&attr1, SCHED_FIFO); pthread_attr_setschedparam (&attr1, &param); pthread_attr_setinheritsched (&attr1, PTHREAD_EXPLICIT_SCHED); pthread_create (&ppid3, &attr, (void *) Thread3, 0); pthread_create (&ppid2, &attr1, (void *) Thread2, 0); pthread_create (&ppid1, &attr2, (void *) Thread1, 0); pthread_join (ppid3, 0); pthread_join (ppid2, 0); pthread_join (ppid1, 0); pthread_attr_destroy (&attr2); pthread_attr_destroy (&attr1); return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex_C; static int A [3][2] = { {1,2}, {3,4}, {5,6} }; static int B [2][3] = { {7,8,9}, {3,7,1} }; static int C [3][3]; void *hesapla(void *mat); struct matris { int i; int j; }; int main() { pthread_t thread[3][3]; int i,j; pthread_mutex_init(&mutex_C, 0); for (i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ struct matris *veri = (struct matris *) malloc(sizeof(struct matris)); veri->i = i; veri->j = j; pthread_create(&thread[i][j], 0, hesapla,(void*) veri); } } for (i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ pthread_join( thread[i][j],0); } } printf("C matrisi:\\n"); for (i = 0; i < 3; i++){ for(j = 0; j < 3; j++){ printf("%d ",C[i][j]); } printf("\\n"); } pthread_mutex_destroy(&mutex_C); exit(0); } void *hesapla(void *mat) { struct matris *veri; veri = (struct matris *)mat; int row = veri->i; int col = veri->j; pthread_mutex_lock(&mutex_C); C[row][col] = (A[row][0]*B[0][col]) + (A[row][1]*B[1][col]); pthread_mutex_unlock(&mutex_C); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex; void sleep_rand(void) { sleep(rand() % 8 + 1); } void *northbound_farmer(void *param) { int id = *((int *) param); sleep_rand(); pthread_mutex_lock(&mutex); sleep_rand(); pthread_mutex_unlock(&mutex); pthread_exit(0); } void *southbound_farmer(void *param) { int id = *((int *) param); sleep_rand(); pthread_mutex_lock(&mutex); sleep_rand(); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(void) { srand(time(0)); pthread_mutex_init(&mutex, 0); pthread_attr_t attr; pthread_t north_farmer_threads[10], south_farmer_threads[7]; pthread_attr_init(&attr); int north_id[10], south_id[7], i; for (i = 0; i < 10; i++) { north_id[i] = i + 1; pthread_create(&north_farmer_threads[i], &attr, northbound_farmer, (void *) &north_id[i]); } for (i = 0; i < 7; i++) { south_id[i] = i + 1; pthread_create(&south_farmer_threads[i], &attr, southbound_farmer, (void *) &south_id[i]); } for (i = 0; i < 10; i++) { pthread_join(north_farmer_threads[i], 0); } for (i = 0; i < 7; i++) { pthread_join(south_farmer_threads[i], 0); } printf("Finished!\\n"); return 0; }
1
#include <pthread.h> struct ezcfg_ezctp { struct ezcfg *ezcfg; int shm_id; size_t shm_size; void *shm_addr; size_t cq_unit_size; size_t cq_length; size_t cq_free; int cq_head; int cq_tail; pthread_mutex_t cq_mutex; }; static bool fill_ezctp_info(struct ezcfg_ezctp *ezctp, const char *conf_path) { char *p; if (conf_path == 0) { return 0; } p = ezcfg_util_get_conf_string(conf_path, EZCFG_EZCFG_SECTION_EZCTP, 0, EZCFG_EZCFG_KEYWORD_SHM_SIZE); if (p == 0) { return 0; } else { ezctp->shm_size = atoi(p); free(p); } p = ezcfg_util_get_conf_string(conf_path, EZCFG_EZCFG_SECTION_EZCTP, 0, EZCFG_EZCFG_KEYWORD_CQ_UNIT_SIZE); if (p == 0) { return 0; } else { ezctp->cq_unit_size = atoi(p); free(p); } ezctp->cq_length = ezctp->shm_size / ezctp->cq_unit_size; if (ezctp->cq_length < 1) { return 0; } ezctp->cq_free = ezctp->cq_length; return 1; } bool ezcfg_ezctp_delete(struct ezcfg_ezctp *ezctp) { struct ezcfg *ezcfg; ASSERT(ezctp != 0); ezcfg = ezctp->ezcfg; pthread_mutex_lock(&ezctp->cq_mutex); if ((void *) -1 != ezctp->shm_addr) { if (shmdt(ezctp->shm_addr) == -1) { ; } else { ; } ezctp->shm_addr = (void *) -1; } if (ezctp->shm_id >= 0) { if (shmctl(ezctp->shm_id, IPC_RMID, 0) == -1) { ; } else { ; } ezctp->shm_id = -1; } pthread_mutex_unlock(&ezctp->cq_mutex); pthread_mutex_destroy(&ezctp->cq_mutex); free(ezctp); return 1; } struct ezcfg_ezctp *ezcfg_ezctp_new(struct ezcfg *ezcfg) { struct ezcfg_ezctp *ezctp; key_t key; ASSERT(ezcfg != 0); ezctp = malloc(sizeof(struct ezcfg_ezctp)); if (ezctp == 0) { err(ezcfg, "can not malloc ezctp\\n"); return 0; } memset(ezctp, 0, sizeof(struct ezcfg_ezctp)); ezctp->ezcfg = ezcfg; ezctp->shm_addr = (void *) -1; pthread_mutex_init(&ezctp->cq_mutex, 0); if (fill_ezctp_info(ezctp, ezcfg_common_get_config_file(ezcfg)) == 0) { ; goto fail_exit; } key = ftok(ezcfg_common_get_shm_ezctp_path(ezcfg), EZCFG_SHM_PROJID_EZCTP); if (key == -1) { ; goto fail_exit; } ezctp->shm_id = shmget(key, ezctp->shm_size, IPC_CREAT|IPC_EXCL|00666); if (ezctp->shm_id < 0) { ; goto fail_exit; } ezctp->shm_addr = shmat(ezctp->shm_id, 0, 0); if ((void *) -1 == ezctp->shm_addr) { ; goto fail_exit; } return ezctp; fail_exit: ezcfg_ezctp_delete(ezctp); return 0; } int ezcfg_ezctp_get_shm_id(struct ezcfg_ezctp *ezctp) { struct ezcfg *ezcfg; ASSERT(ezctp != 0); ezcfg = ezctp->ezcfg; return ezctp->shm_id; } size_t ezcfg_ezctp_get_cq_unit_size(struct ezcfg_ezctp *ezctp) { struct ezcfg *ezcfg; ASSERT(ezctp != 0); ezcfg = ezctp->ezcfg; return ezctp->cq_unit_size; } bool ezcfg_ezctp_insert_data(struct ezcfg_ezctp *ezctp, void *data, size_t n, size_t size) { struct ezcfg *ezcfg; bool insert_flag = 0; size_t i; char *src, *dst; ASSERT(ezctp != 0); ASSERT(data != 0); ASSERT(n > 0); ASSERT(size > 0); ezcfg = ezctp->ezcfg; pthread_mutex_lock(&(ezctp->cq_mutex)); if (ezctp->cq_free >= n) { for (i=0; i<n; i++) { src = (char *)data + (i * size); dst = (char *)ezctp->shm_addr + (ezctp->cq_tail * ezctp->cq_unit_size); memcpy(dst, src, size); ezctp->cq_tail = (ezctp->cq_tail + 1) % ezctp->cq_length; } ezctp->cq_free -= n; insert_flag = 1; } pthread_mutex_unlock(&(ezctp->cq_mutex)); return insert_flag; }
0
#include <pthread.h> int main(int argc, char *argv[]) { int i; int num_req_threads = argc-2; int num_res_threads = MIN_RESOLVER_THREADS; pthread_t req_threads[num_req_threads]; pthread_t res_threads[num_res_threads]; pthread_mutex_init(&queue_mutex, 0); pthread_mutex_init(&output_mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); queue_init(&request_queue, 100); if (argc < MIN_ARGS) { printf("Too Few Arguments.\\nUsage: %s\\n", USAGE); exit(1); } if (argc > MAX_INPUT_FILES + 1) { printf("Too Many Arguments.\\nMax is 10.\\nUsage: %s\\n", USAGE); exit(1); } output_file = fopen(argv[(argc-1)], "w"); if (!output_file) { printf("Can't open output file."); exit(1); } for (i = 0; i < num_req_threads; i++) { pthread_create(&req_threads[i], &attr, requester, argv[i+1]); } for (i = 0; i < num_res_threads; i++) { pthread_create(&res_threads[i], &attr, resolver, 0); } for (i = 0; i < num_req_threads; i++) { pthread_join(req_threads[i], 0); } req_done = 1; for (i = 0; i < num_res_threads; i++) { pthread_join(res_threads[i], 0); } fclose(output_file); pthread_mutex_destroy(&queue_mutex); pthread_mutex_destroy(&output_mutex); queue_cleanup(&request_queue); return 0; } void* requester(void *file_name) { char host[MAX_NAME_LENGTH]; char* temp; FILE* input_file = fopen(file_name, "r"); while (fscanf(input_file, INPUTFS, host) == 1) { while(1) { pthread_mutex_lock(&queue_mutex); if (queue_is_full(&request_queue)) { pthread_mutex_unlock(&queue_mutex); usleep(rand() % 100); } else { temp = malloc(MAX_NAME_LENGTH); strncpy(temp, host, MAX_NAME_LENGTH); queue_push(&request_queue, temp); pthread_mutex_unlock(&queue_mutex); break; } } } fclose(input_file); return 0; } void* resolver() { char* host; char ip[MAX_IP_LENGTH]; while (!queue_is_empty(&request_queue) || !req_done) { pthread_mutex_lock(&queue_mutex); if (!queue_is_empty(&request_queue)) { host = queue_pop(&request_queue); if (host) { pthread_mutex_unlock(&queue_mutex); dnslookup(host, ip, sizeof(ip)); pthread_mutex_lock(&output_mutex); fprintf(output_file, "%s,%s\\n", host, ip); pthread_mutex_unlock(&output_mutex); } free(host); } else { pthread_mutex_unlock(&queue_mutex); } } return 0; }
1
#include <pthread.h> const char invalid[] = {' ','\\n', '<'}; int sharedByteRead = 0; int sharedTotalCount = 0; int total_length; FILE *fp; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; void* GetDataBytes() { char data[5000 + 1]; int len, i, count=0; while(1) { pthread_mutex_lock(&mutex); if(feof(fp)) break; len = fread(data, sizeof(char), 5000, fp); data[len] = '\\0'; if(!feof(fp)) { while(!strchr(invalid, fgetc(fp))) { data[--len] = '\\0'; fseek(fp, -2, 1); } fseek(fp, -1, 1); } pthread_mutex_unlock(&mutex); len = len-total_length+1; for(i=0; i<len; i++) { if(strncmp(&data[i], targ, total_length)==0) ++count; } } pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex2); sharedTotalCount += count; pthread_mutex_unlock(&mutex2); pthread_exit(0); } int main(int argc, char** args) { if(argc != 2) { printf("Error! Filename not found!\\n"); exit(-1); } fp = fopen(args[1], "r"); pthread_t threads[4]; int rc; long t=0; time_t a, b; total_length = strlen(targ); printf("File name : %s \\n", args[1]); printf("Buffer size : %dK\\n", 5000/1000); printf("Number of threads : %d\\n", 4); a = time(0); printf("Searching...\\n"); for(t=0; t<4; t++) { rc = pthread_create(&threads[t], 0, GetDataBytes, 0); if (rc) { printf("ERROR! Code from pthread_create %d\\n", rc); exit(-1); } } for(t=0; t<4; t++) { if(pthread_join(threads[t], 0)) { printf("ERROR! Cannot join threads\\n"); exit(-1); } } b = time(0); double search = difftime(b, a); printf("Searching time used %lf seconds.\\n", search); printf("Found string %d times\\n", sharedTotalCount); pthread_exit(0); }
0
#include <pthread.h> long *id; void *data; } Message; Message * message_create() { Message *message = (Message*) malloc( sizeof(Message ) ); return message; } void message_destroy( Message * message ) { if ( message != 0 ) { free( message ); } } struct LinkedNode *link; Message *message; } LinkedNode; LinkedNode * node_create(Message *message) { LinkedNode *node = (LinkedNode*) malloc( sizeof(LinkedNode) ); node->message = message; return node; } void node_destroy( LinkedNode* node ) { if ( node != 0 ) { message_destroy( node->message ); free( node ); } } LinkedNode *head; long length; } LinkedQueue; LinkedQueue * queue_create() { LinkedQueue *queue = (LinkedQueue*) malloc( sizeof(LinkedQueue) ); return queue; } void queue_destroy_nodes( LinkedNode *head ) { if ( head != 0 ) { LinkedNode *parent = head; while ( parent->link != 0 ) { LinkedNode *link = parent->link; node_destroy( parent ); parent = link; } } } void queue_destroy( LinkedQueue *queue ) { if ( queue != 0 ) { queue_destroy_nodes( queue->head ); } free(queue); } void queue_enqueue( LinkedQueue *queue, LinkedNode *item ) { if (queue->head != 0) { LinkedNode *head = queue->head; head->link = item; } queue->head = item; } LinkedNode * queue_dequeue( LinkedQueue *queue ) { LinkedNode *head = queue->head; queue->head = head->link; return head; } LinkedQueue *queue; pthread_mutex_t lock; } Mailbox; Mailbox * mailbox_create() { Mailbox *mailbox = (Mailbox*) malloc( sizeof(Mailbox) ); mailbox->queue = queue_create(); return mailbox; } void mailbox_put( Mailbox *mailbox, Message *message ) { pthread_mutex_lock( &mailbox->lock ); LinkedNode *node = node_create( message ); queue_enqueue( mailbox->queue, node ); pthread_mutex_unlock( &mailbox->lock ); } Message * mailbox_get( Mailbox *mailbox ) { pthread_mutex_lock( &mailbox->lock ); LinkedNode *node = queue_dequeue( mailbox->queue ); pthread_mutex_unlock( &mailbox->lock ); return node->message; } void mailbox_destroy(Mailbox *mailbox) { if ( mailbox != 0 ) { queue_destroy( mailbox->queue ); pthread_mutex_destroy( &mailbox->lock ); free( mailbox ); } } void lock( pthread_mutex_t *mutex ){ if ( pthread_mutex_trylock(mutex) ) { } } void *data; } Future; Mailbox *mailbox; Future(*send)(Message*); } Actor; void func( void(*fun)() ) { fun(); } void otherfunc() { printf("Herro func\\n"); } int main(int argc, const char ** argv) { func(&otherfunc); const char *one = argv[1]; printf("%s\\n", one); pthread_t threads[8]; for (int i = 0; i < 8; i++) { } }
1
#include <pthread.h> pthread_mutex_t mutex; FILE *fp; int numero = 0; void * worker(void *arg) { int tempo = rand() % 20; int temp; int order = (int)arg; pthread_t thread_id = pthread_self(); printf("Nova thread %d criada TID = %d\\n", order, (unsigned int)thread_id); pthread_mutex_lock(&mutex); temp = numero; temp++; printf("%d\\n", tempo); printf("Thread %d\\n", order); usleep(tempo * 100000); numero = temp; pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char * argv[]) { printf("Iniciando o programa\\n"); pthread_mutex_init(&mutex, 0); pthread_t thread[10]; long cont; for (cont=1; cont<=10; cont++) { pthread_create(&thread[cont], 0, &worker, (void *)cont); } for (cont=1; cont<=10; cont++) { pthread_join(thread[cont], 0); } printf("Finalizando o programa.\\n"); printf("Número %d\\n", numero); pthread_exit(0); pthread_mutex_destroy(&mutex); }
0
#include <pthread.h> char buf[4]; int occupied; int in,out; pthread_mutex_t mutex; pthread_cond_t m; pthread_cond_t l; } buffer_t; buffer_t buffer; void * thread1(void *); void * thread2(void *); pthread_t tid[2]; int main( int argc, char *argv[] ) { int i; pthread_cond_init(&(buffer.m), 0); pthread_cond_init(&(buffer.l), 0); pthread_create(&tid[1], 0, thread2, 0); pthread_create(&tid[0], 0, thread1, 0); for ( i = 0; i < 2; i++) pthread_join(tid[i], 0); printf("\\nNumber of threads terminated:%d\\n", i); } void * thread1(void * parm) { char item[5]="AKASH"; int i; printf("Thread1 is started\\n"); for(i=0;i<5;i++) { if (item[i] == '\\0') break; pthread_mutex_lock(&(buffer.mutex)); if (buffer.occupied >= 4) printf("Thread1 waiting\\n"); while (buffer.occupied >= 4) pthread_cond_wait(&(buffer.l), &(buffer.mutex) ); printf("Thread1 executing\\n"); buffer.buf[buffer.in++] = item[i]; buffer.in %= 4; buffer.occupied++; pthread_cond_signal(&(buffer.m)); pthread_mutex_unlock(&(buffer.mutex)); } printf("Thread1 exiting\\n"); pthread_exit(0); } void * thread2(void * parm) { char item; int i; printf("Thread2 is started\\n"); for(i=0;i<5;i++) { pthread_mutex_lock(&(buffer.mutex) ); if (buffer.occupied <= 0) printf("Thread2 waiting\\n"); while(buffer.occupied <= 0) pthread_cond_wait(&(buffer.m), &(buffer.mutex) ); printf("Thread2 executing\\n"); item = buffer.buf[buffer.out++]; printf("%c\\n",item); buffer.out %= 4; buffer.occupied--; pthread_cond_signal(&(buffer.l)); pthread_mutex_unlock(&(buffer.mutex)); } printf("Thread2 exiting\\n"); pthread_exit(0); }
1
#include <pthread.h> { double *a, *b, sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len; long offset = (long)arg; double mysum, *x, *y; len = dotstr.veclen; start = offset*len; end = start+len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i]*y[i]); } pthread_mutex_lock(&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock(&mutexsum); pthread_exit((void *) 0); } int main() { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double *) malloc(4*100*sizeof(double)); b = (double *) malloc(4*100*sizeof(double)); for (i=0 ; i<100*4; i++) { a[i] = 1.0; b[i] = a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<4; i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0; i<4; i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> unsigned long seqNum; double dt; FILE *file_fd; struct img_struct* img_old; struct img_struct* img_new; float xv_buffer[5]; float yv_buffer[5]; int buf_ind = 0; pthread_t horizontal_velocities_thread; pthread_mutex_t velocity_access_mutex = PTHREAD_MUTEX_INITIALIZER; unsigned char writeImagesToDisk=0; void *horizontal_velocities_thread_main(void *data) { double prevTime = 0; video_GrabImageGrey(img_old); for (;;) { video_GrabImageGrey(img_new); double currentTime = img_new->timestamp; int dxi, dyi; video_blocksum(img_old, img_new, &dxi, &dyi); if (dxi != 0 || dyi != 0) { struct img_struct* tmp = img_new; img_new = img_old; img_old = tmp; } pthread_mutex_lock(&velocity_access_mutex); dt = currentTime - prevTime; xv_buffer[buf_ind] = dxi / dt; yv_buffer[buf_ind] = dyi / dt; buf_ind = (buf_ind+1)%5; seqNum++; prevTime = currentTime; pthread_mutex_unlock(&velocity_access_mutex); printf("%f\\n", util_timestamp()); } video_close(); return 0; } int horizontal_velocities_init(struct horizontal_velocities_struct *hv) { if (video_init() != 0) { printf("video init failed\\n"); exit(-1); } printf("video init done\\n"); img_old = video_CreateImage(1); img_new = video_CreateImage(1); seqNum = 0; int rc = pthread_create(&horizontal_velocities_thread, 0, horizontal_velocities_thread_main, 0); if (rc) { printf( "ctl_Init: Return code from pthread_create(hor_vel_thread) is %d\\n", rc); return 202; } return 0; } void horizontal_velocities_getSample(struct horizontal_velocities_struct *hv, struct att_struct *att) { pthread_mutex_lock(&velocity_access_mutex); if (dt > 0) { hv->xv = util_median(xv_buffer, 5) * att->h * 0.005; hv->yv = util_median(yv_buffer, 5) * att->h * 0.005; hv->dt = dt; } hv->seqNum = seqNum; pthread_mutex_unlock(&velocity_access_mutex); } void horizontal_velocities_print(struct horizontal_velocities_struct *hv, double xpos, double ypos, double h) { printf( "seq=%ld xv=%5.1f,yv=%5.1f, dt=%4.1f xpos=%4.1f ypos=%4.1f h=%4.1f\\n", hv->seqNum, hv->xv, hv->yv, hv->dt * 1000, xpos, ypos, h); } void horizontal_velocities_close() { fclose(file_fd); video_close(); }
1
#include <pthread.h> int campo[10][10], op[10][10], countbombas[100]; pthread_mutex_t mutex_bomba[25]; pthread_t gerando[25]; int verificaBomba(int linha, int coluna, int comparado) { int z; for(z=0; z<25; z++) { if(op[linha][coluna] == comparado) { return 1; } } return 0; } void imprime_inicio() { int i, j, z=0; system("clear"); for(i=0; i<10; i++) { for(j=0; j<10; j++) { campo[i][j] = z; z++; if(z<10) { printf("| %d ", campo[i][j]); } else printf("| %d ", campo[i][j]); } printf("\\n"); } } void gerando(int * bomba) { pthread_mutex_lock(&(mutex_bomba[*bomba])); } void acabou_gerar(int * bomba) { pthread_mutex_unlock(&(mutex_bomba[*bomba])); } void * gera_bombas(void *var) { int * bomba = (int *) (var); srand(time(0)); int tempo = rand() % 10; int aux,contador; sleep(tempo); gerando(bomba); do { int linha = rand() % 10; int coluna = rand() % 10; }while(verificaBomba(linha, coluna, op[linha][coluna])); op[linha][coluna] = -1; acabou_gerar(bomba); pthread_exit(0); } void gera_dicas(void){ int i,j,aux,k=0; for(i=0;i<10;i++){ for(j=0;j<10;j++){ if(op[i--][j--]==-1 && i>0 && j>0) aux++; else if(op[i--][j]==-1 && i>0) aux++; else if(op[i--][j++]==-1 && i>0 && j<10) aux++; else if(op[i][j++]==-1 && j<10) aux++; else if(op[i][j--]==-1 && j>0) aux++; else if(op[i++][j--]==-1 && i<10 && j>0) aux++; else if(op[i++][j]==-1 && i<10) aux++; else if(op[i++][j++]==-1 && i<10 && j<10) aux++; countbombas[k]=aux; aux=0; k++; } } } void atualiza_op(void){ int i,j,k=0; for(i=0;i<9;i++){ for(j=0;j<9;j++){ if(op[i][j] != -1) op[i][j]=countbombas[k]; k++; } } }
0
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1; pthread_mutex_t mutex; int pdev; void *thread1(void *arg) { pthread_mutex_lock(&mutex); pdev = 6; pthread_mutex_unlock(&mutex); } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread1, 0); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pdev = 4; ldv_assert(pdev==4); pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
1
#include <pthread.h> extern char *strtok_r(char *str, const char *delim, char **saveptr); pthread_mutex_t mutex; char **palabras; int num_palabras[3] = {0, 0, 0}; char *ruta; int *numCaracteresLinea; int bloque; char **parrafos; int hilos; int numero_lineas(char *ruta, int *tam_lineas) { if (ruta != 0) { FILE *ar = fopen(ruta, "r"); int lineas = 0; int tam_linea; while (!feof(ar)) { tam_linea++; char c = getc(ar); if (c == '\\n') { if (tam_lineas != 0) { tam_lineas[lineas] = tam_linea; } lineas++; tam_linea = 0; } } fclose(ar); return lineas; } return -1; } void *mostrar_palabras(void *arg) { while (1) { sleep(1); printf("--*-Palabras encontradas-*-- \\nPalabra: %s - > Cantidad: %d\\nPalabra: %s - > Cantidad: %d\\nPalabra: %s - > Cantidad: %d\\n", *(palabras), num_palabras[0], *(palabras + 1), num_palabras[1], *(palabras + 2), num_palabras[2]); } return (void *) 0; } void *conteo(void *arg) { char *str = (char *) arg; char *token; while (token != 0) { sleep(1); if (!strcmp(*(palabras), token)) { pthread_mutex_lock(&mutex); num_palabras[0]++; pthread_mutex_unlock(&mutex); } else if (!strcmp(*(palabras + 1), token)) { pthread_mutex_lock(&mutex); num_palabras[1]++; pthread_mutex_unlock(&mutex); } else if (!strcmp(*(palabras + 2), token)) { pthread_mutex_lock(&mutex); num_palabras[2]++; pthread_mutex_unlock(&mutex); } } return (void *) 0; } int main(int argc, char *argv[]) { if (argc != 6) { printf("USO: ./buscar <RUTA> <HILOS> <PALABRA1> <PALABRA2> <PALABRA3>\\n"); exit(-1); } palabras = malloc(3 * sizeof(char *)); for (int i = 0; i < 3; i++) { *(palabras + i) = argv[3 + i]; *(num_palabras + i) = 0; } ruta = argv[1]; hilos = atoi(argv[2]); int numLineas = numero_lineas(ruta, 0); numCaracteresLinea = malloc(numLineas * sizeof(int)); numero_lineas(ruta, numCaracteresLinea); int totalCaracteres = 0; for (int i = 1; i < numLineas; i++) { totalCaracteres += *(numCaracteresLinea + i); } int bloque = totalCaracteres / hilos; int seek = 0; parrafos = malloc(hilos * sizeof(char *)); for (int i = 0; i < hilos; i++) { FILE *file = fopen(ruta, "r"); fseek(file, seek, 0); *(parrafos + i) = malloc(bloque * sizeof(char)); for (int j = 0; j < bloque; j++) { char c = getc(file); *(*(parrafos + i) + j) = c; } seek = seek + bloque; } pthread_t *t_mostrar = malloc(sizeof(pthread_t)); int stat_mostrar1, stat_mostrar2; int status; pthread_t *threads = malloc(hilos * sizeof(pthread_t)); stat_mostrar1 = pthread_create(t_mostrar, 0, mostrar_palabras, 0); if (stat_mostrar1 != 0) { fprintf(stderr, "Error al crear el hilo para mostrar palabras.\\n"); } for (int i = 0; i < hilos; i++) { status = pthread_create(threads + i, 0, conteo, (void *) *(parrafos + i)); if (status != 0) { fprintf(stderr, "Error al crear el hilo : %d\\n", i); exit(-1); } } for (int j = 0; j < hilos; j++) { int status1 = pthread_join(threads[j], 0); if (status1 != 0) { fprintf(stderr, "Error al esperar por el hilo\\n"); exit(-1); } } stat_mostrar2 = pthread_join(*t_mostrar, 0); if (stat_mostrar2 != 0) { fprintf(stderr, "Error al esperar por el hilo para mostrar palabras.\\n"); } return (0); }
0
#include <pthread.h> int file_des; int record_number; size_t buffer = 1024; char *word; int thread_no; pthread_t *threads_arr; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2= PTHREAD_MUTEX_INITIALIZER; struct record{ int id; char text[1020]; }; int finish =0; long gettid() { return syscall(SYS_gettid); } void *threadFunction(void *arg){ if(pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,0)==EINVAL){ fprintf(stderr,"Error occurred during pthread_setcancelstate\\n"); exit(1); } if(pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,0)==EINVAL){ fprintf(stderr,"Error occurred during pthread_setcanceltype\\n"); exit(1); } ssize_t actually_read; while (!finish) { pthread_mutex_lock(&mutex); for (int i = 0; i < record_number; ++i) { struct record *buf = malloc(sizeof(struct record)); char *recordID = malloc((buffer + 1) * sizeof(char)); actually_read = read(file_des, buf, buffer); if (actually_read == -1) { perror("Error occurred during reading"); exit(1); } strcpy(recordID, buf->text); recordID[actually_read] = '\\0'; if (strstr(recordID, word) != 0) { printf("Thread with TID: %ld found %s in record %d\\n", gettid(), word, buf->id); } if (actually_read == 0) { finish = 0; for (int j = 0; j < thread_no; ++j) { if (!pthread_equal(threads_arr[j], pthread_self())) pthread_cancel(threads_arr[j]); } pthread_mutex_unlock(&mutex); free(recordID); pthread_cancel(pthread_self()); return (void *) 0; } } pthread_mutex_unlock(&mutex); } return (void*)0; } int main(int args, char**argv) { if(args!=5){ fprintf(stderr, "Wrong number of arguments\\n"); exit(1); } thread_no=atoi(argv[1]); file_des= open(argv[2] ,O_RDONLY); if (file_des==-1){ perror("Error during opening file"); exit(1); } record_number = atoi(argv[3]); word=argv[4]; threads_arr = malloc(sizeof(pthread_t) * thread_no); pthread_mutex_lock(&mutex2); for (int i = 0; i < thread_no; ++i) { if(pthread_create(&threads_arr[i],0, &threadFunction,0)){ perror("Error during thread creation"); exit(1); } } pthread_mutex_unlock(&mutex2); for (int j = 0; j < thread_no; ++j) { pthread_join( threads_arr[j], 0); } if(close(file_des)==-1){ perror("Error during closing file"); exit(1); } return 0; }
1
#include <pthread.h> enum { OFF, ON }; void *WriteFunc(void *arg); void *ReadFunc(void *arg); void Handler(int signal_num); sem_t sem; pthread_cond_t cond_read; pthread_mutex_t mutex; size_t g_read_counter = 0; size_t counter = 0; int num_of_readers = 10; volatile int g_flag = 1; int main(int argc, char *argv[]) { int status = 0; struct sigaction act = {0}; int i = 0; pthread_t *reader; pthread_t writer; if (1 < argc) { num_of_readers = atoi(argv[1]); } reader = malloc(sizeof(pthread_t *) * num_of_readers); if (0 == reader) { PRINT_ERROR("malloc error"); return (1); } act.sa_handler = Handler; act.sa_flags = SIGINT; sigaction(SIGINT, &act, 0); status = pthread_mutex_init(&mutex, 0); if (0 != status) { PRINT_ERROR("pthread_mutex_intit error"); return (1); } status = pthread_cond_init(&cond_read, 0); if (0 != status) { PRINT_ERROR("cond_intit error"); return (1); } status = sem_init(&sem, 0, 0); if (0 != status) { PRINT_ERROR("sem_intit error"); return (1); } status = pthread_create(&writer, 0, WriteFunc, 0); if (0 != status) { PRINT_ERROR("pthread_create error"); return (1); } for (i = 0; i < num_of_readers; ++i) { status = pthread_create(&reader[i], 0, ReadFunc, 0); if (0 != status) { PRINT_ERROR("pthread_create error"); return (1); } } pthread_join(writer, 0); if (0 != status) { PRINT_ERROR("pthread_join error"); return (1); } for (i = 0; i < num_of_readers; ++i) { pthread_join(reader[i], 0); if (0 != status) { PRINT_ERROR("pthread_join error"); return (1); } } pthread_cond_destroy(&cond_read); free(reader); printf("exit ok\\n"); return (0); } void *WriteFunc(void *arg) { int i = 0; while (g_flag) { sem_wait(&sem); pthread_mutex_lock(&mutex); g_read_counter = 0; ++counter; printf("writer tid: %lu, data = %lu\\n", pthread_self(), counter); pthread_cond_broadcast(&cond_read); pthread_mutex_unlock(&mutex); } pthread_cond_broadcast(&cond_read); return (0); } void *ReadFunc(void *arg) { int x = counter; while (g_flag) { pthread_mutex_lock(&mutex); x = counter; ++g_read_counter; if (num_of_readers == g_read_counter) { sem_post(&sem); } while (counter == x) { pthread_cond_wait(&cond_read, &mutex); } pthread_mutex_unlock(&mutex); printf("\\t\\t\\t\\treader tid: %lu, data = %lu\\n", pthread_self(), counter); } x = !counter; sem_post(&sem); return (0); } void Handler(int signal_num) { g_flag = 0; puts("in handler"); return; }
0
#include <pthread.h> double variancia_threads = 0; double media_t = 0; static pthread_mutex_t mutexLock; struct parametros_calculo { int posicao; long int *v; }; void* calcula_variancia(void* args) { struct parametros_calculo* p = (struct parametros_calculo*) args; int i = p->posicao; while(i < (p->posicao + 12500)){ pthread_mutex_lock(&mutexLock); variancia_threads += (double) (p->v[i] - media_t) * (p->v[i] - media_t); pthread_mutex_unlock(&mutexLock); i++; } return 0; } int main (int argc, char* argv){ int i; long int v[50000]; for (i = 0; i < 50000; i++){ v[i] = random() % 501; } printf(">> Gerando vetor aleatório com numeros de 0 a 500...\\n"); sleep(1); int pid; pid = fork(); if(pid == 0){ int j; double variancia = 0, media = 0; printf("\\nO FILHO vai resolver pelo método padrão!\\n\\n"); for (j = 0; j < 50000; j++){ media += v[j]; } media = (double) media / 50000; for (j = 0; j < 50000; j++){ variancia += (double) (v[j] - media) * (v[j] - media); } variancia = (double) variancia / 50000; printf("FILHO: O valor da Variância é: %lf\\n", variancia); printf("FILHO TERMINOU!\\n\\n"); } else{ printf("\\nO PAI vai resolver o problema por threads!\\n"); pthread_mutex_init(&mutexLock, 0); for (i = 0; i < 50000; i++){ media_t += v[i]; } media_t = (double) media_t / 50000; pthread_t t01; pthread_t t02; pthread_t t03; pthread_t t04; struct parametros_calculo p01; struct parametros_calculo p02; struct parametros_calculo p03; struct parametros_calculo p04; p01.posicao = 0; p01.v = v; pthread_create (&t01, 0, &calcula_variancia, &p01); p02.posicao = 12500; p02.v = v; pthread_create (&t02, 0, &calcula_variancia, &p02); p03.posicao = 2500; p03.v = v; pthread_create (&t03, 0, &calcula_variancia, &p03); p04.posicao = 37500; p04.v = v; pthread_create (&t04, 0, &calcula_variancia, &p04); pthread_join(t01, 0); pthread_join(t02, 0); pthread_join(t03, 0); pthread_join(t04, 0); pthread_mutex_destroy(&mutexLock); variancia_threads = (double) variancia_threads / 50000; printf(">> PAI: A variância do vetor é: %lf\\n", variancia_threads); printf("PAI TERMINOU!\\n\\n"); } return 0; }
1
#include <pthread.h> char** theArray; pthread_mutex_t mutex; void* ServerEcho(void *args); int main(){ printf("creating mutex \\n"); pthread_mutex_init(&mutex,0); theArray=malloc(100*sizeof(char)); for (int i=0; i<100;i++){ theArray[i]=malloc(100*sizeof(char)); sprintf(theArray[i], "%s%d%s", "String ", i, ": the initial value" ); } struct sockaddr_in sock_var; int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0); int clientFileDescriptor; pthread_t* thread_handles; thread_handles = malloc(1000*sizeof(pthread_t)); sock_var.sin_addr.s_addr=inet_addr("127.0.0.1"); sock_var.sin_port=3000; sock_var.sin_family=AF_INET; if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0) { printf("socket has been created \\n"); listen(serverFileDescriptor,2000); while(1){ for(int i=0;i<1000;i++){ clientFileDescriptor=accept(serverFileDescriptor,0,0); printf("Connected to client %d \\n",clientFileDescriptor); pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor); } for(int i = 0;i<1000;i++){ pthread_join(thread_handles[i],0); } free(thread_handles); pthread_mutex_destroy(&mutex); printf("All threads have joined. Checking Array \\n"); for(int i=0;i<100;i++){ printf("%s\\n",theArray[i]); } for (int i=0; i<100;i++){ free(theArray[i]); } free(theArray); } } else{ printf("socket creation failed \\n"); return 1; } return 0; } void* ServerEcho(void* args){ long clientFileDescriptor = (long) args; char buff[100]; read(clientFileDescriptor,buff,100); int pos; char operation; sscanf(buff, "%d %c", &pos,&operation); printf("a Server thread recieved position %d and operation %c from %ld \\n",pos,operation,clientFileDescriptor); if(operation=='r'){ char msg[100]; pthread_mutex_lock(&mutex); sprintf(msg, "%s", theArray[pos] ); pthread_mutex_unlock(&mutex); write(clientFileDescriptor,msg,100); close(clientFileDescriptor); } else if(operation=='w'){ char msg[100]; sprintf(msg, "%s%d%s","String ", pos, " has been modified by a write request \\n" ); pthread_mutex_lock(&mutex); sprintf(theArray[pos],"%s",msg); pthread_mutex_unlock(&mutex); write(clientFileDescriptor,msg,100); close(clientFileDescriptor); } else{ printf("there has been an error communicating with client \\n"); } return 0; }
0
#include <pthread.h> pthread_mutex_t *muts; struct node ** list; int SIZE; void hash_init(int N) { printf("hash init\\n"); if(N <= MAXTH){ srand( time(0)); SIZE = 10; printf("Number of buckets is %d\\n", SIZE); list = (struct node**)malloc(SIZE * sizeof(struct node*)); muts = (pthread_mutex_t *)malloc(SIZE * sizeof(pthread_mutex_t)); int i; for(i = 0; i < SIZE; i++){ pthread_mutex_init(&muts[i], 0); } } else{ printf("N value is invalid\\n"); } } int hash_insert(int k) { pthread_mutex_lock(&muts[k%SIZE]); int index = k%SIZE; printf("hash inserting %d in bucket %d\\n", k, index); struct node * ptr = list[index]; if(ptr == 0){ list[index] = (struct node*)malloc(sizeof(struct node)); list[index] -> data = k; list[index] -> next = 0; pthread_mutex_unlock(&muts[index]); return 0; } else{ while(ptr -> next != 0){ printf("%d -> in bucket %d\\n", ptr->data, index); if(ptr -> data == k){ printf("zaten var %d\\n", k); pthread_mutex_unlock(&muts[index]); return -1; } ptr = ptr->next; } if(ptr -> data == k){ printf("zaten var ki %d\\n", k); pthread_mutex_unlock(&muts[index]); return -1; } ptr->next = (struct node*)malloc(sizeof(struct node)); ptr->next->data = k; ptr->next->next = 0; pthread_mutex_unlock(&muts[index]); return (0); } } int hash_delete(int k) { pthread_mutex_lock(&muts[k%SIZE]); int index = k%SIZE; printf("hash deleting %d from bucket %d\\n", k, index); struct node * ptr = list[index]; if(ptr != 0){ if(ptr -> data == k){ printf("deleting from %d -> in bucket %d\\n", ptr->data, index); list[index] = ptr -> next; free(ptr); printf("Das root is %d\\n", k); printf("after deleting %d from bucket %d, bucket is like\\n", k, index); pthread_mutex_unlock(&muts[index]); return 0; } } else{ printf("root is null for %d\\n", k); pthread_mutex_unlock(&muts[index]); return -1; } while(ptr->next != 0){ printf("Delete %d - %d -d> bucket: %d\\n", k, ptr->data, index); if(ptr -> next -> data == k){ struct node* temp = ptr -> next; ptr->next = ptr->next->next; free(temp); printf("after deleting %d from bucket %d, bucket is like\\n", k, index); pthread_mutex_unlock(&muts[index]); return 0; } printf("Allah\\n"); ptr = ptr->next; } printf("Can't delete %d\\n", k); pthread_mutex_unlock(&muts[index]); return -1; } int hash_get(int k) { pthread_mutex_lock(&muts[k%SIZE]); int index = k%SIZE; printf("get value %d in bucket %d\\n", k, index); struct node* ptr = list[index]; while(ptr != 0){ if(ptr -> data == k){ pthread_mutex_unlock(&muts[index]); return k; } } printf("got it the value %d in bucket %d\\n", k, index); pthread_mutex_unlock(&muts[index]); return -1; }
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 (top == 0) { printf("stack underflow\\n"); return -2; } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for (i = 0; i < 400; i++) { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { __CPROVER_assume(((400 - i) >= 0) && (i >= 0)); { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint() % 400; if (push(arr, tmp) == (-1)) error(); 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 (top > 0) { if (pop(arr) == (-2)) error(); } pthread_mutex_unlock(&m); } } } int main(void) { pthread_t id1; pthread_t id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> struct csema { pthread_mutex_t m_mutex; pthread_cond_t m_cond; int m_count; }; void csema_ctr(struct csema* p) { memset(p, 0, sizeof(*p)); pthread_mutex_init(&p->m_mutex, 0); pthread_cond_init(&p->m_cond, 0); } void csema_dtr(struct csema* p) { pthread_cond_destroy(&p->m_cond); pthread_mutex_destroy(&p->m_mutex); } void csema_p(struct csema* p, const int n) { pthread_mutex_lock(&p->m_mutex); while (p->m_count < n) pthread_cond_wait(&p->m_cond, &p->m_mutex); p->m_count -= n; pthread_cond_signal(&p->m_cond); pthread_mutex_unlock(&p->m_mutex); } void csema_v(struct csema* p) { pthread_mutex_lock(&p->m_mutex); p->m_count++; pthread_cond_signal(&p->m_cond); pthread_mutex_unlock(&p->m_mutex); } struct cthread { pthread_t m_thread; int m_threadnum; struct csema* m_sema; }; void cthread_ctr(struct cthread* p) { p->m_thread = 0; p->m_sema = 0; } void cthread_dtr(struct cthread* p) { } static int s_debug = 0; static int s_trace = 0; static int s_signal_count; static pthread_mutex_t s_mutex; static pthread_cond_t s_cond; static void thread_func(struct cthread* thread_info) { int i; pthread_mutex_lock(&s_mutex); for (i = 0; i < s_signal_count; i++) { if (s_trace) { printf("thread %d [%d] (1)\\n", thread_info->m_threadnum, i); } csema_v(thread_info->m_sema); pthread_cond_wait(&s_cond, &s_mutex); if (s_trace) { printf("thread %d [%d] (2)\\n", thread_info->m_threadnum, i); } } pthread_mutex_unlock(&s_mutex); } int main(int argc, char** argv) { int optchar; int thread_count; while ((optchar = getopt(argc, argv, "d")) != EOF) { switch (optchar) { case 'd': s_debug = 1; break; default: assert(0); break; } } alarm(100); s_signal_count = argc > optind ? atoi(argv[optind]) : 10; thread_count = argc > optind + 1 ? atoi(argv[optind + 1]) : 10; if (s_debug) printf("&s_cond = %p\\n", &s_cond); pthread_mutex_init(&s_mutex, 0); pthread_cond_init(&s_cond, 0); { int i; struct csema sema; struct cthread* p; struct cthread* thread_vec; csema_ctr(&sema); thread_vec = malloc(sizeof(struct cthread) * thread_count); for (p = thread_vec; p != thread_vec + thread_count; p++) { cthread_ctr(p); p->m_threadnum = p - thread_vec; p->m_sema = &sema; pthread_create(&p->m_thread, 0, (void*(*)(void*))thread_func, &*p); } for (i = 0; i < s_signal_count; i++) { if (s_trace) printf("main [%d] (1)\\n", i); csema_p(&sema, thread_count); if (s_trace) printf("main [%d] (2)\\n", i); pthread_mutex_lock(&s_mutex); pthread_cond_broadcast(&s_cond); pthread_mutex_unlock(&s_mutex); if (s_trace) printf("main [%d] (3)\\n", i); } for (i = 0; i < thread_count; i++) { pthread_join(thread_vec[i].m_thread, 0); cthread_dtr(&thread_vec[i]); } free(thread_vec); csema_dtr(&sema); } pthread_cond_destroy(&s_cond); pthread_mutex_destroy(&s_mutex); fprintf(stderr, "Done.\\n"); return 0; }
1
#include <pthread.h> struct pthread_args { int iterations; pthread_mutex_t mutex; }; void * pi_thread(void *ptr) { double tsum = 0; struct pthread_args *args = (struct pthread_args*)ptr; for(;;) { pthread_mutex_lock(&(args->mutex)); int i = args->iterations; args->iterations += 10; pthread_mutex_unlock(&(args->mutex)); if(i + 10 > 1000000000) break; double low = 0.5 * 1.0/1000000000 + 1.0/1000000000 * i; double upp = 1.0/1000000000 * (i + 10); while(low < upp) { tsum += sqrt(1-low*low) * 1.0/1000000000; low += 1.0/1000000000; } } double *local_sum = malloc(sizeof(*local_sum)); *local_sum = tsum; return local_sum; } void main() { long num_threads = 4; double sum = 0; pthread_t *thread; void *lsum; struct pthread_args thread_arg = {0, PTHREAD_MUTEX_INITIALIZER}; thread = malloc((unsigned long)num_threads * sizeof(*thread)); for (int i = 0; i < num_threads; i++) { pthread_create(thread + i, 0, &pi_thread, &thread_arg); } for (int i = 0; i < num_threads; i++) { pthread_join(thread[i], &lsum ); sum += 4 * (*(double*)lsum); free(lsum); } printf("Reference PI = %.10lf Computed PI = %.10lf\\n", M_PI, sum); printf("Difference to Reference is %.10lf\\n", M_PI - sum); }
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 = 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(&hash_lock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hash_lock); pthread_mutex_unlock(&fp->f_lock); } return fp; } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return fp; } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id) % 29); tfp = fh[idx]; if (tfp == fp) fh[idx] = fp->f_next; else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> int w, h; v2df zero = { 0.0, 0.0 }; v2df four = { 4.0, 4.0 }; v2df nzero; double inverse_w; double inverse_h; char *whole_data; int y_pick; pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER; static void * worker(void *_args) { char *data; double x, y; int bit_num; char byte_acc = 0; for (;;) { pthread_mutex_lock(&y_mutex); y = y_pick; y_pick++; pthread_mutex_unlock(&y_mutex); if (y >= h) return 0; data = &whole_data[(w >> 3) * (int)y]; for(bit_num=0,x=0;x<w;x+=2) { v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 }; v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 }; v2df Zrv = { 0.0, 0.0 }; v2df Ziv = { 0.0, 0.0 }; v2df Trv = { 0.0, 0.0 }; v2df Tiv = { 0.0, 0.0 }; int i = 0; int mask; do { Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ; Zrv = Trv - Tiv + Crv; Trv = Zrv * Zrv; Tiv = Ziv * Ziv; v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four ); mask = __builtin_ia32_movmskpd(delta); } while (++i < 50 && (mask)); byte_acc <<= 2; byte_acc |= mask; bit_num+=2; if(!(bit_num&7)) { data[(bit_num>>3) - 1] = byte_acc; byte_acc = 0; } } if(bit_num&7) { byte_acc <<= (8-w%8); bit_num += 8; data[bit_num>>3] = byte_acc; byte_acc = 0; } } } int main (int argc, char **argv) { pthread_t ids[8]; int i; nzero = -zero; w = h = atoi(argv[1]); inverse_w = 2.0 / w; inverse_h = 2.0 / h; y_pick = 0; whole_data = malloc(w * (w >> 3)); for (i = 0; i < 8; i++) pthread_create(&ids[i], 0, worker, 0); for (i = 0; i < 8; i++) pthread_join(ids[i], 0); pthread_mutex_destroy(&y_mutex); printf("P4\\n%d %d\\n",w,h); fwrite(whole_data, h, w >> 3, stdout); free(whole_data); return 0; }
0
#include <pthread.h> pthread_mutex_t m; pthread_cond_t cl, ce; int ecriture; int nb_lecteurs, nb_lect_att, nb_ecri_att; } lectred; int nb; struct linked_list *next; } linked_list; struct lectred sync; struct linked_list *head; } linked_list_head; linked_list_head llh; void init(lectred* l) { pthread_mutex_init(&(l->m), 0); pthread_cond_init(&(l->cl), 0); pthread_cond_init(&(l->ce), 0); l->ecriture = 0; l->nb_lect_att = 0; l->nb_ecri_att = 0; l->nb_lecteurs = 0; } void begin_read(lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1){ l->nb_lect_att++; pthread_cond_wait(&(l->cl), &(l->m)); l->nb_lect_att--; } l->nb_lecteurs++; pthread_mutex_unlock(&(l->m)); } void end_read(lectred* l) { pthread_mutex_lock(&(l->m)); l->nb_lecteurs--; if(l->nb_lect_att == 0){ pthread_cond_signal(&(l->cl)); } pthread_mutex_unlock(&(l->m)); } void begin_write(lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1 || l->nb_lecteurs > 0){ l->nb_ecri_att++; pthread_cond_wait(&(l->ce), &(l->m)); l->nb_ecri_att--; } l->ecriture = 1; pthread_mutex_unlock(&(l->m)); } void end_write(lectred* l) { pthread_mutex_lock(&(l->m)); l->ecriture = 0; if(l->nb_lect_att > 0){ pthread_cond_broadcast(&(l->cl)); } else if(l->nb_ecri_att > 0){ pthread_cond_signal(&(l->ce)); } pthread_mutex_unlock(&(l->m)); } void list_init(linked_list_head *list) { list->head = 0; init(&list->sync); } int exists(struct linked_list_head *list, int val) { begin_read(&list->sync); printf("thread %u lit\\n", (unsigned int) pthread_self()); sleep(rand() % 5); end_read(&list->sync); return 0; } linked_list* add_elem(linked_list_head* list, int val) { begin_write(&list->sync); printf("thread %u écrit\\n", (unsigned int) pthread_self()); sleep(rand() % 5); end_write(&list->sync); return list->head; } linked_list* remove_element(struct linked_list_head *list, int val) { begin_write(&list->sync); end_write(&list->sync); return list->head; } void* lecteurs() { int r = rand() % (10-1) + 1; if (exists(&llh, r)) {} return (void *) pthread_self(); } void* redacteurs() { int r = rand() % (10-1) + 1; add_elem(&llh, r); return (void *) pthread_self() ; } int main (int argc, char** argv) { if (argc != 3) { printf("Usage : <nb_lecteurs> <nb_redacteurs>\\n"); } int nb_lecteurs = atoi(argv[1]); int nb_redacteurs = atoi(argv[2]); int i=0; list_init(&llh); printf("liste initialisée\\n"); pthread_t tids[nb_redacteurs + nb_lecteurs]; for (; i < nb_redacteurs; i++){ pthread_create(&tids[i], 0, &redacteurs, 0); } printf("rédacteurs créés\\n"); for (; i < nb_lecteurs+nb_redacteurs; i++){ pthread_create(&tids[i], 0, &lecteurs, 0); } printf("lecteurs créés\\n"); for (i = 0; i < nb_lecteurs+nb_redacteurs; i++){ pthread_join(tids[i], 0); } }
1
#include <pthread.h> struct thread_args { int allocation_size; int array_size; int thread_count; }; struct timespec timer_start() { struct timespec start_time; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time); return start_time; } long timer_end(struct timespec start_time) { struct timespec end_time; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time); long diffInNanos = (end_time.tv_nsec) - (start_time.tv_nsec); return diffInNanos; } int MAX_SIZE = 1024 * 1024; int MAX_ALLOCATION_ARRAY_SIZE = 500; char TEST_OUT_FILE[] = "result.tsv"; int MAX_THREADS = 500; FILE *result_file; pthread_mutex_t result_file_mutex = PTHREAD_MUTEX_INITIALIZER; void * nice_thread_run(void *args) { int allocation_size, array_size, thread_count; allocation_size = ((struct thread_args *)args)->allocation_size; array_size = ((struct thread_args *)args)->array_size; thread_count = ((struct thread_args *)args)->thread_count; int i = 0; void **test_arr; long time_elapsed_nanos; struct timespec starttime = timer_start(); test_arr = malloc(array_size * sizeof(void*)); for(i = 0; i < array_size; i++) { test_arr[i] = malloc(allocation_size); if(0 == test_arr) { break; } } time_elapsed_nanos = timer_end(starttime); for(i = 0; i < array_size; i++) { if(0 != test_arr[i]) { free(test_arr[i]); } } free(test_arr); pthread_mutex_lock(&result_file_mutex); fprintf(result_file, "%d\\t%d\\t%d\\t%ld\\n", thread_count, allocation_size, array_size, time_elapsed_nanos); pthread_mutex_unlock(&result_file_mutex); return 0; } int main() { result_file = fopen(TEST_OUT_FILE, "w+"); int thread_count = 50; int i = 0; pthread_t tid[10000]; int array_size = 1; int allocation_size = 8; struct thread_args arg; while (thread_count <= MAX_THREADS) { printf(" Thread count, n = %d \\n", thread_count); while(allocation_size < MAX_SIZE) { array_size = 1; while (array_size < MAX_ALLOCATION_ARRAY_SIZE) { arg.allocation_size = allocation_size; arg.array_size = array_size; arg.thread_count = thread_count; for(i = 0; i < thread_count; i++) { pthread_create(&tid[i], 0, nice_thread_run, (void *)&arg); } for(i = 0; i < thread_count; i++) { pthread_join(tid[i], 0); } array_size *= 10; } allocation_size *= 2; } allocation_size = 8; thread_count += 50; } fclose(result_file); return 0; }
0
#include <pthread.h> int my_num=500; pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t win= PTHREAD_MUTEX_INITIALIZER; int client_guessed=0; int winner_thread=-1; pthread_t threads[10]; int client_count=0; int thread_count=0; void* worker(void*param){ struct sockaddr_in* sock=(struct sockaddr_in*)param; int* c2=(int*)param; int c=*c2; client_count=thread_count; int myId=client_count; printf("client from \\n"); char msg[200]; send(c,msg,strlen(msg),0); while(client_guessed==0){ int number; recv(c,&number,sizeof(number),0); number=ntohl(number); if(client_guessed)break; int no=thread_count; no=htonl(no); send(c,&no,sizeof(no),0); if(number>my_num){ char b='S'; send(c,&b,sizeof(b),0); } if(number<my_num){ char b='H'; send(c,&b,sizeof(b),0); } if(number==my_num){ pthread_mutex_lock(&mylock); client_guessed=1; if(winner_thread==-1) winner_thread=myId; pthread_mutex_unlock(&mylock); } } if(client_guessed){ if(myId==winner_thread){ char b='G'; send(c,&b,sizeof(b),0); printf("we have a winner, thread number %d\\n",myId); pthread_mutex_unlock(&win); close(c); } else{ int no=thread_count; no=htonl(no); send(c,&no,sizeof(no),0); char b='L'; send(c,&b,sizeof(b),0); printf("thread %d looser\\n",myId); } } printf("worker thread has finally come to rest\\n"); } void* resetServer(void*param){ while(1){ pthread_mutex_lock(&win); int i; for(i=0;i<thread_count;i++){ pthread_join(threads[i],0); threads[i]=0; } printf("all threads finished\\n"); pthread_mutex_lock(&mylock); client_guessed=0; winner_thread=-1; client_count=0; my_num=rand()%10000-1; printf("server number: %d\\n",my_num); pthread_mutex_unlock(&mylock); }} int main(){ int s; struct sockaddr_in server, client; int c, l; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { printf("Eroare la crearea socketului server\\n"); return 1; } memset(&server, 0, sizeof(server)); server.sin_port = htons(1234); server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; if (bind(s, (struct sockaddr *) &server, sizeof(server)) < 0) { printf("Eroare la bind\\n"); return 1; } l=sizeof(client); listen(s, 5); pthread_t daemon; pthread_mutex_lock(&win); pthread_create(&daemon,0,resetServer,0); while(1){ c=accept(s,(struct sockaddr*)&client,&l); printf("%d is c\\n",c); pthread_create(&threads[thread_count++],0,worker,(void*)&c); } close(c); return 0; }
1
#include <pthread.h> void (*function)(void*); void* argument; } pool_task_t; pthread_mutex_t lock; pthread_cond_t notify; pthread_t *threads; pool_task_t *queue; int thread_count; int task_queue_size_limit; int head; int tail; } pool_t; static void *thread_do_work(void *thread_pool); pool_t *pool_create(int thread_count, int queue_size) { int i; pool_t* pool = (pool_t*)malloc(sizeof(pool_t)); pthread_mutex_init(&(pool->lock), 0); pthread_cond_init(&(pool->notify), 0); pool->threads = (pthread_t*)malloc(sizeof(pthread_t) * thread_count); for(i = 0; i < thread_count; i++) pthread_create(&(pool->threads[i]), 0, thread_do_work, (void*)pool); pool->queue = (pool_task_t*)malloc(sizeof(pool_task_t) * (queue_size + 1)); pool->thread_count = thread_count; pool->task_queue_size_limit = queue_size; pool->head = 0; pool->tail = 0; return pool; } int pool_add_task(pool_t *pool, void (*function)(void*), void* argument) { int err = 0; int end = pool->tail; if ((end + 1) % (pool->task_queue_size_limit + 1) != pool->head) { pool->queue[end].function = function; pool->queue[end].argument = argument; end = (end + 1) % (pool->task_queue_size_limit + 1); err = pthread_cond_signal(&(pool->notify)); } return err; } int pool_destroy(pool_t *pool) { int err = 0; int i; for(i = 0; i < pool->thread_count; ++i) { pthread_join(pool->threads[i], 0); } free((void*)pool->queue); free((void*)pool->threads); free((void*)pool); return err; } static void *thread_do_work(void *thread_pool) { pool_t* pool = (pool_t*)thread_pool; while(1) { pthread_mutex_lock(&(pool->lock)); if(pool->head != pool->tail) { pool_task_t task = pool->queue[pool->head]; if(task.function == 0) { pthread_mutex_unlock(&(pool->lock)); pthread_exit(0); } pool->head = (pool->head + 1) % (pool->task_queue_size_limit + 1); pthread_mutex_unlock(&(pool->lock)); (task.function)(task.argument); return 1; } pthread_cond_wait(&(pool->notify), &(pool->lock)); if(pool->head != pool->tail) { pool_task_t task = pool->queue[pool->head]; if(task.function == 0) { pthread_mutex_unlock(&(pool->lock)); pthread_exit(0); } pool->head = (pool->head + 1) % (pool->task_queue_size_limit + 1); pthread_mutex_unlock(&(pool->lock)); (task.function)(task.argument); return 0; } } pthread_exit(0); return(0); }
0
#include <pthread.h> int many_handles = 1; int fd; const char * filename; uint64_t stride; uint64_t offset; uint64_t last; uint64_t write_size; pthread_cond_t cond; pthread_mutex_t mutex; struct worker * next; } worker; void * func(void * argp) { worker * arg = argp; void * buf; buf = malloc(2*arg->write_size); buf = (void*)(((intptr_t)buf) & ~((intptr_t)arg->write_size-1)); memset(buf, 0, arg->write_size); pthread_mutex_lock(&arg->mutex); uint64_t offset = 0; if(many_handles) { arg->fd = open(arg->filename, O_WRONLY|O_SYNC); if(arg->fd == -1) { perror("Couldn't open file"); abort(); } } while(offset < arg->last) { while(arg->offset == 0) { pthread_cond_wait(&arg->cond, &arg->mutex); } offset = arg->offset; arg->offset = 0; pthread_mutex_lock(&arg->next->mutex); arg->next->offset = offset + 1; pthread_mutex_unlock(&arg->next->mutex); pthread_cond_signal(&arg->next->cond); int err = pwrite(arg->fd, buf, arg->write_size, arg->stride * offset * arg->write_size); if(err == -1) { perror("Couldn't write"); abort(); } assert(err && err == arg->write_size); } pthread_mutex_unlock(&arg->mutex); if(many_handles) { close(arg->fd); } return 0; } int main(int argc, char * argv[]) { if(argc != 6) { printf("usage: %s filename num_workers num_ops write_size stride", argv[0]); fflush(stdout); abort(); } int NUM_WORKERS = atoi(argv[2]); uint64_t ops = atoll(argv[3]); int write_size = atoi(argv[4]); worker * workers = malloc(sizeof(worker) * NUM_WORKERS); pthread_t* threads = malloc(sizeof(pthread_t) * NUM_WORKERS); uint64_t stride = atoll(argv[5]); int fd = -1; if(!many_handles) { fd = open(argv[1], O_WRONLY|O_SYNC); } for(int i = 0; i < NUM_WORKERS; i++) { workers[i].fd = fd; workers[i].filename = argv[1]; workers[i].offset = 0; workers[i].last = ops; workers[i].write_size = write_size; workers[i].stride = stride; pthread_cond_init(&workers[i].cond,0); pthread_mutex_init(&workers[i].mutex,0); workers[i].next = &workers[(i+1) % NUM_WORKERS]; } for(int i = 0; i < NUM_WORKERS; i++) { pthread_create(&threads[i], 0, func, &workers[i]); } struct timeval start, stop; gettimeofday(&start, 0); workers[0].offset = 1; pthread_cond_signal(&workers[0].cond); for(int i = 0; i < NUM_WORKERS; i++) { pthread_join(threads[i], 0); } gettimeofday(&stop, 0); double elapsed = stasis_timeval_to_double(stasis_subtract_timeval(stop,start)); double ops_per_sec = ((double)ops) / elapsed; printf("%lld ops in %f seconds = %f ops/second, %f speedup, %f mb/sec\\n", (long long)ops, elapsed, ops_per_sec, ops_per_sec/ ( 5400.0/60.0), ((double)ops*write_size)/(1024.0*1024.0*elapsed)); if(!many_handles) { close(fd); } return 0; }
1
#include <pthread.h> void* frame_base; struct RINGBUFFER; { void *pBuffer[4]; unsigned int indexInsert; unsigned int indexRemove; unsigned int count; pthread_mutex_t mutex; sem_t semEmpty; sem_t semFull; void (*f_addBuffer)(struct RINGBUFFER *ringBuffer, void *buffer); void (*f_getBuffer)(struct RINGBUFFER *ringBuffer, void **buffer); } T_RINGBUFFER; void addBuffer(T_RINGBUFFER *ringBuffer, void *buffer) { sem_wait(&(ringBuffer->semFull)); pthread_mutex_lock(&(ringBuffer->mutex)); if (ringBuffer->count < 4) { ringBuffer->pBuffer[ringBuffer->indexInsert] = buffer; if (++(ringBuffer->indexInsert) >= 4) { ringBuffer->indexInsert = 0; } ringBuffer->count++; } pthread_mutex_unlock(&(ringBuffer->mutex)); sem_post(&(ringBuffer->semEmpty)); } void getBuffer(T_RINGBUFFER *ringBuffer, void **buffer) { sem_wait(&(ringBuffer->semEmpty)); pthread_mutex_lock(&(ringBuffer->mutex)); if (ringBuffer->count > 0) { *buffer = ringBuffer->pBuffer[ringBuffer->indexRemove]; if (++(ringBuffer->indexRemove) >= 4) { ringBuffer->indexRemove = 0; } ringBuffer->count--; } pthread_mutex_unlock(&(ringBuffer->mutex)); sem_post(&(ringBuffer->semFull)); } void initRingBuffer(T_RINGBUFFER *ringBuffer) { ringBuffer->count = 0; ringBuffer->indexInsert = 0; ringBuffer->indexRemove = 0; ringBuffer->f_addBuffer = addBuffer; ringBuffer->f_getBuffer = getBuffer; sem_init(&(ringBuffer->semFull), 0, 4); sem_init(&(ringBuffer->semEmpty), 0, 0); pthread_mutex_init(&(ringBuffer->mutex), 0); } int fd; void *fd_mem; void *frame_base; T_RINGBUFFER ringBufferIdle; T_RINGBUFFER ringBufferImagesToNet; void *buffers[4]; int errOk; struct hostent *hp; struct sockaddr_in socket_in; int int_socket; void initSocket(char* ip) { hp = gethostbyname(ip); if (!hp) { exit(1); } bzero((char *)&socket_in, sizeof(socket_in)); socket_in.sin_family = AF_INET; bcopy(hp->h_addr, (char *)&socket_in.sin_addr, hp->h_length); socket_in.sin_port = htons(4444); if ((int_socket = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("socket: socket error"); exit(1); } if (connect(int_socket, (struct sockaddr *)&socket_in, sizeof(socket_in)) < 0) { perror("socket: connect error"); close(int_socket); exit(1); } } void f_bufferProducer() { void *imgBuffer; while (errOk) { ringBufferIdle.f_getBuffer(&ringBufferIdle, &imgBuffer); memcpy(imgBuffer, frame_base, 2592*1944); ringBufferImagesToNet.f_addBuffer(&ringBufferImagesToNet, imgBuffer); } } void f_bufferConsumer() { void *netBuffer; while(errOk) { ringBufferImagesToNet.f_getBuffer(&ringBufferImagesToNet, &netBuffer); if (send(int_socket, netBuffer, 2592*1944, 0) < 0) { printf("error sending data ...\\n"); errOk = 0; } else { ringBufferIdle.f_addBuffer(&ringBufferIdle, netBuffer); } } } void init() { int it; fd = open("/dev/mem", (O_RDWR|O_SYNC)); fd_mem = (void *) malloc(2592*1944*sizeof(char)); frame_base = mmap(0,0x500000,(PROT_READ|PROT_WRITE),MAP_SHARED,fd,0x38000000); initRingBuffer(&ringBufferIdle); initRingBuffer(&ringBufferImagesToNet); errOk = 1; for (it=0; it<4; ++it) { buffers[it] = (void *) malloc(2592*1944*sizeof(char)); ringBufferIdle.f_addBuffer(&ringBufferIdle, buffers[it]); } } void terminate() { int it; for (it=0; it<4; ++it) { free(buffers[it]); } close(int_socket); } int main(int argc, char* argv[]) { init(); initSocket(argv[1]); pthread_t bufferProducer, bufferConsumer; int err; err = pthread_create(&bufferProducer, 0, f_bufferProducer, 0); if (err) { exit(1); } err = pthread_create(&bufferConsumer, 0, f_bufferConsumer, 0); if (err) { exit(1); } pthread_join(bufferProducer, 0); pthread_join(bufferConsumer, 0); terminate(); }
0
#include <pthread.h> struct rt_extrRoadStationTime *extrRoadStationTime(int *findErr) { struct rt_extrRoadStationTime *rt; int num; FILE *fp; mxml_node_t *root; mxml_node_t *item; int statNo; int tmisNo; int routeNo; int bifurcation_distance; int bifurcation_speed; int up_down_trip = -1; num = 0; rt = (struct rt_extrRoadStationTime *)malloc(sizeof(struct rt_extrRoadStationTime)); if(rt == 0){ fprintf(stderr, "malloc0 failed\\n"); *findErr = MALLOC_FAILED; return 0; } rt->ptr = (struct EXTRACT_FR_STT *)malloc(sizeof(struct EXTRACT_FR_STT) * 80); if(rt->ptr == 0){ fprintf(stderr, "malloc1 failed\\n"); *findErr = MALLOC_FAILED; return 0; } pthread_mutex_lock(&trip_num_s.mutex_s_trip_num); up_down_trip = trip_num_s.trip_num % 2; pthread_mutex_unlock(&trip_num_s.mutex_s_trip_num); if (up_down_trip == 1) { fp = fopen("./RawData/roadStationTime_down.xml", "r"); } else { fp = fopen("./RawData/roadStationTime_up.xml", "r"); } if(fp == 0){ perror("fopen"); *findErr = CFG_OPEN_ERR; return 0; } root = mxmlLoadFile(0, fp, MXML_TEXT_CALLBACK); fclose(fp); if(root == 0){ fprintf(stderr, "mxmlLoadFile() err!\\n"); *findErr = CFG_LOAD_ERR; return 0; } item = mxmlFindElement(root, root, "Item", 0, 0, MXML_DESCEND); if(item == 0){ fprintf(stderr, "mxmlFindElement() err!\\n"); *findErr = CFG_FIND_ELEMENT_ERR; return 0; } for(; item != 0; item = mxmlFindElement(item, root, "Item", 0, 0,MXML_DESCEND)){ statNo = atoi(mxmlElementGetAttr(item,"station")); tmisNo = atoi(mxmlElementGetAttr(item,"tmis_num")); routeNo = atoi(mxmlElementGetAttr(item,"route_num")); bifurcation_distance = atoi(mxmlElementGetAttr(item,"bifurcation_distance")); bifurcation_speed = atoi(mxmlElementGetAttr(item,"bifurcation_speed")); rt->ptr[num].station = statNo; rt->ptr[num].tmis = tmisNo; rt->ptr[num].route_num = routeNo; rt->ptr[num].bifurcation_distance = bifurcation_distance; rt->ptr[num].bifurcation_speed = bifurcation_speed; num = num + 1; if(item == 0){ break; } } rt->ptr_size = num; return rt; } void delete(struct rt_extrRoadStationTime *pt) { free(pt); pt = 0; }
1
#include <pthread.h> int VT_mc34704_OC_setup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_OC_cleanup(void) { int rv = TFAIL; rv = TPASS; return rv; } int VT_mc34704_test_OC(void) { int fd; fd = open(MC34704_DEVICE, O_RDWR); if (fd < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to open %s", MC34704_DEVICE); pthread_mutex_unlock(&mutex); return TFAIL; } if (close(fd) < 0) { pthread_mutex_lock(&mutex); tst_resm(TFAIL, "Unable to close file descriptor %d", fd); pthread_mutex_unlock(&mutex); return TFAIL; } return TPASS; }
0
#include <pthread.h> static int top=0; static unsigned int arr[(10)]; pthread_mutex_t m; _Bool flag=(0); 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==(10)) { 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; for(i=0; i<(10); i++) { pthread_mutex_lock(&m); assert(push(arr,i)!=(-1)); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for(i=0; i<(10); i++) { pthread_mutex_lock(&m); if (flag) assert(pop(arr)!=(-2)); pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> double _glfwPlatformGetTime( void ) { struct timeval tv; gettimeofday( &tv, 0 ); return tv.tv_sec + (double) tv.tv_usec / 1000000.0 - _glfwTimer.t0; } void _glfwPlatformSetTime( double time ) { struct timeval tv; gettimeofday( &tv, 0 ); _glfwTimer.t0 = tv.tv_sec + (double) tv.tv_usec / 1000000.0 - time; } void _glfwPlatformSleep( double time ) { struct timeval currenttime; struct timespec wait; pthread_mutex_t mutex; pthread_cond_t cond; long dt_sec, dt_usec; gettimeofday( &currenttime, 0 ); dt_sec = (long) time; dt_usec = (long) ((time - (double)dt_sec) * 1000000.0); wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L; if( wait.tv_nsec > 1000000000L ) { wait.tv_nsec -= 1000000000L; dt_sec ++; } wait.tv_sec = currenttime.tv_sec + dt_sec; pthread_mutex_init( &mutex, 0 ); pthread_cond_init( &cond, 0 ); pthread_mutex_lock( &mutex ); pthread_cond_timedwait( &cond, &mutex, &wait ); pthread_mutex_unlock( &mutex ); pthread_mutex_destroy( &mutex ); pthread_cond_destroy( &cond ); }
0
#include <pthread.h> struct _qsd_pool { qsd_pool *next; qsd_pool *prev; void *data; void *cur; size_t data_sz; pthread_mutex_t pool_lock; }; static qsd_pool *pool_list_head = 0; static qsd_pool *pool_list_tail = 0; static pthread_mutex_t pool_list_lock = PTHREAD_MUTEX_INITIALIZER; qsd_pool *get_new_pool () { qsd_pool *new_pool; new_pool = (qsd_pool *) malloc(sizeof(qsd_pool)); new_pool->data = new_pool->cur = (void *)malloc(1000); new_pool->data_sz = 1000; new_pool->prev = 0; pthread_mutex_init (&(new_pool->pool_lock),0); pthread_mutex_lock (&pool_list_lock); if (!pool_list_head) { pool_list_head = pool_list_tail = new_pool; new_pool->next = 0; } else { pool_list_head->prev = new_pool; new_pool->next = pool_list_head; pool_list_head = new_pool; } pthread_mutex_unlock (&pool_list_lock); return new_pool; } void qsd_delete_pool (qsd_pool *p) { if (!p) return; pthread_mutex_lock (&pool_list_lock); if (!p->next && !p->prev) { pool_list_head = pool_list_tail = 0; } else if (p == pool_list_head) { p->next->prev = 0; pool_list_head = p->next; } else if (p == pool_list_tail) { p->prev->next = 0; pool_list_tail = p->prev; } else { p->prev->next = p->next; p->next->prev = p->prev; } pthread_mutex_unlock (&pool_list_lock); free(p->data); free(p); } void *qsd_pmalloc (qsd_pool *p, size_t size) { pthread_mutex_lock (&(p->pool_lock)); if (p->cur + size < p->data + p->data_sz) { void *ret = p->cur; p->cur += size; pthread_mutex_unlock (&(p->pool_lock)); return ret; } pthread_mutex_unlock (&(p->pool_lock)); return (void *) 0; } void *go2(qsd_pool *p) { void *buf1 = qsd_pmalloc(p,10); void *buf2 = qsd_pmalloc(p,10); void *buf3 = qsd_pmalloc(p,10); return 0; } void *go1(void *x) { qsd_pool *p = get_new_pool(); void *buf1 = qsd_pmalloc(p,10); pthread_t t1; pthread_create(&t1, 0, go2, p); buf1 = qsd_pmalloc(p,10); buf1 = qsd_pmalloc(p,10); } int main() { pthread_t t1,t2; pthread_create(&t1, 0, go1, 0); pthread_create(&t1, 0, go1, 0); }
1
#include <pthread.h> int global_PULSE = 1000; int PIN = 7; pthread_mutex_t lock; void setup() { wiringPiSetup (); int PULSE = 1000; pinMode (PIN,OUTPUT); int arming_time; digitalWrite(PIN,HIGH); for (arming_time = 0; arming_time < 200; arming_time++) { digitalWrite(PIN,HIGH); delayMicroseconds(PULSE); digitalWrite(PIN,LOW); delay(20 - (PULSE/1000)); } } void input_wait(void *ptr) { int *current_val; current_val = (int *) ptr; while (1) { pthread_mutex_lock(&lock); printf("Enter New Value:"); scanf("%d",current_val); pthread_mutex_unlock(&lock); } } int main() { setup(); pthread_mutex_init (&lock,0); printf("Enter Starting Motor Pulse Speed in MicroSecond: "); scanf("%d",&global_PULSE); pthread_t thread; pthread_create(&thread, 0, (void *) &input_wait, (void *) &global_PULSE); int test = global_PULSE; while (1) { digitalWrite(PIN,HIGH); delayMicroseconds(global_PULSE); digitalWrite(PIN,LOW); delay(20 - (global_PULSE/1000)); } pthread_join(&thread,0); printf("\\nCurrent: %d\\n", global_PULSE); return (0); }
0
#include <pthread.h> extern int dev_buzzer_fd; extern char dev_buzzer_mask; extern pthread_mutex_t mutex_buzzer; extern pthread_cond_t cond_buzzer; void *pthread_buzzer (void *arg) { struct input_event event; if ((dev_buzzer_fd = open (DEV_BUZZER, O_RDWR | O_NONBLOCK)) < 0) { printf ("Cann't open file /dev/beep\\n"); exit (-1); } printf ("pthread_buzzer is ok\\n"); while (1) { pthread_mutex_lock (&mutex_buzzer); pthread_cond_wait (&cond_buzzer, &mutex_buzzer); printf ("pthread_buzzer is wake up\\n"); if (dev_buzzer_mask){ event.type = EV_SND; event.code = SND_TONE; event.value = 100; write(dev_buzzer_fd, &event, sizeof(struct input_event)); printf("**buzzer on\\n"); }else{ event.type = EV_SND; event.code = SND_TONE; event.value = 0; write(dev_buzzer_fd, &event, sizeof(struct input_event)); printf("**buzzer off\\n"); } pthread_mutex_unlock (&mutex_buzzer); } return 0; }
1
#include <pthread.h> int *arr; int tid; int size; int nthreads; double *time; } params; int pairmax(int *arr, int startIndex, int endIndex); void *threadParallelSum( void *ptr ); double maximum(double a, double b); long upper_power_of_two(long v); static int globalmax = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; main() { int fileno, nthreads, size; char *file; printf("Select the file name: (Press 1 or 2 or 3)\\n 1.1 million entries\\n 2.2 million entries\\n 3.4 million entries\\n"); scanf("%d", &fileno); switch(fileno){ case 1: printf("File one\\n"); size = 100000; file = "random100000.txt"; break; case 2: printf("File two\\n"); size = 200000; file = "random200000.txt"; break; case 3: printf("File three\\n"); size = 400000; file = "random400000.txt"; break; case 4: printf("File three\\n"); size = 32; file = "random32.txt"; break; } printf("Enter the number of threads : (1, 2, 4, 8, 16)\\n"); scanf("%d", &nthreads); int arr[size]; double time[nthreads], globalTime; FILE *myFile; myFile = fopen(file, "r"); int i = 0; int j = 0 ; fscanf (myFile, "%d", &i); while (!feof (myFile)) { arr[j] = i; j++; fscanf (myFile, "%d", &i); } fclose (myFile); pthread_t threads[nthreads]; params *thread_params = (params*) malloc(nthreads*sizeof(params)); for( i = 0; i < nthreads; i++) { thread_params[i].arr = arr; thread_params[i].tid = i; thread_params[i].size = size; thread_params[i].nthreads = nthreads; thread_params[i].time = time; pthread_create(&threads[i], 0, threadParallelSum, (void*) &thread_params[i]); } for( i = 0; i < nthreads; i++) { pthread_join(threads[i], 0); } for(i = 0; i < nthreads; i++){ globalTime = maximum(globalTime,time[i]); } printf("globalmax : %d , and GlobalTime : %f seconds\\n", globalmax, globalTime); exit(0); } void *threadParallelSum( void *ptr ) { clock_t startT, endT; double cpu_time_used; params *p = (params *) ptr; int tid = p->tid; int chunk_size = (p -> size / p -> nthreads); int start = tid * chunk_size; int end = start + chunk_size; startT = clock(); int threadmax = pairmax(p->arr, start, end-1); pthread_mutex_lock( &mutex1 ); globalmax = maximum(threadmax,globalmax); pthread_mutex_unlock( &mutex1 ); endT = clock(); cpu_time_used = ((double) (endT - startT)) / CLOCKS_PER_SEC; p->time[tid] = cpu_time_used; printf("Time taken by individual thread %d is %f seconds\\n", tid, cpu_time_used); return 0; } int pairmax(int *arr, int startIndex, int endIndex) { if(endIndex-startIndex == 1) { return maximum(arr[startIndex], arr[endIndex]); } else if (endIndex-startIndex == 0) { return maximum(arr[endIndex],arr[endIndex]); } int m = upper_power_of_two((endIndex-startIndex)+1); if( m == (endIndex-startIndex)+1) { m = ((endIndex-startIndex)+1)/2; } int left = pairmax(arr,startIndex,startIndex+m-1); int right = pairmax(arr,startIndex+m,endIndex); return maximum(left,right); } long upper_power_of_two(long v) { v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return (v >> 1)+1; } double maximum(double a , double b) { if(a>b) { return a; } else { return b; } }
0
#include <pthread.h> unsigned int nthreads = 30; int load_grid(int grid[][9], char *filename); int grid[9][9]; int erros = 0; int nextTask = 0; pthread_mutex_t mutexErr, mutexTask; void checkCol(int col) { for (int i = 0; i < 9; i++) { for (int j = i + 1; j < 9; j++) { if (grid[i][col] == grid[j][col]) { printf("Erro na coluna %d!\\n", col + 1); pthread_mutex_lock(&mutexErr); erros++; pthread_mutex_unlock(&mutexErr); return; } } } } void checkRow(int row) { for (int i = 0; i < 9; i++) { for (int j = i + 1; j < 9; j++) { if (grid[row][i] == grid[row][j]) { printf("Erro na linha %d!\\n", row + 1); pthread_mutex_lock(&mutexErr); erros++; pthread_mutex_unlock(&mutexErr); return; } } } } void checkReg(int reg) { int rowBase = (reg / 3) * 3; int rowLimit = ((reg + 3)/ 3) * 3; int colBase = (reg % 3) * 3; int colLimit = ((reg % 3) + 1) * 3; int regVector[9]; int k = -1; for (int i = rowBase; i < rowLimit; i++) { for (int j = colBase; j < colLimit; j++) { regVector[++k] = grid[i][j]; } } for (int i = 0; i < 9; i++) { for (int j = i + 1; j < 9; j++) { if (regVector[i] == regVector[j]) { printf("Erro na região %d!\\n", reg + 1); pthread_mutex_lock(&mutexErr); erros++; pthread_mutex_unlock(&mutexErr); return; } } } } void *check(void* arg) { pthread_mutex_lock(&mutexTask); while (nextTask < 27) { int task; switch ((nextTask / 9)) { case 0: task = nextTask % 9; nextTask++; pthread_mutex_unlock(&mutexTask); checkCol(task); break; case 1: task = nextTask % 9; nextTask++; pthread_mutex_unlock(&mutexTask); checkRow(task); break; case 2: task = nextTask % 9; nextTask++; pthread_mutex_unlock(&mutexTask); checkReg(task); break; } pthread_mutex_lock(&mutexTask); } pthread_mutex_unlock(&mutexTask); return 0; } int main(int argc, char **argv) { if(argc != 3) { printf("Usage: ./t1_v1 file.txt number_threads\\n"); exit(0); } char *gridFile = argv[1]; nthreads = atoi(argv[2]); if(nthreads > 27) nthreads = 27; load_grid(grid, gridFile); pthread_mutex_init(&mutexErr, 0); pthread_mutex_init(&mutexTask, 0); pthread_t thread[nthreads]; for (int i = 0; i < nthreads; i++) { pthread_create(&thread[i], 0, check, 0); } for (int i = 0; i < nthreads; i++) { pthread_t t = thread[i]; pthread_join(t, 0); } printf("%d erros.\\n", erros); pthread_mutex_destroy(&mutexErr); pthread_mutex_destroy(&mutexTask); pthread_exit(0); } int load_grid(int grid[][9], char *filename) { FILE *input_file = fopen(filename, "r"); if (input_file != 0) { for(int i = 0; i < 9; i++) for(int j = 0; j < 9; j++) fscanf(input_file, "%d", &grid[i][j]); fclose(input_file); return 1; } 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 const *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); return 0; }
0
#include <pthread.h> pthread_mutex_t M; int DATA = 0; int accessi1 = 0; int accessi2 = 0; void *thread1_process (void * arg) { int k = 1; while (k) { pthread_mutex_lock(&M); accessi1++; DATA++; k = (DATA >= 10 ? 0 : 1); printf("accessi di T1: %d\\n", accessi1); pthread_mutex_unlock(&M); } pthread_exit (0); } void *thread2_process (void * arg) { int k=1; while (k) { pthread_mutex_lock(&M); accessi2++; DATA++; k = (DATA >= 10 ? 0 : 1); printf("accessi di T2: %d\\n", accessi2); pthread_mutex_unlock(&M); } pthread_exit (0); } int main(int argc, char *argv[]) { pthread_t th1, th2; pthread_mutex_init (&M, 0); if (pthread_create(&th1, 0, thread1_process, 0) < 0) { fprintf (stderr, "create error for thread 1\\n"); exit (1); } if (pthread_create(&th2, 0,thread2_process,0) < 0) { fprintf (stderr, "create error for thread 2\\n"); exit (1); } pthread_join (th1, 0); pthread_join (th2, 0); }
1
#include <pthread.h> long thread_count; long long n; double sum; pthread_mutex_t mutex; void GET_TIME(double now) { struct timeval t; gettimeofday(&t, 0); now = t.tv_sec + t.tv_usec/1000000.0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long i; long long my_n = n/thread_count; long long my_first_i = my_n*my_rank; long long my_last_i = my_first_i + my_n; double my_sum = 0.0; if (my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for (i = my_first_i; i < my_last_i; i++, factor = -factor) { my_sum += factor/(2*i+1); } pthread_mutex_lock(&mutex); sum += my_sum; pthread_mutex_unlock(&mutex); return 0; } double Serial_pi(long long n) { double sum = 0.0; long long i; double factor = 1.0; for (i = 0; i < n; i++, factor = -factor) { sum += factor/(2*i+1); } return 4.0*sum; } int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; double start, finish; thread_count = strtol(argv[1], 0, 10); n = strtoll(argv[2], 0, 10); thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t)); pthread_mutex_init(&mutex, 0); GET_TIME(start); sum = 0.0; for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*)thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); sum = 4.0*sum; GET_TIME(finish); printf("con n = %lld condiciones,\\n", n); printf(" estimado de pi = %.15f\\n", sum); printf("tiempo %e \\n", finish - start); GET_TIME(start); sum = Serial_pi(n); GET_TIME(finish); printf("estimado simle thread= %.15f\\n", sum); printf("tiempo es %e\\n", finish - start); printf("pi = %.15f\\n", 4.0*atan(1.0)); pthread_mutex_destroy(&mutex); free(thread_handles); return 0; }
0
#include <pthread.h> void error(const char * msg){ fprintf(stderr, "%s: %s\\n", strerror(errno)); exit(1); } pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER; int beers = 2000000; void* drink_lots(void* a){ int i; pthread_mutex_lock(&beers_lock); for(i = 0; i < 100000; i++){ beers = beers - 1; } pthread_mutex_unlock(&beers_lock); printf("beers = %i\\n", beers); return 0; } int main(int argc, char const *argv[]) { pthread_t threads[20]; int t; printf("%i bottles of beer on the wall\\n%i bottles of beer\\n", beers, beers); for(t = 0; t < 20; t++){ if(pthread_create(&threads[t], 0, drink_lots, 0) == -1) error("Failed to create thread"); } void* result; for(t = 0; t < 20; t++){ if(pthread_join(threads[t], &result) == -1) error("Can't join thread"); } printf("There are now %i bottles of beer on the wall\\n", beers); return 0; }
1
#include <pthread.h> int count; struct foo *m_fp; 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; 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_rele(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); m_fp=0; printf("fp is free!!!\\n"); } else { pthread_mutex_unlock(&hashlock); } } void *thr_fn(void *arg) { while(m_fp!=0){ foo_hold(m_fp); printf("thread %u is using foo.\\n",(unsigned int)pthread_self()); sleep(1); } printf("thread %u has no foo to use.\\n",(unsigned int)pthread_self()); } void main() { int i,err; unsigned int ntid; for(i=0;i<29;++i) fh[i]=0; m_fp=foo_alloc(); for(i=0;i<5;++i){ err=pthread_create((pthread_t *)(&ntid),0,thr_fn,0); if(err!=0) err_quit("can't create thread:%s \\n",strerror(err)); } sleep(5); while(m_fp!=0){ printf("usage count: %d\\n",m_fp->f_count); foo_rele(m_fp); } printf("usage count: 0\\n"); sleep(10); }
0
#include <pthread.h> struct hdr_mutex* hdr_mutex_alloc(void) { return malloc(sizeof(hdr_mutex)); } void hdr_mutex_free(struct hdr_mutex* mutex) { free(mutex); } int hdr_mutex_init(struct hdr_mutex* mutex) { return pthread_mutex_init(&mutex->_mutex, 0); } void hdr_mutex_destroy(struct hdr_mutex* mutex) { pthread_mutex_destroy(&mutex->_mutex); } void hdr_mutex_lock(struct hdr_mutex* mutex) { pthread_mutex_lock(&mutex->_mutex); } void hdr_mutex_unlock(struct hdr_mutex* mutex) { pthread_mutex_unlock(&mutex->_mutex); } void hdr_yield() { sched_yield(); } int hdr_usleep(unsigned int useconds) { return usleep(useconds); }
1
#include <pthread.h> static int global_time = 100; pthread_mutex_t lock; struct _pulse pulse; } my_message_t; void *time_update( void *ptr ); void *teller_1( void *ptr ); void *teller_2( void *ptr ); void *teller_3( void *ptr ); struct Customer { int time_in; int time_out; struct Customer* next; }*rear, *front; void delQueue() { printf("DeQueue!\\n"); pthread_mutex_lock(&lock); struct Customer *temp, *var=rear; if(var==rear) { rear = rear->next; free(var); } else printf("\\nQueue Empty"); pthread_mutex_unlock(&lock); } void push(int value) { printf("Push\\n"); pthread_mutex_lock(&lock); struct Customer *temp; temp=(struct Customer *)malloc(sizeof(struct Customer)); temp->time_in=value; if (front == 0) { front=temp; front->next=0; rear=front; } else { front->next=temp; front=temp; front->next=0; } pthread_mutex_unlock(&lock); } void display() { printf("Display\\n"); pthread_mutex_lock(&lock); struct Customer *var=rear; if(var!=0) { printf("\\nElements are as: "); while(var!=0) { pthread_mutex_lock(&lock); printf("\\t%d",var->time_in); pthread_mutex_unlock(&lock); var=var->next; } printf("\\n"); } else printf("\\nQueue is Empty"); pthread_mutex_unlock(&lock); } int main(int *argc, char ***argv) { pthread_t thread0, thread1, thread2, thread3; const char *message1 = "Teller 1"; const char *message2 = "Teller 2"; const char *message3 = "Teller 3"; int next_customer_in_time; int timerThread, tellerThread1, tellerThread2, tellerThread3; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } timerThread = pthread_create( &thread0, 0, time_update, (void*) message1); tellerThread1 = pthread_create( &thread1, 0, teller_1, (void*) message1); tellerThread2 = pthread_create( &thread2, 0, teller_2, (void*) message2); while (global_time > 0){ push(global_time); usleep(100000); display(); } pthread_join( thread1, 0); pthread_join( thread2, 0); pthread_mutex_destroy(&lock); printf("Teller 1 returns: %d\\n",timerThread); printf("Teller 1 returns: %d\\n",tellerThread1); printf("Teller 2 returns: %d\\n",tellerThread2); printf("Teller 3 returns: %d\\n",tellerThread3); exit(0); } void *time_update( void *ptr ) { struct sigevent event; struct itimerspec itime; timer_t timer_id; int chid, rcvid; my_message_t msg; chid = ChannelCreate(0); event.sigev_notify = SIGEV_PULSE; event.sigev_coid = ConnectAttach(ND_LOCAL_NODE, 0, chid, _NTO_SIDE_CHANNEL, 0); event.sigev_priority = getprio(0); event.sigev_code = _PULSE_CODE_MINAVAIL; timer_create(CLOCK_REALTIME, &event, &timer_id); itime.it_value.tv_sec = 0; itime.it_value.tv_nsec = 100000000; itime.it_interval.tv_sec = 0; itime.it_interval.tv_nsec = 100000000; timer_settime(timer_id, 0, &itime, 0); for (;;) { rcvid = MsgReceive(chid, &msg, sizeof(msg), 0); if (rcvid == 0) { if (msg.pulse.code == _PULSE_CODE_MINAVAIL) { if (global_time > 0) global_time--; else break; } } } } void *teller_1( void *ptr ) { usleep(500000); while(global_time > 0){ int customer_time; customer_time = rand() % 25 + 1; usleep( 50000 * customer_time ); delQueue(); printf("This is from Thread_1.\\n"); } } void *teller_2( void *ptr ) { usleep(500000); while(global_time > 0){ int customer_time; customer_time = rand() % 25 + 1; usleep( 50000 * customer_time); printf("This is from Thread_2.\\n"); } } void *teller_3( void *ptr ) { while(global_time > 0){ int customer_time; customer_time = rand() % 12 + 1; printf("teller_3 : global_time = %d and customer_time = %d min\\n", global_time, ((customer_time / 2) + (customer_time %2)) ); usleep( 50000 * customer_time ); } }
0
#include <pthread.h> extern pthread_mutex_t mutex_refresh; extern pthread_mutex_t mutex_refresh_updata; extern pthread_mutex_t mutex_global; extern pthread_mutex_t mutex_slinklist; extern pthread_cond_t cond_refresh; extern pthread_cond_t cond_refresh_updata; extern pthread_cond_t cond_sqlite; extern char cgi_status; extern char qt_status; extern int shmid; extern int semid; extern struct env_info_clien_addr all_info_RT; struct shm_addr { char cgi_status; char qt_status; struct env_info_clien_addr rt_status; }; void *pthread_refresh (void *arg) { key_t key_info; int shmid, semid; struct shm_addr *shm_buf; if ((key_info = ftok ("/app", 'i')) < 0) { perror ("ftok info"); exit (-1); } printf ("key = %d\\n", key_info); if ((semid = semget (key_info, 1, IPC_CREAT | IPC_EXCL |0666)) < 0) { if (errno == EEXIST) { semid = semget (key_info, 1, 0666); } else { perror ("semget"); exit (-1); } } else { init_sem (semid, 0, 1); } if ((shmid = shmget (key_info, 1024, IPC_CREAT | IPC_EXCL | 0666)) < 0) { if (errno == EEXIST) { shmid = shmget (key_info, 1024, 0666); shm_buf = (struct shm_addr *)shmat (shmid, 0, 0); } else { perror ("shmget"); exit (-1); } } else { if ((shm_buf = (struct shm_addr *)shmat (shmid, 0, 0)) == (void *)-1) { perror ("shmat"); exit (-1); } } bzero (shm_buf, sizeof (struct shm_addr)); printf ("pthread_refresh is ok\\n"); while (1) { pthread_mutex_lock (&mutex_refresh); pthread_cond_wait (&cond_refresh, &mutex_refresh); sem_p (semid, 0); pthread_mutex_lock (&mutex_global); shm_buf->rt_status = all_info_RT; pthread_mutex_unlock (&mutex_global); sem_v (semid, 0); pthread_mutex_unlock (&mutex_refresh); } return 0; }
1
#include <pthread.h> pthread_mutex_t lockclassroom; pthread_cond_t cv_students; pthread_mutex_t lockquestion; void* answerqestion(void); void Student(int id,pthread_t studentId[]); void* EnterOffice(int id); void QuestionStart(int id); void QuestionDone(int id); void LeaveOffice(int id); void AnswerStart(int id); void AnswerDone(int id); void* Professor(int id); int student_count = 0; int totalS = 0; int Nforks; int classcapasity; int question[2]; int main(int argc, char *argv[]) { if (argc > 2) { if((Nforks = atoi(argv[1]))){ classcapasity = atoi(argv[2]); } else { printf("Try again with 2 Integers separate them by a space\\n"); return -1; } }else{ printf("Try again with 2 Integers separate them by a space\\n"); return -1; } pthread_t studentId[Nforks]; pthread_t prof; pthread_mutex_init(&lockclassroom,0); pthread_mutex_init(&lockquestion,0); pthread_cond_init(&cv_students,0); for (int i=0; i<Nforks;i++) { Student(i,studentId); } pthread_create(&prof, 0, &Professor, 0); for (int i=0; i<Nforks;i++){ pthread_join(studentId[i], 0); } pthread_join(prof,0); pthread_mutex_destroy(&lockquestion); pthread_mutex_destroy(&lockclassroom); pthread_cond_destroy(&cv_students); return 1; } void* Professor(int id){ while(1) { if (question[0] == 1){ AnswerStart(question[1]); AnswerDone(question[1]); question[0] =2; } if (totalS == Nforks){ pthread_exit(0); } } } void Student(int id, pthread_t studentId[]){ pthread_create(&studentId[id], 0, &EnterOffice, (int *)id); } void* EnterOffice( int id){ int Squestion = (id % 4) + 1; if (random() > 32767 / 2){ usleep(10); } pthread_mutex_lock(&lockclassroom); if (student_count>= classcapasity){ pthread_cond_wait(&cv_students, &lockclassroom); } student_count++; pthread_mutex_unlock(&lockclassroom); printf("Student %d shows up in the office \\n",id); for (int i=0; i< Squestion; i++){ if (random() > 32767 / 2){ usleep(10); } pthread_mutex_lock(&lockquestion); QuestionStart(id); question[1]=id; question[0]=1; while(1){ if(question[0]==2){ QuestionDone(id); question[0]=0; break; } } pthread_mutex_unlock(&lockquestion); } LeaveOffice(id); totalS++; pthread_exit(0); } void QuestionStart(int id){ printf("Student %d asks a question\\n",id); } void QuestionDone(int id){ printf("Student %d is satisfied\\n",id); } void LeaveOffice(int id){ printf("Student %d leaves the office.\\n",id); pthread_mutex_lock(&lockclassroom); student_count--; pthread_cond_signal(&cv_students); pthread_mutex_unlock(&lockclassroom); } void AnswerStart(int id){ printf("Professor starts to answer question for student %d\\n",id); } void AnswerDone(int id){ printf("Professor is done with answer for student %d \\n",id); }
0
#include <pthread.h> int N = 0; int P = 0; int C = 0; int X = 0; int Ptime = 0; int Ctime = 0; int *buffer; pthread_mutex_t queue_lock; sem_t queue_empty, queue_full; void enqueue(int value) { int i = 0; for(i=0; i<N; i++) { if(buffer[i]==0){ buffer[i]=value; break; } } fprintf(stderr, "Queue complete \\n"); } void dequeue() { int out = buffer[0],i; fprintf(stderr, "Dequeue complete \\n"); for(i=0;i<X;i++); { buffer[i-1]=buffer[i]; } buffer[N-1]=0; } void spinwait(int times) { int i; for(i=0; i<times; i++); } void producerthread(void *thread) { int i; for(i=1; i<=X;i++) { fprintf(stderr,"Producer thread i=%d \\n", i); sem_wait(&queue_empty); pthread_mutex_lock(&queue_lock); enqueue(i); pthread_mutex_unlock(&queue_lock); sem_post(&queue_full); spinwait(Ptime*100000); } } void consumerthread(void *thread) { printf("spawning consumer \\n"); int i; for (i=1; i<(P*X/C); i++) { sem_wait(&queue_full); pthread_mutex_lock(&queue_lock); dequeue(); pthread_mutex_unlock(&queue_lock); sem_post(&queue_empty); spinwait(Ctime*100000); } } int main(int argc, char *argv[]) { int returnValue, J, H, i; void *arg; pthread_t thread; pthread_t *tids; buffer = calloc(N,sizeof(int)); tids = calloc((P+C),sizeof(pthread_t)); if((pthread_mutex_init(&queue_lock,0))<0) { perror("Can't initialize mutex \\n"); exit(-1); } if (argc != 7) { printf("7 Arguments required \\n", "Program name, N, P, C, X, Ptime, Ctime "); exit(0); } N = atoi(argv[1]); P = atoi(argv[2]); C = atoi(argv[3]); X = atoi(argv[4]); Ptime = atoi(argv[5]); Ctime = atoi(argv[6]); sem_init(&queue_empty, 0, N); sem_init(&queue_full,0,0); clock_t begin, end, final; begin = clock(); fprintf(stderr,"Startime %d \\n",((int)begin)); for (J = 0;J<C; J++){ if((pthread_create(&tids[J], 0,(void*)consumerthread,arg))<0){ perror("Thread Creation Unsuccessful\\n"); exit(-1); } } for (H = 0;H <P; H++){ if((pthread_create(&tids[C+H], 0,(void*)producerthread,arg))<0) { perror("Thread Creation Unsuccessful \\n"); exit(-1); } } for(i=0;i<(P+C);i++) { pthread_join(tids[i],0); } end = clock(); int total = (end-begin); fprintf(stderr, "final time %d \\n", ((int)end)); double finalsec =((double)total/CLOCKS_PER_SEC); fprintf(stderr, "total execution time %f \\n",finalsec); }
1
#include <pthread.h> int id; int claseCliente; } Cliente; sem_t cajGeneral; sem_t cajEmpresarial; pthread_mutex_t mutex; int contGeneral=0; int contEmpresarial=0; void * procesoGeneral(void*); void * procesoEmpresarial(void*); int main(int argc, const char * argv[]) { srand (time(0)); sem_init(&cajGeneral, 0, 5); sem_init(&cajEmpresarial, 0, 3); pthread_t * hilos = (pthread_t *)malloc(sizeof(pthread_t)*150); int clientesGenerales=101; int clientesEmpresariales=51; pthread_mutex_init(&mutex, 0); Cliente* param; int i=0; for (i=0; i< 150; ++i){ param = malloc (sizeof(Cliente)); param->id = i; param->claseCliente = (rand()%2)+1; if (clientesGenerales == 0 && param->claseCliente == 1){ param->claseCliente == 2; } if (clientesEmpresariales == 0 && param->claseCliente == 2){ param->claseCliente == 1; } if ((param->claseCliente)==1){ pthread_create((hilos+i),0, procesoGeneral, (void *) param); clientesGenerales--; } else if((param->claseCliente)==2){ pthread_create((hilos+i),0, procesoEmpresarial, (void *) param); clientesEmpresariales--; } } for (i = 0; i < 150; ++i) { pthread_join(*(hilos+i), 0); } sem_destroy(&cajGeneral); sem_destroy(&cajEmpresarial); free(hilos); free (param); return 0; } void * procesoGeneral(void* param){ int tiempoLlegada, tiempoEspera; tiempoLlegada = (rand()%171)+50; sleep(tiempoLlegada); int numCajero; if (contGeneral<=5){ sem_wait(&cajGeneral); sem_getvalue(&cajGeneral, &numCajero); tiempoEspera = (rand()%4)+2; sleep(tiempoEspera); pthread_mutex_lock(&mutex); contGeneral++; pthread_mutex_unlock(&mutex); sem_post(&cajGeneral); } else{ sem_getvalue(&cajGeneral, &numCajero); sleep(3); pthread_mutex_lock(&mutex); contGeneral=0; pthread_mutex_unlock(&mutex); } pthread_exit(0); } void * procesoEmpresarial(void* param){ int tiempoLlegada, tiempoEspera; tiempoLlegada = (rand()%251)+90; sleep (tiempoLlegada); int numCajero; if(contEmpresarial<=5){ sem_wait(&cajEmpresarial); sem_getvalue(&cajEmpresarial, &numCajero); tiempoEspera = 1; sleep(tiempoEspera); pthread_mutex_lock(&mutex); contEmpresarial++; pthread_mutex_unlock(&mutex); sem_post(&cajEmpresarial); } else{ sem_getvalue(&cajEmpresarial, &numCajero); sleep(3); pthread_mutex_lock(&mutex); contEmpresarial=0; pthread_mutex_unlock(&mutex); } pthread_exit(0); }
0
#include <pthread.h> int My_pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn)(void *), void *arg) { int result=pthread_create(tidp,attr,start_rtn,arg); if(0!=result) { printf("thread(0x%x) call pthread_create failed,because %s\\n", pthread_self(),strerror(result)); }else { printf("thread(0x%x) call pthread_create ok,new thread id is 0x%x\\n", pthread_self(),*tidp); } return result; } void print_thread_id() { printf("current thread id is 0x%x\\n",pthread_self()); } void thread_join_int(pthread_t tid, int *rval_pptr) { int val=pthread_join(tid,rval_pptr); if(0!=val) { printf("thread 0x%x call pthread_join(0x%x,%p) failed,because %s\\n", pthread_self(),tid,rval_pptr,strerror(val)); }else { if(0==rval_pptr) printf("thread 0x%x call pthread_join(0x%x,%p) ok\\n" ,pthread_self(),tid,rval_pptr); else printf("thread 0x%x call pthread_join(0x%x,%p) ok,thread returns %d\\n" ,pthread_self(),tid,rval_pptr,*rval_pptr); } } static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; static void* thread_func (void* arg) { pthread_mutex_lock(&mutex); printf("\\n****** Begin Thread:thread id=0x%x ******\\n",pthread_self()); print_thread_id(); printf("arg is %d\\n",arg); printf("****** End Thread:thread id=0x%x ******\\n\\n",pthread_self()); pthread_mutex_unlock(&mutex); return arg; } void test_thread_create() { M_TRACE("--------- Begin test_thread_create() ---------\\n"); pthread_mutex_lock(&mutex); pthread_t threads[3]; for(int i=0;i<3;i++) My_pthread_create(threads+i,0,thread_func,i); pthread_mutex_unlock(&mutex); int values[3]; for(int i=0;i<3;i++) { thread_join_int(threads[i],values+i); } M_TRACE("--------- End test_thread_create() ---------\\n\\n"); }
1
#include <pthread.h> long long unsigned int in = 0; unsigned int n_threads, nval, *id; pthread_t *monte_carlo_threads; pthread_mutex_t monte_carlo_mutex; void *monte_carlo_pi_thread(void *rank) { unsigned int my_rank = *((unsigned int*) rank); int local_size = nval / n_threads, i_start = my_rank * local_size, i_end = (my_rank == n_threads - 1 ? nval - 1 : (my_rank + 1) * local_size - 1); long long unsigned int local_in = 0, i; double x, y, d; for (i = i_start; i <= i_end; i++) { x = ((rand_r(&my_rank) % 1000000)/500000.0)-1; y = ((rand_r(&my_rank) % 1000000)/500000.0)-1; d = ((x*x) + (y*y)); if (d <= 1) local_in += 1; } pthread_mutex_lock(&monte_carlo_mutex); in += local_in; pthread_mutex_unlock(&monte_carlo_mutex); return 0; } void monte_carlo_pi() { unsigned int i; for (i = 0; i < n_threads; i++) { id[i] = i; pthread_create(&monte_carlo_threads[i], 0, monte_carlo_pi_thread, (void*) &id[i]); } for (i = 0; i < n_threads; i++) pthread_join(monte_carlo_threads[i], 0); } int main(void) { double pi; long unsigned int duracao; struct timeval start, end; scanf("%u %u", &n_threads, &nval); monte_carlo_threads = (pthread_t*) malloc (n_threads * sizeof(pthread_t)); pthread_mutex_init(&monte_carlo_mutex, 0); id = (unsigned int *) malloc (n_threads * sizeof(unsigned int)); srand (time(0)); gettimeofday(&start, 0); monte_carlo_pi(); gettimeofday(&end, 0); duracao = ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)); pi = 4*in / ((double) nval); printf("%lf\\n%lu\\n",pi,duracao); free(id); free(monte_carlo_threads); pthread_mutex_destroy(&monte_carlo_mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; char *services[25] = {"AddTwoNumbers","SubtractTwoNumbers","MultiplyTwoNumbers","DivideTwoNumbers", "Square","SquareRoot","Area","Volume","Perimeter","Circumference","SurfaceArea","Integrate", "Differentiate","Power","Logarithm","StringLength","Encryption","Decryption","EdgeDetection", "FFT","RayTracing","VolumeRendering","ZBuffer","TextureMapping","MotionBlur"}; int *request; int **param; int count; char *str = "Work on this string."; void *server_handler() { int j; printf("\\n............Server is online......... \\n"); while(1){ for (int i = 0; i < count; ++i) { pthread_mutex_lock(&mutex); if(request[i] > 0 && request[i] < 30){ if (param[i][0] != -1) { printf("\\nSERVER : Matching <%d, %d, %s", i+1, request[i], services[request[i] - 1]); j=1; while(param[i][j] != 0){ printf(", %d",param[i][j]); param[i][j] = 0; ++j; } printf(">, which is requested by client[%d]\\n", i+1); }else{ printf("\\nSERVER : Matching <%d, %d, %s, \\"%s\\">, which is requested by client[%d]\\n", i+1, request[i], services[request[i] - 1],str,i+1); } request[i] = 30; printf("\\nSERVER : matching is done succesfully..........\\n"); } pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } } } void *client_handler( void *ptr ) { int i; int cli = *(int *) ptr; int x = cli; ++cli; int parameters; srand((unsigned) time(0)); int z = (rand()%25); z += 1; if((z>0 && z<5) || z==7 || z==9 || z==11 || z==14 || z==19 || z==21 || z==22){ parameters = 2; }else if (z==5 || z==6 || z==10 || z==15){ parameters = 1; }else if (z==16 || z==17 || z==18){ parameters = 0; }else { parameters = 3; } pthread_mutex_lock(&mutex); request[x] = z; if (parameters != 0){ param[x] = malloc((parameters+1) * sizeof(int)); srand((unsigned) time(0)); for (i = 1; i <= parameters; ++i) { param[x][i] = (rand()%100) + 1; } printf("\\nCLIENT[%d] : Request tuple created <%d, %d , %s", cli, cli, request[x], services[request[x] - 1]); for (i = 1; i <= parameters; ++i) { printf(", %d", param[x][i]); } printf(">\\n"); }else{ param[x] = malloc(sizeof(int)); param[x][0] = -1; printf("\\nCLIENT[%d] : Request tuple created <%d, %d , %s,\\"%s\\">\\n", cli, cli, request[x], services[request[x] - 1],str); } while(request[x] != 30){ pthread_cond_wait(&cond,&mutex); } request[x] = 0; printf("\\nCLIENT[%d] : I got the service.\\n",cli); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } int main(int argc, char const *argv[]) { pthread_t s, c; srand((unsigned) time(0)); count = (rand()%15) + 1; int i; request = malloc(count * sizeof(int)); param = malloc(count * sizeof(int *)); if (param == 0){ fprintf(stderr, "out of memory\\n"); exit(0); } if( pthread_create( &s, 0, &server_handler, 0) < 0) { perror("could not create thread"); return 1; } for (i = 0; i < count; ++i) { if( pthread_create( &c, 0, &client_handler, (void *) &i) < 0) { perror("could not create thread"); return 1; } sleep(1); pthread_join(c, 0); } free(request); for(i = 0; i < count; i++) free(param[i]); free(param); exit(0); }
1
#include <pthread.h> static const char alphabet[] = "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789"; static const int alphabet_size = sizeof(alphabet) - 1; static const int max_chars = 20; int current_number_chars = 0; bool success_decrypt = 0; char* md5_to_decrypt; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; char* get_md5(const char *string) { unsigned char result[MD5_DIGEST_LENGTH]; char md5_string[33]; MD5((unsigned char*)string, strlen(string), (unsigned char*)&result); int i; for(i = 0; i < MD5_DIGEST_LENGTH; i++) { sprintf(&md5_string[i*2], "%02x", (unsigned int)result[i]); } return &md5_string; } void brute_force_token_matcher(char *str, int index, int max_size){ for (int i = 0; i < alphabet_size; ++i){ if(success_decrypt) { pthread_exit(&success_decrypt); } str[index] = alphabet[i]; if (index == max_size - 1){ if(strcmp(get_md5(str), md5_to_decrypt) == 0) { pthread_mutex_lock(&lock); printf("\\nMD5 '%s' match as '%s'!\\n", md5_to_decrypt, str); success_decrypt = 1; pthread_mutex_unlock(&lock); pthread_exit(&success_decrypt); } } else { brute_force_token_matcher(str, index + 1, max_size); } } } void brute_sequential(int max_length){ char* buf = malloc(max_length + 1); for (int i = 1; i <= max_length; ++i){ memset(buf, 0, max_length + 1); brute_force_token_matcher(buf, 0, i); } free(buf); } void *brute_match_md5(void *thread_id) { while(current_number_chars <= max_chars) { pthread_mutex_lock(&lock); current_number_chars += 1; printf("\\nTrying match %d sized strings concurrently...", current_number_chars); pthread_mutex_unlock(&lock); brute_sequential(current_number_chars); } pthread_exit(0); } int main (int argc, char *argv[]) { int num_cpus = sysconf(_SC_NPROCESSORS_CONF); int threads_number = num_cpus * 2; md5_to_decrypt = argv[1]; printf("Running with %d threads", threads_number); printf("\\nTrying to decrypt: %s", md5_to_decrypt); pthread_t threads[threads_number]; int thread_id; for(thread_id = 0; thread_id < threads_number; thread_id++){ pthread_create(&threads[thread_id], 0, brute_match_md5, (void *) &thread_id); } pthread_exit(0); }
0
#include <pthread.h> pthread_t threads[2]; struct sched_param nrt_param; pthread_mutex_t rsrcA, rsrcB; volatile int rsrcACnt=0, rsrcBCnt=0, noWait=0; void *grabRsrcs(void *threadid) { if((int)threadid == 1) { printf("THREAD 1 grabbing resources\\n"); pthread_mutex_lock(&rsrcA); rsrcACnt++; if(!noWait) usleep(1000000); printf("THREAD 1 got A, trying for B\\n"); pthread_mutex_lock(&rsrcB); rsrcBCnt++; printf("THREAD 1 got A and B\\n"); pthread_mutex_unlock(&rsrcB); pthread_mutex_unlock(&rsrcA); printf("THREAD 1 done\\n"); } else { printf("THREAD 2 grabbing resources\\n"); pthread_mutex_lock(&rsrcB); rsrcBCnt++; if(!noWait) usleep(1000000); printf("THREAD 1 got B, trying for A\\n"); pthread_mutex_lock(&rsrcA); rsrcACnt++; printf("THREAD 2 got B and A\\n"); pthread_mutex_unlock(&rsrcA); pthread_mutex_unlock(&rsrcB); printf("THREAD 2 done\\n"); } pthread_exit(0); } int main (int argc, char *argv[]) { int rc, safe=0; rsrcACnt=0, rsrcBCnt=0, noWait=0; if(argc < 2) { printf("Will set up unsafe deadlock scenario\\n"); } else if(argc == 2) { if(strncmp("safe", argv[1], 4) == 0) safe=1; else if(strncmp("race", argv[1], 4) == 0) noWait=1; else printf("Will set up unsafe deadlock scenario\\n"); } else { printf("Usage: deadlock [safe|race|unsafe]\\n"); } pthread_mutex_init(&rsrcA, 0); pthread_mutex_init(&rsrcB, 0); printf("Creating thread %d\\n", 1); rc = pthread_create(&threads[0], 0, grabRsrcs, (void *)1); if (rc) {printf("ERROR; pthread_create() rc is %d\\n", rc); perror(0); exit(-1);} printf("Thread 1 spawned\\n"); if(safe) { if(pthread_join(threads[0], 0) == 0) printf("Thread 1: %d done\\n", (int)threads[0]); else perror("Thread 1"); } printf("Creating thread %d\\n", 2); rc = pthread_create(&threads[1], 0, grabRsrcs, (void *)2); if (rc) {printf("ERROR; pthread_create() rc is %d\\n", rc); perror(0); exit(-1);} printf("Thread 2 spawned\\n"); printf("rsrcACnt=%d, rsrcBCnt=%d\\n", rsrcACnt, rsrcBCnt); printf("will try to join CS threads unless they deadlock\\n"); if(!safe) { if(pthread_join(threads[0], 0) == 0) printf("Thread 1: %d done\\n", (int)threads[0]); else perror("Thread 1"); } if(pthread_join(threads[1], 0) == 0) printf("Thread 2: %d done\\n", (int)threads[1]); else perror("Thread 2"); if(pthread_mutex_destroy(&rsrcA) != 0) perror("mutex A destroy"); if(pthread_mutex_destroy(&rsrcB) != 0) perror("mutex B destroy"); printf("All done\\n"); exit(0); }
1
#include <pthread.h> const int LIMIT = -1; const int COUNT = 11; struct prodcons { int buffer[4]; pthread_mutex_t key; int read, write; pthread_cond_t notEmpty; pthread_cond_t notFull; } buffer; void init(struct prodcons * b) { pthread_mutex_init(&b->key, 0); pthread_cond_init(&b->notEmpty, 0); pthread_cond_init(&b->notFull, 0); b->read = 0; b->write = 0; } void Store(struct prodcons * b, int data) { pthread_mutex_lock(&b->key); while ((b->write + 1) % 4 == b->read) { pthread_cond_wait(&b->notFull, &b->key); } b->buffer[b->write] = data; b->write++; if (b->write >= 4) b->write = 0; pthread_cond_signal(&b->notEmpty); pthread_mutex_unlock(&b->key); } int Get (struct prodcons * b) { int data; pthread_mutex_lock(&b->key); while (b->write == b->read) { pthread_cond_wait(&b->notEmpty, &b->key); } data = b->buffer[b->read]; b->read++; if (b->read >= 4) b->read = 0; pthread_cond_signal(&b->notFull); pthread_mutex_unlock(&b->key); return (data); } void * Producer(void * data) { int n; for (n = 0; n < COUNT; n++) { printf("%d --->\\n", n); Store(&buffer, n); sleep(rand() % 4); } Store(&buffer, LIMIT); return (0); } void * Consumer(void * data) { int d; while (1) { d = Get(&buffer); if (d == LIMIT) break; printf("---> %d\\n", d); sleep( rand() % 4); } return (0); } int main(void) { pthread_t th_a, th_b; void * returnValue; init(&buffer); srand (time(0)); pthread_create(&th_a, 0, Consumer, 0); pthread_create(&th_b, 0, Producer, 0); pthread_join(th_a, &returnValue); pthread_join(th_b, & returnValue); pthread_cond_destroy(&buffer.notEmpty); pthread_cond_destroy(&buffer.notFull); pthread_mutex_destroy(&buffer.key); return (0); }
0
#include <pthread.h> int balance; int id; pthread_mutex_t mutex; } bank_account; bank_account A, B; int counter = 0; init_account(bank_account *a) { a->id = counter++; a->balance = 0; pthread_mutex_init(&a->mutex, 0); } void deposit(bank_account *f, bank_account *t, int ammount) { if (f->id == t->id) return; if (f->id < t->id) { pthread_mutex_lock(&f->mutex); pthread_mutex_lock(&t->mutex); } else { pthread_mutex_lock(&f->mutex); pthread_mutex_lock(&t->mutex); } t->balance += ammount; f->balance -= ammount; pthread_mutex_unlock(&t->mutex); pthread_mutex_unlock(&f->mutex); } void *t1(void *arg) { deposit(&A, &B, rand() % 100); return 0; } void *t2(void *arg) { deposit(&B, &A, rand() % 100); return 0; } int main(void) { pthread_t id1, id2; init_account(&A); init_account(&B); int i; for (i = 0; i < 100000; i++) { pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join (id1, 0); pthread_join (id2, 0); printf("%d: A = %d, B = %d.\\n", i, A.balance, B.balance); } return 0; }
1
#include <pthread.h> double result; pthread_mutex_t mutexsum; double func(double x) { return x * x * x + 3; } struct threadArgs { int id; double left; int steps; double step; }; void *PrintHello(void *arguments) { struct threadArgs *args = (struct threadArgs *)arguments; printf("Child id = %d started calculation start %.3f, count %d\\n", args->id, args->left, args->steps); double sum = 0.; for (double i = 0; i < args->steps; ++i) { sum += args->step * func(args->left + i * args->step); } pthread_mutex_lock (&mutexsum); result += sum; pthread_mutex_unlock (&mutexsum); pthread_exit(0); } int main(int argc, char *argv[]) { if (argc < 2) { fprintf(stderr, "Argument for process count is required!"); return 1; } const double a = 0; const double b = 1; const int p = atoi(argv[1]); const int m = 10000; const double step = (b - a) / m; double left, right; result = 0.0; pthread_t *threads = (pthread_t *) malloc(p * sizeof(pthread_t)); pthread_mutex_init(&mutexsum, 0); int rc; long threadId; for (int i = 0; i < p; i++) { struct threadArgs *curArgs = (struct threadArgs *)malloc(sizeof(struct threadArgs)); curArgs->id = i + 1; curArgs->left = a + i * m / p * step; curArgs->steps = m / p; curArgs->step = step; rc = pthread_create(&threads[i], 0, PrintHello, (void *) curArgs); if (rc) { fprintf(stderr, "ERROR; return code from pthread_create() is %d\\n", rc); exit(1); } } for (int i = 0; i < p; ++i) { rc = pthread_join(threads[i], 0); if (rc) { fprintf(stderr, "ERROR: return code from pthread_join() is %d\\n", rc); exit(1); } } printf("Result : %.5f\\n", result); pthread_mutex_destroy(&mutexsum); free(threads); pthread_exit(0); }
0
#include <pthread.h> sem_t semaphore; pthread_mutex_t mutex; pthread_cond_t cond; int count = 0; void *writePipe(void* f) { int *fd = (int*)f; char * msg = "Ashish through pipe!"; int i=0; printf("\\nchild:\\n"); while(msg[i] !='\\0') { pthread_mutex_lock(&mutex); while(count % 2 != 0) { pthread_cond_wait(&cond,&mutex); } count ++; write(fd[1],&msg[i],sizeof(char)); printf("@:%c\\n",msg[i]); i++; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } close(fd[1]); } void *readPipe(void* f) { int *fd = (int*)f; char ch; printf("\\nParent\\n"); int once = 1; while (read(fd[0],&ch,sizeof(char)) > 0) { pthread_mutex_lock(&mutex); while(count % 2 == 0) { pthread_cond_wait(&cond,&mutex); } count++; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } } int main() { pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); sem_init(&semaphore,0,1); int fd[2]; pid_t childpid; if(pipe(fd) < 0) { perror("pipe"); exit(1); } char * msg = "Ashish through pipe!"; char buf[80]; pthread_t pipeIn,pipeOut; pthread_create(&pipeIn,0,&writePipe,fd); pthread_create(&pipeOut,0,&readPipe,fd); pthread_join(pipeIn,0); pthread_join(pipeOut,0); }
1
#include <pthread.h> static int next_command; static int leftSpeed; static int rightSpeed; static unsigned char * leftBump; static unsigned char * rightBump; static int run_thread; static pthread_mutex_t command_mutex; static char bumpsRead; void roombath_init() { pthread_mutex_init(&command_mutex, 0); } void roombath_free() { pthread_mutex_destroy(&command_mutex); } void roombath_direct_drive(int l, int r) { pthread_mutex_lock(&command_mutex); leftSpeed = l; rightSpeed = r; next_command = ROOMBA_DRIVE_DIRECT; pthread_mutex_unlock(&command_mutex); } void roombath_read_bumps(unsigned char * l, unsigned char * r) { pthread_mutex_lock(&command_mutex); bumpsRead = 1; leftBump = l; rightBump = r; next_command = ROOMBA_SENSORS; pthread_mutex_unlock(&command_mutex); while(bumpsRead && run_thread) {} } void roombath_thread_end() { pthread_mutex_lock(&command_mutex); next_command = ROOMBA_END; roomba_direct_drive(0, 0); run_thread = 0; pthread_mutex_unlock(&command_mutex); } void * roomba_thread_func(void * ptr) { run_thread = 1; while (run_thread) { pthread_mutex_lock(&command_mutex); switch (next_command) { case ROOMBA_DRIVE_DIRECT: roomba_direct_drive(leftSpeed, rightSpeed); printf("Driving l=%d, r=%d\\n", leftSpeed, rightSpeed); break; case ROOMBA_SENSORS: roomba_read_bumps(leftBump, rightBump); bumpsRead = 0; break; case ROOMBA_END: roomba_direct_drive(0, 0); run_thread = 0; break; } next_command = ROOMBA_CONTINUE; pthread_mutex_unlock(&command_mutex); } bumpsRead = 0; return 0; }
0
#include <pthread.h> pthread_mutex_t spoons[20]; pthread_mutex_t pr = PTHREAD_MUTEX_INITIALIZER; int spoon_stat[20]={0}; void think(int id){ } void eat(int id){ pthread_mutex_lock(&pr); printf("Philosopher %d is eating with spoons %d and %d!\\n",id,(id)%(20),(id+1)%(20)); spoon_stat[(id)%(20)]++; spoon_stat[(id+1)%(20)]++; int i; for(i=0;i<20;i++){ printf("%d ",spoon_stat[i]); } printf("\\n"); pthread_mutex_unlock(&pr); sleep(1); pthread_mutex_lock(&pr); spoon_stat[(id)%(20)]--; spoon_stat[(id+1)%(20)]--; pthread_mutex_unlock(&pr); } void hungry(int id){ pthread_mutex_lock(&spoons[(id)%(20)]); pthread_mutex_lock(&spoons[(id+1)%(20)]); eat(id); pthread_mutex_unlock(&spoons[(id)%(20)]); pthread_mutex_unlock(&spoons[(id+1)%(20)]); } void* dp(void* id){ int count=3; while(count--){ think(*(int*)id); hungry(*(int*)id); } } int main(){ int i; for(i=0;i<20;i++){ } pthread_t p[20]; int ids[20]; for(i=0;i<20;i++){ ids[i]=i; } for(i=0;i<20;i++){ pthread_create(&p[i],0,dp,&ids[i]); } pthread_exit(0); return 0; }
1
#include <pthread.h> pthread_once_t __continuation_pthread_once = PTHREAD_ONCE_INIT; pthread_key_t __async_pthread_key; int __continuation_pthread_jmpbuf_initialized = 0; int __continuation_pthread_jmpcode[sizeof(jmp_buf) / sizeof(void *)] = { 0 }; static pthread_mutex_t jmpbuf_mutex; static void *continuation_pthread_diff_jmpbuf_help(jmp_buf *) ; static void continuation_pthread_diff_jmpbuf(void) ; static void * __async_pthread_run(struct __AsyncTask * async_task); static struct __AsyncTask *async_copy_stack_frame(struct __AsyncTask *async_task); void(*__continuation_pthread_diff_jmpbuf)(void) = &continuation_pthread_diff_jmpbuf; struct __AsyncTask *(*__async_copy_stack_frame)(struct __AsyncTask *) = &async_copy_stack_frame; static void *continuation_pthread_diff_jmpbuf_help(jmp_buf *environment) { pthread_mutex_lock(&jmpbuf_mutex); setjmp(*environment); pthread_mutex_unlock(&jmpbuf_mutex); FORCE_NO_OMIT_FRAME_POINTER(); return 0; } static void continuation_pthread_diff_jmpbuf(void) { static void *(* volatile diff_jmpbuf_help)(jmp_buf *) = &continuation_pthread_diff_jmpbuf_help; volatile int jmpcode[sizeof(jmp_buf) / sizeof(void *)]; jmp_buf jmpbuf1, jmpbuf2; pthread_t pthread_id; pthread_mutex_init(&jmpbuf_mutex, 0); pthread_mutex_lock(&jmpbuf_mutex); setjmp(jmpbuf1); pthread_create(&pthread_id, 0, (void *(*)(void *))diff_jmpbuf_help, (void *)&jmpbuf1);; memcpy((void *)&jmpbuf2, (void *)&jmpbuf1, sizeof(jmp_buf)); setjmp(jmpbuf1); { int i, j = 0; for (i = 0; i < sizeof(jmp_buf) / sizeof(void *); i++) { if (((void **)&jmpbuf1)[i] != ((void **)&jmpbuf2)[i]) { jmpcode[j++] = i; } } jmpcode[j] = -1; } pthread_mutex_unlock(&jmpbuf_mutex); pthread_join(pthread_id, 0); { volatile int i, j = 0, k = 0; for (i = 0; i < sizeof(jmp_buf) / sizeof(void *); i++) { if (((void **)&jmpbuf1)[i] != ((void **)&jmpbuf2)[i]) { while(jmpcode[j] >= 0 && jmpcode[j] < i) j++; if (jmpcode[j] != i) { __continuation_pthread_jmpcode[k++] = i; } } } __continuation_pthread_jmpcode[k] = -1; } __continuation_pthread_jmpbuf_initialized = 1; pthread_mutex_destroy(&jmpbuf_mutex); FORCE_NO_OMIT_FRAME_POINTER(); } void __continuation_pthread_patch_jmpbuf(jmp_buf *dest, jmp_buf *src) { int i; for (i = 0; __continuation_pthread_jmpcode[i] >= 0; i++) { ((void **)dest)[__continuation_pthread_jmpcode[i]] = ((void **)src)[__continuation_pthread_jmpcode[i]]; } } static void make_key() { pthread_key_create(&__async_pthread_key, 0); } pthread_t __async_pthread_create() { static pthread_once_t __async_pthread_once = PTHREAD_ONCE_INIT; pthread_t pthread_id; int error; struct __AsyncTask *async_task = (struct __AsyncTask *)malloc(sizeof(struct __AsyncTask)); pthread_once(&__async_pthread_once, make_key); async_task->quitable = 0; pthread_mutex_init(&async_task->mutex, 0); pthread_cond_init(&async_task->running, 0); pthread_mutex_lock(&async_task->mutex); error = pthread_create(&pthread_id, 0, (void *(*)(void *))&__async_pthread_run, (void *)async_task); if (error) { free(async_task); async_task = 0; } pthread_setspecific(__async_pthread_key, async_task); return pthread_id; } static void * __async_pthread_run(struct __AsyncTask * async_task) { pthread_mutex_lock(&async_task->mutex); pthread_mutex_unlock(&async_task->mutex); assert(async_task->cont_stub.cont = &async_task->cont); continuation_stub_invoke(&async_task->cont_stub); pthread_mutex_lock(&async_task->mutex); if (!async_task->quitable) { pthread_cond_wait(&async_task->running, &async_task->mutex); } pthread_mutex_unlock(&async_task->mutex); pthread_cond_destroy(&async_task->running); pthread_mutex_destroy(&async_task->mutex); free(async_task); return 0; } static struct __AsyncTask *async_copy_stack_frame(struct __AsyncTask *async_task) { struct __ContinuationStub *cont_stub = &async_task->cont_stub; struct __Continuation *cont = &async_task->cont; memcpy(cont_stub->addr.stack_frame_tail , cont->stack_frame_tail , cont->stack_frame_size); return async_task; }
0
#include <pthread.h> enum { PROC0, PROC1 } volatile state = PROC0; void *print(); const int LINES = 5, LOOP = 10; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t proceed = PTHREAD_COND_INITIALIZER; int main() { pthread_t* handle = malloc(2*sizeof(pthread_t)); long j; for (j = 0; j < 2; ++j) { pthread_create(&handle[j], 0, print, (void *)j); } for (j = 2 - 1; j > 0; --j) { pthread_join(handle[j], 0); } pthread_mutex_destroy(&mutex); free(handle); return 0; } void* print(void* rank) { register int i, q; int my_rank = (long) rank; for (i = 0; i < LOOP; ++i) { switch (my_rank) { case 0: pthread_mutex_lock(&mutex); while (state != PROC0) { pthread_cond_wait(&proceed, &mutex); } pthread_mutex_unlock(&mutex); break; case 1: pthread_mutex_lock(&mutex); while (state != PROC1) { pthread_cond_wait(&proceed, &mutex); } pthread_mutex_unlock(&mutex); break; } for (q = 0; q < LINES; ++q) { switch (my_rank) { case 0: fprintf(stdout, "%d: AAAAAAAAA\\n", i+1); break; case 1: fprintf(stdout, "%d: BBBBBBBBB\\n", i+1); break; } } switch (my_rank) { case 0: pthread_mutex_lock(&mutex); state = PROC1; pthread_cond_signal(&proceed); pthread_mutex_unlock(&mutex); break; case 1: pthread_mutex_lock(&mutex); state = PROC0; pthread_cond_signal(&proceed); pthread_mutex_unlock(&mutex); break; } fprintf(stdout, "\\n"); } return 0; }
1
#include <pthread.h> char *outboard; char *inboard; pthread_barrier_t *barrier; pthread_mutex_t *mutex; int *return_count; int total_nrows; int tid; int gens_max; } arguments; void *evaluate_board(void *thread_args); char* parallel_game_of_life(char* outboard, char* inboard, const int nrows, const int ncols, const int gens_max) { const int num_threads = 8; pthread_t threads[num_threads]; int thread_id[num_threads]; char **return_board_ptr[num_threads]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t barrier; pthread_barrier_init(&barrier, 0, num_threads); char *return_board = 0; int i; int count = -1; for (i = 0; i < num_threads; i++) { return_board_ptr[i] = (char **) malloc(sizeof(char *)); thread_id[i] = i; arguments *thread_args = (arguments *) malloc(1 * sizeof(arguments)); thread_args->outboard = outboard; thread_args->inboard = inboard; thread_args->barrier = &barrier; thread_args->mutex = &mutex; thread_args->return_count = &count; thread_args->total_nrows = nrows; thread_args->tid = thread_id[i]; thread_args->gens_max = gens_max; pthread_create(&threads[i], 0, evaluate_board, (void *) thread_args); } for (i = 0; i < num_threads; i++) { pthread_join(threads[i], (void **) return_board_ptr[i]); if (*return_board_ptr[i] != 0) return_board = *return_board_ptr[i]; } assert(return_board != 0); return return_board; } void *evaluate_board(void *thread_args) { int *return_count = ((arguments *) thread_args)->return_count; pthread_barrier_t *barrier = ((arguments *) thread_args)->barrier; pthread_mutex_t *mutex = ((arguments *) thread_args)->mutex; int tid = ((arguments *) thread_args)->tid; int dim = ((arguments *) thread_args)->total_nrows; char *inboard = ((arguments *) thread_args)->inboard; char *outboard = ((arguments *) thread_args)->outboard; int gens_max = ((arguments *) thread_args)->gens_max; int start_row, start_col, end_row, end_col, i, j, curgen; if (tid % 2) { start_row = 0; end_row = dim >> 1; } else { start_row = dim >> 1; end_row = dim; } switch (tid) { case 0: case 1: start_col = 0; end_col = dim >> 2; break; case 2: case 3: start_col = dim >> 2; end_col = dim >> 1; break; case 4: case 5: start_col = dim >> 1; end_col = dim - (dim >> 2); break; case 6: case 7: start_col = dim - (dim >> 2); end_col = dim; break; default: start_row = 0; start_col = 0; end_row = dim; end_col = dim; } const int tile_size = 32; const int LDA = dim; for (curgen = 0; curgen < gens_max; curgen++) { pthread_barrier_wait(barrier); for (i = start_row; i < end_row; i += tile_size) { int ii; for (j = start_col; j < end_col; j += tile_size) { int jj; for (ii = i; (ii < end_row) && (ii < (i + tile_size)); ii++) { int inorth = wrap_mod(ii - 1, dim); int isouth = wrap_mod(ii + 1, dim); for (jj = j; (jj < end_col) && (jj < (j + tile_size)); jj++) { int jwest = wrap_mod(jj - 1, dim); int jeast = wrap_mod(jj + 1, dim); char neighbor_count = (inboard[(inorth) + LDA*(jwest)]) + (inboard[(ii) + LDA*(jwest)]) + (inboard[(isouth) + LDA*(jwest)]) + (inboard[(inorth) + LDA*(jj)]) + (inboard[(isouth) + LDA*(jj)]) + (inboard[(inorth) + LDA*(jeast)]) + (inboard[(ii) + LDA*(jeast)]) + (inboard[(isouth) + LDA*(jeast)]); char state = (inboard[(ii) + LDA*(jj)]); (outboard[(ii) + LDA*(jj)]) = (neighbor_count == (char) 3) || (state && (neighbor_count >= 2) && (neighbor_count <= 3)); } } } } do { char* temp = outboard; outboard = inboard; inboard = temp; } while(0); } char *return_board = 0; pthread_mutex_lock(mutex); (*return_count)++; if ((*return_count) == 7) { return_board = inboard; } pthread_mutex_unlock(mutex); return return_board; }
0
#include <pthread.h> static volatile unsigned char bee_control = STOP; pthread_mutex_t *bee_mutex; int bee_init() { if (-1 == wiringPiSetup()) { printf("Setup wiringPi failed!"); return 0; } pinMode (bee_Pin, OUTPUT); bee_mutex = (pthread_mutex_t *) malloc( sizeof(pthread_mutex_t) ); pthread_mutex_init(bee_mutex,0); return 1; } void *bee_run(void *arg) { while(1) { if(bee_control == STOP) continue; digitalWrite(bee_Pin, 0); delay(DELAY); digitalWrite(bee_Pin, 1); delay(DELAY); } pthread_mutex_destroy(bee_mutex); pthread_exit(0); } void bee_start() { if( bee_control == START ) return; pthread_mutex_lock(bee_mutex); bee_control = START; pthread_mutex_unlock(bee_mutex); } void bee_stop() { if( bee_control == STOP ) return; pthread_mutex_lock(bee_mutex); bee_control = STOP; pthread_mutex_unlock(bee_mutex); digitalWrite(bee_Pin, 1); }
1
#include <pthread.h> double *A; int num_threads = 2; int N = 33554432; int ocurrencia = 0; double buscar = 1; pthread_mutex_t sumando; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *calculate_prod(void *aux){ int id = *(int*)aux; int i, auxOcurrencia = 0; double auxBuscar = buscar; int limite = N/num_threads; int base = id*limite; int fin = (id+1)*limite; for(i = base;i < fin; i++ ){ if(A[i] == auxBuscar) auxOcurrencia++; } pthread_mutex_lock(&sumando); ocurrencia += auxOcurrencia; pthread_mutex_unlock(&sumando); } int main(int argc, char *argv[]){ if(argc != 3){ return 1; } buscar = atoi(argv[1]); num_threads = atoi(argv[2]); double timetick; int i; int ids[num_threads]; for(i = 0; i < num_threads; i++){ ids[i] = i; } A=(double*)malloc(sizeof(double)*N); for(i = 0; i < N; i++){ A[i] = i; } A[1] = 3.0; A[352] = 3.0; A[23554432] = 3.0; pthread_t p_threads[num_threads]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutex_init(&sumando, 0); for(i=0; i< num_threads; i++){ pthread_create(&p_threads[i], &attr, calculate_prod, (void*) &ids[i]); } timetick = dwalltime(); for(i=0; i< num_threads; i++){ pthread_join(p_threads[i], 0); } printf("Tiempo en segundos %f\\n", dwalltime() - timetick); free(A); return 0; }
0
#include <pthread.h> void *reader(void *); void *writer(void *); int nloop = 1000, nreaders = 6, nwriters = 4; struct { pthread_rwlock_t rwlock; pthread_mutex_t rcountlock; int nreaders; int nwriters; } shared = { PTHREAD_RWLOCK_INITIALIZER, PTHREAD_MUTEX_INITIALIZER }; int main(int argc, char **argv) { int c, i; pthread_t tid_readers[100], tid_writers[100]; while ( (c = getopt(argc, argv, "n:r:w:")) != -1) { switch (c) { case 'n': nloop = atoi(optarg); break; case 'r': nreaders = (((atoi(optarg)) < (100))?(atoi(optarg)):(100)); break; case 'w': nwriters = (((atoi(optarg)) < (100))?(atoi(optarg)):(100)); break; } } if (optind != argc) { return 1; } for (i = 0; i < nreaders; i++) pthread_create(&tid_readers[i], 0, reader, 0); for (i = 0; i < nwriters; i++) pthread_create(&tid_writers[i], 0, writer, 0); for (i = 0; i < nreaders; i++) pthread_join(tid_readers[i], 0); for (i = 0; i < nwriters; i++) pthread_join(tid_writers[i], 0); exit(0); } void* reader(void *arg) { int i; for (i = 0; i < nloop; i++) { pthread_rwlock_rdlock(&shared.rwlock); pthread_mutex_lock(&shared.rcountlock); shared.nreaders++; pthread_mutex_unlock(&shared.rcountlock); if (shared.nwriters > 0) { printf("reader: %d writers found", shared.nwriters); return (void*)0; } pthread_mutex_lock(&shared.rcountlock); shared.nreaders--; pthread_mutex_unlock(&shared.rcountlock); pthread_rwlock_unlock(&shared.rwlock); } return(0); } void* writer(void *arg) { int i; for (i = 0; i < nloop; i++) { pthread_rwlock_wrlock(&shared.rwlock); shared.nwriters++; if (shared.nwriters > 1) { printf("writer: %d writers found", shared.nwriters); return (void*)0; } if (shared.nreaders > 0) { printf("writer: %d readers found", shared.nreaders); return (void*)0; } shared.nwriters--; pthread_rwlock_unlock(&shared.rwlock); } return(0); }
1
#include <pthread.h> struct job { struct job* next; }; struct job * job_queue = 0; pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER; void process_job(struct job *job) { } void* thread_function(void* arg) { while(1) { struct job *next_job; pthread_mutex_lock(&job_queue_mutex); if(job_queue == 0) { next_job = 0; } else { next_job = job_queue; job_queue = job_queue->next; } pthread_mutex_unlock(&job_queue_mutex); if(next_job == 0) { break; } process_job(next_job); free(next_job); } return 0; } void enqueue_job(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); } int main() { pthread_t thread_id; int ret; int parm = 1; pthread_create(&thread_id, 0, &thread_function, &parm); pthread_join(thread_id, (void*)&ret); printf("ret = %d, thread_id = %d\\n", ret, (int)thread_id); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cv; int elves_exited; elf_status *status; void * elf_thread(void *arg) { int id; id = (int) arg; usleep(((int)(20 + ((double)random() / 32767) * (30 - 20 + 1)))); printf("Elf %d prepared sumptious feast!\\n", id); usleep(((int)(10 + ((double)random() / 32767) * (20 - 10 + 1)))); printf("Elf %d cleaned up after messy students!\\n", id); usleep(((int)(1 + ((double)random() / 32767) * (100 - 1 + 1)))); printf("Elf %d: Harry Potter is the greatest Wizard Ever!\\n", id); pthread_mutex_lock(&mutex); status[id] = done; elves_exited++; pthread_cond_signal(&cv); pthread_mutex_unlock(&mutex); return (0); } int main(void) { int keep_running; pthread_t *thread_ids; if (pthread_mutex_init(&mutex, 0) != 0) { fprintf(stderr, "Dobby: Mutex init failed %s\\n", strerror(errno)); exit(1); } if (pthread_cond_init(&cv, 0) != 0) { fprintf(stderr, "Dobby: CV init failed %s\\n", strerror(errno)); exit(1); } thread_ids = malloc(sizeof(pthread_mutex_t) * 6); if (thread_ids == 0) { fprintf(stderr, "Dobby: Malloc of elf thread ids failed %s\\n", strerror(errno)); exit (1); } status = malloc(sizeof(elf_status) * 6); if (status == 0) { fprintf(stderr, "Dobby: Malloc of elf statuses failed %s\\n", strerror(errno)); exit (1); } elves_exited = 0; for (int i = 0; i < 6; i++) { if (pthread_create(thread_ids + i, 0, &elf_thread, (void *)i) != 0) { fprintf(stderr, "Dobby: pthread_create %d failed %s\\n", i, strerror(errno)); exit(1); } status[i] = running; } do { pthread_mutex_lock(&mutex); while (elves_exited == 0) pthread_cond_wait(&cv, &mutex); keep_running = 0; for (int i = 0; i < 6; i++) { if (status[i] == running) keep_running = 1; if (status[i] == done) { status[i] = dismissed; printf("Thanks for your work, Elf %d\\n", i); pthread_join(thread_ids[i], 0); elves_exited--; } } pthread_mutex_unlock(&mutex); } while (keep_running); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cv); free(thread_ids); free(status); printf("Dobby is done\\n"); }
1
#include <pthread.h> static int const writerMaxPeriod = 10; static int const writingMaxPeriod = 5; static int const readerMaxPeriod = 30; static int const readingMaxPeriod = 5; static int const randomSleepsPeriod = 3; { pthread_t threadId; int userId; } thread_info_type; static pthread_mutex_t databaseMutex = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t nReadersMutex = PTHREAD_MUTEX_INITIALIZER; static int nReaders = 0; static void *writer( thread_info_type *info ) { while (1) { sleep(rand() % writerMaxPeriod); pthread_mutex_lock(&databaseMutex); sleep(rand() % writingMaxPeriod); pthread_mutex_unlock(&databaseMutex); } return 0; } static void *reader( thread_info_type *info ) { while (1) { sleep(rand() % writerMaxPeriod); pthread_mutex_lock(&nReadersMutex); if (nReaders == 0) { pthread_mutex_lock(&databaseMutex); } ++nReaders; pthread_mutex_unlock(&nReadersMutex); sleep(rand() % readingMaxPeriod); pthread_mutex_lock(&nReadersMutex); --nReaders; if (nReaders == 0) { pthread_mutex_unlock(&databaseMutex); } pthread_mutex_unlock(&nReadersMutex); } return 0; } int main( int argc, char const *argv[] ) { int i; thread_info_type threads[5 + 2]; int nextThreadIdx = 0; srand(0); for (i = 0; i < 2; ++i) { threads[nextThreadIdx].userId = i + 1; if (pthread_create(&threads[nextThreadIdx].threadId, 0, (thread_routine_type)writer, (void *)&threads[nextThreadIdx]) != 0) { perror("pthread_create"); fprintf(stderr, "Error: pthread_create() failed.\\n"); return 1; } ++nextThreadIdx; } for (i = 0; i < 5; ++i) { threads[nextThreadIdx].userId = i + 1; if (pthread_create(&threads[nextThreadIdx].threadId, 0, (thread_routine_type)reader, (void *)&threads[nextThreadIdx]) != 0) { perror("pthread_create"); fprintf(stderr, "Error: pthread_create() failed.\\n"); return 1; } ++nextThreadIdx; } while (1) ; return 0; }
0
#include <pthread.h> int *buffer; int N, B; int front = 0; int end = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *producer(void *params) { srand(time(0)); int i = 0; int num = 0; while ( i<N ) { while(((front+1) % B) == end); num = rand() % 2000; buffer[front] = num; pthread_mutex_lock(&mutex); front = (front + 1) % B; pthread_mutex_unlock(&mutex); i++; } } void *consumer(void *params) { int i = 0; int num = 0; while ( i<N ) { while (front == end); num = buffer[end]; pthread_mutex_lock(&mutex); end = (end + 1) % B; pthread_mutex_unlock(&mutex); i++; } } long double time_calculation(struct timeval start_t, struct timeval end_t) { long double start_t_usec = (long double) (start_t.tv_sec * 1000000 + start_t.tv_usec); long double end_t_usec = (long double) (end_t.tv_sec * 1000000 + end_t.tv_usec); return (end_t_usec - start_t_usec)/1000000; } int main(int argc, char *argv[]) { pthread_t producer_id, consumer_id; pthread_attr_t attr; struct timeval start_t, init_t, end_t; gettimeofday(&start_t, 0); if ( argc != 3) { fprintf(stderr, "usage: producer_consumer <Number of integers> <Buffer Size>"); return -1; } if ( atoi(argv[1]) < 0 || atoi(argv[2]) < 0) { fprintf(stderr, "Both arguments must be positive integers\\n"); return -1; } if ( atoi(argv[1]) < atoi(argv[2]) ) { fprintf(stderr, "Number of integers must be greater than buffer size.\\n"); return -1; } N = atoi(argv[1]); B = atoi(argv[2]); buffer = malloc(B * sizeof(int)); pthread_attr_init(&attr); pthread_create(&producer_id, &attr, producer, argv[1]); pthread_create(&consumer_id, &attr, consumer, argv[1]); gettimeofday(&init_t, 0); pthread_join(producer_id, 0); pthread_join(consumer_id, 0); gettimeofday(&end_t, 0); printf("%d , %d , %Lf , %Lf\\n", N, B, time_calculation(start_t, init_t) , time_calculation(init_t, end_t)); }
1
#include <pthread.h> static void* (*oldMalloc) (size_t, const void*); static void* (*oldRealloc) (void*, size_t, const void*); static double failDelay; static size_t failMinSize; static double failProbability; static double failStartStamp; pthread_mutex_t lock; static double currentTimeStamp (void) { struct timeval tv; gettimeofday(&tv, 0); return (tv.tv_sec) + (tv.tv_usec / 1000000.0); } static int mustFail (size_t n) { if (failMinSize > 0 && n < failMinSize) { return 0; } if (failProbability == 0.0) { return 0; } if (failStartStamp > 0.0 && currentTimeStamp() < failStartStamp) { return 0; } if (failProbability < 1.0 && failProbability * 32767 < rand()) { return 0; } return 1; } static void* myMalloc (size_t n, const void* x) { void* ptr; pthread_mutex_lock(&lock); __malloc_hook = oldMalloc; if (n > 0 && mustFail(n)) { oldMalloc = __malloc_hook; __malloc_hook = myMalloc; errno = ENOMEM; pthread_mutex_unlock(&lock); return 0; } ptr = malloc(n); oldMalloc = __malloc_hook; __malloc_hook = myMalloc; pthread_mutex_unlock(&lock); return ptr; } static void* myRealloc (void* old, size_t n, const void* x) { void* ptr; pthread_mutex_lock(&lock); __realloc_hook = oldRealloc; if (n > 0 && mustFail(n)) { oldMalloc = __malloc_hook; __malloc_hook = myMalloc; errno = ENOMEM; pthread_mutex_unlock(&lock); return 0; } ptr = realloc(old, n); oldRealloc = __realloc_hook; __realloc_hook = myRealloc; pthread_mutex_unlock(&lock); return ptr; } static void myInit (void) { char* value; pid_t pid; pthread_mutex_init(&lock, 0); oldMalloc = __malloc_hook; oldRealloc = __realloc_hook; __malloc_hook = myMalloc; __realloc_hook = myRealloc; pid = getpid(); failDelay = 0.0; failMinSize = 0; failProbability = 0.1; failStartStamp = 0.0; srand(pid * 32452843 + time(0) * 49979687); value = getenv("BRALLOC" "_PROBABILITY"); if (value != 0) { double v = strtod(value, 0); if (v >= 0.0 && v <= 1.0) { failProbability = v; } } value = getenv("BRALLOC" "_DELAY"); if (value != 0) { double v = strtod(value, 0); if (v > 0.0) { failDelay = v; failStartStamp = currentTimeStamp() + failDelay; } } value = getenv("BRALLOC" "_MINIMUM"); if (value != 0) { unsigned long long v = strtoull(value, 0, 10); if (v > 0) { failMinSize = (size_t) v; } } fprintf(stderr, "WARNING: program execution with bralloc wrapper.\\n" "================================================\\n" "process id: %llu\\n" "failure probability: %0.3f %%\\n" "failure delay: %0.1f s\\n" "failure min size: %llu\\n\\n", (unsigned long long) pid, 100.0 * failProbability, failDelay, (unsigned long long) failMinSize); } void (*__malloc_initialize_hook) (void) = myInit;
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("thread1 : 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 thread 2\\n"); for (i = 0; i < 10; i++) { printf("thread2 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); sleep(3); } printf("thread2 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0) printf("线程1创建失败!\\n"); else printf("线程1被创建\\n"); if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0) printf("线程2创建失败"); 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[1],0); printf("线程2已经结束\\n"); } } int main() { pthread_mutex_init(&mut,0); printf("我是主函数哦,我正在创建线程,呵呵\\n"); thread_create(); printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\\n"); thread_wait(); 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; 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; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=27); } void *thread2() { pthread_mutex_lock(&mx); x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; pthread_mutex_unlock(&mx); } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); y=2; } 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 main(int argc, char const *argv[]) { srand(time(0)); int i,tmp[P],err; err = pthread_mutex_init(&disp_mutex,0); assert(!err); for(i = 0;i < P;++i) { forkState[i] = 1; phil_cycles[i] = 0; err = pthread_mutex_init(&mutex[i],0); assert(!err); err = pthread_cond_init(&forks[i],0); assert(!err); } for(i = 0;i < P;++i) { tmp[i] = i; int err = pthread_create(&philosopher[i],0,(void*)current_thread,(void*)&tmp[i]); assert(!err); } for(i = 0;i < P;++i) { pthread_join(philosopher[i],0); } for(i = 0;i < P;++i) { printf("Philosopher %d : %d cycles.\\n", i+1,phil_cycles[i]); } pthread_mutex_destroy(&disp_mutex); for(i = 0;i < P;++i) { pthread_mutex_destroy(&mutex[i]); pthread_cond_destroy(&forks[i]); } return 0; } void pickup_forks(int i) { pthread_mutex_lock(&mutex[i]); pthread_mutex_lock(&mutex[(i+1)%P]); if(i&1 == 0) { if(!forkState[i]) pthread_cond_wait(&forks[i],&mutex[i]); forkState[i] = 0; if(!forkState[(i+1)%P]) pthread_cond_wait(&forks[(i+1)%P],&mutex[(i+1)%P]); forkState[(i+1)%P] = 0; } else { if(!forkState[(i+1)%P]) pthread_cond_wait(&forks[(i+1)%P],&mutex[(i+1)%P]); forkState[(i+1)%P] = 0; if(!forkState[i]) pthread_cond_wait(&forks[i],&mutex[i]); forkState[i] = 0; } pthread_mutex_unlock(&mutex[i]); pthread_mutex_unlock(&mutex[(i+1)%P]); } void return_forks(int i) { pthread_mutex_lock(&mutex[i]); pthread_cond_signal(&forks[i]); forkState[i] = 1; pthread_mutex_unlock(&mutex[i]); pthread_mutex_lock(&mutex[(i+1)%P]); pthread_cond_signal(&forks[(i+1)%P]); forkState[(i+1)%P] = 1; pthread_mutex_unlock(&mutex[(i+1)%P]); } bool display_count(int p) { bool end = 0; pthread_mutex_lock(&disp_mutex); if(total_cycles >= MAX_CYCLES) { end = 1; pthread_mutex_unlock(&disp_mutex); return end; } pthread_mutex_unlock(&disp_mutex); return end; } void *current_thread(void *philosopher_number) { int p = *(int*)philosopher_number,delay; while(1) { printf("Philosopher %d waiting and trying to pickup forks.\\n",p+1); pickup_forks(p); delay = (rand()%3+1); printf("Philosopher %d is eating for %d seconds.\\n",p + 1, delay); sleep(delay); return_forks(p); delay = (rand()%3+1); printf("Philosopher %d is thinking for %d seconds.\\n",p + 1, delay); sleep(delay); if(display_count(p)) break; else phil_cycles[p]++; } }
1
#include <pthread.h> pthread_mutex_t shared_array_mutex = PTHREAD_MUTEX_INITIALIZER; char shared_array_changed = 0; int a[] = {1, 2, 3, 4, 5, 6, 7, 8}; int b[] = {1, 3, 5, 7, 11, 13, 17, 19, 23}; int c[] = {-9, -7, -5, -3, -1, 0, 1, 2}; void * thread_func1 (void * arg) { int i; for(i = 0; i < 8; i++) { for(;;) { pthread_mutex_lock( &shared_array_mutex ); if( shared_array_changed == 1 ) break; pthread_mutex_unlock( &shared_array_mutex ); } a[i] = a[i] + b[i]; shared_array_changed = 0; pthread_mutex_unlock( &shared_array_mutex ); } pthread_exit( 0 ); } void * thread_func2 (void * arg) { int i; for(i = 0; i < 8; i++) { for(;;) { pthread_mutex_lock( &shared_array_mutex ); if( shared_array_changed == 0 ) break; pthread_mutex_unlock( &shared_array_mutex ); } c[i] = a[i] + c[i]; shared_array_changed = 1; pthread_mutex_unlock( &shared_array_mutex ); } pthread_exit( 0 ); } int main (void) { int i; fprintf (stderr, "Before work\\n"); fprintf (stderr, " a \\t b \\t c\\n"); for(i = 0; i < 8; i++) fprintf (stderr, " %d \\t %d \\t %d\\n", a[i], b[i], c[i]); pthread_t thread1, thread2; pthread_create (&thread1, 0, &thread_func1, 0); pthread_create (&thread2, 0, &thread_func2, 0); fprintf (stderr, "After work\\n"); pthread_join( thread1, 0 ); pthread_join( thread2, 0 ); fprintf (stderr, " a \\t b \\t c\\n"); for(i = 0; i < 8; i++) fprintf (stderr, " %d \\t %d \\t %d\\n", a[i], b[i], c[i]); return 0; }
0
#include <pthread.h> struct cores_pthread *cores_pthread_make (int availables) { int i; struct cores_pthread *cores = malloc(sizeof(struct cores_pthread)); cores->cores = availables; cores->running = 0; cores->threads = malloc(sizeof(pthread_t)*cores->cores); for (i=0; i < cores->cores; ++i) cores->threads[i] = 0; pthread_mutex_init (&cores->mutex, 0); return cores; } short int cores_pthread_destroy (struct cores_pthread *cores) { pthread_mutex_lock (&cores->mutex); if (cores->running) { pthread_mutex_unlock (&cores->mutex); return 1; } pthread_mutex_unlock (&cores->mutex); return 0; } int core_pthread_wait (struct cores_pthread *cores, int core) { int *rc = 0; pthread_join (cores->threads[core], (void **)&rc); cores->threads[core] = 0; return rc != 0 ? *rc : -1; } void cores_pthread_wait (struct cores_pthread *cores) { int i; for (i=0; i < cores->cores; ++i) core_pthread_wait (cores, i); } void *core_pthread_main (void *args) { int *rc = malloc(sizeof(int)); struct core_pthread_main_args *core_main_args = args; struct cores_pthread *cores = core_main_args->cores; *rc = (core_main_args->func)(core_main_args->args); free(core_main_args); pthread_mutex_lock (&cores->mutex); cores->running--; pthread_mutex_unlock(&cores->mutex); pthread_exit(rc); return 0; } short int core_pthread_run (struct cores_pthread *cores, int core, int(core_main)(void *), void *args) { pthread_t thread; struct core_pthread_main_args *core_main_args = malloc(sizeof(struct core_pthread_main_args)); int rc; pthread_mutex_lock (&cores->mutex); if (cores->threads[core]!=0) { pthread_mutex_unlock(&cores->mutex); return 1; } core_main_args->func = core_main; core_main_args->args = args; core_main_args->cores = cores; pthread_mutex_unlock(&cores->mutex); rc = pthread_create(&thread, 0, core_pthread_main, core_main_args); if (!rc) { pthread_mutex_lock (&cores->mutex); cores->threads[core] = thread; cores->running++; pthread_mutex_unlock(&cores->mutex); return 0; } return 1; } int cores_pthread_first_free (struct cores_pthread *cores) { int i = 0; for (i=0; i < cores->cores; ++i) if (!cores->threads[i]) return i; return -1; }
1
#include <pthread.h> pthread_mutex_t semaforo; int * buffer; int tamBuffer; int usoBuffer=0; void * produce(void * l); void * consume(void *); void validaCreate(int e); void validaJoin(int e); int main(){ srand(time(0)); pthread_mutex_init(&semaforo,0); pthread_t * hilos; hilos=(pthread_t *)malloc(sizeof(pthread_t)*2); int unidades; int * limite; int error; int i; limite=(int *)malloc(sizeof(int)); printf("Introduce un espacio en unidades para el buffer: "); scanf("%d",&unidades); buffer=(int *)malloc(sizeof(int)*unidades); tamBuffer=unidades; printf("Introduce el limite de producciones: "); scanf("%d",limite); error=pthread_create(&hilos[0],0,(void *)produce,limite); validaCreate(error); error=pthread_create(&hilos[1],0,(void *)consume,0); validaCreate(error); for(i=0;i<2;i++){ error=pthread_join(hilos[i],0); validaJoin(error); } exit(0); } void validaCreate(int e){ char * mensaje="\\n\\t-Se produjo el error"; switch(e){ case EAGAIN: printf("%s EAGAIN (Sin recursos o maximo de hilos alcanzado) \\n\\n",mensaje); break; case EINVAL: printf("%s EINVAL (Valor de atributos incorrecto)\\n\\n",mensaje); break; case EPERM: printf("%s EPERM (Sin privilegios para configurar la planificacion)\\n\\n",mensaje); break; default: break; } } void validaJoin(int e){ char * mensaje="\\n\\t-Se produjo el error"; switch(e){ case EDEADLK: printf("%s EDEADLK (Se quiso hacer un join a si mismo) \\n\\n",mensaje); break; case EINVAL: printf("%s EINVAL (Hilo detached u otro hilo esperando a que termine)\\n\\n",mensaje); break; case ESRCH: printf("%s ESRCH (El hilo no existe)\\n\\n",mensaje); break; default: break; } } void * produce(void * l){ int * limit=(int *)l; int posicion=0; while(1){ if(*limit!=0){ while(usoBuffer==tamBuffer); pthread_mutex_lock(&semaforo); buffer[posicion]=rand()%10; printf("\\n+ Elemento producido: %d | Posicion: %d", buffer[posicion],posicion); posicion=(posicion+1)%tamBuffer; usoBuffer+=1; *limit-=1; pthread_mutex_unlock(&semaforo); } } pthread_exit(0); } void * consume(void * arg){ int posicion=0; while(1){ while(usoBuffer==0); pthread_mutex_lock(&semaforo); printf("\\n- Elemento consumido: %d | Posicion: %d",buffer[posicion],posicion); posicion=(posicion+1)%tamBuffer; usoBuffer-=1; pthread_mutex_unlock(&semaforo); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t stdout_mutex = PTHREAD_MUTEX_INITIALIZER; int global_histogram[8] = { 0 }; int fhistogram(char const *path) { FILE *f = fopen(path, "r"); int local_histogram[8] = { 0 }; if (f == 0) { fflush(stdout); return -1; } int i = 0; char c; while (fread(&c, sizeof(c), 1, f) == 1) { i++; update_histogram(local_histogram, c); if ((i % 100000) == 0) { pthread_mutex_lock(&stdout_mutex); merge_histogram(local_histogram, global_histogram); print_histogram(global_histogram); pthread_mutex_unlock(&stdout_mutex); } } fclose(f); pthread_mutex_lock(&stdout_mutex); merge_histogram(local_histogram, global_histogram); print_histogram(global_histogram); pthread_mutex_unlock(&stdout_mutex); return 0; } void* worker(void *arg) { struct job_queue *jq = arg; while (1) { FTSENT *p; if (job_queue_pop(jq, (void**)&p) == 0) { fhistogram((char* )(p)); free(p); } else { break; } } return 0; } int main(int argc, char * const *argv) { if (argc < 2) { err(1, "usage: paths..."); exit(1); } int num_threads = 1; char * const *paths = &argv[1]; if (argc > 3 && strcmp(argv[1], "-n") == 0) { num_threads = atoi(argv[2]); if (num_threads < 1) { err(1, "invalid thread count: %s", argv[2]); } paths = &argv[3]; } else { paths = &argv[1]; } struct job_queue jq; job_queue_init(&jq,64); pthread_t *threads = calloc(num_threads, sizeof(pthread_t)); for (int i = 0; i < num_threads; i++) { if (pthread_create(&threads[i], 0, &worker, &jq) != 0) { err(1, "pthread_create() failed"); } } int fts_options = FTS_LOGICAL | FTS_NOCHDIR; FTS *ftsp; if ((ftsp = fts_open(paths, fts_options, 0)) == 0) { err(1, "fts_open() failed"); return -1; } FTSENT *p; while ((p = fts_read(ftsp)) != 0) { switch (p->fts_info) { case FTS_D: break; case FTS_F: job_queue_push(&jq, (void*)strdup(p->fts_path)); break; default: break; } } fts_close(ftsp); job_queue_destroy(&jq); for (int i = 0; i < num_threads; i++) { if (pthread_join(threads[i], 0) != 0) { err(1, "pthread_join() failed"); } } move_lines(9); return 0; }
1
#include <pthread.h> { double *a; double *b; double c; int wsize; int repeat; } dotdata_t; dotdata_t dotdata; pthread_mutex_t mutexsum; void *dotprod_worker(void *arg) { int i, k; long offset = (long) arg; double *a = dotdata.a; double *b = dotdata.b; int wsize = dotdata.wsize; int start = offset*wsize; int end = start + wsize; double mysum; for (k = 0; k < dotdata.repeat; k++) { mysum = 0.0; for (i = start; i < end ; i++) { mysum += (a[i] * b[i]); } } pthread_mutex_lock (&mutexsum); printf ("soma : %lf", mysum); dotdata.c += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } void dotprod_threads(int nthreads) { int i; pthread_t *threads; pthread_attr_t attr; threads = (pthread_t *) malloc(nthreads * sizeof(pthread_t)); pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < nthreads; i++) { pthread_create(&threads[i], &attr, dotprod_worker, (void *) i); } pthread_attr_destroy(&attr); for (i = 0; i < nthreads; i++) { pthread_join(threads[i], 0); } free(threads); } long wtime() { struct timeval t; gettimeofday(&t, 0); return t.tv_sec*1000000 + t.tv_usec; } void fill(double *a, int size, double value) { int i; for (i = 0; i < size; i++) { a[i] = value; } } int main(int argc, char **argv) { int nthreads, wsize, repeat; long start_time, end_time; if ((argc != 4)) { printf("Uso: %s <nthreads> <worksize> <repetitions>\\n", argv[0]); exit(1); } nthreads = atoi(argv[1]); wsize = atoi(argv[2]); repeat = atoi(argv[3]); dotdata.a = (double *) malloc(wsize*nthreads*sizeof(double)); fill(dotdata.a, wsize*nthreads, 0.01); dotdata.b = (double *) malloc(wsize*nthreads*sizeof(double)); fill(dotdata.b, wsize*nthreads, 1.0); dotdata.c = 0.0; dotdata.wsize = wsize; dotdata.repeat = repeat; start_time = wtime(); dotprod_threads(nthreads); end_time = wtime(); printf("%f\\n", dotdata.c); printf("%d thread(s), %ld usec\\n", nthreads, (long) (end_time - start_time)); fflush(stdout); free(dotdata.a); free(dotdata.b); return 0; }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum); pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100000*sizeof(double)); b = (double*) malloc (4*100000*sizeof(double)); for (i=0; i<100000*4; i++) { a[i]=1; b[i]=a[i]; } dotstr.veclen = 100000; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0;i<4;i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0;i<4;i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> static int first[9]; static int second[9]; static int result[9]; char p; static char cmd = 'c'; static pthread_mutex_t mutex; void *crt(void *p) { while (1) { if (cmd == 'c') { pthread_mutex_lock(&mutex); for (int i = 0; i < 9; ++i) { first[i] = (int) (random() % 9 - 0); second[i] = (int) (random() % 9 - 0); } cmd = 's'; pthread_mutex_unlock(&mutex); sleep(1); } } } void *sum(void *p) { while (1) { if (cmd == 's') { pthread_mutex_lock(&mutex); for (int i = 0; i < 9; ++i) { result[i] = first[i] + second[i]; } cmd = 'p'; pthread_mutex_unlock(&mutex); sleep(1); } } } void printing(int *ar) { for (int i = 0; i < 9; ++i) { if (i % 3 == 0) { printf("\\n"); } printf("%i ", ar[i]); } printf("\\n"); } void *prt(void *p) { while (1) { if (cmd == 'p') { pthread_mutex_lock(&mutex); printing(first); printf("+"); printing(second); printf("="); printing(result); printf("\\n\\n"); cmd = 'c'; pthread_mutex_unlock(&mutex); sleep(1); } } } int main() { pthread_mutex_init(&mutex, 0); pthread_t thread_1; pthread_t thread_2; pthread_t thread_3; pthread_create(&thread_1, 0, &crt, 0); pthread_create(&thread_2, 0, &sum, 0); pthread_create(&thread_3, 0, &prt, 0); scanf("%c", &p); if (p == 'x') { return 0; } pthread_join(thread_1, 0); pthread_mutex_destroy(&mutex); }
0
#include <pthread.h> static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int n = 0, size = 0; char buf[5]; void *fun1(void *arg) { pthread_mutex_unlock(&mutex1); int fd = *(int*)arg; while (1) { pthread_mutex_lock(&mutex1); memset(buf,0,sizeof(buf)); if ((n = read(fd,buf,sizeof(buf))) <= 0) { break; } size += n; sleep(1); pthread_mutex_unlock(&mutex2); } } void *fun2(void *arg) { int fd = *(int*)arg; while (1) { pthread_mutex_lock(&mutex2); if ((write(fd,buf,n)) <= 0) { break; } pthread_mutex_unlock(&mutex1); } } void *fun3(void *arg) { int ssize = *(int*)arg; do { printf("%d/%d,%.2f%\\n",size,ssize,1.0*size/ssize*100); sleep(1); }while (size != ssize); } int main(int argc,char **argv) { int fd1, fd2; pthread_t tid1,tid2,tid3; struct stat buf; if (argc != 3) { perror("format err"); exit(0); } if (stat(argv[1],&buf) < 0) { perror("stat err"); exit(0); } if ((fd1 = open(argv[1],O_RDONLY | O_NONBLOCK)) < 0) { perror("open 1 err"); } umask(0000); if ((fd2 = open(argv[2],O_CREAT | O_RDWR | O_TRUNC,0666)) < 0) { perror("open 2 err"); exit(0); } if (pthread_create(&tid1,0,fun1,&fd1) < 0) { perror("create pthread 1 err"); exit(0); } pthread_mutex_lock(&mutex1); if (pthread_create(&tid2,0,fun2,&fd2) < 0) { perror("create pthread 2 err"); exit(0); } pthread_mutex_lock(&mutex2); if (pthread_create(&tid3,0,fun3,&buf.st_size) < 0) { perror("create pthread 3 err"); exit(0); } pthread_join(tid1,0); pthread_cancel(tid2); pthread_join(tid3,0); }
1
#include <pthread.h> extern char **environ; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { printf("thread_init\\n"); pthread_key_create(&key, free); } char *mygetenv(const char *name) { int i, len; char *result_buf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&mutex); result_buf = (char *)pthread_getspecific(key); if(result_buf == 0){ result_buf = malloc(1024); if(result_buf == 0){ pthread_mutex_unlock(&mutex); return 0; } pthread_setspecific(key, result_buf); } len = strlen(name); for(i=0; environ[i]!=0; i++){ if((strncmp(name, environ[i], len)==0) && environ[i][len] == '='){ strcpy(result_buf, &environ[i][len+1]); pthread_mutex_unlock(&mutex); return result_buf; } } pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char const *argv[]) { printf("first:%s\\n", mygetenv("HOME")); printf("second:%s\\n", mygetenv("HOME")); return 0; }
0
#include <pthread.h> pthread_t threads[2]; int tasks[2]; pthread_mutex_t locks[2]; void *thr_f(void *arg) { int id = (int)arg; while (1) { printf("Thread %d waiting for task\\n", id); pthread_mutex_lock(&locks[id]); pthread_mutex_lock(&locks[id]); pthread_mutex_unlock(&locks[id]); printf("Thread %d start task\\n", id); sleep(2); printf("%d\\n", tasks[id]); sleep(2); } return 0; } void pool_init() { for (int i = 0; i < 2; i++) { pthread_mutex_init(&locks[i], 0); pthread_create(&threads[i], 0, thr_f, (void *)(long long)i); } } void pool_destroy() { for (int i = 0; i < 2; i++) { pthread_kill(threads[i], 0); pthread_mutex_destroy(&locks[i]); } } void pool_give_task(int task) { for (int i = 0; i < 2; i++) { if (pthread_mutex_trylock(&locks[i])) { tasks[i] = task; pthread_mutex_unlock(&locks[i]); return; } else { pthread_mutex_unlock(&locks[i]); } } printf("[info]: All threads are bisy. Task declined.\\n"); } int main() { pool_init(); sleep(1); pool_give_task(4); sleep(1); pool_give_task(5); sleep(1); pool_give_task(6); sleep(1); pool_give_task(7); sleep(1); pool_give_task(8); sleep(1); sleep(20); pool_destroy(); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int compare(const int * a, const int * b){ if (*a > *b){ return(1); } else if( *b > *a){ return(-1); } else{ return(0); } } int is_prime(int p){ int i; if(p < 2){ return(0); } i = 2; while(i*i <= p){ if(p % i == 0){ return 0; } i++; } return(1); } int find_primes(int max_num, int * buffer){ int buf_index = 0; int i; for(i = 2; i <= max_num; i++){ if(is_prime(i)){ pthread_mutex_lock(&mutex); buffer[buf_index] = i; buf_index++; pthread_mutex_unlock(&mutex); } } return(buf_index); } int main(int argc, char **argv){ if(argc < 3){ printf("usage: hw2a MAX_NUM MAX_THREADS\\n"); return(1); } unsigned int max_num = atoi(argv[1]); unsigned int num_threads = atoi(argv[2]); int * buffer = malloc(max_num*sizeof(int)); omp_set_num_threads(num_threads); int num_primes = find_primes(max_num,buffer); int i; if(num_primes > 0){ qsort(buffer,num_primes,sizeof(int),(int(*)(const void*,const void*))compare); printf("%d",buffer[0]); for(i = 1; i < num_primes; i++){ printf(", %d", buffer[i]); } printf("\\n"); } return(0); }
0
#include <pthread.h> struct MessagePool *CreateMessagePool() { struct MessagePool *pool = (struct MessagePool *)malloc(sizeof(struct MessagePool)); if (pool == 0) { printf("allocated pool error\\n"); return 0; } pthread_mutex_init(&pool->poolMutex, 0); pool->count = 0; int i = 0; for (i = 0; i < MESSAGE_INIT_NUM; i ++) { struct Message *m = NewMessage(); PutMessage(pool, m); } return pool; } void DeleteMessagePool(struct MessagePool *pool) { if (pool != 0) { pthread_mutex_destroy(&pool->poolMutex); free(pool); } } struct Message *GetMessage(struct MessagePool *pool) { pthread_mutex_lock(&pool->poolMutex); if (pool->count == 0) { return 0; } struct Message *m = pool->head; pool->head = pool->head->next; if (m == pool->tail) { pool->head = pool->tail = 0; } pool->count--; pthread_mutex_unlock(&pool->poolMutex); return m; } void PutMessage(struct MessagePool *pool, struct Message *m) { pthread_mutex_lock(&pool->poolMutex); if (pool->count == 0) { pool->head = m; pool->tail = m; } else { pool->tail->next = m; pool->tail = m; } pool->count++; pthread_mutex_unlock(&pool->poolMutex); }
1
#include <pthread.h> static int fd; static int disconnect; static char *ip; static char *port; static uint32_t cuid; static pthread_t hthid; static pthread_t rthid; static pthread_mutex_t fdlock; pthread_t thid; pthread_mutex_t mutex; pthread_cond_t cond; uint8_t *buff; uint32_t buffsize; uint8_t sent; uint8_t status; uint8_t release; uint32_t size; uint32_t cmd; uint32_t packetid; struct _threc *next; } threc; static threc *threc_head = 0; void fs_buffer_init(threc *rec,uint32_t size) { if (size > 10000) { rec->buff = realloc(rec->buff,size); rec->buffsize = size; } else if (rec->buffsize > 10000) { rec->buff = realloc(rec->buff,10000); rec->buffsize = 10000; } else { fprintf(stderr, "null\\n"); } } threc* fs_get_threc_by_id(uint32_t packetid) { threc *rec; for (rec = threc_head ; rec ; rec=rec->next) { if (rec->packetid==packetid) { return rec; } } return 0; } void get_chunkid(uint8_t *data) { uint64_t chunkid = 0; int8_t status = 0; uint8_t *ptr, hdr[16]; if (DEBUG) { fprintf(stderr, "----get create chunk info ---\\n"); } GET64BIT(chunkid, data); status = create_file(chunkid); if (status != 0) { fprintf(stderr, "create chunk file failed\\n"); } pthread_mutex_lock(&fdlock); if (disconnect == 0 && fd >= 0) { printf("--------------\\n"); ptr = hdr; PUT32BIT(DATTOSER_CREAT_CHUNK, ptr); PUT32BIT(8, ptr); PUT32BIT(0, ptr); PUT32BIT(status, ptr); if (tcptowrite(fd, hdr, 16, 1000) != 16) { disconnect = 1; } } pthread_mutex_unlock(&fdlock); } void analyze_ser_packet(uint32_t type, uint32_t size) { uint8_t *data = 0; data = malloc(size); if (tcptoread(fd, data, size, 1000) != (int32_t)(size)) { fprintf(stderr,"ser: tcp recv error(3)\\n"); disconnect=1; free(data); return; } switch (type) { case ANTOAN_NOP: break; case SERTODAT_DISK_INFO: break; case SERTODAT_CREAT_CHUNK: get_chunkid(data); break; default: break; } free(data); } int8_t analyze_ser_cmd(uint32_t type) { switch (type) { case ANTOAN_NOP: case SERTODAT_DISK_INFO: case SERTODAT_CREAT_CHUNK: return 0; default: break; } return 1; } void connect_ser() { fd = tcpsocket(); if (tcpconnect(fd, ip, port) < 0) { fprintf(stderr, "can't connect to ser(ip:%s,port:%s)\\n", ip, port); tcpclose(fd); fd = -1; return; } else { fprintf(stderr, "connect to ser(ip:%s,port:%s)\\n", ip, port); disconnect = 0; } } void *heartbeat_thread(void *arg) { uint8_t *ptr, hdr[28]; uint64_t totalspace; uint64_t freespace; totalspace = 201; freespace = 102; while (1) { pthread_mutex_lock(&fdlock); if (disconnect == 0 && fd >= 0) { ptr = hdr; PUT32BIT(DATTOSER_DISK_INFO, ptr); PUT32BIT(20, ptr); PUT32BIT(0, ptr); PUT64BIT(totalspace, ptr); PUT64BIT(freespace, ptr); printf("heart beat\\n"); if (tcptowrite(fd, hdr, 28, 1000) != 28) { disconnect = 1; } } pthread_mutex_unlock(&fdlock); sleep(5); } } void *receive_thread(void *arg) { uint8_t *ptr = 0; uint8_t hdr[12] = {0}; uint32_t cmd = 0; uint32_t size = 0; uint32_t packetid = 0; int r = 0; threc *rec = 0; for (;;) { pthread_mutex_lock(&fdlock); if (fd == -1 && disconnect) { connect_ser(); } if (disconnect) { tcpclose(fd); fd = -1; for (rec = threc_head; rec; rec=rec->next) { } } if (fd == -1) { fprintf(stderr, "reconnect ser(ip:%s,port:%s)\\n", ip, port); sleep(2); pthread_mutex_unlock(&fdlock); continue; } pthread_mutex_unlock(&fdlock); r = read(fd,hdr,12); if (r==0) { fprintf(stderr, "ser: connection lost (1)\\n"); disconnect=1; continue; } if (r!=12) { fprintf(stderr,"ser: tcp recv error(1), %d\\n", r); disconnect=1; continue; } ptr = hdr; GET32BIT(cmd,ptr); GET32BIT(size,ptr); GET32BIT(packetid,ptr); fprintf(stderr, "read, cmd:%u\\n", cmd); fprintf(stderr, "read, size:%u\\n", size); fprintf(stderr, "read, packetid:%u\\n", packetid); if (cmd==ANTOAN_NOP && size==4) { continue; } if (size < 4) { fprintf(stderr,"ser: packet too small\\n"); disconnect=1; continue; } size -= 4; if (analyze_ser_cmd(cmd) == 0) { analyze_ser_packet(cmd, size); continue; } rec = fs_get_threc_by_id(packetid); if (rec == 0) { fprintf(stderr, "ser: get unexpected queryid\\n"); disconnect=1; continue; } fs_buffer_init(rec,rec->size+size); if (rec->buff == 0) { disconnect=1; continue; } if (size>0) { r = tcptoread(fd,rec->buff+rec->size,size,1000); int i; fprintf(stderr, "read buf:%s, size:%d\\n", rec->buff, size); for(i = 0; i< size; i++) { fprintf(stderr, "%u-", rec->buff[rec->size+i]); } fprintf(stderr, "\\n"); if (r == 0) { fprintf(stderr,"ser: connection lost (2)\\n"); disconnect=1; continue; } if (r != (int32_t)(size)) { fprintf(stderr,"ser: tcp recv error(2)\\n"); disconnect=1; continue; } } rec->sent=0; rec->status=0; rec->size = size; rec->cmd = cmd; pthread_mutex_lock(&(rec->mutex)); rec->release = 1; pthread_mutex_unlock(&(rec->mutex)); pthread_cond_signal(&(rec->cond)); } } void ser_init(char *_ip, char *_port) { ip = strdup(_ip); port = strdup(_port); cuid = 0; fd = -1; disconnect = 1; pthread_mutex_init(&fdlock,0); pthread_create(&rthid, 0, receive_thread, 0); }
0
#include <pthread.h> double time_diff(struct timeval x , struct timeval y) { double x_ms , y_ms , diff; x_ms = (double)x.tv_sec*1000000 + (double)x.tv_usec; y_ms = (double)y.tv_sec*1000000 + (double)y.tv_usec; diff = (double)y_ms - (double)x_ms; return diff; } pthread_mutex_t prod_mutex; int prod = 0; int* A; int* B; int size; int id; }thread_arg; void* prod_escalar(void* arg){ int i; int begin; int end; int local_prod=0; int block_size = (500000)/(4); thread_arg* t_arg = (thread_arg*) arg; begin = t_arg->id * block_size; end = t_arg->id == ((4) -1) ? t_arg->size : begin+block_size; for(i=begin; i<end ;i++){ local_prod += t_arg->A[i] * t_arg->B[i]; } printf("Thread %d -> Produto local: %d\\n",t_arg->id,local_prod); pthread_mutex_lock(&prod_mutex); prod+=local_prod; pthread_mutex_unlock(&prod_mutex); pthread_exit(0); } int main(void){ int i; int A[(500000)],B[(500000)]; pthread_t threads[(4)]; int rv; thread_arg t_arg[(4)]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); struct timeval before,after; srand(time(0)); for(i=0;i<(500000);i++){ A[i] = rand()% (3); B[i] = rand()% (3); } gettimeofday(&before,0); for(i=0;i<(4);i++){ t_arg[i].id = i; t_arg[i].A = A; t_arg[i].B = B; t_arg[i].size = (500000); pthread_create(&threads[i], &attr, prod_escalar, (void*) &t_arg[i]); } for(i=0;i<(4);i++){ pthread_join(threads[i],(void*) &rv); } gettimeofday(&after,0); printf("O cálculo levou %lf microsegundos: ",time_diff(before,after)); printf("O produto escalar é: %d\\n",prod); pthread_exit(0); }
1
#include <pthread.h> int result = 0; pthread_mutex_t mutex; pthread_mutex_t fict; pthread_mutex_t write; pthread_cond_t blocked; char password[256]; void *WritingThread() { while(1) { pthread_mutex_lock(&write); if (result) break; pthread_mutex_lock(&mutex); printf("Enter password\\n"); scanf("%s", password); pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&fict); } } void *VerifyPassword(void* pass) { char *passw; while(!result) { pthread_mutex_lock(&fict); pthread_mutex_lock(&mutex); passw = (char*) pass; pthread_mutex_unlock(&mutex); if(!strcmp(passw, password)) { printf("The password is confirmed\\n"); result++; pthread_mutex_unlock(&write); break; } else { printf("Incorrect password, try again\\n"); } pthread_mutex_unlock(&write); } } int main (int argc, char *argv[]) { pthread_mutex_lock(&fict); int rc; char pass[256] = "ABCD"; pthread_t threads[2]; printf("In main: creating thread 1\\n"); rc = pthread_create(&threads[0], 0, WritingThread, 0); if (rc) { printf("Error 1 thread; return code is %d\\n", rc); } printf("In main: creating thread 2\\n"); rc = pthread_create(&threads[1], 0, VerifyPassword, (void *) pass); if (rc) { printf("Error 2 thread; return code is %d\\n", rc); } pthread_join(threads[1], 0); printf("Thread 1 finished\\n"); pthread_join(threads[0], 0); printf("Thread 0 finished\\n"); return 0; }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; struct foo * foo_alloc(int id) { struct foo *fp; 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); } } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if (--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void 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> int vec[5000] = {0}; int n = 0; pthread_mutex_t exclusion; void printVector() { int i; for(i = 1; i <= 2000; i++) { printf("%d ", vec[i]); } printf("\\n"); } void *computeThread(void *arg) { printf("Started thread \\n"); int i; for( i = 1; i <= 250; i++) { pthread_mutex_lock(&exclusion); int r = rand() % 1000 + 1 + 1000; int pos = 1, j; while(pos <= n && vec[pos] < r) pos++; n = n + 1; for(j = n; j > pos; j--) { vec[j] = vec[j-1]; } vec[pos] = r; pthread_mutex_unlock(&exclusion); } return 0; } int main(int argc, char* argv[]) { pthread_t threads[8]; srand(time(0)); if(pthread_mutex_init(&exclusion, 0) != 0) { perror("Error creating mutex"); exit(1); } int i; for(i = 0; i < 8; i++) { pthread_create(&threads[i], 0, computeThread, 0 ); } for(i = 0; i < 8; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&exclusion); printf("n: %d\\n", n); printVector(); }
0
#include <pthread.h> int buffer[10]; sem_t buffer_full; sem_t buffer_empty; pthread_mutex_t thread_mutex; pthread_t produce_thread; pthread_t consume_thread; void *consume() { int k = 0; while (k < 100) { sem_wait(&buffer_empty); pthread_mutex_lock(&thread_mutex); int first_product = -1; int i; for (i = 0; i < 10; i++) { printf("%02d ", i); if (buffer[i] == 0) printf("%s", "null"); else { printf("%d", buffer[i]); if (first_product == -1) { printf("\\t<--consume"); first_product = i; } } printf("\\n"); } printf("consume product %02d\\n", first_product); buffer[first_product] = 0; pthread_mutex_unlock(&thread_mutex); sem_post(&buffer_full); k++; } sleep(2); return 0; } void *produce() { int j = 0; while (j < 100) { sem_wait(&buffer_full); pthread_mutex_lock(&thread_mutex); int first_null = -1; int i; for (i = 0; i < 10; i++) { printf("%02d ", i); if (buffer[i] == 0) { printf("%s", "null"); if (first_null == -1) { printf("\\t<--produce"); first_null = i; } } else printf("%d", buffer[i]); printf("\\n"); } printf("produce product %02d\\n",first_null); buffer[first_null] = 1; pthread_mutex_unlock(&thread_mutex); sem_post(&buffer_empty); j++; } sleep(5); return 0; } int main(void) { int index; for (index = 0; index < 10; index++) buffer[index] = 0; sem_init(&buffer_full, 0, 10); sem_init(&buffer_empty, 0, 0); pthread_mutex_init(&thread_mutex, 0); pthread_create(&consume_thread, 0, consume, 0); pthread_create(&produce_thread, 0, produce, 0); pthread_join(consume_thread, 0); pthread_join(produce_thread, 0); return 0; }
1
#include <pthread.h> int N=100; int T=4; pthread_mutex_t count_lock; pthread_cond_t ok_to_proceed; int count; } barrier; double escalar; barrier *barrera; double max, min, suma; double *R; double* M[3]; pthread_mutex_t mutexMax; pthread_mutex_t mutexMin; pthread_mutex_t mutexAvg; void printMatrix(double* M, char* c, int ord){ int i,j; printf("Matriz %s:\\n", c); if(ord==1){ for (i=0;i<N;i++){ for(j=0;j<N;j++){ printf("%f ",M[i+j*N]); } printf("\\n"); } } else { for (i=0;i<N;i++){ for(j=0;j<N;j++){ printf("%f ",M[i*N+j]); } printf("\\n"); } } } double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *hilar(void *s){ int i,k,j,c; int tid = *((int*)s); int cant=0; int inicio=tid*(N/T); int fin=inicio+N/T; double minLocal, maxLocal, sumaLocal; minLocal=9999; maxLocal=-999; sumaLocal=0; for(k=0;k<3;++k){ for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j]; if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j]; sumaLocal+=M[k][i*N+j]; } } } pthread_mutex_lock(&mutexMax); if(maxLocal>max) max=maxLocal; pthread_mutex_unlock(&mutexMax); pthread_mutex_lock(&mutexMin); if(minLocal<min) min=minLocal; pthread_mutex_unlock(&mutexMin); pthread_mutex_lock(&mutexAvg); suma+=sumaLocal; pthread_mutex_unlock(&mutexAvg); pthread_mutex_lock(&(barrera -> count_lock)); barrera -> count ++; if (barrera -> count == T){ barrera -> count = 0; escalar=(max-min)/(suma/(N*N*3)); pthread_cond_broadcast(&(barrera -> ok_to_proceed)); }else{ pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock)); } pthread_mutex_unlock(&(barrera -> count_lock)); for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ M[0][i*N+j] = M[0][i*N+j] * escalar; } } for(k=1;k<3;++k){ for(i=0;i<N;++i){ for(j=inicio;j<fin;++j){ M[k][i+j*N] = M[k][i+j*N] * escalar; } } } pthread_mutex_lock(&(barrera -> count_lock)); barrera -> count ++; if (barrera -> count == T){ barrera -> count = 0; pthread_cond_broadcast(&(barrera -> ok_to_proceed)); }else{ pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock)); } pthread_mutex_unlock(&(barrera -> count_lock)); for(k=1;k<3;++k){ if(k%2==1){ for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ R[i*N+j]=0; for(c=0;c<N;++c){ R[i*N+j]+=M[0][i*N+c]*M[k][c+j*N]; } } } } else { for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ M[0][i*N+j]=0; for(c=0;c<N;++c){ M[0][i*N+j]+=R[i*N+c]*M[k][c+j*N]; } } } } } } int main(int argc,char*argv[]){ int i,j,k; double timetick; if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[2])) <= 0)) { printf("\\nUsar: %s n t\\n n: Dimension de la matriz (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]); exit(1); } R=(double*)malloc(sizeof(double)*N*N); for(i=0;i<3;i++){ M[i]=(double*)malloc(sizeof(double)*N*N); } M[0][0]=1; M[0][1]=2; M[0][2]=3; M[0][3]=4; M[0][4]=5; M[0][5]=6; M[0][6]=7; M[0][7]=8; M[0][8]=9; M[0][9]=10; M[0][10]=11; M[0][11]=12; M[0][12]=13; M[0][13]=14; M[0][14]=15; M[0][15]=16; M[1][0]=17; M[1][1]=21; M[1][2]=25; M[1][3]=29; M[1][4]=18; M[1][5]=22; M[1][6]=26; M[1][7]=30; M[1][8]=19; M[1][9]=23; M[1][10]=27; M[1][11]=31; M[1][12]=20; M[1][13]=24; M[1][14]=28; M[1][15]=32; M[2][0]=33; M[2][1]=37; M[2][2]=41; M[2][3]=45; M[2][4]=34; M[2][5]=38; M[2][6]=42; M[2][7]=46; M[2][8]=35; M[2][9]=39; M[2][10]=43; M[2][11]=47; M[2][12]=36; M[2][13]=40; M[2][14]=44; M[2][15]=48; pthread_t p_threads[T]; pthread_attr_t attr; pthread_attr_init (&attr); int id[T]; pthread_mutex_init(&mutexMax, 0); pthread_mutex_init(&mutexMin, 0); pthread_mutex_init(&mutexAvg, 0); barrera = (barrier*)malloc(sizeof(barrier)); barrera -> count = 0; pthread_mutex_init(&(barrera -> count_lock), 0); pthread_cond_init(&(barrera -> ok_to_proceed), 0); min=9999; max=-999; suma=0; timetick = dwalltime(); for(i=0;i<T;i++){ id[i]=i; pthread_create(&p_threads[i], &attr, hilar, (void *) &id[i]); } for(i=0;i<T;i++){ pthread_join(p_threads[i],0); } printf("\\nTiempo en segundos %f\\n", dwalltime() - timetick); if(3%2 == 1){ free(R); R=M[0]; } printMatrix(R,"R",0); free(barrera); free(R); for(i=1;i<3;i++){ free(M[i]); } return(0); }
0