Dataset Viewer
Auto-converted to Parquet
text
stringlengths
1.16k
7.12k
label
int64
0
1
response
stringclasses
1 value
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define BSIZE 4 #define NUMITEMS 30 typedef struct { char buf[BSIZE]; int occupied; int nextin, nextout; pthread_mutex_t mutex; pthread_cond_t more; pthread_cond_t less; } buffer_t; buffer_t buffer; void *producer(void *); void *consumer(void *); #define NUM_THREADS 2 pthread_t tid[NUM_THREADS]; int main(int argc, char *argv[]) { int i; buffer.occupied = 0; buffer.nextin = 0; buffer.nextout = 0; pthread_mutex_init(&(buffer.mutex), NULL); pthread_cond_init(&(buffer.more), NULL); pthread_cond_init(&(buffer.less), NULL); pthread_create(&tid[0], NULL, producer, NULL); pthread_create(&tid[1], NULL, consumer, NULL); for (i = 0; i < NUM_THREADS; i++) { pthread_join(tid[i], NULL); } printf("\\nmain() reporting that all %d threads have terminated\\n", NUM_THREADS); pthread_mutex_destroy(&(buffer.mutex)); pthread_cond_destroy(&(buffer.more)); pthread_cond_destroy(&(buffer.less)); return 0; } void *producer(void *parm) { char item[NUMITEMS] = "IT'S A SMALL WORLD, AFTER ALL."; int i; printf("producer started.\\n"); fflush(stdout); for(i = 0; i < NUMITEMS; i++) { if (item[i] == '\\0') break; while (buffer.occupied >= BSIZE) { printf("producer waiting.\\n"); fflush(stdout); pthread_cond_wait(&(buffer.less), &(buffer.mutex)); } buffer.buf[buffer.nextin++] = item[i]; buffer.nextin %= BSIZE; buffer.occupied++; printf("producer produced: %c\\n", item[i]); fflush(stdout); pthread_cond_signal(&(buffer.more)); usleep(100000); } printf("producer exiting.\\n"); fflush(stdout); pthread_exit(0); } void *consumer(void *parm) { char item; int i; printf("consumer started.\\n"); fflush(stdout); for(i = 0; i < NUMITEMS; i++) { while(buffer.occupied <= 0) { printf("consumer waiting.\\n"); fflush(stdout); pthread_cond_wait(&(buffer.more), &(buffer.mutex)); } item = buffer.buf[buffer.nextout++]; buffer.nextout %= BSIZE; buffer.occupied--; printf("consumer consumed: %c\\n", item); fflush(stdout); pthread_cond_signal(&(buffer.less)); usleep(150000); } printf("consumer exiting.\\n"); fflush(stdout); pthread_exit(0); }
1
1
#include <stdio.h> #include <pthread.h> #include <errno.h> pthread_mutex_t lock_flag; int flag = 1; void *handlerA(void *arg) { int i =0; while(1) { pthread_mutex_lock(&lock_flag); if(flag == 1) { flag = 2; printf("handlerA: A\\n"); i++; } pthread_mutex_unlock(&lock_flag); sleep(1); if(i >= 10) break; } } void *handlerB(void *arg) { int i = 0; while(1) { pthread_mutex_lock(&lock_flag); if(flag == 2) { flag = 3; printf("handlerB: B\\n"); i++; } pthread_mutex_unlock(&lock_flag); sleep(1); if(i >= 10) break; } } void *handlerC(void *arg) { int i =0; while(1) { pthread_mutex_lock(&lock_flag); if(flag == 3) { flag = 1; printf("handlerC: C\\n"); i++; } pthread_mutex_unlock(&lock_flag); sleep(1); if(i >= 10) break; } } int main() { pthread_t pidA; pthread_t pidB; pthread_t pidC; int ret; pthread_mutex_init(&lock_flag,NULL); ret = pthread_create(&pidA,NULL,handlerA,&flag); if(ret < 0) { perror("pthread create"); return -1; } ret = pthread_create(&pidB,NULL,handlerB,&flag); if(ret < 0) { perror("pthread create"); return -1; } ret = pthread_create(&pidC,NULL,handlerC,&flag); if(ret < 0) { perror("pthread create"); return -1; } pthread_join(pidA,NULL); pthread_join(pidB,NULL); pthread_join(pidC,NULL); return 0; }
0
1
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 3 #define TCOUNT 10 #define COUNT_LIMIT 12 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 < TCOUNT; i++){ count++; if(count == COUNT_LIMIT){ 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); sleep(1); } pthread_exit(NULL); } void *watch_count(void *t){ long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); while(count < COUNT_LIMIT){ 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); 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_exit(NULL); } void main(){ int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, NULL); pthread_cond_init (&count_threshold_cv, NULL); 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 < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", NUM_THREADS, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (NULL); }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> void *producer(void *args); void *consumer(void *args); typedef struct { int a_mem[0xffff]; int b_mem[0xffff]; pthread_mutex_t *a_mutex; pthread_mutex_t *b_mutex; int a_is_processing; int b_is_processing; int a_is_empty; int b_is_empty; pthread_cond_t *a_is_ready, *a_isnt_processing; pthread_cond_t *b_is_ready, *b_isnt_processing; } queue; queue *queueInit(void); void queueDelete(queue *q); int main() { queue *fifo; pthread_t pro, con; fifo = queueInit(); if (fifo == 0) { fprintf(stderr, "main: Queue Init failed.\\n"); exit(1); } pthread_create(&pro, NULL, producer, fifo); pthread_create(&con, NULL, consumer, fifo); pthread_join(pro, NULL); pthread_join(con, NULL); queueDelete(fifo); return 0; } void *producer(void *q) { queue *fifo; int i; fifo = (queue *)q; int fd = 0; void *map_base = 0, *virt_addr = 0; const uint32_t ALT_H2F_BASE = 0xC0000000; const uint32_t ALT_H2F_OCM_OFFSET = 0x00000000; off_t target = ALT_H2F_BASE; unsigned long read_result; int idx = 0; if ((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\\n", __LINE__, __FILE__, errno, strerror(errno)); exit(1); } printf("/dev/mem opened.\\n"); fflush(stdout); map_base = mmap(0, 0x44000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, target & ~(0x44000 - 1)); printf("Memory mapped at address %p.\\n", map_base); fflush(stdout); virt_addr = map_base + (target & (0x44000 - 1)); for (i = 0; i < 20; i++) { pthread_mutex_lock(fifo->a_mutex); while (fifo->a_is_processing) { printf("producer: memory A is processing.\\n"); pthread_cond_wait(fifo->a_isnt_processing, fifo->a_mutex); } fifo->a_is_empty = 0; printf("producer: copying a\\n"); for (idx = 0; idx < 0xffff; idx++) { void* access_addr = virt_addr + ALT_H2F_OCM_OFFSET + idx * 4; read_result = *((uint32_t*) access_addr); fifo->a_mem[idx] = read_result; } printf("producer: copying a (end)\\n"); pthread_mutex_unlock(fifo->a_mutex); pthread_cond_signal(fifo->a_is_ready); pthread_mutex_lock(fifo->b_mutex); while (fifo->b_is_processing) { printf("producer: memory B is processing.\\n"); pthread_cond_wait(fifo->b_isnt_processing, fifo->b_mutex); } fifo->b_is_empty = 0; printf("producer: copying b\\n"); for (idx = 0; idx < 0xffff; idx++) { void* access_addr = virt_addr + ALT_H2F_OCM_OFFSET + idx * 4; read_result = *((uint32_t*) access_addr); fifo->b_mem[idx] = read_result; } printf("producer: copying b (end)\\n"); pthread_mutex_unlock(fifo->b_mutex); pthread_cond_signal(fifo->b_is_ready); } if (munmap(map_base, 0x44000) == -1) { fprintf(stderr, "Error at line %d, file %s (%d) [%s]\\n", __LINE__, __FILE__, errno, strerror(errno)); exit(1); } close(fd); return NULL; } void *consumer(void *q) { queue *fifo; int i; fifo = (queue *)q; for (i = 0; i < 20; i++) { pthread_mutex_lock(fifo->a_mutex); while (fifo->a_is_empty) { printf("consumer: memory A is empty, wait producer.\\n"); pthread_cond_wait(fifo->a_is_ready, fifo->a_mutex); } fifo->a_is_processing = 1; printf("image process A\\n"); usleep(10); fifo->a_is_processing = 0; fifo->a_is_empty = 1; pthread_mutex_unlock(fifo->a_mutex); pthread_cond_signal(fifo->a_isnt_processing); pthread_mutex_lock(fifo->b_mutex); while (fifo->b_is_empty) { printf("consumer: memory B is empty, wait producer.\\n"); pthread_cond_wait(fifo->b_is_ready, fifo->b_mutex); } fifo->b_is_processing = 1; printf("image process B\\n"); usleep(10); fifo->b_is_processing = 0; fifo->b_is_empty = 1; pthread_mutex_unlock(fifo->b_mutex); pthread_cond_signal(fifo->b_isnt_processing); } return NULL; } queue *queueInit(void) { queue *q; q = (queue *)malloc(sizeof(queue)); if (q == NULL) return NULL; q->a_is_processing = 0; q->b_is_processing = 0; q->a_is_empty = 1; q->b_is_empty = 1; q->a_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(q->a_mutex, NULL); q->b_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(q->b_mutex, NULL); q->a_is_ready = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); pthread_cond_init(q->a_is_ready, NULL); q->b_is_ready = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); pthread_cond_init(q->b_is_ready, NULL); q->a_isnt_processing = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); pthread_cond_init(q->a_isnt_processing, NULL); q->b_isnt_processing = (pthread_cond_t *)malloc(sizeof(pthread_cond_t)); pthread_cond_init(q->b_isnt_processing, NULL); return q; } void queueDelete(queue *q) { pthread_mutex_destroy(q->a_mutex); free(q->a_mutex); pthread_mutex_destroy(q->b_mutex); free(q->b_mutex); pthread_cond_destroy(q->a_is_ready); free(q->a_is_ready); pthread_cond_destroy(q->b_is_ready); free(q->b_is_ready); pthread_cond_destroy(q->a_isnt_processing); free(q->a_isnt_processing); pthread_cond_destroy(q->b_isnt_processing); free(q->b_isnt_processing); free(q); }
0
1
#include <pthread.h> #include <iostream> #include <unistd.h> using namespace std; #define NUM_THREADS 3 #define TCOUNT 10 #define COUNT_LIMIT 12 int count1 = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { long my_id = (long)t; for (int i = 0; i < TCOUNT; i++) { count1++; if (count1 >= COUNT_LIMIT) { cout << "inc_count(): thread " << my_id << ", count = " << count1 << " Threshold reached. "; pthread_cond_broadcast(&count_threshold_cv); cout << "Just sent signal.\\n"; } cout << "inc_count(): thread " << my_id << ", count = " << count1 << ", unlocking mutex\\n"; usleep(100); } pthread_exit(NULL); } void *watch_count(void *t) { long my_id = (long)t; cout << "Starting watch_count(): thread " << my_id << "\\n"; while (count1 < COUNT_LIMIT) { cout << "watch_count(): thread " << my_id << " Count= " << count1 << ". Going into wait...\\n"; pthread_cond_wait(&count_threshold_cv, &count_mutex); cout << "watch_count(): thread " << my_id << " Condition signal received. Count= " << count1 << "\\n"; } cout << "watch_count(): thread " << my_id << " Updating the value of count...\\n"; count1 += 125; cout << "watch_count(): thread " << my_id << " count now = " << count1 << ".\\n"; cout << "watch_count(): thread " << my_id << " Unlocking mutex.\\n"; pthread_exit(NULL); } int main(int argc, char *argv[]) { long t1 = 1, t2 = 2, t3 = 3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, NULL); pthread_cond_init(&count_threshold_cv, NULL); 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 (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } cout << "Main(): Waited and joined with " << NUM_THREADS << " threads. Final value of count = " << count1 << ". Done.\\n"; pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(NULL); }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <sys/un.h> #include <syslog.h> static int si_init_flag = 0; static int s_conf_fd = -1; static struct sockaddr_un s_conf_addr; static int s_buf_index = 0; static char s_conf_buf[4][(16384)]; static pthread_mutex_t s_atomic; static char CONF_LOCAL_NAME[16] = "/tmp/cfgClient"; inline int cfgSockSetLocal(const char *pLocalName) { if (pLocalName) { snprintf(CONF_LOCAL_NAME, 15, "%s", pLocalName); return 0; } else return -1; } int cfgSockInit() { if (si_init_flag) return 0; s_conf_fd = socket(AF_UNIX, SOCK_DGRAM, 0); if (s_conf_fd < 0) { return -1; } if (0 != pthread_mutex_init(&s_atomic, 0)) { close(s_conf_fd); s_conf_fd = -1; return -1; } unlink(CONF_LOCAL_NAME); bzero(&s_conf_addr, sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), "%s", CONF_LOCAL_NAME); bind(s_conf_fd, (struct sockaddr *)&s_conf_addr, sizeof(s_conf_addr)); bzero(&s_conf_addr, sizeof(s_conf_addr)); s_conf_addr.sun_family = AF_UNIX; snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), "/tmp/cfgServer"); si_init_flag = 1; return 0; } int cfgSockUninit() { if (!si_init_flag) return 0; cfgSockSaveFiles(); if (s_conf_fd > 0) { close(s_conf_fd); } s_conf_fd = -1; unlink(CONF_LOCAL_NAME); pthread_mutex_destroy(&s_atomic); si_init_flag = 0; return 0; } static int cfgSockSend(const char *command) { int ret = -1; int addrlen = sizeof(s_conf_addr); int len = strlen(command); if (!si_init_flag) return -1; ret = sendto(s_conf_fd, command, len, 0, (struct sockaddr *)&s_conf_addr, addrlen); if (ret != len) { close(s_conf_fd); s_conf_fd = -1; ret = -1; si_init_flag = 0; syslog(LOG_ERR, "send conf message failed, ret = %d, errno %d\\n", ret, errno); } return ret; } static int cfgSockRecv(char *buf, int len) { int ret; if (!si_init_flag) return -1; ret = recv(s_conf_fd, buf, len - 1, 0); if (ret > 0) buf[ret] = '\\0'; else buf[0] = '\\0'; return ret; } static int cfgSockRequest(const char *command, char *recvbuf, int recvlen) { int ret; if (!command || !recvbuf || !recvlen) return -1; ret = cfgSockSend(command); if (ret >= 0) { ret = cfgSockRecv(recvbuf, recvlen); } return ret; } const char *cfgSockGetValue(const char *a_pSection, const char *a_pKey, const char *a_pDefault) { int nRet = -1; char *conf_buf; if (!si_init_flag || (!a_pSection && !a_pKey)) return 0; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index = (s_buf_index + 1) & 3; if (a_pSection && a_pKey) { if (!a_pDefault) snprintf(conf_buf, (16384), "R %s.%s %s", a_pSection, a_pKey, "NULL"); else snprintf(conf_buf, (16384), "R %s.%s %s", a_pSection, a_pKey, a_pDefault); } else { const char *key = (a_pSection) ? a_pSection : a_pKey; if (!a_pDefault) snprintf(conf_buf, (16384), "R %s %s", key, "NULL"); else snprintf(conf_buf, (16384), "R %s %s", key, a_pDefault); } cfgSockRequest(conf_buf, conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); nRet = strncmp(conf_buf, "NULL", 4); if (0 == nRet) { return a_pDefault; } return conf_buf; } int cfgSockSetValue(const char *a_pSection, const char *a_pKey, const char *a_pValue) { char *conf_buf; if (!si_init_flag || (!a_pSection && !a_pKey) || !a_pValue) return -1; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index = (s_buf_index + 1) & 3; if (a_pSection && a_pKey) { snprintf(conf_buf, (16384), "W %s.%s %s", a_pSection, a_pKey, a_pValue); } else { const char *key = (a_pSection) ? a_pSection : a_pKey; snprintf(conf_buf, (16384), "W %s %s", key, a_pValue); } cfgSockRequest(conf_buf, conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); return 0; } int cfgSockSaveFiles() { char *conf_buf; if (!si_init_flag) return -1; pthread_mutex_lock(&s_atomic); conf_buf = s_conf_buf[s_buf_index]; s_buf_index = (s_buf_index + 1) & 3; cfgSockRequest("s", conf_buf, (16384)); pthread_mutex_unlock(&s_atomic); return 0; }
0
1
#include <stdio.h> #include <err.h> #include <stdlib.h> #include <string.h> #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) { copy_employee(&employees[num - 1], &employee_of_the_day); } } 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, NULL, do_loop, &num1)) { errx(EXIT_FAILURE, "pthread_create() error.\\n"); } if (pthread_create(&th2, NULL, do_loop, &num2)) { errx(EXIT_FAILURE, "pthread_create() error.\\n"); } while (1) { 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(EXIT_FAILURE); } 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(EXIT_FAILURE); } 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(EXIT_FAILURE); } 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(EXIT_FAILURE); } 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(EXIT_FAILURE); } printf("lory, employees contents was always consistent\\n"); } exit(EXIT_SUCCESS); }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <linux/netlink.h> #include <errno.h> extern int K; extern int VECT_SIZE; extern int aHash[10]; extern int bHash[10]; extern int m[10]; pthread_t ids[48]; int nextLoc = -1; pthread_mutex_t m_nextLoc; int totalOnes = 0; pthread_mutex_t m_totalOnes; int numMemberships = 0; pthread_mutex_t m_numMemberships; int *M; int *checked; pthread_mutex_t *m_M; int nVertices; struct bloom *a; int ceilDiv(int a, int b); void *countOnes(void *x); void setM(); void resetM(); int checkLocation(int value, int *M); int setLocation(int value, int *M); int resetLocation(int value); void reconstruct0(int loc); void reconstruct1(int loc); void *reconstruct0_thread(void *x); void *reconstruct1_thread(void *x); int main(int argc, char *argv[]){ nVertices = atoi(argv[1]); int nNodes = atoi(argv[2]); K = atoi(argv[4]); VECT_SIZE = atoi(argv[5]); seiveInitial(); struct timespec start, finish, mid; double elapsed, elapsed_m; a = (struct bloom*)malloc(sizeof(struct bloom)); a->bloom_vector = (int*)malloc(sizeof(int)*(VECT_SIZE/NUM_BITS + 1)); init(a); FILE *finput = fopen(argv[3],"r"); int i = 0; int val; while (i<nNodes){ val = 0; fscanf(finput,"%d\\n",&val); insert(val,a); i++; } fclose(finput); int size = ceilDiv(nVertices,NUM_BITS); M = (int*)malloc(sizeof(int)*size); checked = (int*)malloc(sizeof(int)*size); for (i=0;i<size;i++) checked[i] = 0; pthread_mutex_init(&m_nextLoc,0); pthread_mutex_init(&m_totalOnes,0); pthread_mutex_init(&m_numMemberships,0); nextLoc = 0; int rc; clock_gettime(CLOCK_MONOTONIC, &start); for (i=0;i<48;i++){ rc = pthread_create(&ids[i],0,countOnes,(void*)(i)); } void *status; for (i=0;i<48;i++){ pthread_join(ids[i],&status); } clock_gettime(CLOCK_MONOTONIC, &mid); nextLoc = 0; if (totalOnes < VECT_SIZE / 2){ resetM(); for (i=0;i<48;i++) rc = pthread_create(&ids[i],0,reconstruct1_thread,(void*)(i)); for (i=0;i<48;i++) pthread_join(ids[i],&status); } else{ setM(); for (i=0;i<48;i++) rc = pthread_create(&ids[i],0,reconstruct0_thread,(void*)(i)); for (i=0;i<48;i++) pthread_join(ids[i],&status); } clock_gettime(CLOCK_MONOTONIC, &finish); elapsed_m = mid.tv_sec - start.tv_sec; elapsed_m += (mid.tv_nsec - start.tv_nsec)/pow(10,9); elapsed = finish.tv_sec - start.tv_sec; elapsed += (finish.tv_nsec - start.tv_nsec)/pow(10,9); totalOnes = 0; for (i=0;i<size;i++) totalOnes += count_ones(M[i]); printf("RECONSTRUCTED SET OF SIZE %d IN TIME %lf WITH MEMBERSHIPS=%d\\n",totalOnes, elapsed,numMemberships); } void *reconstruct0_thread(void *x){ while(1){ pthread_mutex_lock(&m_nextLoc); int nL = nextLoc; if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){ nextLoc++; pthread_mutex_unlock(&m_nextLoc); reconstruct0(nL); } else{ pthread_mutex_unlock(&m_nextLoc); pthread_exit(0); } } } void *reconstruct1_thread(void *x){ while(1){ pthread_mutex_lock(&m_nextLoc); int nL = nextLoc; if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){ nextLoc++; pthread_mutex_unlock(&m_nextLoc); reconstruct1(nL); } else{ pthread_mutex_unlock(&m_nextLoc); pthread_exit(0); } } } int ceilDiv(int a, int b){ return (a+b-1)/b; } void *countOnes(void *x){ while (1){ pthread_mutex_lock(&m_nextLoc); int nL = nextLoc; if (nL < ceilDiv (VECT_SIZE , NUM_BITS)){ nextLoc++; pthread_mutex_unlock(&m_nextLoc); int z = count_ones(a->bloom_vector[nL]); if (z>0){ pthread_mutex_lock(&m_totalOnes); totalOnes += z; pthread_mutex_unlock(&m_totalOnes); } } else{ pthread_mutex_unlock(&m_nextLoc); pthread_exit(0); } } } void setM(){ int i; int size = ceilDiv(nVertices,NUM_BITS); for (i=0;i<size;i++) M[i] = M[i] | (~0); } void resetM(){ int i; int size = ceilDiv(nVertices,NUM_BITS); for (i=0;i<size;i++) M[i] = 0; } int checkLocation(int value, int *M){ int loc = value / NUM_BITS; int off = value % NUM_BITS; int retVal = 0; if ((M[loc] & (1<<off)) != 0) retVal = 1; return retVal; } int setLocation(int value, int *M){ int loc = value / NUM_BITS; int off = value % NUM_BITS; M[loc] = M[loc] | (1 << off); } int resetLocation(int value){ int loc = value / NUM_BITS; int off = value % NUM_BITS; M[loc] = M[loc] & (~(1 << off)); } void reconstruct0(int loc){ int i; for (i=loc*NUM_BITS;i<(loc+1)*NUM_BITS;i++){ int v = a->bloom_vector[loc] & (1 << (i%NUM_BITS)); if (v==0){ int h = 0; for (h=0;h<3;h++){ int sample = 0, count = 0; while (sample<nVertices){ if (((i-bHash[h])%aHash[h] + (count*m[h])%aHash[h])%aHash[h] == 0){ sample = ((int) (((double)i - bHash[h])/aHash[h] + ((double)count*m[h])/aHash[h])); if (sample>0){ resetLocation(sample); } } sample = ((int) (((double)i - bHash[h])/aHash[h] + ((double)count*m[h])/aHash[h])); count++; } } } } } void reconstruct1(int loc){ int i; int localCount = 0; for (i=loc*NUM_BITS;i<(loc+1)*NUM_BITS;i++){ int v = a->bloom_vector[loc] & (1 << (i%NUM_BITS)); if (v!=0){ int h; for (h=0;h<3;h++){ int sample = 0, count = 0; while (sample<nVertices){ double cd = count, vd = m[h], ad = aHash[h], bd = bHash[h], s; s = (i- bd + cd*vd)/ad; sample = (int) s; if (floor(s)==s){ if ((sample>0)&&(sample<nVertices)&&(!checkLocation(sample,checked))){ setLocation(sample,checked); localCount++; if (is_in(sample,a)){ setLocation(sample,M); } } } count++; } } } } pthread_mutex_lock(&m_numMemberships); numMemberships += localCount; pthread_mutex_unlock(&m_numMemberships); }
0
1
#include "helper.h" void pclock(char *msg, clockid_t cid) { struct timespec ts; printf("%s", msg); if (clock_gettime(cid, &ts) == -1) { perror("clock_gettime"); return; } printf("%4ld.%03ld\\n", ts.tv_sec, ts.tv_nsec / 1000000); } void errp(char *s, int code) { fprintf(stderr, "Error: %s -- %s\\n", s, strerror(code)); } void thr_sleep(time_t sec, long nsec) { struct timeval now; struct timezone tz; struct timespec ts; int retcode; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; if(retcode) { fprintf(stderr, "Error: mutex_lock -- %s\\n", strerror(retcode)); return; } gettimeofday(&now, &tz); ts.tv_sec = now.tv_sec + sec + (nsec / 1000000000L); ts.tv_nsec = (now.tv_usec * 1000) + (nsec % 1000000000L); if(ts.tv_nsec > 1000000000L) { (ts.tv_sec)++; (ts.tv_nsec) -= 1000000000L; } retcode = pthread_cond_timedwait(&cond, &m, &ts); if(retcode != ETIMEDOUT) { if(retcode == 0) { fprintf(stderr, "pthread_cond_timedwait returned early.\\n"); } else { fprintf(stderr, "pthread_cond_timedwait error: %s\\n", strerror(retcode)); return; } } if(retcode) { fprintf(stderr, "Error: mutex_unlock -- %s\\n", strerror(retcode)); return; } pthread_cond_destroy(&cond); pthread_mutex_destroy(&m); } void mulock(int ul, pthread_mutex_t *m) { int retcode = 0; char myErrStr[100]; if (ul) { strcpy(myErrStr, "mutex_unlock"); retcode = pthread_mutex_unlock(m); } else { strcpy(myErrStr, "mutex_lock"); retcode = pthread_mutex_lock(m); } if (retcode) { fprintf(stderr, "%s, %s\\n", myErrStr, strerror(retcode)); } }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <assert.h> #include <sys/time.h> #include <dlfcn.h> #include <errno.h> #include <limits.h> #include <libgen.h> #define PERFINDEX_FAILURE -1 #define MAXPATHLEN 1024 typedef struct parsed_args_struct { char* my_name; char* test_name; int num_threads; long long length; int test_argc; void** test_argv; } parsed_args_t; typedef struct test_struct { int (*setup)(int, long long, int, void**); int (*execute)(int, int, long long, int, void**); int (*cleanup)(int, long long); char** error_str_ptr; } test_t; parsed_args_t args; test_t test; int ready_thread_count = 0; pthread_mutex_t ready_thread_count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t start_cvar = PTHREAD_COND_INITIALIZER; pthread_cond_t threads_ready_cvar = PTHREAD_COND_INITIALIZER; int parse_args(int argc, char** argv, parsed_args_t* parsed_args) { if (argc != 4) { return -1; } parsed_args->my_name = argv[0]; parsed_args->test_name = argv[1]; parsed_args->num_threads = atoi(argv[2]); parsed_args->length = strtoll(argv[3], NULL, 10); parsed_args->test_argc = 0; parsed_args->test_argv = NULL; return 0; } void print_usage(char** argv) { printf("Usage: %s test_name threads length\\n", argv[0]); } int find_test(char* test_name, char* test_path) { char binpath[MAXPATHLEN]; char* dirpath; uint32_t size = sizeof(binpath); int retval; retval = _NSGetExecutablePath(binpath, &size); assert(retval == 0); dirpath = dirname(binpath); snprintf(test_path, MAXPATHLEN, "%s/perfindex-%s.dylib", dirpath, test_name); return access(test_path, F_OK) == 0 ? 0 : -1; } int load_test(char* path, test_t* test) { void* handle; void* p; handle = dlopen(path, RTLD_NOW | RTLD_LOCAL); if (!handle) { fprintf(stderr, "dlopen error: %s\\n", dlerror()); return -1; } p = dlsym(handle, "setup"); test->setup = (int (*)(int, long long, int, void**))p; p = dlsym(handle, "execute"); test->execute = (int (*)(int, int, long long, int, void**))p; if (p == NULL) { fprintf(stderr, "dlsym error: %s\\n", dlerror()); return -1; } p = dlsym(handle, "cleanup"); test->cleanup = (int (*)(int, long long))p; p = dlsym(handle, "error_str"); test->error_str_ptr = (char**)p; return 0; } void start_timer(struct timeval* tp) { gettimeofday(tp, NULL); } void end_timer(struct timeval* tp) { struct timeval tend; gettimeofday(&tend, NULL); if (tend.tv_usec >= tp->tv_usec) { tp->tv_sec = tend.tv_sec - tp->tv_sec; tp->tv_usec = tend.tv_usec - tp->tv_usec; } else { tp->tv_sec = tend.tv_sec - tp->tv_sec - 1; tp->tv_usec = tend.tv_usec - tp->tv_usec + 1000000; } } void print_timer(struct timeval* tp) { printf("%ld.%06ld seconds\\n", tp->tv_sec, (long)tp->tv_usec); } static void* thread_setup(void* arg) { int my_index = (intptr_t)arg; long long work_size = args.length / args.num_threads; int work_remainder = args.length % args.num_threads; if (work_remainder > my_index) { work_size++; } pthread_mutex_lock(&ready_thread_count_lock); ready_thread_count++; if (ready_thread_count == args.num_threads) pthread_cond_signal(&threads_ready_cvar); pthread_cond_wait(&start_cvar, &ready_thread_count_lock); pthread_mutex_unlock(&ready_thread_count_lock); test.execute(my_index, args.num_threads, work_size, args.test_argc, args.test_argv); return NULL; } int main(int argc, char** argv) { int retval; int thread_index; struct timeval timer; pthread_t* threads; char test_path[MAXPATHLEN]; retval = parse_args(argc, argv, &args); if (retval) { print_usage(argv); return -1; } retval = find_test(args.test_name, test_path); if (retval) { printf("Unable to find test %s\\n", args.test_name); return -1; } retval = load_test(test_path, &test); if (retval) { printf("Unable to load test %s\\n", args.test_name); return -1; } if (test.setup) { retval = test.setup(args.num_threads, args.length, 0, NULL); if (retval == PERFINDEX_FAILURE) { fprintf(stderr, "Test setup failed: %s\\n", *test.error_str_ptr); return -1; } } threads = (pthread_t*)malloc(sizeof(pthread_t) * args.num_threads); if (!threads) { perror("malloc"); return -1; } for (thread_index = 0; thread_index < args.num_threads; thread_index++) { retval = pthread_create(&threads[thread_index], NULL, thread_setup, (void*)(intptr_t)thread_index); assert(retval == 0); } pthread_mutex_lock(&ready_thread_count_lock); if (ready_thread_count != args.num_threads) { pthread_cond_wait(&threads_ready_cvar, &ready_thread_count_lock); } pthread_mutex_unlock(&ready_thread_count_lock); start_timer(&timer); pthread_cond_broadcast(&start_cvar); for (thread_index = 0; thread_index < args.num_threads; thread_index++) { pthread_join(threads[thread_index], NULL); if (**test.error_str_ptr) { printf("Test failed: %s\\n", *test.error_str_ptr); } } end_timer(&timer); if (test.cleanup) { retval = test.cleanup(args.num_threads, args.length); if (retval == PERFINDEX_FAILURE) { fprintf(stderr, "Test cleanup failed: %s\\n", *test.error_str_ptr); free(threads); return -1; } } print_timer(&timer); free(threads); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <sys/time.h> #include <math.h> #define GRID_SIZE 16384 float** main_plate; float** main_prev_plate; char** main_locked_cells; pthread_barrier_t barrier_first; pthread_barrier_t barrier_second; pthread_mutex_t critical_begin_end; pthread_mutex_t runnable; typedef struct arg_plate { int nthreads; int begin; int end; } arg_plate_t; double when() { struct timeval tp; gettimeofday(&tp, 0); return ((double)tp.tv_sec + (double)tp.tv_usec * 1e-6); } float** createPlate() { float** plate = (float**)malloc(16384 * sizeof(float*)); int k; for (k = 0; k < 16384; k++) { plate[k] = (float*)malloc(16384 * sizeof(float)); } return plate; } char** createCharPlate() { char** plate = (char**)malloc(16384 * sizeof(char*)); int k; for (k = 0; k < 16384; k++) { plate[k] = (char*)malloc(16384 * sizeof(char)); } return plate; } void copy(float** main, float** result) { int i,j; for (i = 0; i < 16384; i++) { for (j = 0; j < 16384; j++) { result[i][j] = main[i][j]; } } } void initPlate(float** plate, float** prev_plate) { int i, j; for (i = 0; i < 16384; i++) { for (j = 0; j < 16384; j++) { if (i == 0 || j == 0 || j == 16384 -1) { plate[i][j] = 0; prev_plate[i][j] = 0; main_locked_cells[i][j] = '1'; } else if (i == 16384 -1) { plate[i][j] = 100; prev_plate[i][j] = 100; main_locked_cells[i][j] = '1'; } else if (i == 400 && j >= 0 && j <= 330) { plate[i][j] = 100; prev_plate[i][j] = 100; main_locked_cells[i][j] = '1'; } else if (i == 200 && j == 500) { plate[i][j] = 100; prev_plate[i][j] = 100; main_locked_cells[i][j] = '1'; } else { plate[i][j] = 50; prev_plate[i][j] = 50; main_locked_cells[i][j] = '0'; } } } for (i = 0; i < 16384; i++) { if ((i % 20) == 0) { for (j = 0; j < 16384; j++) { plate[i][j] = 100; prev_plate[i][j] = 100; main_locked_cells[i][j] = '1'; } } } for (j = 0; j < 16384; j++) { if ((j % 20) == 0) { for (i = 0; i < 16384; i++) { plate[i][j] = 0; prev_plate[i][j] = 0; main_locked_cells[i][j] = '1'; } } } } void cleanupFloat(float** plate) { int i, j; for (i = 0; i < 16384; i++) { free(plate[i]); } free(plate); } void cleanupChar(char** plate) { int i, j; for (i = 0; i < 16384; i++) { free(plate[i]); } free(plate); } void* update_plate(void* plate_arguments) { for(;;) { pthread_barrier_wait(&barrier_first); arg_plate_t* plate_args = (arg_plate_t*)plate_arguments; int begin = plate_args->begin; int end = plate_args->end; int i, j; for (i = begin; i < end; i++) { for (j = 0; j < 16384; j++) { if (main_locked_cells[i][j] == '0') { main_plate[i][j] = (main_prev_plate[i+1][j] + main_prev_plate[i][j+1] + main_prev_plate[i-1][j] + main_prev_plate[i][j-1] + 4 * main_prev_plate[i][j]) * 0.125; } } } pthread_barrier_wait(&barrier_second); } } char steady(float** current_plate) { int count = 0; int i, j; float main_diff = 0; for (i = 0; i < 16384; i++) { for (j = 0; j < 16384; j++) { if (main_locked_cells[i][j] == '0') { if (current_plate[i][j] > 50) count++; float diff = fabs(current_plate[i][j] - (current_plate[i+1][j] + current_plate[i-1][j] + current_plate[i][j+1] + current_plate[i][j-1]) * 0.25); if (diff > main_diff) main_diff = diff; } } } if (main_diff > 0.1) return (1); else return (0); } void allocateWorkload(int nthreads, int* begin_end) { int step = 16384 / nthreads; int i; int begin = 0; for (i = 0; i < nthreads*2; i++) { begin_end[i] = begin; begin = begin+step; i += 1; begin_end[i] = begin; } } int startUpdate(pthread_t* threads, int nthreads) { printf("Updating plate to steady state\\n"); int iterations = 0; int* begin_end = (int*)malloc((nthreads*2) * sizeof(int)); allocateWorkload(nthreads, begin_end); int i; int j; pthread_t worker[nthreads]; arg_plate_t* plate_args; for (i = 0; i < nthreads; i++) { plate_args = (arg_plate_t*)malloc(sizeof(arg_plate_t)); j = i * 2; plate_args->begin = begin_end[j]; plate_args->end = begin_end[j+1]; pthread_create(&worker[i], 0, &update_plate, (void*)plate_args); } do { iterations++; printf("Iteration: %d\\n", iterations); pthread_barrier_wait(&barrier_first); pthread_barrier_wait(&barrier_second); copy(main_plate, main_prev_plate); } while(steady(main_plate)); return iterations; } int main(int argc, char* argv[]) { double start = when(); printf("Starting time: %f\\n", start); int nthreads = atoi(argv[1]); pthread_t threads[nthreads]; main_plate = createPlate(); main_prev_plate = createPlate(); main_locked_cells = createCharPlate(); initPlate(main_plate, main_prev_plate); pthread_barrier_init(&barrier_first,0,nthreads+1); pthread_barrier_init(&barrier_second,0,nthreads+1); pthread_mutex_init(&critical_begin_end,0); pthread_mutex_init(&runnable,0); int iterations = startUpdate(threads, nthreads); double end = when(); printf("\\nEnding time: %f\\n", end); printf("Total execution time: %f\\n", end - start); printf("Number of iterations: %d\\n\\n", iterations); pthread_barrier_destroy(&barrier_first); pthread_barrier_destroy(&barrier_second); pthread_mutex_destroy(&critical_begin_end); pthread_mutex_destroy(&runnable); printf("Cleanup\\n"); cleanupFloat(main_plate); cleanupFloat(main_prev_plate); cleanupChar(main_locked_cells); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> struct node { char user[5]; char process; int arrival; int duration; int priority; struct node *next; }*head; struct display { char user[5]; int timeLastCalculated; struct display *next; }*frontDisplay, *tempDisplay, *rearDisplay; pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; void initialise(); void insert(char[5], char, int, int, int); void add(char[5], char, int, int, int); int count(); void addafter(char[5], char, int, int, int, int); void* jobDisplay(); void addToSummary(char[], int); void summaryDisplay(); int main(int argc, char *argv[]) { int n; if (argc == 2) { n = atoi(argv[1]); } else if (argc > 2) { printf("Too many arguments supplied.\\n"); return 0; } else { printf("One argument expected.\\n"); return 0; } char user[5], process; int arrivalInput, durationInput, priorityInput; initialise(); printf("\\n\\tUser\\tProcess\\tArrival\\tRuntime\\tPriority\\n"); int i = 1; while (i < 5) { printf("\\t"); if (scanf("%s %c %d %d %d", user, &process, &arrivalInput, &durationInput, &priorityInput) < 5) { printf("\\nThe arguments supplied are incorrect. Try again.\\n"); return 0; } insert(user, process, arrivalInput, durationInput, priorityInput); i++; } printf("\\nThis would result in:\\n\\tTime\\tJob\\n"); pthread_t threadID[n]; for (i = 0; i < n; i++) { if (pthread_create(&threadID[i], NULL, &jobDisplay, NULL) != 0) { perror("Error creating thread"); return 1; } } for (i = 0; i < n; i++) { pthread_join(threadID[i], NULL); } pthread_mutex_destroy(&m1); pthread_mutex_destroy(&m2); summaryDisplay(); return 0; } void initialise() { head = NULL; rearDisplay = NULL; tempDisplay = NULL; frontDisplay = NULL; } void insert(char user[5], char process, int arrival, int duration, int priority) { int c = 0; struct node *temp = head; if (temp == NULL) { add(user, process, arrival, duration, priority); } else { while (temp != NULL) { if ((temp->arrival + temp->duration) < (arrival + duration)) { c++; } temp = temp->next; } if (c == 0) { add(user, process, arrival, duration, priority); } else if (c < count()) { addafter(user, process, arrival, duration, priority, ++c); } else { struct node *right; temp = (struct node *)malloc(sizeof(struct node)); if (temp == NULL) { perror("Memory allocation failed"); exit(1); } strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; right = head; while (right->next != NULL) { right = right->next; } right->next = temp; temp->next = NULL; } } } void add(char user[5], char process, int arrival, int duration, int priority) { struct node *temp = (struct node *)malloc(sizeof(struct node)); if (temp == NULL) { perror("Memory allocation failed"); exit(1); } strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; if (head == NULL) { head = temp; head->next = NULL; } else { temp->next = head; head = temp; } } int count() { struct node *n = head; int c = 0; while (n != NULL) { n = n->next; c++; } return c; } void addafter(char user[5], char process, int arrival, int duration, int priority, int loc) { int i; struct node *temp, *left, *right; right = head; for (i = 1; i < loc; i++) { left = right; right = right->next; } temp = (struct node *)malloc(sizeof(struct node)); if (temp == NULL) { perror("Memory allocation failed"); exit(1); } strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; left->next = temp; temp->next = right; } void* jobDisplay() { pthread_mutex_lock(&m1); struct node* placeholder = head; pthread_mutex_unlock(&m1); if (placeholder == NULL) { pthread_exit(NULL); } int myTime = 0; while (placeholder != NULL) { if (myTime < placeholder->arrival) { sleep(placeholder->arrival - myTime); myTime = placeholder->arrival; } pthread_mutex_lock(&m1); struct node* currentJob = placeholder; pthread_mutex_unlock(&m1); for (int i = 0; i < currentJob->duration; i++) { printf("\\t%d\\t%c\\n", myTime, currentJob->process); myTime++; sleep(1); } addToSummary(currentJob->user, myTime); pthread_mutex_lock(&m1); placeholder = placeholder->next; pthread_mutex_unlock(&m1); } printf("\\t%d\\tIDLE\\n", myTime); pthread_exit(NULL); } void addToSummary(char name[], int timeLeft) { pthread_mutex_lock(&m2); if (rearDisplay == NULL) { rearDisplay = (struct display *)malloc(sizeof(struct display)); if (rearDisplay == NULL) { perror("Memory allocation failed"); pthread_mutex_unlock(&m2); exit(1); } rearDisplay->next = NULL; strcpy(rearDisplay->user, name); rearDisplay->timeLastCalculated = timeLeft; frontDisplay = rearDisplay; } else { tempDisplay = frontDisplay; while (tempDisplay != NULL) { if (strcmp(tempDisplay->user, name) == 0) { tempDisplay->timeLastCalculated = timeLeft; pthread_mutex_unlock(&m2); return; } tempDisplay = tempDisplay->next; } tempDisplay = (struct display *)malloc(sizeof(struct display)); if (tempDisplay == NULL) { perror("Memory allocation failed"); pthread_mutex_unlock(&m2); exit(1); } rearDisplay->next = tempDisplay; strcpy(tempDisplay->user, name); tempDisplay->timeLastCalculated = timeLeft; tempDisplay->next = NULL; rearDisplay = tempDisplay; } pthread_mutex_unlock(&m2); } void summaryDisplay() { printf("\\n\\tSummary\\n"); while (frontDisplay != NULL) { printf("\\t%s\\t%d\\n", frontDisplay->user, frontDisplay->timeLastCalculated); tempDisplay = frontDisplay->next; free(frontDisplay); frontDisplay = tempDisplay; } printf("\\n"); }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <stdbool.h> struct mode_extra_status { int output_pipe_fd; pthread_mutex_t mutex; union switch_data answer; long long rest_time[SWITCH_BUTTON_NUM + 1]; int score; pthread_t background_worker; bool terminated; }; static void *background_worker_main (void *arg); struct mode_extra_status *mode_extra_construct (int output_pipe_fd) { struct mode_extra_status *status; status = malloc (sizeof (*status)); status->output_pipe_fd = output_pipe_fd; pthread_mutex_init (&status->mutex, 0); status->answer.val = 0; status->score = 0; status->terminated = 0; pthread_create (&status->background_worker, 0, &background_worker_main, status); return status; } void mode_extra_destroy (struct mode_extra_status *status) { atomic_store_bool (&status->terminated, 1); pthread_join (status->background_worker, 0); pthread_mutex_destroy (&status->mutex); free (status); } int mode_extra_switch (struct mode_extra_status *status, union switch_data data) { int16_t correct = status->answer.val & data.val; int16_t incorrect = (status->answer.val ^ data.val) & data.val; LOG (LOGGING_LEVEL_HIGH, "[Main Process] correct = %03X, incorrect = %03X.", correct, incorrect); status->answer.val ^= correct; for (int i = 0; i < SWITCH_BUTTON_NUM; ++i) { status->score += (correct & 1); status->score -= (incorrect & 1); correct >>= 1; incorrect >>= 1; } if (status->score < 0) status->score = 0; output_message_fnd_send (status->output_pipe_fd, status->score); return 0; } static void *background_worker_main (void *arg) { struct mode_extra_status *status = arg; long long prev_nano_time = get_nano_time (); long long prev_creation_time = 0; while (!atomic_load_bool (&status->terminated)) { long long cur_nano_time = get_nano_time (); long long time_gap = cur_nano_time - prev_nano_time; prev_nano_time = cur_nano_time; # 110 "mode_extra.c" if (status->answer.bit_fields.s1) { status->rest_time[ 1 ] -= time_gap; if (status->rest_time[ 1 ] < 0) { status->answer.bit_fields.s1 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s2) { status->rest_time[ 2 ] -= time_gap; if (status->rest_time[ 2 ] < 0) { status->answer.bit_fields.s2 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s3) { status->rest_time[ 3 ] -= time_gap; if (status->rest_time[ 3 ] < 0) { status->answer.bit_fields.s3 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s4) { status->rest_time[ 4 ] -= time_gap; if (status->rest_time[ 4 ] < 0) { status->answer.bit_fields.s4 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s5) { status->rest_time[ 5 ] -= time_gap; if (status->rest_time[ 5 ] < 0) { status->answer.bit_fields.s5 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s6) { status->rest_time[ 6 ] -= time_gap; if (status->rest_time[ 6 ] < 0) { status->answer.bit_fields.s6 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s7) { status->rest_time[ 7 ] -= time_gap; if (status->rest_time[ 7 ] < 0) { status->answer.bit_fields.s7 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s8) { status->rest_time[ 8 ] -= time_gap; if (status->rest_time[ 8 ] < 0) { status->answer.bit_fields.s8 = 0; if (status->score > 0) --status->score; } }; if (status->answer.bit_fields.s9) { status->rest_time[ 9 ] -= time_gap; if (status->rest_time[ 9 ] < 0) { status->answer.bit_fields.s9 = 0; if (status->score > 0) --status->score; } }; long long delay_base = 300LL * 1000LL * 1000LL; long long micro_delay = (rand () % 10 + 1) * delay_base; double delay_coef = 5 / ((status->score + 10) / 20.0); if (cur_nano_time - prev_creation_time > delay_coef * delay_base) { int no = 1 + rand () % SWITCH_BUTTON_NUM; status->rest_time[no] = micro_delay; status->answer.val |= (1 << (no-1)); prev_creation_time = cur_nano_time; } output_message_fnd_send (status->output_pipe_fd, status->score); struct dot_matrix_data dot_data = { { { 0, }, } }; int16_t bit_mask = 1; const int x_jump = 2, x_size = 3; const int y_jump = 3, y_size = 4; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (status->answer.val & bit_mask) { int base_y = i * y_jump; int base_x = j * x_jump; for (int y = base_y; y < base_y + y_size; ++y) for (int x = base_x; x < base_x + x_size; ++x) dot_data.data[y][x] = 1; } bit_mask <<= 1; } } output_message_dot_matrix_send (status->output_pipe_fd, &dot_data); usleep ((10*1000)); } return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <fcntl.h> #include <string.h> #include <time.h> #include <sys/time.h> #include <errno.h> #define MAX_CHANNEL 6 static pthread_t threadTickGenerator; static pthread_t threadFIFO2DA[MAX_CHANNEL]; static pthread_mutex_t mutexTick[MAX_CHANNEL]; static pthread_cond_t condTick[MAX_CHANNEL]; int debug = 0; int readAChar(int fifoFD) { char aChar; int err = read(fifoFD, &aChar, 1); if (err < 0) { perror("read"); return -1; } else if (err == 0) { sleep(1); return -2; } return (int)aChar; } void waitTick(int Channel) { pthread_mutex_lock(&mutexTick[Channel]); pthread_cond_wait(&condTick[Channel], &mutexTick[Channel]); pthread_mutex_unlock(&mutexTick[Channel]); } void *functionTickGenerator(void *param) { int Channel; for (Channel = 0; Channel < MAX_CHANNEL; Channel++) { pthread_mutex_init(&mutexTick[Channel], NULL); pthread_cond_init(&condTick[Channel], NULL); } while (1) { struct timespec sleepTime = {0, 40 * 1000000}; for (Channel = 0; Channel < MAX_CHANNEL; Channel++) { pthread_mutex_lock(&mutexTick[Channel]); pthread_cond_signal(&condTick[Channel]); pthread_mutex_unlock(&mutexTick[Channel]); } nanosleep(&sleepTime, NULL); } return NULL; } void *functionFIFO2DA(void *param) { int channel = (intptr_t)param; char stringFIFO[32]; int fifoFD; pthread_detach(pthread_self()); snprintf(stringFIFO, sizeof(stringFIFO), "/tmp/FIFO_CHANNEL%d", channel); fifoFD = open(stringFIFO, O_RDONLY); if (fifoFD < 0) { perror("open"); if (mkfifo(stringFIFO, 0777) != 0) { perror("mkfifo"); goto threadError; } fifoFD = open(stringFIFO, O_RDONLY); if (fifoFD < 0) { perror("open after mkfifo"); goto threadError; } } while (1) { char readBuffer[512 * 1024]; char *walkInBuffer = readBuffer; int readSize; int stringIndex; int readInt; char *toNullPos; readSize = read(fifoFD, readBuffer, sizeof(readBuffer)); if (readSize <= 0) { struct timespec sleepTime = {0, 40 * 1000000}; nanosleep(&sleepTime, NULL); continue; } if (debug) printf("ch%d:", channel); do { toNullPos = strchr(walkInBuffer, ','); if (toNullPos) *toNullPos = '\\0'; stringIndex = sscanf(walkInBuffer, "0x%x", &readInt); if (stringIndex == 0) { stringIndex = sscanf(walkInBuffer, "%d", &readInt); if (stringIndex == 0) { fprintf(stderr, "Invalid number: %s\\n", walkInBuffer); if (toNullPos) { walkInBuffer = toNullPos + 1; continue; } else { break; } } } writeDAC(channel, readInt); waitTick(channel); if (toNullPos) walkInBuffer = toNullPos + 1; else break; } while (strlen(walkInBuffer) > 0); if (debug) printf("\\n"); } threadError: printf("Channel %d exit\\n", channel); if (fifoFD >= 0) close(fifoFD); return NULL; } static const int maxValue[MAX_CHANNEL] = { 120, 240, 60, 30, 30, 30 }; int cpap2psg(int rs232_descriptor, char *cmdBuffer, int cmdSize, int checkedXor) { int expectedLength = 5; if (sendCPAPCmd(rs232_descriptor, cmdBuffer, cmdSize, checkedXor)) return -1; unsigned char responseBuffer[1024]; int responseSize; responseSize = recvCPAPResponse(rs232_descriptor, responseBuffer, sizeof(responseBuffer), expectedLength); if (responseSize < 0) { return responseSize; } int adjustedValue = (65535.0 / maxValue[0]) * responseBuffer[2]; if (debug) printf("cpap:%d -> da:%d\\n", responseBuffer[2], adjustedValue); writeDAC(0, adjustedValue); return 0; } int main(int argc, char **argv) { if (access("/etc/debug", F_OK) == 0) debug = 1; int rs232_descriptor; char cmdBuffer[2] = {0x93, 0xCB}; int cmdSize = sizeof(cmdBuffer); int checkedXor; initDAC(); int deviceDesc = openCPAPDevice(); checkedXor = getCheckedXor(cmdBuffer, cmdSize); pthread_create(&threadTickGenerator, NULL, functionTickGenerator, NULL); while (1) { int err = cpap2psg(deviceDesc, cmdBuffer, cmdSize, checkedXor); if (err == -2) { deviceDesc = openCPAPDevice(); } sleep(1); for (int channel = 0; channel < MAX_CHANNEL; channel++) { if (threadFIFO2DA[channel] == 0) { pthread_create(&threadFIFO2DA[channel], NULL, functionFIFO2DA, (void *)(intptr_t)channel); } } } rs232_close(rs232_descriptor); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <semaphore.h> #include <time.h> #define THREAD_NUM 4 #define BUFFER_SIZE 256 typedef struct Task{ int a, b; }Task; Task taskQueue[BUFFER_SIZE]; int taskCount = 0; pthread_mutex_t mutex; pthread_cond_t condFull; pthread_cond_t condEmpty; void executeTask(Task* task, int id){ int result = task->a + task->b; printf("(Thread %d) Sum of %d and %d is %d\\n", id, task->a, task->b, result); } Task getTask(){ while (taskCount == 0){ pthread_cond_wait(&condEmpty, &mutex); } Task task = taskQueue[0]; int i; for (i = 0; i < taskCount - 1; i++){ taskQueue[i] = taskQueue[i+1]; } taskCount--; pthread_cond_signal(&condFull); return task; } void submitTask(Task task){ while (taskCount == BUFFER_SIZE){ pthread_cond_wait(&condFull, &mutex); } taskQueue[taskCount] = task; taskCount++; pthread_cond_signal(&condEmpty); } void *startThread(void* args); /*--------------------------------------------------------------------*/ int main(int argc, char* argv[]) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&condEmpty, NULL); pthread_cond_init(&condFull, NULL); pthread_t thread[THREAD_NUM]; long i; for (i = 0; i < THREAD_NUM; i++){ if (pthread_create(&thread[i], NULL, &startThread, (void*) i) != 0) { perror("Failed to create the thread"); } } srand(time(NULL)); for (i = 0; i < 500; i++){ Task t = { .a = rand() % 100, .b = rand() % 100 }; submitTask(t); } for (i = 0; i < THREAD_NUM; i++){ if (pthread_join(thread[i], NULL) != 0) { perror("Failed to join the thread"); } } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condEmpty); pthread_cond_destroy(&condFull); return 0; } /* main */ /*-------------------------------------------------------------------*/ void *startThread(void* args) { long id = (long) args; while (1) { Task task = getTask(); if (task.a == -1 && task.b == -1) { // Check for termination task printf("(Thread %ld) Terminating\\n", id); break; // Exit the loop } executeTask(&task, id); sleep(rand() % 5); } return NULL; }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <fcntl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <time.h> #define MAX_CHANNEL 5 #define LISTEN_BACKLOG 50 pthread_t thread[MAX_CHANNEL]; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; int clients[100]; char msg[100]; int max_clients = 100; int setnonblocking(int sock) { int opts = fcntl(sock, F_GETFL); if (opts < 0) { perror("fcntl(F_GETFL)"); return -1; } opts = opts | O_NONBLOCK; if (fcntl(sock, F_SETFL, opts) < 0) { perror("fcntl(F_SETFL)"); return -1; } return 1; } void* thread_connect() { int listenfd, connfd; listenfd = create_conn(10023); if (listenfd <= 0) { perror("create_conn"); exit(EXIT_FAILURE); } memset(clients, 0, sizeof(clients)); int epollfd = epoll_create(101); if (epollfd == -1) { perror("epoll_create"); exit(EXIT_FAILURE); } struct epoll_event ev, events[150]; ev.events = EPOLLIN; ev.data.fd = listenfd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &ev) == -1) { perror("epoll_ctl"); exit(EXIT_FAILURE); } for (;;) { int nfds = epoll_wait(epollfd, events, 150, -1); if (nfds == -1) { perror("epoll_wait"); exit(EXIT_FAILURE); } for (int i = 0; i < nfds; ++i) { int currfd = events[i].data.fd; if (currfd == listenfd) { int conn_sock = accept(listenfd, NULL, NULL); if (conn_sock == -1) { perror("accept"); continue; } int saved = 0; pthread_mutex_lock(&mut); for (int n = 0; n < max_clients; ++n) { if (clients[n] == 0) { clients[n] = conn_sock; saved = 1; break; } } pthread_mutex_unlock(&mut); if (saved == 0) { close(conn_sock); continue; } setnonblocking(conn_sock); ev.events = EPOLLIN | EPOLLET; ev.data.fd = conn_sock; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock, &ev) == -1) { perror("epoll_ctl"); exit(EXIT_FAILURE); } } else { char str[50]; int n = read(currfd, str, sizeof(str)); if (n <= 0) { pthread_mutex_lock(&mut); for (int j = 0; j < max_clients; ++j) { if (clients[j] == currfd) { clients[j] = 0; break; } } pthread_mutex_unlock(&mut); close(currfd); epoll_ctl(epollfd, EPOLL_CTL_DEL, currfd, NULL); } else { pthread_mutex_lock(&mut); strncpy(msg, str, n); pthread_mutex_unlock(&mut); } } } } } void* thread_proc() { while (1) { pthread_mutex_lock(&mut); int len = strlen(msg); if (len > 0) { for (int i = 0; i < max_clients; ++i) { if (clients[i] > 0) { write(clients[i], msg, len); } } memset(msg, 0, sizeof(msg)); } pthread_mutex_unlock(&mut); usleep(200); } } void* thread_route() { while (1) { pthread_mutex_lock(&mut); if (strlen(msg) > 0) { printf("msg: %s\\n", msg); } pthread_mutex_unlock(&mut); usleep(200000); } } int thread_create() { if (pthread_create(&thread[0], NULL, thread_connect, NULL) != 0) { perror("pthread_create"); return -1; } if (pthread_create(&thread[1], NULL, thread_proc, NULL) != 0) { perror("pthread_create"); return -1; } if (pthread_create(&thread[3], NULL, thread_route, NULL) != 0) { perror("pthread_create"); return -1; } return 0; } void thread_wait() { for (int i = 0; i < 3; ++i) { if (thread[i] != 0) { pthread_join(thread[i], NULL); printf("Thread %d ended\\n", i); } } } int create_conn(int port) { struct sockaddr_in servaddr; int listenfd; listenfd = socket(AF_INET, SOCK_STREAM, 0); if (listenfd < 0) { perror("socket"); return -1; } memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) { perror("bind"); return -1; } if (listen(listenfd, LISTEN_BACKLOG) == -1) { perror("listen"); return -1; } return listenfd; } int main(int argc, char** argv) { pthread_mutex_init(&mut, NULL); if (thread_create() != 0) { printf("Error creating threads\\n"); exit(EXIT_FAILURE); } thread_wait(); printf("Server main thread ended\\n"); return 0; }
0
1
#include <pthread.h> #include <unistd.h> #include <stdio.h> #include<math.h> int tickets = 20; pthread_mutex_t mutex; void *mythread1(void) { while (1) { if (tickets > 0) { usleep(1000); printf("ticketse1 sells ticket:%d\\n", tickets--); } else { break; } sleep(1); } return (void *)0; } void *mythread2(void) { while (1) { if (tickets > 0) { usleep(1000); printf("ticketse2 sells ticket:%d\\n", tickets--); } else { break; } sleep(1); } return (void *)0; } int main(int argc, const char *argv[]) { //int i = 0; int ret = 0; pthread_t id1, id2; ret = pthread_create(&id1, NULL, (void *)mythread1, NULL); if (ret) { printf("Create pthread error!\\n"); return 1; } ret = pthread_create(&id2, NULL, (void *)mythread2, NULL); if (ret) { printf("Create pthread error!\\n"); return 1; } pthread_join(id1, NULL); pthread_join(id2, NULL); return 0; }
1
1
#include <stdio.h> #include <pthread.h> #include <unistd.h> pthread_mutex_t m; void *func(void *p) { int *source = (int *)p; for (int i = 0; i < 10; i++) { pthread_mutex_lock(&m); int t = *(source + i); printf("t = %d\\n", t); pthread_mutex_unlock(&m); int j; for (j = i; j > 0 && t < source[j - 1]; j--) { source[j] = source[j - 1]; } source[j] = t; usleep(100); } return NULL; } int main() { int a[10]; pthread_t id; pthread_mutex_init(&m, NULL); pthread_mutex_lock(&m); int success = pthread_create(&id, NULL, func, a); if (success != 0) { perror("pthread_create"); return -1; } for (int i = 0; i < 10; i++) { printf("请输入第%d个数据: ", i + 1); scanf("%d", &a[i]); pthread_mutex_unlock(&m); usleep(100); pthread_mutex_lock(&m); } pthread_mutex_unlock(&m); pthread_join(id, NULL); printf("Sorted array: "); for (int i = 0; i < 10; i++) { printf("%d ", a[i]); } printf("\\n"); pthread_mutex_destroy(&m); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> enum { QUEUE_BUF_SIZE = 100000, }; typedef struct vector_s { int size; int tail; void **buf; } vector_t; typedef struct queue_cycl_s { int front; int tail; int max_size; void **cyclic_buf; } queue_cycl_t; vector_t *vector_init(int size) { vector_t *tmp = (vector_t *)calloc(1, sizeof(vector_t)); if (tmp == NULL) { fprintf(stderr, "vector_init error\\n"); exit(1); } tmp->buf = (void **)calloc(size, sizeof(void *)); if (tmp->buf == NULL) { fprintf(stderr, "vector_init error\\n"); free(tmp); exit(1); } tmp->size = size; tmp->tail = 0; return tmp; } int vector_push_back(vector_t *v, void *data) { if (v->tail == v->size) return 0; v->buf[v->tail++] = data; return 1; } void *vector_pop_back(vector_t *v) { return (v->tail == 0) ? NULL : v->buf[--(v->tail)]; } void vector_delete(vector_t *v) { free(v->buf); free(v); } queue_cycl_t *queue_init() { queue_cycl_t *tmp = (queue_cycl_t *)calloc(1, sizeof(queue_cycl_t)); if (tmp == NULL) { fprintf(stderr, "queue_init error\\n"); exit(1); } tmp->max_size = QUEUE_BUF_SIZE + 1; tmp->cyclic_buf = (void **)calloc(tmp->max_size, sizeof(void *)); if (tmp->cyclic_buf == NULL) { fprintf(stderr, "queue_init error\\n"); free(tmp); exit(1); } return tmp; } int queue_size(queue_cycl_t *q) { return (q->tail >= q->front) ? (q->tail - q->front) : (q->max_size - q->front + q->tail); } int queue_is_full(queue_cycl_t *q) { return ((q->tail + 1) % q->max_size == q->front); } int queue_is_empty(queue_cycl_t *q) { return (q->front == q->tail); } int queue_enqueue(queue_cycl_t *q, void *data) { if (queue_is_full(q)) return 0; q->cyclic_buf[q->tail] = data; q->tail = (q->tail + 1) % q->max_size; return 1; } void *queue_dequeue(queue_cycl_t *q) { if (queue_is_empty(q)) return NULL; void *tmp = q->cyclic_buf[q->front]; q->cyclic_buf[q->front] = NULL; q->front = (q->front + 1) % q->max_size; return tmp; } vector_t *queue_dequeueall(queue_cycl_t *q) { int s = queue_size(q); vector_t *tmp = vector_init(s); void *data = NULL; while ((data = queue_dequeue(q)) != NULL) { if (!vector_push_back(tmp, data)) { queue_enqueue(q, data); fprintf(stderr, "queue_dequeueall error\\n"); exit(1); } } return tmp; } void queue_delete(queue_cycl_t *q) { free(q->cyclic_buf); free(q); } typedef struct actor_s { pthread_t thread; pthread_mutex_t m; pthread_cond_t cond; queue_cycl_t *q; } actor_t; void actor_send_to(actor_t *a, void *msg) { queue_enqueue(a->q, msg); pthread_cond_signal(&a->cond); } void *actor_runner(void *arg) { actor_t *iam = (actor_t *)arg; int buf[50] = {0}; while (1) { while (queue_is_empty(iam->q)) { pthread_cond_wait(&iam->cond, &iam->m); } vector_t *v = queue_dequeueall(iam->q); int *data = NULL, exit_flag = 0; while ((data = vector_pop_back(v)) != NULL) { if (*data == -1) { exit_flag = 1; } else { buf[*data]++; } free(data); } vector_delete(v); if (exit_flag) break; } for (int i = 0; i < 50; i++) { if (buf[i] != n_senders) { fprintf(stderr, "ERROR!!!!!!!!\\n"); } } return NULL; } actor_t *actor_init() { actor_t *tmp = (actor_t *)calloc(1, sizeof(actor_t)); if (tmp == NULL) { fprintf(stderr, "actor_init error\\n"); exit(1); } pthread_mutex_init(&tmp->m, NULL); pthread_cond_init(&tmp->cond, NULL); tmp->q = queue_init(); pthread_create(&tmp->thread, NULL, actor_runner, tmp); return tmp; } void actor_finalize(actor_t *a) { pthread_join(a->thread, NULL); queue_delete(a->q); pthread_mutex_destroy(&a->m); pthread_cond_destroy(&a->cond); free(a); } void *sender(void *arg) { actor_t *receiver = (actor_t *)arg; int *msg = NULL; for (int i = 0; i < 50; i++) { msg = (int *)calloc(1, sizeof(int)); if (msg == NULL) { fprintf(stderr, "Memory allocation failed\\n"); exit(1); } *msg = i; actor_send_to(receiver, msg); } return NULL; } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "Usage: %s <number_of_senders>\\n", argv[0]); exit(1); } n_senders = atoi(argv[1]); pthread_t *senders_id = (pthread_t *)calloc(n_senders, sizeof(pthread_t)); if (senders_id == NULL) { fprintf(stderr, "Memory allocation failed\\n"); exit(1); } actor_t *actor = actor_init(); for (int i = 0; i < n_senders; i++) { pthread_create(&senders_id[i], NULL, sender, actor); } for (int i = 0; i < n_senders; i++) { pthread_join(senders_id[i], NULL); } int *msg_ext = (int *)calloc(1, sizeof(int)); *msg_ext = -1; actor_send_to(actor, msg_ext); actor_finalize(actor); free(senders_id); return 0; }
1
1
#include <stdio.h> #include <pthread.h> #include <semaphore.h> #include <string.h> #define DATA_MAX 5 #define PRO_INIT_VAL (DATA_MAX / 2) #define CON_INIT_VAL (DATA_MAX - PRO_INIT_VAL) static int data; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static pthread_mutex_t mutex; static sem_t sem_pro; static sem_t sem_con; static void *pro_handler(void *arg) { ssize_t i = 100; for (; i > 0; --i) { pthread_mutex_lock(&mutex); ++data; printf("producter: data = %d\\n", data); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); usleep(100000); } } static void *con_handler(void *arg) { ssize_t i = 100; for (; i > 0; --i) { pthread_mutex_lock(&mutex); while (data == 0) { pthread_cond_wait(&cond, &mutex); } while (data > 0) { --data; printf("consumer: data = %d\\n", data); } pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_mutex_init(&mutex, NULL); sem_init(&sem_pro, 0, PRO_INIT_VAL); sem_init(&sem_con, 0, CON_INIT_VAL); data = CON_INIT_VAL; pthread_t pro_id, con_id; int pro_ret = 0; if (pro_ret = pthread_create(&pro_id, NULL, pro_handler, NULL)) { fprintf(stderr, "pthread_create producter: %s", strerror(pro_ret)); goto err_create_producter; } int con_ret = 0; if (con_ret = pthread_create(&con_id, NULL, con_handler, NULL)) { fprintf(stderr, "pthread_create consumer: %s", strerror(con_ret)); goto err_create_consumer; } #if 0 sleep(3); if (pthread_cancel(con_id)) { fprintf(stderr, "error cancel\\n"); } #endif pthread_join(pro_id, NULL); pthread_join(con_id, NULL); sem_destroy(&sem_con); sem_destroy(&sem_pro); pthread_mutex_destroy(&mutex); return 0; err_create_consumer: pthread_join(pro_id, NULL); err_create_producter: sem_destroy(&sem_con); sem_destroy(&sem_pro); pthread_mutex_destroy(&mutex); return -1; }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <linux/netlink.h> #include <errno.h> enum mode { MODE_MB, MODE_MEMBARRIER, MODE_COMPILER_BARRIER, MODE_MEMBARRIER_MISSING_REGISTER, }; enum mode mode; struct map_test { int x, y; int ref; int r2, r4; int r2_ready, r4_ready; int killed; pthread_mutex_t lock; }; static void check_parent_regs(struct map_test *map_test, int r2) { if (map_test->r4_ready) { if (r2 == 0 && map_test->r4 == 0) { fprintf(stderr, "Error detected!\\n"); CMM_STORE_SHARED(map_test->killed, 1); abort(); } map_test->r4_ready = 0; map_test->x = 0; map_test->y = 0; } else { map_test->r2 = r2; map_test->r2_ready = 1; } } static void check_child_regs(struct map_test *map_test, int r4) { if (map_test->r2_ready) { if (r4 == 0 && map_test->r2 == 0) { fprintf(stderr, "Error detected!\\n"); CMM_STORE_SHARED(map_test->killed, 1); abort(); } map_test->r2_ready = 0; map_test->x = 0; map_test->y = 0; } else { map_test->r4 = r4; map_test->r4_ready = 1; } } static void loop_parent(struct map_test *map_test) { int i, r2; for (i = 0; i < 100000000; i++) { uatomic_inc(&map_test->ref); while (uatomic_read(&map_test->ref) < 2 * (i + 1)) { if (map_test->killed) abort(); caa_cpu_relax(); } CMM_STORE_SHARED(map_test->x, 1); switch (mode) { case MODE_MB: cmm_smp_mb(); break; case MODE_MEMBARRIER: case MODE_MEMBARRIER_MISSING_REGISTER: if (-ENOSYS) { perror("membarrier"); CMM_STORE_SHARED(map_test->killed, 1); abort(); } break; case MODE_COMPILER_BARRIER: cmm_barrier(); break; } r2 = CMM_LOAD_SHARED(map_test->y); check_parent_regs(map_test, r2); } } static void loop_child(struct map_test *map_test) { int i, r4; switch (mode) { case MODE_MEMBARRIER: if (-ENOSYS) { perror("membarrier"); CMM_STORE_SHARED(map_test->killed, 1); abort(); } break; default: break; } for (i = 0; i < 100000000; i++) { uatomic_inc(&map_test->ref); while (uatomic_read(&map_test->ref) < 2 * (i + 1)) { if (map_test->killed) abort(); caa_cpu_relax(); } CMM_STORE_SHARED(map_test->y, 1); switch (mode) { case MODE_MB: cmm_smp_mb(); break; case MODE_MEMBARRIER: case MODE_MEMBARRIER_MISSING_REGISTER: cmm_barrier(); break; case MODE_COMPILER_BARRIER: cmm_barrier(); break; } r4 = CMM_LOAD_SHARED(map_test->x); check_child_regs(map_test, r4); } } void print_arg_error(void) { fprintf(stderr, "Please specify test mode: <m>: paired mb, <s>: sys-membarrier, <c>: compiler barrier (error), <n>: sys-membarrier with missing registration (error).\\n"); } int main(int argc, char **argv) { char namebuf[PATH_MAX]; pid_t pid; int fd, ret = 0; void *buf; struct map_test *map_test; pthread_mutexattr_t attr; if (argc < 2) { print_arg_error(); return -1; } if (!strcmp(argv[1], "-m")) { mode = MODE_MB; } else if (!strcmp(argv[1], "-s")) { mode = MODE_MEMBARRIER; } else if (!strcmp(argv[1], "-c")) { mode = MODE_COMPILER_BARRIER; } else if (!strcmp(argv[1], "-n")) { mode = MODE_MEMBARRIER_MISSING_REGISTER; } else { print_arg_error(); return -1; } buf = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); if (buf == MAP_FAILED) { perror("mmap"); ret = -1; goto end; } map_test = (struct map_test *)buf; pthread_mutexattr_init(&attr); pthread_mutexattr_setpshared(&attr, 1); pthread_mutex_init(&map_test->lock, &attr); pid = fork(); if (pid < 0) { perror("fork"); ret = -1; goto unmap; } if (!pid) { loop_child(map_test); return 0; } loop_parent(map_test); pid = waitpid(pid, 0, 0); if (pid < 0) { perror("waitpid"); ret = -1; } unmap: pthread_mutex_destroy(&map_test->lock); pthread_mutexattr_destroy(&attr); if (munmap(buf, 4096)) { perror("munmap"); ret = -1; } end: return ret; }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> void *thread_function(void *arg); pthread_mutex_t work_mutex; pthread_cond_t work_cond; #define WORK_SIZE 1024 char work_area[WORK_SIZE]; int time_to_exit = 0; int main() { int res; pthread_t a_thread; void *thread_result; res = pthread_mutex_init(&work_mutex, NULL); if (res != 0) { perror("Mutex initialization failed"); exit(EXIT_FAILURE); } res = pthread_cond_init(&work_cond, NULL); if (res != 0) { perror("Condition variable initialization failed"); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread creation failed"); exit(EXIT_FAILURE); } pthread_mutex_lock(&work_mutex); printf("Input some text, enter 'end' to finish:\\n"); while (!time_to_exit) { fgets(work_area, WORK_SIZE, stdin); pthread_cond_signal(&work_cond); pthread_mutex_unlock(&work_mutex); pthread_mutex_lock(&work_mutex); while (work_area[0] != '\\0') { pthread_cond_wait(&work_cond, &work_mutex); } } pthread_mutex_unlock(&work_mutex); printf("Waiting for thread to finish...\\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("pthread_join failed"); exit(EXIT_FAILURE); } printf("Thread joined\\n"); pthread_mutex_destroy(&work_mutex); pthread_cond_destroy(&work_cond); exit(EXIT_SUCCESS); } void *thread_function(void *arg) { sleep(1); pthread_mutex_lock(&work_mutex); while (strncmp("end", work_area, 3) != 0) { printf("You input %d characters\\n", (int)(strlen(work_area) - 1)); work_area[0] = '\\0'; pthread_cond_signal(&work_cond); pthread_cond_wait(&work_cond, &work_mutex); } time_to_exit = 1; pthread_cond_signal(&work_cond); pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
0
1
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define NUM_THREADS 4 #define TOTAL_COUNT 10 #define COUNT_LIMIT 12 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 < TOTAL_COUNT; i++) { count++; if (count == COUNT_LIMIT) { 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); /* Do some work so threads can alternate on mutex lock */ sleep(1); } pthread_exit(NULL); } void *watch_count(void *t) { long my_id = (long)t; printf("watch_count(): thread %ld\\n", my_id); while (count < COUNT_LIMIT) { 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_exit(NULL); } int main(int argc, char *argv[]) { int i; long t1=1, t2=2, t3=3, t4=4; pthread_t threads[NUM_THREADS]; pthread_attr_t attr; /* Initialize mutex and condition variable objects */ pthread_mutex_init(&count_mutex, NULL); pthread_cond_init(&count_threshold_cv, NULL); /* For portability, explicitly create threads in a joinable state */ 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); pthread_create(&threads[3], &attr, inc_count, (void *)t4); /* Wait for all threads to complete */ for (i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf ("main(): waited and joined with %d threads. Final value of count = %d. Done.\\n", NUM_THREADS, count); /* Clean up and exit */ pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(NULL); }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <poll.h> #include <errno.h> static struct dlm_lksb lksb; static int use_threads = 0; static int quiet = 0; static pthread_cond_t cond; static pthread_mutex_t mutex; static int ast_called = 0; static int modetonum(char *modestr) { int mode = LKM_EXMODE; if (strncasecmp(modestr, "NL", 2) == 0) mode = LKM_NLMODE; if (strncasecmp(modestr, "CR", 2) == 0) mode = LKM_CRMODE; if (strncasecmp(modestr, "CW", 2) == 0) mode = LKM_CWMODE; if (strncasecmp(modestr, "PR", 2) == 0) mode = LKM_PRMODE; if (strncasecmp(modestr, "PW", 2) == 0) mode = LKM_PWMODE; if (strncasecmp(modestr, "EX", 2) == 0) mode = LKM_EXMODE; return mode; } static char *numtomode(int mode) { switch (mode) { case LKM_NLMODE: return "NL"; case LKM_CRMODE: return "CR"; case LKM_CWMODE: return "CW"; case LKM_PRMODE: return "PR"; case LKM_PWMODE: return "PW"; case LKM_EXMODE: return "EX"; default: return "??"; } } static void usage(char *prog, FILE *file) { fprintf(file, "Usage:\\n"); fprintf(file, "%s [mcnpquhV] <lockname>\\n", prog); fprintf(file, "\\n"); fprintf(file, " -V Show version of dlmtest\\n"); fprintf(file, " -h Show this help information\\n"); fprintf(file, " -m <mode> lock mode (default EX)\\n"); fprintf(file, " -c <mode> mode to convert to (default none)\\n"); fprintf(file, " -n don't block\\n"); fprintf(file, " -p Use pthreads\\n"); fprintf(file, " -u Don't unlock\\n"); fprintf(file, " -C Crash after lock\\n"); fprintf(file, " -q Quiet\\n"); fprintf(file, " -u Don't unlock explicitly\\n"); fprintf(file, "\\n"); } static void ast_routine(void *arg) { struct dlm_lksb *lksb = arg; if (!quiet) printf("ast called, status = %d, lkid=%x\\n", lksb->sb_status, lksb->sb_lkid); pthread_mutex_lock(&mutex); ast_called = 1; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } static void bast_routine(void *arg) { struct dlm_lksb *lksb = arg; if (!quiet) printf("\\nblocking ast called, status = %d, lkid=%x\\n", lksb->sb_status, lksb->sb_lkid); } static int poll_for_ast() { struct pollfd pfd; pfd.fd = dlm_get_fd(); pfd.events = POLLIN; pthread_mutex_lock(&mutex); while (!ast_called) { pthread_mutex_unlock(&mutex); if (poll(&pfd, 1, -1) < 0) { perror("poll"); return -1; } dlm_dispatch(pfd.fd); pthread_mutex_lock(&mutex); } ast_called = 0; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]) { char *resource = "LOCK-NAME"; int flags = 0; int delay = 0; int status; int mode = LKM_EXMODE; int convmode = -1; int do_unlock = 1; int do_crash = 0; signed char opt; opterr = 0; optind = 0; while ((opt = getopt(argc, argv, "?m:nqupc:d:CvV")) != EOF) { switch (opt) { case 'h': usage(argv[0], stdout); exit(0); case '?': usage(argv[0], stderr); exit(0); case 'm': mode = modetonum(optarg); break; case 'c': convmode = modetonum(optarg); break; case 'p': use_threads++; break; case 'n': flags |= LKF_NOQUEUE; break; case 'q': quiet = 1; break; case 'u': do_unlock = 0; break; case 'C': do_crash = 1; break; case 'd': delay = atoi(optarg); break; case 'V': printf("\\nasttest version 0.1\\n\\n"); exit(1); break; } } if (argv[optind]) resource = argv[optind]; if (!quiet) fprintf(stderr, "locking %s %s %s...", resource, numtomode(mode), (flags & LKF_NOQUEUE ? "(NOQUEUE)" : "")); fflush(stderr); if (use_threads) { pthread_cond_init(&cond, NULL); pthread_mutex_init(&mutex, NULL); pthread_mutex_lock(&mutex); dlm_pthread_init(); } status = dlm_lock(mode, &lksb, flags, resource, strlen(resource), 0, ast_routine, &lksb, bast_routine, 0); if (status == -1) { if (!quiet) fprintf(stderr, "\\n"); perror("lock"); return -1; } printf("(lkid=%x)", lksb.sb_lkid); if (do_crash) *(int *)0 = 0xdeadbeef; if (use_threads) { pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } else { poll_for_ast(); } if (delay) sleep(delay); if (!quiet) { fprintf(stderr, "unlocking %s...", resource); fflush(stderr); } if (do_unlock) { status = dlm_unlock(lksb.sb_lkid, 0, &lksb, &lksb); if (status == -1) { if (!quiet) fprintf(stderr, "\\n"); perror("unlock"); return -1; } if (use_threads) { pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } else { poll_for_ast(); } } return 0; }
0
1
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #define FILE_SIZE 671088640 // 800 MB #define BUFFER_SIZE 8 int thread_count = 0; int server_file_des, bytes_read; unsigned long long int block_size = 0, file_pos = 0, total_bytes = 0; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *receive_data(void *thread_id) { unsigned long long int start_pos, end_pos; unsigned long long int local_bytes = 0; char buffer[BUFFER_SIZE]; start_pos = file_pos; file_pos += block_size; end_pos = start_pos + block_size; struct sockaddr_in client_addr; socklen_t addr_len = sizeof(client_addr); while (start_pos < end_pos) { bytes_read = recvfrom(server_file_des, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_addr, &addr_len); if (bytes_read > 0) { local_bytes += bytes_read; start_pos += bytes_read; printf("Thread %ld transferred %llu bytes (total transferred: %llu bytes)\\n", (long)thread_id, local_bytes, start_pos); } else { perror("recvfrom"); break; } } total_bytes += local_bytes; pthread_exit(NULL); } int main() { int ch; printf("Perform Network Benchmarking on\\n1. 1 Thread\\n2. 2 Threads\\n3. 4 Threads\\n4. 8 Threads\\n"); scanf("%d", &ch); if (ch == 1 || ch == 2 || ch == 3 || ch == 4) { thread_count = (ch == 4) ? 8 : ch == 3 ? 4 : ch; printf("Number of Threads: %d\\n", thread_count); } else { printf("Invalid Choice\\nProgram terminated\\n"); return 0; } struct sockaddr_in address; int addrlen = sizeof(address); // Create UDP socket if ((server_file_des = socket(AF_INET, SOCK_DGRAM, 0)) == 0) { perror("Socket failed"); exit(EXIT_FAILURE); } // Setup server address address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(5000); // Bind the socket if (bind(server_file_des, (struct sockaddr *)&address, sizeof(address)) < 0) { perror("Bind failed"); exit(EXIT_FAILURE); } block_size = FILE_SIZE / thread_count; pthread_t threads[thread_count]; for (long j = 0; j < thread_count; j++) { pthread_create(&threads[j], NULL, receive_data, (void*)j); // Thread Creation } for (int k = 0; k < thread_count; k++) { pthread_join(threads[k], NULL); } printf("Total bytes transferred: %llu bytes\\n", total_bytes); close(server_file_des); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <pthread.h> #include <signal.h> #include <fcntl.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <arpa/inet.h> #include <linux/videodev2.h> int sockfd; int cameraFd; unsigned char *devconfp; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void sig_handler(int signo) { if (signo == SIGINT) { printf("SIGINT received, exiting!\\n"); close(sockfd); if (cameraFd >= 0) { close(cameraFd); } exit(0); } } unsigned char *temp; ssize_t length; void get_frame(int cameraFd) { struct v4l2_buffer buf; buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (ioctl(cameraFd, VIDIOC_DQBUF, &buf) == -1) { perror("VIDIOC_DQBUF"); exit(1); } length = buf.bytesused; temp = (unsigned char *)malloc(length); if (!temp) { perror("malloc"); exit(1); } memcpy(temp, (unsigned char *)buf.m.userptr, length); if (ioctl(cameraFd, VIDIOC_QBUF, &buf) == -1) { perror("VIDIOC_QBUF"); free(temp); exit(1); } } int stop = 0; void *frame_capture_thread(void *arg) { enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE; while (!stop) { get_frame(cameraFd); pthread_mutex_lock(&mutex); devconfp = (unsigned char*)malloc(length); if (!devconfp) { perror("malloc"); pthread_mutex_unlock(&mutex); exit(1); } memcpy(devconfp, temp, length); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); usleep(1500); free(temp); } if (ioctl(cameraFd, VIDIOC_STREAMOFF, &type) == -1) { perror("VIDIOC_STREAMOFF"); exit(1); } return NULL; } void send_msg(int fd) { ssize_t size; char readbuffer[1024] = {'\\0'}; char writebuffer[1024] = {'\\0'}; size = read(fd, readbuffer, sizeof(readbuffer) - 1); if (size < 0) { perror("read"); exit(1); } char respbuffer[] = "HTTP/1.0 200 OK\\r\\nConnection: close\\r\\n" "Server: Net-camera-1-0\\r\\nCache-Control: no-store, no-cache, must-revalidate\\r\\n" "Pragma: no-cache\\r\\nContent-Type: multipart/x-mixed-replace; boundary=www.briup.com\\r\\n\\r\\n"; if (write(fd, respbuffer, strlen(respbuffer)) != strlen(respbuffer)) { perror("write"); exit(1); } if (strstr(readbuffer, "snapshot")) { pthread_mutex_lock(&mutex); if (pthread_cond_wait(&cond, &mutex) != 0) { perror("pthread_cond_wait"); pthread_mutex_unlock(&mutex); exit(1); } sprintf(writebuffer, "--www.briup.com\\nContent-Type: image/jpeg\\nContent-Length: %zu\\n\\n", length); write(fd, writebuffer, strlen(writebuffer)); write(fd, devconfp, length); free(devconfp); pthread_mutex_unlock(&mutex); } else { while (1) { pthread_mutex_lock(&mutex); if (pthread_cond_wait(&cond, &mutex) != 0) { perror("pthread_cond_wait"); pthread_mutex_unlock(&mutex); exit(1); } sprintf(writebuffer, "--www.briup.com\\nContent-Type: image/jpeg\\nContent-Length: %zu\\n\\n", length); write(fd, writebuffer, strlen(writebuffer)); write(fd, devconfp, length); pthread_mutex_unlock(&mutex); sleep(1); } } } void *service_thread(void *arg) { int fd = (intptr_t)arg; send_msg(fd); close(fd); return NULL; } int main(int argc, char *argv[]) { if (argc != 3) { fprintf(stderr, "Usage: %s <device> <port>\\n", argv[0]); exit(1); } if (signal(SIGINT, sig_handler) == SIG_ERR) { perror("signal"); exit(1); } if ((cameraFd = open(argv[1], O_RDWR)) < 0) { perror("open"); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { perror("socket"); exit(1); } struct sockaddr_in saddr = {0}; saddr.sin_family = AF_INET; saddr.sin_port = htons(atoi(argv[2])); saddr.sin_addr.s_addr = INADDR_ANY; if (bind(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0) { perror("bind"); exit(1); } if (listen(sockfd, 10) < 0) { perror("listen"); exit(1); } pthread_t capture_thread; if (pthread_create(&capture_thread, NULL, frame_capture_thread, NULL) != 0) { perror("pthread_create"); exit(1); } while (1) { int client_fd = accept(sockfd, NULL, NULL); if (client_fd < 0) { perror("accept"); continue; } pthread_t service; if (pthread_create(&service, NULL, service_thread, (void *)(intptr_t)client_fd) != 0) { perror("pthread_create"); } } return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #define THREADS_NUM 3 typedef struct List { int value; struct List *next; } List; struct List *lista = NULL; pthread_mutex_t mutex; sem_t sem; void display(struct List *element) { printf("["); while (element) { printf("%d", element->value); if (element->next) { printf(", "); } element = element->next; } printf("]\\n"); } void push_f(int value) { struct List *newElement; struct List *cursor = lista; newElement = (struct List *)malloc(sizeof(struct List)); newElement->value = value; newElement->next = NULL; if (lista == NULL) { lista = newElement; } else { while (cursor->next) { cursor = cursor->next; } cursor->next = newElement; } } int pop_f() { if (lista == NULL) { return -1; } struct List *cursor = lista; struct List *prev = NULL; while (cursor->next) { prev = cursor; cursor = cursor->next; } int return_value = cursor->value; if (prev == NULL) { free(cursor); lista = NULL; } else { free(cursor); prev->next = NULL; } return return_value; } void *popThread(void *arg) { while (1) { sem_wait(&sem); int val = pop_f(); if (val != -1) { printf("Thread removed: %d\\n", val); } else { printf("Thread tried to remove from an empty list.\\n"); } display(lista); sleep(3); } return NULL; } void *pushThread(void *arg) { while (1) { int val = rand() % 100; push_f(val); printf("Thread inserted: %d\\n", val); display(lista); sem_post(&sem); sleep(1); } return NULL; } int main() { pthread_t tid[THREADS_NUM]; pthread_mutex_init(&mutex, NULL); sem_init(&sem, 0, 0); // Initialize semaphore with 0 srand(time(NULL)); pthread_create(&tid[0], NULL, pushThread, NULL); pthread_create(&tid[1], NULL, popThread, NULL); pthread_create(&tid[2], NULL, popThread, NULL); for (int i = 0; i < THREADS_NUM; i++) { pthread_join(tid[i], NULL); } sem_destroy(&sem); pthread_mutex_destroy(&mutex); while (lista) { pop_f(); } return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <netdb.h> #include <errno.h> struct dns_discovery_args { FILE *report; char *domain; int nthreads; }; struct dns_discovery_args dd_args; pthread_mutex_t mutexsum; void error(const char *msg) { perror(msg); exit(1); } FILE *ck_fopen(const char *path, const char *mode) { FILE *file = fopen(path, mode); if (file == 0) error("fopen"); return file; } void *ck_malloc(size_t size) { void *ptr = malloc(size); if (ptr == 0) error("malloc"); return ptr; } void chomp(char *str) { while (*str) { if (*str == '\\n' || *str == '\\r') { *str = 0; return; } str++; } } void banner() { printf(" ___ _ ______ ___ _ \\n" " / _ \\\\/ |/ / __/___/ _ \\\\(_)__ _______ _ _____ ______ __\\n" " / // / /\\\\ \\\\/___/ // / (_-</ __/ _ \\\\ |/ / -_) __/ // /\\n" "/____/_/|_/___/ /____/_/___/\\\\__/\\\\___/___/\\\\__/_/ \\\\_, / \\n" " /___/ \\n" "\\tby m0nad\\n\\n"); if (dd_args.report) { fprintf(dd_args.report, " ___ _ ______ ___ _ \\n" " / _ \\\\/ |/ / __/___/ _ \\\\(_)__ _______ _ _____ ______ __\\n" " / // / /\\\\ \\\\/___/ // / (_-</ __/ _ \\\\ |/ / -_) __/ // /\\n" "/____/_/|_/___/ /____/_/___/\\\\__/\\\\___/___/\\\\__/_/ \\\\_, / \\n" " /___/ \\n" "\\tby m0nad\\n\\n"); } } int usage() { printf("usage: ./dns-discovery <domain> [options]\\n" "options:\\n" "\\t-w <wordlist file> (default : %s)\\n" "\\t-t <threads> (default : 1)\\n" "\\t-r <report file>\\n", "wordlist.wl"); if (dd_args.report) { fprintf(dd_args.report, "usage: ./dns-discovery <domain> [options]\\n" "options:\\n" "\\t-w <wordlist file> (default : %s)\\n" "\\t-t <threads> (default : 1)\\n" "\\t-r <report file>\\n", "wordlist.wl"); } exit(0); } FILE *parse_args(int argc, char **argv) { FILE *wordlist = 0; char c, *ptr_wl = "wordlist.wl"; if (argc < 2) usage(); dd_args.domain = argv[1]; dd_args.nthreads = 1; printf("DOMAIN: %s\\n", dd_args.domain); if (dd_args.report) fprintf(dd_args.report, "DOMAIN: %s\\n", dd_args.domain); argc--; argv++; opterr = 0; while ((c = getopt(argc, argv, "r:w:t:")) != -1) { switch (c) { case 'w': ptr_wl = optarg; break; case 't': printf("THREADS: %s\\n", optarg); if (dd_args.report) fprintf(dd_args.report, "THREADS: %s\\n", optarg); dd_args.nthreads = atoi(optarg); break; case 'r': printf("REPORT: %s\\n", optarg); if (dd_args.report) fprintf(dd_args.report, "REPORT: %s\\n", optarg); dd_args.report = ck_fopen(optarg, "a"); break; case '?': if (optopt == 'r' || optopt == 'w' || optopt == 't') { fprintf(stderr, "Option -%c requires an argument.\\n", optopt); exit(1); } default: usage(); } } printf("WORDLIST: %s\\n", ptr_wl); if (dd_args.report) fprintf(dd_args.report, "WORDLIST: %s\\n", ptr_wl); wordlist = ck_fopen(ptr_wl, "r"); printf("\\n"); if (dd_args.report) fprintf(dd_args.report, "\\n"); return wordlist; } void resolve_lookup(const char *hostname) { int ipv = 0; char addr_str[256]; void *addr_ptr = 0; struct addrinfo *res, *ori_res, hints; memset(&hints, 0, sizeof hints); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags |= AI_CANONNAME; if (getaddrinfo(hostname, 0, &hints, &res) == 0) { pthread_mutex_lock(&mutexsum); printf("%s\\n", hostname); if (dd_args.report) fprintf(dd_args.report, "%s\\n", hostname); for (ori_res = res; res; res = res->ai_next) { switch (res->ai_family) { case AF_INET: ipv = 4; addr_ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; break; case AF_INET6: ipv = 6; addr_ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; break; } inet_ntop(res->ai_family, addr_ptr, addr_str, 256); printf("IPv%d address: %s\\n", ipv, addr_str); if (dd_args.report) fprintf(dd_args.report, "IPv%d address: %s\\n", ipv, addr_str); } printf("\\n"); if (dd_args.report) fprintf(dd_args.report, "\\n"); pthread_mutex_unlock(&mutexsum); freeaddrinfo(ori_res); } } void dns_discovery(FILE *file, const char *domain) { char line[256]; char hostname[512]; while (fgets(line, sizeof line, file) != 0) { chomp(line); snprintf(hostname, sizeof hostname, "%s.%s", line, domain); resolve_lookup(hostname); } } void *dns_discovery_thread(void *args) { FILE *wordlist = (FILE *) args; FILE *local_wordlist = tmpfile(); char line[256]; pthread_mutex_lock(&mutexsum); rewind(wordlist); while (fgets(line, sizeof(line), wordlist)) { fputs(line, local_wordlist); } pthread_mutex_unlock(&mutexsum); rewind(local_wordlist); dns_discovery(local_wordlist, dd_args.domain); fclose(local_wordlist); return 0; } int main(int argc, char **argv) { int i; pthread_t *threads; FILE *wordlist; banner(); wordlist = parse_args(argc, argv); threads = (pthread_t *) ck_malloc(dd_args.nthreads * sizeof(pthread_t)); pthread_mutex_init(&mutexsum, NULL); for (i = 0; i < dd_args.nthreads; i++) { if (pthread_create(&threads[i], 0, dns_discovery_thread, (void *) wordlist) != 0) error("pthread_create"); } for (i = 0; i < dd_args.nthreads; i++) { pthread_join(threads[i], 0); } if (dd_args.report) fclose(dd_args.report); free(threads); fclose(wordlist); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <math.h> int MAX_NUMBER = 65535; int max_m_operations = 200; int thread_count = 8; int initial_length = 10; int seed =18; double member_fraction = 0.80; double insert_fraction = 0.10; double delete_fraction = 0.10; struct node** head_node; pthread_mutex_t list_mutex; int max_member_number=0; int max_insert_number=0; int max_delete_number=0; struct node { int data; struct node *next; }; int Member(int value, struct node* head){ struct node* curr=head; while(curr!=0 && curr->data < value) curr = curr->next; if(curr == 0 || curr->data > value){ return 0; }else{ return 1; } } int Insert(int value, struct node** head){ struct node* curr = *head; struct node* prev = 0; struct node* temp; while(curr!=0 && curr-> data < value){ prev=curr; curr=curr->next; } if(curr==0 || curr->data > value){ temp = malloc(sizeof(struct node)); temp->data = value; temp->next = curr; if(prev==0){ *head=temp; } else{ prev->next=temp; } return 1; }else{ return 0; } } int Delete(int value, struct node** head){ struct node* curr= *head; struct node* prev= 0; while(curr!=0 && curr-> data < value){ prev=curr; curr=curr->next; } if(curr!=0 && curr->data == value){ if(prev == 0){ *head = curr->next; free(curr); }else{ prev->next = curr->next; free(curr); } return 1; }else{ return 0; } } void Populate_list(int seed, struct node** head, int n){ srand(seed); *head = malloc(sizeof(struct node)); (*head)->data = rand() % (MAX_NUMBER + 1); int result = 0; for(int i=0;i<n-1;i++){ result = Insert(rand() % (MAX_NUMBER + 1),head); if(!result){ i=i-1; } } } void* Thread_operation(void* rank){ int thread_max_member_number = max_member_number/thread_count; int thread_max_insert_number = max_insert_number/thread_count; int thread_max_delete_number = max_delete_number/thread_count; int thread_member_number=0; int thread_insert_number=0; int thread_delete_number=0; srand(seed); int operation; int random_number; while(thread_member_number<thread_max_member_number || thread_insert_number<thread_max_insert_number || thread_delete_number<thread_max_delete_number){ random_number = rand() % (MAX_NUMBER+1); operation = random_number % 3; if(operation==0 && thread_member_number < thread_max_member_number){ thread_member_number++; Member(random_number, *head_node); } else if(operation==1 && thread_insert_number < thread_max_insert_number){ thread_insert_number++; Insert(random_number, head_node); } else if(operation==2 && thread_delete_number < thread_max_delete_number){ thread_delete_number++; Delete(random_number, head_node); } } return 0; } int main() { head_node = malloc(sizeof(struct node*)); pthread_mutex_init(&list_mutex, 0); int iterations=0; initial_length=1000; max_m_operations=10000; member_fraction=0.99; insert_fraction=0.005; delete_fraction=0.005; thread_count=4; printf("Enter number of samples: "); scanf("%d",&iterations); printf("Enter n: "); scanf("%d",&initial_length); printf("Enter m: "); scanf("%d",&max_m_operations); printf("Enter member_fraction: "); scanf("%lf",&member_fraction); printf("Enter insert_fraction: "); scanf("%lf",&insert_fraction); printf("Enter delete_fraction: "); scanf("%lf",&delete_fraction); printf("Enter thread count: "); scanf("%d",&thread_count); double timespent[iterations]; for(seed=10; seed<11+iterations; seed++){ Populate_list(seed, head_node, initial_length); max_member_number = (int)max_m_operations*member_fraction; max_insert_number = (int)max_m_operations*insert_fraction; max_delete_number = (int)max_m_operations*delete_fraction; clock_t begin = clock(); pthread_t threads[thread_count]; long thread; for(thread=0;thread<thread_count;thread++){ pthread_create(&threads[thread], 0, Thread_operation, (void*) thread); } for(thread=0; thread<thread_count;thread++){ pthread_join(threads[thread],0); } clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; timespent[seed-10]=time_spent; printf("Percentage Complete: %.0f %%",((seed-10)*100)/(float)iterations); printf("\\r"); } double sum=0, sum_var=0, average=0, std_deviation=0, variance=0; for (int i = 0; i < iterations; i++) { sum += timespent[i]; } average = sum / (float)iterations; for (int i = 0; i < iterations; i++) { sum_var = sum_var + pow((timespent[i] - average), 2); } variance = sum_var / (float)(iterations-1); std_deviation = sqrt(variance); printf("Average: %f, std_deviation: %f\\n",average,std_deviation); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <fcntl.h> #include <string.h> #include <assert.h> #include <signal.h> #include <stdbool.h> #include <linux/input.h> #include <mpd/client.h> #include <stdarg.h> #define MAX_CHANNEL 6 enum log_level { DEBUG = 0, INFO = 1, ERROR = 2 }; pthread_t tid[1]; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; int g_isRunning = 1; int g_logLevel = DEBUG; struct mpd_connection *conn; void INT_handler(int sig) { g_isRunning = 0; } void log_message(int level, const char *format, ...) { if (level >= g_logLevel) { va_list arglist; va_start(arglist, format); vfprintf(stderr, format, arglist); va_end(arglist); fprintf(stderr, "\\n"); } } static int handle_error(struct mpd_connection *c) { int err = mpd_connection_get_error(c); assert(err != MPD_ERROR_SUCCESS); log_message(DEBUG, "%d --> %s", err, mpd_connection_get_error_message(c)); mpd_connection_free(c); return 1; } bool run_play_pos(struct mpd_connection *c, int pos) { if (!mpd_run_play_pos(c, pos)) { if (mpd_connection_get_error(c) != MPD_ERROR_SERVER) return handle_error(c); } return true; } void finish_command(struct mpd_connection *conn) { if (!mpd_response_finish(conn)) { handle_error(conn); } } struct mpd_status* get_status(struct mpd_connection *conn) { struct mpd_status *ret = mpd_run_status(conn); if (ret == NULL) { handle_error(conn); } return ret; } void* monitor(void *arg) { pthread_t id = pthread_self(); unsigned long cnt = 0; while (g_isRunning) { log_message(INFO, "%lu: thread keepalive %10ld", (unsigned long)id, cnt); pthread_mutex_lock(&mutex1); if (!mpd_run_change_volume(conn, 0)) { if (!mpd_connection_clear_error(conn)) { handle_error(conn); } } cnt++; pthread_mutex_unlock(&mutex1); usleep(5000000); } log_message(INFO, "%lu: leaving thread", (unsigned long)id); pthread_exit(NULL); } int main() { char devname[] = "/dev/input/event0"; int device; struct input_event ev; struct mpd_status* mpd_state_ptr; int rc; pthread_attr_t attr; void *status; signal(SIGINT, INT_handler); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); conn = mpd_connection_new(NULL, 0, 30000); if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS) { return handle_error(conn); } rc = pthread_create(&tid[0], &attr, &monitor, NULL); pthread_attr_destroy(&attr); device = open(devname, O_RDONLY); if (device < 0) { perror("Error opening device"); mpd_connection_free(conn); exit(EXIT_FAILURE); } while (g_isRunning) { if (read(device, &ev, sizeof(ev)) <= 0) { perror("Error reading device"); continue; } if (ev.type != EV_KEY) continue; pthread_mutex_lock(&mutex1); switch (ev.code) { case KEY_POWER: log_message(INFO, ">>> POWER"); break; case KEY_MUTE: if (ev.value == 1) { if (!mpd_run_change_volume(conn, -1)) { if (!mpd_connection_clear_error(conn)) handle_error(conn); } log_message(INFO, ">>> MUTE"); } break; case KEY_STOP: if (ev.value == 1) { mpd_state_ptr = get_status(conn); if (mpd_status_get_state(mpd_state_ptr) == MPD_STATE_PLAY || mpd_status_get_state(mpd_state_ptr) == MPD_STATE_PAUSE) { if (!mpd_run_stop(conn)) handle_error(conn); log_message(INFO, ">>> STOP"); } mpd_status_free(mpd_state_ptr); } break; case KEY_PLAYPAUSE: if (ev.value == 1) { mpd_state_ptr = get_status(conn); switch (mpd_status_get_state(mpd_state_ptr)) { case MPD_STATE_PLAY: mpd_send_pause(conn, true); finish_command(conn); break; case MPD_STATE_PAUSE: case MPD_STATE_STOP: if (!mpd_run_play(conn)) handle_error(conn); break; default: break; } mpd_status_free(mpd_state_ptr); log_message(INFO, ">>> PLAYPAUSE"); } break; default: continue; } log_message(DEBUG, "\\tKey: %i/0x%x Type: %i State: %i", ev.code, ev.code, ev.type, ev.value); pthread_mutex_unlock(&mutex1); } close(device); pthread_mutex_destroy(&mutex1); rc = pthread_join(tid[0], &status); log_message(DEBUG, "%lu: thread join (rc=%i)", (unsigned long)tid[0], rc); mpd_connection_free(conn); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <stdint.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> static int fd; static int disconnect; static char *ip; static char *port; static uint32_t cuid; static pthread_t hthid; static pthread_t rthid; static pthread_mutex_t fdlock; typedef struct _threc { pthread_t thid; pthread_mutex_t mutex; pthread_cond_t cond; uint8_t *buff; uint32_t buffsize; uint8_t sent; uint8_t status; uint8_t release; uint32_t size; uint32_t cmd; uint32_t packetid; struct _threc *next; } threc; static threc *threc_head = 0; void fs_buffer_init(threc *rec,uint32_t size) { if (size > 10000) { rec->buff = realloc(rec->buff,size); rec->buffsize = size; } else if (rec->buffsize > 10000) { rec->buff = realloc(rec->buff,10000); rec->buffsize = 10000; } else { fprintf(stderr, "null\\n"); } } threc* fs_get_threc_by_id(uint32_t packetid) { threc *rec; for (rec = threc_head ; rec ; rec=rec->next) { if (rec->packetid==packetid) { return rec; } } return 0; } void get_chunkid(uint8_t *data) { uint64_t chunkid = 0; int8_t status = 0; uint8_t *ptr, hdr[16]; if (DEBUG) { fprintf(stderr, "----get create chunk info ---\\n"); } GET64BIT(chunkid, data); status = create_file(chunkid); if (status != 0) { fprintf(stderr, "create chunk file failed\\n"); } if (disconnect == 0 && fd >= 0) { printf("--------------\\n"); ptr = hdr; PUT32BIT(DATTOSER_CREAT_CHUNK, ptr); PUT32BIT(8, ptr); PUT32BIT(0, ptr); PUT32BIT(status, ptr); if (tcptowrite(fd, hdr, 16, 1000) != 16) { disconnect = 1; } } } void analyze_ser_packet(uint32_t type, uint32_t size) { uint8_t *data = 0; data = malloc(size); if (tcptoread(fd, data, size, 1000) != (int32_t)(size)) { fprintf(stderr,"ser: tcp recv error(3)\\n"); disconnect=1; free(data); return; } switch (type) { case ANTOAN_NOP: break; case SERTODAT_DISK_INFO: break; case SERTODAT_CREAT_CHUNK: get_chunkid(data); break; default: break; } free(data); } int8_t analyze_ser_cmd(uint32_t type) { switch (type) { case ANTOAN_NOP: case SERTODAT_DISK_INFO: case SERTODAT_CREAT_CHUNK: return 0; default: break; } return 1; } void connect_ser() { fd = tcpsocket(); if (tcpconnect(fd, ip, port) < 0) { fprintf(stderr, "can't connect to ser(ip:%s,port:%s)\\n", ip, port); tcpclose(fd); fd = -1; return; } else { fprintf(stderr, "connect to ser(ip:%s,port:%s)\\n", ip, port); disconnect = 0; } } void *heartbeat_thread(void *arg) { uint8_t *ptr, hdr[28]; uint64_t totalspace; uint64_t freespace; totalspace = 201; freespace = 102; while (1) { if (disconnect == 0 && fd >= 0) { ptr = hdr; PUT32BIT(DATTOSER_DISK_INFO, ptr); PUT32BIT(20, ptr); PUT32BIT(0, ptr); PUT64BIT(totalspace, ptr); PUT64BIT(freespace, ptr); printf("heart beat\\n"); if (tcptowrite(fd, hdr, 28, 1000) != 28) { disconnect = 1; } } sleep(5); } } void *receive_thread(void *arg) { uint8_t *ptr = 0; uint8_t hdr[12] = {0}; uint32_t cmd = 0; uint32_t size = 0; uint32_t packetid = 0; int r = 0; threc *rec = 0; for (;;) { pthread_mutex_lock(&fdlock); if (fd == -1 && disconnect) { connect_ser(); } if (disconnect) { tcpclose(fd); fd = -1; for (rec = threc_head; rec; rec=rec->next) { } } if (fd == -1) { fprintf(stderr, "reconnect ser(ip:%s,port:%s)\\n", ip, port); sleep(2); continue; } r = read(fd,hdr,12); if (r==0) { fprintf(stderr, "ser: connection lost (1)\\n"); disconnect=1; continue; } if (r!=12) { fprintf(stderr,"ser: tcp recv error(1), %d\\n", r); disconnect=1; continue; } ptr = hdr; GET32BIT(cmd,ptr); GET32BIT(size,ptr); GET32BIT(packetid,ptr); fprintf(stderr, "read, cmd:%u\\n", cmd); fprintf(stderr, "read, size:%u\\n", size); fprintf(stderr, "read, packetid:%u\\n", packetid); if (cmd==ANTOAN_NOP && size==4) { continue; } if (size < 4) { fprintf(stderr,"ser: packet too small\\n"); disconnect=1; continue; } size -= 4; if (analyze_ser_cmd(cmd) == 0) { analyze_ser_packet(cmd, size); continue; } rec = fs_get_threc_by_id(packetid); if (rec == 0) { fprintf(stderr, "ser: get unexpected queryid\\n"); disconnect=1; continue; } fs_buffer_init(rec,rec->size+size); if (rec->buff == 0) { disconnect=1; continue; } if (size>0) { r = tcptoread(fd,rec->buff+rec->size,size,1000); int i; fprintf(stderr, "read buf:%s, size:%d\\n", rec->buff, size); for(i = 0; i< size; i++) { fprintf(stderr, "%u-", rec->buff[rec->size+i]); } fprintf(stderr, "\\n"); if (r == 0) { fprintf(stderr,"ser: connection lost (2)\\n"); disconnect=1; continue; } if (r != (int32_t)(size)) { fprintf(stderr,"ser: tcp recv error(2)\\n"); disconnect=1; continue; } } rec->sent=0; rec->status=0; rec->size = size; rec->cmd = cmd; rec->release = 1; pthread_cond_signal(&(rec->cond)); } } void ser_init(char *_ip, char *_port) { ip = strdup(_ip); port = strdup(_port); cuid = 0; fd = -1; disconnect = 1; pthread_mutex_init(&fdlock,0); pthread_create(&rthid, 0, receive_thread, 0); }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <sys/socket.h> #include <linux/netlink.h> #include <errno.h> struct udp_splice_handle { pthread_mutex_t lock; int sock; uint16_t id; }; static int udp_splice_get_family_id(int sock) { struct { struct nlmsghdr nl; char buf[4096]; } buf; struct genlmsghdr *genl; struct rtattr *rta; struct sockaddr_nl addr = { .nl_family = AF_NETLINK, }; int len; memset(&buf.nl, 0, sizeof(buf.nl)); buf.nl.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN); buf.nl.nlmsg_flags = NLM_F_REQUEST; buf.nl.nlmsg_type = GENL_ID_CTRL; genl = (struct genlmsghdr *)buf.buf; memset(genl, 0, sizeof(*genl)); genl->cmd = CTRL_CMD_GETFAMILY; rta = (struct rtattr *)(genl + 1); rta->rta_type = CTRL_ATTR_FAMILY_NAME; rta->rta_len = RTA_LENGTH(sizeof(UDP_SPLICE_GENL_NAME)); memcpy(RTA_DATA(rta), UDP_SPLICE_GENL_NAME, sizeof(UDP_SPLICE_GENL_NAME)); buf.nl.nlmsg_len += rta->rta_len; if (sendto(sock, &buf, buf.nl.nlmsg_len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("sendto failed"); return -1; } len = recv(sock, &buf, sizeof(buf), 0); if (len < 0) { perror("recv failed"); return -1; } if (len < sizeof(buf.nl) || buf.nl.nlmsg_len != len) { errno = EBADMSG; return -1; } if (buf.nl.nlmsg_type == NLMSG_ERROR) { struct nlmsgerr *errmsg = (struct nlmsgerr *)buf.buf; errno = -errmsg->error; return -1; } len -= sizeof(buf.nl) + sizeof(*genl); while (RTA_OK(rta, len)) { if (rta->rta_type == CTRL_ATTR_FAMILY_ID) { return *(uint16_t *)RTA_DATA(rta); } rta = RTA_NEXT(rta, len); } errno = EBADMSG; return -1; } void *udp_splice_open(void) { struct udp_splice_handle *h; int retval; struct sockaddr_nl addr; h = malloc(sizeof(*h)); if (!h) { perror("malloc failed"); return NULL; } retval = pthread_mutex_init(&h->lock, NULL); if (retval) { errno = retval; free(h); return NULL; } h->sock = socket(PF_NETLINK, SOCK_DGRAM | SOCK_NONBLOCK | SOCK_CLOEXEC, NETLINK_GENERIC); if (h->sock < 0) { perror("socket creation failed"); pthread_mutex_destroy(&h->lock); free(h); return NULL; } memset(&addr, 0, sizeof(addr)); addr.nl_family = AF_NETLINK; if (bind(h->sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) { perror("bind failed"); close(h->sock); pthread_mutex_destroy(&h->lock); free(h); return NULL; } retval = udp_splice_get_family_id(h->sock); if (retval < 0) { close(h->sock); pthread_mutex_destroy(&h->lock); free(h); return NULL; } h->id = retval; return h; } int udp_splice_add(void *handle, int sock, int sock2, uint32_t timeout) { struct { struct nlmsghdr nl; struct genlmsghdr genl; char attrs[RTA_LENGTH(4) * 3]; } req; struct { struct nlmsghdr nl; struct nlmsgerr err; } res; struct rtattr *rta; struct sockaddr_nl addr = { .nl_family = AF_NETLINK }; int len; struct udp_splice_handle *h = handle; memset(&req, 0, sizeof(req.nl) + sizeof(req.genl)); req.nl.nlmsg_len = NLMSG_LENGTH(GENL_HDRLEN); req.nl.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK; req.nl.nlmsg_type = h->id; req.genl.cmd = UDP_SPLICE_CMD_ADD; rta = (struct rtattr *)req.attrs; rta->rta_type = UDP_SPLICE_ATTR_SOCK; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = sock; req.nl.nlmsg_len += rta->rta_len; rta = (struct rtattr *)(((char *)rta) + rta->rta_len); rta->rta_type = UDP_SPLICE_ATTR_SOCK2; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = sock2; req.nl.nlmsg_len += rta->rta_len; if (timeout) { rta = (struct rtattr *)(((char *)rta) + rta->rta_len); rta->rta_type = UDP_SPLICE_ATTR_TIMEOUT; rta->rta_len = RTA_LENGTH(4); *(uint32_t *)RTA_DATA(rta) = timeout; req.nl.nlmsg_len += rta->rta_len; } pthread_mutex_lock(&h->lock); if (sendto(h->sock, &req, req.nl.nlmsg_len, 0, (struct sockaddr *)&addr, sizeof(addr)) < 0) { pthread_mutex_unlock(&h->lock); perror("sendto failed"); return -1; } len = recv(h->sock, &res, sizeof(res), 0); pthread_mutex_unlock(&h->lock); if (len < 0) { perror("recv failed"); return -1; } if (len != sizeof(res) || res.nl.nlmsg_type != NLMSG_ERROR) { errno = EBADMSG; return -1; } if (res.err.error) { errno = -res.err.error; return -1; } return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <math.h> #include <unistd.h> #include <errno.h> // Constants #define CG_MAX 4 #define ND 4 #define X_MAX 4 #define Z_MAX 4 #define ROW 2 #define COL 2 #define d 1 // Global variables pthread_mutex_t mut1, mut2; pthread_cond_t cond1, cond2; int g_status; // Forward declarations void master_wait(); void master_signal(struct Param **params); void slave_wait(struct Param *param); void slave_signal(); void compute_ldm(struct Param *param); // Param structure definition struct Param { int nx, nz, nb, ldnx, ldnz, freeSurface, id, nd, icg, status, exit; int gnxbeg, gnzbeg; const float *prev_wave, *curr_wave, *vel; float *next_wave, *u2, *src_wave, *vsrc_wave, *image, scale; int crnx, crnz, task; struct Param **params; }; // Function definitions void master_wait() { while (g_status != 0) { pthread_cond_wait(&cond1, &mut1); } g_status = CG_MAX; } void master_signal(struct Param **params) { int i; for (i = 0; i < CG_MAX; i++) { params[i * ND]->status = 0; } pthread_cond_broadcast(&cond2); } void slave_wait(struct Param *param) { while (param->status) { pthread_cond_wait(&cond2, &mut2); } } void slave_signal() { g_status--; pthread_cond_signal(&cond1); } 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) { struct Param *param = (struct Param *)ptr; struct Param **params = param->params; compute_ldm(param); while (1) { slave_wait(param); if (param->exit) { break; } param->status = 1; int i; for (i = 0; i < ND; i++) { param = params[param->id + i]; if (param->task == 0) { // Simulating work done by threads (replace with actual implementation) } else if (param->task == 1) { // Simulating work done by threads (replace with actual implementation) } param = params[param->id]; } slave_signal(); } return 0; } 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, NULL) != 0 || pthread_mutex_init(&mut2, NULL) != 0) { printf("Mutex init error\\n"); exit(EXIT_FAILURE); } if (pthread_cond_init(&cond1, NULL) != 0 || pthread_cond_init(&cond2, NULL) != 0) { printf("Cond init error\\n"); exit(EXIT_FAILURE); } for (int ix = 0; ix < X_MAX; ix++) { int cnx = nx - 2 * d; int snx = ceil(cnx * 1.0 / X_MAX); int snxbeg = snx * ix - d + d; int snxend = snx * (ix + 1) + d + d; snxend = snxend < nx ? snxend : nx; snx = snxend - snxbeg; for (int iz = 0; iz < Z_MAX; iz++) { int cnz = nz - 2 * d; int snz = ceil(cnz * 1.0 / Z_MAX); int snzbeg = snz * iz - d + d; int snzend = snz * (iz + 1) + d + d; snzend = snzend < nz ? snzend : nz; snz = snzend - snzbeg; int id = ix * Z_MAX + iz; params[id] = (struct Param *)malloc(sizeof(struct Param)); if (params[id] == NULL) { perror("malloc failed"); exit(EXIT_FAILURE); } 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 (int icg = 0; icg < CG_MAX; icg++) { int id_beg = icg * ND; if (pthread_create(&pt[icg], NULL, fd4t10s_4cg, (void *)params[id_beg]) != 0) { perror("pthread_create failed"); exit(EXIT_FAILURE); } } init = 0; } master_signal(params); master_wait(); } // Cleanup function void fd4t10s_4cg_exit() { for (int icg = 0; icg < CG_MAX; icg++) { params[icg * ND]->exit = 1; } master_signal(params); for (int icg = 0; icg < CG_MAX; icg++) { pthread_join(pt[icg], NULL); } for (int ix = 0; ix < X_MAX; ix++) { for (int iz = 0; iz < Z_MAX; iz++) { free(params[ix * Z_MAX + iz]); } } pthread_mutex_destroy(&mut1); pthread_mutex_destroy(&mut2); pthread_cond_destroy(&cond1); pthread_cond_destroy(&cond2); }
1
1
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <pthread.h> #include <unistd.h> pthread_mutex_t* f; int* hungerOfPhylosophs; int N; void takeLeftFork(int); void takeRightFork(int); void putLeftFork(int); void putRightFork(int); void* meal(void*); int main() { int Hunger, *Nums; pthread_t* P; while (1) { printf("Type number of philosophers and hunger of them:\\n"); scanf("%d%d", &N, &Hunger); if (N == 0) break; f = (pthread_mutex_t*)malloc(N * sizeof(pthread_mutex_t)); hungerOfPhylosophs = (int*)malloc(N * sizeof(int)); P = (pthread_t*)malloc(N * sizeof(pthread_t)); Nums = (int*)malloc(N * sizeof(int)); for (int i = 0; i < N; i++) { pthread_mutex_init(f + i, NULL); hungerOfPhylosophs[i] = Hunger; Nums[i] = i; } for (int i = 0; i < N; i++) { pthread_create(P + i, NULL, meal, Nums + i); } for (int i = 0; i < N; i++) { pthread_join(P[i], NULL); } for (int i = 0; i < N; i++) { pthread_mutex_destroy(f + i); } free(f); free(hungerOfPhylosophs); free(P); free(Nums); printf("All philosophers finished\\n"); } return 0; } // Functions to pick up and put down the forks void takeLeftFork(int name) { if (name == 0) pthread_mutex_lock(f + N - 1); // Philosopher 0 picks the last fork as the left fork else pthread_mutex_lock(f + name - 1); } void takeRightFork(int name) { pthread_mutex_lock(f + name); } void putLeftFork(int name) { if (name == 0) pthread_mutex_unlock(f + N - 1); else pthread_mutex_unlock(f + name - 1); } void putRightFork(int name) { pthread_mutex_unlock(f + name); } void* meal(void* pName) { int name = *(int*)pName; while (hungerOfPhylosophs[name] > 0) { if (name == 0) { takeRightFork(name); takeLeftFork(name); } else { takeLeftFork(name); takeRightFork(name); } hungerOfPhylosophs[name]--; printf("Philosopher %d is eating for 3 seconds, hunger left: %d\\n", name, hungerOfPhylosophs[name]); sleep(3); putLeftFork(name); putRightFork(name); printf("Philosopher %d is thinking for 3 seconds\\n", name); sleep(3); } printf("Philosopher %d has finished eating and is now only thinking\\n", name); return NULL; }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <unistd.h> #include <sys/time.h> #include <fcntl.h> #include <stdint.h> #include <sys/stat.h> #include <errno.h> static char *root; static int workers; static int trials; static int record_absolute; static struct timeval asbolute_start; static pthread_mutex_t worker_sync_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t worker_sync_cond = PTHREAD_COND_INITIALIZER; static volatile int worker_sync_t = -1; static volatile int workers_alive = 0; int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { if(x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if(x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; return x->tv_sec < y->tv_sec; } static void pthread_usleep(unsigned int usecs) { int result; pthread_cond_t timercond = PTHREAD_COND_INITIALIZER; pthread_mutex_t timerlock = PTHREAD_MUTEX_INITIALIZER; struct timespec timerexpires; clock_gettime(CLOCK_REALTIME, &timerexpires); timerexpires.tv_nsec += usecs * 1000; if(timerexpires.tv_nsec >= 1000000000) { timerexpires.tv_sec += timerexpires.tv_nsec / 1000000000; timerexpires.tv_nsec = timerexpires.tv_nsec % 1000000000; } result = ~ETIMEDOUT; while(result != ETIMEDOUT) result = pthread_cond_timedwait(&timercond, &timerlock, &timerexpires); } void *worker_run(void *data) { int id = (int) data; char clkpath[256]; sprintf(clkpath, "%s/clock", root); int clkfd = open(clkpath, O_RDONLY); if(clkfd < 0) { perror("open"); exit(1); } char testpath[256]; sprintf(testpath, "%s/%d", root, id); int fd = open(testpath, O_RDWR | O_CREAT, 0777); if(fd < 0) { perror("open"); exit(1); } char buf[1024]; memset(buf, 'x', sizeof(buf)); ((int *) buf)[0] = id; uint64_t *deltas = malloc(sizeof(uint64_t) * trials * 2); workers_alive++; if(id == 0) { while(workers_alive < workers) pthread_usleep(100000); struct stat statbuf; if(fstat(clkfd, &statbuf) < 0) { perror("fstat"); exit(1); } } int t; for(t = 0; ; t++) { if(id == 0) { if(t >= trials && workers_alive == 1) break; } else { if(t >= trials) break; while(worker_sync_t < t) pthread_cond_wait(&worker_sync_cond, &worker_sync_lock); } struct timeval before; gettimeofday(&before, 0); if(lseek(fd, 0, 0) < 0) { perror("lseek"); exit(1); } if(write(fd, buf, sizeof(buf)) < 0) { perror("write"); exit(1); } struct timeval after; gettimeofday(&after, 0); struct timeval diff; if(record_absolute) timeval_subtract(&diff, &after, &asbolute_start); else timeval_subtract(&diff, &after, &before); deltas[t] = (diff.tv_sec * 1000000) + diff.tv_usec; if(id == 0) { pthread_mutex_lock(&worker_sync_lock); worker_sync_t = t; pthread_cond_broadcast(&worker_sync_cond); pthread_mutex_unlock(&worker_sync_lock); pthread_usleep(49000); } } pthread_mutex_lock(&worker_sync_lock); workers_alive--; pthread_mutex_unlock(&worker_sync_lock); return deltas; } int main(int argc, char *argv[]) { if(argc < 4 || argc > 5) { printf("Usage: concurio [mount-point] [workers] [trials] [-a]\\n"); exit(1); } root = argv[1]; workers = strtol(argv[2], 0, 10); trials = strtol(argv[3], 0, 10); if(argc == 5 && strcmp(argv[4], "-a") == 0) record_absolute = 1; else record_absolute = 0; gettimeofday(&asbolute_start, 0); pthread_t *worker_threads = malloc(sizeof(pthread_t) * workers); int w; for(w = 0; w < workers; w++) pthread_create(&worker_threads[w], 0, worker_run, (void *) w); uint64_t **worker_deltas = malloc(sizeof(uint64_t *) * workers); for(w = 0; w < workers; w++) pthread_join(worker_threads[w], (void **) &worker_deltas[w]); if(record_absolute) printf("absolute\\n"); else printf("write-time\\n"); int t; for(w = 0; w < workers; w++) { for(t = 0; t < trials; t++) printf("%d: %llu\\n", w, worker_deltas[w][t]); free(worker_deltas[w]); } exit(0); }
1
1
#include <stdio.h> #include <pthread.h> const int MAX_COUNT = 5; typedef enum {PING_INIT, PING_READY, PONG_READY} READY; READY g_ready = PING_INIT; pthread_mutex_t thr_cond_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t thr_cond = PTHREAD_COND_INITIALIZER; void * thread_ping (void * arg) { int i = 0; pthread_mutex_lock(&thr_cond_lock); g_ready = PING_READY; pthread_cond_wait(&thr_cond, &thr_cond_lock); while(1) { printf("ping(%d) -> ", ++i); pthread_cond_signal(&thr_cond); if (i == MAX_COUNT) { pthread_mutex_unlock(&thr_cond_lock); break; } else pthread_cond_wait(&thr_cond, &thr_cond_lock); } pthread_exit((void *)1); } void * thread_pong (void * arg) { int i = 0; while(1) { pthread_mutex_lock(&thr_cond_lock); if (g_ready == PING_READY) { pthread_cond_signal(&thr_cond); pthread_cond_wait(&thr_cond, &thr_cond_lock); break; } else pthread_mutex_unlock(&thr_cond_lock); } while(1) { printf("pong(%d)\\n", ++i); pthread_cond_signal(&thr_cond); if (i == MAX_COUNT) { pthread_mutex_unlock(&thr_cond_lock); break; } else pthread_cond_wait(&thr_cond, &thr_cond_lock); } pthread_exit((void *)2); } int main() { pthread_t pthread[2]; int result[2]; pthread_create(&pthread[1], NULL, thread_pong, NULL); pthread_create(&pthread[0], NULL, thread_ping, NULL); pthread_join(pthread[0], (void **)&result[0]); pthread_join(pthread[1], (void **)&result[1]); return 0; }
0
1
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <string.h> int shared = 5; pthread_mutex_t lock; void sendreply(int replyfrompno, int replytopno, int ts) { FILE *ptr; char filename[10]; sprintf(filename, "file%d.txt", replytopno); ptr = fopen(filename, "a"); if (ptr == NULL) { perror("Error opening file"); exit(1); } fprintf(ptr, "%d %d\\n", replyfrompno, ts); fclose(ptr); } void *process1(void *val) { int replyfrom[4] = {0}; int clockvalue = 0; int replyto[4] = {0}; FILE *ptr1, *ptr2, *ptr3; printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt", "r"); if (ptr1 == NULL) { perror("Error opening file1.txt"); exit(1); } int pno = 0, ts = 0, timefromotherprocess = 0; while (fscanf(ptr1, "%d %d", &pno, &ts) != EOF) { if (ts > 0 && (pno == 2 || pno == 3)) { if (ts > timefromotherprocess) timefromotherprocess = ts; } } clockvalue = (clockvalue < timefromotherprocess) ? timefromotherprocess + 1 : clockvalue + 1; printf("file1 %d %d\\n", pno, ts); fclose(ptr1); pthread_mutex_unlock(&lock); printf("--------------process1---------------\\n"); ptr2 = fopen("file2.txt", "a"); ptr3 = fopen("file3.txt", "a"); if (ptr2 == NULL || ptr3 == NULL) { perror("Error opening file2.txt or file3.txt"); exit(1); } fprintf(ptr2, "%d %d\\n", 1, clockvalue); fprintf(ptr3, "%d %d\\n", 1, clockvalue); fclose(ptr2); fclose(ptr3); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt", "r"); if (ptr1 == NULL) { perror("Error opening file1.txt"); pthread_mutex_unlock(&lock); exit(1); } while (fscanf(ptr1, "%d %d", &pno, &ts) != EOF) { if (ts > 0 && (pno != 1)) { sendreply(1, pno, -ts); replyto[pno] = 1; } printf("1file1 %d %d\\n", pno, ts); } fclose(ptr1); pthread_mutex_unlock(&lock); while (1) { pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); ptr1 = fopen("file1.txt", "r"); if (ptr1 == NULL) { perror("Error opening file1.txt"); pthread_mutex_unlock(&lock); exit(1); } while (fscanf(ptr1, "%d %d", &pno, &ts) != EOF) { if (ts < 0) { replyfrom[pno] = 1; } printf("1file1 %d %d\\n", pno, ts); } if (replyfrom[2] == 1 && replyfrom[3] == 1) { fclose(ptr1); pthread_mutex_unlock(&lock); break; } fclose(ptr1); pthread_mutex_unlock(&lock); sleep(2); } pthread_mutex_lock(&lock); printf("--------------process1---------------\\n"); shared = shared + 10; printf("p1 did %d\\n", shared); pthread_mutex_unlock(&lock); return NULL; } void *process2(void *val) { // Implementation similar to process1 // Make sure to adjust file handling and synchronization similarly return NULL; } void *process3(void *val) { // Implementation similar to process1 // Make sure to adjust file handling and synchronization similarly return NULL; } int main() { pthread_t pt[3]; pthread_mutex_init(&lock, NULL); pthread_create(&pt[0], NULL, process1, NULL); pthread_create(&pt[1], NULL, process2, NULL); pthread_create(&pt[2], NULL, process3, NULL); pthread_join(pt[0], NULL); pthread_join(pt[1], NULL); pthread_join(pt[2], NULL); pthread_mutex_destroy(&lock); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <semaphore.h> #include <sys/mman.h> #include <time.h> #include <fcntl.h> #include <errno.h> struct sema_mutex_args_struct { sem_t* id; pthread_mutex_t* mutex; int* status; pthread_barrier_t* barr; }; void* mutex_keeper(void* w_args) { struct sema_mutex_args_struct* args = (struct sema_mutex_args_struct*)w_args; pthread_mutex_t* pmutex = args->mutex; int* status = args->status; pthread_barrier_t* barr = args->barr; struct timespec start; while (*status != -1) { pthread_barrier_wait(barr); if (*status == -1) break; pthread_mutex_lock(pmutex); pthread_barrier_wait(barr); clock_gettime(CLOCK_REALTIME, &start); pthread_mutex_unlock(pmutex); } return NULL; } void* semaphore_keeper(void* w_args) { struct sema_mutex_args_struct* args = (struct sema_mutex_args_struct*)w_args; sem_t* id = args->id; int* status = args->status; pthread_barrier_t* barr = args->barr; struct timespec start; while (*status != -1) { pthread_barrier_wait(barr); if (*status == -1) break; if (sem_wait(id) != 0) perror("sem_wait child"); pthread_barrier_wait(barr); clock_gettime(CLOCK_REALTIME, &start); if (sem_post(id) != 0) printf("sem_post child"); } return NULL; } void semaphore_mutex_not_empty(int w_iterations, int w_drop_cache) { printf("\\nMEASURING SEMAPHORE AND MUTEX ACQUISITION TIME AFTER RELEASE\\n"); struct timespec* start = mmap(NULL, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); struct timespec* finish = mmap(NULL, sizeof(struct timespec), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); int* status = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0); if (start == MAP_FAILED || finish == MAP_FAILED || status == MAP_FAILED) { perror("mmap"); exit(1); } *status = 1; sem_t* id; sem_unlink("releasesem"); if ((id = sem_open("releasesem", O_CREAT | O_EXCL, 0600, 0)) == SEM_FAILED) { perror("sem_open"); exit(1); } if (sem_post(id) != 0) printf("sem_post failed"); struct sema_mutex_args_struct args; args.id = id; args.status = status; args.barr = malloc(sizeof(pthread_barrier_t)); pthread_barrier_init(args.barr, NULL, 2); pthread_t thread_creation; pthread_create(&thread_creation, NULL, semaphore_keeper, (void*)&args); double totSemaphoreCached = 0.0; for (int i = 0; i < w_iterations; i++) { pthread_barrier_wait(args.barr); pthread_barrier_wait(args.barr); if (sem_wait(id) != 0) printf("WAIT FAILED ON PARENT"); clock_gettime(CLOCK_REALTIME, finish); if (i >= (w_iterations / 5)) { totSemaphoreCached += (finish->tv_nsec - start->tv_nsec); } if (sem_post(id) != 0) printf("POST FAILED ON PARENT"); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, NULL); printf("\\nCached\\t\\tmean semaphore acquisition time after release with %d samples: %f ns\\n", w_iterations - (w_iterations / 5), totSemaphoreCached / (w_iterations - (w_iterations / 5))); if (w_drop_cache) { pthread_create(&thread_creation, NULL, semaphore_keeper, (void*)&args); int noncache_iterations = w_iterations / 10; double totSemaphoreUncached = 0.0; *status = 1; for (int i = 0; i < noncache_iterations; i++) { pthread_barrier_wait(args.barr); drop_cache(); // Assuming drop_cache() is defined elsewhere pthread_barrier_wait(args.barr); if (sem_wait(id) != 0) printf("WAIT FAILED ON PARENT"); clock_gettime(CLOCK_REALTIME, finish); totSemaphoreUncached += (finish->tv_nsec - start->tv_nsec); if (sem_post(id) != 0) printf("POST FAILED ON PARENT"); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, NULL); printf("Non-cached\\tmean semaphore acquisition time after release with %d samples: %f ns\\n", noncache_iterations, totSemaphoreUncached / noncache_iterations); } sem_close(id); sem_unlink("releasesem"); args.mutex = malloc(sizeof(pthread_mutex_t)); pthread_mutex_init(args.mutex, NULL); *status = 1; pthread_create(&thread_creation, NULL, mutex_keeper, (void*)&args); double totMutexCached = 0.0; for (int i = 0; i < w_iterations; i++) { pthread_barrier_wait(args.barr); pthread_barrier_wait(args.barr); pthread_mutex_lock(args.mutex); clock_gettime(CLOCK_REALTIME, finish); if (i >= (w_iterations / 5)) { totMutexCached += (finish->tv_nsec - start->tv_nsec); } pthread_mutex_unlock(args.mutex); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, NULL); printf("\\nCached\\t\\tmean mutex acquisition time after release with %d samples: %f ns\\n", w_iterations - (w_iterations / 5), totMutexCached / (w_iterations - (w_iterations / 5))); if (w_drop_cache) { *status = 1; pthread_create(&thread_creation, NULL, mutex_keeper, (void*)&args); int noncache_iterations = w_iterations / 10; double totMutexUncached = 0.0; for (int i = 0; i < noncache_iterations; i++) { pthread_barrier_wait(args.barr); drop_cache(); pthread_barrier_wait(args.barr); pthread_mutex_lock(args.mutex); clock_gettime(CLOCK_REALTIME, finish); totMutexUncached += (finish->tv_nsec - start->tv_nsec); pthread_mutex_unlock(args.mutex); } *status = -1; pthread_barrier_wait(args.barr); pthread_join(thread_creation, NULL); printf("Non-cached\\tmean mutex acquisition time after release with %d samples: %f ns\\n", noncache_iterations, totMutexUncached / noncache_iterations); } pthread_mutex_destroy(args.mutex); free(args.mutex); pthread_barrier_destroy(args.barr); free(args.barr); munmap(status, sizeof(int)); munmap(start, sizeof(struct timespec)); munmap(finish, sizeof(struct timespec)); }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <errno.h> #include "uthash.h" // Ensure you have this library or similar hash table library available #define TypeResponse 1 #define TypeRead 2 #define TypeWrite 3 struct Message { int Seq; int Type; off_t Offset; size_t DataLength; void *Data; pthread_cond_t cond; pthread_mutex_t mutex; }; struct client_connection { int fd; int seq; struct Message *msg_table; pthread_mutex_t mutex; pthread_t response_thread; }; // Dummy functions for send_msg and receive_msg int send_msg(int fd, struct Message *msg) { // Implement the actual sending logic here return 0; // Placeholder for success } int receive_msg(int fd, struct Message *msg) { // Implement the actual receiving logic here return 0; // Placeholder for success } int send_request(struct client_connection *conn, struct Message *req) { int rc = 0; rc = send_msg(conn->fd, req); return rc; } int receive_response(struct client_connection *conn, struct Message *resp) { return receive_msg(conn->fd, resp); } void* response_process(void *arg) { struct client_connection *conn = (struct client_connection *)arg; struct Message *req, *resp; int ret = 0; resp = malloc(sizeof(struct Message)); if (resp == NULL) { perror("cannot allocate memory for resp"); return NULL; } ret = receive_response(conn, resp); while (ret == 0) { if (resp->Type != TypeResponse) { fprintf(stderr, "Wrong type for response of seq %d\\n", resp->Seq); ret = receive_response(conn, resp); continue; } HASH_FIND_INT(conn->msg_table, &resp->Seq, req); if (req != NULL) { HASH_DEL(conn->msg_table, req); } if (req != NULL) { memcpy(req->Data, resp->Data, req->DataLength); free(resp->Data); pthread_cond_signal(&req->cond); } ret = receive_response(conn, resp); } free(resp); if (ret != 0) { fprintf(stderr, "Receive response returned error\\n"); } return NULL; } void start_response_processing(struct client_connection *conn) { int rc; rc = pthread_create(&conn->response_thread, NULL, response_process, conn); if (rc != 0) { perror("Fail to create response thread"); exit(EXIT_FAILURE); } } int new_seq(struct client_connection *conn) { return __sync_fetch_and_add(&conn->seq, 1); } int process_request(struct client_connection *conn, void *buf, size_t count, off_t offset, uint32_t type) { struct Message *req = malloc(sizeof(struct Message)); int rc = 0; if (req == NULL) { perror("cannot allocate memory for req"); return -ENOMEM; } if (type != TypeRead && type != TypeWrite) { fprintf(stderr, "BUG: Invalid type for process_request %d\\n", type); rc = -EFAULT; free(req); return rc; } req->Seq = new_seq(conn); req->Type = type; req->Offset = offset; req->DataLength = count; req->Data = buf; if (req->Type == TypeRead) { memset(req->Data, 0, count); } rc = pthread_cond_init(&req->cond, NULL); if (rc != 0) { perror("Fail to init pthread_cond"); free(req); return -EFAULT; } rc = pthread_mutex_init(&req->mutex, NULL); if (rc != 0) { perror("Fail to init pthread_mutex"); pthread_cond_destroy(&req->cond); free(req); return -EFAULT; } pthread_mutex_lock(&conn->mutex); HASH_ADD_INT(conn->msg_table, Seq, req); pthread_mutex_unlock(&conn->mutex); pthread_mutex_lock(&req->mutex); rc = send_request(conn, req); if (rc < 0) { pthread_mutex_unlock(&req->mutex); pthread_mutex_destroy(&req->mutex); pthread_cond_destroy(&req->cond); free(req); return rc; } pthread_cond_wait(&req->cond, &req->mutex); pthread_mutex_unlock(&req->mutex); pthread_mutex_destroy(&req->mutex); pthread_cond_destroy(&req->cond); free(req); return rc; } int read_at(struct client_connection *conn, void *buf, size_t count, off_t offset) { return process_request(conn, buf, count, offset, TypeRead); } int write_at(struct client_connection *conn, void *buf, size_t count, off_t offset) { return process_request(conn, buf, count, offset, TypeWrite); } struct client_connection *new_client_connection(char *socket_path) { struct sockaddr_un addr; int fd, rc; struct client_connection *conn; fd = socket(AF_UNIX, SOCK_STREAM, 0); if (fd == -1) { perror("socket error"); exit(EXIT_FAILURE); } memset(&addr, 0, sizeof(addr)); addr.sun_family = AF_UNIX; if (strlen(socket_path) >= sizeof(addr.sun_path)) { fprintf(stderr, "socket path is too long, more than %zu characters\\n", sizeof(addr.sun_path) - 1); exit(EXIT_FAILURE); } strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1); if (connect(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) { perror("connect error"); close(fd); exit(EXIT_FAILURE); } conn = malloc(sizeof(struct client_connection)); if (conn == NULL) { perror("cannot allocate memory for conn"); close(fd); return NULL; } conn->fd = fd; conn->seq = 0; conn->msg_table = NULL; rc = pthread_mutex_init(&conn->mutex, NULL); if (rc != 0) { perror("fail to init conn->mutex"); free(conn); close(fd); exit(EXIT_FAILURE); } return conn; } int shutdown_client_connection(struct client_connection *conn) { if (conn == NULL) return -EINVAL; close(conn->fd); pthread_mutex_destroy(&conn->mutex); free(conn); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <pthread.h> #include <linux/spi/spidev.h> #include <string.h> #include <errno.h> #define SPI_MODE SPI_MODE_0 #define SPI_BITS_PER_WORD 8 #define SPI_SPEED_HZ 500000 #define SPI_DELAY 0 #define FPGA_SPI_DEV "/dev/spidev0.0" #define CMD_SERVO 0x01 #define CMD_SPEED_ACC_SWITCH 0x02 #define CMD_AS 0x03 #define CMD_LED 0x04 #define CMD_SPEED 0x05 #define CMD_SPEEDPOLL 0x06 #define CMD_SPEEDRAW 0x07 #define SPI_PREAMBLE 0xAA #define HIGHBYTE(x) ((x) >> 8) #define LOWBYTE(x) ((x) & 0xFF) int fd; FILE *logfd = NULL; static uint8_t spi_mode = SPI_MODE; static uint8_t spi_bits = SPI_BITS_PER_WORD; static uint32_t spi_speed = SPI_SPEED_HZ; static uint16_t spi_delay = SPI_DELAY; pthread_mutex_t spi_mutex; int fpga_open() { int ret; pthread_mutex_init(&spi_mutex, NULL); printf("Will use SPI to send commands to FPGA\\n"); printf("SPI configuration:\\n"); printf(" + dev: %s\\n", FPGA_SPI_DEV); printf(" + mode: %d\\n", spi_mode); printf(" + bits per word: %d\\n", spi_bits); printf(" + speed: %d Hz (%d KHz)\\n\\n", spi_speed, spi_speed / 1000); if ((fd = open(FPGA_SPI_DEV, O_RDWR)) < 0) { perror("E: fpga: spi: Failed to open dev"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_MODE, &spi_mode)) < 0) { perror("E: fpga: spi: can't set spi mode wr"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_MODE, &spi_mode)) < 0) { perror("E: fpga: spi: can't set spi mode rd"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits)) < 0) { perror("E: fpga: spi: can't set bits per word wr"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &spi_bits)) < 0) { perror("E: fpga: spi: can't set bits per word rd"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed)) < 0) { perror("E: fpga: spi: can't set speed wr"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &spi_speed)) < 0) { perror("E: fpga: spi: can't set speed rd"); return -1; } if (fpga_logopen() < 0) { fprintf(stderr, "E: fpga: could not open log\\n"); return -1; } return 0; } void fpga_close() { if (fd >= 0) { close(fd); } if (logfd) { fclose(logfd); } pthread_mutex_destroy(&spi_mutex); } int fpga_logopen() { logfd = fopen("/tmp/ourlog", "a"); if (!logfd) { perror("E: fpga: could not open log file"); return -1; } fprintf(logfd, "--------reopened--------\\n"); return 0; } int spisend(unsigned char *rbuf, unsigned char *wbuf, int len) { int ret; pthread_mutex_lock(&spi_mutex); struct spi_ioc_transfer tr = { .tx_buf = (unsigned long)wbuf, .rx_buf = (unsigned long)rbuf, .len = len, .delay_usecs = spi_delay, .speed_hz = spi_speed, .bits_per_word = spi_bits, }; ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1) { perror("E: fpga: can't send SPI message"); pthread_mutex_unlock(&spi_mutex); return -1; } pthread_mutex_unlock(&spi_mutex); return ret; } void fpga_testservos() { if (fpga_open() < 0) { fprintf(stderr, "E: FPGA: Could not open SPI to FPGA\\n"); exit(EXIT_FAILURE); } printf("Moving servo left\\n"); fpga_setservo(1, 0); sleep(2); printf("Moving servo centre\\n"); fpga_setservo(1, 4000); sleep(2); printf("Moving servo right\\n"); fpga_setservo(1, 8000); sleep(2); printf("Moving servo centre\\n"); fpga_setservo(1, 4000); fpga_close(); }
0
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include <stdbool.h> static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; static unsigned int seed0; static unsigned int seed1; static int have_init = 0; static int read_dev_random (void *buffer, size_t buffer_size) { int fd; ssize_t status = 0; char *buffer_position; size_t yet_to_read; fd = open ("/dev/urandom", O_RDONLY); if (fd < 0) { perror ("open"); return (-1); } buffer_position = (char *) buffer; yet_to_read = buffer_size; while (yet_to_read > 0) { status = read (fd, (void *) buffer_position, yet_to_read); if (status < 0) { if (errno == EINTR) continue; fprintf (stderr, "read_dev_random: read failed.\\n"); break; } buffer_position += status; yet_to_read -= (size_t) status; } close (fd); if (status < 0) return (-1); return (0); } static void do_init (void) { if (have_init) return; read_dev_random (&seed0, sizeof (seed0)); read_dev_random (&seed1, sizeof (seed1)); have_init = 1; } int sn_random_init (void) { have_init = 0; do_init (); return (0); } int sn_random (void) { int r0; int r1; do_init (); r0 = rand_r (&seed0); r1 = rand_r (&seed1); return (r0 ^ r1); } int sn_true_random (void) { int ret = 0; int status; status = read_dev_random (&ret, sizeof (ret)); if (status != 0) return (sn_random ()); return (ret); } int sn_bounded_random (int min, int max) { int range; int rand; if (min == max) return (min); else if (min > max) { range = min; min = max; max = range; } range = 1 + max - min; rand = min + (int) (((double) range) * (((double) sn_random ()) / (((double) 32767) + 1.0))); assert (rand >= min); assert (rand <= max); return (rand); } double sn_double_random (void) { return (((double) sn_random ()) / (((double) 32767) + 1.0)); } # 7 "os21.c" 2 # 1 "pycparser/utils/fake_libc_include/sys/types.h" 1 # 8 "os21.c" 2 # 1 "pycparser/utils/fake_libc_include/sys/syscall.h" 1 # 9 "os21.c" 2 pthread_mutex_t lock; pthread_mutex_t lock2; pthread_cond_t empty; pthread_cond_t full; struct item{ int val; int sleeptime; }; struct item * buffer; void * consumer(void *dummy) { int * curitem = (int *)(dummy); pid_t x = syscall(__NR_gettid); while(1) { fflush(stdout); while(*curitem < 0){ pthread_cond_wait(&empty, &lock); } sleep(buffer[*curitem].sleeptime); printf("(CONSUMER) My ID is %d and I ate the number %d in %d seconds\\n\\n",x,buffer[*curitem].val, buffer[*curitem].sleeptime); buffer[*curitem].val = 0; buffer[*curitem].sleeptime = 0; *curitem = *curitem - 1; if(*curitem == 30){ pthread_cond_signal(&full); } } return 0; } void * producer(void *dummy) { pthread_mutex_lock(&lock2); int * curitem = (int *)(dummy); pid_t x = syscall(__NR_gettid); pthread_mutex_unlock(&lock2); int i = 0; while(1) { sleep(generate_rand(3,7)); fflush(stdout); pthread_mutex_lock(&lock); while(*curitem > 30){ pthread_cond_wait(&full, &lock); } *curitem = *curitem + 1; i = (int)generate_rand(0,10); printf("(PRODUCER) My ID is %d and I created the value %d\\n\\n",x,i); buffer[*curitem].val = i; i = (int)generate_rand(2,9); buffer[*curitem].sleeptime = i; if(*curitem == 0){ pthread_cond_signal(&empty); } pthread_mutex_unlock(&lock); } return 0; } int main(int argc, char **argv) { int * curitem = malloc(sizeof(int)); int curthread = 0; buffer = malloc(sizeof(struct item)*32); *curitem = -1; pthread_mutex_init(&lock, 0); pthread_mutex_init(&lock2, 0); pthread_cond_init(&full, 0); pthread_cond_init(&empty, 0); int threadcap = atoi(argv[1]); pthread_t conthreads[threadcap]; pthread_t prod; pthread_create(&prod, 0, producer, (void*)curitem); for(; curthread < threadcap; curthread++) pthread_create(&conthreads[curthread], 0, consumer, (void*)curitem); pthread_join(prod, 0); for(curthread = 0; curthread < threadcap; curthread++) pthread_join(conthreads[curthread], 0); return 0; }
1
1
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <signal.h> extern void skynet_logger_error(int, const char *, ...); extern void skynet_logger_notice(int, const char *, ...); extern void skynet_malloc(size_t); extern void skynet_free(void *); extern void skynet_config_init(const char *); extern void skynet_config_int(const char *, const char *, int *); extern void skynet_config_string(const char *, const char *, char *, size_t); extern void skynet_mq_init(); extern void skynet_service_init(const char *); extern void skynet_logger_init(unsigned, const char *); extern void skynet_timer_init(); extern void skynet_socket_init(); extern void skynet_service_create(const char *, unsigned, const char *, int); extern void skynet_service_releaseall(); extern void skynet_socket_free(); extern void skynet_config_free(); extern void skynet_socket_exit(); extern int skynet_socket_poll(); extern int skynet_message_dispatch(); extern void skynet_updatetime(); struct monitor { int count; int sleep; int quit; pthread_t *pids; pthread_cond_t cond; pthread_mutex_t mutex; }; static struct monitor *m = 0; void create_thread(pthread_t *thread, void *(*start_routine)(void *), void *arg) { if (pthread_create(thread, 0, start_routine, arg)) { skynet_logger_error(0, "Create thread failed"); exit(1); } } void wakeup(struct monitor *m, int busy) { pthread_mutex_lock(&m->mutex); if (m->sleep >= m->count - busy) { pthread_cond_signal(&m->cond); } pthread_mutex_unlock(&m->mutex); } void *thread_socket(void *p) { struct monitor *m = p; while (1) { pthread_mutex_lock(&m->mutex); if (m->quit) { pthread_mutex_unlock(&m->mutex); break; } pthread_mutex_unlock(&m->mutex); int r = skynet_socket_poll(); if (r == 0) break; if (r < 0) { continue; } wakeup(m, 0); } return 0; } void *thread_timer(void *p) { struct monitor *m = p; while (1) { pthread_mutex_lock(&m->mutex); if (m->quit) { pthread_mutex_unlock(&m->mutex); break; } pthread_mutex_unlock(&m->mutex); skynet_updatetime(); wakeup(m, m->count - 1); usleep(1000); } return 0; } void *thread_worker(void *p) { struct monitor *m = p; while (1) { pthread_mutex_lock(&m->mutex); if (m->quit) { pthread_mutex_unlock(&m->mutex); break; } pthread_mutex_unlock(&m->mutex); if (skynet_message_dispatch()) { pthread_mutex_lock(&m->mutex); ++m->sleep; if (!m->quit) pthread_cond_wait(&m->cond, &m->mutex); --m->sleep; pthread_mutex_unlock(&m->mutex); } } return 0; } void skynet_start(unsigned harbor, unsigned thread) { unsigned i; m = skynet_malloc(sizeof(*m)); memset(m, 0, sizeof(*m)); m->count = thread; m->sleep = 0; m->quit = 0; m->pids = skynet_malloc(sizeof(*m->pids) * (thread + 2)); pthread_mutex_init(&m->mutex, 0); pthread_cond_init(&m->cond, 0); for (i = 0; i < thread; i++) { create_thread(m->pids + i, thread_worker, m); } create_thread(m->pids + i, thread_timer, m); create_thread(m->pids + i + 1, thread_socket, m); skynet_logger_notice(0, "skynet start, harbor:%u workers:%u", harbor, thread); for (i = 0; i < thread; i++) { pthread_join(*(m->pids + i), 0); } skynet_logger_notice(0, "skynet shutdown, harbor:%u", harbor); pthread_mutex_destroy(&m->mutex); pthread_cond_destroy(&m->cond); skynet_free(m->pids); skynet_free(m); } void skynet_shutdown(int sig) { skynet_logger_notice(0, "recv signal:%d", sig); pthread_mutex_lock(&m->mutex); m->quit = 1; skynet_socket_exit(); pthread_cond_broadcast(&m->cond); pthread_mutex_unlock(&m->mutex); } void skynet_coredump(int sig) { skynet_shutdown(sig); skynet_service_releaseall(); signal(sig, SIG_DFL); raise(sig); } void skynet_signal_init() { struct sigaction actTerminate; actTerminate.sa_handler = skynet_shutdown; sigemptyset(&actTerminate.sa_mask); actTerminate.sa_flags = 0; sigaction(SIGTERM, &actTerminate, 0); struct sigaction actCoredump; actCoredump.sa_handler = skynet_coredump; sigemptyset(&actCoredump.sa_mask); actCoredump.sa_flags = 0; sigaction(SIGSEGV, &actCoredump, 0); sigaction(SIGILL, &actCoredump, 0); sigaction(SIGFPE, &actCoredump, 0); sigaction(SIGABRT, &actCoredump, 0); sigset_t bset, oset; sigemptyset(&bset); sigaddset(&bset, SIGINT); pthread_sigmask(SIG_BLOCK, &bset, &oset); } int main(int argc, char *argv[]) { return 0; }
0
1
README.md exists but content is empty.
Downloads last month
52