text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct timespec start[1000], stop[1000]; double minLatency=100000.00; double maxLatency=0; double avgLatency=0; int N_DATA = 1000; pthread_barrier_t barrier; pthread_mutex_t lock; struct buffer { volatile int head; volatile int tail; int size; volatile int *elems; }; buffer_t *createBuffer( int size) { buffer_t *buf; buf = (buffer_t *)malloc( sizeof(buffer_t)); buf->head = 0; buf->tail = 0; buf->size = size+1; buf->elems = (int *)malloc( (size+1)*sizeof(int)); if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); exit(1); } return( buf); } int pop( buffer_t* buf, int *data) { int res; pthread_mutex_lock(&lock); if(buf->head == buf->tail) { res = 0; } else { *data = buf->elems[buf->head]; buf->head = (buf->head+1) % buf->size; res = 1; } pthread_mutex_unlock(&lock); return( res); } int push( buffer_t* buf, int data) { int nextTail; int res; pthread_mutex_lock(&lock); nextTail = (buf->tail + 1) % buf->size; if(nextTail != buf->head) { buf->elems[buf->tail] = data; buf->tail = nextTail; res = 1; } else { res = 0; } pthread_mutex_unlock(&lock); return( res); } struct threadArgs { int tid; buffer_t *in_buf; buffer_t *out_buf; int workload; }; int workUnit( int data) { if( data < 0) data++; return( data); } int process( int tid, int data, int workload) { int i; for( i=0; i<workload; i++) data = workUnit( data); return( data); } void * pipeline( void *arg) { int data; int workload; int i = 0; buffer_t *in; buffer_t *out; int tid; struct timespec startOne, stopOne; in = ((threadArgs_t *)arg)->in_buf; out = ((threadArgs_t *)arg)->out_buf; tid = ((threadArgs_t *)arg)->tid; workload = ((threadArgs_t *)arg)->workload; while(i<N_DATA) { if(pop(in, &data) == 1) { if(tid == 0) clock_gettime (CLOCK_REALTIME, &start[i]); data = process(tid, data, workload); push(out, data); pthread_barrier_wait(&barrier); if(tid == (2)) { clock_gettime (CLOCK_REALTIME, &stop[i]); } i++; } } } double xelapsed (struct timespec a, struct timespec b) { return (a.tv_sec - b.tv_sec) * 1000000.0 + (a.tv_nsec - b.tv_nsec) / 1000.0; } void calculateLatency () { int i; for(i = 0; i< N_DATA; i++) { double tmp = xelapsed(stop[i], start[i]); if (tmp<minLatency) minLatency = tmp; if(tmp>maxLatency) maxLatency = tmp; if(i == 0) avgLatency = tmp; else avgLatency = (avgLatency + tmp)/2; } } double throughput(double latency) { return 1000000.0/latency; } void main(int argc, char *argv[]) { int i, suc; int data; threadArgs_t args[3]; pthread_t threads[3]; buffer_t *in, *inter1, *inter2, *out; double tput; int c; c = pthread_barrier_init(&barrier, 0,3); if( argc == 2) { N_DATA = atoi( argv[1]); } in = createBuffer( N_DATA+1); inter1 = createBuffer( 200); inter2 = createBuffer( 200); out = createBuffer( N_DATA+1); args[0].in_buf = in; args[0].out_buf = inter1; args[0].workload = 100000; args[1].in_buf = inter1; args[1].out_buf = inter2; args[1].workload = 100; args[2].in_buf = inter2; args[2].out_buf = out; args[2].workload = 100; for(i=0;i<3;i++){ pthread_t tid; args[i].tid = i; int res=(int) pthread_create (&tid, 0, pipeline, (void *)&args[i]); if (res < 0) { perror("error creating thread"); abort(); }else if (res==0) { threads[i]=tid; pipeline; } } for(i=0; i<N_DATA;i++) { push(in, i); } for(i=0; i<3; i++) { pthread_join (threads[i], 0); } pthread_mutex_destroy(&lock); calculateLatency(); tput = throughput(avgLatency); for(i=0; i<N_DATA;i++) { suc = 0; while (suc == 0) { suc = pop(out, &data); } } printf ("minLatency=%5.0f (mics) maxLatency=%5.0f (mics) avgLatency=%5.0f (mics) throughput=%5.0f \\n", minLatency, maxLatency, avgLatency, tput); printf ("N_DATA=%d ; workload1=%d ; workload2=%d ; workload3=%d \\n", N_DATA, 100000, 100, 100); }
1
#include <pthread.h> char phil_state[5] = {'T','T', 'T', 'T','T'}; pthread_mutex_t canEat; sem_t amt; const char* semaphore_name = "/amt"; void* dining_table(void* param); void waiter(int phil_num, int request); void check_on_table(); int main() { pthread_t philosophers[5]; pthread_attr_t phil_attr; pthread_attr_init(&phil_attr); pthread_mutex_init(&canEat, 0); if((sem_init(&amt, 0, 5)) == -1){ fprintf(stderr, "sem_open failed\\n"); } int i; int check; for(i = 0; i < 5; i++){ if(pthread_create(&philosophers[i], &phil_attr, dining_table, (void*) i) != 0){ exit(1); } } for(i = 0; i < 5; i++){ if(pthread_join(philosophers[i], 0) != 0){ exit(1); } } printf("\\nAll Philosphers are FULL:\\n"); check_on_table(); sem_close(&amt); sem_unlink(semaphore_name); return 0; } void* dining_table(void* param){ int phil_num = (int)param; int bitesTake = 0; while(bitesTake != 3){ sleep(1); if(phil_state[phil_num] == 'T') { phil_state[phil_num] = 'H'; pthread_mutex_lock(&canEat); waiter(phil_num, 0); pthread_mutex_unlock(&canEat); } if(phil_state[phil_num] == 'E') { sleep(2); pthread_mutex_lock(&canEat); waiter(phil_num, 1); pthread_mutex_unlock(&canEat); bitesTake++; } if(phil_state[phil_num] == 'H'){ pthread_mutex_lock(&canEat); waiter(phil_num, 0); pthread_mutex_unlock(&canEat); } } phil_state[phil_num] = 'F'; } void waiter(int phil_num, int request){ if(request == 0){ if(phil_state[phil_num] == 'H' && phil_state[(phil_num+4) % 5] != 'E' && phil_state[(phil_num + 1) % 5] != 'E'){ if(phil_state[((phil_num+4) % 5) - 2] != 'E' && phil_state[(phil_num + 2) % 5] != 'E') { sem_wait(&amt); sem_wait(&amt); phil_state[phil_num] = 'E'; check_on_table(); } } }else if(request == 1){ phil_state[phil_num] = 'T'; sem_post(&amt); sem_post(&amt); check_on_table(); }else{ } } void check_on_table(){ printf("Waiter came to check on the table:\\n"); int i; for(i = 0; i < 5; i++){ } printf("_____"); }
0
#include <pthread.h> { unsigned char status; char data[1024]; }Block_Info; static int initindicator = 0; pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER; Block_Info memory_block_arr[2]; int init() { memset(memory_block_arr, 0, 2*1024); } char * mymalloc(size) { int lindex; if(size> 1024) { return (0); } pthread_mutex_lock(&gmutex); if (0 == initindicator) { init(); initindicator = 1; } for(lindex = 0; lindex< 2; lindex++) { if(0 == memory_block_arr[lindex].status) { memory_block_arr[lindex].status = 1; pthread_mutex_unlock(&gmutex); return((char *)&memory_block_arr[lindex].data); } else { if((2 - 1) == lindex) { pthread_mutex_unlock(&gmutex); return(0); } } } } void myfree(char * address) { int lindex; pthread_mutex_lock(&gmutex); for(lindex = 0; lindex< 2; lindex++) { if(address == (char *)&memory_block_arr[lindex].data) memory_block_arr[lindex].status = 0; } pthread_mutex_unlock(&gmutex); }
1
#include <pthread.h> int fila[8]; int topo = 0; pthread_mutex_t fila_mutex; pthread_cond_t fila_threshold; void FILA_push(int dado) { int i; for (i = topo; i > 0; i--) fila[i] = fila[i-1]; if (topo < 8) ++topo; fila[0] = dado; } int FILA_pop() { if (topo <= 0) return -1; return fila[--topo]; } void FILA_print() { int i; printf("Topo = %d\\n", topo); printf("["); for (i = 0; i < topo; i++) printf(" %.02d ", fila[i]); for (i = topo; i < 8; i++) puts("]\\n"); } void *produtor(void *threadId) { int produto; for (produto = 1; produto <= 64; produto++) { pthread_mutex_lock(&fila_mutex); if (topo >= 8) { printf("Sem espaco para produzir, produtor parou\\n\\n"); pthread_cond_wait(&fila_threshold, &fila_mutex); } FILA_push(produto); printf("Produzindo produto %.02d\\n", produto); FILA_print(); pthread_mutex_unlock(&fila_mutex); sleep(1); } printf("Nao existem mais produtos a serem produzidos\\n\\n"); pthread_exit(0); } void *consumidor(void *threadId) { int i; for (i = 0; i < 64; i++) { pthread_mutex_lock(&fila_mutex); printf("Consumindo produto %.02d\\n", FILA_pop()); FILA_print(); pthread_cond_signal(&fila_threshold); pthread_mutex_unlock(&fila_mutex); sleep(2); } pthread_exit(0); } int main(void) { pthread_t threads[2]; pthread_mutex_init(&fila_mutex, 0); pthread_cond_init(&fila_threshold, 0); puts("Criando thread produtor\\n"); pthread_create(threads, 0, produtor, 0); puts("Criando thread consumidor\\n"); pthread_create(threads, 0, consumidor, 0); pthread_join(threads[0], 0); pthread_join(threads[1], 0); printf("Todos produtos foram consumidos\\n"); pthread_mutex_destroy(&fila_mutex); pthread_cond_destroy(&fila_threshold); return 0; }
0
#include <pthread.h> static pthread_mutex_t* mutex; static int* data; static int nbth; static void* thread(void *num) { int l = (long int)num; int r = (l+1) % nbth; int token; if( 0 == num ) { pthread_mutex_unlock( mutex + l ); } while(1) { pthread_mutex_lock(mutex + l); token = data[l]; if (token) { data[r] = token - 1; printf ("t%d: recv %d send %d\\n", l, token, token - 1); pthread_mutex_unlock(mutex + r); } else { data[r] = 0; printf ("t%d: recv 0 send 0; exit!\\n", l); pthread_mutex_unlock(mutex + r); pthread_exit( 0 ); } } } void usage () { printf ("Usage: ring [TOKEN [NTH]]\\n"); printf (" TOKEN is %d by default\\n", 20); printf (" NTH is %d by default\\n", 8); exit (1); } int main(int argc, char **argv) { long int i; int token; pthread_t* cthread; pthread_attr_t stack_attr; if (argc > 3) usage (); if (argc == 3) nbth = atoi(argv[2]); else nbth = 8; if (argc >= 2) token = atoi(argv[1]); else token = 20; printf ("ring: nbth %d, token %d\\n", nbth, token); cthread = (pthread_t*) malloc( nbth * sizeof( pthread_t ) ); data = (int*) malloc( nbth * sizeof( int ) ); mutex = (pthread_mutex_t*) malloc( nbth * sizeof( pthread_mutex_t ) ); data[0] = token; for (i = 0; i < nbth; i++) { pthread_mutex_init(mutex + i, 0); pthread_mutex_lock(mutex + i); pthread_create( &(cthread[i]), 0, thread, (void*)i ); } for (i = 0; i < nbth; i++) { pthread_join(cthread[i], 0); } if( 0 != cthread ) { free( cthread ); cthread = 0; } if( 0 != data ) { free( data ); data = 0; } if( 0 != mutex ) { free( mutex ); mutex = 0; } return 0; }
1
#include <pthread.h> int nitems; int buff[1000000]; struct { pthread_mutex_t mutex; int npro; int nval; }put = { PTHREAD_MUTEX_INITIALIZER }; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; }nready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; void *produce(void*), *consume(void*); int main(int argc, char *argv[]) { int i, npthreads, count[100], total = 0; pthread_t tid_produce[100], tid_consume; if(argc != 3){ printf("Usage: %s <Items> <npthread>\\n", argv[0]); exit(1); } nitems = min(atoi(argv[1]), 1000000); npthreads = min(atoi(argv[2]), 100); for(i = 0; i < npthreads; i++){ count[i] = 0; Pthread_create(&tid_produce[i], 0, produce, &count[i]); } for(i = 0; i < npthreads; i++){ if(pthread_join(tid_produce[i], 0) < 0){ perror("pthread_join"); exit(1); } printf("count[%d] = %d\\n", i, count[i]); } pthread_create(&tid_consume, 0, consume, 0); pthread_join(tid_consume, 0); for(i = 0; i < npthreads; i++){ total += count[i]; } printf("total : %d\\n", total); exit(1); } void *produce(void *arg) { for(;;){ pthread_mutex_lock(&put.mutex); if(put.npro >= nitems){ pthread_mutex_unlock(&put.mutex); pthread_exit((void*)0) ; } buff[put.npro] = put.nval; put.npro++; put.nval++; Pthread_mutex_unlock(&put.mutex); Pthread_mutex_lock(&nready.mutex); if(nready.nready == 0) Pthread_cond_signal(&nready.cond); nready.nready ++; Pthread_mutex_unlock(&nready.mutex); *((int*)arg) += 1; } } void *consume(void *arg) { int i; for(i = 0; i < nitems; i++){ Pthread_mutex_lock(&nready.mutex); while(nready.nready == 0) Pthread_cond_wait(&nready.cond, &nready.mutex); nready.nready--; Pthread_mutex_unlock(&nready.mutex); if(buff[i] != i) printf("buff[%d] = %d\\n", i, buff[i]); } return (0); }
0
#include <pthread.h> int worker_count; static char cmd[256]; pthread_mutex_t worker_lock; static void *worker_thread(void* arg); int main(int argc, char **argv) { int i; int result; pthread_t tid; if ((result=pthread_mutex_init(&worker_lock, 0)) != 0) { fprintf(stderr, "file: ""malloc_test.c"", line: %d, " "init_pthread_lock fail, errno: %d, error info: %s", 26, result, strerror(result)); return result; } snprintf(cmd, sizeof(cmd), "ps auxww | grep %s | grep -v grep", argv[0]); worker_count = WORKER_COUNT; for (i=0; i<WORKER_COUNT; i++) { if ((result=pthread_create(&tid, 0, worker_thread, 0)) != 0) { fprintf(stderr, "file: ""malloc_test.c"", line: %d, " "pthread_create fail, errno: %d, error info: %s", 38, result, strerror(result)); return result; } } pthread_join(tid, 0); while (worker_count > 0) { usleep(100); } return 0; } static void *worker_thread(void* arg) { int i; int k; char *p; for(i=1; i<=TASK_COUNT; i++) { for(k=1024; k<=4 * 1024; k++) { p = (char *)malloc(k * 10); assert(p != 0); free(p); } } pthread_mutex_lock(&worker_lock); worker_count--; pthread_mutex_unlock(&worker_lock); return 0; }
1
#include <pthread.h> struct queue_node_s *next; struct queue_node_s *prev; char c; } queue_node_t; struct queue_node_s *front; struct queue_node_s *back; pthread_mutex_t lock; } queue_t; void *producer_routine(void *arg); void *consumer_routine(void *arg); long g_num_prod; pthread_mutex_t g_num_prod_lock; int main(int argc, char **argv) { queue_t queue; pthread_t producer_thread, consumer_thread; void *thread_return = 0; int result = 0; printf("Main thread started with thread id %lu\\n", pthread_self()); memset(&queue, 0, sizeof(queue)); pthread_mutex_init(&queue.lock, 0); g_num_prod = 1; result = pthread_create(&producer_thread, 0, producer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create producer thread: %s\\n", strerror(result)); exit(1); } printf("Producer thread started with thread id %lu\\n", producer_thread); result = pthread_detach(producer_thread); if (0 != result) fprintf(stderr, "Failed to detach producer thread: %s\\n", strerror(result)); result = pthread_create(&consumer_thread, 0, consumer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\\n", strerror(result)); exit(1); } result = pthread_join(consumer_thread, &thread_return); if (0 != result) { fprintf(stderr, "Failed to join consumer thread: %s\\n", strerror(result)); pthread_exit(0); } printf("\\nPrinted %lu characters.\\n", *(long*)thread_return); free(thread_return); pthread_mutex_destroy(&queue.lock); pthread_mutex_destroy(&g_num_prod_lock); return 0; } void *producer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *new_node_p = 0; pthread_t consumer_thread; int result = 0; char c; result = pthread_create(&consumer_thread, 0, consumer_routine, queue_p); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\\n", strerror(result)); exit(1); } result = pthread_detach(consumer_thread); if (0 != result) fprintf(stderr, "Failed to detach consumer thread: %s\\n", strerror(result)); for (c = 'a'; c <= 'z'; ++c) { new_node_p = malloc(sizeof(queue_node_t)); new_node_p->c = c; new_node_p->next = 0; pthread_mutex_lock(&queue_p->lock); if (queue_p->back == 0) { assert(queue_p->front == 0); new_node_p->prev = 0; queue_p->front = new_node_p; queue_p->back = new_node_p; } else { assert(queue_p->front != 0); new_node_p->prev = queue_p->back; queue_p->back->next = new_node_p; queue_p->back = new_node_p; } pthread_mutex_unlock(&queue_p->lock); sched_yield(); } pthread_mutex_lock(&g_num_prod_lock); --g_num_prod; pthread_mutex_unlock(&g_num_prod_lock); return (void*) 0; } void *consumer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *prev_node_p = 0; long count = 0; printf("Consumer thread started with thread id %lu\\n", pthread_self()); pthread_mutex_lock(&queue_p->lock); pthread_mutex_lock(&g_num_prod_lock); while(queue_p->front != 0 || g_num_prod > 0) { pthread_mutex_unlock(&g_num_prod_lock); if (queue_p->front != 0) { prev_node_p = queue_p->front; if (queue_p->front->next == 0) queue_p->back = 0; else queue_p->front->next->prev = 0; queue_p->front = queue_p->front->next; pthread_mutex_unlock(&queue_p->lock); printf("%c", prev_node_p->c); free(prev_node_p); ++count; } else { pthread_mutex_unlock(&queue_p->lock); sched_yield(); } pthread_mutex_lock(&queue_p->lock); pthread_mutex_lock(&g_num_prod_lock); } pthread_mutex_unlock(&g_num_prod_lock); pthread_mutex_unlock(&queue_p->lock); return (void*) count; }
0
#include <pthread.h> static pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t c1 = PTHREAD_COND_INITIALIZER; static int value = 1; static void *threadFunc1(void *arg) { while(value <= 100) { pthread_mutex_lock(&m1); while(value % 2 == 0) { pthread_cond_wait(&c1, &m1); } if (value > 100) { return 0; } fprintf(stdout, "%d\\n", value); value++; pthread_mutex_unlock(&m1); pthread_cond_signal(&c1); } return 0; } static void *threadFunc2(void *arg) { while(value <= 100) { pthread_mutex_lock(&m1); while(value % 2 == 1) { pthread_cond_wait(&c1, &m1); } if (value > 100) { return 0; } fprintf(stdout, "%d\\n", value); value++; pthread_mutex_unlock(&m1); pthread_cond_signal(&c1); } return 0; } static void *threadFunc(void *arg) { int odd = *((int *)arg); while(value <= 100) { pthread_mutex_lock(&m1); if(odd == 1) { while(value % 2 == 0) { pthread_cond_wait(&c1, &m1); } } else { while(value % 2 == 1) { pthread_cond_wait(&c1, &m1); } } if (value > 100) { return 0; } fprintf(stdout, "%d\\n", value); value++; pthread_mutex_unlock(&m1); pthread_cond_signal(&c1); } return 0; } int main(int argc, char *argv[]) { pthread_t t1, t2; int s; int odd = 1, even = 0; s = pthread_create(&t1, 0, threadFunc, &odd); if(s != 0) { fprintf(stderr, "pthread_create failed\\n"); } s = pthread_create(&t2, 0, threadFunc, &even); if(s != 0) { fprintf(stderr, "pthread_create failed\\n"); } s = pthread_join(t1, 0); if(s != 0) { fprintf(stderr, "pthread_join failed\\n"); } s = pthread_join(t2, 0); if(s != 0) { fprintf(stderr, "pthread_join failed\\n"); } exit(0); }
1
#include <pthread.h> int receivingMsgStatus = 5; struct message msg; int runingStatus = 1; pthread_mutex_t statusMutex; struct MsgsQueueData serverQueueData; void setRunningStatus(const int status) { pthread_mutex_lock (&statusMutex); runingStatus = status; pthread_mutex_unlock (&statusMutex); } bool sendMsgServer(const char *msgTxt) { if(msgTxt == 0) { writeToLog("ERROR sndMsgServer(): Can't send message, the given message text is NULL\\n", "MSGS_QUEUE_SERVER"); return 0; } if(strlen(msgTxt) == 0) { writeToLog("ERROR sndMsgServer(): Can't send message, the given message text is empty\\n", "MSGS_QUEUE_SERVER"); return 0; } setRunningStatus(2); struct message answer; bzero(answer.mtxt, MSG_STR_MAX_LEN); answer.mtype = 1; strcpy(answer.mtxt, msgTxt); if (msgsnd(serverQueueData.queueID, &answer, sizeof(answer.mtxt), 0) == ERROR) { writeToLog2("ERROR sndMsgServer(): Can't send a messages to queue: ", strerror(errno), "MSGS_QUEUE_SERVER"); setRunningStatus(3); return 0; } setRunningStatus(1); return 1; } char* receiveMsgServer() { pthread_mutex_lock (&statusMutex); if(receivingMsgStatus == 4) { receivingMsgStatus = 5; pthread_mutex_unlock (&statusMutex); return serverQueueData.receivedMsgTxt; } pthread_mutex_unlock (&statusMutex); return ""; } bool initQueueServer() { bzero(serverQueueData.receivedMsgTxt, MSG_STR_MAX_LEN); bzero(msg.mtxt, MSG_STR_MAX_LEN); if(createQueueMsgsFile()) serverQueueData.queueID = initMsgsQueue(0644 | IPC_CREAT); return (serverQueueData.queueID != ERROR); } const int getRunningStatus() { int status; pthread_mutex_lock (&statusMutex); status = runingStatus; pthread_mutex_unlock (&statusMutex); return status; } void runQueue() { while(getRunningStatus() != 3) { if (getRunningStatus() == 2) continue; if (getRunningStatus() == 1) { if (msgrcv(serverQueueData.queueID, &msg, sizeof(msg.mtxt), 0, 0) != ERROR) { strcpy(serverQueueData.receivedMsgTxt, msg.mtxt); pthread_mutex_lock (&statusMutex); receivingMsgStatus = 4; pthread_mutex_unlock (&statusMutex); bzero(msg.mtxt, MSG_STR_MAX_LEN); } else if(errno != EIDRM) { writeToLog2("ERROR runQueue(): Can't get a messages from queue: ", strerror(errno), "MSGS_QUEUE_SERVER"); break; } } } } void deleteMsgsQueue() { setRunningStatus(3); sleep(1); if (msgctl(serverQueueData.queueID, IPC_RMID, 0) == ERROR) { writeToLog2("ERROR deleteMsgsQueue(): Can't delete the messages queue: ", strerror(errno), "MSGS_QUEUE_SERVER"); } } void deleteQueueMsgsFile() { if(remove(FILE_NAME) == ERROR) { writeToLog2("ERROR: createQueueMsgsFile(): Can't remove the file for the messages queue: ", strerror(errno), "MSGS_QUEUE_SERVER"); } } void deleteQueue() { deleteMsgsQueue(); deleteQueueMsgsFile(); }
0
#include <pthread.h> struct rsmgmt_pkt * rsmgmt_nl_Dequeue(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *head = rsmgmt->rmpkt_nl; pthread_mutex_lock(&rsmgmt->rsmgmt_nl_mutex); if(head == 0){ printf("rsmgmt_pkt : head is NULL\\n"); goto _Exit; } if(head->valid == QUEUE_EMPTY){ head = 0; }else if(head->valid == QUEUE_OCCUPIED){ printf("rsmgmtbuf_Dequeue : QUEUE_OCCUPIED\\n"); rsmgmt->rmpkt_nl = head->link; head = 0; } _Exit: pthread_mutex_unlock(&rsmgmt->rsmgmt_nl_mutex); return head; } int rsmgmt_nl_FreeDequeue(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *head = rsmgmt->rmpkt_nl; pthread_mutex_lock(&rsmgmt->rsmgmt_nl_mutex); if(head->valid != QUEUE_OCCUPIED){ head->valid = QUEUE_EMPTY; } rsmgmt->rmpkt_nl = head->link; pthread_mutex_unlock(&rsmgmt->rsmgmt_nl_mutex); return 0; } struct rsmgmt_pkt * rsmgmt_nl_NewQueue(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *head = rsmgmt->rmpkt_nl; pthread_mutex_lock(&rsmgmt->rsmgmt_nl_mutex); if(head == 0){ printf("rsmgmt_nl_Newqueue: head is NULL\\n"); goto _Exit; } while(head->valid != QUEUE_EMPTY){ head = head->link; if(head->link == rsmgmt->rmpkt_nl){ printf("rsmgmt_nl_Newqueue: buffer is FULL\\n"); head = 0; goto _Exit; } } _Exit: pthread_mutex_unlock(&rsmgmt->rsmgmt_nl_mutex); return head; } int rsmgmt_nl_SetEnqueue(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *head = rsmgmt->rmpkt_nl; pthread_mutex_lock(&rsmgmt->rsmgmt_nl_mutex); head->valid = QUEUE_AVAILABLE; pthread_mutex_unlock(&rsmgmt->rsmgmt_nl_mutex); return 0; } struct rsmgmt_pkt * Net_nodeAllocate(struct rsmgmt_pkt *head,int size) { struct rsmgmt_pkt *new; if((new = malloc(size)) == 0){ printf ("Unable to alloc memory for rsmgmt_pkt !!!\\n"); return 0; } memset(new,0,sizeof(struct rsmgmt_pkt)); if(head == 0){ return new; } head->link = new; return new; } void rsmgmt_mem_free(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *rmpkt = 0; struct rsmgmt_pkt *next = 0; rmpkt = rsmgmt->rmpkt_nl; while(1){ if(rmpkt == 0) break; if(rmpkt->link == rsmgmt->rmpkt_nl){ free(rmpkt); break; } next = rmpkt->link; free(rmpkt); rmpkt = next; } } int rsmgmt_mem_init(struct rsmgmt_wave *rsmgmt) { struct rsmgmt_pkt *rmpkt = 0; int i; if((rmpkt = Net_nodeAllocate(rmpkt,sizeof(struct rsmgmt_pkt))) != 0){ rsmgmt->rmpkt_nl = rmpkt; for(i=0; i<WAVE_RM_MAX_QUEUE; i++){ if((rmpkt = Net_nodeAllocate(rmpkt,sizeof(struct rsmgmt_pkt))) == 0){ printf("[%d] rsmgmt_pkt Queue allocate fail !!!\\n",i); rsmgmt_mem_free(rsmgmt); return -1; } } rmpkt->link = rsmgmt->rmpkt_nl; if(pthread_mutex_init(&rsmgmt->rsmgmt_nl_mutex,0)){ printf("rsmgmt mutext init error\\n"); rsmgmt_mem_free(rsmgmt); return -1; } } return 0; } int rsmgmt_mutex_init(struct rsmgmt_wave *rsmgmt) { if(pthread_mutex_init(&rsmgmt->bsmMsg_mutex,0)){ printf("bsmMsg_mutex init error\\n"); goto _Exit; } if(pthread_mutex_init(&rsmgmt->wsmHeader_mutex,0)){ printf("wsmHeader_mutex init error\\n"); goto _Exit; } return 0; _Exit: pthread_mutex_destroy(&rsmgmt->bsmMsg_mutex); pthread_mutex_destroy(&rsmgmt->wsmHeader_mutex); return -1; }
1
#include <pthread.h> void ft_malloc_display(void) { t_mempage *page; t_memblock *block; size_t p; size_t index; index = 0; ft_putstr("--- START ---\\n"); page = ft_page_store(0, READ); while (page) { ft_printf("page %u informations: size: %lu - blocks count: %lu%s%p\\n", index++, page->size, page->count, " - address: ", page, p = 0); while (p < page->count) { block = &page->blocks[p]; ft_printf("[%3lu]%s%p%s%6lu%s%s%s%lu\\n", p, "\\taddress: ", block->content, " - size: ", page->blocksize, " - used: ", (block->used_size > 0) ? "yes" : "no", " - used size: ", block->used_size); p++; } ft_putchar('\\n'); page = page->next; } ft_putstr("--- END ---\\n"); } void *ft_malloc(size_t const size) { t_mempage *page; t_memblock *block; pthread_mutex_t *lock; if (!size) return (0); lock = ft_memlock(); pthread_mutex_lock(lock); page = ft_page_store(0, READ); block = ft_block_search(page, size); if (block) { block->used_size = size; pthread_mutex_unlock(lock); return (block->content); } pthread_mutex_unlock(lock); return (0); }
0
#include <pthread.h> struct _task{ callback cb; void *args; struct _task *next; }; struct _pool{ int thread_number; int task_queue_size; int max_queue_size; int running; pthread_t *pt; task *task_queue_head; pthread_mutex_t queue_mutex; pthread_cond_t queue_cond; }; void *routine(void *args); void pool_init(pool *p, int thread_number, int max_queue_size) { p->thread_number = thread_number; p->max_queue_size = max_queue_size; p->task_queue_size = 0; p->task_queue_head = 0; p->pt = (pthread_t *)malloc(sizeof(pthread_t)*p->thread_number); if(!p->pt){ perror("malloc pthread_t array failed"); exit(1); } pthread_mutex_init(&p->queue_mutex,0); pthread_cond_init(&p->queue_cond,0); for(int i = 0; i < p->thread_number; i++) { pthread_create (&(p->pt[i]), 0, routine, (void *)p); } p->running = 1; } void pool_clean(pool *p) { if(!p->running) return; p->running = 0; pthread_cond_broadcast(&p->queue_cond); for (int i = 0; i < p->thread_number; ++i) { pthread_join(p->pt[i],0); } free(p->pt); task *temp; while((temp=p->task_queue_head)!=0){ p->task_queue_head = p->task_queue_head->next; free(temp); } pthread_mutex_destroy(&p->queue_mutex); pthread_cond_destroy(&p->queue_cond); free(p); p = 0; } int _pool_add_task(pool *p, task *t) { int ret = 0; pthread_mutex_lock(&p->queue_mutex); if(p->task_queue_size>=p->max_queue_size){ pthread_mutex_unlock(&p->queue_mutex); ret = 1; return ret; } task *temp = p->task_queue_head; if(temp!=0){ while(temp->next!=0){ temp = temp->next; } temp->next = t; }else{ p->task_queue_head = t; pthread_cond_signal(&p->queue_cond); } p->task_queue_size++; pthread_mutex_unlock(&p->queue_mutex); return ret; } int pool_add_task(pool *p, callback cb, void *data) { int ret = 0; task *t = (task *)malloc(sizeof(task)); t->cb = cb; t->args = data; t->next = 0; if((ret=_pool_add_task(p,t))>0){ fprintf(stderr,"add wroker failed,reaching max size of task queue\\n"); return ret; } return ret; } void *routine(void *args) { pool *p = (pool *)args; task *t; fprintf(stdout,"thread_id:%ld\\n",syscall(SYS_gettid)); while(1){ pthread_mutex_lock(&p->queue_mutex); while(p->task_queue_size==0 && p->running){ pthread_cond_wait(&p->queue_cond,&p->queue_mutex); } if(!p->running){ pthread_mutex_unlock(&p->queue_mutex); fprintf(stdout,"thread:%d will exit pool_destroy\\n",(int)pthread_self()); pthread_exit(0); } t = p->task_queue_head; p->task_queue_head = p->task_queue_head->next; p->task_queue_size--; pthread_mutex_unlock(&p->queue_mutex); t->cb(t->args); } pthread_exit(0); } void *callbacktest(void *args) { fprintf(stdout,"from thread:%d---passed parameter:%d\\n",(int)pthread_self(),(int)(*(int *)(args))); } int main() { pool *p = (pool *)malloc(sizeof(pool)); if(p==0){ fprintf(stderr,"malloc pool failed\\n"); } pool_init(p,4,10); int args[10]; for (int i=0;i<10;i++){ args[i] = i; } for (int i=0;i<10;i++){ pool_add_task(p,&callbacktest,&args[i]); } sleep(10); pool_clean(p); return 0; }
1
#include <pthread.h> pthread_mutex_t mux; pthread_cond_t cond_full; pthread_cond_t cond_empty; int qsize; int static counter = 0; void* producer(void* argv) { int i; for (i = 0; i < 3; i ++) { pthread_mutex_lock(&mux); while (qsize == 1) pthread_cond_wait(&cond_full, &mux); printf(" produce %d, item, qsize = %d\\n", counter , qsize); counter ++; pthread_cond_signal(&cond_empty); qsize ++; pthread_mutex_unlock(&mux); } } void* consumer(void* argv) { int val, i; for (i = 0; i < 3; i ++) { pthread_mutex_lock(&mux); if (qsize == 0) pthread_cond_wait(&cond_empty, &mux); printf("consume %d, item, qsize = %d \\n",val, qsize); pthread_cond_signal(&cond_full); qsize --; pthread_mutex_unlock(&mux); } } int main() { int i, ret1, ret2; pthread_t prod[2]; pthread_t cons[2]; qsize = 0; pthread_mutex_init(&mux, 0); pthread_cond_init(&cond_full, 0); pthread_cond_init(&cond_empty, 0); for (i = 0; i < 2; i ++) { ret1 = pthread_create(&prod[i], 0, producer, 0); ret2 = pthread_create(&cons[i], 0, consumer, 0); if (ret1 != 0 || ret2 != 0) { exit(-1); } } for (i = 0; i < 2; i ++) { pthread_join(prod[i], 0); pthread_join(cons[i], 0); } pthread_mutex_destroy(&mux); pthread_cond_destroy(&cond_full); pthread_cond_destroy(&cond_empty); }
0
#include <pthread.h> int fd_mouse; pthread_mutex_t click_mutex = PTHREAD_MUTEX_INITIALIZER; void *thr_fn(void *arg) { fd_mouse = open_mouse(); cx = screen_w / 2; cy = screen_h / 2; while(1) { move_mouse(&fd_mouse); if(buf_mouse[0] & 0x1) { memset(buf_mouse, 0, 8); move_mouse(&fd_mouse); if((buf_mouse[0] & 0x1) == 0) { pthread_mutex_lock(&click_mutex); click_switch = 0; pthread_mutex_unlock(&click_mutex); } } } return; } void create_mouse_thread(pthread_t *ntid) { int err; err = pthread_create(ntid, 0, thr_fn, 0); if(err != 0) { fprintf(stderr, "Error:%d:%s", err, strerror(err)); exit(0); } return; }
1
#include <pthread.h> void search_by_thread( void* ptr); { char* start_ptr; char* end_ptr; int thread_id; int slice_size; char match_str[15]; } thread_data; pthread_mutex_t mutex; int main() { FILE* fRead; char line[15]; char search_str[15]; char* array_ptr; char* temp_ptr; int i = 0; int j = 0; int fchar; int num_inputs = 0; int num_threads; int num_slices; int slice_size = 0; char file_name[] = "fartico_aniketsh_input_partA.txt"; char alt_file[128]; printf("\\n(fartico_aniketsh_input_partA.txt)\\n"); printf("ENTER ALT FILENAME OR (ENTER TO RUN): "); gets(alt_file); printf("\\n"); if(strcmp(alt_file, "") != 0) { strcpy(file_name, alt_file); } fRead = fopen(file_name, "r"); if(fRead == 0) { perror("FILE OPEN FAILED\\n"); exit(1); } while(EOF != (fchar = fgetc(fRead))) { if ( fchar == '\\n') { ++num_inputs; } } if ( fchar != '\\n' ) { ++num_inputs; } fclose(fRead); if ( num_inputs > 4 ) { num_inputs = num_inputs -3; } fRead = fopen(file_name, "r"); if(fRead == 0) { perror("FILE OPEN FAILED\\n"); exit(1); } fgets(search_str, sizeof(search_str), fRead); num_threads = atoi(search_str); fgets(search_str, sizeof(search_str), fRead); num_slices = atoi(search_str); fgets(search_str, sizeof(search_str), fRead); array_ptr = malloc(num_inputs * sizeof(line)); memset(array_ptr, '\\0', num_inputs * sizeof(line)); temp_ptr = array_ptr; slice_size = num_inputs / num_slices; while(fgets(line, sizeof(line), fRead)) { strcpy(&temp_ptr[i*15], line); i++; } pthread_t thread_array[num_threads]; thread_data data_array[num_threads]; int k; for( k = 0; k < num_threads; ++k) { data_array[k].start_ptr = &array_ptr[k * slice_size * 15]; data_array[k].end_ptr = &array_ptr[(k+1) * slice_size * 15]; data_array[k].thread_id = k; data_array[k].slice_size = slice_size; strcpy(data_array[k].match_str, search_str); } pthread_mutex_init(&mutex, 0); for( k = 0; k < num_threads; ++k) { pthread_create(&thread_array[k], 0, (void *) & search_by_thread, (void *) &data_array[k]); } for( k =0; k < num_threads; ++k) { pthread_join(thread_array[k], 0); } pthread_mutex_destroy(&mutex); printf("\\n"); return 0; } void search_by_thread( void* ptr) { thread_data* data; data = (thread_data *) ptr; int i = 0; int position_i = -1; int slice_i = -1; char found_i[] = "no"; char* temp_ptr = data->start_ptr; while( &temp_ptr[i*15] < data->end_ptr) { if( strcmp(&temp_ptr[i*15], data->match_str) == 0) { position_i = (data->thread_id * data->slice_size) + i; slice_i = data->thread_id; strcpy(found_i, "yes"); } i = i +1; } pthread_mutex_lock(&mutex); printf("thread %d, found %s, slice %d, position %d\\n", data->thread_id,found_i, slice_i, position_i); pthread_mutex_unlock(&mutex); pthread_exit(0); }
0
#include <pthread.h> int NUM_THREADS=4; int a[10000000]; double totalsum=0.0; pthread_mutex_t mutex; int print_data=0; int validation=1; double get_time(struct timeval tv_start,struct timeval tv_end) { return (double)(tv_end.tv_sec-tv_start.tv_sec)+((double)tv_end.tv_usec-tv_start.tv_usec)/1000000.0; } void initialize() { int i; for(i=0;i<10000000;i++) a[i]=rand(); } void *thread_func(void *arg) { int i=0; double sum=0.0; long my_id=(long)arg; int chunk=10000000/NUM_THREADS; int start=my_id*chunk; int end=start+chunk; if(my_id==(NUM_THREADS-1)) end=10000000; for(i=start;i<end;i++){ sum+=sqrt((double)(a[i])); } pthread_mutex_lock(&mutex); totalsum+=sum; pthread_mutex_unlock(&mutex); return 0; } void validate() { } void print() { } int main(int argc,char **argv) { int i; struct timeval tv_start; struct timeval tv_end; pthread_t *tids=0; void *status; int result; if(argc>1){ NUM_THREADS=atoi(argv[1]); } printf("Using %d threads...\\n",NUM_THREADS); tids=(pthread_t *)malloc(sizeof(pthread_t) * NUM_THREADS); if(tids==0){ fprintf(stderr,"ERROR[%s:%d]\\n","sum_par.c",74); exit(1); } initialize(); gettimeofday(&tv_start,0); for(i=1;i<NUM_THREADS;i++){ result=pthread_create(&tids[i],0,thread_func,(void *)i); if(result!=0){ printf("Error(%d) occurred in pthread_create.\\n",result); exit(1); } } thread_func(0); for(i=1;i<NUM_THREADS;i++){ pthread_join(tids[i],&status); } gettimeofday(&tv_end,0); printf("-- Parallel Version ==\\nsum: %.4lf\\n\\n",totalsum); printf("Execution with %d threads: %lf sec.\\n",NUM_THREADS,get_time(tv_start,tv_end)); if(validation){ validate(); } if(print_data){ } return 0; }
1
#include <pthread.h> struct products { int buffer[16]; pthread_mutex_t lock; int readpos,writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init_buffer(struct products *b) { pthread_mutex_init(&b->lock,0); pthread_cond_init(&b->notempty,0); pthread_cond_init(&b->notfull,0); b->readpos=0; b->writepos=0; } void write(struct products *b , int data ) { pthread_mutex_lock(&b->lock); while((b->writepos+1)%16==b->readpos) { printf("wait for not full\\n"); pthread_cond_wait(&b->notfull,&b->lock); } b->buffer[b->writepos]=data; b->writepos++; if(b->writepos>=16) b->writepos=0; pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int read(struct products *b) { int data; pthread_mutex_lock(&b->lock); while(b->writepos==b->readpos) { printf("wait for not empty\\n"); pthread_cond_wait(&b->notempty,&b->lock); } data=b->buffer[b->readpos]; b->readpos++; if(b->readpos>=16) b->readpos=0; pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct products buffer_data; void *producter(void *data) { int n; for(n=0;n<50;n++) { printf("write-->%d\\n",n); write(&buffer_data,n); } write(&buffer_data,(-1)); printf("producter stopped\\n"); return 0; } void *consumer(void *data) { int d; while(1) { d=read(&buffer_data); if(d==(-1)) break; printf(" %d-->read\\n",d); } printf("consumer stopped!\\n"); return 0; } int main(void) { pthread_t th_a,th_b; void *retval; int ret; init_buffer(&buffer_data); ret=pthread_create(&th_a,0,(void *)producter,0); if(ret!=0) { perror("pthread producter create"); exit(1); } ret=pthread_create(&th_b,0,(void *)consumer,0); if(ret!=0) { perror("pthread consumer create"); exit(1); } pthread_join(th_a,&retval); pthread_join(th_b,&retval); exit(0); }
0
#include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int contador = 0; int buffer[5]; int N = 5; int consumidos[20]; void *productor(void *argv){ int num_items = 0; int i; int pos_buffer = 0; srand(time(0)); while( num_items < 20){ usleep(rand()%100000); pthread_mutex_lock(&mtx); if (contador != N){ buffer[pos_buffer] = rand()%10; printf("P: METI EN BUFFER %d \\n ",buffer[pos_buffer]); pos_buffer= (++pos_buffer) % N; contador++; fflush(stdout); num_items++; } pthread_mutex_unlock(&mtx); } } void *consumidor(void *argv){ int num_items = 0; int i=0; int pos_buffer = 0; srand(time(0)); while (num_items < 20) { usleep(rand()%100000); pthread_mutex_lock(&mtx); if(contador !=0){ consumidos[i] = buffer[pos_buffer]; printf("C: LEI DEL BUFFER %d \\n ",buffer[pos_buffer]); pos_buffer = (++pos_buffer) % N; contador--; num_items++; } pthread_mutex_unlock(&mtx); } } int main(int argc, char *argv[]){ pthread_t product; pthread_t consum; pthread_create(&product,0,productor,0); sleep(1); pthread_create(&consum,0,consumidor,0); pthread_join(product,0); pthread_join(consum,0); pthread_mutex_destroy(&mtx); }
1
#include <pthread.h> void *producer(void* arg); void *consumer(void* arg); pthread_mutex_t mutex; int running =1; int buff=0; int main() { pthread_t pro,consu; pthread_mutex_init(&mutex,0); if(pthread_create(&pro,0,(void*)producer,0) <0) { printf("线程创建失败\\n" ); } if(pthread_create(&consu,0,(void*)consumer,0) <0) { printf("线程创建失败\\n"); } usleep(10000); running=0; pthread_join(pro,0); pthread_join(consu,0); pthread_mutex_destroy(&mutex); return 0; } void *producer(void* arg){ while(running) { pthread_mutex_lock(&mutex); buff++; printf("生产者生产的总数为 : %d\\n",buff); pthread_mutex_unlock(&mutex); usleep(1); } } void *consumer(void* arg){ while(running) { pthread_mutex_lock(&mutex); buff--; printf("消费者消费后的总数为 : %d\\n",buff); pthread_mutex_unlock(&mutex); usleep(10); } }
0
#include <pthread.h> struct critical_data { int len; char buf[100]; }data[2]; pthread_mutex_t mutex; void * write_thread (void *p) { printf("\\n In Write thread\\n"); if(pthread_mutex_lock(&mutex)==0) { printf("\\n\\t Entering critical section in Write thread \\n"); strcpy(data[0].buf,"Veda Solutions"); data[0].len=strlen("Veda Solutions"); strcpy(data[1].buf,"Solutions"); sleep(4); data[1].len=strlen("Solutions"); pthread_mutex_unlock(&mutex); printf ("\\t Leaving critical section in Write thread\\n"); } printf(" Write job is over\\n"); pthread_exit(0); } void * read_thread(void *p) { struct timespec mytime; time_t currTime = time(0); mytime.tv_sec = time(0)+3; mytime.tv_nsec = 0; printf("\\n In Read thread \\n"); if(pthread_mutex_timedlock(&mutex,&mytime)==0) { printf("\\n\\t Entering critical section in Read thread \\n"); printf("\\n\\t %d %s \\n",data[0].len,data[0].buf); printf("\\n\\t %d %s \\n",data[1].len,data[1].buf); pthread_mutex_unlock(&mutex); printf ("\\t Leaving critical section in Read thread\\n"); } else printf ("\\t Mutex not avalible for Read thread in %d seconds ...",time(0) - currTime); printf("\\n Read job is over\\n"); pthread_exit(0); } int main () { pthread_t tid1,tid2; int rv; pthread_mutex_init(&mutex,0); rv = pthread_create(&tid1, 0, write_thread, 0); if(rv) puts("Failed to create thread"); rv = pthread_create(&tid2, 0, read_thread, 0); if(rv) puts("Failed to create thread"); pthread_join(tid1,0); pthread_join(tid2,0); puts(" Exit Main"); return 0; }
1
#include <pthread.h> pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER; void prepare(void) { printf("prepareing locks,,,\\n"); pthread_mutex_lock(&lock1); pthread_mutex_lock(&lock2); } void parent(void) { printf("parent unlocking locks,,,\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void child(void) { printf("child unlocking locks,,,\\n"); pthread_mutex_unlock(&lock1); pthread_mutex_unlock(&lock2); } void *thr_fn(void *arg) { printf("thread started,,,\\n"); pause(); return 0; } int main(void) { int err; pid_t pid; pthread_t tid; if((err = pthread_atfork(prepare, parent, child)) != 0) { printf("pthread atfork error\\n"); exit(0); } err = pthread_create(&tid, 0, thr_fn, 0); if(err != 0) { printf("pthread create error\\n"); exit(0); } sleep(2); printf("parent about to fork...\\n"); if((pid = fork()) < 0) { printf("fork error\\n"); exit(0); } else if(pid == 0) { printf("child returned from fork..\\n"); } else { printf("parent returned from fork..\\n"); } exit(0); }
0
#include <pthread.h> void * thread_fcn(void * thread_arg); static int num_threads; static double sum, step; static pthread_mutex_t lock; int main(int argc, char *argv[]) { double start_time, end_time; double pi; num_threads = get_integer_environment("NUM_THREADS", 1, "number of threads"); int threadIDs[num_threads]; pthread_t threads[num_threads]; sum = 0.0; step = 1.0/(double) 400000000; start_time = get_time(); pthread_mutex_init(&lock, 0); for (int i = 0; i < num_threads; ++i) threadIDs[i] = i; for (int i = 0; i < num_threads; ++i) pthread_create(&threads[i], 0, thread_fcn, (void *) &threadIDs[i]); for (int i = 0; i < num_threads; ++i) pthread_join(threads[i], 0); pthread_mutex_destroy(&lock); pi = step * sum; end_time = get_time(); printf("parallel program results with %d threads:\\n", num_threads); printf("computed pi = %g (%17.15f)\\n",pi, pi); printf("difference between computed pi and math.h M_PI = %17.15f\\n", fabs(pi - 3.14159265358979323846)); printf("time to compute = %g seconds\\n", end_time - start_time); return 0; } void * thread_fcn(void * thread_arg) { int myID = * (int *) thread_arg; double x; double part_sum = 0.0; for (int i=myID; i < 400000000; i += num_threads) { x = (i+0.5)*step; part_sum += 4.0/(1.0+x*x); } pthread_mutex_lock(&lock); sum += part_sum; pthread_mutex_unlock(&lock); pthread_exit((void* ) 0); }
1
#include <pthread.h> LIST list_init(size_t capacity, bool allowdups); bool list_destroy(LIST *l); bool list_insert(LIST l, uintptr_t *item); bool list_remove(LIST l, uintptr_t *item); bool list_contains(LIST l, uintptr_t *item); bool list_get(LIST l, uintptr_t *item); bool list_look(LIST l, uintptr_t *item); size_t list_size(LIST l); bool list_empty(LIST l); bool list_full(LIST l); struct ListStruct { Node head; pthread_mutex_t mxlock; bool allowdups; size_t capacity; size_t count; }; struct NodeStruct { size_t key; Node next; uintptr_t data; }; LIST list_init(size_t capacity, bool allowdups) { LIST list = malloc(sizeof(*list)); if (list == 0) { errno = ENOMEM; return (0); } Node sentinel = malloc(sizeof(*sentinel)); if (sentinel == 0) { errno = ENOMEM; return (0); } sentinel->key = 0; sentinel->next = 0; sentinel->data = 0; list->head = sentinel; pthread_mutex_init(&list->mxlock, 0); list->allowdups = allowdups; list->capacity = (capacity == 0) ? (SIZE_MAX) : (capacity); list->count = 0; return (list); } bool list_destroy(LIST *l) { pthread_mutex_lock(&(*l)->mxlock); Node curr = (*l)->head, succ = 0; while (curr != 0) { succ = curr->next; free(curr); curr = succ; } pthread_mutex_unlock(&(*l)->mxlock); pthread_mutex_destroy(&(*l)->mxlock); free(*l); *l = 0; return (1); } static inline void list_traverse(Node head, size_t key, uintptr_t *item, Node *eprev, Node *ecurr) { Node prev = head, curr = prev->next; while (curr != 0) { if (curr->key == key && item != 0 && curr->data == *item) { break; } if (curr->key > key) { break; } prev = curr; curr = curr->next; } *eprev = prev; *ecurr = curr; } bool list_insert(LIST l, uintptr_t *item) { Node node = malloc(sizeof(*node)); if (node == 0) { errno = ENOMEM; return (0); } size_t key = *item; node->key = key; node->data = *item; pthread_mutex_lock(&l->mxlock); if (l->count == l->capacity) { pthread_mutex_unlock(&l->mxlock); free(node); errno = EXFULL; return (0); } Node prev, curr; list_traverse(l->head, key, item, &prev, &curr); if (!l->allowdups && curr != 0 && curr->key == key) { pthread_mutex_unlock(&l->mxlock); free(node); errno = EEXIST; return (0); } node->next = curr; prev->next = node; l->count++; pthread_mutex_unlock(&l->mxlock); return (1); } bool list_remove(LIST l, uintptr_t *item) { size_t key = *item; pthread_mutex_lock(&l->mxlock); Node prev, curr; list_traverse(l->head, key, item, &prev, &curr); if (curr != 0 && curr->key == key) { prev->next = curr->next; l->count--; pthread_mutex_unlock(&l->mxlock); free(curr); return (1); } pthread_mutex_unlock(&l->mxlock); errno = ENOENT; return (0); } bool list_contains(LIST l, uintptr_t *item) { size_t key = *item; pthread_mutex_lock(&l->mxlock); Node prev, curr; list_traverse(l->head, key, item, &prev, &curr); if (curr != 0 && curr->key == key) { pthread_mutex_unlock(&l->mxlock); return (1); } pthread_mutex_unlock(&l->mxlock); errno = ENOENT; return (0); } bool list_get(LIST l, uintptr_t *item) { pthread_mutex_lock(&l->mxlock); Node prev = l->head, curr = prev->next; if (curr == 0) { pthread_mutex_unlock(&l->mxlock); errno = ENOENT; return (0); } prev->next = curr->next; l->count--; pthread_mutex_unlock(&l->mxlock); *item = curr->data; free(curr); return (1); } bool list_look(LIST l, uintptr_t *item) { pthread_mutex_lock(&l->mxlock); Node curr = l->head->next; if (curr == 0) { pthread_mutex_unlock(&l->mxlock); errno = ENOENT; return (0); } *item = curr->data; pthread_mutex_unlock(&l->mxlock); return (1); } size_t list_size(LIST l) { pthread_mutex_lock(&l->mxlock); size_t size = l->count; pthread_mutex_unlock(&l->mxlock); return (size); } bool list_empty(LIST l) { pthread_mutex_lock(&l->mxlock); bool empty = (l->count == 0); pthread_mutex_unlock(&l->mxlock); return (empty); } bool list_full(LIST l) { pthread_mutex_lock(&l->mxlock); bool full = (l->count == l->capacity); pthread_mutex_unlock(&l->mxlock); return (full); }
0
#include <pthread.h> pthread_mutex_t thread_lock; int xfernum; int itemnum; int procnum; int THRESHOLD; int mis; int bcmax; int bc; int rawdata[100][30 + 1]; { int counter; int xferrec[100]; } cell; cell wholedata[30][30]; { cell stats; int items[30]; } list; void *large(void *arg); int main() { pthread_attr_t attr; pthread_t thread[procnum]; void *status; int i = 0, j = 0, k = 0; int tag_list[30]; int realitemnum = 0; printf("Enter xfernum, iternum, procnum, THRESHOLD: \\n"); scanf("%d, %d, %d, %d", &xfernum, &itemnum, &procnum, &THRESHOLD); mis = itemnum; bcmax = procnum; bc = 0; for (i = 0; i < xfernum; i++) { for (j = 0; j < 30; j++) { tag_list[j] = 0; } realitemnum = rand() % itemnum + 1; rawdata[i][0] = realitemnum; for (j = 1; j < realitemnum + 1; j++) { int temp; do { temp = rand() % 30; } while (tag_list[temp]); tag_list[temp] = 1; rawdata[i][j] = temp; } } for (i = 0; i < 30; i++) { for (j = 0; j < 30; j++) { wholedata[i][j].counter = 0; for (k = 0; k < xfernum; k++) { wholedata[i][j].xferrec[k] = 0; } } } pthread_mutex_init(&thread_lock, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < procnum; i++) { if (pthread_create(&thread[i], &attr, large, (void *)((long) i))) { printf("THREAD CREATION ERROR! %d\\n", i); return 0; } } pthread_attr_destroy(&attr); for (i = 0; i < procnum; i++) { if (pthread_join(thread[i], &status)) { printf("THREAD JOIN ERROR! %d\\n", i); return 0; } } pthread_mutex_destroy(&thread_lock); pthread_exit(0); } void *large(void *arg) { int i, j, k, s, p; int start, end, flag, count; int threadid, realitemnum; int next_index = 0; int tmp[xfernum]; int index_i = 0, index_j = 0, index = 0; cell local_array[30][30]; list curr_itemset[1000]; list next_itemset[1000]; threadid = (int)((long) arg); start = threadid * xfernum / procnum; end = (threadid + 1) * xfernum / procnum; for (i = 0; i < 30; i++) { for (j = 0; j < 30; j++) { local_array[i][j].counter = 0; for (k = 0; k < xfernum; k++) { local_array[i][j].xferrec[k] = 0; } } } for (i = start; i < end; i++) { realitemnum = rawdata[i][0]; for (j = 1; j < realitemnum + 1; j++) { for (k = j + 1; k < realitemnum + 1; k++) { if (rawdata[i][j] < rawdata[i][k]) { index_i = rawdata[i][j]; index_j = rawdata[i][k]; local_array[index_i][index_j].counter++; local_array[index_i][index_j].xferrec[i] = 1; } else if (rawdata[i][j] > rawdata[i][k]) { index_i = rawdata[i][k]; index_j = rawdata[i][j]; local_array[index_i][index_j].counter++; local_array[index_i][index_j].xferrec[i] = 1; } } } } pthread_mutex_lock(&thread_lock); for (i = 0; i < 30; i++) { for (j = 0; j < 30; j++) { wholedata[i][j].counter = wholedata[i][j].counter + local_array[i][j].counter; for (k = start; k < end; k++) { wholedata[i][j].xferrec[k] = local_array[i][j].xferrec[k]; } } } bc++; pthread_mutex_unlock(&thread_lock); while (bc < bcmax) { } start = threadid * 30 / procnum; end = (threadid + 1) * 30 / procnum; for (i = start; i < end; i++) { for (j = 0; j < 30; j++) { if (wholedata[i][j].counter >= THRESHOLD) { curr_itemset[index].items[0] = i; curr_itemset[index].items[1] = j; curr_itemset[index].stats.counter = wholedata[i][j].counter; for (k = 0; k < xfernum; k++) { curr_itemset[index].stats.xferrec[k] = wholedata[i][j].xferrec[k]; } index++; } } } for (s = 1; s < mis -1; s++) { for (i = 0; i < index-1; i++) { for (j = i+1; j < index; j++) { flag = 1; for (p = 0; p < s; p++) { if(curr_itemset[i].items[p] != curr_itemset[j].items[p]) { flag = 0; break; } } if (!flag) { break; } else { count = 0; for (k = 0; k < xfernum; k++) { tmp[k] = 0; } for (k = 0; k < xfernum; k++) { if (curr_itemset[i].stats.xferrec[k] == curr_itemset[j].stats.xferrec[k]) { if (curr_itemset[i].stats.xferrec[k] > 0) { count++; tmp[k] = 1; } } } if (count >= THRESHOLD) { next_itemset[next_index].stats.counter = count; for (k = 0; k < xfernum; k++) { next_itemset[next_index].stats.xferrec[k] = tmp[k]; } for(p = 0; p <=s; p++) { next_itemset[next_index].items[p] = curr_itemset[i].items[p]; } next_itemset[next_index].items[s+1] = curr_itemset[j].items[s]; next_index++; } } } } index = next_index; for (i = 0; i < next_index; i++) { curr_itemset[i].stats.counter = next_itemset[i].stats.counter; for (k = 0; k < xfernum; k++) { curr_itemset[i].stats.xferrec[k] = next_itemset[i].stats.xferrec[k]; } for (k = 0; k < s+2; k++) { curr_itemset[i].items[k] = next_itemset[i].items[k]; } } next_index = 0; } pthread_exit((void*) 0); }
1
#include <pthread.h> struct input { int num; int cT; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER; int curThread = 1; int timecount = 0; void *createThread(void *input) { struct input *in = input; int actual = in->cT; printf("Hello from thread No. %d!\\n", actual); int tcount = 0; int counter = 0; pthread_mutex_lock(&mutex2); timecount += in->num; pthread_mutex_unlock(&mutex2); pthread_t p1, p2; sleep(in->num); while(tcount < 2) { pthread_mutex_lock(&mutex); if(curThread < 10000) { curThread++; if (tcount == 0){ struct input first; first.num = ((int) rand()%10)+1; first.cT = curThread; pthread_create(&p1, 0, createThread, &first); counter++; } else { struct input sec; sec.num = ((int) rand()%10)+1; sec.cT = curThread; pthread_create(&p2, 0, createThread, &sec); counter++; } } pthread_mutex_unlock(&mutex); tcount++; } if(counter > 0) pthread_join(p1, 0); if(counter > 1) pthread_join(p2, 0); printf("Bye from thread No. %d!\\n", actual); } int main() { struct input start; start.num = 0; start.cT = curThread; createThread(&start); printf("Die Threads haben zusammen %d Sekunden gewartet.\\n", timecount); }
0
#include <pthread.h> struct buffer_t { char data[20]; int in; int out; pthread_mutex_t mutex; sem_t empty; sem_t full; } buffer; int totalItems = 0; pthread_t producer[2], consumer[2]; void *produce(void *tid) { int i; for(i=0; i<100; i++) { sem_wait(&(buffer.full)); pthread_mutex_lock(&(buffer.mutex)); buffer.data[buffer.in] = rand(); printf("producer %ld inserted an item: %d\\n", (long)tid, buffer.data[buffer.in]); buffer.in = (buffer.in + 1) % 20; sem_post(&(buffer.empty)); pthread_mutex_unlock(&(buffer.mutex)); } pthread_exit(0); } void *consume(void *tid) { int done = 0; int i; while(1) { sem_wait(&(buffer.empty)); pthread_mutex_lock(&(buffer.mutex)); if ((totalItems == 100 * 2)) { done = 1; pthread_mutex_unlock(&(buffer.mutex)); } else { printf("consumer %ld removing an item: %d\\n", (long)tid, buffer.data[buffer.out]); buffer.out = (buffer.out + 1) % 20; totalItems++; sem_post(&(buffer.full)); if ((totalItems == 100 * 2)) { done = 1; for(i=0; i < 2 - 1; i++) sem_post(&(buffer.empty)); } pthread_mutex_unlock(&(buffer.mutex)); } if (done) break; } pthread_exit(0); } int main(char *argc[], int argv) { int failed, i; void *status; srand(time(0)); pthread_mutex_init(&(buffer.mutex), 0); sem_init(&(buffer.empty), 0, 0); sem_init(&(buffer.full), 0, 20); buffer.in = 0; buffer.out = 0; for(i=0; i<2; i++) { failed = pthread_create(&(producer[i]), 0,produce, (void*)(long)i); if (failed) { printf("thread_create failed!\\n"); return -1; } } for(i=0; i<2; i++) { failed = pthread_create(&consumer[i], 0,consume,(void*)(long)i); if (failed) { printf("thread_create failed!\\n"); return -1; } } for(i=0; i<2; i++) pthread_join(producer[i], &status); for(i=0; i<2; i++) pthread_join(consumer[i], &status); pthread_exit(0); }
1
#include <pthread.h> int cnt; pthread_mutex_t mutex; } Counter; int k; float result; float *v, *v1, *v2; float **mat; Counter C; void* operation(void* arg) { int* argT = arg; int i = *argT; int j; pthread_detach(pthread_self()); v[i] = 0; for (j=0; j<k; j++) { v[i] += mat[i][j]*v2[i]; } pthread_mutex_lock(&C.mutex); C.cnt--; if (C.cnt == 0) { result = 0; for (i=0; i<k; i++) { result += v1[i]*v[i]; } fprintf(stdout, "Result = %f\\n", result); } pthread_mutex_unlock(&C.mutex); return (void*)0; } int main (int argc, char** argv) { int i, j; int* arg; pthread_t th; if (argc != 2) { fprintf(stderr, "Wrong number of arguments. Syntax: %s k", argv[0]); return -1; } k = atoi(argv[1]); v = (float*) malloc(k*sizeof(float)); v1 = (float*) malloc(k*sizeof(float)); v2 = (float*) malloc(k*sizeof(float)); mat = (float**) malloc(k*sizeof(float*)); for (i=0; i<k; i++) { mat[i] = (float*) malloc(k*sizeof(float)); } srand(time(0)); fprintf(stdout, "v1:\\n"); for (i=0; i<k; i++) { v1[i] = ((float) (rand() % 100) / 100) - 0.5; fprintf(stdout, "%f ", v1[i]); } fprintf(stdout, "\\n"); fprintf(stdout, "v2:\\n"); for (i=0; i<k; i++) { v2[i] = ((float) (rand() % 100) / 100) - 0.5; fprintf(stdout, "%f ", v2[i]); } fprintf(stdout, "\\n"); fprintf(stdout, "matr:\\n"); for (i=0; i<k; i++) { for (j=0; j<k; j++) { mat[i][j] = ((float) (rand() % 100) / 100) - 0.5; fprintf(stdout, "%f ", mat[i][j]); } fprintf(stdout, "\\n"); } fprintf(stdout, "\\n"); pthread_mutex_lock(&C.mutex); C.cnt = k; pthread_mutex_unlock(&C.mutex); for (i=0; i<k; i++) { arg = (int*) malloc(sizeof(int)); *arg = i; pthread_create(&th, 0, operation, arg); } pthread_exit(0); }
0
#include <pthread.h> void init_web(int fd) { char buff[4096]; sprintf(buff,"HTTP/1.0 200 OK\\r\\n" "Connection: Keep-Alive\\r\\n" "Server: Network camera\\r\\n" "Cache-Control: no-cache,no-store,must-revalidate,pre-check=0,max-age=0\\r\\n" "Pragma: no-cache\\r\\n" "Content-Type: multipart/x-mixed-replace;boundary=KK\\r\\n" ); if(write(fd,buff,strlen(buff)) != strlen(buff)){ fprintf(stderr, "write HTTP Error%s\\n", strerror(errno)); return ; } } void init_Whead(int fd,ssize_t size) { char buff[4096]; sprintf(buff,"\\r\\n--KK\\r\\n" "Content-Type: image/jpeg\\n" "Content-Length: %lu\\n\\n", size); if(write(fd,buff,strlen(buff)) != strlen(buff)){ fprintf(stderr, "write head error:%s\\n",strerror(errno)); return; } } void do_sever(int fd) { init_web(fd); while(1){ init_Whead(fd,buffer[okindex].length); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond,&mutex); print_picture(fd,tmp_buf,buffer[okindex].length); pthread_mutex_unlock(&mutex); } } int net_sever(char** port) { int sockfd = socket(AF_INET,SOCK_STREAM,0); if(sockfd < 0){ fprintf(stderr, "socket error:%s\\n",strerror(errno)); exit(1); } struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = htons(atoi(*port)); saddr.sin_addr.s_addr = INADDR_ANY; bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr)); pthread_init(); listen(sockfd,0); pthread_t th; int err = pthread_create(&th,&attr,do_forma,0); if(err < 0){ fprintf(stderr, "do_forma create error:%s\\n",strerror(errno)); } while(1){ int connfd = accept(sockfd,0,0); if(connfd < 0){ printf("connfd < 0\\n"); } create(connfd); } close(sockfd); return 0; }
1
#include <pthread.h> int buffer[100]; int nextp, nextc; int count=0; pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; void printfunction(void * ptr) { int count = *(int *) ptr; if (count==0) { printf("All items produced are consumed by the consumer \\n"); } else { for (int i=0; i<=count; i=i+1) { printf("%d, \\t",buffer[i]); } printf("\\n"); } } void *producer(void *ptr) { int item, flag=0; int in = *(int *) ptr; do { item = (rand()%7)%10; flag=flag+1; nextp=item; buffer[in]=nextp; in=((in+1)%100); while(count <= 100) { pthread_mutex_lock(&mutex); count=count+1; pthread_mutex_unlock(&mutex); printf("Count = %d in produced at Iteration = %d\\n", count, flag); } } while (flag<=100); pthread_exit(0); } void *consumer(void *ptr) { int item, flag=100; int out = *(int *) ptr; do { while (count >0) { nextc = buffer[out]; out=(out+1)%100; printf("\\t\\tCount = %d in consumer at Iteration = %d\\n", count,flag); pthread_mutex_lock(&mutex); count = count-1; pthread_mutex_unlock(&mutex); flag=flag-1; } if (count <= 0) { printf("consumer made to wait...faster than producer.\\n"); } }while (flag>=0); pthread_exit(0); } int main(void) { int in=0, out=0; pthread_t pro, con; pthread_create(&pro, 0, producer, &count); pthread_create(&con, 0, consumer, &count); pthread_join(pro, 0); pthread_join(con, 0); printfunction(&count); }
0
#include <pthread.h> struct queue* consprodqueue; int elementsToPush; int elementsToPop; void *consumerthreadfunction(void* arg){ pthread_mutex_t* mutex= (pthread_mutex_t*) arg; int size; int consumer=pthread_self(); int* ret=malloc(sizeof(int)); while(1){ pthread_mutex_lock(mutex); if(elementsToPop>0){ size=queue_pop_front(consprodqueue,ret); if(size!=-1){ elementsToPop--; printf("Consumer %d: Size: %d \\n",consumer, size); } } else { pthread_mutex_unlock(mutex); free(ret); return 0; } pthread_mutex_unlock(mutex); } } void *producerthreadfunction(void* arg){ pthread_mutex_t* mutex= (pthread_mutex_t*) arg; int randomvalue; int size; int producer=pthread_self(); while(1){ randomvalue=rand(); pthread_mutex_lock(mutex); if(elementsToPush>0){ size=queue_push_back(consprodqueue,randomvalue); if(size!=-1){ elementsToPush--; printf("Producer: %d Size: %d\\n",producer, size); } } else { pthread_mutex_unlock(mutex); printf("Finished!\\n"); return 0; } pthread_mutex_unlock(mutex); } } int len(char * str) { int grddorf=0; while (str[grddorf] != '\\0' && str[grddorf] != ' ' && grddorf != 4022500) ++grddorf; return grddorf; } int str2num(char * str) { int result = 0; int b = 1; int l = len(str); int i; for(i=1; i<l; ++i) b *= 10; for(i=0; i<l; ++i) { result += b * (int)(str[i] - '0'); b /= 10; } return result; } int strIsNum(char * str){ int l= len(str); int i; for(i=0; i<l; i++){ if(!isdigit(str[i])) return 0; } return 1; } int main(int argc, char ** argv, char ** envp) { if(argc!=4){ printf("\\nHUCH!! Das war wohl nichts..........\\nAm besten gleich noch einmal probieren!\\nUsage: ./consprod ANZAHL_PRODUCER ANZAHL_CONSUMER MENGE_DER_ELEMENTE\\nBeispiel:./consprod 4 2 10000\\n\\n"); return -1; } if(!strIsNum(argv[1]) || !strIsNum(argv[2]) || !strIsNum(argv[3])){ printf("\\nHUCH!! Das war wohl nichts..........\\nAm besten gleich noch einmal probieren!\\nUsage: ./consprod ANZAHL_PRODUCER ANZAHL_CONSUMER MENGE_DER_ELEMENTE\\nBeispiel:./consprod 4 2 10000\\n\\n"); return -1; } int prodAmount=str2num(argv[1]); int consAmount= str2num(argv[2]); elementsToPop=str2num(argv[3]); elementsToPush=elementsToPop; consprodqueue = queue_new(100); pthread_t prodT[prodAmount]; pthread_t consT[consAmount]; pthread_mutex_t mutex; pthread_mutex_init(&mutex, 0); int i; for(i=0;i<prodAmount;i++){ if(pthread_create(&prodT[i],0,producerthreadfunction,&mutex)){ fprintf(stderr, "Error creating Threads!\\n"); pthread_mutex_destroy(&mutex); queue_delete(consprodqueue); return 1; } else { printf("Create Prod: %d\\n", i); } } for(i=0;i<consAmount;i++){ if(pthread_create(&consT[i],0,consumerthreadfunction,&mutex)){ fprintf(stderr, "Error creating Threads!\\n"); pthread_mutex_destroy(&mutex); queue_delete(consprodqueue); return 1; } else { printf("Create Cons: %d\\n", i); } } for(i=0;i<prodAmount;i++){ if(pthread_join(prodT[i],0)){ fprintf(stderr, "Error joining Threads!\\n"); pthread_mutex_destroy(&mutex); queue_delete(consprodqueue); return 2; }else { printf("Join Prod: %d\\n", i); } } for(i=0;i<consAmount;i++){ if(pthread_join(consT[i],0)){ fprintf(stderr, "Error joining Threads!\\n"); pthread_mutex_destroy(&mutex); queue_delete(consprodqueue); return 2; } else { printf("Join Cons: %d\\n", i); } } pthread_mutex_destroy(&mutex); queue_delete(consprodqueue); }
1
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; long long i = 0; void *start_counting(void *arg) { for (;;) { pthread_mutex_lock(&mutex); if (i >= 100000) { pthread_mutex_unlock(&mutex); return 0; } ++i; pthread_mutex_unlock(&mutex); printf("i = %lld\\n", i); } } int main(void) { int i = 0; pthread_t *thread_group = malloc(sizeof(pthread_t) * 12); for (i = 0; i < 12; ++i) { pthread_create(&thread_group[i], 0, start_counting, 0); } for (i = 0; i < 12; ++i) { pthread_join(thread_group[i], 0); } return 0; }
0
#include <pthread.h> int NUM_THREADS = 2; double **V,**Q; int n; struct thread_data { int id; }; struct thread_data *thread_data_array; pthread_mutex_t *lock; void *gs(void *threadarg); double vecNorm(double *,int ); double scalarProd(double *,double *,int); int main(int argc, char *argv[]) { int i,j,k,time,t; double sigma,temp_norm,norm; void *status; pthread_t *thread; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); n = atoi(argv[1]); NUM_THREADS = atoi(argv[2]); thread_data_array = (struct thread_data*) malloc(NUM_THREADS*sizeof(struct thread_data)) ; thread = (pthread_t*) malloc(NUM_THREADS * sizeof(pthread_t)); lock=(pthread_mutex_t *)malloc(n*sizeof(pthread_mutex_t)); for (i=0;i<n;i++) pthread_mutex_init(&lock[i], 0); V = (double **)malloc(n*sizeof(double *)); Q = (double **)malloc(n*sizeof(double *)); for(i=0;i<n;i++){ V[i] = (double *)malloc(n*sizeof(double)); Q[i] = (double *)malloc(n*sizeof(double)); } for (i = 0; i<n; i++) for(j=0;j<n;j++) V[i][j] = rand() % 5 + 1; time=timer(); temp_norm = vecNorm(V[0],n); for (k=0; k<n; k++) Q[0][k] = V[0][k]/temp_norm; for(t=0; t<NUM_THREADS-1; t++) { thread_data_array[t].id=t; pthread_create(&thread[t], &attr, gs, (void *)&thread_data_array[t]); } t=NUM_THREADS-1; thread_data_array[t].id=t; gs((void *)&thread_data_array[t]); for(t=0; t<NUM_THREADS-1; t++) pthread_join(thread[t], &status); time=timer()-time; printf("%d %f \\n",NUM_THREADS, time/1000000.0); return 0; } void *gs(void *threadarg){ int k,j,i,id,start; double sigma,temp_norm; struct thread_data *my_data; my_data = (struct thread_data *) threadarg; id=my_data->id; for (j=id;j<n;j+=NUM_THREADS) pthread_mutex_lock(&lock[j]); if (id==0) pthread_mutex_unlock(&lock[0]); for (i=1;i<n;i++){ pthread_mutex_lock(&lock[i-1]); pthread_mutex_unlock(&lock[i-1]); start=(i/NUM_THREADS)*NUM_THREADS; for (j=start+id;j<n;j+=NUM_THREADS){ sigma = scalarProd(Q[i-1],V[j],n); for(k=0;k<n;k++) V[j][k] -=sigma*Q[i-1][k]; if (i==j){ temp_norm=vecNorm(V[i],n); for (k=0; k<n; k++) Q[i][k] = V[i][k]/temp_norm; pthread_mutex_unlock(&lock[i]); } } } } double vecNorm(double *vec,int n){ int i; double local_norm = 0; for(i=0;i<n;i++){ local_norm+= (vec[i]*vec[i]); } return sqrt(local_norm); } double scalarProd(double *a,double *b,int n){ int i; double scalar =0.0; for(i=0;i<n;i++){ scalar +=a[i]*b[i]; } return scalar; }
1
#include <pthread.h> pthread_mutex_t mutex ; pthread_cond_t cond_pro, cond_con ; void* handle(void* arg) { int* pt = (int*)arg ; int soldn = 0 ; int tmp ; while(1) { pthread_mutex_lock(&mutex); while( *pt == 0) { printf("no tickets!\\n"); pthread_cond_signal(&cond_pro); pthread_cond_wait(&cond_con, &mutex); } tmp = *pt ; tmp -- ; *pt = tmp ; soldn ++ ; printf("%u: sold a ticket, %d, left: %d\\n", pthread_self(),soldn, *pt); pthread_mutex_unlock(&mutex); sleep(1); } pthread_mutex_unlock(&mutex); pthread_exit((void*)soldn); } void* handle1(void* arg) { int* pt = (int*)arg ; while(1) { pthread_mutex_lock(&mutex); while(*pt > 0) pthread_cond_wait(&cond_pro, &mutex); *pt = rand() % 20 + 1 ; printf("new tickets: %d\\n", *pt); pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond_con); } } int main(int argc, char* argv[]) { int nthds = atoi(argv[1]); int ntickets = atoi(argv[2]); int total = ntickets; pthread_t thd_bak; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_pro, 0); pthread_cond_init(&cond_con, 0); pthread_t* thd_arr = (pthread_t*)calloc(nthds, sizeof(pthread_t)); int* thd_tickets = (int*)calloc(nthds, sizeof(int)); int i ; for(i = 0; i < nthds; i ++) { pthread_create( thd_arr + i, 0, handle, (void*)&ntickets ); } pthread_create(&thd_bak, 0, handle1, (void*)&ntickets ); for(i = 0; i < nthds; i ++) { pthread_join(thd_arr[i], (void*)(thd_tickets + i)); } int sum ; for(sum = 0, i = 0; i < nthds; i ++) { sum += thd_tickets[i] ; } printf("sold: %d, total: %d, current: %d\\n", sum,total, ntickets); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_pro); pthread_cond_destroy(&cond_con); }
0
#include <pthread.h> int globalInt; int state; pthread_t tid[2]; pthread_mutex_t lock1, lock2; void* thread1(void *arg) { int i = 1; int tempInt; FILE *input = fopen("hw4.in", "r"); while(i == 1) { pthread_mutex_lock(&lock1); if(state == 0) state++; i = fscanf(input, "%d\\n", &globalInt); pthread_mutex_unlock(&lock2); } state++; fclose(input); return 0; } void* thread2(void *output) { while(state <= 1) { pthread_mutex_lock(&lock2); if(state == 1) { if(globalInt % 2 != 0) { fprintf(output, "%d\\n", globalInt); } else { fprintf(output, "%d\\n", globalInt); fprintf(output, "%d\\n", globalInt); } } pthread_mutex_unlock(&lock1); } return 0; } int main(void) { state = 0; FILE* output = fopen("hw4.out", "w"); pthread_create(&(tid[0]), 0, &thread1, 0); pthread_create(&(tid[1]), 0, &thread2, (void*)output); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock1); pthread_mutex_destroy(&lock2); fclose(output); return 0; }
1
#include <pthread.h> int count = 0; double finalresult=0.0; pthread_mutex_t count_mutex; pthread_cond_t count_condvar; void *sub1(void *t) { int i; long tid = (long)t; double myresult=0.0; sleep(1); pthread_mutex_lock(&count_mutex); if ( count < 12) { printf("sub1: thread=%ld going into wait. count=%d\\n",tid,count); pthread_cond_wait(&count_condvar, &count_mutex); printf("sub1: thread=%ld Condition variable signal received.",tid); } printf(" count=%d\\n",count); count++; finalresult += myresult; printf("sub1: thread=%ld count now equals=%d myresult=%e. Done.\\n", tid,count,myresult); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } void *sub2(void *t) { int j,i; long tid = (long)t; double myresult=0.0; for (i=0; i<10; i++) { for (j=0; j<100000; j++) myresult += sin(j) * tan(i); pthread_mutex_lock(&count_mutex); finalresult += myresult; count++; if (count == 12) { printf("sub2: thread=%ld Threshold reached. count=%d. ",tid,count); pthread_cond_signal(&count_condvar); printf("Just sent signal.\\n"); } else { printf("sub2: thread=%ld did work. count=%d\\n",tid,count); } pthread_mutex_unlock(&count_mutex); } printf("sub2: thread=%ld myresult=%e. Done. \\n",tid,myresult); pthread_exit(0); } int main(int argc, char *argv[]) { long t1=1, t2=2, t3=3; int i, rc; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_condvar, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, sub1, (void *)t1); pthread_create(&threads[1], &attr, sub2, (void *)t2); pthread_create(&threads[2], &attr, sub2, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Final result=%e. Done.\\n", 3,finalresult); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_condvar); pthread_exit (0); }
0
#include <pthread.h> static void start(struct ActorSystem * self) { for (int i = 0; i < self->worker_threads_size; i++) { self->worker_threads[i]->start(self->worker_threads[i]); } } static void stop(struct ActorSystem * self) { self->cancel = 1; for (int i = 0; i < self->worker_threads_size; i++) { pthread_cond_signal(& self->thread_cond); } for (int i = 0; i < self->worker_threads_size; i++) { pthread_join(self->worker_threads[i]->thread, 0); } } static int add_actor(struct ActorSystem * self, struct Actor * actor) { if (self->actors_size < self->actors_max) { actor->system = self; actor->id = self->actors_size; self->actors[self->actors_size] = actor; self->actors_size++; return actor->id; } else { return -1; } } static bool send(struct ActorSystem * self, struct Message * message) { struct SafeQueue * message_queue = self->message_queue; bool sent = message_queue->push(message_queue, message); pthread_cond_signal(& self->thread_cond); return sent; } static void receive(struct ActorSystem * self) { struct Message * message; struct Thread * current_thread = self->current_thread(self); while (!self->cancel) { struct SafeQueue * queue = self->message_queue; while (queue->pop(queue, (void **) & message)) { struct Actor * receiver = self->actors[message->receiver]; pthread_mutex_lock(& receiver->mutex); receiver->receive(receiver, message->content); pthread_mutex_unlock(& receiver->mutex); delete(message); } if (!self->cancel) { current_thread->wait(current_thread, & self->thread_cond); } } } static struct Thread * current_thread(struct ActorSystem * self) { pthread_t pthread = pthread_self(); for (int i = 0; i < self->worker_threads_size; i++) { struct Thread * thread = self->worker_threads[i]; if (thread->thread == pthread) { return thread; } } return 0; } static void * constructor(void * _self, va_list * args) { struct ActorSystem * self = _self; self->start = start; self->stop = stop; self->add_actor = add_actor; self->send = send; self->receive = receive; self->current_thread = current_thread; self->actors_max = __builtin_va_arg((* args)); self->actors_size = 0; self->actors = (struct Actor **) malloc(sizeof(struct Actor *) * self->actors_max); self->message_queue = new(SafeQueue, QUEUE_COMPLEX, __builtin_va_arg((* args))); self->worker_threads_size = __builtin_va_arg((* args)); self->worker_threads = (struct Thread **) malloc(sizeof(struct Thread *) * self->worker_threads_size); for (int i = 0; i < self->worker_threads_size; i++) { self->worker_threads[i] = new(Thread, self->receive, self); } pthread_cond_init(& self->thread_cond, 0); pthread_mutex_init(& self->thread_mutex, 0); self->cancel = 0; return self; } static void * destructor(void * _self) { struct ActorSystem * self = _self; for (int i = 0; i < self->actors_size; i++) { delete(self->actors[i]); } free(self->actors); delete(self->message_queue); pthread_cond_destroy(& self->thread_cond); pthread_mutex_destroy(& self->thread_mutex); for (int i = 0; i < self->worker_threads_size; i++) { delete(self->worker_threads[i]); } free(self->worker_threads); return self; } static bool equals(void * self, void * other) { return self == other; } static const struct Class _ActorSystem = { sizeof(struct ActorSystem), constructor, destructor, equals }; const void * ActorSystem = & _ActorSystem;
1
#include <pthread.h> struct Params { int *start; size_t len; int depth; }; pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; void *merge_sort_thread(void *pv); void merge(int *start, int *mid, int *end) { int *res = malloc((end - start)*sizeof(*res)); int *lhs = start, *rhs = mid, *dst = res; while (lhs != mid && rhs != end) *dst++ = (*lhs <= *rhs) ? *lhs++ : *rhs++; while (lhs != mid) *dst++ = *lhs++; while (rhs != end) *dst++ = *rhs++; memcpy(start, res, (end - start)*sizeof(*res)); free(res); } void merge_sort_mt(int *start, size_t len, int depth) { if (len < 2) return; if (depth <= 0 || len < 4) { merge_sort_mt(start, len/2, 0); merge_sort_mt(start+len/2, len-len/2, 0); } else { struct Params params = { start, len/2, depth/2 }; pthread_t thrd; pthread_mutex_lock(&mtx); printf("Starting subthread...\\n"); pthread_mutex_unlock(&mtx); pthread_create(&thrd, 0, merge_sort_thread, &params); merge_sort_mt(start+len/2, len-len/2, depth/2); pthread_join(thrd, 0); pthread_mutex_lock(&mtx); printf("Finished subthread.\\n"); pthread_mutex_unlock(&mtx); } merge(start, start+len/2, start+len); } int cmp_proc2(const void *arg1, const void* arg2) { const int *lhs = arg1; const int *rhs = arg2; return (*lhs < *rhs) ? -1 : (*rhs < *lhs ? 1 : 0); } void merge_sort_mt2(int *start, size_t len, int depth) { if (len < 2) return; if (depth <= 0 || len <= 256) { qsort(start, len, sizeof(*start), cmp_proc2); return; } struct Params params = { start, len/2, depth/2 }; pthread_t thrd; pthread_mutex_lock(&mtx); printf("Starting subthread...\\n"); pthread_mutex_unlock(&mtx); pthread_create(&thrd, 0, merge_sort_thread, &params); merge_sort_mt(start+len/2, len-len/2, depth/2); pthread_join(thrd, 0); pthread_mutex_lock(&mtx); printf("Finished subthread.\\n"); pthread_mutex_unlock(&mtx); merge(start, start+len/2, start+len); } void *merge_sort_thread(void *pv) { struct Params *params = pv; merge_sort_mt(params->start, params->len, params->depth); return pv; } void merge_sort(int *start, size_t len) { merge_sort_mt(start, len, 4); } int main() { static const unsigned int N = 2048; int *data = malloc(N * sizeof(*data)); unsigned int i; srand((unsigned)time(0)); for (i=0; i<N; ++i) { data[i] = rand() % 1024; printf("%4d ", data[i]); if ((i+1)%8 == 0) printf("\\n"); } printf("\\n"); merge_sort(data, N); for (i=0; i<N; ++i) { printf("%4d ", data[i]); if ((i+1)%8 == 0) printf("\\n"); } printf("\\n"); free(data); return 0; }
0
#include <pthread.h> pthread_mutex_t lineMutex; int lineCount=0; char strContain(char*childstr,char*str); char strContainDEFINE(char*str); int countDefine(char*fileName); int find(char * dirName); struct task * next; char* dir; }task; int num; int shutdown; pthread_t* workThread; task* taskHead; task* taskTail; pthread_mutex_t mutex; pthread_cond_t notEmptyCond; }threadPool; threadPool *tp; void* workProcess(void *arg){ int lineNum; pthread_mutex_lock(&tp->mutex); while(1){ while(!tp->shutdown&&tp->taskHead==0){ pthread_cond_wait(&tp->notEmptyCond,&tp->mutex); } if(tp->shutdown==1){ pthread_mutex_unlock(&tp->mutex); pthread_exit(0); } task *t; t=tp->taskHead; tp->taskHead=tp->taskHead->next; if(tp->taskTail==t){ tp->taskTail=0; } pthread_mutex_unlock(&tp->mutex); lineNum=0; printf("way to fine:%s taskNumber:%d\\n",t->dir,getTaskNum()); lineNum=find(t->dir); if(lineNum!=0){ pthread_mutex_lock(&lineMutex); lineCount+=lineNum; pthread_mutex_unlock(&lineMutex); } free(t->dir); free(t); } } int getTaskNum(){ int i=0; pthread_mutex_lock(&tp->mutex); task*p=tp->taskHead; while(p!=tp->taskTail){ i++; p=p->next; } pthread_mutex_unlock(&tp->mutex); return i; } void createThreadPool(int num){ int errorno; if(num<=0) exit(1); tp=(threadPool*)malloc(sizeof(threadPool)); if(tp==0){ exit(1); } tp->num=num; tp->shutdown=0; tp->workThread=(pthread_t*)malloc(num*sizeof(pthread_t)); if (tp->workThread==0){ free(tp); exit(1); } int i=0; for(i=0;i<tp->num;i++){ errorno=pthread_create(&tp->workThread[i],0,workProcess,0); if(errorno!=0){ exit(1); } } tp->taskHead=0; tp->taskTail=0; pthread_mutex_init(&tp->mutex,0); pthread_cond_init(&tp->notEmptyCond,0); } void addTask(char *dir){ task *t=(task*)malloc(sizeof(task)); if(t==0){ exit(1); } t->dir=(char*)malloc(strlen(dir)); strcpy(t->dir,dir); t->next=0; pthread_mutex_lock(&tp->mutex); if(tp->taskTail!=0){ tp->taskTail->next=t; tp->taskTail=t; }else{ tp->taskHead=t; tp->taskTail=t; } pthread_cond_broadcast(&tp->notEmptyCond); pthread_mutex_unlock(&tp->mutex); } void destroyThreadPool(){ } char strContain(char*childstr,char*str){ int clen=strlen(childstr); int len=strlen(str); int i=0; int j=0; for(i=0;i+clen<=len;i++){ for(j=0;j<clen;j++){ if(childstr[j]!=str[i+j]){ break; } } if(j==clen) return 1; } return 0; } char strContainDEFINE(char*str){ int len=strlen(str); int i=0; for(i=0;i+6<=len;i++){ if((str[i]=='d')&&(str[i+1]=='e')&&(str[i+2]=='f')&&(str[i+3]=='i')&&(str[i+4]=='n')&&(str[i+5]=='e')) return 1; } return 0; } int countDefine(char*fileName){ int lineNum=0; FILE *fp=fopen(fileName,"r"); if(fp==0){ perror(fileName); } char content[200]; while(fgets(content,200,fp)){ if(strContainDEFINE(content)==1){ lineNum++; } } fclose(fp); return lineNum; } int find(char * dirName){ char fileName[1000]; int lineNum=0; int dirLen=strlen(dirName); int error; DIR *dir; struct dirent entry; struct dirent *result; struct stat fstat; strcpy(fileName,dirName); fileName[dirLen]='/'; dir = opendir(dirName); int len; for (;;) { fileName[dirLen+1]='\\0'; error = readdir_r(dir, &entry, &result); if (error != 0) { perror("readdir"); return ; } if (result == 0) break; strcat(fileName,result->d_name); stat(fileName,&fstat); if(S_ISDIR(fstat.st_mode)){ if((strcmp(".",result->d_name)==0)||(strcmp("..",result->d_name)==0)) continue; addTask(fileName); }else{ lineNum+=countDefine(fileName); } } closedir(dir); return lineNum; } int main() { pthread_mutex_init(&lineMutex,0); createThreadPool(2); addTask("/usr/include"); sleep(3); printf("%d\\n",lineCount); return 0; }
1
#include <pthread.h> bool *hashTable; pthread_mutex_t *locks; void hashTableCreate(int numOfBlocks) { LOG_PROLOG(); hashTable = (bool*) my_malloc(sizeof(bool) * numOfBlocks); locks = (pthread_mutex_t*) my_malloc(sizeof(pthread_mutex_t) * numOfBlocks); for (int i = 0; i < numOfBlocks; i++) { hashTable[i] = 0; pthread_mutex_init(&locks[i], 0); } LOG_EPILOG(); } void hashTableFree(int numOfBlocks) { LOG_PROLOG(); if (hashTable != 0) { my_free(hashTable); hashTable = 0; } else { LOG_ERROR("Trying to free hashTable which was a NULL pointer"); } if (locks != 0) { for (int i = 0; i < numOfBlocks; i++) { pthread_mutex_destroy(&locks[i]); } my_free(locks); locks = 0; } else { LOG_ERROR("Trying to free locks which was a NULL pointer"); } LOG_EPILOG(); } bool setFlagForAllocatedBlock(int blockNum) { LOG_PROLOG(); bool flag = 0; pthread_mutex_lock (&locks[blockNum]); if (hashTable[blockNum]) { flag = 0; } else { hashTable[blockNum] = 1; flag = 1; } pthread_mutex_unlock(&locks[blockNum]); LOG_EPILOG(); return flag; } bool clearFlagForAllocatedBlock(int blockNum) { LOG_PROLOG(); bool flag; pthread_mutex_lock (&locks[blockNum]); if (!hashTable[blockNum]) { flag = 0; } else { hashTable[blockNum] = 0; flag = 1; } pthread_mutex_unlock(&locks[blockNum]); LOG_EPILOG(); return flag; } int threadId; int numOfBlocks; } CodeCorrectnessTestStructure; void* testCodeCorrectness(void *data) { LOG_PROLOG(); CodeCorrectnessTestStructure *codeCorrectDS = (CodeCorrectnessTestStructure*) data; int threadId = codeCorrectDS->threadId; int numOfBlocks = codeCorrectDS->numOfBlocks; for (int i = 0; i < 20; i++) { int allocBlock = randint(numOfBlocks + 1); LOG_INFO("thread %d allocated block %d", threadId, allocBlock); bool success = setFlagForAllocatedBlock(allocBlock); if (success) { LOG_INFO("thread %d successfully set the flag for block %d", threadId, allocBlock); if (clearFlagForAllocatedBlock(allocBlock)) { LOG_INFO("thread %d successfully cleared the flag for block %d", threadId, allocBlock); } else { LOG_ERROR("thread %d could not clear the flag for block %d", threadId, allocBlock); } } else { LOG_WARN("thread %d could not set the flag for block %d", threadId, allocBlock); } } LOG_EPILOG(); return 0; } void thrmain() { LOG_INIT_CONSOLE(); LOG_INIT_FILE(); int NUM_THREADS = 100; int NUM_BLOCKS = 20; hashTableCreate(NUM_BLOCKS); pthread_t threads[NUM_THREADS]; CodeCorrectnessTestStructure *codeCorrectDS = (CodeCorrectnessTestStructure*)my_malloc(NUM_THREADS * sizeof(CodeCorrectnessTestStructure)); int rc = -1; int numThreads = 0; for (int t = 0; t < NUM_THREADS; t++) { codeCorrectDS[t].numOfBlocks = NUM_BLOCKS; codeCorrectDS[t].threadId = t; LOG_DEBUG("Creating thread at Index %d", t); rc = pthread_create(&threads[t], 0, testCodeCorrectness, (codeCorrectDS + t)); if (rc){ LOG_ERROR("Error creating thread with error code %d", rc); break; } else { numThreads++; } } void *status; for (int t = 0; t < numThreads; t++) { rc = pthread_join(threads[t], &status); } hashTableFree(NUM_BLOCKS); LOG_CLOSE(); }
0
#include <pthread.h> int pbs_msgjob_err( int c, char *jobid, int fileopt, char *msg, char *extend, int *local_errno) { struct batch_reply *reply; int rc; if ((jobid == (char *)0) || (*jobid == '\\0') || (msg == (char *)0) || (*msg == '\\0')) return(PBSE_IVALREQ); pthread_mutex_lock(connection[c].ch_mutex); if ((rc = PBSD_msg_put(c, jobid, fileopt, msg, extend))) { connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); return(PBSE_PROTOCOL); } reply = PBSD_rdrpy(local_errno, c); rc = connection[c].ch_errno; pthread_mutex_unlock(connection[c].ch_mutex); PBSD_FreeReply(reply); return(rc); } int pbs_msgjob( int c, char *jobid, int fileopt, char *msg, char *extend) { pbs_errno = 0; return(pbs_msgjob_err(c, jobid, fileopt, msg, extend, &pbs_errno)); }
1
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; void *thread2 (void *arg); void *thread (void *arg) { long j = (long) arg; int i, ret; pthread_t th[4]; pthread_mutex_lock(&m); pthread_mutex_unlock(&m); printf ("t%ld: running!\\n", j); for (i = 0; i < 4; i++) { ret = pthread_create (th + i, 0, thread2, (void*) j); assert (ret == 0); if (i < 2) { ret = pthread_join (th[i], 0); assert (ret == 0); } } return 0; } void *thread2 (void *arg) { long i = (long) arg; printf ("t%ld': running!\\n", i); return 0; } int main (int argc, char ** argv) { int ret; long i; pthread_t th; (void) argc; (void) argv; ret = pthread_mutex_init (&m, 0); assert (ret == 0); for (i = 0; i < 5; i++) { ret = pthread_create (&th, 0, thread, (void*) i); assert (ret == 0); } pthread_exit (0); }
0
#include <pthread.h> struct partilhar{ int tatuadora; int num_cads; int *num_cls; int *recurso1, *recurso2; }; struct partilhar *partilha; struct sincronizar *sinc; void SOpTattoo_init(int num_cl, int num_cad){ cria_recursos_partilhados(num_cad,num_cl,1); pthread_mutexattr_t attr1; pthread_mutexattr_t attr2; pthread_mutexattr_init(&attr1); pthread_mutexattr_setpshared(&attr1,PTHREAD_PROCESS_SHARED); pthread_mutex_init(&sinc->mutex_tatuadora,&attr1); pthread_mutexattr_init(&attr2); pthread_mutexattr_setpshared(&attr2,PTHREAD_PROCESS_SHARED); pthread_mutex_init(&sinc->mutex_cadeira,&attr2); partilha->tatuadora = 2; partilha->num_cads = num_cad; partilha->num_cls = &num_cl; } void cria_recursos_partilhados(int num_cad, int num_cl, bool criar){ partilha =inicia_recurso("/partilhada",sizeof(struct partilhar),criar); partilha->num_cls=inicia_recurso("/num_clientes",sizeof(int),criar); sinc=inicia_recurso("/sinc2",sizeof(struct sincronizar),criar); partilha->recurso1=inicia_recurso("/cliente",sizeof(int),criar); } int fazer_tatuagem(int cliente){ pthread_mutex_lock(&sinc->mutex_tatuadora); if(partilha->tatuadora == DESCANSAR){ if(alguem_espera()==1) partilha->tatuadora=3; else partilha->tatuadora=2; } if(partilha->tatuadora == OCUPADA){ procura_cadeira(cliente); partilha->tatuadora=-1; if(partilha->num_cads == 0) partilha->tatuadora = -1; } if(partilha->tatuadora != DESCANSAR && partilha->tatuadora != OCUPADA){ partilha->tatuadora = 3; } pthread_mutex_unlock(&sinc->mutex_tatuadora); return partilha->tatuadora; } int procura_cadeira(int cliente){ int var; pthread_mutex_lock(&sinc->mutex_cadeira); printf("ola3\\n"); if(partilha->tatuadora== OCUPADA){ if(partilha->num_cads == LIVRE){ var=1; partilha->num_cads--; } else if (partilha->num_cads ==-1) var=0; } pthread_mutex_unlock(&sinc->mutex_cadeira); return var; } void sair_SOpTattoo(int cliente){ pthread_mutex_lock(&sinc->mutex_tatuadora); destroi_recursos_SopTatoo(); if(alguem_espera()==1) partilha->tatuadora=3; else partilha->tatuadora=2; partilha->num_cls--; pthread_mutex_unlock(&sinc->mutex_tatuadora); } int alguem_espera(){ if(partilha->num_cads != 0) return 1; else return 0; } void destroi_recursos_SopTatoo(){ destroi_recurso("/cliente",sizeof(int) ,partilha->recurso1); destroi_recurso("/sinc2",sizeof(struct sincronizar) ,sinc); destroi_recurso("/num_clientes",sizeof(int),partilha->num_cls); pthread_mutex_destroy(&sinc->mutex_tatuadora); pthread_mutex_destroy(&sinc->mutex_cadeira); }
1
#include <pthread.h> pthread_mutex_t myMutex; char sentence[2000]; int charIndex = 0; char convertUppercase(char lower) { if ((lower > 96) && (lower < 123)) { return (lower - 32); } else { return lower; } } void printChar() { printf("The new sentence is [%d]: \\t%c\\n", charIndex, sentence[charIndex]); charIndex++; } void * convertMessage(void *pVoid) { pthread_mutex_lock(&myMutex); if (charIndex % 2) { sentence[charIndex] = convertUppercase(sentence[charIndex]); } printChar(); pthread_mutex_unlock(&myMutex); return 0; } int main() { pthread_t ts[50]; char buffer[50]; char *p; if (pthread_mutex_init(&myMutex, 0) != 0) { printf("Mutex initialization failed\\n"); return 1; } printf("Please enter a phrase (less than 50 characters): "); if (fgets(buffer, sizeof(buffer), stdin) != 0) { if ((p = strchr(buffer, '\\n')) != 0) { *p = '\\0'; } } strcpy(sentence, buffer); printf("The original sentence is: \\t %s\\n", sentence); for(int i = 0; i < strlen(buffer) + 1; ++i) { pthread_create(&ts[i], 0, convertMessage, 0); } for(int i = 0; i < strlen(buffer); i++) { pthread_join(ts[i], 0); } pthread_mutex_destroy(&myMutex); printf("\\n"); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_t pthread_handle; int selfid; int isWaiting; int blocker_thread_id; int resume_thread_id; pthread_attr_t attr; pthread_cond_t cond; } _pthread_t; void wait(int thid, pthread_cond_t cond_current_thread, int line_no) { pthread_mutex_lock(&mutex); printf("wait called at line no : %d : thread %d is waiting.\\n",line_no ,thid); if(pthread_cond_wait (&cond_current_thread, &mutex)){ printf("pthread_cond_wait failed, thread id = %d, line_no = %d", thid, line_no); pthread_exit(0); } pthread_mutex_unlock(&mutex); } void signal (int sender_thid, int recvr_thid, pthread_cond_t cond_sig_recver_thread, int line_no) { pthread_mutex_lock(&mutex); printf("signal called at line no : %d : thread %d sending signal to thread %d \\n", line_no, sender_thid, recvr_thid); if(pthread_cond_signal(&cond_sig_recver_thread)){ printf("pthread_cond_signal signalling failed, sender_thread id = %d, recvr_thread id = %d, line_no = %d", sender_thid, recvr_thid, line_no); pthread_exit(0); } pthread_mutex_unlock(&mutex); } void pthread_init(_pthread_t _pthread, int JOINABLE) { pthread_attr_init(&_pthread.attr); JOINABLE ? pthread_attr_setdetachstate(&_pthread.attr, PTHREAD_CREATE_JOINABLE): pthread_attr_setdetachstate(&_pthread.attr, PTHREAD_CREATE_DETACHED); pthread_cond_init(&_pthread.cond, 0); _pthread.isWaiting = 0; _pthread.blocker_thread_id = -1; _pthread.resume_thread_id = -1; } int main(int argc, char **argv) { return 0; }
1
#include <pthread.h> pthread_mutex_t mutex_value; int a = 1; int myglobal; pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER; void *thread_function(void *arg) { int i,j; for ( i=0; i<20; i++) { pthread_mutex_lock(&mymutex); j=myglobal; j=j+1; printf("."); fflush(stdout); sleep(1); myglobal=j; pthread_mutex_unlock(&mymutex); } return 0; } int main(void) { pthread_t mythread; int i; if ( pthread_create( &mythread, 0, thread_function, 0) ) { printf("error creating thread."); abort(); } for ( i=0; i<20; i++) { pthread_mutex_lock(&mymutex); myglobal=myglobal+1; pthread_mutex_unlock(&mymutex); printf("o"); fflush(stdout); sleep(1); } if ( pthread_join ( mythread, 0 ) ) { printf("error joining thread."); abort(); } printf("\\nmyglobal equals %d\\n",myglobal); exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void handle(int signum) { int pid = 0; printf("recv signum:%d \\n", signum); while ((pid = waitpid(-1, 0, WNOHANG) ) > 0) { printf("退出子进程pid%d \\n", pid); fflush(stdout); } } int srv_init() { int ret = 0; int shmhdl = 0; key_t key = 0; ret = IPC_CreatShm(".", sizeof(int), &shmhdl); if (ret != 0) { printf("func IPC_CreatShm() err:%d \\n", ret); return ret; } key = ftok(".", 'z'); int semid = 0; ret = sem_creat(key, &semid); if (ret != 0) { printf("func sem_creat() err:%d,重新按照open打开信号酿\\n", ret); if (ret == SEMERR_EEXIST) { ret = sem_open(key, &semid); if (ret != 0) { printf("按照打开的方式,重新获取sem失败:%d \\n", ret); return ret; } } else { return ret; } } int val = 0; ret = sem_getval(semid, &val); if (ret != 0 ) { printf("func sem_getval() err:%d \\n", ret); return ret; } printf("sem val:%d\\n", val); return ret; } void TestFunc_sem() { int ncount = 0; int ret = 0; int shmhdl = 0; int *addr = 0; key_t key = 0; int semid = 0; key = ftok(".", 'z'); sem_open(key, &semid); sem_p(semid); ret = IPC_CreatShm(".", 0, &shmhdl); ret =IPC_MapShm(shmhdl, (void **)&addr); *((int *)addr) = *((int *)addr) + 1; ncount = *((int *)addr); printf("ncount:%d\\n", ncount); ret =IPC_UnMapShm(addr); sem_v(semid); } void TestFunc_mutex() { int ncount = 0; int ret = 0; int shmhdl = 0; int *addr = 0; key_t key = 0; int semid = 0; key = ftok(".", 'z'); sem_open(key, &semid); pthread_mutex_lock(&mutex); ret = IPC_CreatShm(".", 0, &shmhdl); ret =IPC_MapShm(shmhdl, (void **)&addr); *((int *)addr) = *((int *)addr) + 1; ncount = *((int *)addr); printf("ncount:%d\\n", ncount); ret =IPC_UnMapShm(addr); pthread_mutex_unlock(&mutex); } void *Malloc_my_routine(void *arg) { int ret = 0; ret = pthread_detach(pthread_self()); if (0 == arg) { printf("fucn err my_routine param err\\n"); return 0; } int connfd = *((int*)arg); free(arg); char recvbuf[1024]; unsigned int recvbuflen = 1024; while(1) { memset(recvbuf, 0, sizeof(recvbuf)); ret = sck_server_recv(connfd, 0, recvbuf, &recvbuflen); if (ret >= 3000) { printf("func sck_server_recv() err:%d \\n", ret); break; } TestFunc_mutex(); printf("recvbuf = %s\\n", recvbuf); ret = sck_server_send(connfd, 0, recvbuf, recvbuflen); if (ret >= 3000) { printf("func sck_server_send() err:%d \\n", ret); break; } } close(connfd); return 0; } int main(void) { int ret = 0; int listenfd = 0; char ip[1024] = {0}; int port = 0; int connfd = 0; signal(SIGCHLD, handle); signal(SIGPIPE, SIG_IGN); ret = srv_init(); ret = sck_server_init(8001, &listenfd); if (ret != 0) { printf("sckServer_init() err:%d \\n", ret); return ret; } while(1) { int ret = 0; int wait_seconds = 5; ret = sck_server_accept(listenfd, wait_seconds, &connfd, ip, &port); if (ret >= 3000) { printf("timeout....\\n"); continue; } printf("客户端连接成功...\\n"); pthread_t tid = 0; int *pCon = 0; pCon = (int *)malloc(sizeof(int)); *pCon = connfd; ret = pthread_create(&tid, 0, Malloc_my_routine, (void *)pCon); } sck_server_close(listenfd); sck_server_close(connfd); return 0; }
1
#include <pthread.h> static pthread_mutex_t prof_mutex = PTHREAD_MUTEX_INITIALIZER; char* str; int value; } ioctl_s; static ioctl_s ioctl_calls[256]; static int profiling_enabled = 0; void ioctl_start_profiling() { if(profiling_enabled) ioctl_stop_profiling(); memset(ioctl_calls, 0, sizeof(ioctl_calls)); profiling_enabled = 1; } void ioctl_stop_profiling() { int t = 0; if(!profiling_enabled) return; profiling_enabled = 0; while(ioctl_calls[t].str) { free(ioctl_calls[t].str); t++; } memset(ioctl_calls, 0, sizeof(ioctl_calls)); } void ioctl_print_profiling_data() { int t = 0; if(!profiling_enabled) return; BLTS_DEBUG("\\nProfiling data:\\n"); while(ioctl_calls[t].str) { BLTS_DEBUG("%s: %d\\n", ioctl_calls[t].str, ioctl_calls[t].value); t++; } } void ioctl_profile(const char* name) { int t = 0; pthread_mutex_lock(&prof_mutex); if(!profiling_enabled) goto cleanup; while(ioctl_calls[t].str) { if(!strcmp(ioctl_calls[t].str, name)) { ioctl_calls[t].value++; goto cleanup; } t++; } if(t >= 256) { BLTS_DEBUG("MAX_PROFILED_IOCTLS reached - ioctl %s omitted!\\n", name); goto cleanup; } ioctl_calls[t].str = strdup(name); ioctl_calls[t].value++; cleanup: pthread_mutex_unlock(&prof_mutex); }
0
#include <pthread.h> void jelly_reset(struct Jelly *jelly) { jelly->jelly_message_read_head = 0; jelly->jelly_message_write_head = 0; jelly->proximity_locations = 0; jelly->local_proximity = 0; jelly->routing_table_head = 0; jelly->network_packet_receive_read = 0; jelly->network_packet_receive_write = 0; jelly->network_packet_send = 0; printf("not simulated\\n"); } void jelly_sleep(struct Jelly *jelly) { } void jelly_wake(struct Jelly *jelly) { pthread_mutex_lock(&(jelly->simulator_sleep_mutex)); jelly->sleeping = 0; pthread_cond_signal(&(jelly->simulator_sleep_cond)); pthread_mutex_unlock(&(jelly->simulator_sleep_mutex)); } void *jelly_init(void *jelly_init_frame) { struct JellyInitFrame *init_frame = (struct JellyInitFrame *) jelly_init_frame; struct Jelly* jelly = init_frame->jelly; jelly_reset(jelly); jelly->color = init_frame->color; jelly->address = init_frame->address; jelly->position = init_frame->position; jelly->network_ports = init_frame->network_ports; for (;;) { n_process_packets(jelly); m_process_messages(jelly); c_update_color(jelly); n_send_pending_packets(jelly); jelly_sleep(jelly); } return 0; }
1
#include <pthread.h> struct netent *getnetbyaddr(long net, int type) { char *buf = _net_buf(); if (!buf) return 0; return getnetbyaddr_r(net, type, (struct netent *) buf, buf + sizeof(struct netent), NET_BUFSIZE); } struct netent *getnetbyaddr_r(long net, int type, struct netent *result, char *buf, int bufsize) { pthread_mutex_lock(&net_iterate_lock); setnetent(0); while ((result = getnetent_r(result, buf, bufsize)) != 0) { if (result->n_addrtype == type && result->n_net == net) break; } pthread_mutex_unlock(&net_iterate_lock); return result; }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for(fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if(fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if(fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while(tfp->f_next != fp) { tfp = tfp->f_next; } tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } } int main(void) { return 0; }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static void * thr_func(void *p) { int i,j,mark; while(1) { pthread_mutex_lock(&mut_num); while(num == 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } if(num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_mutex_unlock(&mut_num); mark = 0; for(j = 2 ; j < i/2 ; j++) { if(i % j == 0) { mark = 1 ; break; } } if(mark == 0) { printf("[%d] %d is primer\\n",(int)p,i); } } pthread_exit(0); } int main() { int i,err; pthread_t tid[4]; for(i = 0 ; i < 4 ; i++) { err = pthread_create(tid+i,0,thr_func,(void *)i); if(err) { fprintf(stderr,"pthread_create():%s\\n",strerror(err)); exit(1); } } for(i = 30000000 ; i <= 30000200 ; i++) { pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = i; pthread_mutex_unlock(&mut_num); } pthread_mutex_lock(&mut_num); while(num != 0) { pthread_mutex_unlock(&mut_num); sched_yield(); pthread_mutex_lock(&mut_num); } num = -1; pthread_mutex_unlock(&mut_num); for(i = 0 ; i < 4 ; i++) { pthread_join(tid[i],0); } pthread_mutex_destroy(&mut_num); exit(0); }
0
#include <pthread.h> static pthread_mutex_t tty_mutex; static int mtx_inited; static int redirect_to_display; int tty_redirect_to_display() { return redirect_to_display; } void tty_to_display(int to_display) { redirect_to_display = to_display; } int tty_open(struct file *fp, int flags) { redirect_to_display = 0; return 0; } int tty_close(struct file *fp) { return 0; } int tty_read(struct file *fp, struct uio *uio, struct ucred *cred) { int unit = fp->f_devunit; char *buf = uio->uio_iov->iov_base; while (uio->uio_iov->iov_len) { if (uart_read(unit, buf++, portMAX_DELAY)) { uio->uio_iov->iov_len--; uio->uio_resid--; } else { break; } } return 0; } int tty_write(struct file *fp, struct uio *uio, struct ucred *cred) { int unit = fp->f_devunit; char *buf = uio->uio_iov->iov_base; char dbuf[2]; dbuf[1] = '\\0'; if (!mtx_inited) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&tty_mutex, &attr); mtx_inited = 1; } pthread_mutex_lock(&tty_mutex); while (uio->uio_iov->iov_len) { if (*buf == '\\n') { uart_write(unit, '\\r'); } uart_write(unit, *buf); if (redirect_to_display) { dbuf[0] = *buf; display_text(-1,-1, 0, -1, -1, dbuf); } uio->uio_iov->iov_len--; uio->uio_resid--; buf++; } pthread_mutex_unlock(&tty_mutex); return 0; } int tty_stat(struct file *fp, struct stat *sb) { sb->st_mode = S_IFCHR; sb->st_blksize = 1; sb->st_size = 1; return 0; } void tty_lock() { if (!mtx_inited) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&tty_mutex, &attr); mtx_inited = 1; } pthread_mutex_lock(&tty_mutex); } void tty_unlock() { if (!mtx_inited) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&tty_mutex, &attr); } pthread_mutex_unlock(&tty_mutex); }
1
#include <pthread.h> pthread_mutex_t count_mutex; long circleCount; long totalCount; void *CalculatePi(void *args){ long tid = (long)args; long i; float x; float y; long total = 0; long circle = 0; float pi; FILE *urandom; urandom = fopen("/dev/urandom","r"); setvbuf(urandom, 0, _IONBF, 0); unsigned short randstate[3]; randstate[0] = (fgetc(urandom) << 8) | fgetc(urandom); randstate[1] = (fgetc(urandom) << 8) | fgetc(urandom); randstate[2] = (fgetc(urandom) << 8) | fgetc(urandom); fclose(urandom); for(i=0;i<1000000;i++){ x = erand48(randstate)*2 - 1; y = erand48(randstate)*2 - 1; if((x*x + y*y) <= 1){ circle++; } total++; } pthread_mutex_lock(&count_mutex); circleCount += circle; totalCount += total; pthread_mutex_unlock(&count_mutex); pi = (4*circle); pi = pi / total; pthread_exit(0); } int main (int argc, char *argv[]){ circleCount = 0; totalCount = 0; float x; int i; pthread_t threads[10]; int rc; float pi; srand48(time(0)); for(i=0;i < 10; i++){ rc = pthread_create(&threads[i], 0, CalculatePi, (void *)i); if(rc){ printf("ERROR; return code from pthread_create is %d\\n", rc); exit(-1); } } for(i=0;i< 10;i++){ pthread_join(threads[i],0); } pi = 4*circleCount; pi = pi / totalCount; printf("Points Inside Circle: %ld\\n", circleCount); printf("Total Points: %ld\\n", totalCount); printf("PI Calculation: %f\\n", pi); return 0; }
0
#include <pthread.h> static int g_tempdir_nonce = 0; static int g_num_tempdirs = 0; static char **g_tempdirs = 0; static pthread_mutex_t tempdir_lock = PTHREAD_MUTEX_INITIALIZER; static void cleanup_registered_tempdirs(void) { int i; const char *skip_cleanup; skip_cleanup = getenv("SKIP_CLEANUP"); if (skip_cleanup) return; pthread_mutex_lock(&tempdir_lock); for (i = 0; i < g_num_tempdirs; ++i) { remove_tempdir(g_tempdirs[i]); free(g_tempdirs[i]); } free(g_tempdirs); g_tempdirs = 0; pthread_mutex_unlock(&tempdir_lock); } int get_tempdir(char *tempdir, int name_max, int mode) { char tmp[PATH_MAX]; int nonce, pid; const char *base = getenv("TMPDIR"); if (!base) base = "/tmp"; if (base[0] != '/') { if (realpath(base, tmp) == 0) { return -errno; } base = tmp; } pthread_mutex_lock(&tempdir_lock); nonce = g_tempdir_nonce++; pthread_mutex_unlock(&tempdir_lock); pid = getpid(); snprintf(tempdir, name_max, "%s/tempdir.%08d.%08d", base, pid, nonce); if (mkdir(tempdir, mode) == -1) { int ret = errno; return -ret; } return 0; } int register_tempdir_for_cleanup(const char *tempdir) { char **tempdirs; pthread_mutex_lock(&tempdir_lock); tempdirs = realloc(g_tempdirs, sizeof(char*) * (g_num_tempdirs + 1)); if (!tempdirs) return -ENOMEM; g_tempdirs = tempdirs; g_tempdirs[g_num_tempdirs] = strdup(tempdir); if (g_num_tempdirs == 0) atexit(cleanup_registered_tempdirs); g_num_tempdirs++; pthread_mutex_unlock(&tempdir_lock); return 0; } void unregister_tempdir_for_cleanup(const char *tempdir) { int i; char **tempdirs; pthread_mutex_lock(&tempdir_lock); if (g_num_tempdirs == 0) { pthread_mutex_unlock(&tempdir_lock); return; } for (i = 0; i < g_num_tempdirs; ++i) { if (strcmp(g_tempdirs[i], tempdir) == 0) break; } if (i == g_num_tempdirs) { pthread_mutex_unlock(&tempdir_lock); return; } free(g_tempdirs[i]); g_tempdirs[i] = g_tempdirs[g_num_tempdirs - 1]; tempdirs = realloc(g_tempdirs, sizeof(char*) * g_num_tempdirs - 1); if (tempdirs) { g_tempdirs = tempdirs; } g_num_tempdirs--; pthread_mutex_unlock(&tempdir_lock); } void remove_tempdir(const char *tempdir) { run_cmd("rm", "-rf", tempdir, (char*)0); }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for( i=0; i<((20)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_error(); } void *t2(void *arg) { int i; for( i=0; i<(20); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> int sock; int owned; pthread_t owner; int named; } sock_struct; int n_sock; int max_sock; sock_struct **sbs; pthread_mutex_t *mutex; int init_socket_tacker(int max_sockets){ sbs = malloc(sizeof(sock_struct*)*max_sockets); pthread_mutex_init(mutex,0); max_sock = 0; n_sock = 0; return 0; } int get_socket(){ int ret = -1; ret = socket(AF_INET,SOCK_DGRAM,0); return ret; } int get_tracked_socket(){ int ret = -1; return ret; } static int make_tracked_socket(){ int ret = -1; pthread_mutex_lock(mutex); if (n_sock < max_sock){ ret = socket(AF_INET,SOCK_DGRAM,0); } if (ret != -1){ sbs[n_sock]= malloc(sizeof(sock_struct)); sbs[n_sock]->owned = 0; sbs[n_sock]->owner = 0; sbs[n_sock]->named = 0; sbs[n_sock]->sock = ret; n_sock++; } pthread_mutex_unlock(mutex); return ret; } int release_socket(int sock){ return 0; } int close_socket(int sock){ return close(sock); } int set_s_block(int sock){ int flags = fcntl(sock,F_GETFL,0); return fcntl(sock,F_SETFL, flags & (~O_NONBLOCK)); } int set_s_nonblock(int sock){ int flags = fcntl(sock,F_GETFL,0); return fcntl(sock,F_SETFL, flags | O_NONBLOCK ); } int name_socket(int sock, int port){ struct sockaddr_in name; name.sin_family = AF_INET; name.sin_port = htons(port); name.sin_addr.s_addr = htonl(INADDR_ANY); int bound = bind(sock,(struct sockaddr*)&name,sizeof(struct sockaddr_in)); if (bound == -1){ char msg[] = "Bind Error!"; perror(msg); } return bound; } int set_dest_addr(struct sockaddr_in* addr, char* addr_string,int port){ addr->sin_family = AF_INET; addr->sin_port = htons(port); int ret = inet_pton(AF_INET,addr_string,&(addr->sin_addr)); return ret; }
1
#include <pthread.h> void Funcion_Error(int nHilos, FILE *fp,int numLns); int numero_lineas(char *ruta, int *tam_lineas); void * countWords(void * datosNecesarios); void * printEstado(void * arg); struct structuraHilo{ FILE *fp; int InicioLeer; int lineaIn; int *tam_lineas; int lineaFin; }; int numero_Caracteres = 0; int numero_Palabras = 0; char** palabras; int num_palabras[100]; pthread_mutex_t mutex; int main(int argc, char** argv) { if( argc<4 ){ Funcion_Error(1,(void*)1,0); return -1; } else{ int nHilos = atoi(argv[2]); char *ruta = argv[1]; FILE *fp = fopen(ruta,"r"); if(fp==0 || nHilos<=0) { Funcion_Error(nHilos,fp,0); return -1; } numero_Palabras = argc - 3; palabras=(char**)malloc(sizeof(char*)*numero_Palabras); for(int i = 0; i<numero_Palabras; i++){ palabras[i]=argv[i+3]; num_palabras[i]=0; } int *tam_lineas = (int*)malloc(sizeof(int)*10000000); int numeroDeLineas = numero_lineas(ruta,tam_lineas); if(numeroDeLineas>10000000){ Funcion_Error(1,(void*)1,1); return -1; } int numCharDivisible = numero_Caracteres; while((numCharDivisible % nHilos)!=0) numCharDivisible -= 1; int charxHilo = numCharDivisible/nHilos; pthread_t * idHilos = (pthread_t *)malloc(sizeof(pthread_t) * nHilos); if (pthread_mutex_init(&mutex, 0) != 0){ printf("\\nInicializacion de mutex fallida\\n"); return -1; } int lineaInicio = 0; int lnItr=0; int inicioLeer=0; int caracteres=0; int hilosCreados=0; for (int xHilo=0; xHilo<nHilos && caracteres<numero_Caracteres ; xHilo++){ struct structuraHilo *params = (struct structuraHilo*)malloc(sizeof(struct structuraHilo)); int charHiloActual = 0; do{ charHiloActual += tam_lineas[lnItr]; caracteres += tam_lineas[lnItr]; lnItr++; } while( (charHiloActual+tam_lineas[lnItr]) < charxHilo ); params->fp=fp; params->InicioLeer=inicioLeer; params->lineaIn=lineaInicio; if ( xHilo == nHilos-1 ) params->lineaFin = numeroDeLineas-1; else params->lineaFin = lnItr-1; params->tam_lineas=tam_lineas; if ((pthread_create(&(idHilos[xHilo]), 0, countWords, (void *)params)<0)){ printf("Algo salio mal con la creacion del hilo\\n"); return -1; } lineaInicio=lnItr; inicioLeer=caracteres; hilosCreados++; if(lnItr == (numeroDeLineas -1) || lineaInicio == (numeroDeLineas-1)) break; } pthread_t idHiloImpresion; if (pthread_create(&idHiloImpresion, 0, printEstado, 0)<0) { printf("Algo salio mal con la creacion del hilo de impresion\\n"); return -1; } for(int i = 0; i<hilosCreados; i++){ int status = pthread_join(idHilos[i], 0); if(status < 0){ fprintf(stderr, "Error al esperar por el hilo %i\\n",i); exit(-1); } } fclose(fp); for(int i = 0; i<numero_Palabras; i++) { printf("palabra%i: %s aparece %i veces\\n",i+1,palabras[i],num_palabras[i]); } } return 0; } void Funcion_Error(int nHilos, FILE *fp, int numLns){ if(numLns==0){ printf("Error en los parametros introducidos\\n"); if(nHilos<=0) printf(" Ingresar un numero de hilos para el programa\\n"); } else printf("\\nError"); } int numero_lineas(char *ruta, int *tam_lineas){ if(ruta != 0) { FILE* ar = fopen(ruta,"r"); int lineas = 0; int tam_linea_actual = 0; while( !feof(ar) && (lineas<10000000) ){ tam_linea_actual++; numero_Caracteres++; char c = getc(ar); if(c == '\\n'){ if(tam_lineas != 0){ tam_lineas[lineas] = tam_linea_actual; } lineas++; tam_linea_actual=0; } } fclose(ar); return lineas; } return -1; } void * printEstado(void * arg) { while(1) { pthread_mutex_lock(&mutex); for(int i = 0; i<numero_Palabras; i++) { printf("palabra%i: %s aparece %i veces\\n",i+1,palabras[i],num_palabras[i]); } printf("\\n"); pthread_mutex_unlock(&mutex); sleep(1); } } void * countWords(void * datosStruct) { struct structuraHilo *r = (struct structuraHilo*)datosStruct; for(int i = r->lineaIn; i <= r->lineaFin; i++) { int tam = (r->tam_lineas[i]); char *buff; buff = (char *)malloc(sizeof(char)*tam); pthread_mutex_lock(&mutex); fseek(r->fp,r->InicioLeer,0); fgets(buff,tam,r->fp); pthread_mutex_unlock(&mutex); char *token; { for(int j=0; j<numero_Palabras;j++) { int comp = strcmp(token,palabras[j]); if( comp == 0 ) { pthread_mutex_lock(&mutex); (num_palabras[j])++; pthread_mutex_unlock(&mutex); } } } (r->InicioLeer) += tam; } return (void *)0; }
0
#include <pthread.h> pthread_mutex_t kljuc; pthread_cond_t pun, prazan; int ulaz=0, izlaz=0; int M[5]; int duljina=0; int pun_brojac=0; int prazan_brojac=1; int broj_proiz; int kolicina_u_spremniku=0; char *s; int index; }podaci; void * proizvodjac(void *podatak){ podaci* p = (podaci*) podatak; char *s = p->s; int index = p->index; int i = 0; while( 1 ){ pthread_mutex_lock(&kljuc); while( kolicina_u_spremniku == 5 ){ pthread_cond_wait(&pun, &kljuc); } M[ulaz] = s[i]; printf("PROIZVODJAČ%d -> %c\\n", index, s[i]); ulaz = ( ulaz + 1 ) % 5; kolicina_u_spremniku++; if( kolicina_u_spremniku == 1 ){ pthread_cond_signal(&prazan); } pthread_mutex_unlock(&kljuc); if( s[i] == '\\0' ) break; i += 1; sleep( 1 ); } } void* potrosac(void *podaci){ char *s = malloc(duljina+1); int i = 0; while( 1 ){ pthread_mutex_lock(&kljuc); while( kolicina_u_spremniku == 0 ){ pthread_cond_wait(&prazan, &kljuc); } if( M[izlaz] != '\\0') s[i++] = M[izlaz]; else broj_proiz--; printf( "POTROŠAC <- %c\\n", M[izlaz]); izlaz = ( izlaz + 1 ) % 5; --kolicina_u_spremniku; if( kolicina_u_spremniku == 4 ){ pthread_cond_broadcast(&pun); } pthread_mutex_unlock(&kljuc); if( broj_proiz == 0 ) break; } s[i] = '\\0'; printf("Primljeno je: %s\\n", s); } int main(int argc, char **argv){ if( argc < 2 ){ printf("Treba biti vise argumenata komandne linije\\n"); exit( 1 ); } if (pthread_mutex_init(&kljuc, 0) != 0) { printf("Mutex init greska!\\n"); return 1; } if(pthread_cond_init(&pun, 0) != 0) { printf("Pun init greska!\\n"); return 1; } if(pthread_cond_init(&prazan, 0) != 0) { printf("Prazan init greska!\\n"); return 1; } int i; broj_proiz = argc - 1; for( i = 1; i < argc; ++i ) duljina += strlen( argv[i] ) + 1; pthread_t *dretve = malloc( ( argc -1 ) * sizeof( pthread_t ) ); podaci* polje = malloc( (argc -1 ) * sizeof( podaci ) ); for( i = 0; i < argc-1; ++i ){ polje[i].s = argv[i+1]; polje[i].index = i; if( pthread_create( &dretve[i], 0, proizvodjac, &polje[i] ) ){ printf("Greska: pthrad_create\\n"); exit( 1 ); } } pthread_t *potr = malloc( sizeof( pthread_t ) ); pthread_create( &potr[0], 0, potrosac, 0 ); for( i=0; i < argc-1; ++i ) pthread_join(dretve[i], 0); pthread_join(potr[0], 0); pthread_mutex_destroy(&kljuc); free(polje); free(dretve); free(potr); return 0; }
1
#include <pthread.h> pthread_t left_mouse_thread, right_mouse_thread; struct mouse_data* working_data; pthread_mutex_t working_data_mutex = PTHREAD_MUTEX_INITIALIZER; unsigned char left_data[3]; unsigned char right_data[3]; int left_mouse_fd; int right_mouse_fd; void left_mouse_counter(void * blah){ while(1){ read(left_mouse_fd, left_data, 3); pthread_mutex_lock(&working_data_mutex); if(left_data[2] < 128){ working_data->left_mouse_y_delta += left_data[2]; } if(left_data[2] > 128){ working_data->left_mouse_y_delta -= (255 - left_data[2]); } if(left_data[1] < 128){ working_data->left_mouse_x_delta += left_data[1]; } if(left_data[1] > 128){ working_data->left_mouse_x_delta -= (255 - left_data[1]); } pthread_mutex_unlock(&working_data_mutex); } } void right_mouse_counter(void * blah){ while(1){ read(right_mouse_fd, right_data, 3); pthread_mutex_lock(&working_data_mutex); if(right_data[2] < 128){ working_data->right_mouse_y_delta += right_data[2]; } if(right_data[2] > 128){ working_data->right_mouse_y_delta -= (255 - right_data[2]); } if(right_data[1] < 128){ working_data->right_mouse_x_delta += right_data[1]; } if(right_data[1] > 128){ working_data->right_mouse_x_delta -= (255 - right_data[1]); } pthread_mutex_unlock(&working_data_mutex); } } struct mouse_data* get_latest_vector(){ struct mouse_data* r = malloc(sizeof( struct mouse_data)); pthread_mutex_lock(&working_data_mutex); memcpy(r, working_data, sizeof( struct mouse_data)); memset(working_data, 0, sizeof( struct mouse_data)); pthread_mutex_unlock(&working_data_mutex); return r; } void init_mouse_encoder(){ working_data = malloc(sizeof( struct mouse_data )); if((left_mouse_fd = open("/dev/input/mouse2", O_RDONLY)) < 0){ perror("opening left mouse file"); return; } if((right_mouse_fd = open("/dev/input/mouse1", O_RDONLY)) < 0){ perror("opening right mouse file"); return; } pthread_create(&left_mouse_thread, 0, left_mouse_counter, (void *) 0); pthread_create(&right_mouse_thread, 0, right_mouse_counter,(void *) 0); }
0
#include <pthread.h> struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; pthread_mutexattr_t attr; pthread_mutex_t mutex; int makethread(void * (*fn)(void *), void *arg) { int err; pthread_t tid; pthread_attr_t attr; err = pthread_attr_init(&attr); if (err != 0) { return err; } err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (0 == err) { err = pthread_create(&tid, &attr, fn, arg); } pthread_attr_destroy(&attr); return err; } void *timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return (0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_sec * 1000; if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void*)tip); if (0 == err) { return; } } } (*func)(arg); } void retry(void *arg) { pthread_mutex_lock(&mutex); printf("retry\\n"); pthread_mutex_unlock(&mutex); } int main(void) { int err; int condition; int arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) { printf("pthread_mutexattr_init failed:%s\\n", strerror(err)); exit(1); } if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) { printf("can't set recursive type:%s\\n", strerror(err)); exit(1); } if ((err = pthread_mutex_init(&mutex, &attr)) != 0) { printf("can't create recursive mutex:%s\\n", strerror(err)); exit(1); } pthread_mutex_lock(&mutex); if (condition) { timeout(&when, retry, (void*)arg); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int counter; void *task(void *tid) { for(int i = 0; i < 1000000; i++) { pthread_mutex_lock(&mutex); counter += 1; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t threads[20]; int thread_args[20]; int rc, i; for(i = 0; i < 20; ++i) { thread_args[i] = i; rc = pthread_create(&threads[i], 0, task, (void *) &thread_args[i]); assert(0 == rc); } for(i = 0; i < 20; ++i) { rc = pthread_join(threads[i], 0); printf("In main: thread %d is complete\\n", i); assert(0 == rc); } printf("Final value of counter is: %d\\n", counter); printf("Expected value is: %d\\nOff by: %d\\n", 20 * 1000000, 20 * 1000000 - counter); pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=27); return 0; } void *thread2() { pthread_mutex_lock(&mx); x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; pthread_mutex_unlock(&mx); return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
1
#include <pthread.h> int putqueue(int Q[],int *front,int *rear,int item) { sem_wait(&writer); if((*rear+1)%MAX==*front) { printf("Queue overflow\\n"); } if(END==*front) { pthread_mutex_lock(&mut); *front=0; *rear=0; pthread_mutex_unlock(&mut); } else { pthread_mutex_lock(&mut); *rear=(*rear+1)%MAX; pthread_mutex_unlock(&mut); } pthread_mutex_lock(&mut); Q[*rear]=item; pthread_mutex_unlock(&mut); sem_post(&reader); return SUCCESS; } int getqueue(int Q[],int *front,int *rear) { int item; sem_wait(&reader); if(END==*front) { printf("Queue is empty\\n"); } else if(*front==*rear) { pthread_mutex_lock(&mut); item=Q[*front]; *front=END; *rear=END; pthread_mutex_unlock(&mut); sem_post(&writer); return item; } else { pthread_mutex_lock(&mut); item=Q[*front]; *front=(*front+1)%MAX; pthread_mutex_unlock(&mut); sem_post(&writer); return item; } } int initqueue(int Q[],int front,int rear) { int i; for(i=front;i<rear;i++) Q[front]=0; return SUCCESS; }
0
#include <pthread.h> void * run_dynamixel_comm(void * var){ int hz = 100; Dynam_Init(&dynam); pthread_mutex_lock(&dynamixel_mutex); bus.servo[0].id = 1; bus.servo[1].id = 2; bus.servo[0].cmd_mode = WHEEL; bus.servo[1].cmd_mode = WHEEL; Dynam_SetMode(&dynam,&(bus.servo[0])); Dynam_SetMode(&dynam,&(bus.servo[1])); pthread_mutex_unlock(&dynamixel_mutex); while(1){ pthread_mutex_lock(&dynamixel_mutex); switch(bus.servo[0].cmd_flag){ case (NONE): break; case (CMD): Dynam_Command(&dynam,&(bus.servo[0])); break; case (MODE): Dynam_SetMode(&dynam,&(bus.servo[0])); break; case (STATUS): Dynam_Status(&dynam, &(bus.servo[0])); break; } switch(bus.servo[1].cmd_flag){ case (NONE): break; case (CMD): Dynam_Command(&dynam,&(bus.servo[1])); break; case (MODE): Dynam_SetMode(&dynam,&(bus.servo[1])); break; case (STATUS): Dynam_Status(&dynam, &(bus.servo[1])); break; } pthread_mutex_unlock(&dynamixel_mutex); usleep(1000000/hz); } Dynam_Deinit(&dynam); }
1
#include <pthread.h> void* print_msg_func(void *ptr); pthread_mutex_t gmutex1 = PTHREAD_MUTEX_INITIALIZER; int gcounter; int main() { gcounter = 0; pthread_t thread[10]; char* msg = "Messange from thread"; int ret[10]; int i,j; for(i=0; i<10; i++) { ret[i] = pthread_create(&thread[i], 0, print_msg_func, msg); } for(j=0; j<10; j++) { pthread_join(thread[j], 0); } for(j=0; j<10; j++) { printf("Thread %ld returns: %d\\n",thread[j], ret[j]); } return 1; } void* print_msg_func(void *ptr) { char* msg; msg = (char*) ptr; printf("Thread number %ld\\n", pthread_self()); pthread_mutex_lock( &gmutex1 ); gcounter++; printf("%s: counter is: %d\\n",msg,gcounter); pthread_mutex_unlock( &gmutex1 ); }
0
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can't set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> void *philosopher(void *arg); int food_left(); void pick_chop(int p, int c, char *hand); void drop_chop(int c1, int c2); pthread_mutex_t food_lock; pthread_mutex_t chopstick[5]; pthread_t philos[5]; int main(int argn, char* argv[]){ pthread_attr_t attr; int rc; long t; void* status; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&food_lock, 0); for(t = 0; t<5; t++){ pthread_mutex_init(&chopstick[t],0); } for(t = 0; t<5; t++){ rc = pthread_create(&philos[t], &attr, philosopher, (void*)t); if(rc){ printf("ERROR: Return from pthread_create() is %d\\n", rc); } } for(t=0; t<5; t++){ rc = pthread_join(philos[t], &status); if(rc){ printf("ERROR: Return from pthread_join() is %d\\n", rc); } } printf("FOOD Finished!\\nExiting.."); return 0; } void *philosopher(void *arg){ int left_chop, right_chop, f = 200; int tid = (int*)arg; right_chop = tid; left_chop = tid+1; printf("Food left = %d\\n",f); if(left_chop == 5){ left_chop = 0; } while(f = food_left()){ if(tid == 1){ sleep(1); } printf("Philosopher %d is now thinking..\\n", tid); printf("Philosopher %d is now hungry..\\n", tid); pick_chop(tid, right_chop, "Right hand"); pick_chop(tid, left_chop, "Left hand"); printf("Philosopher %d is now eating..\\n", tid); usleep(5000 * (200 - f + 1)); drop_chop(left_chop, right_chop); } return (0); } int food_left(){ static int food = 200; int myfood; pthread_mutex_lock(&food_lock); if(food>0){ food--; } myfood = food; pthread_mutex_unlock(&food_lock); return myfood; } void pick_chop(int id, int c, char* hand){ pthread_mutex_lock(&chopstick[c]); printf("Philosspher %d picked Chopstick %d in %s\\n",id,c,hand); } void drop_chop(int c1, int c2){ pthread_mutex_unlock(&chopstick[c1]); pthread_mutex_unlock(&chopstick[c2]); }
0
#include <pthread.h> char password[9] = "aaaaaaaa"; pthread_mutex_t alock; int keysize; char *target; char *salt; }passwordData; void *passwordLooper(void *arg); int main(int argc, char *argv[]){ int i = 0; if (argc != 4) { fprintf(stderr, "Too few/many arguements give.\\n"); fprintf(stderr, "Proper usage: ./crack threads keysize target\\n"); exit(0); } int threads = *argv[1]-'0'; int keysize = *argv[2]-'0'; char target[9]; strcpy(target, argv[3]); char salt[10]; while ( i < 2 ){ salt[i] = target[i]; i++; } printf("threads = %d\\n", threads); printf("keysize = %d\\n", keysize); printf("target = %s\\n", target); printf("salt = %s\\n", salt); if (threads < 1 || threads > 8){ fprintf(stderr, "0 < threads <= 8\\n"); exit(0); } if (keysize < 1 || keysize > 8){ fprintf(stderr, "0 < keysize <= 8\\n"); exit(0); } pthread_mutex_init(&alock, 0); pthread_t t[threads]; passwordData *pwd = (passwordData*) malloc(sizeof(passwordData)); pwd->keysize= keysize; pwd->target = target; pwd->salt = salt; for (i = 0; i < threads ; i++){ pthread_create(&t[i], 0, passwordLooper, (void*)pwd); } for (i = 0; i < threads; i++){ pthread_join(t[i],0); } } void *passwordLooper(void *arg){ passwordData *pwd = (passwordData *)arg; int result; struct crypt_data data; data.initialized = 0; int level = 0; int ks = pwd->keysize; password[ks] = 0; char localpw[9]; char *target = pwd->target; char *s = pwd->salt; while (level < ks){ level = 0; pthread_mutex_lock(&alock); while (level < ks) { if (password[level] >= 'a' && password[level] < 'z'){ password[level]++; break; } if (password[level] == 'z'){ password[level] = 'a'; level++; } } strcpy(localpw, password); pthread_mutex_unlock(&alock); if (strcmp( crypt_r(localpw, s, &data), target ) == 0){ printf("password found!\\n"); printf("Password = %s\\n", localpw); exit(0); } } if (level >= ks){ printf("Password not found\\n"); exit(0); } return 0; }
1
#include <pthread.h> struct thread_info { pthread_t thread_id; int thread_num; char *thread_para; }; int num = 0; pthread_mutex_t mutex; static void * thread_start(void *arg) { struct thread_info *tinfo = (struct thread_info *)arg; pthread_mutex_lock(&mutex); num++; printf("Thread: (%d) get num value: %d\\n", tinfo->thread_num, num); pthread_mutex_unlock(&mutex); pthread_exit((void *)"T1"); } int main(int argc, char **argv) { int s, tnum, opt, num_threads; struct thread_info *tinfo; pthread_attr_t attr; void *res; num_threads = 1; while ((opt = getopt(argc, argv, "n:")) != -1) { switch (opt) { case 'n': num_threads = strtoul(optarg, 0, 0); break; default: fprintf(stderr, "Usage: %s [-n pthread-num] arg...\\n", argv[0]); exit(1); } } tinfo = calloc(num_threads, sizeof(struct thread_info)); if (tinfo == 0) perror("calloc"); s = pthread_attr_init(&attr); if (s != 0) do { errno = s; perror("pthread_attr_init"); exit(1); } while(0);; s = pthread_mutex_init(&mutex, 0); if(s != 0) do { errno = s; perror("pthread_mutex_init"); exit(1); } while(0);; for(tnum = 0; tnum < num_threads; tnum++) { s = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (s != 0) do { errno = s; perror("pthread_attr_setdetachstate"); exit(1); } while(0);; s = pthread_create(&tinfo[tnum].thread_id, &attr, &thread_start, &tinfo[tnum]); if (s != 0) do { errno = s; perror("pthread_create"); exit(1); } while(0);; tinfo[tnum].thread_num = tnum + 1; } s = pthread_mutex_destroy(&mutex); if(s != 0) do { errno = s; perror("pthread_mutex_destroy"); exit(1); } while(0);; s = pthread_attr_destroy(&attr); if (s != 0) do { errno = s; perror("pthread_attr_destroy"); exit(1); } while(0);; sleep(1000); free(tinfo); exit(0); return 0; }
0
#include <pthread.h> int big_int; pthread_mutex_t pmt; void* thread(void *p) { printf("Thread:start add!\\n"); p = (int*)6; int i; for(i = 0;i < 20000000;i++) { pthread_mutex_lock(&pmt); big_int++; pthread_mutex_unlock(&pmt); } printf("Thread:I have added up!\\n"); pthread_exit(p); } int main(void) { big_int = 0; int i; void *p = malloc(sizeof(int)); pthread_t pt; printf("big_int = %d\\n",big_int); int ret = pthread_mutex_init(&pmt,0); if(ret != 0) { printf("Main:pthread_mutex_init error(%d)\\n",ret); return -1; } printf("Main:start add with child!\\n"); ret = pthread_create(&pt,0,thread,p); if(ret != 0) { printf("Main:pthread_create error(%d)\\n",ret); return -1; } for(i = 0;i < 20000000;i++) { pthread_mutex_lock(&pmt); big_int++; pthread_mutex_unlock(&pmt); } printf("Main:wait my child.\\n"); ret = pthread_join(pt,(void**)p); if(ret != 0) { printf("Main:pthread_join error(%d)\\n",ret); return -1; } printf("p = %d\\n",*((int*)p)); ret = pthread_mutex_destroy(&pmt); if(ret != 0) { printf("Main:pthread_mutex_destory error(%d)\\n",ret); return -1; } printf("big_int = %d\\n",big_int); return 0; }
1
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset * len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i = start; i < end; i++) mysum += x[i] * y[i]; pthread_mutex_lock(&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock(&mutexsum); pthread_exit((void*)0); } int main(int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*)malloc(4 * 100 * sizeof(double)); b = (double*)malloc(4 * 100 * sizeof(double)); for (i = 0; i < 100 * 4; i++) { a[i] = 1.0; b[i] = a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum = 0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for (i = 0; i < 4; i++) { pthread_create(&callThd[i], &attr, dotprod, (void*)i); } pthread_attr_destroy(&attr); for (i = 0; i < 4; i++) pthread_join(callThd[i], &status); printf("Sum = %f\\n", dotstr.sum); free(a); free(b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
0
#include <pthread.h> { char value[4]; char name[16]; } key_t; key_t keys[] = { { { 0x1b, 0x5b, 0x41 }, "dir up" }, { { 0x1b, 0x5b, 0x42 }, "dir down" }, { { 0x1b, 0x5b, 0x43 }, "dir right" }, { { 0x1b, 0x5b, 0x44 }, "dir left" }, }; { int dx; int dy; } dir_t; dir_t dirs[] = { { -1, 0 }, { 1, 0 }, { 0, 1 }, { 0, -1 }, }; struct snake { int x; int y; dir_t dir; } xiaolong = { 25/2, 25/2, { 0, 1 } }; struct snake_body { int x; int y; struct snake_body * next; }; struct snake_body * head; struct snake_body * tail; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; int eaten = 0; int foodx = 25/2, foody = 25/2; int board[25][25]; void * producer(void * arg) { key_t current_key; while (1) { char c; int i; c = getchar(); if (c == 'q' || c == 3) { system("stty -raw echo"); exit(0); } if (c == 0x1b && getchar() == 0x5b) { c = getchar(); for (i = 0; i < sizeof(keys)/sizeof(keys[0]); i++) { if (c == keys[i].value[2]) { pthread_mutex_lock(&lock); current_key = keys[i]; printf("producer: %s\\r\\n", keys[i].name); xiaolong.dir = dirs[i]; xiaolong.x += xiaolong.dir.dx; xiaolong.y += xiaolong.dir.dy; if (xiaolong.x == foodx && xiaolong.y == foody) { foodx = rand() % 25; foody = rand() % 25; } pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); } } } } } void * producer2(void * arg) { while (1) { usleep(1000*500); pthread_mutex_lock(&lock); xiaolong.x += xiaolong.dir.dx; xiaolong.y += xiaolong.dir.dy; if (head == tail) { head->x = xiaolong.x; head->y = xiaolong.y; } else { struct snake_body * p; tail->x = xiaolong.x; tail->y = xiaolong.y; tail->next = head; p = head; head = tail; while (p->next != tail) p = p->next; tail = p; tail->next = 0; } if (xiaolong.x == foodx && xiaolong.y == foody) { struct snake_body * pbody; pbody = malloc(sizeof(*pbody)); pbody->x = xiaolong.x; pbody->y = xiaolong.y; pbody->next = head; head = pbody; foodx = rand() % 25; foody = rand() % 25; } pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); } } void * consumer(void * arg) { while (1) { int i, j; pthread_mutex_lock(&lock); pthread_cond_wait(&has_product, &lock); system("clear"); for (i = 0; i < 25; i++) for (j = 0; j < 25; j++) board[i][j] = '.'; board[foodx][foody] = '$'; struct snake_body * p = head; do { p = p->next; } while (p != 0); for (i = 0; i < 25; i++) { for (j = 0; j < 25; j++) { printf("%c ", board[i][j]); } printf("\\n\\r"); } pthread_mutex_unlock(&lock); } } int main(void) { pthread_t pid, pid2, cid; struct snake_body * pbody; pbody = malloc(sizeof(*pbody)); pbody->x = xiaolong.x; pbody->y = xiaolong.y; head = pbody; tail = pbody; pbody = malloc(sizeof(*pbody)); pbody->x = xiaolong.x; pbody->y = xiaolong.y - 1; tail = pbody; head->next = tail; tail->next = 0; system("stty raw -echo"); pthread_create(&pid, 0, producer, 0); pthread_create(&pid2, 0, producer2, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(pid2, 0); pthread_join(cid, 0); system("stty -raw echo"); return 0; }
1
#include <pthread.h> struct hostent *my_gethostbyname_r(const char *name, struct hostent *res , char *buffer , int buflen , int *h_errnop) { struct hostent *hp; pthread_mutex_lock(&LOCK_gethostbyname_r); hp= gethostbyname(name); *h_errnop= h_errno; return hp; } void my_gethostbyname_r_free() { pthread_mutex_unlock(&LOCK_gethostbyname_r); }
0
#include <pthread.h> pthread_mutex_t chave_vetor; pthread_cond_t condc, condp; int vetor[5]; int quantidade, prod, cons; void* produtor(void *arg) { while(1) { printf("Produtor: antes do lock\\n"); pthread_mutex_lock(&chave_vetor); printf("Produtor: depois do lock\\n"); while (quantidade >= 5) { printf("Produtor dormiu\\n"); pthread_cond_wait(&condp, &chave_vetor); } vetor[prod]=rand()%10+1; printf("Produzido: Vetor[%d]=%d\\n",prod,vetor[prod]); prod=(prod+1)%5; quantidade++; printf("Quantidade = %d\\n",quantidade); pthread_cond_signal(&condc); pthread_mutex_unlock(&chave_vetor); printf("Produtor: saiu do lock\\n"); sleep(rand()%3); } pthread_exit(0); } void* consumidor(void *arg) { while(1) { printf("Consumidor: antes do lock\\n"); pthread_mutex_lock(&chave_vetor); printf("Consumidor: depois do lock\\n"); while (quantidade <= 0) { printf("Consumidor dormiu\\n"); pthread_cond_wait(&condc, &chave_vetor); } printf("Consumido: Vetor[%d]=%d\\n",cons,vetor[cons]); cons=(cons+1)%5; quantidade--; printf("Quantidade = %d\\n",quantidade); pthread_cond_signal(&condp); pthread_mutex_unlock(&chave_vetor); printf("Consumidor: saiu do lock\\n"); sleep(rand()%3); } pthread_exit(0); } int main(int argc, char **argv) { pthread_t pro, con; int codigo_de_erro; quantidade=0; prod=0; cons=0; pthread_mutex_init(&chave_vetor, 0); pthread_cond_init(&condc, 0); pthread_cond_init(&condp, 0); codigo_de_erro = pthread_create(&con, 0, consumidor, 0); if(codigo_de_erro != 0) { printf("Erro na criação de thread filha, Codigo de erro %d\\n", codigo_de_erro); exit(1); } codigo_de_erro = pthread_create(&pro, 0, produtor, 0); if(codigo_de_erro != 0) { printf("Erro na criação de thread filha, Codigo de erro %d\\n", codigo_de_erro); exit(1); } pthread_join(con, 0); pthread_join(pro, 0); pthread_mutex_destroy(&chave_vetor); pthread_cond_destroy(&condc); pthread_cond_destroy(&condp); return 0; }
1
#include <pthread.h> struct skynetCore_t{ pthread_mutex_t protector; pid_t pid; }; int set_priority(int priority) { int policy; struct sched_param param; if (priority < 1 || priority > 63) return -1; pthread_getschedparam(pthread_self(), &policy, &param); param.sched_priority = priority; return pthread_setschedparam(pthread_self(), policy, &param); } int get_priority() { int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, &param); return param.sched_curpriority; } int main(int argc, char *argv[]) { set_priority(3); int skynetDesc = shm_open("/skynetcore", O_RDWR | O_CREAT, S_IRWXU); ftruncate(skynetDesc, sizeof(struct skynetCore_t)); struct skynetCore_t* skynetCore = mmap(0, sizeof(struct skynetCore_t), PROT_READ|PROT_WRITE, MAP_SHARED, skynetDesc, 0); pthread_mutexattr_t skynetProtectorAttr; pthread_mutexattr_init(&skynetProtectorAttr); pthread_mutexattr_setpshared(&skynetProtectorAttr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&skynetCore->protector, &skynetProtectorAttr); pthread_mutex_lock(&skynetCore->protector); skynetCore->pid = getpid(); pthread_mutex_unlock(&skynetCore->protector); int SkynetChannelId = ChannelCreate(0); int SkynetCode; struct _msg_info SkynetClientInfo; while(1){ printf("My priority before receiving is %i\\n", get_priority()); int receivedMessageId = MsgReceive(SkynetChannelId, &SkynetCode, sizeof(int), &SkynetClientInfo); printf("My priority after receiving is %i\\n", get_priority()); printf("I got %i from the skynet client with pid %i and thread id %i\\n", SkynetCode, SkynetClientInfo.pid, SkynetClientInfo.tid); SkynetCode += 1; MsgReply(receivedMessageId, 0, &SkynetCode, sizeof(int)); } return 0; }
0
#include <pthread.h> struct { int a; int b; } foo; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void * thread(void *x) { intptr_t data = (intptr_t) x; while (1) { pthread_mutex_lock(&mutex); if (foo.a != foo.b) { if (data == 0) write(1, "|", 1); else write(1, "_", 1); } foo.a = data; foo.b = data; pthread_mutex_unlock(&mutex); } } int main(void) { pthread_t t1, t2; pthread_create(&t1, 0, thread, (void *) 0); pthread_create(&t2, 0, thread, (void *) 1); pthread_join(t1, 0); pthread_join(t2, 0); return (0); }
1
#include <pthread.h> struct timespec some_time = {0, 10000}; FILE *fptr; pthread_mutex_t LOCK, *m_LOCK = &LOCK; int setup, *s_shm = &setup, current, *c_shm = &current; void produce(void) { int err, *n = 0; printf("%2d P: attempting ot produce \\t %3d\\n", pthread_self(), getpid()); FF; if (pthread_mutex_trylock(m_LOCK) != 0) { printf("%2d P: lock busy \\t %3d\\n", pthread_self(), getpid()); FF; return; } n = (int *)malloc(sizeof(int) * 1); if (n == 0) { printf("%2d P: malloc n error \\t %3d\\n", pthread_self(), getpid()); return; } TRAND(MAX, *n); if ((fptr = fopen(BUFFER, "a")) == 0) { perror(BUFFER); exit(101); } fprintf(fptr, "%3d", *n); fflush(fptr); fclose(fptr); FF; free(n); n = 0; nanosleep(&some_time, 0); if ((err = pthread_mutex_unlock(m_LOCK)) != 0) { fprintf(stderr, "P: unlock mutex failure %\\n", err); exit(102); } printf("%2d P: thread exit! \\t %3d\\n", pthread_self(), getpid()); } void consume(void) { int err, *n = 0; printf("%2d C: attempting to consume \\t %3d\\n", pthread_self(), getpid()); if (pthread_mutex_trylock(m_LOCK) != 0) { printf("%2d C: lock busy \\t %3d\\n", pthread_self(), getpid()); FF; } if ((fptr = fopen(BUFFER, "r+")) == 0) { perror(BUFFER); exit(103); } fseek(fptr, *c_shm * 3, 0); n = (int *)malloc(sizeof(int)); if (n == 0) { printf("%2d C: malloc n error \\t %3d\\n", pthread_self(), getpid()); return; } *n = 0; fscanf(fptr, "%3d", n); if (*n > 0) { FF; fseek(fptr, *c_shm *3, 0); fprintf(fptr, "%3d", -(*n)); fflush(fptr); ++*c_shm; } else { FF; } fclose(fptr); free(n); n = 0; nanosleep(&some_time, 0); if ((err = pthread_mutex_unlock(m_LOCK)) != 0) { fprintf(stderr, "C: unlock failure %d\\n", err); exit(104); } printf("%2d C: thread exit \\t %3d\\n", pthread_self(), getpid()); } void do_work(void) { int i, n; if (!(*s_shm)) { pthread_mutex_lock(m_LOCK); if (!(*s_shm)++) { printf("%2d : clearing the buffer \\t %3d\\n", pthread_self(), getpid()); if ((fptr = fopen(BUFFER, "w+")) == 0) { perror(BUFFER); exit(105); } fclose(fptr); } pthread_mutex_unlock(m_LOCK); } nanosleep(&some_time, 0); for (i = 0; i < 10; ++i) { TRAND(2, n); switch(n) { case 1: produce(); break; case 2: consume(); break; } nanosleep(&some_time, 0); } } int main(int argc, char **argv) { pthread_mutexattr_t the_attr_obj; int i, n; int m_shmid, i_shmid; if (argc != 2) { fprintf(stderr, "Usage: %s n_workers\\n", *argv); return -1; } n = atoi(argv[1]) < MAX ? atoi(argv[1]) : MAX; if ((m_shmid = shmget(IPC_PRIVATE, sizeof(pthread_mutex_t), IPC_CREAT|0666)) < 0) { perror("shmget fail mutex\\n"); return -1; } if ((m_LOCK = (pthread_mutex_t *)shmat(m_shmid, 0, 0)) == (pthread_mutex_t*)-1) { perror("shmat fail mutex\\n"); return -1; } if ((i_shmid = shmget(IPC_PRIVATE, sizeof(int) * 2, IPC_CREAT | 0666 )) < 0) { perror("shmget fail ints\\n"); return -1; } if ((s_shm = (int *)shmat(i_shmid, 0, 0)) == (int *)-1) { perror("shat fail ints\\n"); return -1; } c_shm = s_shm + sizeof(int); *s_shm = 0; *c_shm = 0; pthread_mutexattr_init(&the_attr_obj); pthread_mutexattr_setpshared(&the_attr_obj, PTHREAD_PROCESS_SHARED); pthread_mutex_init(m_LOCK, &the_attr_obj); for (i = 0; i < n; ++i) { if (fork() == 0) { do_work(); exit(2); } } while((n = (int)wait(0)) && n != -1) { ; } shmdt((char *)m_LOCK); shmdt((char *)s_shm); shmctl(m_shmid, IPC_RMID, (struct shmid_ds *)0); shmctl(i_shmid, IPC_RMID, (struct shmid_ds *)0); return 0; }
0
#include <pthread.h> char ch; int x,y; int step; }Word; char ch; short int flag; }inputChar; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; Word *arry; inputChar* inputarry; int score=0; int lose=0; void initArry(int len,int cols,int step) { int i; for(i=0;i<len;++i){ arry[i].ch=rand()%26+'a'; arry[i].x=(i+1)*cols-1; arry[i].y=0; arry[i].step=step; } } void* showChars(void* arg) { int nums = *((int*)arg); while(arry){ int i; pthread_mutex_lock(&m); for(i=0;i<nums;++i){ int j; for(j=0;j<arry[i].y;++j) mvaddch(j,arry[i].x,' '); mvaddch(arry[i].y,arry[i].x,arry[i].ch); arry[i].y += arry[i].step; } pthread_mutex_unlock(&m); refresh(); pthread_mutex_lock(&m); for(i=0;i<nums;++i){ if(arry[i].y>=LINES-1 && arry[i].ch!=' '){ arry[i].ch=rand()%26+'a'; arry[i].y=0; ++lose; } } pthread_mutex_unlock(&m); sleep(1); } return 0; } void* inputChars(void* arg) { int nums =*((int*)arg); while(1){ noecho(); int ch=getch(); int n; pthread_mutex_lock(&m); for(n=0;n<nums;++n){ if(ch==arry[n].ch){ ++score; arry[n].ch=' '; } } pthread_mutex_unlock(&m); } } int main() { initscr(); srand(time(0)); int selfStep=1; int selfNums=8; arry = (Word*)calloc(0,selfNums*sizeof(Word)); initArry(selfNums,COLS/(selfNums+1),selfStep); pthread_t pid[2]; pthread_create(&pid[0],0,showChars,(void*)&selfNums); pthread_create(&pid[1],0,inputChars,(void*)&selfNums); pthread_join(pid[0],0); pthread_join(pid[1],0); free(inputarry); free(arry); pthread_mutex_destroy(&m); endwin(); return 0; }
1
#include <pthread.h> int contador; pthread_mutex_t mutex; sem_t semaforo_productor; sem_t semaforo_consumidor; void agregar(char c); void quitar(); void * productor() { while(1) { char c = 'a' + rand()%24; agregar(c); usleep(1000); } } void * consumidor() { while(1) { quitar(); usleep(1000); } } void * imprimir() { while(1){ int i; printf("%d",contador); printf("\\n"); usleep(1000); } } int main() { pthread_t thread_consumidor; pthread_t thread_productor; contador = 0; pthread_mutex_init(&mutex, 0); sem_init(&semaforo_productor, 0, 10); sem_init(&semaforo_consumidor, 0, 0); pthread_create(&thread_consumidor, 0, consumidor, 0 ); pthread_create(&thread_productor, 0, productor, 0 ); pthread_join(thread_consumidor, 0); return 0; } void agregar(char c) { sem_wait(&semaforo_productor); pthread_mutex_lock(&mutex); contador++; printf("%d\\n",contador); pthread_mutex_unlock(&mutex); sem_post(&semaforo_consumidor); } void quitar() { sem_wait(&semaforo_consumidor); pthread_mutex_lock(&mutex); contador--; printf("%d\\n",contador); pthread_mutex_unlock(&mutex); sem_post(&semaforo_productor); }
0
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; }; struct foo *foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
1
#include <pthread.h> int size; int ref_count; void *hdl; }pl_array_t; static pl_array_t pl_array[3] = { {1*(400), 0, 0} ,{4*(400), 0, 0} ,{26*(400), 0, 0} }; static pthread_mutex_t pl_mutex = PTHREAD_MUTEX_INITIALIZER; void *buf_pl_get(int mtu) { void *pl; int idx = (mtu<=pl_array[0].size) ?0:((mtu<=pl_array[1].size) ?1:((mtu<=pl_array[2].size)?2:-1)); if(idx < 0) { printf("%s >>>>>>>>>> err, BUF_POOL SUPPORT MAX_MTU:%d\\n", __FUNCTION__, 26*(400)); return 0; } pthread_mutex_lock(&pl_mutex); if(!pl_array[idx].hdl) { pl_array[idx].hdl = buf_pool_new(64, pl_array[idx].size, BUF_FLAG_GROWTH|BUF_FLAG_MUTEX); printf("%s >>>>>>>>>> buf_pool_new size:%d\\n", __FUNCTION__, pl_array[idx].size); } pthread_mutex_unlock(&pl_mutex); return pl_array[idx].hdl; } void buf_pl_rel(void *pl) { }
0
#include <pthread.h> int tunsrv_pendbufferwait = 0; int tunsrv_pendbuffer = 0; pthread_mutex_t tunsrv_pendbuffermutex; pthread_cond_t tunsrv_mainwaitcond; pthread_mutex_t tunsrv_mainwaitmutex; pthread_cond_t tunsrv_threadwaitcond; pthread_mutex_t tunsrv_threadwaitmutex; struct tunsrv_buffer_s { pthread_mutex_t buffer_mutex; int free; char buffer[TUNBUFFERSIZE]; int buffer_len; } *tunsrv_buffer; void tunsrv_thread() { int i; while (1) { pthread_mutex_lock(&tunsrv_threadwaitmutex); pthread_cond_wait(&tunsrv_threadwaitcond, &tunsrv_threadwaitmutex); pthread_mutex_unlock(&tunsrv_threadwaitmutex); for (i = 0; i < num_tunsrvbuffers; i++) { if (pthread_mutex_trylock(&tunsrv_buffer[i].buffer_mutex) == 0) { if (tunsrv_buffer[i].free != 0) pthread_mutex_unlock(&tunsrv_buffer[i].buffer_mutex); else { protocol_sendframe(tunsrv_buffer[i].buffer, tunsrv_buffer[i].buffer_len); tunsrv_buffer[i].free = 1; pthread_mutex_unlock(&tunsrv_buffer[i].buffer_mutex); pthread_mutex_lock(&tunsrv_pendbuffermutex); tunsrv_pendbuffer--; pthread_mutex_unlock(&tunsrv_pendbuffermutex); if (tunsrv_pendbufferwait) { pthread_mutex_lock(&tunsrv_mainwaitmutex); pthread_cond_signal(&tunsrv_mainwaitcond); pthread_mutex_unlock(&tunsrv_mainwaitmutex); } } } } } } void tunsrv() { int rc, i; pthread_t tunsrvthreads[num_tunsrvthreads]; pthread_mutex_init(&tunsrv_mainwaitmutex, 0); pthread_cond_init(&tunsrv_mainwaitcond, 0); pthread_mutex_init(&tunsrv_threadwaitmutex, 0); pthread_cond_init(&tunsrv_threadwaitcond, 0); tunsrv_buffer = malloc(num_tunsrvbuffers * sizeof(struct tunsrv_buffer_s)); for (i = 0; i < num_tunsrvbuffers; i++) { pthread_mutex_init(&tunsrv_buffer[i].buffer_mutex, 0); tunsrv_buffer[i].free = 1; } for (i = 0; i < num_tunsrvthreads; i++) { if ((rc = pthread_create(&tunsrvthreads[i], 0, (void *) &tunsrv_thread, 0))) { log_error("Thread %d creation failed: %d\\n", i, rc); break; } } while (1) { for (i = 0; i < num_tunsrvbuffers; i++) { if (pthread_mutex_trylock(&tunsrv_buffer[i].buffer_mutex) == 0) { if (tunsrv_buffer[i].free != 0) { tunsrv_buffer[i].free = 0; tunsrv_buffer[i].buffer_len = tundev_read(tunsrv_buffer[i].buffer, tunmtu); if (tunsrv_buffer[i].buffer_len > 0) { pthread_mutex_unlock(&tunsrv_buffer[i].buffer_mutex); pthread_mutex_lock(&tunsrv_pendbuffermutex); tunsrv_pendbuffer++; pthread_mutex_unlock(&tunsrv_pendbuffermutex); pthread_mutex_lock(&tunsrv_threadwaitmutex); pthread_cond_signal(&tunsrv_threadwaitcond); pthread_mutex_unlock(&tunsrv_threadwaitmutex); } else { tunsrv_buffer[i].free = 1; pthread_mutex_unlock(&tunsrv_buffer[i].buffer_mutex); log_error("Error reading form interface.\\n"); } } else pthread_mutex_unlock(&tunsrv_buffer[i].buffer_mutex); } } if (tunsrv_pendbuffer >= num_tunsrvbuffers) { tunsrv_pendbufferwait = 1; pthread_mutex_lock(&tunsrv_mainwaitmutex); pthread_cond_wait(&tunsrv_mainwaitcond, &tunsrv_mainwaitmutex); pthread_mutex_unlock(&tunsrv_mainwaitmutex); tunsrv_pendbufferwait = 0; } } }
1
#include <pthread.h> int num_switches = 10; pthread_mutex_t mtx; pthread_cond_t cond; pthread_t threads[2]; int i, done = 0; void *f( void *p ) { if( i > 1 ) { pthread_join( threads[ i % 2 ], 0 ); } ++i; if( i < num_switches ) { assert( !pthread_create( &threads[ ( i + 1 ) % 2 ], 0, f, 0 ) ); } else { done = 1; pthread_cond_signal( &cond ); } return p; } int main( int argc, char **argv ) { num_switches = ( argc > 1 ) ? (int)atol( argv[1] ) : 10; num_switches = 1 << num_switches; printf( "NUM_SWITCHES: %d\\n", num_switches ); pthread_mutex_init( &mtx, 0 ); pthread_cond_init( &cond, 0 ); assert( !pthread_create( &threads[0], 0, f, 0 ) ); pthread_mutex_lock( &mtx ); while( !done ) { pthread_cond_wait( &cond, &mtx ); } pthread_mutex_unlock( &mtx ); printf( "%d\\n", i ); return 0; }
0
#include <pthread.h> void show_alloc_mem(void) { pthread_mutex_lock(&g_fastmutex); show_alloc(0); pthread_mutex_unlock(&g_fastmutex); } void show_alloc_mem_hex(void) { pthread_mutex_lock(&g_fastmutex); show_alloc(1); pthread_mutex_unlock(&g_fastmutex); }
1
#include <pthread.h> void *thread_func1(void *ptr); void *thread_func2(void *ptr); static int s_val=0; pthread_mutex_t lock; int main(void) { pthread_t thread1, thread2; int iret1, iret2; iret1 = pthread_create( &thread1, 0, thread_func1, (void*)0); iret2 = pthread_create( &thread2, 0, thread_func2, (void*)0); pthread_join( thread1, 0 ); pthread_join( thread2, 0 ); pthread_mutex_destroy(&lock); return 0; } static void set_val(int val) { s_val = val; } static int get_val(void) { return s_val; } const int kIntvl_usec = 100000; void *thread_func1(void *ptr) { int loop; usleep(kIntvl_usec); for(loop=0; loop<10; loop++) { pthread_mutex_lock(&lock); set_val(get_val() + 1); pthread_mutex_unlock(&lock); usleep(kIntvl_usec * 3); } } void *thread_func2(void *ptr) { int loop; for(loop=0; loop<10; loop++) { pthread_mutex_lock(&lock); printf("thread 2: %d\\n", get_val() ); usleep(kIntvl_usec); pthread_mutex_unlock(&lock); } for(loop=0; loop<20; loop++) { printf("thread 2: %d\\n", get_val() ); usleep(kIntvl_usec); } }
0
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t cond; pthread_t tid[5]; int buffer[2]; int fd; int sequence = 1; char buf[20]; void *data_input(void *arg) { int no1, no2; while (1) { pthread_mutex_lock(&lock); while (sequence != 1) { pthread_cond_wait(&cond, &lock); } sequence = 2; printf("enter 2 numbers for operation: "); scanf("%d %d", &no1, &no2); sprintf(buf, "input numbers: %d and %d\\n", no1, no2); write(fd, buf, strlen(buf)); buffer[0] = no1; buffer[1] = no2; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } } void *data_add(void *arg) { int result, no1, no2; while (1) { pthread_mutex_lock(&lock); while (sequence != 2) { pthread_cond_wait(&cond, &lock); } sequence = 3; no1 = buffer[0]; no2 = buffer[1]; result = no1 + no2; sprintf(buf, "Addition: %d\\n", result); write(fd, buf, strlen(buf)); printf("addition: %d\\n", result); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } } void *data_sub(void *arg) { int result, no1, no2; while (1) { pthread_mutex_lock(&lock); while (sequence != 3) { pthread_cond_wait(&cond, &lock); } sequence = 4; no1 = buffer[0]; no2 = buffer[1]; result = no1 - no2; sprintf(buf, "Substraction: %d\\n", result); write(fd, buf, strlen(buf)); printf("substraction: %d\\n", result); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } } void *data_mul(void *arg) { int result, no1, no2; while (1) { pthread_mutex_lock(&lock); while (sequence != 4) { pthread_cond_wait(&cond, &lock); } sequence = 5; no1 = buffer[0]; no2 = buffer[1]; result = no1 * no2; sprintf(buf, "Multiplication: %d\\n", result); write(fd, buf, strlen(buf)); printf("multiplication: %d\\n", result); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } } void *data_div(void *arg) { float result; int no1, no2; while (1) { pthread_mutex_lock(&lock); while (sequence != 5) { pthread_cond_wait(&cond, &lock); } sequence = 1; no1 = buffer[0]; no2 = buffer[1]; result = (float)no1 / (float)no2; sprintf(buf, "Division: %f\\n", result); write(fd, buf, strlen(buf)); write(fd, "\\n", 1); printf("division: %f\\n\\n", result); pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); } } int main(int argc, char **argv) { int i, ret; if (argc != 2) { printf("invalid arguments.\\n"); return -1; } fd = open(argv[1], O_WRONLY | O_CREAT, 0666); if (fd < 0) { perror("fopen: "); return -1; } ret = pthread_create(&tid[0], 0, &data_input, 0); if (ret < 0) { perror("pthread_create: "); return -1; } ret = pthread_create(&tid[1], 0, &data_add, 0); if (ret < 0) { perror("pthread_create: "); return -1; } ret = pthread_create(&tid[2], 0, &data_sub, 0); if (ret < 0) { perror("pthread_create: "); return -1; } ret = pthread_create(&tid[3], 0, &data_mul, 0); if (ret < 0) { perror("pthread_create: "); return -1; } ret = pthread_create(&tid[4], 0, &data_div, 0); if (ret < 0) { perror("pthread_create: "); return -1; } for (i = 0; i < 5; i++) { pthread_join(tid[i], 0); } close(fd); return 0; }
1
#include <pthread.h> int element[(5)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(void); int stored_elements[(5)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; return 0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (5)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (5)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (5)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for(i=0; i<((5)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: goto ERROR; } void *t2(void *arg) { int i; for(i=0; i<(5); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: goto ERROR; } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main() { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: goto ERROR; } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> int g_socket_queue[5000] = {0}; unsigned short g_port_id = 1; static pthread_mutex_t port_lock; static unsigned short getport() { unsigned short result = 0; pthread_mutex_lock(&port_lock); result = g_port_id++; if (result == 0) { result++; } pthread_mutex_unlock(&port_lock); return result; } int dns_port_init() { int i = 0; struct sockaddr_in temp; for (i = 0;i < 5000; i++) { g_socket_queue[i] = socket(PF_INET, SOCK_DGRAM, 0); bzero(&temp, sizeof(struct sockaddr_in)); temp.sin_addr.s_addr = htonl(INADDR_ANY); temp.sin_port = htons(i+5000); temp.sin_family = AF_INET; if(bind(g_socket_queue[i],(struct sockaddr *)&temp,sizeof(struct sockaddr_in)) < 0) { do {printf("[%s][%d]:""Bind Error:%sn", "dns_port.c", 56,strerror(errno));}while(0); return -1; } } return 0; } unsigned short dns_get_port() { unsigned short portid = getport(); return (portid%5000 + 5000); } int dns_port_to_socket(unsigned short port) { if (port < 5000 || port > 9999) { return -1; } return g_socket_queue[port - 5000]; }
1
#include <pthread.h> int m1[10][10]; int m2[10][10]; int m3[10][10]; int idx, fim; }thread_arg, *ptr_thread_arg; pthread_mutex_t _mutex_lock; void * soma(void *arg) { int j, k, endidx; ptr_thread_arg argument = (ptr_thread_arg)arg; endidx = argument->idx + argument->fim; for(j=argument->idx; j<endidx; j++) { for(k=0; k < 10; k++){ pthread_mutex_lock(&_mutex_lock); m3[j][k]= m1[j][k] + m2[j][k]; pthread_mutex_unlock(&_mutex_lock); sleep(0); } } } int main (int argc, char *argv[]) { pthread_t thread[8]; thread_arg arguments[8]; int result, t, tamanho, restante; char err_msg[128]; int i,j; srand((unsigned int)getpid()); for(i=0; i < 10; i++) for(j=0; j < 10; j++) { m1[i][j]= rand() % 9; m2[i][j]= rand() % 9; m3[i][j]= 0; } pthread_mutex_init(&_mutex_lock, 0); tamanho = 10 / 8; restante = 10 % 8; for(t=0; t<8; t++) { arguments[t].idx = t * tamanho; arguments[t].fim = tamanho; if(t == (8 - 1)) arguments[t].fim += restante; result = pthread_create(&thread[t], 0, soma, &(arguments[t]) );; if (result) { strerror_r(result,err_msg,128); printf("Erro criando thread %d: %s\\n",t,err_msg); exit(0); } } for(t=0; t<8; t++) { result = pthread_join(thread[t], 0); if (result) { strerror_r(result,err_msg,128); fprintf(stderr,"Erro em pthread_join: %s\\n",err_msg); exit(0); } } printf("\\n"); for(i=0; i < 10; i++) { for(j=0; j < 10; j++) printf("%d ", m1[i][j]); printf("\\t"); for(j=0; j < 10; j++) printf("%d ",m2[i][j]); printf("\\t"); for(j=0; j < 10; j++) printf("%2d ",m3[i][j]); printf("\\n"); } printf("\\n"); pthread_mutex_destroy(&_mutex_lock); pthread_exit(0); }
0
#include <pthread.h> char valor; int ocorrencias; }simbolo; pthread_mutex_t mutex; int nthreads; char *arq_nome; simbolo *vetor; simbolo* instancia_vetor_simbolos(){ int i; simbolo *vetor = (simbolo*) malloc(90*sizeof(simbolo)); for(i = 0; i < 90; i++){ vetor[i].valor = (char) i + 33; vetor[i].ocorrencias = 0; } return vetor; } void contabiliza_simbolo(char simb){ int asc_s = (int) simb; if(asc_s > 33 && asc_s < 33+90){ pthread_mutex_lock(&mutex); vetor[asc_s - 33].ocorrencias++; pthread_mutex_unlock(&mutex); } } void imprime_simbolos(simbolo *vetor_simbolos, FILE* arq){ int i; fprintf(arq, "Simbolo, Quantidade\\n"); for( i = 0; i < 90;i++) if(vetor_simbolos[i]. ocorrencias != 0) fprintf(arq, " %c, %d\\n", vetor_simbolos[i].valor, vetor_simbolos[i].ocorrencias); fclose(arq); } void *le_arquivo(void *arg){ int item, c, i, tid = *(int*) arg, tam_arq, tam_bloco, inicio, fim; FILE* arq = fopen(arq_nome, "r"); fseek (arq, 0, 2); tam_arq=ftell (arq); tam_bloco = tam_arq/nthreads; inicio = tam_bloco*tid; fim = inicio + tam_bloco; if(tid == nthreads - 1) fim = tam_arq; fseek (arq, inicio, 0); printf("tid: %i, inicio: %i, fim: %i, tamanho: %i\\n", tid, inicio, fim, tam_arq); for(i = inicio; i < fim; i++){ c = fgetc(arq); contabiliza_simbolo(c); } pthread_exit(0); } int main(int argc, char *argv[]){ int c, t, *tid; double inicio, fim, tempo; pthread_mutex_init(&mutex, 0); if(argc < 4 ){ printf("Execute %s <arquivo entrada> <arquivo saida> <número threads>\\n", argv[0]); exit(1); } if(atoi(argv[3]) < 2){ printf("Número minimo de threads é 2\\n"); exit(1); } GET_TIME(inicio); nthreads = atoi(argv[3]); pthread_t thread[nthreads]; vetor = instancia_vetor_simbolos(); arq_nome = argv[1]; FILE* arq_saida = fopen( argv[2], "w"); for(t = 0; t < nthreads; t++){ tid = (int*) malloc(sizeof(int)); *tid = t; pthread_create(&thread[t], 0, le_arquivo, (void*)tid); } for (t = 0; t < nthreads; t++) { pthread_join(thread[t], 0); } GET_TIME(fim); tempo = fim - inicio; imprime_simbolos(vetor, arq_saida); printf("tempo: %f\\n", tempo); }
1
#include <pthread.h> extern int errno; static void *treat(void *); pthread_t idThread; int thCount; }Thread; Thread *threadsPool; int sd; int nthreads; pthread_mutex_t mlock=PTHREAD_MUTEX_INITIALIZER; void raspunde(int cl,int idThread); int main (int argc, char *argv[]) { struct sockaddr_in server; void threadCreate(int); if(argc<2) { fprintf(stderr,"Eroare: Primul argument este numarul de fire de executie..."); exit(1); } nthreads=atoi(argv[1]); if(nthreads <=0) { fprintf(stderr,"Eroare: Numar de fire invalid..."); exit(1); } threadsPool = calloc(sizeof(Thread),nthreads); if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1) { perror ("[server]Eroare la socket().\\n"); return errno; } int on=1; setsockopt(sd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)); bzero (&server, sizeof (server)); server.sin_family = AF_INET; server.sin_addr.s_addr = htonl (INADDR_ANY); server.sin_port = htons (2909); if (bind (sd, (struct sockaddr *) &server, sizeof (struct sockaddr)) == -1) { perror ("[server]Eroare la bind().\\n"); return errno; } if (listen (sd, 2) == -1) { perror ("[server]Eroare la listen().\\n"); return errno; } printf("Nr threaduri %d \\n", nthreads); fflush(stdout); int i; for(i=0; i<nthreads;i++) threadCreate(i); for ( ; ; ) { printf ("[server]Asteptam la portul %d...\\n",2909); pause(); } }; void threadCreate(int i) { void *treat(void *); pthread_create(&threadsPool[i].idThread,0,&treat,(void*)i); return; } void *treat(void * arg) { int client; struct sockaddr_in from; bzero (&from, sizeof (from)); printf ("[thread]- %d - pornit...\\n", (int) arg);fflush(stdout); for( ; ; ) { int length = sizeof (from); pthread_mutex_lock(&mlock); if ( (client = accept (sd, (struct sockaddr *) &from, &length)) < 0) { perror ("[thread]Eroare la accept().\\n"); } pthread_mutex_unlock(&mlock); threadsPool[(int)arg].thCount++; raspunde(client,(int)arg); close (client); } }; void raspunde(int cl,int idThread) { int nr; if (read (cl, &nr,sizeof(int)) <= 0) { printf("[Thread %d]\\n",idThread); perror ("Eroare la read() de la client.\\n"); } printf ("[Thread %d]Mesajul a fost receptionat...%d\\n",idThread, nr); nr++; printf("[Thread %d]Trimitem mesajul inapoi...%d\\n",idThread, nr); if (write (cl, &nr, sizeof(int)) <= 0) { printf("[Thread %d] ",idThread); perror ("[Thread]Eroare la write() catre client.\\n"); } else printf ("[Thread %d]Mesajul a fost trasmis cu succes.\\n",idThread); }
0
#include <pthread.h> int pthread_sleep (int seconds) { pthread_mutex_t mutex; pthread_cond_t conditionvar; struct timespec timetoexpire; if(pthread_mutex_init(&mutex,0)) { return -1; } if(pthread_cond_init(&conditionvar,0)) { return -1; } struct timeval tp; gettimeofday(&tp, 0); timetoexpire.tv_sec = tp.tv_sec + seconds; timetoexpire.tv_nsec = tp.tv_usec * 1000; pthread_mutex_lock (&mutex); int res = pthread_cond_timedwait(&conditionvar, &mutex, &timetoexpire); pthread_mutex_unlock (&mutex); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&conditionvar); return res; }
1
#include <pthread.h> pthread_mutex_t mutex; int sum = 0; int* array; struct arg_th{ int start; int finish; }; void* sum_elements(void* args){ struct arg_th* data_of_th = (struct arg_th*)args; int start_index = data_of_th->start; int finish_index = data_of_th->finish; pthread_mutex_lock(&mutex); for (int i = start_index; i < finish_index; i++){ sum += array[i]; } pthread_mutex_unlock(&mutex); } int main(int argc, char* argv[]){ if (argc < 2) exit(1); int N = atoi(argv[1]); pthread_t* thread_ids = (pthread_t*)malloc(N*sizeof(pthread_t)); struct arg_th* arguments = (struct arg_th*)malloc(N*sizeof(struct arg_th)); array = (int*)malloc(10000000*sizeof(int)); pthread_mutex_init(&mutex, 0); int len_part = 10000000 / N; for( int i =0; i < 10000000; i++) array[i] = 1; for( int i =0; i < N; i++){ if (i < N-1){ arguments[i].start = i*len_part; arguments[i].finish = (i+1)*len_part; } else{ arguments[N-1].start = arguments[N-2].finish; arguments[N-1].finish = 10000000; } } for (int i = 0; i < N; i++ ){ pthread_create(&thread_ids[i], 0, sum_elements, &arguments[i]); } for (int i = 0; i < N; i++) { pthread_join(thread_ids[i], 0); } printf("Sum %d", sum); free(thread_ids); free(arguments); free(array); }
0
#include <pthread.h> { double *a; double *b; double sum; int veclen; } DOTDATA; DOTDATA dotstr; pthread_t callThd[4]; pthread_mutex_t mutexsum; void *dotprod(void *arg) { int i, start, end, len ; long offset; double mysum, *x, *y; offset = (long)arg; len = dotstr.veclen; start = offset*len; end = start + len; x = dotstr.a; y = dotstr.b; mysum = 0; for (i=start; i<end ; i++) { mysum += (x[i] * y[i]); } pthread_mutex_lock (&mutexsum); dotstr.sum += mysum; pthread_mutex_unlock (&mutexsum); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { long i; double *a, *b; void *status; pthread_attr_t attr; a = (double*) malloc (4*100*sizeof(double)); b = (double*) malloc (4*100*sizeof(double)); for (i=0; i<100*4; i++) { a[i]=1.0; b[i]=a[i]; } dotstr.veclen = 100; dotstr.a = a; dotstr.b = b; dotstr.sum=0; pthread_mutex_init(&mutexsum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(i=0; i<4; i++) { pthread_create(&callThd[i], &attr, dotprod, (void *)i); } pthread_attr_destroy(&attr); for(i=0; i<4; i++) { pthread_join(callThd[i], &status); } printf ("Sum = %f \\n", dotstr.sum); free (a); free (b); pthread_mutex_destroy(&mutexsum); pthread_exit(0); }
1
#include <pthread.h> double a; double b; double area; struct t *proximo; } TAREFA; pthread_mutex_t mutexInsereVetor, mutexRetiraVetor, mutexIntegral; int a, b, nthreads, erroMaximo, numTarefas; TAREFA *vetorTarefas; double calcula_funcao(double x){ return sin(x*x); } double calcula_integral(double localA, double localB){ double integral=0; double intervalo = localB - localA; double altura = calcula_funcao((intervalo/2) + localA); integral = intervalo * altura; return integral; } void imprime_vetor_tarefa(){ printf("VetorTarefas: \\n"); TAREFA *temporaria = vetorTarefas->proximo; while(temporaria->proximo != 0){ printf("[ a=%f, b=%f, c=%f]\\n", temporaria->a, temporaria->b, temporaria->area); temporaria = temporaria->proximo; } printf("\\n"); } void insere_vetor_tarefa(double a, double b, double area){ pthread_mutex_lock(&mutexInsereVetor); TAREFA *tarefa = malloc(sizeof(TAREFA)); tarefa->a=a; tarefa->b=b; tarefa->area=area; tarefa->proximo=0; printf("Tarefa-a: %f\\n", tarefa->a); printf("Tarefa-b: %f\\n", tarefa->b); printf("Tarefa-area: %f\\n", tarefa->area); if(numTarefas == 0){ printf("Vetor Vazio\\n"); if(vetorTarefas->proximo == 0) printf("É nulo\\n"); vetorTarefas->proximo=tarefa; } else { TAREFA *temporaria = vetorTarefas->proximo; while(temporaria->proximo != 0) temporaria = temporaria->proximo; temporaria->proximo = tarefa; } numTarefas++; imprime_vetor_tarefa(); pthread_mutex_unlock(&mutexInsereVetor); } TAREFA *retira_tarefa(){ pthread_mutex_lock(&mutexRetiraVetor); if(vetorTarefas->proximo==0){ return 0; } else { TAREFA *temporaria = vetorTarefas->proximo; vetorTarefas->proximo = temporaria->proximo; numTarefas--; return temporaria; } pthread_mutex_unlock(&mutexRetiraVetor); } void inicia_vetor_tarefa(double a, double b){ double intervalo = b-a; double pontoMedio = (intervalo/2)+a; double umQuartoDoIntervalo = intervalo/4; double tresQuartosDoIntervalo = 3*(intervalo/4); double areaEsquerda, areaDireita; areaEsquerda = intervalo/2 * calcula_funcao(a + umQuartoDoIntervalo); areaDireita = intervalo/2 * calcula_funcao(a + tresQuartosDoIntervalo); printf("A: %f\\n", a); printf("B: %f\\n", b); printf("PM: %f\\n", pontoMedio); printf("Area Esquerda: %f\\n", areaEsquerda); printf("Area Direita: %f\\n", areaDireita); insere_vetor_tarefa(a, pontoMedio, areaEsquerda); insere_vetor_tarefa(pontoMedio, b, areaDireita); } void * threads_integral (void* arg){ int pid = * (int *) arg; printf("Thread id: %d\\n", pid); pthread_exit(0); } void valida_entrada(int argc, char *argv[]){ if(argc<5){ exit(1); } } void valida_threads(int nthreads){ if(nthreads <1 || nthreads>8){ printf("Numero de threads deve ser entre 1 e 8\\n"); exit(1); } } int main(int argc, char *argv[]){ pthread_t *threads; int i; int *pid; double integralInicial; valida_entrada(argc,argv); a = atof(argv[1]); b = atof(argv[2]); erroMaximo = atof(argv[3]); nthreads = atoi(argv[4]); valida_threads(nthreads); threads = (pthread_t *) malloc(sizeof(pthread_t) * nthreads); if(threads==0) { printf("--ERRO: malloc() em vetor de threads\\n"); exit(-1); } TAREFA *vetorTarefas = (TAREFA *) malloc(sizeof(TAREFA)); if(vetorTarefas == 0){ printf("--ERRO: malloc() em vetor de integrais\\n"); } else { vetorTarefas->proximo = 0; numTarefas=0; } integralInicial = calcula_integral(a,b); printf("Integral Inicial: %f\\n", integralInicial); inicia_vetor_tarefa(a, b); for (i= 0; i < nthreads; i++) { pid = malloc(sizeof(int)); if(pid == 0){ printf("--ERRO: malloc() em alocação threads\\n"); exit(-1); } *pid = i; if(pthread_create(&threads[i], 0, threads_integral, (void *) pid)){ printf("--ERRO: pthread_create()\\n"); exit(-1); } } for (i=0; i< nthreads ; i++) { if (pthread_join(threads[i], 0)) { printf("--ERRO: pthread_join() \\n"); exit(-1); } } return 0; }
0
#include <pthread.h> long long counter = 0; int opt_yield = 0; volatile static int lock2 = 0; void add(long long *pointer, long long value) { long long sum = *pointer + value; if (opt_yield) pthread_yield(); *pointer = sum; } void sum(void *a) { int n = *(int*)a; for (int i = 0; i < n; i++) { add(&counter, 1); } for(int i = 0; i < n; i++) { add(&counter, -1); } } void mutexSum(void *a) { int n = *(int *)a; for (int i = 0; i < n; i++) { pthread_mutex_lock(&lock); add(&counter, 1); pthread_mutex_unlock(&lock); } for (int i = 0; i < n; ++i) { pthread_mutex_lock(&lock); add(&counter, -1); pthread_mutex_unlock(&lock); } } void spinSum(void *a) { int n = *(int *)a; for (int i = 0; i < n; i++) { while(__sync_lock_test_and_set(&lock2, 1)) { continue; } add(&counter, 1); __sync_lock_release(&lock2); } for (int i = 0; i < n; i++) { while(__sync_lock_test_and_set(&lock2, 1)) { continue; } add(&counter, -1); __sync_lock_release(&lock2); } } void compareSum(void *a) { int n = *(int *)a; int tmp; long long* countPtr = &counter; long long csum; for (int i = 0; i < n; i++) { do { tmp = *countPtr; csum = tmp + 1; if (opt_yield) pthread_yield(); } while(__sync_val_compare_and_swap(countPtr, tmp, csum)!= tmp); } for (int i = 0; i < n; i++) { do { tmp = *countPtr; csum = tmp - 1; if (opt_yield) pthread_yield(); } while(__sync_val_compare_and_swap(countPtr, tmp, csum)!= tmp); } } int createThreads(int numT, int numI, pthread_t* memory, char sync) { int i; int j; int exitStat = 0; for (i = 0; i < numT; i++) { switch(sync) { case 'a': { j = pthread_create(&memory[i], 0, (void *)&sum, (void *)&numI); if (j != 0) { fprintf(stderr, "ERROR: thread creation, error code: %d\\n", j); exitStat = 1; return exitStat; } break; } case 'm': { j = pthread_create(&memory[i], 0, (void *)&mutexSum, (void *)&numI); if (j != 0) { fprintf(stderr, "ERROR: thread creation, error code: %d\\n", j); exitStat = 1; return exitStat; } break; } case 's': { j = pthread_create(&memory[i], 0, (void *)&spinSum, (void *)&numI); if (j != 0) { fprintf(stderr, "ERROR: thread creation, error code: %d\\n", j); exitStat = 1; return exitStat; } break; } case 'c': { j = pthread_create(&memory[i], 0, (void *)&compareSum, (void *)&numI); if (j != 0) { fprintf(stderr, "ERROR: thread creation, error code: %d\\n", j); exitStat = 1; return exitStat; } break; } } } return exitStat; } int joinThreads(int numT, int numI, pthread_t* memory) { int i; int j; int exitStat = 0; for (i = 0; i < numT; i++) { j = pthread_join(memory[i], 0); if (j != 0) { fprintf(stderr, "ERROR: joining threads: error code is %d\\n", j); exitStat = 1; } } return exitStat; }
1
#include <pthread.h> volatile int connfds[MAX_LINK] = {0}; volatile pthread_t thread_pool[MAX_LINK] = {0}; volatile int conn_num = 0; pthread_mutex_t mutex_connfd_list_index = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_connfd_list = PTHREAD_MUTEX_INITIALIZER; extern volatile int interrupt_flag; int get_index_from_connfd_list() { pthread_mutex_lock(&mutex_connfd_list); int index = 0; for (index = 0; index < MAX_LINK; index++) { if(!connfds[index]) break; } return index == MAX_LINK ? -1 : index; } void communicate_thread_proc(void *ptr) { conn_num++; int index = *((int *)ptr); pthread_mutex_unlock(&mutex_connfd_list_index); int connfd = connfds[index]; char buff; int n; char time_str[30]; current_time_string(time_str); logi("[SOCKET] %d: [%s] Connection established.", connfd, time_str); while (!interrupt_flag) { logi("[SOCKET] %d: Waiting for message...", connfd); n = recv(connfd, &buff, 1, 0); current_time_string(time_str); if (n > 0) { handle_data(connfd, buff); } else { logi("[SOCKET] %d: [%s] Connection closed.", connfd, time_str); break; } } close(connfd); pthread_mutex_lock(&mutex_connfd_list); connfds[index] = 0; conn_num--; pthread_mutex_unlock(&mutex_connfd_list); } int listen_for_client(void *plistenfd) { int connfd_index_used = 1; int index = -1; int connfd; int listenfd = *((int *)plistenfd); while (1) { if (interrupt_flag) { printf("\\nListen thread: SIGINT signal caught. Exiting...\\n"); break; } if (connfd_index_used) { pthread_mutex_lock(&mutex_connfd_list_index); if ((index = get_index_from_connfd_list()) == -1) { continue; } else { connfd_index_used = 0; } pthread_mutex_unlock(&mutex_connfd_list_index); pthread_mutex_unlock(&mutex_connfd_list); } if ((connfd = accept(listenfd, (struct sockaddr *)0, 0)) == -1) { loge("[WARNING] Accept socket error: %s(errno: %d)\\n", strerror(errno), errno); continue; } connfds[index] = connfd; pthread_t thread; pthread_mutex_lock(&mutex_connfd_list_index); pthread_create(&thread, 0, (void *)communicate_thread_proc, (void *)&index); thread_pool[index] = thread; connfd_index_used = 1; } return 0; }
0
#include <pthread.h> extern int errno; int gridsize = 0; int grid[10][10]; int threads_left = 0; pthread_mutex_t lock[10][10]; time_t start_t, end_t; int PrintGrid(int grid[10][10], int gridsize) { int i; int j; for (i = 0; i < gridsize; i++) { for (j = 0; j < gridsize; j++) fprintf(stdout, "%d\\t", grid[i][j]); fprintf(stdout, "\\n"); } return 0; } long InitGrid(int grid[10][10], int gridsize) { int i; int j; long sum = 0; int temp = 0; srand( (unsigned int)time( 0 ) ); for (i = 0; i < gridsize; i++) for (j = 0; j < gridsize; j++) { temp = rand() % 100; grid[i][j] = temp; sum = sum + temp; if (pthread_mutex_init(&lock[i][j], 0) != 0) { printf("\\n mutex initialization failed!\\n"); return 1; } } return sum; } long SumGrid(int grid[10][10], int gridsize) { int i; int j; long sum = 0; for (i = 0; i < gridsize; i++){ for (j = 0; j < gridsize; j++) { sum = sum + grid[i][j]; } } return sum; } int max(int x, int y) { if (x > y) return x; return y; } int min(int x, int y) { if (x < y) return x; return y; } void* do_swaps(void* args) { int i, row1, column1, row2, column2; int temp; grain_type* gran_type = (grain_type*)args; threads_left++; for(i=0; i<20; i++) { row1 = rand() % gridsize; column1 = rand() % gridsize; row2 = rand() % gridsize; column2 = rand() % gridsize; if (*gran_type == ROW) { if (pthread_mutex_trylock(&lock[min(row1, row2)][0])) { i--; usleep(100); continue; } if(!(row1 == row2)) { if(pthread_mutex_trylock(&lock[max(row1, row2)][0])) { pthread_mutex_unlock(&lock[min(row1, row2)][0]); i--; usleep(100); continue; } } } else if (*gran_type == CELL) { if (((row1 * gridsize) + column1) < ((row2 * gridsize) + column2)) { if(pthread_mutex_trylock(&lock[row1][column1])) { i--; usleep(100); continue; } if (!((row1 == row2) && (column1 == column2))) { if(pthread_mutex_lock(&lock[row2][column2])) { pthread_mutex_unlock(&lock[row1][column1]); i--; usleep(100); continue; } } } else { if(pthread_mutex_trylock(&lock[row2][column2])) { i--; usleep(100); continue; } if (!((row1 == row2) && (column1 == column2))) { if(pthread_mutex_lock(&lock[row1][column1])) { pthread_mutex_unlock(&lock[row2][column2]); i--; usleep(100); continue; } } } } else if (*gran_type == GRID) { pthread_mutex_lock(&lock[0][0]); } temp = grid[row1][column1]; sleep(1); grid[row1][column1]=grid[row2][column2]; grid[row2][column2]=temp; if (*gran_type == ROW) { pthread_mutex_unlock(&lock[row1][0]); if (!(row1 == row2)) { pthread_mutex_unlock(&lock[row2][0]); } } else if (*gran_type == CELL) { if (((row1 * gridsize) + column1) < ((row2 * gridsize) + column2)) { pthread_mutex_unlock(&lock[row1][column1]); if (!((row1 == row2) && (column1 == column2))) { pthread_mutex_unlock(&lock[row2][column2]); } } else { pthread_mutex_unlock(&lock[row2][column2]); pthread_mutex_unlock(&lock[row1][column1]); } } else if (*gran_type == GRID) { pthread_mutex_unlock(&lock[0][0]); } } threads_left--; if (threads_left == 0){ time(&end_t); } return 0; } int main(int argc, char **argv) { int nthreads = 0; pthread_t threads[1000]; grain_type rowGranularity = NONE; long initSum = 0, finalSum = 0; int i; if (argc > 3) { gridsize = atoi(argv[1]); if (gridsize > 10 || gridsize < 1) { printf("Grid size must be between 1 and 10.\\n"); return(1); } nthreads = atoi(argv[2]); if (nthreads < 1 || nthreads > 1000) { printf("Number of threads must be between 1 and 1000."); return(1); } if (argv[3][1] == 'r' || argv[3][1] == 'R') rowGranularity = ROW; if (argv[3][1] == 'c' || argv[3][1] == 'C') rowGranularity = CELL; if (argv[3][1] == 'g' || argv[3][1] == 'G') rowGranularity = GRID; } else { printf("Format: gridapp gridSize numThreads -cell\\n"); printf(" gridapp gridSize numThreads -row\\n"); printf(" gridapp gridSize numThreads -grid\\n"); printf(" gridapp gridSize numThreads -none\\n"); return(1); } printf("Initial Grid:\\n\\n"); initSum = InitGrid(grid, gridsize); PrintGrid(grid, gridsize); printf("\\nInitial Sum: %d\\n", initSum); printf("Executing threads...\\n"); srand((unsigned int)time( 0 ) ); time(&start_t); for (i = 0; i < nthreads; i++) { if (pthread_create(&(threads[i]), 0, do_swaps, (void *)(&rowGranularity)) != 0) { perror("thread creation failed:"); exit(-1); } } for (i = 0; i < nthreads; i++) pthread_detach(threads[i]); while (1) { sleep(2); if (threads_left == 0) { fprintf(stdout, "\\nFinal Grid:\\n\\n"); PrintGrid(grid, gridsize); finalSum = SumGrid(grid, gridsize); fprintf(stdout, "\\n\\nFinal Sum: %d\\n", finalSum); if (initSum != finalSum){ fprintf(stdout,"DATA INTEGRITY VIOLATION!!!!!\\n"); } else { fprintf(stdout,"DATA INTEGRITY MAINTAINED!!!!!\\n"); } fprintf(stdout, "Secs elapsed: %g\\n", difftime(end_t, start_t)); exit(0); } } return(0); }
1
#include <pthread.h> struct queue_buff { int buff[10]; int in_point; int out_point; pthread_mutex_t mutex_buff; pthread_cond_t queue_full; pthread_cond_t queue_empty; }; struct queue_buff que_buff; volatile int is_stop = 0; void *thread_producer_func(void *args) { int num = (int)args; while (1) { pthread_mutex_lock(&(que_buff.mutex_buff)); while ((que_buff.in_point + 1) % 10 == que_buff.out_point && is_stop == 0) { pthread_cond_wait(&(que_buff.queue_empty), &(que_buff.mutex_buff)); } if (is_stop == 1) { pthread_mutex_unlock(&(que_buff.mutex_buff)); pthread_exit(0); } printf("生产者 %d 在 %d 位置增加数据\\n", num, que_buff.in_point); que_buff.buff[que_buff.in_point] = num; que_buff.in_point = (que_buff.in_point + 1) % 10; if ((que_buff.in_point + 1) % 10 == que_buff.out_point) { pthread_cond_broadcast(&(que_buff.queue_full)); } pthread_mutex_unlock(&(que_buff.mutex_buff)); usleep(200000); } } void *thread_consumer_func(void *args) { int num = (int)args; int data; while (1) { pthread_mutex_lock(&(que_buff.mutex_buff)); while (que_buff.out_point == que_buff.in_point && is_stop == 0) { pthread_cond_wait(&(que_buff.queue_full), &(que_buff.mutex_buff)); } if (is_stop == 1 && que_buff.out_point == que_buff.in_point) { pthread_mutex_unlock(&(que_buff.mutex_buff)); pthread_exit(0); } printf("\\t\\t\\t\\t\\t消费者 %d 在 %d 位置取出数据\\n", num, que_buff.out_point); data = que_buff.buff[que_buff.out_point]; que_buff.out_point = (que_buff.out_point + 1) % 10; if (que_buff.out_point == que_buff.in_point) { pthread_cond_broadcast(&(que_buff.queue_empty)); } pthread_mutex_unlock(&(que_buff.mutex_buff)); usleep(200000); } } int main(int argc, char *argv[]) { pthread_t thread_producer[10] = {0}; pthread_t thread_consumer[10] = {0}; pthread_mutex_init(&(que_buff.mutex_buff), 0); pthread_cond_init(&(que_buff.queue_full), 0); pthread_cond_init(&(que_buff.queue_empty), 0); int i; for (i = 0; i < 4; i++) { pthread_create(&thread_producer[i], 0, thread_producer_func, (void *)i); } for (i = 0; i < 4; i++) { pthread_create(&thread_consumer[i], 0, thread_consumer_func, (void *)i); } sleep(1); is_stop = 1; pthread_cond_broadcast(&(que_buff.queue_empty)); pthread_cond_broadcast(&(que_buff.queue_full)); for (i = 0; i < 4; i++) { pthread_join(thread_producer[i], 0); pthread_join(thread_consumer[i], 0); } pthread_mutex_destroy(&(que_buff.mutex_buff)); pthread_cond_destroy(&(que_buff.queue_empty)); pthread_cond_destroy(&(que_buff.queue_full)); return 0; }
0