text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> int Escritores; int EscritoresEsp; int Lectores; pthread_mutex_t mutex; pthread_cond_t AccesoEs; pthread_cond_t AccesoLec; }mutex_rw; int mutex_create( mutex_rw* x){ x->Lectores=0; x->Escritores=0; x->EscritoresEsp=0; pthread_cond_init(&(x->AccesoLec),0); pthread_cond_init(&(x->AccesoEs),0); pthread_mutex_init(&(x->mutex),0); return 1; } void mutex_rdlock( mutex_rw* x){ pthread_mutex_lock(&(x->mutex)); while(x->Escritores > 0) pthread_cond_wait(&(x->AccesoLec), &(x->mutex)); x->Lectores++; pthread_mutex_unlock(&(x->mutex)); } void mutex_rdunlock( mutex_rw* x){ pthread_mutex_lock(&(x->mutex)); x->Lectores--; if(x->Lectores==0 && x->EscritoresEsp>0) pthread_cond_signal(&(x->AccesoEs)); pthread_mutex_unlock(&(x->mutex)); } void mutex_wrlock( mutex_rw* x) { pthread_mutex_lock(&(x->mutex)); x->EscritoresEsp++; while(x->Lectores>0 || x->Escritores>0) { pthread_cond_wait(&(x->AccesoEs), &(x->mutex)); } x->EscritoresEsp--; x->Escritores++; pthread_mutex_unlock(&(x->mutex)); } void mutex_wrunlock( mutex_rw* x) { pthread_mutex_lock(&(x->mutex)); x->Escritores--; if(x->EscritoresEsp>0) pthread_cond_signal(&(x->AccesoEs)); pthread_cond_broadcast(&(x->AccesoLec)); pthread_mutex_unlock(&(x->mutex)); } double timeval_diff(struct timeval *a, struct timeval *b) { return (double)(a->tv_sec + (double)a->tv_usec/1000000) - (double)(b->tv_sec + (double)b->tv_usec/1000000); } struct list_node_s { int data; struct list_node_s* next; pthread_mutex_t mutex; }; int thread_count; struct list_node_s** head_pp; pthread_mutex_t mutex; pthread_mutex_t head_p_mutex; pthread_rwlock_t rwlock; int MemberP(int value) { struct list_node_s* temp_p; pthread_mutex_lock(&head_p_mutex); temp_p=*head_pp; while(temp_p != 0 && temp_p->data<value) { if (temp_p->next != 0) { pthread_mutex_lock(&(temp_p->next->mutex)); } if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); temp_p=temp_p->next; } if (temp_p == 0 || temp_p->data >value) { if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } if (temp_p != 0) { pthread_mutex_unlock(&(temp_p->mutex)); } return 0; } else { if (temp_p == *head_pp) { pthread_mutex_unlock(&head_p_mutex); } pthread_mutex_unlock(&(temp_p->mutex)); return 1; } } int Member(int value) { struct list_node_s* curr_p=*head_pp; while(curr_p!=0 && curr_p->data < value) curr_p=curr_p->next; if(curr_p == 0 || curr_p->data >value) return 0; else return 1; } int Insert(int value) { struct list_node_s* curr_p= *head_pp; struct list_node_s* pred_p= 0; struct list_node_s* temp_p; while(curr_p != 0 && curr_p->data<value) { pred_p=curr_p; curr_p=curr_p->next; } if(curr_p == 0 || curr_p->data > value) { temp_p=malloc(sizeof(struct list_node_s)); temp_p->data=value; temp_p->next=curr_p; if (pred_p == 0) *head_pp=temp_p; else pred_p->next=temp_p; return 1; } else return 0; } int Delete(int value) { struct list_node_s* curr_p=*head_pp; struct list_node_s* pred_p= 0; while(curr_p != 0 && curr_p->data < value) { pred_p=curr_p; curr_p=curr_p->next; } if(curr_p != 0 && curr_p->data == value) { if(pred_p == 0) { *head_pp=curr_p->next; free(curr_p); } else { pred_p->next=curr_p->next; free(curr_p); } return 1; } else return 0; } void* LLamarFunc(void* rango) { mutex_rw n_rwlock; mutex_create(&n_rwlock); long mi_rango=(long) rango; printf("Thread numero %ld\\n",mi_rango); mutex_wrlock(&n_rwlock); Insert((int)mi_rango); mutex_wrunlock(&n_rwlock); mutex_rdlock(&n_rwlock); int numero=Member((int)mi_rango); mutex_rdunlock(&n_rwlock); printf("Presente %d\\n",numero); return 0; } int main(int argc,char* argv[]) { long thread; pthread_t* thread_handles; struct list_node_s* head; head=malloc(sizeof(struct list_node_s)); head->data=0; head->next=0; head_pp=&head; thread_count=strtol(argv[1],0,10); thread_handles=malloc (thread_count*sizeof(pthread_t)); struct timeval t_ini, t_fin; double secs; gettimeofday(&t_ini, 0); for(thread=0;thread<thread_count;thread++) pthread_create(&thread_handles[thread],0,LLamarFunc,(void *)thread); for(thread=0;thread<thread_count;thread++) pthread_join(thread_handles[thread],0); gettimeofday(&t_fin, 0); secs = timeval_diff(&t_fin, &t_ini); printf("%.16g millisegundos\\n", secs * 1000.0); free(thread_handles); return 0; }
1
#include <pthread.h> pthread_mutex_t *f_lock = 0; struct shared_context{ int ref_cnt; int last_process; }; struct shared_context * sctx = 0; int main() { int ret; f_lock = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED|MAP_ANON, -1, 0); if(f_lock == MAP_FAILED){ perror("mmap failed"); exit(1); } pthread_mutexattr_t attr; ret = pthread_mutexattr_init(&attr); if(0 != ret){ printf("init mutexattr failed\\n"); exit(1); } ret = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED); if(0 != ret){ printf("init mutexattr shared failed\\n"); exit(1); } ret = pthread_mutex_init(f_lock, &attr); if(0 != ret){ printf("init mutexattr shared failed\\n"); exit(1); } key_t shmid = shmget(1234, sizeof(struct shared_context), IPC_CREAT | 0660); struct shared_context *stex = (struct shared_context*)shmat(shmid, 0, 0); pid_t pid = fork(); if(pid < 0){ perror("fork faild"); }else if(pid > 0){ printf("parent\\n"); pthread_mutex_lock(f_lock); sctx->ref_cnt++; sctx->last_process = getpid(); shmdt((char*)sctx); pthread_mutex_unlock(f_lock); }else{ printf("chiled\\n"); pthread_mutex_lock(f_lock); sctx = (struct shared_context*)shmat(shmid, 0, 0); sctx->ref_cnt++; sctx->last_process = getpid(); shmdt((char*)sctx); pthread_mutex_unlock(f_lock); } struct shmid_ds buf[1234]; shmctl(shmid, IPC_RMID, buf); return 0; }
0
#include <pthread.h> struct s { int datum; struct s *next; }; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = 0; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } pthread_mutex_t mutex[10]; struct s *slot[10]; void *t_fun(void *arg) { int i; pthread_mutex_lock(&mutex[i]); list_add(new(3), slot[i]); pthread_mutex_unlock(&mutex[i]); return 0; } int main () { int j, k; struct s *p; pthread_t t1; slot[j] = new(1); list_add(new(2), slot[j]); slot[k] = new(1); list_add(new(2), slot[k]); p = new(3); list_add(p, slot[j]); p = new(3); list_add(p, slot[k]); pthread_create(&t1, 0, t_fun, 0); pthread_mutex_lock(&mutex[j]); p = slot[j]->next; printf("%d\\n", p->datum); pthread_mutex_unlock(&mutex[j]); return 0; }
1
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; } pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; int control = 0; int nerrors = 0; void pre3( void ) { control++; if ( control != 1 ) nerrors++; } void pre2( void ) { control++; if ( control != 2 ) nerrors++; } void pre1( void ) { control++; if ( control != 3 ) nerrors++; } void par1( void ) { control++; if ( control != 4 ) nerrors++; } void par2( void ) { control++; if ( control != 5 ) nerrors++; } void par3( void ) { control++; if ( control != 6 ) nerrors++; } void chi1( void ) { control += 2; if ( control != 5 ) nerrors++; } void chi2( void ) { control += 2; if ( control != 7 ) nerrors++; } void chi3( void ) { control += 2; if ( control != 9 ) nerrors++; } void * threaded( void * arg ) { int ret, status; pid_t child, ctl; ret = pthread_mutex_lock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to lock mutex" ); } ret = pthread_mutex_unlock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to unlock mutex" ); } child = fork(); if ( child == ( pid_t ) - 1 ) { UNRESOLVED( errno, "Failed to fork" ); } if ( child == ( pid_t ) 0 ) { if ( nerrors ) { FAILED( "Errors occured in the child" ); } exit( PTS_PASS ); } ctl = waitpid( child, &status, 0 ); if ( ctl != child ) { UNRESOLVED( errno, "Waitpid returned the wrong PID" ); } if ( ( !WIFEXITED( status ) ) || ( WEXITSTATUS( status ) != PTS_PASS ) ) { FAILED( "Child exited abnormally" ); } if ( nerrors ) { FAILED( "Errors occured in the parent (only)" ); } return 0; } int main( int argc, char * argv[] ) { int ret; pthread_t ch; output_init(); ret = pthread_mutex_lock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to lock mutex" ); } ret = pthread_create( &ch, 0, threaded, 0 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to create a thread" ); } ret = pthread_atfork( pre1, par1, chi1 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to register the atfork handlers" ); } ret = pthread_atfork( pre2, par2, chi2 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to register the atfork handlers" ); } ret = pthread_atfork( pre3, par3, chi3 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to register the atfork handlers" ); } ret = pthread_mutex_unlock( &mtx ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to unlock mutex" ); } ret = pthread_join( ch, 0 ); if ( ret != 0 ) { UNRESOLVED( ret, "Failed to join the thread" ); } output( "Test passed\\n" ); PASSED; }
0
#include <pthread.h> struct node { struct node * next; char * str; }; pthread_mutex_t mutex; node_t * head = 0; node_t * add_node(node_t * node, node_t * head) { node->next = head; return node; } void show_list(node_t * head) { node_t * cur = head; while(cur) { printf("%s\\n", cur->str); cur = cur->next; } } void * sort_list(void * param) { while(1) { char * tmp; sleep(5); pthread_mutex_lock(&mutex); node_t * node1 = head; node_t * node2 = head; if (!head) { printf("my head is still empty\\n"); } while(node1) { while(node2->next) { if (strcmp(node2->next->str, node2->str) > 0) { tmp = node2->str; node2->str = node2->next->str; node2->next->str = tmp; } node2 = node2->next; } node1 = node1->next; } pthread_mutex_unlock(&mutex); } } int main(int argc, char * argv[]) { char buff[80]; pthread_t thread; int code; pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&mutex, &attr); code = pthread_create(&thread, 0, sort_list, (void *)head); if (code != 0) { char buf[256]; strerror_r(code, buf, sizeof buf); fprintf(stderr, "%s: creating thread: %s\\n", argv[0], buf); exit(1); } while(1) { if (!fgets(buff, 80, stdin)) { exit(1); } size_t l = strlen(buff); if (l != 1 || buff[l - 1] != '\\n') { node_t * node = (node_t *) malloc(sizeof(node_t)); node->str = malloc(sizeof(char) * 80); strncpy(node->str, buff, sizeof(char) * (l-1)); pthread_mutex_lock(&mutex); head = add_node(node, head); pthread_mutex_unlock(&mutex); } else { pthread_mutex_lock(&mutex); show_list(head); pthread_mutex_unlock(&mutex); } } exit(0); }
1
#include <pthread.h> pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; struct node { int num; struct node *next; }; struct node *head = 0; static void *thread_func(void *arg) { struct node *p; while (1) { pthread_mutex_lock(&mtx); while (head == 0) pthread_cond_wait(&cond, &mtx); p = head; head = head->next; printf("Got %d from front of queue\\n", p->num); free(p); pthread_mutex_unlock(&mtx); } return (void *)1; } int main() { pthread_t tid; int i; struct node *p; pthread_create(&tid, 0, thread_func, 0); for (i = 0; i < 10; i++) { p = malloc(sizeof(struct node)); p->num = i; pthread_mutex_lock(&mtx); p->next = head; head = p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } pthread_join(tid, 0); printf("All done -- exiting\\n"); return 0; }
0
#include <pthread.h> static int rescheduled = 0; static pthread_mutex_t eventMutex; static pthread_cond_t eventCond; static pthread_mutex_t eventListMutex; struct testEvent { struct rxevent *event; int fired; int cancelled; }; static struct testEvent events[10000]; static void reschedule(void) { pthread_mutex_lock(&eventMutex); pthread_cond_signal(&eventCond); rescheduled = 1; pthread_mutex_unlock(&eventMutex); return; } static void eventSub(struct rxevent *event, void *arg, void *arg1, int arg2) { struct testEvent *evrecord = arg; pthread_mutex_lock(&eventListMutex); rxevent_Put(&evrecord->event); evrecord->event = 0; evrecord->fired = 1; pthread_mutex_unlock(&eventListMutex); return; } static void reportSub(struct rxevent *event, void *arg, void *arg1, int arg2) { printf("Event fired\\n"); } static void * eventHandler(void *dummy) { struct timespec nextEvent; struct clock cv; struct clock next; pthread_mutex_lock(&eventMutex); while (1) { pthread_mutex_unlock(&eventMutex); next.sec = 30; next.usec = 0; clock_GetTime(&cv); rxevent_RaiseEvents(&next); pthread_mutex_lock(&eventMutex); if (rescheduled) { rescheduled = 0; continue; } clock_Add(&cv, &next); nextEvent.tv_sec = cv.sec; nextEvent.tv_nsec = cv.usec * 1000; pthread_cond_timedwait(&eventCond, &eventMutex, &nextEvent); } pthread_mutex_unlock(&eventMutex); return 0; } int main(void) { int when, counter, fail, fired, cancelled; struct clock now, eventTime; struct rxevent *event; pthread_t handler; plan(8); pthread_mutex_init(&eventMutex, 0); pthread_cond_init(&eventCond, 0); memset(events, 0, sizeof(events)); pthread_mutex_init(&eventListMutex, 0); rxevent_Init(20, reschedule); ok(1, "Started event subsystem"); clock_GetTime(&now); event = rxevent_Post(&now, &now, reportSub, 0, 0, 0); ok(event != 0, "Created a single event"); rxevent_Cancel(&event); ok(1, "Cancelled a single event"); rxevent_RaiseEvents(&now); ok(1, "RaiseEvents happened without error"); ok(pthread_create(&handler, 0, eventHandler, 0) == 0, "Created handler thread"); for (counter = 0; counter < 10000; counter++) { when = random() % 3000; clock_GetTime(&now); eventTime = now; clock_Addmsec(&eventTime, when); pthread_mutex_lock(&eventListMutex); events[counter].event = rxevent_Post(&eventTime, &now, eventSub, &events[counter], 0, 0); if (counter!=999 && random() % 10 == 0) { counter++; events[counter].event = rxevent_Post(&eventTime, &now, eventSub, &events[counter], 0, 0); } if (random() % 4 == 0) { int victim = random() % counter; if (events[victim].event != 0) { rxevent_Cancel(&events[victim].event); events[victim].cancelled = 1; } } pthread_mutex_unlock(&eventListMutex); } ok(1, "Added %d events", 10000); sleep(3); fired = 0; cancelled = 0; fail = 0; for (counter = 0; counter < 10000; counter++) { if (events[counter].fired) fired++; if (events[counter].cancelled) cancelled++; if (events[counter].cancelled && events[counter].fired) fail = 1; } ok(!fail, "Didn't fire any cancelled events"); ok(fired+cancelled == 10000, "Number of fired and cancelled events sum to correct total"); return 0; }
1
#include <pthread.h> void *produce(void *i); void *consume(void *i); pthread_mutex_t mutex[5] = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER; int counter = 0; int buffer[5]; main(int argc, char **argv) { int rc1, rc2; int num_of_producers; int num_of_consumers; int *ret1; int *ret2; int i,j; int *index; pthread_t *producer_thread, *consumer_thread; pthread_t thread1, thread2; num_of_producers= atoi(argv[1]); num_of_consumers= atoi(argv[2]); printf("Number of Producers : %d\\n", num_of_producers); producer_thread=(pthread_t *)malloc(sizeof(pthread_t)*num_of_producers); printf("Number of Consumers : %d\\n", num_of_consumers); consumer_thread=(pthread_t *)malloc(sizeof(pthread_t)*num_of_consumers); ret1=(int *)malloc(sizeof(int)*num_of_producers); ret2=(int *)malloc(sizeof(int)*num_of_consumers); for(i=0;i<5;i++){ buffer[i]=-1; } while(1){ for(i=0;i<num_of_producers;i++){ index= &i; ret1[i]=pthread_create( &producer_thread[i], 0, &produce, (void *) index); } for(i=0;i<num_of_consumers;i++){ index= &i; ret2[i]=pthread_create( &consumer_thread[i], 0, &consume, (void *) index); } for(i=0;i<num_of_producers;i++){ pthread_join(producer_thread[i], 0); } for(i=0;i<num_of_consumers;i++){ pthread_join(consumer_thread[i], 0); } sleep(5); } exit(0); } void *produce( void *i){ int * index; int num=rand()%10; int buff_index; index= (int *) i; buff_index=rand()%5; pthread_mutex_lock( &mutex[buff_index]); if(buffer[buff_index]==-1){ printf("Producer %d produced %d at %d\\n", *index, num, buff_index); buffer[buff_index]=num; } pthread_mutex_unlock( &mutex[buff_index]); } void *consume(void * i){ int *index; index= (int *) i; int buff_index; buff_index=rand()%5; pthread_mutex_lock( &mutex[buff_index]); if(buffer[buff_index]!=-1){ printf("Consumer %d consumed %d at %d\\n", *index, buffer[buff_index], buff_index); buffer[buff_index]=-1; } pthread_mutex_unlock( &mutex[buff_index]); }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t full,empty; int buffer[10],counter; pthread_t tid; void initialize() { pthread_mutex_init(&mutex,0); sem_init(&full,0,0); sem_init(&empty,0,10); counter=0; } void insert_item(int item) { buffer[counter++]=item; } int remove_item() { return buffer[--counter]; } void producer() { int item; sleep(rand()%5); item=rand()%10; sem_wait(&empty); pthread_mutex_lock(&mutex); printf("Producer produced %d\\n",item); insert_item(item); pthread_mutex_unlock(&mutex); sem_post(&full); } void consumer() { sem_wait(&full); pthread_mutex_lock(&mutex); printf("Consumed item %d\\n",remove_item()); pthread_mutex_unlock(&mutex); sem_post(&empty); } int main() { int p=0,c=0,i; initialize(); do { if(p<c) printf("Consumers cannot be more than producers!!!\\n"); printf("Enter No of Producers: "); scanf("%d",&p); printf("Enter No of Consumers: "); scanf("%d",&c); } while(p<c); for(i=0;i<p;i++) pthread_create(&tid,0,(void*)producer,0); for(i=0;i<c;i++) pthread_create(&tid,0,(void*)consumer,0); sleep(9999); return 0; }
1
#include <pthread.h> int fd; static uint8_t spi_mode,spi_bits; static uint32_t spi_speed; static uint16_t spi_delay; pthread_mutex_t spi_mutex; int fpga_open() { int ret; pthread_mutex_init ( &spi_mutex, 0 ); spi_mode = SPI_MODE; spi_bits = SPI_BITS_PER_WORD; spi_speed = SPI_SPEED_HZ; spi_delay = SPI_DELAY; printf ( "Will use SPI to send commands to fpga\\n" ); printf("spi configuration: \\n" ); printf(" + dev: %s\\n", FPGA_SPI_DEV ); printf(" + mode: %d\\n", spi_mode); printf(" + bits per word: %d\\n", spi_bits); printf(" + speed: %d Hz (%d KHz)\\n", spi_speed, spi_speed/1000); printf("\\n"); if ((fd = open(FPGA_SPI_DEV, O_RDWR)) < 0) { printf("E: fpga: spi: Failed to open dev\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_MODE, &spi_mode)) < 0 ) { printf("E: fpga: spi: can't set spi mode wr\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_MODE, &spi_mode)) < 0 ) { printf("E: fpga: spi: can't set spi mode rd\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &spi_bits)) < 0 ) { printf("E: fpga: spi: can't set bits per word wr\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &spi_bits)) < 0 ) { printf("E: fpga: spi: can't set bits per word rd\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &spi_speed)) < 0 ) { printf("E: fpga: spi: can't set speed wr\\n"); return -1; } if ((ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &spi_speed)) < 0 ) { printf("E: fpga: spi: can't set speed rd\\n"); return -1; } if (fpga_logopen() <0) { printf ( "e: fpga: could not open log\\n" ); return -1; } return 0; } void fpga_close() { close(fd); fclose(logfd); } int fpga_setservo ( uint8_t servoNr, uint16_t servoPos ) { unsigned char wbuf[4]; unsigned char rbuf[4]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_SERVO<<4) | (servoNr & 0xf); wbuf[2] = HIGHBYTE(servoPos); wbuf[3] = LOWBYTE(servoPos); if ((spisend(rbuf,wbuf, 4)) != 4) { printf("E: fpga: Could not write specified amount of bytes to printf chardev\\n"); return -1; } return 0; } int fpga_setspeedacc (uint8_t speed_intead_acc ) { unsigned char wbuf[2]; unsigned char rbuf[2]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_SPEED_ACC_SWITCH<<4) | (speed_intead_acc & 0xf); printf ("writing speedacc %d\\n", speed_intead_acc); if ((spisend(rbuf,wbuf, 2)) != 2) { printf("E: fpga: Could not write specified amount of bytes to printf chardev\\n"); return -1; } return 0; } int fpga_as (uint8_t on ) { unsigned char wbuf[2]; unsigned char rbuf[2]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_AS<<4) | (on & 0xf); printf ("writing %d\\n", on); if ((spisend(rbuf,wbuf, 2)) != 2) { printf("E: fpga: Could not write specified amount of bytes to printf chardev\\n"); return -1; } return 0; } int fpga_setleds ( uint8_t onoff, uint8_t leds ) { unsigned char rbuf[2]; unsigned char wbuf[2]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_LED<<4) | (leds & ((1<<2)|(1<<1)|(1<<0))); if ( onoff ) wbuf[1] |= (1<<3); if ((spisend(rbuf,wbuf, 2)) != 2) { printf("E: fpga: Could not write specified amount of bytes to printf chardev\\n"); return -1; } return 0; } int fpga_setspeedv (uint16_t vspeed, uint16_t vsteering ) { unsigned char rbuf[6]; unsigned char wbuf[6]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = CMD_SPEED; wbuf[2] = HIGHBYTE(vspeed); wbuf[3] = LOWBYTE(vspeed); wbuf[4] = HIGHBYTE(vsteering); wbuf[5] = LOWBYTE(vsteering); if ((spisend(rbuf,wbuf, 6)) != 6) { printf("E: fpga: Could not write specified amount of bytes to spi\\n"); return -1; } return 0; } int fpga_logopen() { logfd = fopen("/tmp/ourlog", "a"); if ( !logfd ) return -1; fprintf (logfd, "--------reopened--------\\n"); } int fpga_pollspeed() { unsigned char rbuf[8]; unsigned char wbuf[8]; int acc,speedf,speedr,speedd; int i; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_SPEEDPOLL<<4); wbuf[2] = 0x00; wbuf[3] = 0x00; wbuf[4] = 0x00; wbuf[5] = 0x00; wbuf[6] = 0x00; wbuf[7] = 0x00; if ((spisend(rbuf,wbuf, 8)) != 8) { printf("E: fpga: Could not write specified amount of bytes to spi\\n"); return -1; } for(i=0;i<8;i++) { printf ( "%x - ", rbuf[i]); } printf ( "\\n"); speedf = rbuf[3]; speedr = rbuf[4]; speedd = rbuf[5]; acc = (rbuf[6]<<8) + rbuf[7]; fprintf ( logfd, "%d %d %d %d\\n", speedf, speedr, speedd, acc ); return 0; } int fpga_setspeedraw (uint8_t speed) { unsigned char rbuf[3]; unsigned char wbuf[3]; wbuf[0] = SPI_PREAMBLE; wbuf[1] = (CMD_SPEEDRAW<<4); wbuf[2] = speed; if ((spisend(rbuf,wbuf, 3)) != 3) { printf("E: fpga: Could not write specified amount of bytes to spi\\n"); return -1; } return 0; } int spisend ( char*rbuf, char*wbuf, int len ) { int ret; pthread_mutex_lock ( &spi_mutex ); struct spi_ioc_transfer tr = { .tx_buf = (unsigned long)wbuf, .rx_buf = (unsigned long)rbuf, .len = len, .delay_usecs = SPI_DELAY, .speed_hz = SPI_SPEED_HZ, .bits_per_word = SPI_BITS_PER_WORD, }; ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1){ printf("can't send spi message"); pthread_mutex_unlock ( &spi_mutex ); return -1; } pthread_mutex_unlock ( &spi_mutex ); return ret; } void fpga_testservos() { if ( fpga_open() ) { printf ( "E: FPGA: Could not open SPI to FPGA\\n" ); exit(-1); } printf("Moving servo left\\n"); fpga_setservo(1,0); sleep(2); printf("Moving servo centre\\n"); fpga_setservo(1,4000); sleep(2); printf("Moving servo right\\n"); fpga_setservo(1,8000); sleep(2); printf("Moving servo centre\\n"); fpga_setservo(1,4000); fpga_close(); }
0
#include <pthread.h> int *array; int array_size; int begin; int interval; } Array_arg; int global_sum; pthread_mutex_t lock; void *sum (void *argument) { Array_arg *arg = (Array_arg *)argument; int i, sum = 0; for (i = arg->begin; i < arg->begin + arg->interval; i++) { sum += arg->array[i]; } pthread_mutex_lock(&lock); global_sum += sum; pthread_mutex_unlock(&lock); pthread_exit(0); } int main (int argc, char **argv) { if (argc != 3) { fprintf(stderr, "usage : %s size of array and number of threads\\n", argv[0]); exit (-1) ; } int nb_thread = atoi(argv[2]); if (nb_thread > (atoi(argv[1])/ 2)) { printf("Number of thread is greater to array size divided by 2\\n"); return(-1); } global_sum = 0; if (pthread_mutex_init(&lock, 0) != 0) { printf("Mutex init failed\\n"); } Array_arg arg; arg.array_size = atoi(argv[1]); arg.array = (int *)malloc(arg.array_size * sizeof(int)); srand(time(0)); int i; for (i = 0; i < arg.array_size; i++) { arg.array[i] = rand() % 5 + 3 ; } pthread_t *pthreads = malloc(nb_thread*sizeof(pthread_t)); int interval = arg.array_size / nb_thread; int add = 0; if (interval * nb_thread != arg.array_size) { add = arg.array_size - (interval * nb_thread); } Array_arg args[nb_thread]; int y; for (y = 0; y < nb_thread; y++) { args[y].begin = y * interval; args[y].interval = interval; args[y].array = arg.array; args[y].array_size = arg.array_size; if (y == nb_thread - 1) { args[y].interval += add; } if( pthread_create(&pthreads[y], 0, sum, &args[y]) < 0) { printf("ERROR !\\n"); return -1; } } int j; for (j = 0; j < nb_thread; j++) { pthread_join(pthreads[j], 0); } printf("\\n Value of array :\\n"); for(i = 0; i < arg.array_size; i++){ printf("%d\\n", arg.array[i]); } printf("\\n Value of global :\\n"); printf("%d\\n", global_sum); free(pthreads); free(arg.array); pthread_mutex_destroy(&lock); return 0; }
1
#include <pthread.h> int* vet; pthread_mutex_t mutex; } Data; Data data; void merge(int *vet, int left, int middle, int right) { int i, j, k; int n1 = middle - left + 1; int n2 = right - middle; int L[n1], R[n2]; for (i = 0; i <= n1; i++) L[i] = vet[left + i]; for (j = 0; j <= n2; j++) R[j] = vet[middle + 1 + j]; i = 0; j = 0; k = left; while (i < n1 && j < n2) { if (L[i] <= R[j]) vet[k++] = L[i++]; else vet[k++] = R[j++]; } while (i < n1) vet[k++] = L[i++]; while (j < n2) vet[k++] = R[j++]; } void* threaded_sort(void* args) { int* arg = args; int left, right, middle; void* ret = 0; left = arg[0]; right = arg[1]; if (left < right) { middle = left + (right - left)/2; pthread_t thread1, thread2; int arg1[2] = {left, middle}; pthread_create(&thread1, 0, threaded_sort, arg1); int arg2[2] = {middle + 1, right}; pthread_create(&thread2, 0, threaded_sort, arg2); pthread_join(thread1, &ret); pthread_join(thread2, &ret); pthread_mutex_lock(&data.mutex); merge(data.vet, left, middle, right); pthread_mutex_unlock(&data.mutex); } return ret; } int main(int argc, char ** argv) { int i, n; if (argc != 2) { printf ("Syntax: %s dimension\\n", argv[0]); return (1); } n = atoi(argv[1]); data.vet = (int*) malloc(n * sizeof(int)); pthread_mutex_init(&data.mutex, 0); pthread_mutex_lock(&data.mutex); for(i = 0;i < n;i++) { data.vet[i] = rand() % 100; printf("%d\\n",data.vet[i]); } pthread_mutex_unlock(&data.mutex); printf("\\n"); int arg[2] = {0, n-1}; threaded_sort(arg); pthread_mutex_lock(&data.mutex); for(i = 0;i < n;i++) printf("%d\\n",data.vet[i]); pthread_mutex_unlock(&data.mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t freePos, filledPos; int prod_pos = 0, cons_pos = 0, stock = 0, buffer[20]; void * producer (void * arg); void * consumer (void * arg); int main (int argc, char * argv[]) { pthread_t producerThread[5], consumerThread[7]; int i = 0, * idC = 0, * idP = 0; srand (time(0)); sem_init (&freePos, 0, 20); sem_init (&filledPos, 0, 0); for (i = 0; i < 5; i++) { idP = (int *) malloc (sizeof (int)); *idP = i; if (pthread_create (&producerThread[i], 0, producer, (void *) idP)) { printf ("Falha ao criar producerThread numero %d!!\\n", i); return -1; } } for (i = 0; i < 7; i++) { idC = (int *) malloc (sizeof (int)); *idC = i; if (pthread_create (&consumerThread[i], 0, consumer, (void *) idC)) { printf ("Falha ao criar consumerThread numero %d!!\\n", i); return -1; } } for (i = 0; i < 5; i++) { if (pthread_join (producerThread[i], 0)) return -1; } for (i = 0; i < 7; i++) { if (pthread_join (consumerThread[i], 0)) return -1; } return 0; } void * producer (void * arg) { int i = *((int *) arg); int dataProd; while (1) { printf ("Produtor %d: vou produzir um item\\n", i); sleep (2); sem_wait (&freePos); pthread_mutex_lock (&mutex); dataProd = rand()%1001; printf ("Produtor %d: Produzindo item...\\n", i); sleep (2); printf ("Produtor %d: vou inserir item %d na posicao %d\\n", i, dataProd, prod_pos); buffer[prod_pos] = dataProd; prod_pos = (prod_pos + 1)%20; stock++; printf ("Dados em estoque: %d\\n\\n", stock); pthread_mutex_unlock (&mutex); sem_post (&filledPos); } pthread_exit (0); } void * consumer (void * arg) { int i = *((int *) arg); int removed = 0; while (1) { sleep (2); sem_wait (&filledPos); pthread_mutex_lock (&mutex); if (stock == 0) printf ("\\tConsumidor %d:\\n\\tVou esperar por itens\\n", i); removed = buffer[cons_pos]; printf ("\\tConsumidor %d:\\n\\tDado removido da posicao %d: %d\\n", i, cons_pos, removed); cons_pos = (cons_pos + 1)%20; stock--; printf ("\\tDados em estoque: %d\\n\\n", stock); pthread_mutex_unlock (&mutex); printf ("\\tConsumidor %d:\\n\\tConsumindo dado: %d\\n", i, removed); sem_post (&freePos); sleep (20); } pthread_exit (0); }
1
#include <pthread.h> int file_flag[25]={0}; pthread_mutex_t mutex; int check_file(char filename[]) { pthread_mutex_lock(&mutex); char buf[2]; buf[0]=filename[6]; if(filename[7]!='.') {buf[1]=filename[7];} int tmp=atoi(buf); if(file_flag[tmp-1]==0) { file_flag[tmp-1]=1; pthread_mutex_unlock(&mutex); return 1; } else { pthread_mutex_unlock(&mutex); return 0; } }; void *open_dir_read_file(void* arg) { char* open_add=(char *)arg; DIR *dir; FILE *file; struct dirent *ent; char *line = 0; size_t len = 1000; size_t read; char full_filename[256]; if ((dir = opendir (open_add)) != 0) { while ((ent = readdir (dir)) != 0) { if(ent->d_type == DT_REG) { snprintf(full_filename, sizeof full_filename, "./%s%s\\0", open_add, ent->d_name); if(check_file(ent->d_name)==1) { printf("%s\\n", ent->d_name); FILE* file = fopen(full_filename, "r"); if (file != 0) { while ((read = getline(&line, &len, file)) != -1) { } fclose(file); } } } } closedir (dir); } else { perror (""); } }; int main(int argc, char *argv[]) { if(argc < 2) { printf("Not enough arguments supplied\\n"); return -1; } if(argc > 2) { printf("Too many arguments supplied\\n"); return -1; } printf("%s\\n",argv[1]); pthread_mutex_init(&mutex,0); int ret_1,ret_2; pthread_t tid_1,tid_2; ret_1=pthread_create(&tid_1,0,open_dir_read_file,(void *)argv[1]); ret_2=pthread_create(&tid_2,0,open_dir_read_file,(void *)argv[1]); pthread_join(tid_1,0); pthread_join(tid_2,0); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int num = 0; FILE *fp[4]; int file = 1; void *write_func(void *arg) { int i; int j; int count = (int)arg; for(i = 0; i < 10; i++) { pthread_mutex_lock(&mutex); while(count != num) { pthread_cond_wait(&cond,&mutex); } if(file > 4) { file = 4; } printf("线程%d在操作!写入文件中.....\\n",count + 1); fp[0] = fopen("file1","a+"); fp[1] = fopen("file2","a+"); fp[2] = fopen("file3","a+"); fp[3] = fopen("file4","a+"); for(j = 0; j < file; j++) { putc('A' + count, fp[j]); putc('\\n', fp[j]); } fclose(fp[0]); fclose(fp[1]); fclose(fp[2]); fclose(fp[3]); file++; num = (num + 1) % 4; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond); sleep(1); } } int main() { int i; pthread_t fd[4]; pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); for(i = 0; i < 4; i++) { pthread_create(&fd[i],0,(void *)write_func,(void *)i); } for(i = 0; i < 4; i++) { pthread_join(fd[i],0); } return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; void busyWait(int i) { int j = 21474; i = i < 0 ? 1 : i; while (i>=0) { while (j>=0) {j--;} i--; } } void *funThread1() { printf("Thread 1 trying to lock the mutex now\\n"); pthread_mutex_lock(&mutex); printf("Thread 1 sucessfully locked the mutex!!\\n"); int i; for(i = 0; i < 10; i++){ busyWait(1); printf("This is the first Thread 1\\n"); } pthread_mutex_unlock(&mutex); printf("Thread 1 unlocked the mutex\\n"); } void *funThread2() { printf("Thread 2 trying to lock the mutex now\\n"); pthread_mutex_lock(&mutex); printf("Thread 2 sucessfully locked the mutex!!\\n"); int i; for(i = 0; i < 3 ; i++) { busyWait(1); printf("This is the second Thread 2\\n"); } pthread_mutex_unlock(&mutex); printf("Thread 2 unlocked the mutex\\n"); printf("Thread 2 EXITING!!!!!!!!\\n"); pthread_exit(&i); } void *funThread3() { int i; long j; for(i = 0; i < 2 ; i++) { busyWait(1); printf("This is the third Thread 3\\n"); } for(i = 0; i < 4 ; i++) { for(j=0;j<1000000000;j++){} pthread_yield(); printf("Thread 3 YIELDED!!\\n"); } printf("Thread 3 is done!\\n"); } void *funThread4() { printf("Thread 4 trying to lock the mutex now\\n"); pthread_mutex_lock(&mutex); printf("Thread 4 sucessfully locked the mutex!!\\n"); int i; for(i = 0; i < 4 ; i++) { busyWait(1); printf("This is the fourth Thread 4\\n"); } pthread_mutex_unlock(&mutex); printf("Thread 4 unlocked the mutex\\n"); } int main(int argc, const char * argv[]) { struct timeval start, end; float delta; gettimeofday(&start, 0); pthread_t thread1,thread2,thread3,thread4; pthread_mutex_init(&mutex, 0); pthread_create(&thread1, 0, &funThread1,0); pthread_create(&thread2, 0, &funThread2,0); pthread_create(&thread3, 0, &funThread3,0); pthread_create(&thread4, 0, &funThread4,0); pthread_join(thread1,0); pthread_join(thread2,0); pthread_join(thread3,0); pthread_join(thread4,0); pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); delta = (((end.tv_sec - start.tv_sec)*1000) + ((end.tv_usec - start.tv_usec)*0.001)); printf("Execution time in Milliseconds: %f\\n",delta); printf("Ending main!\\n"); return 0; }
0
#include <pthread.h> { int num_threads,id, plate_size,num_cycles; pthread_barrier_t * barrier; pthread_mutex_t * lock; double ***sheet; double * min; double * max; } Params; static void *slave(void * param) { Params * p = (Params *) param; int id = -1; pthread_mutex_lock(p->lock); id = p->id; p->id = p->id +1; pthread_mutex_unlock(p->lock); int t,i,j; double ** sheet = *p->sheet; double * max = p->max; double * min = p->min; int low = ((id)*(p->plate_size)/(p->num_threads)); int high = ((((id)+1)*(p->plate_size)/(p->num_threads))-1); double ** temp = (double **) malloc(sizeof(double*)*p->plate_size); for(i=0;i<p->plate_size;i++) temp[i] = (double *) malloc(sizeof(double)*p->plate_size); for(t = 0; t < p->num_cycles; t++) { for(i = low; i <= high; i++) { for(j = 1; j < p->plate_size; j++) { if(i == 0) temp[i][j] = 0.25 * (sheet[i][j] + sheet[i+1][j] + sheet[i][j-1] + sheet[i][j+1]); else if(i == p->plate_size - 1) temp[i][j] = 0.25 * (sheet[i-1][j] + sheet[i][j] + sheet[i][j-1] + sheet[i][j+1]); else temp[i][j] = 0.25 * (sheet[i-1][j] + sheet[i+1][j] + sheet[i][j-1] + sheet[i][j+1]); if(temp[i][j] > max[id]) max[id] = temp[i][j]; if(temp[i][j] < min[id]) min[id] = temp[i][j]; } } pthread_barrier_wait(p->barrier); for(i = low; i <= high; i++) for(j = 1; j < p->plate_size - 1; j++) if(i != 0 && i!= p->plate_size-1) sheet[i][j] = temp[i][j]; if(id ==-1) { for(i = 0; i < p->plate_size; i++) { for(j = 0; j < p->plate_size; j++) fprintf(stderr,"%10f ",sheet[i][j]); fprintf(stderr,"\\n"); } } if(id == -1) fprintf(stderr,"\\n"); } pthread_exit(0); } void usage() { printf("metal_plate\\n MPI Program to simulate heat moving through a plate.\\n Jharrod LaFon 2011\\n Usage: metal_plate [args]\\n -v\\t\\tBe verbose\\n -h\\t\\tPrint this message\\n"); } void parse_args(int argc, char ** argv, Params * p) { int c = 0; while((c = getopt(argc,argv,"hn:t:")) != -1) { switch(c) { case 'h': if(p->id == 0) usage(); exit(0); case 'n': p->num_threads = atoi(optarg); break; case 't': p->num_cycles = atoi(optarg); break; default: break; } } return; } int main(int argc, char *argv[]) { Params p; p.num_threads = 4; p.plate_size = 500; p.num_cycles = 1000; struct timespec start,end,elapsed; pthread_barrier_t barrier; pthread_mutex_t id_lock = PTHREAD_MUTEX_INITIALIZER; p.lock = &id_lock; p.barrier = &barrier; parse_args(argc,argv,&p); pthread_barrier_init(&barrier,0,p.num_threads); double ** sheet = (double**) malloc(sizeof(double*)*p.plate_size); double * min = (double *) malloc(sizeof(double)*p.num_threads); double * max = (double *) malloc(sizeof(double)*p.num_threads); int i,j; for(i = 0; i < p.plate_size; i++) { sheet[i] = (double*) malloc(sizeof(double)*p.plate_size); for(j = 0; j < p.plate_size; j++) { if(i == 0 || i == p.plate_size -1 || j == 0 || j == p.plate_size -1) { sheet[i][j] = 232; } else { sheet[i][j] = 97; } } } for(i = 0; i < p.num_threads; i++) { max[i] = 0; min[i] = 232; } p.sheet = &sheet; p.id = 0; p.max = max; p.min = min; pthread_t * threads = (pthread_t *) malloc(sizeof(pthread_t)*p.num_threads); clock_gettime(CLOCK_REALTIME, &start); for(i = 0; i < p.num_threads; i++) { if(pthread_create(&threads[i],0,slave, (void*)&p)<0) perror("pthread_create"); } for(i = 0;i < p.num_threads; i++) if(pthread_join(threads[i],0)) perror("pthread_join"); clock_gettime(CLOCK_REALTIME, &end); elapsed.tv_sec = end.tv_sec - start.tv_sec; elapsed.tv_nsec = end.tv_nsec - start.tv_nsec; if(elapsed.tv_nsec < 0) { elapsed.tv_sec -= 1; elapsed.tv_nsec += 1000000000; } printf("Elapsed time: %ld.%ld\\n",elapsed.tv_sec,elapsed.tv_nsec); fflush(stdout); double global_min = 232, global_max = 0; for(i = 0; i < p.num_threads; i++) { if(global_min > min[i]) global_min = min[i]; if(global_max < max[i]) global_max = max[i]; } fprintf(stderr,"Max temperature: %f Min temperature: %f\\n",global_max,global_min); return 0; }
1
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t cond; data_t _data; struct node * _next; }node_t,*node_p,**node_pp,*list_head; list_head head = 0; static node_p buy_node(data_t data) { node_p new_node = (node_p)malloc(sizeof(node_t)); if(new_node == 0){ printf("%d : %s \\n",errno,strerror(errno)); exit(1); } new_node->_data = data; new_node->_next = 0; return new_node; } static void delete_node(node_p node) { if(node){ free(node); node = 0; } } int is_empty(list_head head) { if(head && head->_next == 0){ return 1; } return 0; } void list_init(node_pp head) { *head = buy_node(-1); } void push_head(list_head head,data_t data) { if(head){ node_p tmp = buy_node(data); tmp->_next = head->_next; head->_next = tmp; } } int pop_head(list_head head,data_t* data) { if(is_empty(head)){ return 0; } node_p tmp = head->_next; head->_next = head->_next->_next; *data = tmp->_data; delete_node(tmp); return 1; } void clear(list_head head) { data_t tmp = 0; while(!is_empty(head)){ pop_head(head,&tmp); } delete_node(head); } void show_list(list_head head) { node_p cur = head->_next; while(cur){ printf("%d",cur->_data); cur = cur->_next; } } void* consumer_data(void* arg) { int count = 10; data_t data = -1; while(count--){ pthread_mutex_lock(&lock); while(is_empty(head)){ pthread_cond_wait(&cond,&lock); } int ret = pop_head(head,&data); pthread_mutex_unlock(&lock); if(ret == 0){ printf("consume data failed..\\n"); }else{ printf("comsume %d data success...\\n",data); } sleep(1); data = -1; } } void* producter_data(void *arg) { int count = 10; while(count--){ pthread_mutex_lock(&lock); push_head(head,count); pthread_mutex_unlock(&lock); pthread_cond_signal(&cond); printf("data is ready,please consume!\\n"); printf("producte %d data done..\\n",count); sleep(5); } } int main() { pthread_mutex_init(&lock,0); pthread_cond_init(&cond,0); list_init(&head); pthread_t consumer,producter; pthread_create(&consumer,0,consumer_data,0); pthread_create(&producter,0,producter_data,0); pthread_join(consumer,0); pthread_join(producter,0); clear(head); pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); return 0; }
0
#include <pthread.h> int thID; int min; int max; } arg; int **a, *b, *c; int N, M, T; pthread_mutex_t mx; void tres (arg *args) { int i, j; int *cl; cl = malloc (N * sizeof (int)); for (i=0; i<N; i++) cl[i] = 0; for (j=args->min; j<args->max; j++) for (i=0; i<N; i++) cl[i] = cl[i] + a[i][j] * b[j]; for (i=0; i<N; i++) { pthread_mutex_lock(&mx); c[i]+= cl[i]; pthread_mutex_unlock(&mx); } } main (int argc, char *argv[]) { struct timeval ts, tf; int i, j; int cl, fr; pthread_t *th; arg *args; N = atoi(argv[1]); M = atoi(argv[2]); T = atoi(argv[3]); th = malloc (T * sizeof (pthread_t)); a = malloc (N * sizeof (int *)); b = malloc (M * sizeof (int)); c = malloc (N * sizeof (int)); args = malloc (T * sizeof (arg)); if (a==0 || th==0 || args==0 || b==0 || c==0) { printf ("Memoria\\n"); exit (1); } for (i=0; i<N; i++) { a[i] = malloc (M * sizeof (int)); if (a[i] == 0) { printf ("Memoria\\n"); exit (1);} } srandom (177845); for (i=0; i<N; i++) { c[i] = 0; for (j=0; j<M; j++) a[i][j] = random() % 10; } for (j=0; j<M; j++) b[j] = random() % 10; (void) pthread_mutex_init(&mx, 0); cl = (int)ceil((float)M/(float)T); fr = (int)floor((float)M/(float)T); for (j=0; j<M%T; j++) { args[j].thID = j; args[j].min = j*cl; args[j].max = (j+1)*cl; } for (j=M%T; j<T; j++) { args[j].thID = j; args[j].min = (M%T)*cl + (j-(M%T))*fr; args[j].max = (M%T)*cl + (j-(M%T)+1)*fr; } gettimeofday (&ts, 0); for (i=0; i<T; i++) pthread_create (&th[i], 0, (void *) tres, (void *)&args[i]); for (i=0; i<T; i++) if (pthread_join (th[i], 0)) {printf ("PJOIN (%d)\\n", i); exit (1);}; gettimeofday (&tf, 0); printf ("Time (col): %f secs\\n", ((tf.tv_sec - ts.tv_sec)*1000000u + tf.tv_usec - ts.tv_usec)/ 1.e6); exit (0); }
1
#include <pthread.h> pthread_mutex_t bucket_lock; int uma_page_mask; struct uma_page_head *uma_page_slab_hash; void thread_bucket_lock(void) { pthread_mutex_lock(&bucket_lock); } void thread_bucket_unlock(void) { pthread_mutex_unlock(&bucket_lock); }
0
#include <pthread.h> int N=3; int mailBox[2]; int readCount=0; pthread_mutex_t read_mutex; pthread_mutex_t write_mutex; void* ring(void*arg){ int *id; int content; id=(int*)arg; char flag=0; int writeCount=2; while(writeCount>=0){ pthread_mutex_lock(&read_mutex); if(readCount==0) pthread_mutex_lock(&write_mutex); readCount++; pthread_mutex_unlock(&read_mutex); if(*id==(mailBox[0]%N)){ flag=1; content=mailBox[1]; } pthread_mutex_lock(&read_mutex); readCount--; if(readCount==0) pthread_mutex_unlock(&write_mutex); pthread_mutex_unlock(&read_mutex); if(flag==1){ pthread_mutex_lock(&write_mutex); mailBox[0]=*id+1; mailBox[1]=content+1; pthread_mutex_unlock(&write_mutex); printf("this is thread_%d:Receive:%d;Send:%d\\n",*id+1,content,content+1); flag=0; writeCount--; } } } int main() { N=3; pthread_t worker_id[N]; int param[N]; mailBox[0]=0; mailBox[1]=0; pthread_mutex_init(&read_mutex,0); pthread_mutex_init(&write_mutex,0); int i; for(i=0;i<N;i++){ param[i]=i; pthread_create(&worker_id[i],0,ring,&param[i]); } for(i=0;i<N;i++){ pthread_join(worker_id[i],0); } return 0; }
1
#include <pthread.h> void* compute_thread (void*); pthread_mutex_t my_sync; main( ) { pthread_t tid; pthread_attr_t attr; char hello[ ] = {"Hello, "}; char thread[ ] = {"thread"}; pthread_attr_init (&attr); pthread_mutex_init (&my_sync,0); pthread_create(&tid, &attr, compute_thread, hello); sleep(1); pthread_mutex_lock(&my_sync); printf(thread); printf("\\n"); pthread_mutex_unlock(&my_sync); exit(0); } void* compute_thread(void* dummy) { pthread_mutex_lock(&my_sync); printf(dummy); pthread_mutex_unlock(&my_sync); sleep(1); return; }
0
#include <pthread.h> char* ipAddress = "192.168.250."; pthread_mutex_t bloqueo; int estado=0; int Comando_ping(char *Direccion) { char *comando = 0; char buffer[1024]; FILE *fp; int stat = 0; asprintf (&comando, "%s %s", "ping", Direccion); printf("%s\\n", comando); fp = popen(comando, "r"); if (fp == 0) { fprintf(stderr, "Fallo\\n"); free(comando); return -1; } while(fread(buffer, sizeof(char), 1024, fp)) { if (strstr(buffer, "1 received")) return 0; } stat = pclose(fp); free(comando); return 1; } void *Trabajo_ping(void *tid) { char * DireccionIP = ipAddress; pthread_mutex_lock (&bloqueo); printf("%s\\n",DireccionIP ); estado = Comando_ping(DireccionIP); if (estado == 0) { printf("Ping a %s satisfactoriamente", DireccionIP); } else { printf("No responde "); } pthread_mutex_unlock(&bloqueo); } int main(int argc, char *argv[]){ int i, tids[40]; pthread_t threads[40]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&bloqueo, 0); char * DireccionIP = ipAddress; printf("%s\\n",DireccionIP ); for (i=0; i<40; i++) { tids[i] = i; pthread_create(&threads[i], &attr, Trabajo_ping,(void *) &tids[i]); } for (i=0; i<40; i++) { pthread_join(threads[i], 0); } pthread_attr_destroy (&attr); pthread_mutex_destroy (&bloqueo); pthread_exit(0); }
1
#include <pthread.h> int kupon[6] = {1,10,23,40,42,45}; int rezultat[7] = {0,0,0,0,0,0,0}; struct lotto{ int *vkupon; int *vrezultat; int s_pos; int k_pos; }; pthread_mutex_t mtx; void* losuj(void *vlotto); int main() { struct lotto s_lotto[1]; int k; for(k = 0; k<1; k++) { s_lotto[k].vkupon = kupon; s_lotto[k].vrezultat = rezultat; s_lotto[k].s_pos = k*(10000000/1); s_lotto[k].k_pos = (k+1)*(10000000/1); } pthread_t thready[1]; pthread_mutex_init(&mtx, 0); srand(time(0)); for(k = 0; k<1; k++) { pthread_create(&thready[k],0,losuj,&s_lotto[k]); } for(k = 0; k<1; k++) pthread_join(thready[k], 0); printf("Ilosc powtorzen: "); for(k = 0; k<7;k++) printf("%d\\t",rezultat[k]); printf("\\nSuma: %d",rezultat[0]+rezultat[1]+rezultat[2]+rezultat[3]+rezultat[4]+rezultat[5]+rezultat[6]); printf("\\n"); pthread_mutex_destroy(&mtx); return 0; } void* losuj(void *vlotto) { struct lotto *in_lotto = (struct lotto *)vlotto; int do_6 = 0; int tmp[6] = {0,0,0,0,0,0}; int wylosowana; int i,j; int porownanie = 0; int ile_rownych = 0; int k = 0; int id = (int)pthread_self(); for(k = in_lotto->s_pos; k < in_lotto->k_pos; k++) { while (do_6 < 6) { porownanie = 0; wylosowana = (rand_r(&id) % 49) + 1; for(i = 0; i < 6; ++i) { if(tmp[i] == wylosowana) porownanie++; } if(!porownanie) { tmp[do_6] = wylosowana; do_6++; } } for(i = 0; i < 6; ++i) { for(j = 0; j <6; ++j) { if(in_lotto->vkupon[i] == tmp[j]) { ile_rownych++; } } } pthread_mutex_lock(&mtx); in_lotto->vrezultat[ile_rownych] += 1; pthread_mutex_unlock(&mtx); ile_rownych = 0; porownanie = 0; do_6 = 0; for(i = 0; i < 6; ++i) tmp[i] = 0; } }
0
#include <pthread.h> int main(int argc, char* argv[]) { int i = 0; int buffer_size = 2048; if(argc != 1) { buffer_size = atoi(argv[1]); } int pixel_buffer_size = buffer_size+1; data.buffer_size = buffer_size; data.pixel_buffer_size = pixel_buffer_size; if((data.buffer = malloc(buffer_size * sizeof(int16_t))) == 0) exit(-1); if((data.pixel_tab = malloc(pixel_buffer_size * sizeof(char))) == 0) exit(-1); init_processing(); usleep(100); for(int j = 0; j < 10; j++) { pthread_mutex_lock(&process_mutex); for(i = 0; i < buffer_size; i++) data.buffer[i] = 0.26; data.position = 65; pthread_cond_signal(&new_data_to_process); pthread_mutex_unlock(&process_mutex); usleep(100); } end_processing(); free(data.pixel_tab); free(data.buffer); return 0; }
1
#include <pthread.h> enum job_cmd { JOB_CMD_RUN, JOB_CMD_END }; struct job { struct job *j_next; struct job *j_prev; pthread_t j_id; enum job_cmd j_cmd; }; struct queue { struct job *q_head; struct job *q_tail; pthread_rwlock_t q_lock; }; struct thr_cond { pthread_t tid; pthread_cond_t cond; pthread_mutex_t mutex; }; static struct queue job_queue; int queue_init (struct queue *qp) { int err; qp->q_head = 0; qp->q_tail = 0; err = pthread_rwlock_init(&qp->q_lock, 0); if (err != 0) return(err); return(0); } void job_insert(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); jp->j_next = qp->q_head; jp->j_prev = 0; if (qp->q_head != 0) qp->q_head->j_prev = jp; else qp->q_tail = jp; qp->q_head = jp; pthread_rwlock_unlock(&qp->q_lock); } void job_append(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); jp->j_next = 0; jp->j_prev = qp->q_tail; if (qp->q_tail != 0) qp->q_tail->j_next = jp; else qp->q_head = jp; qp->q_tail = jp; pthread_rwlock_unlock(&qp->q_lock); } void job_remove(struct queue *qp, struct job *jp) { pthread_rwlock_wrlock(&qp->q_lock); if (jp == qp->q_head) { qp->q_head = jp->j_next; if (qp->q_tail == jp) qp->q_tail = 0; } else if (jp == qp->q_tail) { qp->q_tail = jp->j_prev; if (qp->q_head == jp) qp->q_head = 0; } else { jp->j_prev->j_next = jp->j_next; jp->j_next->j_prev = jp->j_prev; } pthread_rwlock_unlock(&qp->q_lock); } struct job* job_find(struct queue *qp, pthread_t id) { struct job *jp = 0; if (pthread_rwlock_rdlock(&qp->q_lock) != 0) return(0); for (jp = qp->q_head; jp != 0; jp = jp->j_next) if (pthread_equal(jp->j_id, id)) break; pthread_rwlock_unlock(&qp->q_lock); return(jp); } void* thr_fn (void *arg) { struct job *jp = 0; pthread_t id = pthread_self (); struct thr_cond *cond = (struct thr_cond *)arg; int end = 0; while (!end) { pthread_mutex_lock (&(cond->mutex)); while (!(jp = job_find (&job_queue, id))) { pthread_cond_wait (&(cond->cond), &(cond->mutex)); } pthread_mutex_unlock (&(cond->mutex)); switch (jp->j_cmd) { case JOB_CMD_RUN: printf ("received JOB_CMD_RUN\\n"); break; case JOB_CMD_END: printf ("received JOB_CMD_END\\n"); end = 1; break; default: printf ("received unknown cmd : %d\\n", jp->j_cmd); break; } job_remove (&job_queue, jp); free (jp); } pthread_exit ((void *)0); } int main (int argc, char *argv[]) { struct thr_cond thr_cond_array[3], *tc; struct job *jp = 0; int i = 0, err = 0; err = queue_init (&job_queue); if (err) { err_quit ("can't init queue, err = %s\\n", strerror (err)); } for (i = 0; i < 3; i++) { err = pthread_mutex_init (&(thr_cond_array[i].mutex), 0); if (err) { err_quit ("can't init mutex, err = %s\\n", strerror (err)); } err = pthread_cond_init (&(thr_cond_array[i].cond), 0); if (err) { err_quit ("can't init cond, err = %s\\n", strerror (err)); } err = pthread_create (&(thr_cond_array[i].tid), 0, thr_fn, &(thr_cond_array[i])); if (err) { err_quit ("can't create thread, err = %s\\n", strerror (err)); } } for (i = 0; i < 300; i++) { tc = &(thr_cond_array[i % 3]); jp = (struct job *)malloc (sizeof (struct job)); jp->j_id = tc->tid; jp->j_cmd = JOB_CMD_RUN; job_append (&job_queue, jp); pthread_cond_signal (&tc->cond); } for (i = 0; i < 3; i++) { tc = &thr_cond_array[i % 3]; jp = (struct job *)malloc (sizeof (struct job)); jp->j_id = tc->tid; jp->j_cmd = JOB_CMD_END; job_append (&job_queue, jp); pthread_cond_signal (&tc->cond); } for (i = 0; i < 3; i++) { pthread_join (thr_cond_array[i].tid, 0); } exit (0); }
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 clock_gettime(int id, struct timespec *tsp) { struct timeval tv; gettimeofday(&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec * 1000; } 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); free(arg); return(0); } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct to_info *tip; int err; clock_gettime(0, &now); 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; else free(tip); } } } 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) { clock_gettime(0, &when); when.tv_sec += 10; timeout(&when, retry, (void *)((unsigned long)arg)); } pthread_mutex_unlock(&mutex); exit(0); }
1
#include <pthread.h> int lines_read = 0; static ssize_t get_line(int fdin, char *buffer) { ssize_t result = read(fdin, buffer, BOOKZ_LENGTH); return result; } static ssize_t display_line(int fdin, int fdout) { char line[BOOKZ_LENGTH+2]; ssize_t result = get_line(fdin, line); if (result == BOOKZ_LENGTH) { line[BOOKZ_LENGTH] = '\\n'; line[BOOKZ_LENGTH+1] = '\\0'; write(fdout, line, BOOKZ_LENGTH+1); } pthread_mutex_lock(&adz_mutex); int should_display = adz_updated; pthread_mutex_unlock(&adz_mutex); if (should_display) display_adz(fdout); return result; } void display_all(int fdin, int fdout) { lines_read = 0; while (display_line(fdin, fdout) == BOOKZ_LENGTH) { lines_read++; sleep(1); } }
0
#include <pthread.h> char valor; int ocorrencias; }simbolo; pthread_mutex_t mutex; pthread_cond_t cond_leitor, cond_contador; FILE *arq_entrada; simbolo *vetor_contagem_total; char *buffer[1000]; int count=0, nthreads; void insereBuffer (char *cadeia) { static int in = 0; char *cad; if(cadeia != 0){ cad = (char*)malloc(sizeof(char)*1000); strcpy(cad, cadeia); }else cad = 0; pthread_mutex_lock(&mutex); while(count == 1000) { pthread_cond_wait(&cond_leitor, &mutex); } buffer[in] = cad; count++; in = (in + 1)%1000; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_contador); } char *retiraBuffer () { static int out = 0; char *cadeia; pthread_mutex_lock(&mutex); while(count == 0) { pthread_cond_wait(&cond_contador, &mutex); } cadeia = buffer[out]; count--; out = (out + 1)%1000; pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond_leitor); return cadeia; } 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_cadeia_simbolos(char *cadeia, simbolo* vetor){ int i = 0; char simbolo; int asc_s; while((simbolo = cadeia[i]) != '\\0'){ asc_s = (int) simbolo; if(asc_s > 33 && asc_s < 33 +90){ vetor[asc_s - 33].ocorrencias++; } i++; } } void concatena_vetor_contagem(simbolo* vetor){ int i = 0; for(i = 0; i < 90; i++){ vetor_contagem_total[i].ocorrencias += vetor[i].ocorrencias; } } void imprime_simbolos(simbolo *vetor_simbolos, FILE* arq){ int i; printf("Escrevendo saída no arquivo\\n"); 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; char cadeia[1000]; double inicio, fim; GET_TIME(inicio); while(fgets (cadeia, 60, arq_entrada)!=0) { insereBuffer(cadeia); } for(i = 1; i < nthreads; i++){ insereBuffer(0); } GET_TIME(fim); printf("tempo para ler o arquivo: %f\\n", (fim-inicio)); pthread_exit(0); } void *contabiliza_arquivo(void *arg){ int c; char *cadeia; simbolo *vetor_contagem = instancia_vetor_simbolos(); while((cadeia = retiraBuffer()) != 0) { contabiliza_cadeia_simbolos(cadeia, vetor_contagem); free(cadeia); } pthread_mutex_lock(&mutex); concatena_vetor_contagem(vetor_contagem); pthread_mutex_lock(&mutex); } int main(int argc, char *argv[]){ int c, t, *tid; double inicio, fim; printf ("PID: %d\\n", getpid()); pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond_leitor, 0); pthread_cond_init(&cond_contador, 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); } nthreads = atoi(argv[3]); pthread_t thread[nthreads]; arq_entrada = fopen(argv[1], "r"); FILE* arq_saida = fopen( argv[2], "w"); vetor_contagem_total = instancia_vetor_simbolos(); pthread_create(&thread[0], 0, le_arquivo, 0); GET_TIME(inicio); for(t = 1; t < nthreads; t++){ tid = (int*) malloc(sizeof(int)); *tid = t; pthread_create(&thread[t], 0, contabiliza_arquivo, (void*)tid); } for (t = 0; t < nthreads; t++) { pthread_join(thread[t], 0); } GET_TIME(fim); printf("tempo processamento: %f\\n", fim-inicio); GET_TIME(inicio); imprime_simbolos(vetor_contagem_total, arq_saida); GET_TIME(fim); printf("tempo escrever saída: %f\\n", fim-inicio); fclose(arq_entrada); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t vacio,lleno; int buffer[16], numdatos; *consumidor(){ struct datos_tipo *datos_proceso; int a,i,j,p,posicion=0,dato; for(i=0;i<1000;i++){ pthread_mutex_lock(&mutex); while(numdatos==0) pthread_cond_wait(&vacio,&mutex); dato=buffer[posicion]; if(posicion==15) posicion=0; else posicion++; numdatos--; if(numdatos==16 -1) pthread_cond_signal(&lleno); pthread_mutex_unlock(&mutex); printf("\\nsehaconsumidoeldato:%d",dato); fflush(stdout); sleep(1); } } * productor(){ struct datos_tipo *datos_proceso; int a, i, j, p, posicion = 0, dato; for(i=0; i<1000; i++){ pthread_mutex_lock(&mutex); while(numdatos == 16) pthread_cond_wait(&lleno, &mutex); buffer[posicion] = i; dato = i; if(posicion == 15) posicion = 0; else posicion ++; numdatos ++; if(numdatos == 1) pthread_cond_signal(&vacio); pthread_mutex_unlock(&mutex); printf("\\nse ha producido el dato: %d", dato); fflush(stdout); } pthread_exit(0); } main(){ int error; char *valor_devuelto; pthread_t idhilo1, idhilo2, idhilo3, idhilo4; pthread_mutex_init(&mutex, 0); pthread_cond_init(&lleno, 0); pthread_cond_init(&vacio, 0); error=pthread_create(&idhilo1, 0, (void *)productor, 0); if (error != 0){ perror ("No puedo crear hilo"); exit (-1); } error=pthread_create(&idhilo2, 0, (void *)consumidor, 0); if (error != 0){ perror ("No puedo crear thread"); exit (-1); } pthread_join(idhilo2, (void **)&valor_devuelto); pthread_join(idhilo1, (void **)&valor_devuelto); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&lleno); pthread_cond_destroy(&vacio); return 0; }
0
#include <pthread.h> int main(int argc, char const *argv[]) { int err; struct timespec tout; struct tm *tmp; char buf[64]; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&lock); printf("mutex is lock!\\n"); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp); printf("current time:%s\\n", buf); tout.tv_sec += 5; pthread_mutex_unlock(&lock); err = pthread_mutex_timedlock(&lock, &tout); clock_gettime(CLOCK_REALTIME, &tout); tmp = localtime(&tout.tv_sec); strftime(buf, sizeof(buf), "%r", tmp); printf("current time:%s\\n", buf); if(err == 0){ printf("mutex lock again!\\n"); } else { printf("can't lock again! err:%s\\n", strerror(err)); } return 0; }
1
#include <pthread.h> extern char* bloomArray; extern int k; extern long int size; extern pthread_mutex_t* mutexes; extern long int sections; extern int section_bytes; void print(const char* str) { char c; int i; for(i=0; str[i] != 0 ; i++ ) { c = str[i]; if((c >32) && (c < 127)) { printf("%c",c); } else { printf("'\\\\%d'",c); } } printf("\\n"); } void printBloom(char* bloom,int size) { int bit,i,b; char c; for (i=0; i < size; i++) { printf("\\nbyte %d : ",i); c = bloom[i]; for (bit=0; bit < CHAR_BIT; bit++) { b = c & 0X01; printf("%i", b); c = c >> 1; } } printf("\\n"); } void insertBloom(const char*word) { uint64_t value,mask; long int pos; int i,j,imin,tmp; uint64_t bytes[k]; uint64_t bits[k]; long int active_sections[k]; char* bloom = bloomArray; long int bloom_size = size; for(i=0 ; i<k ; i++ ) { value = hash_by(i,word); pos = (long int) (value % (bloom_size*CHAR_BIT)); bytes[i] = pos/CHAR_BIT; bits[i] = pos % CHAR_BIT; active_sections[i] = bytes[i]/section_bytes; } for (i=0 ; i<k-1 ; i++){ imin = i; for (j = i+1; j < k ; j++){ if (active_sections[j] < active_sections[imin]){ imin = j; } } tmp = active_sections[i]; active_sections[i] = active_sections[imin]; active_sections[imin] = tmp; } i=0; while(i < k) { pthread_mutex_lock(&mutexes[i]); j=i+1; while(j < k) { if(active_sections[i] == active_sections[j]) { i++; j++; } else { break;} } i++; } for(i=0 ; i<k ; i++) { mask = 1 << bits[i]; bloom[bytes[i]] = bloom[bytes[i]] | mask; } i=0; while(i < k) { pthread_mutex_unlock(&mutexes[i]); j=i+1; while(j < k) { if(active_sections[i] == active_sections[j]) { i++; j++; } else { break;} } i++; } } int checkBloom(const char*word) { uint64_t value,mask; long int pos; int i,j,imin,tmp; int b; long int active_sections[k]; uint64_t bytes[k]; uint64_t bits[k]; char* bloom = bloomArray; long int bloom_size = size; b = -1; for(i=0 ; i<k ; i++ ) { value = hash_by(i,word); pos = (long int) (value % (bloom_size*CHAR_BIT)); bytes[i] = pos/CHAR_BIT; bits[i] = pos % CHAR_BIT; active_sections[i] = bytes[i]/section_bytes; } for (i=0 ; i<k-1 ; i++){ imin = i; for (j = i+1; j < k ; j++){ if (active_sections[j] < active_sections[imin]){ imin = j; } } tmp = active_sections[i]; active_sections[i] = active_sections[imin]; active_sections[imin] = tmp; } i=0; while(i < k) { pthread_mutex_lock(&mutexes[i]); j=i+1; while(j < k) { if(active_sections[i] == active_sections[j]) { i++; j++; } else { break;} } i++; } for(i=0 ; i<k ; i++) { mask = 1 << bits[i]; b = ((bloom[bytes[i]] & mask) != 0); if(!b){ break; } } i=0; while(i < k) { pthread_mutex_unlock(&mutexes[i]); j=i+1; while(j < k) { if(active_sections[i] == active_sections[j]) { i++; j++; } else { break;} } i++; } if(b ==0) { return 0; } return 1; }
0
#include <pthread.h> struct { char data[10]; int top; } Stack={{0,0,0,0,0,0,0,0,0,0}, 0}; pthread_mutex_t mutx = PTHREAD_MUTEX_INITIALIZER; void* Child(void* arg) { int i; char c; int timeout = 3; do { pthread_mutex_lock(&mutx); if ( Stack.top > 0 ) c = Stack.data[--Stack.top]; else c = 0; pthread_mutex_unlock(&mutx); if ( c != 0 ) { fputc(c, stderr); timeout = 3; } else { sleep(random()); timeout--; } } while ( timeout > 0 ); } int main(void) { char c; pthread_t pchild; if ( pthread_create(&pchild, 0, Child, 0) != 0 ) { perror("Thread"); exit(-1); } c = 'A'; while ( c <= 'Z' ) { pthread_mutex_lock(&mutx); if ( Stack.top < sizeof(Stack.data) ) Stack.data[Stack.top++] = c++; pthread_mutex_unlock(&mutx); sleep(random()%2); } pthread_join(pchild, 0); return 0; }
1
#include <pthread.h> int i = 0; pthread_mutex_t mtx; void* adder(){ for(int x = 0; x < 1000000; x++){ pthread_mutex_lock(&mtx); i++; pthread_mutex_unlock(&mtx); } return 0; } void* subtraher(){ for(int x = 0; x < 100000; x++){ pthread_mutex_lock(&mtx); i--; pthread_mutex_unlock(&mtx); } return 0; } int main(){ pthread_mutex_init(&mtx,0); pthread_t adder_thr; pthread_t subtraher_thr; pthread_create(&adder_thr, 0, adder, 0); pthread_create(&subtraher_thr, 0, subtraher, 0); for(int x = 0; x < 50; x++){ printf("%i\\n", i); } pthread_join(adder_thr, 0); pthread_join(subtraher_thr, 0); printf("Done: %i\\n", i); return 0; }
0
#include <pthread.h> char char1[419430400], char2[419430400], char3[419430400]; long max = 419430400, load_div, buffer_size; struct timeval t; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void file(long max) { printf("\\nGenerating file in Memory...\\n"); int i; for (i = 0; i < max; ++i) { char1[i]= 'A'; } } void *seq_write() { long sw; pthread_mutex_lock( &mutex1 ); for(sw = 0; sw < load_div; sw+= buffer_size) strncpy(char2, char1, buffer_size); pthread_mutex_unlock( &mutex1 ); } void *ran_write() { long rw1, rw2; pthread_mutex_lock( &mutex1 ); for (rw1 = 0;rw1 < load_div; rw1 += buffer_size) { rw2 = rand()% 100; strncpy(&char2[rw2], &char1[rw2], buffer_size); } pthread_mutex_unlock( &mutex1 ); } void *read_write() { long r, w; pthread_mutex_lock( &mutex1 ); for(r = 0; r < load_div; r += buffer_size) memcpy(char2, char1, buffer_size); for(w = 0; w < load_div; w += buffer_size) strncpy(char3, char2, buffer_size); pthread_mutex_unlock(&mutex1); } int main() { int th, a, b, c, d, e, g, choice; double start_th, stop_th, th_t, x, y, z; float th_tp[40]; printf("\\nHow many Threads you want to Create 1, 2, 4 or 8"); printf("\\nEnter Number of Threads: "); scanf("%d",&th); pthread_t threads[th]; printf("\\nSelect Block size: \\n 1. 8B\\t2. 8KB\\t3. 8MB\\t4. 80MB"); printf("\\nEnter Your Choice: "); scanf("%d", &choice); if (choice == 1) { buffer_size = 8; } else if (choice == 2) { buffer_size = 8192; } else if (choice == 3) { buffer_size = 8388608; } else if (choice == 4) { buffer_size = 83886080; } else { printf("Wrong Choice\\n"); } printf ("\\nSelected Thread(s) = %d & Block Size = %li Byte(s)", th, buffer_size); file(max); load_div = max/th; gettimeofday(&t,0); start_th = t.tv_sec+(t.tv_usec/1000000.0); for(a = 0; a < th; a++) { pthread_create(&threads[a],0, &seq_write, 0); } for(b =0; b < th; b++) { pthread_join(threads[b], 0); } gettimeofday(&t,0); stop_th = t.tv_sec+(t.tv_usec/1000000.0); th_t = stop_th - start_th; z = (max/th_t)/(1024*1024); printf("\\nThroughput for Sequential Memory Write: %lf MB/s", z); printf("\\nLatency for Sequential Memory Write: %lf Micro Sec.\\n", (th_t/max)*10000000); sleep(1); gettimeofday(&t, 0); start_th = t.tv_sec+(t.tv_usec/1000000.0); for(c = 0; c < th; c++) { pthread_create(&threads[a],0, &ran_write, 0); } for(d =0; d < th; d++) { pthread_join(threads[d], 0); } gettimeofday(&t, 0); stop_th = t.tv_sec+(t.tv_usec/1000000.0); th_t = stop_th - start_th; y =(max/th_t)/(1024*1024); printf("\\nThroughput for Random Memory Write: %lf MB/s", y); printf("\\nLatency for Random Memory Write: %lf Micro Sec.\\n", (th_t/max)*10000000); sleep(1); gettimeofday(&t, 0); start_th = t.tv_sec+(t.tv_usec/1000000.0); for( e=0; e<th; e++) { pthread_create(&threads[a],0, &read_write, 0); } for(g =0; g < th; g++) { pthread_join(threads[g], 0); } gettimeofday(&t, 0); stop_th = t.tv_sec+(t.tv_usec/1000000.0); th_t = stop_th - start_th; x = (max/th_t)/(1024*1024); printf("\\nThroughput for Memory Read & Write: %lf MB/s", x); printf("\\nLatency for Memory Read & Write: %lf Micro Sec.\\n", (th_t/max)*10000000); return 0; }
1
#include <pthread.h> int lastrow,lastcol; int win=0; int end=0; int row =12; int col= 30; pthread_cond_t cv; pthread_mutex_t mu; int map[20][60]; int getch (void) { int ch; struct termios oldt, newt; tcgetattr(STDIN_FILENO, &oldt); memcpy(&newt, &oldt, sizeof(newt)); newt.c_lflag &= ~( ECHO | ICANON | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL); tcsetattr(STDIN_FILENO, TCSANOW, &newt); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; } void threadtoleft(void *t){ int id = (int)t; int a; int b=35; int c=20; int d=5; int on=0; while(end==0){ pthread_mutex_lock(&mu); if(on==1){ on =0; col--; if(col<0)end=1; } for(a=0;a<60;a++){ if(abs(a-b)<10||abs(a-c)<10||abs(a-d)<10){ map[id][a]=1; if(row==t){ if(abs(col-b)<10||abs(col-c)<10||abs(col-d)<10){ map[id][col] = 2; on =1; } else end =1; } } else map[id][a]=0; } b--; c--; d--; if(b<-10)b=rand()%11+60; if(c<-13) c=rand()%11+60; if(d<-8) d =rand()%11+60; pthread_mutex_unlock(&mu); usleep(120000); } pthread_exit(0); } void threadtoright(void *t){ int id = (int )t; int on=0; int a; int b=50; int c=30; int d=-4; while(end==0){ pthread_mutex_lock(&mu); if(on==1){ on =0; col++; if(col>59)end=1; } for(a=0;a<60;a++){ if(abs(a-b)<7||abs(a-c)<7||abs(a-d)<7){ map[id][a]=1; if(row==id){ if(abs(col-b)<7||abs(col-c)<7||abs(col-d)<7){ map[id][col] = 2; on =1; } else end =1; } } else map[id][a]=0; } b++; c++; d++; if(b>65)b=rand()%10-20; if(c>63)c=rand()%10-20; if(d>66)d=rand()%10-20; pthread_mutex_unlock(&mu); usleep(130000); } pthread_exit(0); } void domove(void *threadid){ char in; int d; while(end==0){ in = getch(); if(in =='A' && col>0){ col=col-1; map[row][col]=2; if(row==0||row==12) map[row][col+1]=3; } else if(in =='D' && col <59){ col = col+1; map[row][col]=2; if(row==0||row==12) map[row][col-1]=3; } else if(in =='W' &&row>0){ row = row -1; map[row][col]=2; if(row==11) map[row+1][col]=3; if(row==0){ map[row+1][col]=1; win =1; } } else if(in =='S' &&row<12){ row = row +1; map[row][col]=2; if(row==12) col = col-1; } else if(in =='Q') end =3; usleep(10000); } pthread_exit(0); } void doprint(void *threadid){ int tid; int a,b;int ke=0 ; tid = (int)threadid; while(end==0){ pthread_mutex_lock(&mu); printf("\\033[2J\\033[0;0H"); for(a=0;a<=12;a++){ for(b=0;b<60;b++){ if(map[a][b]==0) printf(" "); else if(map[a][b]==1) printf("="); else if(map[a][b]==2){ printf("o");} else if(map[a][b]==3) printf("+"); } printf("\\n"); } if(win==1) end=2; pthread_mutex_unlock(&mu); usleep(10000); } pthread_mutex_lock(&mu); if(end ==3){ printf("\\n\\n\\nQUIT IT\\n"); exit(1); } if(end ==1){ printf("\\n\\n\\nLOSE\\n"); exit(1); } if(end ==2){ printf("\\n\\n\\nWIN\\n"); exit(1); } pthread_mutex_unlock(&mu); pthread_exit(0); } int main(){ int a; int b; for(b=0;b<=12;b++){ if(b==0||b==12){ for(a=0;a<60;a++){ map[b][a]=3; } } else{ for(a=30;a<60;a++) map[b][a]=0; } } map[row][col]=2; pthread_t threads[12]; pthread_mutex_init(&mu,0); pthread_cond_init(&cv,0); for(a=1;a<12;a++){ if(a%2==0) pthread_create(&threads[a],0,threadtoleft,(void*)a); else pthread_create(&threads[a],0,threadtoright,(void*)a); } usleep(1000); pthread_create(&threads[0],0,doprint,(void*)0); pthread_create(&threads[12],0,domove,(void*)0); for(a=0;a<12;a++){ pthread_join(threads[a], 0); } pthread_cond_destroy(&cv); pthread_mutex_destroy(&mu); pthread_exit(0); return 0; }
0
#include <pthread.h> struct Settings { int output_result; unsigned long long N; int M; }; struct Settings read_settings(int argc, char** argv) { struct Settings settings; if (argc < 3) { printf("wrong arguments count\\n"); exit(-1); } if (strcmp(argv[1], "-p") == 0) { settings.output_result = 1; settings.N = strtoll(argv[2], 0, 10); settings.M = strtoll(argv[3], 0, 10); } else { settings.output_result = 0; settings.N = strtoll(argv[1], 0, 10); settings.M = strtoll(argv[2], 0, 10); } return settings; } struct Task { unsigned long long base; unsigned long long step; pthread_mutex_t task_seted_mutex; pthread_cond_t task_ready; pthread_mutex_t task_ready_mutex; }; pthread_cond_t tasks_seted; struct Task* tasks; int* thread_num; int m; char* primes; unsigned long long n; unsigned long long sqrt_n; void* thread_function(void* arg) { int thread_num = *arg; while (1) { pthread_mutex_lock(&(tasks[i].task_seted_mutex)); pthread_cond_wait(&tasks_seted, &(tasks[i].task_seted_mutex)); pthread_mutex_unlock(&(tasks[i].task_seted_mutex)); } return 0; } pthread_t* start_threads(int count) { int i; pthread_t* threads = (pthread_t*)malloc(count * sizeof(pthread_t)); tasks = (struct Task*)malloc(count * sizeof(struct Task)); thread_num = (int*)malloc(count * sizeof(int)); for (i = 0; i < count; i++) { pthread_mutex_init(&(tasks[i].task_seted_mutex), 0); pthread_mutex_init(&(tasks[i].task_ready_mutex), 0); pthread_cond_init(&(tasks_seted), 0); thread_num[i] = i; pthread_create(threads + i, &(thread_num[i]), thread_function, 0); } return threads; } void join_threads(int count, pthread_t* threads) { int i; for (i = 0; i < count; i++) { pthread_join(threads[i], 0); pthread_mutex_destroy(&(tasks[i].task_seted_mutex)); pthread_mutex_destroy(&(tasks[i].task_ready_mutex)); pthread_cond_destroy(&(tasks_seted)); } free(threads); free(tasks); free(thread_num); } void set_tasks() { } void wait_tasks_completition() { } char* eratosthenes_sieve() { int i; sqrt_n = (unsigned long long)sqrt((double)n); primes = (char*)malloc(n + 1); memset(primes, 0x01, n + 1); primes[0] = 0; primes[1] = 0; pthread_t* threads = start_threads(m); for (i = 2; i <= sqrt_n; i++) { if (primes[i]) { set_tasks(); pthread_cond_broad_cast(&tasks_seted); wait_tasks_completition(); } } join_threads(m, threads); return primes; } int main(int argc, char** argv) { unsigned long long i; struct Settings settings = read_settings(argc, argv); n = settings.N; m = settings.M; char* primes = eratosthenes_sieve(); if (settings.output_result) { for (i = 2; i < settings.N; i++) { if (primes[i]) { printf("%llu\\n", i); } } } free(primes); return 0; }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_once = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t prt_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init() { pthread_key_create(&key, free); } char *getenv_r(const char *name) { int i, len; char *envbuf; pthread_once(&init_once, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0 ) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i = 0; environ[i] != 0; i++) { if ( (strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { memset(envbuf, 0, 4096); strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return (envbuf); } } pthread_mutex_unlock(&env_mutex); return (0); } { int argc; char **argv; }sarg; void *threadfunc(void *arg) { size_t i ; sarg *pt = (sarg *) arg; for (i = 1; i < pt->argc; i++) { char *p = getenv_r(pt->argv[i]); if (p) { pthread_mutex_lock(&prt_mutex); printf("tid = %lu, adrr = %p: %s = %s\\n", (unsigned long) pthread_self(), p, pt->argv[i], p); pthread_mutex_unlock(&prt_mutex); }else{ pthread_mutex_lock(&prt_mutex); printf("tid = %lu,Don't find %s env value.\\n", (unsigned long) pthread_self(), pt->argv[i]); pthread_mutex_unlock(&prt_mutex); } } sleep(30); } void main(int argc, char *argv[]) { if (argc > 1) { size_t i; int err; pthread_t tid[5]; sarg s; s.argc = argc; s.argv = argv; for (i = 0; i < 5; i++) { err = pthread_create(&tid[i], 0, threadfunc, (void *)&s); if(err != 0){ printf("NO. %d create pthread failed!\\n", i); tid[i] = -1; } } for (i = 0; i < 5; i++) { if (tid[i]>0) { pthread_join(tid[i], 0); } } }else{ printf("Usage:%s <env> <env> ....\\n",argv[0]); } exit(0); }
0
#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 ticket!\\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 ticket: %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(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_con); pthread_cond_destroy(&cond_pro); return 0; }
1
#include <pthread.h> int number; int phil_number; double timing; sem_t *lock; } arg_struct; THINKING = 0, WAITING = 1, EAT = 2, TERMINATE = 3 } State; State *philoStates; pthread_mutex_t *forks; pthread_t *philosopher; pthread_t watcher; int *fork_array; void display_state(int N); const char *state_convert(State philoState); void *func(void * arguments){ arg_struct args = *(arg_struct *)arguments; time_t start, end; double elapsed; start = time(0); int terminate = 1; double timing = args.timing; while (terminate) { end = time(0); elapsed = difftime(end, start); if (elapsed <= timing){ philoStates[args.phil_number] = THINKING; usleep((rand()%10000000)+1); philoStates[args.phil_number] = WAITING; sem_wait(args.lock); pthread_mutex_lock(&forks[args.phil_number]); fork_array[args.phil_number] = args.phil_number; pthread_mutex_lock(&forks[(args.phil_number+1)%args.number]); fork_array[(args.phil_number+1)%args.number] = args.phil_number; philoStates[args.phil_number] = EAT; usleep((rand()%10000000)+1); pthread_mutex_unlock(&forks[args.phil_number]); fork_array[args.phil_number] = -1; pthread_mutex_unlock(&forks[(args.phil_number+1)%args.number]); fork_array[(args.phil_number+1)%args.number] = -1; sem_post(args.lock); philoStates[args.phil_number] = THINKING; } else{ philoStates[args.phil_number] = TERMINATE; pthread_exit(0); } } return(0); } void display_state(int N){ int count =0; int i, terminated; while(1==1){ count=0; usleep(500000); printf("Philo\\t\\tState\\t\\t\\tFork\\t\\tHeld By\\n"); int th=0, waiting=0, eating=0, use=0, available=0; terminated=0; for(i = 0; i < N; i++) { printf("[%d]:\\t\\t%-10s\\t\\t", i, state_convert(philoStates[i])); if(philoStates[i]==TERMINATE){ terminated++; count++; } else if(philoStates[i]==EAT) eating++; else if(philoStates[i]==WAITING) waiting++; else if(philoStates[i]==THINKING) th++; if(fork_array[i]==-1){ printf("[%d]:\\t\\t%-10s\\n", i, "Free"); available++; }else{ printf("[%d]:\\t\\t%d\\n", i, fork_array[i]); use++; } } if(count==N){ printf("Th=%d Wa=%d Ea=%d\\t\\t\\t\\tUse=%d Avail=%d\\n", th, waiting, eating, use, available); pthread_exit(0); } printf("Th=%d Wa=%d Ea=%d\\t\\t\\t\\tUse=%d Avail=%d\\n", th, waiting, eating, use, available); } pthread_exit(0); } const char *state_convert(State philoState){ if(philoState == EAT) { return "Eating"; } else if(philoState == THINKING) { return "Thinking"; } else if(philoState == WAITING){ return "Waiting"; } else if(philoState == TERMINATE){ return "Terminated"; } else return "Error"; } int main(int argc, char *argv[]){ if(argc==4){ int N = atoi(argv[1]); int s = atoi(argv[2]); srand(s); double timing = strtol(argv[3], 0, 10); int i, id[N]; pthread_t tid[N]; sem_t lock; sem_init(&lock, 0, N - 1); fork_array = (int *)malloc(N * sizeof(int)); philosopher = (pthread_t *)malloc(N * sizeof(pthread_t)); forks = (pthread_mutex_t *)malloc(N * sizeof(pthread_mutex_t)); philoStates = (State *)malloc(N * sizeof(State)); for(i = 0; i < N; i++) { fork_array[i] = -1; } for (i = 0; i < N; i++){ pthread_mutex_init(&forks[i],0); } for(i=0;i<N;i++){ arg_struct *args = malloc(sizeof(arg_struct)); args->number = N; args->phil_number = i; args->timing = timing; args->lock = &lock; pthread_create(&philosopher[i], 0, (void *)func, (void * )args); } pthread_create(&watcher, 0, (void *)display_state, (void*) N); pthread_join(watcher, 0); pthread_exit(0); return 0; } else{ printf("Format: <NumPhilosophers> <Seed> <Time>\\n"); return 0; } }
0
#include <pthread.h> char *pais[3] = {"Peru", "Bolivia", "Colombia"}; void proceso(int i, int segment_id) { SEMAFORO *sem; sem = shmat(segment_id,0,0); int k; int c = 0; for(k=0;k<10;k++) { c = sem->count; waitsem((sem)); c = sem->count; printf("Entra %s %d",pais[i], (int)getpid()); fflush(stdout); printf("- %s Sale %d %d\\n",pais[i], (int) getpid(), k); pthread_mutex_lock(&((sem)->count2_mutex)); signalsem((sem)); c = (sem)->count; pthread_mutex_unlock(&((sem)->count2_mutex)); sleep(1); } exit(0); } int main(int argc, char const *argv[]) { SEMAFORO *sem; int segment_id = shmget(IPC_PRIVATE, sizeof(sem), S_IRUSR | S_IWUSR); pid_t tid[3]; printf("segment_id %d\\n",segment_id); int i; int status; sem = shmat(segment_id, 0, 0); (*sem) = (*initsem(1)); for(i=0;i<3;i++) { pid_t t; t = fork(); if(t > 0) { proceso(i, segment_id); } } for(i = 0; i < 3; i++){ wait(&status); } return 0; }
1
#include <pthread.h> int u,r; int *A; int *B; float *C; float nMax, nMin; double sum; pthread_mutex_t m; } results_t; results_t m_myResults; void* do_parallel(void *idx) { int i = (int) idx; int s = i * u + (i > r ? r : i); int e = s + u + ((i+1) > r ? 0 : 1); int c = e-s; if (c) { double sum = 0.0; float nMax = 0.0; float nMin = 10.0; unsigned int rseed = time(0) - (i*11); for (; s < e; s++) { A[s] = rand_r(&rseed) % 10; B[s] = rand_r(&rseed) % 10; C[s] = (A[s]+B[s])/2; sum += C[s]; if (C[s] > nMax) nMax = C[s]; if (C[s] < nMin) nMin = C[s]; } pthread_mutex_lock(&m_myResults.m); m_myResults.sum += sum; if (nMax > m_myResults.nMax) m_myResults.nMax = nMax; if (nMin < m_myResults.nMin) m_myResults.nMin = nMin; pthread_mutex_unlock(&m_myResults.m); } return 0; } int main(int argc, const char * argv[]) { int n = 0; int thread_c = 4; if (argc > 1) n = atoi(argv[1]); if (argc > 2) thread_c = atoi(argv[2]); if (!n || n < 0) { printf("Missing or invalid array size.\\n"); return 0; } m_myResults.nMax = 0.0; m_myResults.nMin = 10.0; m_myResults.sum = 0.0; pthread_mutex_init(&m_myResults.m, 0); A = (int *) malloc(n * sizeof(int)); B = (int *) malloc(n * sizeof(int));; C = (float *) malloc(n * sizeof(float)); pthread_t T[thread_c]; u = n/thread_c; r = n%thread_c; int i; for (i = 0; i < thread_c; i++) { pthread_create(&(T[i]), 0, do_parallel, (void*)i); } for (i = 0; i < thread_c; i++) { pthread_join(T[i], 0); } printf("pthreads - Average is: %.4f, Maximum is: %.2f, Minimum is: %.2f, Count: %d, Threads: %d\\n", m_myResults.sum/n, m_myResults.nMax, m_myResults.nMin, n, thread_c); pthread_mutex_destroy(&m_myResults.m); free(A); free(B); free(C); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_mutex_t mutex2; void *my_func(void *args) { printf("child %ld start\\n", (long)args); dbug_off(); dbug_on(); pthread_mutex_lock(&mutex); printf("child %ld\\n", (long)args); pthread_mutex_unlock(&mutex); dbug_off(); pthread_mutex_lock(&mutex2); printf("child2 %ld\\n", (long)args); pthread_mutex_unlock(&mutex2); dbug_on(); } int main() { dbug_off(); const int nt = 2; pthread_t t[nt]; dbug_on(); pthread_mutex_init(&mutex, 0); dbug_off(); pthread_mutex_init(&mutex2, 0); for (int i = 0; i < nt; i++) { dbug_on(); pthread_create(&t[i], 0, my_func, (void *)i); dbug_off(); } dbug_on(); pthread_mutex_lock(&mutex); printf("parent\\n"); pthread_mutex_unlock(&mutex); dbug_off(); for (int i = 0; i < nt; i++) { dbug_on(); pthread_join(t[i], 0); dbug_off(); } dbug_on(); pthread_mutex_destroy(&mutex); dbug_off(); dbug_on(); return 0; }
1
#include <pthread.h> char salle = 'A'; int nb_A = 0; int nb_B = 0; pthread_mutex_t group_A; pthread_mutex_t group_B; pthread_mutex_t fifo; void* f_group_A(void *arg) { int id = *((int*) arg); int i; for (i = 0; i < 5; i++) { printf("L'étudiant %d (A) veut entrer\\n", id); pthread_mutex_lock(&fifo); pthread_mutex_lock(&group_A); nb_A += 1; if(nb_A == 1) { pthread_mutex_lock(&group_B); } pthread_mutex_unlock(&group_A); pthread_mutex_unlock(&fifo); printf("L'étudiant %d (A) entre dans la salle \\n", id); sleep(rand() % 2); printf("L'étudiant %d (A) sort de la salle\\n", id); pthread_mutex_lock(&group_A); nb_A -= 1; if (nb_A == 0) { pthread_mutex_unlock(&group_B); } pthread_mutex_unlock(&group_A); sleep(rand() % 3); } printf("l'étudiant %d (A) s'en va\\n", id); return 0; } void* f_group_B(void *arg) { int id = *((int*) arg); int i; for (i = 0; i < 5; i++) { printf("L'étudiant %d (B) veut entrer\\n", id); pthread_mutex_lock(&fifo); pthread_mutex_lock(&group_B); nb_A += 1; if(nb_A == 1) { pthread_mutex_lock(&group_A); } pthread_mutex_unlock(&group_B); pthread_mutex_unlock(&fifo); printf("L'étudiant %d (B) entre dans la salle \\n", id); sleep(rand() % 2); printf("L'étudiant %d (B) sort de la salle\\n", id); pthread_mutex_lock(&group_B); nb_A -= 1; if (nb_A == 0) { pthread_mutex_unlock(&group_A); } pthread_mutex_unlock(&group_B); sleep(rand() % 3); } printf("l'étudiant %d (B) s'en va\\n", id); return 0; } int main() { int i, nb[8]; srand(time(0)); pthread_t tid[8]; for (i = 0; i < 5; i++) { nb[i] = i; pthread_create(&tid[i], 0, f_group_A, (void*) &nb[i]); } for (i = 0; i < 3; i++) { nb[i+5] = i; pthread_create(&tid[i+5], 0, f_group_B, (void*) &nb[i+5]); } for (i = 0; i < 8; i++) { pthread_join(tid[i], 0); } puts("Les étudiants ont fini"); pthread_mutex_destroy(&group_A); pthread_mutex_destroy(&group_B); pthread_mutex_destroy(&fifo); return 0; }
0
#include <pthread.h> int count; int reader_count; pthread_mutex_t write_mutex; pthread_mutex_t read_mutex; struct thread_data { int number; int iterations; int sleep; }; void* writer(void* threadarg) { struct thread_data* my_data; my_data = (struct thread_data*) threadarg; int loop; for (loop = 0; loop < my_data->iterations; loop++) { pthread_mutex_lock(&write_mutex); int my_count = count; my_count = my_count + 1; printf("Writer %d wants to update count\\n", my_data->number); sleep(my_data->sleep); count = my_count; printf("Writer %d update count to %d\\n", my_data->number, count); pthread_mutex_unlock(&write_mutex); sleep(my_data->sleep); } pthread_exit(0); } void* reader(void* threadarg) { struct thread_data* my_data; my_data = (struct thread_data*) threadarg; int loop; for (loop = 0; loop < my_data->iterations; loop++) { printf("Reader %d wants to read %d\\n", my_data->number, count); pthread_mutex_lock(&read_mutex); reader_count++; if (1 == reader_count) { pthread_mutex_lock(&write_mutex); } pthread_mutex_unlock(&read_mutex); sleep(my_data->sleep); printf("Reader %d reads count as %d\\n", my_data->number, count); pthread_mutex_lock(&read_mutex); reader_count--; if (0 == reader_count) { pthread_mutex_unlock(&write_mutex); } pthread_mutex_unlock(&read_mutex); sleep(my_data->sleep); } pthread_exit(0); } int main(int argc, char* argv[]) { printf("Start...\\n"); count = 0; reader_count = 0; struct thread_data write_data[2]; struct thread_data read_data[3]; pthread_t write_threads[2]; pthread_t read_threads[3]; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_mutex_init(&read_mutex, 0); pthread_mutex_init(&write_mutex, 0); int t; for (t = 0; t < 2; t++) { write_data[t].number = t; write_data[t].iterations = (t + 4); write_data[t].sleep = ((t % 2 == 0) ? 3 : 1); printf("Writer no. %d will loop for %d times, sleeping %dsec.\\n", write_data[t].number, write_data[t].iterations, write_data[t].sleep); pthread_create(&write_threads[t], &attr, writer, (void *) &write_data[t]); } for (t = 0; t < 3; t++) { read_data[t].number = t; read_data[t].iterations = (t + 4); read_data[t].sleep = ((t % 2 == 0) ? 1 : 2); printf("Reader no. %d will loop for %d times, sleeping %dsec.\\n", read_data[t].number, read_data[t].iterations, read_data[t].sleep); pthread_create(&read_threads[t], &attr, reader, (void *) &read_data[t]); } for (t = 0; t < 2; t++) { pthread_join(write_threads[t], 0); } for (t = 0; t < 3; t++) { pthread_join(read_threads[t], 0); } printf("All threads finished, global count is %d\\n", count); pthread_exit(0); }
1
#include <pthread.h> struct ozy_buffer* ozy_input_buffers_head; struct ozy_buffer* ozy_input_buffers_tail; sem_t ozy_input_buffer_sem; int ozy_input_sequence=0; int ozy_input_buffers=0; pthread_mutex_t ozy_input_buffer_mutex; struct ozy_buffer* ozy_free_buffers_head; struct ozy_buffer* ozy_free_buffers_tail; pthread_mutex_t ozy_free_buffer_mutex; void free_ozy_buffer(struct ozy_buffer* buffer); void put_ozy_free_buffer(struct ozy_buffer* buffer) { pthread_mutex_lock(&ozy_free_buffer_mutex); if(ozy_free_buffers_tail==0) { ozy_free_buffers_head=ozy_free_buffers_tail=buffer; } else { ozy_free_buffers_tail->next=buffer; ozy_free_buffers_tail=buffer; } pthread_mutex_unlock(&ozy_free_buffer_mutex); if(debug_buffers) fprintf(stderr,"put_ozy_free_buffer: %08X\\n",(unsigned int)buffer); } struct ozy_buffer* get_ozy_free_buffer(void) { struct ozy_buffer* buffer; if(ozy_free_buffers_head==0) { fprintf(stderr,"get_ozy_free_buffer: NULL\\n"); return 0; } pthread_mutex_lock(&ozy_free_buffer_mutex); buffer=ozy_free_buffers_head; ozy_free_buffers_head=buffer->next; if(ozy_free_buffers_head==0) { ozy_free_buffers_tail=0; } buffer->size=OZY_BUFFER_SIZE; pthread_mutex_unlock(&ozy_free_buffer_mutex); if(debug_buffers) fprintf(stderr,"get_ozy_free_buffer: %08X\\n",(unsigned int)buffer); return buffer; } void put_ozy_input_buffer(struct ozy_buffer* buffer) { pthread_mutex_lock(&ozy_input_buffer_mutex); buffer->sequence=ozy_input_sequence++; if(ozy_input_buffers_tail==0) { ozy_input_buffers_head=ozy_input_buffers_tail=buffer; } else { ozy_input_buffers_tail->next=buffer; ozy_input_buffers_tail=buffer; } pthread_mutex_unlock(&ozy_input_buffer_mutex); if(debug_buffers) fprintf(stderr,"put_ozy_input_buffer: %08X\\n",(unsigned int)buffer); } struct ozy_buffer* get_ozy_input_buffer(void) { struct ozy_buffer* buffer; if(ozy_input_buffers_head==0) { fprintf(stderr,"get_ozy_input_buffer: NULL\\n"); return 0; } pthread_mutex_lock(&ozy_input_buffer_mutex); buffer=ozy_input_buffers_head; ozy_input_buffers_head=buffer->next; if(ozy_input_buffers_head==0) { ozy_input_buffers_tail=0; } pthread_mutex_unlock(&ozy_input_buffer_mutex); if(debug_buffers) fprintf(stderr,"get_ozy_input_buffer: %08X\\n",(unsigned int)buffer); return buffer; } struct ozy_buffer* new_ozy_buffer() { struct ozy_buffer* buffer; buffer=malloc(sizeof(struct ozy_buffer)); buffer->next=0; buffer->size=OZY_BUFFER_SIZE; if(debug_buffers) fprintf(stderr,"new_ozy_buffer: %08X size=%d\\n",(unsigned int)buffer,buffer->size); return buffer; } void create_ozy_buffers(int n) { struct ozy_buffer* buffer; int i; pthread_mutex_init(&ozy_input_buffer_mutex, 0); pthread_mutex_init(&ozy_free_buffer_mutex, 0); for(i=0;i<n;i++) { buffer=new_ozy_buffer(); put_ozy_free_buffer(buffer); } } void free_ozy_buffer(struct ozy_buffer* buffer) { if(debug) fprintf(stderr,"free_ozy_buffer: %08X\\n",(unsigned int)buffer); put_ozy_free_buffer(buffer); }
0
#include <pthread.h> int mediafirefs_opendir(const char *path, struct fuse_file_info *file_info) { printf("FUNCTION: opendir. path: %s\\n", path); (void)path; (void)file_info; struct mediafirefs_context_private *ctx; ctx = fuse_get_context()->private_data; pthread_mutex_lock(&(ctx->mutex)); fprintf(stderr, "opendir is a no-op\\n"); pthread_mutex_unlock(&(ctx->mutex)); return 0; }
1
#include <pthread.h> int in = 0; int out = 0; int buff[10] = {0,0,0,0,0,0,0,0,0,0}; sem_t empty_sem; sem_t full_sem; pthread_mutex_t mutex; void print() { int i; for(i = 0; i < 10; i++) printf("%d ", buff[i]); printf("\\n"); } void *produce(void *num) { while(1) { sem_wait(&empty_sem); pthread_mutex_lock(&mutex); printf("\\n producer%d put a product in buffer[%d]. Now buffer is: ", *((int*)num), in); buff[in] = 1; print(); in = (in+1) % 10; pthread_mutex_unlock(&mutex); sem_post(&full_sem); sleep(1); } } void *consumer(void *num) { while(1) { sem_wait(&full_sem); pthread_mutex_lock(&mutex); printf("\\n consumer%d get a product from buffer[%d]. Now buffer is: ", *((int*)num), out); buff[out] = 0; print(); out=(out+1)%10; pthread_mutex_unlock(&mutex); sem_post(&empty_sem); sleep(1); } } int main() { pthread_t p; pthread_t c; int i,ini1,ini2,ini3; int ret; int threadProducerNumber[6]; int threadConsumerNumber[4]; for(i=0;i<6;i++) threadProducerNumber[i]=i; for(i=0;i<4;i++) threadConsumerNumber[i]=i; ini1 = sem_init(&empty_sem, 0, 10); ini2 = sem_init(&full_sem, 0, 0); if(ini1 && ini2 != 0) { printf("sem init failed \\n"); exit(1); } ini3 = pthread_mutex_init(&mutex, 0); if(ini3 != 0) { printf("mutex init failed \\n"); exit(1); } for(i=0;i<6;i++) { ret=pthread_create(&p, 0, produce, (void *) &threadProducerNumber[i]); if(ret != 0) { printf("product%d creation failed \\n", i); exit(1); } } for(i=0;i<4;i++) { ret= pthread_create(&c, 0, consumer, (void *) &threadConsumerNumber[i]); if(ret != 0) { printf("consumer%d creation failed \\n", i); exit(1); } } pthread_join(p,0); pthread_join(c,0); return 0; }
0
#include <pthread.h> int clk_t_1 = 0,clk_t_2 = 0,clk_t_3 = 0; int sender = 1; pthread_mutex_t var; void *increament1(void *interval) { int *interval1 = (int *)interval; while(1) { clk_t_1 += *interval1; printf("\\nclk1 : %d",clk_t_1); sleep(3); } } void *increament2(void *interval) { int *interval2 = (int *)interval; while(1) { clk_t_2 += *interval2; printf("\\nclk2 : %d",clk_t_2); sleep(3); } } void *increament3(void *interval) { int *interval3 = (int *)interval; while(1) { clk_t_3 += *interval3; printf("\\nclk3 %d",clk_t_3); sleep(3); } } void *clk1(void *interval) { int *interval1 = (int *)interval; pthread_t t; pthread_create(&t,0,&increament1,(void *)interval1); sleep(5); while(1) { sleep(1); pthread_mutex_lock(&var); printf("\\nrecived message to 1 at %d from %d",clk_t_1,sender); if(sender == 2) { if(clk_t_1<clk_t_2) { clk_t_1 = clk_t_2 + 1; printf("\\nupdated clock to %d",clk_t_1); } } else if(sender == 3) { if(clk_t_1<clk_t_3) clk_t_1 = clk_t_3 + 1; printf("\\nupdated clock to %d",clk_t_1); } sleep(1); printf("\\nmessage send from 1 at %d",clk_t_1); sender = 1; pthread_mutex_unlock(&var); } } void *clk2(void *interval) { int *interval2 = (int *)interval; pthread_t t; pthread_create(&t,0,&increament2,(void *)interval2); while(1) { sleep(1); pthread_mutex_lock(&var); printf("\\nrecived message to 2 at %d from %d",clk_t_2,sender); if(sender == 1) { if(clk_t_2<clk_t_1) { clk_t_2 = clk_t_1 + 1; printf("\\nupdated clock to %d",clk_t_2); } } else if(sender == 3) { if(clk_t_2<clk_t_3) clk_t_2 = clk_t_3 + 1; printf("\\nupdated clock to %d",clk_t_2); } sleep(1); printf("\\nmessage send from 2 at %d",clk_t_2); sender = 2; pthread_mutex_unlock(&var); } } void *clk3(void *interval) { int *interval3 = (int *)interval; pthread_t t; pthread_create(&t,0,&increament3,(void *)interval3); while(1) { sleep(1); pthread_mutex_lock(&var); printf("\\nrecived message to 3 at %d from %d",clk_t_3,sender); if(sender == 2) { if(clk_t_3<clk_t_2) { clk_t_3 = clk_t_2 + 1; printf("\\nupdated clock to %d",clk_t_3); } } else if(sender == 1) { if(clk_t_3<clk_t_1) clk_t_3 = clk_t_1 + 1; printf("\\nupdated clock to %d",clk_t_3); } sleep(1); printf("\\nmessage send from 3 at %d",clk_t_3); sender = 3; pthread_mutex_unlock(&var); } } void main() { pthread_t arr[3]; int interval1,interval2,interval3; interval1 = 3; interval2 = 5; interval3 = 7; pthread_create(&arr[0],0,&clk1,(void *)&interval1); pthread_create(&arr[1],0,&clk2,(void *)&interval2); pthread_create(&arr[2],0,&clk3,(void *)&interval3); pthread_join(arr[0],0); pthread_join(arr[1],0); pthread_join(arr[2],0); }
1
#include <pthread.h> pthread_mutex_t lock; pthread_cond_t not_empty, not_full; int cokes = 5; void* thread_function(void* function); void refill_coke(void); void consume_coke(void); int main(int argc, const char * argv[]) { int i; pthread_t producers[2]; pthread_t consumers[10]; pthread_mutex_init(&lock, 0); pthread_cond_init(&not_empty, 0); pthread_cond_init(&not_full, 0); for (i=0; i<10; i++) { if (pthread_create(&consumers[i], 0,thread_function,(void *) refill_coke )) { perror("Thread creation failed"); exit(1); } } for (i=0; i<2; i++) { if (pthread_create(&producers[i], 0, thread_function, (void *) consume_coke)) { perror("Thread creation failed"); exit(1); } } sleep(10); return 0; } void* thread_function(void* function) { int i; for (i=0; i<10; i++) { ((void (*)(void ))function)(); } pthread_exit(0); } void refill_coke(void) { pthread_mutex_lock(&lock); while(cokes < 10){ printf("--->>%d Refill 10 \\n", pthread_self()); cokes = 10; pthread_cond_signal(&not_empty); } while(cokes == 10 ){ pthread_cond_wait(&not_full, &lock); } pthread_mutex_unlock(&lock); } void consume_coke(void) { pthread_mutex_lock(&lock); while(cokes == 0){ pthread_cond_wait(&not_empty, &lock); } cokes--; pthread_cond_signal(&not_full); printf("<<---%d Take from %d\\n", pthread_self(), cokes); pthread_mutex_unlock(&lock); }
0
#include <pthread.h> int nitems; struct { pthread_mutex_t mutex; int buffer[1000000]; int nput; int nval; } shared = { PTHREAD_MUTEX_INITIALIZER }; struct { pthread_mutex_t mutex; pthread_cond_t cond; int nready; } ready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; void *producer(void *param) { for(;;) { pthread_mutex_lock(&shared.mutex); if (shared.nput >= nitems) { pthread_mutex_unlock(&shared.mutex); return 0; } shared.buffer[shared.nput] = shared.nval++; shared.nput++; pthread_mutex_unlock(&shared.mutex); pthread_mutex_lock(&ready.mutex); if (ready.nready == 0) pthread_cond_signal(&ready.cond); ready.nready++; pthread_mutex_unlock(&ready.mutex); *((int *) param) += 1; } return 0; } void *consumer(void *param) { int i; for (i=0; i<nitems; ++i) { pthread_mutex_lock(&ready.mutex); while (ready.nready == 0) pthread_cond_wait(&ready.cond, &ready.mutex); ready.nready--; pthread_mutex_unlock(&ready.mutex); if(shared.buffer[i] != i) { printf("buffer[%d] = %d\\n", i, shared.buffer[i]); } else { } } return 0; } int main(int argc, char* argv[]) { int i, nthreads = 5; nitems = 1000000; int total = 0, count[5]; pthread_t th[5]; pthread_attr_t thattr; pthread_attr_setdetachstate(&thattr, PTHREAD_CREATE_DETACHED); for(i=0; i<nthreads; ++i) { count[i] = 0; pthread_create(&th[i], 0, producer, &(count[i])); } pthread_t consume; pthread_create(&consume, 0, consumer, 0); pthread_join(consume, 0); printf("\\n"); for(i=0; i<nthreads; ++i) { pthread_join(th[i], 0); printf("thread[%d] produce %d\\n", i, count[i]); total += count[i]; } printf("Total: %d\\n", total); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t fill; int counter; int* buffer; int size; void* producer(void*); void* consumer(void*); void initialize_variables(); void insert(void); void remove_item(void); int main(int argc, char *argv[]) { int random_num; int num=0; pthread_t barber; srand( time(0) ); if(argc!=2){ printf("Not enough parameters\\n"); exit(0); } size=atoi(argv[1]); initialize_variables(); pthread_create(&barber,0,consumer,0); while(1){ pthread_t customer; pthread_create(&customer,0,producer,0); } printf("Exit the program\\n"); return 0; } void initialize_variables(){ int i; if(! (buffer=(int*)malloc(size*sizeof(int))) ){ printf("Error while allocating memory for buffer\\n"); exit(1); } for(i=0; i<size; i++) buffer[i]=0; pthread_mutex_init(&mutex,0); pthread_cond_init(empty, 0); pthread_cond_init(&fill, 0); counter = 0; } void* producer(void* arg){ pthread_mutex_lock(&mutex); while(counter==size) pthread_cond_wait(&empty,&mutex); insert(); sleep(1); pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); pthread_exit(0); } void* consumer(void* arg){ while(1){ pthread_mutex_lock(&mutex); while(counter==0){ printf("Barber is sleeping now\\n"); pthread_cond_wait(&fill,&mutex); } remove_item(); sleep(1); pthread_cond_broadcast(&empty); pthread_mutex_unlock(&mutex); } } void insert(void){ buffer[counter]=1; counter++; } void remove_item(void){ buffer[counter]=0; counter--; }
0
#include <pthread.h> struct kt_for_t; struct kt_for_t *t; long i; } ktf_worker_t; int n_threads; long n; ktf_worker_t *w; void (*func)(void*,long,int); void *data; } kt_for_t; static inline long steal_work(kt_for_t *t) { int i, min_i = -1; long k, min = LONG_MAX; for (i = 0; i < t->n_threads; ++i) if (min > t->w[i].i) min = t->w[i].i, min_i = i; k = __sync_fetch_and_add(&t->w[min_i].i, t->n_threads); return k >= t->n? -1 : k; } static void *ktf_worker(void *data) { ktf_worker_t *w = (ktf_worker_t*)data; long i; for (;;) { i = __sync_fetch_and_add(&w->i, w->t->n_threads); if (i >= w->t->n) break; w->t->func(w->t->data, i, w - w->t->w); } while ((i = steal_work(w->t)) >= 0) w->t->func(w->t->data, i, w - w->t->w); pthread_exit(0); } void kt_for(int n_threads, void (*func)(void*,long,int), void *data, long n) { int i; kt_for_t t; pthread_t *tid; t.func = func, t.data = data, t.n_threads = n_threads, t.n = n; t.w = (ktf_worker_t*)alloca(n_threads * sizeof(ktf_worker_t)); tid = (pthread_t*)alloca(n_threads * sizeof(pthread_t)); for (i = 0; i < n_threads; ++i) t.w[i].t = &t, t.w[i].i = i; for (i = 0; i < n_threads; ++i) pthread_create(&tid[i], 0, ktf_worker, &t.w[i]); for (i = 0; i < n_threads; ++i) pthread_join(tid[i], 0); } struct ktp_t; struct ktp_t *pl; int step, running; void *data; } ktp_worker_t; void *shared; void *(*func)(void*, int, void*); int n_workers, n_steps; ktp_worker_t *workers; pthread_mutex_t mutex; pthread_cond_t cv; } ktp_t; static void *ktp_worker(void *data) { ktp_worker_t *w = (ktp_worker_t*)data; ktp_t *p = w->pl; while (w->step < p->n_steps) { pthread_mutex_lock(&p->mutex); for (;;) { int i; for (i = 0; i < p->n_workers; ++i) { if (w == &p->workers[i]) continue; if (p->workers[i].running && p->workers[i].step == w->step) break; } if (i == p->n_workers) break; pthread_cond_wait(&p->cv, &p->mutex); } w->running = 1; pthread_mutex_unlock(&p->mutex); w->data = p->func(p->shared, w->step, w->step? w->data : 0); pthread_mutex_lock(&p->mutex); w->step = w->step == p->n_steps - 1 || w->data? (w->step + 1) % p->n_steps : p->n_steps; w->running = 0; pthread_cond_broadcast(&p->cv); pthread_mutex_unlock(&p->mutex); } pthread_exit(0); } void kt_pipeline(int n_threads, void *(*func)(void*, int, void*), void *shared_data, int n_steps) { ktp_t aux; pthread_t *tid; int i; if (n_threads < 1) n_threads = 1; aux.n_workers = n_threads; aux.n_steps = n_steps; aux.func = func; aux.shared = shared_data; pthread_mutex_init(&aux.mutex, 0); pthread_cond_init(&aux.cv, 0); aux.workers = alloca(n_threads * sizeof(ktp_worker_t)); for (i = 0; i < n_threads; ++i) { ktp_worker_t *w = &aux.workers[i]; w->step = w->running = 0; w->pl = &aux; w->data = 0; } tid = alloca(n_threads * sizeof(pthread_t)); for (i = 0; i < n_threads; ++i) pthread_create(&tid[i], 0, ktp_worker, &aux.workers[i]); for (i = 0; i < n_threads; ++i) pthread_join(tid[i], 0); pthread_mutex_destroy(&aux.mutex); pthread_cond_destroy(&aux.cv); }
1
#include <pthread.h> int how_much_are_ready; char tipo_de_velocidade; int d, n; int **pista_de_corrida; pthread_mutex_t start=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t launch_condition; pthread_mutex_t *coordenador_de_acesso_a_estrada; int plano; int subida; int descida; } vel; void help(char *name){ printf("USO: %s <nome do arquivo de entrada>\\n", name); } void determina_velocidade(vel *velocidades){ if(tipo_de_velocidade == 'U'){ velocidades->plano = 50; velocidades->subida = 50; velocidades->descida = 50; } else{ velocidades->plano = rand()%20+30; velocidades->subida = rand()%20; velocidades->descida = rand()%30+50; } } int tem_pista_livre(int posicao, int faixa_atual){ int faixa; if(pista_de_corrida[posicao][faixa_atual] == -1) return faixa_atual; for (faixa = 1; faixa <= n; ++faixa) { if(pista_de_corrida[posicao][faixa]==-1) return faixa; } return 0; } int escreve_posicao_na_pista(int tid,int posicao,int faixa){ pthread_mutex_lock(&coordenador_de_acesso_a_estrada[posicao]); if((faixa = tem_pista_livre(posicao, faixa)) != 0){ pista_de_corrida[posicao][faixa] = tid; printf("thread: %d , posicao %d faixa %d\\n", tid, posicao, faixa); fflush(stdout); } pthread_mutex_unlock(&coordenador_de_acesso_a_estrada[posicao]); return faixa; } int retira_ciclista_da_posicao_se_ja_passou(int tid,int posicao,int faixa){ if(faixa != 0){ pthread_mutex_lock(&coordenador_de_acesso_a_estrada[posicao]); pista_de_corrida[posicao][faixa] = -1; pthread_mutex_unlock(&coordenador_de_acesso_a_estrada[posicao++]); } return posicao; } void verifica_velocidade_atual(vel velocidades,int posicao){ if(pista_de_corrida[posicao][0]==(int)'D'){ usleep(10000 - velocidades.descida*100); printf("descida\\n"); } if(pista_de_corrida[posicao][0]==(int)'P'){ usleep(10000 - velocidades.plano*100); printf("plano\\n"); } if(pista_de_corrida[posicao][0]==(int)'S'){ usleep(10000 - velocidades.subida*100); printf("subida\\n"); } } void comecou_corrida(int tid,vel velocidades){ int posicao; int faixa; faixa = 1; for (posicao = 0; posicao < d;) { faixa = escreve_posicao_na_pista(tid,posicao,faixa); verifica_velocidade_atual(velocidades,posicao); posicao = retira_ciclista_da_posicao_se_ja_passou(tid,posicao,faixa); } } void preparando_largada_do_ciclista(int tid){ pthread_mutex_lock(&start); how_much_are_ready ++; printf("\\nciclista %d na linha de largada\\n", tid); if(how_much_are_ready == 50){ printf("\\e[01;31musleep(10000 - velocidades.plano*100);PEDALA FIADAPORRA !\\e[00m\\n"); pthread_cond_broadcast(&launch_condition); } else pthread_cond_wait(&launch_condition, &start); pthread_mutex_unlock(&start); printf("ciclista %d pedalando feito doido\\n", tid); } void *tour_de_la_france(void *arg){ int tid; vel velocidades; tid = *((int *)arg); determina_velocidade(&velocidades); printf("%d %d %d",velocidades.descida,velocidades.plano,velocidades.subida); preparando_largada_do_ciclista(tid); comecou_corrida(tid,velocidades); printf("chegueiiiiii %d\\n",tid); return 0; } void criando_a_pista(){ int i,j; if((pista_de_corrida = malloc(d * sizeof(int*)))!=0){ for(i=0 ; i<d ; i++){ pista_de_corrida[i]=malloc((n+1) * sizeof(int)); } } else { printf("A pista esta sob obras! Corrida adiada para proxima tentativa de alocacao."); exit(1); } for (i = 0; i < d; i++) { for (j = 1; j <= n; j++) { pista_de_corrida[i][j] = -1; } } } void criando_coordenador_das_posicoes(){ int i; coordenador_de_acesso_a_estrada = (pthread_mutex_t *)malloc(d * sizeof (pthread_mutex_t)); if(coordenador_de_acesso_a_estrada != 0){ for (i = 0; i < d; i++) { if(pthread_mutex_init(coordenador_de_acesso_a_estrada + i, 0)){ perror("Erro no vetor de mutex"); exit(1); } } } else{ perror("Erro de allocacao"); exit(1); } } int main(int argc, char **argv){ FILE *in; pthread_t *threads; int *thread_args, k; int i,j, m,inicio; char tipo_de_relevo; int trecho_a_percorrer; if(argc != 2){ help(argv[0]); exit(1); } in = fopen(argv[1], "r"); if(in == 0){ printf("Erro ao abrir o arquivo \\"%s\\"\\n", argv[1]); exit(1); } fscanf(in, "%d %d %c %d", &m, &n, &tipo_de_velocidade, &d); printf("ciclistas = %d\\npistas = %d\\ntipo = %c\\ndistancia = %d\\n\\n", m, n, tipo_de_velocidade, d); criando_a_pista(); criando_coordenador_das_posicoes(); how_much_are_ready = 0; threads = (pthread_t *)malloc(m * sizeof(pthread_t)); thread_args = (int *)malloc(m * sizeof(int)); inicio=0; while(1){ k = fscanf(in,"\\n%c",&tipo_de_relevo); k = fscanf(in,"\\n%d",&trecho_a_percorrer); if(k!=1)break; printf("\\ntipo_de_relevo: %c\\ntrecho_a_percorrer: %d\\n\\n",tipo_de_relevo,trecho_a_percorrer); for (i=0; i < trecho_a_percorrer; ++i) pista_de_corrida[i+inicio][0]=(int)tipo_de_relevo; printf("\\n\\n"); inicio += trecho_a_percorrer; } srand(time(0)); for(i = 0; i < m; i++){ thread_args[i] = i; if(pthread_create(&threads[i], 0, tour_de_la_france, &thread_args[i])){ perror("ciclista nao veio"); exit(1); } printf("ciclista %d pronto !\\n", i); } printf("[%d]\\n", how_much_are_ready); for(i = 0; i < m; i++){ if(pthread_join(threads[i], 0)) perror("ciclista morreu no caminho"); } fclose(in); return 0; }
0
#include <pthread.h> { pthread_mutex_t mut; pthread_cond_t inserimento[2][2][3]; int coda[2][2][3]; int temperatura; int n_piastrelle[2]; }monitor; monitor m; { int id; int t; int qta; int tipo; int temperatura; }lot; lot new_lot(int id) { lot s; s.id = id; s.t= rand()%10; s.qta = rand()%3; s.temperatura = rand()%2; return s; } void print_status() { printf("\\t\\t----- status ------\\n"); printf("\\t\\tm.temperatura: %d\\n",m.temperatura); for (int i = 0; i < 2; ++i) { printf("\\t\\tm.n_piastrelle[%d]:%d\\n",i,m.n_piastrelle[i]); for (int j = 0; j < 2; ++j) { for (int k = 0; k < 3; ++k) { printf("\\t\\tm.coda[%d][%d][%d]: %d\\n",i,j,k,m.coda[i][j][k]); } } } printf("\\t\\t------------------\\n"); } void init() { pthread_mutex_init(&m.mut,0); for (int i = 0; i < 2; ++i) { m.n_piastrelle[i]=0; for (int j = 0; j < 2; ++j) { for (int k = 0; k < 3; ++k) { pthread_cond_init(&m.inserimento[i][j][k],0); m.coda[i][j][k]=0; } } } m.temperatura=0; print_status(); } void signal() { } void in(lot l) { pthread_mutex_lock(&m.mut); while((m.temperatura!=l.temperatura && m.n_piastrelle[m.temperatura]>0) || 5 - m.n_piastrelle[m.temperatura] < l.qta ) { m.coda[l.temperatura][l.tipo][l.qta]++; print_status(); pthread_cond_wait(&m.inserimento[1][1][l.qta],&m.mut); m.coda[l.temperatura][l.tipo][l.qta]--; } printf("lotto [%d] %d %d qta:%d entra \\n",l.id,l.temperatura,l.tipo,l.qta); m.temperatura=l.temperatura; m.n_piastrelle[l.temperatura]+=l.qta; print_status(); pthread_mutex_unlock(&m.mut); } void out(lot l) { pthread_mutex_lock(&m.mut); printf("lotto [%d] %d %d esce\\n",l.id,l.temperatura,l.tipo); m.n_piastrelle[l.temperatura]-=l.qta; print_status(); pthread_mutex_unlock(&m.mut); } void* lotto(void* arg) { int id = (int)arg; printf("lotto [%d] creato\\n",id); lot l; l = new_lot(id); in(l); sleep(l.t); out(l); pthread_exit(0); } int main(int argc, char *argv[]) { init(); pthread_t lotti[5]; for (int i = 0; i < 5; ++i) { if(pthread_create(&lotti[i],0,lotto,(void *)i)<0) { fprintf(stderr, "errore creazione thread lotto [%d]\\n",i); exit(1); } } for (int i = 0; i < 5; ++i) { if(pthread_join(lotti[i],0)){ fprintf(stderr, "errore terminazione thread lotto [%d]\\n",i); exit(1); } else { printf("thread lotto [%d] termiato con successo\\n", i); } } return 0; }
1
#include <pthread.h> static pthread_mutex_t list_mutex; { int len; int seqid; struct _data_t* next; void* data; }data_t; { data_t* first; data_t* tail; int count; int seqid; }list_t; list_t list_cb; void list_tool_init(void) { pthread_mutex_init(&list_mutex, 0); list_cb.first = 0; list_cb.tail = 0; list_cb.count = 0; memset((void *)&list_cb, 0, sizeof(list_cb)); } void list_tool_data_push(void* data, int len) { data_t* listData = (data_t*)malloc(sizeof(data_t)); memset((void*)listData, 0x00, sizeof(data_t)); if(data == 0) { return; } if(listData == 0) { {printf("[list]:""malloc Fail\\n");};; return; } listData->data = data; listData->len = len; pthread_mutex_lock(&list_mutex); {printf("[list]:""the Count is %d\\n", list_cb.count);};; if(list_cb.tail == 0) { list_cb.tail = listData; list_cb.first = listData; {printf("[list]:""set the first\\n");};; } else { list_cb.tail->next = listData; list_cb.tail = listData; } list_cb.count++; list_cb.seqid ++; listData->seqid = list_cb.seqid; pthread_mutex_unlock(&list_mutex); } void* list_tool_data_get(int* len) { static int count; void* data; data_t* curent; if(len == 0) { {printf("[list]:""The len is NULL\\n");};; return 0; } if(list_cb.first != 0) { {printf("[list]:"" first id %d\\n", list_cb.first->seqid);};; *len = list_cb.first->len; data = list_cb.first->data; curent = list_cb.first; pthread_mutex_lock(&list_mutex); list_cb.count--; if(list_cb.first->next == 0) { if(list_cb.count != 0) { {printf("[list]:""count is not 0\\n");};; } list_cb.first = 0; list_cb.tail = 0; {printf("[list]:""list_cb.first is NULL\\n");};; } else { if((list_cb.first->seqid + 1) != list_cb.first->next->seqid) { {printf("[list]:""--------->error\\n");};; } list_cb.first = list_cb.first->next; } pthread_mutex_unlock(&list_mutex); free(curent); if(data == 0) { {printf("[list]:""data == NULL");};; } return data; } else { *len = 0; return 0; } }
0
#include <pthread.h> void *allocate_medium(size_t size) { void *block; pthread_mutex_lock(&g_global_lock); if (g_book_keeper.medium.head == 0) { g_book_keeper.medium.head = allocate_new_zone(MEDIUM_MAX); divide_zone((void*)&(g_book_keeper.medium.head), (void*)&(g_book_keeper.medium.tail), MEDIUM_MAX); } block = allocate_new_block(size, &(g_book_keeper.medium)); pthread_mutex_unlock(&g_global_lock); return (block); }
1
#include <pthread.h> static int data = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_m = PTHREAD_COND_INITIALIZER; static pthread_cond_t cond_j = PTHREAD_COND_INITIALIZER; static int is_prime(int data) { int i; for (i = 2; i < data / 2; i++) { if (data % i == 0) { return 0; } } return 1; } void *jobs(void *unuse) { int mydata; while (1) { pthread_mutex_lock(&mutex); while (data == 0) { pthread_cond_wait(&cond_j, &mutex); } if (data == -1) { pthread_mutex_unlock(&mutex); break; } mydata = data; data = 0; pthread_cond_signal(&cond_m); pthread_mutex_unlock(&mutex); if (is_prime(mydata)) { printf("%d ", mydata); fflush(0); } } return 0; } int main(void) { int i; pthread_t tid[6]; for (i = 0; i < 6; i++) { pthread_create(tid + i, 0, jobs, 0); } for (i = 10; i <= 50; i++) { pthread_mutex_lock(&mutex); while (data != 0) { pthread_cond_wait(&cond_m, &mutex); } data = i; pthread_cond_signal(&cond_j); pthread_mutex_unlock(&mutex); } pthread_mutex_lock(&mutex); while (data != 0) { pthread_cond_wait(&cond_m, &mutex); } data = -1; pthread_mutex_unlock(&mutex); pthread_cond_broadcast(&cond_j); for (i = 0; i < 6; i++) { pthread_join(tid[i], 0); } printf("\\n"); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_j); pthread_cond_destroy(&cond_m); return 0; }
0
#include <pthread.h> int ca = 0; int ce = 0; int ci = 0; int co = 0; int cu = 0; int c; FILE * fp; pthread_t h[3]; pthread_mutex_t candl; pthread_mutex_t cande; int cuentaLineas(); void contador(void * ptr); int main(int argc, char **argv){ int i; int lin = 0; char *nomarch; char buffer[200]; nomarch = argv[1]; fp = fopen(nomarch, "r"); pthread_t h[3]; if(fp == 0){ printf("no se pudo abrir el archivo %s\\n", nomarch); exit(1); } lin = cuentaLineas(); printf(" <lin>: %d\\n", lin); fflush(fp); pthread_mutex_init(&cande, 0); for(i = 0; i < 3; i++){ pthread_create(&h[i], 0, (void *) contador, &i); } for(i = 0; i < 3; i++){ pthread_join(h[i], 0); } printf("-- fin\\n"); fclose(fp); printf("totales: ca: %d, ce %d, ci %d, co %d, cu %d\\n", ca, ce, ci, co, cu); return 0; } void contador(void * ptr){ int id = (int) ptr; int aes = 0; int ees = 0; int ies = 0; int oes = 0; int ues = 0; c = fgetc(fp); while(!feof(fp) || c != '\\n'){ if(c == 'a' || c == 'A') aes++; else if(c == 'e' || c == 'e') ees++; else if(c == 'i' || c == 'I') ies++; else if(c == 'o' || c == 'O') oes++; else if(c == 'u' || c == 'U') ues++; else{ } c = fgetc(fp); } pthread_mutex_lock(&cande); ca = ca + aes; ce = ce + ees; ci = ci + ies; co = co + oes; cu = cu + ues; pthread_mutex_unlock(&cande); printf("Hilo: %d: ca: %2d, ce %2d, ci %2d, co %2d, cu %2d\\n", id, ca, ce, ci, co, cu); pthread_exit(&h[id]); }
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(producer_thread, 0); if (0 != result) { fprintf(stderr, "Failed to join producer thread: %s\\n", strerror(result)); pthread_exit(0); } 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(); } --g_num_prod; 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_unlock(&g_num_prod_lock); pthread_mutex_unlock(&queue_p->lock); return (void*) count; }
0
#include <pthread.h> pthread_mutex_t mutex; int putters; int getters; int putwaiters; int getwaiters; pthread_cond_t putable; pthread_cond_t getable; } Lock; static Lock lock; extern void rwl_report() { if (lock.putters+lock.getters+lock.putwaiters>1) LOG("report(): putters=%d getters=%d putwaiters=%d", lock.putters,lock.getters,lock.putwaiters); } extern void rwl_init() { pthread_mutex_init(&lock.mutex,0); pthread_cond_init(&lock.putable,0); pthread_cond_init(&lock.getable,0); lock.getters=0; lock.putters=0; lock.putwaiters=0; lock.getwaiters=0; } extern void rwl_get_lock() { pthread_mutex_lock(&lock.mutex); lock.getwaiters++; if (lock.putters || lock.putwaiters) do pthread_cond_wait(&lock.getable,&lock.mutex); while (lock.putters); lock.getwaiters--; lock.getters++; pthread_mutex_unlock(&lock.mutex); } extern void rwl_put_lock() { pthread_mutex_lock(&lock.mutex); lock.putwaiters++; while (lock.getters || lock.putters) pthread_cond_wait(&lock.putable,&lock.mutex); lock.putwaiters--; lock.putters++; pthread_mutex_unlock(&lock.mutex); } extern void rwl_get_unlock() { pthread_mutex_lock(&lock.mutex); lock.getters--; pthread_cond_signal(&lock.putable); pthread_mutex_unlock(&lock.mutex); } extern void rwl_put_unlock() { pthread_mutex_lock(&lock.mutex); lock.putters--; if (lock.putwaiters && lock.getwaiters<=opt_queue()) pthread_cond_signal(&lock.putable); else pthread_cond_broadcast(&lock.getable); pthread_mutex_unlock(&lock.mutex); }
1
#include <pthread.h> inline void room_set_id(struct room_t *target, unsigned id) { target->rm_id = id; } inline size_t room_mem_count(struct room_t *target) { return target->rm_mem_count; } static size_t check_if_member(struct room_t *target, struct client_t *victim) { size_t i = 0; while (i < target->rm_mem_count) { if ((*(target->rm_members + i))->cl_id == victim->cl_id) return i; ++i; } return 0; } void insert_where(struct room_t *target, struct client_t *victim) { target->rm_members[target->rm_mem_count++] = victim; } char room_add_member(struct room_t *target, struct client_t *victim) { if (target->rm_mem_count >= ROOM_MAX_MEMBERS) return 1; if (target->rm_members == 0) { target->rm_size = 4; target->rm_members = (struct client_t **) malloc( target->rm_size * sizeof(struct client_t *)); } else if (target->rm_size == target->rm_mem_count) { target->rm_size *= 2; target->rm_members = (struct client_t **) realloc( target->rm_members, target->rm_size); } if (!check_if_member(target, victim)) { insert_where(target, victim); fprintf(stderr, "Success!\\n"); return 0; } return 1; } static void room_remove_sth(struct room_t *target, size_t s) { target->rm_members[s]->cl_room = 0; --target->rm_mem_count; while (s < target->rm_mem_count) { target->rm_members[s] = target->rm_members[s + 1]; ++s; } } char room_remove_member(struct room_t *target, struct client_t *victim) { size_t s; if ((s = check_if_member(target, victim))) return 1; pthread_mutex_lock(&target->rm_locked); room_remove_sth(target, s); pthread_mutex_unlock(&target->rm_locked); return 0; } inline size_t room_free_space(struct room_t *target) { return ROOM_MAX_MEMBERS - target->rm_mem_count; } struct room_t *room_init(void) { struct room_t *ret; ret = (struct room_t *) malloc(1 * sizeof(struct room_t)); ret->rm_id = 0; ret->rm_size = 4; ret->rm_members = 0; ret->rm_highsocket = 0; FD_ZERO(&ret->rm_sockset); ret->rm_members = (struct client_t **) malloc(4 * sizeof(struct client_t *)); pthread_mutex_init(&ret->rm_locked, 0); return ret; } void room_destroy(struct room_t *target) { size_t i = 0; if (target == 0) return; while (i < target->rm_mem_count) client_destroy(target->rm_members[i++]); free(target->rm_members); pthread_mutex_destroy(&target->rm_locked); } char room_send(struct room_t *target, char *buff, size_t sz, struct client_t *sender) { size_t i = 0; char ret; pthread_mutex_lock(&target->rm_locked); while (i < target->rm_mem_count) { if (target->rm_members[i] == sender) { ++i; continue; } ret = (client_buff_push(target->rm_members[i++], buff, sz) > 0 ? 1 : 0); ++i; } pthread_mutex_unlock(&target->rm_locked); return ret; } static void room_build_select_list(struct room_t *target) { unsigned i = 0; FD_ZERO(&target->rm_sockset); while (i < target->rm_mem_count) { if (target->rm_members[i]->cl_sock != 0) { FD_SET(target->rm_members[i]->cl_sock, &target->rm_sockset); if (target->rm_members[i]->cl_sock > target->rm_highsocket) target->rm_highsocket = target->rm_members[i]->cl_sock; } ++i; } } static void room_handle_data(struct room_t *target) { size_t i = 0; int sz; char buff[CLIENT_BUFFER_SIZE]; while (i < target->rm_mem_count) { if (FD_ISSET(target->rm_members[i]->cl_sock, &target->rm_sockset)) { if ((sz = client_pull(target->rm_members[i], buff, PULL_SZ)) < 0) { client_dc(target->rm_members[i]); perror("recv"); continue; } else { room_send(target, buff, sz, target->rm_members[i]); } } ++i; } } static void *room_main_loop(void *tar_dummy) { struct room_t *target = (struct room_t *) tar_dummy; struct timeval timeout; int readsocks = 0; fprintf(stderr, "Room thread spawned\\n"); do { timeout.tv_sec = 1; timeout.tv_usec = 0; room_build_select_list(target); fprintf(stderr, "Room %u is idle\\n", target->rm_id); readsocks = select(target->rm_highsocket + 1, &target->rm_sockset, 0, 0, &timeout); if (readsocks < 0) { perror("select"); return 0; } else if (readsocks == 0) { } else { room_handle_data(target); } } while (1); fprintf(stderr, "Ret??\\n"); return tar_dummy; } inline void room_spawn_thread(struct room_t *target) { pthread_create(&target->rm_thread, 0, room_main_loop, (void *) target); }
0
#include <pthread.h> pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *threadCount1(); void *threadCount2(); int count = 0; int main(int argc, char *argv[]) { pthread_t thread1, thread2; int i; pthread_create( &thread1, 0, &threadCount1, 0); pthread_create( &thread2, 0, &threadCount2, 0); printf("%s getpid = %u pthread_self = %u\\n", __FUNCTION__, (unsigned int)getpid(), (unsigned int)pthread_self()); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Final count: %d\\n",count); exit(0); } void *threadCount1() { printf("%s getpid = %u pthread_self = %u\\n", __FUNCTION__, (unsigned int)getpid(), (unsigned int)pthread_self()); for(;;) { pthread_mutex_lock( &count_mutex ); pthread_cond_wait( &condition_var, &count_mutex ); count++; printf("Counter value threadCount1: %d\\n",count); pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } } void *threadCount2() { printf("%s getpid = %u pthread_self = %u\\n", __FUNCTION__, (unsigned int)getpid(), (unsigned int)pthread_self()); for(;;) { pthread_mutex_lock( &count_mutex ); if( count < 3 || count > 6 ) { pthread_cond_signal( &condition_var ); } else { count++; printf("Counter value threadCount2: %d\\n",count); } pthread_mutex_unlock( &count_mutex ); if(count >= 10) return(0); } }
1
#include <pthread.h> static int counter = 0; static pthread_mutex_t counter_mutex; static void *thread_foo(void *args) { int i = 0; for(i = 0; i < 5; i++) { pthread_mutex_lock(&counter_mutex); { counter = counter + 1; printf("foo: counter is %d\\n", counter); fflush(0); } pthread_mutex_unlock(&counter_mutex); } pthread_exit(0); } static void *thread_bar(void *args) { int i = 0; for(i = 0; i < 5; i++) { pthread_mutex_lock(&counter_mutex); { counter = counter + 1; printf("bar: counter is %d\\n", counter); fflush(0); } pthread_mutex_unlock(&counter_mutex); } pthread_exit(0); } static int init_errorcheck_mutex(pthread_mutex_t *mutex) { pthread_mutexattr_t attr; if(pthread_mutexattr_init(&attr)) { printf("init mutex attr failed.\\n"); return -1; } if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)) { printf("set attr type errorcheck failed.\\n"); return -1; } if(pthread_mutex_init(mutex, &attr)) { printf("init errorcheck mutex failed.\\n"); return -1; } if(pthread_mutexattr_destroy(&attr)) { printf("destory mutex attr failed.\\n"); return -1; } return 0; } static int init_recursive_mutex(pthread_mutex_t *mutex) { pthread_mutexattr_t attr; if(pthread_mutexattr_init(&attr)) { printf("init mutex attr failed.\\n"); return -1; } if(pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) { printf("set attr type recursive failed.\\n"); return -1; } if(pthread_mutex_init(mutex, &attr)) { printf("init recursive mutex failed.\\n"); return -1; } if(pthread_mutexattr_destroy(&attr)) { printf("destory mutex attr failed.\\n"); return -1; } return 0; } static void test_false_lock() { int ret = 0; if (0 != (ret = pthread_mutex_trylock(&counter_mutex))) { printf("(1)trylock failed....%s\\n", strerror(ret)); } if (0 != (ret = pthread_mutex_trylock(&counter_mutex))) { printf("(2)trylock failed....%s\\n", strerror(ret)); } if (0 != (ret = pthread_mutex_lock(&counter_mutex))) { printf("(3)lock failed....%s\\n", strerror(ret)); } } int main() { pthread_t tid_foo; pthread_t tid_bar; if (0 != init_errorcheck_mutex(&counter_mutex)) { printf("init mutex failed...\\n"); return -1; } if (0 != pthread_create(&tid_foo, 0, thread_foo, 0)) { printf("create thread foo failed...\\n"); return -1; } if (0 != pthread_create(&tid_bar, 0, thread_bar, 0)) { printf("create thread bar failed...\\n"); return -1; } if (0 != pthread_join(tid_foo, 0)) { printf("join thread foo failed...\\n"); return -1; } if (0 != pthread_join(tid_bar, 0)) { printf("join thread bar failed...\\n"); return -1; } test_false_lock(); if (0 != pthread_mutex_destroy(&counter_mutex)) { printf("destory mutex failed...\\n"); return -1; } return 0; }
0
#include <pthread.h> void * threadPartialSum(void * args); double globalSum; int numberOfThreads; long length; float * myArray; pthread_mutex_t updateSumLock; int main(int argc, char* argv[]) { long i; pthread_t * threadHandles; int errorCode; double seqSum; long startTime, endTime, seqTime, parallelTime; if (argc != 3) { return(0); }; sscanf(argv[1],"%d",&length); sscanf(argv[2],"%d",&numberOfThreads); threadHandles = (pthread_t *) malloc(numberOfThreads*sizeof(pthread_t)); myArray=(float *) malloc(length*sizeof(float)); srand(5); for (i=0; i < length; i++) { myArray[i] = rand() / (float) 32767; } time(&startTime); seqSum = 0.0; for (i=0; i < length; i++) { seqSum += myArray[i]; } time(&endTime); seqTime = endTime - startTime; time(&startTime); pthread_mutex_init(&updateSumLock, 0); globalSum = 0.0; for (i=0; i < numberOfThreads; i++) { if (errorCode = pthread_create(&threadHandles[i], 0, threadPartialSum, (void *) i) != 0) { printf("pthread %d failed to be created with error code %d\\n", i, errorCode); } } for (i=0; i < numberOfThreads; i++) { if (errorCode = pthread_join(threadHandles[i], (void **) 0) != 0) { printf("pthread %d failed to be joined with error code %d\\n", i, errorCode); } } time(&endTime); parallelTime = endTime - startTime; printf( "Time to sum %ld floats using %d threads %ld seconds (seq. %ld seconds)\\n", length, numberOfThreads, parallelTime, seqTime); printf("Thread's Sum is %lf and seq. sum %lf\\n\\n",globalSum, seqSum); free(myArray); return 0; } void * threadPartialSum(void * rank) { long myRank = (long) rank; long i, blockSize; long firstIndex, lastIndex; double localSum; blockSize = length / numberOfThreads; firstIndex = blockSize * myRank; if (myRank == numberOfThreads-1) { lastIndex = length-1; } else { lastIndex = blockSize * (myRank+1) - 1; } localSum = 0.0; for (i=firstIndex; i <= lastIndex; i++) { localSum += myArray[i]; } pthread_mutex_lock(&updateSumLock); globalSum += localSum; pthread_mutex_unlock(&updateSumLock); return 0; }
1
#include <pthread.h> struct _matrix { unsigned int size; unsigned int elements[6][6]; }; static void matrix_print(struct _matrix *m) { int i, j; printf(" \\r\\n Master : Linux : Printing results \\r\\n"); for (i = 0; i < m->size; ++i) { for (j = 0; j < m->size; ++j) printf(" %d ", (unsigned int)m->elements[i][j]); printf("\\r\\n"); } } static void generate_matrices(int num_matrices, unsigned int matrix_size, void *p_data) { int i, j, k; struct _matrix *p_matrix = p_data; time_t t; unsigned long value; srand((unsigned) time(&t)); for (i = 0; i < num_matrices; i++) { p_matrix[i].size = matrix_size; printf(" \\r\\n Master : Linux : Input matrix %d \\r\\n", i); for (j = 0; j < matrix_size; j++) { printf("\\r\\n"); for (k = 0; k < matrix_size; k++) { value = (rand() & 0x7F); value = value % 10; p_matrix[i].elements[j][k] = value; printf(" %d ", (unsigned int)p_matrix[i].elements[j][k]); } } printf("\\r\\n"); } } static pthread_t ui_thread, compute_thread; static pthread_mutex_t sync_lock; static int fd, compute_flag; static int ntimes = 1; static struct _matrix i_matrix[2]; static struct _matrix r_matrix; void *ui_thread_entry(void *ptr) { int cmd, ret, i; for (i=0; i < ntimes; i++){ printf("\\r\\n **********************************"); printf("****\\r\\n"); printf("\\r\\n Matrix multiplication demo Round %d \\r\\n", i); printf("\\r\\n **********************************"); printf("****\\r\\n"); compute_flag = 1; pthread_mutex_unlock(&sync_lock); printf("\\r\\n Compute thread unblocked .. \\r\\n"); printf(" The compute thread is now blocking on"); printf("a read() from rpmsg device \\r\\n"); printf("\\r\\n Generating random matrices now ... \\r\\n"); generate_matrices(2, 6, i_matrix); printf("\\r\\n Writing generated matrices to rpmsg "); printf("rpmsg device, %d bytes .. \\r\\n", sizeof(i_matrix)); write(fd, i_matrix, sizeof(i_matrix)); sleep(1); printf("\\r\\nEnd of Matrix multiplication demo Round %d \\r\\n", i); } compute_flag = 0; pthread_mutex_unlock(&sync_lock); printf("\\r\\n Quitting application .. \\r\\n"); printf(" Matrix multiplication demo end \\r\\n"); return 0; } void *compute_thread_entry(void *ptr) { int bytes_rcvd; pthread_mutex_lock(&sync_lock); while (compute_flag == 1) { do { bytes_rcvd = read(fd, &r_matrix, sizeof(r_matrix)); } while ((bytes_rcvd < sizeof(r_matrix)) || (bytes_rcvd < 0)); printf("\\r\\n Received results! - %d bytes from ", bytes_rcvd); printf("rpmsg device (transmitted from remote context) \\r\\n"); matrix_print(&r_matrix); pthread_mutex_lock(&sync_lock); } return 0; } int main(int argc, char *argv[]) { unsigned int size; int opt; char *rpmsg_dev="/dev/rpmsg0"; while ((opt = getopt(argc, argv, "d:n:")) != -1) { switch (opt) { case 'd': rpmsg_dev = optarg; break; case 'n': ntimes = atoi(optarg); break; default: printf("getopt return unsupported option: -%c\\n",opt); break; } } printf("\\r\\n Matrix multiplication demo start \\r\\n"); printf("\\r\\n Open rpmsg dev %s! \\r\\n", rpmsg_dev); fd = open(rpmsg_dev, O_RDWR); if (fd < 0) { perror("Failed to open rpmsg device.\\n"); return -1; } if (pthread_mutex_init(&sync_lock, 0) != 0) printf("\\r\\n mutex initialization failure \\r\\n"); pthread_mutex_lock(&sync_lock); printf("\\r\\n Creating ui_thread and compute_thread ... \\r\\n"); pthread_create(&ui_thread, 0, &ui_thread_entry, "ui_thread"); pthread_create(&compute_thread, 0, &compute_thread_entry, "compute_thread"); pthread_join(ui_thread, 0); pthread_join(compute_thread, 0); close(fd); printf("\\r\\n Quitting application .. \\r\\n"); printf(" Matrix multiply application end \\r\\n"); pthread_mutex_destroy(&sync_lock); return 0; }
0
#include <pthread.h> static pthread_mutex_t perf_mutex = PTHREAD_MUTEX_INITIALIZER; static FILE *perf_file; void perf_map_open(void) { char filename[32]; pid_t pid; pid = getpid(); sprintf(filename, "/tmp/perf-%d.map", pid); perf_file = fopen(filename, "w"); if (!perf_file) die("fopen"); } void perf_map_append(const char *symbol, unsigned long addr, unsigned long size) { if (perf_file == 0) return; pthread_mutex_lock(&perf_mutex); fprintf(perf_file, "%lx %lx %s\\n", addr, size, symbol); pthread_mutex_unlock(&perf_mutex); }
1
#include <pthread.h> int hashCount = 0,currentH = 0,pasCount = 0; char **hashes, **passes; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c = PTHREAD_COND_INITIALIZER; int main(int argc, char *argv[]){ FILE *fp, *fp2; int threads, x; hashes = malloc(20000 * sizeof(char*)); passes = malloc(20000 * sizeof(char*)); fp = fopen(argv[1],"r"); fp2 = fopen(argv[2],"r"); hashCount = getinput(fp2,hashes); threads = hashCount / 10; threads += 1; if (threads > 20){ threads = 20; } pasCount = getinput(fp,passes); fclose(fp); fclose(fp2); char pass[pasCount][100]; for (x = 0; x < pasCount; x++){ strcpy(pass[x],passes[x]); } pthread_t thread[threads]; for (x = 0; x < threads;x++){ pthread_create(&thread[x], 0,threadrun,pass); } pthread_mutex_lock(&m); while(currentH < hashCount){ pthread_cond_wait(&c, &m); } pthread_mutex_unlock(&m); for (x = 0; x < hashCount;x++){ printf("%s\\n",hashes[x]); } for(x = 0; x < hashCount; x++){ free(hashes[x]); }for(x = 0; x < pasCount; x++){ free(passes[x]); } free(hashes); free(passes); return 0; } void * threadrun(char pass[][100]){ int location; while(currentH < hashCount){ char temp[64],temp2[64],type[4],salt[64],md5hash[35],password[200], *tok; int x=0,i=0; pthread_mutex_lock(&m); if (currentH >= hashCount){ pthread_mutex_unlock(&m); break; } location = currentH; strcpy(temp,hashes[currentH]); strcpy(temp2,hashes[currentH]); strcat(hashes[location],": "); currentH += 1; pthread_mutex_unlock(&m); tok = strtok(temp,"$"); strcpy(type,tok); if (strcmp(type,"1") == 0){ tok = strtok(0,"$"); strcpy(salt,tok); for (i = 0; i < pasCount; i++){ strcpy(password,pass[i]); char string[100] = "openssl passwd -1 -salt "; strcat(string,salt); strcat(string," "); strcat(string,password); pthread_mutex_lock(&m); FILE *fp; fp = popen(string,"r"); fgets(md5hash,35,fp); fclose(fp); pthread_mutex_unlock(&m); if(compMD5Hash(temp2,md5hash) != 1){ x = pasCount; pthread_mutex_lock(&m); strcat(hashes[location],password); pthread_mutex_unlock(&m); } } } else{ for (i = 0; i < pasCount; i++){ char outhash[BCRYPT_HASHSIZE]; strcpy(password,pass[i]); for (x = 0; x < 30; x++){ salt[x] = temp2[x]; } bcrypt_hashpw(password,salt,outhash); if (strcmp(temp2, outhash) == 0) { x = pasCount; pthread_mutex_lock(&m); strcat(hashes[location],password); pthread_mutex_unlock(&m); } } } } if (location+1 == hashCount){ pthread_cond_signal(&c); } return 0; } int compMD5Hash(char goodHash[], char posHash[]){ int x, returned = 0; for (x = 0; x < 35; x++){ if (goodHash[x] != posHash[x]){ returned = 1; } } return returned; } int getinput(FILE * fp, char ** filein){ int count = 0, size = 20000; char temp[100],*tok; while(fgets(temp,100,fp)){ filein[count] = malloc(100 * sizeof(char)); tok = strtok(temp,"\\n\\0"); strcpy(temp,tok); strcpy(filein[count],temp); count++; if (count >= size){ filein = realloc(filein, size*2); size = size*2; } } return count; }
0
#include <pthread.h> int count = 0; int in = 0; int out = 0; int buffer [20]; pthread_mutex_t mutex; pthread_t tid; pthread_cond_t full; pthread_cond_t empty; int memory_size = 0; int free_memory = 32; int sleep_time = 5; int allocate(){ int item = free_memory; pthread_mutex_lock(&mutex); while (free_memory > memory_size){ pthread_cond_wait(&empty, &mutex); } printf("acquired... %d/%d [free/total] \\n", free_memory, memory_size); memory_size -= free_memory; pthread_cond_signal(&full); pthread_mutex_unlock(&mutex); return item; } int deallocate(){ int item = free_memory; pthread_mutex_lock(&mutex); while (free_memory == 0){ pthread_cond_wait(&full, &mutex); } printf("freed... %d/%d [free/total] \\n", free_memory, memory_size); memory_size += free_memory; pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); return item; } void * consumer(void * param){ int item; while(1){ item = allocate(); sleep(sleep_time); item = deallocate(); } } int main(int argc, char * argv[]) { memory_size = atoi(argv[1]); int threads = atoi(argv[2]); pthread_mutex_init(&mutex, 0); pthread_cond_init(&full,0); pthread_cond_init(&empty,0); int i; for (i = 0; i < threads; i++) pthread_create(&tid, 0, consumer, 0); pthread_join(tid,0); }
1
#include <pthread.h> int chopstick[5] = {0,0,0,0,0}; int state[5]; pthread_cond_t chopstic_cond[5] = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER; void pick_chopstick(int id) { pthread_mutex_lock(&mutex_lock); if(state[id] == 1 && chopstick[id]==0){ chopstick[id] = 1; pthread_cond_wait(&chopstic_cond[id],&mutex_lock); printf("philosopher %d is pick up the left chopstick %d .\\n",id,id); } pthread_mutex_unlock(&mutex_lock); sleep(1); pthread_mutex_lock(&mutex_lock); if(chopstick[(id+1)%5]==0){ chopstick[(id+1)%5] = 1; pthread_cond_wait(&chopstic_cond[(id+1)%5],&mutex_lock); printf("philosopher %d is pick up the right chopstick %d .\\n",id,(id+1)%5); } pthread_mutex_unlock(&mutex_lock); } void take_down_chopstick(int id) { pthread_mutex_lock(&mutex_lock); chopstick[id] = 0; pthread_cond_signal(&chopstic_cond[id]); printf("philosopher %d is take down the left chopstick %d .\\n",id,id); pthread_mutex_unlock(&mutex_lock); pthread_mutex_lock(&mutex_lock); chopstick[(id+1)%5] = 0; pthread_cond_signal(&chopstic_cond[(id+1)%5]); printf("philosopher %d is take down the right chopstick %d .\\n",id,(id+1)%5); pthread_mutex_unlock(&mutex_lock); } void *philosopher(void* data) { int id = (int)data; while(1){ printf("Philosopher %d is thinking\\n",id); sleep(1); state[id] = 1; printf("philosopher %d is hungry.\\n",id); pick_chopstick(id); if(chopstick[id] == 1 && chopstick[(id+1)%5] ==1 && state[id] == 1) { printf("philosopher %d is eating.\\n",id); sleep(1); take_down_chopstick(id); } } } int main(){ int i=0; pthread_t pthred_philosopher[5]; for(i=0;i<5;i++){ pthread_create(&pthred_philosopher[i],0,philosopher,i); state[i]=0; } for(i=0;i<5;i++){ pthread_join(pthred_philosopher[i],0); } return 0; }
0
#include <pthread.h> int value = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cvar = PTHREAD_COND_INITIALIZER; void* alarm_thr(void* data) { int new_value; int old_value = 0; while(1) { pthread_mutex_lock(&mutex); while(value == old_value) pthread_cond_wait(&cvar, &mutex); new_value = value; pthread_mutex_unlock(&mutex); if((new_value >= 90) && (old_value < 90)) { printf("Bumm, the end!\\n"); } else if((new_value >= 60) && (old_value < 60)) { printf("Meleg a helyzet!\\n"); } else if((new_value >= 30) && (old_value < 30)) { printf("Érdemes lenne odafigyelni!\\n"); } old_value = new_value; } return 0; } void* measure_thr(void* data) { int i; for(i = 0; i <= 100; i += 10) { pthread_mutex_lock(&mutex); value = i; pthread_cond_broadcast(&cvar); pthread_mutex_unlock(&mutex); sleep(1); } return 0; } int main() { pthread_t th_m; pthread_t th_a; printf("Program indul...\\n"); if(pthread_create(&th_a, 0, alarm_thr, 0)) { fprintf(stderr, "pthread_create (alarm)"); exit(1); } if(pthread_create(&th_m, 0, measure_thr, 0)) { fprintf(stderr, "pthread_create (measure)"); exit(1); } pthread_join(th_m, 0); printf("Program vége.\\n"); exit(0); }
1
#include <pthread.h> struct shared_mem{ bool flag; int sender; int receiver; int clients; }; int shmid; struct shared_mem* shm; pthread_t *reader_threads,*writer_threads; pthread_cond_t *write_cond,*read_cond; pthread_mutex_t *write_mutex,*read_mutex; void Error(char *msg){ perror("Error "); printf("%s \\n",msg); exit(0); } void init(){ if((shmid = shmget(1234,1024,0666|IPC_CREAT)) < 0){ Error("shmget"); } shm = (struct shared_mem*)shmat(shmid,0,0); if(shm == (struct shared_mem*)-1){ Error("shmat"); } reader_threads = (pthread_t*) malloc(sizeof(pthread_t)*shm->clients); writer_threads = (pthread_t*) malloc(sizeof(pthread_t)*shm->clients); read_cond = (pthread_cond_t*) malloc(sizeof(pthread_cond_t)*shm->clients); write_cond = (pthread_cond_t*) malloc(sizeof(pthread_cond_t)*shm->clients); read_mutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*shm->clients); write_mutex = (pthread_mutex_t*) malloc(sizeof(pthread_mutex_t)*shm->clients); int i; for(i=0;i<shm->clients;i++){ pthread_cond_init(&write_cond[i],0); pthread_cond_init(&read_cond[i],0); pthread_mutex_init(&write_mutex[i],0); pthread_mutex_init(&read_mutex[i],0); } } void* reader(void* ptr){ int *i = (int*) malloc(sizeof(int)); i = (int*)ptr; pthread_mutex_lock(&read_mutex[*i]); if(shm->receiver != *i){ pthread_cond_wait(&read_cond[*i],&read_mutex[*i]); } else{ pthread_cond_signal(&read_cond[*i]); } pthread_mutex_unlock(&read_mutex[*i]); printf("Critical section reader has been ended..\\n"); char myfifo[1024],msg[1024]; snprintf(myfifo,1024,"myfifo%d",shm->sender); int fd = open(myfifo,O_RDONLY); read(fd,msg,1024); printf("Client %d read msg \\" %s \\" from Server %d\\n",shm->receiver,msg,shm->sender); close(fd); } void* writer(void* ptr){ int *i = (int*) malloc(sizeof(int)); i = (int*)ptr; pthread_mutex_lock(&write_mutex[*i]); if(shm->sender != *i){ pthread_cond_wait(&write_cond[*i],&write_mutex[*i]); } else{ shm->flag = 0; pthread_cond_signal(&write_cond[*i]); } pthread_mutex_unlock(&write_mutex[*i]); printf("critical section writer has been ended..\\n"); char myfifo[1024],msg[1024]; snprintf(myfifo,1024,"myfifo%d",shm->sender); int fd = open(myfifo,O_WRONLY); printf("Enter your msg.\\n"); scanf("%s",msg); write(fd,msg,1024); close(fd); } int main(){ init(); printf("%d\\n",shm->clients); int i; while(1){ for(i=0;i<shm->clients;i++){ pthread_create(&writer_threads[i],0,writer,&i); pthread_create(&reader_threads[i],0,reader,&i); } for(i=0;i<shm->clients;i++){ pthread_join(reader_threads[i]); pthread_join(writer_threads[i]); } } }
0
#include <pthread.h> struct data { int *Tab1; int *Tab2; int i; }; pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER; void * Mul(void * par){ pthread_t moi =pthread_self(); int *res=(int *)malloc(sizeof(int)); struct data *mon_D1 = (struct data*)par; *res=(*mon_D1).Tab1[(*mon_D1).i] * (*mon_D1).Tab2[(*mon_D1).i] ; pthread_mutex_lock(&verrou); (*mon_D1).i++; pthread_mutex_unlock(&verrou); printf("Je suis le thread %lu, je fais la multiplication de la %i-eme ligne, mon resultat est : %i\\n",moi, (*mon_D1).i,*res); pthread_exit(res); } int main(){ int taille=0; printf("Entrez la taille de vos vecteurs\\n"); scanf("%i",&taille); int *T1=malloc(sizeof(int)*taille), *T2=malloc(sizeof(int)*taille); printf("Entrez les coordonnées du premier vecteur\\n"); for(int i=0;i<taille;i++){ printf("La valeur du %i-eme parametre: ",i); scanf("%i",&T1[i]); } printf("Entrez les coordonnées du deuxieme vecteur\\n"); for(int i=0;i<taille;i++){ printf("La valeur du %i-eme parametre: ",i); scanf("%i",&T2[i]); } struct data D1; D1.Tab1=T1; D1.Tab2=T2; D1.i=0; pthread_t *TabDeThread = malloc(taille*sizeof(pthread_t)); int somme=0,resultat=0; void *vptr_return; for(int i=0;i<taille;i++){ pthread_create(&(TabDeThread[i]),0,Mul,&D1); } for(int i=0;i<taille;i++){ pthread_join(TabDeThread[i],&vptr_return); somme= *((int *)vptr_return); resultat=resultat+somme; } free(vptr_return); printf("La somme des vecteurs : V1("); for(int i=0;i<taille-1;i++){ printf("%i,",T1[i]); } printf("%i) et V2(",T1[taille-1]); for(int i=0;i<taille-1;i++){ printf("%i,",T2[i]); } printf("%i) a pour resultat : %i\\n",T2[taille-1], resultat); return 0; }
1
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i < 10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { printf("inc_count(): thread %ld, count = %d Threshold reached. ", my_id, count); pthread_cond_signal(&count_threshold_cv); printf("Just sent signal.\\n"); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received. Count= %d\\n", my_id,count); printf("watch_count(): thread %ld Updating the value of count...\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); printf("watch_count(): thread %ld Unlocking mutex.\\n", my_id); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited and joined with %d threads. Final value of count = %d. Done.\\n", 3, count); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit (0); }
0
#include <pthread.h> void *fhilo1(); void *fhilo2(); pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char **argv) { pthread_t hilo1,hilo2; printf("inicio main()\\n"); pthread_mutex_lock(&m2); pthread_create(&hilo1,0,fhilo1,0); pthread_create(&hilo2,0,fhilo2,0); pthread_join(hilo1,0); pthread_join(hilo2,0); printf("fin main()\\n"); exit(0); } void *fhilo1() { int i; for(i=0;i<10;i++) { pthread_mutex_lock(&m1); printf("soy hilo1\\n"); sleep(1); pthread_mutex_unlock(&m2); } pthread_exit(0); } void *fhilo2() { int i; for(i=0;i<10;i++) { pthread_mutex_lock(&m2); printf("soy hilo2\\n"); pthread_mutex_unlock(&m1); } pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t x,wsem; pthread_t tid; int readcount; void intialize() { pthread_mutex_init(&x,0); pthread_mutex_init(&wsem,0); readcount=0; } void * reader (void * param) { int waittime; waittime = rand() % 5; printf("\\nReader is trying to enter"); pthread_mutex_lock(&x); readcount++; if(readcount==1) pthread_mutex_lock(&wsem); printf("\\n%d Reader is inside ",readcount); pthread_mutex_unlock(&x); sleep(waittime); pthread_mutex_lock(&x); readcount--; if(readcount==0) pthread_mutex_unlock(&wsem); pthread_mutex_unlock(&x); printf("\\nReader is Leaving"); } void * writer (void * param) { int waittime; waittime=rand() % 3; printf("\\nWriter is trying to enter"); pthread_mutex_lock(&wsem); printf("\\nWrite has entered"); sleep(waittime); pthread_mutex_unlock(&wsem); printf("\\nWriter is leaving"); sleep(30); exit(0); } int main() { int n1,n2,i; printf("\\nEnter the no of readers: "); scanf("%d",&n1); printf("\\nEnter the no of writers: "); scanf("%d",&n2); for(i=0;i<n1;i++) pthread_create(&tid,0,reader,0); for(i=0;i<n2;i++) pthread_create(&tid,0,writer,0); sleep(30); exit(0); }
0
#include <pthread.h> int source[30]; int minBound[8]; int maxBound[8]; int channel[8]; int th_id = 0; pthread_mutex_t mid; pthread_mutex_t ms[8]; void sort (int x, int y) { int aux = 0; for (int i = x; i < y; i++) { for (int j = i; j < y; j++) { if (source[i] > source[j]) { aux = source[i]; source[i] = source[j]; source[j] = aux; } } } } void *sort_thread (void * arg) { int id = -1; int x, y; pthread_mutex_lock (&mid); id = th_id; th_id++; pthread_mutex_unlock (&mid); x = minBound[id]; y = maxBound[id]; __VERIFIER_assert (x >= 0); __VERIFIER_assert (x < 30); __VERIFIER_assert (y >= 0); __VERIFIER_assert (y < 30); printf ("t%d: min %d max %d\\n", id, x, y); sort (x, y); pthread_mutex_lock (&ms[id]); channel[id] = 1; pthread_mutex_unlock (&ms[id]); return 0; } void *main_continuation (void *arg); pthread_t t[8]; int main () { int i; __libc_init_poet (); for (i = 0; i < 30; i++) { source[i] = __VERIFIER_nondet_int (0, 20); printf ("m: source[%d] = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } pthread_mutex_init (&mid, 0); int j = 0; int delta = 30/8; __VERIFIER_assert (delta >= 1); i = 0; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++; __VERIFIER_assert (i == 8); pthread_t tt; pthread_create (&tt, 0, main_continuation, 0); pthread_join (tt, 0); return 0; } void *main_continuation (void *arg) { int i, k; k = 0; while (k < 8) { i = 0; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; pthread_mutex_lock (&ms[i]); if (channel[i]) k++; pthread_mutex_unlock (&ms[i]); i++; __VERIFIER_assert (i == 8); } __VERIFIER_assert (th_id == 8); __VERIFIER_assert (k == 8); sort (0, 30); printf ("==============\\n"); for (i = 0; i < 30; i++) printf ("m: sorted[%d] = %d\\n", i, source[i]); i = 0; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; __VERIFIER_assert (i == 8); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex[5]; void* dine(void* arg) { int num = (int)arg; int left, right; if(num < 4) { right = num; left = num+1; } else if(num == 4) { right = 0; left = num; } while(1) { pthread_mutex_lock(&mutex[right]); if(pthread_mutex_trylock(&mutex[left]) == 0) { printf("%c 正在吃面。。。。。。\\n", num+'A'); pthread_mutex_unlock(&mutex[left]); } pthread_mutex_unlock(&mutex[right]); sleep(rand()%5); } } int main(int argc, const char* argv[]) { pthread_t p[5]; for(int i=0; i<5; ++i) { pthread_mutex_init(&mutex[i], 0); } for(int i=0; i<5; ++i) { pthread_create(&p[i], 0, dine, (void*)i); } for(int i=0; i<5; ++i) { pthread_join(p[i], 0); } for(int i=0; i<5; ++i) { pthread_mutex_destroy(&mutex[i]); } return 0; }
0
#include <pthread.h> int dimension; double **matrix; int *bestTour; int *currentTour; int *nextTour; double temperature; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void printTour(int *tour) { int i; printf("TOUR: "); for (i = 0; i < dimension; i++) printf("%d ", tour[i]); printf("\\n"); } void printMatrix() { int i,j; for (i = 0; i < dimension; i++) { for (j = 0; j < dimension; j++) printf("%lf ", matrix[i][j]); printf("\\n"); } } double** readMatrix(char* name) { FILE *file; double **matrix; double **coord; int i,j; char buf[100]; dimension = 0; file = fopen(name, "r"); while (fscanf(file," %[^\\n]s", buf) > 0 && !(buf[0] == 'D' && buf[2] == 'M')); dimension = atoi(&buf[12]); while (fscanf(file," %[^\\n]s", buf) > 0 && !(buf[0] == 'N' && buf[1] == 'O')); coord = (double **)malloc(dimension*sizeof(double*)); for(i=0;i<dimension;i++) coord[i] = (double*) malloc(2*sizeof(double)); for(i=0;i<dimension;i++) fscanf(file, "\\n %*[^ ] %lf %lf", &coord[i][0], &coord[i][1]); matrix = (double **)malloc(sizeof(double*)*(dimension)); for (i = 0; i < dimension; i++) matrix[i] = (double *)malloc(sizeof(double)*(dimension)); for (i = 0; i < dimension; i++) { for (j = i + 1 ; j < dimension; j++) { matrix[i][j] = sqrt(pow(coord[i][0] - coord[j][0],2) + pow(coord[i][1] - coord[j][1],2)); matrix[j][i] = matrix[i][j]; } } free(coord); return matrix; } double tourCost(int *tour) { int i; double value = 0.0; for (i = 0; i < dimension - 1; i++) value += matrix[tour[i]][tour[i+1]]; return value + matrix[tour[0]][tour[dimension-1]]; } int* nearestNeighbour() { int *tour; int *visited; double nearestDistance; int nearestIndex; int i,j; visited = (int*) malloc(dimension*sizeof(int)); tour = (int*) malloc(dimension*sizeof(int)); for(i=0;i<dimension;i++) visited[i] = 0; int start; pthread_mutex_lock(&mutex); start = rand()%dimension; pthread_mutex_unlock(&mutex); visited[start] = 1; tour[0] = start; for(i=1;i<dimension;i++) { nearestDistance = FLT_MAX; nearestIndex = 0; for(j=0;j<dimension;j++) { if(!visited[j] && matrix[tour[i-1]][j] < nearestDistance) { nearestDistance = matrix[tour[i-1]][j]; nearestIndex = j; } } tour[i] = nearestIndex; visited[nearestIndex] = 1; } free(visited); return tour; } void swap(int *currentTour, int *nextTour) { int i,aux; for (i = 0; i < dimension; i++) nextTour[i] = currentTour[i]; pthread_mutex_lock(&mutex); int first = (rand() % (dimension - 1)) + 1; int second = (rand() % (dimension - 1)) + 1; pthread_mutex_unlock(&mutex); aux = nextTour[first]; nextTour[first] = nextTour[second]; nextTour[second] = aux; } void* SimulatedAnnealing(void *id) { int *currentTour; int *nextTour; double distance; double delta; int i; currentTour = nearestNeighbour(); distance = tourCost(currentTour); nextTour = (int *)malloc(sizeof(int)*dimension); while (temperature > 0.00001) { swap(currentTour, nextTour); delta = tourCost(nextTour) - distance; if (((delta < 0) || (distance > 0)) && (exp(-delta/temperature) > (double)rand()/32767)) { for (i = 0; i < dimension; i++) currentTour[i] = nextTour[i]; distance = delta + distance; } pthread_mutex_lock(&mutex); temperature *= 0.99999; pthread_mutex_unlock(&mutex); } pthread_mutex_lock(&mutex); if (tourCost(bestTour) > tourCost(currentTour)) { for (i = 0; i < dimension; i++) bestTour[i] = currentTour[i]; } pthread_mutex_unlock(&mutex); return(0); } int main(int argc, char **argv) { int i; void *status; pthread_t *threads; threads = (pthread_t *)malloc(sizeof(pthread_t)*8); temperature = 1000; matrix = readMatrix(argv[1]); bestTour = (int *)malloc(sizeof(int)*dimension); for (i = 0; i < dimension;i++) bestTour[i] = i; pthread_mutex_init(&mutex,0); for (i = 0; i < 8; i++) if (pthread_create(&threads[i], 0, SimulatedAnnealing,(void*)(intptr_t)i)) exit(-1); for (i = 0; i < 8; i++) if (pthread_join(threads[i], &status)) exit(-1); pthread_mutex_destroy(&mutex); printf("Best Distance: %lf\\n", tourCost(bestTour)); return 0; }
1
#include <pthread.h> int head_index = 0; int tail_index = 0; int hw_buffer[1000]; pthread_t p1, p2, p3; pthread_t k1, k2, k3; pthread_mutex_t p_lock; pthread_mutex_t k_lock; int get_zufallszahl(int max_randomnummer){ int randomnummer = rand() % max_randomnummer + 1; return randomnummer; } void put_rand_in_hw_buffer(int rand_nr){ hw_buffer[head_index] = rand_nr; head_index = (head_index + 1) % 1000; } int get_rand_from_hw_buffer(){ int temp_index = tail_index; tail_index = (tail_index + 1) % 1000; return hw_buffer[temp_index]; } void *produzent (){ while(1){ pthread_mutex_lock(&p_lock); if (tail_index - head_index != 1 && tail_index - head_index != 999 ){ put_rand_in_hw_buffer(get_zufallszahl(1000)); } pthread_mutex_unlock(&p_lock); sleep(get_zufallszahl(5)); } return 0; } void *konsument (){ while(1){ pthread_mutex_lock(&k_lock); if (head_index - tail_index != 0){ printf("Auslesen aus Puffer: %d\\n", get_rand_from_hw_buffer()); } pthread_mutex_unlock(&k_lock); sleep(get_zufallszahl(5)); } return 0; } int main(int argc, char *argv[]) { srand(time(0)); pthread_create (&p1, 0, produzent, 0); pthread_create (&p2, 0, produzent, 0); pthread_create (&p3, 0, produzent, 0); sleep(10); pthread_create (&k1, 0, konsument, 0); pthread_create (&k2, 0, konsument, 0); pthread_create (&k3, 0, konsument, 0); pthread_join (p1, 0); pthread_join (p2, 0); pthread_join (p3, 0); pthread_join (k1, 0); pthread_join (k2, 0); pthread_join (k3, 0); pthread_mutex_destroy(&p_lock); pthread_mutex_destroy(&k_lock); return 0; }
0
#include <pthread.h> { void *(*process) (void *arg); void *arg; struct worker *next; } CThread_worker; { pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t *threadid; int max_thread_num; int cur_queue_size; } CThread_pool; int pool_add_worker (void *(*process) (void *arg), void *arg); void *thread_routine (void *arg); static CThread_pool *pool = 0; void pool_init (int max_thread_num) { pool = (CThread_pool *) malloc (sizeof (CThread_pool)); pthread_mutex_init (&(pool->queue_lock), 0); pthread_cond_init (&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); int i = 0; for (i = 0; i < max_thread_num; i++) { pthread_create (&(pool->threadid[i]), 0, thread_routine,0); } } int pool_add_worker (void *(*process) (void *arg), void *arg) { CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock (&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if (member != 0) { while (member->next != 0) member = member->next; member->next = newworker; } else { pool->queue_head = newworker; } assert (pool->queue_head != 0); pool->cur_queue_size++; pthread_mutex_unlock (&(pool->queue_lock)); pthread_cond_signal (&(pool->queue_ready)); return 0; } int pool_destroy (void) { if (pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast (&(pool->queue_ready)); int i; for (i = 0; i < pool->max_thread_num; i++) pthread_join (pool->threadid[i], 0); free (pool->threadid); CThread_worker *head = 0; while (pool->queue_head != 0) { head = pool->queue_head; pool->queue_head = pool->queue_head->next; free (head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free (pool); pool=0; return 0; } void * thread_routine (void *arg) { printf ("starting thread 0x%x\\n", pthread_self ()); while (1) { pthread_mutex_lock (&(pool->queue_lock)); while (pool->cur_queue_size == 0 && !pool->shutdown) { printf ("thread 0x%x is waiting\\n", pthread_self ()); pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); } if (pool->shutdown) { pthread_mutex_unlock (&(pool->queue_lock)); printf ("thread 0x%x will exit\\n", pthread_self ()); pthread_exit (0); } printf ("thread 0x%x is starting to work\\n", pthread_self ()); assert (pool->cur_queue_size != 0); assert (pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock (&(pool->queue_lock)); (*(worker->process)) (worker->arg); free (worker); worker = 0; } pthread_exit (0); } void *myprocess (void *arg) { printf ("threadid is 0x%x, working on task %d\\n", pthread_self (),*(int *) arg); sleep (1); return 0; } int main (int argc, char **argv) { pool_init (5); int *workingnum = (int *) malloc (sizeof (int) * 10); int i; for (i = 0; i < 10; i++) { workingnum[i] = i; pool_add_worker (myprocess, &workingnum[i]); } sleep (5); pool_destroy (); free (workingnum); return 0; }
1
#include <pthread.h> struct Data { int count; pthread_mutex_t lock; int number; }; static struct Data *data = 0; struct Data *data_alloc( void ) { struct Data *data; if ( (data = malloc( sizeof( struct Data ) )) != 0 ) { data->count = 1; if ( pthread_mutex_init( &data->lock, 0 ) != 0 ) { free( data ); return 0; } data->number = -9999; } return data; } void data_hold( struct Data *data ) { assert( data != 0 ); pthread_mutex_lock( &data->lock ); data->count++; pthread_mutex_unlock( &data->lock ); } void data_release( struct Data *data ) { assert( data != 0 ); pthread_mutex_lock( &data->lock ); if ( --data->count == 0 ) { pthread_mutex_unlock( &data->lock ); pthread_mutex_destroy( &data->lock ); free( data ); } else { pthread_mutex_unlock( &data->lock ); } } void *thread_run( void *arg ) { if ( data == 0 ) { if ( (data = data_alloc()) == 0 ) { return (void *) (-1); } } data_hold( data ); data->number = 1111; printf( "data->number is %d\\n", data->number ); data_release( data ); return (void *) 0; } void *thread2_run( void *arg ) { if ( data == 0 ) { if ( (data = data_alloc()) == 0 ) { return (void *) (-1); } } data_hold( data ); data->number = 2222; printf( "data->number is %d\\n", data->number ); data_release( data ); return (void *) 0; } int main( int argc, char **argv ) { pthread_t tid, tid2; int err; if ( (err = pthread_create( &tid, 0, thread_run, 0 )) != 0 ) { err_quit( "error on creating first thread: %s\\n", strerror( err ) ); } if ( (err = pthread_create( &tid2, 0, thread2_run, 0 )) != 0 ) { err_quit( "error on creating second thread: %s\\n", strerror( err ) ); } return 0; }
0
#include <pthread.h> static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER; void output_init() { return; } void output( char * string, ... ) { va_list ap; char *ts="[??:??:??]"; struct tm * now; time_t nw; pthread_mutex_lock(&m_trace); nw = time(0); now = localtime(&nw); if (now == 0) printf(ts); else printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec); __builtin_va_start((ap)); vprintf(string, ap); ; pthread_mutex_unlock(&m_trace); } void output_fini() { return; }
1
#include <pthread.h> int count_par = 0; int child_arr[15] = {0}; int child_time_arr[15]; int count = 0; pthread_mutex_t mutex, mut_write; void getChild(){ printf("В комнате находятся дети: "); for(int i=0;i<15;i++) if(child_arr[i]!=0){ printf("%i ",i); } printf("\\n"); } void *c() { int id; pthread_mutex_lock(&mutex); id = count; count++; pthread_mutex_unlock(&mutex); child_time_arr[id] = 2 + rand() % 7; pthread_mutex_lock(&mut_write); child_arr[id] = 1; printf("Ребенок №%d пришел\\n", id); getChild(); pthread_mutex_unlock(&mut_write); sleep(child_time_arr[id]); pthread_mutex_lock(&mut_write); child_arr[id] = 0; printf("Ребенок №%d ушел\\n", id); getChild(); pthread_mutex_unlock(&mut_write); pthread_exit(0); } int main() { srand(getpid()); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mut_write, 0); pthread_t f1_thread, f2_thread; pthread_t thread[15]; for (int i=0;i<15;i++){ sleep(2 + rand() % 4); pthread_create(&thread[i], 0, &c, 0); } for (int i=0;i<15;i++){ pthread_join(thread[i], 0); } pthread_mutex_destroy(&mutex); pthread_mutex_destroy(&mut_write); return 0; }
0
#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); 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); }
1
#include <pthread.h> static char *gWorkloadPathArray[100]; static unsigned short int gUniqueWorkloadPaths = 0; static pthread_mutex_t counter_mutex; static int counter = 0; static int mode = WORKLOAD_SEQ; int workload_init(const char *workload_path) { int i = 0; char temp_buf[256]; FILE *file_handle; file_handle = fopen(workload_path, "r"); if (file_handle == 0) { fprintf(stderr, "cannot open workload file %s", workload_path); return 1; } while (fscanf(file_handle, "%s", temp_buf) != EOF) gWorkloadPathArray[i++] = strdup(temp_buf); gUniqueWorkloadPaths = i; pthread_mutex_init(&counter_mutex, 0); fclose(file_handle); return 0; } unsigned short int workload_num_unique_paths() { return gUniqueWorkloadPaths; } char* workload_get_path() { if(mode == WORKLOAD_RND) return gWorkloadPathArray[(int)(1.0 * gUniqueWorkloadPaths * rand()/(32767 +1.0))]; pthread_mutex_lock(&counter_mutex); counter++; pthread_mutex_unlock(&counter_mutex); return gWorkloadPathArray[counter % gUniqueWorkloadPaths]; }
0
#include <pthread.h> pthread_mutex_t theMutex; pthread_cond_t condProducer, condConsumer; int buffer [1000]; int buffer_top = 0; void* producerCode(void* ptr) { srand(time(0)); int i,rand_num; for(i = 1; i <= 10000000; i++) { pthread_mutex_lock(&theMutex); while(buffer_top == 1000 -1) { printf("producer is waiting %d\\n", i); pthread_cond_wait(&condProducer, &theMutex); } rand_num = rand() % 11; buffer_top++; buffer[buffer_top] = rand_num; pthread_cond_signal(&condConsumer); pthread_mutex_unlock(&theMutex); } pthread_exit(0); } void* consumerCode(void* ptr) { int i, value = 0; for(i = 1; i <= 10000000; i++) { pthread_mutex_lock(&theMutex); while(buffer_top == -1) { printf("consumer is waiting %d\\n",i); pthread_cond_wait(&condConsumer, &theMutex); } value += buffer[buffer_top]; buffer_top --; pthread_cond_signal(&condProducer); pthread_mutex_unlock(&theMutex); } printf("total value %d\\n", value); pthread_exit(0); } int main () { pthread_t producer, consumer; pthread_mutex_init(&theMutex, 0); pthread_cond_init(&condConsumer, 0); pthread_cond_init(&condProducer, 0); pthread_create(&consumer, 0, consumerCode, 0); pthread_create(&producer, 0, producerCode, 0); pthread_join(producer, 0); pthread_join(consumer, 0); pthread_cond_destroy(&condProducer); pthread_cond_destroy(&condConsumer); pthread_mutex_destroy(&theMutex); return 0; }
1
#include <pthread.h> int state[5]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t s[5] = PTHREAD_MUTEX_INITIALIZER; void put_forks(int); void* philosopher(int*); void take_forks(int); void test(int); void think(int i){ printf("philosopher %d is thinking\\n",i); sleep(1); } void eat(int i){ printf("philosopher %d is eating\\n",i); sleep(1); } void* philosopher(int *data) { int i = (int)data; while (1) { think(i); take_forks(i); eat(i); put_forks(i); } } void take_forks(int i) { printf("philosopher %d want to eat!!\\n",i); pthread_mutex_lock(&mutex); state[i] = 1; test(i); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&s[i]); printf("philosopher %d take the forks... LEFT : %d RIGHT : %d \\n", i, (i+5 -1)%5, (i+1)%5); } void test(int i) { if ( state[i] == 1 && state[(i+5 -1)%5] != 2 && state[(i+1)%5] != 2 ) { pthread_mutex_unlock(&s[i]); } } void put_forks(int i) { pthread_mutex_lock(&mutex); state[i] = 0; test((i+5 -1)%5); test((i+1)%5); pthread_mutex_unlock(&mutex); printf("philosopher %d put the forks... LEFT : %d RIGHT : %d \\n", i, (i+5 -1)%5, (i+1)%5); } int main(){ int i,j; pthread_t pthread[5]; for (i = 0; i < 5; i++) { state[i] = 0; } for (j = 0; j < 5; j++) { pthread_create(&pthread[j], 0, philosopher, (void *)j); } for (j = 0; j < 5; j++) pthread_join(pthread[j],0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER; { int value; int flag; }matrix; void* function1(int *x) { *x=1; pthread_exit(0); } void* function2(int array[2] ) { pthread_mutex_lock(&mutex); if (array[0]<array[1]) { array[0]=0; } else array[0]=1; pthread_mutex_unlock(&mutex); pthread_exit(0); } void* function3(int x[2]) { if (x[0]==1) printf("\\nO megalyteros ari8mos einai to %d\\n",x[1]); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t tid; pthread_attr_t attr; int harray[2]; matrix numbers[argc-1]; int i,j,k; k=0; for (i=1;i<argc;i++) { numbers[i-1].value=atoi(argv[i]); } printf("\\nTo pli8os twn eisagwmenwn timwn einai %d",argc-1); printf("\\nEisagomenes times x="); for (i=0;i<argc-1;i++) printf("%d ",numbers[i].value); for (i=0;i<argc-1;i++) { pthread_attr_init(&attr); pthread_create(&tid,&attr,(void*)function1,&numbers[i].flag); pthread_join(tid,0); } printf("\\nMeta tin arxikopoihsh w="); for (i=0;i<argc-1;i++) printf("%d ",numbers[i].flag); for (i=0;i<argc-1;i++) for (j=0;j<argc-1;j++) { k++; harray[0]=numbers[i].value; harray[1]=numbers[j].value; pthread_attr_init(&attr); pthread_create(&tid,&attr,(void*)function2,&harray); pthread_join(tid,0); numbers[i].flag=harray[0]; if (numbers[i].flag==0) { printf("\\nThread (%d,%d) sigrine tous ari8mous %d kai %d kai brike ton ari8mo %d mikrotero h iso apo ton ari8mo %d",i,j,numbers[i].value,numbers[j].value,numbers[i].value,numbers[j].value); break; } } printf("\\nAri8mos twn threads=%d",k); printf("\\nMeta apo to 2o bhma w="); for (i=0;i<argc-1;i++) printf("%d",numbers[i].flag); for (i=0;i<argc-1;i++) { harray[1]=numbers[i].value; harray[0]=numbers[i].flag; pthread_attr_init(&attr); pthread_create(&tid,&attr,(void*)function3,&harray); pthread_join(tid,0); } return 0; }
1
#include <pthread.h> { void *(*process) (void *arg); void *arg; struct worker *next; } CThread_worker; { pthread_mutex_t queue_lock; pthread_cond_t queue_ready; CThread_worker *queue_head; int shutdown; pthread_t *threadid; int max_thread_num; int cur_queue_size; } CThread_pool; int pool_add_worker (void *(*process) (void *arg), void *arg); void *thread_routine (void *arg); static CThread_pool *pool = 0; void pool_init (int max_thread_num) { pool = (CThread_pool *) malloc (sizeof (CThread_pool)); pthread_mutex_init (&(pool->queue_lock), 0); pthread_cond_init (&(pool->queue_ready), 0); pool->queue_head = 0; pool->max_thread_num = max_thread_num; pool->cur_queue_size = 0; pool->shutdown = 0; pool->threadid = (pthread_t *) malloc (max_thread_num * sizeof (pthread_t)); int i = 0; for (i = 0; i < max_thread_num; i++) { pthread_create (&(pool->threadid[i]), 0, thread_routine,0); } } int pool_add_worker (void *(*process) (void *arg), void *arg) { CThread_worker *newworker = (CThread_worker *) malloc (sizeof (CThread_worker)); newworker->process = process; newworker->arg = arg; newworker->next = 0; pthread_mutex_lock (&(pool->queue_lock)); CThread_worker *member = pool->queue_head; if (member != 0) { while (member->next != 0) member = member->next; member->next = newworker; } else { pool->queue_head = newworker; } assert (pool->queue_head != 0); pool->cur_queue_size++; pthread_mutex_unlock (&(pool->queue_lock)); pthread_cond_signal (&(pool->queue_ready)); return 0; } int pool_destroy () { if (pool->shutdown) return -1; pool->shutdown = 1; pthread_cond_broadcast (&(pool->queue_ready)); int i; for (i = 0; i < pool->max_thread_num; i++) pthread_join (pool->threadid[i], 0); free (pool->threadid); CThread_worker *head = 0; while (pool->queue_head != 0) { head = pool->queue_head; pool->queue_head = pool->queue_head->next; free (head); } pthread_mutex_destroy(&(pool->queue_lock)); pthread_cond_destroy(&(pool->queue_ready)); free (pool); pool=0; return 0; } void * thread_routine (void *arg) { printf ("starting thread %lu\\n", pthread_self ()); while (1) { pthread_mutex_lock (&(pool->queue_lock)); while (pool->cur_queue_size == 0 && !pool->shutdown) { printf ("thread %lu is waiting\\n", pthread_self ()); pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock)); } if (pool->shutdown) { pthread_mutex_unlock (&(pool->queue_lock)); printf ("thread %lu will exit\\n", pthread_self ()); pthread_exit (0); } printf ("thread %lu is starting to work\\n", pthread_self ()); assert (pool->cur_queue_size != 0); assert (pool->queue_head != 0); pool->cur_queue_size--; CThread_worker *worker = pool->queue_head; pool->queue_head = worker->next; pthread_mutex_unlock (&(pool->queue_lock)); (*(worker->process)) (worker->arg); free (worker); worker = 0; } pthread_exit (0); } void * myprocess (void *arg) { printf ("threadid is %lu, working on task %d\\n", pthread_self (),*(int *) arg); sleep (1); return 0; } int main (int argc, char **argv) { pool_init (3); int *workingnum = (int *) malloc (sizeof (int) * 10); int i; for (i = 0; i < 10; i++) { workingnum[i] = i; pool_add_worker (myprocess, &workingnum[i]); } sleep (5); pool_destroy (); free (workingnum); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond_leitor; pthread_cond_t cond_escritor; int escritores = 0; int leitores = 0; { int contador; int idThread; }Arquivo; Arquivo arquivo; void inicializa_leitor(){ pthread_mutex_lock(&mutex); while(escritores > 0){ pthread_cond_wait(&cond_leitor, &mutex); } leitores++; pthread_mutex_unlock(&mutex); } void finaliza_leitor(){ pthread_mutex_lock(&mutex); leitores --; if(leitores == 0 ) pthread_cond_signal(&cond_escritor); pthread_mutex_unlock(&mutex); } void inicializa_escritor(){ pthread_mutex_lock(&mutex); while( (leitores > 0) || (escritores > 0)){ pthread_cond_wait(&cond_escritor,&mutex); } escritores ++; pthread_mutex_unlock(&mutex); } void finaliza_escritor(){ pthread_mutex_lock(&mutex); escritores --; pthread_cond_signal(&cond_escritor); pthread_cond_broadcast(&cond_leitor); pthread_mutex_unlock(&mutex); } void * leitor(void * arg){ int* p = (int *) arg; int pid = (int) *p; Arquivo arquivoLocal; while(1){ printf("Thread Leitora[%d]\\n", pid); inicializa_leitor(); arquivoLocal.contador = arquivo.contador; arquivoLocal.idThread = arquivo.idThread; printf("Leu o contador: [%d] que foi gravado pela Thread: [%d] \\n",arquivoLocal.contador,arquivoLocal.idThread ); finaliza_leitor(); sleep(1); } pthread_exit(0); } void* escritor(void *arg){ int * p = (int *) arg; int pid = (int) *p; while(1){ printf("Thread Escritora[%d]\\n", pid); inicializa_escritor(); pthread_mutex_lock(&mutex); arquivo.contador ++; arquivo.idThread = pid; pthread_mutex_unlock(&mutex); finaliza_escritor(); sleep(1); } pthread_exit(0); } int main(int argc, char *argv[]){ int i,j; int* pid; pthread_t threads[5 +2]; for ( i = 0; i < 2; ++i) { pid = (int*) malloc(sizeof(int)); *pid = i; pthread_create(&threads[i],0, escritor,(void *) pid); } for ( j = 2; j < 5 + 2; ++j) { pid = (int*) malloc(sizeof(int)); *pid = j; pthread_create(&threads[j],0, leitor,(void *) pid); } for (i = 0; i < 5 + 2; ++i) { pthread_join(threads[i],0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond_leitor); pthread_cond_destroy(&cond_escritor); free(pid); return 0; }
1
#include <pthread.h> int available[3]; int maximum[5][3]; int allocation[5][3]; int need[5][3]; pthread_mutex_t mutexavail; pthread_mutex_t mutexalloc; pthread_mutex_t mutexneed; int request_resources(int customer_num, int request[]); int release_resources(int customer_num, int request[]); void print_matrix(int M[5][3],char *name); void generate_maximum() { int ii,jj; srand(time(0)); for(ii=0;ii<5;ii++) { for(jj=0;jj<3;jj++) { maximum[ii][jj] = rand() % available[jj]; allocation[ii][jj] = 0; } } } int request_resources(int customer_num, int request[]) { int iter,j,ii; for(iter=0;iter<3;iter++) { if(request[iter] > need[customer_num][iter]) return -1; } for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] += request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] -= request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexneed); } if(check_safe()<0) { for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] += request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] += request[iter]; pthread_mutex_unlock(&mutexneed); } return -1; } return 0; } int release_resources(int customer_num, int request[]) { int iter; for(iter=0;iter<3;iter++) { pthread_mutex_lock(&mutexalloc); allocation[customer_num][iter] -= request[iter]; pthread_mutex_unlock(&mutexalloc); pthread_mutex_lock(&mutexavail); available[iter] += request[iter]; pthread_mutex_unlock(&mutexavail); pthread_mutex_lock(&mutexneed); need[customer_num][iter] = maximum[customer_num][iter] + allocation[customer_num][iter]; pthread_mutex_unlock(&mutexneed); } return 1; } int check_safe() { int ii,jj, work[3],finish[5]; int success_flag = 0; for(ii=0;ii<3;ii++) { work[ii] = available[ii]; } for(ii=0;ii<5;ii++) { finish[ii] = 0; } for(ii=0;ii<5;ii++) { if(finish[ii]==0) { for(jj=0;jj<3;jj++) { if(need[ii][jj] > work[jj]) return -1; } for(jj=0;jj<3;jj++) work[jj] += allocation[ii][jj]; success_flag = 1; } } return success_flag; } void *thread_create(void *cno) { int ii,j,request[3],request_flag=0; int cust_no = (int)cno; for(ii=0;ii<3;ii++) { request[ii] = rand() % available[ii]; } if(request_resources(cust_no,request)<0) { printf("\\n Customer %d ", cust_no); for(j=0;j<3;j++) printf("%d ", request[j]); printf(":Request DENIED\\n"); } else { request_flag = 1; printf("\\n Customer %d ", cust_no); for(j=0;j<3;j++) printf("%d ", request[j]); printf(":Request ACCEPTED\\n"); } if(request_flag==1) { sleep(rand() % 10); release_resources(cust_no, request); printf("\\n Customer %d released resouces", cust_no); } } void print_matrix(int M[5][3],char *name) { int i,j; printf("\\n-----%s Matrix----\\n",name); for(i=0;i<5;i++) { for(j=0;j<3;j++) printf("%d ",M[i][j]); printf("\\n"); } } int main(int argc, char **argv) { int ii,jj,kk,run_count = 50; pthread_t thread_id; if(argc==(3 +1)) { printf("\\n Available Matrix \\n"); for(ii=1;ii<=3;ii++) { available[ii-1] = abs(atoi(argv[ii])); printf("%d ",available[ii-1]); } printf("\\n"); } generate_maximum(); printf("\\n Maximum matrix is: \\n"); for(ii=0; ii<5;ii++) { for(jj=0; jj<3; jj++) { need[ii][jj] = maximum[ii][jj] - allocation[ii][jj]; printf("%d ",maximum[ii][jj]); } printf("\\n"); } printf("\\n Need Matrix\\n"); for(ii=0; ii< 5;ii++) { for(jj=0;jj<3;jj++) { printf("%d ",need[ii][jj]); } printf("\\n"); } for(ii=0;ii<run_count;ii++) { for(jj=0;jj<5;jj++) { pthread_create(&thread_id,0,thread_create,(void *)jj); } } printf("\\n All threads finished without any deadlocks! "); return 0; }
0
#include <pthread.h> { long int from; long int to; } arg_t; long double pi_x = 0.0; pthread_mutex_t lock_x; void* crunch(void *ptr) { int n; long double pi = 0.0; arg_t *args = (arg_t*)ptr; for (n = args->from; n < args->to; n++) pi = pi + (double)(1 - ((((int)(n)) & 1) << 1)) / ((2 * n) + 1); pthread_mutex_lock(&lock_x); pi_x = pi_x + pi; pthread_mutex_unlock(&lock_x); return 0; } int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: pi <number of iterations>\\n"); exit(1); } int i; long int iterations = atol(argv[1]) / 2; pthread_t thread[2]; arg_t args[2]; struct timeval tv_start, tv_end; struct timezone tz; gettimeofday(&tv_start, &tz); for (i = 0; i < 2; i++) { args[i].from = i * iterations; args[i].to = args[i].from + iterations; pthread_create( &thread[i], 0, crunch, (void*) &args[i]); } for (i = 0; i < 2; i++) pthread_join(thread[i], 0); pi_x = pi_x * 4; gettimeofday(&tv_end, &tz); unsigned duration = (tv_end.tv_sec * 1000 + tv_end.tv_usec / 1000) - (tv_start.tv_sec * 1000 + tv_start.tv_usec / 1000); printf("Pi is %1.32Lf, time was %u ms\\n", pi_x, duration); pthread_exit(0); exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int cant = 0; void* entrada(void *arg) { int i, r, ent; printf("Se abrieron las puertas.\\n"); for(i = 0; i < 50; i++) { pthread_mutex_lock(&mutex); r = (rand() % 10) + 1; ent = (rand() % 1); if(r > cant) { ent = 1; } if(ent) { cant += r; } else { cant -= r; } pthread_mutex_unlock(&mutex); printf("Personas en el jardín: %i\\n", cant); } } int main(int argc, char* argv[]) { pthread_t entradas_thread[2]; pthread_create(&entradas_thread[0], 0, entrada, 0); pthread_create(&entradas_thread[1], 0, entrada, 0); pthread_join(entradas_thread[0], 0); pthread_join(entradas_thread[1], 0); printf("Acabó el día, sacando a %i personas.\\n", cant); return 0; }
0
#include <pthread.h> struct pp_thread_info { int *msgcount; char *msg; int modval; pthread_mutex_t *mutex; pthread_cond_t *cv; }; void * pp_thread(void *arg) { struct pp_thread_info *infop; int c; infop = arg; while (1) { pthread_mutex_lock(infop->mutex); if (*infop->msgcount >= 100) break; while (*infop->msgcount % 2 == infop->modval) pthread_cond_wait(infop->cv, infop->mutex); printf("%s\\n", infop->msg); c = *infop->msgcount; sched_yield(); c = c + 1; *infop->msgcount = c; pthread_cond_broadcast(infop->cv); pthread_mutex_unlock(infop->mutex); sched_yield(); } pthread_mutex_unlock(infop->mutex); return (0); } int main(void) { pthread_t ping_id1, pong_id1; pthread_t ping_id2, pong_id2; pthread_mutex_t mutex; pthread_cond_t cv; struct pp_thread_info ping, pong; int msgcount; msgcount = 0; if (pthread_mutex_init(&mutex, 0) != 0) { fprintf(stderr, "Mutex init failed: %s\\n", strerror(errno)); exit(1); } if (pthread_cond_init(&cv, 0) != 0) { fprintf(stderr, "CV init failed: %s\\n", strerror(errno)); exit(1); } ping.msgcount = &msgcount; ping.msg = "ping"; ping.modval = 0; ping.mutex = &mutex; ping.cv = &cv; pong.msgcount = &msgcount; pong.msg = "pong"; pong.modval = 1; pong.mutex = &mutex; pong.cv = &cv; if ((pthread_create(&ping_id1, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id1, 0, &pp_thread, &pong) != 0) || (pthread_create(&ping_id2, 0, &pp_thread, &ping) != 0) || (pthread_create(&pong_id2, 0, &pp_thread, &pong) != 0)) { fprintf(stderr, "pingpong: pthread_create failed %s\\n", strerror(errno)); exit(1); } pthread_join(ping_id1, 0); pthread_join(pong_id1, 0); pthread_join(ping_id2, 0); pthread_join(pong_id2, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cv); printf("Main thread exiting\\n"); }
1
#include <pthread.h> pthread_t phil[5]; pthread_mutex_t chops[5]; void* func(int n) { int p= (n)%5; while(1){ printf("\\n Philosopher %d is thinking", n); pthread_mutex_lock(&chops[n-1]); pthread_mutex_lock(&chops[p]); printf("\\n Philosopher %d is eating using chops %d and %d",n,n-1,p); sleep(2); pthread_mutex_unlock(&chops[n-1]); pthread_mutex_unlock(&chops[p]); printf("\\n Philosopher %d finished eating",n); } } int main() { int i,k; char msg[10]; for(i=1;i<=5;i++) { k=pthread_mutex_init(&chops[i-1],0); if(k==-1) { printf("\\n Mutex Init failed"); exit(1); } } for(i=1;i<=5;i++) { k=pthread_create(&phil[i-1],0,func,i); if(k!=0) { printf("\\nThread creation error"); exit(0); } } for(i=1;i<=5;i++) {k= pthread_join(phil[i-1],(void*)&msg); if(k!=0) { printf("\\n Thread join failed"); exit(1); } } return 0;}
0
#include <pthread.h> int a[1000]; int global_index = 0; int sum = 0; pthread_mutex_t mutex1; void *slave(void *ignored) { int local_index, partial_sum = 0; do{ pthread_mutex_lock(&mutex1); local_index = global_index; global_index++; pthread_mutex_unlock(&mutex1); if(local_index < 1000) partial_sum += *(a + local_index); }while(local_index < 1000); return; } int main(int argc, char *argv[]) { MPI_Init(&argc, &argv); pthread_mutex_init(&mutex1, 0); int process_rank; int process_count; MPI_Comm_rank(MPI_COMM_WORLD, &process_rank); MPI_Comm_size(MPI_COMM_WORLD, &process_count); pthread_t thread[10]; int runs = 0; int result = 0; int total = 0; if(process_rank == 0) { printf("\\nFinding the sum from 1 to %d, using %d threads and 2 processes.", 1000, 10); for(runs = 0; runs < 1000; runs++) { a[runs] = runs + 1; } MPI_Send(&a, 1000, MPI_INT, 1, 0, MPI_COMM_WORLD); } if(process_rank == 1) { MPI_Recv(&a, 1000, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } if(process_rank == 0) { for(runs = 0; runs < 10; runs ++) { if(runs % 2 == 0) { if(pthread_create(&thread[runs], 0, slave, 0) != 0) perror("Pthread_create failed."); } } for(runs = 0; runs < 1000; runs += 2) { total += a[runs]; } } if(process_rank == 1) { for(runs = 0; runs < 10; runs ++) { if(runs % 2 == 1) { if(pthread_create(&thread[runs], 0, slave, 0) != 0) perror("Pthread_create failed."); } } for(runs = 1; runs < 1000; runs += 2) { result += a[runs]; } MPI_Send(&result, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); } if(process_rank == 0) { MPI_Recv(&result, 1, MPI_INT, 1, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); sum = result + total; printf("\\nTotal from even indexes (computed in process 0): %d\\nTotal from odd indexes (computed in process 1): %d", total, result); printf("\\nThe sum of 1 to %d is %d.\\n\\n", 1000, sum); } MPI_Finalize(); return 0; }
1
#include <pthread.h> int count = 0; int tnums[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_cv = PTHREAD_COND_INITIALIZER; void *change_count(void *idp){ int i; int my_id = *(int *)idp; int start = my_id; int stop = 60 + start; for (i=start; i < stop; i++) { pthread_mutex_lock(&count_mutex); if(i % 4 < 2) count++; else if(i % 4 == 2) count--; if (count == 27) { pthread_cond_signal(&count_cv); printf("inc_count: thread %d, count=%d Threshold reached.\\n", my_id, count); } printf("inc_count: thread %d, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); usleep((50)+random()%((200)-(50)+1)); } pthread_exit(0); } void *watch_count(void *idp){ int my_id = *(int *)idp; printf("Starting watch_count(): thread %d\\n", my_id); pthread_mutex_lock(&count_mutex); pthread_cond_wait(&count_cv, &count_mutex); printf("watch_count: thread %d Condition signal received.\\n", my_id); printf("watch_count: thread %d, count = %d.\\n", my_id, count); pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]){ int i; pthread_t tids[3]; pthread_mutex_init(&count_mutex, 0); pthread_create(&tids[2], 0, watch_count, (void *)&tnums[2]); pthread_create(&tids[0], 0, change_count, (void *)&tnums[0]); pthread_create(&tids[1], 0, change_count, (void *)&tnums[1]); for (i = 0; i < 3; i++) { pthread_join(tids[i], 0); } pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_cv); printf("\\nEnd of processing.\\n"); pthread_exit(0); }
0
#include <pthread.h> int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void *inc_count(void *t) { int i; long my_id = (long)t; for (i=0; i<10; i++) { pthread_mutex_lock(&count_mutex); count++; if (count == 12) { pthread_cond_signal(&count_threshold_cv); printf("inc_count(): thread %ld, count = %d Threshold reached.\\n", my_id, count); } printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n", my_id, count); pthread_mutex_unlock(&count_mutex); sleep(1); } pthread_exit(0); } void *watch_count(void *t) { long my_id = (long)t; printf("Starting watch_count(): thread %ld\\n", my_id); pthread_mutex_lock(&count_mutex); while (count<12) { pthread_cond_wait(&count_threshold_cv, &count_mutex); printf("watch_count(): thread %ld Condition signal received.\\n", my_id); count += 125; printf("watch_count(): thread %ld count now = %d.\\n", my_id, count); } pthread_mutex_unlock(&count_mutex); pthread_exit(0); } int main (int argc, char *argv[]) { int i, rc; long t1=1, t2=2, t3=3; pthread_t threads[3]; pthread_attr_t attr; pthread_mutex_init(&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, watch_count, (void *)t1); pthread_create(&threads[1], &attr, inc_count, (void *)t2); pthread_create(&threads[2], &attr, inc_count, (void *)t3); for (i=0; i<3; i++) { pthread_join(threads[i], 0); } printf ("Main(): Waited on %d threads. Done.\\n", 3); pthread_attr_destroy(&attr); pthread_mutex_destroy(&count_mutex); pthread_cond_destroy(&count_threshold_cv); pthread_exit(0); }
1
#include <pthread.h> static struct dlm_lksb lksb; static int use_threads = 0; static int quiet = 0; static pthread_cond_t cond; static pthread_mutex_t mutex; static int ast_called = 0; static int modetonum(char *modestr) { int mode = LKM_EXMODE; if (strncasecmp(modestr, "NL", 2) == 0) mode = LKM_NLMODE; if (strncasecmp(modestr, "CR", 2) == 0) mode = LKM_CRMODE; if (strncasecmp(modestr, "CW", 2) == 0) mode = LKM_CWMODE; if (strncasecmp(modestr, "PR", 2) == 0) mode = LKM_PRMODE; if (strncasecmp(modestr, "PW", 2) == 0) mode = LKM_PWMODE; if (strncasecmp(modestr, "EX", 2) == 0) mode = LKM_EXMODE; return mode; } static char *numtomode(int mode) { switch (mode) { case LKM_NLMODE: return "NL"; case LKM_CRMODE: return "CR"; case LKM_CWMODE: return "CW"; case LKM_PRMODE: return "PR"; case LKM_PWMODE: return "PW"; case LKM_EXMODE: return "EX"; default: return "??"; } } static void usage(char *prog, FILE *file) { fprintf(file, "Usage:\\n"); fprintf(file, "%s [mcnpquhV] <lockname>\\n", prog); fprintf(file, "\\n"); fprintf(file, " -V Show version of dlmtest\\n"); fprintf(file, " -h Show this help information\\n"); fprintf(file, " -m <mode> lock mode (default EX)\\n"); fprintf(file, " -c <mode> mode to convert to (default none)\\n"); fprintf(file, " -n don't block\\n"); fprintf(file, " -p Use pthreads\\n"); fprintf(file, " -u Don't unlock\\n"); fprintf(file, " -C Crash after lock\\n"); fprintf(file, " -q Quiet\\n"); fprintf(file, " -u Don't unlock explicitly\\n"); fprintf(file, "\\n"); } static void ast_routine(void *arg) { struct dlm_lksb *lksb = arg; if (!quiet) printf("ast called, status = %d, lkid=%x\\n", lksb->sb_status, lksb->sb_lkid); if (use_threads) { pthread_mutex_lock(&mutex); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); } else { ast_called = 1; } } static void bast_routine(void *arg) { struct dlm_lksb *lksb = arg; if (!quiet) printf("\\nblocking ast called, status = %d, lkid=%x\\n", lksb->sb_status, lksb->sb_lkid); } static int poll_for_ast() { struct pollfd pfd; pfd.fd = dlm_get_fd(); pfd.events = POLLIN; while (!ast_called) { if (poll(&pfd, 1, 0) < 0) { perror("poll"); return -1; } dlm_dispatch(pfd.fd); } ast_called = 0; return 0; } int main(int argc, char *argv[]) { char *resource = "LOCK-NAME"; int flags = 0; int delay = 0; int status; int mode = LKM_EXMODE; int convmode = -1; int do_unlock = 1; int do_crash = 0; signed char opt; opterr = 0; optind = 0; while ((opt=getopt(argc,argv,"?m:nqupc:d:CvV")) != EOF) { switch(opt) { case 'h': usage(argv[0], stdout); exit(0); case '?': usage(argv[0], stderr); exit(0); case 'm': mode = modetonum(optarg); break; case 'c': convmode = modetonum(optarg); break; case 'p': use_threads++; break; case 'n': flags |= LKF_NOQUEUE; break; case 'q': quiet = 1; break; case 'u': do_unlock = 0; break; case 'C': do_crash = 1; break; case 'd': delay = atoi(optarg); break; case 'V': printf("\\nasttest version 0.1\\n\\n"); exit(1); break; } } if (argv[optind]) resource = argv[optind]; if (!quiet) fprintf(stderr, "locking %s %s %s...", resource, numtomode(mode), (flags&LKF_NOQUEUE?"(NOQUEUE)":"")); fflush(stderr); if (use_threads) { pthread_cond_init(&cond, 0); pthread_mutex_init(&mutex, 0); pthread_mutex_lock(&mutex); dlm_pthread_init(); } status = dlm_lock(mode, &lksb, flags, resource, strlen(resource), 0, ast_routine, &lksb, bast_routine, 0); if (status == -1) { if (!quiet) fprintf(stderr, "\\n"); perror("lock"); return -1; } printf("(lkid=%x)", lksb.sb_lkid); if (do_crash) *(int *)0 = 0xdeadbeef; if (use_threads) pthread_cond_wait(&cond, &mutex); else poll_for_ast(); if (delay) sleep(delay); if (!quiet) { fprintf(stderr, "unlocking %s...", resource); fflush(stderr); } if (do_unlock) { status = dlm_unlock(lksb.sb_lkid, 0, &lksb, &lksb); if (status == -1) { if (!quiet) fprintf(stderr, "\\n"); perror("unlock"); return -1; } if (use_threads) pthread_cond_wait(&cond, &mutex); else poll_for_ast(); } return 0; }
0