text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c = PTHREAD_COND_INITIALIZER; struct global { int flag; int gameover; } g; struct data { int indice; int point; int tirage; } d[2]; int tirage() { int r; r = rand()%2; return r; } void * handler (void * arg) { struct data *dat = (struct data *) arg; do { pthread_mutex_lock(&m); while (g.flag == dat->indice) { pthread_cond_wait (&c, &m); } pthread_mutex_unlock(&m); while (tirage()==tirage() && g.gameover == 0) { dat->point++; if (dat->point == 10) { g.gameover = 1; break; } } dat->tirage++; pthread_mutex_lock(&m); g.flag = dat->indice; pthread_cond_signal (&c); pthread_mutex_unlock(&m); if (g.gameover) { pthread_exit(0); } } while (1); } int main (void) { pthread_t t1, t2; sranddev(); d[0].indice = 0; d[0].point = 0; d[0].tirage = 0; pthread_create(&t1, 0, handler, &d[0]); d[1].indice = 1; d[1].point = 0; d[1].tirage = 0; pthread_create(&t2, 0, handler, &d[1]); pthread_join(t1, 0); pthread_join(t2, 0); }
1
#include <pthread.h> char *axis_names[ABS_MAX + 1] = { "X", "Y", "Z", "Rx", "Ry", "Rz", "Throttle", "Rudder", "Wheel", "Gas", "Brake", "?", "?", "?", "?", "?", "Hat0X", "Hat0Y", "Hat1X", "Hat1Y", "Hat2X", "Hat2Y", "Hat3X", "Hat3Y", "?", "?", "?", "?", "?", "?", "?", }; char *button_names[KEY_MAX - BTN_MISC + 1] = { "Btn0", "Btn1", "Btn2", "Btn3", "Btn4", "Btn5", "Btn6", "Btn7", "Btn8", "Btn9", "?", "?", "?", "?", "?", "?", "LeftBtn", "RightBtn", "MiddleBtn", "SideBtn", "ExtraBtn", "ForwardBtn", "BackBtn", "TaskBtn", "?", "?", "?", "?", "?", "?", "?", "?", "Trigger", "ThumbBtn", "ThumbBtn2", "TopBtn", "TopBtn2", "PinkieBtn", "BaseBtn", "BaseBtn2", "BaseBtn3", "BaseBtn4", "BaseBtn5", "BaseBtn6", "BtnDead", "BtnA", "BtnB", "BtnC", "BtnX", "BtnY", "BtnZ", "BtnTL", "BtnTR", "BtnTL2", "BtnTR2", "BtnSelect", "BtnStart", "BtnMode", "BtnThumbL", "BtnThumbR", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "WheelBtn", "Gear up", }; void event(int x, int y); void * update(void * arg); void turn(int fd, int right); int left; int right; int b[4] = { 0 }; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t cnd_mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cnd = PTHREAD_COND_INITIALIZER; int main (int argc, char **argv) { int fd, i; unsigned char axes = 2; unsigned char buttons = 2; int version = 0x000800; char name[128] = "Unknown"; uint16_t btnmap[KEY_MAX - BTN_MISC + 1]; uint8_t axmap[ABS_MAX + 1]; if (argc != 4) { puts(""); puts("Usage: jstest <device> <host> <port>"); puts(""); return 1; } if ((fd = open(argv[1], O_RDONLY)) < 0) { perror("jsrobot"); return 1; } ioctl(fd, JSIOCGVERSION, &version); ioctl(fd, JSIOCGAXES, &axes); ioctl(fd, JSIOCGBUTTONS, &buttons); ioctl(fd, JSIOCGNAME(128), name); ioctl(fd, JSIOCGAXMAP, axmap); ioctl(fd, JSIOCGBTNMAP, btnmap); printf("Driver version is %d.%d.%d.\\n", version >> 16, (version >> 8) & 0xff, version & 0xff); printf("Joystick (%s) has %d axes (", name, axes); for (i = 0; i < axes; i++) printf("%s%s", i > 0 ? ", " : "", axis_names[axmap[i]]); puts(")"); printf("and %d buttons (", buttons); for (i = 0; i < buttons; i++) printf("%s%s", i > 0 ? ", " : "", button_names[btnmap[i] - BTN_MISC]); puts(")."); if (axes < 2) { printf("No enought axes.\\n"); exit(0); } int *axis; char *button; struct js_event js; axis = calloc(axes, sizeof(int)); button = calloc(buttons, sizeof(char)); int sock; if ((sock = getsockfd(argv[2], argv[3])) < 0) { fprintf(stderr, "Error: getsockfd(%s,%s)\\n", argv[2], argv[3]); exit(1); } pthread_t pth; pthread_create(&pth, 0, update, &sock); while (1) { if (read(fd, &js, sizeof(struct js_event)) != sizeof(struct js_event)) { perror("\\njstest: error reading"); return 1; } switch(js.type & ~JS_EVENT_INIT) { case JS_EVENT_BUTTON: button[js.number] = js.value; break; case JS_EVENT_AXIS: axis[js.number] = js.value; break; } if (button[1] && !b[1]) { b[1] = 1; can_write(sock, bin, 1051, 0); } else if (button[3] && !b[2]) { b[2] = 1; turn(sock, 0); } else if (button[3] && !b[3]) { b[3] = 1; turn(sock, 1); } else { b[1] = 0; b[2] = 0; b[3] = 0; event(axis[0], -axis[1]); } } return -1; } void turn(int fd, int right) { short int value = 2106; if (!right) { value = -value; } can_write(fd, bin, 1026, 2, ((char*)&value)[0], ((char*)&value)[1]); } void event(int _x, int _y) { static time_t t = 0; int x = (_x * 80) / 32767; int y = (_y * 80) / 32767; if (pthread_mutex_lock(&mtx) < 0) { perror("pthread_mutex_lock"); exit(1); } left = y; right = y; + x * (y-80) / 160; if (x > 0) { left -= x * (y-80) / 160; right -= x * (y+80) / 160; } else { left += x * (y+80) / 160; right += x * (y-80) / 160; } if (pthread_mutex_unlock(&mtx) < 0) { perror("pthread_mutex_unlock"); exit(1); } pthread_mutex_lock(&cnd_mtx); pthread_cond_signal(&cnd); pthread_mutex_unlock(&cnd_mtx); } void * update(void * arg) { int l = 81; int r = 81; int u = 0; struct can_t packet; packet.id = 1032; packet.length = 2; while (1) { if (l == left && r == right) { u++; } else { u = 0; } if (u < 3) { if (pthread_mutex_lock(&mtx) < 0) { perror("pthread_mutex_lock"); exit(1); } l = left; r = right; if (pthread_mutex_unlock(&mtx) < 0) { perror("pthread_mutex_unlock"); exit(1); } packet.b[0] = l; packet.b[1] = r; can_pwrite(*((int*)arg), bin, &packet); usleep(200 * 1000); } else { pthread_mutex_lock(&cnd_mtx); pthread_cond_wait(&cnd, &cnd_mtx); pthread_mutex_unlock(&cnd_mtx); } printf("\\r"); printf("%+04d %+04d %d %d %d", left, right, b[1], b[2], b[3]); fflush(stdout); } }
0
#include <pthread.h> char buffer[80000 + 1]; int wordcount; pthread_mutex_t lock; struct param { int index; int start; int end; }; void wcount(struct param *arg); double sec(void); int main (int argc, char *argv[]){ FILE *fp = fopen(argv[1], "r"); if (fp != 0) { size_t newLen = fread(buffer, sizeof(char), 80000, fp); if (newLen == 0) { fputs("Error reading file\\n", stderr); exit(0); } else { buffer[++newLen] = '\\0'; } pthread_t tid[8]; pthread_attr_t attr; struct param p[8]; int part = 80000/8; int i, cut; pthread_attr_init(&attr); for(i = 0; i < 8; i++){ p[i].index = i; if(i == 0){ p[i].start = 0; }else{ p[i].start = (p[i - 1].end) + 1; } cut = (i + 1) * part; while(buffer[cut] != ' ' && buffer[cut] != '\\n' && cut != (i + 2) * part){ cut++; } p[i].end = cut; } if (pthread_mutex_init(&lock, 0) != 0){ printf("mutex init failed\\n"); return 1; } double t; t = sec(); for(i = 0; i < 8; i++){ pthread_create(&tid[i], &attr, (void*)wcount, &p[i]); } for(i = 0; i < 8; i++){ pthread_join(tid[i], 0); } t = sec() - t; printf("%d word(s): Runtime %f\\n", wordcount, t); pthread_mutex_destroy(&lock); fclose(fp); } return 0; } double sec(void){ return (double)clock()/CLOCKS_PER_SEC; } void wcount(struct param *arg){ pthread_mutex_lock(&lock); int i; if(((buffer[arg->start]) >='a' && (buffer[arg->start]) <= 'z') || ((buffer[arg->start]) >='A' && (buffer[arg->start]) <= 'Z') || ((buffer[arg->start]) >='0' && (buffer[arg->start]) <= '9')){ wordcount++; } for(i = arg->start; i < (arg->end); i++){ if(buffer[i] == ' ' || buffer[i] == '\\n'){ if(((buffer[i + 1]) >='a' && (buffer[i + 1]) <= 'z') || ((buffer[i + 1]) >='A' && (buffer[i + 1]) <= 'Z') || ((buffer[i + 1]) >='0' && (buffer[i + 1]) <= '9')){ wordcount++; } } } pthread_mutex_unlock(&lock); pthread_exit(0); }
1
#include <pthread.h> void* clnt_connection(void * arg); void send_message(char* message, int len); void error_handling(char * message); int clnt_number=0; int clnt_socks[10]; pthread_mutex_t mutx; int main(int argc, char **argv) { int serv_sock; int clnt_sock; struct sockaddr_in serv_addr; struct sockaddr_in clnt_addr; int clnt_addr_size; pthread_t thread; if(argc != 2) { printf("Usage : %s <port>\\n", argv[0]); exit(1); } if(pthread_mutex_init(&mutx,0)) error_handling("mutex init error"); serv_sock = socket(PF_INET, SOCK_STREAM, 0); if(serv_sock == -1) error_handling("socket() error"); memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1) error_handling("bind() error"); if(listen(serv_sock, 5) == -1) error_handling("listen() error"); while(1) { clnt_addr_size = sizeof(clnt_addr); clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size); pthread_mutex_lock(&mutx); clnt_socks[clnt_number++]=clnt_sock; pthread_mutex_unlock(&mutx); pthread_create(&thread, 0, clnt_connection, (void*) clnt_sock); printf(" IP : %s \\n", inet_ntoa(clnt_addr.sin_addr)); } return 0; } void *clnt_connection(void *arg) { int clnt_sock = (int) arg; int str_len=0; char message[100]; int i; while((str_len=read(clnt_sock, message, sizeof(message))) != 0 ) send_message(message, str_len); pthread_mutex_lock(&mutx); for(i=0;i<clnt_number;i++){ if(clnt_sock == clnt_socks[i]) { for(;i<clnt_number-1;i++) clnt_socks[i] = clnt_socks[i+1]; break; } } clnt_number--; pthread_mutex_unlock(&mutx); close(clnt_sock); return 0; } void send_message(char * message, int len) { int i; pthread_mutex_lock(&mutx); for(i=0;i<clnt_number;i++) write(clnt_socks[i], message, len); pthread_mutex_unlock(&mutx); } void error_handling(char * message) { fputs(message, stderr); fputc('\\n',stderr); exit(1); }
0
#include <pthread.h> struct hostent *my_gethostbyname_r(const char *name, struct hostent *res , char *buffer , int buflen , int *h_errnop) { struct hostent *hp; pthread_mutex_lock(&LOCK_gethostbyname_r); hp= gethostbyname(name); *h_errnop= h_errno; return hp; } void my_gethostbyname_r_free() { pthread_mutex_unlock(&LOCK_gethostbyname_r); }
1
#include <pthread.h> struct listnode* create_node(char *str) { if(!str) { fprintf(stderr, "Error creating node.\\n"); return 0; } unsigned int strln = strlen(str); struct listnode *tmp_node = malloc(sizeof(struct listnode)); tmp_node->str = malloc((strln + 1) * sizeof(char)); strcpy(tmp_node->str, str); tmp_node->next = 0; return tmp_node; } void insert_node(struct listnode **first_node_ptr, struct listnode *new_node) { pthread_mutex_lock(&mutex_insert); if(!(*first_node_ptr)) { *first_node_ptr = new_node; pthread_mutex_unlock(&mutex_insert); } else if(!(*first_node_ptr)->next) { (*first_node_ptr)->next = new_node; pthread_mutex_unlock(&mutex_insert); } else { struct listnode *next_node = (*first_node_ptr)->next; struct listnode *tmp_node = 0; while(next_node) { tmp_node = next_node; next_node = tmp_node->next; } tmp_node->next = new_node; pthread_mutex_unlock(&mutex_insert); } } struct listnode* pop(struct listnode **first_node_ptr) { pthread_mutex_lock(&mutex_pop); if(!(*first_node_ptr)) { fprintf(stderr, "List head is null.\\n"); pthread_mutex_unlock(&mutex_pop); return 0; } else { struct listnode *old_first_node = *first_node_ptr; *first_node_ptr = (*first_node_ptr)->next; pthread_mutex_unlock(&mutex_pop); return old_first_node; } } void print_nodes(struct listnode **first_node) { fprintf(stdout, "Printing all nodes... \\n"); if(!(*first_node)) { fprintf(stderr, "No nodes in list.\\n"); } else { fprintf(stdout, "%s\\n", (*first_node)->str); struct listnode *next_node = (*first_node)->next; while(next_node) { fprintf(stdout, "%s\\n", next_node->str); next_node = next_node->next; } } } void free_nodes(struct listnode **first_node) { if(!(*first_node)) { fprintf(stderr, "Head node is null.\\n"); } else { struct listnode *current_node = *first_node; struct listnode *next_node = current_node->next; while(next_node) { free(current_node->str); free(current_node); current_node = next_node; next_node = current_node->next; } free(current_node->str); free(current_node); *first_node = 0; } }
0
#include <pthread.h> Turn turn = None; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition = PTHREAD_COND_INITIALIZER; void *first (void *args) { while(1) { pthread_mutex_lock(&lock); while(turn != First) pthread_cond_wait(&condition, &lock); printf("first\\n"); turn = Second; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&lock); } } void *second (void *args) { while(1) { pthread_mutex_lock(&lock); while(turn != Second) pthread_cond_wait(&condition, &lock); printf("second\\n"); turn = Third; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&lock); } } void *third (void *args) { while(1) { pthread_mutex_lock(&lock); while(turn != Third) pthread_cond_wait(&condition, &lock); printf("third\\n"); turn = First; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&lock); } } int main () { char buf[32]; pthread_t t1,t2,t3; pthread_create(&t3, 0, third, 0); pthread_create(&t2, 0, second, 0); pthread_create(&t1, 0, first, 0); sleep(1); pthread_mutex_lock(&lock); printf("Start\\n"); sleep(1); turn = First; pthread_cond_broadcast(&condition); pthread_mutex_unlock(&lock); printf("Enter \\"end\\" to end...\\n"); while(strcmp(gets(buf), "end") != 0); return 0; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo * foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp->f_next; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } struct foo * foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp)%29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_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); } else { pthread_mutex_unlock(&hashlock); } }
0
#include <pthread.h> pthread_mutex_t mutex_lock; sem_t students_sem; sem_t ta_sem; int waiting_students; void* studentRoutine(void* param); void* taRoutine(void* param); int main(void) { printf("CS149 SleepingTA from Mark Casapao\\n"); waiting_students = 0; pthread_mutex_init(&mutex_lock, 0); sem_init(&ta_sem, 0, 0); sem_init(&students_sem, 0, 0); pthread_t ta; if(pthread_create(&ta,0,taRoutine,0) != 0){ printf("Thread error type 2"); } pthread_t students[4]; for(int i=0; i<4; i++) { int *arg = malloc(sizeof(*arg)); if ( arg == 0 ) { fprintf(stderr, "Couldn't allocate memory for thread arg.\\n"); exit(1); } *arg = i+1; if(pthread_create(&students[i],0,studentRoutine,(void*)arg) != 0){ printf("Thread error type 1"); } } for(int i=0; i<4; i++){ pthread_join(students[i],0); } printf("No more students need help, closing TA's office hours.\\n"); pthread_cancel(ta); pthread_mutex_destroy(&mutex_lock); sem_destroy(&students_sem); sem_destroy(&ta_sem); return 0; } void* studentRoutine(void* studentID){ int id = *((int*) studentID); int rand = id; int helpsNeeded = 2; while(helpsNeeded != 0){ int random = (rand_r(&rand) % 3) + 1; printf("Student %i is programming for %i second(s).\\n",id,random); sleep(random); pthread_mutex_lock(&mutex_lock); if(waiting_students != 2){ waiting_students++; printf(" Student %i sat down in waiting room. %i student(s) currently waiting.\\n",id,waiting_students); pthread_mutex_unlock(&mutex_lock); sem_post(&students_sem); sem_wait(&ta_sem); printf(" Student %i has received help from TA.\\n",id); helpsNeeded--; } else{ printf(" Student %i noticed the waiting room was full and resumes programming.\\n",id); pthread_mutex_unlock(&mutex_lock); } } printf("Congratulations! Student %i has finished their program assignment!\\n", id); free(studentID); pthread_exit(0); } void* taRoutine(void* param){ while(1){ sem_wait(&students_sem); pthread_mutex_lock(&mutex_lock); waiting_students--; printf(" TA chose a student to help for 3 seconds. %i student(s) currently waiting.\\n", waiting_students); pthread_mutex_unlock(&mutex_lock); sem_post(&ta_sem); sleep(3); } }
1
#include <pthread.h> pthread_mutex_t lock; void * thread_func(void * arg) { FILE * fp = (FILE *)arg; int n; char buf[32]; int semid; printf("Hello this is %d\\n", pthread_self()); pthread_mutex_lock(&lock); printf("%d got the mutex!\\n", pthread_self()); fseek(fp, 0, 0); fgets(buf, 32, fp); if (buf[strlen(buf)-1] == '\\n') buf[strlen(buf)-1] = '\\0'; n = atoi(buf); fseek(fp, 0, 0); sleep(3); fprintf(fp, "%d", n+1); fflush(fp); pthread_mutex_unlock(&lock); return 0; } int main(void) { pthread_t tid[5]; int i, ret; FILE * fp; fp = fopen("tmp", "r+"); if (fp == 0) { perror("fopen"); exit(1); } pthread_mutex_init(&lock, 0); for (i = 0; i < 5; i++) { ret = pthread_create(tid+i, 0, thread_func, (void *)fp); if (ret) { fprintf(stderr, "%s\\n", strerror(ret)); exit(1); } } for (i = 0; i < 5; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&lock); fclose(fp); exit(0); }
0
#include <pthread.h> bool AGING_Init() { ASSERT_PRINT("Entering:AGING_Init()\\n"); Aging_Registers = calloc(NumOfPagesInMM, sizeof (unsigned int)); int i = 0; for (i = 0; i < NumOfPagesInMM; i++) Aging_Registers[i] = 0; pthread_mutex_init(&Aging_mutex, 0); if (pthread_create(&Aging, 0, AGING_Main, 0) != 0) return FALSE; ASSERT_PRINT("Exiting:AGING_Init()\\n"); return TRUE; } void AGING_Close() { ASSERT_PRINT("Entering:AGING_Close()\\n"); AGING_ShouldClose = TRUE; ASSERT_PRINT("Exiting:AGING_Close()\\n"); } void AGING_DeInit() { ASSERT_PRINT("Entering:AGING_DeInit()\\n"); free(Aging_Registers); ASSERT_PRINT("Exiting:AGING_DeInit()\\n"); } void* AGING_Main() { ASSERT_PRINT("Entering:AGING_Main()\\n"); int i = 0; unsigned int m = ((unsigned int) - 1 >> 1) + 1; while (!AGING_ShouldClose) { pthread_mutex_lock(&Aging_mutex); if (IPT != 0) { ASSERT_PRINT("Aging deamon kicks in...\\n"); for (i = 0; i < NumOfPagesInMM; i++) { Aging_Registers[i] >>= 1; if (IPT[i] != 0 && IPT[i]->referenceBit == TRUE) { Aging_Registers[IPT[i]->frame] |= m; } if (IPT[i] != 0) IPT_UpdateReferencetyBit(IPT[i]->frame, FALSE); } } ASSERT_PRINT("Aging deamon finished...\\n"); pthread_mutex_unlock(&MM_Counter_Mutex); } AGING_DeInit(); ASSERT_PRINT("Exiting:AGING_Main()\\n"); }
1
#include <pthread.h> int n, **matrix; pthread_mutex_t matrix_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_main(void *arg) { int thread_number = *((int *)arg), i, j; int op = rand() % 2; if (thread_number % 2 == 0) { for (i = 0; i < n; i++) { if (op == 0) { pthread_mutex_lock(&matrix_mutex); matrix[i][thread_number] += thread_number; pthread_mutex_unlock(&matrix_mutex); } else { pthread_mutex_lock(&matrix_mutex); matrix[i][thread_number] -= thread_number; pthread_mutex_unlock(&matrix_mutex); } } } else { for (j = 0; j < n; j++) { if (op == 0) { pthread_mutex_lock(&matrix_mutex); matrix[thread_number][j] += thread_number; pthread_mutex_unlock(&matrix_mutex); } else { pthread_mutex_lock(&matrix_mutex); matrix[thread_number][j] += thread_number; pthread_mutex_unlock(&matrix_mutex); } } } pthread_mutex_lock(&matrix_mutex); printf("\\nThread: %d\\n", thread_number); print_matrix(matrix, n, n); pthread_mutex_unlock(&matrix_mutex); free(arg); return 0; } int main(int argc, char *argv[]) { int i; printf("Matrix size N = "); scanf("%d", &n); pthread_t *array_threads = malloc(sizeof(pthread_t) * n); matrix = (int**)malloc(n * sizeof(int*)); for (i = 0; i < n; i++) { matrix[i] = (int*)calloc(n, n * sizeof(int)); } rand_seed(); print_matrix(matrix, n, n); for (i = 0; i < n; i++) { int *temp_i = malloc(sizeof(int)); *temp_i = i; pthread_create(&array_threads[i], 0, thread_main, temp_i); } for (i = 0; i < n; i++) { pthread_join(array_threads[i] , 0) ; } free(array_threads); for (i = 0; i < n; i++) { free(matrix[i]); } free(matrix); return 0; }
0
#include <pthread.h> pthread_mutex_t count_mutex; pthread_mutex_t stop_mutex; pthread_cond_t count_empty_cond; pthread_cond_t count_full_cond; int count=0; int iteration=0; enum THREAD_ENUM{ FILL_THREAD=0, EMPTY_THREAD=1, ALL_THREADS }; char THREAD_NAMES[ALL_THREADS][64]={ "FILL", "EMPTY" }; void *fillCount(void *id) { long thread_id = (long)id; while(1){ printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 49, thread_id, count); pthread_mutex_lock(&count_mutex); while(0 != count){ printf("%s::%d thread %ld count: %d, wait buffer empty\\n", __FUNCTION__, 53, thread_id, count); pthread_cond_wait(&count_empty_cond, &count_mutex); printf("%s::%d thread %ld count: %d, receive empty signal\\n", __FUNCTION__, 56, thread_id, count); } while(20 > count){ count++; printf("%s::%d thread %ld fill count: %d\\n", __FUNCTION__, 62, thread_id, count); } if(60 < count){ printf("%s::%d thread %ld count: %d, count filled\\n", __FUNCTION__, 66, thread_id, count); pthread_cond_signal(&count_full_cond); printf("%s::%d thread %ld count: %d, signaled full\\n", __FUNCTION__, 68, thread_id, count); } pthread_mutex_unlock(&count_mutex); pthread_mutex_lock(&stop_mutex); iteration++; if(iteration > 100){ pthread_mutex_unlock(&stop_mutex); pthread_exit(0); } pthread_mutex_unlock(&stop_mutex); } printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 81, thread_id, count); pthread_exit(0); } void *emptyCount(void *id) { long thread_id = (long)id; while(1){ printf("%s::%d thread %ld, count: %d\\n", __FUNCTION__, 91, thread_id, count); pthread_mutex_lock(&count_mutex); int rtn=EINVAL; while(60 != count && ETIMEDOUT != rtn){ pthread_mutex_lock(&stop_mutex); printf("iteration: %d\\n", iteration); pthread_mutex_unlock(&stop_mutex); printf("%s::%d thread %ld count: %d, wait buffer filled\\n", __FUNCTION__, 100, thread_id, count); struct timespec max_wait; clock_gettime(CLOCK_REALTIME, &max_wait); const int MAX_WAIT_SEC = 3; max_wait.tv_sec += MAX_WAIT_SEC; rtn = pthread_cond_timedwait(&count_full_cond, &count_mutex, &max_wait); printf("%s::%d thread %ld count: %d, break cond_timedwait\\n", __FUNCTION__, 107, thread_id, count); } while( 0 != count){ count--; printf("%s::%d thread %ld empty count: %d\\n", __FUNCTION__, 112, thread_id, count); } printf("%s::%d thread %ld count: %d, count emptyed\\n", __FUNCTION__, 115, thread_id, count); pthread_cond_signal(&count_empty_cond); printf("%s::%d thread %ld count: %d, signaled empty\\n", __FUNCTION__, 117, thread_id, count); pthread_mutex_unlock(&count_mutex); pthread_mutex_lock(&stop_mutex); iteration++; if(iteration > 100){ pthread_mutex_unlock(&stop_mutex); pthread_exit(0); } pthread_mutex_unlock(&stop_mutex); } printf("%s::%d thread %ld count: %d, going to exit thread\\n", __FUNCTION__, 129, thread_id, count); pthread_exit(0); } int main(int argc, char *argv[]){ long t1=1, t2=2; pthread_t fillThread, emptyThread; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_empty_cond, 0); pthread_cond_init(&count_full_cond, 0); pthread_attr_init(&attr); pthread_create(&fillThread, &attr, fillCount, (void *)t1); pthread_create(&emptyThread, &attr, emptyCount, (void *)t2); pthread_join(fillThread, 0); pthread_join(emptyThread, 0); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_empty_cond); pthread_cond_destroy(&count_full_cond); pthread_exit(0); return 0; }
1
#include <pthread.h> int g_key = 0x333; pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER; void incSem() { int shmid; int *addr = 0; pthread_mutex_lock(&g_mutex); { shm_create(".", 0, &shmid); shm_map(shmid, (void **)&addr); *(int*)addr += 1; printf("count:%d\\n", *(int*)addr); shm_unmap(addr); sleep(1); } pthread_mutex_unlock(&g_mutex); } void sigHandler(int sig) { while(waitpid(-1, 0, WNOHANG)); } void* thread_routine(void *arg) { incSem(); return 0; } int main() { signal(SIGCHLD, sigHandler); int ret = 0; int shmid; ret = shm_create(".", sizeof(int), &shmid); if (ret != 0) { printf("main shm_create error\\n"); return ret; } pthread_t tids[20]; int i = 0; for (i = 0; i < 3; i++) { pthread_create(&tids[i], 0, thread_routine, 0); } for (i = 0; i < 3; i++) { pthread_join(tids[i], 0); } return 0; }
0
#include <pthread.h> extern int idx, sink; extern double dsink; extern void *psink; void bit_shift_main (void); void dynamic_buffer_overrun_main (void); void dynamic_buffer_underrun_main (void); void cmp_funcadr_main (void); void conflicting_cond_main (void); void data_lost_main (void); void data_overflow_main (void); void data_underflow_main (void); void dead_code_main (void); void dead_lock_main (void); void deletion_of_data_structure_sentinel_main (void); void double_free_main (void); void double_lock_main (void); void double_release_main (void); void endless_loop_main (void); void free_nondynamic_allocated_memory_main (void); void free_null_pointer_main (void); void func_pointer_main (void); void function_return_value_unchecked_main (void); void improper_termination_of_block_main (void); void insign_code_main (void); void invalid_extern_main (void); void invalid_memory_access_main (void); void littlemem_st_main (void); void livelock_main (void); void lock_never_unlock_main (void); void memory_allocation_failure_main(void); void memory_leak_main (void); void not_return_main (void); void null_pointer_main (void); void overrun_st_main (void); void ow_memcpy_main (void); void pow_related_errors_main (void); void ptr_subtraction_main (void); void race_condition_main (void); void redundant_cond_main (void); void return_local_main (void); void sign_conv_main (void); void sleep_lock_main (void); void st_cross_thread_access_main (void); void st_overflow_main (void); void st_underrun_main (void); void underrun_st_main (void); void uninit_memory_access_main (void); void uninit_pointer_main (void); void uninit_var_main (void); void unlock_without_lock_main (void); void unused_var_main (void); void wrong_arguments_func_pointer_main (void); void zero_division_main (void); pthread_mutex_t livelock_001_glb_A; pthread_mutex_t livelock_001_glb_B; int x,y; void *mythreadA(void *pram) { while(1) { pthread_mutex_lock(&livelock_001_glb_A); x=x+1; pthread_mutex_unlock(&livelock_001_glb_A); int status=pthread_mutex_trylock(&livelock_001_glb_B); pthread_mutex_unlock(&livelock_001_glb_B); if(status==0) { break; } } return 0; } void *mythreadB(void *pram) { while(1) { pthread_mutex_lock(&livelock_001_glb_B); y=y+1; pthread_mutex_unlock(&livelock_001_glb_B); int status=pthread_mutex_trylock(&livelock_001_glb_A); pthread_mutex_unlock(&livelock_001_glb_A); if(status==0) { break; } } return 0; } void livelock_001() { pthread_t pthreadA,pthreadB; pthread_mutex_init(&livelock_001_glb_A,0); pthread_mutex_init(&livelock_001_glb_B,0); pthread_create(&pthreadA,0,mythreadA,0); pthread_create(&pthreadB,0,(void *) &mythreadB,0); pthread_join(pthreadA,0); pthread_join(pthreadB,0); } extern volatile int vflag; void livelock_main () { if (vflag> 0) { livelock_001 (); } }
1
#include <pthread.h> struct colam { int ilec; int iesc; int cdat; int buf[10]; } cola; pthread_mutex_t mcola = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t no_llena = PTHREAD_COND_INITIALIZER; pthread_cond_t no_vacia = PTHREAD_COND_INITIALIZER; void pon_dato(int dato) { struct colam *pzona = &cola; pthread_mutex_lock(&mcola); while(pzona->cdat == 10) { pthread_cond_wait(&no_llena, &mcola); } pzona->buf[pzona->iesc] = dato; pzona->iesc++; if(pzona->iesc == 10) pzona->iesc = 0; pzona->cdat++; if(pzona->cdat != 10) { pthread_cond_signal(&no_llena); } else printf("!cola llena!\\n"); pthread_cond_signal(&no_vacia); pthread_mutex_unlock(&mcola); } void extrae_dato(int *pdato) { int dato; struct colam *pzona = &cola; pthread_mutex_lock(&mcola); while(pzona->cdat == 0) { pthread_cond_wait(&no_vacia, &mcola); } dato = pzona->buf[pzona->ilec]; pzona->ilec++; if(pzona->ilec == 10) pzona->ilec = 0; pzona->cdat--; pthread_cond_signal(&no_llena); if(pzona->cdat != 0) pthread_cond_signal(&no_vacia); else printf("!cola vacia!\\n"); pthread_mutex_unlock(&mcola); *pdato = dato; }
0
#include <pthread.h> int testFermat(unsigned long p); unsigned long getRand(unsigned long a,unsigned long b); unsigned long NWD(unsigned long a, unsigned long b); unsigned long mulMod(unsigned long a, unsigned long b, unsigned long n); unsigned long powMod(unsigned long a, unsigned long e, unsigned long n); void *countIt(void *arg); const unsigned long lp[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,107,109,113,127,131,137,139,149,151,157,163, 167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269, 271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383, 389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499, 503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619, 631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751, 757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881, 883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997,1009 }; pthread_mutex_t mojmuteks=PTHREAD_MUTEX_INITIALIZER; int id = 0; int prims[20]; int main(int argc, char *argv[]) { int primes = (int) strtol(argv[1], (char **)0, 10); int bits = (int) strtol(argv[2], (char **)0, 10); srand((unsigned) time(0)); int min = pow(2, (bits-1)); int max = pow(2, bits)-1; pthread_t watki[primes]; int i; for(i=0; i<primes; i++) { if ( pthread_create( &watki[i], 0, countIt,0) ) printf("błąd przy tworzeniu wątku\\n"); abort(); if ( pthread_join ( watki[i], 0 ) ) { printf("błąd w kończeniu wątku\\n"); exit(); } } printf("Wygenerowana liczba pierwsza - fermat %d\\n", los); return 0; } void *countIt(void *arg) { int los; int myid; while(1) { pthread_mutex_lock(&mojmuteks); myid = id; id++; pthread_mutex_unlock(&mojmuteks); printf("Watek nr: %d\\n", myid); los = min + rand() / (32767 / (max - min + 1) + 1); if(los % 2 == 0) los += 1; if(1 == testFermat(los)) break; sleep(1); } prims[myid]= los; return 0; } int testFermat(unsigned long p) { unsigned long a; int i, t; t = 1; for(i = 0; i < 169; i++) if((p != lp[i]) && (p % lp[i] == 0)) { return 0; } if(t && (p > 1009)) { for(i = 1; i <= 10; i++) { a = getRand(2,p-1); if((NWD(p,a) != 1) || (powMod(a,p-1,p) != 1)) { return 0; } } } return t; } unsigned long getRand(unsigned long a,unsigned long b) { unsigned long w; int i; for(i = 1; i <= 8; i++) { w <<= 8; w &= rand() % 256; } return a + (w % (b - a)); } unsigned long NWD(unsigned long a, unsigned long b) { unsigned long t; while(b) { t = b; b = a % b; a = t; } return a; } unsigned long mulMod(unsigned long a, unsigned long b, unsigned long n) { unsigned long m,w; w = 0; for(m = 1; m; m <<= 1) { if(b & m) w = (w + a) % n; a = (a << 1) % n; } return w; } unsigned long powMod(unsigned long a, unsigned long e, unsigned long n) { unsigned long m,p,w; p = a; w = 1; for(m = 1; m; m <<= 1) { if(e & m) w = mulMod(w,p,n); p = mulMod(p,p,n); } return w; }
1
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp; for (;;) { pthread_mutex_lock(&lock); while (head == 0) pthread_cond_wait(&has_product, &lock); mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("Consume %d\\n", mp->num); free(mp); sleep(rand() % 5); } } void *producer(void *p) { struct msg *mp; for (;;) { mp = malloc(sizeof(struct msg)); pthread_mutex_lock(&lock); mp->next = head; mp->num = rand() % 1000; head = mp; printf("Produce %d\\n", mp->num); pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(int argc, char *argv[]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t forks[5]; pthread_t phils[5]; void *philosopher (void *id); int food_on_table (); void get_fork (int, int, char *); void down_forks (int, int); pthread_mutex_t foodlock; int sleep_seconds = 0; int main (int argn, char **argv) { int i; if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&foodlock, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&forks[i], 0); for (i = 0; i < 5; i++) pthread_create (&phils[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (phils[i], 0); return 0; } void * philosopher (void *num) { int id; int left_fork, right_fork, f; id = (int)num; printf ("Philosopher %d sitting down to dinner.\\n", id); right_fork = id; left_fork = id + 1; if (left_fork == 5) { left_fork = right_fork; right_fork=0; } while (f = food_on_table ()) { printf ("Philosopher %d: get dish %d.\\n", id, f); get_fork (id, right_fork, "right"); get_fork (id, left_fork, "left"); printf ("Philosopher %d: eating.\\n", id); usleep (30000 * (50 - f + 1)); down_forks (left_fork, right_fork); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table () { static int food = 50; int myfood; pthread_mutex_lock (&foodlock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&foodlock); return myfood; } void get_fork (int phil, int fork, char *hand) { pthread_mutex_lock (&forks[fork]); printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork); } void down_forks (int f1, int f2) { pthread_mutex_unlock (&forks[f1]); pthread_mutex_unlock (&forks[f2]); }
1
#include <pthread.h> struct s { int datum; struct s *next; }; struct cache { struct s *slots[10]; pthread_mutex_t mutex[10]; } c; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = 0; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } void *t_fun(void *arg) { int i; pthread_mutex_lock(&c.mutex[i]); list_add(new(3), c.slots[i]); pthread_mutex_unlock(&c.mutex[i]); return 0; } int main () { int j; struct s *p; pthread_t t1; c.slots[j] = new(1); list_add(new(2), c.slots[j]); pthread_create(&t1, 0, t_fun, 0); pthread_mutex_lock(&c.mutex[j]); p = c.slots[j]->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&c.mutex[j]); return 0; }
0
#include <pthread.h> pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; int count = 1; int sended =0; int lastprime=2; int TCOUNT; int COUNT_LIMIT; int catchprime; void *watch_count(void *t); void *int_count(void *t); int test_prime(int); int main(int argc,char* argv[]){ TCOUNT = atoi(argv[1]); COUNT_LIMIT = atoi(argv[2]); pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); int i; int t1 = 1; int t2 = 2; int t3 = 3; pthread_t threads[3]; pthread_create(&threads[0],0,watch_count,(void *)t1); usleep(100); pthread_create(&threads[1],0,int_count,(void *)t2); usleep(100); pthread_create(&threads[2],0,int_count,(void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("Main() : Waited and joined with %d threads. Final value of count = %d Down.\\n", 3, count ) ; pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); } void *watch_count(void *t){ int my_id = (int)t; printf("Starting Watch_count(): thread %d, p = %d Going to wait...\\n",my_id,count ) ; pthread_mutex_lock( &count_mutex ) ; if( count < COUNT_LIMIT ){ pthread_cond_wait( &count_threshold_cv, &count_mutex ) ; printf("watch_count(): thread %d Conditional signal received. p = %d\\n",my_id ,catchprime); printf("watch_count(): thread %d Updating the value of p...\\n", my_id ) ; printf("the lastest prime found before p = %d\\n", lastprime ) ; printf("watch_count(): thread %d count p now = %d\\n", my_id, catchprime = catchprime + lastprime ) ; printf("watch_count():thread 1 Unlocking mutex\\n"); count = catchprime; } pthread_mutex_unlock( &count_mutex ) ; usleep(10000); pthread_exit(0); } void *int_count(void *t){ int my_id = (int)t; int i; int c; while(count < TCOUNT){ pthread_mutex_lock(&count_mutex); if(test_prime(count))lastprime = count; count++; printf("prime_count(): thread %d, p = %d \\n", t,count); if(test_prime(count)){ printf("prime_count(): thread %d, find prime = %d \\n", t,count); if(sended==0 && count == COUNT_LIMIT){ printf("prime_count(): thread %d, prime = %d prime reached.\\n", my_id, count) ; catchprime = count; pthread_cond_signal( &count_threshold_cv ) ; sended ==1; printf("Just send signal.\\n") ; } } if(count >=TCOUNT){ pthread_mutex_unlock(&count_mutex); usleep(10000); break; } pthread_mutex_unlock(&count_mutex); usleep(10000); } pthread_exit(0); } int test_prime(int c){ int i; int k =1; for(i=2;i<c;i++){ if(c%i == 0){ k =0; break; } } return k; }
1
#include <pthread.h> struct luargs { int i, j, partition; }; static void print(mtype *arr); void *lu(void*); pthread_t threads[4][4]; pthread_cond_t conds[4][4]; pthread_mutex_t mutexes[4][4]; int done[4][4]; struct luargs args[4][4]; mtype A[4*4]; mtype x[4], P[4]; int n; static void swap_rows(int x, int y) { int i; if (x == y) return; for (i = 0; i < n; ++i) { do { mtype temp = ((A[x * 4 + i])); ((A[x * 4 + i])) = ((A[y * 4 + i])); ((A[y * 4 + i])) = temp;} while(0); } } void printd(int a,int b) { fprintf(stderr, "done(%d,%d): [%d, %d, %d, %d]\\n", a,b,done[0][0], done[0][1], done[1][0], done[1][1]); } void waitthread(int a, int b,int i, int j) { if (i < 0 || j < 0) return; pthread_mutex_lock(&mutexes[i][j]); while (!done[i][j]) { pthread_cond_wait(&conds[i][j], &mutexes[i][j]); } pthread_mutex_unlock(&mutexes[i][j]); } void *lu(void *_arg) { struct luargs *args = _arg; int partition = args->partition; int probsize = n / partition; int row0 = args->i * probsize; int col0 = args->j * probsize; int row1 = (args->i + 1) * probsize; int col1 = (args->j + 1) * probsize; int k; for (k = row0; k < row1; ++k) { P[k] = k; } waitthread(args->i,args->j,args->i - 1, args->j); waitthread(args->i,args->j,args->i, args->j - 1); for (k = col0; k < col1; ++k) { int i; int maxrow = k; for (i = k + 1; i < row1; ++i) { if ((A[maxrow * 4 + k]) < fabs((A[i * 4 + k]))) maxrow = i; } if (!(A[maxrow * 4 + k])) { printf("[%d, %d] [%d, %d] \\n", row0,col0, row1, col1); printf("searched %d %d\\n", k+1,row1); printf("Singular matrix %d %d.\\n",args->i,args->j); exit(1); } swap_rows(k, maxrow); do { mtype temp = (P[k]); (P[k]) = (P[maxrow]); (P[maxrow]) = temp;} while(0); int j; for (i = k + 1; i < row1; ++i) { float o=(A[i * 4 + k]); (A[i * 4 + k]) = (A[i * 4 + k]) / (A[k * 4 + k]); if (o!=(A[i * 4 + k])) { ; } for (j = k + 1; j < col1; ++j) { o = (A[i * 4 + j]); (A[i * 4 + j]) = (A[i * 4 + j]) - (A[i * 4 + k]) * (A[k * 4 + j]); if(o!=(A[i * 4 + j])) { ; } } } } pthread_mutex_lock(&mutexes[args->i][args->j]); done[args->i][args->j] = 1; pthread_mutex_unlock(&mutexes[args->i][args->j]); pthread_cond_broadcast(&conds[args->i][args->j]); return 0; } void plu(int partition) { int i; int probsize = n / partition; for (i = 0; i < partition; ++i) { int j; for (j = 0; j < partition; ++j) { args[i][j].i = i; args[i][j].j = j; args[i][j].partition = partition; done[i][j] = 0; pthread_mutex_init(&mutexes[i][j], 0); pthread_cond_init(&conds[i][j], 0); pthread_create(&threads[i][j], 0, lu, &args[i][j]); } } for (i = 0; i < partition; ++i) { int j; for (j = 0; j < partition; ++j) { pthread_join(threads[i][j], 0); } } for (i = 0; i < partition; ++i) { int j; for (j = 0; j < partition; ++j) { pthread_mutex_destroy(&mutexes[i][j]); pthread_cond_destroy(&conds[i][j]); } } printf("finished %d\\n", partition); } void genmatrix(int seed) { bseed(seed); int i; for (i = 0; i < n; ++i) { int j; for (j = 0; j < n; ++j) { (A[i * 4 + j]) = brand() % 100 + 100; } } } int main(void) { n = 4; int i; for (i = 1; i <= n / 2; i *= 2) { genmatrix(1); plu(i); print(A); } return 0; } static void print(mtype *arr) { int i; for (i = 0; i < n; ++i) { int j; for (j = 0; j < n; ++j) { printf("%8.3f ", (arr[i * 4 + j])); } printf("\\n"); } }
0
#include <pthread.h> int client_fds[10]; int client_idx; int output_fd; int barrier; pthread_mutex_t client_fds_lock; pthread_mutex_t file_lock; void* racey_worker(void* data) { int fd; int n = 0; char buf[256]; printf("Thread into position\\n"); while (barrier == 0) {} for (;;) { for (;;) { syscall(318); pthread_mutex_lock(&client_fds_lock); syscall(319); if (client_fds[client_idx] > 0) { printf("Worker got a connection %d\\n", client_idx); fd = client_fds[client_idx]; syscall(320); client_fds[client_idx] = -1; client_idx --; pthread_mutex_unlock(&client_fds_lock); break; } pthread_mutex_unlock(&client_fds_lock); syscall(320); } do { syscall(318); n = read(fd, buf, sizeof(buf)); syscall(319); syscall(318); pthread_mutex_lock(&file_lock); syscall(319); write(output_fd, buf, n); pthread_mutex_unlock(&file_lock); } while (n > 0); printf("I'm done with this\\n"); close(fd); } } int main(int argc, char **argv) { struct sockaddr_in serv_addr; struct sockaddr_in client_addr; unsigned short server_port; unsigned int client_len; int server_fd; int client_fd; int i; pthread_t threads[10]; pthread_attr_t attr; if (argc != 2) { fprintf(stderr, "Usage: %s <Server Port>\\n", argv[0]); exit(1); } server_port = atoi(argv[1]); pthread_mutex_init(&client_fds_lock, 0); pthread_mutex_init(&file_lock, 0); output_fd = open("./output.txt", O_WRONLY|O_CREAT, 0644); if (output_fd == -1) { printf("Couldn't create output file, abort\\n"); return 1; } if ((server_fd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { printf("Couldn't create socket, abort\\n"); return 1; } memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(server_port); if (bind(server_fd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { printf("Couldn't bind socket, abort\\n"); return 1; } pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); client_idx = -1; barrier = 0; for (i = 0; i < 10; i++) { client_fds[i] = -1; if (pthread_create(&threads[i], &attr, racey_worker, 0) < 0) { printf("HOLY SHIT\\n"); return 1; } } barrier = 1; if (listen(server_fd, 10) < 0) { printf("Couldn't listen to socket, abort\\n"); return 1; } for (;;) { client_len = sizeof(client_addr); syscall(318); if ((client_fd = accept(server_fd, (struct sockaddr *) &client_addr, &client_len)) < 0) { printf("Couldn't do shit, abort\\n"); syscall(319); return 1; } syscall(319); syscall(320); printf("Incoming connection\\n"); while (1) { syscall(318); pthread_mutex_lock(&client_fds_lock); syscall(319); if (client_idx < 10) { syscall(320); client_idx ++; client_fds[client_idx] = client_fd; pthread_mutex_unlock(&client_fds_lock); break; } pthread_mutex_unlock(&client_fds_lock); syscall(320); } printf("Connection put into position %d\\n", client_idx); } }
1
#include <pthread.h> pthread_mutex_t fork1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork2 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork3 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork4 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fork5 = PTHREAD_MUTEX_INITIALIZER; void* philisopher_1(void* arg){ while(1){ pthread_mutex_lock(&fork1); pthread_mutex_lock(&fork2); printf("Philospher 1 is eating\\n"); usleep(10); pthread_mutex_unlock(&fork2); pthread_mutex_unlock(&fork1); usleep(10); } } void* philisopher_2(void* arg){ while(1){ pthread_mutex_lock(&fork2); pthread_mutex_lock(&fork3); printf("Philospher 2 is eating\\n"); usleep(10); pthread_mutex_unlock(&fork3); pthread_mutex_unlock(&fork2); usleep(10); } } void* philisopher_3(void* arg){ while(1){ pthread_mutex_lock(&fork3); pthread_mutex_lock(&fork4); printf("Philospher 3 is eating\\n"); usleep(10); pthread_mutex_unlock(&fork4); pthread_mutex_unlock(&fork3); usleep(10); } } void* philisopher_4(void* arg){ while(1){ pthread_mutex_lock(&fork4); pthread_mutex_lock(&fork5); printf("Philospher 4 is eating\\n"); usleep(10); pthread_mutex_unlock(&fork5); pthread_mutex_unlock(&fork4); usleep(10); } } void* philisopher_5(void* arg){ while(1){ pthread_mutex_lock(&fork5); pthread_mutex_lock(&fork1); printf("Philospher 5 is eating\\n"); usleep(10); pthread_mutex_unlock(&fork1); pthread_mutex_unlock(&fork5); usleep(10); } } int main(void){ pthread_t philisopher1; pthread_t philisopher2; pthread_t philisopher3; pthread_t philisopher4; pthread_t philisopher5; pthread_create(&philisopher1, 0, &philisopher_1, 0); pthread_create(&philisopher2, 0, &philisopher_2, 0); pthread_create(&philisopher3, 0, &philisopher_3, 0); pthread_create(&philisopher4, 0, &philisopher_4, 0); pthread_create(&philisopher5, 0, &philisopher_5, 0); pthread_join(philisopher1, 0); pthread_join(philisopher2, 0); pthread_join(philisopher3, 0); pthread_join(philisopher4, 0); pthread_join(philisopher5, 0); }
0
#include <pthread.h> struct node { char user[5]; char process; int arrival; int duration; struct node *next; }*head; struct display { char user[5]; int timeLastCalculated; struct display *next; }*frontDisplay, *tempDisplay, *rearDisplay; pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; void initialise(); void insert(char[5], char, int, int); void add(char[5], char, int, int); int count(); void addafter(char[5], char, int, int, int); void* jobDisplay(); void addToSummary(char[], int); void summaryDisplay(); int main( int argc, char *argv[] ) { int n; if( argc == 2 ) { n = atoi(argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\\n"); return 0; } else { printf("One argument expected.\\n"); return 0; } char user[5], process; int arrivalInput, durationInput; initialise(); printf("\\n\\tUser\\tProcess\\tArrival\\tDuration\\n"); int i = 1; while ( i < 5 ) { printf("\\t"); if ( scanf("%s\\t%c\\t%d\\t%d", user, &process, &arrivalInput, &durationInput) < 4 ) { printf("\\nThe arguments supplied are incorrect. Try again.\\n"); return 0; } insert(user, process, arrivalInput, durationInput); i++; } printf("\\nThis would result in:\\n\\tTime\\tJob\\n"); pthread_t threadID[n]; i = 0; for ( i = 0; i < n; i++ ) { pthread_create(&(threadID[i]),0,&jobDisplay,0); } pthread_join(threadID[0],0); pthread_mutex_destroy(&m1); pthread_mutex_destroy(&m2); summaryDisplay(); return 0; } void initialise() { head=0; rearDisplay=0; tempDisplay=0; frontDisplay=0; } void insert(char user[5], char process, int arrival, int duration) { int c = 0; struct node *temp; temp = head; if ( temp == 0 ) { add(user, process, arrival, duration); } else { while ( temp != 0 ) { if ( ( temp->arrival + temp->duration ) < ( arrival + duration ) ) { c++; } temp = temp->next; } if ( c == 0 ) { add(user, process, arrival, duration); } else if ( c < count() ) { addafter(user, process, arrival, duration, ++c); } else { struct node *right; temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; right = (struct node *)head; while ( right->next != 0 ) { right = right->next; } right->next = temp; right = temp; right->next = 0; } } } void add(char user[5], char process, int arrival, int duration) { struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; if ( head == 0 ) { head = temp; head->next = 0; } else { temp->next = head; head = temp; } } int count() { struct node *n; int c = 0; n = head; while ( n != 0 ) { n=n->next; c++; } return c; } void addafter(char user[5], char process, int arrival, int duration, int loc) { int i; struct node *temp,*left,*right; right = head; for(i = 1; i < loc; i++) { left = right; right = right->next; } temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; left->next = temp; left = temp; left->next = right; return; } void* jobDisplay() { char tempUser[5]; char myJob = ' '; int myTime = 0; int myCounter = 0; int tempTime = 0; pthread_mutex_lock(&m1); struct node* placeholder = head; pthread_mutex_unlock(&m1); if ( placeholder == 0 ) { return; } while ( placeholder != 0 ) { if ( myTime < placeholder->arrival ) { sleep( placeholder->arrival - myTime ); myTime = placeholder->arrival; } pthread_mutex_lock(&m1); if ( placeholder->next != 0 ) { if ( placeholder->next->duration < placeholder->duration ) { strcpy(tempUser, placeholder->user); myJob = placeholder->process; tempTime = placeholder->duration - 1; printf("\\t%d\\t%c\\n", myTime, myJob); myTime++; sleep(1); placeholder = placeholder->next; } } pthread_mutex_unlock(&m1); myCounter = 1; while ( myCounter <= placeholder->duration ) { printf("\\t%d\\t%c\\n", myTime, placeholder->process); myTime++; myCounter++; sleep(1); } addToSummary(placeholder->user, myTime); if ( myJob != ' ' ) { myCounter = 1; while ( myCounter <= tempTime ) { printf("\\t%d\\t%c\\n", myTime, myJob); myTime++; myCounter++; sleep(1); } addToSummary(tempUser, myTime); myJob = ' '; } pthread_mutex_lock(&m1); placeholder = placeholder->next; pthread_mutex_unlock(&m1); } printf("\\t%d\\tIDLE\\n", myTime); return 0; } void addToSummary(char name[], int timeLeft) { pthread_mutex_lock(&m2); if ( rearDisplay == 0 ) { rearDisplay = (struct display *)malloc(1*sizeof(struct display)); rearDisplay->next = 0; strcpy(rearDisplay->user, name); rearDisplay->timeLastCalculated = timeLeft; frontDisplay = rearDisplay; } else { tempDisplay = frontDisplay; while ( tempDisplay != 0 ) { if ( strcmp(tempDisplay->user, name) == 0 ) { tempDisplay->timeLastCalculated = timeLeft; break; } tempDisplay = tempDisplay->next; } if ( tempDisplay == 0 ) { tempDisplay = (struct display *)malloc(1*sizeof(struct display)); rearDisplay->next = tempDisplay; strcpy(tempDisplay->user, name); tempDisplay->timeLastCalculated = timeLeft; tempDisplay->next = 0; rearDisplay = tempDisplay; } } pthread_mutex_unlock(&m2); } void summaryDisplay() { printf("\\n\\tSummary\\n"); while ( frontDisplay != 0 ) { printf("\\t%s\\t%d\\n", frontDisplay->user, frontDisplay->timeLastCalculated); tempDisplay = frontDisplay->next; free(frontDisplay); frontDisplay = tempDisplay; } printf("\\n"); }
1
#include <pthread.h> static pthread_mutex_t mutex; static pthread_once_t init = PTHREAD_ONCE_INIT; extern char** environ; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); } int getenv_r(const char* name, char* buffer, int size) { pthread_once(&init, thread_init); int len = strlen(name); pthread_mutex_lock(&mutex); int i; for (i = 0; environ[i] != 0; ++i) { if (!strncmp(name, environ[i], len) && (environ[i][len] == '=')) { int value_len = strlen(&environ[i][len + 1]); if (value_len >= size) { pthread_mutex_unlock(&mutex); return ENOSPC; } strcpy(buffer, &environ[i][len + 1]); pthread_mutex_unlock(&mutex); return 0; } } pthread_mutex_unlock(&mutex); return ENOENT; } int main(int argc, char* argv[]) { char env[1024]; getenv_r("HOME", env, 1024); printf("HOME:%s\\n", env); return 0; }
0
#include <pthread.h> pthread_t th; size_t id, result; } TestThread; char *locks, *data; pthread_mutex_t *mutexes; void* worker_bitlock(void *ptr) { TestThread *wrkr = (TestThread*)ptr; size_t i; for(i = 0; i < 10000; i++) { bitlock_yield_acquire(locks, i); wrkr->result += i + *(volatile char *)&data[i]; data[i] = wrkr->id; usleep(5); bitlock_release(locks, i); usleep(5); } return 0; } void* worker_bitlock_spin(void *ptr) { TestThread *wrkr = (TestThread*)ptr; size_t i; for(i = 0; i < 10000; i++) { bitlock_acquire(locks, i); wrkr->result += i + *(volatile char *)&data[i]; data[i] = wrkr->id; usleep(5); bitlock_release(locks, i); usleep(5); } return 0; } void* worker_mutex(void *ptr) { TestThread *wrkr = (TestThread*)ptr; size_t i; for(i = 0; i < 10000; i++) { pthread_mutex_lock(&mutexes[0]); wrkr->result += i + *(volatile char *)&data[i]; data[i] = wrkr->id; usleep(5); pthread_mutex_unlock(&mutexes[0]); usleep(5); } return 0; } void* worker_mutexes(void *ptr) { TestThread *wrkr = (TestThread*)ptr; size_t i; for(i = 0; i < 10000; i++) { pthread_mutex_lock(&mutexes[i]); wrkr->result += i + *(volatile char *)&data[i]; data[i] = wrkr->id; usleep(5); pthread_mutex_unlock(&mutexes[i]); usleep(5); } return 0; } int main(int argc, char **argv) { char *method = "Bitlocks"; void* (*func)(void*) = worker_bitlock; if(argc == 2 && strcmp(argv[1],"bits") == 0) {} else if(argc == 2 && strcmp(argv[1],"mutex") == 0) { method = "Mutex"; func = worker_mutex; } else if(argc == 2 && strcmp(argv[1],"mutexes") == 0) { method = "Mutexes"; func = worker_mutexes; } else if(argc == 2 && strcmp(argv[1],"spin") == 0) { method = "Bitlocks-Spin"; func = worker_bitlock_spin; } else if(argc != 1) { fprintf(stderr, "usage: ./bitlock_test <bits|mutex|spin>\\n"); exit(-1); } printf("\\nTesting %s\\n\\n", method); int rc; size_t i, num_threads = 30; TestThread workers[num_threads]; locks = (char*)calloc(1, (10000 +7)/8); data = (char*)calloc(1, 10000); mutexes = (pthread_mutex_t*)calloc(10000, sizeof(pthread_mutex_t)); for(i = 0; i < 10000; i++) pthread_mutex_init(&mutexes[i], 0); for(i = 0; i < num_threads; i++) { workers[i] = (TestThread){.id = i+1, .result = 0}; rc = pthread_create(&workers[i].th, 0, func, &workers[i]); if(rc) { fprintf(stderr, "pthread error: %s\\n", strerror(rc)); exit(-1); } } for(i = 0; i < num_threads; i++) { rc = pthread_join(workers[i].th, 0); if(rc) { fprintf(stderr, "pthread error: %s\\n", strerror(rc)); exit(-1); } } for(i = 0; i < 10000; i++) pthread_mutex_destroy(&mutexes[i]); size_t sum = 0, expsum = 0; for(i = 0; i < 10000; i++) sum += data[i]; for(i = 0; i < num_threads; i++) sum += workers[i].result; expsum = ((10000 -1)*(((10000 -1)+1)/2)+(((10000 -1)&1) ? 0 : (10000 -1)/2))*num_threads + ((num_threads)*(((num_threads)+1)/2)+(((num_threads)&1) ? 0 : (num_threads)/2))*10000; bool pass = (sum == expsum); for(i = 0; i < sizeof(locks) && locks[i] == 0; i++) {} if(i < sizeof(locks)) { printf("locks not zeroed!\\n"); pass = 0; } printf("sum: %zu exp: %zu\\n", sum, expsum); printf("%s.\\n\\n", pass ? "Pass" : "Fail"); free(mutexes); free(data); free(locks); return pass ? 0 : 1; }
1
#include <pthread.h> pthread_cond_t condizione = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int m,n,x; int contatore; int **matrice; int *array; int mThread; void stampa ( ){ printf("\\n"); for (int i = 0; i < m; i++) { for(int j=0;j<n;j++){ printf("%d \\t",matrice[i][j]); } printf("\\n"); } } void *funzione (void *param){ int indice= *(int*)param; for(int j=0;j<n;j++){ pthread_mutex_lock(&mutex); if (x==matrice[indice][j]) { contatore++; array[indice]=matrice[indice][j]; } mThread--; pthread_mutex_unlock(&mutex); } if (mThread==0) { pthread_mutex_lock(&mutex); pthread_cond_signal(&condizione); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *funzione2 (void *param){ pthread_mutex_lock(&mutex); while(mThread>0){ pthread_cond_wait(&condizione,&mutex); } pthread_mutex_unlock(&mutex); for (int i = 0; i < n; ++i) { if (array[i]!=0) { printf("%d\\n", array[i]); } } pthread_exit(0); } int main(int argc, char const *argv[]) { m = atoi(argv[1]); n = atoi(argv[2]); x = atoi(argv[3]); mThread=m; pthread_t thread[m]; array=(int*)malloc(sizeof(int)*n); for (int i = 0; i < n; i++) { array[i]=0; } matrice=(int**)malloc(sizeof(int*)*m); for (int i = 0; i < m; i++) { matrice[i]=(int*)malloc(sizeof(int)*n); for (int j = 0; j < n; j++) { matrice[i][j]=rand()%10; } } for (int i = 0; i < m; i++) { int *indice =malloc(sizeof(int)); *indice=i; pthread_create(&thread[i],0,funzione,indice); } pthread_create(&thread[m],0,funzione2,0); for (int i = 0; i <=m ; i++) { pthread_join(thread[i],0); } stampa ( ); return 0; }
0
#include <pthread.h> int api_running = 1; int api_wait = 0; int last_ind = 511; pthread_mutex_t rp_analog_sig_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t thread0; float *ana_sig_array = 0; float *ptime = 0; float *panalog_signals = 0; unsigned int sleep_delta_T; unsigned int num_of_meas; FILE *fd = 0; int rp_init_API(void) { if(rp_Init() != RP_OK) { fprintf(stderr, "Rp api init failed!n"); } return 0; } int rp_start_API(void) { pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); pthread_mutex_lock(&rp_analog_sig_mutex); ptime = (float*)calloc(SIG_LENGTH, sizeof(*ptime)); char *mode = "w"; char *file_path = 0; file_path = (char*)malloc(sizeof(char)*512); if( file_path == 0 ) return 1; file_path[0] = '\\0'; strcpy(file_path, DEBUG_PATH); fd = fopen(file_path, mode); int i; for( i = 0; i < SIG_LENGTH; ++i) { ptime[i] = i; } panalog_signals = (float*)calloc(NUM_ANA_SIG * NUM_ANA_SIG_LEN, sizeof(*panalog_signals)); ana_sig_array = panalog_signals; fprintf(fd, "ptime addr:%p\\tpanalog_signals addr:%p\\n", ptime, panalog_signals); api_running = 1; if( pthread_create(&thread0, &attr, read_analog_sig, 0) != 0 ) { fprintf(stderr, "Error creating thread\\n"); return -3; } return 0; } int rp_stop_API(void) { api_running = 0; rp_Release(); free(ptime); free(panalog_signals); fclose(fd); return 0; } int rp_copy_analog_signals(float ***signals, int *sig_idx) { float **s = *signals; if( last_ind < 511 ) { *sig_idx = 1; return -1; } else { *sig_idx = SIG_LENGTH - 1; last_ind = 0; } memcpy(&s[0][0], ptime, sizeof(float) * SIG_LENGTH); memcpy(&s[1][0], ana_sig_array, sizeof(float) * SIG_LENGTH); memcpy(&s[2][0], &ana_sig_array[SIG_LENGTH], sizeof(float) * SIG_LENGTH); return 0; } void *read_analog_sig(void *ptr) { unsigned int i; int send_ms = 0; float *panalog_sig0 = panalog_signals; float *panalog_sig1 = &panalog_signals[NUM_ANA_SIG_LEN]; float *panalog_sig2 = &panalog_signals[(NUM_ANA_SIG_LEN*2)]; float *panalog_sig3 = &panalog_signals[(NUM_ANA_SIG_LEN*3)]; float *pcurr_sig0 = 0; float *pcurr_sig1 = 0; float *pcurr_sig2 = 0; float *pcurr_sig3 = 0; while(api_running) { while( *pdelta_T == -1 && *pnum_of_meas == -1 ) usleep(2000); sleep_delta_T = ((unsigned int)((*pdelta_T) * 1000)); num_of_meas = (unsigned int)(*pnum_of_meas); i = 0; while(num_of_meas > 0) { if( *pmeas_control == 3 ) { *pdelta_T = -1; *pnum_of_meas = -1; break; } while( *pmeas_control == 1 ) usleep(2000); pcurr_sig0 = panalog_sig0; pcurr_sig1 = panalog_sig1; pcurr_sig2 = panalog_sig2; pcurr_sig3 = panalog_sig3; for( i = 0; i < NUM_ANA_SIG_LEN; ++i ) { if( num_of_meas == 0) { for( ; i < NUM_ANA_SIG_LEN; ++i) { *pcurr_sig0 = -100; *pcurr_sig1 = -100; *pcurr_sig2 = -100; *pcurr_sig3 = -100; ++pcurr_sig0; ++pcurr_sig1; ++pcurr_sig2; ++pcurr_sig3; } break; } rp_ApinGetValue(RP_AIN0, pcurr_sig0); rp_ApinGetValue(RP_AIN1, pcurr_sig1); rp_ApinGetValue(RP_AIN2, pcurr_sig2); rp_ApinGetValue(RP_AIN3, pcurr_sig3); ++pcurr_sig0; ++pcurr_sig1; ++pcurr_sig2; ++pcurr_sig3; ++last_ind; --num_of_meas; usleep(sleep_delta_T); send_ms += *pdelta_T; if( send_ms >= SEND_MS ) { ++i; for( ; i < NUM_ANA_SIG_LEN; ++i) { *pcurr_sig0 = -100; *pcurr_sig1 = -100; *pcurr_sig2 = -100; *pcurr_sig3 = -100; ++pcurr_sig0; ++pcurr_sig1; ++pcurr_sig2; ++pcurr_sig3; } last_ind = 511; send_ms = 0; break; } } send_ms = 0; if( num_of_meas <= 0) { *pdelta_T = -1; *pnum_of_meas = -1; last_ind = 511; } ++(*pchange); if( *pchange == 100e3 ) *pchange = 1; while( last_ind == 511 ) usleep(2000); } } return 0; } void *read_analog_sig2(void *ptr) { int i; int sleep_delta_T; int num_of_meas; while(api_running) { pthread_mutex_lock(&rp_analog_sig_mutex); api_wait = 0; sleep_delta_T = (int)(*pdelta_T); num_of_meas = (int)(*pnum_of_meas); for( i = 0;i < num_of_meas; ++i) { ++(*pchange); sleep(sleep_delta_T); } *ptrig_mode = 2; api_wait = 1; pthread_mutex_unlock(&rp_analog_sig_mutex); } return 0; }
1
#include <pthread.h> extern int run; int auth_thread_init(struct mosquitto_db *db){ int res = 0; pthread_mutex_init(&db->auth_list_mutex, 0); res = pthread_create( &db->auth_thread_id, 0,_mosquitto_auth_thread_main, db) ; if( res != 0 ){ _mosquitto_log_printf(0, MOSQ_LOG_ERR, "pthread_create() call failed.error[%d] info is %s.", res, strerror(res)) ; return -1 ; } return 0 ; } int auth_thread_destroy(struct mosquitto_db *db){ pthread_join( db->auth_thread_id, 0) ; pthread_mutex_destroy(&db->auth_list_mutex); return 0 ; } void *_mosquitto_auth_thread_main(void *obj){ struct mosquitto_db *db = (struct mosquitto_db *)obj ; struct mosquitto * context = 0; db= db ; while(run){ struct _mosquitto_auth_list * waitauthlist = 0 ; if(db->waiting_auth_list != 0){ pthread_mutex_lock(&db->auth_list_mutex) ; waitauthlist = db->waiting_auth_list ; db->waiting_auth_list = 0 ; pthread_mutex_unlock(&db->auth_list_mutex) ; } struct _mosquitto_auth_list *head = waitauthlist ; while(waitauthlist){ context = waitauthlist->context ; assert( context->sock != -1 ) ; if(strcmp(context->username, context->password) == 0){ context->auth_result = CONNACK_ACCEPTED ; } else { context->auth_result = CONNACK_ACCEPTED ; } _mosquitto_log_printf(0, MOSQ_LOG_INFO, "hello thread, accept client[%s], name[%s], pwd[%s]\\n", context->id, context->username, context->password) ; waitauthlist = waitauthlist->next ; } if( head ){ pthread_mutex_lock(&db->auth_list_mutex) ; if( db->finished_auth_list == 0){ db->finished_auth_list = head ; } else { waitauthlist = db->finished_auth_list ; while(waitauthlist->next != 0) { waitauthlist = waitauthlist->next ; } waitauthlist->next = head ; } pthread_mutex_unlock(&db->auth_list_mutex) ; } usleep(1); } return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(400)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(400)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(400); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(400); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> static pthread_mutex_t muxLog; FILE * fp; void inizializzazioneLogFile(const char * filename){ time_t t; char ts[64]; pthread_mutex_init(&muxLog, 0); fp = fopen(filename,"w+"); t = time(0); ctime_r(&t,ts); ts[strlen(ts)-1] = '\\0'; fprintf(fp, "****************************************************\\n"); fprintf(fp, "**Chat Server started @%s **\\n",ts); fprintf(fp, "****************************************************\\n"); } void loginLog(const char * filename, char *username){ time_t t; char ts[64]; pthread_mutex_lock(&muxLog); t = time(0); ctime_r(&t,ts); ts[strlen(ts)-1] = '\\0'; fprintf(fp, "%s:login:%s\\n", ts, username); pthread_mutex_unlock(&muxLog); } void logoutLog(const char * filename,char *username) { time_t t; char ts[64]; pthread_mutex_lock(&muxLog); t = time(0); ctime_r(&t,ts); ts[strlen(ts)-1] = '\\0'; fprintf(fp, "%s:logout:%s\\n", ts, username); pthread_mutex_unlock(&muxLog); } void singleLog(const char * filename,char *mittente, char *destinatario, char *messaggio) { time_t t; char ts[64]; pthread_mutex_lock(&muxLog); t = time(0); ctime_r(&t,ts); ts[strlen(ts)-1] = '\\0'; fprintf(fp, "%s:%s:%s:%s\\n", ts, mittente, destinatario, messaggio); pthread_mutex_unlock(&muxLog); } void logClose(){ fclose(fp); }
0
#include <pthread.h> int Inicializar() { int i, err_retorno; pthread_attr_t attr; pthread_mutex_init(&clientes_a_chegar_mutex, 0); clientes_a_chegar = N_CLIENTES; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); for(i=0; i<N_FILAS; ++i) { sem_init(&fila[i], 0, 0); } for(i=0; i<N_FILAS; i++) { err_retorno = pthread_create(&cliente_thread[i], &attr, Cliente, (void *)i); if(err_retorno) break; } for(i=0; i<N_FILAS; i++) { err_retorno = pthread_create(&caixa_thread[i], &attr, Caixa, (void *)i); if(err_retorno) break; } return err_retorno; } void *Cliente(void *arg) { int tid = (int)arg; int menor; while(1) { pthread_mutex_lock(&clientes_a_chegar_mutex); if(clientes_a_chegar > 0) { clientes_a_chegar -= 1; pthread_mutex_unlock(&clientes_a_chegar_mutex); } else { pthread_mutex_unlock(&clientes_a_chegar_mutex); break; } menor = Menor_Fila(); sem_post(&fila[menor]); } pthread_exit(0); } void *Caixa(void *arg) { int tid = (int) arg; int i, fila_atual, fila_escolhida; int clientes_atendidos = 0; uint32_t tempo; int npessoas; while(1) { fila_escolhida = -1; fila_atual = tid; do { sem_getvalue(&fila[fila_atual], &npessoas); if(npessoas > 0) { sem_wait(&fila[fila_atual]); for(tempo = 0; tempo < 0xFFFFFF; ++tempo); fila_escolhida = fila_atual; ++clientes_atendidos; break; } ++fila_atual; if(fila_atual >= N_FILAS) fila_atual = 0; } while (fila_atual != tid); if(fila_escolhida == -1) { pthread_mutex_lock(&clientes_a_chegar_mutex); if(clientes_a_chegar == 0) { pthread_mutex_unlock(&clientes_a_chegar_mutex); break; } else { pthread_mutex_unlock(&clientes_a_chegar_mutex); continue; } } else if(ECHO && clientes_atendidos % 100 == 0) { printf("%d clientes atendidos pelo caixa %d ateh agora\\n", clientes_atendidos, tid); } } if(ECHO) printf("Caixa %d atendeu %d clientes. Fechando agora.\\n", tid, clientes_atendidos); pthread_exit(0); } void Encerrar() { int i; for(i = 0; i < N_FILAS; ++i) { pthread_join(cliente_thread[i], 0); } for(i = 0; i < N_FILAS; ++i) { pthread_join(caixa_thread[i], 0); } } int Menor_Fila() { int i; int v; int menor_i = 0; int menor_v; sem_getvalue(&fila[0], &menor_v); for(i=1; i < N_FILAS; ++i) { sem_getvalue(&fila[i], &v); if(v < menor_v) { menor_i = i; sem_getvalue(&fila[i], &menor_v); } } return menor_i; }
1
#include <pthread.h> pthread_t thread1; pthread_mutex_t mutex; pthread_mutexattr_t mta; int ret; void *a_thread_func() { ret=pthread_mutex_unlock(&mutex); pthread_exit((void*)0); } int main() { if(pthread_mutexattr_init(&mta) != 0) { perror("Error at pthread_mutexattr_init()\\n"); return PTS_UNRESOLVED; } if(pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK) != 0) { printf("Test FAILED: Error setting the attribute 'type'\\n"); return PTS_FAIL; } if(pthread_mutex_init(&mutex, &mta) != 0) { perror("Error intializing the mutex.\\n"); return PTS_UNRESOLVED; } if(pthread_mutex_lock(&mutex) != 0 ) { perror("Error locking the mutex first time around.\\n"); return PTS_UNRESOLVED; } if(pthread_create(&thread1, 0, a_thread_func, 0) != 0) { perror("Error creating a thread.\\n"); return PTS_UNRESOLVED; } pthread_join(thread1, 0); if(ret == 0) { printf("Test FAILED: Expected an error when trying to unlock a mutex that was locked by another thread. Returned 0 instead.\\n"); return PTS_FAIL; } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); if(pthread_mutexattr_destroy(&mta)) { perror("Error at pthread_mutexattr_destory().\\n"); return PTS_UNRESOLVED; } printf("Test PASSED\\n"); return PTS_PASS; }
0
#include <pthread.h> struct to_info{ void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void *timedout_helper(void *arg) { struct to_info *pto_info = (struct to_info *)arg; nanosleep(&pto_info->to_wait, 0); (*pto_info->to_fn)(pto_info->to_arg); return (void *)0; } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ( (when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec) ) { if (tip = (struct to_info *)malloc(sizeof(struct to_info))) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_nsec - now.tv_nsec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec + 100000000; } err = makethread(timedout_helper, (void *)arg); if (err == 0) return ; } } (*func)(arg); } pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; void retry(void *arg) { pthread_mutex_lock(&mutex); printf("in retry\\n"); pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&mutexattr))) { printf("error:%s\\n", strerror(err)); } if ((err = pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE))) { printf("error:%s\\n", strerror(err)); } if ((err = pthread_mutex_init(&mutex, &mutexattr))) { printf("error:%s\\n", strerror(err)); } pthread_mutex_lock(&mutex); if (condition) { timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); sleep(2); return 0; }
1
#include <pthread.h> struct registers { unsigned long counter; unsigned long instructions_cnt; }; struct context { unsigned long timeline; struct registers reg; }; struct pcb { pthread_mutex_t mutex; pthread_t tid; unsigned long idx; unsigned long state; struct registers reg; }; struct qbar { struct pcb *front; struct pcb *rear; unsigned int max_size; }; struct pcb *ready_queue[20]; struct context *cntxp; int c; void schedular(unsigned long); void *thr_fn(void *); int main(int argc, char *argv[]) { int err, i; char buff[MAXLINE]; struct pcb *pcbp; sprintf(buff, "usage: %s [1|2|3|4]\\n", argv[0]); sprintf(buff, "%s 1 (default): first come first served\\n", buff); sprintf(buff, "%s 2 : shortest job first\\n", buff); sprintf(buff, "%s 3 : round robin\\n", buff); sprintf(buff, "%s 4 : priority", buff); if (argc != 2) { printf("%s\\n", buff); exit(1); } if ((cntxp = malloc(sizeof(struct context))) != 0) { cntxp->timeline = 0; cntxp->reg.counter = 0; cntxp->reg.instructions_cnt = 0; } else { err_sys("can't malloc memory for context"); } srand(time(0)); for (i = 0; i < 20; ++i) { if ((pcbp = malloc(sizeof(struct pcb))) != 0) { pcbp->idx = i+1; pcbp->state = 0; pcbp->reg.counter = 0; pcbp->reg.instructions_cnt = rand() % 10 + 1; err = pthread_mutex_init(&pcbp->mutex, 0); if (err != 0) { free(pcbp); err_exit(err, "can't init mutex"); } } else { err_sys("can't malloc memory for struct pcb"); } err = pthread_mutex_lock(&pcbp->mutex); if (err != 0) err_exit(err, "can't lock mutex in main thread"); err = pthread_create(&pcbp->tid, 0, thr_fn, &pcbp->mutex); if (err != 0) err_exit(err, "can't create thread"); pcbp->state = 1; ready_queue[i] = pcbp; } schedular((unsigned long)atoi(argv[1])); exit(0); } void dispatcher(struct pcb *pcbp) { unsigned long timeline_old = cntxp->timeline; cntxp->reg.counter = pcbp->reg.counter; cntxp->reg.instructions_cnt = pcbp->reg.instructions_cnt; printf("thread %lu - start at time: %lu\\n", pcbp->idx, cntxp->timeline); pthread_mutex_unlock(&pcbp->mutex); pthread_join(pcbp->tid, 0); printf("thread %lu - CPU burst time: %lu\\n", pcbp->idx, cntxp->timeline - timeline_old); pcbp->reg.counter = cntxp->reg.counter; } struct pcb * first_come_first_served() { if (c == 20) return 0; return ready_queue[c++]; } struct pcb * shortest_job_first() { } struct pcb * round_robin() { } struct pcb * priority() { } void schedular(unsigned long type) { struct pcb *pcbp; c = 0; for ( ; ; ) { if (type == 1) { pcbp = first_come_first_served(); } else if (type == 2) { pcbp = shortest_job_first(); } else if (type == 3) { pcbp = round_robin(); } else if (type == 4) { pcbp = priority(); } else { exit(1); } if (pcbp == 0) break; dispatcher(pcbp); } } void * thr_fn(void *mutex) { for ( ; ; ) { pthread_mutex_lock((pthread_mutex_t *)mutex); if (cntxp->reg.counter == cntxp->reg.instructions_cnt) break; ++(cntxp->reg.counter); sleep(1); ++(cntxp->timeline); pthread_mutex_unlock(mutex); } pthread_exit(0); }
0
#include <pthread.h> int field [100][100] ; void makeField(); void makeField(){ int i=0; int j=0; for(i=0;i<100;i++){ for(j =0;j<100;j++){ field[i][j]==0; } } field[50][50] = 1024; } int getPosition(int x, int y){ if(field[x][y]!=0){ return 1; } } void setPosition(int x, int y, int val){ pthread_mutex_unlock(&fieldMutex); pthread_mutex_lock(&fieldMutex); field[x][y] = val; pthread_mutex_unlock(&fieldMutex); } void Pos(int x){ int i=0; pthread_mutex_unlock(&fieldMutex); pthread_mutex_lock(&fieldMutex); int done = 0; int j=0; for(i=0;i<100;i++){ for(j=0;j<100;j++){ if(field[i][j]==x){ printf("%d", i); printf(" ,"); printf("%d", j); done = 1; pthread_mutex_unlock(&fieldMutex); break; } } if(done==1){ pthread_mutex_unlock(&fieldMutex); break; } } }
1
#include <pthread.h> pthread_mutex_t m1; pthread_mutex_t m2; int *x; int *y; void* thread_a(void *args) { pthread_mutex_lock(&m1); pthread_mutex_lock(&m2); *x = 2; pthread_mutex_unlock(&m2); if (1) { sleep(2); printf("aborting, x = %d, y = %d\\n", *x, *y); abort(); } pthread_mutex_unlock(&m1); return 0; } void* thread_b(void *args) { sleep(1); pthread_mutex_lock(&m2); *y = *x; pthread_mutex_unlock(&m2); return 0; } int main(void) { pthread_t tid1, tid2; x = (int*)nvmalloc(sizeof(int), (char*)"x"); y = (int*)nvmalloc(sizeof(int), (char*)"y"); if (isCrashed()) { nvrecover(x, sizeof(int), (char*)"x"); nvrecover(y, sizeof(int), (char*)"y"); printf("recovered, x = %d, y = %d\\n", *x, *y); } else{ *x = 0; *y = 0; pthread_mutex_init(&m1, 0); pthread_mutex_init(&m2, 0); pthread_create(&tid1, 0, thread_a, 0); pthread_create(&tid2, 0, thread_b, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); } return 0; }
0
#include <pthread.h> int MAX = 10; semaphore mutex = 1; semaphore empty = MAX; semaphore full = 0; pthread_mutex_t mutex; pthread_cond_t condc, condp; int buffer = 0; void* produtor(void *ptr) { int i; int num = (int)(size_t)ptr; num++; for (i = 0; i < MAX; i++) { pthread_mutex_lock(&mutex); while (buffer != 0) { printf("PRODUTOR %d: Buffer CHEIO. Indo dormir ZzzZzzZzz \\n", num); pthread_cond_wait(&condp, &mutex); } printf("PRODUTOR %d: Acordado! Produzindo...\\n", num); buffer = i; pthread_cond_signal(&condc); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void* consumidor(void *ptr) { int i; int num = (int)(size_t)ptr; num++; for (i = 1; i < MAX; i++) { pthread_mutex_lock(&mutex); while (buffer == 0){ printf("CONSUMIDOR %d: Buffer VAZIO. Indo dormir ZzzZzzZzz\\n", num); pthread_cond_wait(&condc, &mutex); } printf("CONSUMIDOR %d: Acordado! Consumindo...\\n", num); buffer = 0; pthread_cond_signal(&condp); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char **argv) { int i; pthread_t pro[3], con[3]; if(argc > 1) MAX = atoi(argv[1]); pthread_mutex_init(&mutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); for(i = 0; i < 3 ; i++) pthread_create(&pro[i], 0, produtor, (void *)(size_t)i); for(i = 0; i < 3; i++) pthread_create(&con[i], 0, consumidor, (void *)(size_t)i); for(i = 0; i < 3 ; i++) pthread_join(pro[i], 0); for(i = 0; i < 3; i++) pthread_join(con[i], 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); }
1
#include <pthread.h> static pthread_mutex_t parent_mutex[10]; static pthread_mutex_t child_mutex[10]; static void * routine(void * arg) { for (int i = 0; i < 10; ++i) { pthread_mutex_lock(&child_mutex[i]); } for (int i = 0; i < 10; ++i) { pthread_mutex_lock(&parent_mutex[i]); pthread_mutex_unlock(&parent_mutex[i]); printf("Child %d\\n", i + 1); pthread_mutex_unlock(&child_mutex[i]); } return 0; } int main() { pthread_t thread; pthread_mutexattr_t attrs; pthread_mutexattr_init(&attrs); pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_ERRORCHECK); for (int i = 0; i < 10; ++i) { pthread_mutex_init(&parent_mutex[i], &attrs); pthread_mutex_init(&child_mutex[i], &attrs); pthread_mutex_lock(&parent_mutex[i]); } pthread_create(&thread, 0, routine, 0); sleep(1); for (int i = 0; i < 10; ++i) { if (i > 0) { pthread_mutex_lock(&child_mutex[i - 1]); pthread_mutex_unlock(&child_mutex[i - 1]); } printf("Parent %d\\n", i + 1); pthread_mutex_unlock(&parent_mutex[i]); } sleep(100); pthread_join(thread, 0); for (int i = 0; i < 10; ++i) { pthread_mutex_destroy(&parent_mutex[i]); pthread_mutex_destroy(&child_mutex[i]); } }
0
#include <pthread.h> extern pthread_mutex_t tel_mutex; int test_tel_start(void) { int cur_row=2; int ret, fd, ps_state; char tmp[512]; char* ptmp = 0; time_t start_time,now_time; char property[PROPERTY_VALUE_MAX]; char moemd_tel_port[BUF_LEN]; char write_buf[1024] = {0}; ui_fill_locked(); ui_show_title(MENU_TEST_TEL); ui_set_color(CL_GREEN); cur_row = ui_show_text(cur_row, 0, TEL_TEST_START); cur_row = ui_show_text(cur_row, 0, TEL_TEST_TIPS); gr_flip(); property_get(PROP_MODEM_LTE_ENABLE, property, "not_find"); if(!strcmp(property, "1")) sprintf(moemd_tel_port,"/dev/stty_lte2"); else sprintf(moemd_tel_port,"/dev/stty_w2"); LOGD("mmitest tel test %s",moemd_tel_port); fd=open(moemd_tel_port,O_RDWR); if(fd<0){ LOGE("mmitest tel test failed"); ret = RL_FAIL; goto end; } pthread_mutex_lock(&tel_mutex); tel_send_at(fd,"AT+SFUN=2",0,0, 0); ret = tel_send_at(fd,"AT+SFUN=4",0,0, 100); pthread_mutex_unlock(&tel_mutex); if(ret < 0 ){ ret = RL_FAIL; ui_set_color(CL_RED); ui_show_text(cur_row,0,TEL_DIAL_FAIL); gr_flip(); sleep(1); goto end; } start_time=time(0); for(;;){ tel_send_at(fd, "AT+CREG?", tmp, sizeof(tmp), 0); ptmp = strstr(tmp, "CREG"); LOGD("+CREG =%s", ptmp); eng_tok_start(&ptmp); eng_tok_nextint(&ptmp, &ps_state); LOGD("get ps mode=%d", ps_state); if(2 == ps_state){ eng_tok_nextint(&ptmp, &ps_state); LOGD("get ps state=%d", ps_state); if((1 == ps_state) || (8 == ps_state) || (5 == ps_state)) { break; } } sleep(2); now_time = time(0); if (now_time - start_time > TEL_TIMEOUT ){ LOGE("mmitest tel test failed"); ret = RL_FAIL; ui_set_color(CL_RED); ui_show_text(cur_row,0,TEL_DIAL_FAIL); gr_flip(); sleep(1); goto end; } } cur_row = ui_show_text(cur_row, 0, TEL_DIAL_OVER); usleep(200*1000); tel_send_at(fd,"AT+SSAM=1",0,0,0); gr_flip(); ret = ui_handle_button(TEXT_PASS, 0,TEXT_FAIL); tel_send_at(fd,"ATH",0,0, 0); tel_send_at(fd,"AT",0,0, 0); end: if(fd >= 0) close(fd); save_result(CASE_TEST_TEL,ret); return ret; }
1
#include <pthread.h> static int accounts[ 10 ]; static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static int sum( void ) { int s = 0; int i; for ( i = 0; i < 10; i++ ) { s += accounts[ i ]; } return s; } static void *transfer( void *acc_from ) { int from = *(int *) acc_from; while ( 1 ) { pthread_mutex_lock( &lock ); int to = random() % 10; int amount = random() % 1000; if ( accounts[ from ] < amount ) { pthread_mutex_unlock( &lock ); return (void *) 0; } accounts[ from ] -= amount; printf( "terminal '%d': %5d from [%02d] to [%02d]\\t", pthread_self(), amount, from, to ); accounts[ to ] += amount; printf( "sum is %5d\\n", sum() ); pthread_mutex_unlock( &lock ); usleep( random() % 200 ); } return (void *) 0; } int main( void ) { pthread_t id[ 10 ]; int i; for ( i = 0; i < 10; i++ ) { accounts[ i ] = 1000; } alarm( 1 ); for ( i = 0; i < 10; i++ ) { pthread_create( id+i, 0, transfer, (void *) &i ); } return 0; }
0
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t C = PTHREAD_COND_INITIALIZER; int customer_count = 0; int chair_count = 5; int max_customer_count = 10; int total = 10; pthread_cond_t call_customer=PTHREAD_COND_INITIALIZER; pthread_cond_t start_haircut=PTHREAD_COND_INITIALIZER; pthread_cond_t end_haircut =PTHREAD_COND_INITIALIZER; pthread_cond_t wake_barber=PTHREAD_COND_INITIALIZER; pthread_cond_t check_remaining = PTHREAD_COND_INITIALIZER; int ameya=10; int array_ameya[10]; int got_seat[10]; void barber(void) { pthread_mutex_lock(&m); while (1) { } pthread_mutex_unlock(&m); } void customer(int customer_num) { pthread_mutex_lock(&m); pthread_mutex_unlock(&m); } void *customer_thread(void *context) { int customer_num = (int)context; customer(customer_num); return 0; } void *barber_thread(void *context) { barber(); return 0; } void q2(void) { } void q3(void) { }
1
#include <pthread.h> static inline struct spdk_nvme_ns_data * _nvme_ns_get_data(struct spdk_nvme_ns *ns) { return &ns->ctrlr->nsdata[ns->id - 1]; } static int nvme_ns_identify_update(struct spdk_nvme_ns *ns) { struct nvme_completion_poll_status status; struct spdk_nvme_ns_data *nsdata; int rc; nsdata = _nvme_ns_get_data(ns); status.done = 0; rc = nvme_ctrlr_cmd_identify_namespace(ns->ctrlr, ns->id, nsdata, nvme_completion_poll_cb, &status); if (rc != 0) { return rc; } while (status.done == 0) { pthread_mutex_lock(&ns->ctrlr->ctrlr_lock); spdk_nvme_qpair_process_completions(&ns->ctrlr->adminq, 0); pthread_mutex_unlock(&ns->ctrlr->ctrlr_lock); } if (spdk_nvme_cpl_is_error(&status.cpl)) { memset(nsdata, 0, sizeof(*nsdata)); ns->stripe_size = 0; ns->sector_size = 0; ns->md_size = 0; ns->pi_type = 0; ns->sectors_per_max_io = 0; ns->sectors_per_stripe = 0; ns->flags = 0; return 0; } ns->sector_size = 1 << nsdata->lbaf[nsdata->flbas.format].lbads; ns->sectors_per_max_io = spdk_nvme_ns_get_max_io_xfer_size(ns) / ns->sector_size; ns->sectors_per_stripe = ns->stripe_size / ns->sector_size; ns->flags = 0x0000; if (ns->ctrlr->cdata.oncs.dsm) { ns->flags |= SPDK_NVME_NS_DEALLOCATE_SUPPORTED; } if (ns->ctrlr->cdata.vwc.present) { ns->flags |= SPDK_NVME_NS_FLUSH_SUPPORTED; } if (ns->ctrlr->cdata.oncs.write_zeroes) { ns->flags |= SPDK_NVME_NS_WRITE_ZEROES_SUPPORTED; } if (nsdata->nsrescap.raw) { ns->flags |= SPDK_NVME_NS_RESERVATION_SUPPORTED; } ns->md_size = nsdata->lbaf[nsdata->flbas.format].ms; ns->pi_type = SPDK_NVME_FMT_NVM_PROTECTION_DISABLE; if (nsdata->lbaf[nsdata->flbas.format].ms && nsdata->dps.pit) { ns->flags |= SPDK_NVME_NS_DPS_PI_SUPPORTED; ns->pi_type = nsdata->dps.pit; if (nsdata->flbas.extended) ns->flags |= SPDK_NVME_NS_EXTENDED_LBA_SUPPORTED; } return rc; } uint32_t spdk_nvme_ns_get_id(struct spdk_nvme_ns *ns) { return ns->id; } bool spdk_nvme_ns_is_active(struct spdk_nvme_ns *ns) { const struct spdk_nvme_ns_data *nsdata = _nvme_ns_get_data(ns); return nsdata->ncap != 0; } uint32_t spdk_nvme_ns_get_max_io_xfer_size(struct spdk_nvme_ns *ns) { return ns->ctrlr->max_xfer_size; } uint32_t spdk_nvme_ns_get_sector_size(struct spdk_nvme_ns *ns) { return ns->sector_size; } uint64_t spdk_nvme_ns_get_num_sectors(struct spdk_nvme_ns *ns) { return _nvme_ns_get_data(ns)->nsze; } uint64_t spdk_nvme_ns_get_size(struct spdk_nvme_ns *ns) { return spdk_nvme_ns_get_num_sectors(ns) * spdk_nvme_ns_get_sector_size(ns); } uint32_t spdk_nvme_ns_get_flags(struct spdk_nvme_ns *ns) { return ns->flags; } enum spdk_nvme_pi_type spdk_nvme_ns_get_pi_type(struct spdk_nvme_ns *ns) { return ns->pi_type; } bool spdk_nvme_ns_supports_extended_lba(struct spdk_nvme_ns *ns) { return (ns->flags & SPDK_NVME_NS_EXTENDED_LBA_SUPPORTED) ? 1 : 0; } uint32_t spdk_nvme_ns_get_md_size(struct spdk_nvme_ns *ns) { return ns->md_size; } const struct spdk_nvme_ns_data * spdk_nvme_ns_get_data(struct spdk_nvme_ns *ns) { nvme_ns_identify_update(ns); return _nvme_ns_get_data(ns); } int nvme_ns_construct(struct spdk_nvme_ns *ns, uint16_t id, struct spdk_nvme_ctrlr *ctrlr) { struct pci_id pci_id; assert(id > 0); ns->ctrlr = ctrlr; ns->id = id; ns->stripe_size = 0; if (ctrlr->transport->ctrlr_get_pci_id(ctrlr, &pci_id) == 0) { if (pci_id.vendor_id == SPDK_PCI_VID_INTEL && pci_id.dev_id == INTEL_DC_P3X00_DEVID && ctrlr->cdata.vs[3] != 0) { ns->stripe_size = (1 << ctrlr->cdata.vs[3]) * ctrlr->min_page_size; } } return nvme_ns_identify_update(ns); } void nvme_ns_destruct(struct spdk_nvme_ns *ns) { }
0
#include <pthread.h> int epfd; int addEpollEvent(int epfd, int fd, struct epoll_event *event) { if( epoll_ctl(epfd, EPOLL_CTL_ADD, fd, event) == -1) return -1; return 1; } int modifyEpollEvent(int epfd, int fd, struct epoll_event *event) { if( epoll_ctl (epfd, EPOLL_CTL_MOD, fd, event) == -1) return -1; return 1; } int deleteEpollEvent(int epfd, int fd) { struct epoll_event event; if(epoll_ctl(epfd, EPOLL_CTL_DEL, fd, &event) == -1) return -1; return 1; } int epollCreate() { epfd = epoll_create(EPOLL_LISTEN_MAX); return epfd; } void *listenEpollEvent() { struct epoll_event events[EPOLL_LISTEN_MAX]; int nfds; while(1) { nfds = epoll_wait(epfd, events, EPOLL_LISTEN_MAX, -1); int i; for(i = 0; i < nfds; i ++) { while(Pstack_empty(&freeRecvThreadStack) == 1) { printf("there is no thread available!\\n"); usleep(100); } pthread_mutex_lock(&freeRecvThreadStackMutex); int availableThreadId = Pstack_top(&freeRecvThreadStack); Pstack_pop(&freeRecvThreadStack); pthread_mutex_unlock(&freeRecvThreadStackMutex); recvThreadParaTable[availableThreadId].sockfd = events[i].data.fd; pthread_mutex_unlock(&(recvThreadParaTable[availableThreadId].mutex)); } } close(epfd); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t forks[5]; pthread_mutex_t cntlock; int cnt = 0; void bsleep() { for(int i = 0; i < 50; i++) sched_yield(); } void* act() { int tid = pthread_self(); int f1 = (int)(tid-1)%5; int f2 = (int)tid%5; int eating = 0; int ret = pthread_mutex_lock(&forks[f1]); assert(!ret); printf("T%d: Took fork %d\\n", tid, f1); bsleep(); printf("T%d: Try taking fork %d\\n", tid, f2); while (!eating) { ret = pthread_mutex_trylock(&forks[f2]); if(ret) { printf("T%d: Couldn't take fork %d, code: %d\\n", tid, f2, ret); bsleep(); continue; } printf("T%d: Took fork %d\\n", tid, f2); eating = 1; } pthread_mutex_unlock(&forks[f2]); pthread_mutex_unlock(&forks[f1]); printf("T%d: done eating\\n", tid); pthread_mutex_lock(&cntlock); cnt++; pthread_mutex_unlock(&cntlock); return 0; } int main() { pthread_t t[5]; pthread_mutex_init(&cntlock, 0); for (int i = 0; i < 5; i++) pthread_mutex_init(&forks[i], 0); for (int i = 0; i < 5; i++) pthread_create(&t[i], 0, &act, 0); while(1) { pthread_mutex_lock(&cntlock); int c = cnt; pthread_mutex_unlock(&cntlock); printf("PARENT: Check cnt: %d\\n", c); if(c == 5) break; else bsleep(); } for (int i = 0; i < 5; i++) { int ret = pthread_mutex_destroy(&forks[i]); assert(!ret); } printf("PARENT: success, over and out\\n"); return 0; }
0
#include <pthread.h> struct queue_root { struct queue_head *in_queue; struct queue_head *out_queue; pthread_mutex_t lock; }; struct queue_root *ALLOC_QUEUE_ROOT() { struct queue_root *root = malloc(sizeof(struct queue_root)); pthread_mutex_init(&root->lock, 0); root->in_queue = 0; root->out_queue = 0; return root; } void INIT_QUEUE_HEAD(struct queue_head *head) { head->next = ((void*)0xCAFEBAB5); } void queue_put(struct queue_head *new, struct queue_root *root) { while (1) { struct queue_head *in_queue = root->in_queue; new->next = in_queue; if (__sync_bool_compare_and_swap(&root->in_queue, in_queue, new)) { break; } } } struct queue_head *queue_get(struct queue_root *root) { pthread_mutex_lock(&root->lock); if (!root->out_queue) { while (1) { struct queue_head *head = root->in_queue; if (!head) { break; } if (__sync_bool_compare_and_swap(&root->in_queue, head, 0)) { while (head) { struct queue_head *next = head->next; head->next = root->out_queue; root->out_queue = head; head = next; } break; } } } struct queue_head *head = root->out_queue; if (head) { root->out_queue = head->next; } pthread_mutex_unlock(&root->lock); return head; }
1
#include <pthread.h> int numFiles = 0; int totalTime = 0; pthread_mutex_t mutexTotalTime; void* dispatch_execute (void* arg); void* worker_execute(void* arg); void printStats(int); int main() { srand(time(0)); pthread_mutex_init(&mutexTotalTime, 0); int status; pthread_t dispatch; if ((status = pthread_create(&dispatch, 0, dispatch_execute, 0)) != 0) { fprintf(stderr, "Uh oh...something went wrong creating thread %d: %s\\n", status, strerror(status)); exit(1); } if ((status = pthread_join(dispatch, 0)) != 0) { fprintf(stderr, "Uh oh...something went wrong joining thread %d: %s\\n", status, strerror(status)); exit(1); } pthread_mutex_destroy(&mutexTotalTime); return 0; } void* dispatch_execute (void* arg) { signal(SIGINT, printStats); int bufIndex = 0; while (1) { if (bufIndex == 4000) bufIndex = 0; char* buf = malloc(sizeof(char) * 255); printf("What file would you like? "); if(fgets(buf, 255, stdin) == 0) { perror("Uh oh...something went wrong reading input"); exit(1); } buf = realloc(buf, sizeof(char) * strlen(buf)); int status; pthread_t worker; if ((status = pthread_create(&worker, 0, worker_execute, (void*) buf)) != 0) { fprintf(stderr, "Uh oh...something went wrong creating thread %d: %s\\n", status, strerror(status)); exit(1); } if ((status = pthread_detach(worker)) != 0) { fprintf(stderr, "Uh oh...something went wrong detaching thread %d: %s\\n", status, strerror(status)); exit(1); } numFiles++; bufIndex++; } return arg; } void* worker_execute (void* arg) { char* filename = (char*) arg; int workerTime = 0; int randNum = rand(); if ((randNum % 5) == 0) { int rand7to10 = rand() % (10 - 7 + 1) + 7; workerTime = rand7to10; sleep(workerTime); printf("\\nIt took %d secs to get file %s\\n", workerTime, filename); } else { workerTime = 1; sleep(workerTime); printf("\\nIt took %d sec to get file %s", workerTime, filename); } free(filename); pthread_mutex_lock(&mutexTotalTime); totalTime += workerTime; pthread_mutex_unlock(&mutexTotalTime); return 0; } void printStats (int sigNum) { printf("\\n"); printf("Well, looks like we're done for the day.\\n"); printf("Here's how many files we found: %d\\n", numFiles); float avgTime = (float) totalTime / (float) numFiles; printf("Here's the average time we took to get your files today: %f secs\\n", avgTime); exit(0); }
0
#include <pthread.h> long a = 0; long b = 0; pthread_mutex_t a_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t b_mutex = PTHREAD_MUTEX_INITIALIZER; void *a_thread(void *arg) { printf("This thread increments a and adds to b\\n"); int ret = pthread_mutex_lock(&a_mutex); if(ret == EINVAL) { printf("Error locking a_mutex\\n"); pthread_exit(0); } sleep(1); a++; ret = pthread_mutex_lock(&b_mutex); if(ret == EINVAL) { printf("Error locking b_mutex\\n"); pthread_exit(0); } sleep(1); b += a; pthread_mutex_unlock(&b_mutex); pthread_mutex_unlock(&a_mutex); pthread_exit(0); } void *b_thread(void *arg) { printf("This thread increments b and multiplies a by b\\n"); int ret = pthread_mutex_lock(&b_mutex); if(ret == EINVAL) { printf("Error locking b_mutex\\n"); pthread_exit(0); } b++; ret = pthread_mutex_lock(&a_mutex); if(ret == EINVAL) { printf("Error locking a_mutex\\n"); pthread_exit(0); } a *= b; pthread_mutex_unlock(&a_mutex); pthread_mutex_unlock(&b_mutex); pthread_exit(0); } int main() { pthread_t my_a_thread[5]; pthread_t my_b_thread[5]; long id; for (id = 0; id < 5; id++) { int ret = pthread_create(&my_a_thread[id], 0, &a_thread, 0); ret = pthread_create(&my_b_thread[id], 0, &b_thread, 0); } for (id = 0; id < 5; id++) { pthread_join(my_a_thread[id], 0); pthread_join(my_b_thread[id], 0); } printf("main program done\\n"); printf("a = %ld\\n", a); printf("b = %ld\\n", b); pthread_exit(0); }
1
#include <pthread.h> struct message { long msg_type; char msg_text[BUFFER_SIZE]; }msgbuf; static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t v = PTHREAD_COND_INITIALIZER; void *receiver(void *args) { int qid = *(int *)args; bzero(msgbuf.msg_text, BUFFER_SIZE); while(1){ pthread_mutex_lock(&m); int len = strlen(msgbuf.msg_text); printf("len = %d\\n", len); while(strlen(msgbuf.msg_text) != 0) pthread_cond_wait(&v, &m); int ret = msgrcv(qid, &msgbuf, sizeof msgbuf, R2J, 0); printf("ret : %d\\n", ret); fprintf(stderr, "\\nPeer: %s\\n", msgbuf.msg_text); printf("len1: %d\\n", strlen(msgbuf.msg_text)); bzero(&msgbuf, BUFFER_SIZE + sizeof(long)); printf("len2: %d\\n", strlen(msgbuf.msg_text)); pthread_cond_broadcast(&v); pthread_mutex_unlock(&m); sleep(1); } } void *sender(void *args) { int qid = *(int *)args; while(1){ pthread_mutex_lock(&m); while(strlen(msgbuf.msg_text) == 0) pthread_cond_wait(&v, &m); Msgsnd(qid, &msgbuf, strlen(msgbuf.msg_text), 0); bzero(msgbuf.msg_text, BUFFER_SIZE); pthread_cond_broadcast(&v); pthread_mutex_unlock(&m); } } int main(void) { int qid; key_t key; key = Ftok(".", 'a'); qid = Msgget(key, IPC_CREAT|0666); printf("Open queue %d\\n", qid); printf("(\\"quit\\" to exit) "); pthread_t tid1, tid2; Pthread_create(&tid1, 0, receiver, (void *)&qid); char buf4fgets[80]; while(1){ printf("Me: "); Fgets(buf4fgets, BUFFER_SIZE, stdin); pthread_mutex_lock(&m); while(strlen(msgbuf.msg_text)) pthread_cond_wait(&v, &m); strncpy(msgbuf.msg_text, buf4fgets, BUFFER_SIZE); msgbuf.msg_type = J2R; pthread_cond_broadcast(&v); pthread_mutex_unlock(&m); } pause(); pthread_exit(0); }
0
#include <pthread.h> int isPrime(int n){ for(int i=2;i<n;i++){ if(n%i ==0){ return 0; } } if(n==1){ return 0; } return 1; } int numPrimes = 0; int n = 50; int intervalSize; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void* countPrimes(void* params){ int i = *((int*)params); int start = (i*intervalSize) + 1; int numPrimesThisInterval = 0; for(int x = start;x<start+intervalSize;x++){ if(isPrime(x) == 1){ numPrimesThisInterval ++; } } printf("Number of primes [%i - %i] = %i\\n",start,start+intervalSize,numPrimesThisInterval); pthread_mutex_lock(&lock); printf("Thread %i aqquired the lock\\n",i); numPrimes += numPrimesThisInterval; pthread_mutex_unlock(&lock); printf("Thread %i released the lock\\n",i); pthread_exit(0); } int main(){ pthread_t threads[10]; intervalSize = n / 10; int argsArray[10]; for(int i=0;i<10;i++){ argsArray[i] = i; } for(int i=0;i<10;i++){ pthread_create(&threads[i],0,countPrimes,(void*)&(argsArray[i])); } for(int i=0;i<10;i++){ pthread_join(threads[i], 0); } pthread_mutex_destroy(&lock); printf("Number of primes from 1 to %i = %i\\n\\n",n,numPrimes); return 0; }
1
#include <pthread.h> pthread_mutex_t proMutex; pthread_mutex_t cusMutex; sem_t emptysem; sem_t fullsem; char g_caDish[10]; int g_iProNum = 0; void *product(void *arg) { int num = (int)arg; while (1) { sem_wait(&emptysem); pthread_mutex_lock(&proMutex); srand((unsigned int)time(0)); g_caDish[g_iProNum] = rand() % 26 + 'A'; printf("第%d个生产者往第%d个盘子中生产了%c食物\\n", num+1, g_iProNum+1, g_caDish[g_iProNum]); g_iProNum = (g_iProNum+1)%10; pthread_mutex_unlock(&proMutex); sem_post(&fullsem); sleep(1); } } int g_iCusNum = 0; void *custom(void *arg) { int num = (int)arg; while (1) { sem_wait(&fullsem); pthread_mutex_lock(&cusMutex); printf("第%d个消费者消费了第%d个盘子中的%c食物\\n", num+1, g_iCusNum+1, g_caDish[g_iCusNum]); g_caDish[g_iCusNum] = '\\0'; g_iCusNum = (g_iCusNum+1)%10; pthread_mutex_unlock(&cusMutex); sem_post(&emptysem); sleep(1); } } int main(void) { memset(g_caDish, '\\0', 10); sem_init(&emptysem, 0, 10); sem_init(&fullsem, 0, 0); pthread_t cus[15]; int i = 0; for (; i < 15; i++) { pthread_create(cus+i, 0, custom , (void*)i); } pthread_t pro[5]; for (i = 0; i < 5; i++) { pthread_create(pro+i, 0, product , (void *)i); } for (i = 0; i < 15; i++) { pthread_join(cus[i], 0); } for (i = 0; i < 5; i++) { pthread_join(pro[i], 0); } return 0; }
0
#include <pthread.h> void* led_one(); void* led_two(); pthread_mutex_t lock_mutex = PTHREAD_MUTEX_INITIALIZER; int main(void) { pthread_t led_one_thread; pthread_t led_two_thread; int led_one_thread_ret = pthread_create(&led_one_thread, 0, led_one, 0); int led_two_thread_ret = pthread_create(&led_two_thread, 0, led_two, 0); if(led_one_thread_ret != 0) { printf("Thread fail to create! Error: %d", led_one_thread_ret); return 1; } if(led_two_thread_ret != 0) { printf("Thread fail to create! Error: %d", led_two_thread_ret); return 1; } pthread_join(led_one_thread, 0); pthread_join(led_two_thread, 0); pthread_mutex_destroy(&lock_mutex); pthread_exit(0); return 0; } void* led_one(void) { int i = 0; if (wiringPiSetup() == -1) { return (void*) 1; } pinMode (0, OUTPUT); for (;;) { pthread_mutex_lock(&lock_mutex); digitalWrite(0, 1); delay(2000); pthread_mutex_unlock(&lock_mutex); digitalWrite(0, 0); delay(2000); } } void* led_two(void) { int i = 0; if (wiringPiSetup() == -1) { return (void*) 1; } pinMode (1, OUTPUT); for (;;) { pthread_mutex_lock(&lock_mutex); digitalWrite(1, 1); delay(2000); pthread_mutex_unlock(&lock_mutex); digitalWrite(1, 0); delay(2000); } }
1
#include <pthread.h> volatile static char buf[bufSize]; volatile static int head = 0; volatile static int tail = 0; volatile static int n = 0; static pthread_mutex_t bufMutex; static pthread_cond_t bufEmptyCv; static pthread_cond_t bufFullCv; void put(long id, char ch) { pthread_mutex_lock(&bufMutex); while (n == bufSize) { pthread_cond_wait(&bufFullCv, &bufMutex); } buf[tail] = ch; tail = (tail + 1) % bufSize; ++n; pthread_cond_signal(&bufEmptyCv); pthread_mutex_unlock(&bufMutex); } char get(long id) { char ch; pthread_mutex_lock(&bufMutex); while (n == 0) { printf("Consumer thread %ld going to wait\\n", id); pthread_cond_wait(&bufEmptyCv, &bufMutex); } ch = buf[head]; head = (head + 1) % bufSize; --n; printf("Consumer thread %ld ready: n = %d\\n", id, n); pthread_cond_signal(&bufFullCv); pthread_mutex_unlock(&bufMutex); return ch; } void* produce(void* t) { for (int i = 0; i < maxCount; ++i) { put(myId, 'x'); usleep(800000); } pthread_exit(0); } void* consume(void* t) { for (int i = 0; i < maxCount; ++i) { get(myId); usleep(200000); } pthread_exit(0); } int main(int argc, char *argv[]) { long t[numThreads] = {1, 2, 3, 4}; pthread_t p1; pthread_t p2; pthread_t c1; pthread_t c2; pthread_attr_t attr; pthread_mutex_init(&bufMutex, 0); pthread_cond_init (&bufEmptyCv, 0); pthread_cond_init (&bufFullCv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&p1, &attr, produce, (void*)t[0]); pthread_create(&p2, &attr, produce, (void*)t[1]); pthread_create(&c1, &attr, consume, (void*)t[2]); pthread_create(&c2, &attr, consume, (void*)t[3]); pthread_join(p1, 0); pthread_join(p2, 0); pthread_join(c1, 0); pthread_join(c2, 0); pthread_attr_destroy(&attr); pthread_mutex_destroy(&bufMutex); pthread_cond_destroy(&bufEmptyCv); pthread_cond_destroy(&bufFullCv); pthread_exit(0); }
0
#include <pthread.h> datatype name; struct node *next; } node; node *front, *rear; int len; } queue; void queue_init(queue *q) { q->front = q->rear = 0; q->len = 0; } void queue_put(queue *q, datatype new_name) { node *mynode = (node *)malloc(sizeof(node)); mynode->name = new_name; mynode->next = 0; if (q->rear) q->rear->next = mynode; q->rear = mynode; if (q->front == 0) q->front = mynode; q->len++; } datatype queue_get(queue *q) { node *mynode; datatype myname; if (q->front != 0) mynode = q->front; myname = mynode->name; q->front = q->front->next; q->len--; free(mynode); return myname; } void queue_print(queue *q) { node *tmp = q->front; while(tmp != 0) { printf("%s ", tmp->name); tmp = tmp->next; } printf("\\n"); } pthread_cond_t q_not_full = PTHREAD_COND_INITIALIZER; pthread_cond_t q_not_empty = PTHREAD_COND_INITIALIZER; pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER; void producer(void *q) { queue *qt = q; while(1) { pthread_mutex_lock(&qlock); while(qt->len >= 10) { pthread_cond_wait(&q_not_full, &qlock); } queue_put(qt, "* "); pthread_mutex_unlock(&qlock); pthread_cond_signal(&q_not_empty); } } void consumer(void *q) { queue *qt = q; while(1) { pthread_mutex_lock(&qlock); while(qt->len <= 0) { pthread_cond_wait(&q_not_empty, &qlock); } datatype back_name = queue_get(qt); pthread_mutex_unlock(&qlock); pthread_cond_signal(&q_not_full); } } int main() { pthread_t tid1, tid2; queue *q=(queue *)malloc(sizeof(queue)); queue_init(q); long stime = clock(); long etime = clock(); pthread_create(&tid1, 0, (void *)producer, (void *)q); pthread_create(&tid2, 0, (void *)consumer, (void *)q); while((float)(etime-stime)/CLOCKS_PER_SEC < 0.00001) { etime = clock(); } return 0; }
1
#include <pthread.h> pthread_mutex_t locki[26]; pthread_mutex_t lockb[26]; int busy[26]; int inode[32]; pthread_t tids[27]; void *thread_routine(void * arg) { int i,b,j; int tid; tid = *((int *)arg); assert(tid>=0 && tid<27); i = tid % 32; assert(i >=0 && i < 26); pthread_mutex_lock( &locki[i] ); if( inode[i]==0 ) { b = (i*2) % 26; for(j=0; j<26/2; j++) { pthread_mutex_lock( &lockb[b] ); if(!busy[b]) { busy[b] = 1; inode[i] = b+1; printf(" "); pthread_mutex_unlock( &lockb[b] ); break; } pthread_mutex_unlock( &lockb[b] ); b = (b+1) % 26; } } assert(i >=0 && i < 26); pthread_mutex_unlock( &locki[i] ); pthread_exit(0); } int main() { int i; int arg[27]; for(i = 0; i < 26;i++) { pthread_mutex_init(&locki[i],0); pthread_mutex_init(&lockb[i],0); busy[i] = 0; } for(i=0;i<27;i++) { arg[i]=i; pthread_create(&tids[i], 0, thread_routine, &arg[i]); } for(i=0;i<27;i++) pthread_join(tids[i], 0); for(i=0;i<26;i++) { pthread_mutex_destroy(&locki[i]); pthread_mutex_destroy(&lockb[i]); } return 0; }
0
#include <pthread.h> struct readerArgs { int fd; size_t number; }; ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset); void getCurrentTime(char *str, size_t maxLength); void* readerFunc(readerArgs *args); void* writerFunc(void *fd); void clearResources(int fd); pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; pthread_mutex_t stdoutMutex = PTHREAD_MUTEX_INITIALIZER; int main() { int fd = open("File", O_CREAT | O_RDWR | O_TRUNC, 00777); pthread_t readers[10], writer; readerArgs args[10]; if (fd == -1) { printf("Error: %s", strerror(errno)); clearResources(fd); return -1; } errno = pthread_create(&writer, 0, writerFunc, &fd); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } for (int i = 0; i < 10; i++) { args[i].fd = fd; args[i].number = i + 1; errno = pthread_create(readers + i, 0, (void* (*)(void*)) readerFunc, args + i); if (errno != 0) { printf("Error: %s\\n", strerror(errno)); clearResources(fd); return -1; } } pthread_join(writer, 0); for (int i = 0; i < 10; i++) pthread_join(readers[i], 0); clearResources(fd); return 0; } ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset) { char buf[maxLength]; ssize_t retVal = pread(fd, buf, maxLength, offset); size_t newLinePos; if (retVal == -1) return -1; newLinePos = strcspn(buf, "\\n"); if (newLinePos == strlen(buf)) return 0; newLinePos++; strncpy(str, buf, newLinePos); return newLinePos; } void* readerFunc(readerArgs *args) { char str[100]; int fd = args->fd; ssize_t number = args->number, bytesCount; off_t offset = 0; do { pthread_rwlock_rdlock(&rwlock); bytesCount = pgetLine(fd, str, 100, offset); pthread_rwlock_unlock(&rwlock); if (bytesCount <= 0) { pthread_mutex_lock(&stdoutMutex); printf("Thread%lu wait for data...\\n", number); pthread_mutex_unlock(&stdoutMutex); sleep(1); continue; } offset += bytesCount; if (strncmp(str, "END", 3) == 0) break; pthread_mutex_lock(&stdoutMutex); printf("Thread%lu %s", number, str); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); if (offset > 100*10) return 0; } while (1); pthread_mutex_lock(&stdoutMutex); printf("Thread%lu END\\n", number); fflush(stdout); pthread_mutex_unlock(&stdoutMutex); return 0; } void* writerFunc(void *fd) { int _fd = *(int*)fd; char str[100], timeStr[50]; for (int i = 1; i < 10 + 1; i++) { getCurrentTime(timeStr, 50); sprintf(str, "Line %d Current time %s\\n", i, timeStr); pthread_rwlock_wrlock(&rwlock); write(_fd, str, strlen(str)); pthread_rwlock_unlock(&rwlock); } pthread_rwlock_wrlock(&rwlock); write(_fd, "END\\n", 4); pthread_rwlock_unlock(&rwlock); return 0; } void getCurrentTime(char *str, size_t maxLength) { static struct timeval timer; gettimeofday(&timer, 0); strftime(str, maxLength, "%T.", localtime(&timer.tv_sec)); sprintf(str + strlen(str), "%ld", timer.tv_usec); } void clearResources(int fd) { close(fd); pthread_rwlock_destroy(&rwlock); pthread_mutex_destroy(&stdoutMutex); }
1
#include <pthread.h> struct critical_data { int len; char buf[100]; }data[2]; pthread_mutex_t mutex; void * write_thread (void *p) { printf("\\n In Write thread\\n"); if(pthread_mutex_lock(&mutex)==0) { printf("\\n\\t Entering critical section in Write thread \\n"); strcpy(data[0].buf,"Veda Solutions"); data[0].len=strlen("Veda Solutions"); strcpy(data[1].buf,"Solutions"); sleep(2); data[1].len=strlen("Solutions"); pthread_mutex_unlock(&mutex); printf ("\\t Leaving critical section in Write thread\\n"); } printf(" Write job is over\\n"); pthread_exit(0); } void * read_thread(void *p) { printf("\\n In Read thread \\n"); if(pthread_mutex_trylock(&mutex)==0) { printf("\\n\\t Entering critical section in Read thread \\n"); printf("\\n\\t %d %s \\n",data[0].len,data[0].buf); printf("\\n\\t %d %s \\n",data[1].len,data[1].buf); pthread_mutex_unlock(&mutex); printf ("\\t Leaving critical section in Read thread\\n"); } else printf ("\\t Mutex not avalible for Read thread\\n"); printf(" Read job is over\\n"); pthread_exit(0); } int main () { pthread_t tid1,tid2; int rv; pthread_mutex_init(&mutex,0); rv = pthread_create(&tid1, 0, write_thread, 0); if(rv) puts("Failed to create thread"); rv = pthread_create(&tid2, 0, read_thread, 0); if(rv) puts("Failed to create thread"); pthread_join(tid1,0); pthread_join(tid2,0); puts(" Exit Main"); return 0; }
0
#include <pthread.h> struct thrd_data{ int id; int start; int end; }; int count = 0; pthread_mutex_t count_mtx; void *do_work(void *thrd_arg) { struct thrd_data *t_data; int i,min, max; int myid; int mycount = 0; t_data = (struct thrd_data *) thrd_arg; myid = t_data->id; min = t_data->start; max = t_data->end; printf ("Thread %d finding prime from %d to %d\\n", myid,min,max-1); if (myid==0) { for (i=8;i<max;i++) { if (i%2==0) { printf("\\n%d Not a prime (2)\\n",i); } else if (i%3==0) { printf("\\n%d Not a prime (3)\\n",i); } else if (i%5==0) { printf("\\n%d Not a prime (5)\\n",i); } else if (i%7==0) { printf("\\n%d Not a prime (7)\\n",i); } else { printf("\\nFound a prime: %d\\n",i); mycount = mycount + 1; } } pthread_mutex_lock (&count_mtx); count = count + mycount + 4; pthread_mutex_unlock (&count_mtx); pthread_exit(0); } else { for (i=min;i<max;i++) { if (i%2==0) { printf("\\n%d Not a prime (2)\\n",i); } else if (i%3==0) { printf("\\n%d Not a prime (3)\\n",i); } else if (i%5==0) { printf("\\n%d Not a prime (5)\\n",i); } else if (i%7==0) { printf("\\n%d Not a prime (7)\\n",i); } else { printf("\\nFound a prime: %d\\n",i); mycount = mycount + 1; } } pthread_mutex_lock (&count_mtx); count = count + mycount; pthread_mutex_unlock (&count_mtx); pthread_exit(0); } } int main(int argc, char *argv[]) { int i, n, n_threads; int k, nq, nr; struct thrd_data *t_arg; pthread_t *thread_id; pthread_attr_t attr; pthread_mutex_init(&count_mtx, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); printf ("enter the range n = "); scanf ("%d", &n); printf ("enter the number of threads n_threads = "); scanf ("%d", &n_threads); thread_id = (pthread_t *)malloc(sizeof(pthread_t)*n_threads); t_arg = (struct thrd_data *)malloc(sizeof(struct thrd_data)*n_threads); nq = n / n_threads; nr = n % n_threads; k = 1; for (i=0; i<n_threads; i++){ t_arg[i].id = i; t_arg[i].start = k; if (i < nr) k = k + nq + 1; else k = k + nq; t_arg[i].end = k; pthread_create(&thread_id[i], &attr, do_work, (void *) &t_arg[i]); } for (i=0; i<n_threads; i++) { pthread_join(thread_id[i], 0); } printf ("Done. Count= %d \\n", count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mtx); pthread_exit (0); }
1
#include <pthread.h> int count = 0; int count1 = 0; pthread_mutex_t lock; void * ThreadAdd(void * a) { int i, tmp; for(i = 0; i < 1000000; i++) { tmp = count; tmp = tmp+1; count = tmp; pthread_mutex_lock( &lock ); ++count1; pthread_mutex_unlock( &lock ); } return 0; } int main(int argc, char * argv[]) { pthread_t tid1, tid2; pthread_mutex_init( &lock , 0 ); if(pthread_create(&tid1, 0, ThreadAdd, 0)) { printf("\\n ERROR creating thread 1"); exit(1); } if(pthread_create(&tid2, 0, ThreadAdd, 0)) { printf("\\n ERROR creating thread 2"); exit(1); } if(pthread_join(tid1, 0)) { printf("\\n ERROR joining thread"); exit(1); } if(pthread_join(tid2, 0)) { printf("\\n ERROR joining thread"); exit(1); } pthread_mutex_destroy(&lock); if (count < 2 * 1000000) printf("\\n BOOM! count is [%d], should be %d\\n", count, 2*1000000); else printf("\\n OK! count is [%d]\\n", count); if (count1 < 2 * 1000000) printf("\\n BOOM! count1 is [%d], should be %d\\n", count1, 2*1000000); else printf("\\n OK! count1 is [%d]\\n", count1); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pileA = 5; int pileB = 0; int pileC = 0; void* monk(void *arg) { while (pileA > 0) { pthread_mutex_lock(&mutex); printf("Monk : Je passe un paquet de A à B, laisse moi bien le poser\\n"); pileA--; sleep(rand() % 5); pileB++; printf("Monk : paquet posé !\\n"); pthread_mutex_unlock(&mutex); sleep(1); } return 0; } void* impatient(void *arg) { int error; while (pileC < 5) { struct timespec absolute_time; clock_gettime(CLOCK_REALTIME, &absolute_time); absolute_time.tv_sec += 2; error = pthread_mutex_timedlock(&mutex, &absolute_time); assert(error == 0 || error == ETIMEDOUT); if (error == ETIMEDOUT) { puts("Impatient : T'es vraiment trop lent. J'vais prendre un café\\n"); sleep(1); continue; } if (pileB > 0) { pileB--; pileC++; puts("J'ai passé un paquet de B à C\\n"); } pthread_mutex_unlock(&mutex); } return 0; } int main() { srand(time(0)); pthread_t tid[2]; printf("Paquets sur les piles A=%d B=%d C=%d\\n", pileA, pileB, pileC); pthread_create(&tid[0], 0, impatient, 0); pthread_create(&tid[1], 0, monk, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); printf("Paquets sur les piles A=%d B=%d C=%d\\n", pileA, pileB, pileC); return 0; }
1
#include <pthread.h> int ticket_number; int cycles_number; pthread_mutex_t ticketMutex; pthread_cond_t condition; void printHelp() { printf("Program ocekava na prikazove radce jako prvni parametr pocet vlaken M a pocet pruchodu kritickou sekci N. N, M >= 0\\nPriklad spusteni: program 1024 100\\n"); } int getticket(void) { static int ticket = 0; int tmp_ticket; pthread_mutex_lock(&ticketMutex); tmp_ticket = ticket; ++ticket; pthread_mutex_unlock(&ticketMutex); return tmp_ticket; } void await(int aenter) { pthread_mutex_lock(&ticketMutex); while (aenter != ticket_number) { pthread_cond_wait(&condition, &ticketMutex); } } void advance(void) { ticket_number++; pthread_mutex_unlock(&ticketMutex); pthread_cond_broadcast(&condition); } void *TaskCode(void *id) { int ticket; long threadID; unsigned int seed; threadID = (long)id; seed = (long)id; while ((ticket = getticket()) < cycles_number) { nanosleep((const struct timespec[]) { {0, (rand_r(&seed) % 5001) * 100000} }, 0); await(ticket); printf("%d\\t(%ld)\\n", ticket, threadID + 1); fflush(stdout); advance(); nanosleep((const struct timespec[]) { {0, (rand_r(&seed) % 5001) * 100000} }, 0); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t *threads; pthread_attr_t attr; long *taskIDs; int rc, thread_number, threads_count; char *endptr; if (argc == 1) { printHelp(); return 0; } else if (argc != 3) { printf("Chyba pri zadavani vstupnich parametru.\\nSpustte aplikaci bez parametru pro spusteni napovedy.\\n"); return -1; } threads_count = (int)strtol(argv[1], &endptr, 10); if (!*argv[1] || *endptr || threads_count < 0) { printf("Chyba pri zadavani vstupnich parametru.\\nSpustte aplikaci bez parametru pro spusteni napovedy.\\n"); return -1; } cycles_number = (int)strtol(argv[2], &endptr, 10); if (!*argv[2] || *endptr || cycles_number < 0) { printf("Chyba pri zadavani vstupnich parametru.\\nSpustte aplikaci bez parametru pro spusteni napovedy.\\n"); return -1; } ticket_number = 0; threads = (pthread_t*)malloc(threads_count * sizeof(pthread_t)); taskIDs = (long*)malloc(threads_count * sizeof(long)); pthread_attr_init(&attr); pthread_mutex_init(&ticketMutex, 0); pthread_cond_init(&condition, 0); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (thread_number = 0; thread_number < threads_count; thread_number++) { taskIDs[thread_number] = thread_number; rc = pthread_create(&threads[thread_number], &attr, TaskCode, (void*)taskIDs[thread_number]); if (rc) { printf("Chyba s kodem \\"%d\\" pri volani funkce pthread_create()\\n", rc); exit(-1); } } pthread_attr_destroy(&attr); for (thread_number = 0; thread_number < threads_count; thread_number++) { rc = pthread_join(threads[thread_number], 0); if (rc) { printf("Chyba s kodem \\"%d\\" pri volani funkce pthread_join()\\n", rc); exit(-1); } } free(threads); free(taskIDs); pthread_cond_destroy(&condition); pthread_mutex_destroy(&ticketMutex); return 0; }
0
#include <pthread.h> pthread_mutex_t m; int s = 0; int l = 0; void* thr1(void* arg) { pthread_mutex_lock (&m); __VERIFIER_assert (l==0 || s==1); s = 1; l = 1; pthread_mutex_unlock (&m); return 0; } int main() { s = __VERIFIER_nondet_int(0, 1000); pthread_t t[5]; pthread_mutex_init (&m, 0); int i = 0; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); i++; pthread_create (&t[i], 0, thr1, 0); return 0; }
1
#include <pthread.h> const int NUM_THREADS = 3; const int NUM_INC = 10; const int COUNT_LIMIT = 12; int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_cond; void *inc_count(void *t) { int my_id = *(int*)t; for (int i = 0; i < NUM_INC; ++i){ pthread_mutex_lock(&count_mutex); count++; if (count == COUNT_LIMIT){ pthread_cond_signal(&count_cond); printf("inc_count: thread %d, count = %d Threshold reached.\\n",my_id,count); } printf("inc_count: thread %d, count = %d, unlockung mutex\\n",my_id,count); pthread_mutex_unlock(&count_mutex); sleep(1); } return 0; } void *watch_count(void *t) { int my_id = *(int*)t; printf("Starting watch_count: thread %d\\n",my_id); pthread_mutex_lock(&count_mutex); while (count < COUNT_LIMIT){ pthread_cond_wait(&count_cond, &count_mutex); printf("watch_count: thread %d signal recived.\\n",my_id); count += 125; printf("watch_count: thread %d count now = %d.\\n",my_id,count); } pthread_mutex_unlock(&count_mutex); return 0; } int main(int argc, char *argv[]) { pthread_t threads[NUM_THREADS]; int ids[NUM_THREADS]; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_cond,0); ids[0] = 0; pthread_create(&threads[0], 0, watch_count, (void *)&ids[0]); for (int i = 1; i < NUM_THREADS; ++i ){ ids[i] = i; pthread_create(&threads[i], 0, inc_count, (void *)&ids[i]); } for (int i = 0; i < NUM_THREADS; ++i){ pthread_join(threads[i],0); } printf("Main(): Waited on %d threads. Done.\\n",NUM_THREADS); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_cond); return 0; }
0
#include <pthread.h> const char *DESTINATION_FILE = "destination.txt"; pthread_mutex_t mutex; void printToFile( int lettersCount, char *sourceFile); void *readFile( void *filename ) { char *sourceFile = filename; printf("The file %s has entered to the lecture function \\n", sourceFile); FILE *openFile = fopen(sourceFile,"r"); int lettersCount = 0; char character; while( ( character = fgetc( openFile ) ) != EOF ){ lettersCount++; } fclose( openFile ); int finalLettersCount; finalLettersCount = lettersCount - 1; printToFile( finalLettersCount , sourceFile ); pthread_exit(0); } void printToFile(int lettersCount, char *sourceFile) { pthread_mutex_lock(&mutex); FILE *openDestinyFile = fopen(DESTINATION_FILE, "a"); fprintf(openDestinyFile, "EL numero de letras en el archivo %s es de: %d\\n", sourceFile, lettersCount ); fclose(openDestinyFile); pthread_mutex_unlock(&mutex); } int main(int argc, char const *argv[]){ char *fileName_1 = "f1.txt"; char *fileName_2 = "f2.txt"; char *fileName_3 = "f3.txt"; char *fileName_4 = "f4.txt"; FILE *destinyFile = fopen(DESTINATION_FILE,"w+"); fclose(destinyFile); pthread_t file_1, file_2, file_3, file_4; pthread_mutex_init(&mutex,0); pthread_create(&file_1, 0, readFile, fileName_1); pthread_create(&file_2, 0, readFile, fileName_2); pthread_create(&file_3, 0, readFile, fileName_3); pthread_create(&file_4, 0, readFile, fileName_4); pthread_join(file_1,0); pthread_join(file_2,0); pthread_join(file_3,0); pthread_join(file_4,0); pthread_mutex_destroy(&mutex); printf("End of function\\n"); return 0; }
1
#include <pthread.h> struct responce_times { struct timeval start_time; struct timeval end_time; int responce_time; }; int atack_start = 0; char *host = 0; char *path = 0; int *ilist = 0; pthread_mutex_t mutex; struct responce_times *responce_list = 0; int responce_i = 0; int debug_i = 0; void *atack(void *arg) { pid_t pid; pthread_t tid; struct sockaddr_in addr; int sock; char *msg; int l, ret; char buf[64]; ssize_t recv_size = 0; ssize_t send_size = 0; long user_id = 0; char *subpath; int i; pid = getpid(); tid = pthread_self(); pthread_mutex_lock( &mutex ); i = responce_i; responce_i++; pthread_mutex_unlock( &mutex ); subpath = malloc(100); if(subpath == 0) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : cannot do malloc().\\n", *((int*)arg), pid, (long)tid); return 0; } srand((unsigned)time(0) + syscall(SYS_gettid)); user_id = rand() % 300000; sprintf(subpath, "/api?user_id=%ld", user_id); l = strlen(host) + strlen(path) + strlen(subpath) + 64; msg = malloc(l); if(msg == 0) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : cannot do malloc().\\n", *((int*)arg), pid, (long)tid); return 0; } while( ! atack_start ) { usleep(100000); } printf("[%6d] atack. to %s %s%s: pid=%d, tid=%ld\\n", *((int*)arg), host, path, subpath, pid, (long)tid); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_family = AF_INET; addr.sin_port = htons(80); addr.sin_addr.s_addr = inet_addr(host); sock = socket(AF_INET, SOCK_STREAM, 0); gettimeofday(&responce_list[i].start_time, 0); ret = connect( sock, (struct sockaddr*)(&addr), sizeof(struct sockaddr_in) ); sprintf(msg, "GET %s%s HTTP/1.1\\r\\nHost: %s\\r\\n\\r\\n", path, subpath, host); send_size = send(sock, msg, strlen(msg), 0); printf("while前\\n"); while(1) { recv_size = recv(sock, buf, 1, 0); if(recv_size == -1) { fprintf(stderr, "[%6d] pid=%d, tid=%ld : recv() socket error.\\n", *((int*)arg), pid, (long)tid); break; } if(recv_size == 0) { printf("ブレーク\\n"); break; } } printf("while後:%d\\n",++debug_i); gettimeofday(&responce_list[i].end_time, 0); close(sock); return arg; } pthread_attr_t make_min_stack() { long default_stack_size = 10485760; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, default_stack_size); size_t stacksize; pthread_attr_getstacksize (&attr, &stacksize); return attr; } int main(int ac, char *av[]) { pid_t pid; pthread_t *tlist; void *result; int thread_num; int status; int i; int count_down; if(ac != 5) { fprintf(stderr, "Usage: %s thread_num count_down hostname path\\n", av[0]); return 1; } pthread_attr_t attr = make_min_stack(); thread_num = atoi(av[1]); if(thread_num <= 0) { fprintf(stderr, "Error: thread_num must be greater than 0.\\n"); return 1; } pthread_mutex_init( &mutex, 0 ); count_down = atoi(av[2]); if(count_down < 0) count_down = 0; host = av[3]; path = av[4]; tlist = malloc(sizeof(pthread_t) * thread_num); ilist = malloc(sizeof(int) * thread_num); responce_list = malloc(sizeof(struct responce_times) * thread_num); pid = getpid(); for(i=0; i<thread_num; i++) { ilist[i] = i; status = pthread_create(tlist+i, &attr, atack, (void*)(ilist+i)); if( status != 0 ) { fprintf(stderr, "Error: cannot create a thread: %d\\n", i); tlist[i] = 0; }else{ } } for(i=count_down; i>0; i--) { fprintf(stderr, "%d\\n", i); sleep(1); } atack_start = 1; for(i=0; i<thread_num; i++) { if(tlist[i] == 0) { continue; } pthread_join(tlist[i], &result); } pthread_mutex_destroy( &mutex ); for(i=0; i<thread_num; i++) { printf("responce time %d = %Lf\\n", i, ((long double)responce_list[i].end_time.tv_sec + (long double)responce_list[i].end_time.tv_usec * 1.0E-6) -((long double)responce_list[i].start_time.tv_sec + (long double)responce_list[i].start_time.tv_usec * 1.0E-6) ); } return 0; }
0
#include <pthread.h> pthread_mutex_t mutex, mutex2, mutex3; time_t init_time; int cnt, cnt2; void espera_activa( int tiempo) { time_t t; t = time(0) + tiempo; while(time(0) < t); } int get_the_time(){ return (time(0) - init_time); } void *tareaA( void * args) { printf("%d::A::voy a dormir\\n", get_the_time()); sleep(3); printf("%d::A::me despierto y pillo mutex\\n", get_the_time()); pthread_mutex_lock(&mutex); printf("%d::A::incremento valor\\n", get_the_time()); ++cnt; printf("%d::A::desbloqueo mutex\\n", get_the_time()); pthread_mutex_unlock(&mutex); printf("%d::A::FINISH\\n", get_the_time()); } void *tareaM( void * args) { printf("\\t%d::M::me voy a dormir\\n", get_the_time()); sleep(2); printf("\\t%d::M::me despierto y pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t%d::M::pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t%d::M::incremento variable cnt2\\n", get_the_time()); ++cnt2; printf("\\t%d::M::libero mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t%d::M::libero mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t%d::M::FINSIH\\n", get_the_time()); } void *tareaB( void * args) { printf("\\t\\t%d::B::me voy a dormir\\n", get_the_time()); sleep(1); printf("\\t\\t%d::B::me despierto y pillo mutex3\\n", get_the_time()); pthread_mutex_lock(&mutex3); printf("\\t\\t%d::B::espera activa\\n", get_the_time()); espera_activa(3); printf("\\t\\t%d::B::pillo mutex2\\n", get_the_time()); pthread_mutex_lock(&mutex2); printf("\\t\\t%d::B::incremento cnt2\\n", get_the_time()); ++cnt2; printf("\\t\\t%d::B::suelto mutex2\\n", get_the_time()); pthread_mutex_unlock(&mutex2); printf("\\t\\t%d::B::suelto mutex3\\n", get_the_time()); pthread_mutex_unlock(&mutex3); printf("\\t\\t%d::B::FINISH\\n", get_the_time()); } int main() { pthread_t hebraA, hebraM, hebraB; pthread_attr_t attr; pthread_mutexattr_t attrM; struct sched_param prio; time( &init_time); cnt = 0; cnt2 = 0; printf("===DEBUG MODO \\"ON\\"===\\nEXEC_TIME::THREAD_TAG::VERBOSE_INFO\\n\\n"); pthread_mutexattr_init(&attrM); if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_NONE) != 0) { printf("ERROR en __set_protocol\\n"); exit(-1); } pthread_mutex_init(&mutex, &attrM); pthread_mutex_init(&mutex2, &attrM); pthread_mutex_init(&mutex3, &attrM); if( pthread_attr_init( &attr) != 0) { printf("ERROR en __attr_init\\n"); exit(-1); } if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){ printf("ERROR __setinheritsched\\n"); exit(-1); } if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) { printf("ERROR __setschedpolicy\\n"); exit(-1); } int error; prio.sched_priority = 1; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam %d\\n", error); exit(-1); } if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) { printf("ERROR __pthread_create \\ttipo: %d\\n", error); exit(-1); } prio.sched_priority = 2; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } prio.sched_priority = 3; if( pthread_attr_setschedparam(&attr, &prio) != 0) { printf("ERROR __attr_setschedparam\\n"); exit(-1); } if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) { printf("ERROR __pthread_create\\n"); exit(-1); } pthread_join(hebraA, 0); pthread_join(hebraM, 0); pthread_join(hebraB, 0); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i = 0; i < 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("int_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(void) { int i; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) pthread_join(threads[i], 0); printf("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
0
#include <pthread.h> extern int make_thread( void *(*)(void *), void * ); struct Info { void (*func)( void * ); void *arg; struct timespec time2wait; }; void *timeout_helper( void *arg ) { struct Info *tip; tip = (struct Info *) arg; nanosleep( &tip->time2wait, 0 ); (*tip->func)(tip->arg); return (void *)0; } void timeout( const struct timespec *when, void (*func)(void *), void *arg ) { struct timespec now; struct timeval tv; struct Info *tip; gettimeofday( &tv, 0 ); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ( (when->tv_sec > now.tv_sec) || ((when->tv_sec == now.tv_sec) && (when->tv_nsec > now.tv_nsec)) ) { tip = (struct Info *) malloc( sizeof( struct Info ) ); if ( tip != 0 ) { tip->func = func; tip->arg = arg; tip->time2wait.tv_sec = when->tv_sec - now.tv_sec; if ( when->tv_nsec >= now.tv_nsec ) { tip->time2wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->time2wait.tv_sec--; tip->time2wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } if ( make_thread( timeout_helper, (void *) tip ) == 0 ) { return; } } } (*func)( arg ); } static pthread_mutexattr_t attr; static pthread_mutex_t mutex; void retry( void *arg ) { pthread_mutex_lock( &mutex ); pthread_mutex_unlock( &mutex ); } int main( void ) { int err, condition, arg; struct timespec when; if ( (err = pthread_mutexattr_init( &attr )) != 0 ) { err_exit( err, "pthread_mutexattr_init failed" ); } if ( (err = pthread_mutexattr_settype( &attr, PTHREAD_MUTEX_RECURSIVE )) != 0 ) { err_exit( err, "cannot set recursive type" ); } if ( (err = pthread_mutex_init( &mutex, &attr )) != 0 ) { err_exit( err, "cannot create recursive mutex" ); } pthread_mutex_lock( &mutex ); if ( condition ) { timeout( &when, retry, (void *) arg ); } pthread_mutex_unlock( &mutex ); return 0; } extern int make_thread( void *(*fn)(void *), void *arg ) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init( &attr ); if ( err != 0 ) { return err; } err = pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); if ( err == 0 ) { err = pthread_create( &tid, &attr, fn, arg ); } pthread_attr_destroy( &attr ); return err; }
1
#include <pthread.h> int g_buffer[10]; unsigned short in = 0; unsigned short out = 0; unsigned short produce_id = 0; unsigned short consume_id = 0; sem_t g_sem_full; sem_t g_sem_empty; pthread_mutex_t g_mutex; pthread_t g_thread[1 +1]; void* consume(void *arg) { int i; int num = (int)arg; while (1) { printf("%d wait buffer not empty\\n", num); sem_wait(&g_sem_empty); pthread_mutex_lock(&g_mutex); for (i=0; i<10; i++) { printf("%02d ", i); if (g_buffer[i] == -1) printf("%s", "null"); else printf("%d", g_buffer[i]); if (i == out) printf("\\t<--consume"); printf("\\n"); } consume_id = g_buffer[out]; printf("%d begin consume product %d\\n", num, consume_id); g_buffer[out] = -1; out = (out + 1) % 10; printf("%d end consume product %d\\n", num, consume_id); pthread_mutex_unlock(&g_mutex); sem_post(&g_sem_full); sleep(1); } return 0; } void* produce(void *arg) { int num = (int)arg; int i; while (1) { printf("%d wait buffer not full\\n", num); sem_wait(&g_sem_full); pthread_mutex_lock(&g_mutex); for (i=0; i<10; i++) { printf("%02d ", i); if (g_buffer[i] == -1) printf("%s", "null"); else printf("%d", g_buffer[i]); if (i == in) printf("\\t<--produce"); printf("\\n"); } printf("%d begin produce product %d\\n", num, produce_id); g_buffer[in] = produce_id; in = (in + 1) % 10; printf("%d end produce product %d\\n", num, produce_id++); pthread_mutex_unlock(&g_mutex); sem_post(&g_sem_empty); sleep(5); } return 0; } int main(void) { int i; for (i=0; i<10; i++) g_buffer[i] = -1; sem_init(&g_sem_full, 0, 10); sem_init(&g_sem_empty, 0, 0); pthread_mutex_init(&g_mutex, 0); for (i=0; i<1; i++) pthread_create(&g_thread[i], 0, consume, (void*)i); for (i=0; i<1; i++) pthread_create(&g_thread[1 +i], 0, produce, (void*)i); for (i=0; i<1 +1; i++) pthread_join(g_thread[i], 0); sem_destroy(&g_sem_full); sem_destroy(&g_sem_empty); pthread_mutex_destroy(&g_mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; int best_rank; int cnt; long int tid; } Leader; Leader* leader; sem_t* barrier; int randomRank(int max); void* thRoutine(void* thArg); int main(int argc, char** argv) { int *arg, i, j, k, ranks[10]; pthread_t th; srand(time(0)); leader = (Leader*)malloc(sizeof(Leader)); pthread_mutex_init(&leader->mutex, 0); leader->best_rank = 0; leader->cnt = 0; barrier = (sem_t*)malloc(sizeof(sem_t)); sem_init(barrier, 0, 0); for (i=0; i<10; i++) { ranks[i] = i; } k = 10; for (i=0; i<10; i++) { arg = (int*)malloc(sizeof(int)); j = randomRank(k); *arg = ranks[i] + 1; ranks[j] = ranks[--k]; pthread_create(&th, 0, (void*)thRoutine, (void*)arg); } pthread_exit(0); } int randomRank(int max) { int r; r = rand() % max; return (int)r; } void* thRoutine(void* thArg) { int* rank = (int*)thArg; int i; long int id; id = pthread_self(); pthread_detach(pthread_self()); pthread_mutex_lock(&leader->mutex); if (leader->best_rank < *rank) { leader->best_rank = *rank; leader->tid = id; } leader->cnt++; if (leader->cnt == 10) { for(i=0; i<10; i++) { sem_post(barrier); } } pthread_mutex_unlock(&leader->mutex); sem_wait(barrier); fprintf(stdout, "Thread ID: %ld\\tThread Rank: %d\\tLeader ID: %ld\\tLeader Rank: %d\\n", id, *rank, leader->tid, leader->best_rank); pthread_exit((void*)0); }
1
#include <pthread.h> struct QueueEntry { char* string; int empty; int timestamp; }; struct QueueEntry Q[3]; pthread_mutex_t Q_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t signal_mutex = PTHREAD_MUTEX_INITIALIZER; int g_timestamp = 0; void Q_init(); void Q_clear(); void Q_add(const char*); void* thread1(void* arg); void* thread2(void* arg); int main() { Q_init(); pthread_t thread; pthread_create(&thread, 0, thread2, 0); thread1(0); pthread_join(thread, 0); return 0; } void* thread1(void* arg) { Q_add("data 0"); Q_add("data 1"); Q_add("data 2"); Q_add("data 3"); Q_add("data 4"); Q_clear(); return 0; } void* thread2(void* arg) { Q_add("data 5"); Q_add("data 6"); Q_add("data 7"); Q_add("data 8"); Q_add("data 9"); Q_clear(); return 0; } void Q_init() { int i; for (i = 0; i < 3; i++) { Q[i].string = 0; Q[i].empty = 1; Q[i].timestamp = 0; } } void Q_clear() { Q_init(); } int Q_full() { pthread_mutex_lock(&Q_mutex); int idx; int ret = 1; for (idx = 0; idx < 3; idx++) if (Q[idx].empty) ret = 0; pthread_mutex_unlock(&Q_mutex); return ret; } void Q_discard_oldest() { int discardidx; int discardts; int idx; pthread_mutex_lock(&Q_mutex); discardidx = 0; discardts = Q[0].timestamp; for (idx = 1; idx < 3; idx++) if (discardts > Q[idx].timestamp) { discardidx = idx; discardts = Q[idx].timestamp; } fputs ("discard ", stdout); fputs (Q[discardidx].string, stdout); fputs ("\\n", stdout); free(Q[discardidx].string); Q[discardidx].empty = 1; Q[discardidx].string = 0; Q[discardidx].timestamp = 0; pthread_mutex_unlock(&Q_mutex); } void Q_add(const char* s) { if (Q_full()) Q_discard_oldest(); pthread_mutex_lock(&Q_mutex); int idx; for (idx = 0; idx < 3; idx++) { if (Q[idx].empty) break; } Q[idx].empty = 0; Q[idx].timestamp = ++g_timestamp; Q[idx].string = strdup(s); fputs ("add ", stdout); fputs (Q[idx].string, stdout); fputs ("\\n", stdout); pthread_mutex_unlock(&Q_mutex); }
0
#include <pthread.h> int quit,sum,j; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc =PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { printf("thr_fn\\n"); if (j==0){ printf("the init j success\\n"); while(j<101){ pthread_mutex_lock(&lock); sum += j; pthread_mutex_unlock(&lock); j++; } pthread_mutex_lock(&lock); printf("the sum:%d\\n", sum); pthread_mutex_unlock(&lock); } pthread_exit((void *)0); } int main(int argc, char **argv) { int i,err,num =0; pthread_t tid[i]; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err) return(err); err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); if (err==0){ for (int i = 0; i < 5; ++i) { err = pthread_create(&tid[i],&attr,thr_fn,(void *)&num); if (err) { printf("craete err\\n"); } } }else printf("set pthread detach failed\\n"); pthread_attr_destroy(&attr); sleep(1); for (int i = 5; i >0; --i) { printf("wait the thread:%d\\n", i); err = pthread_join(tid[i],(void *)&err); if (!err) { printf("wait success thread :%d\\n",i); } } return 0; }
1
#include <pthread.h> pthread_t thread_id; int id, arr, run, prio; }Flow; void init(char *str, Flow *flow); int flowComp(const void *A, const void *B); int comp(const Flow *flowA, const Flow *flowB); static void start(Flow *self); void finish(); int flowComp(const void *A, const void *B); void control(Flow *flow); int main(int argc, char *argv[]); pthread_mutex_t mu1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mu2 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t idle = PTHREAD_COND_INITIALIZER; int status = 1; int currID; Flow *waiting[100]; int numWait = 0; void init(char *str, Flow *flow){ flow->id = strtonum(strtok(str,":"), 1, 32767, 0); flow->arr = strtonum(strtok(0,","), 1, 32767, 0); flow->run = strtonum(strtok(0,","), 1, 32767, 0); flow->prio = strtonum(str, 1, 32767, 0); int x = atoi(strtok(str,":")); printf("%d \\n", x); } int flowComp(const void *A, const void *B){ return comp((Flow *) A, (Flow *) B); } int comp(const Flow *flowA, const Flow *flowB){ do{ if(flowA->prio < flowB->prio){ return -1; } else if(flowA->prio > flowB->prio){ return 1; } else if(flowA->prio == flowB->prio){ do{ if(flowA->arr > flowB->arr){ return -1; } else if(flowA->arr < flowB->arr){ return 1; } else if(flowA->arr == flowB->arr){ do{ if(flowA->run > flowB->run){ return -1; } else if(flowA->run < flowB->run){ return 1; } else if(flowA->run == flowB->run){ do{ if(flowA->id > flowB->id){ return -1; } else if(flowA->id < flowB->id){ return 1; } else if(flowA->id == flowB->id){ return 0; } }while(0); } }while(0); } }while(0); } }while(0); return 0; } static void start(Flow *self){ pthread_mutex_lock(&mu1); if(status == 1 && numWait == 0){ status = 0; pthread_mutex_unlock(&mu1); return; } pthread_mutex_lock(&mu2); waiting[numWait] = self; numWait++; qsort(waiting, numWait, sizeof(Flow), flowComp); pthread_mutex_unlock(&mu2); while(status == 0 || comp(waiting[0], self) != 0){ printf("Flow %2d waits for the finish of flow %2d. \\n", self->id, currID); pthread_cond_wait(&status, &mu1); } waiting[0] = waiting[numWait-1]; qsort(waiting, numWait, sizeof(Flow), flowComp); status = 0; numWait--; pthread_mutex_unlock(&mu1); } void finish(){ pthread_mutex_lock(&mu1); status = 1; pthread_mutex_unlock(&mu1); pthread_cond_broadcast(&status); } void * flowCTRL(void *flow){ control((Flow *) flow); return 0; } void control(Flow *flow){ struct timespec arrival, service, removal; time_t t; arrival.tv_nsec = flow->arr *1000 *1000; service.tv_nsec = flow->run *1000 *1000; nanosleep(&arrival, &removal); printf("Flow %2d arrives: arrival time (%.2f), transmission time (%.1f), priority (%2d). \\n", flow->id, flow->arr, flow->run, flow->prio); start(flow); currID = flow->id; time(&t); printf("Flow %2d starts its transmission at time %.2f. \\n", flow->id, ctime(&t)); nanosleep(&service, &removal); time(&t); printf("Flow %2d finishes its transmission at time %d. \\n", flow->id, ctime(&t)); finish(); } int main(int argc, char *argv[]){ FILE *f; char *l; size_t len = 0; Flow *flow; if(argc < 2){ errx(1, "Error"); } f = fopen(argv[1], "r"); getline(&l, &len, f); printf("File opened"); while(getline(&l, &len, &f) != -1){ flow = (Flow *)malloc(sizeof(flow)); init(l, flow); pthread_create(&flow->thread_id, 0, flowCTRL, flow); } free(l); fclose(f); pthread_exit(0); return 0; }
0
#include <pthread.h> struct jack_ringbuffer* jack_output_buffer; pthread_mutex_t jack_output_buffer_mutex; int jack_put_bytes=0; int jack_get_bytes=0; struct jack_ringbuffer* new_jack_ringbuffer(int n) { struct jack_ringbuffer* buffer; buffer=malloc(sizeof(struct jack_ringbuffer)); if(buffer!=0) { buffer->size=n; buffer->entries=0; buffer->buffer_1=malloc(sizeof(float)*n); buffer->buffer_2=malloc(sizeof(float)*n); buffer->buffer_3=malloc(sizeof(float)*n); buffer->buffer_4=malloc(sizeof(float)*n); buffer->insert_index=0; buffer->remove_index=0; } return buffer; } int jack_ringbuffer_space(struct jack_ringbuffer* buffer) { return buffer->size-buffer->entries; } int jack_ringbuffer_entries(struct jack_ringbuffer* buffer) { return buffer->entries; } int jack_ringbuffer_put(float f1,float f2,float f3,float f4) { int i; pthread_mutex_lock(&jack_output_buffer_mutex); jack_put_bytes+=sizeof(float); if(jack_ringbuffer_space(jack_output_buffer)>1) { jack_output_buffer->buffer_1[jack_output_buffer->insert_index]=f1; jack_output_buffer->buffer_2[jack_output_buffer->insert_index]=f2; jack_output_buffer->buffer_3[jack_output_buffer->insert_index]=f3; jack_output_buffer->buffer_4[jack_output_buffer->insert_index]=f4; jack_output_buffer->entries++; jack_output_buffer->insert_index++; if(jack_output_buffer->insert_index>=jack_output_buffer->size) { jack_output_buffer->insert_index=0; } i=4; } else { i=0; } pthread_mutex_unlock(&jack_output_buffer_mutex); if(debug_buffers) fprintf(stderr,"jack_ringbuffer_put: insert_index=%d remove_index=%d entries=%d space=%d\\n",jack_output_buffer->insert_index,jack_output_buffer->remove_index,jack_ringbuffer_entries(jack_output_buffer),jack_ringbuffer_space(jack_output_buffer)); return i; } int jack_ringbuffer_get(float* f1,float* f2,float* f3,float*f4,int nframes,int buffer_count) { int entries; pthread_mutex_lock(&jack_output_buffer_mutex); entries=nframes; if(jack_output_buffer->entries<nframes) { entries=jack_output_buffer->entries; fprintf(stderr,"jack_ringbuffer_get: buffer=%d wanted %d got %d\\n",buffer_count,nframes,entries); } jack_get_bytes+=entries*sizeof(float); if(debug_buffers) fprintf(stderr,"jack_ring_buffer_get space=%d entries=%d total=%d\\n",jack_ringbuffer_space(jack_output_buffer),jack_ringbuffer_entries(jack_output_buffer),jack_get_bytes); if((jack_output_buffer->remove_index+entries)<=jack_output_buffer->size) { memcpy(f1,&jack_output_buffer->buffer_1[jack_output_buffer->remove_index],entries*sizeof(float)); memcpy(f2,&jack_output_buffer->buffer_2[jack_output_buffer->remove_index],entries*sizeof(float)); memcpy(f3,&jack_output_buffer->buffer_3[jack_output_buffer->remove_index],entries*sizeof(float)); memcpy(f4,&jack_output_buffer->buffer_4[jack_output_buffer->remove_index],entries*sizeof(float)); } else { memcpy(f1,&jack_output_buffer->buffer_1[jack_output_buffer->remove_index],(jack_output_buffer->size-jack_output_buffer->remove_index)*sizeof(float)); memcpy(f2,&jack_output_buffer->buffer_2[jack_output_buffer->remove_index],(jack_output_buffer->size-jack_output_buffer->remove_index)*sizeof(float)); memcpy(f3,&jack_output_buffer->buffer_3[jack_output_buffer->remove_index],(jack_output_buffer->size-jack_output_buffer->remove_index)*sizeof(float)); memcpy(f4,&jack_output_buffer->buffer_4[jack_output_buffer->remove_index],(jack_output_buffer->size-jack_output_buffer->remove_index)*sizeof(float)); memcpy(&f1[jack_output_buffer->size-jack_output_buffer->remove_index],jack_output_buffer->buffer_1,(entries-(jack_output_buffer->size-jack_output_buffer->remove_index))*sizeof(float)); memcpy(&f2[jack_output_buffer->size-jack_output_buffer->remove_index],jack_output_buffer->buffer_2,(entries-(jack_output_buffer->size-jack_output_buffer->remove_index))*sizeof(float)); memcpy(&f3[jack_output_buffer->size-jack_output_buffer->remove_index],jack_output_buffer->buffer_3,(entries-(jack_output_buffer->size-jack_output_buffer->remove_index))*sizeof(float)); memcpy(&f4[jack_output_buffer->size-jack_output_buffer->remove_index],jack_output_buffer->buffer_4,(entries-(jack_output_buffer->size-jack_output_buffer->remove_index))*sizeof(float)); } jack_output_buffer->entries-=entries; jack_output_buffer->remove_index+=entries; if(jack_output_buffer->remove_index>=jack_output_buffer->size) { jack_output_buffer->remove_index-=jack_output_buffer->size; } pthread_mutex_unlock(&jack_output_buffer_mutex); return entries; } int create_jack_ringbuffer(int n) { if(debug) fprintf(stderr,"create_jack_ringbuffer: entry: %d\\n",n); pthread_mutex_init(&jack_output_buffer_mutex, 0); jack_output_buffer=new_jack_ringbuffer(n); if(debug) fprintf(stderr,"create_jack_ringbuffer: exit\\n"); }
1
#include <pthread.h> struct lectred { pthread_mutex_t m; pthread_cond_t cl, ce; int ecriture; int nb_lecteurs, nb_lect_att, nb_ecri_att; }; struct linked_list { int nb; struct linked_list *next; }; struct linked_list_head { struct lectred sync; struct linked_list *head; }; struct linked_list_head liste; void init(struct lectred* l) { pthread_mutex_init(&(l->m), 0); pthread_cond_init(&(l->cl), 0); pthread_cond_init(&(l->ce), 0); l->ecriture = 0; l->nb_lect_att = 0; l->nb_ecri_att = 0; l->nb_lecteurs = 0; } void begin_read(struct lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1){ l->nb_lect_att++; pthread_cond_wait(&(l->cl), &(l->m)); l->nb_lect_att--; } l->nb_lecteurs++; pthread_mutex_unlock(&(l->m)); } void end_read(struct lectred* l) { pthread_mutex_lock(&(l->m)); printf("Fin lecture\\n"); l->nb_lecteurs--; if(l->nb_lect_att == 0){ pthread_cond_signal(&(l->cl)); } pthread_mutex_unlock(&(l->m)); } void begin_write(struct lectred* l) { pthread_mutex_lock(&(l->m)); while(l->ecriture == 1 || l->nb_lecteurs > 0 || l->nb_lect_att > 0){ l->nb_ecri_att++; pthread_cond_wait(&(l->ce), &(l->m)); l->nb_ecri_att--; } l->ecriture = 1; pthread_mutex_unlock(&(l->m)); } void end_write(struct lectred* l) { pthread_mutex_lock(&(l->m)); l->ecriture = 0; printf("Fin écriture\\n"); 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(struct linked_list_head *list) { list->head = 0; init(&list->sync); } int exists(struct linked_list_head *list, int val) { struct linked_list *p; begin_read(&list->sync); p = list->head; while(p != 0) { if (p->nb == val) { end_read(&list->sync); return 1; } p = p->next; } end_read(&list->sync); return 0; } void add_element(struct linked_list_head *list, struct linked_list *l) { struct linked_list **p, **prec; begin_write(&list->sync); prec = 0; p = &list->head; while((*p) != 0) { prec = p; p = &(*p)->next; } if (prec != 0) { (*prec)->next = l; } else { list->head = l; } sleep(rand()%2); end_write(&list->sync); } struct linked_list* remove_element(struct linked_list_head *list, int val) { struct linked_list **p, *ret = 0; begin_write(&list->sync); p = &list->head; while((*p) != 0) { if ((*p)->nb == val) { ret = *p; *p = (*p)->next; break; } p = &(*p)->next; } sleep(rand()%2); end_write(&list->sync); return ret; } void* lecture(void* arg) { pthread_t tid = pthread_self () ; srand ((int) tid) ; int val = rand()%2 + 1; if (exists(&liste, val)) { printf("Lecteur %lu, cherche valeur %d dans la liste : présente\\n", (unsigned long) tid, val); } else { printf("Lecteur %lu, cherche valeur %d dans la liste : non présente\\n", (unsigned long) tid, val); } return 0; } void* ecriture(void* arg) { pthread_t tid = pthread_self () ; srand ((int) tid) ; int val = rand()%2; if (val) { val = rand()%2 + 1; printf("Rédacteur %lu, ajoute la valeur %d dans la liste\\n", (unsigned long) tid, val); struct linked_list *l; l = malloc(sizeof(struct linked_list)); l->nb = val; l->next = 0; add_element(&liste, l); } else { val = rand()%2 + 1; struct linked_list *l; if ((l = remove_element(&liste, val)) != 0) { printf("Rédacteur %lu, supprime la valeur %d dans la liste si elle existe : réussi\\n", (unsigned long) tid, val); free(l); } else { printf("Rédacteur %lu, supprime la valeur %d dans la liste si elle existe : raté\\n", (unsigned long) tid, val); } } return 0; } int main (int argc, char** argv) { int i, nb_lecteur, nb_redacteur; pthread_t *tid_lecteur; pthread_t *tid_redacteur; if (argc != 3 && (atoi(argv[1]) <= 0 || atoi(argv[2]) <= 0)) { printf("usage: %s <nb_lecteur> <nd_redacteur>\\n\\t- nb_lecteur et nb_redacteur > 0\\n", argv[0]); return 0; } list_init(&liste); nb_lecteur = atoi(argv[1]); nb_redacteur = atoi(argv[2]); tid_lecteur = malloc(nb_lecteur * sizeof(pthread_t)); tid_redacteur = malloc(nb_redacteur * sizeof(pthread_t)); for(i=0; i < nb_lecteur; i++) { pthread_create(&tid_lecteur[i], 0, lecture, 0); } for(i=0; i < nb_redacteur; i++) { pthread_create(&tid_redacteur[i], 0, ecriture, 0); } for(i=0; i < nb_lecteur; i++) { pthread_join(tid_lecteur[i], 0); } for(i=0; i < nb_redacteur; i++) { pthread_join(tid_redacteur[i], 0); } free(tid_lecteur); free(tid_redacteur); return 1; }
0
#include <pthread.h> { int start, end, *q, pos; }table_s, *table; int nbthread = 4, n = 20; int *rethread; { int i; pthread_mutex_t *mutex; }patate_s, *patate; int *rethread; patate o; int sumseq(int *q, int n) { int ret=0; for (int i=0 ; i< n ; i++) ret += q[i]; return ret; } void *sum(void *a) { int ret = 0; table s = (table)a; for(int i=s->start ; i<=s->end ; i++) ret += s->q[i]; pthread_mutex_lock(o->mutex); rethread[o->i] = ret; o->i++; pthread_mutex_unlock(o->mutex); return 0; } int sumthread(int *q, int n) { pthread_t tids[nbthread]; table *s = malloc(sizeof(table_s)*nbthread); for(int i=0 ; i<nbthread ; i++) { s[i] = malloc(sizeof(table_s)); s[i]->q = q; s[i]->start = i*(n/nbthread); s[i]->end = (i+1)*(n/nbthread) -1; s[i]->pos = i; pthread_create(&tids[i], 0, sum, s[i]); } for(int i = 0 ; i<nbthread ; i++) { pthread_join (tids[i], 0); free(s[i]); } free(s); return sumseq(rethread, nbthread); } int main(int argc, char *argv[]) { o = malloc(sizeof(patate_s)); o->mutex = malloc(sizeof(pthread_mutex_t)); srand(time(0)); if (argc < 3) printf("strarting with n = 20 and nbthread = 4\\n"); else if (argc == 3) { n = atoi(argv[1]); nbthread = atoi(argv[2]); printf("strarting with n = %i and nbthread = %i\\n", n, nbthread); } else { printf("to many values.\\n use : ./main n nbthread\\n"); exit(0); } rethread = malloc(sizeof(int)*nbthread); int q[n]; for(int i=0; i<n ; i++) q[i] = rand()%40; time_t a, b; a = time(0); int reta = sumseq(q,n); a = time(0) - a; b = time(0); int retb = sumthread(q,n); b = time(0) - b; if (reta == retb) printf("patate\\n"); else printf("papillon\\n"); printf("executed linear sum in %i ms and threaded sum in %i ms\\n", (int)a, (int)b); return 0; }
1
#include <pthread.h> void *ssu_loop1(void *arg); void *ssu_loop2(void *arg); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int shared_value; int main(void) { pthread_t tid1, tid2; int status; shared_value = 0; if(pthread_create(&tid1, 0, ssu_loop1, 0) != 0) { fprintf(stderr, "pthread_create error\\n"); exit(1); } sleep(1); if(pthread_create(&tid2, 0, ssu_loop2, 0) != 0) { fprintf(stderr, "pthread_create error\\n"); exit(1); } if(pthread_join(tid1, (void *)&status) != 0) { fprintf(stderr, "pthread_join error\\n"); exit(1); } if(pthread_join(tid2, (void *)&status) != 0) { fprintf(stderr, "pthread_join error 2\\n"); exit(1); } status = pthread_mutex_destroy(&mutex); printf("code = %d\\n", status); printf("programming is end\\n"); exit(0); } void *ssu_loop1(void *arg) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("loop1 : %d\\n", shared_value); shared_value++; if(i == 10) return 0; pthread_mutex_unlock(&mutex); sleep(1); } return 0; } void *ssu_loop2(void *arg) { int i; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); printf("loop2 : %d\\n", shared_value); shared_value++; pthread_mutex_unlock(&mutex); sleep(2); } return 0; }
0
#include <pthread.h> struct timeval startread,startcalc,finish,readtime,calctime,overalltime; int n,a[100],value;int thread_count,count; pthread_mutex_t mutex; void *t1(void *x) { int i=(int)x; int k; if(i==thread_count-1) { for(k=(i)*(n);k<count;k++){ if(a[k]==3) { pthread_mutex_lock (&mutex); value++; pthread_mutex_unlock (&mutex); } }} else { for(k=(i)*(n);k<(i+1)*(n);k++) { if(a[k]==3) { pthread_mutex_lock (&mutex); value++; pthread_mutex_unlock (&mutex); } } } } void main(int argc ,char *argv[] ) { FILE *fp,*fp1; if(argc!=2){ printf("Arguments not sufficient\\n"); exit(0); } thread_count=*argv[1]-48; pthread_t p[thread_count]; fp=fopen("/home/sunny/number.txt","r"); int c;char d;int i=0; if(fp==0) { printf("File empty"); } while(fscanf(fp,"%c",&d)!=EOF) { if(d=='\\n') count++; } fclose(fp); fp1=fopen("/home/sunny/number.txt","r"); if(fp1==0) { printf("File empty"); } gettimeofday(&startread,0); while(fscanf(fp1,"%d",&c)!=EOF) { a[i]=c; i++; } fclose(fp1); gettimeofday(&startcalc,0); n=count/(thread_count); for(i=0;i<thread_count;i++) { pthread_create(&p[i],0,t1,(void *)i); } for(i=0;i<thread_count;i++) { pthread_join(p[i],0); } gettimeofday(&finish,0); timersub(&startcalc,&startread,&readtime); timersub(&finish,&startread,&overalltime); timersub(&finish,&startcalc,&calctime); printf("Reading time : %ld.%03ld \\n",readtime.tv_sec,readtime.tv_usec); printf("calculation time : %ld.%03ld \\n",calctime.tv_sec,calctime.tv_usec); printf("Overall time : %ld.%03ld \\n",overalltime.tv_sec,overalltime.tv_usec); printf("Count:%d ",count); printf("No.of 3's: %d\\n",value); }
1
#include <pthread.h> struct udp_splice_handle { pthread_mutex_t lock; int sock; uint16_t id; }; static int udp_splice_get_family_id(int sock) { struct { struct nlmsghdr nl; char buf[4096]; } buf; struct genlmsghdr *genl; struct rtattr *rta; struct sockaddr_nl addr = { .nl_family = AF_NETLINK, }; int len; memset(&buf.nl, 0, sizeof(buf.nl)); buf.nl.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN); buf.nl.nlmsg_flags = NLM_F_REQUEST; buf.nl.nlmsg_type = GENL_ID_CTRL; genl = (struct genlmsghdr *)buf.buf; memset(genl, 0, sizeof(*genl)); genl->cmd = CTRL_CMD_GETFAMILY; rta = (struct rtattr *)(genl + 1); rta->rta_type = CTRL_ATTR_FAMILY_NAME; rta->rta_len = RTA_LENGTH(sizeof(UDP_SPLICE_GENL_NAME)); memcpy(RTA_DATA(rta), UDP_SPLICE_GENL_NAME, sizeof(UDP_SPLICE_GENL_NAME)); buf.nl.nlmsg_len += rta->rta_len; if (sendto(sock, &buf, buf.nl.nlmsg_len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) goto err; len = recv(sock, &buf, sizeof(buf), 0); if (len < 0) goto err; if (len < sizeof(buf.nl) || buf.nl.nlmsg_len != len) { errno = EBADMSG; goto err; } if (buf.nl.nlmsg_type == NLMSG_ERROR) { struct nlmsgerr *errmsg = (struct nlmsgerr *)buf.buf; errno = -errmsg->error; goto err; } len -= sizeof(buf.nl) + sizeof(*genl); while (RTA_OK(rta, len)) { if (rta->rta_type == CTRL_ATTR_FAMILY_ID) return *(uint16_t *)RTA_DATA(rta); rta = RTA_NEXT(rta, len); } errno = EBADMSG; err: return -1; } void *udp_splice_open(void) { struct udp_splice_handle *h; int retval; struct sockaddr_nl addr; h = malloc(sizeof(*h)); if (!h) goto err; retval = pthread_mutex_init(&h->lock, 0); if (retval) { errno = retval; goto err2; } h->sock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, NETLINK_GENERIC); if (h->sock < 0) goto err3; memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; if (bind(h->sock, (struct sockaddr *)&addr, sizeof(addr))) goto err4; retval = udp_splice_get_family_id(h->sock); if (retval < 0) goto err4; h->id = retval; return h; err4: close(h->sock); err3: pthread_mutex_destroy(&h->lock); err2: free(h); err: return 0; } int udp_splice_add(void *handle, int sock, int sock2, uint32_t timeout) { struct { struct nlmsghdr nl; struct genlmsghdr genl; char attrs[RTA_LENGTH(4) * 3]; } req; struct { struct nlmsghdr nl; struct nlmsgerr err; } res; struct rtattr *rta; struct sockaddr_nl addr = { .nl_family = AF_NETLINK, }; int len; struct udp_splice_handle *h = handle; memset(&req, 0, sizeof(req.nl) + sizeof(req.genl)); req.nl.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN); req.nl.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nl.nlmsg_type = h->id; req.genl.cmd = UDP_SPLICE_CMD_ADD; rta = (struct rtattr *)req.attrs; rta->rta_type = UDP_SPLICE_ATTR_SOCK; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = sock; req.nl.nlmsg_len += rta->rta_len; rta = (struct rtattr *)(((char *)rta) + rta->rta_len); rta->rta_type = UDP_SPLICE_ATTR_SOCK2; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = sock2; req.nl.nlmsg_len += rta->rta_len; if (timeout) { rta = (struct rtattr *)(((char *)rta) + rta->rta_len); rta->rta_type = UDP_SPLICE_ATTR_TIMEOUT; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = timeout; req.nl.nlmsg_len += rta->rta_len; } pthread_mutex_lock(&h->lock); if (sendto(h->sock, &req, req.nl.nlmsg_len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) len = -1; else len = recv(h->sock, &res, sizeof(res), 0); pthread_mutex_unlock(&h->lock); if (len < 0) goto err; if (len != sizeof(res) || res.nl.nlmsg_type != NLMSG_ERROR) { errno = EBADMSG; goto err; } if (res.err.error) { errno = -res.err.error; goto err; } return 0; err: return -1; } static int udp_splice_do(void *handle, uint8_t cmd, int sock) { struct { struct nlmsghdr nl; struct genlmsghdr genl; union { char buf[RTA_LENGTH(4)]; struct rtattr rta; }; } req; struct { struct nlmsghdr nl; struct nlmsgerr err; } res; struct sockaddr_nl addr = { .nl_family = AF_NETLINK, }; int len; struct udp_splice_handle *h = handle; memset(&req, 0, sizeof(req.nl) + sizeof(req.genl)); req.nl.nlmsg_len = sizeof(req); req.nl.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nl.nlmsg_type = h->id; req.genl.cmd = cmd; req.rta.rta_type = UDP_SPLICE_ATTR_SOCK; req.rta.rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(&req.rta) = sock; pthread_mutex_lock(&h->lock); if (sendto(h->sock, &req, req.nl.nlmsg_len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) len = -1; else len = recv(h->sock, &res, sizeof(res), 0); pthread_mutex_unlock(&h->lock); if (len < 0) goto err; if (len != sizeof(res) || res.nl.nlmsg_type != NLMSG_ERROR) { errno = EBADMSG; goto err; } if (res.err.error) { errno = -res.err.error; goto err; } return 0; err: return -1; } int udp_splice_get(void *handle, int sock) { return udp_splice_do(handle, UDP_SPLICE_CMD_GET, sock); } int udp_splice_delete(void *handle, int sock) { return udp_splice_do(handle, UDP_SPLICE_CMD_DELETE, sock); } void udp_splice_close(void *handle) { struct udp_splice_handle *h = handle; close(h->sock); pthread_mutex_destroy(&h->lock); free(h); }
0
#include <pthread.h> void search_by_thread( void* ptr); { char* start_ptr; char* end_ptr; int slice_id; } slice_data; { char* start_ptr; char* end_ptr; int thread_id; int num_slices; char match_str[16]; char* array_address; slice_data* slice_struct_address; } thread_data; int slice_counter = 0; pthread_mutex_t mutex; pthread_mutex_t mutex2; int main() { FILE* fRead; char line[16]; char search_str[16]; char* array_ptr; char* temp_ptr; int i = 0; int j = 0; int fchar; int num_inputs = 0; int num_threads; int num_slices; int slice_size = 0; double time; fRead = fopen("fartico_aniketsh_input_partB.txt", "r"); Timer_start(); while(EOF != (fchar = fgetc(fRead))) {if ( fchar == '\\n'){++num_inputs;}} if ( fchar != '\\n' ){++num_inputs;} fclose(fRead); if ( num_inputs > 4 ) { num_inputs = num_inputs -3; } fRead = fopen("fartico_aniketsh_input_partB.txt", "r"); num_threads = fgetc(fRead) - 48; fgetc(fRead); fgets(line, sizeof(line), fRead); num_slices = atoi(line); fgets(search_str, sizeof(search_str), fRead); array_ptr = malloc(num_inputs * sizeof(line)); memset(array_ptr, '\\0', num_inputs * sizeof(line)); temp_ptr = array_ptr; slice_size = num_inputs / num_slices; while(fgets(line, sizeof(line), fRead)) { strcpy(&temp_ptr[i*16], line); i++; } Timer_elapsedUserTime(&time); while(&temp_ptr[j*16] < &temp_ptr[i*16]) { j++; } printf("\\n\\nITEMS STORED: %d ITEMS PRINTED: %d\\n",i, j); printf("MEMORY USED: %d\\n", (&temp_ptr[i*16] - temp_ptr)); printf("TIME TO STORE: %g\\n", time); printf("INPUTS: %d\\n", num_inputs); printf("THREADS: %d\\n", num_threads); printf("SLICES: %d\\n", num_slices); printf("SEARCH STR: %s", search_str); printf("SIZE OF SLICES: %d\\n\\n", slice_size); pthread_t thread_array[num_threads]; thread_data data_array[num_threads]; slice_data slice_array[num_slices]; int k; for( k = 0; k < num_threads; ++k) { data_array[k].start_ptr = &array_ptr[k * slice_size * 16]; data_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 16]; data_array[k].thread_id = k; strcpy(data_array[k].match_str, search_str); data_array[k].array_address = array_ptr; data_array[k].slice_struct_address = slice_array; data_array[k].num_slices = num_slices; } for ( k = 0; k < num_slices; ++k) { slice_array[k].start_ptr = &array_ptr[k * slice_size * 16]; slice_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 16]; slice_array[k].slice_id = k; } pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutex2, 0); for( k = 0; k < num_threads; ++k) { pthread_create(&thread_array[k], 0, (void *) & search_by_thread, (void *) &data_array[k]); } for( k =0; k < num_threads; ++k) { pthread_join(thread_array[k], 0); } pthread_mutex_destroy(&mutex); return 0; } void search_by_thread( void* ptr) { thread_data* data; data = (thread_data *) ptr; int temp_slice; char* temp_ptr; int i=0; int j; while(1) { pthread_mutex_lock(&mutex2); printf("LOCK.."); if ( slice_counter < data->num_slices) { temp_slice = slice_counter; slice_counter = slice_counter + 1; } else { temp_slice = -1; } printf("...Unlock-------------------------------->%d\\n", data->thread_id); pthread_mutex_unlock(&mutex2); if (temp_slice == -1) { break; } j =0; temp_ptr = data->slice_struct_address[temp_slice].start_ptr; while( &temp_ptr[j * 16] < data->slice_struct_address[temp_slice].end_ptr) { if (strcmp(&temp_ptr[j*16], data->match_str) == 0) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } j = j + 1; } i++; } printf("THREAD (%d) RAN -->%d<--\\n", data->thread_id, i); pthread_exit(0); }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void printMsg(char *str, int err) { printf("%s:%s\\n", str, strerror(err)); exit(1); } void *thr_fn(void *arg) { int err; int signo; for (; ;) { err = sigwait(&mask, &signo); if (err != 0) { printMsg("sigwait failed", err); } switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return (0); default: printf("unexpected signal: %d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { printMsg("SIG_BLOCK error", err); } if ((err = pthread_create(&tid, 0, thr_fn, 0)) != 0) { printMsg("can't create thread", err); } pthread_mutex_lock(&lock); while (0 == quitflag) { pthread_cond_wait(&wait, &lock); } pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { printMsg("SIG_SETMASK", 0); } exit(0); }
0
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t thereAreOxygen, thereAreHydrogen; pthread_t oxygen, hydrogen[2]; int numberOxygen = 0 , numberHydrogen=0; int activeOxygen = 0 , activeHydrogen=0; int currentOxygen = 0 , currentHydrogen=0; void dataIn(){ int var=0; if(numberHydrogen==1){ while (var<=0) { printf("Queda 1 atomo de hidrogeno, ingrese atomos de hidrogeno: ", numberHydrogen ); scanf("%d",&var); } numberHydrogen+=var; } var=0; if(numberOxygen==0 && numberHydrogen>0){ while (var<=0) { printf("Hay %d atomo(s) de hidrogeno, ingrese atomos de oxigeno: ", numberHydrogen ); scanf("%d",&var); } numberOxygen+=var; } var=0; if(numberHydrogen==0 && numberOxygen>0){ while (var<=0) { printf("Hay %d atomo(s) de oxigeno, ingrese atomos de hidrogeno: ", numberOxygen ); scanf("%d",&var);} numberHydrogen+=var; } } void startHydrogen(){ pthread_mutex_lock(&lock); ++activeHydrogen; while (activeOxygen<1) { pthread_cond_wait(&thereAreHydrogen, &lock); } --numberHydrogen; pthread_mutex_unlock(&lock); } void startOxygen(){ pthread_mutex_lock(&lock); ++activeOxygen; while (activeHydrogen<2) { pthread_cond_wait(&thereAreOxygen, &lock); } --numberOxygen; pthread_mutex_unlock(&lock); } void doneOxygen() { pthread_mutex_lock(&lock); printf("Signaling hydrogen in broadcast...\\n"); dataIn(); pthread_cond_broadcast(&thereAreHydrogen); --activeOxygen; ++currentOxygen; pthread_mutex_unlock(&lock); } void doneHydrogen() { pthread_mutex_lock(&lock); printf("Signaling oxygen ...\\n"); dataIn(); pthread_cond_signal(&thereAreOxygen); --activeHydrogen; ++currentHydrogen; pthread_mutex_unlock(&lock); } void *Oxigeno(void *id) { long tid = (long)id; printf("oxigeno[%ld] preparado para ser H2O \\n", tid); startOxygen(); printf("oxigeno[%ld] convirtiendose \\n"); sleep(rand()%5); printf("oxigeno[%ld] es H2O \\n", tid); doneOxygen(); sleep(rand()%5); pthread_exit(0); } void *Hidrogeno(void *id) { long tid = (long)id; printf("hidrogeno(%ld) preparado\\n", tid); startHydrogen(); printf("hidrogeno(%ld) convirtiendose\\n", tid); sleep(rand()%5); printf("hidrogeno(%ld) es h2O\\n", tid); doneHydrogen(); sleep(rand()%5); pthread_exit(0); } int main(int argc, char *argv[]) { while (numberOxygen<=0) { printf("Ingrese atomos de oxigeno:"); scanf("%d",&numberOxygen); } while (numberHydrogen<=0) { printf("Ingrese atomos de hidrogeno:"); scanf("%d",&numberHydrogen); } long i=0; srand(time(0)); printf("main(): creando threads hidrogeno\\n"); for (i=0; i<2; i++) { if (pthread_create(&hydrogen[i], 0, Hidrogeno, (void *)i)) { printf("Error creando thread hidrogeno[%ld]\\n", i); exit(1); } } i=0; printf("main(): creando thread Oxigeno\\n"); if (pthread_create(&oxygen, 0,Oxigeno, (void *)i)) { printf("Error creando thread oxigeno[%ld]\\n", i); exit(1); } void *status; for (i=0; i<2; i++) { pthread_join(hydrogen[i],&status); } pthread_join(oxygen,&status); pthread_exit(0); }
1
#include <pthread.h> static sem_t _sem_send_msgs_empty; static sem_t _sem_send_msgs_full; static char *send_msgs[16] = { 0 }; static pthread_mutex_t _lock_send_id; void thread_sendstream_post_new_msg(char *msg) { static int pos = 0; assert(msg != 0); sem_wait(&_sem_send_msgs_empty); pthread_mutex_lock(&_lock_send_id); send_msgs[pos] = msg; ++pos; if (pos >= 16) pos = 0; pthread_mutex_unlock(&_lock_send_id); sem_post(&_sem_send_msgs_full); } char *thread_sendstream_get_next_msg(void) { static int pos = 0; char *msg = 0; sem_wait(&_sem_send_msgs_full); msg = send_msgs[pos]; send_msgs[pos] = 0; ++pos; if (pos >= 16) pos = 0; sem_post(&_sem_send_msgs_empty); assert(msg != 0); return msg; } void thread_sendstream_init(void) { if (sem_init(&_sem_send_msgs_empty, 0, 16) != 0) perror("semaphore init failed"); if (sem_init(&_sem_send_msgs_full, 0, 0) != 0) perror("semaphore init failed"); if (pthread_mutex_init(&_lock_send_id, 0) != 0) perror("mutex init failed"); } static void thread_sendstream_close(void *vargs) { struct thread *t = (struct thread *) vargs; for (unsigned int i = 0; i < 16; ++i) { free(send_msgs[i]); send_msgs[i] = 0; } sem_destroy(&_sem_send_msgs_empty); sem_destroy(&_sem_send_msgs_full); pthread_mutex_destroy(&_lock_send_id); } void *thread_sendstream(void *vargs) { struct thread *t = (struct thread *) vargs; pthread_cleanup_push(thread_sendstream_close, t); while (session.state != STATE_DEAD) { char *msg = thread_sendstream_get_next_msg(); stream_send_msg(session.wfs, msg); stream_flush(session.wfs); free(msg); } pthread_cleanup_pop(1); return thread_close(t); }
0
#include <pthread.h> int kill (pid_t pid, int signo) { if (pid != getpid ()) { errno = EOPNOTSUPP; return -1; } pthread_mutex_lock (&sig_lock); struct sigwaiter *waiter; for (waiter = sigwaiters; waiter; waiter = waiter->next) if ((waiter->signals & sigmask (signo))) { sigdelset (&process_pending, signo); pthread_mutex_lock (&waiter->ss->lock); sigdelset (&waiter->ss->pending, signo); memset (&waiter->info, 0, sizeof (waiter->info)); waiter->info.si_signo = signo; sigwaiter_unblock (waiter); return 0; } pthread_mutex_unlock (&sig_lock); return pthread_kill (pthread_self (), signo); }
1
#include <pthread.h> struct station { int passenger_count; int train_in_station; }; struct station cal_station; pthread_mutex_t station_key; pthread_cond_t train_arrived; pthread_cond_t seats_available; pthread_cond_t train_loaded; pthread_mutex_t seats_key; int seats_count; void* passenger_arrive(void* arg){ struct station *station = (struct station*)arg; pthread_mutex_lock(&station_key); station->passenger_count+=1; pthread_mutex_unlock(&station_key); printf("\\npassenger arrived,\\t passenger_count=%d", station->passenger_count); pthread_mutex_lock(&seats_key); while(1){ if(seats_count>0){ pthread_mutex_lock(&station_key); station->passenger_count-=1; seats_count-=1; printf("\\npassenger boarded"); if(station->passenger_count==0||seats_count==0){ pthread_cond_signal(&train_loaded); } pthread_mutex_unlock(&seats_key); pthread_mutex_unlock(&station_key); break; }else{ pthread_cond_wait(&train_arrived, &seats_key); continue; } } pthread_exit(0); } void* train_arrive(void* arg){ struct station *station = (struct station*)arg; pthread_mutex_lock(&station_key); seats_count=500; station->train_in_station=1; printf("\\n****************************************************************"); printf("\\nTRAIN ARRIVED"); printf("\\n****************************************************************"); if(station->passenger_count==0){ printf("\\n****************************************************************"); printf("\\nTRAIN LEFT"); printf("\\n****************************************************************"); pthread_mutex_unlock(&station_key); pthread_exit(0); } pthread_cond_broadcast(&train_arrived); pthread_cond_wait(&train_loaded, &station_key); printf("\\n****************************************************************"); printf("\\nTRAIN LEFT"); printf("\\n****************************************************************"); station->train_in_station=0; pthread_mutex_unlock(&station_key); pthread_exit(0); } void* spawn_passengers(void* arg){ srand(time(0)); while(1){ pthread_t passenger; pthread_create(&passenger, 0, passenger_arrive, &cal_station); int interval = rand()%10; usleep(interval*150); } pthread_exit(0); } void* spawn_trains(void* arg){ while(1){ usleep(500000); pthread_t train; pthread_create(&train, 0, train_arrive, &cal_station); pthread_join(train, 0); } pthread_exit(0); } int main(){ cal_station.passenger_count=0; cal_station.train_in_station=0; pthread_mutex_init(&station_key, 0); pthread_mutex_init(&seats_key, 0); pthread_cond_init(&train_arrived, 0); pthread_cond_init(&seats_available, 0); pthread_cond_init(&train_loaded, 0); pthread_t passenger_factory; pthread_create(&passenger_factory, 0, spawn_passengers, 0); pthread_t train_factory; pthread_create(&train_factory, 0, spawn_trains, 0); pthread_join(passenger_factory, 0); pthread_join(train_factory, 0); return 0; }
0
#include <pthread.h> extern sem_t GroupSize; void *gc_thread(void *arg) { struct sock_token *token = (struct sock_token *)arg; sem_wait(&(token->done)); sem_close(&token->done); Free(token->client); Free(token->time_lock); Free(token->last_time); Free(token); } void *thread_dispatcher(void *arg) { debug("====thread_dispatcher\\n"); struct connection_info *conn_info = (struct connection_info*)arg; char buff[1024]; int length; length = recv(conn_info->connection, buff, sizeof(buff), 0); if (length == -1) { debug("recv info failed\\n"); return 0; } buff[length] = '\\0'; debug("from %s: %s\\n", inet_ntoa(conn_info->client->sin_addr), buff); debug("%s: waiting...\\n", buff); sem_wait(&GroupSize); debug("%s: continue...\\n", buff); debug("=====create threads\\n"); int ret; time_t *last_time; Malloc(last_time, 1); *last_time = time(0); pthread_mutex_t *time_lock; Malloc(time_lock, 1); ret = pthread_mutex_init(time_lock, 0); if (ret) { debug("pthread_mutex_init failed, error number: %d\\n", ret); perror(strerror(ret)); return 0; } pthread_attr_t attr; pthread_t heartbeat; pthread_t timer; pthread_t gc; memset(&heartbeat, 0, sizeof(heartbeat)); memset(&timer, 0, sizeof(timer)); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); struct sock_token *token; Malloc(token, 1); token->connection = conn_info->connection; token->client = conn_info->client; token->last_time = last_time; token->time_lock = time_lock; strcpy(token->user, buff); sem_init(&token->done, 0, 0); strcpy(buff, "starting...\\n"); send(conn_info->connection, buff, strlen(buff), 0); do { if (pthread_create(&heartbeat, &attr, heartbeat_thread, (void *)token) != 0) { perror("create heartbeat failed"); break; } token->heartbeat = heartbeat; if (pthread_create(&timer, &attr, timer_thread, (void *)token) != 0) { perror("create timer failed"); break; } if (pthread_create(&gc, &attr, gc_thread, (void *)token) != 0) { perror("create garbage failed"); break; } pthread_attr_destroy(&attr); debug("thread_dispatcher ended\\n"); Free(conn_info); pthread_exit(0); } while (0); pthread_attr_destroy(&attr); sem_close(&(token->done)); close(token->connection); Free(token->last_time); Free(token->time_lock); Free(token->client); Free(conn_info); Free(token); debug("thread_dispatcher ended\\n"); } void *heartbeat_thread(void *arg) { debug("tcpThread\\n"); pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); struct sock_token *token = (struct sock_token *)arg; char recvbuff[1024]; char sendbuff[1024]; strcpy(sendbuff, "got message\\n"); int length; int i = 0; while (1) { pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0); pthread_testcancel(); length = recv(token->connection, recvbuff, sizeof(recvbuff), 0); pthread_testcancel(); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0); if (length == -1) { debug("recv failed\\n"); break; } recvbuff[length] = '\\0'; pthread_mutex_lock(token->time_lock); *(token->last_time) = time(0); pthread_mutex_unlock(token->time_lock); debug("from: %s:%d, msg:%s\\n", inet_ntoa(token->client->sin_addr), ntohs(token->client->sin_port), recvbuff); send(token->connection, sendbuff, strlen(sendbuff), 0); if (strcmp(recvbuff, "exit") == 0) break; } token->heartbeat = 0; debug("heartbeat_thread exit\\n"); pthread_exit(0); return 0; } void *timer_thread(void *arg) { debug("timer_thread\\n"); struct sock_token *token = (struct sock_token *)arg; time_t now; double diff; do { sleep(1); now = time(0); pthread_mutex_lock(token->time_lock); diff = difftime(now, *(token->last_time)); pthread_mutex_unlock(token->time_lock); } while(diff < 5.0); if (token->heartbeat) { if (!pthread_cancel(token->heartbeat)) debug("cancel the heartbeat thread\\n"); else debug("cancel heartbeat thread failed\\n"); token->heartbeat = 0; } close(token->connection); pthread_mutex_destroy(token->time_lock); debug("-----user: `%s` left\\n", token->user); sem_post(&GroupSize); sem_post(&token->done); }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); exit(0); }
0
#include <pthread.h> int g_counter = 0; int g_stop_it = 0; pthread_mutex_t mutex_stop = PTHREAD_MUTEX_INITIALIZER; int sockaddrInit(const char *host, int port, struct sockaddr_in *peer) { int code; memset(peer, '\\0', sizeof(struct sockaddr_in)); peer->sin_family = AF_INET; peer->sin_port = htons(port); code = inet_pton(AF_INET, host, &(peer->sin_addr)); if (1 != code) { fprintf(stderr, "inet_pton failed: %s \\n", strerror(errno)); return -1; } return 0; } void generateTimeWait(struct sockaddr_in *peer) { int code; int s; s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "create socket failed: %s \\n", strerror(errno)); return; } code = connect(s, (struct sockaddr *)peer, sizeof(struct sockaddr_in)); if (0 != code) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "connect socket failed: %d, %s \\n", errno, strerror(errno)); return; } { code = close(s); if (0 != code) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "close socket failed: %s \\n", strerror(errno)); return; } } pthread_mutex_lock(&mutex_stop); g_counter += 1; printf("counter: %d \\n", g_counter); pthread_mutex_unlock(&mutex_stop); } int main(int argc, char *argv[]) { int code; struct sockaddr_in peer; code = sockaddrInit("127.0.0.1", 11211, &peer); if (0 != code) { exit(1); } pthread_t tid; while (!g_stop_it) { code = pthread_create(&tid, 0, (void *)generateTimeWait, (void *)&peer); if (0 != code) { pthread_mutex_lock(&mutex_stop); g_stop_it = 1; pthread_mutex_unlock(&mutex_stop); fprintf(stderr, "pthread_create failed: %s \\n", strerror(code)); } else { pthread_join(tid, 0); } } printf("Total counter: %d \\n", g_counter); exit(0); }
1
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product=PTHREAD_COND_INITIALIZER; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp; for (;;) { pthread_mutex_lock(&lock); while(head==0) pthread_cond_wait(&has_product,&lock); mp=head; head=mp->next; pthread_mutex_unlock(&lock); printf("Cinsume %d\\n",mp->num); free(mp); sleep(rand()%5); } } void *producer(void *p) { struct msg *mp; for (;;) { mp=malloc(sizeof(struct msg)); mp->num=rand()%1000+1; printf("Produce %d\\n",mp->num); pthread_mutex_lock(&lock); mp->next=head; head=mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand()%5); } } int main(int argc, const char *argv[]) { pthread_t pid,cid; srand(time(0)); pthread_create(&pid,0,producer,0); pthread_create(&cid,0,consumer,0); pthread_join(pid,0); pthread_join(cid,0); return 0; }
0
#include <pthread.h> int numOfPassengersOnBus; int turn; void* print_message(void* ptr); pthread_mutex_t verrou; int main(int argc, char* argv[]) { pthread_t tProducer, tConsumer1, tConsumer2; const char* msg1 = "Producer"; const char* msg2 = "Consumer1"; const char* msg3 = "Consumer2"; numOfPassengersOnBus = 0; pthread_mutex_init(&verrou, 0); int r1 = pthread_create(&tProducer, 0, print_message, (void*)msg1 ); int r2 = pthread_create(&tConsumer1, 0, print_message, (void*)msg2 ); int r3 = pthread_create(&tConsumer2, 0, print_message, (void*)msg3 ); pthread_join(tProducer, 0); pthread_join(tConsumer1, 0); pthread_join(tConsumer2, 0); return 0; } void* print_message(void* ptr) { srand(time(0)); char* msg = (char*) ptr; while(1) { if(msg[0]=='P') { while(numOfPassengersOnBus>0){}; pthread_mutex_lock(&verrou); if(numOfPassengersOnBus<=0) { numOfPassengersOnBus++; printf("%s produced %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%2); } else { while(numOfPassengersOnBus<=0){}; pthread_mutex_lock(&verrou); if(numOfPassengersOnBus>0) { numOfPassengersOnBus--; printf("%s consumed %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%4); } } return 0; }
1
#include <pthread.h> static pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER; struct mntent *getmntent_r (FILE *filep, struct mntent *mnt, char *buff, int bufsize) { static const char sep[] = " \\t\\n"; char *cp, *ptrptr; if (!filep || !mnt || !buff) return 0; while ((cp = fgets(buff, bufsize, filep)) != 0) { continue; break; } if (cp == 0) return 0; ptrptr = 0; mnt->mnt_fsname = strtok_r(buff, sep, &ptrptr); if (mnt->mnt_fsname == 0) return 0; mnt->mnt_dir = strtok_r(0, sep, &ptrptr); if (mnt->mnt_dir == 0) return 0; mnt->mnt_type = strtok_r(0, sep, &ptrptr); if (mnt->mnt_type == 0) return 0; mnt->mnt_opts = strtok_r(0, sep, &ptrptr); if (mnt->mnt_opts == 0) mnt->mnt_opts = ""; cp = strtok_r(0, sep, &ptrptr); mnt->mnt_freq = (cp != 0) ? atoi(cp) : 0; cp = strtok_r(0, sep, &ptrptr); mnt->mnt_passno = (cp != 0) ? atoi(cp) : 0; return mnt; } struct mntent *getmntent(FILE * filep) { struct mntent *tmp; static char *buff = 0; static struct mntent mnt; pthread_mutex_lock(&(mylock)); if (!buff) { buff = malloc(1024); if (!buff) abort(); } tmp = getmntent_r(filep, &mnt, buff, 1024); pthread_mutex_unlock(&(mylock)); return(tmp); } int addmntent(FILE * filep, const struct mntent *mnt) { if (fseek(filep, 0, 2) < 0) return 1; return (fprintf (filep, "%s %s %s %s %d %d\\n", mnt->mnt_fsname, mnt->mnt_dir, mnt->mnt_type, mnt->mnt_opts, mnt->mnt_freq, mnt->mnt_passno) < 0 ? 1 : 0); } char *hasmntopt(const struct mntent *mnt, const char *opt) { return strstr(mnt->mnt_opts, opt); } FILE *setmntent(const char *name, const char *mode) { return fopen(name, mode); } int endmntent(FILE * filep) { if (filep != 0) fclose(filep); return 1; }
0
#include <pthread.h> struct tdata { int count; int turn; int thread; pthread_mutex_t lock; int thread_count; }; void *countUp(void *param) { struct tdata* datas = (struct tdata*)param; pthread_mutex_lock(&datas->lock); int thread_id = datas->thread; datas->thread++; pthread_mutex_unlock(&datas->lock); while(datas->count < 20) { pthread_mutex_lock(&datas->lock); if(datas->turn == thread_id && datas->count < 20) { printf("thread %d: %d\\n",thread_id, datas->count); datas->turn = (datas->turn+1) % datas->thread_count; datas->count++; } pthread_mutex_unlock(&datas->lock); } } int main(int argc, char* argv[]) { pthread_t threads[2]; printf("starting up\\n"); struct tdata datums = {0,0,0,PTHREAD_MUTEX_INITIALIZER,3}; int i; for(i = 0; i < datums.thread_count; i++) { int ec = pthread_create(&threads[i], 0, countUp, (void *)&datums); if (ec){ printf("ERROR; return code from pthread_create() is %d\\n", ec); } } pthread_exit(0); }
1
#include <pthread.h> long thread_count; pthread_mutex_t mutex; char** messages; void* Thread_prod_con(void* rank); void Get_args(int argc, char* argv[]); void Usage(char* prog_name); int main(int argc, char* argv[]) { pthread_t* thread_handles; Get_args(argc, argv); thread_handles = malloc(sizeof(pthread_t) * thread_count); pthread_mutex_init(&mutex, 0); messages = malloc(sizeof(char*) * thread_count); printf("Making %ld threads\\n", thread_count); long i; for (i = 0; i < thread_count; i++) { messages[i] = 0; } for (i = 0; i < thread_count; i++) { long* index = malloc(sizeof(long)); *index = i; pthread_create(&thread_handles[i], 0, Thread_prod_con, index); } for (i = 0; i < thread_count; i++) { pthread_join(thread_handles[i], 0); } return 0; } void* Thread_prod_con(void* rank) { long my_rank = *((long*) rank); long dest = (my_rank + 1) % thread_count; int received = 0; int sent = 0; while (!sent || !received) { pthread_mutex_lock(&mutex); if (!sent && messages[dest] == 0) { char* message = malloc(sizeof(char) * 100); sprintf(message, "Thread %ld sent this message to thread %ld\\n", my_rank, dest); messages[dest] = message; sent = 1; } if (!received && messages[my_rank] != 0) { printf("%ld got message: %s", my_rank, messages[my_rank]); received = 1; } pthread_mutex_unlock(&mutex); } return 0; } void Get_args(int argc, char* argv[]) { if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0) Usage(argv[0]); } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <k>\\n", prog_name); fprintf(stderr, " k should be the number of threads\\n"); exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex1; pthread_mutex_t mutex2; int maxYield = 20; void *second_thread(void *a) { assert(a == 0); printf("T2: acquire lock\\n"); assert(pthread_mutex_lock(&mutex1) == 0); printf("T2: got the lock. Yielding now %d times.\\n", maxYield); int c = 0; while(c++ < maxYield) sched_yield(); printf("T2: release the lock. Goodbye.\\n"); assert(! pthread_mutex_unlock(&mutex1)); return 0; } long volatile locked = 0; long volatile unlocked[6]; void* takeAndRelease(void *nr) { int n = (int )(long)nr; printf("T%d: Taking mutex\\n", n); locked = n; pthread_mutex_lock(&mutex1); printf("T%d: Got mutex, release\\n", n); unlocked[n] = 1; pthread_mutex_unlock(&mutex1); return 0; } void *takeM2thenM1(void *a) { out("Taking M2"); assert(!pthread_mutex_lock(&mutex2)); out("Taking M1"); int ret = pthread_mutex_lock(&mutex1); out("%d", ret); assert(!ret); out("Got M1, ending"); return 0; } int main() { printf("T1: init mutex\\n"); assert(!pthread_mutex_init(&mutex1, 0)); assert(pthread_mutex_init(0, 0)); assert(pthread_mutex_init(&mutex1, 0)); printf("T1: messing with wrong mutex\\n"); assert(pthread_mutex_init(0, 0)); assert(pthread_mutex_lock(0)); assert(pthread_mutex_unlock(0)); assert(pthread_mutex_trylock(0)); assert(pthread_mutex_destroy(0)); assert(pthread_mutex_lock(&mutex2)); assert(pthread_mutex_unlock(&mutex2)); assert(pthread_mutex_trylock(&mutex2)); assert(pthread_mutex_destroy(&mutex2)); printf("T1: create T2\\n"); pthread_t t2; pthread_create(&t2, 0, second_thread, 0); assert(t2); printf("T1: Yielding now %d times.\\n", maxYield / 4); int c = 0; while (c++ < maxYield / 4) sched_yield(); printf("T1: try destroy\\n"); assert(pthread_mutex_destroy(&mutex1)); printf("T1: try lock\\n"); assert(pthread_mutex_trylock(&mutex1)); printf("T1: try unlock: %d == %d\\n", pthread_mutex_unlock(&mutex1), EPERM); assert(pthread_mutex_unlock(&mutex1)); printf("T1: lock\\n"); assert(! pthread_mutex_lock(&mutex1)); printf("T1: got lock, lock again: %d == %d\\n", pthread_mutex_lock(&mutex1), EDEADLK); assert(pthread_mutex_lock(&mutex1)); printf("T1: starting threads 3, 4, 5 in that order to lock the mutex\\n"); for(int i = 3; i < 6; i++) { printf("T1: starting thread %d\\n", i); pthread_create(&t2, 0, takeAndRelease,(void *) (long)i); while(locked != i); } assert(! unlocked[3] && ! unlocked[4] && !unlocked[5]); printf("T1: Started all threads, now releasing the mutex, you should see from 3 to 5 again\\n"); assert(!pthread_mutex_unlock(&mutex1)); assert(pthread_mutex_unlock(&mutex1)); locked = 0; for(int i = 3; i < 6; i++) { printf("T1: waiting for thread %d to release lock\\n", i); while (! unlocked[i]); } out("Checking deadlock\\n"); assert(!pthread_mutex_init(&mutex2, 0)); assert(!pthread_mutex_destroy(&mutex1)); assert(!pthread_mutex_init(&mutex1, 0)); assert(!pthread_mutex_lock(&mutex1)); out("Creating thread"); pthread_t t_dead; assert(!pthread_create(&t_dead, 0, takeM2thenM1, 0)); sched_yield(); sched_yield(); sched_yield(); sched_yield(); sched_yield(); out("Try Lock Mutex2"); assert(pthread_mutex_lock(&mutex2)); printf("T1: Fin\\n"); return 0; }
1
#include <pthread.h> static int keyCols[3] = { 5, 16, 1 }; static int keyRows[4] = { 0, 2, 3, 4 }; unsigned waitingFirst = 0; unsigned waitingLast = 0; int* buffer = 0; size_t currentBufferSize = 0; pthread_t driverThread; pthread_mutex_t bufferMutex; pthread_cond_t eventsQueued; static void internal_allocateBuffer() { if (buffer == 0) { buffer = malloc(500 * sizeof(int)); waitingFirst = 0; waitingLast = 0; currentBufferSize = 500; (void)("Allocated initial buffer %p with %x places\\n", buffer, (unsigned int) currentBufferSize); } else { if (waitingFirst >= 250) { int* newBuffer = malloc(currentBufferSize * sizeof(int)); memcpy(newBuffer, buffer + waitingFirst, (currentBufferSize - waitingFirst) * sizeof(int)); free(buffer); buffer = newBuffer; waitingLast -= waitingFirst; waitingFirst = 0; (void)("Buffer copied to %p\\n", buffer); } else { buffer = realloc(buffer, currentBufferSize * 2 * sizeof(int)); currentBufferSize = currentBufferSize * 2; (void)("Buffer reallocated to %p with %x places\\n", buffer, (unsigned int) currentBufferSize); } } } void addEvent(int event) { pthread_mutex_lock (&bufferMutex); (void)("Adding event %x\\n", (unsigned int) event); if (waitingLast >= currentBufferSize-1) { internal_allocateBuffer(); } buffer[waitingLast] = event; waitingLast += 1; pthread_cond_broadcast(&eventsQueued); pthread_mutex_unlock (&bufferMutex); } int waitEvent() { int retEvent = 0; pthread_mutex_lock (&bufferMutex); while (waitingLast <= waitingFirst) { pthread_cond_wait(&eventsQueued, &bufferMutex); } retEvent = buffer[waitingFirst]; waitingFirst += 1; (void)("Waited for event %x\\n", (unsigned int) retEvent); pthread_mutex_unlock (&bufferMutex); return retEvent; } int readEvent() { int retEvent = -1; pthread_mutex_lock (&bufferMutex); if (waitingLast > waitingFirst) { retEvent = buffer[waitingFirst]; waitingFirst += 1; } if (retEvent >= 0) (void)("Read event %x\\n", (unsigned int) retEvent); pthread_mutex_unlock (&bufferMutex); return retEvent; } int keyboardStatus[4 * 3]; int getKeyStatus(int row, int col) { return keyboardStatus[row + col * 4]; } void setKeyStatus(int row, int col, int stat) { keyboardStatus[row + col * 4] = stat; } int driverStatus = 0; void* driverLoop(void* thrdparams) { wiringPiSetup(); for (int i = 0; i < 4*3; i++) keyboardStatus[i] = 0; for (int i = 0; i < 3; i++) { pinMode(keyCols[i], OUTPUT); digitalWrite(keyCols[i], LOW); } for (int i = 0; i < 4; i++) { pinMode(keyRows[i], INPUT); } pthread_mutex_lock (&bufferMutex); internal_allocateBuffer(); pthread_cond_broadcast(&eventsQueued); pthread_mutex_unlock (&bufferMutex); while(driverStatus) for (int i = 0; i < 3; i++) { digitalWrite(keyCols[i], HIGH); delayMicroseconds(120); for (int i2 = 0; i2 < 4; i2++) { int status = digitalRead(keyRows[i2]); if (getKeyStatus(i2, i) != status) { setKeyStatus(i2, i, status); addEvent(i2 + i * 4 + (status << 8)); } } digitalWrite(keyCols[i], LOW); delayMicroseconds(120); } pthread_exit(0); } void endDriver() { if (driverStatus == 0) { (void)("Error, driver not running"); return; } driverStatus = 0; pthread_join(driverThread, 0); } void startDriver() { if (driverStatus == 1) { (void)("Error, driver already running"); return; } driverStatus = 1; pthread_cond_init(&eventsQueued, 0); pthread_mutex_lock (&bufferMutex); pthread_create(&driverThread, 0, driverLoop, 0); pthread_cond_wait(&eventsQueued, &bufferMutex); pthread_mutex_unlock (&bufferMutex); } int main (int argc, char *argv[]) { startDriver(); int i = 0; while(i = waitEvent()) { } endDriver(); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void *); void *thread2(void *); int i=1; int main(void) { pthread_t t_a; pthread_t t_b; pthread_create(&t_a,0,thread1,(void *)0); pthread_create(&t_b,0,thread2,(void *)0); pthread_join(t_a, 0); pthread_join(t_b, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(0); } void *thread1(void *junk) { for(i=1;i<=6;i++) { pthread_mutex_lock(&mutex); printf("thread1: lock %d\\n", 49); if(i%3==0){ printf("thread1:signal 1 %d\\n", 51); pthread_cond_signal(&cond); printf("thread1:signal 2 %d\\n", 53); sleep(5); } pthread_mutex_unlock(&mutex); printf("thread1: unlock %d\\n\\n", 57); sleep(1); } } void *thread2(void *junk) { while(i<6) { pthread_mutex_lock(&mutex); printf("thread2: lock %d\\n", 67); if(i%3!=0){ printf("thread2: wait 1 %d\\n", 69); pthread_cond_wait(&cond,&mutex); printf("thread2: wait 2 %d\\n", 71); } pthread_mutex_unlock(&mutex); printf("thread2: unlock %d\\n\\n", 74); sleep(1); } }
1
#include <pthread.h> void * serverthread(void * parm); pthread_mutex_t mut; int visits = 0; main (int argc, char *argv[]) { struct hostent *ptrh; struct protoent *ptrp; struct sockaddr_in sad; struct sockaddr_in cad; int sd, sd2; int port; int alen; pthread_t tid; pthread_mutex_init(&mut, 0); memset((char *)&sad,0,sizeof(sad)); sad.sin_family = AF_INET; sad.sin_addr.s_addr = INADDR_ANY; if (argc > 1) { port = atoi (argv[1]); } else { port = 5193; } if (port > 0) sad.sin_port = htons((u_short)port); else { fprintf (stderr, "bad port number %s/n",argv[1]); exit (1); } if ( ((int)(ptrp = getprotobyname("tcp"))) == 0) { fprintf(stderr, "cannot map \\"tcp\\" to protocol number"); exit (1); } sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto); if (sd < 0) { fprintf(stderr, "socket creation failed\\n"); exit(1); } if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) { fprintf(stderr,"bind failed\\n"); exit(1); } if (listen(sd, 6) < 0) { fprintf(stderr,"listen failed\\n"); exit(1); } alen = sizeof(cad); fprintf( stderr, "Server up and running.\\n"); while (1) { printf("SERVER: Waiting for contact ...\\n"); if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) { fprintf(stderr, "accept failed\\n"); exit (1); } pthread_create(&tid, 0, serverthread, (void *) sd2 ); } close(sd); } void * serverthread(void * parm) { int tsd, tvisits; char buf[100]; tsd = (int) parm; pthread_mutex_lock(&mut); tvisits = ++visits; pthread_mutex_unlock(&mut); sprintf(buf,"This server has been contacted %d time%s\\n", tvisits, tvisits==1?".":"s."); printf("SERVER thread: %s", buf); send(tsd,buf,strlen(buf),0); close(tsd); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *functionCount1(); void *functionCount2(); int count = 0; void main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, &functionCount1, 0); pthread_create( &thread2, 0, &functionCount2, 0); pthread_join( thread1, 0); pthread_join( thread2, 0); exit(0); } void *functionCount1() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 != 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount1: %d\\n",count); pthread_cond_signal( &condition_var ); if ( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } } void *functionCount2() { for(;;) { pthread_mutex_lock( &count_mutex ); if ( count % 2 == 0 ) { pthread_cond_wait( &condition_var, &count_mutex ); } count++; printf("Counter value functionCount2: %d\\n",count); pthread_cond_signal( &condition_var ); if( count >= 200 ) { pthread_mutex_unlock( &count_mutex ); return(0); } pthread_mutex_unlock( &count_mutex ); } }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int idCinta; int maxBeltSize; int toGenerate; void *Consumer(){ struct element *elemGotptr; struct element elemGot; while(1){ if(queue_empty() == 0){ pthread_mutex_lock(&mutex); elemGotptr = queue_get(); elemGot = *elemGotptr; if(elemGot.last == 1){ pthread_exit(0); } pthread_mutex_unlock(&mutex); } } } void *Producer(){ struct element elem; int i = 0; while(1){ if(queue_empty() == 1){ pthread_mutex_lock(&mutex); elem.num_edition = i; elem.id_belt = idCinta; if(i == toGenerate-1){ elem.last = 1; } if(queue_put(&elem) == -1){ int valueExit = -1; pthread_exit(&valueExit); } i++; pthread_mutex_unlock(&mutex); } if(i == toGenerate){ pthread_exit(0); } } } int main (int argc, const char * argv[] ){ if(argc > 5 || argc < 5){ fprintf(stderr, "[ERROR][process_manager] Arguments not valid.\\n"); exit(-1); } char *ptr; idCinta = strtol(argv[1], &ptr,10); maxBeltSize= strtol(argv[3], &ptr,10); toGenerate = strtol(argv[4], &ptr,10); sem_t *idSemaphore; idSemaphore = sem_open(argv[2],O_CREAT, 0, 0); if(idSemaphore == SEM_FAILED){ fprintf(stderr,"[ERROR][process_manager] Process manager could not open semaphore\\n"); exit(-1); } printf("[OK][process_manager] Process_manager with id: %d waiting to produce %d elements.\\n",idCinta, toGenerate); if(sem_wait(idSemaphore) == -1){ fprintf(stderr,"[ERROR][process_manager] Process manager could not do P operation on semaphore\\n"); exit(-1); } queue_init(maxBeltSize); pthread_mutex_init(&mutex, 0); pthread_t idConsumer, idProducer; printf("[OK][process_manager] Belt with id: %d has been created with a maximum of %d elements.\\n",idCinta, maxBeltSize); pthread_create(&idProducer, 0, Producer, 0); pthread_create(&idConsumer, 0, Consumer, 0); if((pthread_join(idProducer, 0)) != 0 ){; fprintf(stderr, "[ERROR][process_manager] There was an error executing process_manager with id: %d.\\n", idCinta); } if((pthread_join(idConsumer, 0)) != 0){ fprintf(stderr, "[ERROR][process_manager] There was an error executing process_manager with id: %d.\\n", idCinta); } printf("[OK][process_manager] Process_manager with id: %d has produced %d elements.\\n", idCinta, toGenerate); queue_destroy(); sem_close(idSemaphore); exit (0); }
0