text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> buffer_t buffer[5]; int buffer_index; pthread_mutex_t buffer_mutex; sem_t full_sem; sem_t empty_sem; void insertbuffer(buffer_t value) { if (buffer_index < 5) { buffer[buffer_index++] = value; } else { printf("Buffer overflow\\n"); } } buffer_t dequeuebuffer() { if (buffer_index > 0) { return buffer[--buffer_index]; } else { printf("Buffer underflow\\n"); } return 0; } void *producer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { sleep(rand() % 10); value = rand() % 100; sem_wait(&full_sem); pthread_mutex_lock(&buffer_mutex); insertbuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&empty_sem); printf("Producer %d added %d to buffer\\n", thread_numb, value); } pthread_exit(0); } void *consumer(void *thread_n) { int thread_numb = *(int *)thread_n; buffer_t value; int i=0; while (i++ < 2) { sem_wait(&empty_sem); pthread_mutex_lock(&buffer_mutex); value = dequeuebuffer(value); pthread_mutex_unlock(&buffer_mutex); sem_post(&full_sem); printf("Consumer %d dequeue %d from buffer\\n", thread_numb, value); } pthread_exit(0); } int main(int argc, int **argv) { buffer_index = 0; pthread_mutex_init(&buffer_mutex, 0); sem_init(&full_sem, 0, 5); sem_init(&empty_sem, 0, 0); pthread_t thread[6]; int thread_numb[6]; int i; for (i = 0; i < 6; ) { thread_numb[i] = i; pthread_create(thread + i, 0, producer, thread_numb + i); i++; thread_numb[i] = i; pthread_create(&thread[i], 0, consumer, &thread_numb[i]); i++; } for (i = 0; i < 6; i++) pthread_join(thread[i], 0); pthread_mutex_destroy(&buffer_mutex); sem_destroy(&full_sem); sem_destroy(&empty_sem); return 0; }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int scholarship = 4000; static int total = 0; static void *calculate(void *data); struct Data { const char *name; int doze; }; int main(void) { pthread_t tid1; pthread_t tid2; pthread_t tid3; struct Data a = { "A", 2 }; struct Data b = { "B", 1 }; struct Data c = { "C", 1 }; pthread_create(&tid1, 0, calculate, &a); pthread_create(&tid2, 0, calculate, &b); pthread_create(&tid3, 0, calculate, &c); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_join(tid3, 0); printf("Total given out: %d\\n", total); return 0; } static void *calculate(void *arg) { struct Data *data = arg; float result; while (scholarship > 0) { sleep(data->doze); pthread_mutex_lock(&mutex); result = scholarship * 0.25; result = ceil(result); total = total + result; scholarship = scholarship - result; if (result >= 1) { printf("%s = %.2f\\n", data->name, result); } if (scholarship < 1) { printf("Thread %s exited\\n", data->name); pthread_mutex_unlock(&mutex); return 0; } pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int main() { printf("Initializing mutex as recursive...\\n"); pthread_mutex_t mutex; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); if (pthread_mutex_init(&mutex, &attr) != 0) { fprintf(stderr, "pthread_mutex_init failed\\n"); return 1; }; pthread_t me = pthread_self(); printf("MY THID: %d\\n", me); printf("Trying to first-lock the mutex...\\n"); pthread_mutex_lock(&mutex); printf("Mutex type: %d; PTHREAD_MUTEX_RECUSRIVE=%d\\n", mutex.__type, PTHREAD_MUTEX_RECURSIVE); printf("MUTEX OWNER: %d\\n", mutex.__owner); printf("Trying to second-lock the mutex...\\n"); pthread_mutex_lock(&mutex); printf("Releasing the mutex twice...\\n"); pthread_mutex_unlock(&mutex); pthread_mutex_unlock(&mutex); printf("OK\\n"); return 0; };
1
#include <pthread.h> pthread_mutex_t aarrived, barrived; pthread_cond_t lock; int islocked = 0; void main() { pthread_cond_init(&lock, 0); pthread_mutex_init(&aarrived, 0); pthread_mutex_init(&barrived, 0); pthread_t threada, threadb; void *threadAFunction(), *threadBFunction(); pthread_create(&threada, 0, *threadAFunction, 0); pthread_create(&threadb, 0, *threadBFunction, 0); pthread_join(threada, 0); pthread_join(threadb, 0); } void sem_wait(pthread_mutex_t *mutex) { pthread_mutex_lock(mutex); while (islocked != 0) { islocked = pthread_cond_wait(&lock, mutex); } pthread_mutex_unlock(mutex); } void sem_signal(pthread_mutex_t *mutex) { pthread_mutex_unlock(mutex); pthread_cond_signal(&lock); } void *threadAFunction() { puts("a1"); sem_signal(&aarrived); sem_wait(&barrived); puts("a2"); pthread_exit(0); } void *threadBFunction() { puts("b1"); sem_signal(&barrived); sem_wait(&aarrived); puts("b2"); pthread_exit(0); }
0
#include <pthread.h> static int si_init_flag = 0; static int s_conf_fd = -1; static struct sockaddr_un s_conf_addr ; static int s_buf_index = 0; static char s_conf_buf[(16384)]; static pthread_mutex_t s_atomic; static char CONF_LOCAL_NAME[16] = "/tmp/rptClient"; inline int netReportSockSetLocal(const char * pLocalName) { if (pLocalName) { snprintf(CONF_LOCAL_NAME, 15, pLocalName); return 0; } else return -1; } int netReportSockInit() { if (si_init_flag) return 0; s_conf_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (s_conf_fd < 0) { return -1; } if (0 != pthread_mutex_init(&s_atomic, 0)) { close(s_conf_fd); s_conf_fd = -1; return -1; } unlink(CONF_LOCAL_NAME); bzero(&s_conf_addr , sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), CONF_LOCAL_NAME); bind(s_conf_fd, (struct sockaddr *)&s_conf_addr, sizeof(s_conf_addr)); bzero(&s_conf_addr , sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), "/tmp/rptServer"); si_init_flag = 1; return 0; } int netReportSockUninit() { if (!si_init_flag) return 0; if (s_conf_fd > 0) { close(s_conf_fd); } s_conf_fd = -1; unlink(CONF_LOCAL_NAME); pthread_mutex_destroy(&s_atomic); si_init_flag = 0; return 0; } static int netReportSockSend(const char *command) { int ret = -1 ; int addrlen = sizeof(s_conf_addr) ; int len = strlen(command); if (!si_init_flag) return -1; ret = sendto(s_conf_fd , command, len, 0, (struct sockaddr *)&s_conf_addr , addrlen); if (ret != len) { close(s_conf_fd) ; s_conf_fd = -1; ret = -1 ; si_init_flag = 0; syslog(LOG_ERR, "send conf message failed , ret = %d , errno %d\\n", ret, errno); } return ret ; } static int netReportSockRecv(char * buf, int len) { int ret; if (!si_init_flag) return -1; ret = recv(s_conf_fd , buf, len-1, 0); if (ret > 0) buf[ret] = '\\0'; else buf[0] = '\\0'; return ret; } static int netReportSockRequest(const char* command, char *recvbuf, int recvlen) { int ret; if (!command || !recvbuf || !recvlen) return -1; ret = netReportSockSend(command); if (ret >= 0) { ret = netReportSockRecv(recvbuf, recvlen); } return ret; } int net_report(const char* pValue) { char *conf_buf; if (!si_init_flag || !pValue) return -1; pthread_mutex_lock(&s_atomic); netReportSockRequest(pValue, s_conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); return 0; }
1
#include <pthread.h> pthread_mutex_t forks[5]; pthread_mutex_t lforks; pthread_t phils[5]; void *philosopher (void *id); int food_on_table (); void get_fork (int, int, char *); void down_forks (int, int); pthread_mutex_t foodlock; int sleep_seconds = 0; int main (int argn, char **argv) { int i; if (argn == 2) sleep_seconds = atoi (argv[1]); pthread_mutex_init (&foodlock, 0); pthread_mutex_init (&lforks, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&forks[i], 0); for (i = 0; i < 5; i++) pthread_create (&phils[i], 0, philosopher, (void *)i); for (i = 0; i < 5; i++) pthread_join (phils[i], 0); return 0; } void * philosopher (void *num) { int id; int left_fork, right_fork, f; id = (int)num; printf ("Philosopher %d sitting down to dinner.\\n", id); right_fork = id % 5; left_fork = (id + 1) % 5; while (f = food_on_table ()) { printf ("Philosopher %d: get dish %d.\\n", id, f); pthread_mutex_lock(&lforks); get_fork (id, left_fork, "left "); get_fork (id, right_fork, "right"); pthread_mutex_unlock(&lforks); printf ("Philosopher %d: eating.\\n", id); usleep (30000 * (50 - f + 1)); down_forks (left_fork, right_fork); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table () { static int food = 50; int myfood; pthread_mutex_lock (&foodlock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&foodlock); return myfood; } void get_fork (int phil, int fork, char *hand) { pthread_mutex_lock (&forks[fork]); printf ("Philosopher %d: got %s fork %d\\n", phil, hand, fork); } void down_forks (int f1, int f2) { pthread_mutex_unlock (&forks[f1]); pthread_mutex_unlock (&forks[f2]); }
0
#include <pthread.h> void * process_request(void * arg); void * process_response(void * arg); void setnonblockingmode(int fd); pthread_mutex_t mutex; struct epoll_event *ep_events; struct epoll_event event; int epfd, event_cnt; int fd_cnt = 0; int store[22222]; BOOL request_finish = 0; int main(int argc, char *argv[]) { pthread_t req_thread, res_thread; setnonblockingmode(1); setnonblockingmode(2); epfd = epoll_create(100); ep_events = (struct epoll_event*) malloc(sizeof(struct epoll_event)*100); pthread_mutex_init(&mutex, 0); pthread_create(&req_thread, 0, process_request, 0); pthread_create(&res_thread, 0, process_response, 0); pthread_join(req_thread, 0); pthread_mutex_lock(&mutex); request_finish = 1; pthread_mutex_unlock(&mutex); pthread_join(res_thread, 0); printf("[*] Brute Fail!\\n"); close(epfd); free(ep_events); pthread_mutex_destroy(&mutex); return 0; } void * process_request(void * arg) { int sock; struct sockaddr_in serv_addr; char http_cmn[3000]; char http_send[3000]; int pw; memset(&serv_addr, 0, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); serv_addr.sin_port = htons(80); strcpy(http_cmn,"POST /bruteTest/index.php HTTP/1.1 \\r\\n"); strcat(http_cmn,"Host: 127.0.0.1 \\r\\n"); strcat(http_cmn,"Content-Type: application/x-www-form-urlencoded \\r\\n"); strcat(http_cmn,"Content-Length: 100 \\r\\n"); strcat(http_cmn,"\\r\\n"); strcat(http_cmn,"id=admin&pw="); for(pw=0; pw<=10000; ++pw) { printf("[*] Trying %d...\\n",pw); while((sock=socket(PF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "socket() error!!\\n"); } while(connect(sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -1) { fprintf(stderr, "connect() error!!\\n"); } setnonblockingmode(sock); sprintf(http_send, "%s%d", http_cmn, pw); send(sock, http_send, strlen(http_send), 0); shutdown(sock, SHUT_WR); event.events = EPOLLIN; event.data.fd = sock; pthread_mutex_lock(&mutex); if(epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &event) != 0) { fprintf(stderr, "epoll_ctl() error!!\\n"); close(sock); --pw; } ++fd_cnt; store[sock] = pw; pthread_mutex_unlock(&mutex); } return 0; } void * process_response(void * arg) { int sock; char http_recv[3000]; int recv_sz; int i; while(1) { pthread_mutex_lock(&mutex); if(request_finish && fd_cnt <= 0) { pthread_mutex_unlock(&mutex); break; } event_cnt = epoll_wait(epfd, ep_events, 100, 0); pthread_mutex_unlock(&mutex); for(i=0; i<event_cnt; ++i) { sock = ep_events[i].data.fd; while(1) { recv_sz=recv(sock, http_recv, 3000 -1, 0); if(recv_sz == 0) { break; } else if(recv_sz < 0) { if(errno == EAGAIN) break; else fprintf(stderr,"recv return -1!!\\n"); } else { http_recv[recv_sz] = '\\0'; if(strstr(http_recv,"Success")) { pthread_mutex_lock(&mutex); printf("[*] Found!\\n[*] Password is %d\\n", store[sock]); epoll_ctl(epfd, EPOLL_CTL_DEL, sock, 0); --fd_cnt; pthread_mutex_unlock(&mutex); close(sock); exit(1); } } } pthread_mutex_lock(&mutex); printf("[*] Trying %d... finished!\\n", store[sock]); epoll_ctl(epfd, EPOLL_CTL_DEL, sock, 0); --fd_cnt; pthread_mutex_unlock(&mutex); close(sock); } } return 0; } void setnonblockingmode(int fd) { int flag = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flag | O_NONBLOCK); }
1
#include <pthread.h> extern SLAVE_FUN(fd4t10s_sw)(); extern SLAVE_FUN(cross_correlation_sw)(); struct Param; void master_wait() { pthread_mutex_lock(&mut1); while(g_status != 0) { pthread_cond_wait(&cond1, &mut1); } pthread_mutex_unlock(&mut1); g_status = CG_MAX; } void master_signal(struct Param** params) { int i; pthread_mutex_lock(&mut2); for(i = 0 ; i < CG_MAX ; i ++) params[i * ND]->status = 0; pthread_cond_broadcast(&cond2); pthread_mutex_unlock(&mut2); } void slave_wait(struct Param* param) { pthread_mutex_lock(&mut2); while(param->status) pthread_cond_wait(&cond2, &mut2); pthread_mutex_unlock(&mut2); } void slave_signal() { pthread_mutex_lock(&mut1); g_status --; pthread_cond_signal(&cond1); pthread_mutex_unlock(&mut1); } void compute_ldm(struct Param *param) { int nx = param->nx; int nz = param->nz; int nb = param->nb; int cnx = nx - 2 * d; int cnz = nz - 2 * d; int snx = ceil(cnx * 1.0 / ROW); int snz = ceil(cnz * 1.0 / COL); int cid = 0; int rid = 0; int snxbeg = snx * cid - d + d; int snzbeg = snz * rid - d + d; int snxend = snx * (cid + 1) + d + d; int snzend = snz * (rid + 1) + d + d; snxend = snxend < nx ? snxend : nx; snzend = snzend < nz ? snzend : nz; snx = snxend - snxbeg; snz = snzend - snzbeg; int vel_size = (snx - 2 * d) * (snz - 2 * d) * sizeof(float); int curr_size = snx * snz * sizeof(float); int total = vel_size * 2 + curr_size * 2 + nb * sizeof(float) + 6 * sizeof(float); printf("LDM consume: vel_size = %dB, curr_size = %dB, total = %dB\\n", vel_size, curr_size, total); } int fd4t10s_4cg(void *ptr) { athread_init(); struct Param *param = (struct Param *)ptr; struct Param **params = param->params; int id = param->id; compute_ldm(param); while(1) { slave_wait(param); if(param->exit) break; param->status = 1; int i, j; for(i = 0 ; i < ND ; i ++) { param = params[id + i]; if(param->task == 0) { athread_spawn(fd4t10s_sw, param); athread_join(); } else if(param->task == 1) { athread_spawn(cross_correlation_sw, param); athread_join(); } param = params[id]; } slave_signal(); } } int id, icg, ix, iz; int cnx, cnz; int snx, snz; int snxbeg, snzbeg; int snxend, snzend; pthread_t pt[CG_MAX]; struct Param *params[X_MAX * Z_MAX]; void fd4t10s_nobndry_zjh_2d_vtrans_cg(const float *prev_wave, const float *curr_wave, float *next_wave, const float *vel, float *u2, int nx, int nz, int nb, int nt, int freeSurface) { static int init = 1; if(init) { if(pthread_mutex_init(&mut1, 0) != 0) printf("mutex init error\\n"); if(pthread_cond_init(&cond1, 0) != 0) printf("cond init error\\n"); for(ix = 0 ; ix < X_MAX ; ix ++) { cnx = nx - 2 * d; snx = ceil(cnx * 1.0 / X_MAX); snxbeg = snx * ix - d + d; snxend = snx * (ix + 1) + d + d; snxend = snxend < nx ? snxend : nx; snx = snxend - snxbeg; for(iz = 0 ; iz < Z_MAX ; iz ++) { cnz = nz - 2 * d; snz = ceil(cnz * 1.0 / Z_MAX); snzbeg = snz * iz - d + d; snzend = snz * (iz + 1) + d + d; snzend = snzend < nz ? snzend : nz; snz = snzend - snzbeg; id = ix * Z_MAX + iz; params[id] = (struct Param *)malloc(sizeof(struct Param)); params[id]->nx = snx; params[id]->nz = snz; params[id]->ldnx = nx; params[id]->ldnz = nz; params[id]->nb = nb; params[id]->freeSurface = freeSurface; params[id]->id = id; params[id]->nd = ND; params[id]->icg = id / ND; params[id]->status = 1; params[id]->exit = 0; params[id]->gnxbeg = snxbeg; params[id]->gnzbeg = snzbeg; params[id]->params = params; } } g_status = CG_MAX; } if(init) { for(icg = 0 ; icg < CG_MAX ; icg ++) { int id_beg = icg * ND; pthread_create(&pt[icg], 0, fd4t10s_4cg, (void *)params[id_beg]); } init = 0; } for(ix = 0 ; ix < X_MAX ; ix ++) { cnx = nx - 2 * d; snx = ceil(cnx * 1.0 / X_MAX); snxbeg = snx * ix - d + d; for(iz = 0 ; iz < Z_MAX ; iz ++) { cnz = nz - 2 * d; snz = ceil(cnz * 1.0 / Z_MAX); snzbeg = snz * iz - d + d; id = ix * Z_MAX + iz; params[id]->prev_wave = prev_wave + snxbeg * nz + snzbeg; params[id]->curr_wave = curr_wave + snxbeg * nz + snzbeg; params[id]->next_wave = next_wave + snxbeg * nz + snzbeg; params[id]->vel = vel + snxbeg * nz + snzbeg; params[id]->u2 = u2 + snxbeg * nz + snzbeg; params[id]->task = 0; } } master_signal(params); master_wait(); } void cross_correlation_cg(float *src_wave, float *vsrc_wave, float *image, int nx, int nz, float scale) { for(ix = 0 ; ix < X_MAX ; ix ++) { snx = ceil(nx * 1.0 / X_MAX); snxbeg = snx * ix; snxend = snx * (ix + 1); snxend = snxend < nx ? snxend : nx; snx = snxend - snxbeg; for(iz = 0 ; iz < Z_MAX ; iz ++) { snz = ceil(nz * 1.0 / Z_MAX); snzbeg = snz * iz; snzend = snz * (iz + 1); snzend = snzend < nz ? snzend : nz; snz = snzend - snzbeg; id = ix * Z_MAX + iz; params[id]->src_wave = src_wave + snxbeg * nz + snzbeg; params[id]->vsrc_wave = vsrc_wave + snxbeg * nz + snzbeg; params[id]->image = image + snxbeg * nz + snzbeg; params[id]->scale = scale; params[id]->crnx = snx; params[id]->crnz = snz; params[id]->task = 1; } } master_signal(params); master_wait(); } void fd4t10s_4cg_exit() { int icg; for(icg = 0 ; icg < CG_MAX ; icg ++) params[icg * ND]->exit = 1; master_signal(params); for(icg = 0 ; icg < CG_MAX ; icg ++) { pthread_join(pt[icg], 0); } int ix, iz; for(ix = 0 ; ix < X_MAX ; ix ++) for(iz = 0 ; iz < Z_MAX ; iz ++) free(params[ix * Z_MAX + iz]); }
0
#include <pthread.h> { int count; pthread_mutex_t lock; pthread_mutex_t s; } Semaphore; Semaphore *full, *empty; int in, out; int buffer[16]; static void semaphore_init (Semaphore *s, int i) { pthread_mutex_init (&s->lock, 0); pthread_mutex_init (&s->s, 0); pthread_mutex_lock(&s->s); s->count = i; } static void semaphore_wait (Semaphore *s) { pthread_mutex_lock (&s->lock); s->count--; if (s->count < 0){ pthread_mutex_unlock (&s->lock); pthread_mutex_lock (&s->s); } else pthread_mutex_unlock (&s->lock); } static void semaphore_signal (Semaphore *s) { pthread_mutex_lock (&s->lock); s->count++; if (s->count <= 0) pthread_mutex_unlock (&s->s); pthread_mutex_unlock (&s->lock); } static void put (int data) { semaphore_wait(empty); buffer[in] = data; in = (in + 1) % 16; semaphore_signal(full); } static int get (void){ int data; semaphore_wait(full); data = buffer[out]; out = (out + 1) % 16; semaphore_signal(empty); return data; } static void * producer (void *data) { int n; for (n = 0; n < 10000; n++) { printf ("%d --->\\n", n); put (n); } put ((-1)); return 0; } static void * consumer (void *data) { int d; while (1){ d = get(); if (d == (-1)) break; printf ("<--- %d\\n", d); } return 0; } int main (void) { pthread_t th_a, th_b; void *retval; empty = (Semaphore *) malloc(sizeof(Semaphore)); full = (Semaphore *) malloc(sizeof(Semaphore)); semaphore_init (empty, 16); semaphore_init (full, 0); in = 0; out = 0; pthread_create (&th_a, 0, producer, 0); pthread_create (&th_b, 0, consumer, 0); pthread_join (th_a, &retval); pthread_join (th_b, &retval); return 0; }
1
#include <pthread.h> int A = 5; int B = 5; pthread_mutex_t mutex_A = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_B = PTHREAD_MUTEX_INITIALIZER; void *generate(void *arg) { int i; for (i=1; i<100; i++) { pthread_mutex_lock(&mutex_A); A = i; A = 5; pthread_mutex_unlock(&mutex_A); sleep(1); } return 0; } void *process(void *arg) { while (1) { pthread_mutex_lock(&mutex_A); if (A > 0) { A++; pthread_mutex_lock(&mutex_B); B = A; B--; pthread_mutex_unlock(&mutex_B); A--; pthread_mutex_unlock(&mutex_A); } else pthread_mutex_unlock(&mutex_A); sleep(2); } return 0; } void *dispose(void *arg) { int p; while (1) { pthread_mutex_lock(&mutex_B); if (B > 0) { p = B; pthread_mutex_unlock(&mutex_B); assert(p == 5); } else pthread_mutex_unlock(&mutex_B); sleep(5); } return 0; } int main () { pthread_t t1, t2, t3; int i; pthread_create(&t1, 0, generate, 0); pthread_create(&t2, 0, process, 0); pthread_create(&t3, 0, dispose, 0); for (i=0; i<10; i++) { pthread_mutex_lock(&mutex_A); pthread_mutex_lock(&mutex_B); assert(A == B); pthread_mutex_unlock(&mutex_B); pthread_mutex_unlock(&mutex_A); sleep(3); } return 0; }
0
#include <pthread.h> int fd[2]; int emptypos = 5000; long produceNum = 0; long consumeNum = 0; struct element { int flag; struct element *next; }; struct queue { struct element *head; struct element *tail; }; struct queue myqueue; int empty() { if(!myqueue.head || !myqueue.tail) return 1; else return 0; } int full() { if(emptypos == 0) return 1; else return 0; } void push(struct element *product) { if(empty()) { myqueue.head = product; myqueue.tail = product; (myqueue.head)->next = 0; emptypos--; } else { (myqueue.tail)->next = product; myqueue.tail = product; product = 0; emptypos--; } } struct element* pop() { if(empty()) { return 0; } else { struct element* tmp; tmp = myqueue.head; myqueue.head = (myqueue.head)->next; tmp->next = 0; emptypos++; return tmp; } } int initqueue(int queuelen) { struct element *tmp = 0; myqueue.head = 0; myqueue.tail = 0; for(int i = 0; i < queuelen; i++) { tmp = (struct element *)malloc(sizeof(struct element)); if(0 == tmp) { perror("malloc failed"); exit(1); } tmp->flag = 1; tmp->next = 0; push(tmp); tmp = 0; } return 0; } pthread_cond_t preadyr = PTHREAD_COND_INITIALIZER; pthread_cond_t preadyw = PTHREAD_COND_INITIALIZER; pthread_mutex_t plock = PTHREAD_MUTEX_INITIALIZER; void doproduce(struct element *tmp) { tmp->flag = 1; tmp->next = 0; } void *produce(void *arg) { struct element *tmp = 0; int n = 0; while(1) { n = read(fd[0],&tmp,sizeof(struct element *)); if(0 > n) { perror("read error"); pthread_exit(0); } doproduce(tmp); produceNum++; printf("\\tthread %u produce %ld\\n",(unsigned int)pthread_self(),produceNum); pthread_mutex_lock(&plock); while(full()) { pthread_cond_wait(&preadyw, &plock); } push(tmp); pthread_mutex_unlock(&plock); pthread_cond_broadcast(&preadyr); } } void doconsume(struct element *tmp) { tmp->flag = 0; tmp->next = 0; } void *consume(void *arg) { struct element *tmp = 0; int n = 0; while(1) { tmp = 0; pthread_mutex_lock(&plock); while(empty()) { pthread_cond_wait(&preadyr, &plock); } tmp = pop(); pthread_mutex_unlock(&plock); pthread_cond_broadcast(&preadyw); doconsume(tmp); consumeNum++; n = write(fd[1], &tmp, sizeof(struct element*)); if(0 > n) { perror("write pipe error"); pthread_exit(0); } } } int main(int argc,char *argv[]) { if(argc < 4) { printf("usage:%s producerNum, consumerNum, runtime\\n",argv[0]); exit(1); } int runtime = atoi(argv[3]); printf("aaaa\\n"); initqueue(5000); if(pipe(fd) < 0) { perror("pipe error"); exit(1); } for(int i = 0; i < atoi(argv[1]); i++) { pthread_t protid; if(0 != pthread_create(&protid, 0, produce, 0)) { perror("can't create producer thread"); exit(1); } if(0 != pthread_detach(protid)) { perror("detach error"); exit(1); } } printf("bbbbbbbbb\\n"); for(int j = 0; j < atoi(argv[2]); j++) { pthread_t contid; if(0 != pthread_create(&contid, 0, consume, 0)) { perror("can't create consumer thread"); exit(1); } if(0 != pthread_detach(contid)) { perror("detach error"); exit(1); } } printf("cccccccc\\n"); sleep(runtime); printf("produceNum = %ld, producerate = %ld\\n", produceNum, produceNum/runtime); printf("consumeNum = %ld, consumerate = %ld\\n", consumeNum, consumeNum/runtime); return 0; }
1
#include <pthread.h> static void * recv_thread_func(void * pv); static void * reconnect_thread_func(void * pv); static int connect_server(); int sockfd; unsigned char connect_flag=0; unsigned char recv_thread_start=1; unsigned char reconnect_thread_start=1; char * ip ; int port; char recv_buf[1024]; pthread_mutex_t con_mut; pthread_t recv_thread; pthread_t reconnect_thread; void init_net_server(void) { int recv_state; recv_thread=0; reconnect_thread=0; pthread_mutex_init(&con_mut,0); recv_state=pthread_create(&recv_thread,0,recv_thread_func,0); if(recv_state != 0) { _debug("the recv thread create error ! the recv_state is %d ",recv_state); }else { _debug("the recv thread create success ! the recv_state is %d ",recv_state); } recv_thread_start=1; } int start_server(char * server_ip,int server_port) { int ret; int reconect_state; ip=server_ip; port=server_port; ret=connect_server(); reconect_state=pthread_create(&reconnect_thread,0,reconnect_thread_func,0); if(reconect_state != 0) { _debug("the reconect thread create error ! the reconect_state is %d ",reconect_state); }else { _debug("the reconect thread create success ! the reconect_state is %d ",reconect_state); } reconnect_thread_start=1; return ret; } static int connect_server() { struct sockaddr_in servaddr; int con; sockfd=socket(AF_INET,SOCK_STREAM,0); _debug("the socket stream flag is [%d] ",sockfd); servaddr.sin_family=AF_INET; inet_pton(AF_INET,ip,&servaddr.sin_addr); servaddr.sin_port = htons(port); con=connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)); if(con < 0) { pthread_mutex_lock(&con_mut); connect_flag=0; pthread_mutex_unlock(&con_mut); _debug("connect the server is error ,the con is %d " ,con); close(sockfd); return (-1); } else { pthread_mutex_lock(&con_mut); connect_flag=1; pthread_mutex_unlock(&con_mut); _debug("connect the server is success,the con is %d ",con); return 0; } } int net_send(void * buf,int length) { int error=-1; if(get_connected_state()) { error=write(sockfd,buf,length); } return error; } int net_recv(void * buf,int length) { int error=-1; if(get_connected_state()) { error=read(sockfd,buf,length); } return error; } void set_connected_state(unsigned char s) { pthread_mutex_lock(&con_mut); connect_flag=s; pthread_mutex_unlock(&con_mut); } unsigned char get_connected_state(void) { return connect_flag; } void close_con() { if(get_connected_state() || sockfd >0 ) { close(sockfd); } } static void * recv_thread_func(void * pv) { int recv_len=-1; while(recv_thread_start) { if(get_connected_state()) { _debug("---------------net recv---------------------"); recv_len = read(sockfd,recv_buf,1024); if(recv_len <= 0) { close_con(); set_connected_state(0); } else { _debug("recv : the len is %d , the data is %s ",recv_len,recv_buf); } } } } static void * reconnect_thread_func(void * pv) { while(reconnect_thread_start) { if(!get_connected_state()) { _debug("------------reconnec to the server----------"); connect_server(); } sleep(30); } } void close_thread(void) { recv_thread_start=0; reconnect_thread_start=0; if(recv_thread != 0 ) { pthread_join(recv_thread,0); } if(reconnect_thread != 0) { pthread_join(reconnect_thread,0); } }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void *thread1(void *); void *thread2(void *); int i=1; int main() { pthread_t t_a; pthread_t t_b; pthread_create(&t_a,0,thread1,(void*)0); pthread_create(&t_b,0,thread2,(void*)0); pthread_join(t_b,0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); exit(0); } void *thread1(void *junk) { for(i=1;i<=9;i++) { pthread_mutex_lock(&mutex); if(i%3 == 0) { pthread_cond_signal(&cond); } else printf("thread1:%d\\n",i); pthread_mutex_unlock(&mutex); sleep(1); } } void *thread2(void *junk) { while(i<=9) { pthread_mutex_lock(&mutex); if(i%3 !=0) pthread_cond_wait(&cond,&mutex); printf("thread2:%d\\n",i); pthread_mutex_unlock(&mutex); sleep(1); } }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
0
#include <pthread.h> int qleitor=0; int qescritor=0; pthread_cond_t cond_l, cond_e; pthread_mutex_t mutex; int tid; int count; } t_Args; t_Args global; void *leitor(void* arg){ int tid = *(int*)arg; int boba1=10000, boba2=0; while(1){ pthread_mutex_lock(&mutex); while(qescritor>0) pthread_cond_wait(&cond_l, &mutex); qleitor++; printf("leitor %d leu contador = %d escrito por %d\\n", tid, global.count, global.tid); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); qleitor--; if(qleitor==0) pthread_cond_signal(&cond_e); pthread_mutex_unlock(&mutex); while(boba2<boba1) boba2++; } } void *escritor(void* arg){ int tid = *(int*)arg; while(1){ pthread_mutex_lock(&mutex); while((qleitor>0) || (qescritor>0)) pthread_cond_wait(&cond_e, &mutex); qescritor++; pthread_mutex_unlock(&mutex); global.count++; global.tid = tid; pthread_mutex_lock(&mutex); qescritor--; pthread_cond_signal(&cond_e); pthread_cond_broadcast(&cond_l); pthread_mutex_unlock(&mutex); } } int main(int argc, char*argv[]) { pthread_t *leitores, *escritores; int t; int *tid; global.count = 0; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_l, 0); pthread_cond_init(&cond_e, 0); leitores = (pthread_t *) malloc(sizeof(pthread_t) * 5); if(leitores==0) { printf("--ERRO: leitor malloc()\\n"); exit(1); } escritores = (pthread_t *) malloc(sizeof(pthread_t) * 5); if(escritores==0) { printf("--ERRO: escritor malloc()\\n"); exit(1); } for(t=0;t<5;t++){ tid = malloc(sizeof(int)); if(tid == 0){ printf("--ERRO: malloc()\\n"); exit(1); } *tid = t; if(pthread_create(&leitores[t],0,leitor,(void*)tid)){ printf("--ERRO: leitor pthread_create()\\n"); exit(1); } } for(t=0;t<5;t++){ tid = malloc(sizeof(int)); if(tid == 0){ printf("--ERRO: malloc()\\n"); exit(1); } *tid = t; if(pthread_create(&escritores[t],0,escritor,(void*)tid)){ printf("--ERRO: escritor pthread_create()\\n"); exit(1); } } for(t=0;t<5;t++){ if(pthread_join(leitores[t],0)){ printf("--ERRO: leitor pthread_join()\\n"); exit(1); } } for(t=0;t<5;t++){ if(pthread_join(escritores[t],0)){ printf("--ERRO: escritor pthread_join()\\n"); exit(1); } } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_l); pthread_cond_destroy(&cond_e); free(leitores); free(escritores); return 0; }
1
#include <pthread.h> void *producer_fun(void *arg); void *consumer_fun(void *arg); pthread_mutex_t con_mutex, pro_mutex; sem_t empty, full; int in = -1; int out = -1; int main(void) { pthread_t consumer, producer; int producer_num = 0; int consumer_num = 0; pthread_mutex_init(&pro_mutex, 0); pthread_mutex_init(&con_mutex, 0); sem_init(&empty, 0, 4); sem_init(&full, 0, 0); while(producer_num < 3) { pthread_create(&producer, 0, producer_fun, 0); ++producer_num; } while(consumer_num < 10) { pthread_create(&consumer, 0, consumer_fun, 0); ++consumer_num; } while(1) continue; pthread_mutex_destroy(&pro_mutex); pthread_mutex_destroy(&con_mutex); sem_destroy(&empty); sem_destroy(&full); exit(1); } void *producer_fun(void *arg) { pthread_detach(pthread_self()); while(1) { printf("product a good,waiting\\n"); sem_wait(&empty); pthread_mutex_lock(&pro_mutex); in = (in + 1) % 4; printf("the good is in the buff %d\\n", in); pthread_mutex_unlock(&pro_mutex); sem_post(&full); sleep(3); } } void *consumer_fun(void *arg) { pthread_detach(pthread_self()); while(1) { sem_wait(&full); pthread_mutex_lock(&con_mutex); out = (out + 1) % 4; printf("consumer take out a good in buff %d\\n",out); pthread_mutex_unlock(&con_mutex); sem_post(&empty); sleep(2); } }
0
#include <pthread.h> double sum=0.0, a[1000000]; pthread_mutex_t sum_mutex; void *do_work(void *tid) { int i, start, *mytid, end; double mysum=0.0; mytid = (int *) tid; start = (*mytid * 1000000 / 4); end = start + 1000000 / 4; printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1); for (i=start; i < end ; i++) { a[i] = i * 1.0; mysum = mysum + a[i]; } pthread_mutex_lock (&sum_mutex); sum = sum + mysum; pthread_mutex_unlock (&sum_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, start, tids[4]; pthread_t threads[4]; pthread_attr_t attr; pthread_mutex_init(&sum_mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i=0; i<4; i++) { tids[i] = i; pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]); } for (i=0; i<4; i++) { pthread_join(threads[i], 0); } printf ("Done. Sum= %e \\n", sum); sum=0.0; for (i=0;i<1000000;i++){ a[i] = i*1.0; sum = sum + a[i]; } printf("Check Sum= %e\\n",sum); pthread_attr_destroy(&attr); pthread_mutex_destroy(&sum_mutex); pthread_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 mutx; 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(&mutx, 0); serv_sock=socket(PF_INET, SOCK_STREAM, 0); printf("*****check elevter*****\\n"); 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(&mutx); clnt_socks[clnt_cnt++]=clnt_sock; pthread_mutex_unlock(&mutx); 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; int i = 0; char msg[100]; memset(&msg,0,sizeof(msg)); while(1) { str_len=read(clnt_sock,msg,sizeof(msg)); printf("msg : %s msg_len : %d \\n",msg,str_len); send_msg(msg, str_len); } pthread_mutex_lock(&mutx); 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(&mutx); close(clnt_sock); return 0; } void send_msg(char * msg, int len) { int i; pthread_mutex_lock(&mutx); for(i=0; i<clnt_cnt; i++) write(clnt_socks[i], msg, len); pthread_mutex_unlock(&mutx); } void error_handling(char * msg) { fputs(msg, stderr); fputc('\\n', stderr); exit(1); }
0
#include <pthread.h> int sharedVar = 0; int numReader = 0; pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_write = PTHREAD_COND_INITIALIZER; void *writer (void *param); void *reader (void *param); int main(int argc, char *argv[]) { pthread_t tid1, tid2; int i; if(pthread_create(&tid1, 0, writer, 0) != 0) { fprintf(stderr, "Unable to create writer thread\\n"); exit(1); } if(pthread_create(&tid2, 0, reader, 0) != 0) { fprintf(stderr, "Unable to create reader thread\\n"); exit(1); } for (i = 0; i < 10; ++i) { pthread_join(tid1, 0); pthread_join(tid2, 0); } printf("Parent quiting\\n"); return 0; } void *writer(void *param) { int cntWri; for (cntWri = 0; cntWri < 10; ++cntWri) { usleep((rand()%50)*1000*5); pthread_mutex_lock (&m1); while(numReader != 0) { printf("numReader > 0, wait to write ...\\n"); pthread_cond_wait(&c_write,&m1); } sharedVar = cntWri; pthread_mutex_unlock (&m1); printf("write value %d \\n",cntWri); printf("number of reader is %d \\n",numReader); } return 0; } void *reader(void *param) { int cntRead; int readVal; pthread_mutex_lock(&m2); numReader++; pthread_mutex_unlock(&m2); for (int cntRead = 0; cntRead < 10; ++cntRead) { usleep((rand()%50)*1000*20); pthread_mutex_lock (&m1); readVal = sharedVar; pthread_mutex_unlock (&m1); printf("read value %d \\n",readVal); printf("number of reader is %d \\n",numReader); } pthread_mutex_lock(&m2); numReader--; pthread_mutex_unlock(&m2); if(numReader == 0){ pthread_cond_broadcast(&c_write); } return 0; }
1
#include <pthread.h> int numOfPassengersOnBus; int turn; void* print_message(void* ptr); pthread_mutex_t verrou; struct node { int x; struct node *next; }; int main(int argc, char* argv[]) { pthread_t tProducer, tConsumer1, tConsumer2; const char* msg1 = "Producer"; const char* msg2 = "Consumer"; numOfPassengersOnBus = 0; struct node* list; list = malloc( sizeof(struct node) ); struct node* top; top = list; struct node* tail; tail = list; pthread_mutex_init(&verrou, 0); int r1 = pthread_create(&tProducer, 0, print_message, (void*)msg1 ); int r2 = pthread_create(&tConsumer1, 0, print_message, (void*)msg2 ); pthread_join(tProducer, 0); pthread_join(tConsumer1, 0); return 0; } void* print_message(void* ptr) { srand(time(0)); char* msg = (char*) ptr; while(1) { if(msg[0]=='P') { while(numOfPassengersOnBus>0){}; pthread_mutex_lock(&verrou); if(numOfPassengersOnBus<=0) { numOfPassengersOnBus++; printf("%s produced %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%2); } else { while(numOfPassengersOnBus<=0){}; pthread_mutex_lock(&verrou); if(numOfPassengersOnBus>0) { numOfPassengersOnBus--; printf("%s consumed %d\\n", msg, numOfPassengersOnBus); } pthread_mutex_unlock(&verrou); sleep(rand()%4); } } return 0; }
0
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; struct msg *mp; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { for (;;) { pthread_mutex_lock(&lock); while (head == 0) { pthread_cond_wait(&has_product, &lock); } mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("-Consume ---%d\\n", mp->num); free(mp); sleep(rand() % 5); } } void *producer(void *p) { for (;;) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("-Produce ---%d\\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(int argc, char *argv[]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
1
#include <pthread.h> void errormessage(char *); { int head; int tail; int validItems; char data[5]; pthread_mutex_t lock; }cmdque; cmdque cmd_buff; void errormessage(char *message) { perror(message); exit(1); } void cmd_init(cmdque *cmd_buff) { int i; cmd_buff->head=0; cmd_buff->tail=0; cmd_buff->validItems=0; for(i=0;i<5;i++) cmd_buff->data[i]=0; if(pthread_mutex_init(&cmd_buff->lock,0)!=0) { printf("Mutex failed\\n"); exit(1); } printf("Initialization completed..\\n"); } int isEMPTY(cmdque *cmd_buff) { if(cmd_buff->validItems==0) { printf("CmdQue is empty\\n"); return 1; } else return 0; } int isFULL(cmdque *cmd_buff) { if(cmd_buff->validItems>=5) { printf("CmdQue is full\\n"); return 1; } else return 0; } void cmd_push(cmdque *cmd_buff,char data ) { if(isFULL(cmd_buff)) { printf("You cannot add items..\\n"); } else { cmd_buff->validItems++; cmd_buff->data[cmd_buff->tail] = data; cmd_buff->tail=(cmd_buff->tail + 1)%5; } } void cmd_pop(cmdque *cmd_buff,char *data) { if(isEMPTY(cmd_buff)) { printf("No elements to remove\\n"); *data = -1; } else { *data=cmd_buff->data[cmd_buff->head]; cmd_buff->head=(cmd_buff->head + 1)%5; cmd_buff->validItems--; } } void display_cmdque(cmdque *cmd_buff) { int front,rear,items,i=0; front = cmd_buff->head; rear = cmd_buff->tail; items = cmd_buff->validItems; while(items>0) { printf("head =%d,tail =%d,data=%d front=%d items=%d\\n",cmd_buff->head,cmd_buff->tail,cmd_buff->data[front],front,cmd_buff->validItems); front++; front=front%5; items--; } } void *tid_push(void *arg) { cmdque *tmp; tmp=(cmdque *)arg; int sock; int i=0; int s_bind; int s_accept; int s_listen; unsigned int c_len; struct sockaddr_in s_sock; struct sockaddr_in c_sock; char buffer[100]; char pass[5]; int size_recv; unsigned short serverPORT = 8000; printf("Inside the tid_push\\n"); s_sock.sin_family = AF_INET; s_sock.sin_addr.s_addr = INADDR_ANY; s_sock.sin_port = htons(serverPORT); memset(buffer,0,sizeof(buffer)); memset(pass,0,sizeof(pass)); strcpy(pass,"123"); sock = socket(PF_INET, SOCK_STREAM, 0); if(sock < 0) errormessage("socket creation failed"); s_bind = bind(sock, (struct sockaddr *)&s_sock, sizeof(s_sock)); if(s_bind < 0) errormessage("bind failed"); s_listen = listen(sock, 3); if(s_listen < 0) errormessage("listen failed"); printf("Server initialization ready, waiting for password \\n"); s_accept = accept(sock,(struct sockaddr *)&c_sock, &c_len); if(s_accept < 0) errormessage("accept failed"); printf("Connected... verifing password...\\n"); size_recv = recv(s_accept,buffer,sizeof(buffer),0); if(size_recv < 0 ) errormessage("recv failed"); if(strcmp(buffer,pass) == 0 ) printf("Password success..\\n"); else errormessage("Password failed.. connection closed"); while(1){ memset(buffer,0,sizeof(buffer)); size_recv=recv(s_accept,buffer,sizeof(buffer),0); if(size_recv == 0 ) errormessage("Cleint disconnected.."); pthread_mutex_lock(&tmp->lock); cmd_push((cmdque *)arg,buffer[0]); pthread_mutex_unlock(&tmp->lock); printf("pushed value = %c \\n",buffer[0]); } } void *tid_pop(void *arg) { int i=3; char rem_value=0; cmdque *tmp; tmp=(cmdque *)arg; printf("Inside the tid_pop\\n"); while(1){ pthread_mutex_lock(&tmp->lock); cmd_pop((cmdque *)arg,&rem_value); pthread_mutex_unlock(&tmp->lock); sleep(1); if(rem_value==-1) { } else printf("poped value = %c \\n",rem_value); } } int main() { int rem_value; pthread_t ntid[3]; int tid1,tid2; cmd_init(&cmd_buff); printf("cmd_buff->lock =%p\\n",&cmd_buff.lock); tid1=pthread_create(&(ntid[0]),0,tid_push,&cmd_buff); if(tid1!=0) { printf("Cant create thread\\n"); return 0; } tid2=pthread_create(&(ntid[1]),0,tid_pop,&cmd_buff); if(tid2!=0) { printf("Cant create thread\\n"); return 0; } pthread_join(ntid[1],0); pthread_join(ntid[0],0); display_cmdque(&cmd_buff); return 0; }
0
#include <pthread.h> struct employee { int number; int id; char first_name[32]; char last_name[32]; char department[32]; int root_number; }; struct employee employees[] = { { 1, 12345678, "astro", "Bluse", "Accounting", 101 }, { 2, 87654321, "Shrek", "Charl", "Programmer", 102 }, }; struct employee employee_of_the_day; void copy_employee(struct employee *from, struct employee *to) { memcpy(to, from, sizeof(struct employee)); } pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *do_loop(void *data) { int num = *(int *)data; while (1) { pthread_mutex_lock(&lock); copy_employee(&employees[num - 1], &employee_of_the_day); pthread_mutex_unlock(&lock); } } int main(int argc, const char *argv[]) { pthread_t th1, th2; int num1 = 1; int num2 = 2; int i; copy_employee(&employees[0], &employee_of_the_day); if (pthread_create(&th1, 0, do_loop, &num1)) { errx(1, "pthread_create() error.\\n"); } if (pthread_create(&th2, 0, do_loop, &num2)) { errx(1, "pthread_create() error.\\n"); } while (1) { pthread_mutex_lock(&lock); struct employee *p = &employees[employee_of_the_day.number - 1]; if (p->id != employee_of_the_day.id) { printf("mismatching 'id', %d != %d (loop '%d')\\n", employee_of_the_day.id, p->id, i); exit(1); } if (strcmp(p->first_name, employee_of_the_day.first_name)) { printf("mismatching 'first_name', %s != %s (loop '%d')\\n", employee_of_the_day.first_name, p->first_name, i); exit(1); } if (strcmp(p->last_name, employee_of_the_day.last_name)) { printf("mismatching 'last_name', %s != %s (loop '%d')\\n", employee_of_the_day.last_name, p->last_name, i); exit(1); } if (strcmp(p->department, employee_of_the_day.department)) { printf("mismatching 'department', %s != %s (loop '%d')\\n", employee_of_the_day.department, p->department, i); exit(1); } if (p->root_number != employee_of_the_day.root_number) { printf("mismatching 'root_number', %d != %d (loop '%d')\\n", employee_of_the_day.root_number, p->root_number, i); exit(1); } printf("lory, employees contents was always consistent\\n"); pthread_mutex_unlock(&lock); } exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; sem_t semaphore[2]; char buffer[N_BUFFER][13], temp[13]; int ptr_read = 0, finish = 0; int escolher_ficheiro(){ int id_file = rand() % 5; return id_file; } int leitor(){ int file, i, wrong, x; char linha[10], primeira[10], filename[13]; while(1){ wrong = 0; i = 0; if(finish) break; if(sem_wait(&semaphore[0]) != 0){ perror("Wait on semaphore0: Failed"); return -1; } if(finish) break; if(pthread_mutex_lock(&mutex) != 0){ perror("Lock mutex: Failed"); return -1; } strcpy(filename, buffer[ptr_read]); if(strcmp(filename, "") == 0){ pthread_mutex_unlock(&mutex); continue; } ptr_read = (ptr_read + 1) % N_BUFFER; if(pthread_mutex_unlock(&mutex) != 0){ perror("Unlock mutex: Failed"); return -1; } if(sem_post(&semaphore[1]) != 0){ perror("Post semaphore1: Failed"); return -1; } file = open(filename, O_RDONLY | PERMISSION_CODE_R); if (file < 0){ perror("Open: Failed.\\n"); continue; } if(flock(file, LOCK_SH) < 0){ perror("Flock on Lock: Failed.\\n"); close(file); return -1; } x = read(file, primeira, 10); printf("%d\\n", x); if(x < 10){ perror("First Read: Failed.\\n"); flock(file, LOCK_UN); close(file); continue; } while(read(file, linha, 10) != 0){ if(strncmp(primeira, linha, 10) != 0){ perror("Linha nao corresponde: Erro.\\n"); wrong = 1; } if(wrong) break; i++; } if(flock(file, LOCK_UN) < 0){ perror("Flock on Unlock: Failed.\\n"); close(file); return -1; } close(file); if(wrong) continue; if(i != (N_LINES - 1)){ perror("Não acabou o ficheiro: Erro.\\n"); return -1; } printf("Read success on %s!\\n", filename); } return 0; } int main(){ int i, receive; pthread_t thread_array[N_THREAD_READ]; int ptr_write = 0; srand(time(0)); if(pthread_mutex_init(&mutex, 0) != 0){ perror("Initialize mutex: Failed"); return -1; } for(i = 0; i < 2; i++){ if(sem_init(&semaphore[i], 0, i * N_BUFFER) != 0){ perror("Initialize semaphore: Failed"); return -1; } } for(i = 0; i < N_THREAD_READ; i++){ if(pthread_create(&thread_array[i], 0, (void *) leitor, 0) != 0){ perror("Create thread: Failed"); return -1; } } while(1){ if(sem_wait(&semaphore[1]) != 0){ perror("Wait semaphore1: Failed"); return -1; } receive = read(0, temp, N_INPUT); if(receive < 0){ perror("Read stream: Failed!\\n"); continue; } else if(receive == 0){ finish = 1; for(i = 0; i < N_THREAD_READ; i++) sem_post(&semaphore[0]); break; } strcpy(buffer[ptr_write], temp); ptr_write = (ptr_write + 1) % N_BUFFER; if(sem_post(&semaphore[0]) != 0){ perror("Post semaphore0: Failed"); return -1; } } puts("Reader finished"); for(i = 0; i < N_THREAD_READ; i++){ if(pthread_join(thread_array[i], 0) != 0){ perror("Join thread: Failed"); } } return 0; }
0
#include <pthread.h> int buffer = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_consumer = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_productor = PTHREAD_COND_INITIALIZER; void* consumer_th(void* arg) { pthread_mutex_lock(&mutex); for (;;) { sleep(1); if (buffer <= 0) { printf("=%s->%d=====consumer wait productor to product..., buffer=%d\\n", __func__, 23, buffer); pthread_cond_wait(&cond_consumer, &mutex); } buffer--; printf("=%s->%d====consumer consume a buffer, buffer=%d\\n", __func__, 28, buffer); if (0 == buffer) { pthread_cond_signal(&cond_productor); printf("=%s->%d====Notify productor...,, buffer: %d\\n", __func__, 33, buffer); } } pthread_mutex_unlock(&mutex); return 0; } void* productor_th(void* arg) { for (;;) { sleep(1); pthread_mutex_lock(&mutex); if (buffer >= 5) { printf("=%s->%d=====productor wait consume buffer to 0..., buffer=%d\\n", __func__, 53, buffer); pthread_cond_signal(&cond_productor); } buffer++; printf("=%s->%d====Product add a buffer..., buffer: %d\\n", __func__, 58, buffer); if (5 == buffer) { pthread_cond_signal(&cond_consumer); printf("=%s->%d====Notify consumer...,, buffer: %d\\n", __func__, 63, buffer); } pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, const char* argv[]) { pthread_t tid_productor, tid_consumer; if (0 != pthread_create(&tid_consumer, 0, consumer_th, 0)) { printf("pthread_create failed!\\n"); return -1; } if (0 != pthread_create(&tid_productor, 0, productor_th, 0)) { printf("pthread_create failed!\\n"); return -1; } pthread_join(tid_productor, 0); pthread_join(tid_consumer, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; static void *start(void *str) { char buffer[1024]; snprintf(buffer, sizeof (buffer), "thread in %s\\n", str); printf("%s", buffer); pthread_mutex_lock(&mutex); return 0; } int main(int argc, char **argv) { void *handle = dlopen(SHARED_LIBRARY, RTLD_NOW | RTLD_LOCAL); if (!handle) { fprintf(stderr, "dlopen(%s): %s\\n", SHARED_LIBRARY, dlerror()); return 1; } pthread_mutex_init(&mutex, 0); pthread_mutex_lock(&mutex); pthread_t thread; if (pthread_create(&thread, 0, start, argv[0])) { fprintf(stderr, "pthread_create(): %m\\n"); return 1; } union { void *addr; void *(*fn)(void *); } sym; sym.addr = dlsym(handle, "hello"); if (!sym.addr) { fprintf(stderr, "%s: symbol 'hello' not found\\n", SHARED_LIBRARY); dlclose(handle); return 1; } sym.fn(argv[0]); dlclose(handle); pthread_mutex_unlock(&mutex); pthread_join(thread, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> int sillas = 4; int pendiente = 0; pthread_mutex_t enanoMtx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t blancaMtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t enanoCond = PTHREAD_COND_INITIALIZER; pthread_cond_t blancaCond = PTHREAD_COND_INITIALIZER; void * blancaCtrl(void*); void * enanoCtrl(void*); int main(void) { int i = 0; srand(time(0)); pthread_t tBlanca = pthread_create(&tBlanca, 0, blancaCtrl, 0); pthread_t * tEnano = (pthread_t*)malloc(sizeof(pthread_t) * 7); for (i = 0; i < 7; i++) pthread_create(tEnano + i, 0, enanoCtrl, i); for (i = 0; i < 7; i++) pthread_join(*(tEnano + i), 0); pthread_join(tBlanca, 0); free(tEnano); return 0; } void * blancaCtrl(void * arg) { while (1) { pthread_mutex_lock(&blancaMtx); if (pendiente == 0) { printf("B :: Vuelta\\n"); pthread_cond_wait(&blancaCond, &blancaMtx); } printf("B :: Pedir\\n"); pthread_mutex_unlock(&blancaMtx); printf("B :: Cocinando\\n"); sleep(rand() % 5); pthread_mutex_lock(&blancaMtx); pendiente--; pthread_cond_signal(&enanoCond); pthread_mutex_unlock(&blancaMtx); printf("B :: Liberando\\n"); } pthread_exit(0); } void * enanoCtrl(void * arg) { while (1) { printf("E :: trabajando\\n", (int)arg); sleep(rand() % 17); pthread_mutex_lock(&enanoMtx); if (sillas > 0) { sillas--; printf(" E(%d) :: Sentado en %d silla\\n", (int)arg, sillas); pthread_mutex_unlock(&enanoMtx); pthread_mutex_lock(&blancaMtx); pendiente++; pthread_mutex_unlock(&blancaMtx); pthread_cond_signal(&blancaCond); printf(" E(%d) :: Pidiendo\\n", (int)arg); pthread_mutex_lock(&blancaMtx); pthread_cond_wait(&enanoCond, &blancaMtx); pthread_mutex_unlock(&blancaMtx); printf(" E(%d) :: Comiendo\\n", (int)arg); sleep(rand() % 2); pthread_mutex_lock(&enanoMtx); sillas++; printf(" E(%d) :: Dejando la %d silla\\n", (int)arg, sillas); pthread_mutex_unlock(&enanoMtx); } else { printf(" E(%d) :: No disponible\\n", (int)arg); pthread_mutex_unlock(&enanoMtx); } } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t emptySlots; pthread_cond_t filledSlots; int N; int buffer[10000]; int in = 0; int out = 0; int count = 0; int fin = 0; int num; void *producer(void *param); void *consumer(void *param); int main(int argc, char *argv[]){ int i = 0; if (argc != 2) { fprintf(stderr,"usage: 'nameOfFile.txt' \\n"); return -1; } FILE *entrada; int ch, num_lineas; entrada = fopen(argv[1], "r"); num_lineas = 0; while ((ch = fgetc(entrada)) != EOF) if (ch == '\\n') num_lineas++; fclose(entrada); int NThreads = num_lineas * 2; N = NThreads; pthread_t tid[NThreads]; pthread_mutex_init(&mutex, 0); pthread_cond_init(&emptySlots, 0); pthread_cond_init(&filledSlots, 0); fin = open(argv[1], O_RDONLY,0); startTimer(); for(i=0;i<NThreads;i++) { if(i%2 == 0) pthread_create(&tid[i],0,producer,0); if(i%2 == 1) pthread_create(&tid[i],0,consumer,0); } for(i=0;i<NThreads;i++) pthread_join(tid[i],0); printf("Time: %ld\\n",endTimer()); return 0; } void *producer(void *param){ int res = 0; char buffin[1000]; int num; usleep(5000+rand()%100); pthread_mutex_lock(&mutex); if(count == N) pthread_cond_wait(&emptySlots, &mutex); count++; while(res != -1){ res = readSplit(fin, buffin, '\\n', 1000); sscanf(buffin,"%d",&num); buffer[in] = num; in = (in+1); } pthread_mutex_unlock(&mutex); pthread_cond_signal(&filledSlots); pthread_exit(0); } void *consumer(void *param){ int num; int prime; pthread_mutex_lock(&mutex); if(count == 0) pthread_cond_wait(&filledSlots, &mutex); count--; num = buffer[out]; prime = isPrime(num); if(prime == 0){ printf("The number %d is prime\\n", num); }else{ printf("The number %d is not prime\\n", num); } out = (out+1)%N; pthread_mutex_unlock(&mutex); pthread_cond_signal(&emptySlots); usleep(1000+rand()%100); pthread_exit(0); }
0
#include <pthread.h> extern void init_scheduler(int); extern int scheduleme(float, int, int, int); FILE *fd; struct _thread_info { int id; float arrival_time; int required_time; int priority; }; double _global_time; float _last_event_time; pthread_mutex_t _time_lock; pthread_mutex_t _last_event_lock; void set_last_event(float last_event) { pthread_mutex_lock(&_last_event_lock); if (last_event > _last_event_time) _last_event_time = last_event; pthread_mutex_unlock(&_last_event_lock); } float get_global_time() { return _global_time; } void advance_global_time(float next_arrival) { pthread_mutex_lock(&_time_lock); float next_ms = floor(_global_time + 1.0); if ((next_arrival < next_ms) && (next_arrival > 0)) _global_time = next_arrival; else _global_time = next_ms; pthread_mutex_unlock(&_time_lock); } float read_next_arrival(float *arrival_time, int *id, int *required_time, int *priority) { *arrival_time = -1.0; char c[15]; fscanf(fd, "%f.1", arrival_time); fgets(c, 1, fd); fscanf(fd, "%d", id); fgets(c, 1, fd); fscanf(fd, "%d", required_time); fgets(c, 1, fd); fscanf(fd, "%d", priority); fgets(c, 10, fd); return *arrival_time; } int open_file(char *filename) { char mode = 'r'; fd = fopen(filename, &mode); if (fd == 0) { printf("Invalid input file specified: %s\\n", filename); return -1; } else { return 0; } } void close_file() { fclose(fd); } void *worker_thread(void *arg) { _thread_info_t *myinfo = (_thread_info_t *)arg; float time_remaining = myinfo->required_time * 1.0; float scheduled_time; set_last_event(myinfo->arrival_time); scheduled_time = scheduleme(myinfo->arrival_time, myinfo->id, time_remaining, myinfo->priority); while (time_remaining > 0) { set_last_event(scheduled_time); printf("%3.0f - %3.0f: T%d\\n", scheduled_time, scheduled_time + 1.0, myinfo->id); while(get_global_time() < scheduled_time + 1.0) { sched_yield(); } time_remaining -= 1.0; scheduled_time = scheduleme(get_global_time(), myinfo->id, time_remaining, myinfo->priority); } free(myinfo); pthread_exit(0); } int _pre_init(int sched_type) { pthread_mutex_init(&_time_lock, 0); pthread_mutex_init(&_last_event_lock, 0); init_scheduler(sched_type); _global_time = 0.0; _last_event_time = -1.0; } int main(int argc, char *argv[]) { int inactivity_timeout = 50; if (argc < 3) { printf ("Not enough parameters specified. Usage: a.out <scheduler_type> <input_file>\\n"); printf (" Scheduler type: 0 - First Come, First Served (Non-preemptive)\\n"); printf (" Scheduler type: 1 - Shortest Remaining Time First (Preemptive)\\n"); printf (" Scheduler type: 2 - Priority-based Scheduler (Preemptive)\\n"); printf (" Scheduler type: 3 - Multi-Level Feedback Queue w/ Aging (Preemptive)\\n"); return -1; } if (open_file(argv[2]) < 0) return -1; _pre_init(atoi(argv[1])); int this_thread_id = 0; _thread_info_t *ti; float next_arrival_time; pthread_t pt; ti = malloc(sizeof(_thread_info_t)); next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority)); if (next_arrival_time < 0) return -1; pthread_create(&pt, 0, worker_thread, ti); while (_last_event_time != ti->arrival_time) sched_yield(); ti = malloc(sizeof(_thread_info_t)); next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority)); while ((get_global_time() - _last_event_time) < inactivity_timeout) { advance_global_time(next_arrival_time); if (get_global_time() == next_arrival_time) { pthread_create(&pt, 0, worker_thread, ti); while (_last_event_time < ti->arrival_time) { sched_yield(); } ti = malloc(sizeof(_thread_info_t)); next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority)); if (next_arrival_time < 0) { free(ti); } } else { int loop_counter = 0; while ((_last_event_time < get_global_time()) && (loop_counter < 100000)) { loop_counter++; sched_yield(); } } } close_file(); return 0; }
1
#include <pthread.h> void initMutex(pthread_mutex_t *mutexsum) { pthread_mutex_init(mutexsum, 0); } void lockMutex(pthread_mutex_t *mutexsum) { pthread_mutex_lock (mutexsum); } int lockMutexAndWait(pthread_mutex_t *mutexsum) { int errCode; int retval = 1; struct timespec abs_timeout; clock_gettime(CLOCK_REALTIME, &abs_timeout); abs_timeout.tv_sec += 8; errCode = pthread_mutex_timedlock (mutexsum, &abs_timeout); if(errCode != 0) { printf("Errot Code %d" , errCode); retval = 0; } return retval; } void releaseMutex(pthread_mutex_t *mutexsum) { pthread_mutex_unlock (mutexsum); }
0
#include <pthread.h> pthread_mutex_t ctr_mutex; pthread_cond_t ctr_cond; int ctr; void *add(void *p) { while(ctr < 10) { pthread_mutex_lock(&ctr_mutex); ctr++; printf("ADD: New value of ctr is %d\\n", ctr); if(ctr>=10) { printf("ADD: Reached limit of %d! Waking up print thread\\n", 10); pthread_cond_signal(&ctr_cond); } pthread_mutex_unlock(&ctr_mutex); sleep(1); } pthread_exit(0); } void *print(void *p) { pthread_mutex_lock(&ctr_mutex); printf("PRINT: Current value of ctr is %d\\n", ctr); if(ctr < 10) { printf("PRINT: ctr is too small. Zzzz.. g'night!\\n"); pthread_cond_signal(&ctr_cond); pthread_cond_wait(&ctr_cond, &ctr_mutex); printf("PRINT: ctr is now %d! Exiting thread.\\n", ctr); } pthread_mutex_unlock(&ctr_mutex); pthread_exit(0); } int main() { pthread_t threads[2]; ctr=0; pthread_mutex_init(&ctr_mutex, 0); pthread_cond_init(&ctr_cond, 0); pthread_create(&threads[1], 0, print, 0); pthread_mutex_lock(&ctr_mutex); pthread_cond_wait(&ctr_cond, &ctr_mutex); pthread_create(&threads[0], 0, add, 0); pthread_mutex_unlock(&ctr_mutex); pthread_join(threads[1], 0); pthread_mutex_destroy(&ctr_mutex); pthread_cond_destroy(&ctr_cond); pthread_exit(0); }
1
#include <pthread.h> pthread_t filosofos[5]; int pratos[5]; pthread_mutex_t palitos[5]; void *filosofo(void *args) { int *ptr = (int*) (args); int N = (*ptr); printf("Entrando no filosofo %d\\n", N); while (pratos[N] < 5) { pthread_mutex_lock(& (palitos[N]) ); pthread_mutex_lock(& (palitos[(N+1)%5]) ); pratos[N] += 1; printf("Filosofo %d: prato %d\\n", N, pratos[N]); sleep(1); pthread_mutex_unlock(& (palitos[N]) ); pthread_mutex_unlock(& (palitos[(N+1)%5]) ); } return 0; } int main() { int k; int idx[5]; for (int i=0; i<5; i++) { idx[i] = i; pthread_create(& (filosofos[i]), 0, filosofo, &(idx[i]) ); } while (1) { sleep(1); k=0; for (int i=0; i<5; i++) if (pratos[i] < 5) k++; printf("Thread principal esta viva! Faltam %d filosofos\\n", k); if (k==0) break; } }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (12 == count) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count < 12) { printf("watch_count(): thread %ld Count = %d. Going into wait ... \\n", my_id, count); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count = %d\\n", my_id, count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); 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 and joined with %d threads. Final value of count = %d. Done. \\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t theMutex; pthread_cond_t condc, condp; int buffer=0; void* producer(void* ptr) { int x; for(x=0; x<=4; x++) { pthread_mutex_lock(&theMutex); printf("Producer Locked\\n"); while(buffer!=0) { printf("Producer waiting\\n"); pthread_cond_wait(&condp, &theMutex); } printf("Producer creating widget %d\\n", x); buffer=x; printf("Signaling Consumer\\n"); pthread_cond_signal(&condc); pthread_mutex_unlock(&theMutex); printf("Producer unlocked\\n"); } pthread_exit(0); } void* consumer(void* ptr) { int x; for(x=1; x<=4; x++) { pthread_mutex_lock(&theMutex); printf("Consumer locked\\n"); while(buffer==0) { printf("Consumer waiting\\n"); pthread_cond_wait(&condc, &theMutex); } printf("Consumer consuming widget %d\\n", x); buffer=0; printf("Signaling Producer\\n"); pthread_cond_signal(&condp); pthread_mutex_unlock(&theMutex); printf("Consumer unlocked\\n"); } pthread_exit(0); } int main() { pthread_t pro, con; pthread_mutex_init(&theMutex, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); printf("Creating Consumer\\n"); pthread_create(&con, 0, consumer, 0); printf("Creating Producer\\n"); pthread_create(&pro, 0, producer, 0); printf("Executing Producer\\n"); pthread_join(pro, 0); printf("Executing Consumer\\n"); pthread_join(con, 0); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); pthread_mutex_destroy(&theMutex); return 0; }
0
#include <pthread.h> pthread_mutex_t write_lock; pthread_mutex_t read_lock; enum Status i2c_temp_init(uint8_t fd,uint8_t addr) { if(addr == 0x48 || addr == 0x49 || addr == 0x4A || addr==0x4B) { if(ioctl(fd,I2C_SLAVE,addr)<0) { return FAIL; } return SUCCESS; } else return FAIL; } enum Status i2c_light_init(uint8_t fd,uint8_t addr) { if(addr == 0x29 || addr == 0x39 || addr == 0x49) { if(ioctl(fd,I2C_SLAVE,addr)<0) { stat = FAIL; } stat = SUCCESS; stat = write_light_registers(fd,T_LOW,0x1500); if (stat) { printf("\\nERR:Could not write value into T_LOW Register\\n"); } stat = write_light_registers(fd,T_HIGH,0xFFFF); if(stat) { printf("\\nERR:Could not write value into T_HIGH Register\\n"); } } else stat = FAIL; return stat; } enum Status i2c_write(uint8_t fd,uint8_t *val) { pthread_mutex_init(&write_lock,0); pthread_mutex_lock(&write_lock); if(write(fd,val,1)!=1) { return FAIL; } pthread_mutex_unlock(&write_lock); pthread_mutex_destroy(&write_lock); return SUCCESS; } enum Status i2c_write_word(uint8_t fd,uint8_t *val) { pthread_mutex_init(&write_lock,0); pthread_mutex_lock(&write_lock); if(write(fd,val,3)!=3) { return FAIL; } pthread_mutex_unlock(&write_lock); pthread_mutex_destroy(&write_lock); return SUCCESS; } enum Status i2c_write_light(uint8_t fd,uint8_t *val) { if(write(fd,val,2)!=2) { return FAIL; } return SUCCESS; } enum Status i2c_read_word(uint8_t fd,uint8_t *val) { pthread_mutex_init(&read_lock,0); pthread_mutex_lock(&read_lock); if(read(fd,val,2)!=2) { return FAIL; } pthread_mutex_unlock(&read_lock); pthread_mutex_destroy(&read_lock); return SUCCESS; } enum Status i2c_read(uint8_t fd,uint8_t *val) { pthread_mutex_init(&read_lock,0); pthread_mutex_lock(&read_lock); if(read(fd,val,1)!=1) { return FAIL; } pthread_mutex_unlock(&read_lock); pthread_mutex_destroy(&read_lock); return SUCCESS; }
1
#include <pthread.h> char* key; char* value; size_t value_len; struct hash_item** pprev; struct hash_item* next; } hash_item; hash_item* hash[1024]; pthread_mutex_t hash_mutex; hash_item* hash_get(const char* key, int create) { unsigned b = string_hash(key) % 1024; hash_item* h = hash[b]; while (h != 0 && strcmp(h->key, key) != 0) { h = h->next; } if (h == 0 && create) { h = (hash_item*) malloc(sizeof(hash_item)); h->key = strdup(key); h->value = 0; h->value_len = 0; h->pprev = &hash[b]; h->next = hash[b]; hash[b] = h; if (h->next != 0) { h->next->pprev = &h->next; } } return h; } void* connection_thread(void* arg) { int cfd = (int) (uintptr_t) arg; FILE* fin = fdopen(cfd, "r"); FILE* f = fdopen(cfd, "w"); pthread_detach(pthread_self()); char buf[1024], key[1024]; size_t sz; while (fgets(buf, 1024, fin)) { pthread_mutex_lock(&hash_mutex); if (sscanf(buf, "get %s ", key) == 1) { hash_item* h = hash_get(key, 0); if (h != 0) { fprintf(f, "VALUE %s %zu %p\\r\\n", key, h->value_len, h); fwrite(h->value, 1, h->value_len, f); fprintf(f, "\\r\\n"); } fprintf(f, "END\\r\\n"); fflush(f); } else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) { hash_item* h = hash_get(key, 1); free(h->value); h->value = (char*) malloc(sz); h->value_len = sz; fread(h->value, 1, sz, fin); fprintf(f, "STORED %p\\r\\n", h); fflush(f); } else if (sscanf(buf, "delete %s ", key) == 1) { hash_item* h = hash_get(key, 0); if (h != 0) { free(h->key); free(h->value); *h->pprev = h->next; if (h->next) { h->next->pprev = h->pprev; } free(h); fprintf(f, "DELETED %p\\r\\n", h); } else { fprintf(f, "NOT_FOUND\\r\\n"); } fflush(f); } else if (remove_trailing_whitespace(buf)) { fprintf(f, "ERROR\\r\\n"); fflush(f); } pthread_mutex_unlock(&hash_mutex); } if (ferror(fin)) { perror("read"); } fclose(fin); (void) fclose(f); return 0; } int main(int argc, char** argv) { int port = 6168; if (argc >= 2) { port = strtol(argv[1], 0, 0); assert(port > 0 && port <= 65535); } int fd = open_listen_socket(port); pthread_mutex_init(&hash_mutex, 0); while (1) { int cfd = accept(fd, 0, 0); if (cfd < 0) { perror("accept"); exit(1); } pthread_t t; int r = pthread_create(&t, 0, connection_thread, (void*) (uintptr_t) cfd); if (r != 0) { perror("pthread_create"); exit(1); } } }
0
#include <pthread.h> int nextNum; pthread_mutex_t nextNumLock; pthread_mutex_t genPrimesLock; int getNext() { int temp; pthread_mutex_lock(&nextNumLock); nextNum++; temp = nextNum; pthread_mutex_unlock(&nextNumLock); return temp; } void addPrime(int newPrime) { pthread_mutex_lock(&genPrimesLock); generatedPrimes = (int*) realloc(generatedPrimes, sizeof(generatedPrimes[0]) * (generatedPrimesSize+1)); generatedPrimes[generatedPrimesSize] = newPrime; generatedPrimesSize++; pthread_mutex_unlock(&genPrimesLock); } void *controlMain(void* args) { pthread_t* genThreads = args; int i=0; pthread_mutex_init(&nextNumLock, 0); pthread_mutex_init(&genPrimesLock, 0); for(i=0; i<numThreads; i++) { pthread_join(genThreads[i],0); } terminate = 1; printf("Found primes: %d\\n", generatedPrimesSize); pthread_mutex_destroy(&nextNumLock); pthread_mutex_destroy(&genPrimesLock); printf("All generation threads have completed, exiting.\\n"); pthread_exit(0); }
1
#include <pthread.h> static char running = 1; static long long counter = 0; pthread_mutex_t c_mutex; int i; void *process (void *arg) { while (running) { pthread_mutex_lock (&c_mutex); if (i > 4) pthread_exit (0); counter++; pthread_mutex_unlock (&c_mutex); } pthread_exit (0); } int main () { pthread_t threadId; void *retval; pthread_mutex_init (&c_mutex, 0); if (pthread_create (&threadId, 0, process, "0")) { perror("pthread_create"); exit(errno); }; for (i = 0; i < 10; i++) { sleep (1); pthread_mutex_lock (&c_mutex); printf ("%lld\\n", counter); pthread_mutex_unlock (&c_mutex); } running = 0; if (pthread_join (threadId, &retval)) { perror("pthread_join"); exit(errno); }; return 0; }
0
#include <pthread.h> static void process_function(); static void process_function_actual(int job_type); static int process_judege(struct Job *job); extern void ftp_file_manage_init(){ register_job(JOB_TYPE_FTP_FILE_MANAGE,process_function,process_judege,CALL_BY_TCP_DATA_MANAGE); } static void process_function(){ int job_type = JOB_TYPE_FTP_FILE_MANAGE; while(1){ pthread_mutex_lock(&(job_mutex_for_cond[job_type])); pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type])); pthread_mutex_unlock(&(job_mutex_for_cond[job_type])); process_function_actual(job_type); } } static void process_function_actual(int job_type){ struct Job_Queue private_jobs; private_jobs.front = 0; private_jobs.rear = 0; get_jobs(job_type,&private_jobs); struct Job current_job; time_t nowtime; struct tcp_stream *a_tcp; while(!jobqueue_isEmpty(&private_jobs)){ jobqueue_delete(&private_jobs,&current_job); if(current_job.client_rev == 0|| current_job.client_rev->head == 0 || current_job.client_rev->head->data == 0|| current_job.client_rev->head->length == 0) continue; pthread_mutex_lock(&ftp_file_mutex); struct FTP_FILE_NODE *one_ftp_file = ftp_file_list_find_remove(&ftp_file_list,current_job.current_desport); pthread_mutex_unlock(&ftp_file_mutex); if(one_ftp_file == 0){ continue; } struct Ftp_file_manage_information ftp_file_manange_information; if(one_ftp_file->user == 0) ftp_file_manange_information.user = ""; else ftp_file_manange_information.user = one_ftp_file->user; if(one_ftp_file->password == 0) ftp_file_manange_information.password = ""; else ftp_file_manange_information.password = one_ftp_file->password; if(one_ftp_file->file_name == 0) ftp_file_manange_information.file_name = ""; else ftp_file_manange_information.file_name = one_ftp_file->file_name; if(one_ftp_file->handle == 0) ftp_file_manange_information.handle = ""; else ftp_file_manange_information.handle = one_ftp_file->handle; char *type = safe_file_judge_type(current_job.client_rev->head->data,current_job.client_rev->head->length); if(type == 0) ftp_file_manange_information.file_type = ""; else ftp_file_manange_information.file_type = type; ftp_file_manange_information.data = current_job.client_rev->head->data; ftp_file_manange_information.data_length = current_job.client_rev->head->length; sql_factory_add_ftp_record(&ftp_file_manange_information,current_job.hash_index); if(current_job.client_rev != 0){ wireless_list_free(current_job.client_rev); free(current_job.client_rev); } free(one_ftp_file); } } static int process_judege(struct Job *job){ struct FTP_FILE_NODE *point; job->data_need = 1; job->ismutildesport =1; int i; pthread_mutex_lock(&ftp_file_mutex); point = ftp_file_list.head; while(point != 0){ job->desports[job->number_desports++] = point->desport; point = point->next; } pthread_mutex_unlock(&ftp_file_mutex); if(job->number_desports == 0) return 0; return 1; }
1
#include <pthread.h> struct sk_buff * alloc_skb(uint32_t datasize) { struct sk_buff *skb = malloc(sizeof(struct sk_buff)); skb->dev = 0; skb->dst = 0; skb->protocol = 0; skb->len = 0; skb->data = malloc(datasize); skb->head = skb->data; skb->tail = skb->data; skb->end = skb->data+ datasize; skb->alloc_mode = SKBUFF_ALLOC_DEFAULT; } struct sk_buff * alloc_p_skb(uint8_t *buf,uint32_t len) { struct sk_buff *skb = malloc(sizeof(struct sk_buff)); skb->dev = 0; skb->dst = 0; skb->list = 0; skb->prev = 0; skb->next = 0; skb->protocol = 0; skb->len = 0; skb->data = buf; skb->head = skb->data; skb->tail = skb->data; skb->end = skb->data+ len; skb->alloc_mode = SKBUFF_ALLOC_PARTIAL; } void free_skb(struct sk_buff* skb) { if(skb->alloc_mode == SKBUFF_ALLOC_DEFAULT) free(skb->head); free(skb); } static uint8_t* __skb_put(struct sk_buff* skb,uint32_t len) { uint8_t *tmp = skb->tail; skb->tail += len; skb->len += len; return tmp; } static uint8_t * __skb_push(struct sk_buff * skb,uint32_t len) { skb->data -= len; skb->len += len; return skb->data; } static uint8_t* __skb_pull(struct sk_buff *skb,uint32_t len) { skb->len -= len; return skb->data += len; } uint8_t* skb_put(struct sk_buff* skb,uint32_t len) { return __skb_put(skb,len); } uint8_t * skb_push(struct sk_buff * skb,uint32_t len) { return __skb_push(skb,len); } uint8_t* skb_pull(struct sk_buff *skb,uint32_t len) { return __skb_pull(skb,len); } void skb_reserve(struct sk_buff* skb,uint32_t len) { skb->data += len; skb->tail += len; } void skb_queue_init(struct sk_buff_head * list) { list->prev = (struct sk_buff *)list; list->next = (struct sk_buff *)list; list->len = 0; pthread_mutex_init(&list->lock,0); } void skb_queue_push_front(struct sk_buff_head * list,struct sk_buff * skb) { pthread_mutex_lock(&list->lock); skb->list = list; struct sk_buff * tprev = (struct sk_buff *)list; struct sk_buff* tnext = list->next; skb->prev = tprev; skb->next = tnext; tprev->next = skb; tnext->prev = skb; list->len++; pthread_mutex_unlock(&list->lock); } void skb_queue_push_back(struct sk_buff_head * list,struct sk_buff * skb) { pthread_mutex_lock(&list->lock); skb->list = list; struct sk_buff * tnext = (struct sk_buff *)list; struct sk_buff* tprev = list->prev; skb->prev = tprev; skb->next = tnext; tprev->next = skb; tnext->prev = skb; list->len++; pthread_mutex_unlock(&list->lock); } struct sk_buff * skb_queue_pop_front(struct sk_buff_head *list) { pthread_mutex_lock(&list->lock); struct sk_buff * tprev = (struct sk_buff*) list; struct sk_buff * res = list->next; if(tprev == res) { pthread_mutex_unlock(&list->lock); return 0; } struct sk_buff * tnext = res->next; tprev->next = tnext; tnext->prev = tprev; list->len--; res->next = 0; res->prev = 0; res->list = 0; pthread_mutex_unlock(&list->lock); return res; } struct sk_buff * skb_queue_pop_back(struct sk_buff_head *list) { pthread_mutex_lock(&list->lock); struct sk_buff * tnext = (struct sk_buff*) list; struct sk_buff * res = list->prev; if(tnext == res) { pthread_mutex_unlock(&list->lock); return 0; } struct sk_buff * tprev = res->prev; tprev->next = tnext; tnext->prev = tprev; list->len--; res->next = 0; res->prev = 0; res->list = 0; pthread_mutex_unlock(&list->lock); return res; }
0
#include <pthread.h> static State gamestate; int row; int col; char under_char; }frog_info; static frog_info frog; int id; Direction dir; int row; int sleeptime; }log_line_info; static log_line_info logs_info[(20)]; pthread_t log_thread[(20)]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; const char grass[]="||||||||"; const char logs[]="==== "; const char frog_entity[] = "O"; char lines[(20)][((sizeof(logs)-1)*(8)+1)]; void init_game(int num_logs_per_line){ int i,j; for(i=0;i<num_logs_per_line;i++){ strcat(lines[(0)],grass); strcat(lines[((20) + (0) + 1)],grass); for(j=(0)+1;j<((20) + (0) + 1);j++) strcat(lines[j],logs); } for(i=0;i<num_logs_per_line;i++){ mvprintw((0),0,lines[(0)]); mvprintw(((20) + (0) + 1),0,lines[((20) + (0) + 1)]); for(j=(0)+1;j<((20) + (0) + 1);j++) mvprintw(j,0,lines[j]); } }; void init_log_line(log_line_info *log,int id,Direction dir){ log->id=id; log->dir=dir; log->row=id+(0)+1; log->sleeptime=(rand()%10+1)*100000; } void init_frog(){ frog.row=((20) + (0) + 1); frog.col=((sizeof(logs)-1)*(8)+1)/2; frog.under_char = '|'; mvprintw(frog.row,frog.col,frog_entity); } void log_line_move(log_line_info *log){ pthread_mutex_lock(&mutex); char tmpline[((sizeof(logs)-1)*(8)+1)]; int length; int row = log->id+(0)+1; length=strlen(lines[row]); strcpy(tmpline,lines[row]); if(log->dir==LEFT){ strncpy(lines[row],(const char *)(tmpline+1),length-1); lines[row][length-1]=tmpline[0]; } else{ strncpy(lines[row]+1,(const char *)tmpline,length-1); lines[row][0]=tmpline[length-1]; } mvprintw(row,0,lines[row]); if(frog.row==row){ frog.col=frog.col+((log->dir==LEFT)?-1:1); mvprintw(frog.row,frog.col,frog_entity); } if(frog.col<0||frog.col>(((sizeof(logs)-1)*(8)+1)-2)) gamestate=LOSE; move(0,0); refresh(); pthread_mutex_unlock(&mutex); } void *log_function(void *data){ log_line_info *log; log = (log_line_info *)data; while(gamestate==PLAYING){ log_line_move(log); usleep(log->sleeptime); } return 0; } void move_frog(State state){ pthread_mutex_lock(&mutex); mvprintw(frog.row,frog.col,&(frog.under_char)); switch(state){ case UP: if(frog.row>(0)) frog.row--; break; case DOWN: if(frog.row<((20) + (0) + 1)) frog.row++; break; case LEFT: if(frog.col>0) frog.col--; break; case RIGHT: if(frog.col<((sizeof(logs)-1)*(8)+1)-2) frog.col++; break; default: break; } mvprintw(frog.row,frog.col,frog_entity); frog.under_char=lines[frog.row][frog.col]; if(frog.under_char==' ') gamestate=LOSE; if(frog.row==(0)) gamestate=WIN; move(0,0); refresh(); pthread_mutex_unlock(&mutex); } int main(int argc,char *argv[]){ int i; char ch; Direction dir=LEFT; srand(time(0)); initscr(); clear(); cbreak(); noecho(); keypad(stdscr,TRUE); timeout(100); init_game((8)); for(i=0;i<(20);i++){ init_log_line(&logs_info[i],i,dir); dir=(dir==LEFT)?RIGHT:LEFT; } init_frog(); gamestate=PLAYING; refresh(); for(i=0;i<(20);i++) pthread_create(&log_thread[i],0,&log_function,&logs_info[i]); while(gamestate==PLAYING){ ch=getch(); switch(ch){ case 'w': move_frog(UP); break; case 's': move_frog(DOWN); break; case 'a': move_frog(LEFT); break; case 'd': move_frog(RIGHT); break; case 'q': gamestate=QUIT; break; default: break; } } for(i=0;i<(20);i++) pthread_join(log_thread[i],0); echo(); nocbreak(); endwin(); switch(gamestate){ case WIN: printf("You WIN!!\\n"); break; case LOSE: printf("You LOSE!!\\n"); break; case QUIT: printf("You QUIT!!\\n"); break; default: printf("This state should be unreached\\n"); break; } exit(0); }
1
#include <pthread.h> uint32_t ip; uint16_t port; uint32_t readopcnt; uint32_t writeopcnt; struct _csdbentry *next; } csdbentry; static csdbentry *csdbhtab[256]; static pthread_mutex_t *csdblock; void csdb_init(void) { uint32_t i; for (i=0 ; i<256 ; i++) { csdbhtab[i]=0; } csdblock = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(csdblock,0); } uint32_t csdb_getreadcnt(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); uint32_t result = 0; csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { result = e->readopcnt; break; } } pthread_mutex_unlock(csdblock); return result; } uint32_t csdb_getwritecnt(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); uint32_t result = 0; csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { result = e->writeopcnt; break; } } pthread_mutex_unlock(csdblock); return result; } uint32_t csdb_getopcnt(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); uint32_t result = 0; csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { result = e->readopcnt + e->writeopcnt; break; } } pthread_mutex_unlock(csdblock); return result; } void csdb_readinc(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { e->readopcnt++; pthread_mutex_unlock(csdblock); return; } } e = malloc(sizeof(csdbentry)); e->ip = ip; e->port = port; e->readopcnt = 1; e->writeopcnt = 0; e->next = csdbhtab[hash]; csdbhtab[hash] = e; pthread_mutex_unlock(csdblock); } void csdb_readdec(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { e->readopcnt--; pthread_mutex_unlock(csdblock); return; } } pthread_mutex_unlock(csdblock); } void csdb_writeinc(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { e->writeopcnt++; pthread_mutex_unlock(csdblock); return; } } e = malloc(sizeof(csdbentry)); e->ip = ip; e->port = port; e->readopcnt = 0; e->writeopcnt = 1; e->next = csdbhtab[hash]; csdbhtab[hash] = e; pthread_mutex_unlock(csdblock); } void csdb_writedec(uint32_t ip,uint16_t port) { uint32_t hash = (((ip)*0x7b348943+(port))%(256)); csdbentry *e; pthread_mutex_lock(csdblock); for (e=csdbhtab[hash] ; e ; e=e->next) { if (e->ip == ip && e->port == port) { e->writeopcnt--; pthread_mutex_unlock(csdblock); return; } } pthread_mutex_unlock(csdblock); }
0
#include <pthread.h> int timer_getoverrun (timerid) timer_t timerid; { struct timer_node *timer; int retval = -1; pthread_mutex_lock (&__timer_mutex); if (! timer_valid (timer = timer_id2ptr (timerid))) __set_errno (EINVAL); else retval = 0; pthread_mutex_unlock (&__timer_mutex); return retval; }
1
#include <pthread.h> void *find_min(void *) ; pthread_mutex_t minimum_value_lock; long int partial_list_size; int minimum_value; long int *list; long int NumElements, CLASS_SIZE; int NumThreads; int main (int argc,char * argv[]) { pthread_t *threads; pthread_attr_t pta; int iteration,THREADS,ret_count; double time_start, time_end; struct timeval tv; struct timezone tz; double MemoryUsed = 0.0; char * CLASS; int counter; printf("\\n\\t\\t--------------------------------------------------------------------------"); printf("\\n\\t\\t Centre for Development of Advanced Computing (C-DAC)"); printf("\\n\\t\\t C-DAC Multi Core Benchmark Suite 1.0"); printf("\\n\\t\\t Email : RarchK"); printf("\\n\\t\\t---------------------------------------------------------------------------"); printf("\\n\\t\\t Objective : Sorting Single Dimension Array (Integer Operations)\\n "); printf("\\n\\t\\t Performance of Sorting a Minimum value in a large Single Dimension Array "); printf("\\n\\t\\t on Multi Socket Multi Core Processor using 1/2/4/8 threads \\n"); printf("\\n\\t\\t..........................................................................\\n"); if( argc != 3 ){ printf("\\t\\t Very Few Arguments\\n "); printf("\\t\\t Syntax : exec <Class-Size> <Threads>\\n"); exit(-1); } else { CLASS = argv[1]; THREADS = atoi(argv[2]); } if( strcmp(CLASS, "A" )==0){ CLASS_SIZE = 10000000; } if( strcmp(CLASS, "B" )==0){ CLASS_SIZE = 100000000; } if( strcmp(CLASS, "C" )==0){ CLASS_SIZE = 1000000000; } NumElements = CLASS_SIZE; NumThreads = THREADS; printf("\\n\\t\\t Array Size : %ld",NumElements); printf("\\n\\t\\t Threads : %d",NumThreads); printf("\\n"); if (NumThreads < 1 ) { printf("\\n Number of threads must be greater than zero. Aborting ...\\n"); return 0; } if ((NumThreads != 1) && (NumThreads != 2) && (NumThreads != 4) && (NumThreads != 8)) { printf("\\n Number of Threads must be 1 or 2 or 4 or 8. Aborting ...\\n"); return 0; } if ( ( NumElements % NumThreads ) != 0 ) { printf("\\n Number of threads not a factor of Integer List size. Aborting.\\n"); return 0 ; } partial_list_size = NumElements / NumThreads; list = (long int *)malloc(sizeof(long int) * NumElements); MemoryUsed += ( NumElements * sizeof(long int)); gettimeofday(&tv, &tz); time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; for(counter = 0 ; counter < NumElements ; counter++){ srand48((unsigned int)NumElements); list[counter] = (rand()%1000)+1.0; } threads = (pthread_t *)malloc(sizeof(pthread_t)*NumThreads); minimum_value = list[0]; ret_count=pthread_mutex_init(&minimum_value_lock, 0); if(ret_count) { printf("\\n ERROR : Return code from pthread_mutex_init() is %d ",ret_count); exit(-1); } ret_count=pthread_attr_init(&pta); if(ret_count) { printf("\\n ERROR : Return code from pthread_attr_init() is %d ",ret_count); exit(-1); } pthread_attr_setscope(&pta,PTHREAD_SCOPE_SYSTEM); for(counter = 0 ; counter < NumThreads ; counter++) { ret_count=pthread_create(&threads[counter],&pta,(void *(*) (void *)) find_min,(void *) (counter+1)); if(ret_count) { printf("\\n ERROR : Return code from pthread_create() is %d ",ret_count); exit(-1); } } for(counter = 0 ; counter < NumThreads ; counter++) { ret_count=pthread_join(threads[counter],0); if(ret_count) { printf("\\n ERROR : Return code from pthread_join() is %d ",ret_count); exit(-1); } } ret_count=pthread_attr_destroy(&pta); if(ret_count) { printf("\\n ERROR : Return code from pthread_attr_destroy() is %d ",ret_count); exit(-1); } gettimeofday(&tv, &tz); time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0; printf("\\n\\t\\t Minimum Value found in the Integer list : %d",minimum_value); printf("\\n\\t\\t Memory Utilised : %lf MB",(MemoryUsed / (1024*1024))); printf("\\n\\t\\t Time Taken in Seconds (T) : %lf Seconds",( time_end - time_start)); printf("\\n\\t\\t..........................................................................\\n"); free(list); free(threads); return 0; } void *find_min(void * myid ) { int my_min; long int counter; int myId = (int)myid; my_min = list[(myId-1)*partial_list_size]; for (counter = ((myId - 1) * partial_list_size); counter <= ((myId * partial_list_size) - 1); counter++){ if (list[counter] < my_min) my_min = list[counter]; } pthread_mutex_lock(&minimum_value_lock) ; if (my_min < minimum_value) minimum_value = my_min; pthread_mutex_unlock(&minimum_value_lock) ; pthread_exit(0); }
0
#include <pthread.h> static int g_temp_cute_leak_check = 0; static pthread_mutex_t mmap_mutex = PTHREAD_MUTEX_INITIALIZER; void init_mmap_mutex() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mmap_mutex, &attr); pthread_mutexattr_destroy(&attr); } void deinit_mmap_mutex() { } static struct cute_mmap_ctx *get_cute_mmap_ctx_tail(struct cute_mmap_ctx *mmap) { struct cute_mmap_ctx *p; if (mmap == 0) { return 0; } for (p = mmap; p->next != 0; p = p->next) ; return p; } struct cute_mmap_ctx *add_allocation_to_cute_mmap_ctx(struct cute_mmap_ctx *mmap, size_t size, void *addr) { struct cute_mmap_ctx *head = 0; struct cute_mmap_ctx *p = 0; if (g_cute_last_ref_file == 0) { return mmap; } pthread_mutex_lock(&mmap_mutex); head = mmap; if (head == 0) { ( g_temp_cute_leak_check = g_cute_leak_check, g_cute_leak_check = 0, (head) = tru_malloc(sizeof(struct cute_mmap_ctx)), (head)->next = 0, (head)->line_nr = g_cute_last_exec_line, strncpy((head)->file_path, g_cute_last_ref_file, sizeof((head)->file_path)-1), g_cute_leak_check = g_temp_cute_leak_check ); p = head; } else { p = get_cute_mmap_ctx_tail(mmap); ( g_temp_cute_leak_check = g_cute_leak_check, g_cute_leak_check = 0, (p->next) = tru_malloc(sizeof(struct cute_mmap_ctx)), (p->next)->next = 0, (p->next)->line_nr = g_cute_last_exec_line, strncpy((p->next)->file_path, g_cute_last_ref_file, sizeof((p->next)->file_path)-1), g_cute_leak_check = g_temp_cute_leak_check ); p = p->next; } p->id = ++g_cute_mmap_id; p->size = size; p->addr = addr; if (p->id == g_cute_leak_id) { raise(SIGTRAP); } pthread_mutex_unlock(&mmap_mutex); return head; } struct cute_mmap_ctx *rm_allocation_from_cute_mmap_ctx(struct cute_mmap_ctx *mmap, void *addr) { struct cute_mmap_ctx *head = 0; struct cute_mmap_ctx *burn = 0; struct cute_mmap_ctx *last = 0; pthread_mutex_lock(&mmap_mutex); head = mmap; if (mmap == 0) { pthread_mutex_unlock(&mmap_mutex); return 0; } for (burn = mmap; burn != 0; last = burn, burn = burn->next) { if (burn->addr == addr) { break; } } if (burn != 0) { if (last == 0) { head = burn->next; burn->next = 0; } else { last->next = burn->next; burn->next = 0; } free(burn); } pthread_mutex_unlock(&mmap_mutex); return head; } void del_cute_mmap_ctx(struct cute_mmap_ctx *mmap) { struct cute_mmap_ctx *p = 0, *t = 0; int temp = 0; pthread_mutex_lock(&mmap_mutex); temp = g_cute_leak_check; g_cute_leak_check = 0; for (t = p = mmap; t != 0; p = t) { t = p->next; tru_free(p); } g_cute_leak_check = temp; pthread_mutex_unlock(&mmap_mutex); }
1
#include <pthread.h> void *worker(void *params) { t_worker_thread *worker; t_thread_pool *parent; t_queue **active_threads; t_queue **idle_threads; worker = params; parent = worker->parent; active_threads = &parent->active_threads; idle_threads = &parent->idle_threads; worker->running = 1; pthread_mutex_lock(&worker->mutex); pthread_cond_signal(&worker->ready_cond); pthread_mutex_unlock(&worker->mutex); while (worker->running) { pthread_mutex_lock(&worker->mutex); pthread_cond_wait(&worker->cond, &worker->mutex); pthread_mutex_unlock(&worker->mutex); queue_enqueue(active_threads, new_lst(worker)); worker->thread_job->task_function(worker->thread_job->params); queue_remove(active_threads, worker); queue_enqueue(idle_threads, new_lst(worker)); pthread_mutex_lock(&worker->mutex); if (++(parent->tasks_done) >= parent->max_tasks) sem_post(parent->done); pthread_mutex_unlock(&worker->mutex); } return (0); }
0
#include <pthread.h> static pthread_mutex_t piMutexes [4] ; int piThreadCreate (void *(*fn)(void *)) { pthread_t myThread ; return pthread_create (&myThread, 0, fn, 0) ; } void piLock (int key) { pthread_mutex_lock (&piMutexes [key]) ; } void piUnlock (int key) { pthread_mutex_unlock (&piMutexes [key]) ; }
1
#include <pthread.h> int common=0; int common2=0; pthread_mutex_t lck; pthread_mutex_t lck2; void* print(void* unused) { int x=1,i; int retval; pthread_mutex_lock(&lck); common++; sleep(1); printf("Common: %d\\tx: %d ( Thread ID: %d )\\n",common,x,(int)pthread_self()); fflush(stdout); x++; pthread_mutex_unlock(&lck); pthread_mutex_lock(&lck2); printf("a"); fflush(stdout); pthread_mutex_unlock(&lck2); } int main(int argc, char *argv[]) { pthread_mutex_init (&lck, 0); pthread_mutex_init (&lck2, 0); int i; pthread_t threads[3]; for(i=0;i<3;i++) pthread_create (&(threads[i]),0,&print,0); for(i=0;i<3;i++) pthread_join(threads[i],0); pthread_exit(0); }
0
#include <pthread.h> static int init(void) { if (LOCK_INIT == 1) return (0); LOCK_INIT = 1; pthread_mutex_init(&g_locker, 0); return (ft_init_malloc()); } void *malloc(size_t size) { void *ptr; if (init() || size == 0) return (0); pthread_mutex_lock(&g_locker); ptr = malloc_unsafe(size); pthread_mutex_unlock(&g_locker); return (ptr); } void free(void *addr) { if (init()) return ; pthread_mutex_lock(&g_locker); free_unsafe(addr); pthread_mutex_unlock(&g_locker); } void *realloc(void *addr, size_t size) { void *ptr; if (init() || size == 0) return (0); pthread_mutex_lock(&g_locker); ptr = realloc_unsafe(addr, size); pthread_mutex_unlock(&g_locker); return (ptr); }
1
#include <pthread.h> int N=100; int T=4; pthread_mutex_t count_lock; pthread_cond_t ok_to_proceed; int count; } barrier; double escalar; barrier *barrera; double max, min, suma; double *R; double* M[4]; pthread_mutex_t mutexMax; pthread_mutex_t mutexMin; pthread_mutex_t mutexAvg; double dwalltime(){ double sec; struct timeval tv; gettimeofday(&tv,0); sec = tv.tv_sec + tv.tv_usec/1000000.0; return sec; } void *hilar(void *s){ int i,k,j,c; int tid = *((int*)s); int inicio=tid*(N/T); int fin=inicio+N/T; double minLocal, maxLocal, sumaLocal; minLocal=9999; maxLocal=-999; sumaLocal=0; for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ R[i*N+j]=0; if(M[0][i*N+j] < minLocal) minLocal=M[0][i*N+j]; if(M[0][i*N+j] > maxLocal) maxLocal=M[0][i*N+j]; if(M[1][i*N+j] < minLocal) minLocal=M[1][i*N+j]; if(M[1][i*N+j] > maxLocal) maxLocal=M[1][i*N+j]; sumaLocal+=M[0][i*N+j]+M[1][i*N+j]; for(c=0;c<N;++c){ R[i*N+j]+=M[0][i*N+c]*M[1][c+j*N]; } } } for(k=2;k<4;++k){ if(k%2==1){ for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ R[i*N+j]=0; if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j]; if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j]; sumaLocal+=M[k][i*N+j]; for(c=0;c<N;++c){ R[i*N+j]+=M[0][i*N+c]*M[k][c+j*N]; } } } } else { for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ M[0][i*N+j]=0; if(M[k][i*N+j] < minLocal) minLocal=M[k][i*N+j]; if(M[k][i*N+j] > maxLocal) maxLocal=M[k][i*N+j]; sumaLocal+=M[k][i*N+j]; for(c=0;c<N;++c){ M[0][i*N+j]+=R[i*N+c]*M[k][c+j*N]; } } } } } pthread_mutex_lock(&mutexMax); if(maxLocal>max) max=maxLocal; pthread_mutex_unlock(&mutexMax); pthread_mutex_lock(&mutexMin); if(minLocal<min) min=minLocal; pthread_mutex_unlock(&mutexMin); pthread_mutex_lock(&mutexAvg); suma+=sumaLocal; pthread_mutex_unlock(&mutexAvg); pthread_mutex_lock(&(barrera -> count_lock)); barrera -> count ++; if (barrera -> count == T){ barrera -> count = 0; escalar=pow(((max-min)/(suma/(N*N*4))),4); if(4%2 == 1){ free(R); R=M[0]; } pthread_cond_broadcast(&(barrera -> ok_to_proceed)); }else{ pthread_cond_wait(&(barrera -> ok_to_proceed),&(barrera -> count_lock)); } pthread_mutex_unlock(&(barrera -> count_lock)); for(i=inicio;i<fin;++i){ for(j=0;j<N;++j){ R[i*N+j] *= escalar; } } } int main(int argc,char*argv[]){ int i,j,k; double timetick; if ((argc != 3) || ((N = atoi(argv[1])) <= 0) || ((T = atoi(argv[2])) <= 0)) { printf("\\nUsar: %s n t\\n n: Dimension de la matriz (nxn X nxn)\\n t: Cantidad de threads\\n", argv[0]); exit(1); } R=(double*)malloc(sizeof(double)*N*N); for(i=0;i<4;i++){ M[i]=(double*)malloc(sizeof(double)*N*N); } for(k=0;k<4;++k){ for(i=0;i<N;++i){ for(j=0;j<N;++j){ M[k][i*N+j] = (double) (rand() % 1000000000); } } } pthread_t p_threads[T]; pthread_attr_t attr; pthread_attr_init (&attr); int id[T]; pthread_mutex_init(&mutexMax, 0); pthread_mutex_init(&mutexMin, 0); pthread_mutex_init(&mutexAvg, 0); barrera = (barrier*)malloc(sizeof(barrier)); barrera -> count = 0; pthread_mutex_init(&(barrera -> count_lock), 0); pthread_cond_init(&(barrera -> ok_to_proceed), 0); min=9999; max=-999; suma=0; timetick = dwalltime(); for(i=0;i<T;i++){ id[i]=i; pthread_create(&p_threads[i], &attr, hilar, (void *) &id[i]); } for(i=0;i<T;i++){ pthread_join(p_threads[i],0); } printf("\\nTiempo en segundos %f\\n", dwalltime() - timetick); free(barrera); free(R); for(i=1;i<4;i++){ free(M[i]); } return(0); }
0
#include <pthread.h> float* normProf(long double *temp , int nbins); long double maxArray(long double *temp , int nbins); float maxBand(float *temp , int nchans); float minBand(float *temp , int nchans); struct parameters check_adc; struct POLYCO polyco; void *plotFold(void *pa) { int i,check; float f,g,*xb,max,*xval,min,bmin,bmax; long int nacc = 0; long double *temp; float *prof; long double phase; double mjd; long long int samp=0, samp1 =0; int bin =0; double tsmp; int flag; int nbins; long double psec; check_adc = inputParameters(); nbins = check_adc.nbins; pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); tsmp = check_adc.nacc*timeSample; while(flag==1) { if(samp1==0 || nbins != check_adc.nbins) { samp1=0; nbins=check_adc.nbins; temp = (long double *) malloc(nbins*sizeof(long double)); } xval = (float *) malloc(nbins*sizeof(float)); xb = (float *) malloc(check_adc.nfft/2*sizeof(float)); if(samp1 == 0) { for(i=0;i<nbins;i++) { xval[i] = (float) i; xval[i] = ((xval[i]/nbins)*4800)+100; temp[i] = 0.0; } } pthread_mutex_lock(&fold_mutex); check = foldVal; pthread_mutex_unlock(&fold_mutex); while(check != 1) { pthread_mutex_lock(&fold_mutex); check = foldVal; pthread_mutex_unlock(&fold_mutex); pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); if(flag==0) { free(temp); free(xval); free(xb); free(timeSeries); return; } } check_adc = inputParameters(); mjd = tstart +(tsmp*samp)/(86400); get_nearest_polyco(adc.polyco_file,mjd,&polyco); psec=polyco_period(mjd,polyco); for(i=0;i<nsout1;i++) { phase = (long double)(((long double)samp)*((long double)tsmp)/psec); phase = phase - (long int)(phase); samp1++; samp++; bin = (int)(((long double) nbins )*phase); temp[bin] += timeSeries[i]; } prof = normProf(temp,nbins); for(i=0;i<check_adc.nfft/2;i++) { xb[i] = (float)i; } max = maxBand(prof,nbins); min = minBand(prof,nbins); if(samp1 > (int)(check_adc.facc/(check_adc.nacc*timeSample))) { free(temp); samp1 =0; } cpgbeg(0,"/xs",1,1); cpgenv(0,5000,0,5000,0,-2); cpgaxis("N", 100, 3000, 100, 3000 +2000, -0.2+min, max+0.2, 0.5, 5, 0.3, 0.0, 0.5, -1, 0); cpgaxis("N", 100, 3000, 100 +4800, 3000, 1, (float) nbins, ((float)nbins/10), 5, -0.3, 0.0, 0.5, 0.5, 0); for(i=0;i<nbins;i++) { xval[i] = (((float)i/(float)nbins)*4800)+100; prof[i] = 3000 +2000*(prof[i]+0.2-min)/(max-min+0.4); } cpgmtxt("B",-34,0.5,.5,"PULSE PROFILE"); if(check_adc.correlation == 0 && check_adc.gpu != 1) { cpgmtxt("B",-15,0.5,.5,"BAND SHAPE"); pthread_mutex_lock(&finalBand_mutex); bmax = maxBand(finalBand,check_adc.nfft/2); bmin = minBand(finalBand,check_adc.nfft/2); cpgaxis("N", 100, 100, 100, 100 +2000, bmin, bmax, ((int)(bmax-bmin)/2), 5, 0.3, 0.0, 0.5, -1, 0); cpgaxis("N", 100, 100, 100 +4800, 100, 1, check_adc.nfft/2, check_adc.nfft/20, 5, -0.3, 0.0, 0.5, 0.5, 0); for(i=0;i<check_adc.nfft/2;i++) { xb[i] = ((xb[i]/(check_adc.nfft/2))*4800)+100; finalBand[i] = 100 +2000*(finalBand[i]-bmin)/(bmax-bmin); } cpgline(check_adc.nfft/2,xb,finalBand); pthread_mutex_unlock(&finalBand_mutex); } cpgline(nbins,xval,prof); free(prof); free(xb); free(xval); pthread_mutex_lock(&fold_mutex); foldVal=0; printf("finished in the folding thread %d \\n",foldVal); fflush(stdout); pthread_mutex_unlock(&fold_mutex); pthread_mutex_lock(&foldStop_mutex); flag = foldStop; pthread_mutex_unlock(&foldStop_mutex); } return(0); } float* normProf(long double *temp , int nbins) { int i; long double max; float *prof; prof = (float*) malloc(nbins*sizeof(float)); max = maxArray(temp,nbins); if(max == 0) max =1; for(i=0;i<nbins;i++) { prof[i] = (float)(temp[i]/(long double)max); } return prof; } long double maxArray(long double *temp , int nbins) { int i; long double t=0.0; for(i=0;i<nbins;i++) { if(temp[i] > t) { t = temp[i]; } } return t; } float maxBand(float *temp , int nchans) { int i; float t=0.0; for(i=0;i<nchans;i++) { if(temp[i] > t) { t = temp[i]; } } return t; } float minBand(float *temp , int nchans) { int i; float t = 3000000.0; for(i=0;i<nchans;i++) { if(temp[i] < t) { t = temp[i]; } } return t; }
1
#include <pthread.h> pthread_mutex_t mutex; void* writing() { time_t rawtime; struct tm *timeinfo; int file; int num_str = 1; char str[100]; while(1) { pthread_mutex_lock(&mutex); time(&rawtime); timeinfo = localtime(&rawtime); file = open("time.txt", O_CREAT|O_WRONLY|O_APPEND, 0700); write(file, str, strlen(str)); num_str++; pthread_mutex_unlock(&mutex); sleep(1); } pthread_exit(0); } void* reading() { int file; int str_read = 0; int str_write = 0; char str[100]; while(1) { pthread_mutex_lock(&mutex); file = open("time.txt", O_CREAT|O_RDONLY, 0700); while ((str_read = read(file, str, 128)) > 0) { str_write = write (1, str, str_read); } printf("&&&&&&&&&&&&&&&&&&&&\\n"); pthread_mutex_unlock(&mutex); sleep(5); } pthread_exit(0); } int main (int argc, char* argv[]) { pthread_t writer; pthread_t readers [10]; int i; if(pthread_create(&writer, 0, writing, 0)<0) { printf("ERROR: create writer thread false\\n"); return -1; } for (i = 0; i<10; ++i) { if(pthread_create(&readers[i], 0, reading, 0)<0) { printf("ERROR: create reading thread %d false\\n", i); return -1; } } if(pthread_join(writer, 0)<0) { printf("ERROR: joining writer thread false\\n"); return -1; } for (i = 0; i<10; ++i) { if(pthread_join(readers[i], 0)<0) { printf("ERROR: joining reading thread %d false\\n", i); return -1; } } return 0; }
0
#include <pthread.h> struct single_pty { int master; int slave; pthread_mutex_t lock; } array[500]; struct array_info { struct single_pty *array; int size; }; static void *ptmx_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i, tries; while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->master == -1) { for (tries = 0; tries < 1; tries++) { cur->master = open("/dev/ptmx", O_RDWR); if (cur->master >= 0) break; } if (tries == 1) { printf("*** cannot open /dev/ptmx: " "%s\\n", strerror(errno)); fflush(stdout); cur->master = -1; } } pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void *slave_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i, tries; char *ptsn; while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->master != -1 && cur->slave == -1) { ptsn = ptsname(cur->master); if (ptsn == 0) goto out; for (tries = 0; tries < 1; tries++) { cur->slave = open(ptsn, O_RDWR | O_NONBLOCK); if (cur->slave >= 0) break; } if (tries == 1) ; } out: pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void *reader_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i; char buff[200]; while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->master != -1 && cur->slave != -1) read(cur->slave, buff, sizeof(buff)); pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void *writer_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i; char buff[200]; memset(buff, 'a', sizeof(buff)); while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->master != -1) write(cur->master, buff, sizeof(buff)); if (cur->slave != -1) write(cur->slave, buff, sizeof(buff)); pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void *ptmx_closer_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i; while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->master != -1) { close(cur->master); cur->master = -1; } pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void *slave_closer_thread(void *arg) { struct array_info *info = arg; struct single_pty *array = info->array, *cur; int size = info->size, i; while (1) { for (i = 0; i < 500; ) { cur = &array[i]; pthread_mutex_lock(&cur->lock); if (cur->slave != -1) { close(cur->slave); cur->slave = -1; } pthread_mutex_unlock(&cur->lock); i += ((rand() % 10) + 1); } } return 0; } static void sodomize_pty(struct single_pty *array, int size) { int i; struct array_info info = { .array = array, .size = size }; pthread_t last; printf("Creating threads...\\n"); fflush(stdout); for (i = 0; i < 50; i++) { switch(rand() % 6) { case 0: if (pthread_create(&last, 0, ptmx_thread, &info)) { perror("Error creating thread: "); return; } break; case 1: if (pthread_create(&last, 0, slave_thread, &info)) { perror("Error creating thread: "); return; } break; case 2: if (pthread_create(&last, 0, reader_thread, &info)) { perror("Error creating thread: "); return; } break; case 3: if (pthread_create(&last, 0, writer_thread, &info)) { perror("Error creating thread: "); return; } break; case 4: if (pthread_create(&last, 0, ptmx_closer_thread, &info)) { perror("Error creating thread: "); return; } break; case 5: if (pthread_create(&last, 0, slave_closer_thread, &info)) { perror("Error creating thread: "); return; } break; } } pthread_join(last, 0); } int main(int argc, char *argv[]) { int i; for (i = 0; i < 500; i++) pthread_mutex_init(&array[i].lock, 0); sodomize_pty(array, 500); }
1
#include <pthread.h> static sigset_t set; static pthread_mutex_t mutex; static unsigned char run = 1; static char buffer[128]; static unsigned char readline(void) { int idx = 0; char ch; ch = getchar(); while (ch >= 0) { if (ch == '\\n' || idx == 128 -2) { buffer[idx++] = ' '; buffer[idx] = '\\0'; break; } else { buffer[idx++] = ch; } ch = getchar(); } return ch < 0; } static void *wait_start(void *arg) { int sig; while (1) { sigwait(&set, &sig); if (sig == SIGINT) { printf("SIGINT has been sensed.\\n"); pthread_mutex_lock(&mutex); run = 0; pthread_mutex_unlock(&mutex); break; } } } static unsigned char parseline(char *cmdline, char **argv) { unsigned char bg; char *delim = 0; char *buf = cmdline; int argc = 0, idx; while (*buf && (*buf == ' ')) { buf++; } while (delim = strchr(buf, ' ')) { argv[argc++] = buf; *delim = '\\0'; buf = delim + 1; while (*buf && (*buf == ' ')) { buf++; } } argv[argc] = 0; if (0 == argc) { bg = 1; } else if (0 != (bg = (*argv[argc-1] == '&'))) { argv[--argc] = 0; } return bg; } static void eval(char *cmdline, char *environ[]) { char *argv[128]; unsigned char bg; pid_t pid; bg = parseline(cmdline, argv); if (0 == argv[0]) { return; } else if (strcmp(argv[0], "&")) { if (0 == (pid = fork_proc())) { if (execve(argv[0], argv, environ) < 0) { printf("%s: Command not found.\\n", argv[0]); exit(0); } } else if (!bg) { int status; if (waitpid(pid, &status, 0) < 0) { unix_error("waitfg: waitpid error"); } } else { printf("%d %s", pid, cmdline); } } } int main(int argc, char *argv[], char *env[]) { pthread_t thread; sigemptyset(&set); sigaddset(&set, SIGINT); sigprocmask(SIG_BLOCK, &set, 0); mutex_init(&mutex); create_thread(&thread, wait_start, 0); while (1) { printf("tiny-shell > "); fflush(stdout); if (readline()) { printf("EOF has been sensed.\\n"); break; } else { eval(buffer, env); mutex_lock(&mutex); if (run) { mutex_unlock(&mutex); } else { mutex_unlock(&mutex); break; } } } mutex_destroy(&mutex); }
0
#include <pthread.h> int min(int a,int b) { if(a>b) return b; else return a; } int nitems; struct { pthread_mutex_t mutex; int buff[1000000]; int nput; int nval; }shared ={ PTHREAD_MUTEX_INITIALIZER }; void *produce(void*), *consume(void*); void *produce(void *arg) { for(;;) { 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) { int i; for(i=0;i<nitems;i++) { if(shared.buff[i]!=i) printf("buff[%d]=%d\\n",i,shared.buff[i]); } return 0; } int main(int argc,char** argv) { int i,nthreads,count[100]; pthread_t tid_produce[100],tid_consume; if(argc!=3) printf("error\\n"); nitems=min(atoi(argv[1]),1000000); nthreads=min(atoi(argv[2]),100); for(i=0;i<nthreads;i++) { count[i]=0; pthread_create(&tid_produce[i],0,produce, &count[i]); } for(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); exit(0); }
1
#include <pthread.h> int thread_no; int *data; pthread_mutex_t *mutex; } thread_arg_t; void thread_func(void *arg) { thread_arg_t* targ = (thread_arg_t *) arg; int i, result; for(i=0; i<10; i++) { pthread_mutex_lock(targ->mutex); result = targ->data[i] + 1; sched_yield(); targ->data[i] = result; pthread_mutex_unlock(targ->mutex); } } int main() { pthread_t handle[2]; thread_arg_t targ[2]; int data[10]; int i; pthread_mutex_t mutex; for(i=0; i<10; i++) data[i] = 0; pthread_mutex_init(&mutex, 0); for(i=0; i<2; i++) { targ[i].thread_no = i; targ[i].data = data; targ[i].mutex = &mutex; pthread_create(&handle[i], 0, (void *)thread_func, (void *)&targ[i]); } for(i=0; i<2; i++) { pthread_join(handle[i], 0); } pthread_mutex_destroy(&mutex); for(i=0; i<10; i++) printf("data%d : %d\\n", i, data[i]); return 0; }
0
#include <pthread.h> int pack_queue_init(struct pack_queue *q) { pthread_mutexattr_t attr; q->q_front = 0; q->q_rear = 0; q->q_size = SEND_QUEUE_SZ; q->q_items = calloc(q->q_size, sizeof(struct pack_item)); if (q->q_items == 0) return -1; if (pthread_mutexattr_init(&attr) < 0) return -1; if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK_NP) < 0) return -1; if (pthread_mutex_init(&q->q_mutex, &attr) < 0) return -1; if (pthread_mutexattr_destroy(&attr) < 0) return -1; if (pthread_cond_init(&q->q_cond_get, 0) < 0) return -1; if (pthread_cond_init(&q->q_cond_put, 0) < 0) return -1; return 0; } int pack_queue_get(struct pack_queue *q, struct pack_item *request) { if (!is_pack_queue_alive(q)) { errno = EINVAL; return -1; } if (pthread_mutex_lock(&q->q_mutex) < 0) return -1; while (q->q_front % q->q_size == q->q_rear % q->q_size) { if (pthread_cond_wait(&q->q_cond_put, &q->q_mutex) < 0) return -1; } if (!is_pack_queue_alive(q)) { pthread_mutex_unlock(&q->q_mutex); errno = EINVAL; return -1; } memcpy(request, &q->q_items[q->q_rear], sizeof(struct pack_item)); q->q_rear = (q->q_rear + 1) % q->q_size; pthread_cond_broadcast(&q->q_cond_get); if (pthread_mutex_unlock(&q->q_mutex) < 0) return -1; return 0; } int pack_queue_put(struct pack_queue *q, uint16_t op, const struct ether_addr *sha, const struct in_addr spa, const struct ether_addr *tha, const struct in_addr tpa, const struct ether_addr *src_ha, const struct ether_addr *dst_ha) { struct pack_item *ptr; if (!is_pack_queue_alive(q)) { errno = EINVAL; return -1; } if (pthread_mutex_lock(&q->q_mutex) < 0) return -1; while ((q->q_front + 1) % q->q_size == q->q_rear % q->q_size) { if (pthread_cond_wait(&q->q_cond_get, &q->q_mutex) < 0) return -1; } if (!is_pack_queue_alive(q)) { pthread_mutex_unlock(&q->q_mutex); errno = EINVAL; return -1; } ptr = &q->q_items[q->q_front]; ptr->op = op; memcpy(&ptr->src_ha, src_ha == 0 ? sha : src_ha, sizeof(struct ether_addr)); memcpy(&ptr->dst_ha, dst_ha == 0 ? tha : dst_ha, sizeof(struct ether_addr)); memcpy(&ptr->sha, sha, sizeof(struct ether_addr)); memcpy(&ptr->tha, tha, sizeof(struct ether_addr)); memcpy(&ptr->spa, &spa, sizeof(struct in_addr)); memcpy(&ptr->tpa, &tpa, sizeof(struct in_addr)); q->q_front = (q->q_front + 1) % q->q_size; pthread_cond_broadcast(&q->q_cond_put); if (pthread_mutex_unlock(&q->q_mutex) < 0) return -1; return 0; } int pack_queue_terminate(struct pack_queue *q) { void *ptr; if (pthread_mutex_lock(&q->q_mutex) < 0) return -1; if (is_pack_queue_alive(q)) { q->q_front = 0; q->q_rear = 0; q->q_size = 0; ptr = (void *) q->q_items; q->q_items = 0; free(ptr); pthread_cond_broadcast(&q->q_cond_get); pthread_cond_broadcast(&q->q_cond_put); } if (pthread_mutex_unlock(&q->q_mutex) < 0) return -1; return 0; } int pack_queue_destroy(struct pack_queue *q) { if (q->q_items) pack_queue_terminate(q); pthread_cond_destroy(&q->q_cond_get); pthread_cond_destroy(&q->q_cond_put); pthread_mutex_destroy(&q->q_mutex); return 0; }
1
#include <pthread.h> int rank; char finished; pthread_mutex_t mutex; pthread_cond_t cond; } thread_data; thread_data td[10]; void* hello_thread(void *rank) { int thread_rank = *(int *)rank; if (thread_rank > 0) { thread_data *prev = &td[thread_rank - 1]; pthread_mutex_lock(&prev->mutex); if (!prev->finished) pthread_cond_wait(&prev->cond, &prev->mutex); pthread_mutex_unlock(&prev->mutex); } printf("Hello from thread %d\\n", thread_rank); if (thread_rank < 10 -1) { thread_data *curr = &td[thread_rank]; pthread_mutex_lock(&curr->mutex); curr->finished = 1; pthread_cond_signal(&curr->cond); pthread_mutex_unlock(&curr->mutex); } return 0; } int main(void) { int rank = 0; int err; pthread_t thread_ids[10]; while(rank < 10) { td[rank].finished = 0; pthread_mutex_init(&td[rank].mutex, 0); pthread_cond_init(&td[rank].cond, 0); rank++; } rank = 0; while(rank < 10) { td[rank].rank = rank; err = pthread_create(&(thread_ids[rank]), 0, hello_thread, (void*)&td[rank].rank); if (err != 0) { printf("Can't create thread error =%d\\n", err); return 1; } rank++; } rank = 0; while(rank < 10) { pthread_join(thread_ids[rank], 0); rank++; } rank = 0; while(rank < 10) { pthread_mutex_destroy(&td[rank].mutex); pthread_cond_destroy(&td[rank].cond); rank++; } return 0; }
0
#include <pthread.h> int stack[10]; int prod_counter = 0; pthread_mutex_t mutex_prod = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_prod = PTHREAD_COND_INITIALIZER; int cons_counter = 0; pthread_mutex_t mutex_cons = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond_cons = PTHREAD_COND_INITIALIZER; pthread_mutex_t tab_mutex[10]; void Push(int c) { int index; pthread_mutex_lock(&mutex_prod); while ( prod_counter == ( cons_counter + 100 ) ) pthread_cond_wait(&cond_prod, &mutex_prod); index = prod_counter; prod_counter++; pthread_cond_broadcast(&cond_cons); pthread_mutex_lock(&tab_mutex[index % 10]); pthread_mutex_unlock(&mutex_prod); stack[(index % 10)] = c; pthread_mutex_unlock(&tab_mutex[index]); } char Pop() { int index; pthread_mutex_lock(&mutex_cons); while ( prod_counter == cons_counter ) pthread_cond_wait(&cond_cons, &mutex_cons); index = cons_counter; cons_counter++; pthread_cond_broadcast(&cond_prod); pthread_mutex_lock(&tab_mutex[index % 10]); pthread_mutex_unlock(&mutex_cons); int c = stack[(index % 10)]; pthread_mutex_unlock(&tab_mutex[index]); return c; } void* Producteur(void* arg) { int c; while ((c = getchar()) != EOF) { Push(c); } return 0; } void* Consommateur(void* arg) { for (;;) { putchar( Pop() ); fflush(stdout); } return 0; } int main(int argc, char** argv) { pthread_t tid_prod[5], tid_cons[3]; int i; for( i=0; i<10; i++){ pthread_mutex_init(tab_mutex+i, 0); } for ( i=0; i<5; i++){ if ( pthread_create(&tid_prod[i], 0, Producteur, 0) ){ perror("error : pthread_create prod\\n"); exit(1); } } for ( i=0; i<3; i++){ if ( pthread_create(&tid_cons[i], 0, Consommateur, 0) ){ perror("error : pthread_create cons\\n"); exit(1); } } for( i=0; i<5; i++){ if ( pthread_join(tid_prod[i], 0) ){ perror("error : pthread_join prod\\n"); exit(1); } } for( i=0; i<3; i++){ if( pthread_join(tid_cons[i], 0) ){ perror("error : pthread_join cons\\n"); exit(1); } } return 0; }
1
#include <pthread.h> const int buffer_size = 100; const int retry_times = 50; extern pthread_mutex_t signal_master_dead_mtx; extern pthread_cond_t signal_master_dead_cv; extern pthread_cond_t signal_server_bind_failed_cv; char init_status_and_backup_buffer[buffer_size]; void * client_main(void * data) { struct addrinfo hints, *res; int sockfd; data = 0; sprintf(init_status_and_backup_buffer, "tasks: 0, 0, 0, 0. stop: 0. dir: -1. last_stable_floor: 0." " position 0.0. moving vector 0.\\n"); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; getaddrinfo(server_addr, server_port, &hints, &res); int new_socket_count = 0; NEW_SOCKET: if( new_socket_count > retry_times ){ new_socket_count = 0; pthread_mutex_lock(&signal_master_dead_mtx); pthread_cond_signal(&signal_master_dead_cv); pthread_mutex_unlock(&signal_master_dead_mtx); pthread_mutex_lock(&signal_master_dead_mtx); pthread_cond_wait(&signal_server_bind_failed_cv, &signal_master_dead_mtx); pthread_mutex_unlock(&signal_master_dead_mtx); } new_socket_count++; sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if(sockfd == -1) { perror("socket"); pthread_exit((void *)1); } int rc = connect(sockfd, res->ai_addr, res->ai_addrlen); if(rc != 0){ perror("connect"); close(sockfd); goto NEW_SOCKET; } read(sockfd, init_status_and_backup_buffer, buffer_size); puts(init_status_and_backup_buffer); while(1){ rc = send(sockfd, inquery_msg, strlen(inquery_msg)+1, MSG_NOSIGNAL); if(rc <= 0){ close(sockfd); perror("write"); goto NEW_SOCKET; } rc = read(sockfd, init_status_and_backup_buffer, buffer_size); if(rc <= 0){ close(sockfd); perror("read"); goto NEW_SOCKET; } puts(init_status_and_backup_buffer); usleep(inquery_interval); } pthread_exit((void *)0); }
0
#include <pthread.h> int places = 10; pthread_mutex_t mutex; pthread_cond_t conditionVar; void *parking(void* carNum); int main(int argc, char *argv[]){ pthread_t cars[40]; int rc ,i; rc = pthread_mutex_init(&mutex, 0); if(rc != 0){ printf("init error!! \\n"); } rc =pthread_cond_init (&conditionVar, 0); if(rc != 0){ printf("init error!! \\n"); } srand( (unsigned)time(0)+(unsigned)getpid()); printf("hello world!! \\n\\n"); printf("num of available places is :%d\\n -- start --\\n\\n", places); for(i=0; i<40; i++){ rc=pthread_create(&cars[i], 0, parking, (void*)i); if(rc){ printf("ERROR code is %d\\n", rc); exit(-1); } } for(i=0; i<40; i++){ pthread_join(cars[i], 0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&conditionVar); pthread_exit(0); } void *parking(void *carNum){ int carNumber, state; carNumber = (int)carNum; while(1){ state = usleep(rand()%100000); if(state != 0) { printf("usleep error! \\n");} state =pthread_mutex_lock(&mutex); if(state != 0) { printf("mutex lock error! \\n");} while(places == 0){ printf("=== condition Variable Area : Wait !! \\n"); pthread_cond_wait(&conditionVar, &mutex); } places --; printf("%d is entered.\\n", carNumber); printf("num of available places is :%d\\n", places); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); places ++; printf("%d is left.\\n", carNumber); printf("num of available places is :%d\\n", places); pthread_mutex_unlock(&mutex); pthread_cond_signal(&conditionVar); pthread_exit(0); } }
1
#include <pthread.h> int arr[1000][1000]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; FILE *fout; void initArray() { fout = fopen("output.txt", "w"); if (fout != 0) { printf("opened successful"); } int i = 0; int j = 0; for (i = 0; i < 1000; i++) { for (j = 0; j < 1000; j++) { srand(time(0)); arr[i][j] = rand() % 100; } } for (i = 0; i < 1000; i++) { for (j = 0; j < 1000; j++) { fprintf(fout, "%d ", arr[i][j]); } fprintf(fout, "end \\n"); } fclose(fout); } int main() { initArray(); int globalmax = arr[0][0]; omp_set_num_threads(20); int localmax; int id; int i; int j; int startc; int startr; int finishc; int finishr; int c; int r; fprintf(stdout, "ting ting: %u\\n", (unsigned)time(0)); { id = omp_get_thread_num(); localmax = arr[0][0]; r = id / 5; c = id % 5; startc = 200 * c; finishc = startc + 200; startr = 250 * r; finishr = startr + 250; for (i = startr; i < finishr; i++) { for (j = startc; j < finishc; j++) { if (localmax < arr[i][j]) localmax = arr[i][j]; } } pthread_mutex_lock(&mutex); if (globalmax < localmax) globalmax = localmax; pthread_mutex_unlock(&mutex); } printf("Sum: %d", globalmax); }
0
#include <pthread.h> double buf[256]; int buf_ptr = 0; static pthread_mutex_t buf_lock; void store(double x) { pthread_mutex_lock(&buf_lock); buf[buf_ptr++] = x; buf_ptr &= (256 - 1); pthread_mutex_unlock(&buf_lock); } int run_test(int n) { int i; for (i = 0; i < n; i++) { double a, b, c, d, e, f, g, h; if (i & 1) { a = i * 100 + 39; b = (3000000 - i * 6); } else { a = (2800000 - i * 7); b = i * 121 + 45; } store(a); store(b); a = a / 23456; b = b / 12345; store(a); store(b); c = a * a; store(c); d = b * b; store(d); e = c - d; store(e); f = a + b; store(f); g = a - b; store(g); h = f * g; store(h); if (e - h > 0.000001) { printf("Mismatch: a=%f, b=%f: e=%f, h=%f, delta=%f\\n", a, b, e, h, e-h); printf("VFP test FAILED!\\n"); return -1; } } return 0; } static void *run_thread_test(void *args) { return (void *)(long)run_test(*(int *)args); } static int start_test(int nthreads, int niter) { pthread_t *threads; int i, j; int ret, res; pthread_mutex_init(&buf_lock, 0); if (!nthreads) goto run_once; threads = malloc(nthreads * sizeof(threads)); if (!threads) goto run_once; for (i = 0; i < nthreads; i++) { ret = pthread_create(&threads[i], 0, run_thread_test, &niter); if (ret) { printf("Failed to create %d thread\\n", i); for (j = 0; j < i; j++) pthread_join(threads[j], 0); goto bail_out; } } for (i = 0; i < nthreads; i++) { pthread_join(threads[i], (void **)&res); ret |= res; } bail_out: free(threads); pthread_mutex_destroy(&buf_lock); return ret; run_once: ret = run_test(niter); pthread_mutex_destroy(&buf_lock); return ret; } int main(int argc, char** argv) { int nthreads = 0, niter; if (argc < 2) { printf("Usage: %s [iterations] [threads]\\n", argv[0]); return -1; } niter = atoi(argv[1]); if (argc > 2) nthreads = atoi(argv[2]); printf("Running test with %d threads (%d iterations)\\n", nthreads, niter); return start_test(nthreads, niter); }
1
#include <pthread.h> const int PRODUCT_NUM = 10; const int BUFFER_SIZE = 4; int buffer[BUFFER_SIZE]; pthread_mutex_t mutex; sem_t sem_empty, sem_full; int p_idx, c_idx; int g_idx; void ConsumerFunc(void) { volatile int flag = 1; while (flag) { sem_wait(&sem_full); pthread_mutex_lock(&mutex); printf(" (%d)===>%d\\n", c_idx, buffer[c_idx]); if (buffer[c_idx] == PRODUCT_NUM) { flag = 0; } c_idx = (c_idx+1) % BUFFER_SIZE; sleep(rand()%3); pthread_mutex_unlock(&mutex); sem_post(&sem_empty); } } void ProducerFunc(void) { int i; for (i = 1; i <= PRODUCT_NUM; i++) { sem_wait(&sem_empty); pthread_mutex_lock(&mutex); buffer[p_idx] = i; printf("%d===>(%d)\\n", buffer[p_idx], p_idx); p_idx = (p_idx+1) % BUFFER_SIZE; sleep(rand()%2); pthread_mutex_unlock(&mutex); sem_post(&sem_full); } } int main(void) { pthread_t p_tid; pthread_t c_tid1, c_tid2; p_idx = c_idx = 0; g_idx = 0; pthread_mutex_init(&mutex, 0); sem_init(&sem_empty, 0, 2); sem_init(&sem_full, 0, 0); pthread_create(&p_tid, 0, (void*)ProducerFunc, 0); pthread_create(&c_tid1, 0, (void*)ConsumerFunc, 0); pthread_join(p_tid, 0); pthread_join(c_tid1, 0); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> static struct index *Dindex; static unsigned short port; static pthread_mutex_t M_index = PTHREAD_MUTEX_INITIALIZER; void *work(void *mes){ void *data, *resp; struct parameter *para; struct doc *doc; struct count *count; struct query *query, *ptr; struct query_rsl *query_rsl; char command; int size; para = (struct parameter *)mes; receive_data(para->socket_fd, &data); memcpy(&command, data, sizeof(char)); if(command == (char)CMD_INDEX){ load_doc(&doc, data); count_doc(doc, &count); size = dump_count(count, &resp); send_data(para->socket_fd,resp, size); printf("[CNode] Do index for %s\\n.", doc->name); } else if(command == (char)CMD_RETRIEVE){ load_query(&query, data); pthread_mutex_lock(&M_index); retrieve_f_index(Dindex, 100, query, &query_rsl); pthread_mutex_unlock(&M_index); size = dump_query_rsl(query_rsl, &resp); send_data(para->socket_fd,resp, size); ptr = query; printf("[CNode] Retrieve data: ("); while(ptr != 0){ printf("%s ",ptr->term); ptr = ptr->next; } printf(")\\n"); free_query(&query); } else if(command == (char)CMD_UPDATE){ pthread_mutex_lock(&M_index); load_index(&Dindex, data); pthread_mutex_unlock(&M_index); printf("[CNode] Update the index.\\n"); } else{ } free(data); free(resp); pthread_exit(0); } int regis(unsigned short iport){ char buf[50], *ptr; int client_fd; char com; com = (char)CMD_REGISTER; memcpy((void *)buf, (void *)&com, sizeof(char)); memcpy(buf+1, &iport, sizeof(unsigned short)); ptr += (sizeof(char) + sizeof(unsigned short)); ptr = '\\0'; client_fd = open_clientfdi(get_ip(NAME_IP), NAME_PORT); send_data(client_fd, buf, 10); receive_data(client_fd, (void *)&buf); if(*buf == (char)CMD_SUCC){ printf("[CNode] Registered!\\n"); } close(client_fd); return 0; } int main(int argc, char *argv[]){ int server_fd; int connect_fd; int i; struct parameter *p; pthread_t thread; port = NAME_PORT; for(i=0;i<100; i++){ server_fd = open_listenfd(port); if(server_fd != -1){ printf("[CNode] Binding to port(%d).\\n", port); break; } printf("[CNode] Failed to bind port, try a new one.\\n"); port++; } regis(port); while(1){ connect_fd = accept(server_fd, 0, 0); p = (struct parameter *)malloc(sizeof(struct parameter)); memset(p, 0, sizeof(struct parameter)); p->socket_fd = connect_fd; pthread_create(&thread, 0, work, (void *)p); } return 0; }
1
#include <pthread.h> unsigned int v_in, v_out; static pthread_mutex_t mutex_saisie, mutex_resultat; void *thread_entree_sortie(void *threadid) { printf("Entrez une valeur : "); scanf("%d", &v_in); pthread_mutex_unlock(&mutex_saisie); pthread_mutex_lock(&mutex_resultat); printf("Le resultat du calcul est : %d\\n", v_out); pthread_exit(0); } void *thread_calcul(void *threadid) { pthread_mutex_lock(&mutex_saisie); printf("On lance le calcul pour %d\\n", v_in); v_out = v_in*v_in; pthread_mutex_unlock(&mutex_resultat); pthread_exit(0); } int main (int argc, char *argv[]) { pthread_t threads[2]; int i, rc; void *ret; pthread_mutex_init (&mutex_saisie, 0); pthread_mutex_init (&mutex_resultat, 0); pthread_mutex_lock(&mutex_saisie); pthread_mutex_lock(&mutex_resultat); rc = pthread_create(&threads[0], 0, thread_calcul, 0); if (rc){ printf("Erreur creation thread : %d\\n", rc); exit(2); } rc = pthread_create(&threads[1], 0, thread_entree_sortie, 0); if (rc){ printf("Erreur creation thread : %d\\n", rc); exit(2); } for (i = 0; i < 2; ++i) { (void)pthread_join (threads[i], &ret); } pthread_exit(0); }
0
#include <pthread.h> volatile int shared_counter = 0; pthread_t people[100]; pthread_mutex_t lock; void* returnToChair() { pthread_mutex_lock(&lock); for(int i=0; i<1000;i++) { shared_counter++; } pthread_mutex_unlock(&lock); return 0; } int main(void) { if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n Mutex Initialization failed!\\n"); return 1; } clock_t begin, end; double individual_time_spent; int threadReturn; begin = clock(); int i = 0; while(i < 100) { threadReturn = pthread_create(&(people[i]), 0, &returnToChair, 0); if (threadReturn != 0) printf("\\ncan't create thread :[%s]", strerror(threadReturn)); else i++; } end = clock(); pthread_mutex_destroy(&lock); individual_time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("Time: %f\\n", individual_time_spent); printf("Counter: %d\\n", shared_counter); return 0; }
1
#include <pthread.h> uint64_t * nombresPremiers(uint64_t n, int * taille); uint64_t * factorisation(uint64_t n, int * taille); void print_prime_factors(uint64_t n); void * run(void * param); static pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutexScanf=PTHREAD_MUTEX_INITIALIZER; static FILE * f = 0; int main() { int i=0; if((f=fopen("numbers.txt","r")) != 0) { pthread_t t1=0; pthread_t t2=0; pthread_create(&t1, 0, run, 0); pthread_join(t1, 0); fclose(f); } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mutexScanf); return 0; } uint64_t * nombresPremiers(uint64_t n, int * taille) { uint64_t i; uint64_t * renvoi = (uint64_t *) malloc(sizeof(uint64_t)*n); int indice = 2; int saut = 2; renvoi[0]=2; renvoi[1]=3; for(i=5; i<=n; i+=saut, saut=6-saut) { uint64_t j; for(j=(uint64_t)(sqrt(i-1)+1); j>1 && i%j!=0; j--); if(j=1) { renvoi[indice++] = i; } } *taille=indice; return renvoi; } uint64_t * factorisation(uint64_t n, int * taille) { uint64_t * renvoi = (uint64_t *) malloc(sizeof(uint64_t)*((uint64_t)sqrt(n)+1)); int indice = 0; int taillePremier=0; uint64_t * tabPremier = nombresPremiers(sqrt(n)+2, &taillePremier); int i; uint64_t produit = 1; for(i=0; i<taillePremier && produit < n; i++) { if(n%tabPremier[i]==0) { renvoi[indice++]=tabPremier[i]; produit *= tabPremier[i]; n/=tabPremier[i]; i--; } } if(indice==0 || n!= 1) { renvoi[indice++]=n; } *taille=indice; free(tabPremier); return renvoi; } void print_prime_factors(uint64_t nombre) { int t=0; uint64_t * tab = factorisation(nombre, &t); int i; pthread_mutex_lock(&mutex); printf("%lld : ", nombre); for(i=0; i<t; i++) { printf(" %lld", tab[i]); } printf("\\n"); pthread_mutex_unlock(&mutex); free(tab); } void * run(void * param) { uint64_t n; pthread_mutex_lock(&mutexScanf); while(fscanf(f, "%lld",&n) != EOF) { pthread_mutex_unlock(&mutexScanf); print_prime_factors(n); pthread_mutex_lock(&mutexScanf); } pthread_mutex_unlock(&mutexScanf); pthread_exit(0); }
0
#include <pthread.h> static struct termworker_context_t *termworker_context; char generate_transaction(int *keying_time, int *mean_think_time) { double threshold; char transaction; threshold = get_percentage(); if (threshold < transaction_mix.new_order_threshold) { transaction = NEW_ORDER; *keying_time = key_time.new_order; *mean_think_time = think_time.new_order; } else if (transaction_mix.payment_actual != 0 && threshold < transaction_mix.payment_threshold) { transaction = PAYMENT; *keying_time = key_time.payment; *mean_think_time = think_time.payment; } else if (transaction_mix.order_status_actual != 0 && threshold < transaction_mix.order_status_threshold) { transaction = ORDER_STATUS; *keying_time = key_time.order_status; *mean_think_time = think_time.order_status; } else if (transaction_mix.delivery_actual != 0 && threshold < transaction_mix.delivery_threshold) { transaction = DELIVERY; *keying_time = key_time.delivery; *mean_think_time = think_time.delivery; } else { transaction = STOCK_LEVEL; *keying_time = key_time.stock_level; *mean_think_time = think_time.stock_level; } return transaction; } void enqueue_terminal(int termworker_id, int term) { char transaction; int keying_time; int mean_think_time; unsigned int running_time; int low, high; struct terminal_queue_t *term_queue = &termworker_context[termworker_id].term_queue; struct terminal_t *terms = term_queue->terminals; transaction = generate_transaction(&keying_time, &mean_think_time); running_time = keying_time * 1000 + get_think_time(mean_think_time) + term_queue->timing; pthread_mutex_lock(&term_queue->queue_mutex); low = 0; high = term_queue->length; while (high > low) { int mid = low + (high - low) / 2; if (terms[term_queue->queue[mid]].running_time >= running_time) low = mid + 1; else high = mid; } memmove(term_queue->queue + low + 1, term_queue->queue + low, (term_queue->length - low) * sizeof(tqueue_t)); term_queue->queue[low] = (tqueue_t)(term - termworker_context[termworker_id].start_term); terms[term_queue->queue[low]].running_time = running_time; terms[term_queue->queue[low]].id = term; terms[term_queue->queue[low]].node.client_data.transaction = transaction; term_queue->length++; sem_post(&term_queue->queue_length); pthread_mutex_unlock(&term_queue->queue_mutex); } struct terminal_t *dequeue_terminal(int termworker_id, unsigned int *delay) { struct terminal_t *term; struct terminal_queue_t *term_queue = &termworker_context[termworker_id].term_queue; sem_wait(&term_queue->queue_length); pthread_mutex_lock(&term_queue->queue_mutex); term_queue->length--; term = &term_queue->terminals[term_queue->queue[term_queue->length]]; *delay = term->running_time - term_queue->timing; term_queue->timing = term->running_time; pthread_mutex_unlock(&term_queue->queue_mutex); return term; } void init_termworker_array(int thread_count) { termworker_context = malloc(sizeof(struct termworker_context_t) * thread_count); } struct termworker_context_t * init_termworker_context(int id, int thread_count) { int terminal_count; struct termworker_context_t *tc = &termworker_context[id]; tc->id = id; tc->start_term = id * terminals_per_thread; if(id == thread_count - 1) tc->end_term = (w_id_max - w_id_min + 1) * terminals_per_warehouse; else tc->end_term = (id + 1) * terminals_per_thread; if (mode_altered > 0) { tc->start_term = 0; tc->end_term = 1; } terminal_count = tc->end_term - tc->start_term; tc->term_queue.queue = malloc(sizeof(tqueue_t) * terminal_count); tc->term_queue.terminals = malloc(sizeof(struct terminal_t) * terminal_count); tc->term_queue.length = 0; tc->term_queue.timing = 0; sem_init(&tc->term_queue.queue_length, 0, 0); pthread_mutex_init(&tc->term_queue.queue_mutex, 0); return &termworker_context[id]; } void destroy_termworker_array(int thread_count) { int i; for(i = 0; i < thread_count; i++) { struct termworker_context_t *tc = &termworker_context[i]; sem_destroy(&tc->term_queue.queue_length); pthread_mutex_destroy(&tc->term_queue.queue_mutex); free(tc->term_queue.queue); free(tc->term_queue.terminals); } }
1
#include <pthread.h> static pthread_mutex_t i2c_lock; int ipc_i2c_read(unsigned char addr,unsigned char *data,int len,unsigned char mode) { int ret_val,data_counter=0; wait_for_gpio_interrupt_i2c(); pthread_mutex_lock(&i2c_lock); switch(mode) { case EIGHT_BIT: if(data != 0) { while(len != 0) { if(read_i2c_8bit(addr,&data[data_counter]) < 0) { printf("\\n Data Read Failed"); fflush(stdout); ret_val = -1; break; } } len--; data_counter++; } break; case SIXTEEN_BIT: break; default: printf("\\n Wrong mode passed: Possible values are 8BIT, 16BIT"); break; } pthread_mutex_unlock(&i2c_lock); return ret_val; } int ipc_i2c_write(unsigned char addr,unsigned char *data,int len,unsigned char mode) { int data_counter = 0,ret_val = 0; pthread_mutex_lock(&i2c_lock); switch(mode) { case EIGHT_BIT: if(data != 0) { while(len != 0) { if(write_i2c_8bit(data[data_counter],addr) < 0) { printf("\\n Data Written Failed at index %d", data_counter); fflush(stdout); ret_val = -1; break; } len--; data_counter++; } } break; case SIXTEEN_BIT: break; } pthread_mutex_unlock(&i2c_lock); return ret_val; }
0
#include <pthread.h> int buffer[10]; int inicio_buffer = 0; int final_buffer = 0; int total_buffer = 0; pthread_mutex_t trava; void* produtor(void *arg) { for (int i = 0; i < 20; i++) { while (total_buffer == 10); buffer[inicio_buffer] = i; pthread_mutex_lock(&trava); total_buffer += 1; pthread_mutex_unlock(&trava); inicio_buffer += 1; if (inicio_buffer == 10) inicio_buffer = 0; } return 0; } void* consumidor(void *arg) { for (int j = 0; j < 20; j++) { while (total_buffer == 0); printf("%d\\t", buffer[final_buffer]); pthread_mutex_lock(&trava); total_buffer -= 1; pthread_mutex_unlock(&trava); final_buffer += 1; if (final_buffer == 10) final_buffer = 0; } return 0; } int main(int argc, char **argv) { pthread_t thread_prod, thread_cons; pthread_create(&thread_prod, 0, produtor, 0); pthread_create(&thread_cons, 0, consumidor, 0); pthread_join(thread_prod, 0); pthread_join(thread_cons, 0); printf("Terminando programa!\\n"); return 0; }
1
#include <pthread.h> struct malloc_chunk { INTERNAL_SIZE_T prev_size; INTERNAL_SIZE_T size; struct malloc_chunk* fd; struct malloc_chunk* bk; struct malloc_chunk* fd_nextsize; struct malloc_chunk* bk_nextsize; }; pthread_t thrd; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *thrd_f(void *p) { void *mem = malloc(0x40); mchunkptr chunk = (mchunkptr)((char*)mem - offsetof(struct malloc_chunk, fd)); printf("allocated victim chunk in thread arena with requested size 0x40, " "victim->size == 0x%zx\\n", chunk->size); printf("emulating corruption of the NON_MAIN_ARENA bit of victim->size\\n"); chunk->size = chunk->size & ~0x4; printf("freeing victim chunk, entering it into a fastbin of the main arena\\n"); free(mem); pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); while (1) sleep(1); pthread_exit(0); } int main(int argc, const char* argv[]) { int rc = 0; void *brk_heap = malloc(1); printf("brk heap is around: %p\\n", brk_heap); pthread_mutex_lock(&mutex); pthread_create(&thrd, 0, thrd_f, 0); pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); printf("making a malloc request in the main thread\\n"); void *main_chunk = malloc(0x40); printf("the address of the chunk returned in the main thread: %p\\n", main_chunk); return 0; }
0
#include <pthread.h> static const char *devName = "/dev/i2c-1"; struct message { struct message *next; int data; }; pthread_mutex_t lock; pthread_cond_t more; struct message *newest; struct message *oldest; } queue; void enqueue(queue *q, const int m) { struct message *n; n->next = 0; n->data = m; pthread_mutex_lock(&(q->lock)); if(q->newest == 0) { q->newest = n; q->oldest = n; } else { q->newest->next = n; q->newest = n; } pthread_cond_signal(&(q->more)); pthread_mutex_unlock(&(q->lock)); } int dequeue(queue *q) { pthread_mutex_lock(&(q->lock)); while(q->newest == 0) { pthread_cond_wait(&(q->more), &(q->lock)); } int result = q->newest->data; q->newest = q->newest->next; if(q->newest == 0) { q->oldest = 0; } pthread_mutex_unlock(&(q->lock)); return result; } int file; queue q = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0 }; void worker_thread() { printf("Worker thread started\\n"); while(1) { int num = dequeue(&q); printf("Sending %d\\n", num); if(write(file, &num, 1) == 1) { usleep(100000); char buf[1]; if(read(file, buf, 1) == 1) { int temp = (int) buf[0]; printf("Received %d\\n", temp); } } else { fprintf(stderr, "I2C: Failed to send message\\n"); } } } int main(int argc, char** argv) { int num; printf("I2C: Connecting\\n"); if((file = open(devName, O_RDWR)) < 0) { fprintf(stderr, "I2C: Failed to access %s\\n", devName); exit(1); } printf("I2C: Acquiring bus to 0x%02x\\n", 0x04); if(ioctl(file, I2C_SLAVE, 0x04) < 0) { fprintf(stderr, "I2C: Failed to acquire bus access to slave 0x%x\\n", 0x04); exit(1); } pthread_t thread; pthread_create(&thread, 0, (void *) &worker_thread, 0); printf("Please enter a number between 0 and 255: "); while(~scanf("%d", &num)) { if(num >= 0 && num <= 255) { enqueue(&q, num); } else { fprintf(stderr, "Not a valid number!\\n"); } printf("Please enter a number between 0 and 255: "); } pthread_cancel(thread); pthread_join(thread, 0); return 0; }
1
#include <pthread.h> pthread_cond_t s_cond; pthread_mutex_t s_mutex1; pthread_mutex_t s_mutex2; static void* thread(void* arg) { pthread_mutex_lock(&s_mutex2); pthread_mutex_lock(&s_mutex1); pthread_cond_signal(&s_cond); pthread_cond_wait(&s_cond, &s_mutex1); return 0; } int main(int argc, char** argv) { pthread_t tid; pthread_cond_init(&s_cond, 0); pthread_mutex_init(&s_mutex1, 0); pthread_mutex_init(&s_mutex2, 0); pthread_mutex_lock(&s_mutex1); pthread_create(&tid, 0, &thread, 0); pthread_cond_wait(&s_cond, &s_mutex1); pthread_mutex_unlock(&s_mutex1); pthread_cancel(tid); pthread_join(tid, 0); pthread_cancel(tid); fprintf(stderr, "Test finished.\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; int i2c_write(int addr, unsigned char *i2c_tx_buf, int txcnt) { pthread_mutex_lock(&mutex); int fd, ret; struct i2c_rdwr_ioctl_data data; fd=open("/dev/i2c-1",O_RDWR); if(fd < 0) { perror("open error"); pthread_mutex_unlock(&mutex); return -1; } data.msgs=(struct i2c_msg*)malloc(sizeof(struct i2c_msg)); if(!data.msgs) { perror("malloc error"); close(fd); pthread_mutex_unlock(&mutex); return -1; } if(ioctl(fd, I2C_SLAVE_FORCE, addr) < 0) printf("error\\n"); ioctl(fd,I2C_TIMEOUT,1); ioctl(fd,I2C_RETRIES,2); data.nmsgs = 1; (data.msgs[0]).len = txcnt; (data.msgs[0]).addr = addr; (data.msgs[0]).flags = 0; (data.msgs[0]).buf = i2c_tx_buf; ret = ioctl(fd, I2C_RDWR, (unsigned long)&data); free(data.msgs); close(fd); pthread_mutex_unlock(&mutex); return ret; } int i2c_read(int addr, unsigned char *i2c_tx_buf, int txcnt, unsigned char *i2c_rx_buf, int rxcnt) { pthread_mutex_lock(&mutex); int fd, ret; struct i2c_rdwr_ioctl_data data; fd=open("/dev/i2c-1",O_RDWR); if(fd < 0) { perror("open error"); pthread_mutex_unlock(&mutex); return -1; } data.msgs=(struct i2c_msg*)malloc(2*sizeof(struct i2c_msg)); if(!data.msgs) { perror("malloc error"); close(fd); pthread_mutex_unlock(&mutex); return -1; } if(ioctl(fd, I2C_SLAVE_FORCE, addr) < 0) printf("error\\n"); ioctl(fd,I2C_TIMEOUT,1); ioctl(fd,I2C_RETRIES,2); data.nmsgs = 2; (data.msgs[0]).len = txcnt; (data.msgs[0]).addr = addr; (data.msgs[0]).flags = 0; (data.msgs[0]).buf = i2c_tx_buf; (data.msgs[1]).len = rxcnt; (data.msgs[1]).addr = addr; (data.msgs[1]).flags = I2C_M_RD; (data.msgs[1]).buf = i2c_rx_buf; ret = ioctl(fd, I2C_RDWR, (unsigned long)&data); free(data.msgs); close(fd); pthread_mutex_unlock(&mutex); return ret; } int dibcom_i2c_write(int addr, unsigned char *i2c_tx_buf, int txcnt) { return i2c_write(addr, i2c_tx_buf, txcnt); } int FPGA_i2c_write(int addr, unsigned char *i2c_tx_buf, int txcnt) { return i2c_write(addr, i2c_tx_buf, txcnt); } int dibcom_i2c_read(int addr, unsigned char *i2c_tx_buf, int txcnt, unsigned char *i2c_rx_buf, int rxcnt) { return i2c_read( addr, i2c_tx_buf, txcnt, i2c_rx_buf, rxcnt); } int FPGA_i2c_read(int addr, unsigned char *i2c_tx_buf, int txcnt, unsigned char *i2c_rx_buf, int rxcnt) { return i2c_read(addr, i2c_tx_buf, txcnt, i2c_rx_buf, rxcnt); }
1
#include <pthread.h> void pthread_testcancel (void) { struct pthread_internal_t *p = (struct pthread_internal_t*)pthread_self(); int cancelled; pthread_init(); pthread_mutex_lock (&p->cancel_lock); cancelled = (p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_ENABLE) && (p->attr.flags & PTHREAD_ATTR_FLAG_CANCEL_PENDING); pthread_mutex_unlock (&p->cancel_lock); if (cancelled) pthread_exit (PTHREAD_CANCELED); }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return(0); default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't created thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); exit(0); }
1
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err; int condition; int arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can't set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> long birim_iterasyon; double Pi; long circleCount = 0; pthread_t *threads; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* monte_carlo(void* arg){ long i; long incircle_thread = 0; unsigned int rand_state = rand(); for (i = 0; i < birim_iterasyon; i++){ double x = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0; double y = rand_r(&rand_state) / ((double)32767 + 1) * 2.0 - 1.0; if ((x*x + y*y)<1){ incircle_thread++; } } Pi = (4. * (double)incircle_thread) /((double)birim_iterasyon * 1); pthread_mutex_lock(&mutex); circleCount += incircle_thread; pthread_mutex_unlock(&mutex); } int main(int argc, char *argv[]) { int i ; long iterasyon_sayisi=atol(argv[1]); int thread_sayisi=atoi(argv[2]); birim_iterasyon=(iterasyon_sayisi/thread_sayisi); if (argc != 3 || strcmp(argv[1], "--help") == 0) { fprintf(stderr, "Usage: %s <iterasyon sayisi> <thread sayisi>\\n", argv[0]); } threads = malloc(sizeof(pthread_t)*thread_sayisi); for (i = 0; i < thread_sayisi; i++) { pthread_create(&threads[i], 0, monte_carlo, 0); } for (i = 0; i < thread_sayisi; i++) { pthread_join(threads[i], 0); } printf("Pi = %lf\\n", Pi); }
1
#include <pthread.h> int space=0; int MAX_DIRECTORIES = 200; char **Filename; int level[2]={0}; char **filesystem; int condition1=0, condition2=0; extern int alphasort(); void compareFS(int k); void *traverseSystem(void *threadid); pthread_cond_t condition = PTHREAD_COND_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char*argv[]) { int i; filesystem = (char**)malloc(sizeof(char*)*(argc-1)); Filename = (char**)malloc(sizeof(char*)*(100)); for(i=0;i<argc-1;i++) { Filename[i]= 0; filesystem[i] = (char*)malloc(sizeof(char)*100); strcpy(filesystem[i],argv[i+1]); } compareFS(argc-1); return 0; } void compareFS(int k){ pthread_t threads[2]; int i=0,j=1; pthread_create(&threads[0], 0,&traverseSystem,(void*)&i); pthread_create(&threads[1], 0,&traverseSystem,(void*)&j); pthread_join(threads[0], 0); pthread_join(threads[1], 0); } void addDirectory(char *path,char **directories, int *index){ (*index)++; directories[*index]=(char*)malloc(sizeof(char)*MAXPATHLEN); strcpy(directories[*index],path); } void makepath(char *pathname, char *pwd, char *append){ if(strcpy(pathname,pwd) == 0){printf("Error getting path\\n"); exit(0);} strcat(pathname,"/"); strcat(pathname,append); } int mod(int i){return i>=0?i:(-1*i);} void *traverseSystem(void *data){ int count,i,index=-1; struct direct **files; int file_select(); char pathname[MAXPATHLEN]; if(getcwd(pathname,MAXPATHLEN) == 0){printf("Error getting path\\n"); exit(0);} strcat(pathname,"/"); int threadId = *(int*)data; strcat(pathname,filesystem[threadId]); char **directories = (char**) malloc(sizeof(char*)*MAX_DIRECTORIES); addDirectory(pathname,directories,&index); index++; directories[index]=0; int front=0; while(front<index) { if(directories[front]!=0) { printf("pathname: %s\\n",directories[front]); count = scandir(directories[front], &files, file_select, alphasort); if(count <= 0){ printf("No files in this directory\\n");exit(0);} for (i=0;i<count;++i) { Filename[threadId]=files[i]->d_name; pthread_mutex_lock(&condition_mutex); if((level[threadId]>level[mod(threadId-1)])||(Filename[mod(threadId-1)]!=0 && strcmp(files[i]->d_name,Filename[mod(threadId-1)])>0)){ printf("THREADID: %d waiting on file:",threadId); printf("%s AT LEVEL %d while other thread at level %d acessing file: %s\\n", Filename[threadId],level[threadId],level[mod(threadId-1)],Filename[mod(threadId-1)]); pthread_cond_signal(&condition); while(pthread_cond_wait(&condition,&condition_mutex)); } else if(Filename[mod(threadId-1)]!=0 && (strcmp(files[i]->d_name,Filename[mod(threadId-1)])==0)) { printf("common file found: %s\\n",files[i]->d_name); if(files[i]->d_type == DT_DIR) { makepath(pathname,directories[front],files[i]->d_name); addDirectory(pathname,directories,&index); } pthread_cond_broadcast(&condition); } pthread_mutex_unlock(&condition_mutex); } } else { index++; directories[index]=0; level[threadId]++; } front++; } return 0; } int file_select(struct direct *entry){ if ((strcmp(entry->d_name, ".") == 0) ||(strcmp(entry->d_name, "..") == 0)) return (0); return (!0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main() { int rc; if((rc=pthread_mutex_lock(&mutex))!=0) { fprintf(stderr,"Error at pthread_mutex_lock(), rc=%d\\n",rc); return PTS_UNRESOLVED; } rc = pthread_mutex_trylock(&mutex); if(rc!=EBUSY) { fprintf(stderr,"Expected %d(EBUSY), got %d\\n",EBUSY,rc); printf("Test FAILED\\n"); return PTS_FAIL; } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); printf("Test PASSED\\n"); return PTS_PASS; }
1
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; int count = 0; char cp_from[1024] = {0}; char cp_to[1024] = {0}; void open_file(FILE **fp1, FILE **fp2) { *fp1 = fopen(cp_from, "r"); if(0 == *fp1) { printf("open file %s error\\n", cp_from); exit(1); } *fp2 = fopen(cp_to, "r+"); if(0 == *fp2) { printf("open file %s error\\n", cp_to); exit(1); } return; } void close_file(FILE **fp1, FILE **fp2) { fclose(*fp1); fclose(*fp2); return; } void printid(void) { pthread_t tid; tid = pthread_self(); printf("Thread id: %u\\n", (unsigned int)tid); return; } int do_count(void) { int n; pthread_mutex_lock(&count_mutex); count = count + 1024; n = count - 1024; pthread_mutex_unlock(&count_mutex); return n; } void my_copy(FILE **fp1, FILE **fp2) { int ret = -1; int n; char buf[1024] = {0}; while(ret != 0) { n = do_count(); fseek(*fp1, n, 0); fseek(*fp2, n, 0); memset(buf, 0, sizeof(buf)); ret = fread(buf, 1, 1024, *fp1); fwrite(buf, ret, 1, *fp2); } return; } void *thr_fn(void *arg) { FILE *fp1; FILE *fp2; open_file(&fp1, &fp2); my_copy(&fp1, &fp2); close_file(&fp1, &fp2); return; } void create_thread(pthread_t *ntid) { int err; err = pthread_create(ntid, 0, thr_fn, 0); if(err != 0) { fprintf(stderr, "error: %d: %s", err, strerror(err)); exit(0); } return; } void create_file(void) { FILE *fp; fp = fopen(cp_to, "w"); if(0 == fp) { printf("create file %s error\\n", cp_to); exit(1); } fclose(fp); return; } int main(int argc, char* argv[]) { int err; int i, n; pthread_t *ntid; printf("How many threads do you want to create?\\nn = "); scanf("%d", &n); printf("Please input a file:\\ncp_from = "); scanf("%s", cp_from); printf("Please input a file:\\ncp_to = "); scanf("%s", cp_to); create_file(); ntid = (pthread_t *)malloc(sizeof(pthread_t) * n); for(i = 0; i < n; i++) { create_thread(ntid + i); } printf("You create %d threads.\\n", n); printf("Please wait for a moment....\\n"); for(i = 0; i < n; i++) { pthread_join(*(ntid + i), 0); } printf("Copy finish!\\n"); free(ntid); return 0; }
0
#include <pthread.h> struct txn_node *get_txn_node(int new_txn_id,long log_rec_no) { struct txn_node *new_txn_node; new_txn_node = (struct txn_node *)malloc(sizeof(struct txn_node)); new_txn_node->txn_id = new_txn_id; new_txn_node->cur_state = RUNNING; new_txn_node->first_LRN = log_rec_no; new_txn_node->last_LRN = log_rec_no; new_txn_node->file_rec_no = 0; new_txn_node->next = 0; new_txn_node->wait_mode = -1; new_txn_node->waiting_for_inode = 0; new_txn_node->blocked_tid = 0; new_txn_node->before_after = 0; return new_txn_node; } int assign_new_txnid(void) { pthread_mutex_lock(&txnid_mutex); txn_id = txn_id+1; pthread_mutex_unlock(&txnid_mutex); return(txn_id); } void new_txn_insert(int new_txn_id,int log_rec_no) { struct txn_node *new_txn_node,*ptr_txn_node,*foll_txn_node; pthread_mutex_lock(&txn_mutex); if(head_txn_list == 0) head_txn_list = get_txn_node(new_txn_id,log_rec_no); else{ new_txn_node = get_txn_node(new_txn_id,log_rec_no); ptr_txn_node = head_txn_list; while(ptr_txn_node!=0){ if(ptr_txn_node->txn_id > new_txn_id) break; foll_txn_node = ptr_txn_node; ptr_txn_node = ptr_txn_node->next; } if(ptr_txn_node == head_txn_list){ head_txn_list=new_txn_node; new_txn_node->next = ptr_txn_node; } else{ foll_txn_node->next = new_txn_node; new_txn_node->next = ptr_txn_node; } } pthread_mutex_unlock(&txn_mutex); } void txn_delete(int txnid) { struct txn_node *ptr_txn_node,*foll_txn_node; pthread_mutex_lock(&txn_mutex); ptr_txn_node = head_txn_list; while(ptr_txn_node->txn_id != txnid) { foll_txn_node = ptr_txn_node; ptr_txn_node = ptr_txn_node->next; } if(ptr_txn_node == head_txn_list) head_txn_list = ptr_txn_node->next; else foll_txn_node->next = ptr_txn_node->next; free(ptr_txn_node); pthread_mutex_unlock(&txn_mutex); }
1
#include <pthread.h> static struct packet_buffer pktbuf; static struct packet_buffer_t *pktlink; static struct packet_buffer_t *pkt_freelist; static struct packet_buffer_t *pkt_use_front; static struct packet_buffer_t *pkt_use_rear; static int packet_buffer_count = 0; static int bufuse = 0; static pthread_mutex_t mutex_used = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t mutex_free = PTHREAD_MUTEX_INITIALIZER; static int pktbuf_num_of_buffers (void) { return packet_buffer_count; } static int pktbuf_num_of_freebuf (void) { return packet_buffer_count - bufuse; } static struct packet_buffer_t *request (void) { struct packet_buffer_t *ptr; pthread_mutex_lock (&mutex_free); if ((ptr = pkt_freelist) != 0) { pkt_freelist = ptr->next; bufuse++; } pthread_mutex_unlock (&mutex_free); return ptr; } static void bufready (struct packet_buffer_t *pkt) { pthread_mutex_lock (&mutex_used); pkt->next = 0; if (pkt_use_front == 0) { pkt->prev = 0; pkt_use_front = pkt; } else { pkt->prev = pkt_use_rear; pkt_use_rear->next = pkt; } pkt_use_rear = pkt; pthread_mutex_unlock (&mutex_used); } static struct packet_buffer_t *retrieve (void) { struct packet_buffer_t *ptr; pthread_mutex_lock (&mutex_used); if ((ptr = pkt_use_front) != 0) { pkt_use_front = ptr->next; } pthread_mutex_unlock (&mutex_used); return ptr; } static void dequeue (struct packet_buffer_t *pkt) { pthread_mutex_lock (&mutex_free); pkt->next = pkt_freelist; pkt_freelist = pkt; bufuse--; pthread_mutex_unlock (&mutex_free); } static void pktbuf_close (void) { int len; len = packet_buffer_count; packet_buffer_count = 0; bufuse = 0; free (pktlink); } static int pktbuf_count (void) { return bufuse; } struct packet_buffer *init_packet_buffer_v2 (const int number_of_buffer) { int i; struct packet_buffer_t *ptr; fprintf (stderr, "Allocate %d packet buffer ... ", number_of_buffer); if ((pktlink = utils_calloc (number_of_buffer, sizeof (struct packet_buffer_t))) == 0) { fprintf (stderr, "error\\n"); return 0; } else { packet_buffer_count = number_of_buffer; } for (i = 0, ptr = 0; i < packet_buffer_count; i++) { pktlink[i].prev = 0; pktlink[i].next = ptr; ptr = &pktlink[i]; } pkt_freelist = ptr; pkt_use_front = 0; pkt_use_rear = 0; fprintf (stderr, "ok\\n"); bufuse = 0; pktbuf.request = &request; pktbuf.retrieve = &retrieve; pktbuf.dequeue = &dequeue; pktbuf.ready = &bufready; pktbuf.close = &pktbuf_close; pktbuf.count = &pktbuf_count; pktbuf.num_of_buffers = &pktbuf_num_of_buffers; pktbuf.num_of_freebuf = &pktbuf_num_of_freebuf; return &pktbuf; }
0
#include <pthread.h> static volatile int data; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_m = PTHREAD_COND_INITIALIZER; static pthread_cond_t cond_j = PTHREAD_COND_INITIALIZER; static int is_prime(int d) { int i; for (i = 2; i < d / 2; i++) { if (d % i == 0) { return 0; } } return 1; } void *jobs(void *unuse) { int d; while (1) { pthread_mutex_lock(&mutex); while (data == 0) { pthread_cond_wait(&cond_j, &mutex); } if (data < 0) { pthread_mutex_unlock(&mutex); break; } d = data; if (is_prime(d)) { printf("%d ", d); fflush(0); } else { printf("\\033[31m%d\\033[0m ", d); fflush(0); } data = 0; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_m); } return 0; } int main(void) { int i; pthread_t tid[8]; for (i = 0; i < 8; i++) { pthread_create(tid + i, 0, jobs, 0); } for (i = 100000001; i <= 100000100; i++) { pthread_mutex_lock(&mutex); while (data > 0) { pthread_cond_wait(&cond_m, &mutex); } data = i; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_j); } pthread_mutex_lock(&mutex); while (data > 0) { pthread_cond_wait(&cond_m, &mutex); } data = -1; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond_j); for (i = 0; i < 8; i++) { pthread_join(tid[i], 0); } printf("\\n"); return 0; }
1
#include <pthread.h> int sigaction (int sig, const struct sigaction *restrict sa, struct sigaction *restrict osa) { if (sig <= 0 || sig >= NSIG) { errno = EINVAL; return -1; } struct signal_state *ss = &_pthread_self ()->ss; pthread_mutex_lock (&ss->lock); if (osa) *osa = ss->actions[sig - 1]; if (sa) { ss->actions[sig - 1] = *sa; sigdelset (&ss->blocked, SIGKILL); sigdelset (&ss->blocked, SIGSTOP); if (sa->sa_handler == SIG_IGN || (sa->sa_handler == SIG_DFL && default_action (sig) == sig_ignore)) { sigdelset (&ss->pending, sig); sigdelset (&process_pending, sig); } } pthread_mutex_unlock (&ss->lock); return 0; }
0
#include <pthread.h> int buff[10]; int buff_index; pthread_mutex_t buff_mutex; sem_t buff_sem_full; int push_front(int val) { if(buff_index < 10) { buff[buff_index++] = val; return 0; } else return -1; } int pop_front() { if(buff_index > 0) return buff[--buff_index]; else return -1; } void* producer(void* arg) { int result; while(1) { for(int i = 0 ; i < 20 ; i++) { pthread_mutex_lock(&buff_mutex); result = push_front(i); printf("producer : %d | result = %d\\n", i, result); pthread_mutex_unlock(&buff_mutex); if(result != -1) sem_post(&buff_sem_full); } sleep(10); } } void* consumer(void* arg) { int temp; while(1) { printf("consumer - sem_wait\\n"); sem_wait(&buff_sem_full); printf("consumer - po sem_wait\\n"); pthread_mutex_lock(&buff_mutex); temp = pop_front(); printf("consumer : %d\\n", temp); pthread_mutex_unlock(&buff_mutex); } } int main() { pthread_t th1, th2; pthread_mutex_init(&buff_mutex, 0); sem_init(&buff_sem_full, 0, 0); pthread_create(&th1, 0, producer, 0); pthread_create(&th2, 0, consumer, 0); pthread_join(th1, 0); pthread_join(th2, 0); return 0; }
1
#include <pthread.h> int rand_r(unsigned int *seedp); int thread_count; unsigned int n; long long unsigned int in_global = 0; long step_bins; pthread_mutex_t lock; void* monte_carlo_pi(void* args) { long long unsigned int in = 0, i; double x, y, d; long thread; unsigned int seed = time(0); thread = (long) args; for(i = thread*step_bins; i < ((((thread*step_bins) + step_bins) < (n)) ? ((thread*step_bins) + step_bins) : (n)); i++) { x = ((rand_r(&seed) % 1000000)/500000.0)-1; y = ((rand_r(&seed) % 1000000)/500000.0)-1; d = ((x*x) + (y*y)); if (d <= 1) { in+=1; } } pthread_mutex_lock(&lock); in_global += in; pthread_mutex_unlock(&lock); return 0; } int main(void) { double pi; long unsigned int duracao; struct timeval start, end; long thread; pthread_t* thread_handles; scanf("%d %u",&thread_count, &n); thread_handles = malloc (thread_count*sizeof(pthread_t)); step_bins = ceil(n*1.0/thread_count*1.0); srand (time(0)); gettimeofday(&start, 0); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, monte_carlo_pi, (void*) thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } gettimeofday(&end, 0); duracao = ((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)); pi = 4*in_global/((double)n); printf("%lf\\n%lu\\n",pi,duracao); free(thread_handles); return 0; }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait1=PTHREAD_COND_INITIALIZER; void * thr_fn(void * arg) { int err, signo; for(;;) { err=sigwait(&mask, &signo); if(err!=0) { fprintf(stderr, "sigwait failed\\n"); exit(0); } switch(signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag=1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait1); return (0); default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main() { 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) { fprintf(stderr, "SIG_BLOCK error\\n"); exit(0); } err=pthread_create(&tid, 0, thr_fn, 0); if(err!=0) { fprintf(stderr, "can't create thread\\n"); exit(0); } pthread_mutex_lock(&lock); while(quitflag==0) pthread_cond_wait(&wait1, &lock); pthread_mutex_unlock(&lock); quitflag=0; if(sigprocmask(SIG_SETMASK, & oldmask, 0)<0) printf("SIG_SETMASK error\\n"); exit(0); }
1
#include <pthread.h> sem_t space_nums; sem_t data_nums; pthread_mutex_t consuming = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t producting= PTHREAD_MUTEX_INITIALIZER; int buf[6]; void *consumer(void *arg) { int index = 0; while(1) { sleep(1); sem_wait(&data_nums); pthread_mutex_lock(&consuming); int data = buf[index]; printf("NO.%ud consumer done... data is : %d, index = %d\\n", pthread_self(), data, index); sem_post(&space_nums); index++; index %= 6; pthread_mutex_unlock(&consuming); } printf("\\n"); } void *productor(void *arg) { int index = 0; while(1) { pthread_mutex_lock(&producting); sem_wait(&space_nums); buf[index] = rand() % 1234; printf(" ^ No.%ud productor done ... data is : %d, index = %d\\n", pthread_self(), buf[index], index); sem_post(&data_nums); ++index; index %= 6; pthread_mutex_unlock(&producting); } } int main() { sem_init(&space_nums, 0, 6); sem_init(&data_nums, 0, 0); pthread_mutex_init(&consuming, 0); pthread_mutex_init(&producting, 0); pthread_t p_id1, p_id2, p_id3, p_id4; pthread_t c_id1, c_id2; pthread_create(&p_id1, 0, &consumer, 0); pthread_create(&c_id1, 0, &productor, 0); pthread_create(&c_id2, 0, &productor, 0); pthread_join(p_id1, 0); pthread_join(c_id1, 0); sem_destroy(&space_nums); sem_destroy(&data_nums); return 0; }
0
#include <pthread.h> struct mail_box { pthread_mutex_t lock; pthread_cond_t cond; struct message *list; }; struct message { struct message *next; void *data; }; struct mail_box *mail_box_create (void) { struct mail_box *mb; if ((mb = calloc (1, sizeof (*mb))) == 0) goto no_mem; if ((errno = pthread_mutex_init (&mb->lock, 0)) != 0) goto no_lock; if ((errno = pthread_cond_init (&mb->cond, 0)) != 0) goto no_cond; mb->list = 0; return mb; no_cond: pthread_mutex_destroy (&mb->lock); no_lock: free (mb); no_mem: return 0; } int mail_box_destroy (struct mail_box *mb) { struct message *p, *next; if ((errno = pthread_mutex_destroy (&mb->lock)) != 0) return -1; pthread_cond_destroy (&mb->cond); for (p = mb->list; p != 0; p = next) { next = p->next; free (p); } free (mb); return 0; } void message_list_add (struct message **p, struct message *m) { for (; *p != 0; p = &(*p)->next) {} *p = m; } int mail_box_put (struct mail_box *mb, void *data) { struct message *message; if ((message = malloc (sizeof (*message))) == 0) goto no_mem; if ((errno = pthread_mutex_lock (&mb->lock)) != 0) goto no_lock; message->next = 0; message->data = data; message_list_add (&mb->list, message); pthread_cond_signal (&mb->cond); pthread_mutex_unlock (&mb->lock); return 0; no_lock: free (message); no_mem: return -1; } void *mail_box_get (struct mail_box *mb) { struct message *message; void *data; if ((errno = pthread_mutex_lock (&mb->lock)) != 0) return 0; while (mb->list == 0) pthread_cond_wait (&mb->cond, &mb->lock); message = mb->list; mb->list = message->next; data = message->data; free (message); pthread_mutex_unlock (&mb->lock); return data; }
1
#include <pthread.h> size_t k; int file; char* word; int N; pthread_t* threads; sigset_t mask; pthread_mutex_t mutex; pthread_t main_thread_id; struct thread_args { int id; } **args; void exit_program(int status, char* message) { if(status == 0) { printf("%s\\n",message); } else { perror(message); } exit(status); } int seek_for_word(char *buffer) { char id_str[sizeof(int)], text[RECORDSIZE+1]; char *strtok_pointer; char strtok_buf[RECORDSIZE*k]; strtok_pointer = strtok_buf; for(int i =0;i<k;++i) { char *p = strtok_r(buffer, SEPARATOR,&strtok_pointer); strcpy(id_str, p); int id = atoi(id_str); p = strtok_r(0, "\\n",&strtok_pointer); if(p!=0) { strncpy(text, p, RECORDSIZE+1); if (strstr(text, word) != 0) { return id; } } } return -1; } void *parallel_reader(void *arg) { int id; char buffer[1024*k]; struct thread_args *tmp = arg; int jump = tmp->id; long multiplier = RECORDSIZE*jump*k; while(pread(file,buffer,RECORDSIZE*k,multiplier) > 0) { if((id = seek_for_word(buffer)) != -1) { printf("Found the word %s! Record id: %d, thread id: %zu\\n",word,id,pthread_self()); } multiplier += (N*RECORDSIZE*k); } printf("End of thread life.\\n"); while(1); } void exit_handler() { if(file!=0) { close(file); } if(threads != 0) { free(threads); } if(args !=0) { for (int i = 0; i < N; ++i) { if (args[i] != 0) free(args[i]); } free(args); } } void init_mask() { sigset_t mask; sigemptyset(&mask); sigaddset(&mask, SIGUSR1); sigaddset(&mask, SIGTERM); pthread_sigmask(SIG_BLOCK,&mask,0); } void signal_handler(int signum) { pthread_mutex_lock(&mutex); pthread_t id = pthread_self(); printf("Catched singal %d, my id: %zu", signum, id); if(id == main_thread_id) { printf(" I'm main thread\\n"); } else { printf(" I'm worker thread\\n"); } fflush(stdin); pthread_mutex_unlock(&mutex); } void init_signals() { struct sigaction sa; sigemptyset(&(sa.sa_mask)); sa.sa_flags = 0; sa.sa_handler = signal_handler; if(sigaction(SIGUSR1,&sa, 0) == -1) { exit_program(1,"Couldn't initialize signal handlers for SIGUSR1"); } struct sigaction sa2; sigemptyset(&(sa2.sa_mask)); sa2.sa_flags = 0; sa2.sa_handler = signal_handler; if(sigaction(SIGTERM,&sa2,0) == -1) { exit_program(1,"Couldn't initialize signal handlers for SIGTERM"); } } int get_signal(int n) { switch(n) { case 1: return SIGUSR1; case 2: return SIGTERM; case 3: return SIGKILL; default: return SIGSTOP; } } char *get_signal_str(int n) { switch(n) { case 1: return "SIGUSR1"; case 2: return "SIGTERM"; case 3: return "SIGKILL"; default: return "SIGSTOP"; } } int main(int argc, char ** argv) { if(argc != 6) { exit_program(0, "Pass 4 arguments: N - the number of threads, filename - the name of the file to read records from" "k - the number of records read by a thread in a single access, word - the word we seek in the file for, signal - the type of signal to send " "1 - SIGUSR1, 2 - SIGTERM, 3 - SIGKILL, 4 - SIGSTOP\\n"); } atexit(exit_handler); N = atoi(argv[1]); char *filename = argv[2]; k = (size_t) atoi(argv[3]); if(k<=0 || N <= 0) { exit_program(0,"Pass the N and k parameters > 0"); } word = argv[4]; if((file = open(filename, O_RDONLY)) == -1) { exit_program(1, "Couldn't open the file to read records from"); } main_thread_id = pthread_self(); pthread_mutex_init(&mutex,0); threads = malloc(sizeof(int)*N); args = malloc(sizeof(struct thread_args*)*N); init_mask(); for(int i=0;i<N;++i) { args[i] = malloc(sizeof(struct thread_args)); args[i]->id = i; if(pthread_create(&threads[i],0,parallel_reader,args[i])) { exit_program(1,"Failed to create thread"); } } int signal = atoi(argv[5]); printf("Sending %s to thread...\\n",get_signal_str(signal)); pthread_kill(threads[0],get_signal(signal)); printf("Sent!\\n"); pthread_mutex_destroy(&mutex); pthread_exit(0); }
0
#include <pthread.h> static pthread_mutex_t _swap_locks[32U]; int32_t android_atomic_add(int32_t value, volatile int32_t* addr) { int32_t oldValue; do { oldValue = *addr; } while (android_atomic_release_cas(oldValue, oldValue+value, addr)); return oldValue; } int32_t android_atomic_and(int32_t value, volatile int32_t* addr) { int32_t oldValue; do { oldValue = *addr; } while (android_atomic_release_cas(oldValue, oldValue&value, addr)); return oldValue; } int32_t android_atomic_or(int32_t value, volatile int32_t* addr) { int32_t oldValue; do { oldValue = *addr; } while (android_atomic_release_cas(oldValue, oldValue|value, addr)); return oldValue; } int android_atomic_acquire_cmpxchg(int32_t oldvalue, int32_t newvalue, volatile int32_t* addr) { return android_atomic_release_cmpxchg(oldvalue, newvalue, addr); } int android_atomic_release_cmpxchg(int32_t oldvalue, int32_t newvalue, volatile int32_t* addr) { int result; pthread_mutex_t* lock = &_swap_locks[((unsigned)(void*)(addr) >> 3U) % 32U]; pthread_mutex_lock(lock); if (*addr == oldvalue) { *addr = newvalue; result = 0; } else { result = 1; } pthread_mutex_unlock(lock); return result; }
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("cleanup 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); while(1) { pthread_mutex_lock(&mtx); while(head==0) { pthread_cond_wait(&cond,&mtx); } p=head; head=head->n_next; printf("Got %d from front of queue/n\\n",p->n_number); free(p); pthread_mutex_unlock(&mtx); } pthread_cleanup_pop(0); return 0; } int main(int argc,char **argv) { pthread_t tid; int i; struct node *p; pthread_create(&tid,0,thread_func,0); for(i=0;i<10;i++) { p=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("thread 1 wanna end the line.So cancel thread 2./n\\n"); pthread_cancel(tid); pthread_join(tid,0); printf("all done --exiting/n\\n"); return 0; }
0
#include <pthread.h> static pthread_mutex_t table_lock = PTHREAD_MUTEX_INITIALIZER; static void * dev_table; static struct fd_device * fd_device_new_impl(int fd) { struct fd_device *dev = calloc(1, sizeof(*dev)); if (!dev) return 0; atomic_set(&dev->refcnt, 1); dev->fd = fd; dev->handle_table = drmHashCreate(); dev->name_table = drmHashCreate(); return dev; } static int devkey(int fd) { struct stat s; if (fstat(fd, &s)) { ERROR_MSG("stat failed: %s", strerror(errno)); return -1; } return s.st_ino; } struct fd_device * fd_device_new(int fd) { struct fd_device *dev = 0; int key = devkey(fd); pthread_mutex_lock(&table_lock); if (!dev_table) dev_table = drmHashCreate(); if (drmHashLookup(dev_table, key, (void **)&dev)) { dev = fd_device_new_impl(fd); drmHashInsert(dev_table, key, dev); } else { dev = fd_device_ref(dev); } pthread_mutex_unlock(&table_lock); return dev; } struct fd_device * fd_device_ref(struct fd_device *dev) { atomic_inc(&dev->refcnt); return dev; } void fd_device_del(struct fd_device *dev) { if (!atomic_dec_and_test(&dev->refcnt)) return; pthread_mutex_lock(&table_lock); drmHashDestroy(dev->handle_table); drmHashDestroy(dev->name_table); drmHashDelete(dev_table, devkey(dev->fd)); pthread_mutex_unlock(&table_lock); free(dev); }
1
#include <pthread.h> int min; int max; } limit; pthread_mutex_t *lock; int *count; char *str; int max = 0; size_t l = 0; void getString(); void * runner(void *param); int main(int argc, char const* argv[]) { getString(); l = strlen(str); count = calloc(26, sizeof(int)); pthread_t tid[4]; lock = malloc(sizeof(pthread_mutex_t) * 26); for (int i = 0; i < 26; i++) { pthread_mutex_init(&lock[i], 0); } limit limit0 = {.min = 0, .max = l/4}; limit limit1 = {.min = l/4 + 1, .max = l/2}; limit limit2 = {.min = l/2 + 1, .max = 3*l/4}; limit limit3 = {.min = 3*l/4 + 1, .max = l}; pthread_create(&tid[0], 0, runner, &limit0); pthread_create(&tid[1], 0, runner, &limit1); pthread_create(&tid[2], 0, runner, &limit2); pthread_create(&tid[3], 0, runner, &limit3); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_join(tid[2], 0); pthread_join(tid[3], 0); printf("Entered string is: %s\\n", str); int norm = log(max)*3; for (int i = 0; i < 26; i++) { if (count[i] == 0) continue; printf("%c\\t(%d)\\t|", 'A'+i, count[i]); for (int equal = 0; equal < count[i]/norm; equal++) { printf("="); } if (count[i]%norm != 0) printf("-"); printf("\\n"); } printf("\\n1 equal = %d\\n", norm); for (int i = 0; i < 26; i++) { pthread_mutex_destroy(&lock[i]); } } void * runner(void *param) { limit *lim = param; for (int i = lim->min; i <= lim->max; i++) { if (isalpha(str[i])) { pthread_mutex_lock(&lock[tolower(str[i]) - 'a']); count[tolower(str[i]) - 'a']++; pthread_mutex_unlock(&lock[tolower(str[i]) - 'a']); if (count[tolower(str[i]) - 'a'] > max) max = count[tolower(str[i]) - 'a']; } } pthread_exit(0); } void getString() { size_t size = 100; int ch; size_t len = 0; str = realloc(0, sizeof(char)*size); while(EOF!=(ch=getc(stdin))){ str[len++]=ch; if(len==size){ str = realloc(str, sizeof(char)*(size+=16)); } } str[len++]='\\0'; }
0
#include <pthread.h> struct msg { struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp; for(; ;) { pthread_mutex_lock(&lock); while(head == 0) pthread_cond_wait(&has_product, &lock); mp = head; head = mp->next; pthread_mutex_unlock(&lock); free(mp); sleep(rand() % 5); } } void *producer(void *p) { struct msg *mp; for(; ;) { mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000 + 1; printf("Producer %d \\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand() % 5); } } int main(void) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
1
#include <pthread.h> struct lmq_msg { unsigned len; char *data; struct lmq_msg *next; }; int lmq_init(struct lmq_queue *q) { int fds[2]; if (pipe(fds)) return -1; memset(q, 0, sizeof(struct lmq_queue)); q->notify_r = fds[0]; q->notify_w = fds[1]; pthread_mutex_init(&q->mutex, 0);; return 0; } int lmq_free(struct lmq_queue *q) { struct lmq_msg *qm, *qmf; int i; pthread_mutex_lock(&q->mutex);; for (i = 0; i < LMQ_NPRIORITIES; i++) { qm = q->priorities_head[i]; while (qm != 0) { qmf = qm; qm = qm->next; free(qmf->data); free(qmf); } } pthread_mutex_unlock(&q->mutex);; return 0; } int lmq_send(struct lmq_queue *q, void *msg, size_t len, int prio) { struct lmq_msg *qm; int r; qm = (struct lmq_msg *)malloc(sizeof(struct lmq_msg)); if (qm == 0) { errno = ENOMEM; return -1; } memset(qm, 0, sizeof(struct lmq_msg)); qm->data = (char *)malloc(len); if (qm == 0) { errno = ENOMEM; return -1; } memcpy(qm->data, msg, len); qm->len = len; pthread_mutex_lock(&q->mutex);; if (q->priorities_tail[prio] == 0) { q->priorities_tail[prio] = q->priorities_head[prio] = qm; } else { q->priorities_tail[prio]->next = qm; q->priorities_tail[prio] = qm; } pthread_mutex_unlock(&q->mutex);; r = 0; while (r != 1) { r = write(q->notify_w, "x", 1); if (r < 0 && r != EAGAIN) break; } return len; } int lmq_recv(struct lmq_queue *q, void *msg, size_t len, int *prio) { char b; int i, r; int ret; struct lmq_msg *qm = 0; pthread_mutex_lock(&q->mutex);; for (i = 0; i < LMQ_NPRIORITIES; i++) { if (q->priorities_head[i] != 0) { qm = q->priorities_head[i]; if (qm->len > len) { pthread_mutex_unlock(&q->mutex);; errno = EMSGSIZE; return -1; } q->priorities_head[i] = qm->next; if (q->priorities_head[i] == 0) q->priorities_tail[i] = 0; break; } } pthread_mutex_unlock(&q->mutex);; if (qm == 0) { errno = EAGAIN; return -1; } memcpy(msg, qm->data, qm->len); ret = qm->len; if (prio != 0) *prio = i; free(qm->data); free(qm); r = 0; while (r != 1) { r = read(q->notify_r, &b, 1); if (r < 0 && r != EAGAIN) break; } return ret; } int lmq_getfd(struct lmq_queue *q) { return q->notify_r; }
0
#include <pthread.h> pthread_mutex_t lock; int value; }SharedInt; sem_t sem; SharedInt* sip; void plus(int* v2) { pthread_mutex_lock(&(sip->lock)); sip->value = sip->value + *v2; pthread_mutex_unlock(&(sip->lock)); } void *functionWithCriticalSection(int* v2) { plus(v2); sem_post(&sem); } int main() { sem_init(&sem, 0, 0); SharedInt si; sip = &si; sip->value = 0; int v2 = 1; pthread_mutex_init(&(sip->lock), 0); pthread_t thread1; pthread_t thread2; pthread_create (&thread1,0,functionWithCriticalSection,&v2); pthread_create (&thread2,0,functionWithCriticalSection,&v2); sem_wait(&sem); sem_wait(&sem); pthread_mutex_destroy(&(sip->lock)); sem_destroy(&sem); printf("%d\\n", sip->value); return 0; }
1
#include <pthread.h> int balance; int id; pthread_mutex_t mutex; } bank_account; bank_account A, B; int counter = 0; init_account(bank_account *a) { a->id = counter++; a->balance = 0; pthread_mutex_init(&a->mutex, 0); } void deposit(bank_account *f, bank_account *t, int ammount) { if (f->id == t->id) return; if (f->id < t->id) { pthread_mutex_lock(&f->mutex); pthread_mutex_lock(&t->mutex); } else { pthread_mutex_lock(&t->mutex); pthread_mutex_lock(&f->mutex); } t->balance += ammount; f->balance -= ammount; pthread_mutex_unlock(&t->mutex); pthread_mutex_unlock(&f->mutex); } void *t1(void *arg) { deposit(&A, &B, rand() % 100); return 0; } void *t2(void *arg) { deposit(&B, &A, rand() % 100); return 0; } int main(void) { pthread_t id1, id2; init_account(&A); init_account(&B); int i; for (i = 0; i < 100000; i++) { pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join (id1, 0); pthread_join (id2, 0); printf("%d: A = %d, B = %d.\\n", i, A.balance, B.balance); } return 0; }
0