text
stringlengths
192
6.24k
label
int64
0
1
#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 += 2; 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> void interface(){ while(1){ pthread_mutex_lock(&mutexEjecuta); mostrarMenu(); pthread_mutex_unlock(&mutexEjecuta); scanf("%i",&opcion); switch(opcion) { case 1 : pthread_mutex_lock(&mutexEjecuta); iniciarPrograma(); break; case 2: pthread_mutex_lock(&mutexEjecuta); finalizarPrograma(); pthread_mutex_unlock(&mutexEjecuta); break; case 3: pthread_mutex_lock(&mutexEjecuta); desconectarConsola(); pthread_mutex_unlock(&mutexEjecuta); break; case 4: pthread_mutex_lock(&mutexEjecuta); limpiarMensajes(); pthread_mutex_unlock(&mutexEjecuta); break; default: printf("Opcion invalida, vuelva a intentar\\n\\n"); break; } } } void iniciarPrograma(){ printf("Iniciar Programa\\n\\n"); pthread_create(&threadNewProgram, 0, hiloNuevoPrograma, 0); return; } void finalizarPrograma(){ int n ; signed int soc; printf("Finalizar Programa\\n\\n"); printf("Ingrese el PID a finalizar: \\n"); scanf("%i",&n); soc = matriz[n]; log_debug(logger,"Se finalizara PID: %d, en socket:%d ", n, soc); if(soc > 0){ enviar(soc, FINALIZAR_PROGRAMA_DESDE_CONSOLA, sizeof(int), &n); close(soc); matriz[n] = 0; } else printf("El pid %d ya no se encuentra conectado al Kernel\\n", n); if(pthread_cancel(matrizHilos[n]) == 0){ log_debug(logger,"Hilo finalizado"); } else{ log_error(logger,"error al finalizar Hilo"); } return; } void desconectarConsola(){ int i; signed int soc; log_info(logger, "Desconectar Consola\\n\\n"); for( i= 0; i< MAXPID; i++){ soc = matriz[i]; if (soc > 0){ enviar(soc, FINALIZAR_PROGRAMA_DESDE_CONSOLA, sizeof(int), &i); close(soc); printf("Se cierra pid: %d \\n", i); matriz[i] = 0; if(pthread_cancel(matrizHilos[i]) == 0){ printf("Hilo finalizado\\n"); } else{ printf("error al finalizar Hilo\\n"); } } } return; } void limpiarMensajes(){ printf("Limpiar Mensajes\\n\\n"); system("clear"); return; } void mostrarMenu(){ printf("\\nIngrese la opcion deseada:\\n"); printf("OPCION 1 - INICIAR PROGRAMA\\n"); printf("OPCION 2 - FINALIZAR PROGRAMA\\n"); printf("OPCION 3 - DESCONECTAR CONSOLA\\n"); printf("OPCION 4 - LIMPIAR MENSAJES\\n"); printf("Su Opcion:\\n"); }
0
#include <pthread.h> struct prodcons { int buffer[16]; pthread_mutex_t lock; int readpos, writepos; pthread_cond_t notempty; pthread_cond_t notfull; }; void init(struct prodcons *b) { pthread_mutex_init(&b->lock, 0); pthread_cond_init(&b->notempty, 0); pthread_cond_init(&b->notfull, 0); b->readpos = 0; b->writepos = 0; } void put(struct prodcons *b, int data) { pthread_mutex_lock(&b->lock); if ((b->writepos + 1) % 16 == b->readpos) { pthread_cond_wait(&b->notfull, &b->lock); } b->buffer[b->writepos] = data; b->writepos++; if (b->writepos >= 16) { b->writepos = 0; } pthread_cond_signal(&b->notempty); pthread_mutex_unlock(&b->lock); } int get(struct prodcons *b) { int data; pthread_mutex_lock(&b->lock); if (b->writepos == b->readpos) { pthread_cond_wait(&b->notempty, &b->lock); } data = b->buffer[b->readpos]; b->readpos++; if (b->readpos >= 16) { b->readpos = 0; } pthread_cond_signal(&b->notfull); pthread_mutex_unlock(&b->lock); return data; } struct prodcons buffer; void *producer(void *data) { int n; for (n = 0; n < 10000; n++) { printf("%d --->\\n", n); put(&buffer, n); } put(&buffer, (-1)); return 0; } void *consumer(void *data) { int d; while (1) { d = get(&buffer); if (d == (-1)) { break; } printf("--->%d \\n", d); } return 0; } int main(void) { pthread_t th_a, th_b; void *retval; init(&buffer); pthread_create(&th_a, 0, producer, 0); pthread_create(&th_b, 0, consumer, 0); pthread_join(th_a, &retval); pthread_join(th_b, &retval); return 0; }
1
#include <pthread.h> static int the_msgq; static pthread_t the_thread; static pthread_mutex_t the_mutex = PTHREAD_MUTEX_INITIALIZER; static short must_continue; int added_sensors[32]; unsigned int sensor_count; int add_sensor( unsigned int id ) { int i = 0; pthread_mutex_lock( &the_mutex ); for( i = 0; i < 32; i++ ) { if( added_sensors[i] == 0 ) { added_sensors[i] = id; sensor_count++; break; } } pthread_mutex_unlock( &the_mutex ); if( i == 32 ) return 1; return 0; } unsigned int sensor_exists( unsigned int id ) { int i; pthread_mutex_lock( &the_mutex ); for( i = 0; i < 32; i++ ) { if( added_sensors[i] == id ) break; } pthread_mutex_unlock( &the_mutex ); return i; } void remove_sensor( unsigned int id ) { int res = sensor_exists( id ); if( res >= 0 && res < 32 ) { pthread_mutex_lock( &the_mutex ); added_sensors[res] = 0; sensor_count--; pthread_mutex_unlock( &the_mutex ); } else printf( "No sensor found.\\n" ); } void* callback( void* ptr ) { int buffer; srand( 5 ); pthread_mutex_lock( &the_mutex ); must_continue = 1; buffer = 1; pthread_mutex_unlock( &the_mutex ); while( buffer == 1 ) { int index; int id = (rand() % 32); if( id == 0 ) continue; index = sensor_exists( id ); if( index >= 0 && index < 32 ) { int res; struct msg_drv_notify buf; buf.msg_type = DRV_MSG_TYPE; buf.id_sensor = id; buf.flag_value = 8; buf.value = (float) (rand()%1024); res = msgsnd( the_msgq, (const void*) &buf, sizeof(struct msg_drv_notify) - sizeof(long), 0 ); } usleep( rand()%(20000 -5000) + 5000 ); pthread_mutex_lock( &the_mutex ); buffer = must_continue; pthread_mutex_unlock( &the_mutex ); } } int drv_init( const char* addr, int port ) { int i; printf( "%s::%s -> Connexion à %s:%d\\n", "driver.c", __FUNCTION__, addr, port ); for( i = 0; i < 32; i++ ) added_sensors[i] = 0; sensor_count = 0; return 0; } int drv_run( int msgq_id ) { int ret; the_msgq = msgq_id; ret = pthread_create( &the_thread, 0, callback, 0 ); return 0; } void drv_stop( void ) { pthread_mutex_lock( &the_mutex ); must_continue = 0; pthread_mutex_unlock( &the_mutex ); pthread_join(the_thread, 0); printf( "%s::%s -> Stop\\n", "driver.c", __FUNCTION__ ); } int drv_add_sensor( unsigned int id_sensor ) { return add_sensor( id_sensor ); } void drv_remove_sensor( unsigned int id_sensor ) { remove_sensor( id_sensor ); } int drv_send_data( unsigned int id_sensor, char trame ) { return 0; } void drv_get_info( char* buffer, int max_length ) { strcpy( buffer, "Driver de test, v1.0" ); }
0
#include <pthread.h> pthread_mutex_t g_qlock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t g_qready = PTHREAD_COND_INITIALIZER; int id = 0; struct message { int m_msg_id; }; struct message_queue { struct message * p_next; }; struct message_queue workq; void deal_msg(struct message * p_msg) { printf("msg id is %d\\n", p_msg->m_msg_id); fflush(0 ); } void * process_msg(void * arg) { for (;;) { pthread_mutex_lock(&g_qlock); while (workq.p_next == 0 ) { pthread_cond_wait(&g_qready, &g_qlock); } deal_msg(workq.p_next); free(workq.p_next); workq.p_next = 0; pthread_mutex_unlock(&g_qlock); } return 0; } void * add_msg_to_quence(void * arg) { for (;;) { pthread_mutex_lock(&g_qlock); struct message * p_mess = (struct message *) malloc(sizeof(struct message)); p_mess->m_msg_id = id; workq.p_next = p_mess; id++; pthread_mutex_unlock(&g_qlock); pthread_cond_signal(&g_qready); } return 0; } int main(int argc, char ** argv) { pthread_t t_produce; pthread_t t_customer; pthread_create(&t_customer, 0, process_msg, 0 ); pthread_create(&t_produce, 0, add_msg_to_quence, 0 ); pthread_join(t_customer, 0 ); pthread_join(t_produce, 0 ); }
1
#include <pthread.h> void sig_handler_quit (int); void *find_file (void *arg); void *dispatch_executer (void *arg); int files_sent, files_found = 0; pthread_mutex_t mutex_total_time, retrieved, sent; int total_time = 0; int main (int argc, char **argv) { srand (time (0)); pthread_mutex_init (&mutex_total_time, 0); pthread_mutex_init (&retrieved, 0); pthread_mutex_init (&sent, 0); int status; pthread_t dispatch; if ((status = pthread_create (&dispatch, 0, dispatch_executer, 0)) != 0) { fprintf (stderr, "Uh oh...something went wrong creating thread %d: %s\\n", status, strerror (status)); exit (1); } if ((status = pthread_join (dispatch, 0)) != 0) { fprintf (stderr, "Uh oh...something went wrong joining thread %d: %s\\n", status, strerror (status)); exit (1); } pthread_mutex_destroy (&mutex_total_time); pthread_mutex_destroy (&retrieved); pthread_mutex_destroy (&sent); return 0; } void * dispatch_executer (void *arg) { signal (SIGINT, sig_handler_quit); for (;;) { printf ("Enter a file name: \\n"); char *buf = malloc (sizeof (char) * 1024); if (fgets (buf, 1024, stdin) == 0) { perror ("Uh oh...something went wrong reading input"); exit (1); } buf = realloc (buf, sizeof (char) * strlen (buf)); int status; pthread_t workers; if ((status = pthread_create (&workers, 0, find_file, (void *) buf)) != 0) { fprintf (stderr, "thread create error %d: %s\\n", status, strerror (status)); exit (1); } if ((status = pthread_detach (workers)) != 0) { fprintf (stderr, "thread detach error %d: %s\\n", status, strerror (status)); exit (1); } pthread_mutex_lock (&retrieved); files_found++; pthread_mutex_unlock (&retrieved); } return arg; } void * find_file (void *arg) { char *filename = (char *) arg; filename[strlen (filename) - 1] = '\\0'; pthread_mutex_lock (&sent); files_sent++; pthread_mutex_unlock (&sent); int flag_simulate_slow_io = ((rand () % 5) == 0); int rand_time = ( flag_simulate_slow_io ? ((rand () % 4) + 7) : 1 ); sleep (rand_time); printf ("Found the file '%s' in %d second%c%c\\n", filename, rand_time, ((rand_time == 1) ? '.' : 's'), ((rand_time == 1) ? ' ' : '.') ); pthread_mutex_lock (&mutex_total_time); total_time += rand_time; pthread_mutex_unlock (&mutex_total_time); pthread_exit ((void *) arg); } void sig_handler_quit (int signum) { printf (" received. Exiting the program\\n"); printf ("The amount of files asked for is: %d\\n", files_sent); printf ("The amount of files found is: %d\\n", files_found); printf ("The amount of time it took was %d second%c%c\\n", total_time, ((total_time == 1) ? '.' : 's'), ((total_time == 1) ? ' ' : '.') ); exit (0); }
0
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER; void* thr_fn(void* arg) { int err, signo; for (;;) { err = sigwait(&mask, &signo); if (err != 0) { fprintf(stderr, "sigwait failed: %s\\n", strerror(err)); exit(1); } switch (signo) { case SIGINT: printf("\\ninterrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&waitloc); return 0; default: printf("unexpected signal %d\\n", signo); exit(1); } } } int main() { int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(&mask, SIGINT); sigaddset(&mask, SIGQUIT); if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) { fprintf(stderr, "SIG_BLOCK error\\n"); exit(1); } err = pthread_create(&tid, 0, thr_fn, 0); if (err != 0) { fprintf(stderr, "can't create thread\\n"); exit(1); } pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&waitloc, &lock); pthread_mutex_unlock(&lock); quitflag = 0; if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) { fprintf(stderr, "SIG_SETMASK error\\n"); exit(1); } return 0; }
1
#include <pthread.h> void init_matrix (int **matrix, int fils, int cols) { int i, j; for (i = 0; i < fils; i++) { for (j = 0; j < cols; j++) { matrix[i][j] = 1; } } } int **matrix1; int **matrix2; int **matrixR; int matrix1_fils; int matrix1_cols; int matrix2_fils; int matrix2_cols; pthread_t *thread_list; pthread_mutex_t mutex; int pending_jobs = 0; struct job { int i, j; struct job *next; }; struct job *job_list = 0; struct job *last_job = 0; void add_job(int i, int j){ struct job *job = malloc(sizeof(struct job)); job->i = i; job->j = j; job->next = 0; if(pending_jobs == 0){ job_list = job; last_job = job; } else{ last_job->next = job; last_job = job; } pending_jobs++; } struct job* get_job(){ struct job *job = 0; if(pending_jobs > 0){ job = job_list; job_list = job->next; if(job_list == 0){ last_job = 0; } pending_jobs--; } return job; } void do_job(struct job *job) { int k, acum; acum = 0; for (k = 0; k < matrix1_cols; k++) { acum += matrix1[job->i][k] * matrix2[k][job->j]; } matrixR[job->i][job->j] = acum; } void* dispatch_job () { struct job *job; while(1) { pthread_mutex_lock(&mutex); job = get_job(); pthread_mutex_unlock(&mutex); if (job) { do_job(job); free(job); } else { pthread_exit(0); } } } int main (int argc, char **argv) { if (argc > 3) { printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]); matrix1_fils = strtol(argv[1], (char **) 0, 10); matrix1_cols = strtol(argv[2], (char **) 0, 10); matrix2_fils = matrix1_cols; matrix2_cols = strtol(argv[3], (char **) 0, 10); int i,j; matrix1 = (int **) calloc(matrix1_fils, sizeof(int*)); for (i = 0; i < matrix1_fils; i++){ matrix1[i] = (int *) calloc(matrix1_cols, sizeof(int)); } matrix2 = (int **) calloc(matrix2_fils, sizeof(int*)); for (i = 0; i < matrix2_fils; i++){ matrix2[i] = (int *) calloc(matrix2_cols, sizeof(int)); } matrixR = (int **) malloc(matrix1_fils * sizeof(int*)); for (i = 0; i < matrix1_fils; i++){ matrixR[i] = (int *) malloc(matrix2_cols * sizeof(int)); } init_matrix(matrix1, matrix1_fils, matrix1_cols); init_matrix(matrix2, matrix2_fils, matrix2_cols); for (i = 0; i < matrix1_fils; i++) { for (j = 0; j < matrix2_cols; j++) { add_job(i,j); } } thread_list = malloc(sizeof(pthread_t) * 3); pthread_mutex_init(&mutex, 0); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS); for (i = 0; i < 3; i++) { pthread_create(&thread_list[i], &attr, dispatch_job, 0); } for (i = 0; i < 3; i++) { pthread_join(thread_list[i], 0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); free(thread_list); for (i = 0; i < matrix1_fils; i++) { free(matrix1[i]); } free(matrix1); for (i = 0; i < matrix2_fils; i++) { free(matrix2[i]); } free(matrix2); for (i = 0; i < matrix1_fils; i++) { free(matrixR[i]); } free(matrixR); return 0; } fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]); return -1; }
0
#include <pthread.h> int oskit_sem_close(sem_t *sem) { int enabled; pthread_mutex_lock(&semn_space.semn_lock); save_preemption_enable(enabled); disable_preemption(); pthread_lock(&sem->sem_lock); if (--(sem->sem_refcount) == 0 && (sem->sem_flag & SEM_UNLINK_FLAG)) { sem_remove(sem); } else { pthread_unlock(&sem->sem_lock); } restore_preemption_enable(enabled); pthread_mutex_unlock(&semn_space.semn_lock); return 0; }
1
#include <pthread.h> int BufferSize; void *Producer_Function(); void *Consumer_Function(); int BufferIndex=0; int sleepTime = 10; 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(int argc, char* argv[]) { if(argc != 3) { printf("command line arguement has to be 2\\n"); exit(-1); } BufferSize = atoi(argv[1]); sleepTime = atoi(argv[2]); pthread_t ptid,ctid; BUFFER=(char *) malloc(sizeof(char) * BufferSize); pthread_create(&ptid,0,Producer_Function,0); pthread_create(&ctid,0,Consumer_Function,0); pthread_join(ptid,0); pthread_join(ctid,0); return 0; } void *Producer_Function() { while(1) { pthread_mutex_lock(&mVar); if(BufferIndex==BufferSize) { pthread_cond_wait(&Buffer_Not_Full,&mVar); } BUFFER[BufferIndex]='@'; printf("Producer number %d produces \\n",BufferIndex); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Empty); BufferIndex++; sleep(sleepTime); } } void *Consumer_Function() { while(1) { pthread_mutex_lock(&mVar); if(BufferIndex==-1) { pthread_cond_wait(&Buffer_Not_Empty,&mVar); } printf("Consume : %d \\n",BufferIndex--); pthread_mutex_unlock(&mVar); pthread_cond_signal(&Buffer_Not_Full); } }
0
#include <pthread.h> int num_threads; pthread_t p_threads[65536]; pthread_attr_t attr; int list[268435456]; int list_size; pthread_mutex_t lock_minimum; int minimum; int count; void *find_minimum (void *s) { int j; int thread_id = (int) s; int chunk_size = list_size/num_threads; int my_start = thread_id*chunk_size; int my_end = (thread_id+1)*chunk_size-1; if (thread_id == num_threads-1) my_end = list_size-1; int my_minimum = list[my_start]; for (j = my_start+1; j <= my_end; j++) { if (my_minimum > list[j]) my_minimum = list[j]; } pthread_mutex_lock(&lock_minimum); if(minimum > my_minimum || count == 0) { minimum = my_minimum; } count++; pthread_mutex_unlock(&lock_minimum); pthread_exit(0); } int main(int argc, char *argv[]) { struct timeval start, stop; double total_time; int i, j; int true_minimum; if (argc != 3) { printf("Need two integers as input \\n"); printf("Use: <executable_name> <list_size> <num_threads>\\n"); exit(0); } if ((list_size = atoi(argv[argc-2])) > 268435456) { printf("Maximum list size allowed: %d.\\n", 268435456); exit(0); }; if ((num_threads = atoi(argv[argc-1])) > 65536) { printf("Maximum number of threads allowed: %d.\\n", 65536); exit(0); }; if (num_threads > list_size) { printf("Number of threads (%d) < list_size (%d) not allowed.\\n", num_threads, list_size); exit(0); }; pthread_mutex_init(&lock_minimum, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); unsigned int seed = 0; srand(seed); for (j = 0; j < list_size; j++) list[j] = rand_r(&seed); count = 0; gettimeofday(&start, 0); for (i = 0; i < num_threads; i++) { pthread_create(&p_threads[i], &attr, find_minimum, (void * )i); } for (i = 0; i < num_threads; i++) { pthread_join(p_threads[i], 0); } true_minimum = list[0]; for (j = 1; j < list_size; j++) if (true_minimum > list[j]) true_minimum = list[j]; if (true_minimum != minimum) printf("Houston, we have a problem!\\n"); gettimeofday(&stop, 0); total_time = (stop.tv_sec-start.tv_sec) +0.000001*(stop.tv_usec-start.tv_usec); printf("Threads = %d, minimum = %d, time (sec) = %8.4f\\n", num_threads, minimum, total_time); pthread_attr_destroy(&attr); pthread_mutex_destroy(&lock_minimum); }
1
#include <pthread.h> pthread_mutex_t Mutex; pthread_cond_t Condition; int Value; } semaphore_type; void Wait(semaphore_type *Semaphore) { pthread_mutex_lock(&(Semaphore->Mutex)); Semaphore->Value--; if (Semaphore->Value < 0) { pthread_cond_wait(&(Semaphore->Condition),&(Semaphore->Mutex)); } pthread_mutex_unlock(&(Semaphore->Mutex)); } void Signal(semaphore_type *Semaphore) { pthread_mutex_lock(&(Semaphore->Mutex)); Semaphore->Value++; if (Semaphore->Value <= 0) { pthread_cond_signal(&(Semaphore->Condition)); } pthread_mutex_unlock(&(Semaphore->Mutex)); } void *Incrementer(void *Dummy) { extern int CommonInt; extern semaphore_type MySemaphore; extern pthread_mutex_t IntMutex; sleep(rand() % 4); Wait(&MySemaphore); pthread_mutex_lock(&IntMutex); CommonInt--; printf("The common integer is now down to %d\\n",CommonInt); pthread_mutex_unlock(&IntMutex); sleep(rand() % 2); pthread_mutex_lock(&IntMutex); CommonInt++; printf("The common integer is now up to %d\\n",CommonInt); pthread_mutex_unlock(&IntMutex); Signal(&MySemaphore); return(0); } int main(int argc,char *argv[]) { extern int CommonInt; extern semaphore_type MySemaphore; extern pthread_mutex_t IntMutex; int Index; pthread_t NewThread; pthread_mutex_init(&MySemaphore.Mutex,0); pthread_cond_init(&MySemaphore.Condition,0); MySemaphore.Value = atoi(argv[2]); pthread_mutex_init(&IntMutex,0); CommonInt = atoi(argv[2]); srand(atoi(argv[3])); for (Index=0;Index<atoi(argv[1]);Index++) { if (pthread_create(&NewThread,0,Incrementer,0) != 0) { perror("Creating thread"); exit(1); } if (pthread_detach(NewThread) != 0) { perror("Detaching thread"); exit(1); } } printf("Exiting the main program, leaving the threads running\\n"); pthread_exit(0); } int CommonInt; semaphore_type MySemaphore; pthread_mutex_t IntMutex;
0
#include <pthread.h> char forks_action( char action, char chopstick, struct s_arg_philosopher_thread *pharg, struct s_philosopher *ph) { pthread_mutex_t *mutex[2]; mutex[0] = &pharg->philosophers->forks[ph->forks_index[LEFT_FORK]]; mutex[1] = &pharg->philosophers->forks[ph->forks_index[RIGHT_FORK]]; if (action == LOCK) { if (chopstick == LEFT_FORK || chopstick == BOTH_FORK) { pthread_mutex_lock(mutex[0]); lphilo_take_chopstick(mutex[0]); } if (chopstick == RIGHT_FORK || chopstick == BOTH_FORK) { pthread_mutex_lock(mutex[1]); lphilo_take_chopstick(mutex[1]); } } else if (action == RELEASE) { if (chopstick == LEFT_FORK || chopstick == BOTH_FORK) { pthread_mutex_unlock(mutex[0]); lphilo_release_chopstick(mutex[0]); } if (chopstick == RIGHT_FORK || chopstick == BOTH_FORK) { pthread_mutex_unlock(mutex[1]); lphilo_release_chopstick(mutex[1]); } } return 1; } char philo_eat(struct s_arg_philosopher_thread *ph_arg, struct s_philosopher *philosopher) { int i; i = -1; while (++i < ph_arg->philosophers->nbr_philo) { if (ph_arg->philosophers->philosophers[i].cur_eat >= ph_arg->philosophers->max_eat) { forks_action(RELEASE, BOTH_FORK, ph_arg, philosopher); return 0; } } philosopher->state = EAT; lphilo_eat(); philosopher->cur_eat++; return 1; } void *s_philosopher_thread(void *arg) { int i; struct s_arg_philosopher_thread *ph_arg; struct s_philosopher *philosopher; ph_arg = (struct s_arg_philosopher_thread*) arg; philosopher = &ph_arg->philosophers->philosophers[ph_arg->index]; i = 0; while (1) { if (philosopher->state == THINK) { forks_action(LOCK, BOTH_FORK, ph_arg, philosopher); if (!philo_eat(ph_arg, philosopher)) return 0; forks_action(RELEASE, BOTH_FORK, ph_arg, philosopher); usleep(1400); } else if (philosopher->state == UNKNOWN || philosopher->state == SLEEP) { forks_action(LOCK, LEFT_FORK, ph_arg, philosopher); philosopher->state = THINK; lphilo_think(); forks_action(RELEASE, LEFT_FORK, ph_arg, philosopher); } else if (philosopher->state == EAT && (philosopher->state = SLEEP)) lphilo_sleep(); } } char start_philosophers_threads( struct s_philosophers *philosophers) { int i; t_arg_philosopher_thread *arg_p; i = -1; while (++i < philosophers->nbr_philo) { if (!(arg_p = s_arg_philosopher_thread_init(i, philosophers))) return 0; philosophers->philosophers[i].s_arg_philosopher_thread = arg_p; if (pthread_create(&philosophers->philosophers[i].thread, 0, s_philosopher_thread, arg_p) != 0) return 0; } return 1; }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; sem_t blanks; sem_t datas; int ringBuf[30]; void *productRun(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product is done... data is: %d\\n",data); sem_post(&datas); } } void *productRun2(void *arg) { int i = 0; while(1) { sem_wait(&blanks); int data = rand()%1234; ringBuf[i++] = data; i %= 30; printf("product2 is done... data is: %d\\n",data); sem_post(&datas); } } void *consumerRun(void *arg) { int i = 0; while(1) { usleep(1456); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer is done... data is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } void *consumerRun2(void *arg) { int i = 0; while(1) { usleep(1234); pthread_mutex_lock(&mutex); sem_wait(&datas); int data = ringBuf[i++]; i %= 30; printf("consumer2 is done...data2 is: %d\\n",data); sem_post(&blanks); pthread_mutex_unlock(&mutex); } } int main() { sem_init(&blanks, 0, 30); sem_init(&datas, 0, 0); pthread_t tid1,tid2,tid3,tid4; pthread_create(&tid1, 0, productRun, 0); pthread_create(&tid4, 0, productRun2, 0); pthread_create(&tid2, 0, consumerRun, 0); pthread_create(&tid3, 0, consumerRun2, 0); pthread_join(tid1,0); pthread_join(tid2,0); pthread_join(tid3,0); pthread_join(tid4,0); sem_destroy(&blanks); sem_destroy(&datas); return 0; } int sem_ID; int customers_count=0; int eflag=0,fflag=0; void barber() { printf("barber started\\n"); while(1) { sem_change(sem_ID, 0, -1); printf("a %d\\n",customers_count); if(customers_count==0) { printf("barber sleeping\\n"); eflag=1; sem_change(sem_ID, 0, 1); printf("b%d\\n",customers_count); sem_change(sem_ID, 1, -1); printf("c%d\\n",customers_count); sem_change(sem_ID, 0, -1); printf("d%d\\n",customers_count); } sem_change(sem_ID, 0, 1); printf("e%d\\n",customers_count); printf("f%d\\n",customers_count); sem_change(sem_ID, 4, -1); customers_count--; printf("g%d\\n",customers_count); } } void customer(void *arg) { sem_change(sem_ID, 0, -1); printf("h%d\\n",customers_count); if(customers_count==5) { int *ptr=(int*)arg; *ptr=0; printf("No place for customer %d so leaving\\n", pthread_self()); sem_change(sem_ID, 0, 1); printf("i%d\\n",customers_count); return; } customers_count++; if(customers_count==1 && eflag==1) { sem_change(sem_ID, 1, 1); printf("j%d\\n",customers_count); printf("Barber Wokw up\\n"); eflag=0; } sem_change(sem_ID, 0, 1); printf("k%d\\n",customers_count); printf("Customer %d got a place\\n", (int)pthread_self()); printf("l%d\\n",customers_count); printf("Cutting for %d customer\\n", pthread_self()); sleep(rand()%5+4); sem_change(sem_ID, 4, 1); printf("m%d\\n",customers_count); int *ptr=(int*)arg; *ptr=0; } int main(int argc, char* argv[]) { pthread_t barber_thread; int live_threads[5 +2]; pthread_t customer_thread[5 +2]; int i; for(i=0; i<5 +2; i++) live_threads[i]=0; int array[]={1, 0, 5, 0, 0}; sem_ID=sem_init_diff_val(5,array); pthread_create(&barber_thread, 0, (void*)&barber, 0); sleep(2); while(1) {int i; for(i=0; i<5 +2; i++) { if(live_threads[i]==0) { live_threads[i]=1; pthread_create(&customer_thread[i], 0, (void*)&customer, (void*)&live_threads[i]); } } } exit(0); }
0
#include <pthread.h> struct control_info { int workload; int rounds; }; char g_buffer[(4*1024) * (4*1024)]; pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER; unsigned int overlap_count = 0; void unit_work(void) { int i; int f,f1,f2; struct timeinfo begin, end; f1 =12441331; f2 = 3245235; for (i = 47880000; i > 0; i--) { f *= f1; f1 *= f2; f1 *= f2; f2 *= f; f2 *= f; f *= f1; f *= f1; f1 *= f2; f1 *= f2; f2 *= f; f2 *= f; f *= f1; } } void * child_thread(void * data) { struct control_info * pCntrl = (struct control_info *)data; char * pStart = 0; int pages = 0; int i = 0, j = 0; int workload = pCntrl->workload; int rounds = pCntrl->rounds; fprintf(stderr, "%d : total rounds %d\\n", getpid(), rounds); while(i < rounds) { fprintf(stderr, "%d : now rounds %d\\n", getpid(), i); pthread_mutex_lock(&g_lock); pthread_mutex_unlock(&g_lock); for(j = 0; j < workload; j++) { unit_work(); } i++; continue; } fprintf(stderr, "in the end, rounds %d\\n", i); } const long int A = 48271; const long int M = 2147483647; static int random2(unsigned int m_seed) { long tmp_seed; long int Q = M / A; long int R = M % A; tmp_seed = A * ( m_seed % Q ) - R * ( m_seed / Q ); if ( tmp_seed >= 0 ) { m_seed = tmp_seed; } else { m_seed = tmp_seed + M; } return (m_seed%M); } void print_help(void) { printf("Please check the input\\n"); printf("1, overall workload with units of ms. Normally 16000.\\n"); printf("2, number of threads. Not a must, default is 8. It should be set when conflict rate is not 0\\n"); } int main(int argc,char**argv) { double elapse = 0.0; int i, j; int workload; int times; char * addr = (char *)((unsigned int)g_buffer+(4*1024)); struct control_info *cntrl; int random_seed = time(0); pthread_mutex_init(&g_lock, 0); start(0); if(argc < 2) { print_help(); exit(1); } workload = atoi(argv[1]); const int thr_num = (argc == 3) ? atoi(argv[2]):8; pthread_t waiters[thr_num]; cntrl = (struct control_info *)malloc(thr_num * sizeof(struct control_info)); if(cntrl == 0) { printf("Can not alloc space for control structure\\n"); exit(1); } memset((void *)cntrl, 0, (thr_num * sizeof(struct control_info))); for(i = 0; i < thr_num; i++) { struct control_info * control = (struct control_info *)((int)cntrl + i * sizeof(struct control_info)); control->rounds = 5; control->workload = workload; } for(j = 0; j < thr_num; j++) { pthread_create (&waiters[j], 0, child_thread, (void *)&cntrl[j]); } for(j = 0; j < thr_num; j++) { pthread_join (waiters[j], 0); } elapse = stop(0, 0); printf("elapse %ld\\n", elapse2ms(elapse)); free(cntrl); return 0; }
1
#include <pthread.h> uint16_t breakpoints[MAX_BREAKPOINTS] = {0}; uint8_t breakpoints_len = 0; char cmd[32] = {0}; extern volatile uint8_t RUNNING; extern volatile uint8_t STEP; pthread_mutex_t mutex; pthread_cond_t condA; void* debugger_main(void *running) { pthread_mutex_init(&mutex, 0); RUNNING = 1; while (1) { while (RUNNING == 1) pthread_cond_wait(&condA, &mutex); printf("\\n> "); fgets(cmd, 32, stdin); if (debugger_cmd(cmd)) { cpu_step(); debugger_set_state(1); } } } void debugger_set_state(uint8_t state) { pthread_mutex_lock(&mutex); RUNNING = state; pthread_cond_signal(&condA); pthread_mutex_unlock(&mutex); } uint8_t debugger_cmd(char *cmd) { uint16_t addr = 0; uint16_t ret = 0; char *tok; tok = strtok(cmd, " "); switch(*tok) { case 'b': tok = strtok(0, " "); if (tok == 0) { printf("Missing address.\\n"); } else { addr = strtoul(tok, 0, 16); if (addr == 0) { printf("Invalid address.\\n"); } else { printf("Added breakpoint at address $%04hx.\\n", addr); debugger_add_breakpoint(addr); } } break; case 'c': ret = 1; break; case 'd': tok = strtok(0, " "); if (tok == 0) { printf("Missing address.\\n"); } else { addr = strtoul(tok, 0, 16); if (addr == 0) { printf("Invalid address.\\n"); } else { if (debugger_remove_breakpoint(addr)) { printf("Removed breakpoint at address $%04hx.\\n", addr); } else { printf("Breakpoint at address $%04hx not found.\\n", addr); } } } break; case 'h': debugger_help(); break; case 'i': debugger_info(); break; case 'l': debugger_list_breakpoints(); break; case 'r': ret = 1; break; case 's': STEP = 1; ret = 1; break; case 'x': exit(0); break; default: printf("Invalid command, type 'h' for list of commands.\\n"); } return ret; } void debugger_help() { printf("COMMANDS:\\n"); printf(" b -- Add breakpoint e.g. b 12ab\\n"); printf(" c -- Continue rom execution\\n"); printf(" d -- Delete breakpoint e.g. d 12ab\\n"); printf(" h -- This menu\\n"); printf(" i -- CPU info\\n"); printf(" l -- List breakpoints\\n"); printf(" r -- Run rom\\n"); printf(" s -- Step, execute one instruction\\n"); printf(" x -- Exit\\n"); } void debugger_list_breakpoints() { uint8_t i = 0; while (breakpoints[i] != 0) { printf("[%d] $%04hx\\n", i, breakpoints[i]); i++; } if (i == 0) { printf("No breakpoints.\\n"); } } void debugger_add_breakpoint(uint16_t addr) { if (breakpoints_len < MAX_BREAKPOINTS) { breakpoints[breakpoints_len] = addr; breakpoints_len++; } } uint8_t debugger_remove_breakpoint(uint16_t addr) { uint8_t i; for(i = 0; i < MAX_BREAKPOINTS && breakpoints[i] != addr; i++); if (addr && breakpoints[i] == addr) { breakpoints[i] = breakpoints[breakpoints_len - 1]; breakpoints[breakpoints_len - 1] = 0; breakpoints_len--; return 1; } return 0; } uint8_t debugger_in_breakpoints(uint16_t addr) { uint8_t i; for (i = 0; i < breakpoints_len; i++) { if (breakpoints[i] == addr) return 1; } return 0; } void debugger_info() { cpu_debug(); }
0
#include <pthread.h> pthread_t tid[] = {100, 200, 300, 400}; pthread_mutex_t lock1, lock2, lock3, lock4; int pages[5000][3]; void* thread1(void *arg) { while(1) { pthread_mutex_lock(&lock1); int randPage = rand() % 5000; int randOperation = rand() % 2; if(pages[randPage][0] == 0) { if(randOperation == 0) { pages[randPage][0] = 100; pages[randPage][1] = 1; pages[randPage][2] = 0; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } else { pages[randPage][0] = 100; pages[randPage][1] = 1; pages[randPage][2] = 1; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } } else if(pages[randPage][0] == 100 || pages[randPage][0] == 200 || pages[randPage][0] == 300) printf("Page fault\\n"); pthread_mutex_unlock(&lock2); } return 0; } void* thread2(void *arg) { while(1) { pthread_mutex_lock(&lock2); int randPage = rand() % 5000; int randOperation = rand() % 2; if(pages[randPage][0] == 0) { if(randOperation == 0) { pages[randPage][0] = 200; pages[randPage][1] = 1; pages[randPage][2] = 0; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } else { pages[randPage][0] = 200; pages[randPage][1] = 1; pages[randPage][2] = 1; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } } else if(pages[randPage][0] == 100 || pages[randPage][0] == 200 || pages[randPage][0] == 300) printf("Page fault\\n"); pthread_mutex_unlock(&lock3); } return 0; } void* thread3(void *arg) { while(1) { pthread_mutex_lock(&lock3); int randPage = rand() % 5000; int randOperation = rand() % 2; if(pages[randPage][0] != 100 || pages[randPage][0] != 200 || pages[randPage][0] != 300) { if(randOperation == 0) { pages[randPage][0] = 300; pages[randPage][1] = 1; pages[randPage][2] = 0; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } else { pages[randPage][0] = 300; pages[randPage][1] = 1; pages[randPage][2] = 1; printf("Setting page %d PID to %d, R to %d, and M to %d\\n", randPage, pages[randPage][0], pages[randPage][1], pages[randPage][2]); } } else if(pages[randPage][0] == 100 || pages[randPage][0] == 200 || pages[randPage][0] == 300) printf("Page fault\\n"); pthread_mutex_unlock(&lock4); } return 0; } void* thread4(void *arg) { while(1) { int i = 0; pthread_mutex_lock(&lock4); for(i; i < 5000; i++) { if(pages[i][1] == 1) { printf("Resetting R\\n"); pages[i][1] = 0; if(pages[i][2] == 1) { pages[i][2] = 0; printf("Resetting M\\n"); printf("Simulating print\\n"); int wait = time(0) + 1; while(time(0) < wait); } } pages[i][0] = 0; } pthread_mutex_unlock(&lock1); } } int main(void) { int seed = time(0); srand(seed); int i, j; for(i = 0; i < 5000; i++) { for(j = 0; j < 3; j++) { pages[i][j] = 0; } } pthread_create(&(tid[100]), 0, &thread1, 0); pthread_create(&(tid[200]), 0, &thread2, 0); pthread_create(&(tid[300]), 0, &thread3, 0); pthread_create(&(tid[400]), 0, &thread4, 0); pthread_join(tid[100], 0); pthread_join(tid[200], 0); pthread_join(tid[300], 0); pthread_join(tid[400], 0); pthread_mutex_destroy(&lock1); pthread_mutex_destroy(&lock2); pthread_mutex_destroy(&lock3); pthread_mutex_destroy(&lock4); return 0; }
1
#include <pthread.h> int *array; int length, count= 0; pthread_t *ids; pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER; int length_per_thread; void * count3p(void *myI){ int i, myStart, myEnd, myIdx= (int)myI; myStart= length_per_thread * myIdx; myEnd= myStart + length_per_thread; printf("Thread idx %d, Starting at %d Ending at %d\\n", myIdx, myStart, myEnd-1); pthread_mutex_lock(&mtx); for(i=myStart; i < myEnd; i++){ if(array[i] == 3){ count++; } } pthread_mutex_unlock(&mtx); } void count3Launcher(int n) { int i; for (i= 0; i < n; i++) { Pthread_create(&ids[i], 0, count3p, (void *)i); } } void count3Joiner(int n) { int i; for (i= 0; i < n; i++) { Pthread_join(ids[i], 0); } } int main( int argc, char *argv[]){ int i; struct timeval s,t; if ( argc != 2 ) { printf("Usage: %s <number of threads>\\n", argv[0]); return 1; } int n = atoi(argv[1]); ids = (pthread_t *)malloc(n*sizeof(pthread_t)); array= (int *)malloc(384*1024*1024*sizeof(int)); length = 384*1024*1024; srand(0); for(i=0; i < length; i++){ array[i] = rand() % 4; } if ( (384*1024*1024 % n) != 0 ) { printf("Work unevenly distributed among threads is not supported by this implementation!!!\\n"); return 2; } length_per_thread = 384*1024*1024 / n; printf("Using %d threads; length_per_thread = %d\\n", n, length_per_thread); gettimeofday(&s, 0); count3Launcher(n); count3Joiner(n); gettimeofday(&t, 0); printf("Count of 3s = %d\\n", count); printf("Elapsed time (us) = %ld\\n", (t.tv_sec - s.tv_sec)*1000000 + (t.tv_usec - s.tv_usec)); return 0; }
0
#include <pthread.h> { char *file; char *command; int bufferSize; char *directory; } s_request; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int bytes = 0; void *scanFile( s_request *request ) { pthread_mutex_lock(&mutex); struct rusage usage; struct timeval start, end, startUser, endUser; getrusage(RUSAGE_SELF, &usage); start = usage.ru_stime; startUser = usage.ru_utime; int byteNumber = 0; char *bufferCommand = "-b"; char *mmapCommand = "-mem"; int readFileReference; int writeFileReference; int bufferSize = request->bufferSize; int numberOfBytesRead = bufferSize; int *buffer[bufferSize]; char destination[1024]; char command[1024]; strncpy(destination, request->directory, sizeof(destination) - 1); destination[sizeof(destination) - 1] = '\\0'; strcat(destination, request->file); strncpy(command, request->command, sizeof(command) - 1); command[sizeof(command) - 1] = '\\0'; if (!strcmp(command, bufferCommand)) { if ((readFileReference = open(request->file, O_RDONLY)) == -1) { printf("Failed to open file. Aborting.\\n"); exit(1); } if ((writeFileReference = open(destination, O_CREAT | O_RDWR, 0777)) == -1) { printf("Failed to open write file. Aborting.\\n"); exit(1); } while ((byteNumber = read(readFileReference, buffer, numberOfBytesRead)) != 0) { bytes += byteNumber; write(writeFileReference, buffer, byteNumber); bzero(buffer, bufferSize); } close(writeFileReference); close(readFileReference); } else if (!strcmp(command, mmapCommand)) { struct stat st; stat(request->file, &st); size_t fileSize = st.st_size; if ((readFileReference = open(request->file, O_RDONLY)) == -1) { printf("Failed to open file. Aborting.\\n"); exit(1); } void *mmappedData = mmap(0, fileSize, PROT_READ, MAP_PRIVATE, readFileReference, 0); if ((writeFileReference = open(destination, O_CREAT | O_RDWR, 0777)) == -1) { printf("Failed to open write file. Aborting.\\n"); exit(1); } bytes += write(writeFileReference, mmappedData, fileSize); munmap(mmappedData, fileSize); close(readFileReference); } else { if ((readFileReference = open(request->file, O_RDONLY)) == -1) { printf("Failed to open file. Aborting.\\n"); exit(1); } if ((writeFileReference = open(destination, O_CREAT | O_RDWR, 0777)) == -1) { printf("Failed to open write file. Aborting.\\n"); exit(1); } while ((byteNumber = read(readFileReference, buffer, numberOfBytesRead)) != 0) { bytes += byteNumber; write(writeFileReference, buffer, byteNumber); bzero(buffer, bufferSize); } close(writeFileReference); close(readFileReference); } getrusage(RUSAGE_SELF, &usage); end = usage.ru_stime; endUser = usage.ru_utime; printf("Started copying %s at: %ld.%lds (system), %ld.%lds (user)\\n", request->file, start.tv_sec, start.tv_usec, startUser.tv_sec, startUser.tv_usec); printf("Ended copying %s at: %ld.%lds, %ld.%lds (user)\\n", request->file, end.tv_sec, end.tv_usec, endUser.tv_sec, endUser.tv_usec); printf("\\n"); pthread_mutex_unlock(&mutex); return (void *)bytes; }
1
#include <pthread.h> key_t key; int shmid; int *lost; pthread_mutex_t lock; Window window; Display* display; int users; int main(int argc, char *argv[]) { key = 42; shmid = shmget(key, 1, 0644 | IPC_CREAT); lost = shmat(shmid, (void *)0, 0); *lost = 0; pthread_mutex_init(&lock, 0); users = count_users(); display = XOpenDisplay(0); window = focussed_window(); srand(time(0)); int r = rand(); char pname[10]; sprintf(pname, "%d", r); int size = strlen(argv[0]); strncpy(argv[0],pname,size); prctl(PR_SET_NAME, *pname); pid_t fg = tcgetpgrp(0); if(fg != getpgrp() && fg != -1) { end(); } pid_t cpid; cpid = fork(); if(cpid == 0) { printf("Hit enter to keep the timer from reaching zero.\\n"); pthread_t parent, time, limiter; pthread_create(&parent, 0, check_parent, 0); pthread_create(&time, 0, timer, 0); pthread_create(&limiter, 0, limit, 0); signal(SIGTERM, end); while(1) { if(getchar()) { pthread_cancel(time); pthread_create(&time, 0, timer, 0); } } } else { pthread_t windowChecker, userChecker; pthread_create(&windowChecker, 0, check_window, 0); pthread_create(&userChecker, 0, check_users, 0); signal(SIGINT, end); signal(SIGHUP, end); signal(SIGTERM, end); signal(SIGTSTP, end); signal(SIGKILL, end); wait(0); end(); } return 0; } void end() { pthread_mutex_lock(&lock); if(*lost == 0) { printf("\\n\\nGame over.\\n"); fopen("game.over", "ab+"); *lost = 1; } pthread_mutex_unlock(&lock); exit(0); } Window focussed_window() { Window w; int revert_to; XGetInputFocus(display, &w, &revert_to); return w; } int count_users() { FILE *ufp; ufp = fopen(_PATH_UTMP, "r"); int num = 0; struct utmp usr; while(fread((char *)&usr, sizeof(usr), 1, ufp) == 1) { if(*usr.ut_name && *usr.ut_line && *usr.ut_line != '~') { num++; } } fclose(ufp); return num; } void *check_users() { while(1) { usleep(100000); if(count_users() > users) { end(); } } } void *check_window() { while(1) { usleep(100000); if(focussed_window() != window) { end(); } } } void *check_parent() { while(1) { usleep(100000); if(getppid() <=1) { end(); } } } void *limit() { sleep(600); printf("\\n\\nYou have won!\\n"); pthread_mutex_lock(&lock); *lost = 1; pthread_mutex_unlock(&lock); end(); return 0; } void *timer() { printf("\\n"); for(int i = 10; i > 0; i--) { sleep(1); printf("%d.. ", i); fflush(stdout); } end(); return 0; }
0
#include <pthread.h> void rw_init(struct rw_lock_s *rwLock) { pthread_mutex_init(&rwLock->mutex, 0); pthread_cond_init(&rwLock->noWriters, 0); pthread_cond_init(&rwLock->noActiveWriter, 0); pthread_cond_init(&rwLock->noReaders, 0); rwLock->readers = 0; rwLock->writers = 0; rwLock->writerActive = 0; } void rw_lock_read(struct rw_lock_s *rwLock) { pthread_mutex_lock(&rwLock->mutex); while (rwLock->writers > 0) { pthread_cond_wait(&rwLock->noWriters, &rwLock->mutex); } rwLock->readers++; pthread_mutex_unlock(&rwLock->mutex); } void rw_unlock_read(struct rw_lock_s *rwLock) { pthread_mutex_lock(&rwLock->mutex); rwLock->readers--; if (rwLock->readers == 0) { pthread_cond_signal(&rwLock->noReaders); } pthread_mutex_unlock(&rwLock->mutex); } int rw_trylock_write(struct rw_lock_s *rwLock) { pthread_mutex_lock(&rwLock->mutex); if (rwLock->readers > 0 || rwLock->writers > 0 || rwLock->writerActive) { pthread_mutex_unlock(&rwLock->mutex); return 0; } else { rwLock->writers++; rwLock->writerActive = 1; pthread_mutex_unlock(&rwLock->mutex); return 1; } } void rw_lock_write(struct rw_lock_s *rwLock) { pthread_mutex_lock(&rwLock->mutex); rwLock->writers++; while (rwLock->readers > 0) { pthread_cond_wait(&rwLock->noReaders, &rwLock->mutex); } while (rwLock->writerActive) { pthread_cond_wait(&rwLock->noActiveWriter, &rwLock->mutex); } rwLock->writerActive = 1; pthread_mutex_unlock(&rwLock->mutex); } void rw_unlock_write(struct rw_lock_s *rwLock) { pthread_mutex_lock(&rwLock->mutex); rwLock->writerActive = 0; rwLock->writers--; if (rwLock->writers > 0) { pthread_cond_signal(&rwLock->noActiveWriter); } else { pthread_cond_signal(&rwLock->noWriters); } pthread_mutex_unlock(&rwLock->mutex); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_t thr1, thr2, thr3; pthread_attr_t attr1, attr2, attr3; void * fonction_2(void * unused) { int i, j; fprintf(stderr, " T2 demarre\\n"); fprintf(stderr, " T2 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T2 se termine\\n"); return 0; } void * fonction_3(void * unused) { int i, j; fprintf(stderr, " T3 demarre\\n"); fprintf(stderr, " T3 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, " T3 tient le mutex\\n"); fprintf(stderr, " T3 travaille...\\n"); for (i = 0; i < 100000; i ++) for (j = 0; j < 10000; j ++) ; fprintf(stderr, " T3 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, " T3 se termine\\n"); return 0; } void * fonction_1(void *unused) { fprintf(stderr, "T1 demarre\\n"); fprintf(stderr, "T1 demande le mutex\\n"); pthread_mutex_lock(& mutex); fprintf(stderr, "T1 tient le mutex\\n"); fprintf(stderr, "reveil de T3\\n"); pthread_create(& thr3, &attr3, fonction_3, 0); fprintf(stderr, "reveil de T2\\n"); pthread_create(& thr2, &attr2, fonction_2, 0); fprintf(stderr, "T1 lache le mutex\\n"); pthread_mutex_unlock(& mutex); fprintf(stderr, "T1 se termine\\n"); return 0; } int main(int argc, char * argv []) { struct sched_param param; pthread_mutexattr_t attr; pthread_mutexattr_init(& attr); pthread_mutexattr_setprotocol (& attr, PTHREAD_PRIO_INHERIT); pthread_mutex_init(& mutex, &attr); pthread_attr_init(& attr1); pthread_attr_init(& attr2); pthread_attr_init(& attr3); pthread_attr_setschedpolicy(& attr1, SCHED_FIFO); pthread_attr_setschedpolicy(& attr2, SCHED_FIFO); pthread_attr_setschedpolicy(& attr3, SCHED_FIFO); param.sched_priority = 10; pthread_attr_setschedparam(& attr1, & param); param.sched_priority = 20; pthread_attr_setschedparam(& attr2, & param); param.sched_priority = 30; pthread_attr_setschedparam(& attr3, & param); pthread_attr_setinheritsched(& attr1, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr2, PTHREAD_EXPLICIT_SCHED); pthread_attr_setinheritsched(& attr3, PTHREAD_EXPLICIT_SCHED); if ((errno = pthread_create(& thr1, & attr1, fonction_1, 0)) != 0) { perror("pthread_create"); exit(1); } pthread_join(thr1, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t mx1=PTHREAD_MUTEX_INITIALIZER; int st; int vec; int *ar; void *f1(void *arg) { int i,j; while(st) { pthread_mutex_lock(&mx1); j=0; for(i=1;i<1000;i++) if (ar[i]==1)j++; printf("Vec %d %d \\n",j,ar[0]); pthread_mutex_unlock(&mx1); sleep(1); } pthread_exit(arg); } void *fr(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); vec--; ar[0]--; for(i=1;i<1000;i++) if (ar[i]==1){ar[i]=0;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void *fw(void *arg) { int i; while(st) { pthread_mutex_lock(&mx1); vec++; ar[0]++; for(i=1;i<1000;i++) if (ar[i]==0){ar[i]=1;break;} pthread_mutex_unlock(&mx1); } pthread_exit(arg); } void ha(int i) { st=0; signal(SIGINT,ha); } int main(int args, char **argv, char **argc) { int nM,nN,i,shmid; pthread_t t; pthread_t tr[100]; pthread_t tw[100]; struct stat sta; struct ipc_perm perm; struct shmid_ds ds; key_t kk; stat("prg.o",&sta); kk=ftok("prg.o",0x57); printf( "id-- %lx %lx %x \\n", (u_long)sta.st_dev,(u_long)sta.st_ino,(u_int)kk); shmid=shmget(kk,1000*sizeof(int),IPC_CREAT| 0644 ); if(shmid==-1) { perror("shmget");exit(1);}; ar=shmat(shmid,0,0); if(ar==0) { perror("shmat");exit(1);}; for(i=0;i<1000;i++) ar[i]=0; if(args==1) { printf("prg N n \\n"); } vec=0; if(args==3) { signal(SIGINT,ha); nN=atoi(&argv[1][0]); nM=atoi(&argv[2][0]); if(nN>100)exit(1); if(nM>100)exit(1); st=1; for(i=0;i<nN;i++) pthread_create(&tr[i],0,fr,0); for(i=0;i<nM;i++) pthread_create(&tw[i],0,fw,0); pthread_create(&t,0,f1,0); for(i=0;i<nM;i++) pthread_join(tw[i],0); for(i=0;i<nN;i++) pthread_join(tr[i],0); pthread_join(t,0); shmdt(ar); printf("Ok \\n"); return 0; } }
1
#include <pthread.h> struct thread_arg { pthread_t tid; int idx; char *x, *y; } t_arg[3]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *start_func(void *); void clean_thread(struct thread_arg *); char *sum_strnum(const char *, const char *); int main() { t_arg[0].idx = 0; t_arg[0].x = "1"; t_arg[0].y = "3"; if (pthread_create(&t_arg[0].tid, 0, start_func, &t_arg[0]) != 0) { exit(1); } t_arg[1].idx = 1; t_arg[1].x = "4"; t_arg[1].y = "4"; if (pthread_create(&t_arg[1].tid, 0, start_func, &t_arg[1]) != 0) { exit(1); } t_arg[2].idx = 2; t_arg[2].x = "1"; t_arg[2].y = "5"; if (pthread_create(&t_arg[2].tid, 0, start_func, &t_arg[2]) != 0) { exit(1); } clean_thread(t_arg); return 0; } void *start_func(void *arg) { struct thread_arg *t_arg = (struct thread_arg *)arg; char *ret_str = sum_strnum(t_arg->x, t_arg->y); if (t_arg->idx == 0) usleep(500000); printf("%s + %s = %s (%p)\\n", t_arg->x, t_arg->y, ret_str, ret_str); pthread_exit(t_arg); } void clean_thread(struct thread_arg *t_arg) { int i; struct thread_arg *t_arg_ret; for (i=0; i<3; i++, t_arg++) { pthread_join(t_arg->tid, (void **)&t_arg_ret); pr_out("pthread_join : %d - %lu", t_arg->idx, t_arg->tid); } } char *sum_strnum(const char *s1, const char *s2) { static char buf_sum[16]; pthread_mutex_lock(&mutex); snprintf(buf_sum, sizeof(buf_sum), "%d", atoi(s1) + atoi(s2)); pthread_mutex_unlock(&mutex); return buf_sum; }
0
#include <pthread.h> struct timespec start; struct timespec stop; int num = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* FirstThread(void *n) { while(num == 1) { pthread_mutex_lock(&mutex); num=0; pthread_mutex_unlock(&mutex); } } void* SecondThread(void *n) { while(num == 0) { pthread_mutex_lock(&mutex); num=1; pthread_mutex_unlock(&mutex); } } int main() { pthread_t id1, id2; clock_gettime(CLOCK_MONOTONIC, &start); pthread_create(&id1, 0, FirstThread, 0); pthread_create(&id2, 0, SecondThread, 0); pthread_join(id1, 0); pthread_join(id2, 0); clock_gettime(CLOCK_MONOTONIC, &stop); double result = (stop.tv_sec - start.tv_sec)*(1000000000) + (double)(stop.tv_nsec - start.tv_nsec); printf("The cost of thread-switching function is %lf nanoseconds\\n" , result); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex ; pthread_cond_t cond ; void *thread1( void *arg ) { pthread_cleanup_push(pthread_mutex_unlock ,&mutex); while(1) { printf("thread1 is running !! \\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond ,&mutex); printf("thread 1 is apply the conditionn !! \\n"); pthread_mutex_unlock(&mutex); sleep(1); } pthread_cleanup_pop(0); } void *thread2( void *arg ) { while(1) { printf("thread2 is running !! \\n"); pthread_mutex_lock(&mutex); pthread_cond_wait(&cond ,&mutex); printf("thread2 is apply the conditionn !! \\n"); pthread_mutex_unlock(&mutex); sleep(1); } } int main(void) { pthread_t tid1 ,tid2 ; printf("520520505201505205020502220500\\n"); pthread_mutex_init(&mutex,0); pthread_cond_init(&cond,0); pthread_create(&tid1 ,0,(void *)thread1 ,0); pthread_create(&tid2 ,0,(void *)thread2 ,0); do { pthread_cond_signal(&cond); }while(1); sleep(50); pthread_exit(0); }
0
#include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; int f_id; }; static struct foo *g_fp = 0; struct foo *foo_alloc(int id) { struct foo *fp; if((fp = malloc(sizeof(struct foo))) != 0){ fp->f_count = 1; fp->f_id = id; if(pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } } return(fp); } void foo_hold(struct foo *fp) { int i; pthread_mutex_lock(&fp->f_lock); for(i = 0; i < 100; i++){ fp->f_count++; printf("fp fcount:%d\\n", fp->f_count); } pthread_mutex_unlock(&fp->f_lock); } static void sig_alrm(int signo){ printf("enter sig alrm!\\n"); pthread_mutex_unlock(&g_fp->f_lock); } void foo_hold_1(struct foo *fp) { int i; if(signal(SIGINT, sig_alrm) == SIG_ERR){ printf("signal receive error!\\n"); exit(1); } pthread_mutex_lock(&fp->f_lock); for(i = 0; i < 5; i++){ fp->f_count++; printf("thread 1 fp fcount:%d\\n", fp->f_count); } pause(); } void foo_hold_2(struct foo *fp) { int i; pthread_mutex_lock(&fp->f_lock); for(i = 0; i < 5; i++){ fp->f_count++; printf("thread 2 fp fcount:%d\\n", fp->f_count); } pthread_mutex_unlock(&fp->f_lock); } void foo_rele(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); if(--fp->f_count == 0) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); } } void *thr_func1(void *argv) { int i; printf("start thread 1!\\n"); for(i = 0; i < 100; i++){ foo_hold_1(g_fp); } printf("end of thread 1!\\n"); } void *thr_func2(void *argv) { int i; printf("start thread 2!\\n"); for(i = 0; i < 100; i++){ foo_hold_2(g_fp); } printf("end of thread 2!\\n"); } int main(void) { pthread_t tid1,tid2; g_fp = foo_alloc(1); pthread_create(&tid1,0,thr_func1, 0); pthread_create(&tid2, 0, thr_func2, 0); pause(); foo_rele(g_fp); pause(); return 0; }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; int f_id; struct foo *f_next; char name[20]; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); snprintf(fp->name, 20, "%d_foo", id); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo * foo_find(int id) { struct foo *fp; pthread_mutex_lock(&hashlock); for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lock); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp->f_id)%29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = tfp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } } void *thread_func(void *arg) { struct foo *fp; long thread_num = (long)arg; int i; for (i = 0; i<1000; i++) foo_alloc(i+(1000*thread_num)); for (i = 0; i<500; i++){ fp = foo_find(random()%1000); if (!fp) continue; foo_hold(fp); sprintf(fp->name, "I'm %s", fp->name); foo_rele(fp); } return 0; } int main(void) { pthread_t tid[40]; long i; int rc; srand(time(0)); for (i = 0; i<40; i++){ if (rc = pthread_create(&tid[i], 0, thread_func, (void*)&i)){ printf("pthread_create() error\\n"); exit(-1); } } for (i = 0; i<40; i++){ if (rc = pthread_join(tid[i], 0)){ printf("pthread_join() error\\n"); exit(-1); } } return 0; }
0
#include <pthread.h> void do_one_thing(int *); void do_another_thing(int *); void do_wrap_up(int, int); int r1 = 0, r2 = 0, r3 = 0; pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER; extern int main(int argc, char **argv) { pthread_t thread1, thread2; if (argc > 1) r3 = atoi(argv[1]); if (pthread_create(&thread1, 0, (void *) do_one_thing, (void *) &r1) != 0) perror("pthread_create"),exit(1); if (pthread_create(&thread2, 0, (void *) do_another_thing, (void *) &r2) != 0) perror("pthread_create"),exit(1); if (pthread_join(thread1, 0) != 0) perror("pthread_join"), exit(1); if (pthread_join(thread2, 0) != 0) perror("pthread_join"), exit(1); do_wrap_up(r1, r2); return 0; } void do_one_thing(int *pnum_times) { int i, j, x; pthread_t ti; ti = pthread_self(); pthread_mutex_lock(&r3_mutex); if(r3 > 0) { x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4; i++) { printf("doing one thing\\n"); for (j = 0; j < 10000; j++) x = x + i; printf("thread %d: got x = %d\\n", (int)ti, x); (*pnum_times)++; } } void do_another_thing(int *pnum_times) { int i, j, x; pthread_t ti; ti = pthread_self(); pthread_mutex_lock(&r3_mutex); if(r3 > 0) { x = r3; r3--; } else { x = 1; } pthread_mutex_unlock(&r3_mutex); for (i = 0; i < 4; i++) { printf("doing another \\n"); for (j = 0; j < 10000; j++) x = x + i; printf("thread %d: got x = %d\\n", (int)ti, x); (*pnum_times)++; } } void do_wrap_up(int one_times, int another_times) { int total; total = one_times + another_times; printf("All done, one thing %d, another %d for a total of %d\\n", one_times, another_times, total); }
1
#include <pthread.h> int promedio=0; int maximo=0; int minimo=1000; int longitud=0; pthread_mutex_t bloqueo; void* Valor_minimo(void *l){ int *p = (int*)l; int a=0; pthread_mutex_lock(&bloqueo); for (a=0; a < longitud; a++) { if (p[a]<=minimo){ minimo=p[a]; } } pthread_mutex_unlock(&bloqueo); pthread_exit(0); } void* Valor_maximo(void *l){ int a; int *p = (int*)l; pthread_mutex_lock(&bloqueo); for (a=0; a < longitud; a++) { if (p[a]>=maximo){ maximo=p[a]; } } pthread_mutex_unlock(&bloqueo); pthread_exit(0); } void* Valor_promedio(void *l){ int *p = (int*) l; int a=0; pthread_mutex_lock(&bloqueo); for (a=0; a < longitud; a++) { promedio=promedio+p[a]; } promedio=promedio/a; pthread_mutex_unlock(&bloqueo); pthread_exit(0); } int main(int argc, char *argv[]) { int b; pthread_t threads[3]; pthread_attr_t attr; printf("Ingrese la cantidad de numeros que desee operar: \\n"); scanf("%d",&longitud); int lista[longitud]; for (b = 0; b < longitud; b++) { int numeros; scanf("%d", &numeros); lista[b]=numeros; } pthread_mutex_init(&bloqueo, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_create(&threads[0], &attr, Valor_minimo, (void *) &lista); pthread_create(&threads[1], &attr, Valor_maximo, (void *) &lista); pthread_create(&threads[2], &attr, Valor_promedio, (void *) &lista); for (b=0; b<3; b++) { pthread_join(threads[b], 0); } printf("Minimo: %d\\n", minimo); printf("Maximo: %d\\n", maximo); printf("Promedio: %d\\n", promedio); pthread_attr_destroy(&attr); pthread_mutex_destroy(&bloqueo); pthread_exit (0); }
0
#include <pthread.h> int tid; double stuff; } thread_data_t; int shared_x; pthread_mutex_t lock_x; void* thread_func(void *arg) { thread_data_t* data = (thread_data_t*) arg; pthread_mutex_lock(&lock_x); printf("In thread_func, thread id: %d\\n", data->tid); shared_x += data->stuff; printf("shared_x=%d\\n", shared_x); pthread_mutex_unlock(&lock_x); pthread_exit(0); } int main(int argc, char** argv){ pthread_t thr[16]; int i, rc; thread_data_t thr_data[16]; shared_x = 0; pthread_mutex_init(&lock_x, 0); for (i = 0; i < 16; i++){ thr_data[i].tid = i; thr_data[i].stuff = i + 1; if ((rc = pthread_create(&thr[i], 0, thread_func, &thr_data[i]))){ fprintf(stderr, "error: pthread_create, rc: %d\\n", rc); return 1; } } for (i = 0; i < 16; ++i){ pthread_join(thr[i], 0); } return 0; }
1
#include <pthread.h> static pthread_mutex_t q_mutex; { char ch; int num; struct link *next; }*Link; { Link rear; Link front; }Link_queue; Link_queue my_queue; int is_empty_queue(Link_queue *my_queue) { if((my_queue->rear == 0) && (my_queue->front == 0)) { return -2; } else { return -3; } } int is_malloc(Link temp) { if(temp == 0) { printf("malloc error!\\n"); exit(1); } } void init_link_queue(Link_queue *my_queue) { my_queue->rear = 0; my_queue->front = 0; } int push_link_queue(Link_queue *my_queue, char ch, int num) { Link p; p = (Link)malloc(sizeof(struct link)); is_malloc(p); p->ch = ch; p->num = num; if(my_queue->rear == 0 && my_queue->front == 0) { my_queue->rear = p; my_queue->front = p; p->next = 0; return 0; } my_queue->rear->next = p; p->next = 0; my_queue->rear = p; return 0; } void display_queue(Link_queue * my_queue) { Link p; p = (Link)malloc(sizeof(struct link)); is_malloc(p); printf("now the produce line is"); p = my_queue->front; while(p != 0) { printf(" %c",p->ch); p = p->next; } printf("\\n"); } void *thread_handle0(void *arg) { int i = 0; int num = 0; Link_queue *my_queue = (Link_queue *)arg; while(1) { char ch = 'A' + i; printf("in produce thread[0] produce char %c\\n",ch); i++; if(i == 26) { i = 0; } pthread_mutex_lock(&q_mutex,0); push_link_queue(my_queue,ch,num); display_queue(my_queue); pthread_mutex_unlock(&q_mutex,0); sleep(2); } } void *thread_handle1(void *arg) { int i = 0; int num = 1; Link_queue *my_queue = (Link_queue *)arg; while(1) { char ch = 'A' + i; printf("in produce thread[1] produce char %c\\n",ch); i++; if(i == 26) { i = 0; } pthread_mutex_lock(&q_mutex,0); push_link_queue(my_queue,ch,num); display_queue(my_queue); pthread_mutex_unlock(&q_mutex,0); sleep(2); } } int *thread_handle2(void *arg) { Link_queue *my_queue = (Link_queue *)arg; Link p; p = (Link)malloc(sizeof(struct link)); is_malloc(p); if(is_empty_queue(my_queue) == -2) { printf("the produce is empty!\\n"); return 0; } while(1) { pthread_mutex_lock(&q_mutex,0); p = my_queue->front; my_queue->front = my_queue->front->next; my_queue->rear = my_queue->rear->next; printf("in produce thread[%d] get char %c\\n\\n",p->num,p->ch); free(p); pthread_mutex_unlock(&q_mutex,0); sleep(1); } return 0; } int main() { int i; pthread_t pid[3]; pthread_mutex_init(&q_mutex,0); init_link_queue(&my_queue); int ret = pthread_create(&pid[0],0,thread_handle0,&my_queue); ret = pthread_create(&pid[2],0,thread_handle2,&my_queue); ret = pthread_create(&pid[1],0,thread_handle1,&my_queue); for(i = 0; i < 3; i++) { pthread_join(pid[i],0); } return 0; }
0
#include <pthread.h> int **matrice = 0; int rows = 0, cols = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int maggiore = 0; int running_threads = 4 -1; void *calcola( void *arg){ int somma = 0; int pos = *(int * )arg; printf("\\n\\nPosizione %d\\n", pos); if(pos == 0){ for (int row = 0; row < rows ; row++) { somma = somma + matrice[row][row]; } printf("Diag sx = %d\\n",somma); } if(pos == 1){ for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { if(row + col == cols-1){ somma = somma + matrice[row][col]; } } } printf("Diag dx = %d\\n",somma); } if(pos == 2){ for (int col = 0; col < cols; col++) { somma = somma + matrice[rows/2][col]; } printf("Riga centrale %d\\n",somma); } if(pos == 3){ for (int row = 0; row < rows; row++) { somma = somma + matrice[row][cols/2]; } printf("Col centrale = %d\\n",somma); } pthread_mutex_lock(&mutex); if(somma > maggiore){ maggiore = somma; } running_threads--; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char *argv[]){ if(argc < 2 || (atoi(argv[1]) % 2 == 0)){ printf("Devi inserire la dimensione della matrice dispari.\\n"); return 1; } rows = atoi(argv[1]); cols = atoi(argv[1]); matrice = malloc( rows * sizeof(int *)); for(int row = 0; row < rows; row++){ matrice[row] = malloc(cols * sizeof(int)); for(int col = 0; col < cols; col++){ int valore = 1 + rand() % 5; matrice[row][col] = valore; } } for (int row = 0; row < rows ; row++) { for (int col = 0; col < cols; col++) { int valore = 1+rand()%10; printf("%d \\t",matrice[row][col]); } printf("\\n"); } pthread_t *threads = malloc(4 * sizeof(pthread_t)); for (int i = 0; i < 4; i++){ int *pos=malloc(sizeof(int)); *pos=i; pthread_create(&threads[i],0,calcola,pos); } for (int i = 0; i < 4; i++){ pthread_join(threads[i],0); } while(running_threads > 0){ sleep(1); } printf("\\n\\nMaggiore = %d\\n", maggiore); return 0; }
1
#include <pthread.h> int make_listen(int port); void handle_connection(FILE* fin, FILE* fout); int remove_trailing_whitespace(char* buf); static pthread_mutex_t mutex; static int n_connection_threads; void* connection_thread(void* arg) { FILE* f = (FILE*) arg; pthread_mutex_lock(&mutex); ++n_connection_threads; pthread_mutex_unlock(&mutex); pthread_detach(pthread_self()); handle_connection(f, f); fclose(f); pthread_mutex_lock(&mutex); --n_connection_threads; pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char** argv) { int port = 6168; if (argc >= 2) { port = strtol(argv[1], 0, 0); assert(port > 0 && port <= 65535); } int fd = make_listen(port); raise_file_limit(); pthread_mutex_init(&mutex, 0); while (1) { int cfd = accept(fd, 0, 0); if (cfd < 0) { perror("accept"); exit(1); } while (n_connection_threads > 100) sched_yield(); pthread_t t; FILE* f = fdopen(cfd, "a+"); setvbuf(f, 0, _IONBF, 0); int r = pthread_create(&t, 0, connection_thread, (void*) f); if (r != 0) { perror("pthread_create"); exit(1); } } } void handle_connection(FILE* fin, FILE* fout) { char buf[1024]; while (fgets(buf, 1024, fin)) if (remove_trailing_whitespace(buf)) { struct servent* service = getservbyname(buf, "tcp"); int port = service ? ntohs(service->s_port) : 0; fprintf(fout, "%s,%d\\n", buf, port); } if (ferror(fin)) perror("read"); } int make_listen(int port) { int fd = socket(AF_INET, SOCK_STREAM, 0); assert(fd >= 0); int r = fcntl(fd, F_SETFD, FD_CLOEXEC); assert(r >= 0); int yes = 1; r = setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); assert(r >= 0); struct sockaddr_in address; memset(&address, 0, sizeof(address)); address.sin_family = AF_INET; address.sin_port = htons(port); address.sin_addr.s_addr = INADDR_ANY; r = bind(fd, (struct sockaddr*) &address, sizeof(address)); assert(r >= 0); r = listen(fd, 100); assert(r >= 0); return fd; } int remove_trailing_whitespace(char* buf) { int len = strlen(buf); while (len > 0 && isspace((unsigned char) buf[len - 1])) { --len; buf[len] = 0; } return len; }
0
#include <pthread.h> pthread_mutex_t forks[5]; void eat(void *temp){ int *me; me = temp; printf("Philo %i initializing\\n\\r", *me); int right_fork; int left_fork; if((*me)%2==0) { left_fork = *me; right_fork = *me+1; if(*me == 4) { right_fork = 0; } } else { left_fork = *me+1; right_fork = *me; if(*me == 4) { left_fork = 0; } } printf("Philo %i have left fork: %i, right fork: %i \\n\\r", *me, left_fork, right_fork); int count = 0; while(1) { pthread_mutex_lock(&forks[left_fork]); printf("Philo %i picked up left fork %i\\n\\r",*me,left_fork); pthread_mutex_lock(&forks[right_fork]); printf("Philo %i picked up right fork %i\\n\\r",*me,right_fork); pthread_mutex_unlock(&forks[left_fork]); printf("Philo %i dropped up left fork %i\\n\\r",*me,left_fork); pthread_mutex_unlock(&forks[right_fork]); printf("Philo %i dropped up right fork %i\\n\\r",*me,right_fork); count++; printf("Philo %i has eaten %i times\\n\\r", *me, count); } } int main(void){ pthread_t philo[5]; int args[5] = {0,1,2,3,4}; int i = 0; for(i = 0; i<5; i++) { printf("Init fork %i\\n\\r", i); pthread_mutex_init(&forks[i], 0); } for(i = 0; i<5; i++) { printf("Init philo %i\\n\\r", i); pthread_create(&philo[i], 0, eat, &args[i]); } i = 4; int j = 0; for(j = 0; j<5; j++) { pthread_join(philo[0], 0); } return 1; }
1
#include <pthread.h> pthread_t t[5]; int self[5]; pthread_mutex_t mutex; pthread_cond_t condition[5]; philstat status[5]; int foodEaten[5]; } table; table * tab; void printstate(void){ static char stat[] = "THE"; int i; for (i=0; i<5; i++) { printf("%5c", stat[(int)(tab->status)[i]]); } printf("\\n"); } void printfoodeaten(void){ printf("Total Food Eaten: \\n"); int i; for (i=0; i<5; i++) { printf("%5d", (tab->foodEaten)[i]); } printf("\\n"); } int test (int i) { if ( ((tab->status)[i] == hungry) && ((tab->status)[(i+1)% 5] != eating) && ((tab->status)[(i-1+5)% 5] != eating)) { (tab->status)[i] = eating; pthread_cond_signal(&((tab->condition)[i])); return 1; } return 0; } void pickup_forks(int k) { pthread_mutex_lock(&(tab->mutex)); (tab->status)[k] = hungry; printstate(); if (!test(k)) { pthread_cond_wait(&((tab->condition)[k]), &(tab->mutex)); } printstate(); pthread_mutex_unlock(&(tab->mutex)); } void putdown_forks(int k) { pthread_mutex_lock(&(tab->mutex)); (tab->status)[k] = thinking; (tab->foodEaten)[k]++; printstate(); test((k+1)%5); test((k-1+5)%5); pthread_mutex_unlock(&(tab->mutex)); } table * tableinit(void *(* philosopher)(void *)) { int i; tab = (table *) malloc (sizeof(table)); if(pthread_mutex_init(&(tab->mutex), 0) != 0) { perror("pthread_mutex_init"); exit(1); } for (i=0; i<5; i++) { (tab->self)[i] = i; (tab->status)[i] = thinking; if(pthread_cond_init(&((tab->condition)[i]), 0) != 0) { perror("pthread_cond_init"); exit(1); } } for (i=0; i<5; i++) { if (pthread_create(&((tab->t)[i]),0, philosopher, &((tab->self)[i]))!= 0) { perror("pthread_create"); exit(1); } } return tab; }
0
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static pthread_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init( void ) { pthread_key_create( &key, free ); } char *getenv( const char *env_name ) { int i, len; char *env_value; pthread_once( &init_done, thread_init ); pthread_mutex_lock( &env_mutex ); env_value = (char *) pthread_getspecific( key ); if ( env_value == 0 ) { env_value = (char *) malloc( ARG_MAX ); if ( env_value == 0 ) { pthread_mutex_unlock( &env_mutex ); return 0; } pthread_setspecific( key, env_value ); } len = strlen( env_name ); for ( i = 0; environ[i] != 0; i++ ) { if ( (strncmp( env_name, environ[i], len ) == 0) && (environ[i][len] == '=') ) { strcpy( env_value, &environ[ i ][ len+1 ] ); pthread_mutex_unlock( &env_mutex ); return env_value; } } pthread_mutex_unlock( &env_mutex ); return 0; }
1
#include <pthread.h> void mux_2_memtoreg(void *not_used){ pthread_barrier_wait(&threads_creation); 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); } if((( (separa_MemtoReg & cs.value) >> MemtoReg_POS) & 0x01) == 0) mux_memtoreg_buffer.value = aluout; else mux_memtoreg_buffer.value = mdr; pthread_mutex_lock(&mux_memtoreg_result); mux_memtoreg_buffer.isUpdated = 1; pthread_cond_signal(&mux_memtoreg_execution_wait); pthread_mutex_unlock(&mux_memtoreg_result); pthread_barrier_wait(&current_cycle); mux_memtoreg_buffer.isUpdated = 0; pthread_barrier_wait(&update_registers); } }
0
#include <pthread.h> static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; static char key_buffer[256]; static unsigned int read_idx; static unsigned int write_idx; static int shift; static int caps; static const unsigned char keymap[2][128] = { { 0, 0xFF, '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=', 0xFF, 0xFF, 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 0xFF, '[', '\\n', 0xFF, 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 0xFF, '~', '\\'', 0xFF, ']', 'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', ';', 0xFF, 0xFF, 0xFF, ' ', 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, '-', 0xFF, 0xFF, 0xFF, '+', 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF , 0xFF , '\\\\', 0xFF, 0xFF, 0xFF }, { 0, ')', '_', '+', 0xFF, 0xFF, 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 0xFF, '{', '\\n', 0xFF, 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 0xFF, '^', '"', 0xFF, '}', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', ':', 0xFF, 0xFF, 0xFF, ' ', 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, '-', 0xFF, 0xFF, 0xFF, '+', 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, '|', 0xFF, 0xFF, 0xFF } }; static void key_press_6502(void *opaque, int keycode) { if(keycode >= 128) { return; } if(keycode == 42 || keycode == 54) { shift = 1; return; } if(keycode == 58) { caps = !caps; return; } shift = shift ^ caps; write_char(keymap[shift][keycode]); shift = 0; } void write_char(char c) { if(c == '\\r') { c = '\\n'; } pthread_mutex_lock(&mutex); key_buffer[write_idx] = c; write_idx = (write_idx + 1) % 256; if(write_idx == read_idx) { read_idx = (read_idx + 1) % 256; } pthread_mutex_unlock(&mutex); } void init_keyboard(void) { qemu_add_kbd_event_handler(key_press_6502, 0); } char read_char(void) { char c; pthread_mutex_lock(&mutex); if(read_idx == write_idx) { c = 0; } else { c = key_buffer[read_idx]; read_idx = (read_idx + 1) % 256; } pthread_mutex_unlock(&mutex); return c; }
1
#include <pthread.h> int *array; int result = 0; pthread_mutex_t mutex; struct range { int begin; int end; }; void sum(void *arg) { struct range ran = *((struct range *)arg); int res = 0; for (int i = ran.begin; i < ran.end; i++) { res += array[i]; } pthread_mutex_lock(&mutex); result += res; pthread_mutex_unlock(&mutex); } void setupArray() { array = (int *)malloc(10000000 * sizeof(int)); for (int i = 0; i < 10000000; i++) { array[i] = 1; } } int main(int argc, char **argv) { int thread_count; sscanf(argv[1], "%d", &thread_count); pthread_mutex_init(&mutex, 0); setupArray(); pthread_t *threads = (pthread_t *)malloc(thread_count * sizeof(pthread_t)); struct range *ranges = (struct range *)malloc(thread_count * sizeof(struct range)); int step = 10000000 / thread_count; for (int i = 0; i < thread_count; i++) { ranges[i].begin = i * step; ranges[i].end = (i + 1 < thread_count) ? (i + 1) * step : 10000000; pthread_create(threads + i, 0, &sum, ranges + i); } for (int i = 0; i < thread_count; i++) { pthread_join(*(threads + i), 0); } printf("%d\\n", result); return 0; }
0
#include <pthread.h> { RET_OK = 0, RET_FAIL }Ret; { int r_cursor; int w_cursor; size_t length; void* data[0]; }FifoRing; FifoRing* fifo_ring_create(size_t length) { FifoRing* thiz = 0; if(!(length > 1)) return 0;; thiz = (FifoRing*)malloc(sizeof(FifoRing) + length * sizeof(void*)); if(thiz != 0) { thiz->r_cursor = 0; thiz->w_cursor = 0; thiz->length = length; } return thiz; } Ret fifo_ring_pop(FifoRing* thiz, void** data) { Ret ret = RET_FAIL; if(!(thiz != 0 && data != 0)) return RET_FAIL;; if(thiz->r_cursor != thiz->w_cursor) { *data = thiz->data[thiz->r_cursor]; thiz->r_cursor = (thiz->r_cursor + 1)%thiz->length; ret = RET_OK; } return ret; } Ret fifo_ring_push(FifoRing* thiz, void* data) { int w_cursor = 0; Ret ret = RET_FAIL; if(!(thiz != 0)) return RET_FAIL;; w_cursor = (thiz->w_cursor + 1) % thiz->length; if(w_cursor != thiz->r_cursor) { thiz->data[thiz->w_cursor] = data; thiz->w_cursor = w_cursor; ret = RET_OK; } return ret; } void fifo_ring_destroy(FifoRing* thiz) { if(thiz != 0) { free(thiz); } return; } { FifoRing* fifo; pthread_cond_t cond; pthread_mutex_t mutex; pthread_t tids[10]; }ServerInfo; static void* client_handler(void* param) { int data = 0; int sock_client = 0; ServerInfo* server_info = (ServerInfo*)param; while(1) { pthread_mutex_lock(&server_info->mutex); pthread_cond_wait(&server_info->cond, &server_info->mutex); if(fifo_ring_pop(server_info->fifo, (void**)&sock_client) != RET_OK) { } pthread_mutex_unlock(&server_info->mutex); if(recv(sock_client, &data, sizeof(data), 0) == sizeof(data)) { printf("client pid=%d\\n", data); data = pthread_self(); if(send(sock_client, &data, sizeof(data), 0) != sizeof(data)) { perror("send"); } } else { perror("recv"); } close(sock_client); } return 0; } int main(int argc, char* argv[]) { int i = 0; int opt_value = 1; int addrlen = sizeof(struct sockaddr_in); int sock_client = 0; struct sockaddr_in addr_server = {0}; struct sockaddr_in addr_client = {0}; int sock_listen = socket(PF_INET, SOCK_STREAM, 0); ServerInfo server_info = {0}; if(sock_listen < 0) { perror("socket"); return 1; } addr_server.sin_family = PF_INET; addr_server.sin_addr.s_addr = INADDR_ANY; addr_server.sin_port =htons(0x1234); setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR, &opt_value,sizeof(opt_value)); if(bind(sock_listen, (struct sockaddr*)&addr_server, sizeof(addr_server)) < 0) { perror("bind"); return 1; } if(listen(sock_listen, 5) < 0) { perror("listen"); return 1; } server_info.fifo = fifo_ring_create(256); pthread_cond_init(&server_info.cond, 0); pthread_mutex_init(&server_info.mutex, 0); for(i = 0; i < 10; i++) { pthread_create(&(server_info.tids[i]), 0, client_handler, &server_info); } for(i = 0; i < 10; i++) { if((sock_client = accept(sock_listen, (struct sockaddr*)&addr_client, &addrlen)) < 0) { break; } fifo_ring_push(server_info.fifo, (void*)sock_client); pthread_cond_signal(&server_info.cond); } fifo_ring_destroy(server_info.fifo); pthread_cond_destroy(&server_info.cond); pthread_mutex_destroy(&server_info.mutex); close(sock_listen); return 0; }
1
#include <pthread.h> int g_buffer[10]; unsigned in = 0; unsigned out = 0; unsigned produce_id = 0; unsigned consume_id = 0; sem_t g_sem_full; sem_t g_sem_empty; pthread_mutex_t g_mutex; pthread_t g_thread[1 + 5]; void *consume(void *arg) { int num = (int) arg; while (1) { printf("%d wait to consume..\\n", num); sem_wait(&g_sem_empty); pthread_mutex_lock(&g_mutex); int i; for (i = 0; i < 10; ++i) { printf("%02d ", i); if (g_buffer[i] == -1) printf("%s", "null"); else printf("%d", g_buffer[i]); if (i == out) printf("\\t<--consume"); printf("\\n"); } consume_id = g_buffer[out]; printf("begin consume product %d\\n", consume_id); g_buffer[out] = -1; if (++out == 10) out = 0; printf("end consume product %d\\n", consume_id); pthread_mutex_unlock(&g_mutex); sem_post(&g_sem_full); sleep(1); } return 0; } void *produce(void *arg) { int num = (int) arg; int i; while (1) { printf("%d wait to produce..\\n", num); sem_wait(&g_sem_full); pthread_mutex_lock(&g_mutex); for (i = 0; i < 10; ++i) { printf("%02d ", i); if (g_buffer[i] == -1) printf("%s", "null"); else printf("%d", g_buffer[i]); if (i == in) printf("\\t<--produce"); printf("\\n"); } printf("begin produce product %d\\n", produce_id); g_buffer[in] = produce_id; if (++in == 10) in = 0; printf("end produce product %d\\n", produce_id++); pthread_mutex_unlock(&g_mutex); sem_post(&g_sem_empty); sleep(1); } return 0; } int main(int argc, char *argv[]) { sem_init(&g_sem_full, 0, 10); sem_init(&g_sem_empty, 0, 0); pthread_mutex_init(&g_mutex, 0); int i; for (i = 0; i < 10; ++i) g_buffer[i] = -1; for (i = 0; i < 1; ++i) pthread_create(&g_thread[i], 0, consume, (void *) i); for ( ; i < 5 + 1; ++i) pthread_create(&g_thread[i], 0, produce, (void *) i); for (i = 0; i < 1 + 5; ++i) pthread_join(g_thread[i], 0); sem_destroy(&g_sem_empty); sem_destroy(&g_sem_full); pthread_mutex_destroy(&g_mutex); return 0; }
0
#include <pthread.h> int othm_thread_stop_check(struct othm_thread *thread) { int value; pthread_mutex_lock(&thread->stop_mutex); value = thread->stop_bool; pthread_mutex_unlock(&thread->stop_mutex); return value; } void othm_thread_stop_mutate(struct othm_thread *thread, int value) { pthread_mutex_lock(&thread->stop_mutex); thread->stop_bool = value; pthread_mutex_unlock(&thread->stop_mutex); } void *othm_thread_run_chain(struct othm_thread *thread, struct othm_list *chain, struct othm_thread_control *control, struct othm_thread_control *lower_control, struct othm_list *controller) { struct othm_list *exec_ptr; exec_ptr = chain; control->skip = 0; if (exec_ptr == 0) return 0; do { if (controller != 0) { othm_thread_run_chain(thread, controller->here, control->controller_control, control, controller->next); } if (!control->skip) { OTHM_PRIM_FUNCT_GET((((struct othm_comp *) exec_ptr->here)->prim), OTHM_CHAIN_FUNCT) (exec_ptr, control, lower_control); exec_ptr = (control->position != 0) ? control->position : exec_ptr->next; control->position = 0; } else { control->skip = 0; exec_ptr = exec_ptr->next; } } while (!othm_thread_stop_check(thread) && exec_ptr); return 0; } void *othm_thread_run(void *thread) { othm_thread_run_chain(((struct othm_thread *) thread), ((struct othm_thread *) thread)->chain, ((struct othm_thread *) thread)->top_control, 0, ((struct othm_thread *) thread)->controller); pthread_exit(0); } struct othm_thread *othm_thread_new(long t, struct othm_list *chain, struct othm_list *controller, void *result, void *state) { struct othm_thread *thread; struct othm_thread_control *tc; struct othm_list *c; thread = malloc(sizeof(struct othm_thread)); thread->t = t; pthread_mutex_init(&thread->stop_mutex, 0); thread->stop_bool = 0; thread->chain = chain; thread->controller = controller; thread->top_control = malloc(sizeof(struct othm_thread_control)); tc = thread->top_control; tc->result = result; tc->state = state; for (c = controller; c != 0; c = c->next) { tc->controller_control = malloc(sizeof(struct othm_thread_control)); tc = tc->controller_control; } return thread; } struct othm_list *othm_thread_controller_new(struct othm_list *first, ...) { va_list argp; struct othm_list *list; struct othm_list *head; struct othm_list *tail; if (first == 0) return 0; list = first; head = malloc(sizeof(struct othm_list)); tail = head; __builtin_va_start((argp)); do { tail->here = list; } while ((list = __builtin_va_arg((argp))) ? (tail->next = malloc(sizeof(struct othm_list)), tail = tail->next, 1) : 0); tail->next = 0; ; return head; } void othm_thread_start(struct othm_thread *thread) { thread->rc = pthread_create(&thread->thread, 0, othm_thread_run, (void *) thread); }
1
#include <pthread.h> char quit[] = ":quit"; char nomore[] = "No more connection // MAX 10\\n"; char greet0[] = "------------------------------------------------------------------\\n"; char greet1[] = "------------------- Welcome to CSRC chat server ------------------\\n"; char greet2[] = "------------------------------------------------------------------\\n"; int list_c[MAX_CLIENT]; pthread_t thread; pthread_t login_thread; pthread_mutex_t mutex; void *do_chat(void *); int run_n_server() { int c_socket, s_socket; struct sockaddr_in s_addr, c_addr; unsigned int len; unsigned int res; int n; int pid; char rcvBuffer[1000]; if(pthread_mutex_init(&mutex, 0) != 0) { printf("Cannot create mutex\\n"); return -1; } if ((s_socket = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("Could not create socket"); } puts("Socket Created!"); bzero((char*) &s_addr, sizeof(s_addr)); s_addr.sin_addr.s_addr = htonl(INADDR_ANY); s_addr.sin_family = AF_INET; s_addr.sin_port = htons(PORT); if(bind(s_socket, (struct sockaddr *) &s_addr, sizeof(s_addr)) < 0) { printf("Can't Bind\\n"); return -1; } puts("Bind Done!!"); if(listen(s_socket, 1) < 0) { printf("Listen Fail\\n"); return -1; } for(int i = 0; i < MAX_CLIENT; i++) { list_c[i] = -1; } puts("Waiting for incoming connections..."); while(1) { len = sizeof(c_addr); c_socket = accept(s_socket, (struct sockaddr *) &c_addr, &len); write(c_socket, greet0, strlen(greet0)); write(c_socket, greet1, strlen(greet1)); write(c_socket, greet2, strlen(greet2)); res = pushClient(c_socket); if(res < 0) { write(c_socket, nomore, strlen(nomore)); close(c_socket); } else { if(pthread_create(&thread, 0, do_chat, (void *) c_socket) < 0) { perror("pthread create error!!!!!\\n"); exit(1); } } } } void * do_chat(void *arg) { int c_socket = (int) arg; char chatData[1024]; int n; while(1) { memset(chatData, 0, sizeof(chatData)); if((n = read(c_socket, chatData, sizeof(chatData))) > 0) { for(int i = 0; i < MAX_CLIENT; i++) { if(strstr(chatData, quit) != 0) { popClient(c_socket); break; } if(list_c[i] != -1 && list_c[i] != c_socket) { write(list_c[i], chatData, n); } } } } } int pushClient(int c_socket) { int i; for (i = 0; i < MAX_CLIENT; i++) { pthread_mutex_lock(&mutex); if(list_c[i] == -1) { list_c[i] = c_socket; pthread_mutex_unlock(&mutex); return i; } pthread_mutex_unlock(&mutex); } if(i == MAX_CLIENT) return -1; } int popClient(int s) { close(s); for(int i = 0; i < MAX_CLIENT; i++) { pthread_mutex_lock(&mutex); if(s == list_c[i]) { list_c[i] = -1; pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> pthread_t tabla_hilos[8]; int suma=0; pthread_mutex_t mutex; int id; char *cadena; }hilos_param; int id; char *cadena; }orden; orden posiciones [8]; hilos_param parametros [8]; void *funcion_coches(hilos_param *p){ int aleatorio; printf(" Salida %s %d \\n", p->cadena,p->id); fflush (stdout); aleatorio=rand(); pthread_mutex_lock(&mutex); suma=suma+aleatorio; pthread_mutex_unlock(&mutex); sleep(1 + (aleatorio%4)); printf("Llegada %s %d \\n",p->cadena,p->id); pthread_exit(&suma); } int main (){ int i, *res; printf("Inicio proceso de creacion de los hilos ....\\n"); for(i=0;i<8;i++){ parametros[i].id=i; parametros[i].cadena="coche"; if(pthread_create(&tabla_hilos[i],0,(void *)&funcion_coches,(void *)&parametros[i])==0){ printf("Hilo creado correctamente hilo %d \\n",i); }else{ printf("Error en crear el hilo \\n"); } } printf("Proceso de creacion de hilos terminado\\n"); printf("Salida de coches\\n"); pthread_mutex_init(&mutex,0); for(i=0;i<8;i++){ pthread_join(tabla_hilos[i],(void **)(&res)); } pthread_mutex_destroy(&mutex); printf("Todos los coches han LLegado a la Meta, el valor aleatorio: %d \\n",*res); return 0; }
1
#include <pthread.h> pthread_mutex_t usertable_mutex = PTHREAD_MUTEX_INITIALIZER; void send_response (const int, const char *); void server_doit (struct connection_info *c) { ssize_t s; int error; char cmd; int i; char hbuf[NI_MAXHOST]; char sbuf[NI_MAXSERV]; char rbuf[MAXBUFLEN]; void doit_post (const int, const char *, const char *); void doit_retrieve (const int); error = getnameinfo ((struct sockaddr *) &c->from, c->fromlen, hbuf, sizeof (hbuf), sbuf, sizeof (sbuf), NI_NUMERICHOST | NI_NUMERICSERV); if (error) { fprintf (stderr, "doit (): %s\\n", gai_strerror (error)); close (c->fd); return; } send_response (c->fd, RESPONSE_HELLO); printf ("*** %s connected\\n", hbuf); memset (rbuf, 0, MAXBUFLEN); while ((s = read (c->fd, rbuf, MAXBUFLEN)) > 0) { sanitize (rbuf, s); cmd = rbuf[0]; for (i = 1; isspace (rbuf[i]); i++) { if (rbuf[i] == '\\0') break; } switch (cmd) { case 'P': doit_post (c->fd, hbuf, &rbuf[i]); break; case 'R': doit_retrieve (c->fd); break; case 'Q': printf ("*** %s quits\\n", hbuf); send_response (c->fd, RESPONSE_BYE); close (c->fd); return; default: printf ("*** %s unknown command %c\\n", hbuf, cmd); break; } memset (rbuf, 0, MAXBUFLEN); } close (c->fd); printf ("*** %s is gone\\n", hbuf); } struct msg_item { char poster_name[128]; time_t time; char host[NI_MAXHOST]; char msg[(MAXBUFLEN)]; } msg_table[100]; unsigned int msg_head = 0; pthread_mutex_t msg_table_mutex = PTHREAD_MUTEX_INITIALIZER; void doit_post (const int fd, const char hbuf[], const char *rbuf) { time_t t; int s; char buf[(MAXBUFLEN)]; send_response (fd, RESPONSE_POST_GOAHEAD); s = read (fd, buf, (MAXBUFLEN)); sanitize (buf, s); time (&t); pthread_mutex_lock (&msg_table_mutex); { msg_table[msg_head].time = t; strncpy (msg_table[msg_head].host, hbuf, NI_MAXHOST); strncpy (msg_table[msg_head].poster_name, rbuf, 128); strncpy (msg_table[msg_head].msg, buf, (MAXBUFLEN)); printf ("*** %s @ %s posted new message at %s", msg_table[msg_head].poster_name, msg_table[msg_head].host, ctime (&msg_table[msg_head].time)); printf ("%s\\n", msg_table[msg_head].msg); ++msg_head; msg_head %= 100; } pthread_mutex_unlock (&msg_table_mutex); send_response (fd, RESPONSE_POST_OK); } void doit_retrieve (const int fd) { unsigned int i; send_response (fd, RESPONSE_MESSAGE_FOLLOWS); pthread_mutex_lock (&msg_table_mutex); { char *s; unsigned int n; char buf[MAXBUFLEN]; i = msg_head; n = 1; do { if (msg_table[i].host[0] != '\\0') { sprintf (buf, "Message %d\\r\\n", n++); write (fd, buf, strlen (buf)); write (fd, msg_table[i].poster_name, strlen (msg_table[i].poster_name)); write (fd, "\\r\\n", 2); write (fd, msg_table[i].host, strlen (msg_table[i].host)); write (fd, "\\r\\n", 2); s = ctime (&msg_table[i].time); write (fd, s, strlen (s) - 1); write (fd, "\\r\\n", 2); write (fd, msg_table[i].msg, strlen (msg_table[i].msg)); write (fd, "\\r\\n", 2); } ++i; i %= 100; } while (i != msg_head); send_response (fd, RESPONSE_MESSAGE_ENDS); } pthread_mutex_unlock (&msg_table_mutex); } void send_response (const int fd, const char *s) { write (fd, s, strlen (s) + 1); }
0
#include <pthread.h>extern void __VERIFIER_error() ; unsigned int __VERIFIER_nondet_uint(); static int top=0; static unsigned int arr[(5)]; pthread_mutex_t m; _Bool flag=(0); void error(void) { ERROR: __VERIFIER_error(); return; } void inc_top(void) { top++; } void dec_top(void) { top--; } int get_top(void) { return top; } int stack_empty(void) { (top==0) ? (1) : (0); } int push(unsigned int *stack, int x) { if (top==(5)) { printf("stack overflow\\n"); return (-1); } else { stack[get_top()] = x; inc_top(); } return 0; } int pop(unsigned int *stack) { if (get_top()==0) { printf("stack underflow\\n"); return (-2); } else { dec_top(); return stack[get_top()]; } return 0; } void *t1(void *arg) { int i; unsigned int tmp; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); tmp = __VERIFIER_nondet_uint()%(5); if (push(arr,tmp)==(-1)) error(); flag=(1); pthread_mutex_unlock(&m); } } void *t2(void *arg) { int i; for( i=0; i<(5); i++) { pthread_mutex_lock(&m); if (flag) { if (!(pop(arr)!=(-2))) error(); } pthread_mutex_unlock(&m); } } int main(void) { pthread_t id1, id2; pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, 0); pthread_create(&id2, 0, t2, 0); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> pthread_mutex_t mutex; int *comm_fd; void *accept_client_co(void *communication_fd); int stream_socket(int port); void sig_handler(int sig); void sig_handler(int sig) { switch(sig){ case SIGINT: free(comm_fd); printf("Server was stopped by user action.\\n" ); exit(0); break; case SIGTERM: free(comm_fd); printf("Server was stopped by terminal signal.\\n" ); exit(0); break; default: perror("Unknown signal"); break; } } int stream_socket(int port){ struct sigaction sa; pthread_t thread; int socket_fd; int optval = 1, thread_err; struct sockaddr_in servaddr; comm_fd = (int *)malloc(sizeof(int)); if(comm_fd == 0) fprintf(stderr, "Couldn't allocate memory for thread argument\\n"); sigemptyset(&sa.sa_mask); sa.sa_handler = &sig_handler; sa.sa_flags = 0; if (sigaction(SIGINT, &sa, 0) == -1) { perror("9"); } if (sigaction(SIGTERM, &sa, 0) == -1) { perror("9"); } socket_fd = socket(AF_INET, SOCK_STREAM, 0); if(socket_fd == -1) return 1; if(setsockopt(socket_fd , SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)) == -1) return 6; bzero( &servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(port); if(bind(socket_fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) == -1) return 2; if(listen(socket_fd, 4) == -1) return 3; pthread_mutex_init(&mutex, 0); while(1) { *comm_fd = accept(socket_fd, (struct sockaddr*) 0, 0); thread_err = pthread_create(&thread, 0, accept_client_co, (void **)comm_fd); if(thread_err != 0) return 7; } free(comm_fd); return 0; } void *accept_client_co(void *communication_fd){ int comm_fd; int msg_size; char str[100]; comm_fd = *((int*)communication_fd); pthread_mutex_lock (&mutex); while( (msg_size = recv(comm_fd, str, 100, 0)) != 0){ printf("Server received %d bytes: %s\\n", msg_size, str); printf("Echoing back: %s\\n", str); write(comm_fd, str, strlen(str)+1); bzero( str, 100); pthread_mutex_unlock (&mutex); } pthread_exit(0); } int main(int argc, char const *argv[]) { int port; int err; if(argc != 2){ fprintf(stderr, "Usage: %s [port] \\n", argv[0]); exit(1); }else if( (port = atoi(argv[1])) == 0){ fprintf(stderr, "Please enter a valid port number \\n"); exit(1); } err = stream_socket(port); if(err == 1) fprintf(stderr, "Server failed to create a socket \\n"); else if(err == 2) fprintf(stderr, "Bind failed \\n"); else if(err == 3) fprintf(stderr, "Server failed to set up the queue \\n"); else if(err == 4) fprintf(stderr, "Server failed to read from socket \\n"); else if(err == 5) fprintf(stderr, "Server failed to write to socket \\n"); else if(err != 0) fprintf(stderr, "Server accidentally quit \\n"); return 0; }
0
#include <pthread.h> int count = 0; pthread_mutex_t count_mutex; pthread_cond_t count_threshold_cv; void * inc_count (void* arg) { count++; pthread_mutex_lock (&count_mutex); pthread_mutex_unlock (&count_mutex); return 0; } void * watch_count (void *idp) { pthread_mutex_lock (&count_mutex); pthread_mutex_unlock (&count_mutex); count++; return 0; } int main (int argc, char *argv[]) { int i; pthread_t a,b; pthread_mutex_init (&count_mutex, 0); pthread_cond_init (&count_threshold_cv, 0); pthread_create (&a, 0, watch_count, 0); pthread_create (&b, 0, inc_count, 0); pthread_join (a, 0); pthread_join (b, 0); pthread_mutex_destroy (&count_mutex); return 0; }
1
#include <pthread.h> void *Enqueuer(); void *Dequeuer(); unsigned int readIndex = 0; unsigned int writeIndex = 0; char dataBuffer[2][20]; pthread_cond_t bufferNotFull=PTHREAD_COND_INITIALIZER; pthread_cond_t bufferNotEmpty=PTHREAD_COND_INITIALIZER; pthread_mutex_t mutexLock=PTHREAD_MUTEX_INITIALIZER; int sockfd; int portno; int clientlen; struct sockaddr_in serveraddr; struct sockaddr_in clientaddr; struct hostent *hostp; char *hostaddrp; int optval; int n; void error(char *msg) { perror(msg); exit(1); } void *Enqueuer() { while(1) { printf("Enqueuer entered \\n"); pthread_mutex_lock(&mutexLock); printf("Enqueuer acquired lock\\n"); if(abs(writeIndex - readIndex) == 2) { printf("Waiting for buffer not to be full\\n"); writeIndex %= 2; pthread_cond_wait(&bufferNotFull,&mutexLock); } memset(dataBuffer[writeIndex],0,20); n = recvfrom(sockfd, dataBuffer[writeIndex], 20, 0, (struct sockaddr *) &clientaddr, &clientlen); if (n < 0) error("ERROR in recvfrom"); printf("Received datagram \\t %s \\n", dataBuffer[writeIndex]); printf("Written index : %u \\n",writeIndex); writeIndex = (writeIndex + 1); pthread_mutex_unlock(&mutexLock); printf("Enqueuer released teh lock \\n"); pthread_cond_signal(&bufferNotEmpty); } } void *Dequeuer() { while(1) { printf("\\n Dequeuer entered"); pthread_mutex_lock(&mutexLock); printf("\\n Dequeuer acquired lock"); if(readIndex == writeIndex) { pthread_cond_wait(&bufferNotEmpty,&mutexLock); } printf("Dequeuer::Sendto is going to be called. \\n"); n = sendto(sockfd, dataBuffer, strlen(dataBuffer[readIndex]), 0, (struct sockaddr *) &clientaddr, clientlen); printf("\\n Send to result is %d ", n); if (n < 0) error("ERROR in sendto"); printf("Consume : %d \\n",readIndex); readIndex = (readIndex + 1) % 2; pthread_mutex_unlock(&mutexLock); pthread_cond_signal(&bufferNotFull); } } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s <port>\\n", argv[0]); exit(1); } portno = atoi(argv[1]); sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd < 0) error("ERROR opening socket"); optval = 1; setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const void *)&optval , sizeof(int)); bzero((char *) &serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons((unsigned short)portno); if (bind(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0) error("ERROR on binding"); clientlen = sizeof(clientaddr); pthread_t ptid,ctid; pthread_create(&ptid,0,Enqueuer,0); pthread_create(&ctid,0,Dequeuer,0); pthread_join(ptid,0); pthread_join(ctid,0); return 0; }
0
#include <pthread.h> static int error(int cod,const char*const msg) { if (cod<0) { perror(msg); exit(1); } return cod; } { pthread_mutex_t guard; volatile unsigned val; } Shared; Shared theShared; static void* increment(void* data) { unsigned long count=(1ul<<20); while(count--) { pthread_mutex_lock(&theShared.guard); ++theShared.val; pthread_mutex_unlock(&theShared.guard); } } static void* decrement(void *data) { Shared* shared=(Shared*)data; unsigned long count=(1ul<<20); while(count--) { pthread_mutex_lock(&theShared.guard); --theShared.val; pthread_mutex_unlock(&theShared.guard); } } static void result() { printf("theShared->val=%d\\n",theShared.val); } static void sequentially() { increment(0); decrement(0); } static void concurrent() { pthread_t inc; pthread_t dec; error(pthread_create(&inc, 0, increment, 0), "inc" ); error(pthread_create(&dec, 0, decrement, 0), "dec" ); pthread_join(inc,0); pthread_join(dec,0); } int main(int argc,char** args) { theShared.val=0; concurrent(); result(); return 0; }
1
#include <pthread.h> int indice_philo; int nbr_portion; }philo_t; pthread_cond_t cond; philo_t *philo; struct file_baguette *next; }file_baguette_t; void prendre_baguettes(philo_t *p); void poser_baguettes(int i); int manger(int i); void wait_in_fifo(int i, philo_t *p); void sortir_fifo(int i); void signaler_fifo(int i); void *philosophe(void *arg); int baguette_dispo[5]; pthread_mutex_t mutex; file_baguette_t **fifo_baguettes; void prendre_baguettes(philo_t *p){ int i = p->indice_philo; pthread_mutex_lock(&mutex); while(!baguette_dispo[i] || !baguette_dispo[(i+1)%5]){ if(!baguette_dispo[i]){ wait_in_fifo(i,p); } else if(!baguette_dispo[(i+1)%5]){ wait_in_fifo((i+1)%5, p); } else if(!baguette_dispo[i] && !baguette_dispo[(i+1)%5]){ wait_in_fifo(i, p); wait_in_fifo((i+1)%5, p); } } baguette_dispo[i] = 0; baguette_dispo[(i+1)%5] = 0; sortir_fifo(i); sortir_fifo((i+1)%5); pthread_mutex_unlock(&mutex); } void poser_baguettes(int i){ pthread_mutex_lock(&mutex); baguette_dispo[i] = 1; baguette_dispo[(i+1)%5] = 1; signaler_fifo(i); signaler_fifo((i+1)%5); pthread_mutex_unlock(&mutex); } int manger(int i){ return i = i - 1; } void wait_in_fifo(int i, philo_t *p){ if(fifo_baguettes[i] == 0){ fifo_baguettes[i] = malloc(sizeof(file_baguette_t)); file_baguette_t *tete = fifo_baguettes[i]; if(pthread_cond_init(&(tete->cond), 0) != 0){ fprintf(stderr, "Cond init error\\n"); exit(5); } tete->philo = p; tete->next = 0; pthread_cond_wait(&(tete->cond), &mutex); }else{ int existe = 0; file_baguette_t *courant = fifo_baguettes[i]; while(courant->next != 0){ if(courant->philo == p) existe = 1; courant = courant->next; } if(!existe){ if(fifo_baguettes[i]->next == 0){ fifo_baguettes[i]->next = malloc(sizeof(file_baguette_t)); file_baguette_t *next = fifo_baguettes[i]->next; if(pthread_cond_init(&(next->cond), 0) != 0){ fprintf(stderr, "Cond init error\\n"); exit(5); } next->philo = p; next->next = 0; pthread_cond_wait(&(next->cond), &mutex); } } } } void sortir_fifo(int i){ if(fifo_baguettes[i] != 0){ if(fifo_baguettes[i]->next != 0){ fifo_baguettes[i] = fifo_baguettes[i]->next; }else{ fifo_baguettes[i] = 0; } } } void signaler_fifo(int i){ if(fifo_baguettes[i] != 0){ pthread_cond_signal(&(fifo_baguettes[i]->cond)); } } void *philosophe(void *arg){ philo_t *p = (philo_t *)arg; pthread_t tid; tid = pthread_self(); while(p->nbr_portion){ srand ((int) tid) ; usleep (rand() / 32767 * 1000000.); prendre_baguettes(p); printf("philospophe %d mange\\n", p->indice_philo); p->nbr_portion = manger(p->nbr_portion); poser_baguettes(p->indice_philo); } printf("Thread %x indice %d a FINI !\\n", (unsigned int)tid, p->indice_philo); return (void *) tid; } int main(int argc, char const *argv[]){ philo_t *philos; if(pthread_mutex_init(&mutex,0) != 0){ fprintf(stderr, "Mutex init error\\n"); exit(1); } fifo_baguettes = malloc(sizeof(file_baguette_t *)*5); if(fifo_baguettes == 0){ fprintf(stderr, "fifo_baguettes error\\n"); exit(2); } for(int i=0; i<5; i++){ baguette_dispo[i] = 1; } pthread_t *tids ; tids = malloc(sizeof(pthread_t)*5); if(tids == 0){ fprintf(stderr, "Malloc pthread_t error\\n"); exit(3); } philos = malloc(sizeof(philo_t)*5); if (philos == 0){ fprintf(stderr, "Malloc philo_t error\\n"); exit(4); } for(int i = 0 ;i <5 ;i++){ philos[i].indice_philo = i; philos[i].nbr_portion = 10; pthread_create(&tids[i],0,philosophe,&philos[i]); } for(int j = 0;j <5 ; j++){ pthread_join(tids[j],0); } free(tids); free(fifo_baguettes); return 0; }
0
#include <pthread.h> const int size = 1000; unsigned char *image; int yc = 0; pthread_mutex_t lock_yc = PTHREAD_MUTEX_INITIALIZER; static void calcul(int x, int y, unsigned char *pixel) { long double p_x = (long double)x/size * 2.0l - 1.0l; long double p_y = (long double)y/size * 2.0l - 1.0l; long double tz = 0.7; long double zoo = powl(0.5l, 13.0l * tz); long double cc_x = -0.05l + p_x * zoo; long double cc_y = 0.6805l + p_y * zoo; long double z_x = 0.0l; long double z_y = 0.0l; long double m2 = 0.0l; long double co = 0.0l; long double dz_x = 0.0l; long double dz_y = 0.0l; int i; for (i = 0; i < 2560; i++) { long double old_dz_x, old_z_x; if (m2 > 1024.0l) continue; old_dz_x = dz_x; dz_x = 2.0l * z_x * dz_x - z_y * dz_y + 1.0l; dz_y = 2.0l * z_x * dz_y + z_y * old_dz_x; old_z_x = z_x; z_x = cc_x + z_x * z_x - z_y * z_y; z_y = cc_y + 2.0l * old_z_x * z_y; m2 = z_x * z_x + z_y * z_y; co += 1.0l; } long double d = 0.0l; if (co < 2560.0l) { long double dot_z = z_x * z_x + z_y * z_y; d = sqrtl(dot_z/(dz_x*dz_x+dz_y*dz_y)) * logl(dot_z); pixel[0] = fmodl(co,256.0l); d = 4.0l * d / zoo; if (d < 0.0l) d = 0.0l; if (d > 1.0l) d = 1.0l; pixel[1] = fmodl((1.0l-d) * 255.0l * 300.0l, 255.0l); d = powl(d, 50.0l*0.25l); pixel[2] = d * 255.0l; } else pixel[0]=pixel[1]=pixel[2]=0; } void* parallel() { int x,y; while(1) { pthread_mutex_lock(&lock_yc); if(yc>=size) { pthread_mutex_unlock(&lock_yc); pthread_exit(0); } y = yc; yc=yc+1; pthread_mutex_unlock(&lock_yc); for (x = 0; x < size; x++) calcul(x, y, image+3*(y * size + x)); } } int main(int argc, char const *argv[]) { if(argc < 2) return 0; FILE *file; image = malloc(3*size*size); int N=1; sscanf(argv[1],"%d",&N); pthread_t *thread = malloc(N*sizeof(pthread_t)); int n = 0; while(n<N) { pthread_create(thread+n,0,parallel,0); n++; } n = 0; while(n<N) { pthread_join(*(thread+n),0); n++; } file = fopen("image.ppm", "w"); fprintf(file, "P6\\n%d %d\\n255\\n", size, size); fwrite(image, size, size * 3, file); fclose(file); free(image); return 0; }
1
#include <pthread.h> static void main_loop (int rpipe, int wpipe, struct listen_info * info) { while (1) { int fd; int priority; char * message; int result = receive_pipe_message_any (50, &message, &fd, &priority); if (result != 0) { snprintf (log_buf, LOG_SIZE, "receive_pipe_message_any returns %d\\n", result); log_print (); } if (result < 0) { if (fd == rpipe) { snprintf (log_buf, LOG_SIZE, "ad pipe %d closed\\n", rpipe); log_print (); break; } snprintf (log_buf, LOG_SIZE, "error on file descriptor %d, closing\\n", fd); log_print (); listen_remove_fd (info, fd); close (fd); } else if (result > 0) { snprintf (log_buf, LOG_SIZE, "got %d bytes from %s (fd %d, priority %d)\\n", result, (fd == rpipe) ? "ad" : "client", fd, priority); log_print (); int i; pthread_mutex_lock (&(info->mutex)); if (fd != rpipe) listen_record_usage (info, fd); for (i = 0; i < info->num_fds; i++) { int xfd = info->fds [i]; int same = (fd == xfd); if (xfd == rpipe) xfd = wpipe; same = (same || (fd == xfd)); if (! same) { if (! send_pipe_message (xfd, message, result, priority)) { snprintf (log_buf, LOG_SIZE, "error sending to info pipe %d/%d at %d\\n", info->fds [i], xfd, i); log_print (); } else { } } else { } } pthread_mutex_unlock (&(info->mutex)); free (message); } } } void alocal_main (int rpipe, int wpipe) { init_log ("alocal"); snprintf (log_buf, LOG_SIZE, "in main\\n"); log_print (); struct listen_info info; snprintf (log_buf, LOG_SIZE, "calling listen_init_info\\n"); log_print (); listen_init_info (&info, 256, "alocal", ALLNET_LOCAL_PORT, 1, 1, 1, 0); snprintf (log_buf, LOG_SIZE, "calling listen_add_fd\\n"); log_print (); listen_add_fd (&info, rpipe, 0); snprintf (log_buf, LOG_SIZE, "calling main loop\\n"); log_print (); main_loop (rpipe, wpipe, &info); pthread_cancel (info.thread4); pthread_cancel (info.thread6); snprintf (log_buf, LOG_SIZE, "end of alocal main thread\\n"); log_print (); }
0
#include <pthread.h> int idx=0; int ctr1=1, ctr2=0; int readerprogress1=0, readerprogress2=0; pthread_mutex_t mutex; void __VERIFIER_atomic_use1(int myidx) { __VERIFIER_assume(myidx <= 0 && ctr1>0); ctr1++; } void __VERIFIER_atomic_use2(int myidx) { __VERIFIER_assume(myidx >= 1 && ctr2>0); ctr2++; } void __VERIFIER_atomic_use_done(int myidx) { if (myidx <= 0) { ctr1--; } else { ctr2--; } } void __VERIFIER_atomic_take_snapshot(int readerstart1, int readerstart2) { readerstart1 = readerprogress1; readerstart2 = readerprogress2; } void __VERIFIER_atomic_check_progress1(int readerstart1) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1); if (!(0)) ERROR: __VERIFIER_error();; } return; } void __VERIFIER_atomic_check_progress2(int readerstart2) { if (__VERIFIER_nondet_int()) { __VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1); if (!(0)) ERROR: __VERIFIER_error();; } return; } void *qrcu_reader1(void* arg) { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress1 = 1; readerprogress1 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void *qrcu_reader2(void* arg) { int myidx; while (1) { myidx = idx; if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use1(myidx); break; } else { if (__VERIFIER_nondet_int()) { __VERIFIER_atomic_use2(myidx); break; } else {} } } readerprogress2 = 1; readerprogress2 = 2; __VERIFIER_atomic_use_done(myidx); return 0; } void* qrcu_updater(void* arg) { int i; int readerstart1=__VERIFIER_nondet_int(), readerstart2=__VERIFIER_nondet_int(); int sum; __VERIFIER_atomic_take_snapshot(readerstart1, readerstart2); if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; } else {} if (sum > 1) { pthread_mutex_lock(&mutex); if (idx <= 0) { ctr2++; idx = 1; ctr1--; } else { ctr1++; idx = 0; ctr2--; } if (idx <= 0) { while (ctr1 > 0); } else { while (ctr2 > 0); } pthread_mutex_unlock(&mutex); } else {} __VERIFIER_atomic_check_progress1(readerstart1); __VERIFIER_atomic_check_progress2(readerstart2); return 0; } int main() { pthread_t t1, t2, t3; pthread_mutex_init(&mutex, 0); pthread_create(&t1, 0, qrcu_reader1, 0); pthread_create(&t2, 0, qrcu_reader2, 0); pthread_create(&t3, 0, qrcu_updater, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_join(t3, 0); pthread_mutex_destroy(&mutex); return 0; }
1
#include <pthread.h> static pthread_mutex_t send_nl_mutex; int GetNetLinkInterface(int prototype,int group,int pid) { struct sockaddr_nl sock_addr; int sockfd; sockfd = socket(AF_NETLINK, SOCK_RAW, prototype); if(sockfd == -1){ printf("socket create error\\n"); return -1; } memset(&sock_addr,0,sizeof(struct sockaddr_nl)); sock_addr.nl_family = AF_NETLINK; sock_addr.nl_groups = group; sock_addr.nl_pid = pid; if(bind(sockfd, (struct sockaddr *)&sock_addr,sizeof(sock_addr)) < 0){ printf("%d netlink client bind error !!!!\\n",prototype); return -1; } if(pthread_mutex_init(&send_nl_mutex,0)){ printf("send_nl_mutex error\\n"); close(sockfd); return -1; } DBG_MSG(BASIC_MSG_LEVEL,"GetNetLinkInterface : protocol type (%d), PID (%d)\\n",prototype,pid); return sockfd; } int RecvNetLinkData(int sockfd,int length,int pid, unsigned char *buffer) { struct sockaddr_nl nladdr; struct msghdr msg; struct iovec iov; struct nlmsghdr *nlh=0; int ret; nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(length)); memset(nlh, 0, NLMSG_SPACE(length)); nlh->nlmsg_len = NLMSG_LENGTH(0); nlh->nlmsg_pid = pid; nlh->nlmsg_flags = 0; memset(&nladdr, 0, sizeof(nladdr)); nladdr.nl_family = AF_NETLINK; nladdr.nl_pid = 0; nladdr.nl_groups = 0; iov.iov_base = (void *)nlh; iov.iov_len = length; msg.msg_name = (void *)&(nladdr); msg.msg_namelen = sizeof(nladdr); msg.msg_iov = &iov; msg.msg_iovlen = 1; ret=recvmsg(sockfd, &msg, 0); if (ret<=0) { free(nlh); return 0; } ret -= NLMSG_LENGTH(0); memcpy(buffer,NLMSG_DATA(nlh),ret); free(nlh); return ret; } int SendNetLinkData(int sockfd,int length,int pid, unsigned char *buffer) { struct sockaddr_nl sAddr; struct nlmsghdr *nlh = 0; struct msghdr msg; struct iovec iov; int retval; pthread_mutex_lock(&send_nl_mutex); memset(&sAddr, 0, sizeof(struct sockaddr_nl)); sAddr.nl_family = AF_NETLINK; sAddr.nl_pid = 0; sAddr.nl_groups = 0; nlh = (struct nlmsghdr *)malloc(NLMSG_SPACE(length)); memset(nlh, 0, NLMSG_SPACE(length)); nlh->nlmsg_len = NLMSG_LENGTH(0); nlh->nlmsg_pid = pid; nlh->nlmsg_flags = 0; memcpy(NLMSG_DATA(nlh),buffer,length); iov.iov_base = (void *)nlh; iov.iov_len = nlh->nlmsg_len; msg.msg_name = &sAddr; msg.msg_namelen = sizeof(sAddr); msg.msg_iov = &iov; msg.msg_iovlen = 1; retval = send(sockfd, nlh, (nlh->nlmsg_len+length), 0); free(nlh); pthread_mutex_unlock(&send_nl_mutex); return retval; }
0
#include <pthread.h> int thread_flag; pthread_cond_t thread_flag_cv; pthread_mutex_t thread_flag_mutex; void wait_n_secs(int seconds, unsigned char show_output) { int i; for (i = 1; i <= seconds; ++i) { usleep(1000000); if (show_output) printf("Second %d\\n", i); } } void do_work() { static int counter = 0; printf("do_work() counting %d\\n", counter); ++counter; usleep(1000000/3); } void initialize_flag() { pthread_mutex_init(&thread_flag_mutex, 0); pthread_cond_init(&thread_flag_cv, 0); thread_flag = 0; } void* thread_function(void* thread_arg) { while (1) { pthread_mutex_lock(&thread_flag_mutex); while (!thread_flag) pthread_cond_wait(&thread_flag_cv, &thread_flag_mutex); pthread_mutex_unlock(&thread_flag_mutex); do_work(); } return 0; } void set_thread_flag(int flag_value) { pthread_mutex_lock(&thread_flag_mutex); thread_flag = flag_value; pthread_cond_signal(&thread_flag_cv); pthread_mutex_unlock(&thread_flag_mutex); } int main(int argc, char** argv) { pthread_t thread1, thread2; initialize_flag(); printf("Creating new thread\\n"); pthread_create(&thread1, 0, thread_function, 0); printf("New thread created\\n"); printf("Wait 5 seconds\\n"); wait_n_secs(5, 1); printf("Now a new thread will run with output\\n" "Press Enter to block the thread\\n"); set_thread_flag(1); getchar(); set_thread_flag(0); printf("Thread is blocked, so now we will " "cancel it to exit the program\\n"); pthread_cancel(thread1); return 0; }
1
#include <pthread.h> static int globalVar = 0; static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* threadFunction(void* arg){ int local = 0; int x; for(x = 0; x < 100000000; x++){ pthread_mutex_lock(&mutex); local = globalVar; local++; globalVar = local; pthread_mutex_unlock(&mutex); } return 0; } int main(int argc, char** argv){ pthread_t t1, t2; pthread_create(&t1, 0, threadFunction, 0); pthread_create(&t2, 0, threadFunction, 0); pthread_join(t1, 0); pthread_join(t2, 0); printf("Global is: %d", globalVar); return 0; }
0
#include <pthread.h> int array[4]; int array_index = 0; pthread_mutex_t mutex; void *thread(void * arg) { pthread_mutex_lock(&mutex); array[array_index] = 1; pthread_mutex_unlock(&mutex); return 0; } void *main_continuation (void *arg); pthread_t t[4]; int main() { int i; pthread_t t[4]; pthread_mutex_init(&mutex, 0); i = 0; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); array_index++; pthread_mutex_unlock(&mutex); i++; pthread_create(&t[i], 0, thread, 0); pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex); i++; __VERIFIER_assert (i == 4); __VERIFIER_assert (array_index < 4); pthread_t tt; pthread_create(&tt, 0, main_continuation, 0); pthread_join (tt, 0); return 0; } void *main_continuation (void *arg) { int i, sum; i = 0; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; pthread_join (t[i], 0); i++; __VERIFIER_assert (i == 4); sum = 0; i = 0; sum += array[i]; i++; sum += array[i]; i++; sum += array[i]; i++; sum += array[i]; i++; __VERIFIER_assert (i == 4); printf ("m: sum %d SIGMA %d\\n", sum, 4); __VERIFIER_assert (sum <= 4); return 0; }
1
#include <pthread.h> pthread_mutex_t mut1; pthread_mutex_t mut2; void *t1_main(void *unused); void *t2_main(void *unused); void *t2_main(void *unused) { pthread_mutex_lock(&mut1); printf("t2 has mut2\\n"); pthread_mutex_lock(&mut2); printf("t2 has mut2\\n"); pthread_mutex_unlock(&mut2); printf("t2 released mut2\\n"); pthread_mutex_unlock(&mut1); printf("t2 released mut2\\n"); return 0; } void *t1_main(void *unused) { pthread_mutex_lock(&mut1); printf("t1 has mut1\\n"); pthread_mutex_lock(&mut2); printf("t1 has mut2\\n"); pthread_mutex_unlock(&mut2); printf("t1 released mut2\\n"); pthread_mutex_unlock(&mut1); printf("t1 released mut1\\n"); return 0; } int main(int argc, char *argv[]) { pthread_t t1; pthread_t t2; pthread_mutex_init(&mut1, 0); pthread_mutex_init(&mut2, 0); pthread_create(&t1, 0, t1_main, 0); pthread_create(&t2, 0, t2_main, 0); pthread_exit((void *) 0); }
0
#include <pthread.h> pthread_mutex_t mutex_tabaco = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_papel = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutex_fosforos = PTHREAD_MUTEX_INITIALIZER; void * agente(void * arg){ pthread_mutex_lock(&mutex_tabaco); pthread_mutex_lock(&mutex_papel); pthread_mutex_lock(&mutex_fosforos); int ing1, ing2; srand (time(0)); ing1 = rand() % 3 + 1; ing2 = rand() % 3 + 1; while(ing2==ing1){ ing2 = rand() % 3 + 1; } if(ing1 == 1 || ing2 == 1){ pthread_mutex_unlock(&mutex_tabaco); } if(ing1 == 2 || ing2 == 2){ pthread_mutex_unlock(&mutex_papel); } if(ing1 == 3 || ing2 == 3){ pthread_mutex_unlock(&mutex_papel); } } void * fumador(void * arg){ pthread_mutex_lock(&mutex_tabaco); while (pthread_mutex_trylock(&mutex_papel)) { pthread_mutex_unlock(&mutex_tabaco); pthread_mutex_lock(&mutex_tabaco); while (pthread_mutex_trylock(&mutex_papel)) { pthread_mutex_unlock(&mutex_fosforos); pthread_mutex_lock(&mutex_fosforos); } } printf("Enrollando y Fumando"); pthread_mutex_unlock(&mutex_fosforos); pthread_mutex_unlock(&mutex_papel); pthread_mutex_unlock(&mutex_tabaco); sleep(4); } int main(int argc, const char * argv[]) { pthread_t * tid; int nhilos; int i; nhilos = 4; tid = malloc(nhilos * sizeof(pthread_t)); printf("Creando hilos ...\\n"); pthread_create(tid, 0, fumador, (void *)0); pthread_create(tid+1, 0, fumador, (void *)1); pthread_create(tid+2, 0, fumador, (void *)2); pthread_create(tid+4, 0, agente, (void *)2); printf("Se crearon %d hilos ...\\n", nhilos); for (i = 0; i < nhilos; ++i) { pthread_join(*(tid+i), 0); printf("Se unió el hilo %d con TID = %d...\\n", i, *(tid+i)); } printf("Soy el proceso principal y ya terminaron todos los hilos...\\n"); free(tid); return 0; }
1
#include <pthread.h> void *TransmitThread(void *arg) { struct sigevent sig_event; struct timespec ts_period; sig_event.sigev_notify = SIGEV_UNBLOCK; ts_period.tv_sec = 0; ts_period.tv_nsec = TRANSMIT_WAIT_TIME*1000*1000; while (0 == *(int *)arg) { unsigned char buffer1[BUFFER_SIZE] = {0}; unsigned char dataLen1 = 0; unsigned char buffer2[BUFFER_SIZE] = {0}; unsigned char dataLen2 = 0; timer_timeout(CLOCK_REALTIME, _NTO_TIMEOUT_SEM, &sig_event, &ts_period, 0); if (0 == sem_wait(&globalVar.resourceSem)) { pthread_mutex_lock(&globalVar.dataMutex); GET_BTOTVAR(globalVar.bToTVar[0], buffer1, dataLen1); GET_BTOTVAR(globalVar.bToTVar[1], buffer2, dataLen2); pthread_mutex_unlock(&globalVar.dataMutex); } else { SET_ERROR(ERR_TRANSMIT_WAIT_TIMEOUT); } if (dataLen1 != 0 || dataLen2 != 0) { if (0 == sem_wait(&shareMemPtr->semMutex)) { SET_TTOCVAR(shareMemPtr->tToCVar[0], buffer1, dataLen1); SET_TTOCVAR(shareMemPtr->tToCVar[1], buffer2, dataLen2); shareMemPtr->errorSet &= 0; sem_post(&shareMemPtr->semMutex); SET_SEM(&shareMemPtr->resourceSem); CLR_ERROR(ERROR_MASK_TRANSMIT); } } else { if (0 == sem_wait(&shareMemPtr->semMutex)) { unsigned int errSet = 0; GET_ERROR(errSet); shareMemPtr->errorSet = errSet; sem_post(&shareMemPtr->semMutex); } } } shm_unlink(SHM_NAME); return 0; }
0
#include <pthread.h> pthread_mutex_t cadeados[NUM_CONTAS]; int contasSaldos[NUM_CONTAS]; int sinal = 0; int somaCreditos = 0; FILE *sim; int contaExiste(int idConta) { return (idConta > 0 && idConta <= NUM_CONTAS); } void inicializarContas() { int i; for (i=0; i<NUM_CONTAS; i++) contasSaldos[i] = 0; } int debitar(int idConta, int valor) { sleep(ATRASO); if (!contaExiste(idConta)) { return -1; } pthread_mutex_lock(&cadeados[idConta-1]); if (contasSaldos[idConta - 1] < valor) { pthread_mutex_unlock(&cadeados[idConta-1]); return -1; } sleep(ATRASO); contasSaldos[idConta - 1] -= valor; pthread_mutex_unlock(&cadeados[idConta-1]); return 0; } int creditar(int idConta, int valor) { sleep(ATRASO); if (!contaExiste(idConta)){ return -1; } pthread_mutex_lock(&cadeados[idConta-1]); contasSaldos[idConta - 1] += valor; somaCreditos += valor; pthread_mutex_unlock(&cadeados[idConta-1]); return 0; } int lerSaldo(int idConta) { sleep(ATRASO); if (!contaExiste(idConta)){ return -1; } pthread_mutex_lock(&cadeados[idConta-1]); int saldo = contasSaldos[idConta - 1]; pthread_mutex_unlock(&cadeados[idConta-1]); return saldo; } int transferir(int idorigem, int iddestino, int valor) { if (!contaExiste(idorigem) || (!contaExiste(iddestino))) return -1; if (contasSaldos[idorigem-1] < valor) return -1; pthread_mutex_lock(&cadeados[idorigem-1]); pthread_mutex_lock(&cadeados[iddestino-1]); contasSaldos[idorigem-1]-= valor; contasSaldos[iddestino-1] += valor; pthread_mutex_unlock(&cadeados[iddestino-1]); pthread_mutex_unlock(&cadeados[idorigem-1]); return 0; } int simular(int numAnos) { char filename[50]; sprintf(filename, "i-banco-sim-%d.txt", getpid()); sim = fopen(filename, "w"); if(numAnos<0) { fprintf(sim, "Numero de anos tem de ser maior ou igual a 0\\n"); return -1; } else { for(int i=0; i<=numAnos && sinal == 0; i++) { fprintf(sim, "SIMULACAO: Ano %d\\n", i); fprintf(sim, "=================\\n"); for(int k=1; k <= NUM_CONTAS; k++){ if(i==0) fprintf(sim, "Conta %d, Saldo %d\\n", k, lerSaldo(k)); else { creditar(k, lerSaldo(k)*(0.1)); debitar(k, 1); fprintf(sim, "Conta %d, Saldo %d\\n", k, lerSaldo(k)); } } } } if(fclose(sim) != 0){ perror("Erro ao fechar o ficheiro"); } return 1; } void tratamentosinal(int s) { sinal = 1; }
1
#include <pthread.h> void *thread0(void *); void *thread1(void *); pthread_t tid[4]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int main(int argc, char* argv[], char* envp[]) { int i = 0; int id[4]; id[0] = 0; pthread_create(&tid[0], 0, thread0, (void*)&id[0]); id[1] = 1; pthread_create(&tid[1], 0, thread1, (void*)&id[1]); sleep(2); pthread_cond_signal(&cond); for(i = 0; i < 2 ; i++){ pthread_join(tid[i], 0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } void *thread1(void *arg){ printf("mutex locks in threading number : %d\\n", *((int*)arg)); pthread_mutex_lock(&mutex); printf("in the critical section, threading number : %d\\n", *((int*)arg)); printf("threading number : 0 is now pthread_cond_wait\\n"); pthread_cond_wait(&cond, &mutex); printf("wake up from threading number : %d\\n", *((int*)arg)); printf("threading number : %d is now sleep..\\n", *((int*)arg)); sleep(5); printf("threading number : %d mutex unlock!\\n", *((int*)arg)); pthread_mutex_unlock(&mutex); } void *thread0(void *arg){ printf("mutex locks in threading number : %d\\n", *((int*)arg)); pthread_mutex_lock(&mutex); printf("in the critical section, threading number : %d\\n", *((int*)arg)); printf("threading number : 1 is now pthread_cond_wait\\n"); pthread_cond_wait(&cond, &mutex); printf("wake up from threading number : %d\\n", *((int*)arg)); printf("threading number : %d is now sleep..\\n", *((int*)arg)); sleep(5); printf("threading number : %d mutex unlock!\\n", *((int*)arg)); pthread_mutex_unlock(&mutex); }
0
#include <pthread.h> pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int num; void* thr_fn1(void* arg) { while (1) { pthread_mutex_lock(&mutex); num++; printf("thread1: num = %d\\n", num); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if (num >= 100) { pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); break; } else pthread_mutex_unlock(&mutex); } pthread_exit((void*)1); } void* thr_fn2(void* arg) { while (1) { pthread_mutex_lock(&mutex); num += 2; printf("thread2: num = %d\\n", num); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex); if (num >= 100) { pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); break; } else pthread_mutex_unlock(&mutex); } pthread_exit((void*)2); } void* thr_fn3(void* arg) { pthread_mutex_lock(&mutex); while (num < 100) pthread_cond_wait(&cond, &mutex); printf("ahaha, num = :%d\\n", num); pthread_mutex_unlock(&mutex); pthread_exit((void*)3); } int main() { int err; pthread_t tid1, tid2, tid3; void* tret; num = 0; err = pthread_create(&tid1, 0, thr_fn1, 0); if (err != 0) err_exit(err, "cant create thread 1."); err = pthread_create(&tid2, 0, thr_fn2, 0); if (err != 0) err_exit(err, "cant create thread 1."); err = pthread_create(&tid3, 0, thr_fn3, 0); if (err != 0) err_exit(err, "cant create thread 1."); sleep(2); printf("main thread: num = %d\\n", num); err = pthread_join(tid1, &tret); if (err != 0) err_exit(err, "main thread cant join thread 1."); printf("thread1 exit code: %d\\n", (int)tret); err = pthread_join(tid2, &tret); if (err != 0) err_exit(err, "main thread cant join thread 2."); printf("thread2 exit code: %d\\n", (int)tret); err = pthread_join(tid3, &tret); if (err != 0) err_exit(err, "main thread cant join thread 3."); printf("thread3 exit code: %d\\n", (int)tret); exit(0); }
1
#include <pthread.h> static int num = 0; static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER; struct arg{ int i; }; void cal(int i, void* p); static void* func(void *p); int main(int argc, const char *argv[]) { int err, i; pthread_t tid[4]; for (i = 0; i < 4; i++) { err = pthread_create(tid+i, 0, func, (void*)i); if (err) { fprintf(stderr, "pthread_create():%s\\n", strerror(err)); exit(1); } } for (i = 30000000; i <= 30000200; i++) { pthread_mutex_lock(&mut_num); while (num != 0) { pthread_cond_wait(&cond_num, &mut_num); } num = i; pthread_cond_signal(&cond_num); pthread_mutex_unlock(&mut_num); sleep(1); } pthread_mutex_lock(&mut_num); while (num != 0) { pthread_cond_wait(&cond_num, &mut_num); } num=-1; pthread_cond_broadcast(&cond_num); pthread_mutex_unlock(&mut_num); for (i = 0; i < 4; i++) { pthread_join(tid[i], 0); } pthread_mutex_destroy(&mut_num); pthread_cond_destroy(&cond_num); exit(0); } static void* func(void *p) { int i; while (1) { pthread_mutex_lock(&mut_num); while (num == 0) { pthread_cond_wait(&cond_num, &mut_num); } if (num == -1) { pthread_mutex_unlock(&mut_num); break; } i = num; num = 0; pthread_cond_broadcast(&cond_num); pthread_mutex_unlock(&mut_num); cal(i, p); } pthread_exit(0); } void cal(int i, void* p) { int j,mark; mark = 1; for(j = 2; j < i/2; j++) { if(i % j == 0) { mark = 0; break; } } if(mark) printf("[%d]%d is a primer.\\n",(int)p,i); }
0
#include <pthread.h> int ticketcount = 10; pthread_mutex_t mutex; pthread_cond_t cond; void *salewindow(void *args) { while(1){ pthread_mutex_lock(&mutex); if(ticketcount > 0){ printf("window %d start sale ticket! The ticket is : %d\\n", (int)args, ticketcount); ticketcount--; if(ticketcount == 0) pthread_cond_signal(&cond); printf("sale ticket finish! The last ticket is %d\\n", ticketcount); }else{ pthread_mutex_unlock(&mutex); break; } pthread_mutex_unlock(&mutex); sleep(1); } } void *setticket(void *args) { pthread_mutex_lock(&mutex); if(ticketcount > 0) pthread_cond_wait(&cond, &mutex); ticketcount = 10; pthread_mutex_unlock(&mutex); sleep(1); pthread_exit(0); } int main(void) { pthread_t pid1, pid2, pid3; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); pthread_create(&pid1, 0, salewindow, (void *)1); pthread_create(&pid2, 0, salewindow, (void *)2); pthread_create(&pid3, 0, setticket, 0); pthread_join(pid1, 0); pthread_join(pid2, 0); pthread_join(pid3, 0); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> int thread_count; double sum; clock_t starttime,endtime; pthread_mutex_t mutex; void* Thread_sum(void* rank); int main(int argc, char* argv[]) { starttime=clock(); long thread; pthread_t* thread_handles; double error; thread_count = strtol(argv[1], 0, 10); pthread_mutex_init(&mutex, 0); thread_handles = malloc (thread_count*sizeof(pthread_t)); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Thread_sum, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); pthread_mutex_destroy(&mutex); free(thread_handles); endtime=clock(); error = fabs((4*sum - 3.141592653589793238462643)/3.141592653589793238462643) * 100; printf("\\n Value of pi : %11.20e\\n", 4*sum); printf(" Maximum value of n: : %ld\\n",10000000000); printf(" Number of threads: : %d\\n", thread_count); printf(" Percentage Error : %11.10e\\n", error); printf(" Total time taken : %11.10e\\n\\n", (double)(endtime-starttime)/(double)CLOCKS_PER_SEC); return 0; } void* Thread_sum(void* rank) { long my_rank = (long) rank; double factor; long long i; long long my_n = 10000000000/thread_count; long long my_first_i = my_n*my_rank; long long my_last_i = my_first_i + my_n; double my_sum = 0.0; if (my_first_i % 2 == 0) factor = 1.0; else factor = -1.0; for (i = my_first_i; i <= my_last_i; i++, factor = -factor) { my_sum += factor/(2*i + 1); } pthread_mutex_lock (&mutex); sum += my_sum; pthread_mutex_unlock(&mutex); return 0; }
0
#include <pthread.h> long a = 0; long b = 0; pthread_mutex_t a_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t b_mutex = PTHREAD_MUTEX_INITIALIZER; void *a_thread(void *arg) { printf("This thread increments a and adds to b\\n"); int ret = pthread_mutex_lock(&a_mutex); if(ret == EINVAL) { printf("Error locking a_mutex\\n"); pthread_exit(0); } sleep(1); a++; ret = pthread_mutex_lock(&b_mutex); if(ret == EINVAL) { printf("Error locking b_mutex\\n"); pthread_exit(0); } sleep(1); b += a; pthread_mutex_unlock(&b_mutex); pthread_mutex_unlock(&a_mutex); pthread_exit(0); } void *b_thread(void *arg) { printf("This thread increments b and multiplies a by b\\n"); int ret = pthread_mutex_lock(&a_mutex); ret = pthread_mutex_lock(&b_mutex); if(ret == EINVAL) { printf("Error locking b_mutex\\n"); pthread_exit(0); } b++; if(ret == EINVAL) { printf("Error locking a_mutex\\n"); pthread_exit(0); } a *= b; pthread_mutex_unlock(&b_mutex); pthread_mutex_unlock(&a_mutex); pthread_exit(0); } int main() { pthread_t my_a_thread[5]; pthread_t my_b_thread[5]; long id; for (id = 0; id < 5; id++) { int ret = pthread_create(&my_a_thread[id], 0, &a_thread, 0); ret = pthread_create(&my_b_thread[id], 0, &b_thread, 0); } for (id = 0; id < 5; id++) { pthread_join(my_a_thread[id], 0); pthread_join(my_b_thread[id], 0); } printf("main program done\\n"); printf("a = %ld\\n", a); printf("b = %ld\\n", b); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* doit(void *arg) { printf("pid = %d begin doit ...\\n", (int)getpid()); pthread_mutex_lock(&mutex); struct timespec ts = {2, 0}; nanosleep(&ts, 0); pthread_mutex_unlock(&mutex); printf("pid = %d end doit ...\\n", (int)getpid()); return 0; } void prepare(void) { pthread_mutex_unlock(&mutex); } void parent(void) { pthread_mutex_lock(&mutex); } int main(void) { pthread_atfork(&prepare, &parent, 0); printf("pid = %d Entering main ...\\n", (int)getpid()); pthread_t tid; pthread_create(&tid, 0, doit, 0); struct timespec ts = {1, 0}; nanosleep(&ts, 0); if(fork() == 0) { doit(0); } pthread_join(tid, 0); printf("pid = %d Exiting main ...\\n", (int)getpid()); return 0; }
0
#include <pthread.h> sem_t sem_fila[4]; sem_t sem_cliente[4]; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int tamanho_fila[4]; int clientes[4 * 100]; int index_cliente; int clientes_restantes; void inicializar() { index_cliente = -1; clientes_restantes = 4 * 100; pthread_mutex_init(&mutex, 0); for (int i = 0; i < 4; i++) sem_init(&sem_fila[i], 0, 0); for (int i = 0; i < 4; i++) sem_init(&sem_cliente[i], 0, 0); } void finalizar() { pthread_mutex_destroy(&mutex); for (int i = 0; i < 4; i++) sem_destroy(&sem_fila[i]); for (int i = 0; i < 4; i++) sem_destroy(&sem_cliente[i]); } int buscarFilaComMenorTamanho() { if (tamanho_fila[0] == 0) return 0; int menorFila = 0; for (int i = 1; i < 4; i++) { if (tamanho_fila[i] == 0) { return i; } if (tamanho_fila[i] < tamanho_fila[menorFila]) { menorFila = i; } } return menorFila; } void serAtendido(int cliente) { printf("Cliente %d sendo atendido\\n", cliente); } int getIdCliente() { return rand() % 10000; } void novoCliente() { int cliente = getIdCliente(); printf("Cliente %d chegou.\\n", cliente); pthread_mutex_lock(&mutex); int menorFila = buscarFilaComMenorTamanho(); sem_post(&sem_cliente[menorFila]); tamanho_fila[menorFila] += 1; clientes_restantes -= 1; index_cliente += 1; clientes[index_cliente] = cliente; pthread_mutex_unlock(&mutex); sem_wait(&sem_fila[menorFila]); serAtendido(cliente); } int todasFilasVazias() { pthread_mutex_lock(&mutex); int todasVazias = 1; for (int i = 0; i < 4; i++) if (tamanho_fila[i] > 0) { todasVazias = 0; break; } pthread_mutex_unlock(&mutex); return todasVazias; } void atenderCliente(int fila, int cliente) { printf("Caixa %d atendendo cliente %d \\n", fila, cliente); sleep(1); } int atenderClienteFila(int fila_origem, int fila_atendendo) { pthread_mutex_lock(&mutex); if (tamanho_fila[fila_origem] > 0) { int cliente = clientes[index_cliente]; index_cliente -= 1; tamanho_fila[fila_origem] -= 1; sem_post(&sem_fila[fila_origem]); pthread_mutex_unlock(&mutex); sem_wait(&sem_cliente[fila_origem]); if (fila_origem != fila_atendendo) { printf("Cliente %d saiu do caixa %d para o caixa %d.\\n", cliente, fila_origem, fila_atendendo); } atenderCliente(fila_atendendo, cliente); return 1; } pthread_mutex_unlock(&mutex); return 0; } void atenderTodosClienteFila(int fila) { while (atenderClienteFila(fila, fila)); } void filaVaziaAtenderOutraFila(int fila) { for (int fila_origem = 0; fila_origem < 4; fila_origem++) { if ((fila != fila_origem) && (atenderClienteFila(fila_origem, fila))) break; } } void desbloquearTodasFilas() { for (int i = 0; i < 4; i++) { sem_post(&sem_cliente[i]); } } void bloquearFila(int fila) { printf("bloqueando fila %d vazia. \\n", fila); sem_wait(&sem_cliente[fila]); } void atendimentoFila(int fila) { while (1) { atenderTodosClienteFila(fila); filaVaziaAtenderOutraFila(fila); if (todasFilasVazias()) { if (clientes_restantes <= 0){ desbloquearTodasFilas(); break; } bloquearFila(fila); } } } void *threadNovosCliente(void *id) { int _id = (int) id; for (int i = 0; i < 100; i++) novoCliente(); if (clientes_restantes <= 0) { desbloquearTodasFilas(); printf("Todos clientes devidamente enfileirados.\\n\\n"); } pthread_exit(0); } void *threadAtenderFila(void *fila) { int index = (int) fila; atendimentoFila(index); pthread_exit(0); } int main() { int i; srand((unsigned int) time(0)); pthread_t tfila[4]; pthread_t tclientes[4]; inicializar(); printf("Total de clientes: \\t%d\\n", 4 * 100); printf("Total de caixas: \\t%d\\n\\n", 4); for (i = 0; i < 4; i++) if (pthread_create(&tclientes[i], 0, &threadNovosCliente, (void *) i)) { printf("Erro na criacao da thread."); }; for (i = 0; i < 4; i++) if (pthread_create(&tfila[i], 0, &threadAtenderFila, (void *) i)) { printf("Erro na criacao da thread."); }; for (i = 0; i < 4; i++) { pthread_join(tfila[i], 0); } printf("Todos clientes devidamente atendidos.\\n\\n"); finalizar(); return 0; }
1
#include <pthread.h> void init_users(int sock, struct connected_users* users_list) { int i=0; users_list->current_user = -1; users_list->sock_serv = sock; users_list->nb_users = 0; pthread_mutex_init( &(users_list->mutex), 0 ); for (i=0; i<CLIENTS_NB; i++) { users_list->users[i].sock = -1; memset(&(users_list->users[i].info), 0, sizeof(struct sockaddr_in)); users_list->users[i].info_len = sizeof(struct sockaddr_in); } } void* server_accepting(void* p_data) { struct connected_users* users_list = p_data; int i = 0; struct user_t tmpUser; for (;;) { for(i=0; i<CLIENTS_NB; i++) { if(users_list->users[i].sock == -1) { pthread_mutex_lock( &(users_list->mutex) ); users_list->nb_users++; pthread_mutex_unlock( &(users_list->mutex) ); do_accept(users_list->sock_serv, &(users_list->users[i].sock), &(users_list->users[i].info), users_list->users[i].info_len ); if(users_list->nb_users >= CLIENTS_NB) { pthread_mutex_lock( &(users_list->mutex) ); users_list->nb_users--; pthread_mutex_unlock( &(users_list->mutex) ); do_write(users_list->users[i].sock, "[Server] There are too many users connected at the moment, please try again later.\\r\\n"); close(users_list->users[i].sock); users_list->users[i].sock = -1; } else { pthread_mutex_lock( &(users_list->mutex) ); users_list->current_user = i; pthread_create( &(users_list->users[i].thread), 0, client_handling, users_list ); } } } } } void* client_handling(void* p_data) { struct connected_users* users_list = (struct connected_users*) p_data; int id = users_list->current_user; int cont = 1; struct user_t* user = &(users_list->users[id]); char buffer[SIZE_BUFFER]; char buffer2[SIZE_BUFFER]; pthread_mutex_unlock( &(users_list->mutex) ); cont = 1; while(cont) { memset(buffer, 0, sizeof(char)*SIZE_BUFFER); if(do_read(user->sock, buffer, SIZE_BUFFER) != 0) { if( strncmp(buffer, "/quit", 5) ) { sprintf(buffer2, "[Server] %s", buffer); do_write(user->sock, buffer2); } else { quit(users_list, id); cont = 0; } } else { quit(users_list, id); cont = 0; } } return 0; } void quit(struct connected_users* users_list, int id) { pthread_mutex_lock( &(users_list->mutex) ); do_write(users_list->users[id].sock, "[Server] You will now be terminated.\\n"); close(users_list->users[id].sock); users_list->nb_users--; users_list->users[id].sock = -1; pthread_cancel(users_list->users[id].thread); pthread_mutex_unlock( &(users_list->mutex) ); }
0
#include <pthread.h> pthread_t tid[25]; pthread_mutex_t lock1, lock2, lock3; struct Airplane { int id; int fuel; bool emergency; }; struct Runway { int id; bool occupied; }; struct Runway runways[3]; struct Airplane airplanes[25]; void init(){ int i, j; for(i = 0; i < sizeof runways; i++) { runways[i].id = i; runways[i].occupied = 0; } for(j = 0; j < sizeof airplanes; j++) { airplanes[j].id = j; airplanes[j].fuel = rand() % 40 + 10; int random = rand() % 10; if(random = 0){ airplanes[j].emergency = 1; } else { airplanes[j].emergency = 0; } } } void landPlane(int planeID, int runwayID) { printf("Plane %d is beginning to land on runway %d\\n Fuel = %d\\n", planeID, runwayID, airplanes[planeID].fuel); sleep(3); printf("Plane %d has landed on runway %d\\n Fuel = %d\\n", planeID, runwayID, airplanes[planeID].fuel - 3); sleep(2); printf("Plane %d has cleard the runway %d\\n Fuel = %d\\n", planeID, runwayID, airplanes[planeID].fuel); if(runwayID == 1){ pthread_mutex_unlock(&lock1); } else if(runwayID == 2) { pthread_mutex_unlock(&lock2); } else if(runwayID == 3){ pthread_mutex_unlock(&lock3); } pthread_join(tid[planeID], 0); } void* spawnPlane(void *plane){ int planeID; planeID = ((struct Airplane*)plane)->id; printf("Plane %d has arrived.\\n Fuel = %d", planeID, airplanes[planeID].fuel); int i; while(airplanes[planeID].fuel > 2){ if(pthread_mutex_lock(&lock1) == 0){ landPlane(planeID, 1); return; } else if(pthread_mutex_lock(&lock2) == 0){ landPlane(planeID, 2); return; } else if(pthread_mutex_lock(&lock3) == 0){ landPlane(planeID, 3); return; } else { sleep(1); airplanes[planeID].fuel--; } } printf("Plane %d has run out of fuel and crashed\\n", planeID); return; } int main(void) { int i = 0; int err; printf("initializing\\n"); init(); if (pthread_mutex_init(&lock1, 0) != 0){ printf("\\n mutex init failed\\n"); return 1; } if (pthread_mutex_init(&lock2, 0) != 0){ printf("\\n mutex init failed\\n"); return 1; } if (pthread_mutex_init(&lock3, 0) != 0){ printf("\\n mutex init failed\\n"); return 1; } while(i < 25){ err = pthread_create(&(tid[i]), 0, spawnPlane, (void *)&airplanes[i]); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); i++; int sleepTime = rand() % 5; sleep(sleepTime); } pthread_mutex_destroy(&lock1); pthread_mutex_destroy(&lock2); pthread_mutex_destroy(&lock3); return 0; }
1
#include <pthread.h> int market() { srand(time(0)); _market_value = 100 * _stocks; pthread_t threads[_stocks]; pthread_create(&_up_watch, 0, (void*)watch_up, 0); pthread_create(&_down_watch, 0, (void*)watch_down, 0); for(int i = 0;i < _stocks;i++) { pthread_create(&threads[i], 0, (void*)hurr_durr_im_a_stock, 0); } pthread_join(_up_watch, 0); pthread_join(_down_watch, 0); for(int i = 0;i < _stocks;i++) { pthread_cancel(threads[i]); } return 0; } void sig_handler(int signum) { pthread_exit(0); } void watch_up() { signal(SIGUSR1, sig_handler); while(1) { pthread_mutex_lock(&_market_write_lock); if(_market_value > (1.0+((float)_delta/100)) * 100 * (float)_stocks) { fprintf(stdout, "Market up to %f\\n", _market_value); fprintf(stdout, "Total Market Price of %d Stocks: %f\\n", _stocks, _market_value); pthread_kill(_down_watch, SIGUSR1); pthread_mutex_unlock(&_market_write_lock); pthread_exit(0); } pthread_mutex_unlock(&_market_write_lock); } } void watch_down() { signal(SIGUSR1, sig_handler); while(1) { pthread_mutex_lock(&_market_write_lock); if(_market_value < (1.0-((float)_delta/100)) * 100 * (float)_stocks) { fprintf(stdout, "Market down to %f\\n", _market_value); fprintf(stdout, "Total Market Price of %d Stocks: %f\\n", _stocks, _market_value); pthread_kill(_up_watch, SIGUSR1); pthread_mutex_unlock(&_market_write_lock); pthread_exit(0); } pthread_mutex_unlock(&_market_write_lock); } }
0
#include <pthread.h> struct CRYPTO_dynlock_value { pthread_mutex_t mutex; }; pthread_mutex_t *openssl_mutex = 0; unsigned long openssl_thread_id( void ) { return( (unsigned long)pthread_self() ); } void openssl_mutex_lock( int mode, int n, const char *file, int line ) { if( mode & CRYPTO_LOCK ) pthread_mutex_lock( &openssl_mutex[n] ); else pthread_mutex_unlock( &openssl_mutex[n] ); } struct CRYPTO_dynlock_value *openssl_dl_create( const char *file, int line ) { int st; struct CRYPTO_dynlock_value *dl; dl = malloc( sizeof( pthread_t ) ); if( dl != 0 ) { st = pthread_mutex_init( &dl->mutex, 0 ); if( st != 0 ) { free( dl ); dl = 0; } } return( dl ); } void openssl_dl_destroy( struct CRYPTO_dynlock_value *dl, const char *file, int line ) { pthread_mutex_destroy( &dl->mutex ); free( dl ); } void openssl_dl_lock( int mode, struct CRYPTO_dynlock_value *dl, const char *file, int line ) { if( mode & CRYPTO_LOCK ) pthread_mutex_lock( &dl->mutex ); else pthread_mutex_unlock( &dl->mutex ); } int openssl_thread_init( void ) { int i, st, max = CRYPTO_num_locks(); if( openssl_mutex == 0 ) { openssl_mutex = calloc( max, sizeof( pthread_mutex_t ) ); if( openssl_mutex == 0 ) return( 0 ); for( i = 0; i < max; i++ ) { st = pthread_mutex_init( &openssl_mutex[i], 0 ); if( st != 0 ) return( 0 ); } } CRYPTO_set_id_callback( openssl_thread_id ); CRYPTO_set_locking_callback( openssl_mutex_lock ); CRYPTO_set_dynlock_create_callback( openssl_dl_create ); CRYPTO_set_dynlock_destroy_callback( openssl_dl_destroy ); CRYPTO_set_dynlock_lock_callback( openssl_dl_lock ); return( 1 ); }
1
#include <pthread.h> static int (*real_pthread_mutex_lock)(pthread_mutex_t *); static int (*real_pthread_mutex_unlock)(pthread_mutex_t *); static void init() { static int inited; if (inited++ > 0) { return; } real_pthread_mutex_lock = dlsym(RTLD_NEXT, "pthread_mutex_lock"); if (!real_pthread_mutex_lock) { printf("error in dlsym pthread_mutex_lock %s\\n", dlerror()); exit(-1); } real_pthread_mutex_unlock = dlsym(RTLD_NEXT, "pthread_mutex_unlock"); if (!real_pthread_mutex_unlock) { printf("error in dlsym pthread_mutex_unlock %s\\n", dlerror()); exit(-1); } } static void addr2line(void *pc) { char addr2line_cmd[100]; snprintf(addr2line_cmd, sizeof addr2line_cmd, "addr2line -e /proc/%d/exe %p", getpid(), pc); printf(" -> "); fflush(stdout); system (addr2line_cmd); } static void print_backtrace(void (*addr2line)(void *), bool verbose) { void **fp = (void **) __builtin_frame_address (0); void *saved_fp = __builtin_frame_address (1); void *saved_pc = __builtin_return_address (1); int depth = 0; if (verbose) printf (" [%d] pc == %p fp == %p\\n", depth++, saved_pc, saved_fp); addr2line(saved_pc); fp = saved_fp; while (fp != 0) { saved_fp = *fp; fp = saved_fp; if (*fp == 0) break; saved_pc = *(fp + 1); if (verbose) printf (" [%d] pc == %p fp == %p\\n", depth++, saved_pc, saved_fp); addr2line(saved_pc); } } int pthread_mutex_lock(pthread_mutex_t *mutex) { init(); printf("pthread_mutex_lock: Locking mutex located at %p, called from\\n", mutex); print_backtrace(addr2line, 0); return real_pthread_mutex_lock(mutex); } int pthread_mutex_unlock(pthread_mutex_t *mutex) { init(); printf("pthread_mutex_unlock: Unlocking mutex located at %p, called from\\n", mutex); print_backtrace(addr2line, 0); return real_pthread_mutex_unlock(mutex); }
0
#include <pthread.h> extern struct FileList* root; int selectPiece(struct FileList* file, struct PeerList* peer) { struct PeerList* cursor = file->peer; char* sum; int* index; int i, j; srand(time(0)); sum = (char*)malloc((file->file_size + MAXLEN) / MAXLEN); memset(sum, 0x00, (file->file_size + MAXLEN) / MAXLEN); index = (int*)malloc(sizeof(int) * ((file->file_size + MAXLEN) / MAXLEN)); for(i = 0; i < (file->file_size + MAXLEN) / MAXLEN; i++) index[i] = i; while(cursor) { for(i = 1; i <= (file->file_size + MAXLEN) / MAXLEN; i++) sum[i - 1] += getPiece(cursor->bitmap, i) ? 1 : 0; cursor = cursor->next; } for(i = 0; i < (file->file_size + MAXLEN) / MAXLEN; i++) { for(j = i + 1; j < (file->file_size + MAXLEN) / MAXLEN; j++) { if(sum[index[i]] > sum[index[j]]) { int temp; temp = index[j]; index[j] = index[i]; index[i] = temp; } else if(sum[index[i]] > sum[index[j]] && (rand() % 2)) { int temp; temp = index[j]; index[j] = index[i]; index[i] = temp; } } } for(i = 0; i < (file->file_size + MAXLEN) / MAXLEN; i++) { if(!getPiece(file->bitmap, index[i] + 1) && !getPiece(file->downloading, index[i] + 1)) if(getPiece(peer->bitmap, index[i] + 1)) { int result = index[i] + 1; setPiece(file->downloading, index[i] + 1); free(sum); free(index); return result; } } free(sum); free(index); return -1; } void* download(void* arg) { struct FileList* file; struct PeerList* peer; int servSock; struct sockaddr_in servAddr; int servAddrLen; char buffer[MAXLEN + 9]; int bufferLen; char* bitmap; int i; memcpy(&file, arg, sizeof(struct FileList*)); memcpy(&peer, arg + sizeof(struct FileList*), sizeof(struct PeerList*)); bitmap = (char*)malloc((file->file_size + MAXLEN) / MAXLEN); pthread_detach(pthread_self()); free(arg); while(1) { for(i = 1; i <= (file->file_size + MAXLEN) / MAXLEN; i++) if(!getPiece(file->bitmap, i)) break; if(i == (file->file_size + MAXLEN) / MAXLEN + 1) break; if((servSock = socket(PF_INET, SOCK_STREAM, 0)) == -1) { fprintf(stderr, "socket create error\\n"); free(bitmap); return 0; } servAddrLen = sizeof(servAddr); memset(&servAddr, 0, servAddrLen); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = peer->IP; servAddr.sin_port = htons((unsigned short)9001); if(connect(servSock, (struct sockaddr*)&servAddr, servAddrLen)) { fprintf(stderr, "connect error\\n"); close(servSock); sleep(10); continue; } buffer[0] = 0x06; bufferLen = 5; buffer[bufferLen++] = strlen(file->file_name); memcpy(buffer + bufferLen, file->file_name, strlen(file->file_name)); bufferLen += strlen(file->file_name); if(putMsg(servSock, buffer, bufferLen)) continue; if(getMsg(servSock, buffer, &bufferLen)) continue; buffer[0] = 0x07; bufferLen = 5; memcpy(buffer + bufferLen, file->bitmap, (file->file_size + MAXLEN) / MAXLEN); bufferLen += (file->file_size + MAXLEN) / MAXLEN; if(putMsg(servSock, buffer, bufferLen)) continue; if(getMsg(servSock, buffer, &bufferLen)) continue; memcpy(bitmap, buffer + 5, (file->file_size + MAXLEN) / MAXLEN); updatePeer(file, peer->IP, bitmap); int piece = selectPiece(file, peer); if(piece < 0) { close(servSock); sleep(1); continue; } buffer[0] = 0x08; bufferLen = 5; piece = htonl(piece); memcpy(buffer + bufferLen, &piece, 4); bufferLen += 4; if(putMsg(servSock, buffer, bufferLen)) continue; if(getMsg(servSock, buffer, &bufferLen)) continue; piece = ntohl(piece); pthread_mutex_lock(&(file->mutex)); writePiece(file->file_name, piece, buffer + 9, bufferLen - 9); pthread_mutex_unlock(&(file->mutex)); setPiece(file->bitmap, piece); close(servSock); } free(bitmap); return 0; } void* leecher(void* arg) { struct FileList* file = (struct FileList*)arg; struct PeerList** cursor = &(file->peer); struct connection* c; char buffer[MAXLEN]; int bufferLen; int i; pthread_detach(pthread_self()); while(1) { for(i = 1; i <= (file->file_size + MAXLEN) / MAXLEN; i++) if(!getPiece(file->bitmap, i)) break; if(i == ((file->file_size + MAXLEN) / MAXLEN) + 1) break; while(*cursor) { void* arg; pthread_t t; arg = malloc(sizeof(struct FileList*) + sizeof(struct PeerList*)); memcpy(arg, &file, sizeof(struct FileList*)); memcpy(arg + sizeof(struct FileList*), cursor, sizeof(struct PeerList*)); if(pthread_create(&t, 0, download, arg)) { fprintf(stderr, "thread create error\\n"); return 0; } cursor = &((*cursor)->next); } sleep(1); } printf("downloading %s is complete\\n", file->file_name); }
1
#include <pthread.h> int cont; int id; } estrutura; volatile estrutura estr; pthread_mutex_t mutex; pthread_cond_t cond; volatile int lendo = 0, escrevendo = 0, filaEscrever = 0; volatile int continua; void * escrever (void * tid) { int id = * (int *) tid; free(tid); while (1) { pthread_mutex_lock(&mutex); continua--; filaEscrever++; while (lendo || escrevendo) pthread_cond_wait(&cond, &mutex); escrevendo = 1; estr.cont++; estr.id = id; escrevendo = 0; filaEscrever--; pthread_cond_broadcast(&cond); printf("Thread %d escrevendo\\n", id); pthread_mutex_unlock(&mutex); } pthread_exit(0); } void * ler (void * tid) { int id = * (int *) tid; free(tid); estrutura estrLocal; while (1) { pthread_mutex_lock(&mutex); while (estrLocal.cont == estr.cont || filaEscrever || escrevendo && estr.id != -1) pthread_cond_wait(&cond, &mutex); lendo = 1; estrLocal.cont = estr.cont; estrLocal.id = estr.id; lendo = 0; pthread_cond_broadcast(&cond); printf("Thread %d (leitora) - id: %d - cont: %d\\n", id, estrLocal.id, estrLocal.cont); pthread_mutex_unlock(&mutex); } pthread_exit(0); } int main(int argc, char const *argv[]) { pthread_t threads[(5 + 2)]; int i, *tid; estr.cont = 0; estr.id = -1; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); for (i = 0; i < 5; ++i) { tid = malloc(sizeof(int)); *tid = i; pthread_create(&threads[*tid], 0, escrever, (void *) tid); } for (i = 0; i < 2; ++i) { tid = malloc(sizeof(int)); *tid = 5 + i; pthread_create(&threads[*tid], 0, ler, (void *) tid); } for (i = 0; i < (5 + 2); ++i) { pthread_join(threads[i], 0); } return 0; }
0
#include <pthread.h> int produce = 0; pthread_mutex_t mutex; pthread_cond_t cond; void *thread_pro(void *argv) { for (;;) { pthread_mutex_lock(&mutex); printf("thead_pro product [%d]\\n", produce++); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); usleep(500*1000); } } void *thread_cos(void *argv) { int id = (int)argv; for (;;) { pthread_mutex_lock(&mutex); while (produce <= 0) pthread_cond_wait(&cond, &mutex); printf("thread[%d] using product[%d]\\n", id, produce--); pthread_mutex_unlock(&mutex); usleep(500*1000); } } int main() { pthread_t cos1, cos2, pro; int ret; pthread_mutex_init(&mutex, 0); pthread_cond_init(&cond, 0); ret = pthread_create(&pro, 0, thread_pro, 0); assert(ret == 0); ret = pthread_create(&cos1, 0, thread_cos, (void*)1); assert(ret == 0); ret = pthread_create(&cos2, 0, thread_cos, (void*)2); assert(ret == 0); pthread_join(pro, 0); pthread_join(cos1, 0); pthread_join(cos2, 0); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> void* pack(void *data) { const char *COLORS[] = {"AliceBlue","AntiqueWhite","Aqua","Aquamarine","Azure","Beige","Bisque","Black","BlanchedAlmond","Blue","BlueViolet","Brown","BurlyWood","CadetBlue","Chartreuse","Chocolate","Coral","CornflowerBlue","Cornsilk","Crimson","Cyan","DarkBlue","DarkCyan","DarkGodenRod","DarkGray","DarkGrey","DarkGreen","DarkKhaki","DarkMagenta","DarkOliveGreen","Darkorange","DarkOrchid","DarkRed","DarkSalmon","DarkSeaGreen","DarkSlateBlue","DarkSlateGray","DarkSlateGrey","DarkTurquoise","DarkViolet","DeepPink","DeepSkyBlue","DimGray","DimGrey","DodgerBlue","FireBrick","FloralWhite","ForestGreen","Fuchsia","Gainsboro","GhostWhite","God","GodenRod","Gray","Grey","Green","GreenYellow","HoneyDew","HotPink","IndianRed","Indigo","Ivory","Khaki","Lavender","LavenderBlush","LawnGreen","LemonChiffon","LightBlue","LightCoral","LightCyan","LightGodenRodYellow","LightGray","LightGrey","LightGreen","LightPink","LightSalmon","LightSeaGreen","LightSkyBlue","LightSlateGray","LightSlateGrey","LightSteelBlue","LightYellow","Lime","LimeGreen","Linen","Magenta","Maroon","MediumAquaMarine","MediumBlue","MediumOrchid","MediumPurple","MediumSeaGreen","MediumSlateBlue","MediumSpringGreen","MediumTurquoise","MediumVioletRed","MidnightBlue","MintCream","MistyRose","Moccasin","NavajoWhite","Navy","OdLace","Olive","OliveDrab","Orange","OrangeRed","Orchid","PaleGodenRod","PaleGreen","PaleTurquoise","PaleVioletRed","PapayaWhip","PeachPuff","Peru","Pink","Plum","PowderBlue","Purple","Red","RosyBrown","RoyalBlue","SaddleBrown","Salmon","SandyBrown","SeaGreen","SeaShell","Sienna","Silver","SkyBlue","SlateBlue","SlateGray","SlateGrey","Snow","SpringGreen","SteelBlue","Tan","Teal","Thistle","Tomato","Turquoise","Violet","Wheat","White","WhiteSmoke","Yellow","YellowGreen"}; struct AssemblyLine *line = (struct AssemblyLine *) data; struct Product box[BOX_SIZE]; int index = 0; int tid = (int)pthread_self() % 10000; int total = PRODUCTS*ASSEMBLY; int j; for (j = line->total_packed; j < total; ++j) { pthread_mutex_lock(&line->mutex); if (line->total_packed >= total) { pthread_mutex_unlock(&line->mutex); break; } if (line->count !=0) { while (line->count == 0) { pthread_cond_wait(&line->empty, &line->mutex); } box[index] = line->products[line->out];++index; if (index == BOX_SIZE) { index = 0; int i = 0, color = 0; printf("[Packer %d]: I have a box of products containing: ",tid); for(;i<BOX_SIZE-1;++i) { color = box[i].color; printf("%s %d, ",COLORS[color],box[i].id); } printf("%s %d\\n",COLORS[color],box[BOX_SIZE-1].id); } line->out = (line->out + 1) % LINE_SIZE; line->count--;++line->total_packed; pthread_cond_broadcast(&line->empty); } pthread_mutex_unlock(&line->mutex); } printf("DONE PACKIN\\n"); return 0; }
0
#include <pthread.h> enum { STATE_A, STATE_B } state = STATE_A; pthread_cond_t condA = PTHREAD_COND_INITIALIZER; pthread_cond_t condB = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadA() { int i = 0, rValue, loopNum; while(i<5) { pthread_mutex_lock(&mutex); while (state != STATE_A) pthread_cond_wait(&condA, &mutex); pthread_mutex_unlock(&mutex); for(loopNum = 1; loopNum <= 5; loopNum++) printf("Hello %d\\n", loopNum); pthread_mutex_lock(&mutex); state = STATE_B; pthread_cond_signal(&condB); pthread_mutex_unlock(&mutex); i++; } return 0; } void *threadB() { int n = 0, rValue; while(n<5) { pthread_mutex_lock(&mutex); while (state != STATE_B) pthread_cond_wait(&condB, &mutex); pthread_mutex_unlock(&mutex); printf("Goodbye\\n"); pthread_mutex_lock(&mutex); state = STATE_A; pthread_cond_signal(&condA); pthread_mutex_unlock(&mutex); n++; } return 0; } int main(int argc, char *argv[]) { pthread_t a, b; pthread_create(&a, 0, threadA, 0); pthread_create(&b, 0, threadB, 0); pthread_join(a, 0); pthread_join(b,0); return 0; }
1
#include <pthread.h> pthread_t thd[2]; pthread_mutex_t mutex; int global; static pid_t get_current_tid() { return syscall(SYS_gettid); } void foo(int*p) { int j = 0; int i = 0; int sum = 0; int tid = get_current_tid(); int *q = (int*)malloc(1000); for (j = 0; j < 6000; j++) { if(j%100 == 0) pthread_mutex_lock(&mutex); sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; if (j%100== 0) pthread_mutex_unlock(&mutex); } free(q); } void foo_2(int *p) { int i = 0; for(i = 0; i< 10000; i++) { foo(p); *p = 1; } } void foo_1(int *p) { foo_2(p); } void foo_0(int *p) { foo_1(p); pthread_exit(0); } void bar(int *p) { int j = 0; int i = 0; int sum = 0; int tid = get_current_tid(); int* q = (int*)malloc(1000); for (j = 0; j < 20000; j++) { sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; sum = sum + j; } free(q); } void bar_2(int *p) { int i = 0; for(i = 0; i< 10000; i++) { bar(p); *p = 1; } } void bar_1(int *p) { bar_2(p); } void bar_0(int *p) { bar_1(p); pthread_exit(0); } int main() { int i; int rv; racez_start(); printf("the address of global is %p\\n", &global); for(i = 0; i < 2; i++) { if(i%2 == 0) { rv = pthread_create(&thd[i], 0, foo_0, (void*)&global); } else { rv = pthread_create(&thd[i], 0, bar_0, (void*)&global); } if(rv != 0) { printf("pthread_create failed!\\n"); exit(0); } } for(i = 0; i < 2; i++) { rv = pthread_join(thd[i], 0); if( rv != 0) { printf("pthread_join failed\\n"); exit(0); } } racez_stop(); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond_var[5]; pthread_t threadID[5]; void * philospher(void *num); void pickup_forks(int); void return_forks(int); void philosopher_can_eat(int); int state[5]; int philosophers[5]={0,1,2,3,4}; void *philospher(void *num) { while(1) { int x = rand() % 3; int *i = num; sleep(x+1); printf("%d seconds waited...\\n", x+1); pickup_forks(*i); return_forks(*i); } } void pickup_forks(int philosopher_number) { pthread_mutex_lock (&mutex); state[philosopher_number] = 1; printf("Philosopher %d is Hungry now \\n", philosopher_number+1); philosopher_can_eat(philosopher_number); if (state[philosopher_number] != 2){ pthread_cond_wait(&cond_var[philosopher_number], &mutex); } pthread_mutex_unlock (&mutex); } void return_forks(int philosopher_number) { pthread_mutex_lock (&mutex); state[philosopher_number] = 0; printf("Philosopher %d is putting forks %d and %d down. She is thinking now. \\n", philosopher_number+1, (philosopher_number+4)%5 +1, philosopher_number+1); philosopher_can_eat((philosopher_number+4)%5); philosopher_can_eat((philosopher_number+1)%5); pthread_mutex_unlock (&mutex); } void philosopher_can_eat(int philosopher_number) { if (state[philosopher_number] == 1 && state[(philosopher_number+4)%5] != 2 && state[(philosopher_number+1)%5] != 2) { state[philosopher_number] = 2; printf("Philosopher %d is picking up fork %d and %d. She is eating now \\n", philosopher_number+1, (philosopher_number+4)%5 +1, philosopher_number+1); pthread_cond_signal(&cond_var[philosopher_number]); } } int main() { int i; time_t t; srand((unsigned) time(&t)); pthread_t threadID[5]; for(i=0; i < 5; i++) { state[i] = 0; pthread_cond_init(&cond_var[i], 0); } pthread_mutex_init (&mutex, 0); for(i=0; i < 5; i++) { pthread_create(&threadID[i], 0, philospher, &philosophers[i]); printf("Philosopher %d is thinking now \\n", i+1); } for(i=0; i<5; i++) { pthread_join(threadID[i], 0); } pthread_mutex_destroy(&mutex); }
1
#include <pthread.h> pthread_cond_t Var_Cond; pthread_mutex_t Verrou; pthread_t Thread_Id; int Threads_Finis; } Zone_Part_t; Zone_Part_t Zone_Part; sem_t sem; int main(int argc, char *argv[]){ pthread_t Tid_main, Threads[1000]; int i, Acquittes, Nbre_Threads; void Un_Thread (void); if (argc != 2){ printf("Utilisation : %s n (nbre de threads)\\n", argv[0]); exit(1); } Nbre_Threads = atoi(argv[1]); if (Nbre_Threads > 1000){ printf(" Pas plus de %d threads !\\n", Nbre_Threads); exit(2); } srandom(time(0)); Tid_main=pthread_self(); Acquittes = 0; Zone_Part.Threads_Finis = 0; pthread_cond_init(&Zone_Part.Var_Cond, 0); pthread_mutex_init(&Zone_Part.Verrou, 0); sem_init(&sem, 0, 0); for (i=0; i < Nbre_Threads ; i++){ pthread_create(&Threads[i], 0, (void *(*)(void *))Un_Thread, 0); printf("main (Tid (0x)%x vient de creer : (0x)%x\\n", (int)Tid_main, (int)Threads[i]); } sem_post(&sem); pthread_mutex_lock(&Zone_Part.Verrou); while (Zone_Part.Threads_Finis < Nbre_Threads){ pthread_cond_wait(&Zone_Part.Var_Cond, &Zone_Part.Verrou); Acquittes++; printf("\\n\\n----------------%d----------------\\n\\n", Acquittes); printf("main (Tid (0x)%x) : fin du thread (0x)%x\\n", (int)Tid_main, (int)Zone_Part.Thread_Id); sem_post(&sem); } pthread_mutex_unlock(&Zone_Part.Verrou); printf("main (Tid (0x)%x) : FIN, nbre de threads acquittes : %d, nbre de threads termines : %d\\n", (int)Tid_main, Acquittes,Zone_Part.Threads_Finis); return 0; } void Un_Thread(void){ pthread_t Mon_Tid; int i, Nbre_Iter; Mon_Tid = pthread_self(); Nbre_Iter = random()/10000; printf("Thread (0x)%x : DEBUT, %d iterations\\n", (int)Mon_Tid, Nbre_Iter); sem_wait(&sem); i=0; while(i < Nbre_Iter) i++; pthread_mutex_lock(&Zone_Part.Verrou); Zone_Part.Thread_Id = Mon_Tid ; Zone_Part.Threads_Finis++ ; pthread_cond_signal(&Zone_Part.Var_Cond); printf("Thread (0x)%x : FIN \\n", (int)Mon_Tid); pthread_mutex_unlock(&Zone_Part.Verrou); }
0
#include <pthread.h> struct Node { int data; struct Node *next; }; int Member(int value, struct Node *head_p); int Insert(int value, struct Node **head_pp); int Delete(int value, struct Node **head_pp); void *Operations(void *rank); void freeMemory(struct Node **head_pp); int n, m, sampleCount; float mMember, mInsert, mDelete; double sum, sqrSum; const int MAX_THREADS = 1024; long thread_count; pthread_mutex_t mutex; int memberCount = 0, insertCount = 0, deleteCount = 0; struct Node *head = 0; int main(int argc, char *argv[]) { double startTime, finishTime, elapsedTime; sum = 0, sqrSum = 0; long thread; pthread_t *thread_handles; if (argc != 8) { printf("Command required: ./llist_mutex numOfThreads n m mMember mInsert mDelete numOfSamples\\n"); } thread_count = strtol(argv[1], 0, 10); if (thread_count <= 0 || thread_count > MAX_THREADS) { printf("Please give the command: ./llist_mutex numOfThreads n m mMember mInsert mDelete numOfSamples\\n"); } n = (int)strtol(argv[2], (char **)0, 10); m = (int)strtol(argv[3], (char **)0, 10); mMember = (float)atof(argv[4]); mInsert = (float)atof(argv[5]); mDelete = (float)atof(argv[6]); sampleCount = (float)atof(argv[7]); if (n <= 0 || m <= 0 || mMember + mInsert + mDelete != 1.0) { printf("Command required: ./llist_mutex numOfThreads n m mMember mInsert mDelete numOfSamples\\n"); } int j; for (j = 0; j < sampleCount; j++) { int i; for (i = 0; i < n; i++) { int r = rand() % 65536; if (!Insert(r, &head)) { i--; } } thread_handles = (pthread_t *)malloc(thread_count * sizeof(pthread_t)); GET_TIME(startTime); pthread_mutex_init(&mutex, 0); for (thread = 0; thread < thread_count; thread++) { pthread_create(&thread_handles[thread], 0, Operations, (void *)thread); } for (thread = 0; thread < thread_count; thread++) { pthread_join(thread_handles[thread], 0); } pthread_mutex_destroy(&mutex); GET_TIME(finishTime); elapsedTime = finishTime - startTime; freeMemory(&head); sum += elapsedTime; sqrSum += elapsedTime*elapsedTime; } printData("mutex", n, m, sampleCount, mMember, mInsert, mDelete, thread_count, sum, sqrSum); return 0; } void *Operations(void *rank) { long i; long fraction = m / thread_count; for (i = 0; i < fraction; i++) { float p = (rand() % 10000 / 10000.0); int r = rand() % 65536; if (p < mMember) { pthread_mutex_lock(&mutex); Member(r, head); memberCount++; pthread_mutex_unlock(&mutex); } else if (p < mMember + mInsert) { pthread_mutex_lock(&mutex); Insert(r, &head); insertCount++; pthread_mutex_unlock(&mutex); } else { pthread_mutex_lock(&mutex); Delete(r, &head); deleteCount++; pthread_mutex_unlock(&mutex); } } return 0; } int Member(int value, struct Node *head_p) { struct Node *curr_p = head_p; while (curr_p != 0 && curr_p->data < value) { curr_p = curr_p->next; } if (curr_p == 0 || curr_p->data > value) { return 0; } else { return 1; } } int Insert(int value, struct Node **head_pp) { struct Node *curr_p = *head_pp; struct Node *pred_p = 0; struct Node *temp_p = 0; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p == 0 || curr_p->data > value) { temp_p = malloc(sizeof(struct Node)); temp_p->data = value; temp_p->next = curr_p; if (pred_p == 0) { *head_pp = temp_p; } else { pred_p->next = temp_p; } return 1; } else { return 0; } } int Delete(int value, struct Node **head_pp) { struct Node *curr_p = *head_pp; struct Node *pred_p = 0; while (curr_p != 0 && curr_p->data < value) { pred_p = curr_p; curr_p = curr_p->next; } if (curr_p != 0 && curr_p->data == value) { if (pred_p == 0) { *head_pp = curr_p->next; free(curr_p); } else { pred_p->next = curr_p->next; free(curr_p); } return 1; } else { return 0; } } void freeMemory(struct Node **head_pp) { struct Node *curr_p; struct Node *succ_p; if (head_pp == 0) return; curr_p = *head_pp; succ_p = curr_p->next; while (succ_p != 0) { free(curr_p); curr_p = succ_p; succ_p = curr_p->next; } free(curr_p); *head_pp = 0; }
1
#include <pthread.h> void *thread_fun(void* arg); pthread_mutex_t work_mutex; char workarea[1024]; int time_to_exit = 0; int main(void) { int res; pthread_t thread_a; void * thread_result; res = pthread_mutex_init(&work_mutex,0); if (res != 0) { perror("Semaphore initiation failed"); exit(1); } res = pthread_create(&thread_a,0,thread_fun,0); if (res != 0) { perror("thread failed"); exit(1); } pthread_mutex_lock(&work_mutex); printf("Enter some text.enter end to finish\\n"); while (!time_to_exit) { fgets(workarea,1024,stdin); pthread_mutex_unlock(&work_mutex); while (1) { pthread_mutex_lock(&work_mutex); if (workarea[0] != '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); } else{ break; } } } printf("Waiting for thread to finish...\\n"); res = pthread_join(thread_a,&thread_result); if (res != 0) { perror("Thread join failed"); exit(1); } printf("Join success\\n"); return 0; } void *thread_fun(void* arg) { sleep(1); pthread_mutex_lock(&work_mutex); while (strncmp("end",workarea,3) != 0) { printf("You input %d characters\\n", strlen(workarea) - 1); workarea[0] = '\\0'; pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); while (workarea[0] == '\\0') { pthread_mutex_unlock(&work_mutex); sleep(1); pthread_mutex_lock(&work_mutex); } } time_to_exit = 1; workarea[0] = '\\0'; pthread_mutex_unlock(&work_mutex); pthread_exit(0); }
0
#include <pthread.h> char coup_tcp[13]; char coup_part[13]; char rdy = 0; pthread_mutex_t synchro_mutex; pthread_cond_t synchro_cv; char * send_plateau_a() { static int player = 0; static int first = 1; static pthread_t th; int retour = 0; if (first) { first = 0; coup_part[0] = 0; coup_tcp[0] = 0; pthread_mutex_init(&synchro_mutex, 0); pthread_cond_init (&synchro_cv, 0); retour = pthread_create(&th, 0, jouer_radio_VS, 0 ); if (retour != 0) { perror(strerror(errno)); exit(1); } pthread_mutex_lock(&synchro_mutex); while (!rdy) pthread_cond_wait(&synchro_cv, &synchro_mutex); rdy = 0; pthread_mutex_unlock(&synchro_mutex); return string_plat(); } if (player) { pthread_mutex_lock(&synchro_mutex); while (coup_tcp[0] == 0){ pthread_cond_wait(&synchro_cv, &synchro_mutex); } strcpy(coup_part, coup_tcp); coup_tcp[0]=0; pthread_cond_signal(&synchro_cv); rdy = 0; pthread_mutex_unlock(&synchro_mutex); } else { pthread_mutex_lock(&synchro_mutex); send_coup_a(); pthread_cond_signal(&synchro_cv); rdy = 0; pthread_mutex_unlock(&synchro_mutex); } pthread_mutex_lock(&synchro_mutex); while (!rdy) pthread_cond_wait(&synchro_cv, &synchro_mutex); send_msg_to_diff(coup_part); rdy = 0; coup_part[0] = 0; pthread_mutex_unlock(&synchro_mutex); player = !player; return string_plat(); } void send_coup_a() { char * coup = get_best(); strcpy(coup_part, coup); raz_vote(); } int process_input_client_gounki_a(char * buff, int descSock, char * address_caller) { char mess[TAILLE_MAX_TCP]; if (strncmp(buff, "INFO", 4) == 0) { format_mess_desc(mess, "Un serveur de jeu Gounki communautaire ou vous affronter une IA !"); send(descSock, mess, strlen(mess), 0); send(descSock, "VOTE\\r\\n", strlen("VOTE\\r\\n"), 0); send(descSock, "ENDM\\r\\n", strlen("ENDM\\r\\n"), 0); return 1; } else if (strncmp(buff, "HELP", 4) == 0) { if (strncmp(buff + 5, "VOTE", 4) == 0) { format_mess_help(mess, "Comande pour participer au jeu VOTE suivit du coup : VOTE a1-b1", "VOTE"); send(descSock, mess, strlen(mess), 0); return 1; } } else if (strncmp(buff, "VOTE", 4) == 0) { char * end = strchr(buff, '\\n'); end[0] = 0; receive_vote(buff + 5); return 1; } return 0; } int process_input_diffu_gounki_a(char * buf) { if (strncmp(buf, "PLAY", 4) == 0) { pthread_mutex_lock(&synchro_mutex); strcpy(coup_tcp,buf+5); pthread_cond_broadcast(&synchro_cv); pthread_mutex_unlock(&synchro_mutex); return 1; } return 0; }
1
#include <pthread.h> static void clean_sys_thread(void *arg){ if(arg){ free(arg); } } void *sys_thread(void *arg){ FILE *fp; struct Sysinfo *siptr; struct Sysinfo *tail; char buffer[100]; struct SysCPU syscpu; struct tms procpu; long lastctime, curctime; long lastitime, curitime; long lastptime, curptime; long totalmem; long totalfree; long procmem; pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); while(statis.start==0); lastctime = 0; lastitime = 0; lastptime = 0; while(1){ if((siptr=malloc(sizeof(struct Sysinfo)))==0){ printf("malloc Sysinfo failed!\\n"); exit(1); } siptr->next = 0; if((fp = fopen("/proc/stat", "r"))==0){ printf("open /proc/stat failed\\n"); perror("fopen"); exit(1); } fscanf(fp, "%s%ld%ld%ld%ld%ld%ld%ld%ld%ld%ld", buffer, &syscpu.user, &syscpu.nice, &syscpu.system, &syscpu.idle, &syscpu.iowait, &syscpu.irq, &syscpu.softirq, &syscpu.steal, &syscpu.guest, &syscpu.guestnice ); if(fclose(fp)!=0){ perror("fclose"); exit(1); } times(&procpu); curctime = syscpu.user+syscpu.nice+syscpu.system+syscpu.idle+ syscpu.iowait+syscpu.irq+syscpu.softirq+syscpu.steal+ syscpu.guest+syscpu.guestnice; curitime = syscpu.idle; curptime = procpu.tms_utime+procpu.tms_stime+ procpu.tms_cutime+procpu.tms_cstime; siptr->cpu_usage = 100-(double)(curitime-lastitime)/(curctime-lastctime)*100.0; siptr->pcpu_usage = (double)(curptime-lastptime)/(curctime-lastctime)*100.0; lastctime = curctime; lastitime = curitime; lastptime = curptime; if((fp = fopen("/proc/meminfo", "r"))==0){ printf("open /proc/meminfo failed\\n"); exit(1); } fscanf(fp, "%s%ld%s%s%ld%s", buffer, &totalmem, buffer+15, buffer+30, &totalfree, buffer+45 ); if(fclose(fp)!=0){ perror("fclose"); exit(1); } memset(buffer, 0, 100); strcpy(buffer, "/proc/"); sprintf(buffer+strlen(buffer), "%d", (int)statis.pid); strcat(buffer, "/status"); if((fp = fopen(buffer, "r"))==0){ printf("open %s failed\\n", buffer); exit(1); } do{ fscanf(fp, "%s", buffer); if(strcmp(buffer, "VmRSS:")==0){ fscanf(fp, "%ld", &procmem); break; }else fgets(buffer, 100, fp); }while(1); siptr->mem_usage = 100-(double)totalfree/totalmem*100.0; siptr->pmem_usage = (double)procmem/totalmem*100.0; if(fclose(fp)!=0){ perror("fclose"); exit(1); } pthread_mutex_lock(&statis.si_mutex); if(statis.sihead==0) statis.sihead = siptr; else tail->next = siptr; tail = siptr; siptr = 0; pthread_mutex_unlock(&statis.si_mutex); usleep(conf.sysinterval*1000); } }
0
#include <pthread.h> pthread_mutex_t lock; int count; void * chunk(void * thread_id){ int id=*(int *) thread_id; int counter=0; int i; for(i=id*((100000*8)/100);i<(id+1)*((100000*8)/100);i++){ if(is_prime(i)) counter++; } pthread_mutex_lock(&lock); count+=counter; pthread_mutex_unlock(&lock); } int main(){ pthread_t threads[100]; int i; int thread_num[100]; int time; count=0; time=get_time_sec(); for(i=0;i<100;i++){ thread_num[i]=i; pthread_create(&threads[i],0,chunk,(void*)&thread_num[i]); } for(i=0;i<100;i++){ pthread_join(threads[i],0); } printf("Number of primes=%d, took %fs\\n",count, get_time_sec()-time); return 0; }
1
#include <pthread.h> int table[128]; pthread_mutex_t cas_mutex[128]; pthread_t tids[13]; int cas(int * tab, int h, int val, int new_val) { int ret_val = 0; pthread_mutex_lock(&cas_mutex[h]); if ( tab[h] == val ) { tab[h] = new_val; ret_val = 1; } pthread_mutex_unlock(&cas_mutex[h]); return ret_val; } void * thread_routine(void * arg) { int tid; int m = 0, w, h; tid = (int)arg; while(1){ if ( m < 4 ){ w = (++m) * 11 + tid; } else{ pthread_exit(0); } h = (w * 7) % 128; while ( cas(table, h, 0, w) == 0){ h = (h+1) % 128; } } } int main() { int i; for (i = 0; i < 128; i++) pthread_mutex_init(&cas_mutex[i], 0); for (i = 0; i < 13; i++){ pthread_create(&tids[i], 0, thread_routine, (void*)(i) ); } for (i = 0; i < 13; i++){ pthread_join(tids[i], 0); } for (i = 0; i < 128; i++){ pthread_mutex_destroy(&cas_mutex[i]); } }
0
#include <pthread.h> struct entry_s *create_network_map_entry(struct workspace_mount_s *workspace, struct directory_s *directory, struct name_s *xname, unsigned int *error) { struct stat st; st.st_mode=S_IFDIR | S_IRUSR | S_IXUSR | S_IWUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH; st.st_uid=0; st.st_gid=0; st.st_ino=0; st.st_dev=0; st.st_nlink=2; st.st_rdev=0; st.st_size=0; st.st_blksize=0; st.st_blocks=0; get_current_time(&st.st_mtim); memcpy(&st.st_ctim, &st.st_mtim, sizeof(struct timespec)); memcpy(&st.st_atim, &st.st_mtim, sizeof(struct timespec)); return _fs_common_create_entry(workspace, directory, xname, &st, 0, error); } static void install_net_services_context(unsigned int service, struct context_address_s *address, struct timespec *found, unsigned long hostid, unsigned int serviceid, void *ptr) { struct service_context_s *context=(struct service_context_s *) ptr; struct workspace_mount_s *workspace=context->workspace; struct inode_s *inode=0; struct directory_s *root_directory=0; if (workspace->syncdate.tv_sec < found->tv_sec || (workspace->syncdate.tv_sec == found->tv_sec && workspace->syncdate.tv_nsec < found->tv_nsec)) { workspace->syncdate.tv_sec = found->tv_sec; workspace->syncdate.tv_nsec = found->tv_nsec; } inode=&workspace->rootinode; if (lock_directory_excl(inode)==-1) { logoutput("install_net_services_context: unable to lock root directory"); return; } root_directory=get_directory(inode); unlock_directory_excl(inode); if (service==WORKSPACE_SERVICE_SFTP) { unsigned int error=0; if (install_ssh_server_context(workspace, inode->alias, address->target.network.address, address->target.network.port, &error)!=0) { logoutput("install_net_services_context: unable to connect to %s:%i", address->target.network.address, address->target.network.port); } } } static void install_net_services_all(unsigned int service, struct context_address_s *address, struct timespec *found, unsigned long hostid, unsigned long serviceid) { struct fuse_user_s *user=0; struct workspace_mount_s *workspace=0; struct workspace_base_s *base=0; unsigned int hashvalue=0; void *index=0; struct list_element_s *list=0; rwlock: lock_users_hash(); nextuser: user=get_next_fuse_user(&index, &hashvalue); if (! user) { logoutput("install_net_services_all: ready"); unlock_users_hash(); return; } if (!(user->options & WORKSPACE_TYPE_NETWORK)) goto nextuser; pthread_mutex_lock(&user->mutex); unlock_users_hash(); list=user->workspaces.head; while(list) { workspace=get_container_workspace(list); base=workspace->base; if (base->type==WORKSPACE_TYPE_NETWORK) { struct service_context_s *context=0; context=get_container_context(workspace->contexes.head); while (context) { if (context->type==SERVICE_CTX_TYPE_SERVICE && context->serviceid==serviceid) break; context=get_container_context(context->list.next); } if (! context) install_net_services_context(service, address, found, hostid, serviceid, (void *) workspace->context); } list=workspace->list.next; } pthread_mutex_unlock(&user->mutex); goto rwlock; } void install_net_services_cb(unsigned int service, struct context_address_s *address, struct timespec *found, unsigned long hostid, unsigned long serviceid, void *ptr) { if (service==WORKSPACE_SERVICE_SFTP) { logoutput("install_net_services_cb: found sftp at %s", address->target.network.address); } else { if (service==WORKSPACE_SERVICE_SMB) { logoutput("install_net_services_cb: found smb://%s; not supported yet", address->target.smbshare.server); } else if (service==WORKSPACE_SERVICE_NFS) { logoutput("install_net_services_cb: found nfs at %s; not supported yet", address->target.network.address); } else if (service==WORKSPACE_SERVICE_WEBDAV) { logoutput("install_net_services_cb: found webdav at %s; not supported yet", address->target.network.address); } else if (service==WORKSPACE_SERVICE_SSH) { logoutput("install_net_services_cb: found ssh at %s; ignoring", address->target.network.address); } return; } if (ptr) { install_net_services_context(service, address, found, hostid, serviceid, ptr); } else { install_net_services_all(service, address, found, hostid, serviceid); } }
1
#include <pthread.h> static char rcsId[]="$Id: ikcbl.c,v 1.1 1999/12/16 21:58:23 lanzm Exp lanzm $"; int ikcbl_init_bl(struct ikc_backlog_head* list_head, pthread_mutex_t* mutex) { list_head->list = 0; list_head->mutex = mutex; return 0; } int ikcbl_add_request(struct ikc_backlog_head* list_head, struct ikc_request* request) { struct ikc_backlog_list* new_list_elem; new_list_elem = malloc(sizeof(struct ikc_backlog_list)); if(!new_list_elem) { ikc_log_exit(IKC_LOG, "ikcbl_add: unable to allocate memory for new_list_elem\\n"); } pthread_mutex_lock(list_head->mutex); new_list_elem->request = request; if(list_head->list == 0) { list_head->list = new_list_elem; list_head->list->next = 0; list_head->list->prev = 0; } else { new_list_elem->next = list_head->list; new_list_elem->next->prev = new_list_elem; new_list_elem->prev = 0; list_head->list = new_list_elem; } pthread_mutex_unlock(list_head->mutex); return 0; } int ikcbl_remove_request(struct ikc_backlog_head* list_head, unsigned int request_nbr) { struct ikc_backlog_list* to_find; to_find = list_head->list; while(to_find != 0 && to_find->request->request_nbr != request_nbr) { to_find = to_find->next; } if(to_find == 0) { return -1; } if(to_find->next != 0) { to_find->next->prev = to_find->prev; } if(to_find->prev != 0) { to_find->prev->next = to_find->next; } __ikc_free_request(to_find->request); free(to_find->request); free(to_find); return 0; } int ikcbl_try_respond_from_backlog(struct ikc_backlog_head* list_head, struct ikc_request* request) { struct ikc_backlog_list* to_find; pthread_mutex_lock(list_head->mutex); to_find = list_head->list; while(to_find != 0 && to_find->request->request_nbr != request->request_nbr) { to_find = to_find->next; } if(to_find == 0) { pthread_mutex_unlock(list_head->mutex); return -1; } else { memcpy(to_find->request->cliaddr, request->cliaddr, request->cli_len); ikcr_respond_to_client(to_find->request); } pthread_mutex_unlock(list_head->mutex); return 0; } int ikcbl_remove_threads_last_request(struct ikc_backlog_head* list_head, struct ikc_request* request) { struct ikc_backlog_list* to_find; pthread_mutex_lock(list_head->mutex); to_find = list_head->list; while(to_find != 0 && to_find->request->host_id != request->host_id && to_find->request->thread_id != request->thread_id) { to_find = to_find->next; } if(to_find == 0) { pthread_mutex_unlock(list_head->mutex); return -1; } else { ikcbl_remove_request(list_head, request->request_nbr); } pthread_mutex_unlock(list_head->mutex); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int counter, global_sum_done; void *work_thread(void* tParam){ struct thread_data *myData; myData=(struct thread_data*) tParam; long me; int NUM_THREADS, xsize, ysize, part_start, part_length,i; pixel* src; int *sum; float *global_sum; NUM_THREADS = myData->started_threads; me = myData->threadID; xsize=myData->xsize; ysize=myData->ysize; src=myData->src; sum=myData->local_sum; global_sum=myData->global_sum; calc_part(&part_start,&part_length,me,NUM_THREADS,ysize); *sum = threshfilter_part_1(xsize,part_start, part_length,src); pthread_mutex_lock(&mutex); counter++; pthread_cond_broadcast(&cond); while(counter < NUM_THREADS){ pthread_cond_wait(&cond, &mutex); } if(me == 0){ for( i=0; i<NUM_THREADS; i++){ float tmp = (xsize*ysize); (*global_sum) = (*global_sum) + (float)(*(sum + i))/tmp; printf("local_sum: %d, global_sum: %d\\n", *(sum+i), *global_sum); } global_sum_done = 1; } pthread_cond_broadcast(&cond); while(global_sum_done != 1){ pthread_cond_wait(&cond, &mutex); } pthread_mutex_unlock(&mutex); threshfilter_part_2(xsize,part_start,part_length, src,global_sum,me); return 0; } int main (int argc, char ** argv) { int xsize, ysize, colmax, NUM_THREADS,i,imagecounter; pixel* src; struct timespec stime, etime; char *imagename, *filename, *outfile; src = malloc(MAX_PIXELS*sizeof(*src)); if (argc != 3) { fprintf(stderr, "Usage: %s <number of threads> <write_image(0 or 1)>\\n", argv[0]); exit(1); } NUM_THREADS = atoi(argv[1]); for(imagecounter = 0; imagecounter<4; imagecounter++){ switch(imagecounter){ case 0: imagename = "im1.ppm"; filename = "im1thres.txt"; outfile = "test1.ppm"; break; case 1: imagename = "im2.ppm"; filename = "im2thres.txt"; outfile = "test2.ppm"; break; case 2: imagename = "im3.ppm"; filename = "im3thres.txt"; outfile = "test3.ppm"; break; case 3: imagename = "im4.ppm"; filename = "im4thres.txt"; outfile = "test4.ppm"; break; } int local_sum[NUM_THREADS]; long long int global_sum = 0; if(read_ppm (imagename, &xsize, &ysize, &colmax, (char *) src) != 0) exit(1); if (colmax > 255) { fprintf(stderr, "Too large maximum color-component value\\n"); exit(1); } printf("Has read the image, calling filter\\n"); pthread_t thread_handle[NUM_THREADS]; struct thread_data thread_data_array[NUM_THREADS]; for(i=0; i<NUM_THREADS; i++){ thread_data_array[i].global_sum = &global_sum; thread_data_array[i].xsize = xsize; thread_data_array[i].ysize = ysize; thread_data_array[i].src = src; thread_data_array[i].started_threads = NUM_THREADS; thread_data_array[i].local_sum = &(local_sum[i]); } clock_gettime(CLOCK_REALTIME, &stime); for(i=0; i<NUM_THREADS; i++) { thread_data_array[i].threadID = i; pthread_create(&thread_handle[i], 0, work_thread, &(thread_data_array[i])); } for(i=0; i<NUM_THREADS; i++) { pthread_join(thread_handle[i], 0); } clock_gettime(CLOCK_REALTIME, &etime); printf("Filtering took: %g secs\\n", (etime.tv_sec - stime.tv_sec) + 1e-9*(etime.tv_nsec - stime.tv_nsec)) ; printf("Writing output file\\n"); if(argv[2] == 1){ if(write_ppm (outfile, xsize, ysize, (char *)src) != 0) exit(1); } if(write_txt( filename, ((etime.tv_sec - stime.tv_sec) + 1e-9*(etime.tv_nsec - stime.tv_nsec)), NUM_THREADS ) != 0) exit(1); } return(0); }
1
#include <pthread.h> struct foo *fh[29]; pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; struct foo { int f_count; pthread_mutex_t f_lock; struct foo *f_next; int f_id; }; struct foo *foo_alloc(void) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { fre(fp); return(0); } idx = (((unsigned long)fp) % 29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&fp->f_lock); fp->f_count++; pthread_mutex_unlock(&fp->f_lock); } struct foo *foo_find(int id) { struct foo *fp; int idx; idx = (((unsigned long)fp) % 29); pthread_mutex_lock(&hashlock); for (fp = fh[idx]; fp != 0; fp = fp->f_next) { if (fp->f_id == id) { foo_hold(fp); break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&fp->f_lock); if (fp->f_count == 1) { pthread_mutex_unlock(&fp->f_lcok); pthread_mutex_lock(&hashlock); pthread_mutex_lock(&fp->f_lock); if (fp->f_count != 1) { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); pthread_mutex_unlock(&hashlock); return; } idx = (((unsigned long)fp) % 29); tfp = fh[idx]; if (tfp == fp) { fh[idx] = fp->f_next; } else { while (tfp->f_next != fp) tfp = ftp->f_next; tfp->f_next = fp->f_next; } pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); pthread_mutex_destroy(&fp->f_lock); free(fp); } else { fp->f_count--; pthread_mutex_unlock(&fp->f_lock); } }
0
#include <pthread.h> void *thread_main(void *arg); struct sync_var { pthread_mutex_t mutex; pthread_cond_t waitq; int num, num2wait; }; static void sync_var_init(struct sync_var *v, int num, int num2wait) { pthread_mutex_init(&v->mutex, 0); pthread_cond_init(&v->waitq, 0); v->num=num; v->num2wait=num2wait; } static int sync_var_wait4(struct sync_var *v) { pthread_mutex_lock(&v->mutex); while(v->num!=v->num2wait) pthread_cond_wait(&v->waitq, &v->mutex); v->num=0; pthread_mutex_unlock(&v->mutex); return v->num; } static int sync_var_delta(struct sync_var *v, int delta) { int num; pthread_mutex_lock(&v->mutex); v->num+=delta; num=v->num; if (v->num==v->num2wait) pthread_cond_signal(&v->waitq); pthread_mutex_unlock(&v->mutex); return num; } struct sync_var sv; int main(void) { int n=10; pthread_t tid; sync_var_init(&sv, 0, 10); while(n--) { pthread_create(&tid, 0, thread_main, (void*)n); } sync_var_wait4(&sv); printf("main saliendo...\\n"); return 0; } void *thread_main(void *arg) { int n=(int)arg; pthread_detach(pthread_self()); usleep(random()%10000); printf("thread_num=%d\\n", n); sync_var_delta(&sv, +1); return 0; }
1
#include <pthread.h> struct arg_set { char *fname; int count; }; struct arg_set *mailbox; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t flag = PTHREAD_COND_INITIALIZER; int main(int ac, char *av[]) { pthread_t t1, t2; struct arg_set args1, args2; void *count_words(void *); int reports_in = 0; int total_words = 0; if (ac != 3) { printf("usage: %s file1 file2\\n", av[0]); exit(1); } pthread_mutex_lock(&lock); args1.fname = av[1]; args1.count = 0; pthread_create(&t1, 0, count_words, (void *)&args1); args2.fname = av[2]; args2.count = 0; pthread_create(&t2, 0, count_words, (void *)&args2); while (reports_in < 2) { printf("MAIN: waiting for flag to go up\\n"); pthread_cond_wait(&flag, &lock); printf("MAIN: Wow! flag was raised, I have the locak\\n"); printf("%7d: %s\\n", mailbox->count, mailbox->fname); total_words += mailbox->count; if (mailbox == &args1) pthread_join(t1, 0); if (mailbox == &args2) pthread_join(t2, 0); mailbox = 0; pthread_cond_signal(&flag); reports_in ++; } printf("%7d: total words\\n", total_words); } void *count_words(void *a) { struct arg_set *args = a; FILE *fp; int c, prevc = '\\0'; if ( (fp = fopen(args->fname, "r")) != 0 ) { while ( (c = getc(fp)) != EOF ) { if ( !isalnum(c) && isalnum(prevc) ) args->count++; prevc = c; } fclose(fp); } else { perror(args->fname); } printf("COUNT: waiting to get lock\\n"); pthread_mutex_lock(&lock); printf("COUNT: have lock , storing data\\n"); if ( mailbox != 0 ) pthread_cond_wait(&flag, &lock); mailbox = args; printf("COUNT: raising flag\\n"); pthread_cond_signal(&flag); printf("COUNT: unlocaking box\\n"); pthread_mutex_unlock(&lock); return 0; }
0
#include <pthread.h> int archivos_Inicia(); int escrbirArchivo(char * contenido, char *url); void *hiloWriteWEB(void *dummyPtr); int numeroHilos = 0; pthread_t thread_id [2]; pthread_mutex_t mutexEscritura = PTHREAD_MUTEX_INITIALIZER; int counterCache = 0; int archivos_Inicia () { int i; for(i=0; i < 2; i++) { pthread_create( &thread_id[i], 0, hiloWriteWEB, 0 ); } return 0; } int archivos_joinHilos(){ int j; for(j=0; j < 2; j++) { pthread_join( thread_id[j], 0); } } void *hiloWriteWEB(void *dummyPtr) { int idhilo = numeroHilos++; while (1){ pthread_mutex_lock( &mutexEscritura ); if (cache_size()>counterCache){ char * archivo = cache_get(counterCache); char * paginaActual = cacheNombres_get(counterCache); printf("(A)----- Hilo numero: %ld Elemento %d de %d (%s) \\n", idhilo, counterCache, cache_size(), paginaActual); counterCache++; escrbirArchivo(archivo, paginaActual); printf("(A)----- Hilo numero: %ld finaliza (%s)\\n", idhilo, paginaActual); } else{ printf("(A)----- Hilo numero: %ld Cache vacio \\n", idhilo); } pthread_mutex_unlock( &mutexEscritura ); sleep (1); } } int escrbirArchivo(char * contenido, char *url) { FILE *archivo; char* html = ".html"; char* arch; arch = strcat(url, html); if((archivo = fopen(arch,"a"))==0) { printf("No se puede escrbir el archivo \\n"); exit(1); } fprintf(archivo,contenido); fclose(archivo); return 1; }
1
#include <pthread.h> pthread_mutex_t disk_mutex = PTHREAD_MUTEX_INITIALIZER; int log_to_disk(int from_lan) { extern char hiscall[]; extern char comment[]; extern char my_rst[]; extern char his_rst[]; extern char last_rst[4]; extern char qsonrstr[5]; extern char lan_logline[]; extern int rit; extern int trx_control; extern int cqmode; extern int outfreq; extern int block_part; extern char lan_message[]; extern char thisnode; extern int lan_mutex; extern int cqwwm2; extern int no_rst; pthread_mutex_lock(&disk_mutex); if (!from_lan) { addcall(); makelogline(); store_qso(logline4); send_lan_message(LOGENTRY, logline4); if (trx_control && (cqmode == S_P)) addspot(); hiscall[0] = '\\0'; comment[0] = '\\0'; strncpy(last_rst, his_rst, sizeof(last_rst)); his_rst[1] = '9'; my_rst[1] = '9'; } else { strncpy(lan_logline, lan_message + 2, 87); strcat(lan_logline, " "); if (cqwwm2 == 1) { if (lan_logline[0] != thisnode) lan_logline[79] = '*'; } lan_logline[87] = '\\0'; total = total + score2(lan_logline); addcall2(); store_qso(lan_logline); } if (from_lan) lan_mutex = 2; else lan_mutex = 1; scroll_log(); lan_mutex = 0; attron(modify_attr(COLOR_PAIR(NORMCOLOR))); if (!from_lan) mvprintw(12, 54, " "); attron(COLOR_PAIR(C_LOG) | A_STANDOUT); if (!from_lan) { mvprintw(7, 0, logline0); mvprintw(8, 0, logline1); mvprintw(9, 0, logline2); } mvprintw(10, 0, logline3); mvprintw(11, 0, logline4); refreshp(); attron(COLOR_PAIR(C_WINDOW)); mvprintw(12, 23, qsonrstr); if (no_rst) { mvaddstr(12, 44, "---"); mvaddstr(12, 49, "---"); } else { mvaddstr(12, 44, his_rst); mvaddstr(12, 49, my_rst); } sync(); if ((rit == 1) && (trx_control == 1)) outfreq = RESETRIT; block_part = 0; pthread_mutex_unlock(&disk_mutex); return (0); }
0
#include <pthread.h> struct pid_data{ pthread_mutex_t pid_mutex; pid_t pid; }; char buffer[1500]; int set_priority(int priority); int get_priority(); int message_server(); int main(int argc, char *argv[]) { printf("Welcome to the QNX Momentics IDE\\n"); int f_desc = shm_open("/dev/shmem/sharedpid", O_RDWR | O_CREAT, S_IRWXU); ftruncate(f_desc, (sizeof(struct pid_data))); struct pid_data* voidy = mmap(0, (sizeof(struct pid_data)), (PROT_READ | PROT_WRITE), MAP_SHARED, f_desc, 0); pthread_mutexattr_t mutey; pthread_mutexattr_init(&mutey); pthread_mutexattr_setpshared(&mutey, PTHREAD_PROCESS_SHARED); pthread_mutex_init(&voidy->pid_mutex, &mutey ); pthread_mutex_lock(&voidy->pid_mutex); voidy->pid = getpid(); printf("My pid is %d \\n", voidy->pid); pthread_mutex_unlock(&voidy->pid_mutex); int channelID = message_server(); return 0; } int message_server(){ set_priority(20); printf("I am now a server \\n\\n"); int channelID, clientID; channelID = ChannelCreate(0); struct _msg_info client_info; while(1){ printf("PRIORITY BEFORE: %i\\n", get_priority()); clientID = MsgReceive(channelID, &buffer, sizeof buffer, &client_info); printf("PRIORITY AFTER: %i\\n\\n", get_priority()); printf("CLIENT INFO: \\n"); printf("from client with ID: %d\\n", client_info.pid); printf("from process with ID: %d\\n", client_info.pid); printf("Received msg of length: %d\\n", client_info.msglen); printf("client sent: %c \\n\\n", buffer[0]); buffer[0] = 'S'; int someKindOfReturn; someKindOfReturn = MsgReply(clientID, EOK, buffer, sizeof buffer); } return channelID; } 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; }
1
#include <pthread.h> const char direction_array[]={'E','N','W','S'}; int direction_int(char ch) { switch(ch) { case 'e': return 0; case 'n': return 1; case 'w': return 2; case 's': return 3; default : return 0; } } pthread_mutex_t crossing[4]={PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER}; pthread_cond_t signal[4] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER}; pthread_cond_t queue[4] = {PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER,PTHREAD_COND_INITIALIZER}; pthread_mutex_t queueLock[4]={PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER , PTHREAD_MUTEX_INITIALIZER};; int wait[4]={0, 0, 0, 0}; int direction; int thread_number; }data; void arrive(int thr_num, int direction) { pthread_mutex_lock(&queueLock[direction]); while(wait[direction]) { pthread_cond_wait( &queue[direction], &queueLock[direction]); } wait[direction] = 1; pthread_mutex_unlock(&queueLock[direction]); printf("BAT %d from %c arrives at crossing\\n", thr_num, direction_array[direction]); } void cross(int direction) { pthread_mutex_lock(&crossing[direction]); pthread_mutex_lock(&crossing[(direction+1)%4]); pthread_mutex_lock(&queueLock[direction]); wait[direction] = 0; pthread_cond_signal( &queue[direction]); pthread_mutex_unlock(&queueLock[direction]); sleep(1); } void leave(int thr_num, int direction) { pthread_mutex_unlock(&crossing[direction]); pthread_mutex_unlock(&crossing[(direction+1)%4]); printf("BAT %d from %c leaving crossing\\n" , thr_num , direction_array[direction]); } void *BAT(void *arg) { data dt = *((data *)arg); free(arg); int direction = dt.direction; int thr_num = dt.thread_number; arrive(thr_num, direction); cross(direction); leave(thr_num, direction); } pthread_mutex_t check_mutex=PTHREAD_MUTEX_INITIALIZER; int check() { pthread_mutex_lock(&check_mutex); int t= (wait[0] && wait[1] && wait[2] && wait[3]); pthread_mutex_unlock(&check_mutex); return t; } void *MAN(void *arg) { int wait_flag = 1; while(1) { if(check() && wait_flag) { printf("DEADLOCK: BAT jam detected, signaling next to go\\n"); wait_flag=0; } if(!check()) { wait_flag=1; } } } void *BATMAN(void *arg) { char *sequence = (char *)arg; int seq_len = strlen(sequence); pthread_t man_thread; pthread_create(&man_thread, 0 , MAN , 0); pthread_t *bat_threads = (pthread_t *)malloc(sizeof(pthread_t) * seq_len); data *dt; for(int i=0; i < seq_len ; i++) { dt=(data *)malloc(sizeof(data)); dt->direction = direction_int(sequence[i]); dt->thread_number=i+1; pthread_create(&bat_threads[i], 0 , BAT ,(void *)dt); } for(int i=0; i < seq_len ; i++) pthread_join(bat_threads[i],0); } void init_shared_resource() { pthread_mutex_init(&check_mutex , 0); for(int i=0 ; i < 4 ; i++) { pthread_mutex_init(&crossing[i],0); pthread_cond_init(&signal[i],0); pthread_cond_init(&queue[i] , 0); pthread_mutex_init(&queueLock[i], 0); } } void delete_shared_resource() { pthread_mutex_destroy(&check_mutex); for(int i=0 ; i < 4 ; i++) { pthread_mutex_destroy(&crossing[i]); pthread_cond_destroy(&signal[i]); pthread_cond_destroy(&queue[i]); pthread_mutex_destroy(&queueLock[i]); } } int main(int argc , char *argv[]) { if(argc < 2) { printf("enter directions:\\n"); exit(0); } init_shared_resource(); pthread_t bat_threadID; pthread_create(&bat_threadID ,0 , BATMAN , argv[1]); pthread_join(bat_threadID, 0); delete_shared_resource(); exit(0); return 0; }
0