text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t non_full; pthread_cond_t non_empty; int elemsInQueue; int maxSize; int countElems; int id; void argsNotValid(){ fprintf(stderr, "[ERROR][process_manager] Arguments not valid.\\n"); } void errorInPM(int id){ fprintf(stderr,"[ERROR][process_manager] There was an error executing process_manager with id: %d.\\n", id); } int checkArgs(int i, const char * semName, const char * number){ if(i == 2){ if(semName[0] == '\\0'){ return 0; } } else{ return isNumber(number); } } int isNumber(const char arg[]){ int i = 0; if (arg[1] == '-'){ return 0; } for (i; arg[i] != 0; i++){ if (!isdigit(arg[i])){ return 0; } } return 1; } void * producer(void *threadid){ int i = 0; int elemsProduced = 0; for(i = 0; i < countElems; i++){ struct element * elem; elem->num_edition = i; elem->id_belt = id; if(i + 1 == countElems){ elem->last = 1; } else{ elem->last = 0; } pthread_mutex_lock(&mutex); while(queue_full()){ pthread_cond_wait(&non_full, &mutex); pthread_cond_signal(&non_empty); } queue_put(elem); if(elem->last){ pthread_cond_wait(&non_full, &mutex); } pthread_cond_signal(&non_empty); pthread_mutex_unlock(&mutex); } long tid = pthread_self(); return 0; } void * consumer(void *threadid){ struct element * elem; int i; do{ pthread_mutex_lock(&mutex); while(queue_empty()){ pthread_cond_wait(&non_empty, &mutex); } elem = queue_get(); if(elem == 0){ printf("Failed to get the element from the queue\\n"); } else if(elem->last == 1){ printf("[OK][process_manager] Process_manager with id: %d has produced %d elements.\\n", id, countElems); } pthread_cond_signal(&non_full); pthread_mutex_unlock(&mutex); } while(elem->last == 0); long tid = pthread_self(); return 0; } int main (int argc, const char * argv[] ){ int i; const char * semName; int boolean; int value; sem_t *sem; void *end; id = *argv[0] - '0'; semName = argv[1]; maxSize = *argv[2] - '0'; countElems = *argv[3] - '0'; if(maxSize < 0 || id < 0 || countElems < 0){ argsNotValid(); return -1; } boolean = 1; for(i = 0; i < argc - 1; i+=2){ boolean = checkArgs(i, semName, argv[i]); if(!boolean){ argsNotValid(); return -1; } } if ( (sem = sem_open(semName, 0)) == SEM_FAILED){ printf("Process_manager failed to open semaphore: %s\\n", semName); } printf("[OK][process_manager] Process_manager with id: %d waiting to produce %d elements.\\n", id, countElems); sem_wait(sem); boolean = queue_init(maxSize); if(boolean != 0){ errorInPM(id); return -1; } printf("[OK][process_manager] Belt with id: %d has been created with a maximum of %d elements.\\n", id, maxSize); sem_post(sem); pthread_t t_producer, t_consumer; if(pthread_create(&t_producer, 0, (void*)producer, pthread_self)){ printf("Failed to create the producer thread\\n"); fflush(stdout); } if(pthread_create(&t_consumer, 0, (void*)consumer, pthread_self)){ printf("Failed to create the consumer thread\\n"); fflush(stdout); } pthread_join(t_consumer, &end); printf("Join Consumer\\n"); pthread_join(t_producer, &end); printf("Join Producer\\n"); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&non_full); pthread_cond_destroy(&non_empty); boolean = queue_destroy(); if (boolean != 0){ errorInPM(id); return -1; } return 0; }
1
#include <pthread.h> struct dmove { int src; int dst; }; static pthread_mutex_t m; struct record { struct dmove *moves; int capacity; int size; int pos; int forward; }; struct record *record_create(int capacity) { struct record *l = malloc(sizeof(struct record)); l->moves = malloc(sizeof(struct dmove) * capacity); l->capacity = capacity; l->size = 0; l->pos = -1; l->forward = 1; return l; } void record_free(struct record *l) { free(l->moves); free(l); } int record_add(struct record *l, int src, int dst) { pthread_mutex_lock(&m); if (l->size < l->capacity) { l->moves[l->size].src = src; l->moves[l->size].dst = dst; ++l->size; pthread_mutex_unlock(&m); return 1; } pthread_mutex_unlock(&m); return 0; } int record_next(struct record *l) { if (record_is_end(l)) return 0; ++l->pos; l->forward = 1; return 1; } int record_previous(struct record *l) { if (record_is_begin(l)) return 0; --l->pos; l->forward = 0; return 1; } int record_is_end(struct record *l) { pthread_mutex_lock(&m); int b = l->pos >= l->size - 1; pthread_mutex_unlock(&m); return b; } int record_is_begin(struct record *l) { return l->pos < 0; } int record_pos_is_valid(struct record *l) { pthread_mutex_lock(&m); int b = l->pos >= -1 && l->pos < l->size; pthread_mutex_unlock(&m); return b; } int record_get_current_src(struct record *l) { if (record_pos_is_valid(l) && l->forward) return l->moves[l->pos].src; return -1; } int record_get_current_dest(struct record *l) { if (record_pos_is_valid(l) && l->forward) return l->moves[l->pos].dst; return -1; } int record_get_rewind_src(struct record *l) { if (record_pos_is_valid(l) && l->forward == 0) return l->moves[l->pos + 1].dst; return -1; } int record_get_rewind_dest(struct record *l) { if (record_pos_is_valid(l) && l->forward == 0) return l->moves[l->pos + 1].src; return -1; }
0
#include <pthread.h> struct releve { char dateTime[sizeof "JJ/MM/AAAA HH:MM:SS"]; int temperature; } releve; time_t now; struct tm tm_now; pthread_t tacheReleve,tacheR1; pthread_attr_t tacheReleve_attr,tacheR1_attr; sem_t semR1; pthread_mutex_t mutexReleve; struct releve rel; FILE *f; int fdTimer; int flagFin = 0; void stop(){ flagFin = 1; } int createPosixTask(char * nomTache, int priorite, int taillePile,int periode, pthread_t *tache, pthread_attr_t *tache_attr, void*(*codeTache)(void*)){ pthread_attr_init(tache_attr); pthread_attr_setstacksize(tache_attr,taillePile); pthread_attr_setschedpolicy(tache_attr,SCHED_FIFO); struct sched_param tache_param = {.sched_priority = priorite}; pthread_attr_setschedparam(tache_attr, &tache_param); pthread_attr_setdetachstate(tache_attr,PTHREAD_CREATE_JOINABLE); if(periode !=0){ struct timespec currentTime; if(clock_gettime(CLOCK_MONOTONIC,&currentTime)){ printf("Erreur lors de la recuperation du temps courant! \\n"); exit(1); } if((fdTimer = timerfd_create(CLOCK_MONOTONIC ,0)) == -1){ printf("Erreur lors de la creation du timer ! \\n "); exit(1); } struct itimerspec conftimer; if(periode >= 1000000){ conftimer.it_interval.tv_sec = periode/1000000; conftimer.it_interval.tv_nsec = periode%1000000; }else{ conftimer.it_interval.tv_sec = 0; conftimer.it_interval.tv_nsec = periode*1000; } currentTime.tv_sec += 1; conftimer.it_value = currentTime; if(timerfd_settime(fdTimer,TFD_TIMER_ABSTIME,&conftimer,0)){ printf("Erreur impossible de demarrer le timer! \\n"); exit(1); } } if((pthread_create(tache,tache_attr,(void*(*)(void*))codeTache,(void*)0)!=0)){ printf("Erreur de creation du thread ! \\n"); exit(1); } } void waitPeriod(){ uint64_t topstimer; if(read(fdTimer,&topstimer,sizeof(topstimer))<0){ printf("Attend sur timer echoue ! \\n"); }else{ if(topstimer > 1){ printf("periode marquee pour le thread nb : %lu \\n", (long unsigned int)topstimer); } } } void* codeReleve(void* arg){ int cpt = 1; while(!flagFin){ waitPeriod(); time_t date_actuelle; now = time (0); tm_now = *localtime (&now); pthread_mutex_lock(&mutexReleve); strftime (releve.dateTime, sizeof releve.dateTime, "%d/%m/%Y %H:%M:%S", &tm_now); rel.temperature = rand()%40; pthread_mutex_unlock(&mutexReleve); sem_post(&semR1); } return 0; } void * codeEcriture(void * arg){ while(!flagFin){ sem_wait(&semR1); pthread_mutex_lock(&mutexReleve); fprintf(f, " %s | temperature: %d °C\\n", releve.dateTime, rel.temperature); printf(" %s | temperature: %d °C\\n", releve.dateTime, rel.temperature); pthread_mutex_unlock(&mutexReleve); } return 0; } int main(){ f = fopen("resultat.txt", "w"); if (f == 0){ printf("Erreur dans l'ouverture du fichier\\n"); exit(1); } mlockall(MCL_CURRENT | MCL_FUTURE); if((sem_init(&semR1,0,0)) == -1){ printf("impossible de creer sem1 \\n"); exit(1); } if((pthread_mutex_init(&mutexReleve,0)!=0)){ printf("Erreur lors de l'initialisation du mutex \\n"); exit(1); } if((createPosixTask("Ecriture",2,200,0,&tacheR1,&tacheR1_attr,codeEcriture)!=0)){ printf("Erreur creation tache ecriture fichier \\n"); exit(1); } if((createPosixTask("Releve",3,200,500000,&tacheReleve,&tacheReleve_attr,codeReleve)!=0)){ printf("Erreur creation tache de releve temperature \\n"); exit(1); } signal(SIGINT,stop); pause(); flagFin = 1; pthread_join(tacheR1,0); pthread_join(tacheReleve,0); sem_destroy(&semR1); pthread_mutex_destroy(&mutexReleve); fclose(f); printf("Fermeture du programme \\n"); return 0; }
1
#include <pthread.h> static void init_notification_thread_command(struct notification_thread_command *cmd) { memset(cmd, 0, sizeof(*cmd)); CDS_INIT_LIST_HEAD(&cmd->cmd_list_node); lttng_waiter_init(&cmd->reply_waiter); } static int run_command_wait(struct notification_thread_handle *handle, struct notification_thread_command *cmd) { int ret; uint64_t notification_counter = 1; pthread_mutex_lock(&handle->cmd_queue.lock); cds_list_add_tail(&cmd->cmd_list_node, &handle->cmd_queue.list); ret = write(handle->cmd_queue.event_fd, &notification_counter, sizeof(notification_counter)); if (ret < 0) { PERROR("write to notification thread's queue event fd"); cds_list_del(&cmd->cmd_list_node); goto error_unlock_queue; } pthread_mutex_unlock(&handle->cmd_queue.lock); lttng_waiter_wait(&cmd->reply_waiter); return 0; error_unlock_queue: pthread_mutex_unlock(&handle->cmd_queue.lock); return -1; } enum lttng_error_code notification_thread_command_register_trigger( struct notification_thread_handle *handle, struct lttng_trigger *trigger) { int ret; enum lttng_error_code ret_code; struct notification_thread_command cmd; init_notification_thread_command(&cmd); cmd.type = NOTIFICATION_COMMAND_TYPE_REGISTER_TRIGGER; cmd.parameters.trigger = trigger; ret = run_command_wait(handle, &cmd); if (ret) { ret_code = LTTNG_ERR_UNK; goto end; } ret_code = cmd.reply_code; end: return ret_code; } enum lttng_error_code notification_thread_command_unregister_trigger( struct notification_thread_handle *handle, struct lttng_trigger *trigger) { int ret; enum lttng_error_code ret_code; struct notification_thread_command cmd; init_notification_thread_command(&cmd); cmd.type = NOTIFICATION_COMMAND_TYPE_UNREGISTER_TRIGGER; cmd.parameters.trigger = trigger; ret = run_command_wait(handle, &cmd); if (ret) { ret_code = LTTNG_ERR_UNK; goto end; } ret_code = cmd.reply_code; end: return ret_code; } enum lttng_error_code notification_thread_command_add_channel( struct notification_thread_handle *handle, char *session_name, uid_t uid, gid_t gid, char *channel_name, uint64_t key, enum lttng_domain_type domain, uint64_t capacity) { int ret; enum lttng_error_code ret_code; struct notification_thread_command cmd; init_notification_thread_command(&cmd); cmd.type = NOTIFICATION_COMMAND_TYPE_ADD_CHANNEL; cmd.parameters.add_channel.session_name = session_name; cmd.parameters.add_channel.uid = uid; cmd.parameters.add_channel.gid = gid; cmd.parameters.add_channel.channel_name = channel_name; cmd.parameters.add_channel.key.key = key; cmd.parameters.add_channel.key.domain = domain; cmd.parameters.add_channel.capacity = capacity; ret = run_command_wait(handle, &cmd); if (ret) { ret_code = LTTNG_ERR_UNK; goto end; } ret_code = cmd.reply_code; end: return ret_code; } enum lttng_error_code notification_thread_command_remove_channel( struct notification_thread_handle *handle, uint64_t key, enum lttng_domain_type domain) { int ret; enum lttng_error_code ret_code; struct notification_thread_command cmd; init_notification_thread_command(&cmd); cmd.type = NOTIFICATION_COMMAND_TYPE_REMOVE_CHANNEL; cmd.parameters.remove_channel.key = key; cmd.parameters.remove_channel.domain = domain; ret = run_command_wait(handle, &cmd); if (ret) { ret_code = LTTNG_ERR_UNK; goto end; } ret_code = cmd.reply_code; end: return ret_code; } void notification_thread_command_quit( struct notification_thread_handle *handle) { int ret; struct notification_thread_command cmd; init_notification_thread_command(&cmd); cmd.type = NOTIFICATION_COMMAND_TYPE_QUIT; ret = run_command_wait(handle, &cmd); assert(!ret && cmd.reply_code == LTTNG_OK); }
0
#include <pthread.h> pthread_mutex_t forks[5] ; void *sim(void *p) { int i = (int)p; while(1) { printf("Philosopher %d is hungry\\n",i); if(i == 4) { pthread_mutex_lock(&forks[0]); printf("Philosopher %d taking right fork\\n",i); sleep(1); if(pthread_mutex_trylock(&forks[4])) { pthread_mutex_unlock(&forks[0]); printf("Philosopher %d returning right fork\\n",i); } else { printf("Philosopher %d taking left fork\\n",i); sleep(1); printf("Philosopher %d eating\\n",i); sleep(1); pthread_mutex_unlock(&forks[0]); printf("Philosopher %d returning right fork\\n",i); pthread_mutex_unlock(&forks[4]); printf("Philosopher %d returning left fork\\n",i); printf("Philosopher %d is thinking\\n",i); sleep(1); } } else { pthread_mutex_lock(&forks[i]); printf("Philosopher %d taking left fork\\n",i); sleep(1); if(pthread_mutex_trylock(&forks[(i+1)%5])) { pthread_mutex_unlock(&forks[i]); printf("Philosopher %d returning left fork\\n",i); } else { printf("Philosopher %d taking right fork\\n",i); sleep(1); printf("Philosopher %d eating\\n",i); sleep(1); pthread_mutex_unlock(&forks[i]); sleep(1); printf("Philosopher %d returning left fork\\n",i); pthread_mutex_unlock(&forks[(i+1)%5]); printf("Philosopher %d returning right fork\\n",i); printf("Philosopher %d is thinking\\n",i); sleep(1); } } } } int main() { int i; pthread_t philosopher[5]; for(i=0;i<5;++i) { pthread_mutex_unlock(&forks[i]); } for(i=0;i<5;++i) pthread_create(&philosopher[i],0,sim, (void *)i); for(i=0;i<5;++i) pthread_join(philosopher[i],0); return 0; }
1
#include <pthread.h> extern int random_utime(void); pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t status; int activity[5]; int activity_counter_eat[5]; enum { THINK, HUNGRY, EAT } state_t; void pick_fork(int* id) { pthread_mutex_lock(&mutex); activity[*id] = HUNGRY; printf("PHILOSOPHER %d IS %s\\n",*id,"HUNGRY"); if(activity[(*id+1)%5]!= EAT && activity[(*id+5 -1)%5]!=EAT) { activity [*id]=EAT; printf("PHILOSOPHER %d IS %s\\n",*id,"PICKING LEFT FORK"); printf("PHILOSOPHER %d IS %s\\n",*id,"PICKING RIGHT FORK"); printf("PHILOSOPHER %d IS %s\\n",*id,"EATING"); activity_counter_eat[*id]++; } else { printf("PHILOSOPHER %d IS %s\\n",*id,"WAITING"); pthread_cond_wait(&status,&mutex); } pthread_mutex_unlock(&mutex); } void put_fork(int* id) { pthread_mutex_lock(&mutex); activity[*id]=THINK; printf("PHILOSOPHER %d IS %s\\n",*id,"THINKING"); pthread_cond_signal(&status); pthread_mutex_unlock(&mutex); } void* dine(void* id) { int* i; i =(int*) id; printf("PHILOSOPHER %d IS %s\\n",*i,"SITTING AT TABLE, SAYS HELLO!!!"); while(1) { do { if(activity_counter_eat[*i]==5) goto Exit; pick_fork(i); } while (activity[*i] == HUNGRY); put_fork(i); usleep(random_utime()); } Exit: printf("PHILOSOPHER %d IS %s\\n",*i,"LEAVING THE TABLE,SAYS BYE!!!"); pthread_exit(0); } int main () { int rc =0; int j =0; int ret_val=0; int arg=0; pthread_t p_thread_id[5]; int eat_stats_id[5]; int p_id[5]; for(j=0;j< 5;j++) { p_id[j]=j; rc = pthread_create(&p_thread_id[j], 0, &dine, &p_id[j]); if(rc!=0) printf("Error Thread Creation"); } for(j=0;j<5;j++) { pthread_join(p_thread_id[j],0); } pthread_exit(0); return (0); }
0
#include <pthread.h> void *thread_work(void* arg){ DBG_PRINT("thread_work ----------------- %s\\n",arg); char thread_name[MAX_NAME_LEN]; strcpy(thread_name,arg); while(1) { struct msgQueue_msg* msg = 0; struct msgQueue * mq ; mq = gMsgQueue_get_msgQueue(); if(mq!=0){ msg = msgQueue_get_msg(mq); if(msg!=0){ DBG_PRINT("%s,get msg msg->msgData->code = %d \\n",thread_name,msg->msgData->code); if(mq->cb != 0){ mq->cb(msg->source,msg->msgData); } msgQueue_release_msg(msg); }else{ DBG_PRINT("%s,get msg --!!!!!---------- \\n",thread_name); } }else{ pthread_mutex_lock(&sysenv_mutex); pthread_cond_wait(&sysenv_cond, &sysenv_mutex); pthread_mutex_unlock(&sysenv_mutex); } } } void mysysenv_resumework(){ pthread_mutex_lock(&sysenv_mutex); pthread_cond_broadcast(&sysenv_cond); pthread_mutex_unlock(&sysenv_mutex); } void mysysenv_init(){ msgModule_init(); myhandle_init(); myservice_init(); } void mysysenv_startwork(){ DBG_PRINT("enter mysysenv_startwork\\n"); pthread_t th[WORK_THREAD_NUM]; pthread_mutex_init(&sysenv_mutex,0); pthread_cond_init(&sysenv_cond,0); int i; for (i=0;i<WORK_THREAD_NUM;i++){ char str[MAX_NAME_LEN]; sprintf(str, "thread-%d" , i); pthread_create(&th[i],0,thread_work,str); sleep(1); } for (i=0;i<WORK_THREAD_NUM;i++){ pthread_join(th[i],0); } }
1
#include <pthread.h> extern char **environ; pthread_mutex_t lock; void *threadFunc(void *arg) { pthread_mutex_lock(&lock); printf("Acquired lock!\\n"); char *str; str=(char*)arg; const char *cmd = "sudo gatttool -b C4:4F:B7:B1:41:D7 --char-write-req --handle=0x000f --value=0100 --listen"; FILE *ble_listen = popen(cmd, "r"); printf("Connected\\n"); char buf[1024]; while (fgets(buf, sizeof(buf), ble_listen) != 0) { printf("%s\\n", buf); } pclose(ble_listen); printf("Disconnected\\n"); pthread_mutex_unlock(&lock); return 0; } int main(int argc, char *argv[]) { int whitelistSize = getWhitelistSize(); char *whitelist[whitelistSize]; int i = 0; int status; int pid[whitelistSize]; pid_t wpid; pthread_t tID[whitelistSize]; getListWhitelistMAC(whitelistSize, whitelist); printf("Whitelist size: %d\\n", whitelistSize); int err; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } for (i=0; i < whitelistSize; i++) { printf("Creating thread %d\\n", i); err = pthread_create(&(tID[i]),0,threadFunc, "hello world"); } pthread_join((tID[0]), 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> static void write_cancel(void*); static void read_cancel(void*); void rw_init(struct rwlock *L) { L->readers_active = 0; L->readers_wait = 0; L->writers_wait = 0; L->writers_active = 0; pthread_mutex_init(&L->mutex, 0); pthread_cond_init(&L->read, 0); pthread_cond_init(&L->write, 0); L->valid = VALID; } void rw_writer_lock(struct rwlock *L) { int response; if (L->valid != VALID) return; response = pthread_mutex_lock(&L->mutex); if (response != 0) return; if (L->writers_active || L->readers_active > 0) { L->writers_wait++; pthread_cleanup_push (write_cancel, (void*)L); while (L->writers_active || L->readers_active > 0) { response = pthread_cond_wait(&L->write, &L->mutex); if (response != 0) break; } pthread_cleanup_pop(0); L->writers_wait--; } if (response == 0) L->writers_active = 1; pthread_mutex_unlock(&L->mutex); } void rw_writer_unlock(struct rwlock *L) { int response; if (L->valid != VALID) return; response = pthread_mutex_lock(&L->mutex); if (response != 0) return; L->writers_active = 0; if (L->readers_wait > 0) { response = pthread_cond_broadcast(&L->read); if (response != 0) { pthread_mutex_unlock(&L->mutex); return; } } else if (L->writers_wait > 0) { response = pthread_cond_signal(&L->write); if (response != 0) { pthread_mutex_unlock(&L->mutex); return; } } pthread_mutex_unlock(&L->mutex); } void rw_reader_lock(struct rwlock *L) { int response; if (L->valid != VALID) return; response = pthread_mutex_lock(&L->mutex); if (response != 0) return; if (L->writers_active) { L->readers_wait++; pthread_cleanup_push (read_cancel, (void*)L); while (L->writers_active) { response = pthread_cond_wait(&L->read, &L->mutex); if (response != 0) break; } pthread_cleanup_pop(0); L->readers_wait--; } if (response == 0) L->readers_active++; pthread_mutex_unlock(&L->mutex); } void rw_reader_unlock(struct rwlock *L) { int response; if (L->valid != VALID) return; response = pthread_mutex_lock(&L->mutex); if (response != 0) return; L->readers_active--; if (L->readers_active == 0 && L->writers_wait > 0) response = pthread_cond_signal(&L->write); pthread_mutex_unlock(&L->mutex); } void rw_destroy(struct rwlock *L) { int response; if (L->valid != VALID) return; response = pthread_mutex_lock(&L->mutex); if (response != 0) return; if (L->readers_active > 0 || L->writers_active) { pthread_mutex_unlock(&L->mutex); return; } if (L->readers_wait != 0 || L->writers_wait != 0) { pthread_mutex_unlock(&L->mutex); return; } L->valid = INVALID; response = pthread_mutex_unlock(&L->mutex); if (response != 0) return; pthread_mutex_destroy(&L->mutex); pthread_cond_destroy(&L->read); pthread_cond_destroy(&L->write); } static void write_cancel(void *param) { struct rwlock *l = (struct rwlock *) param; l->writers_wait--; pthread_mutex_unlock(&l->mutex); } static void read_cancel(void *param) { struct rwlock *l = (struct rwlock *) param; l->readers_wait--; pthread_mutex_unlock(&l->mutex); }
1
#include <pthread.h> int a=0; pthread_mutex_t lock; void *func1(void *arg) { pthread_mutex_lock(&lock); a=1; sleep(1); printf("%s-%d\\n",__func__,a); pthread_mutex_unlock(&lock); } void *func2(void *arg) { pthread_mutex_lock(&lock); a=2; printf("%s-%d\\n",__func__,a); pthread_mutex_unlock(&lock); } void *func3(void *arg) { pthread_mutex_lock(&lock); a=3; printf("%s-%d\\n",__func__,a); pthread_mutex_unlock(&lock); } void *func4(void *arg) { pthread_mutex_lock(&lock); a=4; printf("%s-%d\\n",__func__,a); pthread_mutex_unlock(&lock); } void *func5(void *arg) { pthread_mutex_lock(&lock); a=5; printf("%s-%d\\n",__func__,a); pthread_mutex_unlock(&lock); } int main() { pthread_mutex_init(&lock,0); pthread_t pid1,pid2,pid3,pid4,pid5; pthread_create(&pid1,0,func1,0); pthread_create(&pid2,0,func2,0); pthread_create(&pid3,0,func3,0); pthread_create(&pid4,0,func4,0); pthread_create(&pid5,0,func5,0); pthread_join(pid1,0); pthread_join(pid2,0); pthread_join(pid3,0); pthread_join(pid4,0); pthread_join(pid5,0); pthread_mutex_destroy(&lock); }
0
#include <pthread.h> static pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond=PTHREAD_COND_INITIALIZER; struct node { int n_number; struct node *n_next; } *head=0; static void cleanup_handler(void* arg) { printf("Clean up handler of second thread.\\n"); free(arg); (void)pthread_mutex_unlock(&mtx); } static void *thread_func(void *arg) { struct node* p = 0; pthread_cleanup_push(cleanup_handler, p); pthread_mutex_lock(&mtx); while(1) { while( head == 0 ) { pthread_cond_wait(&cond,&mtx); } p=head; head=head->n_next; printf("Got%dfromfrontofqueue\\n",p->n_number); free(p); } pthread_mutex_unlock(&mtx); pthread_cleanup_pop(0); return 0; } int main(void) { int i; pthread_t tid; struct node *p; pthread_create(&tid, 0, thread_func, 0); for(i=0; i<10; i++) { p=(struct node*)malloc(sizeof(struct node)); p->n_number=i; pthread_mutex_lock(&mtx); p->n_next=head; head=p; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); sleep(1); } printf("thread1wannaendthecancelthread2.\\n"); pthread_cancel(tid); pthread_join(tid,0); printf("Alldone--exiting\\n"); return 0; }
1
#include <pthread.h> extern void __VERIFIER_error() ; int __VERIFIER_nondet_int(void); void ldv_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; } pthread_t t1; pthread_mutex_t mutex; int pdev; void *thread1(void *arg) { pthread_mutex_lock(&mutex); pdev = 6; ldv_assert(pdev==6); pthread_mutex_unlock(&mutex); } int module_init() { pthread_mutex_init(&mutex, 0); pdev = 1; ldv_assert(pdev==1); if(__VERIFIER_nondet_int()) { pthread_create(&t1, 0, thread1, 0); return 0; } pdev = 3; ldv_assert(pdev==3); pthread_mutex_destroy(&mutex); return -1; } void module_exit() { void *status; pthread_join(t1, &status); pthread_mutex_destroy(&mutex); pdev = 5; ldv_assert(pdev==5); } int main(void) { if(module_init()!=0) goto module_exit; module_exit(); module_exit: return 0; }
0
#include <pthread.h> { pthread_cond_t c; pthread_mutex_t m; }cond_mutex_t; cond_mutex_t cm = { PTHREAD_COND_INITIALIZER, PTHREAD_MUTEX_INITIALIZER }; static void * wait_thread(void * param); static void * worker_thread(void * param); pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static int count = 0; static int data[6]; unsigned int seed; volatile int quit = 0; int main(int argc, char ** argv) { int rc; int i; pthread_t th[(4) + 1]; seed = time(0); void * ret_code = 0; rc = pthread_create(&th[0], 0, wait_thread, 0); if(0 != rc) { perror("pthread_create"); exit(1); } usleep(5000); for(i = 1; i <= (4); ++i) { rc = pthread_create(&th[i], 0, worker_thread, 0); if(0 != rc) { perror("pthread_create"); exit(1); } } char c = 0; printf("press enter to quit.\\n"); while(1) { scanf("%c", &c); if(c == '\\n') break; } quit = 1; pthread_cond_broadcast(&cm.c); pthread_join(th[0], &ret_code); for(i = 1; i <= (4); ++i) { pthread_join(th[i], &ret_code); } rc = (int)(long)ret_code; pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cm.c); pthread_mutex_destroy(&cm.m); return rc; } static void * worker_thread(void * param) { while(!quit) { pthread_mutex_lock(&mutex); if(quit) { pthread_mutex_unlock(&mutex); break; } if(count == 6) { printf("正在与【等待线程】争抢资源...\\n"); pthread_mutex_unlock(&mutex); usleep(10000); continue; } if(count > 6) { fprintf(stderr, "同步的逻辑出现问题,请检查源代码。\\n"); printf("请按回车建退出...\\n"); quit = 1; pthread_mutex_unlock(&mutex); break; } data[count++] = rand_r(&seed) % 1000; if(count == 6) { pthread_mutex_lock(&cm.m); pthread_cond_signal(&cm.c); pthread_mutex_unlock(&cm.m); } pthread_mutex_unlock(&mutex); usleep(100000); } pthread_exit((void *)(long)0); } static void * wait_thread(void * param) { int i, sum; pthread_mutex_lock(&cm.m); while(!quit) { pthread_cond_wait(&cm.c, &cm.m); if(quit) break; pthread_mutex_lock(&mutex); sum = 0; printf("average = ("); for(i = 0; i < 6; ++i) { sum += data[i]; printf(" %3d ", data[i]); if(i < (6 - 1)) printf("+"); } printf(") / %d = %.2f\\n", 6, (double)sum / (double)6); count = 0; pthread_mutex_unlock(&mutex); } pthread_mutex_unlock(&cm.m); pthread_exit((void *)(long)0); }
1
#include <pthread.h> struct Thread *threads = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static int JobCount = 0; static struct Job * head = 0; static struct Job * tail = 0; static int threadStatus = 0; void InitThreads() { int i = 0; int err = 0; threadStatus = 1; pthread_t tid; threads = (struct Thread *)malloc(sizeof(struct Thread) * 3); for (; i < 3; ++i) { err = pthread_create(&tid, 0, ThreadEntry, 0); assert(err == 0); threads[i].tid = tid; } } void * ThreadEntry(void *arg) { struct Job *job = 0; printf("thread create success, going loop!\\n"); while (1) { pthread_mutex_lock(&mutex); while (JobCount <= 0 && (threadStatus == 1)) { pthread_cond_wait(&cond, &mutex); } if (threadStatus == 0) { pthread_mutex_unlock(&mutex); break; } job = head; head = head->next; JobCount--; if (head == 0) { tail = 0; } pthread_mutex_unlock(&mutex); DoJob(job); FreeJob(job); job = 0; } return 0; } void FinitThread() { pthread_mutex_lock(&mutex); threadStatus = 0; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); int i = 0; for (;i < 3; ++i) { pthread_join(threads[i].tid, 0); } pthread_mutex_lock(&mutex); while (head != 0) { FreeJob(head); head = head->next; } pthread_mutex_unlock(&mutex); free(threads); } void EnqueJob(struct Job *job) { pthread_mutex_lock(&mutex); if (tail == 0) { head = job; tail = job; } else { tail->next = job; tail = job; } tail->next = 0; JobCount++; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> enum {sta_chk = 1, sta_err, sta_ter, sta_rd, sta_rec, sta_wr, sta_eof}; static int fd_sock = -1; static int stop = 0; static FILE *msg_fp = 0; static pthread_mutex_t rec_mut = PTHREAD_MUTEX_INITIALIZER; static int resend = 0; static int time_to_exit = TIME_TO_EXIT; static int send_msg(int fd_req, struct msg_st *msg) { struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(REQPT); inet_pton(AF_INET, SERVER, &server_addr.sin_addr); while (sendto(fd_req, msg, sizeof(*msg), 0, (void *)&server_addr, sizeof(server_addr)) == -1) { if (errno != EINTR) return -1; } return 0; } static FILE *open_check(int fd_sock, const char *filename, const char *newfile, int wrflag, struct msg_st *msg) { FILE *fp; if (wrflag == 'w') { fp = fopen(newfile, "w"); msg->msg_len = 0; } else if (wrflag == 'a') { fp = fopen(newfile, "a"); fseeko(fp, 0, 2); msg->msg_len = ftello(fp); fseeko(fp, 0, 0); } else return 0; if (fp == 0) return 0; msg->mtype = htons(REQ); memset((char *)(msg->content), 0, MAXLEN); strncpy((char *)(msg->content), filename, MAXLEN); if (send_msg(fd_sock, msg) != 0) { fclose(fp); return 0; } return fp; } static int write_data(const struct msg_st *msg, FILE *fp) { int ret; ret = fwrite(msg->content, 1, ntohl(msg->msg_len), fp); if (ret != ntohl(msg->msg_len)) { return ferror(fp); } return 0; } static void *re_send(void *arg) { struct msg_st *msg = arg; struct timeval tim; tim.tv_usec = 0; while (time_to_exit > 0) { tim.tv_sec = TIME_TO_EXIT - time_to_exit + 1; select(0, 0, 0, 0, &tim); pthread_mutex_lock(&rec_mut); if (resend) { send_msg(fd_sock, msg); fprintf(stderr, "time out, resend.\\n"); } time_to_exit--; if (time_to_exit == 0) { fprintf(stderr, "time_out, exit....\\n"); stop = 1; kill(getpid(), SIGINT); } pthread_mutex_unlock(&rec_mut); } pthread_exit(0); } static void rec_file(int fd_sock, const char *filename, const char *newfile, int wrflag) { int status = sta_chk, ret; int started = 0; struct msg_st msg; pthread_t pth_timer; pthread_create(&pth_timer, 0, re_send, &msg); pthread_detach(pth_timer); while (!stop) { started = 1; switch (status) { case sta_chk: msg_fp = open_check(fd_sock, filename, newfile, wrflag, &msg); status = (msg_fp == 0 ? sta_err : sta_rd); break; case sta_err: fprintf(stderr,"check file %s failed: %s\\n",filename, msg.content); status = sta_ter; break; case sta_ter: stop = 1; break; case sta_rd: if (recvfrom(fd_sock, &msg,sizeof(msg), 0, 0, 0) == -1) { status = (errno == EINTR ? sta_rd : sta_ter); break; } pthread_mutex_lock(&rec_mut); resend = 0; pthread_mutex_unlock(&rec_mut); if ((int)ntohl(msg.msg_len) < 0) { status = sta_err; } else status = (ntohl(msg.msg_len) == 0 ? sta_ter: sta_wr); break; case sta_wr: if ((ret = write_data(&msg, msg_fp)) == 0) { status = sta_rec; } else { fprintf(stderr, "fwrite to %s failed, error code: %d\\n ", newfile, ret); status = sta_ter; } break; case sta_rec: msg.mtype = htons(REC); memset((char *)(msg.content), 0, MAXLEN); send_msg(fd_sock, &msg); pthread_mutex_lock(&rec_mut); resend = 1; time_to_exit = TIME_TO_EXIT; pthread_mutex_unlock(&rec_mut); status = sta_rd; break; default: status = sta_ter; break; } } if (msg_fp != 0) fclose(msg_fp); if (started) { msg.mtype = htons(STP); memset(msg.content, 0, MAXLEN); send_msg(fd_sock, &msg); } return; } static void sig_han(int unused) { stop = 1; } static void install_sig(void) { struct sigaction sig; sig.sa_handler = sig_han; sigemptyset(&sig.sa_mask); sig.sa_flags = 0; sigaction(SIGINT, &sig, 0); return; } int main(int argc, char *argv[]) { if (argc < 3) { fprintf(stderr, "usage %s: file path.\\n", argv[0]); exit(1); } install_sig(); if ((fd_sock = socket(PF_INET, SOCK_DGRAM, 0)) == -1) { fprintf(stderr, "create socket to %s failed.\\n", SERVER); exit(1); } rec_file(fd_sock, argv[1], argv[2], 'w'); close(fd_sock); return 0; }
1
#include <pthread.h> void pc_shift_left(void *not_used){ pthread_barrier_wait(&threads_creation); int pc_temp; while(1) { pthread_mutex_lock(&control_sign); if(!cs.isUpdated){ while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0); } pthread_mutex_unlock(&control_sign); if(cs.invalidInstruction){ pthread_barrier_wait(&update_registers); pthread_exit(0); } pc_shift_left_buffer.value = (ir & 0x03ffffff) << 2; pc_temp = (0xf0000000 & pc); pc_shift_left_buffer.value = (pc_temp | pc_shift_left_buffer.value); pthread_mutex_lock(&pc_shift_left_result); pc_shift_left_buffer.isUpdated = 1; pthread_cond_signal(&pc_shift_left_execution_wait); pthread_mutex_unlock(&pc_shift_left_result); pthread_barrier_wait(&current_cycle); pc_shift_left_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
0
#include <pthread.h> int n = 100; pthread_cond_t sig1 = PTHREAD_COND_INITIALIZER; pthread_cond_t sig2 = PTHREAD_COND_INITIALIZER; pthread_mutex_t mut1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mut2 = PTHREAD_MUTEX_INITIALIZER; void* thread_function1(void* unused) { int i; printf("\\n"); for (i = 0; i < n; i++) { printf("a "); } printf("\\n"); printf("\\nthread_function1 sends signal sig2 for the thread_function2\\n"); pthread_mutex_lock(&mut2); pthread_cond_signal(&sig2); pthread_mutex_unlock(&mut2); printf("\\nSignal sig2 is sent!\\n"); printf("\\nthread_function1 waits for receiving of the signal sig1\\n"); pthread_mutex_lock(&mut1); pthread_cond_wait(&sig1,&mut1); pthread_mutex_unlock(&mut1); printf("\\nthread_function1 works after receiving of the signal sig1\\n"); printf("\\n"); for (i = 0; i < n; i++) { printf("b "); } printf("\\n"); return 0; } void* thread_function2(void* unused) { int i; printf("\\n"); for (i = 0; i < n; i++) { printf("1 "); } printf("\\n"); printf("\\nthread_function2 sends signal sig1 for the thread_function1\\n"); pthread_mutex_lock(&mut1); pthread_cond_signal(&sig1); pthread_mutex_unlock(&mut1); printf("\\nSignal sig1 is sent!\\n"); printf("\\nthread_function2 waits for receiving of the signal sig2\\n"); pthread_mutex_lock(&mut2); pthread_cond_wait(&sig2,&mut2); pthread_mutex_unlock(&mut2); printf("\\nthread_function2 works after receiving of the signal sig2\\n"); printf("\\n"); for (i = 0; i < n; i++) { printf("2 "); } printf("\\n"); return 0; } int main() { pthread_t thread1; pthread_t thread2; pthread_create (&thread1, 0, &thread_function1, 0); pthread_create (&thread2, 0, &thread_function2, 0); pthread_join (thread1, 0); pthread_join (thread2, 0); printf("\\nProgram finished !!!\\n"); return 0; }
1
#include <pthread.h> pthread_t thread[2]; pthread_mutex_t mut; int number=0, i; void *thread1() { printf ("thread1 : I'm thread 1\\n"); for (i = 0; i < 10; i++) { printf("thread1: i=%d\\n", i); pthread_mutex_lock(&mut); printf("thread1 got the mut\\n"); printf("thread1 : number = %d\\n",number); number++; pthread_mutex_unlock(&mut); printf("thread1 given the mut\\n"); } printf("thread1 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void *thread2() { printf("thread2 : I'm thread 2\\n"); for (i = 0; i < 10; i++) { printf("thread2 : number = %d\\n",number); pthread_mutex_lock(&mut); number++; pthread_mutex_unlock(&mut); } printf("thread2 :主函数在等我完成任务吗?\\n"); pthread_exit(0); } void thread_create(void) { int temp; memset(&thread, 0, sizeof(thread)); if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0) printf("线程2创建失败"); else printf("线程2被创建\\n"); if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0) printf("线程1创建失败!\\n"); else printf("线程1被创建\\n"); } void thread_wait(void) { if(thread[0] !=0) { pthread_join(thread[0],0); printf("线程1已经结束\\n"); } if(thread[1] !=0) { pthread_join(thread[1],0); printf("线程2已经结束\\n"); } } int main() { pthread_mutex_init(&mut,0); printf("我是主函数,我正在创建线程。\\n"); thread_create(); printf("我是主函数,我正在等待线程完成任务阿。\\n"); thread_wait(); return 0; }
0
#include <pthread.h> pthread_t tid[10000]; int counter; pthread_mutex_t lock; int queue[30]; int front; int b_one_inUse; int b_two_inUse; int usage; double average; double simpleTime; double complexTime; double numSimple; double numComplex; double totalTime; double totalWaitTime; FILE *fp; struct person { int order; }; void* baristas(void *z) { struct timeval start, end; gettimeofday(&start, 0); struct person *personTest = z; int jType = personTest->order; int finished = 0; int i; int j; unsigned long long t; pthread_mutex_lock(&lock); int tempFront = front; pthread_mutex_unlock(&lock); while (finished == 0) { if (b_one_inUse == 0) { pthread_mutex_lock(&lock); b_one_inUse = 1; jType = queue[tempFront]; front += 1; pthread_mutex_unlock(&lock); if (personTest->order == 1) for(i = 0;i<2100000;i++); else if (personTest->order == 0) for(i = 0;i<1100000;i++); pthread_mutex_lock(&lock); gettimeofday(&end, 0); t = ((end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)); if(personTest->order ==1 && (t < 2000000000)) { complexTime += totalWaitTime + t; totalWaitTime += t; numComplex++; } else if(personTest->order == 0 && (t < 2000000000)) { simpleTime += totalWaitTime +t ; totalWaitTime += t; numSimple++; } finished = 1; b_one_inUse = 0; pthread_mutex_unlock(&lock); usage--; } else if (b_two_inUse == 0) { pthread_mutex_lock(&lock); b_two_inUse = 1; jType = queue[tempFront]; front += 1; pthread_mutex_unlock(&lock); if (personTest->order == 1 ) for(j = 0;j<2000000;j++); else if (personTest->order == 0) for(j = 0;j<1000000;j++); pthread_mutex_lock(&lock); gettimeofday(&end, 0); t = ((end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec)); if(personTest->order ==1 && (t < 2000000000)) { complexTime += totalWaitTime + t; totalWaitTime += t; numComplex++; } else if(personTest->order == 0 && (t < 2000000000)) { simpleTime += totalWaitTime +t ; totalWaitTime += t; numSimple++; } finished = 1; b_two_inUse = 0; pthread_mutex_unlock(&lock); usage--; } } } void initialize() { totalWaitTime = 0; simpleTime = 0; complexTime = 0; numSimple = 0; numComplex = 0; totalTime = 0; b_one_inUse = 0; b_two_inUse = 0; front = 1; usage = 0; average = 0; } void runTest(int num) { srand(time(0)); int created = 0; int a = num; int numOrders = a; int i; int r; initialize(); struct person customers[a]; for (i = 0; i<numOrders;i++) { r = rand()%2; customers[i].order = r; } pthread_mutex_init(&lock, 0) != 0; struct timeval startT, endT; gettimeofday(&startT, 0); while (created < a) { if (usage < 2) { pthread_create(&(tid[created]), 0, &baristas, &customers[created]); usage++; created++; } } for (i = 0;i<a;i++) { pthread_join(tid[i], 0); } gettimeofday(&endT, 0); pthread_mutex_destroy(&lock); } void displayTest(int sizeTest) { double average_s = 0; double average_c = 0; int i; for(i = 0; i<1;i++) { runTest(sizeTest); average = (complexTime/(numComplex))/1000; average_c += average; average = (simpleTime/(numSimple))/1000; average_s += average; } ; fprintf(fp,"%d %0.2f %0.2f\\n",sizeTest, (average_c/5), (average_s/5)); } int main(void) { int rc; size_t s1; pthread_attr_t attr; pthread_attr_init(&attr); s1=200000; pthread_attr_setstacksize(&attr, 100); fp = fopen("data1.dat", "w"); if(fp == 0) { printf("derp\\n"); exit(0); } displayTest(10); displayTest(50); displayTest(100); displayTest(250); displayTest(500); displayTest(1000); displayTest(2000); displayTest(10000); return 0; }
1
#include <pthread.h> pthread_cond_t cond_reset = PTHREAD_COND_INITIALIZER; pthread_cond_t cond_inc = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int valeur_commune = 0; void* incr_routine(void * thread_number){ int i = *(int*) thread_number; i += 1; while (1) { struct timespec tim; tim.tv_sec = 0; tim.tv_nsec = 500 * 1000000L; pthread_mutex_lock(&lock); if(valeur_commune < 5) { printf("inc%d : before x=%d\\n", i, valeur_commune); valeur_commune++; printf("\\t after x=%d\\n", valeur_commune); } if(valeur_commune == 5){ pthread_cond_signal(&cond_reset); pthread_cond_wait(&cond_inc, &lock); } pthread_mutex_unlock(&lock); nanosleep(&tim, 0); } pthread_exit(0); } void* reset_routine(void * thread_number){ int i = *(int*) thread_number; struct timespec tim; tim.tv_sec = 0; tim.tv_nsec = 200 * 1000000L; while(1){ pthread_mutex_lock(&lock); pthread_cond_wait(&cond_reset, &lock); printf("reset%d : before x=%d\\n", i, valeur_commune); if(valeur_commune >= 5){ valeur_commune = 0; } printf("\\t after x=%d\\n", valeur_commune); pthread_cond_signal(&cond_inc); pthread_mutex_unlock(&lock); nanosleep(&tim, 0); } pthread_exit(0); } int main (void){ pthread_t threads_inc[3]; pthread_t threads_reset[1]; for(int i = 0; i < 3; i++){ printf("-----this is incr%d-----\\n", i+1); pthread_create(&threads_inc[i], 0, incr_routine, (void*)&i); } for(int i = 0; i < 1; i++){ printf("=====this is reset%d=====\\n", i+1); pthread_create(&threads_reset[i], 0, reset_routine, (void*)&i); } while (1) { } return 0; }
0
#include <pthread.h> volatile int thr_ready = 0; pthread_mutex_t thr_init_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t thr_init = PTHREAD_COND_INITIALIZER; void sig_handler(int signo); void* thr_fn(void *arg) { int signo; sigset_t mask, wait; sigfillset(&mask); sigdelset(&mask, SIGINT); pthread_sigmask(SIG_BLOCK, &mask, 0); pthread_mutex_lock(&thr_init_lock); thr_ready = 1; pthread_mutex_unlock(&thr_init_lock); pthread_cond_signal(&thr_init); printf("thread[%x] waiting for SIGINT\\n", (int)pthread_self()); sleep(999); printf("thread[%x] stop waiting for SIGINT\\n", (int)pthread_self()); return 0; } void sig_handler(int signo) { printf("caught sig[%d] in thread[%x]\\n", signo, (int)pthread_self()); } int main(void) { int ret; void *thr_ret; pthread_t tid; struct sigaction sa; sa.sa_handler = sig_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; if (sigaction(SIGINT, &sa, 0) < 0) return 1; if (0 != (ret = pthread_create(&tid, 0, thr_fn, 0))) return 2; printf("pid: %d\\nmain: [%x]\\nthr: [%x]\\n", (int)getpid(), (int)pthread_self(), (int)tid); pthread_mutex_lock(&thr_init_lock); while (!thr_ready) pthread_cond_wait(&thr_init, &thr_init_lock); pthread_mutex_unlock(&thr_init_lock); printf("send SIGINT to thread[%x]\\n", (int)tid); ret = pthread_kill(tid, SIGINT); printf("pthread_kill return %d\\n", ret); if (ret != 0) return 3; pthread_join(tid, &thr_ret); printf("thread exit: %d\\n", (int)thr_ret); worker_log wl = printf; wl("wl\\n"); return 0; }
1
#include <pthread.h> int main(int argc , char** argv) { pthread_mutex_t LOCK_A, LOCK_B, LOCK_C, LOCK_D, LOCK_E, LOCK_F, LOCK_G; pthread_mutex_t LOCK_H, LOCK_I; MY_INIT(argv[0]); DBUG_ENTER("main"); DBUG_PUSH("d:t:O,/tmp/trace"); printf("This program is testing the mutex deadlock detection.\\n" "It should print out different failures of wrong mutex usage" "on stderr\\n\\n"); safe_mutex_deadlock_detector= 1; pthread_mutex_init(&LOCK_A, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_B, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_C, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_D, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_E, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_F, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_G, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_H, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_I, MY_MUTEX_INIT_FAST); printf("Testing A->B and B->A\\n"); fflush(stdout); pthread_mutex_lock(&LOCK_A); pthread_mutex_lock(&LOCK_B); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_B); pthread_mutex_lock(&LOCK_B); pthread_mutex_lock(&LOCK_A); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_B); printf("Testing A->B and B->A again (should not give a warning)\\n"); pthread_mutex_lock(&LOCK_B); pthread_mutex_lock(&LOCK_A); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_B); printf("Testing A->C and C->D and D->A\\n"); pthread_mutex_lock(&LOCK_A); pthread_mutex_lock(&LOCK_C); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_C); pthread_mutex_lock(&LOCK_C); pthread_mutex_lock(&LOCK_D); pthread_mutex_unlock(&LOCK_D); pthread_mutex_unlock(&LOCK_C); pthread_mutex_lock(&LOCK_D); pthread_mutex_lock(&LOCK_A); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_D); printf("Testing E -> F ; H -> I ; F -> H ; H -> I -> E\\n"); fflush(stdout); pthread_mutex_lock(&LOCK_E); pthread_mutex_lock(&LOCK_F); pthread_mutex_unlock(&LOCK_E); pthread_mutex_unlock(&LOCK_F); pthread_mutex_lock(&LOCK_H); pthread_mutex_lock(&LOCK_I); pthread_mutex_unlock(&LOCK_I); pthread_mutex_unlock(&LOCK_H); pthread_mutex_lock(&LOCK_F); pthread_mutex_lock(&LOCK_H); pthread_mutex_unlock(&LOCK_H); pthread_mutex_unlock(&LOCK_F); pthread_mutex_lock(&LOCK_H); pthread_mutex_lock(&LOCK_I); pthread_mutex_lock(&LOCK_E); pthread_mutex_unlock(&LOCK_E); pthread_mutex_unlock(&LOCK_I); pthread_mutex_unlock(&LOCK_H); printf("\\nFollowing shouldn't give any warnings\\n"); printf("Testing A->B and B->A without deadlock detection\\n"); fflush(stdout); pthread_mutex_destroy(&LOCK_A); pthread_mutex_destroy(&LOCK_B); pthread_mutex_init(&LOCK_A, MY_MUTEX_INIT_FAST); pthread_mutex_init(&LOCK_B, MY_MUTEX_INIT_FAST); my_pthread_mutex_lock(&LOCK_A, MYF(MYF_NO_DEADLOCK_DETECTION)); pthread_mutex_lock(&LOCK_B); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_B); pthread_mutex_lock(&LOCK_A); my_pthread_mutex_lock(&LOCK_B, MYF(MYF_NO_DEADLOCK_DETECTION)); pthread_mutex_unlock(&LOCK_A); pthread_mutex_unlock(&LOCK_B); printf("Testing A -> C ; B -> C ; A->B\\n"); fflush(stdout); pthread_mutex_lock(&LOCK_A); pthread_mutex_lock(&LOCK_C); pthread_mutex_unlock(&LOCK_C); pthread_mutex_unlock(&LOCK_A); pthread_mutex_lock(&LOCK_B); pthread_mutex_lock(&LOCK_C); pthread_mutex_unlock(&LOCK_C); pthread_mutex_unlock(&LOCK_B); pthread_mutex_lock(&LOCK_A); pthread_mutex_lock(&LOCK_B); pthread_mutex_unlock(&LOCK_B); pthread_mutex_unlock(&LOCK_A); pthread_mutex_destroy(&LOCK_A); pthread_mutex_destroy(&LOCK_B); pthread_mutex_destroy(&LOCK_C); pthread_mutex_destroy(&LOCK_D); pthread_mutex_destroy(&LOCK_E); pthread_mutex_destroy(&LOCK_F); pthread_mutex_destroy(&LOCK_G); pthread_mutex_destroy(&LOCK_H); pthread_mutex_destroy(&LOCK_I); my_end(MY_DONT_FREE_DBUG); exit(0); }
0
#include <pthread.h> pthread_mutex_t mx, my; int x=2, y=2; void *thread1() { int a; pthread_mutex_lock(&mx); a = x; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); a = a + 1; pthread_mutex_lock(&my); y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; y = y + a; pthread_mutex_unlock(&my); x = x + x + a; pthread_mutex_unlock(&mx); assert(x!=207); return 0; } void *thread2() { x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; x=x+2; return 0; } void *thread3() { pthread_mutex_lock(&my); y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; y=y+2; pthread_mutex_unlock(&my); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mx, 0); pthread_mutex_init(&my, 0); pthread_create(&t1, 0, thread1, 0); pthread_create(&t2, 0, thread2, 0); pthread_create(&t3, 0, thread3, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mx); pthread_mutex_destroy(&my); return 0; }
1
#include <pthread.h> int numThreads = 0; pthread_mutex_t mutexNumThreads; pthread_mutex_t mutexWrite; pthread_mutex_t mutexRecv; { unsigned short port_id; char * ipaddr; int maxthreads; } serv_info; void * down_client(serv_info * threadArgs) { FILE * writeFile = fopen("client_final.txt", "wt"); pthread_mutex_lock(&mutexNumThreads); int threadNum = numThreads++; pthread_mutex_unlock(&mutexNumThreads); int down_cnt = 0; int con_fd = 0; int ret = 0; char recv_buf[1024]; char blocknum[128]; sprintf(blocknum, "%d", threadNum); struct sockaddr_in serv_addr; unsigned short port = 0; port = threadArgs -> port_id; memset(&serv_addr, 0, sizeof(struct sockaddr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr = inet_addr(threadArgs->ipaddr); while(1) { int block_num = atoi(blocknum); con_fd = socket(PF_INET, SOCK_STREAM, 0); if(con_fd == -1) { perror("Socket Error\\n"); pthread_exit((void*) -1); } ret = connect(con_fd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)); if(ret < 0) { perror("Connection Error\\n"); pthread_exit((void*) -1); } ret = send(con_fd, blocknum, 128, 0); if(ret < 0) { perror("Block Request Failed"); close(con_fd); pthread_exit((void*) -1); } pthread_mutex_lock(&mutexRecv); memset(recv_buf, 0, sizeof(recv_buf)); ret = recv(con_fd, recv_buf, 1024, 0); if(ret < 0) { perror("Block Recv Failed"); close(con_fd); pthread_exit((void*) -1); } if(recv_buf[0] == 0) { printf("break and end thread: %d\\n", threadNum); pthread_mutex_unlock(&mutexRecv); break; } pthread_mutex_unlock(&mutexRecv); pthread_mutex_lock(&mutexWrite); printf("block_num: %d from thread: %d printing to position: %d\\n printed out: %s\\n", block_num, threadNum, 1024*block_num, &recv_buf); fseek(writeFile, (1024*block_num), 0); if(strlen(recv_buf) > 1024) fwrite(&recv_buf, 1024, 1, writeFile); else fwrite(&recv_buf, strlen(recv_buf), 1, writeFile); rewind(writeFile); pthread_mutex_unlock(&mutexWrite); down_cnt++; block_num = block_num + threadArgs -> maxthreads; sprintf(blocknum, "%d", block_num); } free(threadArgs); fclose(writeFile); close(con_fd); return (void *)down_cnt; } int main(int argc, char ** argv) { pthread_mutex_init(&mutexNumThreads, 0); pthread_mutex_init(&mutexWrite, 0); pthread_mutex_init(&mutexRecv, 0); if (argc < 3 || argc%2 != 1) { printf("correct input: ./client_final <ipaddr1> <port1> <ipaddr2> <port2>...\\n"); return -1; } int maxthreads = (argc-1)/2; void * downCnts[maxthreads]; pthread_t threads[maxthreads]; char * IPs[maxthreads]; char * ports[maxthreads]; int j = 1; int i = 0; while(i < maxthreads) { IPs[i] = argv[j]; j = j+2; i++; } j = 2; i = 0; while(i < maxthreads) { ports[i] = argv[j]; j = j+2; i++; } for(int i=0; i < maxthreads; i++) { serv_info * threadArgs = malloc(sizeof(serv_info)); threadArgs -> port_id = atoi(ports[i]); threadArgs -> ipaddr = IPs[i]; threadArgs -> maxthreads = maxthreads; pthread_create(&threads[i], 0, down_client, threadArgs); } for(int i=0; i < maxthreads; i++) { pthread_join(threads[i], &downCnts[i]); } for(int i=0; i < maxthreads; ++i) { printf("Thread %d wrote %d blocks to client_final.txt\\n", i+1, (int)downCnts[i]); } pthread_mutex_destroy(&mutexNumThreads); pthread_mutex_destroy(&mutexWrite); pthread_mutex_destroy(&mutexRecv); return 0; }
0
#include <pthread.h> pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t can_read = PTHREAD_COND_INITIALIZER; pthread_cond_t can_write = PTHREAD_COND_INITIALIZER; int i = 0; void * do_it_a(void * p) { pthread_mutex_lock(&lock); if (i != 0) pthread_cond_wait(&can_write, &lock); i = 10; pthread_cond_signal(&can_read); pthread_mutex_unlock(&lock); } void * do_it_b(void * p) { pthread_mutex_lock(&lock); if (i != 0) pthread_cond_wait(&can_write, &lock); i = 100; pthread_cond_signal(&can_read); pthread_mutex_unlock(&lock); } void * do_it_add(void * p) { pthread_mutex_lock(&lock); if (i == 0) pthread_cond_wait(&can_read, &lock); int a = i; i = 0; pthread_cond_signal(&can_write); pthread_mutex_unlock(&lock); pthread_mutex_lock(&lock); if (i == 0) pthread_cond_wait(&can_read, &lock); int b = i; pthread_cond_signal(&can_write); pthread_mutex_unlock(&lock); printf("%d\\n", a+b); } int main() { pthread_t t1; pthread_t t2; pthread_t t3; pthread_create(&t1, 0, do_it_a, 0); pthread_create(&t2, 0, do_it_b, 0); pthread_create(&t3, 0, do_it_add, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); return 0; }
1
#include <pthread.h> int shared = 5; pthread_mutex_t lock; int thread_num; char buf[80]; } tinfo_t; void* thread_func(void *arg) { tinfo_t *tmp = (tinfo_t*)arg; printf("Thread %u - modifying shared data while holding mutex\\n", tmp->thread_num); pthread_mutex_lock(&lock); shared++; pthread_mutex_unlock(&lock); pthread_exit(0); } int main() { int ret = 0; int i = 0; printf("Shared data initially starts at %u. %u threads will inc by one\\n", shared, 2); ret = pthread_mutex_init(&lock, 0); if (0 != ret) { printf("Mutex init failed: %u\\n", ret); return 0; } tinfo_t thread_args[2]; for (i = 0; i < 2; i++) { thread_args[i].thread_num = i; sprintf(thread_args[i].buf, "Thread Number: %u", i); } pthread_t tids[2] = { 0 }; for (i = 0; i < 2; i++) { ret = pthread_create(&tids[i], 0, thread_func, (void*)&thread_args[i]); if (0 == ret) { printf("Thread %i created succesfully\\n", i); } else { printf("Thread %i create failed: ret=%u\\n", i, ret); } } for (i = 0; i < 2; i++) { pthread_join(tids[i], 0); } pthread_mutex_destroy(&lock); printf("New shared data val: %u\\n", shared); return 0; }
0
#include <pthread.h> long sum=0; struct interval { long start; long end; int tid; }; pthread_mutex_t sum_mutex; void *add(void *arg) { intv *myinterval = (intv*) arg; long start = myinterval->start; long end = myinterval->end; printf("I am thread %d and my interval is %ld to %ld\\n", myinterval->tid,start,end); long j; for(j=start;j<=end;j++) { pthread_mutex_lock(&sum_mutex); sum += j; pthread_mutex_unlock(&sum_mutex); } printf("Thread %d finished\\n",myinterval->tid); pthread_exit((void*) 0); } int main (int argc, char *argv[]) { intv *intervals; intervals = (intv*) malloc(4*sizeof(intv)); void *status; pthread_t threads[4]; pthread_mutex_init(&sum_mutex,0); int i; for(i=0; i<4; i++) { intervals[i].start = i*(1280000000/4); intervals[i].end = (i+1)*(1280000000/4) - 1; intervals[i].tid=i; pthread_create(&threads[i], 0, add, (void *) &intervals[i]); } for(i=0; i<4; i++) pthread_join(threads[i], &status); printf ("Final Global Sum=%li\\n",sum); free (intervals); pthread_exit(0); }
1
#include <pthread.h> int N, NUMROWS, NUMTHREADS; double *c, *a, *b; pthread_mutex_t mutex; void populate_matrices(int N){ int i,j; srand(time(0)); a = (double*) malloc(N * N * sizeof(double)); b = (double*) malloc(N * N * sizeof(double)); c = (double*) malloc(N * N * sizeof(double)); for (i = 0; i < N; i++){ for (j = 0; j < N; j++) { a[i*N + j] = rand()*100; b[i*N + j] = rand()*100; c[i*N + j] = 0.0; } } } void multiply_matrices(int i, int j, int k, int N){ double temp = 0; for (i = 0; i < N; i++){ for (j = 0; j < N; j++){ temp = 0.0; for (k = 0; k < N; k++){ temp += a[i*N + k] * b[k*N + j]; } c[i*N + j] = temp; } } } void calculate_infinityNorm( int N){ int i,j; double temp = 0; double inf_norm = 0; for (i = 0; i < N; i++){ temp = 0.0; for (j = 0; j < N; j++){ temp += fabs(c[i*N + j]); } if(temp > inf_norm){ inf_norm = temp; } } } void calculate_infinityNorm_viaPthreads(int thread_id){ int i,j; double temp = 0; double inf_norm = 0; int partition_start = (N/NUMTHREADS)*thread_id; int partition_end = (NUMROWS+(thread_id*NUMROWS)); for (i = partition_start; i < partition_end; i++){ temp = 0.0; pthread_mutex_lock(&mutex); for (j = 0; j < N; j++){ temp += fabs(c[i*N + j]); } if(temp > inf_norm){ inf_norm = temp; } pthread_mutex_unlock(&mutex); } } void multiply_matrices_viaPthreads(int thread_id){ int i,j,k; double row_norm = 0, row_sum = 0, temp = 0; int partition_start = (N/NUMTHREADS)*thread_id; int partition_end = (NUMROWS+(thread_id*NUMROWS)); for (i = partition_start; i < partition_end; i++) { for (j = 0; j < N; j++) { temp = 0.0; for (k = 0; k < N; k++) { temp += a[i*N + k] * b[k*N + j]; } c[i*N + j] = temp; } } } int main(int argc, char* argv[]){ int i,j,k,t,thread_i; double average = 0; N = atoi(argv[1]); NUMTHREADS = atoi(argv[2]); int TIMES_TO_RUN = atoi(argv[3]); NUMROWS = N/NUMTHREADS; if (N%NUMTHREADS != 0) { printf("\\n Number of threads must evenly divide N\\n"); return 0; } if (NUMTHREADS < 1) { printf("\\n Number of threads must be greater than zero\\n"); return 0; } populate_matrices(N); struct timeval tv1, tv2; struct timezone tz; pthread_t *threads; threads = (pthread_t *) malloc(sizeof(pthread_t) * NUMTHREADS); for(t = 0; t < TIMES_TO_RUN; t++) { gettimeofday(&tv1, &tz); multiply_matrices(i,j,k,N); gettimeofday(&tv2, &tz); double elapsed = (double)(tv2.tv_sec - tv1.tv_sec) + (double)(tv2.tv_usec - tv1.tv_usec) * 1.e-6; average += elapsed; } printf(" Average Straightforward IJK: %lf sec.\\n", average/TIMES_TO_RUN); average = 0.0; populate_matrices(N); for(t = 0; t < TIMES_TO_RUN; t++) { gettimeofday(&tv1, &tz); for (thread_i = 0; thread_i < NUMTHREADS; thread_i++) pthread_create(&threads[thread_i], 0, (void *(*) (void *)) multiply_matrices_viaPthreads, (void *) (thread_i)); for (thread_i = 0; thread_i < NUMTHREADS; thread_i++) pthread_join(threads[thread_i], 0); gettimeofday(&tv2, &tz); double elapsed = (double)(tv2.tv_sec - tv1.tv_sec) + (double)(tv2.tv_usec - tv1.tv_usec) * 1.e-6; average += elapsed; } printf(" Average Pthreads Straightforward IJK: %lf sec.\\n", average/TIMES_TO_RUN); average = 0.0; for(t = 0; t < TIMES_TO_RUN; t++) { gettimeofday(&tv1, &tz); calculate_infinityNorm(N); gettimeofday(&tv2, &tz); double elapsed = (double)(tv2.tv_sec - tv1.tv_sec) + (double)(tv2.tv_usec - tv1.tv_usec) * 1.e-6; average += elapsed; } printf(" Average Serial infinity norm: %lf sec.\\n", average/TIMES_TO_RUN); average = 0.0; for(t = 0; t < TIMES_TO_RUN; t++) { gettimeofday(&tv1, &tz); for (thread_i = 0; thread_i < NUMTHREADS; thread_i++) pthread_create(&threads[thread_i], 0, (void *(*) (void *)) calculate_infinityNorm_viaPthreads, (void *) (thread_i)); for (thread_i = 0; thread_i < NUMTHREADS; thread_i++) pthread_join(threads[thread_i], 0); gettimeofday(&tv2, &tz); double elapsed = (double)(tv2.tv_sec - tv1.tv_sec) + (double)(tv2.tv_usec - tv1.tv_usec) * 1.e-6; average += elapsed; } printf(" Average Pthreads infinity norm: %lf sec.\\n", average/TIMES_TO_RUN); return 0; }
0
#include <pthread.h> struct bufpool { char *buf; int ref_cnt; pthread_mutex_t mutex; }; static struct bufpool *udpbp; static unsigned int udpbp_cnt; static unsigned int start; int bufpool_init(unsigned int perbuf_size, unsigned int startp, unsigned int ports) { char *buffers; if (udpbp) return -1; buffers = (char *)malloc(perbuf_size * ports); if (!buffers) return -1; udpbp = (struct bufpool *)malloc(sizeof(*udpbp) * ports); if (!udpbp) return -1; udpbp_cnt = ports; start = startp; memset(udpbp, 0, sizeof(*udpbp) * ports); for (unsigned int i = 0; i < ports; i++) { udpbp[i].buf = buffers + perbuf_size * i; pthread_mutex_init(&udpbp[i].mutex, 0); } return 0; } char *bufpool_get(unsigned int port) { if (!udpbp || port < start || port > (start + udpbp_cnt)) return 0; int i = port - start; if (__sync_fetch_and_add(&udpbp[i].ref_cnt, 1)) pthread_mutex_lock(&udpbp[i].mutex); return udpbp[i].buf; } void bufpool_put(unsigned int port) { if (!udpbp || port < start || port > (start + udpbp_cnt)) return; int i = port - start; if (udpbp[i].ref_cnt && __sync_sub_and_fetch(&udpbp[i].ref_cnt, 1)) pthread_mutex_unlock(&udpbp[i].mutex); } void bufpool_deinit(void) { if (!udpbp) return; free(udpbp[0].buf); free(udpbp); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_t ThreadOne; pthread_t ThreadTwo; int mutexDestroy; int buffer [ 10 ]; void *Consumer ( void *argument ) { int counter; int secondCounter; for ( secondCounter = 0 ; secondCounter < 5 ; secondCounter++ ) { pthread_mutex_lock ( &mutex ); for ( counter = 0 ; counter < 10 ; counter++ ) { printf ( "\\n\\tCosumer: Array [ %d ] = %d.", counter, buffer [ counter ] ); } pthread_mutex_unlock ( &mutex ); printf ( "\\n" ); } return 0; } void *Producer ( void *argument ) { int counter; int secondCounter; for ( secondCounter = 0 ; secondCounter < 5 ; secondCounter++ ) { pthread_mutex_lock ( &mutex ); for ( counter = 0 ; counter < 10 ; counter++ ) { buffer [ counter ] = secondCounter; printf ( "\\n\\tProducer: Array [ %d ] = %d.", counter, buffer [ counter ] ); } pthread_mutex_unlock ( &mutex ); } return 0; } int main ( int argc, char const *argv [ ] ) { pthread_create ( &ThreadOne, 0, Producer, 0 ); pthread_create ( &ThreadTwo, 0, Consumer, 0 ); pthread_join ( ThreadOne, 0 ); pthread_join ( ThreadTwo, 0 ); printf ( "\\n" ); if ( mutexDestroy < 0 ) { printf ( "\\n\\n\\tMutex cannot initialize." ); exit ( 0 ); } else { printf ( "\\tMutex succesfully destroyed.\\n\\n" ); } }
0
#include <pthread.h> long int reader_count; long int writer_count; long int reader_loop; long int writer_loop; int rwlock_enabled=1; struct read_write_lock { pthread_mutex_t mtx; pthread_cond_t cond; int readers; int writers; }; struct read_write_lock rwlock; pthread_spinlock_t spinlock; long int data=0; void InitalizeReadWriteLock(struct read_write_lock * rw) { rw->readers = 0; rw->writers = 0; pthread_cond_init(&rw->cond, 0); pthread_mutex_init(&rw->mtx, 0); } void ReaderLock(struct read_write_lock * rw) { pthread_mutex_lock(&rw->mtx); while(rw->writers){ pthread_cond_wait(&rw->cond, &rw->mtx); } rw->readers++; pthread_mutex_unlock(&rw->mtx); } void ReaderUnlock(struct read_write_lock * rw) { pthread_mutex_lock(&rw->mtx); rw->readers--; pthread_cond_broadcast(&rw->cond); pthread_mutex_unlock(&rw->mtx); } void WriterLock(struct read_write_lock * rw) { pthread_mutex_lock(&rw->mtx); while(rw->writers || rw->readers){ pthread_cond_wait(&rw->cond, &rw->mtx); } rw->writers++; pthread_mutex_unlock(&rw->mtx); } void WriterUnlock(struct read_write_lock * rw) { pthread_mutex_lock(&rw->mtx); rw->writers--; pthread_cond_broadcast(&rw->cond); pthread_mutex_unlock(&rw->mtx); } void *ReaderFunction(void *arg) { int threadNUmber = *((int *)arg); for(int i=0;i<reader_loop;i++) { if(rwlock_enabled) ReaderLock(&rwlock); else pthread_spin_lock(&spinlock); printf("Reader: %2d, value: %ld\\n",threadNUmber, data); if(rwlock_enabled) ReaderUnlock(&rwlock); else pthread_spin_unlock(&spinlock); usleep(900); } } void *WriterFunction(void *arg) { int threadNUmber = *((int *)arg); for(int i=0;i<writer_loop;i++) { if(rwlock_enabled) WriterLock(&rwlock); else pthread_spin_lock(&spinlock); data++; printf("Writer: %2d, value: %ld\\n",threadNUmber, data); if(rwlock_enabled) WriterUnlock(&rwlock); else pthread_spin_unlock(&spinlock); usleep(900); } } int main(int argc, char *argv[]) { pthread_t *writer_threads; pthread_t *reader_threads; int *threadNUmber; struct args *arg; time_t start, stop; if(argc<6) { printf("read-write <readers-count> <writers-count> <reader-loop-size> <writer-loop-size> <enable/disable rwlock>\\n"); exit(1); } reader_count=atol(argv[1]); writer_count=atol(argv[2]); reader_loop=atol(argv[3]); writer_loop=atol(argv[4]); rwlock_enabled=atoi(argv[5]); pthread_spin_init(&spinlock,0); InitalizeReadWriteLock(&rwlock); time(&start); writer_threads = (pthread_t *) malloc(writer_count * sizeof(pthread_t)); reader_threads = (pthread_t *) malloc(reader_count * sizeof(pthread_t)); for(int i=0;i<writer_count; i++) { int ind = i; pthread_create(&writer_threads[i], 0, WriterFunction, &ind); } for(int i=0;i<reader_count; i++) { int ind = i; pthread_create(&reader_threads[i], 0, ReaderFunction, &ind); } for(int i=0;i<writer_count; i++) pthread_join(writer_threads[i],0); for(int i=0;i<reader_count; i++) pthread_join(reader_threads[i],0); time(&stop); printf("Finished in about %.0f seconds. \\n", difftime(stop, start)); exit(1); }
1
#include <pthread.h> pthread_mutex_t mutex; int sum = 0; void* sumfunc1() { int i; for (i = 0; i < 10000 / 2; ++i) { pthread_mutex_lock(&mutex); int temp_sum = sin(i) * sin(i) + cos(i) * cos(i); sum += temp_sum; pthread_mutex_unlock(&mutex); } return 0; } void* sumfunc2() { int i; for (i = 10000 / 2; i < 10000; ++i) { pthread_mutex_lock(&mutex); int temp_sum = sin(i) * sin(i) + cos(i) * cos(i); sum += temp_sum; pthread_mutex_unlock(&mutex); } return 0; } int main() { int mutexInitializationError = pthread_mutex_init(&mutex, 0); if (mutexInitializationError) { printf("Mutex was not initialized!\\n"); return 0; } pthread_t thread1; pthread_t thread2; pthread_create(&thread1, 0, sumfunc1, 0); pthread_create(&thread2, 0, sumfunc1, 0); pthread_join(thread1, 0); pthread_join(thread2, 0); printf("%d \\n", sum); pthread_mutex_destroy(&mutex); return 0; }
0
#include <pthread.h> extern int tab[NB_LIGNE][NB_COLONNE]; extern pthread_mutex_t mutexGrille; static bool fireOn = 1; void nouveauCanon() { pthread_t thread_id; if (pthread_create(&thread_id, 0, threadCanon, 0) != 0) { Trace("Erreur lors du lancement du thread de gestion" "du canon" ); exit(1); } pthread_detach(thread_id); } void* threadCanon(void* vdata) { Trace("Lock canon ..."); pthread_mutex_lock(&mutexGrille); tab[LGN_CANONS][NB_COLONNE / 4] = CANON1; DessineCanon(LGN_CANONS, NB_COLONNE / 4, 1); pthread_mutex_unlock(&mutexGrille); Trace("OK Lock canon ..."); struct sigaction Action; Action.sa_flags = 0; sigemptyset(&Action.sa_mask); Action.sa_handler = pressionTouche; sigaction(SIGUSR1, &Action, 0); sigaction(SIGUSR2, &Action, 0); sigaction(SIGHUP, &Action, 0); sigaction(SIGQUIT, &Action, 0); pause(); } void pressionTouche(int sig) { Trace("Lock canon ..."); pthread_mutex_lock(&mutexGrille); Trace("OK Lock canon ..."); int col; for (int i = 0; i < NB_COLONNE; i++) { if (tab[LGN_CANONS][i] == CANON1) { col = i; break; } } switch (sig) { case SIGUSR1: deplacerCanon(col, -1); break; case SIGUSR2: deplacerCanon(col, +1); break; case SIGHUP: lancerMissile(col); break; case SIGQUIT: Trace("Canon détruit"); pthread_exit(0); break; } pthread_mutex_unlock(&mutexGrille); } void deplacerCanon(int col, int dx) { col += dx; if (col < 0 || col >= NB_COLONNE || tab[LGN_CANONS][col] != VIDE) { return; } tab[LGN_CANONS][col - dx] = VIDE; DessineVide(LGN_CANONS, col - dx); tab[LGN_CANONS][col] = CANON1; DessineCanon(LGN_CANONS, col, 1); } void* fireOnThread(void* args); void lancerMissile(int col) { if (fireOn) { nouveauMissile(LGN_CANONS - 1, col, 1); pthread_t tid; if (pthread_create(&tid, 0, fireOnThread, 0) != 0) { Trace("Erreur lors du lancement du thread de timeout"); exit(1); } pthread_detach(tid); } } void* fireOnThread(void* args) { fireOn = 0; milisec_sleep(TIR_SLEEP); fireOn = 1; }
1
#include <pthread.h> extern int makethread(void *(*)(void *), void *); struct to_info { void (*to_fn)(void *); void *to_arg; struct timespec to_wait; }; void * timeout_helper(void *arg) { struct to_info *tip; tip = (struct to_info *)arg; nanosleep(&tip->to_wait, 0); (*tip->to_fn)(tip->to_arg); return 0; } void timeout(const struct timespec *when, void (*func)(void *), void *arg) { struct timespec now; struct timeval tv; struct to_info *tip; int err; gettimeofday(&tv, 0); now.tv_sec = tv.tv_sec; now.tv_nsec = tv.tv_usec * 1000; if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) { tip = malloc(sizeof(struct to_info)); if (tip != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) { tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; } else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } err = makethread(timeout_helper, (void *)tip); if (err == 0) return; } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void *arg) { pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); } int main(void) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init(&attr)) != 0) err_exit(err, "pthread_mutexattr_init failed"); if ((err = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit(err, "can't set recursive type"); if ((err = pthread_mutex_init(&mutex, &attr)) != 0) err_exit(err, "can't create recursive mutex"); pthread_mutex_lock(&mutex); if (condition) { timeout(&when, retry, (void *)arg); } pthread_mutex_unlock(&mutex); exit(0); }
0
#include <pthread.h> int flag; pthread_cond_t flag_cv; pthread_mutex_t flag_mutex; void *func(void * arg); void msleep( int msec ); int procesa_args(int argc, char *argv[]); int n_hilos; int msec_disparo; int msec_consumo; int main(int argc, char *argv[]) { pthread_t tid[20]; int i; if (!procesa_args(argc, argv)) return 1; flag=0; pthread_mutex_init(&flag_mutex, 0); pthread_cond_init(&flag_cv, 0); for(i=0;i<n_hilos;i++) pthread_create(&tid[i], 0, func, (void*) 'A'+i ); i=10; printf("lanzando 10 disparos , %d hilos ...\\n", n_hilos); while(i--) { msleep(msec_disparo); pthread_mutex_lock(&flag_mutex); flag=1; pthread_cond_signal(&flag_cv); pthread_mutex_unlock(&flag_mutex); } pthread_mutex_lock(&flag_mutex); flag=-1; pthread_cond_broadcast(&flag_cv); pthread_mutex_unlock(&flag_mutex); for(i=0;i<n_hilos;i++) pthread_join(tid[i], 0); write(STDOUT_FILENO, "\\n", 1); return 0; } void *func(void * arg) { int ch=(int) arg; int cont=1; while(cont) { pthread_mutex_lock(&flag_mutex); while(flag==0) { write(STDOUT_FILENO, ".", 1); pthread_cond_wait(&flag_cv, &flag_mutex); } if (flag<0) cont=0; else flag=0; pthread_mutex_unlock(&flag_mutex); if(cont)write(STDOUT_FILENO, &ch, 1); msleep(msec_consumo); } return 0; } int procesa_args(int argc, char *argv[]) { if (argc!=4) { fprintf(stderr, "uso: %s n_hiles msec_disparo msec_consumo\\n" " ej: %s 1 50 10\\n" " ej: %s 5 50 10\\n" " ej: %s 5 10 50 (pierde ...)\\n" , argv[0], argv[0], argv[0], argv[0]); return 0; } n_hilos=atoi(argv[1]); msec_disparo=atoi(argv[2]); msec_consumo=atoi(argv[3]); if (!n_hilos|| n_hilos > 20 || !msec_disparo || !msec_consumo) return 0; return 1; } void msleep( int msec ) { struct timespec ts = { 0, msec * 1E6 }; nanosleep(&ts, 0); }
1
#include <pthread.h> pthread_mutex_t m_access; pthread_mutex_t m_write_num; int write_num = 0; char buf[1024]; void *read_hand(void * arg) { FILE *fp_rd = fopen("./a.txt","rb"); pthread_detach(pthread_self()); pthread_mutex_lock(&m_access); pthread_mutex_lock(&m_write_num); if( write_num != 0) { printf("a reader start!!\\n"); if( 0 == fp_rd ) { perror("read error\\n"); exit(-1); } char buf_read[1024]; while( memset(buf_read,0,1024),fgets(buf_read,1024,fp_rd) != 0) { fputs(buf_read,stdout); } sleep(3); pthread_mutex_unlock(&m_access); } pthread_mutex_unlock(&m_write_num); fclose(fp_rd); } void *write_hand(void * arg ) { pthread_detach( pthread_self()); pthread_mutex_lock(&m_write_num); if( 0 == write_num ) { pthread_mutex_lock(&m_access); } pthread_mutex_unlock(&m_write_num); pthread_mutex_lock(&m_write_num); ++write_num; pthread_mutex_unlock(&m_write_num); pthread_mutex_lock( &m_access ); FILE *fp_wr = fopen("./a.txt","a"); printf("a writer start\\n"); if( 0 == fp_wr ) { perror("write error\\n"); exit(-1); } pthread_mutex_unlock( &m_access ); pthread_mutex_lock(&m_write_num); --write_num; pthread_mutex_unlock(&m_write_num); pthread_mutex_lock(&m_write_num); if( 0 == write_num ) { pthread_mutex_unlock(&m_access); } pthread_mutex_unlock(&m_write_num); fclose(fp_wr); } int main() { int i =1 ; pthread_mutex_init(&m_access,0); pthread_mutex_init(&m_write_num,0); srand(getpid()); while(1) { i++; if( i % 2 != 0 ) { pthread_t tid; pthread_create(&tid,0,read_hand,0); } else { pthread_t tid; pthread_create(&tid,0,write_hand,0); } } pthread_mutex_destroy(&m_access); pthread_mutex_destroy(&m_write_num); }
0
#include <pthread.h> pthread_t producer[20], consumer[20]; pthread_mutex_t mutex; int p[20], c[20]; sem_t full, empty; int counter = 0, size; int buffer[100]; void* ProducerFunc(void* x) { while (1) { int *num = x, i; sem_wait(&empty); pthread_mutex_lock(&mutex); buffer[counter++] = rand() % 10 + 1; printf("\\n\\nProducer %d produced an item %d. Buffer : ", *num, buffer[counter - 1]); printf("["); for (i = 0; i < size; i++) { printf(" %d", buffer[i]); } printf(" ]"); pthread_mutex_unlock(&mutex); sem_post(&full); sleep(1); } } void* ConsumerFunc(void* y) { while (1) { int *n = y, i; sem_wait(&full); pthread_mutex_lock(&mutex); printf("\\n\\n\\t\\t\\tConsumer %d consumed an item %d. Buffer : ", *n, buffer[counter - 1]); buffer[--counter] = 0; printf("["); for (i = 0; i < size; i++) { printf(" %d", buffer[i]); } printf(" ]"); pthread_mutex_unlock(&mutex); sem_post(&empty); sleep(1); } } void main() { int con, pro, i, *num; printf("\\nEnter the size of the buffer :"); scanf("%d", &size); sem_init(&full, 0, 0); sem_init(&empty, 0, size); printf("\\nEnter the number of producers :"); scanf("%d", &pro); printf("\\nEnter the number of consumers :"); scanf("%d", &con); for (i = 0; i < pro; i++) { p[i] = i; pthread_create(&producer[i], 0, ProducerFunc, &p[i]); } for (i = 0; i < con; i++) { c[i] = i; pthread_create(&consumer[i], 0, ConsumerFunc, &c[i]); } for (i = 0; i < con; i++) { pthread_join(consumer[i], 0); } for (i = 0; i < pro; i++) { pthread_join(producer[i], 0); } }
1
#include <pthread.h> int routerTable[256]; pthread_mutex_t router_mutex; void ManageRoute_init(){ printf("ManageRoute_init\\n"); pthread_mutex_init(&router_mutex, 0); } void del_router(int dst){ if(dst==255){ while(system("route del default")==0); return; } pthread_mutex_lock( &router_mutex); if (routerTable[dst]!=0){ char cmd[50]; memset(cmd,0,sizeof(cmd)); strcpy(cmd,"route del "); int i, j; int len=strlen(cmd); for(i=0,j=0;j<3;i++){ cmd[len++]=HOSTIP[i]; if(HOSTIP[i]=='.') j++; } sprintf(cmd+len,"%d",dst); printf("%s\\n",cmd); system(cmd); routerTable[dst] = 0; } pthread_mutex_unlock( &router_mutex); } void add_router(int dst, int gw){ pthread_mutex_lock( &router_mutex); if (routerTable[dst]==gw){ pthread_mutex_unlock( &router_mutex); return; } pthread_mutex_unlock( &router_mutex); del_router(dst); pthread_mutex_lock( &router_mutex); char cmd[50]; memset(cmd,0,sizeof(cmd)); int i, j,len; if(dst==255){ strcpy(cmd,"route add default gw "); len=strlen(cmd); for(i=0,j=0;j<3;i++){ cmd[len++]=HOSTIP[i]; if(HOSTIP[i]=='.') j++; } } else{ strcpy(cmd,"route add "); len=strlen(cmd); for(i=0,j=0;j<3;i++){ cmd[len++]=HOSTIP[i]; if(HOSTIP[i]=='.') j++; } sprintf(cmd+len,"%d gw ",dst); len=strlen(cmd); for(i=0,j=0;j<3;i++){ cmd[len++]=HOSTIP[i]; if(HOSTIP[i]=='.') j++; } } sprintf(cmd+len,"%d",gw); printf("%s\\n",cmd); system(cmd); routerTable[dst] = gw; pthread_mutex_unlock( &router_mutex); } int get_gw(int dst){ return routerTable[dst]; }
0
#include <pthread.h> float money; int n; int mark; pthread_mutex_t mut; struct INFO { float rmoney; pthread_t thread; }info[5]; int flag = 1; void *writemoney(void) { money = 100.0; mark = n = 3; pthread_exit(0); } void *readmoney(void *arg) { int *pth = (int *)arg; if(money == 0 || mark == 0) { for(int i = 0; i < 5; i ++) { if(info[i].thread != *pth) pthread_cancel(info[i].thread); } printf("该红包已被撤销\\n"); } else if(money != 0 && mark!= 0) { time_t ts; srand((unsigned int)time(&ts)+*pth); float readmoney = rand()%(10000/(n-1))/100.0; if(readmoney == 0.00) { readmoney = 0.01; } pthread_mutex_lock(&mut); if(mark > 1) { printf("id :[%lu] 抢了%.2f元", pthread_self(), readmoney); info[flag++].rmoney = readmoney; money -= readmoney; mark--; printf("剩余%.2f元\\n", money); } if(mark == 1) { readmoney = money; printf("id :[%lu] 抢了%.2f元", pthread_self(), readmoney); info[flag++].rmoney = readmoney; money -= readmoney; mark--; printf("剩余%.2f元\\n", money); } { } pthread_mutex_unlock(&mut); } pthread_exit(0); } int main() { int temp; if((temp = pthread_create(&info[0].thread, 0, (void *)writemoney, 0)) == 0) { printf("线程write创建成功\\n"); } sleep(1); int nth = 4; for(int i = 1; i <= nth; i++) { if((temp = pthread_create(&info[i].thread, 0, (void *)readmoney, &info[i].thread)) == 0) { printf("线程read%d创建成功\\n", i); } } printf("等待线程结束\\n"); for(int i = 0; i < nth+1; i++) pthread_join(info[i].thread, 0); printf("线程结束\\n"); printf("/*********抢红包信息*********/\\n"); float max = 0.0; int x; for(int i = 1; i <= nth; i++) { if(info[i].rmoney > max) { max = info[i].rmoney; x = i; } if(info[i].rmoney == 0.00) { printf("线程%d手慢无\\n", i); } else { printf("线程%d抢了%.2f元\\n", i, info[i].rmoney); } } printf("/**********运气王**********/\\n"); printf("线程%d 抢了%.2f元\\n", x, max); return 0; }
1
#include <pthread.h> static pthread_t thread[256]; static pthread_mutex_t mutex[256]; static pthread_cond_t cond[256]; static volatile int full[256]; static volatile int data[256]; static int cycles; static int tokens; static void send_to (int i, int d) { pthread_mutex_lock (&(mutex[i])); while (full[i]) pthread_cond_wait (&(cond[i]), &(mutex[i])); full[i] = 1; data[i] = d; pthread_cond_signal (&(cond[i])); pthread_mutex_unlock (&(mutex[i])); } static int recv_from (int i) { int d; pthread_mutex_lock (&(mutex[i])); while (!full[i]) pthread_cond_wait (&(cond[i]), &(mutex[i])); full[i] = 0; d = data[i]; pthread_cond_signal (&(cond[i])); pthread_mutex_unlock (&(mutex[i])); return d; } static void *root (void *n) { int this = (int) n; int next = (this + 1) % 256; int i, sum, token; send_to (next, 1); token = recv_from (this); fprintf (stdout, "start\\n"); fflush (stdout); for (i = 0; i < tokens; ++i) send_to (next, i + 1); while (cycles > 0) { for (i = 0; i < tokens; ++i) { token = recv_from (this); send_to (next, token + 1); } cycles--; } sum = 0; for (i = 0; i < tokens; ++i) sum += recv_from (this); fprintf (stdout, "end\\n"); fflush (stdout); fprintf (stdout, "%d\\n", sum); send_to (next, 0); token = recv_from (this); return 0; } static void *element (void *n) { int this = (int) n; int next = (this + 1) % 256; int token; do { token = recv_from (this); send_to (next, token > 0 ? token + 1 : token); } while (token); return 0; } int main (int argc, char *argv[]) { int i; if (argc >= 2) cycles = atoi (argv[1]); else cycles = 0; if (argc >= 3) tokens = atoi (argv[2]); else tokens = 1; for (i = 0; i < 256; ++i) full[i] = data[i] = 0; for (i = 256 - 1; i >= 0; --i) { pthread_mutex_init (&(mutex[i]), 0); pthread_cond_init (&(cond[i]), 0); if (i == 0) pthread_create (&(thread[i]), 0, root, (void *)i); else pthread_create (&(thread[i]), 0, element, (void *)i); } pthread_join (thread[0], 0); return 0; }
0
#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; }
1
#include <pthread.h> pthread_mutex_t mutex; void *thread1(void *null) { printf("\\n In thread1 \\n"); getchar(); if(pthread_mutex_lock(&mutex)==0) { getchar(); } pthread_mutex_unlock(&mutex); getchar(); printf("\\n Exit thread1 \\n"); pthread_exit(0); } void *thread2(void *null) { printf("\\n In thread2 \\n"); sleep(1); getchar(); if(pthread_mutex_lock(&mutex)==0) { sleep(5); pthread_mutex_unlock(&mutex); } printf("\\n Exit thread2 \\n"); pthread_exit(0); } int main (int argc, char *argv[]) { pthread_mutexattr_t attrmutex; int inherit,policy,priority,rc; struct sched_param param; pthread_t tid1,tid2,tid3; pthread_attr_t attr; pthread_attr_init(&attr); pthread_mutexattr_init(&attrmutex); pthread_mutexattr_setprotocol(&attrmutex,PTHREAD_PRIO_INHERIT); pthread_mutex_init(&mutex,&attrmutex); pthread_attr_setinheritsched(&attr,PTHREAD_EXPLICIT_SCHED); param.sched_priority=75; pthread_setschedparam(pthread_self(),SCHED_FIFO,&param); param.sched_priority=70; pthread_attr_setschedpolicy(&attr,SCHED_RR); pthread_attr_setschedparam(&attr,&param); pthread_create(&tid1, &attr, thread1, 0); param.sched_priority=90; pthread_attr_setschedpolicy(&attr,SCHED_RR); pthread_attr_setschedparam(&attr,&param); pthread_create(&tid2, &attr, thread2, 0); rc = pthread_join(tid1,0); rc = pthread_join(tid2,0); pthread_attr_destroy(&attr); printf("\\n Exiting from main Thread\\n"); pthread_exit(0); }
0
#include <pthread.h> sem_t* taquillas; sem_t** salas; int total = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t inicia_pelicula = PTHREAD_COND_INITIALIZER; void* comprarBoleto(void*); void* reloj(void*); int main() { int i, j; taquillas = (sem_t*) malloc (10 * sizeof(sem_t)); salas = (sem_t**) malloc (10 * sizeof(sem_t*)); for (i = 0; i < 10; ++i) { sem_init(&taquillas[i], 0, 3); salas[i] = (sem_t*) malloc (3 * sizeof(sem_t)); for (j = 0; j < 3; ++j) sem_init(&salas[i][j], 0, 50); } srand((int) time(0)); pthread_t thread_reloj; pthread_create(&thread_reloj, 0, reloj, 0); pthread_t threads[1000]; for (i = 0; i < 1000; ++i) { sleep(rand() % 5); pthread_create(&threads[i], 0, comprarBoleto, (void*) (intptr_t) i); } for (i = 0; i < 1000; ++i) { pthread_join(threads[i], 0); ++total; } for (i = 0; i < 10; ++i) { sem_destroy(&taquillas[i]); for (j = 0; j < 3; ++j) sem_destroy(&salas[i][j]); free(salas[i]); } free(salas); free(taquillas); } void* comprarBoleto(void* p) { int id = (intptr_t) p; int complejo = rand() % 10; int sala = rand() % 3; printf("Cliente %d esperando en taquilla. Complejo: %d, Sala: %d\\n", id, complejo, sala); sem_wait(&taquillas[complejo]); printf("Cliente %d comprando boleto. Complejo: %d, Sala: %d\\n", id, complejo, sala); sleep(5); printf("Cliente %d compró boleto. Complejo: %d, Sala: %d\\n", id, complejo, sala); sem_post(&taquillas[complejo]); sem_wait(&salas[complejo][sala]); printf("Cliente %d esperando inicio. Complejo: %d, Sala: %d\\n", id, complejo, sala); pthread_mutex_lock(&mutex); pthread_cond_wait(&inicia_pelicula, &mutex); pthread_mutex_unlock(&mutex); printf("Cliente %d viendo película. Complejo: %d, Sala: %d\\n", id, complejo, sala); sleep(30); sem_post(&salas[complejo][sala]); printf("Cliente %d salió. Complejo: %d, Sala: %d\\n", id, complejo, sala); } void* reloj(void* p) { while (total < 1000) { sleep(60); pthread_mutex_lock(&mutex); printf("\\n\\nInicia la película\\n\\n"); pthread_cond_broadcast(&inicia_pelicula); pthread_mutex_unlock(&mutex); } }
1
#include <pthread.h> struct student { int id; int age; }stu; int i; pthread_mutex_t mutex; void *thread1(void *arg) { while(1) { pthread_mutex_lock(&mutex); stu.id=i; stu.age=i; if(stu.id!=stu.age) { printf("id = %d ,age =%d \\n",stu.id,stu.age); break; } i++; pthread_mutex_unlock(&mutex); } return (void*)0; } void *thread2(void *arg) { while(1) { pthread_mutex_lock(&mutex); stu.id=i; stu.age=i; if(stu.id!=stu.age) { printf("id = %d ,age =%d \\n",stu.id,stu.age); break; } i++; pthread_mutex_unlock(&mutex); } return (void*)0; } int main() { pthread_t tid1,tid2; int err; err = pthread_mutex_init(&mutex,0); if(err) { printf("初始化信号量失败\\n"); return 0; } err = pthread_create(&tid1,0,thread1,0); if(err) { printf("新线程1创建失败\\n"); return 0; } err = pthread_create(&tid2,0,thread2,0); if(err) { printf("新线程2创建失败\\n"); return 0; } pthread_join(tid1,0); pthread_join(tid2,0); return 0; }
0
#include <pthread.h> char character_name[30]; char symbol; int thread_num; int condition; int frozen; int position; pthread_t thread_id; }thread_data; struct mutex_shared{ int BOARD[2][10]; int WINNER; int CONDITION; } SHARED_DATA; pthread_mutex_t object_mutex; void magic(thread_data *objects); void printGrid(); void init_data(thread_data *objects); void place(thread_data *objects, int number); void move_object(thread_data *objects); int getRandom(int rangeLow, int rangeHigh, struct timeval time); void move_object(thread_data *objects){ struct timeval time; pthread_mutex_lock(&object_mutex); if(SHARED_DATA.CONDITION == objects->condition && SHARED_DATA.WINNER != 1){ SHARED_DATA.CONDITION = objects->thread_num; if(objects->frozen == 0 && objects->thread_num != 2){ SHARED_DATA.BOARD[objects->thread_num][objects->position] = '-'; printf("%s moved one space\\n",objects->character_name); objects->position++; SHARED_DATA.BOARD[objects->thread_num][objects->position] = objects->symbol; }else if(objects->thread_num == 2){ if(objects[0].frozen == 1){ objects[0].frozen = 0; }else{ objects[0].frozen = getRandom(0,1,time); } if(objects[1].frozen == 1){ objects[1].frozen = 0; }else{ objects[1].frozen = getRandom(0,1,time); } }else{ printf("%s is frozen\\n", objects->character_name); } if(objects->position >= 9){ SHARED_DATA.WINNER = 1; printf("%s wins !", objects->character_name); } } printf("shared %d, objects %d\\n",SHARED_DATA.CONDITION, objects->condition); printGrid(); pthread_mutex_unlock(&object_mutex); } void *API(void *thread){ static int count = 0; thread_data *objects = (thread_data *)thread; while(SHARED_DATA.WINNER != 1){ move_object(objects); sleep(2); } pthread_exit(0); } void printGrid(){ for(int i=0; i<2; i++){ for(int j=0; j<10; j++){ printf("%c", SHARED_DATA.BOARD[i][j]); } printf("\\n"); } } int getRandom(int rangeLow, int rangeHigh, struct timeval time){ gettimeofday(&time, 0); srandom((unsigned int) time.tv_usec); double myRand = rand()/(1.0 + 32767); int range = rangeHigh - rangeLow + 1; int myRand_scaled = (myRand * range) + rangeLow; return myRand_scaled; } void init_data(thread_data *objects){ struct timeval time; for(int i=0; i<2; i++){ for(int j=0; j<10; j++){ SHARED_DATA.BOARD[i][j] = '-'; } } printGrid(); SHARED_DATA.CONDITION = 2; objects[0].symbol = 'T'; objects[0].thread_num = 0; objects[0].condition = 2; objects[0].frozen = 0; objects[0].position = 0; strcpy(objects[0].character_name, "Tweety"); objects[1].symbol = 'M'; objects[1].thread_num = 1; objects[1].condition = 0; objects[1].frozen = 0; objects[1].position = 0; strcpy(objects[1].character_name, "Muttley"); objects[2].symbol = 'A'; objects[2].thread_num = 2; objects[2].condition = 1; objects[2].frozen = 0; objects[2].position = 0; strcpy(objects[2].character_name, "Marvin"); for(int i=0; i<3; i++){ printf("name: %s, symbol: %c, thread_num: %d\\n", objects[i].character_name, objects[i].symbol, objects[i].thread_num); printf("-----------------------------------------------\\n"); } SHARED_DATA.BOARD[0][0] = objects[0].symbol; SHARED_DATA.BOARD[1][0] = objects[1].symbol; printGrid(); } int main(int argc, char *argv[]){ thread_data thread[3]; init_data(thread); pthread_mutex_init(&object_mutex, 0); for(int i=0; i<3; i++){ thread[i].thread_num = i; pthread_create(&(thread[i].thread_id), 0, API,(void *)(&thread[i])); } for(int i=0; i<3; i++){ pthread_join(thread[i].thread_id, 0); } pthread_mutex_destroy(&object_mutex); return 0; }
1
#include <pthread.h> void *SighandThread(void *args) { while(1) { if(flag_mask) { flag_mask_copy = flag_mask; if (flag_mask & TIMER_EVENT) { flag_mask ^= TIMER_EVENT; } if (flag_mask & ASYNC_EVENT) { flag_mask ^= ASYNC_EVENT; } if (flag_mask & SIGINT_EVENT) { printf("%s\\n","Sighandler got SIGINT"); flag_mask ^= SIGINT_EVENT; break; } } else { pthread_mutex_lock(&dataQ_mutex); pthread_cond_wait(&condvar,&dataQ_mutex); pthread_mutex_unlock(&dataQ_mutex); } } printf("%s\\n","Outside sighandler thread"); } void sighandler_sigint(int signum) { printf("Caught signal sigint, coming out...\\n"); flag_mask |= SIGINT_EVENT; int32_t retval = pthread_cond_broadcast(&condvar); if(retval != 0) { printf("condition signal failed, error code - %d\\n", retval); } } void sighandler_sigusr1(int signum) { printf("Caught signal sigusr, coming out...\\n"); uint8_t c; uint32_t bytes_sent=0; memset(logmsg_req, 0, sizeof(LogMsg)); printf("before get char in sig usr1 \\n"); srand(time(0)); c = rand() % 2; printf("rand value - %d\\n", c); if(c == 0) { printf("%s char - %d\\n","yaha aaya",c); logmsg_req->sourceId = MAIN_TASK; logmsg_req->requestID = GET_TEMP_C; logmsg_req->level = INFO; logmsg_req->timestamp = time(0); printf("%s\\n","Struct created"); pthread_mutex_lock(&tempQ_mutex); if ((bytes_sent = mq_send (tempreq_queue_handle,(const char*)&logmsg_req, sizeof(LogMsg), 7)) != 0) { perror ("[HandlerThread] Sending:"); } pthread_mutex_unlock(&tempQ_mutex); printf("%s\\n","Struct sent"); flag_mask |= ASYNC_EVENT; int32_t retval = pthread_cond_broadcast(&condvar); if(retval != 0) { printf("condition signal failed, error code - %d\\n", retval); } } if(c==1) { printf("%s char - %d\\n","yaha pe aaya",c); logmsg_req->sourceId = MAIN_TASK; logmsg_req->requestID = GET_TEMP_K; logmsg_req->level = WARNING; logmsg_req->timestamp = time(0); pthread_mutex_lock(&tempQ_mutex); if ((bytes_sent = mq_send(tempreq_queue_handle,(const char*)&logmsg_req, sizeof(LogMsg), 8)) != 0) { perror ("[HandlerThread] Sending:"); } pthread_mutex_unlock(&tempQ_mutex); usleep(100); flag_mask |= ASYNC_EVENT; int32_t retval = pthread_cond_broadcast(&condvar); if(retval != 0) { printf("condition signal failed, error code - %d\\n", retval); } } printf("return from sigusr1 sighandler \\n"); }
0
#include <pthread.h> void *producer (void *args); void *consumer (void *args); pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; sem_t notFull; sem_t notEmpty; int buf[4]; long head, tail; int full, empty; } queue; queue *queueInit (void); void queueDelete (queue *q); void queueAdd (queue *q, int in); void queueDel (queue *q, int *out); int main () { queue *fifo; pthread_t pro, con; fifo = queueInit (); if (fifo == 0) { fprintf (stderr, "main: Queue Init failed.\\n"); exit (1); } sem_init(&notEmpty, 0, 0); sem_init(&notFull, 0, 4); pthread_create (&pro, 0, producer, fifo); pthread_create (&con, 0, consumer, fifo); pthread_join (pro, 0); pthread_join (con, 0); queueDelete (fifo); return 0; } void *producer (void *q) { queue *fifo; int i; fifo = (queue *)q; for (i = 0; i < 20; i++) { if (fifo->full) { printf ("producer: queue FULL.\\n"); } sem_wait(&notFull); pthread_mutex_lock(&mut); queueAdd (fifo, i); pthread_mutex_unlock(&mut); sem_post(&notEmpty); printf("producer: inserted %d\\n",i); usleep (100000); } return (0); } void *consumer (void *q) { queue *fifo; int i, d; fifo = (queue *)q; for (i = 0; i < 20; i++) { if (fifo->empty) { printf ("consumer: queue EMPTY.\\n"); } sem_post(&notEmpty); pthread_mutex_lock(&mut); queueDel (fifo, &d); pthread_mutex_unlock(&mut); sem_post(&notFull); printf ("consumer: recieved %d.\\n", d); usleep(200000); } return (0); } queue *queueInit (void) { queue *q; q = (queue *)malloc (sizeof (queue)); if (q == 0) return (0); q->empty = 1; q->full = 0; q->head = 0; q->tail = 0; return (q); } void queueDelete (queue *q) { free (q); } void queueAdd (queue *q, int in) { q->buf[q->tail] = in; q->tail++; if (q->tail == 4) q->tail = 0; if (q->tail == q->head) q->full = 1; q->empty = 0; return; } void queueDel (queue *q, int *out) { *out = q->buf[q->head]; q->head++; if (q->head == 4) q->head = 0; if (q->head == q->tail) q->empty = 1; q->full = 0; return; }
1
#include <pthread.h> int R[MAX_N+1][MAX_C+1]; int thread_create(void * (*start_func)(void *), void *arg){ int status = 0; pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); status = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); if(status == 0) status = pthread_create(&tid, &attr, start_func, arg); if(status != 0) status = pthread_create(&tid, 0, start_func, arg); return status; } int sync_progress = 0; pthread_mutex_t sync_mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t sync_cond = PTHREAD_COND_INITIALIZER; void barrier_sync(int num_process,int pid){ pthread_mutex_lock(&sync_mut); if(sync_progress + 1 < num_process){ ++sync_progress; pthread_cond_wait(&sync_cond,&sync_mut); } else{ pthread_cond_broadcast(&sync_cond); } pthread_mutex_unlock(&sync_mut); } int max(int i,int j){ return i>=j ? i : j; } int min(int i,int j){ return i<=j ? i : j; } void t_knapsack(int num_thread,int tid,int *P,int *W,int N,int C){ int i,j,prg; --W;--P; for(i=1;i<=N;i++){ int t = C / num_thread + 1; for(j=t*tid+1; j<=min(C,t*(tid+1)) ;j++){ int v = (j-W[i]>=0) ? P[i] + R[i-1][j-W[i]] : 0; R[i][j] = max(R[i-1][j],v); } barrier_sync(num_thread,tid); } } struct ThreadParams{ int num_thread; int tid; int *P; int *W; int N; int C; }; void *exec_thread(void *param){ struct ThreadParams *p = param; t_knapsack(p->num_thread,p->tid,p->P,p->W,p->N,p->C); return 0; } int p_knapsack(int num_thread,int *P,int *W,int N,int C){ int i; for(i=0;i<=C;++i)R[0][i] = 0; for(i=1;i<=N;++i)R[i][0] = 0; struct ThreadParams *p = (struct ThreadParams*)malloc(sizeof(struct ThreadParams) * num_thread); sync_progress = 0; for(i=0;i<num_thread;++i){ p[i].num_thread = num_thread; p[i].tid = i; p[i].P = P; p[i].W = W; p[i].N = N; p[i].C = C; } for(i=0;i<num_thread-1;++i) thread_create(exec_thread,&p[i]); exec_thread(&p[num_thread-1]); return R[N][C]; } double elapsed_time(struct timeval start,struct timeval end) { return end.tv_sec-start.tv_sec + 1e-6*(end.tv_usec-start.tv_usec); } main(){ struct timeval start,end; gettimeofday(&start, 0); int t,i,T,N,C,*P,*W; const int num_thread = 2; scanf("%d",&T); for(t=0;t<T;++t){ scanf("%d",&C); scanf("%d",&N); P = (int*)malloc(sizeof(int) * N); W = (int*)malloc(sizeof(int) * N); for(i=0;i<N;++i){ scanf("%d %d",&W[i],&P[i]); } printf("%d\\n",p_knapsack(num_thread,P,W,N,C)); } gettimeofday(&end, 0); printf("%lf\\n", elapsed_time(start,end)); }
0
#include <pthread.h> struct threadData { char *t; char *p; int t_len; int p_len; int startpos; }; void readtext(char *t, int len); void *search(void *arg); int found = 0; int p_index; pthread_mutex_t lock; int main(int argc, char *argv[]) { if (argc != 3) exit(1); int t_len = atoi(argv[2]); char *pattern = (char *) malloc(100); strcpy(pattern, argv[1]); char *text = (char *) malloc(t_len); readtext(text, t_len); pthread_t tid[10]; ThreadData threadArgs[10]; pthread_mutex_init(&lock, 0); int id; for (id = 0; id < 10; id++) { threadArgs[id].t = text; threadArgs[id].p = pattern; threadArgs[id].t_len = t_len; threadArgs[id].p_len = strlen(pattern); threadArgs[id].startpos = id; int status = pthread_create(&tid[id], 0, search, &threadArgs[id]); if (status != 0) { printf("Can't create thread %d.\\n", id); exit(1); } } for (id = 0; id < 10; id++) pthread_join(tid[id], 0); if (found) printf("Pattern beings at character %d.\\n", p_index + 1); else printf("Pattern not found!\\n"); free(pattern); pattern = 0; free(text); text = 0; pthread_exit(0); } void readtext(char *t, int len) { int i = 0; char c; while (scanf("%c", &c) != EOF && i < len) { t[i] = c; i++; } } void *search(void *arg) { ThreadData *myargs = (ThreadData *) arg; char *text = myargs->t; char *pattern = myargs->p; int t_len = myargs->t_len; int p_len = myargs->p_len; int start = myargs->startpos; int i, count; while (1) { count = 0; pthread_mutex_lock(&lock); if (found || start + p_len > t_len) { pthread_mutex_unlock(&lock); break; } for (i = 0; i < p_len; i++) if (text[start + i] == pattern[i]) count++; else break; if (count == p_len) { found = 1; p_index = start; pthread_mutex_unlock(&lock); break; } else pthread_mutex_unlock(&lock); start += 10; } pthread_exit(0); }
1
#include <pthread.h> struct job{ pthread_t tid; Job next; int val; }; pthread_mutex_t q_lock=PTHREAD_MUTEX_INITIALIZER; int insert(Job head,int val,pthread_t tid) { Job p,q; p=head; if(p!=0) { while(p->next!=0) { p=p->next; } } q=(struct job *)malloc(sizeof(struct job)); if(q==0) { perror("fail to malloc"); return -1; } q->next=0; q->val=val; q->tid=tid; if(p==0) { head=q; return 0; } p->next=q; return 0; } int free_job(Job head) { struct job * p, *q; for(p=head;p!=0;p=p->next) { q=p; p=p->next; free(q); } return 0; } void print(Job head) { Job p; for(p=head;p!=0;p=p->next) printf("thread %u: val %d\\n",(unsigned int)p->tid,p->val); } void * tf9(void *arg) { long long count; struct job *p,*q; struct job *task=0; pthread_t tid; struct timeval begintime,endtime; float elapsed_time; tid=pthread_self(); count=0; while(count<100000000) { if(pthread_mutex_trylock(&q_lock)==0) { q=(struct job *)arg; p=q->next; while(p!=0) { if(tid==p->tid) count++; p=p->next; } pthread_mutex_unlock(&q_lock); } } gettimeofday(&endtime,0); elapsed_time=1000000*(endtime.tv_sec-begintime.tv_sec)+endtime.tv_usec-begintime.tv_usec; elapsed_time/=1000000; printf("This total used time is:%f secons.\\n",elapsed_time); return (void *)0; } int main(void) { struct job *item; struct job *p,*q; pthread_t tid1,tid2; int i,err; struct timeval begintime; gettimeofday(&begintime,0); item=(struct job *)malloc(sizeof(struct job)); item->next=0; item->val=0; item->tid=-1; err=pthread_create(&tid1,0,tf9,item)!=0; if(err!=0) { printf("fail to create thread %d\\n",strerror(err)); exit(1); } if(pthread_create(&tid2,0,tf9,item)!=0) { printf("fail to create thread %d\\n",strerror(err)); exit(1); } printf("===the 1st put===\\n"); pthread_mutex_lock(&q_lock); for(i=0;i<2;i++) { if(insert(item,i,tid1)==-1) exit(1); if(insert(item,i+1,tid2)==-1) exit(1); } if(insert(item,10,tid1)==-1) exit(1); pthread_mutex_unlock(&q_lock); printf("===the 2nd put===\\n"); pthread_mutex_lock(&q_lock); if(insert(item,9,tid2)==-1) exit(1); pthread_mutex_lock(&q_lock); err=pthread_join(tid1,0); if(err!=0) { printf("can't join thread %d\\n",strerror(err)); exit(1); } pthread_join(tid2,0); if(err!=0) { printf("can't join thread %d\\n",strerror(err)); exit(1); } printf("main thread done\\n"); return 0; }
0
#include <pthread.h> struct melon g_melon; int melon_init(uint32_t nb_threads) { uint32_t i = 0; g_melon.stop = 0; g_melon.fibers_count = 0; g_melon.ready = 0; pthread_mutexattr_t mutex_attr; if (pthread_mutexattr_init(&mutex_attr)) return -1; if (pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE)) goto failure_mutex; if (pthread_mutex_init(&g_melon.lock, &mutex_attr)) goto failure_mutex; pthread_mutexattr_destroy(&mutex_attr); if (pthread_cond_init(&g_melon.ready_cond, 0)) goto failure_cond; if (pthread_cond_init(&g_melon.fibers_count_zero, 0)) goto failure_cond2; melon_stack_init(); if (nb_threads == 0) nb_threads = sysconf(_SC_NPROCESSORS_ONLN); g_melon.threads_nb = nb_threads > 0 ? nb_threads : 1; int rlimit_nofile = _POSIX_OPEN_MAX; struct rlimit rl; if (!getrlimit(RLIMIT_NOFILE, &rl)) rlimit_nofile = rl.rlim_max; g_melon.io = calloc(1, sizeof (*g_melon.io) * rlimit_nofile); if (!g_melon.io) goto failure_calloc; if (melon_io_manager_init()) goto failure_io_manager; if (melon_timer_manager_init()) goto failure_timer_manager; g_melon.threads = malloc(sizeof (*g_melon.threads) * g_melon.threads_nb); for (i = 0; i < g_melon.threads_nb; ++i) if (pthread_create(g_melon.threads + i, 0, melon_sched_run, 0)) goto failure_pthread; return 0; failure_pthread: g_melon.stop = 1; for (; i > 0; --i) pthread_join(g_melon.threads[i - 1], 0); free(g_melon.threads); g_melon.threads = 0; melon_timer_manager_deinit(); failure_timer_manager: melon_io_manager_deinit(); failure_io_manager: free(g_melon.io); g_melon.io = 0; failure_calloc: pthread_cond_destroy(&g_melon.fibers_count_zero); failure_cond2: pthread_cond_destroy(&g_melon.ready_cond); failure_cond: pthread_mutex_destroy(&g_melon.lock); failure_mutex: pthread_mutexattr_destroy(&mutex_attr); return -1; } void melon_deinit() { assert(g_melon.fibers_count == 0); pthread_mutex_lock(&g_melon.lock); g_melon.stop = 1; pthread_cond_broadcast(&g_melon.ready_cond); pthread_mutex_unlock(&g_melon.lock); melon_io_manager_deinit(); melon_timer_manager_deinit(); for (unsigned i = 0; i < g_melon.threads_nb; ++i) pthread_join(g_melon.threads[i], 0); free(g_melon.threads); g_melon.threads = 0; melon_stack_deinit(); pthread_cond_destroy(&g_melon.fibers_count_zero); pthread_cond_destroy(&g_melon.ready_cond); pthread_mutex_destroy(&g_melon.lock); free(g_melon.io); g_melon.io = 0; } void melon_wait() { pthread_mutex_lock(&g_melon.lock); while (1) { assert(g_melon.fibers_count >= 0); if (g_melon.fibers_count == 0) break; pthread_cond_wait(&g_melon.fibers_count_zero, &g_melon.lock); } pthread_mutex_unlock(&g_melon.lock); }
1
#include <pthread.h> static int medium_ended; static int go_foward; pthread_mutex_t mutex; void* thread1_code(void* args){ struct sched_param param; param.sched_priority = 30; pthread_setschedparam(pthread_self(),SCHED_FIFO,&param); printf("Thread basse priorite\\n"); pthread_mutex_lock(&mutex); while(!go_foward); pthread_mutex_unlock(&mutex); pthread_exit(0); } void* thread2_code(void* args){ struct sched_param param; param.sched_priority = 50; pthread_setschedparam(pthread_self(),SCHED_FIFO,&param); printf("Thread moyenne priorite\\n"); medium_ended = 1; pthread_exit(0); } void* thread3_code(void* args){ struct sched_param param; param.sched_priority = 80; pthread_setschedparam(pthread_self(),SCHED_FIFO,&param); printf("Thread haute priorité\\n"); pthread_mutex_lock(&mutex); if(medium_ended == 1) printf("INVERSION DE PRIORITE\\n"); else printf("PAS D'INVERSION DE PRIORITE\\n"); pthread_exit(0); } int main(int argc,char** argv){ pthread_t threads[3]; pthread_mutexattr_t m_attr; void *arg; arg = malloc(sizeof(char)); pthread_mutexattr_init(&m_attr); pthread_mutexattr_setpshared(&m_attr, PTHREAD_PROCESS_SHARED); if(argc==2 && strcmp(argv[1],"heritage")==0){ pthread_mutexattr_setprotocol(&m_attr, PTHREAD_PRIO_INHERIT); printf("Heritage de priorité activé\\n"); } pthread_mutex_init(&mutex, &m_attr); pthread_create(&threads[0],0,&thread1_code,arg); sleep(5); pthread_create(&threads[1],0,&thread3_code,arg); sleep(5); pthread_create(&threads[2],0,&thread2_code,arg); go_foward=1; pthread_join(threads[1],0); return 0; }
0
#include <pthread.h> float hole= 0; int flag= 0; pthread_mutex_t lock_hole; pthread_cond_t cond_hole; void delay(){ int aux2; for (aux2= 600000; aux2 > 0; aux2--); return; } void delay2(){ int aux2; for (aux2= 100000; aux2 > 0; aux2--); return; } double get(){ int aux1; pthread_mutex_lock(&lock_hole); pthread_cond_wait(&cond_hole, &lock_hole); aux1= hole; pthread_mutex_unlock(&lock_hole); return aux1; } double inc(){ int aux1; pthread_mutex_lock(&lock_hole); for (aux1=0;aux1<10;aux1++) { hole= hole + 0.100000000; delay2(); } pthread_cond_signal(&cond_hole); pthread_mutex_unlock(&lock_hole); return hole; } void* producer(int* name){ int aux1, aux2, aux3, count; for (aux1 = 0; aux1 < 20; aux1++) { printf("Producer inc: %.3f\\n", inc()); } pthread_exit(0); } void* consumer(int* name){ int aux1, aux2, aux3; for (aux1 = 0; aux1 < 10; aux1++) { printf("Consumer got: %.3f\\n", get()); delay(); } pthread_exit(0); } void main(){ pthread_t simpleThread1, simpleThread2; int status, aux1, priority; int pro1 = 0; int pro2 = 1; pthread_mutex_init(&lock_hole, 0); pthread_cond_init(&cond_hole, 0); pthread_setconcurrency(100); printf("Concurrency %d\\n", pthread_getconcurrency()); pthread_create(&simpleThread1, 0, producer, (void*) &pro1); pthread_create(&simpleThread2, 0, consumer, (void*) 0); pthread_join(simpleThread1, 0); pthread_join(simpleThread2, 0); }
1
#include <pthread.h> struct foo { int f_count; int f_addtimes; pthread_mutex_t f_mutex; }; struct foo * foo_alloc() { struct foo* fp; fp = (struct foo*)malloc(sizeof(struct foo)); if(fp != 0) { fp->f_count = 0; fp->f_addtimes = 0; pthread_mutex_init(&fp->f_mutex,0); } return fp; } void foo_addtimes(struct foo *fp) { pthread_mutex_lock(&fp->f_mutex); fp->f_addtimes++; pthread_mutex_unlock(&fp->f_mutex); } void foo_add(struct foo *fp) { pthread_mutex_lock(&fp->f_mutex); fp->f_count++; foo_addtimes(fp); pthread_mutex_unlock(&fp->f_mutex); } void * thread_func1(void *arg) { struct foo *fp = (struct foo*)arg; printf("thread 1 start.\\n"); foo_add(fp); printf("in thread 1 count = %d\\n",fp->f_count); printf("thread 1 exit.\\n"); pthread_exit((void*)1); } int main() { pthread_t pid1; int err; void *pret; struct foo *fobj; fobj = foo_alloc(); pthread_create(&pid1,0,thread_func1,(void*)fobj); pthread_join(pid1,&pret); printf("thread 1 exit code is: %d\\n",(int)pret); exit(0); }
0
#include <pthread.h> void *v1(void *path){ if (start_time.tv_sec == 0 && start_time.tv_usec == 0) { if (gettimeofday(&start_time, 0)) { fprintf(stderr, "Failed to run Variant 1: unable to get current time\\n"); exit(1); } } char *file, *file_ext, new_path[1000]; pthread_t thread; DIR *inDir; struct dirent *inDirent; struct stat st; pthread_mutex_lock(&log_mutex); num_dir++; num_threads++; pthread_mutex_unlock(&log_mutex); inDir = opendir(path); if (!inDir) { fprintf(stderr, "Error encountered in Variant 1: invalid input path.\\n"); fprintf(stderr, " Unable to open directory at %s\\n", (char *) path); pthread_exit(0); } while ( (inDirent = readdir(inDir)) ) { file = inDirent->d_name; strcpy(new_path, path); strcat(new_path, "/"); strcat(new_path, file); if (!strcmp(file, ".") || !strcmp(file, "..") || !strcmp(file, ".DS_Store")) { continue; } stat(new_path, &st); if (S_ISDIR(st.st_mode)) { pthread_create(&thread, 0, v1, new_path); pthread_join(thread, 0); continue; } file_ext = strrchr(file, '.'); if (!file_ext) { continue; } pthread_mutex_lock(&log_mutex); num_files++; pthread_mutex_unlock(&log_mutex); if (!strcmp(file_ext, ".png") || !strcmp(file_ext, ".bmp") || !strcmp(file_ext, ".gif") || !strcmp(file_ext, ".jpg")) { pthread_mutex_lock(&html_mutex); generate_html(new_path); pthread_mutex_unlock(&html_mutex); } } pthread_mutex_lock(&time_mutex); if (gettimeofday(&end_time, 0)) { fprintf(stderr, "Failed to run Variant 1: unable to get current time\\n"); exit(1); } pthread_mutex_unlock(&time_mutex); closedir(inDir); pthread_exit(0); }
1
#include <pthread.h> int main(int argc,char **argv) { int ret; pthread_t view_id; pid_t view_pid=0,audio_pid=0; fb_init(); ts_init(); show_jpglogo("./image/welcome.jpg"); sleep(3); show_menu(); ret = pthread_create(&view_id, 0,picview_thread, 0); if(ret == -1) goto pthread_create_err; while(1) { pthread_mutex_lock(&mutex); printf(" main get lock!\\n"); m = get_motion(); printf(" main put lock!\\n"); pthread_mutex_unlock(&mutex); usleep(1000); switch(m) { case button1: printf("button1 Prev\\n"); if(audio_pid != 0) kill(audio_pid,SIGKILL); audio_pid = start_audio(BACKWARD); break; case button2: printf("button2 Next\\n"); if(audio_pid != 0) kill(audio_pid,SIGKILL); audio_pid = start_audio(FORWARD); break; case button3: printf("button3 Stop\\n"); kill(audio_pid,SIGSTOP); break; case button4: printf("button4 Continue\\n"); kill(audio_pid,SIGCONT); break; case button5: printf("button5 Load\\n"); traverse_file_dir("/photo/dir"); signal(SIGCHLD,waitp); break; } } fb_uninit(); ts_uninit(); return 0; pthread_create_err: printf(" pthread_create err!\\n"); return -1; }
0
#include <pthread.h> double x; double y; double r; } Ball; struct _listNode * next; int isblock; Ball ball; } listNode; float startx; float starty; float endx; float endy; } PM; void insert(Ball ball, int isblock); double distance(Ball b1, Ball b2); double m_abs(double num); int judge(Ball b); void freeBox(); void putBall(); void search(void *pm); void putBlock(double x, double y); listNode *head = 0, *tail = 0; Ball maxBall; double step = 1/128.0; int num = 0; double r2 = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int flag = 1; int main(int argc, char *argv[]) { int n, blocks, i; pthread_mutex_init(&mutex,0); printf("\\n\\nEnter the number of balls and blocks (to put blocks add number and position): "); while(scanf("%d%d", &n, &blocks) != EOF) { num = 0, r2 = 0; head = 0, tail = 0; for(i = 0; i < blocks; i ++) { double x, y; scanf("%lf%lf", &x, &y); putBlock(x, y); } printf("\\nnum\\t x\\t y\\t r\\t sum(r^2)\\n"); for(i = 0; i < n; i ++) { putBall(); } freeBox(); printf("\\nsum of R^2:\\t %lf\\n", r2); flag = 1; printf("\\n\\nEnter the number of balls and blocks (to put blocks add number and position): "); } printf("\\n"); return 0; } void putBlock(double x, double y) { Ball ball = {x, y, 0}; insert(ball, 1); } void freeBox() { printf("Ball.r: "); while(head) { listNode *tmp = head; head = tmp->next; printf("%lf ", tmp->ball.r); free(tmp); } } void insert(Ball ball, int isblock) { listNode * node = (listNode *)malloc(sizeof(listNode)); if (isblock || flag) { node->isblock = isblock; node->ball = ball; node->next = head; head = node; tail = head; if ((!isblock) && flag) { flag = 0; } } else { node->isblock = isblock; node->ball = ball; node->next = tail->next; tail->next = node; tail = node; } } void putBall() { int i; pthread_t thread[4]; PM *pm[4]; for (i = 0; i < 4; i++) { pm[i] = (PM*)malloc(sizeof(PM)); } Ball ball = {-1, -1, 0}; maxBall = ball; pm[0]->startx=-1, pm[0]->starty=-1, pm[0]->endx=0, pm[0]->endy=0; pm[1]->startx=-1, pm[1]->starty=0, pm[1]->endx=0, pm[1]->endy=1; pm[2]->startx=0, pm[2]->starty=-1, pm[2]->endx=1, pm[2]->endy=0; pm[3]->startx=0, pm[3]->starty=0, pm[3]->endx=1, pm[3]->endy=1; pthread_create (&thread[0], 0, (void*)search, (void*)pm[0]); pthread_create (&thread[1], 0, (void*)search, (void*)pm[1]); pthread_create (&thread[2], 0, (void*)search, (void*)pm[2]); pthread_create (&thread[3], 0, (void*)search, (void*)pm[3]); pthread_join (thread[0], 0); pthread_join (thread[1], 0); pthread_join (thread[2], 0); pthread_join (thread[3], 0); if(judge(maxBall)) { insert(maxBall, 0); num++; r2 += maxBall.r * maxBall.r; printf("%d\\t %.3lf\\t %.3lf\\t %.3lf\\t %lf \\n", num, maxBall.x, maxBall.y, maxBall.r, r2); } } void search(void *p) { int i, j; PM *pm = (PM*)p; Ball ball = {pm->startx, pm->starty, 0}; for (i = 0; ball.x <= pm->endx; ++i) { ball.x += step; ball.y = -1; for (j = 0; ball.y <= pm->endy; ++j) { ball.y += step; ball.r = 0; double rstep = 0.1; while(rstep >= 0.00001) { if(ball.r > maxBall.r) { pthread_mutex_lock(&mutex); maxBall = ball; pthread_mutex_unlock(&mutex); } ball.r += rstep; if(!judge(ball)) { ball.r -= rstep; rstep /= 10; } } } } } int judge(Ball b) { if((m_abs(b.x) + b.r) > 1 || (m_abs(b.y) + b.r) > 1) { return 0; } listNode *tmp = head; while(tmp) { Ball ball = tmp->ball; if(distance(b, ball) < b.r + ball.r ) { return 0; } tmp = tmp->next; } return 1; } double m_abs(double num) { if(num > 0) return num; return 0 - num; } double distance(Ball b1, Ball b2) { double x1 = b1.x; double y1 = b1.y; double x2 = b2.x; double y2 = b2.y; return pow((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2), 0.5); }
1
#include <pthread.h> void *Producer(); void *Consumer(); int BufferIndex = 0; int counter = 100; char *BUFFER; pthread_cond_t Buffer_Not_Full = PTHREAD_COND_INITIALIZER; pthread_cond_t Buffer_Not_Empty = PTHREAD_COND_INITIALIZER; pthread_mutex_t mVar = PTHREAD_MUTEX_INITIALIZER; int main() { pthread_t ptid, ctid; BUFFER = (char *) malloc(sizeof(char) * 10); pthread_create(&ptid, 0, Producer, 0); pthread_create(&ctid, 0, Consumer, 0); pthread_join(ptid, 0); pthread_join(ctid, 0); return 0; } void *Producer() { for(int i = 1; i <= counter; i++){ pthread_mutex_lock(&mVar); if(BufferIndex == 10){ pthread_cond_wait(&Buffer_Not_Full, &mVar); } BUFFER[BufferIndex++] = '@'; printf("Produce : %d, i = %d\\n", BufferIndex, i); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Empty); } return 0; } void *Consumer() { for(int j = 1; j <= counter; j++){ pthread_mutex_lock(&mVar); if(BufferIndex == -1){ pthread_cond_wait(&Buffer_Not_Empty, &mVar); } printf("Consume : %d, j = %d \\n", BufferIndex--, j); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Full); } return 0; }
0
#include <pthread.h> pthread_mutex_t gLock; int val = 10; void *Print(void *pArg) { int id = getpid(); printf("I am the PTHREAD. My PID is %d\\n", id); pthread_mutex_lock(&gLock); val += 1; pthread_mutex_unlock(&gLock); return 0; } int main (int argc, char **argv, char **envp) { pthread_t tHandles; int pid = getpid(); int ret; pthread_mutex_init(&gLock,0); printf("I am the MAIN. My PID is %d\\n", pid); ret = pthread_create(&tHandles, 0, Print, (void *)5); if (ret) { printf("Error, value returned from create_thread: %d\\n", ret); } else { printf("I am the MAIN, and I successfully launched a pthread.\\n"); pthread_mutex_lock(&gLock); val -= 1; pthread_mutex_unlock(&gLock); ret = pthread_join(tHandles, 0); if(ret) { printf("Error on join()\\n"); exit(-1); } printf("I am the MAIN, the pthread has finished\\n"); printf("val: %d\\n", val); } pthread_exit(0); return 0; }
1
#include <pthread.h> char letters[26] = "abcdefghijklmnopqrstuvwxyz"; pthread_mutex_t mutex; useconds_t delays[3]; void * invert_letters() { static char curr_low = 1; while(1) { int i; pthread_mutex_lock(&mutex); for (i = 0; i < 26; ++i) { letters[i] += curr_low ? -32 : 32; } curr_low = !curr_low; pthread_mutex_unlock(&mutex); usleep(delays[1]); } return 0; } void * inverse_letters() { while(1) { int i = 0; char swap; pthread_mutex_lock(&mutex); for (i = 0; i < 26 / 2; ++i) { swap = letters[i]; letters[i] = letters[26 - i - 1]; letters[26 - i - 1] = swap; } pthread_mutex_unlock(&mutex); usleep(delays[2]); } return 0; } void sig_handler(int signo) { if (signo == SIGINT) { printf("%s\\n", "Destroying mutex"); pthread_mutex_destroy(&mutex); _exit(0); } } int main(int argc, char * argv[]) { pthread_t thread1; pthread_t thread2; int i; for (i = 1; i < 3; ++i) { delays[i - 1] = i < argc ? strtol(argv[i], 0, 10) * 1000: 1000000; if (delays[i - 1] <= 0) { delays[i - 1] = 1000000; } } pthread_mutex_init(&mutex, 0); if (signal(SIGINT, sig_handler) == SIG_ERR) perror("Could not catch SIGINT\\n"); pthread_create(&thread1, 0, invert_letters, 0); pthread_create(&thread2, 0, inverse_letters, 0); while(1) { pthread_mutex_lock(&mutex); printf("%s\\n", letters); pthread_mutex_unlock(&mutex); usleep(delays[0]); } return 0; }
0
#include <pthread.h> void *philosopher (void *id); void grab_chopstick (int, int, char *); void down_chopsticks (int, int); int food_on_table (); pthread_mutex_t chopstick[5]; pthread_t philo[5]; pthread_mutex_t food_lock; int sleep_seconds = 0; int i; int main (int argn, char **argv){ if (argn == 2) sleep_seconds = atoi (argv[1]); else { printf("The program requires an interger argument representing the number of seconds philosopher 1 sleeps \\n"); exit(1); } pthread_mutex_init (&food_lock, 0); for (i = 0; i < 5; i++) pthread_mutex_init (&chopstick[i], 0); for (i = 0; i < 5; i++) pthread_create (&philo[i], 0, philosopher, (void *)(intptr_t)i); for (i = 0; i < 5; i++) pthread_join (philo[i], 0); return 0; } void * philosopher (void *num) { int id; int i, left_chopstick, right_chopstick, f; id = (intptr_t)num; printf ("Philosopher %d is done thinking and now ready to eat.\\n", id); right_chopstick = id; left_chopstick = id + 1; if (left_chopstick == 5) left_chopstick = 0; while ((f = food_on_table ())>0) { if (id == 1) { printf("Philosopher 1 sleeps %d\\n", sleep_seconds); sleep (sleep_seconds); } if(id % 2 == 0){ grab_chopstick (id, right_chopstick, "right "); grab_chopstick (id, left_chopstick, "left"); } if(id % 2 != 0){ grab_chopstick (id, left_chopstick, "left"); grab_chopstick (id, right_chopstick, "right "); } printf ("Philosopher %d: eating.\\n", id); usleep (5000 * (100 - f + 1)); down_chopsticks (left_chopstick, right_chopstick); } printf ("Philosopher %d is done eating.\\n", id); return (0); } int food_on_table (){ static int food = 100; int myfood; pthread_mutex_lock (&food_lock); if (food > 0) { food--; } myfood = food; pthread_mutex_unlock (&food_lock); return myfood; } void grab_chopstick (int phil, int c, char *hand) { printf ("Philosopher %d: try to get %s chopstick %d\\n", phil, hand, c); pthread_mutex_lock (&chopstick[c]); printf ("Philosopher %d: got %s chopstick %d\\n", phil, hand, c); } void down_chopsticks (int c1, int c2){ pthread_mutex_unlock (&chopstick[c1]); pthread_mutex_unlock (&chopstick[c2]); }
1
#include <pthread.h>extern int __VERIFIER_nondet_int(void); extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; void init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for(i=0; i<(20); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for(i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutexWriter = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexReader = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t condReader = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int condition = 0; int count = 0; int put = 0; int get = 0; int readerCount; int ReadingRoom[4]; int reader(void) { int threadNr = pthread_self(); printf("create reader : %d \\n", threadNr); while( 1 ) { pthread_mutex_lock( &mutex ); while( condition == 0 ) pthread_cond_wait( &cond, &mutex ); printf("reader %d read\\n", threadNr ); condition = 0; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } void* writer( void * arg ) { while( 1 ) { pthread_mutex_lock( &mutex ); while( condition == 1 ) pthread_cond_wait( &cond, &mutex ); printf("writer %d write\\n", pthread_self() ); condition = 1; pthread_cond_signal( &cond ); pthread_mutex_unlock( &mutex ); } return( 0 ); } pthread_t tid[5]; int main( void ) { int i = 0; pthread_create( 0, 0, &writer, 0 ); for(i=0; i < 4 ; i++){ pthread_create(&tid[i],0,reader, 0 ); } }
1
#include <pthread.h> char state[3][10]; pthread_mutex_t chopstick[5]=PTHREAD_MUTEX_INITIALIZER; void *fun(int j){ printf("hungry: %d\\n",j); if(j%2==0){ pthread_mutex_lock(&chopstick[j]); pthread_mutex_lock(&chopstick[(j+1)%5]); }else{ pthread_mutex_lock(&chopstick[(j+1)%5]); pthread_mutex_lock(&chopstick[j]); } printf("Started Eating: %d\\n",j); sleep(5); printf("Finish Eating: %d\\n",j); pthread_mutex_unlock(&chopstick[j]); pthread_mutex_unlock(&chopstick[(j+1)%5]); printf("thinking: %d\\n"); } int main(int argc,char *argv[]){ if(argc!=2){fprintf(stderr,"Enter number of threads\\n"); exit(1);} int size,i; size=atoi(argv[1]); pthread_t thread_id[size]; printf("Everyone is thinking\\n"); for(i=0;i<5;i++){ strcpy(state[i],"thinking"); pthread_mutex_init(&chopstick[i], 0); } for(i=0;i<size;i++){ sleep(2); pthread_create(&thread_id[i],0,&fun,i); } for(i=0;i<size;i++){ pthread_join(thread_id[i],0); } return 0; }
0
#include <pthread.h> struct pbxfoo *pbxfoo_alloc(void) { struct pbxfoo *fp = 0; if((fp=(struct pbxfoo *)malloc(sizeof(struct pbxfoo))) != 0){ memset(fp, 0, sizeof(struct pbxfoo)); fp->f_ref = 1; if(pthread_mutex_init(&fp->f_lock, 0) != 0 ){ free(fp); return 0; } } return fp; } void pbxfoo_ref(struct pbxfoo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_ref++; pthread_mutex_unlock(&fp->f_lock); } void pbxfoo_unref(struct pbxfoo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_ref--; pthread_mutex_unlock(&fp->f_lock); } void pbxfoo_show(struct pbxfoo *fp) { if(fp != 0){ fprintf(stderr, "Results :\\n"); fprintf(stderr, "f_count : %d\\n", fp->f_ref); fprintf(stderr, "name : %s\\n", fp->name); fprintf(stderr, "score : %d\\n", fp->score); } else{ fprintf(stderr, "pass a NULL pointer to %s\\n", __func__); } } void pbxfoo_destroy(struct pbxfoo *fp) { pthread_mutex_lock(&fp->f_lock); if(--fp->f_ref == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); }else{ pthread_mutex_unlock(&fp->f_lock); } } void pbxfoo_maintest(struct pbxfoo *fp) { if(fp != 0){ pbxfoo_ref(fp); snprintf(fp->name, 32, "Yuesichiu"); fp->score = 98; pbxfoo_show(fp); pbxfoo_unref(fp); } } int main() { int res = 0; struct pbxfoo *fp = pbxfoo_alloc(); if(fp == 0){ return 0; } pbxfoo_maintest(fp); pbxfoo_destroy(fp); return 0; }
1
#include <pthread.h> void *sum(void *p); double *v1, *v2; double sumtotal = 0.0; int numthreads, n; pthread_mutex_t mutex; int main(int argc, char **argv) { int i; pthread_t workers[8]; struct timeval start, end; gettimeofday(&start, 0); pthread_mutex_init(&mutex, 0); scanf("%d %d", &n, &numthreads); v1 = (double *) malloc(n * sizeof (double)); v2 = (double *) malloc(n * sizeof (double)); for (i = 0; i < n; i++) { v1[i] = 1; v2[i] = 2; } for (i = 0; i < numthreads; i++) pthread_create(&workers[i], 0, sum, i); for (i = 0; i < numthreads; i++) pthread_join(workers[i], 0); free(v1); free(v2); pthread_mutex_destroy(&mutex); gettimeofday(&end, 0); long spent = (end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec); printf("%.0f\\n%ld\\n", sumtotal, spent); return 0; } void *sum(void *p) { int myid = (int) p; int start = (myid * (long long) n) / numthreads; int end = ((myid + 1) * (long long) n) / numthreads; int i, k = myid, m = 1, len; double sum = 0.0; len = end - start; for (i = 0; i < len / 64; i++) { for (k = 0; k < 64; k++) { m = start + (i * 64 + k); sum += v1[m] * v2[m]; } } if ((len / 64) * 64 != len) { for (m = start + (len / 64) * 64; m < end; m++) { sum += v1[m] * v2[m]; } } pthread_mutex_lock(&mutex); sumtotal += sum; pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> int buffer[3]; int add = 0; int rem = 0; int num = 0; pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t c_cons = PTHREAD_COND_INITIALIZER; pthread_cond_t c_prod = PTHREAD_COND_INITIALIZER; void *producer(void *param); void *consumer(void *param); int main(int argc, char *argv[]) { pthread_t tid1, tid2; int i; if (pthread_create(&tid1, 0, producer, 0) != 0) { fprintf(stderr, "Unable to create producer thread\\n"); exit(1); } if (pthread_create(&tid2, 0, consumer, 0) != 0) { fprintf(stderr, "Unable to create consumer thread\\n"); exit(1); } pthread_join(tid1, 0); pthread_join(tid2, 0); printf("Parent quiting\\n"); } void *producer(void *param) { int i; for (i = 0; i <= 20; i++) { pthread_mutex_lock(&m); if (num > 3) exit(1); while (num == 3) pthread_cond_wait(&c_prod, &m); buffer[add] = i; add = (add + 1) % 3; num++; pthread_mutex_unlock(&m); pthread_cond_signal(&c_cons); printf("producer: inserted %d \\n", i); fflush(stdout); } printf("producer quiting \\n"); fflush(stdout); return 0; } void *consumer(void *param) { int consnum; while (1) { pthread_mutex_lock(&m); if (num < 0) exit(1); while (num == 0) pthread_cond_wait(&c_cons, &m); consnum = buffer[rem]; rem = (rem + 1) % 3; num--; pthread_mutex_unlock(&m); pthread_cond_signal(&c_prod); printf("Consumer: consumed %d \\n", consnum);fflush(stdout); } }
1
#include <pthread.h> pthread_mutex_t mutexid; pthread_mutex_t mutexres; int idcount = 0; pthread_mutex_t joinmutex[4]; int join[4]; int result[4]; int target; int sequence[(4 * 30)]; void *thread (void *arg) { int id, i, from, count, l_target; pthread_mutex_lock (&mutexid); l_target = target; id = idcount; idcount++; pthread_mutex_unlock (&mutexid); __VERIFIER_assert (id >= 0); __VERIFIER_assert (id <= 4); from = id * 30; count = 0; for (i = 0; i < 30; i++) { if (sequence[from + i] == l_target) { count++; } if (count > 30) { count = 30; } } printf ("t: id %d from %d count %d\\n", id, from, count); pthread_mutex_lock (&mutexres); result[id] = count; pthread_mutex_unlock (&mutexres); pthread_mutex_lock (&joinmutex[id]); join[id] = 1; pthread_mutex_unlock (&joinmutex[id]); return 0; } int main () { int i; pthread_t t[4]; int count; i = __VERIFIER_nondet_int (0, (4 * 30)-1); sequence[i] = __VERIFIER_nondet_int (0, 3); target = __VERIFIER_nondet_int (0, 3); printf ("m: target %d\\n", target); pthread_mutex_init (&mutexid, 0); pthread_mutex_init (&mutexres, 0); for (i = 0; i < 4; i++) { pthread_mutex_init (&joinmutex[i], 0); result[i] = 0; join[i] = 0; } i = 0; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; pthread_create (&t[i], 0, thread, 0); i++; __VERIFIER_assert (i == 4); int j; i = 0; pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } pthread_mutex_lock (&joinmutex[i]); j = join[i]; pthread_mutex_unlock (&joinmutex[i]); i++; if (j == 0) { return 0; } if (i != 4) { return 0; } __VERIFIER_assert (i == 4); count = 0; for (i = 0; i < 4; i++) { count += result[i]; printf ("m: i %d result %d count %d\\n", i, result[i], count); } printf ("m: final count %d\\n", count); __VERIFIER_assert (count >= 0); __VERIFIER_assert (count <= (4 * 30)); return 0; }
0
#include <pthread.h> struct apc100{ int fd; struct apc100_cumulativeness cumulativenss; pthread_t tid; pthread_mutex_t cumulativeness_lock; void *cb_in_arg; void (*cb_in)(void*, struct apc100_cumulativeness *); }; static void _noncanonical(struct termios *t) { t->c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); } static void _baudrate_115200(struct termios *t) { cfsetispeed(t, B9600); cfsetospeed(t, B9600); } static void _8N1(struct termios *t) { t->c_cflag &= ~PARENB; t->c_cflag &= ~CSTOPB; t->c_cflag &= ~CSIZE; t->c_cflag |= CS8; } static void _flowcontrol_off(struct termios *t) { t->c_cflag &= ~CRTSCTS; t->c_cflag |= CREAD | CLOCAL; t->c_cflag &= ~(IXON | IXOFF | IXANY); t->c_cc[VMIN] = 43; t->c_cc[VTIME] = 0; } static void _response_parse(char *response, struct apc100_cumulativeness *c) { char in_str[6] = {0,}; char out_str[6] = {0,}; char count_str[6] = {0,}; memcpy(in_str, &response[9], 5); memcpy(out_str, &response[15], 5); memcpy(count_str, &response[21], 5); c->in = atoi(in_str); c->out = atoi(out_str); c->count = atoi(count_str); } static void* _polling(void *arg) { struct apc100 *a = arg; struct apc100_cumulativeness c; while (1) { if (apc100_cumulativeness(a, &c) < 0) goto yield; if (memcmp(&a->cumulativenss, &c, sizeof(struct apc100_cumulativeness)) == 0) goto yield; if (a->cumulativenss.in != c.in) { if (a->cb_in) a->cb_in(a->cb_in_arg, &c); } memcpy(&a->cumulativenss, &c, sizeof(struct apc100_cumulativeness)); yield: sched_yield(); pthread_testcancel(); } return 0; } static void _polling_cancel(struct apc100 *a) { pthread_cancel(a->tid); pthread_join(a->tid, 0); } static void _polling_start(struct apc100 *a) { pthread_create(&a->tid, 0, _polling, a); } int apc100_cumulativeness(void *_a, struct apc100_cumulativeness *c) { if (_a == 0) { return -1; } struct apc100 *a = _a; pthread_mutex_lock(&a->cumulativeness_lock); usleep(1000); char *cmd = "[0000BTR]"; int written = write(a->fd, cmd, strlen(cmd)); if (written != strlen(cmd)) { printf("[ERR] written failed. %d\\n", written); goto err_write; } char response[43 + 1] = {0,}; int nr_read = read(a->fd, response, sizeof(response)); if (nr_read != 43) { printf("[ERR] read failed. %d\\n", nr_read); goto err_read; } pthread_mutex_unlock(&a->cumulativeness_lock); printf("%s\\n", response); _response_parse(response, c); return 0; err_write: err_read: pthread_mutex_unlock(&a->cumulativeness_lock); return -1; } int apc100_in_trigger(void *_a, void (*cb)(void *, struct apc100_cumulativeness*), void *arg) { if (_a == 0) { return -1; } struct apc100* a = _a; a->cb_in = cb; a->cb_in_arg = arg; return 0; } void *apc100_init(char *tty) { if (tty == 0) { printf("[ERR] Invalid tty\\n"); return 0; } struct apc100 *a = calloc(1, sizeof(struct apc100)); if (a == 0) { printf("[ERR] calloc failed. size:%ld\\n", sizeof(struct apc100)); return 0; } a->fd = open(tty, O_RDWR|O_NOCTTY); if (a->fd == -1) { printf("[ERR] tty open failed\\n"); goto err_open; } struct termios termios; tcgetattr(a->fd, &termios); _baudrate_115200(&termios); _8N1(&termios); _flowcontrol_off(&termios); _noncanonical(&termios); if (tcsetattr(a->fd, TCSANOW, &termios) < 0) { printf("[ERR] tcsetattr failed\\n"); goto err_tcsetattr; } pthread_mutex_init(&a->cumulativeness_lock, 0); _polling_start(a); return a; err_tcsetattr: close(a->fd); err_open: free(a); return 0; } void apc100_cleanup(void *_a) { if (!_a) return; struct apc100 *a = _a; _polling_cancel(a); close(a->fd); free(a); }
1
#include <pthread.h> inline unsigned int hash_pjw(const char* name) { unsigned int val = 0,i; for(; *name; ++name){ val = (val << 2) + *name; if(i = val & ~0x3fff) val = (val ^ (i >> 12)) & 0x3fff; } return val; } void initContactorTable() { int i; for(i = 0; i < hashTableSize; i++){ pthread_mutex_init( &contactorTable[i].lock, 0 ); contactorTable[i].addr = -1; } } int contactorReg(const char *name, const int addr) { unsigned int val = hash_pjw(name); pthread_mutex_lock( &contactorTable[val].lock ); if( contactorTable[val].addr == -1 ){ contactorTable[val].addr = addr; pthread_mutex_unlock( &contactorTable[val].lock ); return 1; } else{ pthread_mutex_unlock( &contactorTable[val].lock ); return 0; } } int contactorIsExist(const char *name) { unsigned int val = hash_pjw(name); return contactorTable[val].addr; } int contactorGetAddr(const char *name) { unsigned int val = hash_pjw(name); return (contactorTable[val].addr); } void contactorOffline(const char *name) { unsigned int val = hash_pjw(name); assert( contactorTable[val].addr ); pthread_mutex_lock( &contactorTable[val].lock ); close(contactorTable[val].addr); contactorTable[val].addr = -1; pthread_mutex_unlock( &contactorTable[val].lock ); } void contactorTableDestory() { int i; for(i = 0; i < hashTableSize; i++){ ; } }
0
#include <pthread.h> void trends_pos(double *dt_p, struct task_par *tp) { if(((*dt_p) += 2 ) >= (dx-5)) { rectfill(screen, d, sezy-1, d+dx, sezy-d-dy, COL_BG); (*dt_p) = 0; } axis(d, sezy-d, "theta"); line(screen, d, sezy-d -fmod(PID_p[n_p].ref, dy), d +dx-5, sezy-d -fmod(PID_p[n_p].ref, dy), COL_REF); pthread_mutex_lock(&mux_p[n_p]); line(screen, (*dt_p) +d, sezy-d, (*dt_p) +d, (-out_ctr_p[n_p] +sezy-d), COL_MOT_REF); pthread_mutex_unlock(&mux_p[n_p]); } void trends_vel(double *dt_v, struct task_par *tp) { if(((*dt_v) += 2 ) >= (dx-5)) { rectfill(screen, d+sezxm, sezy-1, d+sezxm+dx, sezy-d -dy, COL_BG); (*dt_v) = 0; } axis(d+sezxm, sezy-d, "omega"); line(screen, d+sezxm, sezy-d -fmod(PID_v[n_v].ref, dy), d+sezxm+dx-5, sezy-d -fmod(PID_v[n_v].ref, dy), COL_REF); pthread_mutex_lock(&mux_v[n_v]); line(screen, (*dt_v)+ d+sezxm, sezy-d, (*dt_v) +d+sezxm, (-out_ctr_v[n_v] +sezy-d), COL_MOT_REF); pthread_mutex_unlock(&mux_v[n_v]); } void trends_tor(double *dt_t, struct task_par *tp) { if(((*dt_t) += 2 ) >= (dx-5)) { rectfill(screen, d+2*sezxm, sezy-1, d+2*sezxm+dx, sezy-d-dy, COL_BG); (*dt_t) = 0; } axis(d+2*sezxm, sezy-d, "torque"); line(screen, d+2*sezxm, sezy-d -fmod(PID_t[n_t].ref, dy), d+2*sezxm+dx-5, sezy-d -fmod(PID_t[n_t].ref, dy), COL_REF); pthread_mutex_lock(&mux_t[n_t]); line(screen, (*dt_t) +d+2*sezxm, sezy-d, (*dt_t) +d+2*sezxm, (-out_ctr_t[n_t] +sezy-d), COL_MOT_REF); pthread_mutex_unlock(&mux_t[n_t]); }
1
#include <pthread.h> int threads_amount; char *file_name; int records_to_read; char *to_find; int records_size = 1024; int fd; int END_FILE = 0; int records_transfered; int *finished; pthread_key_t records; pthread_t *threads; pthread_mutex_t out_mutex = PTHREAD_MUTEX_INITIALIZER; int main(int argc, char *argv[]) { if (argc < 5) { printf("Usage: finder threads_amount file_name records_to_read to_find\\n"); exit(0); } else { threads_amount = atoi(argv[1]); file_name = argv[2]; records_to_read = atoi(argv[3]); to_find = argv[4]; } fd = open(file_name, O_RDONLY); if (fd == -1) { perror("File doesn't exists!"); exit(-1); } int err; pthread_key_create(&records, 0); threads = malloc(threads_amount * sizeof(pthread_t)); for (int t = 0; t < threads_amount; t++) { err = pthread_create(&threads[t], 0, &do_some_thing, 0); if (err == -1) { perror("erroor while creating thread\\n"); } } for (int t = 0; t < threads_amount; t++) pthread_join(threads[t], 0); for (int r = 0; r < records_to_read; r++) { pthread_key_delete(records); } return 0; } void *do_some_thing(void *arg) { pthread_t myTID = pthread_self(); if (-1 == pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, 0)) { perror("setting cancel_type"); exit(-1); } while (!END_FILE) { pthread_testcancel(); if (read_file()) { END_FILE = 1; } else { void *buff; buff = pthread_getspecific(records); int index; char *record = malloc(sizeof(char) * 1020); for (int r = 0; r < records_to_read; r++) { memcpy(&index, buff, sizeof(int)); buff += sizeof(int); memcpy(record, buff, 1020); if (record) if (strstr(record, to_find) != 0) { pthread_mutex_lock(&out_mutex); for (int act_t = 0; act_t < threads_amount; act_t++) { if (!pthread_equal(myTID, threads[act_t])) { pthread_cancel(threads[act_t]); } END_FILE = 1; } printf("TID: %ld Found %s in\\n %d %s\\n", myTID, to_find, index, record); pthread_mutex_unlock(&out_mutex); exit(0); } buff += 1020; } pthread_testcancel(); } } } int read_file() { void *buff = malloc(sizeof(char) * 1024 * records_to_read); ssize_t bytes_read; bytes_read = read(fd, buff, sizeof(char) * 1024 * records_to_read); pthread_setspecific(records, buff); return !bytes_read; }
0
#include <pthread.h> pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER; int sum = 0; void *countgold(void *param) { int i; for (i = 0; i < 10000000; i++) { pthread_mutex_lock(&m); sem_wait(&s); sum += 1; sem_post(&s); pthread_mutex_unlock(&m); } return 0; } int main() { pthread_t tid1, tid2; pthread_create(&tid1, 0, countgold, 0); pthread_create(&tid2, 0, countgold, 0); pthread_join(tid1, 0); pthread_join(tid2, 0); pthread_mutex_destroy(&m); printf("ARRRRG sum is %d\\n", sum); return 0; }
1
#include <pthread.h> volatile int counter = 0; pthread_mutex_t mutext = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void * pthread_func(void * arg){ pthread_mutex_lock(&mutext); while(1){ do{ printf("thread2: counter = %d\\n",counter); while(counter ==8){ printf("thread2: wait start\\n"); pthread_cond_wait(&cond,&mutext); printf("thread2: wait end\\n"); } counter++; }while(counter<20); counter = 20; } } int main(int argc, char *argv[]){ pthread_t a_thread,b_thread; pthread_create(&a_thread,0, pthread_func, 0); int i; while(1){ printf("main_thread: counter = %d\\n",counter); pthread_mutex_lock(&mutext); if(counter ==8){ pthread_cond_signal(&cond); counter = 0; printf("main_thread: counter changed = %d\\n",counter); } pthread_mutex_unlock(&mutext); } pthread_join (a_thread,0); 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 *idp) { int j, i; double result = 0.0; int *my_id = idp; 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 %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); for (j = 0; j < 1000; j++) result = result + (double) random (); } pthread_exit (0); } void *watch_count (void *idp) { int *my_id = idp; printf ("Starting watch_count(): thread %d\\n", *my_id); pthread_mutex_lock (&count_mutex); while (count < 12) { pthread_cond_wait (&count_threshold_cv, &count_mutex); printf ("watch_count(): thread %d Condition signal received.\\n", *my_id); } pthread_mutex_unlock (&count_mutex); pthread_exit (0); } int main (int argc, char *argv []) { int i, rc; 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, inc_count, (void *) &thread_ids [0]); pthread_create (&threads [1], &attr, inc_count, (void *) &thread_ids [1]); pthread_create (&threads [2], &attr, watch_count, (void *) &thread_ids [2]); 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> extern int makethread(void* (*)(void*), void*); struct to_info { void (*to_fun)(void*); void *to_arg; struct timespec to_wait; }; void my_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) { printf("entry thread\\n"); struct to_info* tip = (struct to_info*)arg; clock_nanosleep(0, 0, &tip->to_wait, 0); (*tip->to_fun)(tip->to_arg); free(arg); return 0; } void timeout(const struct timespec* when, void (*func)(void*), void* arg) { printf("entry timeout\\n"); struct timespec now; struct to_info* tip; int ret; my_clock_gettime(0, &now); if((when->tv_sec>now.tv_sec) || (when->tv_sec==now.tv_sec && when->tv_nsec>now.tv_nsec)) { tip = (struct to_info*)malloc(sizeof(struct to_info)); if(tip!=0) { tip->to_fun = 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; } printf("ready to call helper\\n"); ret = makethread(timeout_helper, (void*)tip); if(ret==0) return; else free(tip); } } (*func)(arg); } pthread_mutexattr_t attr; pthread_mutex_t mutex; void retry(void* arg) { pthread_mutex_lock(&mutex); printf("entry retry function\\n"); printf("arg: %lu\\n", (unsigned long)arg); pthread_mutex_unlock(&mutex); } int main(int argc, char** argv) { int ret; if((ret=pthread_mutexattr_init(&attr))!=0) { perror("pthrea_mutexattr_init failed"); exit(1); } if((ret=pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE))!=0) { perror("cannot set recursive type"); exit(1); } if((ret=pthread_mutex_init(&mutex, &attr))!=0) { perror("cannot create recursive mutex"); exit(1); } int condition = 1; pthread_mutex_lock(&mutex); if(condition) { unsigned long arg = 2; struct timespec when; my_clock_gettime(0, &when); when.tv_sec += 5; timeout(&when, retry, (void*)(arg)); } pthread_mutex_unlock(&mutex); sleep(10); exit(0); }
0
#include <pthread.h> void *philosopher_thread(void *); pthread_mutex_t monitor = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t conditions[5]; int forks[5]; int main(int argc, char *argv[]) { pthread_t philosophers[5]; for (int i = 0; i < 5; i++) pthread_create(&philosophers[i], 0, &philosopher_thread, (void *)(intptr_t) i); for (int i = 0; i < 5; i++) pthread_join(philosophers[i], 0); } void *philosopher_thread(void * args) { int position = (intptr_t) args; int counter = 0; int left = position; int right = (position + 1) % 5; while (1) { pthread_mutex_lock(&monitor); while(forks[left]) pthread_cond_wait(&conditions[left], &monitor); while(forks[right]) pthread_cond_wait(&conditions[right], &monitor); forks[right] = forks[left] = 1; printf("Philsopher nr %d \\t get forks\\n", position); pthread_mutex_unlock(&monitor); printf("Philsopher nr %d \\t is eating\\n", position); counter++; forks[right] = forks[left] = 0; printf("Philsopher nr %d \\t released forks\\n", position); pthread_cond_signal(&conditions[left]); pthread_cond_signal(&conditions[right]); } }
1
#include <pthread.h> struct pid_data{ pthread_mutex_t pid_mutex; pid_t pid; }; int set_priority(int priority){ int policy; struct sched_param param; if (priority < 1 || priority > 63) return -1; pthread_getschedparam(pthread_self(), &policy, &param); param.sched_priority = priority; return pthread_setschedparam(pthread_self(), policy, &param); } int get_priority(){ int policy; struct sched_param param; pthread_getschedparam(pthread_self(), &policy, &param); return param.sched_curpriority; } int main(int argc, char *argv[]) { set_priority(4); printf("Welcome to Hello, we are creating memory\\n"); int fd = shm_open("/sharepid", O_RDWR |O_CREAT, S_IRWXU); ftruncate(fd, sizeof(struct pid_data)); struct pid_data *ptr = (struct pid_data*)mmap(0,sizeof(struct pid_data),PROT_READ | PROT_WRITE,MAP_SHARED,fd,0); pthread_mutexattr_t myattr; pthread_mutexattr_setpshared(&myattr, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&ptr->pid_mutex, &myattr ); pthread_mutex_lock(&ptr->pid_mutex); ptr->pid = getpid(); printf("PID written: %i\\n", ptr->pid); pthread_mutex_unlock(&ptr->pid_mutex); char data_buffer[100]; char message_reply[] = "Message reply"; struct _msg_info msg_info; int ch_id = ChannelCreate(0); while(1){ int msg_id = MsgReceive(ch_id, data_buffer, 100*sizeof(char),&msg_info); printf("Current server priority: %i\\n", get_priority()); printf("Data buffer received from Client: %s\\n", data_buffer); printf("Client PID: %i\\nClient TID: %i\\n", msg_info.pid, msg_info.tid); MsgReply(msg_id, 0, message_reply, sizeof(message_reply)); } return 0; }
0
#include <pthread.h> pthread_mutex_t globalLock; int nb_lecteur; pthread_cond_t notif_lecteur; pthread_cond_t notif_ecrivain; int redacteur_attente; int on_a_ecrivain; int on_a_lecteur; } lecteur_redacteur_t; lecteur_redacteur_t lecteur_redacteur; int iterations; int donnee; } donnees_thread_t; void dodo(int scale) { usleep((random()%1000000)*scale); } void initialiser_lecteur_redacteur (lecteur_redacteur_t* lr) { pthread_mutex_init(&lr->globalLock, 0); pthread_cond_init(&lr->notif_lecteur, 0); pthread_cond_init(&lr->notif_ecrivain, 0); lr->nb_lecteur = 0; lr->redacteur_attente = 0; lr->on_a_ecrivain = 0; lr->on_a_lecteur = 0; } void detruire_lecteur_redacteur (lecteur_redacteur_t* lr) { pthread_mutex_destroy(&lr->globalLock); pthread_cond_destroy(&lr->notif_lecteur); pthread_cond_destroy(&lr->notif_ecrivain); } void debut_lecture(lecteur_redacteur_t* lr){ pthread_mutex_lock(&lr->globalLock); while(lr->on_a_ecrivain){ pthread_cond_wait(&lr->notif_lecteur, &lr->globalLock); } lr->nb_lecteur++; pthread_mutex_unlock(&lr->globalLock); } void fin_lecture(lecteur_redacteur_t* lr){ pthread_mutex_lock(&lr->globalLock); lr->nb_lecteur--; if(lr->nb_lecteur == 0) { pthread_cond_signal(&lr->notif_ecrivain); } pthread_mutex_unlock(&lr->globalLock); } void debut_redaction(lecteur_redacteur_t* lr){ pthread_mutex_lock(&lr->globalLock); lr->redacteur_attente++; while(lr->on_a_ecrivain || lr->nb_lecteur){ pthread_cond_wait(&lr->notif_ecrivain, &lr->globalLock); } lr->redacteur_attente--; lr->on_a_ecrivain = 1; pthread_mutex_unlock(&lr->globalLock); } void fin_redaction(lecteur_redacteur_t* lr){ pthread_mutex_lock(&lr->globalLock); lr->on_a_ecrivain = 0; if(lr->redacteur_attente == 0) { pthread_cond_broadcast(&lr->notif_lecteur); } else { pthread_cond_signal(&lr->notif_ecrivain); } pthread_mutex_unlock(&lr->globalLock); } void *lecteur(void *args) { donnees_thread_t *d = args; int i, valeur; srandom((int) pthread_self()); for (i=0; i < d->iterations; i++) { dodo(2); debut_lecture(&d->lecteur_redacteur); printf("Thread %x : debut lecture\\n", (int) pthread_self()); valeur = d->donnee; dodo(1); printf("Thread %x : ", (int) pthread_self()); if (valeur != d->donnee) printf("LECTURE INCOHERENTE !!!\\n"); else printf("lecture coherente\\n"); fin_lecture(&d->lecteur_redacteur); } pthread_exit(0); } void *redacteur(void *args) { donnees_thread_t *d = args; int i, valeur; srandom((int) pthread_self()); for (i=0; i < d->iterations; i++) { dodo(2); debut_redaction(&d->lecteur_redacteur); printf("Thread %x : debut redaction......\\n", (int) pthread_self()); valeur = random(); d->donnee = valeur; dodo(1); printf("Thread %x : ", (int) pthread_self()); if (valeur != d->donnee) printf("REDACTION INCOHERENTE !!!\\n"); else printf("redaction coherente......\\n"); fin_redaction(&d->lecteur_redacteur); } pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t *threads, *thread_courant; donnees_thread_t donnees_thread; int i, nb_lecteurs, nb_redacteurs; void *resultat; if (argc < 4) { fprintf(stderr, "Utilisation: %s nb_lecteurs nb_redacteurs " "nb_iterations\\n", argv[0]); exit(1); } nb_lecteurs = atoi(argv[1]); nb_redacteurs = atoi(argv[2]); donnees_thread.iterations = atoi(argv[3]); threads = malloc((nb_lecteurs+nb_redacteurs)*sizeof(pthread_t)); thread_courant = threads; initialiser_lecteur_redacteur(&donnees_thread.lecteur_redacteur); for (i=0; i<nb_lecteurs; i++) pthread_create(thread_courant++, 0, lecteur, &donnees_thread); for (i=0; i<nb_redacteurs; i++) pthread_create(thread_courant++, 0, redacteur, &donnees_thread); for (i=0; i<nb_lecteurs+nb_redacteurs; i++) pthread_join(threads[i], &resultat); detruire_lecteur_redacteur(&donnees_thread.lecteur_redacteur); free(threads); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex_sum; long int A[100][100]; long int total; pthread_t threads[1000]; int r; int c; void * threadSum(void *); int main() { int status; long int i; long int j; long int t_no; pthread_attr_t attr; int num_t; pthread_mutex_init(&mutex_sum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); total = 0; scanf("%d %d", &r, &c); for (i = 0; i < r; i++) { for (j = 0; j < c; j++) { scanf("%ld", &A[i][j]); } } num_t = r; for (i = 0; i < num_t; i++) { t_no = i; status = pthread_create(&threads[i], &attr, threadSum, (void *) t_no); if (status) { printf("ERROR: Return code from pthread_create() is %d\\n", status); exit(1); } } pthread_attr_destroy(&attr); for (i = 0; i < num_t; i++) { pthread_join(threads[i], 0); } printf("Total Sum = %ld\\n", total); pthread_mutex_destroy(&mutex_sum); pthread_exit(0); return 0; } void * threadSum(void * t_no) { long int t_n; long int i; long int partial_sum; t_n = (long int) t_no; partial_sum = 0; pthread_mutex_lock(&mutex_sum); for (i = 0; i < c; i++) { partial_sum += A[t_n][i]; } total += partial_sum; pthread_mutex_unlock(&mutex_sum); pthread_exit((void *) 0); }
0
#include <pthread.h> void* funcionProd(void * arg); void* funcionCon(void * arg); int tam_cola = 0,cola = 0,producidos= 0,consumidos=0,items = 0; int hilos_prod,hilos_con; double tprod = 0,tcon= 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condicion1 = PTHREAD_COND_INITIALIZER; pthread_cond_t condicion2 = PTHREAD_COND_INITIALIZER; int main(int argc, char** argv){ int s= 0; if(argc!=7){ printf("Uso correcto:./programa <num_hilos_proc> <tiempo_prod> <num_hilos_const> <tiempo_const> <tam_cola> <total_items>\\n"); } if (argc==7){ hilos_prod = atoi(argv[1]); hilos_con= atoi(argv[3]); tprod = atof(argv[2])/1000000; tcon = atof(argv[4])/1000000; tam_cola = atoi(argv[5]); items = atoi(argv[6]); pthread_t *consumidores = (pthread_t *)malloc(sizeof(pthread_t)*hilos_con); pthread_t *productores = (pthread_t *)malloc(sizeof(pthread_t)*hilos_prod); printf("Numero de productores: %d\\n", hilos_prod); printf("Numero de consumidores: %d\\n", hilos_con); printf("Tamaño de cola: %d elementos\\n", tam_cola); printf("Tiempo de consumo: %.2f segundos\\n", tcon*1000000); printf("Tiempo de producción: %.2f segundos\\n", tprod*1000000); printf("Total de items a producir: %d elementos.\\n\\n",items); if(hilos_con >hilos_prod){ s= hilos_con; } else{ s=hilos_prod; } int *arreglos=malloc(s*sizeof(int)); for(int i=0;i<s;i++){ arreglos[i] =i+1; } for(int i=0;i<s;i++){ if(i<hilos_prod){ pthread_create(&(productores[i]),0,funcionProd,&arreglos[i]); } if(i<hilos_con){ pthread_create(&(consumidores[i]),0,funcionCon,&arreglos[i]); } } for(int i=0;i<s;i++){ if(i<hilos_prod) { pthread_join(productores[i],0); } if(i<hilos_con){ pthread_join(consumidores[i],0); } } pthread_cond_destroy(&condicion1); pthread_cond_destroy(&condicion2); } return 0; } void* funcionProd(void * arg){ int c=0; while(c==0){ pthread_mutex_lock(&mutex); while(cola == tam_cola && consumidos<items) pthread_cond_wait(&condicion2,&mutex); usleep(tprod); if(producidos<items){ cola++; producidos++; printf("Productor %d ha producido 1 item, tamaño cola = %d\\n",*((int *)arg),cola); }else{ c=20; } pthread_cond_signal(&condicion1); pthread_mutex_unlock(&mutex); } return 1; } void* funcionCon(void * arg){ int c=0; while(c==0){ pthread_mutex_lock(&mutex); while(cola == 0 && producidos<items) pthread_cond_wait(&condicion1,&mutex); usleep(tcon); if(consumidos<items){ consumidos=consumidos+1; cola=cola-1; printf("Consumidor %d ha consumido 1 item, tamaño cola = %d\\n",*((int *)arg),cola); }else{ c=20; } pthread_cond_signal(&condicion2); pthread_mutex_unlock(&mutex); } return 1; }
1
#include <pthread.h> extern char dev_camera_mask; extern int dev_camera_fd; extern pthread_mutex_t mutex_camera; extern pthread_cond_t cond_camera; void *pthread_camera (void *arg) { unsigned char picture = 0; if ((dev_camera_fd = open (DEV_CAMERA, O_RDWR | O_NOCTTY | O_NDELAY)) < 0) { printf ("Cann't open file /tmp/webcam\\n"); exit (-1); } printf ("pthread_camera is ok\\n"); while (1) { pthread_mutex_lock (&mutex_camera); pthread_cond_wait (&cond_camera, &mutex_camera); picture = dev_camera_mask; printf("dev_camera_mask = %d\\n", dev_camera_mask); pthread_mutex_unlock (&mutex_camera); switch (picture){ case 1:{ write (dev_camera_fd, "one", 3); break; } case 3:{ write (dev_camera_fd, "three", 5); break; } case 5:{ write (dev_camera_fd, "five", 4); break; } case 7:{ write (dev_camera_fd, "seven", 5); break; } case 9:{ write (dev_camera_fd, "nine", 4); break; } default:{ break; } } } }
0
#include <pthread.h> pthread_mutex_t mtx= PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int BUFFER[5]={1,1,1,0,0}; int N=3; void * productor(){ int i; int j; for(i=0;i<20;i++){ pthread_mutex_lock(&mtx); while(N==5){ pthread_cond_wait(&cond,&mtx); } BUFFER[N]=BUFFER[N]+1; printf("El BUFFER tras producir:"); for(j=0;j<5;j++){ printf("[%d]",BUFFER[j]); } printf(" %d \\n",N); N++; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); } } void * consumidor(){ int i; int j; for(i=0;i<20;i++){ pthread_mutex_lock(&mtx); while(N==0){ pthread_cond_wait(&cond,&mtx); } BUFFER[N-1]=BUFFER[N-1]-1; printf("El BUFFER tras consumir:"); for(j=0;j<5;j++){ printf("[%d]",BUFFER[j]); } printf("\\n"); N--; pthread_cond_signal(&cond); pthread_mutex_unlock(&mtx); } } main(){ pthread_t pthcons, pthprod; int j; pthread_create(&pthcons,0,consumidor,0); pthread_create(&pthprod,0,productor,0); pthread_join(pthcons,0); pthread_join(pthprod,0); for(j=0;j<5;j++){ printf("[%d]",BUFFER[j]); } printf("\\n"); pthread_mutex_destroy(&mtx); pthread_cond_destroy(&cond); }
1
#include <pthread.h> extern char ** environ; pthread_mutex_t env_mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init (void) { pthread_mutexattr_t attr; pthread_mutexattr_init (&attr); pthread_mutexarrt_settype (&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init (&env_mutex, &attr); phtread_mutex_destroy (attr); } int getenv_r (const char * name, char * buf, int buflen) { int len, olen; pthread_once (&init_done, thread_init); len = strlen (name); pthread_mutex_lock (&env_mutex); for (int i = 0; environ[i] != 0; i++) { if ((strncmp (name, environ[i], len) == 0) && (environ[i][len] == '=')) { olen = strlen (&environ[i][len + 1]); if (olen >= buflen) { pthread_mutex_unlock (&env_mutex); return (ENOSPC); } strcpy (buf, &environ[i][len + 1]); pthread_mutex_unlock (&env_mutex); return 0; } } pthread_mutex_unlock (&env_mutex); return (ENOENT); }
0
#include <pthread.h> extern int fd_export; extern int fd_led[8]; extern int fd_led_value[8]; extern int fd_sw[8]; char ld_number[8][3] = {"61", "62", "63", "64", "65", "66", "67", "68"}; char sw_number[8][3] = {"69", "70", "71", "72", "73", "74", "75", "76"}; extern char sw_status[8]; extern int function_status; extern pthread_mutex_t mut; void initGpio() { int i; fd_export = open(M_GPIO_EXPORT, O_WRONLY); for(i=0; i<8; i++) { write(fd_export, ld_number[i], sizeof(ld_number[i])); write(fd_export, sw_number[i], sizeof(ld_number[i])); } fd_led[0] = open(M_GPIO_DIRECTION(61), O_RDWR); fd_led[1] = open(M_GPIO_DIRECTION(62), O_RDWR); fd_led[2] = open(M_GPIO_DIRECTION(63), O_RDWR); fd_led[3] = open(M_GPIO_DIRECTION(64), O_RDWR); fd_led[4] = open(M_GPIO_DIRECTION(65), O_RDWR); fd_led[5] = open(M_GPIO_DIRECTION(66), O_RDWR); fd_led[6] = open(M_GPIO_DIRECTION(67), O_RDWR); fd_led[7] = open(M_GPIO_DIRECTION(68), O_RDWR); for(i=0; i<8; i++) { write(fd_led[i], "out", sizeof("out")); } fd_led_value[0] = open(M_GPIO_VALUE(61), O_RDWR); fd_led_value[1] = open(M_GPIO_VALUE(62), O_RDWR); fd_led_value[2] = open(M_GPIO_VALUE(63), O_RDWR); fd_led_value[3] = open(M_GPIO_VALUE(64), O_RDWR); fd_led_value[4] = open(M_GPIO_VALUE(65), O_RDWR); fd_led_value[5] = open(M_GPIO_VALUE(66), O_RDWR); fd_led_value[6] = open(M_GPIO_VALUE(67), O_RDWR); fd_led_value[7] = open(M_GPIO_VALUE(68), O_RDWR); clearLed(); fd_sw[0] = open(M_GPIO_VALUE(69), O_RDONLY); fd_sw[1] = open(M_GPIO_VALUE(70), O_RDONLY); fd_sw[2] = open(M_GPIO_VALUE(71), O_RDONLY); fd_sw[3] = open(M_GPIO_VALUE(72), O_RDONLY); fd_sw[4] = open(M_GPIO_VALUE(73), O_RDONLY); fd_sw[5] = open(M_GPIO_VALUE(74), O_RDONLY); fd_sw[6] = open(M_GPIO_VALUE(75), O_RDONLY); fd_sw[7] = open(M_GPIO_VALUE(76), O_RDONLY); for(i=0; i<8; i++) { sw_status[i] = '0'; write(fd_led_value[i], GPIO_FALSE, sizeof(GPIO_FALSE)); } sw_status[7] = '1'; function_status = 0; } void closeGpio() { int i; for(i=0; i<8; i++) { write(fd_led_value[i], GPIO_FALSE, sizeof(GPIO_FALSE)); } for(i=0; i<8; i++) { close(fd_sw[i]); close(fd_led_value[i]); close(fd_led[i]); } close(fd_export); fd_export = open(M_GPIO_UNEXPORT, O_WRONLY); for(i=0; i<8; i++) { write(fd_export, ld_number[i], sizeof(ld_number[i])); if(i != 7) write(fd_export, sw_number[i], sizeof(ld_number[i])); } close(fd_export); } void clearLed() { int i; for(i=0; i<8; i++) { write(fd_led_value[i], GPIO_FALSE, sizeof(GPIO_FALSE)); } } void rGetSWFD() { int i; for(i=0; i<8; i++) { close(fd_sw[i]); } fd_sw[0] = open(M_GPIO_VALUE(69), O_RDONLY); fd_sw[1] = open(M_GPIO_VALUE(70), O_RDONLY); fd_sw[2] = open(M_GPIO_VALUE(71), O_RDONLY); fd_sw[3] = open(M_GPIO_VALUE(72), O_RDONLY); fd_sw[4] = open(M_GPIO_VALUE(73), O_RDONLY); fd_sw[5] = open(M_GPIO_VALUE(74), O_RDONLY); fd_sw[6] = open(M_GPIO_VALUE(75), O_RDONLY); fd_sw[7] = open(M_GPIO_VALUE(76), O_RDONLY); } void updateLed() { int i; char sw_value; rGetSWFD(); for(i=0; i<7; i++) { sw_value = '0'; read(fd_sw[i], &sw_value, sizeof(sw_value)); sw_status[i] = sw_value; } function_status = 0; for(i=0; i<7; i++) { if(sw_status[i] == '1') function_status += 1<<i; } if(function_status == 1) return; for(i=0; i<7; i++) { if(sw_status[i] == '1') { write(fd_led_value[i], GPIO_TRUE, sizeof(GPIO_TRUE)); } else { write(fd_led_value[i], GPIO_FALSE, sizeof(GPIO_FALSE)); } } } void* swThread() { while(1) { pthread_mutex_lock(&mut); updateLed(); pthread_mutex_unlock(&mut); sleep(3); } } void setLedValue(int number, int status) { if(status) { write(fd_led_value[number], GPIO_TRUE, sizeof(GPIO_TRUE)); return; } write(fd_led_value[number], GPIO_FALSE, sizeof(GPIO_FALSE)); }
1
#include <pthread.h> volatile int running_threads = 0; pthread_mutex_t running_mutex = PTHREAD_MUTEX_INITIALIZER; void *startThread(void *vargp) { int myid = (int)vargp; if (0) { printf("Thread %d starting...\\n", myid); } if (0) { printf("get_unique_id returned an error!\\n"); exit(1); } int i; for (i = 0; i < 10; i++) { long res; int child_pid = fork(); if (child_pid < 0 ) printf("Fork failed %i \\n", child_pid); else if (child_pid > 0) { size_t limit = 3; size_t nr_children; pid_t pid_list[limit]; res= get_child_pids(pid_list, limit, &nr_children) ? errno : 0; } } pthread_mutex_lock(&running_mutex); running_threads--; pthread_mutex_unlock(&running_mutex); } int main() { int i; pthread_t tid; printf("Creating threads...\\n"); for (i = 0; i < 4 ; i++) { pthread_mutex_lock(&running_mutex); running_threads++; pthread_mutex_unlock(&running_mutex); pthread_create(&tid, 0, startThread, (void *)i); } while (running_threads > 0) { sleep(1); } printf("Things look good!\\n"); pthread_exit(0); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t s[5]; state_t state[5]; int done; int eatcount[5]; void philosopher(void *); void think(int i); void take_forks(int i); void eat(int i); void put_forks(int i); void test(int i); void mysleep(int milliseconds); int main(int argc, char **argv) { int i; pthread_t thread[5]; done = 0; pthread_mutex_init(&mutex, 0); for (i = 0; i < 5; i++) { pthread_cond_init(&s[i], 0); eatcount[i] = 0; } for (i = 0; i < 5; i++) { if (pthread_create(&thread[i], 0, (void *) philosopher, (void *) i) != 0) { perror("pthread_create"); return 1; } } mysleep(10*100); done = 1; for (i = 0; i < 5; i++) { if (pthread_join(thread[i], 0) != 0) { perror("pthread_join"); return 2; } } pthread_mutex_destroy(&mutex); for (i = 0; i < 5; i++) { pthread_cond_destroy(&s[i]); } printf("\\n"); for (i = 0; i < 5; i++) { printf("Philosopher %d got to eat %d times\\n", i, eatcount[i]); } return 0; } void philosopher(void *pi) { int i = (int) pi; printf("philosopher thread %d starting...\\n", i); while (!done) { think(i); take_forks(i); eat(i); put_forks(i); } } void take_forks(int i) { pthread_mutex_lock(&mutex); state[i] = HUNGRY; test(i); while (state[i] != EATING) pthread_cond_wait(&s[i], &mutex); pthread_mutex_unlock(&mutex); } void put_forks(int i) { pthread_mutex_lock(&mutex); state[i] = THINKING; test((((i)+5 -1)%5)); test((((i)+1)%5)); pthread_mutex_unlock(&mutex); } void test(int i) { if (state[i] == HUNGRY && state[(((i)+5 -1)%5)] != EATING && state[(((i)+1)%5)] != EATING) { state[i] = EATING; pthread_cond_signal(&s[i]); } } void think(int i) { int milliseconds = random() % 1000; printf("philosopher %d is thinking for %d milliseconds...\\n", i, milliseconds); mysleep(milliseconds); } void eat(int i) { int milliseconds = random() % 1000; eatcount[i]++; printf("\\tphilosopher %d is eating for %d milliseconds...\\n", i, milliseconds); mysleep(milliseconds); } void mysleep(int milliseconds) { struct timespec ts; ts.tv_sec = milliseconds / 1000; ts.tv_nsec = (milliseconds % 1000) * 1000; nanosleep(&ts, 0); }
1
#include <pthread.h> static int s_interrupted = 0; pthread_mutex_t lock; int req_num = 0; int fd; static void s_signal_handler (int signal_value) { s_interrupted = 1; } static void s_catch_signals (void) { struct sigaction action; action.sa_handler = s_signal_handler; action.sa_flags = 0; sigemptyset (&action.sa_mask); sigaction (SIGINT, &action, 0); sigaction (SIGTERM, &action, 0); } static void *worker_routine(void *context) { struct req_data req_data; char *buf; void *receiver = zmq_socket(context, ZMQ_REP); zmq_connect(receiver, "inproc://workers"); s_catch_signals(); while (1){ m_recv(receiver, &req_data); switch(req_data.length) { case ZERO: buf = (char *)malloc((ZERO + 1) * sizeof(char)); break; case ONE: buf = (char *)malloc((ONE + 1) * sizeof(char)); break; case TWO: buf = (char *)malloc((TWO + 1) * sizeof(char)); break; case THREE: buf = (char *)malloc((THREE + 1) * sizeof(char)); break; default: debug_puts("LENGTH ERROR"); } lseek(fd, req_data.offset, 0); read(fd, buf, req_data.length); s_send(receiver, buf); free(buf); pthread_mutex_lock(&lock); req_num++; pthread_mutex_unlock(&lock); if (s_interrupted) { debug_puts("CTRL+C...."); break; } } zmq_close(receiver); return 0; } int main(int argc, const char *argv[]) { void *context = zmq_init (1); char tcp[14] = "tcp://*:"; strncat(tcp, argv[1], 5); void *service = zmq_socket(context, ZMQ_ROUTER); zmq_bind(service, tcp); void *workers = zmq_socket (context, ZMQ_DEALER); zmq_bind(workers, "inproc://workers"); pthread_mutex_init(&lock, 0); fd = open("/dev/sdb", O_RDONLY); if (fd == -1) { debug_puts("FILE can't open"); return 1; } printf("Waiting for request %s\\n", argv[1]); printf("Create 5 worker thread\\n"); int thread_nbr; for (thread_nbr = 0; thread_nbr < 5; thread_nbr++) { pthread_t worker; pthread_create(&worker, 0, worker_routine, context); } zmq_device (ZMQ_QUEUE, service, workers); debug_print("%d", req_num); zmq_close(service); zmq_close(workers); zmq_term(context); return 0; }
0
#include <pthread.h> const char* text = "Some text!"; const int text_size = 10; const int file_size = (10 * sizeof(char)); pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER; void *thread_one( void *ptr ); void *thread_two( void *ptr ); void main() { pthread_t thread1, thread2; pthread_create( &thread1, 0, thread_one, (void*) 0); pthread_create( &thread2, 0, thread_two, (void*) 0); pthread_join( thread1, 0); pthread_join( thread2, 0); printf("Complete!\\n"); exit(0); } void *thread_one( void *ptr ) { printf("First thread start!\\n"); int i; int fd; int result; char *map; pthread_mutex_lock(&count_mutex); printf("First thread mutex lock!\\n"); fd = open("/tmp/mmapped.bin", O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600); if (fd == -1) { perror("Error opening file for writing"); exit(1); } result = lseek(fd, file_size-1, 0); if (result == -1) { close(fd); perror("Error calling lseek() to 'stretch' the file"); exit(1); } result = write(fd, "", 1); if (result != 1) { close(fd); perror("Error writing last byte of the file"); exit(1); } map = mmap(0, file_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(1); } for (i = 1; i <=text_size; ++i) { map[i] = text[i-1]; } if (munmap(map, file_size) == -1) { perror("Error un-mmapping the file"); } close(fd); pthread_cond_signal( &condition_var ); printf("First thread signal!\\n"); pthread_mutex_unlock( &count_mutex ); printf("First thread mutex unlock!\\n"); printf("First thread end!\\n"); } void *thread_two( void *ptr ) { printf("Second thread start!\\n"); int i; int fd; char *map; pthread_mutex_lock(&count_mutex); printf("Second thread mutex lock!\\n"); printf("Second thread cond wait!\\n"); pthread_cond_wait( &condition_var, &count_mutex ); fd = open("/tmp/mmapped.bin", O_RDONLY); if (fd == -1) { perror("Error opening file for reading"); exit(1); } map = mmap(0, file_size, PROT_READ, MAP_SHARED, fd, 0); if (map == MAP_FAILED) { close(fd); perror("Error mmapping the file"); exit(1); } for (i = 1; i <=text_size; ++i) { printf("%c", map[i]); } printf("\\n"); if (munmap(map, file_size) == -1) { perror("Error un-mmapping the file"); } close(fd); pthread_mutex_unlock( &count_mutex ); printf("Second thread mutex unlock!\\n"); printf("Second thread end!\\n"); }
1
#include <pthread.h> int do_debug = 0; int do_thread = 0; int do_stdin = 0; int do_sleep = 0; pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER; int threadcount = 0; struct sockets { int local; FILE *in, *out; }; struct sockets *get_sockets(int); int socket_setup(void); int debug(char *, ...); int fail(char *, ...); int warn(char *, ...); int roll_die(int); void *roll_dice(void *); void spawn(struct sockets *); int debug(char *fmt, ...) { va_list ap; int r; __builtin_va_start((ap)); if (do_debug) { r = vfprintf(stderr, fmt, ap); } else { r = 0; } ; return r; } int warn(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); ; return r; } int fail(char *fmt, ...) { int r; va_list ap; __builtin_va_start((ap)); r = vfprintf(stderr, fmt, ap); exit(1); ; return r; } int roll_die(int n) { return rand() % n + 1; } void * roll_dice(void *v) { struct sockets *s = v; char inbuf[512]; if (!s || !s->out || !s->in) return 0; fprintf(s->out, "enter die rolls, or q to quit\\n"); while (fgets(inbuf, sizeof(inbuf), s->in) != 0) { int dice; int size; if (inbuf[0] == 'q') { fprintf(s->out, "buh-bye!\\n"); if (s->local == 0) { shutdown(fileno(s->out), SHUT_RDWR); } fclose(s->out); fclose(s->in); if (s->local == 0) { free(s); } pthread_mutex_lock(&count_mutex); --threadcount; if (threadcount == 0) exit(0); pthread_mutex_unlock(&count_mutex); return 0; } if (sscanf(inbuf, "%dd%d", &dice, &size) != 2) { fprintf(s->out, "Sorry, but I couldn't understand that.\\n"); } else { int i; int total = 0; for (i = 0; i < dice; ++i) { int x = roll_die(size); total += x; fprintf(s->out, "%d ", x); fflush(s->out); if (do_sleep) sleep(1); } fprintf(s->out, "= %d\\n", total); } } return 0; } int main(int argc, char *argv[]) { int o; int sock; while ((o = getopt(argc, argv, "dstS")) != -1) { switch (o) { case 'S': do_sleep = 1; break; case 'd': do_debug = 1; break; case 's': do_stdin = 1; break; case 't': do_thread = 1; break; } } if (do_thread) { pthread_mutex_init(&count_mutex, 0); } if (do_stdin) { struct sockets s; s.local = 1; s.in = stdin; s.out = stdout; if (do_thread) { spawn(&s); } else { roll_dice(&s); exit(0); } } sock = socket_setup(); while (1) { struct sockets *s = get_sockets(sock); if (s) { if (do_thread) { spawn(s); } else { roll_dice(s); exit(0); } } } return 0; } int socket_setup(void) { struct protoent *tcp_proto; struct sockaddr_in local; int r, s, one; tcp_proto = getprotobyname("tcp"); if (!tcp_proto) { fail("Can't find TCP/IP protocol: %s\\n", strerror(errno)); } s = socket(PF_INET, SOCK_STREAM, tcp_proto->p_proto); if (s == -1) { fail("socket: %s\\n", strerror(errno)); } one = 1; setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one)); memset(&local, 0, sizeof(struct sockaddr_in)); local.sin_family = AF_INET; local.sin_port = htons(6173); r = bind(s, (struct sockaddr *) &local, sizeof(struct sockaddr_in)); if (r == -1) { fail("bind: %s\\n", strerror(errno)); } r = listen(s, 5); if (r == -1) { fail("listen: %s\\n", strerror(errno)); } return s; } struct sockets * get_sockets(int sock) { int conn; if ((conn = accept(sock, 0, 0)) < 0) { warn("accept: %s\\n", strerror(errno)); return 0; } else { struct sockets *s; s = malloc(sizeof(struct sockets)); if (s == 0) { warn("malloc failed.\\n"); return 0; } s->local = 0; s->in = fdopen(conn, "r"); s->out = fdopen(conn, "w"); setlinebuf(s->in); setlinebuf(s->out); return s; } } void spawn(struct sockets *s) { pthread_t p; pthread_mutex_lock(&count_mutex); pthread_create(&p, 0, roll_dice, (void *) s); ++threadcount; pthread_mutex_unlock(&count_mutex); }
0
#include <pthread.h> int size; char buf[4]; }test_thread_func_st; void sbt_thread_detatch( ){ pthread_detach(pthread_self()); } void sbt_thread_exit( ){ pthread_exit(0); } static void *sub_thread_detach(test_thread_func_st* param){ int i; pthread_t tid = pthread_self(); LOGD("Start(threadID=0x%x)", tid ); LOGD("param->size=%d", param->size ); for( i=0; i<param->size; i++ ){ sleep(1); LOGI("param->buf[%d]=%d", i, param->buf[i] ); } LOGD("End(threadID=0x%x)", tid); sbt_thread_detatch(); return 0; } static void *sub_thread_join(int* param){ int i; pthread_t tid = pthread_self(); LOGD("Start(threadID=0x%x)", tid ); for( i=0; i<*param; i++ ){ sleep(1); LOGI("count = %d" , i); } LOGD("End(threadID=0x%x)", tid); return 0; } static void *test_sleep_func(){ pthread_t tid = pthread_self(); LOGD("Start(threadID=0x%x)", tid ); sleep(1); LOGD("End(threadID=0x%x)", tid); return 0; } pthread_mutex_t test_mutex; static void *sub_thread_exclusive(int* param){ pthread_t tid = pthread_self(); LOGD("Start(param=0x%x threadID=0x%x)", *param, tid ); pthread_mutex_lock(&test_mutex); test_sleep_func(); pthread_mutex_unlock(&test_mutex); LOGD("End(threadID=0x%x)", tid); return 0; } void sbt_thread_run( const void* func, const void* f_arg, short int join_flg, long int stk_size){ pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); if(0==stk_size){ pthread_attr_setstacksize( &attr, 64 * 1024 ); }else{ pthread_attr_setstacksize( &attr, stk_size ); } if(1==join_flg){ pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); }else{ pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_DETACHED ); } pthread_create( &thread, &attr, (void*)func, (void*)f_arg ); if(1==join_flg){ pthread_join( thread, 0 ); } pthread_attr_destroy(&attr); return; } int sbt_thread_test_join(){ int loop_cnt = 6; pthread_t tid = pthread_self(); LOGD( "Start (main threadID=0x%x)", tid ); sbt_thread_run( (const void*)sub_thread_join, (const void*)&loop_cnt , 1, 0); LOGD( "End (main threadID=0x%x)", tid ); return 0; } int sbt_thread_test_detatch(){ test_thread_func_st* st_thread_func = 0; pthread_t tid = pthread_self(); LOGD( "Start (main threadID=0x%x)", tid ); st_thread_func = (test_thread_func_st*)malloc( sizeof(test_thread_func_st) ); st_thread_func->size = 4; st_thread_func->buf[0] = 1; st_thread_func->buf[1] = 2; st_thread_func->buf[2] = 3; st_thread_func->buf[3] = 4; sbt_thread_run( (const void*)sub_thread_detach, (const void*)st_thread_func, 0, 0); free(st_thread_func); LOGD( "End (main threadID=0x%x)", tid ); sbt_thread_exit(); return 0; } int sbt_thread_test_exclusive(){ int i = 0; pthread_t tid = pthread_self(); LOGD( "Start (main threadID=0x%x)", tid ); for(i=0; i<3; i++){ sbt_thread_run( (const void*)sub_thread_exclusive, (const void*)&i , 1, 0); } LOGD( "End (main threadID=0x%x)", tid ); return 0; }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(800)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(800)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (800)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (800)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (800)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); value = __VERIFIER_nondet_int(); if (enqueue(&queue,value)) { goto ERROR; } stored_elements[0]=value; if (empty(&queue)) { goto ERROR; } pthread_mutex_unlock(&m); for( i=0; i<((800)-1); i++) { pthread_mutex_lock(&m); if (enqueue_flag) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i+1]=value; enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); } return 0; ERROR: __VERIFIER_error(); } void *t2(void *arg) { int i; for( i=0; i<(800); i++) { pthread_mutex_lock(&m); if (dequeue_flag) { if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); } return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> uint8_t ts_buffer[5000]; pthread_mutex_t read_mutex = {0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, __LOCK_INITIALIZER}; int bufhead = 0; int buftail = 0; bool all_abort = FALSE; bool pushbyte(uint8_t data); bool popbyte(uint8_t *data); void tinystream_cb(int id, uint8_t *data, int length) { int i, count; bool result = FALSE; pthread_mutex_lock(&read_mutex); for (i=0; i < length; i++) { result = FALSE; count = 0; while (!result) { result = pushbyte(data[i]); if (!result) { pthread_mutex_unlock(&read_mutex); count++; usleep(50000); if (count > 100) { dbg(TSRC,"Callback probably deadlocked.\\n"); } pthread_mutex_lock(&read_mutex); } } } pthread_mutex_unlock(&read_mutex); } bool pushbyte(uint8_t data) { unsigned int nextbyte; nextbyte = (buftail + 1) % 5000; if (nextbyte == bufhead) { dbg(TSRC,"buffer full!\\n"); return FALSE; } ts_buffer[buftail] = data; buftail = nextbyte; dbg(TSRC,"(< %02x)",data); return TRUE; } bool popbyte(uint8_t *data) { if (bufhead == buftail) { return FALSE; } *data = ts_buffer[bufhead]; bufhead = (bufhead + 1) % 5000; dbg(TSRC,"(> %02x)",*data); return TRUE; } bool peekbyte(uint8_t *data) { if (bufhead == buftail) { return FALSE; } *data = ts_buffer[bufhead]; return TRUE; } int tinystream_init(const char* host, int port) { all_abort = FALSE; pthread_mutex_lock(&read_mutex); memset(&ts_buffer, 0, sizeof(ts_buffer)); bufhead = 0; buftail = 0; pthread_mutex_unlock(&read_mutex); return tinyrely_init(host,port); } int tinystream_close() { all_abort = TRUE; return tinyrely_destroy(); } int tinystream_connect(int address) { return tinyrely_connect(tinystream_cb, address); } int tinystream_read(int id, uint8_t *buf, int length) { int i, count; bool result = FALSE; pthread_mutex_lock(&read_mutex); dbg(TSRC,"tstream_read(%i)...",length); for (i=0; i < length; i++) { result = FALSE; count = 0; while (!result) { result = popbyte(&buf[i]); if (!result) { pthread_mutex_unlock(&read_mutex); if (all_abort) { return -1; } count++; usleep(50000); if (count > 200 && i > 0) { dbg(TSRC,"tinyrely_read probably dead.\\n"); } pthread_mutex_lock(&read_mutex); } else { dbg(TSRC," %02x ",buf[i]); } } } dbg(TSRC,"...\\n"); pthread_mutex_unlock(&read_mutex); return 0; } int tinystream_peek(int id, uint8_t *abyte) { bool result = FALSE; pthread_mutex_lock(&read_mutex); result = FALSE; while (!result) { result = peekbyte(abyte); if (!result) { pthread_mutex_unlock(&read_mutex); if (all_abort) { return -1; } usleep(50000); pthread_mutex_lock(&read_mutex); } } pthread_mutex_unlock(&read_mutex); return 0; } int tinystream_write(int id, const uint8_t *buf, int length) { return tinyrely_send(id, buf, length); } int tinystream_close_connection(int id) { return tinyrely_close(id); }
1
#include <pthread.h> int ticket=10; pthread_mutex_t lock; pthread_cond_t cond; void* salewinds1(void* args){ while(1){ pthread_mutex_lock(&lock); if(ticket>0){ sleep(1); printf("win1 start sale ticket! the ticket is:%d\\n",ticket); ticket--; sleep(2); printf("sale tikcet finish! ticket has:%d\\n",ticket); }else{ pthread_mutex_unlock(&lock); pthread_exit(0); } if(ticket==0) pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); sleep(1); } } void* salewinds2(void* args){ while(1){ pthread_mutex_lock(&lock); if(ticket>0){ sleep(1); printf("win2 start sale ticket! the ticket is:%d\\n",ticket); ticket--; sleep(2); printf("sale tikcet finish! ticket has:%d\\n",ticket); }else{ pthread_mutex_unlock(&lock); pthread_exit(0); } if(ticket==0) pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); sleep(1); } } void* setticket(void* args){ pthread_mutex_lock(&lock); if(ticket>0) pthread_cond_wait(&cond,&lock); ticket=10; pthread_mutex_unlock(&lock); sleep(1); pthread_exit(0); } int main(){ pthread_t pthid1,pthid2,pthid3; pthread_mutex_init(&lock,0); pthread_cond_init(&cond,0); pthread_create(&pthid1,0,salewinds1,0); pthread_create(&pthid2,0,salewinds2,0); pthread_create(&pthid3,0,setticket,0); pthread_join(pthid1,0); pthread_join(pthid2,0); pthread_join(pthid3,0); pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); return 0; }
0
#include <pthread.h> int condvar_was_hit = 0; int count = 0; int thread_ids[3] = {0,1,2}; pthread_mutex_t count_lock=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t count_hit_threshold=PTHREAD_COND_INITIALIZER; void *inc_count(void *null) { int i=0; for (i=0; i<10; i++) { pthread_mutex_lock(&count_lock); count++; printf("inc_counter(): count = %d, unlocking mutex\\n", count); if (count == 12) { printf("hit threshold!\\n"); pthread_cond_signal(&count_hit_threshold); } pthread_mutex_unlock(&count_lock); } return(0); } void *watch_count(void *null) { pthread_mutex_lock(&count_lock); while (count < 12) { pthread_cond_wait(&count_hit_threshold, &count_lock); condvar_was_hit = 1; } pthread_mutex_unlock(&count_lock); return(0); } extern int main(void) { int i; pthread_t threads[3]; pthread_create(&threads[0], 0, watch_count, 0); sleep(1); pthread_create(&threads[1], 0, inc_count, 0); pthread_create(&threads[2], 0, inc_count, 0); for (i = 0; i < 3; i++) { pthread_join(threads[i], 0); } if (condvar_was_hit == 1) printf("condvar was hit!\\n"); else if (condvar_was_hit > 1) printf("condvar was multi-hit...\\n"); else printf("condvar was missed...\\n"); return 0; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void * thr_fn(void *arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) err_exit(err, "sigwait failed"); switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return 0; default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main(void) { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) err_exit(err, "SIG_BLOCK error"); err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) err_exit(err, "can't create thread"); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&wait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) err_sys("SIG_SETMASK error"); exit(0); }
0
#include <pthread.h> pthread_mutex_t* mutex; pthread_cond_t* var; int wait_general; int wait_empresarial; } params; sem_t sem_generales; sem_t sem_empresariales; int cajeros_generales[5]; int generales_disponibles[5]; int cajeros_empresariales[3]; int empresariales_disponibles[3]; pthread_mutex_t mutex_generales; pthread_mutex_t mutex_empresariales; void* operaciones_generales(void*); void* operaciones_empresariales(void*); void* crear_generales(void*); void* crear_empresariales(void*); void* wait_g(void*); void* wait_e(void*); int main() { sem_init(&sem_generales, 0, 5); sem_init(&sem_empresariales, 0, 3); srand((int) time(0)); pthread_t creador_generales, creador_empresariales, verificador; pthread_create(&creador_generales, 0, crear_generales, 0); pthread_create(&creador_empresariales, 0, crear_empresariales, 0); int i; for (i = 0; i < 5; ++i) { cajeros_generales[i] = 5; generales_disponibles[i] = 1; } for (i = 0; i < 3; ++i) { cajeros_empresariales[i] = 5; empresariales_disponibles[i] = 1; } pthread_join(creador_generales, 0); pthread_join(creador_empresariales, 0); sem_destroy(&sem_generales); sem_destroy(&sem_empresariales); return 0; } void* crear_generales(void* p) { pthread_t threads_generales[100], *aux; int i; for (aux = threads_generales, i = 1; aux < (threads_generales + 100); ++aux, ++i) { sleep((rand() % 18) + 5); pthread_create(aux, 0, operaciones_generales, (void*) (intptr_t) i); } for (aux = threads_generales; aux < (threads_generales + 100); ++aux) { pthread_join(*aux, 0); } pthread_exit(0); } void* crear_empresariales(void* p) { pthread_t threads_empresariales[50], *aux; int i; for (aux = threads_empresariales, i = 100 + 1; aux < (threads_empresariales + 50); ++aux, ++i) { sleep((rand() % 26) + 9); pthread_create(aux, 0, operaciones_empresariales, (void*) (intptr_t) i); } for (aux = threads_empresariales; aux < (threads_empresariales + 50); ++aux) { pthread_join(*aux, 0); } pthread_exit(0); } void* wait_g(void* p) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); sleep(1); sem_wait(&sem_generales); params* parametros = (params*) p; pthread_mutex_lock(parametros->mutex); parametros->wait_general = 1; pthread_cond_signal(parametros->var); pthread_mutex_unlock(parametros->mutex); pthread_exit(0); } void* wait_e(void* p) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); sleep(2); sem_wait(&sem_empresariales); params* parametros = (params*) p; pthread_mutex_lock(parametros->mutex); parametros->wait_empresarial = 1; pthread_cond_signal(parametros->var); pthread_mutex_unlock(parametros->mutex); pthread_exit(0); } void* operaciones_generales(void* p) { int id = (intptr_t) p, i = 0, cajero, temp_status; printf("Llegó el cliente %d. Operación general\\n", id); pthread_mutex_t mutex; pthread_cond_t var; pthread_t espera_g, espera_e; pthread_mutex_init(&mutex, 0); pthread_cond_init(&var, 0); params parametros; parametros.mutex = &mutex; parametros.var = &var; parametros.wait_general = 0; parametros.wait_empresarial = 0; pthread_create(&espera_g, 0, wait_g, &parametros); pthread_create(&espera_e, 0, wait_e, &parametros); pthread_mutex_lock(&mutex); pthread_cond_wait(&var, &mutex); temp_status = parametros.wait_general; if (temp_status == 1) { pthread_cancel(espera_e); if (parametros.wait_empresarial) sem_post(&sem_empresariales); } else pthread_cancel(espera_g); pthread_mutex_unlock(&mutex); if (temp_status) { pthread_mutex_lock(&mutex_generales); while (!generales_disponibles[i]) ++i; generales_disponibles[i] = 0; cajero = i; pthread_mutex_unlock(&mutex_generales); printf("Atendiendo al cliente %d en el cajero G%d. Operación general\\n", id, cajero); sleep((rand() % 19) + 12); cajeros_generales[cajero]--; if (cajeros_generales[cajero] == 0) { printf("Cajero G%d en espera\\n", cajero); sleep(18); cajeros_generales[cajero] = 5; } pthread_mutex_lock(&mutex_generales); generales_disponibles[cajero] = 1; pthread_mutex_unlock(&mutex_generales); sem_post(&sem_generales); } else { pthread_mutex_lock(&mutex_empresariales); while (!empresariales_disponibles[i]) ++i; empresariales_disponibles[i] = 0; cajero = i; pthread_mutex_unlock(&mutex_empresariales); printf("Atendiendo al cliente %d en el cajero E%d. Operación general\\n", id, cajero); sleep((rand() % 19) + 12); cajeros_empresariales[cajero]--; if (cajeros_empresariales[cajero] == 0) { printf("Cajero E%d en espera\\n", cajero); sleep(18); cajeros_empresariales[cajero] = 5; } pthread_mutex_lock(&mutex_empresariales); empresariales_disponibles[cajero] = 1; pthread_mutex_unlock(&mutex_empresariales); sem_post(&sem_empresariales); } pthread_exit(0); } void* operaciones_empresariales(void* p) { int id = (intptr_t) p, i = 0, cajero; printf("Llegó el cliente %d. Operación empresarial\\n", id); sem_wait(&sem_empresariales); pthread_mutex_lock(&mutex_empresariales); while (!empresariales_disponibles[i]) ++i; empresariales_disponibles[i] = 0; cajero = i; pthread_mutex_unlock(&mutex_empresariales); printf("Atendiendo al cliente %d en el cajero E%d. Operación empresarial\\n", id, cajero); sleep((rand() % 19) + 12); cajeros_empresariales[cajero]--; if (cajeros_empresariales[cajero] == 0) { printf("Cajero E%d en espera\\n", cajero); sleep(18); cajeros_empresariales[cajero] = 5; } pthread_mutex_lock(&mutex_empresariales); empresariales_disponibles[cajero] = 1; pthread_mutex_unlock(&mutex_empresariales); sem_post(&sem_empresariales); pthread_exit(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); } return 0; } int main(int argc, const char* argv[]) { pthread_t p[5]; for(int i=0; i<5; ++i) { pthread_create(&p[i], 0, dine, (void*)i); } for(int i=0; i<5; ++i) { pthread_mutex_init(&mutex[i], 0); } 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> static void* event_loop_thread(void *arg); static pthread_t event_thread_id = 0; static pthread_mutex_t event_mutex_id; static pthread_mutexattr_t event_mutex_mutexattr; static pthread_t event_mutex_owner_id = 0; static uint32_t owner_count = 0; static sem_t event_start_sema_id; static sem_t event_signal_sema_id; void eventOS_scheduler_mutex_wait(void) { pthread_mutex_lock(&event_mutex_id); if (0 == owner_count) { event_mutex_owner_id = pthread_self(); } owner_count++; } void eventOS_scheduler_mutex_release(void) { owner_count--; if (0 == owner_count) { event_mutex_owner_id = 0; } pthread_mutex_unlock(&event_mutex_id); } uint8_t eventOS_scheduler_mutex_is_owner(void) { return pthread_self() == event_mutex_owner_id ? 1 : 0; } void eventOS_scheduler_signal(void) { int err = sem_post(&event_signal_sema_id); assert(err == 0); } void eventOS_scheduler_idle(void) { eventOS_scheduler_mutex_release(); int err = sem_wait(&event_signal_sema_id); assert(err == 0); eventOS_scheduler_mutex_wait(); } static void* event_loop_thread(void *arg) { tr_debug("event_loop_thread create"); int err = sem_wait(&event_start_sema_id); assert(err == 0); eventOS_scheduler_mutex_wait(); tr_debug("event_loop_thread"); eventOS_scheduler_run(); } void ns_event_loop_thread_create(void) { int err = 0; err = sem_init(&event_start_sema_id, 0, 1); assert(err == 0); err = sem_wait(&event_start_sema_id); assert(err == 0); err = pthread_mutexattr_init(&event_mutex_mutexattr); assert(err == 0); err = pthread_mutexattr_settype(&event_mutex_mutexattr, PTHREAD_MUTEX_RECURSIVE_NP); assert(err == 0); err = pthread_mutex_init(&event_mutex_id, &event_mutex_mutexattr); assert(err == 0); err = sem_init(&event_signal_sema_id, 0, 1); assert(err == 0); pthread_create(&event_thread_id, 0, &event_loop_thread, 0); } void ns_event_loop_thread_start(void) { int err = sem_post(&event_start_sema_id); assert(err == 0); } void ns_event_loop_thread_cleanup(void) { int err = pthread_cancel(event_thread_id); assert(err == 0); err = pthread_join(event_thread_id, 0); assert(err == 0); err = pthread_mutex_destroy(&event_mutex_id); assert(err == 0); err = pthread_mutexattr_destroy(&event_mutex_mutexattr); assert(err == 0); err = sem_destroy(&event_start_sema_id); assert(err == 0); err = sem_destroy(&event_signal_sema_id); }
1
#include <pthread.h> struct map *init_map() { int i ; struct map *m = malloc(sizeof(struct map)) ; for(i = 0 ; i <= ID_MAX ; i++) { m->name_from_id[i] = 0 ; assert(pthread_mutex_init(&m->map_lock[i], 0)==0); } assert(pthread_mutex_init(&m->size_lock, 0)==0); m->map_size = 0 ; return m ; } void destroy_map(struct map *m) { int i ; struct map_entry *p, *old ; for(i = 0 ; i <= ID_MAX ; i++) { p = m->name_from_id[i] ; while(p != 0) { old = p ; p = p->next ; free(old) ; } assert(pthread_mutex_destroy(&m->map_lock[i])==0); } assert(pthread_mutex_destroy(&m->size_lock)==0); free(m); } u_int get_name(struct map *m,u_int id) { struct map_entry *p, *new ; u_int i = id%(ID_MAX+1) ; pthread_mutex_lock(&m->map_lock[i]) ; p=m->name_from_id[i] ; while(p != 0 && p->ID != id) { p=p->next ; } if(p != 0) { pthread_mutex_unlock(&m->map_lock[i]) ; return p->name ; } else { pthread_mutex_lock(&m->size_lock) ; assert(m->map_size != ID_MAX) ; new = malloc(sizeof(struct map_entry)) ; new->ID = id ; new->name = m->map_size++ ; new->next = m->name_from_id[i] ; m->name_from_id[i] = new ; m->id_from_name[new->name] = new->ID ; pthread_mutex_unlock(&m->size_lock) ; pthread_mutex_unlock(&m->map_lock[i]) ; return new->name ; } } u_int get_id(struct map *m, u_int name) { assert(name < m->map_size) ; return m->id_from_name[name] ; } u_int get_map_size(struct map *m) { u_int s ; pthread_mutex_lock(&m->size_lock) ; s = m->map_size ; pthread_mutex_unlock(&m->size_lock) ; return s ; }
0