text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int sval;
int fval;
} Args;
long unsigned int thread_count;
pthread_mutex_t * mutex;
int *vet, nbins;
double max, min, h, *val;
double min_val(double * vet,int nval) {
int i;
double min;
min = FLT_MAX;
for(i=0;i<nval;i++) {
if(vet[i] < min)
min = vet[i];
}
return min;
}
double max_val(double * vet, int nval) {
int i;
double max;
max = FLT_MIN;
for(i=0;i<nval;i++) {
if(vet[i] > max)
max = vet[i];
}
return max;
}
void * count_parallel(void * count_args) {
Args * args = (Args *) count_args;
int i, j, count;
double min_t, max_t;
for(j=0;j<nbins;j++) {
count = 0;
min_t = min + j*h;
max_t = min + (j+1)*h;
for(i=args->sval; i<=args->fval; i++) {
if(val[i] <= max_t && val[i] > min_t) {
count++;
}
}
pthread_mutex_lock(&mutex[j]);
vet[j] += count;
pthread_mutex_unlock(&mutex[j]);
}
return 0;
}
int main(int argc, char * argv[]) {
int nval, i, group;
long unsigned int duracao, thread;
struct timeval start, end;
pthread_t* thread_handles;
Args * count_args;
scanf("%lu",&thread_count);
scanf("%d",&nval);
scanf("%d",&nbins);
val = (double *)malloc(nval*sizeof(double));
vet = (int *)malloc(nbins*sizeof(int));
mutex = (pthread_mutex_t *)malloc(nbins*sizeof(pthread_mutex_t));
thread_handles = (pthread_t*)malloc(thread_count*sizeof(pthread_t));
count_args = (Args *)malloc(thread_count*sizeof(Args));
for(i=0;i<nval;i++) {
scanf("%lf",&val[i]);
}
min = floor(min_val(val,nval));
max = ceil(max_val(val,nval));
h = (max - min)/nbins;
group = floor(nval/thread_count);
for(i=0; i<nbins;i++) {
pthread_mutex_init(&mutex[i], 0);
}
gettimeofday(&start, 0);
for(thread = 0; thread < thread_count - 1; thread++) {
count_args[thread].sval = thread*group;
count_args[thread].fval = (thread+1)*group - 1;
pthread_create(&thread_handles[thread], 0, count_parallel, &count_args[thread]);
}
count_args[thread].sval = thread*group;
count_args[thread].fval = (thread+1)*group - 1 + nval%thread_count;
pthread_create(&thread_handles[thread], 0, count_parallel, &count_args[thread]);
for(thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
gettimeofday(&end, 0);
duracao = ((end.tv_sec * 1000000 + end.tv_usec) -
(start.tv_sec * 1000000 + start.tv_usec));
printf("%.2lf",min);
for(i=1;i<=nbins;i++) {
printf(" %.2lf",min + h*i);
}
printf("\\n");
printf("%d",vet[0]);
for(i=1;i<nbins;i++) {
printf(" %d",vet[i]);
}
printf("\\n");
printf("%lu\\n",duracao);
free(vet);
free(val);
free(thread_handles);
for(i=0; i<nbins;i++) {
pthread_mutex_destroy(&mutex[i]);
}
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
struct params
{
size_t start;
size_t size;
char data[10000];
};
size_t size;
size_t current_position = 0;
FILE* fp;
FILE* write_fp;
char cnt = 1;
short count = 0;
pthread_t threads[20];
int id_threads[20];
params_t problems[20];
char buff[10000];
pthread_cond_t cond_start_work;
pthread_cond_t cond_ready;
pthread_cond_t cond_exit;
int start_flag = 0;
int ready;
int main_is_break = 0;
int main_signal_flag = 0;
int get_new_task = 0;
int get_new_thread = 0;
size_t lock_cnt = 0;
pthread_mutex_t mutex_write;
pthread_mutex_t start_work;
pthread_mutex_t safe_ready;
pthread_mutex_t mutex_exit;
void * body(void * param)
{
int me_num = *(int*)param;;
char swap_buff;
char out_cond = 0;
size_t i = 0;
size_t j;
while(1)
{
pthread_mutex_lock(&mutex_exit);
++lock_cnt;
if(main_is_break == 1 && lock_cnt == 20)
pthread_cond_signal(&cond_exit);
pthread_mutex_unlock(&mutex_exit);
pthread_mutex_lock(&start_work);
pthread_mutex_lock(&safe_ready);
get_new_thread = 1;
if(get_new_task == 0)
{
pthread_cond_wait(&cond_ready, &safe_ready);
}
get_new_task = 0;
problems[me_num].start = current_position;
i = 0;
for(;i < size;++i)
problems[me_num].data[i] = buff[i];
problems[me_num].size = size;
pthread_cond_signal(&cond_ready);
pthread_mutex_unlock(&start_work);
pthread_mutex_unlock(&safe_ready);
pthread_mutex_lock(&mutex_exit);
--lock_cnt;
pthread_mutex_unlock(&mutex_exit);
for(i = 0;i < problems[me_num].size - 1;++i)
{
for(j = 0;j < problems[me_num].size - i - 1;++j)
{
if(problems[me_num].data[j] > problems[me_num].data[j+1])
{
swap_buff = problems[me_num].data[j+1];
problems[me_num].data[j + 1] = problems[me_num].data[j];
problems[me_num].data[j] = swap_buff;
}
}
}
pthread_mutex_lock(&mutex_write);
fwrite(problems[me_num].data, 1, problems[me_num].size, write_fp);
printf("WRITE\\n");
pthread_mutex_unlock(&mutex_write);
}
}
int main(int argc, char** argv)
{
int flg;
int i = 0;
fp = fopen(argv[1], "rb+");
write_fp = fopen(argv[2], "wb+");
if(!fp || !write_fp)
{
printf("ERROR: can't open file\\n");
exit(1);
}
for(;i < 20; ++i)
{
id_threads[i] = i;
pthread_create(threads + i, 0, body, &id_threads[i]);
}
while(1)
{
size = fread(buff, 1,10000, fp);
printf("size: %d\\n", size);
if (size == 0)
break;
current_position += size;
pthread_mutex_lock(&safe_ready);
get_new_task = 1;
if(get_new_thread == 0)
{
pthread_cond_wait(&cond_ready, &safe_ready);
}
get_new_thread = 0;
get_new_task = 0;
pthread_cond_signal(&cond_ready);
pthread_mutex_unlock(&safe_ready);
}
pthread_mutex_lock(&mutex_exit);
main_is_break = 1;
if(lock_cnt != 20)
pthread_cond_wait(&cond_exit, &mutex_exit);
pthread_mutex_unlock(&mutex_exit);
i = 0;
for(;i < 20;++i)
{
pthread_cancel(threads[i]);
}
fclose(fp);
fclose(write_fp);
return 0;
}
| 0
|
#include <pthread.h>
int card_channel[100];
char channelstr[CHANNEL_NUMBER][3]= {
"1","2","3","4","5","6","7",
"8","9","10","11","12","13"};
static int current_channel = 0;
static void *process_function(void *);
static void process_function_actual(int job_type);
static int process_judege(struct Job *job);
void change_channel_init(){
register_job(JOB_TYPE_CHANGE_CHANNEL,process_function,process_judege,CALL_BY_TIMER);
}
static void *process_function(void *arg){
int job_type = JOB_TYPE_CHANGE_CHANNEL;
while(1){
pthread_mutex_lock(&(job_mutex_for_cond[job_type]));
pthread_cond_wait(&(job_cond[job_type]),&(job_mutex_for_cond[job_type]));
pthread_mutex_unlock(&(job_mutex_for_cond[job_type]));
process_function_actual(job_type);
}
}
static void process_function_actual(int job_type){
struct Job_Queue private_jobs;
private_jobs.front = 0;
private_jobs.rear = 0;
get_jobs(job_type,&private_jobs);
struct Job current_job;
time_t nowtime;
struct tcp_stream *a_tcp;
while(!jobqueue_isEmpty(&private_jobs)){
}
}
static int process_judege(struct Job *job){
job->current_channel = current_channel;
current_channel = (current_channel+1) % CHANNEL_NUMBER;
return 1;
}
| 1
|
#include <pthread.h>
struct job {
struct job* next;
};
struct job* job_queue;
extern void process_job (struct job*);
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t job_queue_count;
void initialize_job_queue ()
{
job_queue = 0;
sem_init (&job_queue_count, 0, 0);
}
void* thread_function (void* arg)
{
while (1) {
struct job* next_job;
sem_wait (&job_queue_count);
pthread_mutex_lock (&job_queue_mutex);
next_job = job_queue;
job_queue = job_queue->next;
pthread_mutex_unlock (&job_queue_mutex);
process_job (next_job);
free (next_job);
}
return 0;
}
void enqueue_job ( )
{
struct job* new_job;
new_job = (struct job*) malloc (sizeof (struct job));
pthread_mutex_lock (&job_queue_mutex);
new_job->next = job_queue;
job_queue = new_job;
sem_post (&job_queue_count);
pthread_mutex_unlock (&job_queue_mutex);
}
| 0
|
#include <pthread.h>
struct app_txn_array app_admin_confirm_array;
struct app_txn_array app_admin_request_array;
struct app_txn_array app_best_sellers_array;
struct app_txn_array app_buy_confirm_array;
struct app_txn_array app_buy_request_array;
struct app_txn_array app_home_array;
struct app_txn_array app_new_products_array;
struct app_txn_array app_order_display_array;
struct app_txn_array app_order_inquiry_array;
struct app_txn_array app_product_detail_array;
struct app_txn_array app_search_request_array;
struct app_txn_array app_search_results_array;
struct app_txn_array app_shopping_cart_array;
void init_app_txn_array(struct app_txn_array *txn_array, int ArraySize)
{
int i;
pthread_mutex_init(&txn_array->txn_array_mutex, 0);
txn_array->size = ArraySize;
txn_array->pin = (int *) malloc(sizeof(int) * ArraySize);
txn_array->data_array = (union interaction_data_t *)
malloc(sizeof(union interaction_data_t) * ArraySize);
txn_array->txn_result = (int *) malloc(sizeof(int) * ArraySize);
for (i = 0; i < txn_array->size; i++)
{
txn_array->pin[i] = 0;
bzero(&txn_array->data_array[i], sizeof(union interaction_data_t));
txn_array->txn_result[i] = OK;
}
}
int PinSlot(struct app_txn_array *txn_array)
{
int i;
pthread_mutex_lock(&txn_array->txn_array_mutex);
for (i = 0; i < txn_array->size; i++)
{
if (txn_array->pin[i] == 0)
{
txn_array->pin[i] = 1;
pthread_mutex_unlock(&txn_array->txn_array_mutex);
return i;
}
}
pthread_mutex_unlock(&txn_array->txn_array_mutex);
return -1;
}
int FreeSlot(struct app_txn_array *txn_array, int SlotID)
{
pthread_mutex_lock(&txn_array->txn_array_mutex);
txn_array->pin[SlotID] = 0;
bzero(&txn_array->data_array[SlotID], sizeof(union interaction_data_t));
pthread_mutex_unlock(&txn_array->txn_array_mutex);
return 1;
}
| 1
|
#include <pthread.h>
pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER;
struct arg_struct{
int tI;
char* host;
int portNum;
FILE * file;
int inc;
};
void* client(void* n){
struct arg_struct *args = n;
int client_fd;
int rec;
char rec_buf[1024];
struct sockaddr_in serv_addr;
FILE* toWrite = args->file;
char send_buf[128];
sprintf(send_buf, "%d", args->tI);
while(1){
if((client_fd = socket(AF_INET, SOCK_STREAM, 0))<0){
printf("\\n Could not create socket \\n");
return;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(args->portNum);
serv_addr.sin_addr.s_addr = inet_addr(args->host);
if(connect(client_fd, (struct sockaddr *)&serv_addr,sizeof(serv_addr))<0){
printf("Could not connect \\n");
return;
}
send(client_fd, send_buf, 128, 0);
rec = recv(client_fd, rec_buf, sizeof(rec_buf), 0);
if(rec<=0){
break;
}
if(rec<1024){
char rec_buf_2[rec];
strncpy (rec_buf_2,rec_buf, rec);
fseek(args->file, args->tI * 1024, 0);
fwrite(rec_buf_2, rec, 1,args->file);
break;
}
pthread_mutex_lock(&myMutex);
fseek(args->file, args->tI * 1024, 0);
fwrite(rec_buf, 1024, 1,args->file);
pthread_mutex_unlock(&myMutex);
args->tI = args->tI + args->inc;
sprintf(send_buf, "%d", args->tI);
close(client_fd);
}
}
int main(int argc, char *argv[]){
if (argc < 3) {
printf("Need to supply a host and port!\\n");
exit(0);
}
int numOf = (argc-1)/2;
struct arg_struct args[numOf];
pthread_t threads[numOf];
FILE *f;
f = fopen("output.txt", "w");
int i = 0;
int j = 0;
for(i=1; i<=numOf*2; i=i+2){
args[j].host = argv[i];
j++;
}
j=0;
for(i=2; i<=(numOf*2)+1; i=i+2){
args[j].portNum = atoi(argv[i]);
j++;
}
for(i = 0; i<numOf; i++){
args[i].tI = i;
args[i].file = f;
args[i].inc = numOf;
pthread_create(&threads[i], 0, &client, (void *)&args[i]);
}
for(i=0; i<numOf; i++){
pthread_join(threads[i], 0);
}
fclose(f);
return 0;
}
| 0
|
#include <pthread.h>
char mybuf[25];
pthread_mutex_t my_lock;
sem_t s_signal;
void first(void *firstarg ) {
sleep(1);
fprintf(stderr, "First thread executing\\n");
pthread_mutex_lock(&my_lock);
sprintf(&mybuf[0], "Hi CSC 615\\n");
pthread_mutex_unlock(&my_lock);
sem_post(&s_signal);
}
void second(void *secondarg) {
fprintf(stderr, "Second thread executing\\n");
sem_wait(&s_signal);
pthread_mutex_lock(&my_lock);
fprintf(stderr, &mybuf[0], sizeof(mybuf));
pthread_mutex_unlock(&my_lock);
}
main() {
int retvalue;
pthread_t tid_first, tid_second;
void *arg;
fprintf(stderr,"Main Program executing\\n");
if ((retvalue = pthread_mutex_init(&my_lock,0)) < 0) {
perror("Can't initialize mutex");
exit(-1);
}
sem_init(&s_signal,0,0);
if ((retvalue=pthread_create(&tid_first,0, (void *)first, arg)) < 0){
perror("Can't create first thread");
exit(-1);
}
fprintf(stderr,"First Thread Created\\n");
if ((retvalue=pthread_create(&tid_second,0, (void *)second, arg)) < 0) exit(-1);
fprintf(stderr,"Second Thread Created\\n");
fprintf(stderr,"Waiting for first thread to exit\\n");
pthread_join(tid_first,0);
fprintf(stderr,"Waiting for second thread to exit\\n");
pthread_join(tid_second,0);
fprintf(stderr,"Main routine exiting\\n");
}
| 1
|
#include <pthread.h>
int pid;
int state;
int rounds;
int num_philos;
int handedness;
pthread_mutex_t** forks;
} Philosopher;
void doActivity(int activity,Philosopher* p,unsigned* seed)
{
p->state = activity;
double v = ((double)rand_r(seed)) / 32767 * 5.0;
usleep(v);
}
int dining(Philosopher* philo){
pthread_mutex_t** forks = philo->forks;
int counter = 0;
unsigned seed = (unsigned)pthread_self();
while(counter < philo->rounds){
switch(philo->state){
case 0:
printf("P[%d] Thinking\\n", philo->pid);
doActivity(1, philo, &seed);
break;
case 1:
doActivity(2, philo, &seed);
if(philo->pid % 2){
pthread_mutex_lock(forks[philo->pid]);
pthread_mutex_lock(forks[ (philo->pid+1) % philo->num_philos ]);
}else{
pthread_mutex_lock(forks[ (philo->pid+1) % philo->num_philos ]);
pthread_mutex_lock(forks[philo->pid]);
}
printf("P[%d] Hungry\\n", philo->pid);
break;
case 2:
printf("P[%d] Eating\\n", philo->pid);
doActivity(0, philo, &seed);
if(philo->pid % 2){
pthread_mutex_unlock(forks[ (philo->pid+1) % philo->num_philos ]);
pthread_mutex_unlock(forks[philo->pid]);
}else{
pthread_mutex_unlock(forks[philo->pid]);
pthread_mutex_unlock(forks[ (philo->pid+1) % philo->num_philos ]);
}
counter++;
break;
}
}
return 1;
}
int main(int argc,char* argv[])
{
int n = atoi(argv[1]);
int c = atoi(argv[2]);
if(argc != 3){
printf("Incorrent Parameters\\n");
return -1;
}
if(n < 2){
printf("You don't have enough Philosophers\\n");
return -1;
}
int i;
pthread_t tids[n];
Philosopher** philos = malloc(sizeof(Philosopher*) * n);
pthread_mutex_t** forks = malloc(sizeof(pthread_mutex_t*) * n);
for(i = 0; i < n; i++){
forks[i] = malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(forks[i], 0);
}
for(i = 0; i < n; i++){
philos[i] = malloc(sizeof(Philosopher) * n);
philos[i]->pid = i;
philos[i]->state = 0;
philos[i]->rounds = c;
philos[i]->num_philos = n;
philos[i]->forks = forks;
pthread_create(&tids[i],0,(void*(*)(void*))dining,(void*)philos[i]);
}
for(i = 0; i < n; i++){
pthread_join(tids[i],0);
}
for(i = 0; i < n; i++){
pthread_mutex_destroy(forks[i]);
free(forks[i]);
free(philos[i]);
}
free(forks);
free(philos);
return 0;
}
| 0
|
#include <pthread.h>
struct Nodo *siguiente;
struct Nodo *anterior;
char valor;
}Elemento;
int tamano;
Elemento *inicio;
Elemento *fin;
}Lista;
Lista *list;
int insercion(Lista *lista, char dato);
int supresion(Lista *lista, int pos);
void *consumidor(void *arg);
void *productor(void *arg);
sem_t nodosUsados;
sem_t nodosVacios;
pthread_mutex_t mymutex;
int main() {
sem_init(&nodosUsados, 0, 0);
sem_init(&nodosVacios, 0, 100);
pthread_mutex_init(&mymutex, 0);
pthread_t thread_productor;
pthread_t thread_consumidor;
list->inicio = 0;
list->fin = 0;
pthread_create(&thread_productor, 0, productor, 0);
pthread_create(&thread_consumidor, 0, consumidor, 0);
pthread_join(thread_productor, 0);
pthread_join(thread_consumidor, 0);
pthread_exit(0);
}
int insercion(Lista *lista, char dato) {
pthread_mutex_lock(&mymutex);
Elemento *nuevo = malloc(sizeof(Elemento));
nuevo->valor = dato;
sem_wait(&nodosVacios);
if(lista->inicio == 0)
nuevo->siguiente = 0;
nuevo->anterior = 0;
lista->inicio = nuevo;
lista->fin = nuevo;
lista->fin = nuevo;
nuevo->anterior = 0;
nuevo->siguiente = lista->fin->siguiente;
lista->tamano += 1;
printf("Nodo : %c", nuevo->valor);
sem_post(&nodosUsados);
pthread_mutex_unlock(&mymutex);
return lista->tamano;
}
int supresion(Lista *lista, int pos) {
pthread_mutex_lock(&mymutex);
sem_wait(&nodosUsados);
Elemento *temp = lista->fin;
lista->fin->siguiente = lista->fin;
lista->tamano -= 1;
free(temp);
sem_wait(&nodosVacios);
pthread_mutex_unlock(&mymutex);
return lista->tamano;
}
void *consumidor(void *arg) {
while(1){
int n = supresion(list, 0);
}
sleep(1);
}
void *productor(void *arg) {
while(1){
char dato = 'a';
int n = insercion(list, dato);
}
sleep(1);
}
| 1
|
#include <pthread.h>
extern int makethread(void *(*)(void *), void *);
struct to_info {
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void clock_gettime(int id, struct timespec *tsp)
{
struct timeval tv;
gettimeofday(&tv, 0);
tsp->tv_sec = tv.tv_sec;
tsp->tv_nsec = tv.tv_usec * 1000;
}
void * timeout_helper(void *arg)
{
struct to_info *tip;
tip = (struct to_info *)arg;
nanosleep((&tip->to_wait), (0));
(*tip->to_fn)(tip->to_arg);
free(arg);
return(0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(0, &now);
if ((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)) {
tip = malloc(sizeof(struct to_info));
if (tip != 0) {
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if (when->tv_nsec >= now.tv_nsec) {
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
} else {
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makethread(timeout_helper, (void *)tip);
if (err == 0)
return;
else
free(tip);
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
int main(void)
{
int err, condition, arg;
struct timespec when;
if ((err = pthread_mutexattr_init(&attr)) != 0)
err_exit(err, "pthread_mutexattr_init failed");
if ((err = pthread_mutexattr_settype(&attr,
PTHREAD_MUTEX_RECURSIVE)) != 0)
err_exit(err, "can't set recursive type");
if ((err = pthread_mutex_init(&mutex, &attr)) != 0)
err_exit(err, "can't create recursive mutex");
pthread_mutex_lock(&mutex);
if (condition) {
clock_gettime(0, &when);
when.tv_sec += 10;
timeout(&when, retry, (void *)((unsigned long) arg));
}
pthread_mutex_unlock(&mutex);
exit(0);
}
| 0
|
#include <pthread.h>
struct Request;
struct Msg;
struct Request
{
int pid;
};
struct Msg
{
int pid;
char data[512];
};
char *servername = "server1";
char *famfifo = "server1";
int ffd;
int semid;
int numclients = 0;
int ifd,ofd;
int cfd[10][2];
struct pollfd pfd[10];
pthread_t tid;
pthread_mutex_t mut;
inline int semGet(int numsem)
{
int semkey = ftok("/tmp",1024);
int semid = semget(1024,numsem,IPC_CREAT|0666);
assert(semid != -1);
return semid;
}
void genearteFifo(int pid)
{
int ret;
char buff[512];
sprintf(buff,"%d.out",pid);
ret = mkfifo(buff,0666);
assert(ret != -1);
ofd = open(buff,O_RDWR);
assert(ofd != -1);
sprintf(buff,"%d.in",pid);
ret = mkfifo(buff,0666);
assert(ret != -1);
ifd = open(buff,O_RDWR);
assert(ifd != -1);
return;
}
void* pollFifo(void *args)
{
setbuf(stdout, 0);
int i,j;
struct Msg msg;
while(1)
{
pthread_mutex_lock(&mut);
int status = poll(pfd,numclients,0);
if(status > 0)
{
for(i=0;i<numclients;i++)
{
if(pfd[i].revents == POLLIN)
{
read(cfd[i][1],&msg,(sizeof(struct Msg)));
printf("MSG received from client (%d): %s\\n",msg.pid,msg.data);
for(j=0;j<numclients;j++)
{
if(j!=i)
{
write(cfd[j][0],&msg,(sizeof(struct Msg)));
}
}
}
}
}
pthread_mutex_unlock(&mut);
}
}
int main(int argc, char const *argv[])
{
setbuf(stdout, 0);
printf("%s created============\\n",servername);
semid = semGet(2);
printf("semid: %d\\n",semid);
unsigned short arr[] = {1,0};
semInit(semid,arr,2);
unlink(famfifo);
int ret = mkfifo(famfifo,0666);
assert(ret != -1);
ffd = open(famfifo,O_RDWR);
assert(ffd != -1);
assert(pthread_mutex_init(&mut,0) == 0);
assert(pthread_create(&tid,0,pollFifo,0) == 0);
struct Request req;
int i;
while(1)
{
semWait(semid,1);
read(ffd,&req,(sizeof(struct Request)));
printf("Request received from: %d\\n",req.pid);
genearteFifo(req.pid);
cfd[numclients][1] = ifd;
cfd[numclients][0] = ofd;
pfd[numclients].fd = ifd;
pfd[numclients].events = POLLIN;
pfd[numclients].revents = 0;
pthread_mutex_lock(&mut);
numclients++;
printf("numclients %d\\n",numclients);
pthread_mutex_unlock(&mut);
semSignal(semid,1);
}
return 0;
}
| 1
|
#include <pthread.h>
int VALEUR;
pthread_mutex_t mutex;
void traitementLong() {
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 10;
nanosleep(&ts, 0);
}
void* f0(void* _p) {
int i;
for(i = 0; i < 1000; i++) {
pthread_mutex_lock(&mutex);
int x = VALEUR;
traitementLong();
VALEUR = x + 1;
pthread_mutex_unlock(&mutex);
}
puts("f0_fini");
return 0;
}
void* f1(void* _p) {
int i;
for(i = 0; i < 1000; i++) {
pthread_mutex_lock(&mutex);
int x = VALEUR;
traitementLong();
VALEUR = x + 2;
pthread_mutex_unlock(&mutex);
}
puts("f1_fini");
return 0;
}
int main() {
pthread_mutex_init(&mutex, 0);
pthread_t pid[2];
pthread_create(&pid[0], 0, f0, 0);
pthread_create(&pid[1], 0, f1, 0);
pthread_join(pid[0], 0);
pthread_join(pid[1], 0);
pthread_mutex_destroy(&mutex);
printf("VALEUR=%d\\n", VALEUR);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t myMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t game_thread, time_thread;
int game_return, time_return;
struct socketThread {
pthread_t thread;
int inUse;
};
struct socketThread socketThreads[5];
void waitFor (unsigned int secs) {
unsigned int retTime = time(0) + secs;
while (time(0) < retTime);
}
void *PlayGame ()
{
int input1, input2;
printf("enter the first integer:\\n");
scanf("%d",&input1);
printf("enter the second integer:\\n");
scanf("%d", &input2);
printf("sum of %d and %d is: %d", input1, input2, input1 + input2);
pthread_mutex_unlock(&myMutex);
}
int main()
{
int threadCount;
int i;
for (i = 0; i < 5; ++i) {
if (!socketThreads[i].inUse) {
pthread_mutex_lock(&myMutex);
socketThreads[i].inUse = 1;
game_return = pthread_create(&socketThreads[i].thread, 0, PlayGame, 0);
}
else {
threadCount++;
}
}
pthread_join(socketThreads[i].thread,0);
socketThreads[i].inUse = 0;
printf("Program over\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int iter = 1;
int odd = 1;
static void *third_thread_func()
{
while(iter <= 100)
{
if(!odd)
{
pthread_mutex_lock(&mutex);
printf("Thread three: %d\\n", iter++);
odd = 1;
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(0);
}
static void *second_thread_func()
{
while(iter < 100)
{
if(odd)
{
pthread_mutex_lock(&mutex);
printf("Thread two: %d\\n", iter++);
odd = 0;
pthread_mutex_unlock(&mutex);
}
}
pthread_exit(0);
}
static void *first_thread_func()
{
pthread_t second_thread, third_thread;
pthread_create(&second_thread, 0, second_thread_func, 0);
pthread_create(&third_thread, 0, third_thread_func, 0);
pthread_join(second_thread, 0);
pthread_join(third_thread, 0);
pthread_exit(0);
}
int main()
{
pthread_t thread;
pthread_mutex_init(&mutex, 0);
pthread_create(&thread, 0, first_thread_func, 0);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtx;
static pthread_cond_t cv;
static uint8_t cur_count = 0;
static uint8_t total_count = 0;
static const uint8_t TOTAL_COUNT_THRESHOLD = 100;
static void *
consumer_fn(void *ctx)
{
uint8_t id = (uint8_t) ctx;
printf("%s: starting thread %u\\n", __func__, id);
pthread_mutex_lock(&mtx);
while ((total_count <= TOTAL_COUNT_THRESHOLD) || (0 != cur_count)) {
while ((0 == cur_count) && (total_count <= TOTAL_COUNT_THRESHOLD)) {
pthread_cond_wait(&cv, &mtx);
}
if (0 != cur_count) {
--cur_count;
printf("%s: thread %u consumed one, cur_count=%u (total=%u)\\n",
__func__, id, cur_count, total_count);
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&mtx);
pthread_mutex_lock(&mtx);
}
}
pthread_mutex_unlock(&mtx);
printf("%s: finishing thread %u\\n", __func__, id);
pthread_exit(0);
}
static void *
producer_fn(void *ctx)
{
uint8_t id = (uint8_t) ctx;
uint8_t count;
static const uint8_t MAX_PER_RND = 10;
printf("%s: starting thread %u\\n", __func__, id);
pthread_mutex_lock(&mtx);
while (total_count <= TOTAL_COUNT_THRESHOLD) {
if (0 == cur_count) {
count = (rand() % MAX_PER_RND);
cur_count += count;
total_count += cur_count;
printf("%s: thread %u produced %u (total=%u)\\n", __func__, id,
count, total_count);
pthread_cond_broadcast(&cv);
}
while (cur_count > 0) {
pthread_cond_wait(&cv, &mtx);
}
}
pthread_mutex_unlock(&mtx);
printf("%s: finishing thread %u\\n", __func__, id);
pthread_exit(0);
}
int
main(int argc, char **argv)
{
static const uint8_t PRODUCER_THREAD_COUNT = 5;
static const uint8_t CONSUMER_THREAD_COUNT = 10;
pthread_t producer_threads[PRODUCER_THREAD_COUNT];
pthread_t consumer_threads[CONSUMER_THREAD_COUNT];
uint8_t i;
srand(42);
pthread_mutex_init(&mtx, 0);
pthread_cond_init(&cv, 0);
for (i = 0; i < PRODUCER_THREAD_COUNT; ++i) {
pthread_create(&producer_threads[i], 0, producer_fn,
(void *) (uintptr_t) (i + 1));
}
for (i = 0; i < CONSUMER_THREAD_COUNT; ++i) {
pthread_create(&consumer_threads[i], 0, consumer_fn,
(void *) (uintptr_t) (i + 1));
}
for (i = 0; i < PRODUCER_THREAD_COUNT; ++i) {
pthread_join(producer_threads[i], 0);
}
printf("%s: %u producer threads finished\\n", __func__,
PRODUCER_THREAD_COUNT);
for (i = 0; i < CONSUMER_THREAD_COUNT; ++i) {
pthread_join(consumer_threads[i], 0);
}
printf("%s: %u consumer threads finished\\n", __func__,
CONSUMER_THREAD_COUNT);
printf("%s: total=%u, cur_count=%u\\n", __func__, total_count, cur_count);
pthread_mutex_destroy(&mtx);
pthread_cond_destroy(&cv);
return 0;
}
| 1
|
#include <pthread.h>
struct tmfs_worker {
struct tmfs_worker *prev;
struct tmfs_worker *next;
pthread_t thread_id;
size_t bufsize;
char *buf;
struct tmfs_mt *mt;
};
struct tmfs_mt {
pthread_mutex_t lock;
int numworker;
int numavail;
struct tmfs_session *se;
struct tmfs_chan *prevch;
struct tmfs_worker main;
sem_t finish;
int exit;
int error;
};
static void list_add_worker(struct tmfs_worker *w, struct tmfs_worker *next)
{
struct tmfs_worker *prev = next->prev;
w->next = next;
w->prev = prev;
prev->next = w;
next->prev = w;
}
static void list_del_worker(struct tmfs_worker *w)
{
struct tmfs_worker *prev = w->prev;
struct tmfs_worker *next = w->next;
prev->next = next;
next->prev = prev;
}
static int tmfs_loop_start_thread(struct tmfs_mt *mt);
static void *tmfs_do_work(void *data)
{
struct tmfs_worker *w = (struct tmfs_worker *) data;
struct tmfs_mt *mt = w->mt;
while (!tmfs_session_exited(mt->se)) {
int isforget = 0;
struct tmfs_chan *ch = mt->prevch;
struct tmfs_buf fbuf = {
.mem = w->buf,
.size = w->bufsize,
};
int res;
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
res = tmfs_session_receive_buf(mt->se, &fbuf, &ch);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
if (res == -EINTR)
continue;
if (res <= 0) {
if (res < 0) {
tmfs_session_exit(mt->se);
mt->error = -1;
}
break;
}
pthread_mutex_lock(&mt->lock);
if (mt->exit) {
pthread_mutex_unlock(&mt->lock);
return 0;
}
if (!(fbuf.flags & TMFS_BUF_IS_FD)) {
struct tmfs_in_header *in = fbuf.mem;
if (in->opcode == TMFS_FORGET ||
in->opcode == TMFS_BATCH_FORGET)
isforget = 1;
}
if (!isforget)
mt->numavail--;
if (mt->numavail == 0)
tmfs_loop_start_thread(mt);
pthread_mutex_unlock(&mt->lock);
tmfs_session_process_buf(mt->se, &fbuf, ch);
pthread_mutex_lock(&mt->lock);
if (!isforget)
mt->numavail++;
if (mt->numavail > 10) {
if (mt->exit) {
pthread_mutex_unlock(&mt->lock);
return 0;
}
list_del_worker(w);
mt->numavail--;
mt->numworker--;
pthread_mutex_unlock(&mt->lock);
pthread_detach(w->thread_id);
free(w->buf);
free(w);
return 0;
}
pthread_mutex_unlock(&mt->lock);
}
sem_post(&mt->finish);
return 0;
}
int tmfs_start_thread(pthread_t *thread_id, void *(*func)(void *), void *arg)
{
sigset_t oldset;
sigset_t newset;
int res;
pthread_attr_t attr;
char *stack_size;
pthread_attr_init(&attr);
stack_size = getenv("TMFS_THREAD_STACK");
if (stack_size && pthread_attr_setstacksize(&attr, atoi(stack_size)))
fprintf(stderr, "tmfs: invalid stack size: %s\\n", stack_size);
sigemptyset(&newset);
sigaddset(&newset, SIGTERM);
sigaddset(&newset, SIGINT);
sigaddset(&newset, SIGHUP);
sigaddset(&newset, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &newset, &oldset);
res = pthread_create(thread_id, &attr, func, arg);
pthread_sigmask(SIG_SETMASK, &oldset, 0);
pthread_attr_destroy(&attr);
if (res != 0) {
fprintf(stderr, "tmfs: error creating thread: %s\\n",
strerror(res));
return -1;
}
return 0;
}
static int tmfs_loop_start_thread(struct tmfs_mt *mt)
{
int res;
struct tmfs_worker *w = malloc(sizeof(struct tmfs_worker));
if (!w) {
fprintf(stderr, "tmfs: failed to allocate worker structure\\n");
return -1;
}
memset(w, 0, sizeof(struct tmfs_worker));
w->bufsize = tmfs_chan_bufsize(mt->prevch);
w->buf = malloc(w->bufsize);
w->mt = mt;
if (!w->buf) {
fprintf(stderr, "tmfs: failed to allocate read buffer\\n");
free(w);
return -1;
}
res = tmfs_start_thread(&w->thread_id, tmfs_do_work, w);
if (res == -1) {
free(w->buf);
free(w);
return -1;
}
list_add_worker(w, &mt->main);
mt->numavail ++;
mt->numworker ++;
return 0;
}
static void tmfs_join_worker(struct tmfs_mt *mt, struct tmfs_worker *w)
{
pthread_join(w->thread_id, 0);
pthread_mutex_lock(&mt->lock);
list_del_worker(w);
pthread_mutex_unlock(&mt->lock);
free(w->buf);
free(w);
}
int tmfs_session_loop_mt(struct tmfs_session *se)
{
int err;
struct tmfs_mt mt;
struct tmfs_worker *w;
memset(&mt, 0, sizeof(struct tmfs_mt));
mt.se = se;
mt.prevch = tmfs_session_next_chan(se, 0);
mt.error = 0;
mt.numworker = 0;
mt.numavail = 0;
mt.main.thread_id = pthread_self();
mt.main.prev = mt.main.next = &mt.main;
sem_init(&mt.finish, 0, 0);
tmfs_mutex_init(&mt.lock);
pthread_mutex_lock(&mt.lock);
err = tmfs_loop_start_thread(&mt);
pthread_mutex_unlock(&mt.lock);
if (!err) {
while (!tmfs_session_exited(se))
sem_wait(&mt.finish);
pthread_mutex_lock(&mt.lock);
for (w = mt.main.next; w != &mt.main; w = w->next)
pthread_cancel(w->thread_id);
mt.exit = 1;
pthread_mutex_unlock(&mt.lock);
while (mt.main.next != &mt.main)
tmfs_join_worker(&mt, mt.main.next);
err = mt.error;
}
pthread_mutex_destroy(&mt.lock);
sem_destroy(&mt.finish);
tmfs_session_reset(se);
return err;
}
| 0
|
#include <pthread.h>
sem_t empty_pot,full_pot;
static pthread_mutex_t servings_mutex;
static pthread_mutex_t print_mutex;
static int servings=15;
void *Savage(void *id)
{
int savage_id=*(int *)id;
while(1)
{
pthread_mutex_lock(&servings_mutex);
if(servings==0)
{
sem_post(&empty_pot);
printf("\\nSavage %d signalled the cook\\n", savage_id);
sem_wait(&full_pot);
servings=15;
}
servings--;
printf("Servings--->%d\\n", servings);
pthread_mutex_lock(&print_mutex);
printf("Savage %d is eating\\n", savage_id);
pthread_mutex_unlock(&print_mutex);
pthread_mutex_unlock(&servings_mutex);
sleep(2);
pthread_mutex_lock(&print_mutex);
printf("Savage %d is DONE eating\\n", savage_id);
pthread_mutex_unlock(&print_mutex);
}
pthread_exit(0);
}
void Cook(void *cid)
{
while(1)
{
sem_wait(&empty_pot);
printf("\\nCook filled the pot\\n\\n");
sem_post(&full_pot);
}
pthread_exit(0);
}
int main(void)
{
int i, id[3];
pthread_t tid[3];
pthread_mutex_init(&servings_mutex,0);
pthread_mutex_init(&print_mutex,0);
sem_init(&empty_pot, 0, 0);
sem_init(&full_pot, 0, 0);
for (i = 0; i < 3; ++i)
{
id[i]=i;
pthread_create(&tid[i],0,(void *)Savage,(void *)&id[i]);
}
pthread_create(&tid[i],0,(void *)Cook,(void *)&id[i]);
for (i=0; i<3; i++)
pthread_join(tid[i], 0);
pthread_join(tid[i],0);
return(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * thread1(void *);
void * thread2(void *);
volatile int i;
int main(int argc ,char *argv[])
{
pthread_t tid1 , tid2;
pthread_create(&tid1 , 0 , thread1 , 0);
pthread_create(&tid2 , 0 , thread2 , 0);
pthread_join(tid1 , 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void * thread1(void * arg)
{
for(i = 1 ; i < 9 ; i++)
{
pthread_mutex_lock(&mutex);
printf("thread1 start:\\n");
if(i % 3 == 0)
{
pthread_cond_signal(&cond);
}
printf("thread1 : %d\\n" , i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void * thread2(void * arg)
{
while(i < 9)
{
pthread_mutex_lock(&mutex);
printf("thread2 start:\\n");
if(i % 3 != 0)
{
pthread_cond_wait(&cond , &mutex);
}
printf("thread2 : %d\\n", i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 0
|
#include <pthread.h>
void error(const char * message)
{
fprintf(stderr, "%s\\n", message);
exit(1);
}
static const struct stream_defn * const stream_defns[] = {
&mem_stream,
&pipe_stream,
&tcp_stream,
&unix_stream,
};
struct xfer_data {
struct timespec tstamp;
unsigned int canary;
char payload[];
};
struct run_config {
const struct stream_defn * stream;
size_t xfersz;
};
static int config_run(int argc, char ** argv, struct run_config * cfg)
{
unsigned int i;
if (argc == 3) {
const char * input;
const struct stream_defn * stream;
char * end;
unsigned long xfersz;
input = argv[1];
stream = 0;
for (i = 0; i < sizeof(stream_defns) / sizeof(*stream_defns); i++)
if (strcmp(stream_defns[i]->name, input) == 0)
stream = stream_defns[i];
if (stream == 0) {
printf("%s is not a valid stream type\\n", input);
goto usage;
}
input = argv[2];
xfersz = strtoul(input, &end, 0);
switch (*end) {
case '\\0':
break;
case 'K':
case 'k':
xfersz <<= 10;
break;
case 'M':
case 'm':
xfersz <<= 20;
break;
default:
xfersz = 0;
break;
}
if (xfersz == 0) {
printf("%s is not a valid transfer size\\n", input);
goto usage;
}
if (xfersz < sizeof(struct xfer_data)) {
printf("%s is too small\\n", input);
goto usage;
}
cfg->stream = stream;
cfg->xfersz = xfersz;
return 0;
}
usage:
printf("usage:\\n");
printf(" %s <stream type> <transfer size>\\n", argv[0]);
printf("available stream type options:\\n");
for (i = 0; i < sizeof(stream_defns) / sizeof(*stream_defns); i++)
printf(" -> %s\\n", stream_defns[i]->name);
printf("transfer size can have an optional K,k,M,m suffix\\n");
printf("^C to terminate\\n");
return 1;
}
static long timespec_delta(const struct timespec * old,
const struct timespec * new)
{
long delta;
delta = 0;
delta += new->tv_sec - old->tv_sec;
delta *= 1000000000;
delta += new->tv_nsec - old->tv_nsec;
return delta;
}
struct xfer_stats {
pthread_mutex_t lock;
unsigned long delay;
unsigned int count;
} ;
static struct xfer_stats xfer_stats;
static void * measurer_worker(const struct run_config * config)
{
void (*rxfn)(void * data, size_t size);
size_t size;
struct xfer_data * data;
rxfn = config->stream->rx;
size = config->xfersz;
data = malloc(size);
for (;;) {
struct timespec tstamp;
long delta;
rxfn(data, size);
clock_gettime(CLOCK_MONOTONIC, &tstamp);
delta = timespec_delta(&data->tstamp, &tstamp);
if (delta < 0)
error("negative latency measurement");
if (data->canary != 0xDEADF1F0)
error("corrupted canary in transfer");
pthread_mutex_lock(&xfer_stats.lock);
xfer_stats.delay += delta;
xfer_stats.count++;
pthread_mutex_unlock(&xfer_stats.lock);
}
return 0;
}
static void * provider_worker(const struct run_config * config)
{
void (*txfn)(const void * data, size_t size);
size_t size;
struct xfer_data * data;
struct timespec wait;
int iter;
txfn = config->stream->tx;
size = config->xfersz;
data = malloc(size);
clock_gettime(CLOCK_MONOTONIC, &wait);
for (iter = 0;; iter++) {
memset(data->payload, iter, size - sizeof(*data));
data->canary = 0xDEADF1F0;
clock_gettime(CLOCK_MONOTONIC, &data->tstamp);
txfn(data, size);
wait.tv_nsec += 1000;
wait.tv_sec += wait.tv_nsec / 1000000000;
wait.tv_nsec %= 1000000000;
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &wait, 0);
}
return 0;
}
static void * reporter_worker(const struct run_config * config)
{
size_t size;
struct timespec pstamp, nstamp;
unsigned long pdelay, ndelay, delay;
unsigned int pcount, ncount, count;
size = config->xfersz;
clock_gettime(CLOCK_MONOTONIC, &pstamp);
pdelay = 0;
pcount = 0;
for (;;) {
unsigned int snooze;
long seconds;
double mbytes;
double thruput;
double latency;
for (snooze = 5; snooze != 0;)
snooze = sleep(snooze);
pthread_mutex_lock(&xfer_stats.lock);
delay = xfer_stats.delay;
count = xfer_stats.count;
pthread_mutex_unlock(&xfer_stats.lock);
clock_gettime(CLOCK_MONOTONIC, &nstamp);
seconds = timespec_delta(&pstamp, &nstamp) / 1000000000;
ndelay = delay;
ncount = count;
delay -= pdelay;
count -= pcount;
mbytes = (double)(count * size) / (double)(1024 * 1024);
thruput = (double)mbytes / (double)seconds;
latency = (double)delay / (double)count;
printf("%lf mbs %lf mbps %lf ns\\n",
mbytes, thruput, latency);
pstamp = nstamp;
pdelay = ndelay;
pcount = ncount;
}
return 0;
}
int main(int argc, char ** argv)
{
struct run_config config;
pthread_t measurer;
pthread_t provider;
pthread_t reporter;
if (config_run(argc, argv, &config))
return 0;
config.stream->ini(config.xfersz);
pthread_mutex_init(&xfer_stats.lock, 0);
xfer_stats.delay = 0;
xfer_stats.count = 0;
if (pthread_create(&measurer, 0,
(void * (*)(void *))measurer_worker, &config) != 0)
error("failed to create measurer worker");
if (pthread_create(&provider, 0,
(void * (*)(void *))provider_worker, &config) != 0)
error("failed to create provider worker");
if (pthread_create(&reporter, 0,
(void * (*)(void *))reporter_worker, &config) != 0)
error("failed to create reporter worker");
pause();
return 0;
}
| 1
|
#include <pthread.h>
int somma_voti;
int votanti;
} Film;
struct Film arrayFilm[10];
pthread_mutex_t mutex_threads[10];
void *ThreadCode(void *t) {
long tid;
long result = 1;
int i;
int voto;
tid = (int)t;
for (i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex_threads[i]);
voto = rand() % 10 + 1;
arrayFilm[i].somma_voti += voto;
arrayFilm[i].votanti++;
printf("Utente %ld. Film %d - Voto %d\\n", tid, i, voto);
pthread_mutex_unlock(&mutex_threads[i]);
}
pthread_exit((void*) result);
}
int main (int argc, char *argv[]) {
int i, rc, bestfilm;
long t;
long result;
float voto, bestvoto = 0;
pthread_t threads[3];
srand(time(0));
for (i = 0; i < 10; i++) {
pthread_mutex_init(&mutex_threads[i], 0);
arrayFilm[i] = (Film){.somma_voti = 0, .votanti = 0};
}
for (t = 0; t < 3; t++) {
printf("Main: Intervistato %ld.\\n", t);
rc = pthread_create(&threads[t], 0, ThreadCode, (void*)t);
if (rc) {
printf ("ERRORE: %d\\n", rc);
exit(-1);
}
}
for (t = 0; t < 3; t++) {
rc = pthread_join(threads[t], (void *)&result);
if (rc) {
printf ("ERRORE: join thread %ld codice %d.\\n", t, rc);
} else {
printf("Main: Finito intervistato %ld.\\n", t);
}
}
printf("\\n\\nMain: Risultati finali.\\n");
for (i = 0; i < 10; i++) {
voto = arrayFilm[i].somma_voti/((double)arrayFilm[i].votanti);
printf("Film %d: %f\\n", i, voto);
if(voto> bestvoto)
{
bestvoto = voto;
bestfilm=i;
}
}
printf("\\nMiglior film %d con voto %f\\n\\n",bestfilm,bestvoto);
printf("Main: Termino...\\n\\n");
}
| 0
|
#include <pthread.h>
extern pthread_mutex_t rand_lock;
extern int MIN_PROGRAMMING_TIME;
extern int MAX_PROGRAMMING_TIME;
extern int MIN_HELPING_TIME;
extern int MAX_HELPING_TIME;
int generateSomeTime(int caller_type, unsigned int* seed)
{
if (caller_type)
{
pthread_mutex_lock(&rand_lock);
int period = rand_r(seed);
pthread_mutex_unlock(&rand_lock);
return (MIN_PROGRAMMING_TIME+period%(MAX_PROGRAMMING_TIME-MIN_PROGRAMMING_TIME));
}
else
{
pthread_mutex_lock(&rand_lock);
int period = rand_r(seed);
pthread_mutex_unlock(&rand_lock);
return (MIN_HELPING_TIME+period%(MAX_HELPING_TIME-MIN_HELPING_TIME));
}
}
| 1
|
#include <pthread.h>
struct thread_data{
char * chunk;
int *ch_size;
unsigned int *histo;
pthread_mutex_t * mutex;
pthread_cond_t * cond_cons;
pthread_cond_t * cond_prod;
int id;
};
void processing(char * chunk, unsigned int* histogram, const int sajz){
for (int i=0; i<sajz; i++) {
if (chunk[i] >= 'a' && chunk[i] <= 'z')
histogram[chunk[i]-'a']++;
else if(chunk[i] >= 'A' && chunk[i] <= 'Z')
histogram[chunk[i]-'A']++;
}
}
void* parallel(void* threadArg){
struct thread_data *data = threadArg;
unsigned int *histogram;
histogram = calloc(26, sizeof(*histogram));
char * mojmoj = calloc(CHUNKSIZE, sizeof(*mojmoj));
int size;
do {
pthread_mutex_lock(data->mutex);
pthread_cond_wait(data->cond_cons, data->mutex);
size = *data->ch_size;
if(size==0) {
pthread_mutex_unlock(data->mutex);
break;
}
memcpy(mojmoj, data->chunk, size);
pthread_cond_signal(data->cond_prod);
pthread_mutex_unlock(data->mutex);
processing(mojmoj, histogram, size);
} while (size!=0);
data->histo = histogram;
free(mojmoj);
return 0;
}
void* kopiraj(void* threadArg){
struct thread_data *data = threadArg;
usleep(100);
pthread_mutex_lock(data->mutex);
do {
*data->ch_size = get_chunk(data->chunk);
usleep(100000);
pthread_cond_broadcast(data->cond_cons);
if(*data->ch_size==0){break;};
pthread_cond_wait(data->cond_prod, data->mutex);
} while (*data->ch_size > 0);
usleep(1000);
pthread_cond_broadcast(data->cond_cons);
pthread_mutex_unlock(data->mutex);
return 0;
}
void get_histogram(unsigned int* histogram,
unsigned int num_threads) {
struct thread_data *seznam;
seznam = malloc(num_threads * sizeof(*seznam));
pthread_t *thread;
thread = malloc(num_threads * sizeof(*thread));
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_cons = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_prod = PTHREAD_COND_INITIALIZER;
char *chunk = malloc( CHUNKSIZE );
int size = 0;
seznam[0].chunk = chunk;
seznam[0].ch_size = &size;
seznam[0].mutex = &mutex;
seznam[0].cond_cons = &cond_cons;
seznam[0].cond_prod = &cond_prod;
seznam[0].id = 0;
pthread_create(thread, 0, &kopiraj, seznam);
for (int i=1; i<num_threads; i++){
seznam[i].chunk = chunk;
seznam[i].ch_size = &size;
seznam[i].mutex = &mutex;
seznam[i].cond_cons = &cond_cons;
seznam[i].cond_prod = &cond_prod;
seznam[i].id = i;
pthread_create(thread+i, 0, ¶llel, seznam+i);
}
for(int i = 1; i < num_threads; ++i) {
pthread_join(thread[i], 0);
for(int j = 0; j < NALPHABET; j++) {
histogram[j] += seznam[i].histo[j];
}
}
pthread_join(thread[0], 0);
pthread_join(thread[1],0);
free(chunk);
free(thread);
free(seznam);
}
| 0
|
#include <pthread.h>
void *serverClient(void *ptrFile);
char achFileList[5][10] = {"12.mp3","file2","file1.c","file4.c","file2.c"};
int iLenght;
struct sockaddr_in caddr;
pthread_t clientThread[1];
pthread_mutex_t mutexLock;
int iSocketDis;
int main()
{
int iIndex;
for (iIndex = 1; iIndex <= 1; iIndex++)
{
pthread_create(&clientThread[iIndex], 0, serverClient, (void *) iIndex );
}
for (iIndex = 1; iIndex <= 1; iIndex++)
{
pthread_join(clientThread[iIndex], 0);
}
printf("MAIN END\\n");
}
void *serverClient(void *clientNum)
{
char achData[1024];
int iNum;
int iIndex;
int pid;
char achFileName[20];
char preEXE[10] = "./";
char *achEXE[1];
FILE *fp;
pthread_mutex_lock(&mutexLock);
iNum = (int *)clientNum;
iSocketDis=socket(AF_INET,SOCK_STREAM,0);
caddr.sin_family=AF_INET;
caddr.sin_addr.s_addr=inet_addr("192.168.55.8");
caddr.sin_port=htons(3001);
iLenght=sizeof(caddr);
strcpy(achData,achFileList[iNum - 1]);
connect(iSocketDis,(const struct sockaddr*) &caddr,iLenght);
write(iSocketDis,achData,sizeof(achData));
printf("Client %d >> %s\\n",iNum,achData);
memset(achFileName,0,sizeof(achFileName));
strcpy(achFileName,achData);
pthread_mutex_unlock(&mutexLock);
int count = 0;
while(read(iSocketDis,achData,sizeof(achData))){
if(strcmp(achData,"-1") == 0){
break;
}
fp=fopen("new.mp3","a");
fwrite(achData,1,sizeof(achData),fp);
printf("count %d\\n",++count );
memset(achData,0,sizeof(achData));
fclose(fp);
}
printf("client end\\n");
close(iSocketDis);
}
| 1
|
#include <pthread.h>
char thread_msg[] ="Hello Thread!";
volatile int counter = 0;
pthread_mutex_t myMutex;
void *demo_mutex(void *param)
{
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&myMutex);
counter++;
usleep(1);
printf("thread %d counter = %d\\n", (int)param, counter);
pthread_mutex_unlock(&myMutex);
}
}
int doMutex()
{
int one = 1, two = 2, three = 3;
pthread_t thread1, thread2, thread3;
pthread_mutex_init(&myMutex,0);
pthread_create(&thread1, 0, demo_mutex, (void*)one);
pthread_create(&thread2, 0, demo_mutex, (void*)two);
pthread_create(&thread3, 0, demo_mutex, (void*)three);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
pthread_mutex_destroy(&myMutex);
return 0;
}
void *thread_fnc(void * arg){
printf("This is thread_fnc(), arg is %s\\n", (char*) arg);
strcpy(thread_msg,"Thread has completed,and say, bye!");
pthread_exit("'Exit from thread'");
}
void display_thread_join()
{
int ret;
pthread_t my_thread;
void *ret_join;
ret = pthread_create(&my_thread, 0, thread_fnc, (void*) thread_msg);
if(ret != 0) {
perror("pthread_create failed\\n");
exit(1);
}
printf("Waiting for thread to finish...\\n");
ret = pthread_join(my_thread, &ret_join);
if(ret != 0) {
perror("pthread_join failed");
exit(1);
}
printf("Thread joined, it returned %s\\n", (char *) ret_join);
printf("New thread message: %s\\n",thread_msg);
}
void *worker_thread(void *arg)
{
printf("This is worker_thread()[%ld]\\n", (long)arg);
pthread_exit((void*)911);
}
void join_thread()
{
int i;
pthread_t thread;
pthread_create(&thread, 0, worker_thread, 0);
pthread_join(thread, (void **)&i);
printf("%d\\n",i);
}
void call_base()
{
pthread_t my_thread[5];
int ret;
long i = 0;
printf("In main: creating thread\\n");
for(; i < 5; i++)
{
ret = pthread_create(&my_thread[i], 0, &worker_thread, (void*)i);
if(ret != 0) {
printf("Error: pthread_create() failed\\n");
exit(1);
}
}
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(800)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(800))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int numofPlayer,itr;
pthread_mutex_t mutex;
int playIds[4],listenIds[4];
int broadcast(char *sendtext,int length){
for(itr=0;itr<numofPlayer;itr++){
if(write(listenIds[itr],sendtext,length)<0){
printf("listener connection shutdown\\n");
return 0;
}
}
return 1;
}
void playThreadFunc(void *ptr){
char buffer[2];
bzero(buffer,2);
int sockId,send;
sockId=*((int *) ptr);
write(sockId,"ok",2);
while(1){
if(read(sockId,buffer,2)<0){
printf("player connection shutdown\\n");
break;
}
pthread_mutex_lock (&mutex);
printf("sent\\n");
send=broadcast(buffer,2);
pthread_mutex_unlock(&mutex);
if(!send)
break;
}
}
int main(){
struct sockaddr_in serv_addr;
struct sockaddr_in play_addr[4];
struct sockaddr_in listen_addr[4];
int sockfd,optval=1;
char buffer[2];
pthread_t threads[4];
int playlen[4],listenlen[4];
if ((sockfd=socket(AF_INET, SOCK_STREAM, 0))==-1){
printf("socket initialization error\\n");
exit(1);
}
serv_addr.sin_family=AF_INET;
serv_addr.sin_port=htons(27000);
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bzero( &(serv_addr.sin_zero), sizeof(serv_addr) );
if ( bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(struct sockaddr)) == -1 ){
printf("bind error\\n");
exit(1);
}
numofPlayer=0;
while(1){
printf("waiting for listen socket\\n");
if ( listen(sockfd, 10) == -1 ){
printf("listen error\\n");
exit(1);
}
listenlen[numofPlayer]=sizeof(listen_addr);
listenIds[numofPlayer]=accept(sockfd, (struct sockaddr *) &listen_addr[numofPlayer], &listenlen[numofPlayer]);
if(listenIds[numofPlayer]<0){
printf("accept error\\n");
exit(1);
}
setsockopt(listenIds[numofPlayer], IPPROTO_TCP, TCP_NODELAY, (char *) &optval, sizeof(int));
printf("waiting for play socket..\\n");
if ( listen(sockfd, 10) == -1 ){
printf("listen error\\n");
exit(1);
}
playlen[numofPlayer]=sizeof(play_addr);
playIds[numofPlayer]=accept(sockfd, (struct sockaddr *) &play_addr[numofPlayer], &playlen[numofPlayer]);
if(playIds[numofPlayer]<0){
printf("accept error\\n");
exit(1);
}
pthread_create(&threads[numofPlayer],0,(void *) &playThreadFunc,&playIds[numofPlayer]);
numofPlayer++;
}
return 0;
}
| 0
|
#include <pthread.h>
void *b[(8)];
int in = 0, out = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
sem_t countsem, spacesem;
void init()
{
sem_init(&countsem, 0, 0);
sem_init(&spacesem, 0, (8));
}
void enqueue(void *value)
{
sem_wait( &spacesem );
pthread_mutex_lock(&lock);
b[ (in++) & ((8)-1) ] = value;
pthread_mutex_unlock(&lock);
sem_post(&countsem);
}
void *dequeue()
{
sem_wait(&countsem);
pthread_mutex_lock(&lock);
void *result = b[(out++) & ((8)-1)];
pthread_mutex_unlock(&lock);
sem_post(&spacesem);
return result;
}
void main()
{
int v[] = {0,1,2,3,4,5,6,7};
int* p = &v[0];
init();
printf("after init - in: %d out: %d \\n", in, out);
for (int ibuff=0; ibuff!=20; ibuff++)
{
enqueue(p);
printf("after enqueue - in: %d out: %d \\n", in, out);
dequeue();
printf("after dequeue - in: %d out: %d \\n", in, out);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t * create_mutex()
{
pthread_mutex_t *mutex = mmap(0, sizeof(pthread_mutex_t), (PROT_READ | PROT_WRITE), (MAP_SHARED | MAP_ANON), -1, 0);
if (mutex == MAP_FAILED)
{
perror("create_mutex:mmap");
return 0;
}
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mutex, &attr);
return mutex;
}
pthread_mutex_t * create_mutex2()
{
pthread_mutex_t *mutex = malloc(sizeof(pthread_mutex_t));
if (mutex == 0)
{
perror("create_mutex2:malloc");
return 0;
}
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mutex, &attr);
return mutex;
}
int main(int argc, char **argv)
{
printf("hello pthread_test2\\n");
pthread_mutex_t *mutex = create_mutex();
if (mutex == 0)
{
exit(1);
}
pid_t pid = fork();
if (pid < 0)
{
perror("main:fork");
exit(1);
}
if (pid == 0)
{
printf("child:before lock ----\\n");
pthread_mutex_lock(mutex);
printf("child:after lock ----\\n");
sleep(1);
printf("child:before unlock ----\\n");
pthread_mutex_unlock(mutex);
printf("child:after unlock ----\\n");
return 0;
}
printf("parent:before lock ****\\n");
pthread_mutex_lock(mutex);
printf("parent:after lock ****\\n");
sleep(1);
printf("parent:before unlock ****\\n");
pthread_mutex_unlock(mutex);
printf("parent:after unlock ****\\n");
sleep(3);
munmap(mutex, sizeof(pthread_mutex_t));
return 0;
}
| 0
|
#include <pthread.h>
char* buf[5];
int pos;
pthread_mutex_t mutex;
void* fuck(void* shit){
pthread_mutex_lock(&mutex);
buf[pos] = shit;
sleep(1);
pos++;
pthread_mutex_unlock(&mutex);
}
int main(){
pthread_mutex_init(&mutex,0);
pthread_t tid1;
pthread_create(&tid1,0,fuck,"zhangfei");
pthread_t tid2;
pthread_create(&tid2,0,fuck,"guanyu");
pthread_join(tid1,0);
pthread_join(tid2,0);
int i = 0;
for(i = 0;i < pos;i++){
printf("%s ",buf[i]);
}
printf("\\n");
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t threads[100];
pthread_mutex_t mutex;
int a[100], b[100];
int sum, tamanho;
void printArray()
{
int cont =0;
printf("\\nA = ");
while (cont < 100)
{
printf("%d, ", a[cont]);
cont++;
}
cont = 0;
printf("\\nB = ");
while (cont < 100)
{
printf("%d, ", b[cont]);
cont++;
}
}
void *produtoEscalar(void *arg)
{
int i, inicio, fim;
long numThread;
int produtoEscalarParcial = 0, *x, *y;
numThread = (long) arg;
int quant = 100 / 100;
inicio = numThread * quant - 1;
fim = inicio + quant;
x = a;
y = b;
inicio++;
for (i = inicio; i <= fim; i++)
{
produtoEscalarParcial += (x[i] * y[i]);
}
pthread_mutex_lock(&mutex);
sum += produtoEscalarParcial;
printf("\\nThread %ld calculou de %d a %d: produto escalar parcial = %d",
numThread, inicio, fim, produtoEscalarParcial);
pthread_mutex_unlock(&mutex);
pthread_exit((void*) 0);
}
int main(int argc, char *argv[]) {
srand(time(0));
long i;
if(100%100!=0 || 100 < 100)
{
printf("\\nDivisão não inteira");
exit(0);
}
for (i = 0; i < 100; i++)
{
a[i] = rand() % 10;
b[i] = rand() % 10;
}
printArray();
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 100; i++)
{
pthread_create(&threads[i], 0, produtoEscalar, (void *) i);
}
for (i = 0; i < 100; i++) {
pthread_join(threads[i], 0);
}
printf("\\nProduto escalar = %d \\n", sum);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int estado [(5)];
pthread_mutex_t mutex;
pthread_mutex_t mux_filo [(5)];
pthread_t jantar[(5)];
void * filosofo ( void * param );
void pegar_hashi ( int id_filosofo );
void devolver_hashi ( int id_filosofo );
void intencao ( int id_filosofo );
void comer ( int id_filosofo );
void pensar ( int id_filosofo );
void * filosofo ( void * vparam )
{
int * id = (int *) (vparam);
printf("Filosofo %d foi criado com sucesso\\n", *(id) );
while ( 1 )
{
pensar( *(id) );
pegar_hashi( *(id) );
comer( *(id) );
devolver_hashi( *(id) );
}
pthread_exit( (void*) 0 );
}
void pegar_hashi ( int id_filosofo )
{
pthread_mutex_lock( &(mutex) );
printf("Filosofo %d esta faminto\\n", id_filosofo);
estado[ id_filosofo ] = (1);
intencao( id_filosofo );
pthread_mutex_unlock( &(mutex) );
pthread_mutex_lock( &(mux_filo[id_filosofo]) );
}
void devolver_hashi ( int id_filosofo )
{
pthread_mutex_lock ( &(mutex) );
printf("Filosofo %d esta pensando\\n", id_filosofo);
estado[ id_filosofo ] = (0);
intencao( (id_filosofo + (5) - 1) % (5) );
intencao( (id_filosofo + 1) % (5) );
pthread_mutex_unlock ( &(mutex) );
}
void intencao ( int id_filosofo )
{
printf("Filosofo %d esta com intencao de comer\\n", id_filosofo);
if( (estado[id_filosofo] == (1)) &&
(estado[(id_filosofo + (5) - 1) % (5)] != (2)) &&
(estado[(id_filosofo + 1) % (5)] != (2) ) )
{
printf("Filosofo %d ganhou a vez de comer\\n", id_filosofo);
estado[ id_filosofo ] = (2);
pthread_mutex_unlock( &(mux_filo[id_filosofo]) );
}
}
void pensar ( int id_filosofo )
{
int r = (rand() % 10 + 1);
printf("Filosofo %d pensa por %d segundos\\n", id_filosofo, r );
sleep( r );
}
void comer ( int id_filosofo )
{
int r = (rand() % 10 + 1);
printf("Filosofo %d come por %d segundos\\n", id_filosofo, r);
sleep( r );
}
int main ( void )
{
int cont;
int status;
pthread_mutex_init( &(mutex), 0);
for( cont = 0 ; cont < (5) ; cont++ )
{
pthread_mutex_init( &(mux_filo[cont]), 0 );
}
for( cont = 0 ; cont < (5) ; cont++ )
{
status = pthread_create( &(jantar[cont]), 0, filosofo, (void *) &(cont) );
if ( status )
{
printf("Erro criando thread %d, retornou codigo %d\\n", cont, status );
return 1;
}
}
pthread_mutex_destroy( &(mutex) );
for( cont = 0 ; cont < (5) ; cont++ )
{
pthread_mutex_destroy( &(mux_filo[cont]) );
}
pthread_exit( 0 );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t m1,m2,m3;
void* thread_capital(void *p)
{
char ch;
for(ch = 'A' ; ch <= 'Z' ; ++ch)
{
pthread_mutex_lock(&m1);
printf("%c\\t",ch);
fflush(stdout);
sleep(1);
pthread_mutex_unlock(&m2);
}
}
void* thread_small(void *p)
{
char ch;
for(ch = 'a' ; ch <= 'z' ; ++ch)
{
pthread_mutex_lock(&m2);
printf("%c\\t",ch);
fflush(stdout);
sleep(1);
pthread_mutex_unlock(&m3);
}
}
void* thread_number(void *p)
{
int i;
for(i = 1 ; i < 27 ; ++i)
{
pthread_mutex_lock(&m3);
printf("%d\\n",i);
sleep(1);
pthread_mutex_unlock(&m1);
}
}
int main()
{
pthread_t t1,t2,t3;
pthread_create(&t1,0,thread_capital,0);
pthread_create(&t2,0,thread_small,0);
pthread_create(&t3,0,thread_number,0);
pthread_mutex_lock(&m2);
pthread_mutex_lock(&m3);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t w_mutex;
char w_area[1024];
int time_to_exit = 0;
void *thread_func()
{
sleep(1);
pthread_mutex_lock(&w_mutex);
while(strncmp("end", w_area, 3) != 0)
{
printf("You input %d characters\\n", strlen(w_area) -1);
w_area[0] = '\\0';
pthread_mutex_unlock(&w_mutex);
sleep(1);
pthread_mutex_lock(&w_mutex);
while (w_area[0] == '\\0' )
{
pthread_mutex_unlock(&w_mutex);
sleep(1);
pthread_mutex_lock(&w_mutex);
}
}
time_to_exit = 1;
w_area[0] = '\\0';
pthread_mutex_unlock(&w_mutex);
pthread_exit(0);
}
int main()
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&w_mutex, 0);
if (res != 0)
{
perror("Mutex Initialization failed\\n");
exit(1);
}
res = pthread_create(&a_thread, 0, thread_func, 0);
if (res != 0)
{
perror("thread creation failed\\n");
exit(1);
}
pthread_mutex_lock(&w_mutex);
printf("Input some text. Enter ‘end’ to finish\\n");
while(!time_to_exit)
{
fgets(w_area, 1024, stdin);
pthread_mutex_unlock(&w_mutex);
while(1)
{
pthread_mutex_lock(&w_mutex);
if (w_area[0] != '\\0')
{
pthread_mutex_unlock(&w_mutex);
sleep(1);
}
else
{
break;
}
}
}
pthread_mutex_unlock(&w_mutex);
printf("\\n Waiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if (res != 0)
{
perror("Thread join failed");
exit(1);
}
printf("Thread joined\\n");
pthread_mutex_destroy(&w_mutex);
exit(0);
return 0;
}
| 1
|
#include <pthread.h>
void *picture_thread(void *arg) {
int ret = -1;
struct path_t *jpeg_filepath = 0;
enum main_notify_target notify = NOTIFY_NONE;
for (;;) {
pthread_mutex_lock(&global.client.thread_attr.picture_mutex);
while (global.client.picture_target == NOTIFY_NONE) {
pthread_cond_wait(&global.client.thread_attr.picture_cond,
&global.client.thread_attr.picture_mutex);
}
notify = global.client.picture_target;
global.client.picture_target = NOTIFY_NONE;
if (notify == NOTIFY_PICTURE) {
int width = global.client.image_width;
int height = global.client.image_height;
int length = width * height * 2;
pthread_rwlock_rdlock(&global.client.thread_attr.bufferYUYV_rwlock);
memcpy(global.client.pyuyv422buffer,
global.client.bufferingYUYV422, length);
pthread_rwlock_unlock(&global.client.thread_attr.bufferYUYV_rwlock);
YUYV422toRGB888INT(global.client.pyuyv422buffer, width, height,
global.client.rgbbuffer, length);
jpeg_filepath = client_get_filepath(JPEG_FILE);
assert(jpeg_filepath != 0);
dmd_log(LOG_INFO, "in %s, write a jpegfile to %s\\n",
__func__, jpeg_filepath->path);
ret = write_jpeg(jpeg_filepath->path, global.client.rgbbuffer, 100,
width, height, 0);
assert(ret == 0);
pthread_mutex_lock(&global_stats->mutex);
if (global_stats->current_motion != 0) {
increase_motion_pictures(global_stats->current_motion);
}
pthread_mutex_unlock(&global_stats->mutex);
free(jpeg_filepath->path);
jpeg_filepath->path = 0;
free(jpeg_filepath);
jpeg_filepath = 0;
notify = NOTIFY_NONE;
pthread_mutex_unlock(&global.client.thread_attr.picture_mutex);
} else if (notify == NOTIFY_EXIT) {
dmd_log(LOG_INFO, "in %s, thread to exit\\n", __func__);
notify = NOTIFY_NONE;
pthread_mutex_unlock(&global.client.thread_attr.picture_mutex);
break;
}
}
pthread_mutex_lock(&total_thread_mutex);
total_thread--;
pthread_mutex_unlock(&total_thread_mutex);
pthread_exit(0);
}
int write_jpeg(char *filename, unsigned char *buf, int quality,
int width, int height, int gray) {
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE *fp;
int i = 0;
unsigned char *line;
int line_length;
assert(filename != 0);
if ((fp = fopen(filename, "wb+")) == 0) {
dmd_log(LOG_ERR, "fopen error:%s\\n", strerror(errno));
return -1;
}
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
jpeg_stdio_dest(&cinfo, fp);
cinfo.image_width = width;
cinfo.image_height = height;
cinfo.input_components = gray ? 1 : 3;
cinfo.in_color_space = gray ? JCS_GRAYSCALE : JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, quality, TRUE);
jpeg_start_compress(&cinfo, TRUE);
line_length = gray ? width : width * 3;
line = buf;
for (i = 0; i < height; i++) {
jpeg_write_scanlines(&cinfo, &line, 1);
line += line_length;
}
jpeg_finish_compress(&cinfo);
jpeg_destroy_compress(&cinfo);
fclose(fp);
return 0;
}
| 0
|
#include <pthread.h>
sem_t clientes, foiChamado;
pthread_mutex_t mutex;
pthread_cond_t atendentes;
int proximoCliente;
void *Atendentes(void *arg){
int i, pid = * (int *) arg;
while(1){
sem_wait(&clientes);
printf("Tem clientes na padaria!\\n");
pthread_mutex_lock(&mutex);
printf("Eu sou o atendente %d e chamo o cliente %d!\\n", pid, proximoCliente);
proximoCliente++;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&atendentes);
sem_post(&foiChamado);
}
}
void *Clientes(void *arg){
int pid = * (int *) arg;
pthread_mutex_lock(&mutex);
while(pid != proximoCliente) {
pthread_cond_wait(&atendentes, &mutex);
}
pthread_mutex_unlock(&mutex);
sem_post(&clientes);
sem_wait(&foiChamado);
printf("Eu sou o cliente %d e é minha vez\\n", pid);
}
int main(int argc, char *argv[]) {
pthread_t atend[3];
pthread_t cli[20];
int i, *pid;
proximoCliente=0;
sem_init(&clientes, 0, 0);
sem_init(&foiChamado, 0, 0);
printf("Padaria abriu!\\n");
for (i = 0; i < 3; i++){
pid = malloc(sizeof(int));
if(pid == 0){
printf("--ERRO: malloc() em alocação threads\\n"); exit(-1);
}
*pid = i;
pthread_create(&atend[i], 0, Atendentes, (void *) pid);
}
for (i = 0; i < 20; i++){
pid = malloc(sizeof(int));
if(pid == 0){
printf("--ERRO: malloc() em alocação threads\\n"); exit(-1);
}
*pid = i;
pthread_create(&cli[i], 0, Clientes, (void *) pid);
}
for (i = 0; i < 20; i++) {
pthread_join(cli[i], 0);
}
printf("Padaria fechou!\\n");
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&atendentes);
return 0;
}
| 1
|
#include <pthread.h>
const char * thread_outgoing_writer_tslogid = "outgoing_writer";
void * thread_outgoing_writer (void * arg)
{
tslog(0, thread_outgoing_writer_tslogid, "Started.");
struct thread_outgoing_synchroblock * synchroblock = arg;
int code;
do
{
tslog(0, thread_outgoing_writer_tslogid, "Signalling that we are a ready and waiting for socket fd.");
pthread_mutex_lock(&(synchroblock->mutex));
synchroblock->ready_writer = 1;
pthread_cond_broadcast(&(synchroblock->ready_cond));
while (!synchroblock->socket_ready)
{
pthread_cond_wait(&(synchroblock->socket_cond), &(synchroblock->mutex));
}
int fd = synchroblock->socket_fd;
pthread_mutex_unlock(&(synchroblock->mutex));
tslog(0, thread_outgoing_writer_tslogid, "typa, rabotaem...");
code = -1; usleep(20000000);
if (code == -1)
{
tslog(0, thread_outgoing_writer_tslogid, "typa, error...");
pthread_cond_broadcast(&(synchroblock->error_cond));
usleep(1000000);
continue;
}
} while (1);
}
| 0
|
#include <pthread.h>
char phil_state[5] = {'T','T', 'T', 'T','T'};
pthread_mutex_t canEat;
sem_t amt;
const char* semaphore_name = "/amt";
void* dining_table(void* param);
void waiter(int phil_num, int request);
void check_on_table(int bites);
int main() {
pthread_t philosophers[5];
pthread_attr_t phil_attr;
pthread_attr_init(&phil_attr);
pthread_mutex_init(&canEat, 0);
if((sem_init(&amt, 0, 5)) == -1){
fprintf(stderr, "sem_open failed\\n");
}
printf("=========================================================================\\n");
printf("| ====== PHILOSOPHERS ====== |\\n");
printf("=========================================================================\\n");
printf(" Phil_0 | Phil_1 | Phil_2 | Phil_3 | Phil_4 |\\n");
check_on_table(0);
int i;
int check;
for(i = 0; i < 5; i++){
if(pthread_create(&philosophers[i], &phil_attr, dining_table, (void*) i) != 0){
exit(1);
}
}
for(i = 0; i < 5; i++){
if(pthread_join(philosophers[i], 0) != 0){
exit(1);
}
}
check_on_table(0);
printf("\\n...DONE.\\n");
sem_close(&amt);
sem_unlink(semaphore_name);
return 0;
}
void* dining_table(void* param){
int phil_num = (int)param;
int bitesTake = 0;
while(bitesTake != 3){
sleep(bitesTake+1);
if(phil_state[phil_num] == 'T') {
phil_state[phil_num] = 'H';
pthread_mutex_lock(&canEat);
waiter(phil_num, 0);
pthread_mutex_unlock(&canEat);
}
if(phil_state[phil_num] == 'E') {
sem_wait(&amt);
sem_wait(&amt);
sleep(2);
bitesTake++;
pthread_mutex_lock(&canEat);
check_on_table(bitesTake);
waiter(phil_num, 1);
pthread_mutex_unlock(&canEat);
sem_post(&amt);
sem_post(&amt);
}
if(phil_state[phil_num] == 'H'){
pthread_mutex_lock(&canEat);
waiter(phil_num, 0);
pthread_mutex_unlock(&canEat);
}
}
phil_state[phil_num] = 'T';
}
void waiter(int phil_num, int request){
if(request == 0){
if(phil_state[phil_num] == 'H' && phil_state[(phil_num+4) % 5] != 'E' && phil_state[(phil_num + 1) % 5] != 'E'){
phil_state[phil_num] = 'E';
}
}else if(request == 1){
phil_state[phil_num] = 'T';
}
}
void check_on_table(int bites){
int i;
for(i = 0; i < 5; i++){
if (phil_state[i] == 'T')
printf(" thinking |");
else if(phil_state[i] == 'H')
printf(" *hungry* |");
else if(phil_state[i] == 'E')
printf(" EATING(%d) |", bites);
}
printf("\\n---------------------------------------------------------------------------\\n");
}
| 1
|
#include <pthread.h>
int buffer[3];
int add = 0;
int rem = 0;
int num = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_cons = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_prod = PTHREAD_COND_INITIALIZER;
void *productor (void *param);
void *consumidor (void *param);
int main(int argc, char *argv[]) {
pthread_t tid1, tid2;
int i;
if(pthread_create(&tid1, 0, productor, 0) != 0) {
fprintf(stderr, "No se pudo crear el thread productor\\n");
exit(1);
}
if(pthread_create(&tid2, 0, consumidor, 0) != 0) {
fprintf(stderr, "No se pudo crear el thread consumidor\\n");
exit(1);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
printf("Padre terminando\\n");
return 0;
}
void *productor(void *param) {
int i;
for (i=1; i<=20; i++) {
pthread_mutex_lock (&m);
if (num > 3) {
exit(1);
}
while (num == 3) {
pthread_cond_wait (&c_prod, &m);
}
buffer[add] = i;
add = (add+1) % 3;
num++;
pthread_mutex_unlock (&m);
pthread_cond_signal (&c_cons);
printf ("productor: inserto %d\\n", i);
fflush (stdout);
}
printf("productor terminando\\n");
fflush(stdout);
return 0;
}
void *consumidor(void *param) {
int i;
while(1) {
pthread_mutex_lock (&m);
if (num < 0) {
exit(1);
}
while (num == 0) {
pthread_cond_wait (&c_cons, &m);
}
i = buffer[rem];
rem = (rem+1) % 3;
num--;
pthread_mutex_unlock (&m);
pthread_cond_signal (&c_prod);
printf ("Valor consumido %d\\n", i); fflush(stdout);
}
return 0;
}
| 0
|
#include <pthread.h>
void *find_words(void*);
int map_reduce(int number_threads, char *string, struct list *list);
int main(void) {
char *string;
int cur_time, i, j;
struct list *list;
struct stat *buf;
buf = (struct stat *) malloc(sizeof(struct stat));
stat("./Don_Quixote.txt", buf);
int fd = open("./Don_Quixote.txt", O_RDONLY);
string = (char *)malloc(sizeof(char) * buf->st_size);
read(fd, string, buf->st_size);
list = (struct list *)malloc(sizeof(struct list));
for(j = 2; j < 4; ++j) {
list_init(list);
cur_time = clock();
map_reduce(j, string, list);
cur_time = clock() - cur_time;
printf("%d\\n\\n", cur_time);
for(i = 0; i < list->current_length; ++i)
free(list->head[i]);
list_destroy(list);
}
free(string);
free(list);
exit(0);
}
int is_separator(char *simbol, char *separators) {
while(*separators != 0) {
if(*simbol == *separators)
return 1;
++separators;
}
return 0;
}
void *find_words(void *arg) {
struct list *list;
char *begin, *end;
char *new_begin, *new_str;
int i, is_unique;
void **pointer;
pointer = (void **)arg;
list = (struct list *)(pointer[0]);
begin = (char *)(pointer[1]);
end = (char *)(pointer[2]);
while(begin != end) {
while(begin <= end && is_separator(begin, " ,.?!"))
++begin;
if(begin > end)
return 0;
new_begin = begin;
while(new_begin <= end && !is_separator(new_begin, " ,.?!"))
++new_begin;
--new_begin;
pthread_mutex_lock(list->mutex);
is_unique = 0;
for(i = 0; i < list->current_length; ++i) {
if(strncmp(list->head[i], begin, new_begin - begin + 1) == 0) {
is_unique = 1;
break;
}
}
if(is_unique == 0) {
new_str = (char *)malloc(sizeof(char) * (new_begin - begin + 2));
memcpy(new_str, begin, new_begin - begin + 1);
new_str[new_begin - begin + 1] = '\\0';
list_add(list, new_str);
}
pthread_mutex_unlock(list->mutex);
usleep(1000);
begin = new_begin + 1;
}
pthread_exit(0);
}
int map_reduce(int number_threads, char *string, struct list *list) {
int length, delta_length, i, begin_offset, end_offset, cur_pthread;
void ***arg;
pthread_t *pthreads;
pthreads = (pthread_t *)malloc(sizeof(pthread_t)*number_threads);
arg = (void ***)malloc(sizeof(void *) * number_threads);
length = strlen(string);
delta_length = length / number_threads;
begin_offset = 0;
cur_pthread = 0;
for(i = 0; i < number_threads; ++i) {
if(i == number_threads - 1)
end_offset = length;
else {
end_offset = delta_length * (i + 1);
while(end_offset >= begin_offset && !is_separator(string + end_offset, " ,.?!"))
--end_offset;
}
if(end_offset >= begin_offset) {
arg[cur_pthread] = (void **)malloc(sizeof(void *) * 3);
arg[cur_pthread][0] = list;
arg[cur_pthread][1] = string + begin_offset;
arg[cur_pthread][2] = string + end_offset - 1;
pthread_create((pthreads + cur_pthread), 0, find_words, (void*)(arg[cur_pthread]));
++cur_pthread;
}
begin_offset = end_offset;
}
for(i = 0; i < cur_pthread; ++i) {
pthread_join(pthreads[i], 0);
free(arg[i]);
}
free(pthreads);
free(arg);
return 0;
}
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static void *lock_unlock(void *arg)
{
while (! isend) {
pthread_mutex_lock(&m);
count ++;
pthread_mutex_unlock(&m);
}
return arg;
}
static void test_exec(void)
{
pthread_t t;
count = 0;
pthread_create(&t, 0, lock_unlock, 0);
pthread_join(t, 0);
}
static void test_print_results(int sig)
{
isend = 1;
print_results();
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct sigevent event2;
volatile unsigned counter;
volatile int timeCounter = 0;
struct _pulse pulse;
int czasy[4] = {100, 200, 500, 3500};
int thread_chid;
{
short type;
}my_msg;
void *dummy(void *arg) {
int srv_coid;
my_msg msg;
my_msg reply;
printf("in thread : %d", pthread_self());
if ( (srv_coid = name_open( "server_nameE", 0 )) == -1)
{
printf("failed to find server, errno %d\\n", errno );
exit(1);
}
printf("msg sending\\n");
MsgSend( srv_coid, &msg, sizeof(msg), &reply, sizeof(reply));
printf("\\nThread %d unblock",pthread_self() );
return 0;
}
const struct sigevent *handler( void *area, int id ) {
if ( ++counter == czasy[timeCounter] ) {
printf("timeout counter : %d", timeCounter);
counter = 0;
timeCounter++;
return( &event2 );
}
else
return( 0 );
}
int main() {
my_msg msg;
my_msg reply;
name_attach_t *attach;
if ( (attach = name_attach( 0, "server_nameE", 0 )) == 0)
{
printf("server:failed to attach name, errno %d\\n", errno );
exit(1);
}
thread_chid = ChannelCreate(0);
int i;
int id;
int chid,coid, rcvid;
int tid;
int rcvidMsg[4];
for(i = 0; i < 4 ;i++){
pthread_create(&tid,0,dummy,0 );
rcvidMsg[i] = MsgReceive( attach->chid, &msg, sizeof( msg ), 0 );
printf("msgReceive, i = %d\\n",i);
}
printf("rcvidMsg[3] = %d", rcvidMsg[3]);
ThreadCtl( _NTO_TCTL_IO, 0 );
chid = ChannelCreate( 0 );
coid = ConnectAttach( 0, 0, chid, _NTO_SIDE_CHANNEL, 0 );
SIGEV_PULSE_INIT( &event2, coid, getprio(0), SIGEV_INTR, 0 );
id=InterruptAttach( SYSPAGE_ENTRY(qtime)->intr, &handler,
0, 0, 0 );
int functionCounter = 0;
while(1){
rcvid = MsgReceivePulse( chid, &pulse, sizeof( pulse ), 0 );
if (pulse.code == SIGEV_INTR) {
printf("\\n->>>i get handle interrupt as pulse, so i reply to : %d",functionCounter);
MsgReply(rcvidMsg[functionCounter], EOK, &reply, sizeof(reply) );
pthread_mutex_lock( &mutex );
functionCounter++;
pthread_mutex_unlock( &mutex );
if(functionCounter == 4){
printf("\\nkoniec!!");
break;
}
}
}
sleep(10);
InterruptDetach(id);
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_assume(int);
extern void __VERIFIER_error() ;
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; }
const int SIGMA = 3;
int *array;
int array_index=-1;
pthread_mutex_t mutexes[SIGMA];
pthread_mutex_t mutex_index = PTHREAD_MUTEX_INITIALIZER;
void *thread(void * arg)
{
int i;
pthread_mutex_lock (&mutex_index);
i = array_index;
pthread_mutex_unlock (&mutex_index);
pthread_mutex_lock (mutexes + i);
array[i] = 1;
pthread_mutex_unlock (mutexes + i);
return 0;
}
int main()
{
int tid, sum;
pthread_t *t;
t = (pthread_t *)malloc(sizeof(pthread_t) * SIGMA);
array = (int *)malloc(sizeof(int) * SIGMA);
__VERIFIER_assume(t != 0);
__VERIFIER_assume(array != 0);
for (tid = 0; tid < SIGMA; tid++) pthread_mutex_init (mutexes + tid, 0);
for (tid=0; tid<SIGMA; tid++) {
pthread_mutex_lock (&mutex_index);
array_index++;
pthread_mutex_unlock (&mutex_index);
pthread_create(&t[tid], 0, thread, 0);
}
for (tid=0; tid<SIGMA; tid++) {
pthread_join(t[tid], 0);
}
for (tid=sum=0; tid<SIGMA; tid++) {
sum += array[tid];
}
return 0;
}
| 1
|
#include <pthread.h>
long THREAD_NUMBER = 0;
int isCanceled = 0;
pthread_t *thread;
pthread_barrier_t barrier;
pthread_mutex_t farestAccess;
int farestThread = 0;
int thread_id;
int threads_count;
} thread_attributes;
void sigint_handler( int sig ) {
if (sig == SIGINT) {
isCanceled = 1;
}
return;
}
void *count_sum( void * arg ) {
double *result = (double *)calloc(1,sizeof(double));
thread_attributes attr = *(thread_attributes *)arg;
int padding = attr.threads_count*1000;
long start = 1000*attr.thread_id;
long end = start + 1000;
while ( !isCanceled ) {
pthread_mutex_lock(&farestAccess);
if (farestThread < end) {
farestThread = end;
}
pthread_mutex_unlock(&farestAccess);
for (long i = start; i < end; i++) {
result[0] += 1.0/(i*4.0 + 1.0);
result[0] -= 1.0/(i*4.0 + 3.0);
}
start += padding;
end += padding;
}
pthread_mutex_lock(&farestAccess);
while (farestThread > end) {
for (long i = start; i < end; i++) {
result[0] += 1.0/(i*4.0 + 1.0);
result[0] -= 1.0/(i*4.0 + 3.0);
}
start += padding;
end += padding;
}
pthread_mutex_unlock(&farestAccess);
printf("%ld\\n", end);
pthread_exit(result);
}
int main( int argc, char **argv ) {
if (argc < 2) {
printf("Threads amount is not entered\\n");
return 1;
}
struct sigaction action;
action.sa_handler = sigint_handler;
sigaction(SIGINT,&action,0);
double pi = 0;
THREAD_NUMBER = atoi(argv[1]);
thread = (pthread_t *)malloc(THREAD_NUMBER * sizeof(pthread_t));
thread_attributes attributes[THREAD_NUMBER];
pthread_mutex_init(&farestAccess, 0);
for (int i = 0; i < THREAD_NUMBER; i++) {
attributes[i].thread_id = i;
attributes[i].threads_count = THREAD_NUMBER;
if (0 != pthread_create(thread + i , 0, count_sum, &attributes[i])) {
perror("Could not create thread\\n");
return 1;
}
}
printf("All threads are created\\n");
int isRight = 1;
double *result;
for (int i = 0; i < THREAD_NUMBER; i++) {
if (0 != pthread_join(*(thread + i), (void *)(&result))) {
perror("Could not join thread\\n");
return 1;
}
if (0 == result) {
fprintf(stderr, "Thread returned nullptr\\n");
isRight = 0;
}
else {
pi += *result;
free(result);
printf("pi is added\\n");
}
}
pthread_mutex_destroy(&farestAccess);
if ( isRight ) {
printf("Pi is : %f\\n",pi * 4.0);
free(thread);
return 0;
}
else {
printf("Could not count pi value\\n");
free(thread);
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
int fib(int n)
{
if(n == 0) return 1;
if(n == 1) return 1;
return fib(n-2) + fib(n-1);
}
{
int fib_arg;
int* pfree_threads;
pthread_mutex_t* pconsole_mutex;
pthread_mutex_t* pstart_mutex;
} fib_data;
void* thread_main(void* param)
{
fib_data data = *(fib_data*)param;
free(param);
int result = fib(data.fib_arg);
pthread_mutex_lock(data.pconsole_mutex);
printf(" fib(%d) = %d\\n", data.fib_arg, result);
pthread_mutex_unlock(data.pconsole_mutex);
pthread_mutex_lock(data.pstart_mutex);
++(*data.pfree_threads);
pthread_mutex_unlock(data.pstart_mutex);
return 0;
}
int main(int argc, const char* argv[])
{
int max_fib = 40;
int max_threads = (argc>1)?atoi(argv[1]):4;
if(max_threads == 0) max_threads = 4;
pthread_mutex_t console_mutex, start_mutex;
pthread_mutex_init(&console_mutex, 0);
pthread_mutex_init(&start_mutex, 0);
int free_threads = max_threads;
int f;
for(f=max_fib; f!=0; --f)
{
while(1)
{
pthread_mutex_lock(&start_mutex);
int found = free_threads;
pthread_mutex_unlock(&start_mutex);
if(found) break;
}
pthread_t t;
fib_data* pdata = malloc(sizeof(fib_data));
pdata->fib_arg = f-1;
pdata->pfree_threads = &free_threads;
pdata->pconsole_mutex = &console_mutex;
pdata->pstart_mutex = &start_mutex;
pthread_mutex_lock(&start_mutex);
--free_threads;
pthread_mutex_unlock(&start_mutex);
pthread_create(&t, 0, thread_main, pdata);
pthread_detach(t);
}
while(1)
{
pthread_mutex_lock(&start_mutex);
int done = free_threads == max_threads;
pthread_mutex_unlock(&start_mutex);
if(done) break;
}
printf("Done\\n");
pthread_mutex_destroy(&start_mutex);
pthread_mutex_destroy(&console_mutex);
return 0;
}
| 1
|
#include <pthread.h>
void * sumRow(void * arg);
pthread_t threads[4];
int sum = 0;
pthread_mutex_t mutex;
int main(int argc, char *argv[]) {
int array[4][10], i, j;
srand(time(0));
for (i = 0; i < 4; i++) {
for (j = 0; j < 10; j++) {
array[i][j] = rand() % 10;
printf("%d ", array[i][j]);
}
printf("\\n");
}
for (i = 0; i < 4; i++) {
pthread_create(&threads[i], 0, sumRow, (void *) array[i]);
}
for (i = 0; i < 4; i++) {
pthread_join(threads[i], 0);
}
printf("Sum %d", sum);
return 0;
}
void * sumRow(void * arg) {
int * a = (int *) arg;
int sumTemp = 0, i = 0;
for (i = 0; i < 10; i++) {
sumTemp += a[i];
}
pthread_mutex_lock(&mutex);
sum += sumTemp;
pthread_mutex_unlock(&mutex);
return ((void *) 0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t sslock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t sscond = PTHREAD_COND_INITIALIZER;
static bool sender_active;
static int sender_sock;
static FILE *sender_fout;
static void fail_sender(int sock, int priority, const char *fmt, ...)
{
char *core_msg = 0;
char *client_msg = 0;
int r;
va_list ap;
__builtin_va_start((ap));
r = vasprintf(&core_msg, fmt, ap);
;
if (r != -1) {
syslog(priority, "%s", core_msg);
r = asprintf(&client_msg, "thruport: %s\\n", core_msg);
if (r != -1) {
write(sock, client_msg, r);
free(client_msg);
}
free(core_msg);
}
}
void instantiate_sender_service(int sock)
{
pthread_mutex_lock(&sslock);
bool a = sender_active;
pthread_mutex_unlock(&sslock);
if (a) {
fail_sender(sock, LOG_ERR, "another sender is already active");
close(sock);
return;
}
int sock2 = dup(sock);
if (sock2 < 0) {
fail_sender(sock, LOG_ERR, "failed to dup sender socket: %m");
close(sock);
return;
}
FILE *fsock_out = fdopen(sock2, "w");
if (fsock_out == 0) {
fail_sender(sock, LOG_ERR, "failed to fdopen sender socket: %m");
close(sock2);
close(sock);
return;
}
setbuf(fsock_out, 0);
pthread_mutex_lock(&sslock);
sender_sock = sock;
sender_fout = fsock_out;
sender_active = 1;
pthread_cond_signal(&sscond);
pthread_mutex_unlock(&sslock);
}
void disconnect_sender(const char *reason)
{
pthread_mutex_lock(&sslock);
if (sender_active) {
if (reason)
fprintf(sender_fout, "thruport: %s\\n", reason);
fclose(sender_fout);
close(sender_sock);
sender_sock = -1;
sender_fout = 0;
sender_active = 0;
}
pthread_mutex_unlock(&sslock);
}
static void unlock(void *arg)
{
pthread_mutex_t *mutex = arg;
pthread_mutex_unlock(mutex);
}
int await_sender_socket(void)
{
int sock;
pthread_mutex_lock(&sslock);
pthread_cleanup_push(unlock, &sslock); {
while (!sender_active)
pthread_cond_wait(&sscond, &sslock);
sock = sender_sock;
} pthread_cleanup_pop(1);
return sock;
}
void report_sender_error(int priority, const char *msg)
{
int e = errno;
syslog(priority, "%s: %m", msg);
pthread_mutex_lock(&sslock);
FILE *fout = sender_fout;
pthread_mutex_unlock(&sslock);
if (fout) {
fprintf(fout, "%s: %s\\n", msg, strerror(e));
fflush(fout);
}
}
| 1
|
#include <pthread.h>
void* consumme(void* param)
{
struct consommateur_param* consommateurParam=(struct consommateur_param*)param;
int size = SIZE;
struct facteurPremier* local = (struct facteurPremier*) malloc(sizeof(*local)*size);
int i;
for(i=0;i<size;i++)
{
local[i].nombre=0;
local[i].multiplicite=0;
local[i].file='\\0';
}
struct nombre n1;
int isBufferEmpty=0;
int isProducing=1;
while(isProducing || !isBufferEmpty)
{
pthread_mutex_lock(consommateurParam->lock);
isProducing=*(consommateurParam->isProducing);
pthread_mutex_unlock(consommateurParam->lock);
isBufferEmpty = readBuffer(consommateurParam->buffer1, &n1);
if (isBufferEmpty != 0 || n1.nombre==0) {
n1.nombre = 0;
n1.file = "\\0";
}
else {
factorisation(&n1,&local,&size);
}
}
publish_result(consommateurParam->global,consommateurParam->size,local,&size,consommateurParam->lockGlobal);
free(param);
free(local);
param=0;
local=0;
return 0;
}
int publish_result(struct facteurPremier** facteurPremierG, int *size, struct facteurPremier* resultatsLocaux, int *localSize, pthread_mutex_t *protectGlobalList)
{
pthread_mutex_lock(protectGlobalList);
int indice = 0;
int nbr = 0;
int countUpdate = 0;
while (indice < *size && (*facteurPremierG)[indice].nombre != 0)
{
indice++;
}
while (nbr < *localSize && resultatsLocaux[nbr].nombre != 0) {
nbr ++;
}
int curseur1 = 0;
for (curseur1; curseur1 < *localSize; curseur1++) {
int deja = 0;
int curseur2 = 0;
for (curseur2; curseur2 < *size && deja ==0; curseur2++) {
if((*facteurPremierG)[curseur2].nombre == resultatsLocaux[curseur1].nombre) {
(*facteurPremierG)[curseur2].multiplicite = resultatsLocaux[curseur1].multiplicite + (*facteurPremierG)[curseur2].multiplicite;
(*facteurPremierG)[curseur2].file = resultatsLocaux[curseur1].file;
deja = 1;
countUpdate ++;
}
}
if (deja == 0) {
if (indice == *size) {
realloc_s ((void **) facteurPremierG,((size_t) *size) * (sizeof **facteurPremierG) * 2);
*size = (*size )* 2;
realloc_zeros(indice, *facteurPremierG, size);
}
if((*facteurPremierG)[indice].nombre == 0) {
(*facteurPremierG)[indice].nombre = resultatsLocaux[curseur1].nombre ;
(*facteurPremierG)[indice].multiplicite = resultatsLocaux[curseur1].multiplicite;
(*facteurPremierG)[indice].file = resultatsLocaux[curseur1].file;
indice ++;
countUpdate ++;
}
}
}
if (countUpdate == nbr) {
pthread_mutex_unlock(protectGlobalList);
return 0;
}
else {
pthread_mutex_unlock(protectGlobalList);
return 1;
}
}
| 0
|
#include <pthread.h>
void serial_init(int fd)
{
struct termios options;
tcgetattr(fd, &options);
options.c_cflag |= ( CLOCAL | CREAD );
options.c_cflag &= ~CSIZE;
options.c_cflag &= ~CRTSCTS;
options.c_cflag |= CS8;
options.c_cflag &= ~CSTOPB;
options.c_iflag |= IGNPAR;
options.c_iflag &= ~(ICRNL | IXON);
options.c_oflag = 0;
options.c_lflag = 0;
cfsetispeed(&options, B115200);
cfsetospeed(&options, B115200);
tcsetattr(fd,TCSANOW,&options);
}
void* recv_from_uart_handler(void* args){
int fd = -1;
char recv_buf[UARTDATALEN] = {0};
if(0 == (hp = create_list_head(&tp))){
perror("create_list_head failed");
return 0;
}
while(1){
pthread_mutex_lock(&mutex_uart);
transfer_msg_to_buf(recv_buf);
printf_envmsg(recv_buf);
pthread_mutex_lock(&mutex_list);
if(!write_to_list_tail(&tp,recv_buf)){
perror("write_to_list_tail failed");
break;
}
printf_list_long(hp);
pthread_mutex_unlock(&mutex_list);
printf("tp:%p, hp:%p\\n",tp,hp);
pthread_mutex_unlock(&mutex_uart);
if(pthread_cond_signal(&cond_list)){
perror("pthread_cond_signal failed");
}
sleep(1);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
extern int nthreads, verbose;
extern char * outfile_name;
static FILE * outfile;
static int* data;
static int nitems;
static int capacity;
int start_merge = 0;
int start;
int end;
int size;
}node_t;
int q_count, m_count, q_in, m_in, q_out, m_out;
pthread_cond_t en1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t de1 = PTHREAD_COND_INITIALIZER;
node_t* q_queue[(64)];
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
static int compare_fn(const void *arg1, const void *arg2) {
return (*((int*)arg1)) - (*((int*)arg2));
}
void q_enqueue(node_t* node) {
pthread_mutex_lock(&m1);
while(q_count >= (64)){
pthread_cond_wait(&en1, &m1);
}
q_queue[(q_in) % (64)] = node;
(q_count)++;
(q_in)++;
pthread_cond_broadcast(&de1);
pthread_mutex_unlock(&m1);
}
int q_null_flag = 0;
node_t* q_dequeue() {
if(q_null_flag){
return 0;
}
pthread_mutex_lock(&m1);
while((q_count) <= 0){
pthread_cond_wait(&de1, &m1);
}
node_t *cur = q_queue[(q_out) % (64)];
if(cur == 0){
q_null_flag = 1;
pthread_cond_broadcast(&en1);
pthread_mutex_unlock(&m1);
return 0;
}
(q_count)--;
(q_out)++;
pthread_cond_broadcast(&en1);
pthread_mutex_unlock(&m1);
return cur;
}
void p_merge(){
}
pthread_cond_t s_leep = PTHREAD_COND_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
void barrier(){
pthread_mutex_lock(&m2);
if(!start_merge){
while(!start_merge)
pthread_cond_wait(&s_leep, &m2);
}
else{
pthread_cond_broadcast(&s_leep);
}
pthread_mutex_unlock(&m2);
}
int No = 0;
void* myworker_func(void* arg){
node_t * node;
while((node = q_dequeue())){
qsort(data + node->start, node->size, sizeof(int), compare_fn);
if(verbose) {
print_stat(data, node->start, node->end);
}
free(node);
}
barrier();
if(nitmes<=256)
return 0;
int seg_len = nitems / nthreads;
p_merge();
return 0;
}
pthread_t *tid;
void stream_init() {
outfile = open_outfile(outfile_name);
data = malloc(16777216*sizeof(int));
tid = malloc((nthreads-1) * sizeof(pthread_t));
for(int i=0; i<nthreads-1; i++){
pthread_create(&tid[i], 0, myworker_func, 0);
}
}
void stream_data(int* buffer, int count) {
int old_n = nitems;
nitems += count;
node_t * new_node = malloc(sizeof(node_t));
new_node->size = count;
new_node->start = old_n;
new_node->end = nitems;
for(int i=0; i<count; i++){
data[old_n+i] = buffer[i];
}
q_enqueue(new_node);
}
void stream_end() {
start_merge = 1;
q_enqueue(0);
create_tesks(0, 0, nitems);
myworker_func(0);
void* t;
for(int i=0; i<(nthreads-1); i++){
pthread_join(tid[i], &t);
}
for(int i = 0; i < nitems; i++)
fprintf(outfile, "%d\\n", data[i]);
if(outfile != stdout)
fclose(outfile);
}
| 0
|
#include <pthread.h>
struct thread_data {
int min_fd;
volatile int max_fd;
const char * mails_outdir;
};
static pthread_mutex_t max_fd_mutex = PTHREAD_MUTEX_INITIALIZER;
static bool has_trailing_slash(const char * dirname) {
assert(dirname);
size_t len_dirname = strlen(dirname);
assert(len_dirname > 0);
return (dirname[len_dirname - 1] == '/');
}
static char * malloc_concat_dirname_basename(
const char * dirname, const char * basename) {
assert(dirname && basename);
size_t len_dirname = strlen(dirname);
assert(len_dirname > 0);
const bool trailing_slash = has_trailing_slash(dirname);
const size_t len_basename = strlen(basename);
const size_t len_res = len_dirname + (trailing_slash ? 0 : 1) + len_basename;
char * const res = malloc(len_res + 1);
assert(res);
const int len_copied = snprintf(res, len_res + 1, "%s%s%s",
dirname, (trailing_slash ? "" : "/"), basename);
assert(len_copied == (int)len_res);
return res;
}
void ripp_file(int input_fd, char * buffer, size_t buffer_size, const char * mails_outdir) {
struct timespec ts;
const int gettime_res = clock_gettime(CLOCK_REALTIME, &ts);
if (gettime_res) {
fprintf(stderr, "[%d] ERROR: Could not get system time to make file name, error %d.\\n", input_fd, errno);
return;
}
char filename[PATH_MAX];
const bool trailing_slash = has_trailing_slash(mails_outdir);
const int len_copied = snprintf(filename, PATH_MAX, "%s%smpack-%ld-%ld.eml",
mails_outdir, trailing_slash ? "" : "/", (long)ts.tv_sec, ts.tv_nsec);
if ((len_copied < 0) || (len_copied > PATH_MAX - 1)) {
fprintf(stderr, "[%d] ERROR: Could not make file name, error %d.\\n", input_fd, errno);
return;
}
const int output_fd = open(filename, O_WRONLY | O_CREAT | O_EXCL, 0600);
if (output_fd == -1) {
fprintf(stderr, "[%d] ERROR: Could not open file \\"%s\\" for writing, error %d.\\n",
input_fd, filename, errno);
} else {
unsigned long total_written = 0;
bool write_error_reported = 0;
for (;;) {
const int bytes_read = read(input_fd, buffer, buffer_size);
if (bytes_read == -1) {
fprintf(stderr, "[%d] ERROR: Could not read from file descriptor, error %d.\\n", input_fd, errno);
break;
}
const int bytes_written = write(output_fd, buffer, bytes_read);
if (bytes_written < bytes_read) {
fprintf(stderr, "[%d] ERROR: Could not write to file \\"%s\\", error %d.\\n",
input_fd, filename, errno);
write_error_reported = 1;
break;
}
total_written += bytes_written;
if (bytes_read < (int)buffer_size) {
break;
}
}
close(output_fd);
if (! write_error_reported)
printf("[%d] Ripped, %lu bytes written to \\"%s\\".\\n",
input_fd, total_written, filename);
}
close(input_fd);
}
static void * ripper_thread(void * p) {
struct thread_data * data = (struct thread_data *)p;
char buffer[4096];
int input_fd = data->min_fd;
for (;;) {
int bytes_read = pread(input_fd, buffer, sizeof(buffer), 0);
if (bytes_read != -1) {
ripp_file(input_fd, buffer, sizeof(buffer), data->mails_outdir);
}
pthread_mutex_lock(&max_fd_mutex);
if (input_fd < data->max_fd) {
input_fd++;
} else {
if (data->max_fd > data->min_fd)
data->max_fd--;
input_fd = data->min_fd;
}
pthread_mutex_unlock(&max_fd_mutex);
sleep(1);
}
return 0;
}
int main(int argc, char ** argv) {
printf("Hello from %s version %s.\\n"
"Please use responsibly. Thanks.\\n"
"\\n",
"mpack traffic ripper", "2011.12.31.19.27");
if (argc != 2) {
fprintf(stderr, "USAGE:\\n %s MAILS_OUTDIR\\n", argv[0]);
return 1;
}
pthread_t thread;
const char * mails_outdir = argv[1];
mkdir(mails_outdir, 0700);
const int inotify_fd = inotify_init();
assert(inotify_fd != -1);
const char * const mpack_tmp_dirs[] = {"/tmp", "/var/tmp"};
const char * wd_to_dir[30];
bool at_least_one_watch = 0;
size_t i = 0;
for (; i < sizeof(mpack_tmp_dirs) / sizeof(char *); i++) {
const int wd = inotify_add_watch(inotify_fd, mpack_tmp_dirs[i], IN_CLOSE_WRITE);
if (wd == -1) {
fprintf(stderr, "ERROR: Could not listening to \\"%s\\".\\n", mpack_tmp_dirs[i]);
continue;
}
assert(wd < (int)(sizeof(wd_to_dir) / sizeof(char *)));
wd_to_dir[wd] = mpack_tmp_dirs[i];
at_least_one_watch = 1;
printf("Now listening to \\"%s\\"...\\n", mpack_tmp_dirs[i]);
}
if (! at_least_one_watch) {
return 1;
}
char buffer[(sizeof(struct inotify_event) + PATH_MAX)];
struct thread_data data;
data.min_fd = inotify_fd + 1;
data.mails_outdir = mails_outdir;
printf("Starting ripper thread...\\n\\n");
const int pthread_create_res = pthread_create(&thread, 0, ripper_thread, (void *)&data);
assert(pthread_create_res == 0);
for (;;) {
const int bytes_read = read(inotify_fd, buffer, (sizeof(struct inotify_event) + PATH_MAX));
if (bytes_read == -1) {
continue;
}
int bytes_processed = 0;
while (bytes_processed < bytes_read) {
struct inotify_event * const event = (struct inotify_event *)(buffer + bytes_processed);
if (! strncmp(event->name, "mpack", sizeof("mpack") - 1)
&& (strlen(event->name) >= (sizeof("mpack") - 1) + (sizeof("XXXXXX") - 1))) {
char * const target = malloc_concat_dirname_basename(wd_to_dir[event->wd], event->name);
assert(target);
const int fd = open(target, O_RDONLY);
if (fd != -1) {
printf("[%d] Adding file \\"%s\\" to queue\\n", fd, target);
pthread_mutex_lock(&max_fd_mutex);
if (fd > data.max_fd) {
data.max_fd = fd;
}
pthread_mutex_unlock(&max_fd_mutex);
} else {
fprintf(stderr, "[X] ERROR: Failed to grab file \\"%s\\", error %d\\n", target, errno);
}
free(target);
}
bytes_processed += sizeof(struct inotify_event) + event->len;
}
}
close(inotify_fd);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *idp)
{
int j,i;
double result=0.0;
int *my_id = idp;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %d, count = %d Threshold reached.\\n",
*my_id, count);
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\\n",
*my_id, count);
pthread_mutex_unlock(&count_mutex);
for (j=0; j < 1000; j++)
result = result + (double)random();
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
int *my_id = idp;
printf("Starting watch_count(): thread %d\\n", *my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal received.\\n", *my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, rc;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
int size,borad[32][32],sum = 0,next[32];
pthread_mutex_t sumLock;
int dijiyobu(int id, int position) {
for(int i = 0; i < next[id]; i++) {
if(borad[id][i] == position || abs(borad[id][i] - position) == next[id] - i) return 0;
}
return 1;
}
void queen(int id) {
if(next[id] == size) {
pthread_mutex_lock(&sumLock);
sum++;
pthread_mutex_unlock(&sumLock);
return;
}
for(int i = 0 ; i < size; i++) {
if(dijiyobu(id, i)) {
borad[id][next[id]] = i;
next[id]++;
queen(id);
next[id]--;
}
}
}
void *goqueen(void* n) {
int id = *((int *)n);
queen(id);
pthread_exit(0);
}
int main() {
pthread_t pt[32];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&sumLock, 0);
scanf("%d", &size);
for (int id = 0; id < size; id++) {
borad[id][0] = id;
next[id] = 1;
int tid = pthread_create(&pt[id], &attr, goqueen, (void*)&borad[id][0]);
}
for (int id = 0; id <size; id++) {
pthread_join(pt[id], 0);
}
printf("sum = %d\\n",sum);
pthread_attr_destroy(&attr);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct divide{
int start,end;
};
struct timeval startread,startcalc,readtime,finish,calctime,overalltime;
char buf1[1000000][50],buf[1000000];
int count,idx;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
void *thread_fun(void *bkm){
struct divide *d=((struct divide*)bkm);
int size=atoi(buf1[0]);
while(d->start >= 0 && d->start < d->end && d->start < size){
if(strcmp(buf1[d->start],"3")==0){
pthread_mutex_lock(&lock);
count++;
pthread_mutex_unlock(&lock);
}printf("wo gaye\\n");
d->start++;
}
}
int main(int argc,char *argv[]){
if(argc!=2){
fprintf(stderr,"Enter Max number of threads\\n");
exit(1);
}
int k,i,j,size;
size=atoi(argv[1]);
system("touch data.txt");
system("rm -r data.txt");
int fp1=open("data.txt",O_WRONLY|O_CREAT,0644);
if(fp1==-1){ perror("file cannot open");}
for(k=1;k<=size;k++){
count=0;idx=1;
pthread_t thread_id[k];
if (pthread_mutex_init(&lock, 0) != 0){
printf("\\n mutex init failed\\n");
return 1;
}
gettimeofday(&startread, 0);
int t1,t2;
t1=clock();
int fp=open("a.txt",O_RDONLY);
read(fp,buf,sizeof(buf));
char *ele;
ele=strtok(buf,"\\n");
j=0;
while(ele!=0){
strcpy(buf1[j++],ele);
ele=strtok(0,"\\n");
}
close(fp);
gettimeofday(&startcalc, 0);
int ss=atoi(buf1[0]);
int jump=ceil(ss/k);
struct divide *d=(struct divide*)malloc(sizeof(struct divide));
for(i=0;i<k;i++){
d->start=(jump*i)+1;
d->end=jump*(i+1);
pthread_create(&thread_id[i],0,&thread_fun,(void*)&d);
}
free(d);
for(i=0;i<k;i++){
pthread_join(thread_id[i],0);
}
t2=clock();
gettimeofday(&finish, 0);
timersub(&startcalc, &startread, &readtime);
timersub(&finish, &startcalc, &calctime);
timersub(&finish, &startread, &overalltime);
pthread_mutex_destroy(&lock);
char threads[10],time[10],temp[20];
sprintf(threads,"%d",k);
sprintf(time,"%lf",((double)(t2-t1))/CLOCKS_PER_SEC);
strcpy(temp,threads); strcat(temp," "); strcat(temp,time); strcat(temp," \\n");
int sss=strlen(temp);
char temp1[sss];
strcpy(temp1,temp);
write(fp1,temp1,sizeof(temp1));
}
close(fp1);
system("gnuplot > load 'plot'");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
float gen_time;
float clock_ticks;
int id = 0;
int ger_fd;
int tick = 0;
int id;
float p_time;
char fifo[15];
float initTick;
int ticks;
Direction dir;
} Vehicle;
void write_log(Vehicle *vehicle, int state){
char dest[2];
char line[200];
char obs[10];
switch(state){
case 3:
strcpy(obs, "entrada");
break;
case 5:
strcpy(obs, "saida");
break;
case 2:
strcpy(obs, "cheio");
break;
case 1:
strcpy(obs, "fechado");
break;
}
switch(vehicle->dir){
case NORTH:
strcpy(dest, "N");
break;
case SOUTH:
strcpy(dest, "S");
break;
case EAST:
strcpy(dest, "E");
break;
case WEST:
strcpy(dest, "W");
break;
}
if (state == 5)
sprintf(line, "%8d ; %7d ; %6s ; %10d ; %6d ; %7s\\n", (int)vehicle->initTick+vehicle->ticks, vehicle->id, dest, (int) vehicle->ticks, (int)(clock_ticks-vehicle->initTick), obs);
else
sprintf(line, "%8d ; %7d ; %6s ; %10d ; %6s ; %7s\\n", (int)vehicle->initTick, vehicle->id, dest, (int) vehicle->ticks, "?", obs);
write(ger_fd, &line, strlen(line));
strcpy(line, "");
}
void* process_V(void* arg){
void* ret = 0;
Vehicle vehicle = *(Vehicle*) arg;
int fdWrite, fdRead;
int state;
if (mkfifo(vehicle.fifo, 0660) != 0)
perror("Error making fifo\\n");
switch(vehicle.dir){
case NORTH:
fdWrite = open("fifoN", O_WRONLY | O_NONBLOCK);
break;
case SOUTH:
fdWrite = open("fifoS", O_WRONLY | O_NONBLOCK);
break;
case WEST:
fdWrite = open("fifoW", O_WRONLY | O_NONBLOCK);
break;
case EAST:
fdWrite = open("fifoE", O_WRONLY | O_NONBLOCK);
break;
default:
break;
}
if (fdWrite != -1){
write(fdWrite, &vehicle, sizeof(Vehicle));
close(fdWrite);
fdRead = open(vehicle.fifo, O_RDONLY);
if (fdRead != -1){
read(fdRead, &state, sizeof(int));
write_log(&vehicle, state);
if(state != 2){
read(fdRead, &state, sizeof(int));
state = 5;
}
}
else;
}
else
state = 2;
write_log(&vehicle, state);
unlink(vehicle.fifo);
return ret;
}
float gen_vehicle(float tot, float curr){
Vehicle *new_vehicle = (Vehicle*)malloc(sizeof(Vehicle));
new_vehicle->id = id;
id++;
int r = rand() % 4;
new_vehicle->initTick = curr;
pthread_t genV;
switch(r){
case 0:
new_vehicle->dir = NORTH;
break;
case 1:
new_vehicle->dir = SOUTH;
break;
case 2:
new_vehicle->dir = EAST;
break;
case 3:
new_vehicle->dir = WEST;
break;
}
char buff[100];
sprintf(buff, "%s%d", "fifo", new_vehicle->id);
strcpy(new_vehicle->fifo, buff);
float park_time = ((rand() % 10) + 1) * clock_ticks;
new_vehicle->p_time = park_time;
new_vehicle->ticks = park_time/clock_ticks;
if(pthread_create(&genV, 0, process_V, new_vehicle) != 0)
perror("Error creating process_v thread...\\n");
int x = rand() % 10;
int tick_till_ncar;
if(x < 2){
tick_till_ncar = 2;
}
else if(x < 5){
tick_till_ncar = 1;
}
else
tick_till_ncar = 0;
return tick_till_ncar;
}
int main(int argc, char* argv[]){
if (argc != 3){
perror("Wrong number of arguments");
exit(1);
}
ger_fd = open("gerador.log", O_WRONLY | O_CREAT, 0660);
char ger_format[] = "Registo do gerador:\\nt(ticks) ; id_viat ; destin ; t_estacion ; t_vida ; observ\\n";
pthread_mutex_lock(&mutex);
write(ger_fd, ger_format, strlen(ger_format));
pthread_mutex_unlock(&mutex);
srand(time(0));
gen_time = (float) atoi(argv[1]);
clock_ticks = (float) atoi(argv[2]);
float num_ticks;
int ticks_for_ncar = 0;
num_ticks = (gen_time/clock_ticks) * 1000;
do{
if (ticks_for_ncar == 0)
ticks_for_ncar = gen_vehicle(clock_ticks, tick);
else
ticks_for_ncar--;
usleep(clock_ticks * 1000);
tick++;
} while (num_ticks != tick);
close(ger_fd);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t input_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t op_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t display_buffer_lock = PTHREAD_MUTEX_INITIALIZER;
static sem_t semitems;
static sem_t semslots;
static sem_t seminput;
pthread_t thid1,thid2,thid3,thid4;
int cnt=0;
char indata[20],outdata[20];
void *input_thread(void *arg)
{
int ret;
char str[20];
while(1)
{
printf("enter the value of a: ");
fflush(stdout);
ret=fgets(str,sizeof(str),stdin);
if(ret==0) exit(1);
pthread_mutex_lock(&input_buffer_lock);
strncpy(indata,str,sizeof(indata));
cnt++;
pthread_mutex_unlock(&input_buffer_lock);
}
pthread_exit(0);
}
void *op_thread(void *arg)
{
int i=0;
char ch[20];
while(1)
{
pthread_mutex_lock(&op_buffer_lock);
while(cnt!=0){
for(i=0;indata[i]!='\\0';i++)
ch[i]=indata[i]-32;
ch[i]='\\0';
strncpy(outdata,ch,sizeof(ch));
printf("ans: %s",outdata);
fflush(stdout);
cnt--;
}
pthread_mutex_unlock(&op_buffer_lock);
}
pthread_exit(0);
}
void *disp_thread(void *arg)
{
pthread_exit(0);
}
int main()
{
int ret;
sigset_t set1,set2;
sigfillset(&set1);
sigprocmask(SIG_BLOCK,&set1,&set2);
ret = pthread_create(&thid1,0,input_thread,0);
if(ret>0) { printf("error in thread creation for consumer\\n"); exit(1); }
ret = pthread_create(&thid3,0,disp_thread,0);
if(ret>0) { printf("error in thread creation for producer\\n"); exit(4); }
ret = pthread_create(&thid2,0,op_thread,0);
if(ret>0) { printf("error in thread creation for consumer\\n"); exit(2); }
pthread_join(thid1,0);
pthread_join(thid2,0);
pthread_join(thid3,0);
pthread_join(thid4,0);
exit(0);
}
| 0
|
#include <pthread.h>
int read_count = 1;
pthread_mutex_t read_count_mutex;
sem_t sem_write_access;
void initialize()
{
sem_init(&sem_write_access,0,1);
pthread_mutex_init(&read_count_mutex,0);
}
int shared_data = 0;
void* reader(void *data)
{
pthread_mutex_lock(&read_count_mutex);
read_count++;
if (read_count == 1)
{
sem_wait(&sem_write_access);
}
pthread_mutex_unlock(&read_count_mutex);
printf("reading shared data : %d\\n",shared_data);
pthread_mutex_lock(&read_count_mutex);
read_count--;
if (read_count == 0)
{
sem_post(&sem_write_access);
}
pthread_mutex_unlock(&read_count_mutex);
}
void* writer(void *data)
{
sem_wait(&sem_write_access);
shared_data = (int)data;
sem_post(&sem_write_access);
printf("writing to data : %d\\n",shared_data);
}
int main(int argc,char *argv[])
{
if (argc != 3)
{
fprintf(stderr,"Error: correct format is <executable> number_of_readers number_of_writers\\n");
return -1;
}
int i=0,num_readers = 0, num_writers = 0;
num_readers = atoi(argv[1]);
num_writers = atoi(argv[2]);
num_readers = (num_readers > (20 >> 1)) ? 20 >> 1 : num_readers;
num_writers = (num_writers > (20 >> 1)) ? 20 >> 1 : num_writers;
initialize();
pthread_t reader_threads[num_readers];
pthread_t writer_threads[num_writers];
for (i=0;i<=num_readers;i++)
{
pthread_create(&reader_threads[i],0,reader,0);
}
for (i=0;i<=num_writers;i++)
{
pthread_create(&writer_threads[i],0,writer,(void*)(i+1));
}
pthread_t more_readers[num_readers];
for (i=0;i<=num_readers;i++)
{
pthread_create(&more_readers[i],0,reader,0);
}
for (i=0;i<=num_readers;i++)
{
pthread_join(reader_threads[i],0);
pthread_join(more_readers[i],0);
}
for (i=0;i<=num_writers;i++)
{
pthread_join(writer_threads[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tp_pthread_create(void*(*main_entry_point)(void *),void *res,pthread_cond_t *condition){
int result;
pthread_t thread_id;
pthread_attr_t thread_attr;
result = pthread_attr_init(&thread_attr);
if (result != 0) {
assert(result);
}
result = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
if (result != 0) {
assert(result);
}
pthread_mutex_t mutex_t;
result = pthread_mutex_init(&mutex_t, 0);
if (result != 0) {
assert(result);
}
pthread_mutex_lock(&mutex_t);
int thread_error = pthread_create(&thread_id, &thread_attr, main_entry_point, res);
pthread_mutex_unlock(&mutex_t);
result = pthread_cond_timedwait(condition, &mutex_t, 0);
if (result != 0) {
assert(result);
}
if (thread_error != 0) {
assert(thread_error);
}
pthread_attr_destroy(&thread_attr);
pthread_mutex_destroy(&mutex_t);
return thread_id;
}
| 0
|
#include <pthread.h>
static int g_temp_cute_leak_check = 0;
pthread_mutex_t mmap_mutex = PTHREAD_MUTEX_INITIALIZER;
static struct cute_mmap_ctx *get_cute_mmap_ctx_tail(struct cute_mmap_ctx *mmap) {
struct cute_mmap_ctx *p;
if (mmap == 0) {
return 0;
}
for (p = mmap; p->next != 0; p = p->next)
;
return p;
}
struct cute_mmap_ctx *add_allocation_to_cute_mmap_ctx(struct cute_mmap_ctx *mmap,
size_t size, void *addr) {
struct cute_mmap_ctx *head = 0;
struct cute_mmap_ctx *p = 0;
pthread_mutex_lock(&mmap_mutex);
head = mmap;
if (head == 0) {
( g_temp_cute_leak_check = g_cute_leak_check, g_cute_leak_check = 0, (head) = malloc(sizeof(struct cute_mmap_ctx)), (head)->next = 0, (head)->line_nr = g_cute_last_exec_line, strncpy((head)->file_path, g_cute_last_ref_file, sizeof((head)->file_path)-1), g_cute_leak_check = g_temp_cute_leak_check );
p = head;
} else {
p = get_cute_mmap_ctx_tail(mmap);
( g_temp_cute_leak_check = g_cute_leak_check, g_cute_leak_check = 0, (p->next) = malloc(sizeof(struct cute_mmap_ctx)), (p->next)->next = 0, (p->next)->line_nr = g_cute_last_exec_line, strncpy((p->next)->file_path, g_cute_last_ref_file, sizeof((p->next)->file_path)-1), g_cute_leak_check = g_temp_cute_leak_check );
p = p->next;
}
p->id = ++g_cute_mmap_id;
p->size = size;
p->addr = addr;
if (p->id == g_cute_leak_id) {
raise(SIGTRAP);
}
pthread_mutex_unlock(&mmap_mutex);
return head;
}
struct cute_mmap_ctx *rm_allocation_from_cute_mmap_ctx(struct cute_mmap_ctx *mmap,
void *addr) {
struct cute_mmap_ctx *head = 0;
struct cute_mmap_ctx *burn = 0;
struct cute_mmap_ctx *last = 0;
pthread_mutex_lock(&mmap_mutex);
head = mmap;
if (mmap == 0) {
pthread_mutex_unlock(&mmap_mutex);
return 0;
}
for (burn = mmap; burn != 0; last = burn, burn = burn->next) {
if (burn->addr == addr) {
break;
}
}
if (burn != 0) {
if (last == 0) {
head = burn->next;
burn->next = 0;
} else {
last->next = burn->next;
burn->next = 0;
}
free(burn);
}
pthread_mutex_unlock(&mmap_mutex);
return head;
}
void del_cute_mmap_ctx(struct cute_mmap_ctx *mmap) {
struct cute_mmap_ctx *p = 0, *t = 0;
int temp = 0;
pthread_mutex_lock(&mmap_mutex);
temp = g_cute_leak_check;
g_cute_leak_check = 0;
for (t = p = mmap; t != 0; p = t) {
t = p->next;
free(p);
}
g_cute_leak_check = temp;
pthread_mutex_unlock(&mmap_mutex);
}
| 1
|
#include <pthread.h>
struct prodcons{
int buf[16];
pthread_mutex_t lock;
int readpos,writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
}prodcons;
void init(struct prodcons *b){
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos=0;
b->writepos=0;
}
void destroy(struct prodcons *b){
pthread_mutex_destroy(&b->lock);
pthread_cond_destroy(&b->notempty);
pthread_cond_destroy(&b->notfull);
}
void put(struct prodcons *b,int data){
pthread_mutex_lock(&b->lock);
while((b->writepos+1)%16==b->readpos){
printf("wait for not full\\n");
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buf[b->writepos]=data;
b->writepos++;
if(b->writepos >= 16)
b->writepos=0;
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
void* producer(void* data){
int n;
for(n=0;n<=50;++n){
sleep(1);
printf("put-->%d\\n",n);
put(&prodcons,n);
}
}
int get(struct prodcons *b){
pthread_mutex_lock(&b->lock);
while(b->writepos==b->readpos){
printf("wait for not empty\\n");
pthread_cond_wait(&b->notempty,&b->lock);
}
int data=b->buf[b->readpos];
b->readpos++;
if(b->readpos>=16)
b->readpos=0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
void* consumer(void* data){
while(1){
sleep(2);
int d=get(&prodcons);
if(d==(-1))
break;
printf("%d-->get\\n",d);
}
printf("consumer stopped!\\n");
pthread_exit(0);
}
int main(){
pthread_t pthid1,pthid2;
init(&prodcons);
pthread_create(&pthid1,0,producer,0);
pthread_create(&pthid2,0,consumer,0);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
destroy(&prodcons);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t g_mutex;
pthread_cond_t g_cond;
pthread_t g_thread[2 + 2];
int nready = 0;
void *consume(void* arg) {
int num = (int) arg;
while(1) {
pthread_mutex_lock(&g_mutex);
{
while (0 == nready) {
printf("%d begin wait a condition, count = %d\\n", num, nready);
pthread_cond_wait(&g_cond, &g_mutex);
}
printf("%d begin consume product, count = %d\\n", num, nready);
--nready;
printf("%d end consume product, count = %d\\n", num, nready);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
}
return 0;
}
void *produce(void *arg) {
int num = (int)arg;
while(1) {
pthread_mutex_lock(&g_mutex);
{
printf("%d begin procude product, count = %d\\n", num, nready);
++nready;
printf("%d end procude product, count = %d\\n", num, nready);
pthread_cond_signal(&g_cond);
printf("%d signal\\n", num);
pthread_mutex_unlock(&g_mutex);
sleep(1);
}
}
return 0;
}
int main() {
int i = 0;
pthread_mutex_init(&g_mutex, 0);
pthread_cond_init(&g_cond, 0);
for (i = 0; i < 2; i++) {
pthread_create(&g_thread[i], 0, consume, (void*)i);
}
for (i = 0; i < 2; i++) {
pthread_create(&g_thread[i], 0, produce, (void*)i);
}
for (i = 0; i < 2 + 2; i++) {
pthread_join(g_thread[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
unsigned int number[10];
pthread_mutex_t lock;
void print_sched_attr(int num){
int policy, rtn;
struct sched_param param;
rtn = pthread_getschedparam(pthread_self(), &policy, ¶m);
if(rtn != 0) perror("Unable to retrieve pthread sched param: ");
printf("Scheduler attributes for [%d]:pid %d, thread %ld, policy: %s, priority: %d\\n",
num,
getpid(),
syscall(SYS_gettid),
(policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???",
param.sched_priority);
}
void *func1(void *arg)
{
int val = *((int *) arg);
printf("Thread start: number %d\\n", val);
print_sched_attr(val);
unsigned int i;
for(i = 0; i < 10000; i++){
if(i == 10000 / 2){
printf("Thread %d is %f way done.\\n", val,number[val]/((float)(10000)));
print_sched_attr(val);
}
pthread_mutex_lock(&lock);
number[val]++;
pthread_mutex_unlock(&lock);
}
printf("Thread end: number %d\\n", val);
return 0;
}
int main(int argc, char* argv[]) {
pthread_t threads[10];
pthread_attr_t attr[10];
int i;
for(i = 0; i < 10; i++){
int ret = pthread_attr_init(&attr[i]);
if(ret != 0){
perror("pthread_attr_init: ");
return 1;
}
}
for(i = 0; i < 10; i++){
int *arg = malloc(sizeof(*arg));
*arg = i;
int ret = pthread_create(&threads[i], &attr[i], func1, arg);
if(ret != 0){
perror("pthread_create: ");
return 1;
}
}
printf("Done creating threads.\\n");
for(i = 0; i < 10; i++){
int rtn = pthread_join(threads[i], 0);
if(rtn != 0){
perror("pthread_join: ");
}
}
return 0;
}
| 0
|
#include <pthread.h>
void init_crasher()
{
srand(time(0));
long crash_sleep = 1+(int) (50.0*rand()/(32767 +1.0));
crash_now = 0;
pthread_mutex_init(&(crash_mutex), 0);
if (pthread_create(&(crash_thread), 0, crash_return,
(void *)(crash_sleep)) != 0) {
fprintf(stderr,"Didn't init crasher thread\\n");
}
pthread_detach(crash_thread);
}
int crash_write(int vdisk, const void * buf, int num_bytes)
{
pthread_mutex_lock(&(crash_mutex));
if (0 == crash_now){
pthread_mutex_unlock(&(crash_mutex));
return write(vdisk, buf, num_bytes);
} else {
pthread_mutex_unlock(&(crash_mutex));
fprintf(stderr, "SUPERBLOCK: %i\\n", sb.clean_shutdown);
fprintf(stderr, "CRASH!!!!!\\n");
exit(-1);
}
pthread_mutex_unlock(&(crash_mutex));
return 0;
}
void * crash_return(void * args) {
long crash_sleep = (long)args;
fprintf(stderr, "crash sleeping for %lu\\n",
crash_sleep * CRASHES_IN_100);
sleep(crash_sleep * CRASHES_IN_100);
pthread_mutex_lock(&(crash_mutex));
crash_now = 1;
pthread_mutex_unlock(&(crash_mutex));
return 0;
}
| 1
|
#include <pthread.h>
int in_use[PID_MAX + 1];
pthread_mutex_t test_mutex;
void *allocator(void *param)
{
int i, pid;
for (i = 0; i < 10; i++) {
sleep((int)(random() % 5));
pid = allocate_pid();
printf("allocated %d\\n",pid);
if (pid == -1)
printf("No pid available\\n");
else {
pthread_mutex_lock(&test_mutex);
if (in_use[pid] == 1) {
fprintf(stderr,"***PID ALREADY IN USE****\\n");
}
else
in_use[pid] = 1;
pthread_mutex_unlock(&test_mutex);
sleep((int)(random() % 5));
release_pid(pid);
pthread_mutex_lock(&test_mutex);
in_use[pid] = 0;
pthread_mutex_unlock(&test_mutex);
printf("released %d\\n",pid);
}
}
}
int main(void)
{
int i;
pthread_t tids[100];
for (i = 0; i <= PID_MAX; i++) {
in_use[i] = 0;
}
pthread_mutex_init(&test_mutex, 0);
if (allocate_map() == -1)
return -1;
srandom((unsigned)time(0));
for (i = 0; i < 100; i++) {
pthread_create(&tids[i], 0, allocator, 0);
}
for (i = 0; i < 100; i++)
pthread_join(tids[i], 0);
printf("***DONE***\\n");
return 0;
}
| 0
|
#include <pthread.h>
int a;
pthread_mutex_t mutex;
pthread_cond_t cv;
int thread_index;
} thread_param;
void *Thread_A(void *arg) {
thread_param *params = (thread_param *) arg;
printf("thread %d is created\\n", params->thread_index);
pthread_mutex_lock(&mutex);
if (a < 5) {
printf("Thread %d goes to sleep\\n", params->thread_index);
pthread_cond_wait(&cv, &mutex);
}
printf("thread %d wakes up\\n", params->thread_index);
pthread_mutex_unlock(&mutex);
}
void *Thread_B(void *arg) {
thread_param *param = (thread_param *) arg;
int i;
printf("thread %d created\\n", param->thread_index);
for (i=0; i < 5; i++) {
pthread_mutex_lock(&mutex);
a++;
printf("thread %d says a is %d\\n", param->thread_index, a);
if (a==5)
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mutex);
}
}
int main(void) {
a = 0;
int i;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cv, 0);
pthread_t *threads = (pthread_t *) malloc(sizeof(pthread_t *) * 2);
thread_param *thread_params = (thread_param *) malloc(sizeof(thread_param *) * 2);
for (i = 0; i < 2; i++)
thread_params[i].thread_index = i;
if (pthread_create(&threads[0], &attr, Thread_A, &thread_params[0]) != 0)
printf("thread creating failed\\n");
if (pthread_create(&threads[1], &attr, Thread_B, &thread_params[1]) != 0)
printf("thread creating failed\\n");
pthread_attr_destroy(&attr);
for (i = 0; i < 2; i++) {
if (pthread_join(threads[i], 0) != 0) {
printf("joing thread failed\\n");
}
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cv);
free(threads);
free(thread_params);
return 0;
}
| 1
|
#include <pthread.h>
void * handle_clnt(void * arg);
void send_msg(char * msg, int len);
void error_handling(char * msg);
int clnt_cnt=0;
int clnt_socks[256];
pthread_mutex_t mutx;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
if(argc!=2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
while(1)
{
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr, &clnt_adr_sz);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_cnt++]=clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock);
pthread_detach(t_id);
printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr));
}
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg)
{
int clnt_sock=*((int*)arg);
int str_len=0, i;
char msg[256];
while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0)
send_msg(msg, str_len);
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
{
if(clnt_sock==clnt_socks[i])
{
while(i++<clnt_cnt-1)
clnt_socks[i]=clnt_socks[i+1];
break;
}
}
clnt_cnt--;
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void send_msg(char * msg, int len)
{
int i;
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
write(clnt_socks[i], msg, len);
pthread_mutex_unlock(&mutx);
}
void error_handling(char * msg)
{
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
| 0
|
#include <pthread.h>
struct node *head_gv;
char work_set[30][1024 * 32];
struct thread_arg{
int start_row ;
int n_sentence;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int printWordCount(char *sentence)
{
int ret = 0;
int letter = 0;
int word_count = 0;
char word_buf[32];
char *chp = sentence;
struct node* next_node;
int flag = 0;
int word_end = 0;
if (!chp) {
ret = -EINVAL;
return ret;
}
while((*chp != '\\0') && letter < 32)
{
word_end = (*chp ==' '|| *chp =='\\t'|| *chp =='\\n');
if(flag && word_end) {
word_buf[letter] = '\\0';
pthread_mutex_lock(&mutex);
ret= search(word_buf, head_gv);
pthread_mutex_unlock(&mutex);
if (!ret) {
next_node = (struct node*)malloc(sizeof(struct node));
pthread_mutex_lock(&mutex);
strncpy((char*)next_node->word, word_buf, 32);
next_node->count = 1;
head_gv = append(next_node, head_gv);
pthread_mutex_unlock(&mutex);
}
word_count++;
letter = 0;
flag = 0;
} else if ((!flag && !word_end) || (flag)) {
word_buf[letter] = *chp;
letter++;
flag = 1;
}
chp++;
}
if (letter >= 32) {
ret = -EINVAL;
} else {
}
return ret;
}
void* thread_work(void* arg)
{
int print_ret=0;
struct thread_arg* th_arg = (struct thread_arg*) arg;
int i =0;
for (i=th_arg->start_row; i< th_arg->start_row + th_arg->n_sentence; i++)
{
print_ret = printWordCount(work_set[i]);
}
pthread_exit(0);
}
int work_item = 0;
int main(void) {
int ret = 0;
char *str = 0;
char sentence[1024 * 32];
int tid = 0;
pthread_t threads[4];
struct thread_arg arg[4];
int exit_code[4];
int *exit_ptr[4];
int rows_per_thread;
int req_threads;
head_gv = (struct node*)malloc(sizeof(struct node));
strcpy((char*)head_gv->word, "\\0");
initHead(head_gv);
FILE *fp;
fp = fopen("sampletext2.txt", "r");
if (!fp) {
printf("ERR File :%d\\n", errno);
return errno;
}
do {
str = fgets(sentence, 1024 * 32, fp);
if (!str) {
break;
} else {
strcpy((char*)work_set[work_item], str);
work_item++;
}
} while (str && (work_item < 30));
fclose(fp);
req_threads = (work_item/10) + 1;
if (req_threads > 4) {
req_threads = 4;
}
rows_per_thread = work_item/req_threads;
for(tid =0; tid < req_threads ; tid++)
{
arg[tid].start_row = rows_per_thread * tid;
assert(arg[tid].start_row < work_item);
arg[tid].n_sentence = rows_per_thread;
if (tid == req_threads) {
arg[tid].n_sentence+=work_item % req_threads;
}
pthread_create(&threads[tid], 0, &thread_work, &arg[tid]);
}
for(tid =0; tid < 4;tid++) {
exit_ptr[tid] = &exit_code[tid];
pthread_join(threads[tid], (void*)&exit_ptr[tid]);
}
printf("Word List\\t\\tFrequency\\n");
printlist(head_gv);
deletelist(head_gv);
head_gv = 0;
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t cv;
pthread_mutex_t mutex;
int length;
int queue[200];
void *producer(void *param){
for(int i=0;i<200;i++){
pthread_mutex_lock(&mutex);
queue[length++]=i;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&mutex);
}
}
void *producer(void * param){
item_t *item;
for(int i=0;i<200;i++){
pthread_mutex_lock(&mutex);
queue[length++]=i;
pthread_cond_broadcast(&cv);
pthread_mutex_unlock(mutex);
}
}
void *consumer(void *param){
for(int i=0;i<200;i++){
int seconds=0;
pthread_mutex_lock(&mutex);
while(length==0){
pthread_cond_wait(&cv,&mutex);
}
int item = queue[--length];
pthread_mutex_unlock(&mutex);
}
}
int main(){
pthread_t threads[2];
pthread_cond_init(&cv,0);
pthread_mutex_init(&mutex,0);
length=0;
pthread_create(&threads[0],0,producer,0);
pthread_create(&threads[1],0,consumer,0);
pthread_join(&threads[1],0);
pthread_join(&threads[0],0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cv);
}
| 0
|
#include <pthread.h>
pthread_t philosopher[5];
pthread_mutex_t forks[5];
void *funmutex(int n);
void *funmutex(int n) {
printf("\\nPhilosopher %d is thinking \\n",n);
pthread_mutex_lock(&forks[n]);
pthread_mutex_lock(&forks[(n+1)%5]);
printf("\\nPhilosopher %d is eating \\n",n);
sleep(3);
pthread_mutex_unlock(&forks[n]);
pthread_mutex_unlock(&forks[(n+1)%5]);
printf("\\nPhilosopher %d has finished eating \\n",n);
}
int main() {
int i,k;
void *msg;
for(i=1;i<=5;i++) {
k=pthread_mutex_init(&forks[i],0);
if(k==-1) {
printf("Mutex initialization failed\\n");
exit(1);
}
}
for(i=1;i<=5;i++) {
k=pthread_create(&philosopher[i],0,(void *)funmutex,(int *)i);
if(k!=0) {
printf("Thread creation error");
exit(1);
}
}
for(i=1;i<=5;i++) {
k=pthread_join(philosopher[i],&msg);
if(k!=0) {
printf("Thread join failure");
exit(1);
}
}
for(i=1;i<=5;i++) {
k=pthread_mutex_destroy(&forks[i]);
if(k!=0) {
printf("Mutex Destroyed\\n");
exit(1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
struct keyset {
const char **set;
int set_size;
int next_idx;
pthread_mutex_t lock;
};
struct keyset *
keyset_init(int num, const char *prefix)
{
struct keyset *ks;
char buf[128];
int i;
ks = malloc(sizeof(*ks));
memset(ks, 0, sizeof(*ks));
pthread_mutex_init(&ks->lock, 0);
ks->set_size = num;
ks->set = malloc(num * sizeof(char*));
for (i = 0; i < num; i++) {
if (prefix != 0)
sprintf(buf, "%stestkey-%d", prefix, i);
else
sprintf(buf, "testkey-%d", i);
ks->set[i] = strdup(buf);
}
keyset_reset(ks);
return ks;
}
void
keyset_reset(struct keyset *ks)
{
ks->next_idx = 0;
}
const char *
keyset_get_key(struct keyset *ks, int *id)
{
int idx;
const char *key;
pthread_mutex_lock(&ks->lock);
idx = ks->next_idx;
ks->next_idx++;
if (ks->next_idx >= ks->set_size)
ks->next_idx = 0;
key = ks->set[idx];
pthread_mutex_unlock(&ks->lock);
if (id != 0)
*id = idx;
return key;
}
| 0
|
#include <pthread.h>
int tlog_mask = 31;
static int t_init = 0;
static char tproc[PROC_NAME_SIZE];
static pthread_mutex_t mask_mutex = PTHREAD_MUTEX_INITIALIZER;
static void signal2_callback(char *proc, int value1, int value2)
{
switch (value1) {
case 1:
if ((value2 < 0) || (value2 > 8))
return;
pthread_mutex_lock(&mask_mutex);
tlog_mask |= (1 << value2);
pthread_mutex_unlock(&mask_mutex);
break;
case 2:
if ((value2 < 0) || (value2 > 8))
return;
pthread_mutex_lock(&mask_mutex);
tlog_mask &= ~(1 << value2);
pthread_mutex_unlock(&mask_mutex);
break;
case 3:
if ((value2 < 0) || (value2 > 255))
return;
pthread_mutex_lock(&mask_mutex);
tlog_mask = value2;
pthread_mutex_unlock(&mask_mutex);
break;
default:
return;
break;
}
return;
}
int tsyslog_set(int value)
{
if (!t_init)
return 1;
signal2_callback("", 1, value);
return 0;
}
int tsyslog_del(int value)
{
if (!t_init)
return 1;
signal2_callback("", 2, value);
return 0;
}
int tsyslog_replace(int value)
{
if (!t_init)
return 1;
signal2_callback("", 3, value);
return 0;
}
int tsyslog_get(void)
{
if (!t_init)
return 256;
return tlog_mask;
}
static void _tsyslog(int priority, const char *fmt, ...)
{
va_list ap;
if (!t_init)
return;
if (tlog_mask & (1 << priority)) {
__builtin_va_start((ap));
vsyslog(priority, fmt, ap);
;
}
}
int tsyslog_prio_init(char *name, int priomask)
{
int retvalue;
if (t_init)
return 3;
if ((priomask < 0) || (priomask > 255))
return 4;
signal2_callback("", 3, priomask);
if ((retvalue = tsyslog_init(name)) != 0)
return retvalue;
return 0;
}
int tsyslog_init(char *name)
{
int oldvalue = 0;
int retvalue = 0;
if (t_init) {
syslog(LOG_INFO,
"tsyslog_init: Already registered in this process (%d) as %s. You wanted %s.",
getpid(), tproc, name);
return 3;
}
if (name == 0)
return 1;
strncpy(tproc, name, (PROC_NAME_SIZE - 1));
logfunction_register(_tsyslog);
openlog(tproc, LOG_NDELAY | LOG_CONS, LOG_LOCAL0);
pthread_mutex_lock(&mask_mutex);
oldvalue = tlog_mask;
tlog_mask = 64;
tsyslog(LOG_INFO, "Initializing tsyslog\\n");
tlog_mask = oldvalue;
pthread_mutex_unlock(&mask_mutex);
if ((retvalue = init_memshare(tproc, 50, 512)) != 0) {
syslog(LOG_ERR, "tsyslog_init: init_memshare returned %d",
retvalue);
return 2;
}
signal2_register(signal2_callback);
t_init = 1;
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(5))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (get_top()==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(5);
if (push(arr,tmp)==(-1))
error();
flag=(1);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (flag)
{
if (!(pop(arr)!=(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t qMutex;
pthread_cond_t qCond;
int loggerrunning = 1;
char* message;
int length;
struct queue *next;
} Queue;
Queue *pendingLogs;
int queueEmpty() {
return pendingLogs == 0;
}
int logpop(char* msg, int buffersize) {
pthread_mutex_lock(&qMutex);
if (queueEmpty()){
pthread_mutex_unlock(&qMutex);
return 1;
}
else {
Queue *currentP = pendingLogs;
Queue *prevP = 0;
while (currentP->next != 0){
prevP = currentP;
currentP = currentP->next;
}
strncpy(msg, currentP->message, currentP->length);
msg[(currentP->length)] = '\\0';
free(currentP);
currentP = 0;
if (prevP){
prevP->next = 0;
} else {
if (!currentP){
pendingLogs = 0;
}
}
pthread_mutex_unlock(&qMutex);
return 0;
}
}
void *logpush(char* msg) {
Queue *newQueueP = malloc(sizeof(*newQueueP));
newQueueP->message = malloc(strlen(msg)*sizeof(char)+1);
newQueueP->length = strlen(msg);
strncpy(newQueueP->message, msg, strlen(msg));
newQueueP->next = 0;
pthread_mutex_lock(&qMutex);
if (queueEmpty()) {
pendingLogs = newQueueP;
}
else if (!queueEmpty()){
newQueueP->next = pendingLogs;
pendingLogs = newQueueP;
}
pthread_cond_signal(&qCond);
pthread_mutex_unlock(&qMutex);
}
void *writeLog(void *intP){
int *runningP = (int *) intP;
FILE *logfileP = fopen("/var/log/erss-proxy.log", "a+");
printf("writing to %S", "/var/log/erss-proxy.log");
char *buff = malloc(sizeof(char)*50);
pthread_mutex_lock(&qMutex);
while (*runningP){
while (queueEmpty()){
pthread_cond_wait(&qCond, &qMutex);
}
pthread_mutex_unlock(&qMutex);
int rc = logpop(buff, 50);
if (!rc) {
printf("logging thread wrote: %s \\n", buff);
fprintf(logfileP, "%s\\n", buff);
}
memset(buff, 0, 50*sizeof(char));
}
fclose(logfileP);
free(buff);
exit(0);
}
int initlogging(){
pthread_t logThread;
int rc;
rc = pthread_create(&logThread, 0, writeLog, &loggerrunning);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
return -1;
}
return 0;
}
int stoplogging(){
loggerrunning = 0;
}
| 1
|
#include <pthread.h>
pthread_t threads[3];
pthread_mutex_t mutex;
pthread_cond_t event;
int cpt_global=0;
void rdva()
{
if(cpt_global==3*10)
{
pthread_mutex_lock(&mutex);
pthread_cond_broadcast(&event);
pthread_mutex_unlock(&mutex);
}
else
{
drawrec (300,30,5,200);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&event,&mutex);
pthread_mutex_unlock(&mutex);
}
}
void rdvb()
{
if(cpt_global==3*10)
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&event);
pthread_cond_signal(&event);
pthread_mutex_unlock(&mutex);
}
else
{
drawrec (300,30,5,200);
pthread_mutex_lock(&mutex);
pthread_cond_wait(&event,&mutex);
pthread_mutex_unlock(&mutex);
}
}
void *th_fonc (void * arg) {
int i,j;
int numero;
int m1,m2,m3;
int k;
numero = (int)arg;
m1 = 20;
m2 = 30;
m3 = 40;
thread_wait(-1,0,0);
if(numero==0)
{
printf("numero= %d, i=%d \\n",numero,i);
pthread_mutex_lock(&mutex);
drawstr (30, 75, "_0_", 3);
drawrec (100,50,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
printf("num %d j=%d\\n",numero,j);
thread_wait(numero,0,30);
pthread_mutex_lock(&mutex);
k=cpt_global;
fillrec (100,52,100+j*10,26,"yellow");
k++;
cpt_global=k;
pthread_mutex_unlock(&mutex);
if(j==10)
{
rdvb();
}
}
flushdis ();
}
if(numero==1)
{
i = m1;
printf("numero= %d, i=%d \\n",numero,i);
pthread_mutex_lock(&mutex);
drawstr (30, 125, "_1_", 3);
drawrec (100,100,100+m2*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m2;j++) {
printf("num %d j=%d\\n",numero,j);
thread_wait(numero,0,70);
pthread_mutex_lock(&mutex);
k=cpt_global;
fillrec (100,102,100+j*10,26,"green");
k++;
cpt_global=k;
pthread_mutex_unlock(&mutex);
if(j==10)
{
rdvb();
}
}
flushdis ();
}
if(numero==2)
{
i = m1;
printf("numero= %d, i=%d \\n",numero,i);
pthread_mutex_lock(&mutex);
drawstr (30, 175, "_2_", 3);
drawrec (100,150,100+m3*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m3;j++) {
printf("num %d j=%d\\n",numero,j);
thread_wait(numero,0,100);
pthread_mutex_lock(&mutex);
k=cpt_global;
fillrec (100,152,100+j*10,26,"blue");
k++;
cpt_global=k;
pthread_mutex_unlock(&mutex);
if(j==10)
{
rdvb();
}
}
flushdis ();
}
return ( (void *)(numero+100) );
}
int main(int argc, char *argv[])
{
int is, i;
void* val=0;
initrec();
is = pthread_mutex_init(&mutex, 0);
pthread_cond_init(&event, 0);
for (i = 0; i<3; i++) {
printf("Creation du thread : %d\\n",i);
is = pthread_create(&threads[i], 0, th_fonc, (void *)i );
if(is==-1){perror("Erreur");}
}
for (i = 0; i < 3; i++) {
is = pthread_join(threads[i], &val);
if(is==-1){perror("Erreur");}
printf("Fin du thread : %d\\n",i);
}
detruitrec();
return 0;
}
| 0
|
#include <pthread.h>
int flag;
pthread_cond_t cond;
pthread_mutex_t mutex;
void init()
{
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
flag = 0;
}
void *consume_wait(void *pid)
{
int id = *(int *)pid;
while (1)
{
pthread_mutex_lock(&mutex);
while (!flag)
{
pthread_cond_wait(&cond, &mutex);
}
--flag;
printf("<<<pick one:flag=%d\\n", flag);
pthread_mutex_unlock(&mutex);
}
return 0;
}
void *produce_notify()
{
pthread_mutex_lock(&mutex);
if (flag == 0)
pthread_cond_signal(&cond);
++flag;
printf(">>>produce one:flag=%d\\n", flag);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
int id;
pthread_t wait[3], notify[10];
init();
for(id=0; id<10; id++)
pthread_create(¬ify[id], 0,
produce_notify, 0);
for(id=0; id<3; id++)
pthread_create(&wait[id], 0,
consume_wait, &id);
printf("Wait for all threads to stop\\n");
for(id=0; id<10; id++)
pthread_join(notify[id], 0);
for(id=0; id<3; id++)
pthread_join(wait[id], 0);
printf("end main thread is running\\n");
return 0;
}
| 1
|
#include <pthread.h>
{
FILE *file;
char *fileName;
char *filePath;
int isDebug;
size_t maxSize;
size_t actSize;
pthread_mutex_t mutex;
} *log_t;
static const unsigned long dftFileSize = (1 * 0x400 * 0x100000L);
static pthread_mutex_t logMutex = PTHREAD_MUTEX_INITIALIZER;
static log_t sLogger = 0;
void redis_log_init(const char *log_dir, int log_flag, const char *log_progname)
{
char ident[(4096)];
struct stat st;
sLogger = (log_t) malloc(sizeof(struct log_st));
memset(sLogger, 0, sizeof(struct log_st));
memset((void *)ident, 0, sizeof(ident));
snprintf(ident, (4096) - 1 , "%.200s/%s.log", log_dir, log_progname);
sLogger->file = fopen(ident, "a+");
if(sLogger->file == 0) {
fprintf(stderr,
"ERROR: couldn't open logfile: %m\\n");
return ;
}
sLogger->isDebug = log_flag;
sLogger->fileName = strdup(ident);
sLogger->filePath = strdup(log_dir);
sLogger->maxSize = dftFileSize;
if (stat(ident, &st) == -1) {
sLogger->actSize = 0;
} else {
sLogger->actSize = st.st_size;
}
}
void redis_log_destroy() {
if (sLogger) {
if (sLogger->fileName)
free(sLogger->fileName);
if (sLogger->filePath)
free(sLogger->filePath);
if (sLogger->file)
fclose(sLogger->file);
free(sLogger);
sLogger = 0;
}
}
static void log_check(size_t size)
{
if (sLogger->actSize + size > sLogger->maxSize)
{
char divFileName[512];
struct timeval tmval;
struct tm *time;
gettimeofday(&tmval, 0);
time = localtime(&(tmval.tv_sec));
snprintf(divFileName, 512, "%s_%4d_%02d_%02d_%02d_%02d_%02d",
sLogger->fileName, time->tm_year + 1900, time->tm_mon + 1,
time->tm_mday, time->tm_hour, time->tm_min, time->tm_sec);
fclose(sLogger->file);
rename(sLogger->fileName, divFileName);
sLogger->file = fopen(sLogger->fileName, "a+");
sLogger->actSize = 0;
}
}
static int do_log(int lvl, char *fmt, va_list ap)
{
char *s = ": ";
char message[(4096)];
time_t timeval;
size_t len, size;
if (lvl < sLogger->isDebug)
{
return 0;
}
timeval = time(0);
strcpy(message, ctime(&timeval));
switch(lvl) {
case L_DEBUG:
s = ": Debug: ";
break;
case L_WARN:
s = ": Warn: ";
break;
case L_INFO:
s = ": Info: ";
break;
case L_ERR:
s = ": Error: ";
break;
}
strncpy(message + 24, s, sizeof(message) - 24);
len = strlen(message);
vsnprintf(message + len, (4096) - len, fmt, ap);
if (strlen(message) >= sizeof(message))
exit(-1);
for (s = message; *s; s++) {
if (*s == '\\r' || *s == '\\n') {
*s = ' ';
} else if ((unsigned char)(*s) < 32
|| ((unsigned char)(*s) >= 128
&& (unsigned char)(*s) <= 160)) {
*s = '?';
}
}
size = strlen(message)+1;
log_check(size);
sLogger->actSize += size;
fprintf(sLogger->file,"%s", message);
fprintf(sLogger->file, "\\n");
fflush(sLogger->file);
return 0;
}
int redis_log_debug(char *msg, ...)
{
va_list ap;
int r;
__builtin_va_start((ap));
pthread_mutex_lock(&logMutex);
r = do_log(L_DEBUG, msg, ap);
pthread_mutex_unlock(&logMutex);
;
return r;
}
int redis_log(int lvl, char *msg, ...)
{
va_list ap;
int r;
__builtin_va_start((ap));
pthread_mutex_lock(&logMutex);
r = do_log(lvl, msg, ap);
pthread_mutex_unlock(&logMutex);
;
return r;
}
| 0
|
#include <pthread.h>
static int glob = 0;
static pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t mtx3 = PTHREAD_MUTEX_INITIALIZER;
static void *
threadFunc1(void *arg)
{
pthread_mutex_lock(&mtx1);
if(glob%2==0){
pthread_mutex_lock(&mtx2);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx2);
pthread_mutex_unlock(&mtx1);
}
else{
pthread_mutex_lock(&mtx3);
glob += 1;
printf("in t1 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx3);
pthread_mutex_unlock(&mtx1);
}
return 0;
}
static void *
threadFunc2(void *arg)
{
pthread_mutex_lock(&mtx2);
pthread_mutex_lock(&mtx1);
glob += 1;
printf("in t2 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx1);
pthread_mutex_unlock(&mtx2);
return 0;
}
static void *
threadFunc3(void *arg)
{
pthread_mutex_lock(&mtx3);
pthread_mutex_lock(&mtx1);
glob += 1;
printf("in t3 glob = %d\\n", glob);
pthread_mutex_unlock(&mtx1);
pthread_mutex_unlock(&mtx3);
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t t1, t2, t3;
int s;
s = pthread_create(&t1, 0, threadFunc1, 0);
s = pthread_create(&t2, 0, threadFunc2, 0);
s = pthread_create(&t3, 0, threadFunc3, 0);
s = pthread_join(t1, 0);
s = pthread_join(t2, 0);
s = pthread_join(t3, 0);
printf("glob = %d\\n", glob);
return 0;
}
| 1
|
#include <pthread.h>
char stol[10] = {' ',' ',' ',' ',' ',' ',' ',' ',' ',' '};
int pozicia_na_umiestnenie = 0;
int pozicia_na_zobratie = 0;
int stoj = 0;
int pocetVygenerovanych = 0, pocetTestovanych = 0;
pthread_mutex_t mutexSynchronizacia = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condPlny = PTHREAD_COND_INITIALIZER;
pthread_cond_t condPrazdny = PTHREAD_COND_INITIALIZER;
int jePlnyStol(){
if(pocetVygenerovanych - pocetTestovanych == 10){
return 1;
}
return 0;
}
int jePrazdnyStol(){
if(pocetVygenerovanych == pocetTestovanych){
return 1;
}
return 0;
}
char generuj_pismenko(void)
{
sleep(1);
return 'A';
}
void testuj_pismenko(char pismenko)
{
sleep(2);
}
void *generovac_pismenok( void *ptr ) {
while(!stoj) {
char pismenko = generuj_pismenko();
pthread_mutex_lock(&mutexSynchronizacia);
while(jePlnyStol()){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ptr;
}
printf("G: Plny stol ... cakam\\n");
pthread_cond_wait(&condPlny, &mutexSynchronizacia);
}
stol[pozicia_na_umiestnenie] = pismenko;
pocetVygenerovanych++;
printf("G: Vygeneroval som pismenko | rozdiel: %d\\n", pocetVygenerovanych - pocetTestovanych);
pozicia_na_umiestnenie = (pozicia_na_umiestnenie + 1) % 10;
pthread_cond_signal(&condPrazdny);
pthread_mutex_unlock(&mutexSynchronizacia);
}
return 0;
}
void *testovac_pismenok( void *ptr ) {
while(!stoj) {
pthread_mutex_lock(&mutexSynchronizacia);
while(jePrazdnyStol()){
if(stoj){
pthread_mutex_unlock(&mutexSynchronizacia);
return ptr;
}
printf("T: Prazdny stol ... cakam\\n");
pthread_cond_wait(&condPrazdny, &mutexSynchronizacia);
}
char pismenko = stol[pozicia_na_zobratie];
pocetTestovanych++;
printf("T: Otestoval som pismenko | rozdiel: %d\\n", pocetVygenerovanych - pocetTestovanych);
pozicia_na_zobratie = (pozicia_na_zobratie + 1) % 10;
pthread_cond_signal(&condPlny);
pthread_mutex_unlock(&mutexSynchronizacia);
testuj_pismenko(pismenko);
}
return 0;
}
int main(void) {
int i;
pthread_t generovaci[4];
pthread_t testovaci[10];
for (i=0;i<4;i++) pthread_create( &generovaci[i], 0, &generovac_pismenok, 0);
for (i=0;i<10;i++) pthread_create( &testovaci[i], 0, &testovac_pismenok, 0);
sleep(30);
printf("Koniec simulacie !!!\\n");
pthread_mutex_lock(&mutexSynchronizacia);
stoj = 1;
pthread_cond_broadcast(&condPlny);
pthread_cond_broadcast(&condPrazdny);
pthread_mutex_unlock(&mutexSynchronizacia);
for (i=0;i<4;i++) pthread_join( generovaci[i], 0);
for (i=0;i<10;i++) pthread_join( testovaci[i], 0);
printf("Pocet vygenerovanych pismen: %d\\n", pocetVygenerovanych);
printf("Pocet otestovanych pismen: %d\\n", pocetTestovanych);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_t philosopher[50];
pthread_mutex_t chopstick[50];
int p=5;
int meal=5;
void *func(int n)
{
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n+1)%p]);
printf ("Philosopher %d is eating\\n\\n",n);
usleep(500000);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%p]);
printf ("Philosopher %d finished eating\\n",n);
printf ("Philosopher %d is thinking\\n",n);
return(0);
}
int main(int argc, char *argv[] )
{
if(argc==1)
{
p=5;
meal=5;
}
if(argc==2)
{
p=atoi(argv[1]);
meal=5;
}
if(argc==3)
{
p=atoi(argv[1]);
meal=atoi(argv[2]);
}
printf ("All %d philosophers are thinking\\n",p);
for(int j=0;j<meal;j++)
{
for(int i=0;i<p;i++)
pthread_mutex_init(&chopstick[i],0);
for(int i=0;i<p;i++)
pthread_create(&philosopher[i],0,(void *)func,(void *)i);
for(int i=0;i<p;i++)
pthread_join(philosopher[i],0);
for(int i=0;i<p;i++)
pthread_mutex_destroy(&chopstick[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
int quit_flag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void thread_f(void* arg) {
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\n[thread]interrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quit_flag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return 0;
default:
printf("\\n[thread]unexprected signal\\n");
}
}
}
int main(void) {
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
pthread_sigmask(SIG_BLOCK, &mask, &oldmask);
pthread_create(&tid, 0, thread_f, 0);
pthread_mutex_lock(&lock);
while(quit_flag == 0) {
pthread_cond_wait(&wait, &lock);
}
pthread_mutex_unlock(&lock);
quit_flag = 0;
sigprocmask(SIG_SETMASK, &oldmask, 0);
}
| 0
|
#include <pthread.h>
struct connection_pool* new_connection_pool() {
struct connection_pool* pool = malloc(sizeof(struct connection_pool));
pool->head = 0;
pool->tail = 0;
pthread_mutex_init(&(pool->mutex), 0);
return pool;
}
void delete_connection_pool(struct connection_pool* pool) {
while (pool->head != 0) {
struct connection_list* list = pool->head;
while (list->head != 0) {
int sockfd = get_connection(pool, list->host, list->port);
close(sockfd);
}
pool->head = list->next;
free(list->host);
free(list);
}
pthread_mutex_destroy(&(pool->mutex));
free(pool);
}
int get_connection(struct connection_pool* pool, char* host, int port) {
int sockfd;
pthread_mutex_lock(&(pool->mutex));
struct connection_list* list = pool->head;
while (list != 0) {
if (strcmp(list->host, host) == 0 && list->port == port) {
break;
} else {
list = list->next;
}
}
if (list == 0) {
list = malloc(sizeof(struct connection_list));
list->head = 0;
list->tail = 0;
list->host = malloc(strlen(host) + 1);
strcpy(list->host, host);
list->port = port;
list->next = 0;
if (pool->head == 0) {
pool->head = list;
pool->tail = list;
} else {
pool->tail->next = list;
pool->tail = list;
}
}
if (list->head != 0) {
struct connection* conn = list->head;
list->head = conn->next;
if (list->head == 0) {
list->tail = 0;
}
sockfd = conn->sockfd;
free(conn);
} else {
sockfd = open_connection(host, port);
}
pthread_mutex_unlock(&(pool->mutex));
return sockfd;
}
void release_connection(struct connection_pool* pool, char* host, int port, int sockfd) {
pthread_mutex_lock(&(pool->mutex));
struct connection_list* list = pool->head;
while (list != 0) {
if (strcmp(list->host, host) == 0 && list->port == port) {
struct connection* conn = malloc(sizeof(struct connection));
conn->sockfd = sockfd;
conn->next = 0;
if (list->head == 0) {
list->head = conn;
list->tail = conn;
} else {
list->tail->next = conn;
list->tail = conn;
}
break;
}
list = list->next;
}
pthread_mutex_unlock(&(pool->mutex));
}
int open_connection(char* host, int port) {
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
if (inet_pton(AF_INET, host, &server_addr.sin_addr) < 0) {
printf("Error processing the hostname\\n");
return -1;
}
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Failed to create socket\\n");
return -1;
}
if (connect(sockfd, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0) {
printf("Failed to connect to %s:%d\\n", host, port);
return -1;
}
return sockfd;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_stoj = PTHREAD_MUTEX_INITIALIZER;
int stoj = 0;
pthread_mutex_t mutex_tazko_chori = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_lahko_chori = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_vysetrenie = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_t;
pthread_cond_t cond_l;
int count_tazko_chori = 0;
int count_lahko_chori = 0;
int count_vsetci = 0;
int pritomni_t = 0;
int pritomni_l = 0;
void volno_lahko_chory(int i) {
printf("lahko chory pacient %d je doma\\n", i);
sleep(3);
}
void vysetrenie_lahko_choreho(int i) {
pthread_mutex_lock(&mutex_vysetrenie);
printf("%d lahko chory sa dostavil pred miestnost\\n", i);
while(pritomni_t != 0 || pritomni_l >= 2)
pthread_cond_wait(&cond_l, &mutex_vysetrenie);
pritomni_l++;
printf("%d lahko chory bude vstupovat do miestnostnosti\\n", i);
pthread_mutex_unlock(&mutex_vysetrenie);
pthread_mutex_lock(&mutex_lahko_chori);
printf("vysetrenie %d lahko choreho\\n", i);
sleep(0.5);
count_lahko_chori++;
count_vsetci++;
pthread_mutex_unlock(&mutex_lahko_chori);
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_l--;
printf("lahko chory %d opustuje miestnostnost\\n", i);
pthread_cond_broadcast(&cond_t);
pthread_cond_broadcast(&cond_l);
pthread_mutex_unlock(&mutex_vysetrenie);
}
void *lahka_choroba( void *ptr ) {
int i = (int*)ptr;
pthread_mutex_lock(&mutex_stoj);
while(!stoj) {
pthread_mutex_unlock(&mutex_stoj);
vysetrenie_lahko_choreho(i);
volno_lahko_chory(i);
pthread_mutex_lock(&mutex_stoj);
}
pthread_mutex_unlock(&mutex_stoj);
return 0;
}
void volno_tazko_chory(int i) {
printf("tazko chory pacient %d je doma\\n", i);
sleep(5);
}
void vysetrenie_tazko_choreho(int i) {
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_t++;
printf("%d tazko chory sa dostavil pred miestnost\\n", i);
while(pritomni_l != 0)
pthread_cond_wait(&cond_t, &mutex_vysetrenie);
printf("%d tazko chory bude vstupovat do miestnostnosti\\n", i);
pthread_mutex_unlock(&mutex_vysetrenie);
pthread_mutex_lock(&mutex_tazko_chori);
printf("vysetrenie %d tazko choreho\\n", i);
sleep(1);
count_tazko_chori++;
count_vsetci++;
pthread_mutex_unlock(&mutex_tazko_chori);
pthread_mutex_lock(&mutex_vysetrenie);
pritomni_t--;
printf("tazko chory %d opustuje miestnostnost\\n", i);
pthread_cond_broadcast(&cond_l);
pthread_mutex_unlock(&mutex_vysetrenie);
}
void *vazna_choroba( void *ptr ) {
int i = (int*)ptr;
pthread_mutex_lock(&mutex_stoj);
while(!stoj) {
pthread_mutex_unlock(&mutex_stoj);
vysetrenie_tazko_choreho(i);
volno_tazko_chory(i);
pthread_mutex_lock(&mutex_stoj);
}
pthread_mutex_unlock(&mutex_stoj);
return 0;
}
int main(void) {
int i;
pthread_t vazne_chori[3];
pthread_t lahko_chori[7];
for (i=0;i<3;i++) pthread_create( &vazne_chori[i], 0, &vazna_choroba,(void*)i);
for (i=0;i<7;i++) pthread_create( &lahko_chori[i], 0, &lahka_choroba, (void*)i);
sleep(20);
pthread_mutex_lock(&mutex_stoj);
stoj = 1;
pthread_cond_broadcast(&cond_l);
pthread_cond_broadcast(&cond_t);
pthread_mutex_unlock(&mutex_stoj);
for (i=0;i<3;i++) pthread_join( vazne_chori[i], 0);
for (i=0;i<7;i++) pthread_join( lahko_chori[i], 0);
printf("pocet vysetreni tazko chorych: %d, lahko_chorich: %d, vsetkych: %d\\n ", count_tazko_chori, count_lahko_chori, count_vsetci);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t evento;
int n_elementos=0;
int buffer[3];
int indProd = 0;
int indCons = 0;
int n_prod = 0;
void * Productor(void * arg) {
int dato;
while (1) {
dato = rand()%100;
sleep(rand()%3);
pthread_mutex_lock(&mutex);
while (n_elementos == 3 && n_prod!=10)
pthread_cond_wait(&evento, &mutex);
if (n_prod==10) {
pthread_mutex_unlock(&mutex);
break;
}
printf("Producimos elemento %d=%d insertado en posición %d\\n", n_prod, dato, indProd);
buffer[indProd] = dato;
indProd = (indProd + 1) % 3;
n_elementos ++;
n_prod++;
pthread_cond_broadcast(&evento);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void * Consumidor(void * arg) {
int dato;
while (1) {
pthread_mutex_lock(&mutex);
while (n_elementos == 0 && n_prod!=10)
pthread_cond_wait(&evento, &mutex);
if (n_prod==10) {
pthread_mutex_unlock(&mutex);
break;
}
dato = buffer[indCons];
printf("Consumimos elemento %d extraido de posición %d\\n", dato, indCons);
indCons = (indCons + 1) % 3;
n_elementos--;
pthread_cond_broadcast(&evento);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t pTh1, pTh2;
pthread_t cTh1, cTh2;
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&evento, 0);
pthread_create(&pTh1, 0, Productor, 0);
pthread_create(&pTh2, 0, Productor, 0);
pthread_create(&cTh1, 0, Consumidor, 0);
pthread_create(&cTh2, 0, Consumidor, 0);
pthread_join(pTh1, 0);
pthread_join(pTh2, 0);
pthread_join(cTh1, 0);
pthread_join(cTh2, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&evento);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_t thread;
pthread_cond_t can_eat;
int id;
int tid;
} philosopher;
static philosopher diners[5];
static int stop=0;
static pthread_mutex_t chopstick[5];
static unsigned long user_progress[5];
static unsigned long user_time[5];
static unsigned long sys_progress[5];
static unsigned long sys_time[5];
pthread_mutex_t *right_chop (philosopher *p)
{
return &chopstick[(p->id == 0 ? 5 -1 : (p->id)-1)];
}
pthread_mutex_t *left_chop (philosopher *p)
{
return &chopstick[p->id];
}
philosopher *left_phil (philosopher *p)
{
return &diners[(p->id == 0 ? 5 -1 : (p->id)-1)];
}
philosopher *right_phil (philosopher *p)
{
return &diners[(p->id == (5 -1) ? 0 : (p->id)+1)];
}
void think_one_thought()
{
int i,j;
i = 0;
i++;
for (j=0; j<200; j++) {
i++;
}
}
void eat_one_mouthful()
{
int i, j;
i = 0;
i++;
for (j=0; j<200; j++) {
i++;
}
}
static void *dp_thread(void *arg)
{
int think_rnd;
int eat_rnd;
int i;
philosopher *me;
me = (philosopher *) arg;
me->tid = syscall(__NR_gettid);
while (!stop) {
think_rnd = (rand() % 10000);
eat_rnd = (rand() % 10000);
for (i = 0; i < think_rnd; i++){
think_one_thought();
}
pthread_mutex_lock(left_chop(me));
pthread_mutex_lock(right_chop(me));
for (i = 0; i < eat_rnd; i++){
eat_one_mouthful();
}
pthread_mutex_unlock(right_chop(me));
pthread_mutex_unlock(left_chop(me));
}
return 0;
}
void set_table()
{
int i;
for (i = 0; i < 5; i++) {
pthread_mutex_init(&chopstick[i], 0);
}
for (i = 0; i < 5; i++) {
diners[i].id = i;
diners[i].tid = -1;
user_progress[i] = 0;
user_time[i] = 0;
sys_progress[i] = 0;
sys_time[i] = 0;
}
for (i = 0; i < 5; i++) {
pthread_create(&(diners[i].thread), 0, dp_thread, &diners[i]);
}
i = 0;
while (i < 5) {
if(diners[i].tid != -1) i++;
else sleep(1);
}
}
void print_progress()
{
int i;
char buf[256];
printf ("\\nUser time:\\t");
for (i = 0; i < 5; i++) {
sprintf(buf, "%lu / %lu", user_progress[i], user_time[i]);
if (strlen(buf) < 8)
printf("%s\\t\\t", buf);
else
printf("%s\\t", buf);
}
printf ("\\nSystem time:\\t");
for (i = 0; i < 5; i++) {
sprintf(buf, "%lu / %lu", sys_progress[i], sys_time[i]);
if (strlen(buf) < 8)
printf("%s\\t\\t", buf);
else
printf("%s\\t", buf);
}
printf("\\n");
}
int check_for_deadlock()
{
int deadlock;
char filename[256];
int i;
int j;
FILE *statf;
unsigned long new_sys_time;
unsigned long new_user_time;
deadlock = 1;
for (i = 0; i < 5; i++) {
}
return deadlock;
}
int main(int argc, char **argv)
{
int i;
int deadlock;
deadlock = 0;
srand(time(0));
set_table();
do {
sleep(5);
deadlock = 0;
if (check_for_deadlock()) {
deadlock = 1;
break;
}
print_progress();
} while (!deadlock);
stop = 1;
printf ("Reached deadlock\\n");
for (i = 0; i < 5; i++)
pthread_mutex_unlock(&chopstick[i]);
for (i = 0; i < 5; i++)
pthread_join(diners[i].thread, 0);
return 0;
}
| 0
|
#include <pthread.h>
int initStop()
{
printf("stared initializing");
fflush(stdout);
pthread_mutex_lock(&acqStop_mutex);
acqStop = 1;
pthread_mutex_unlock(&acqStop_mutex);
pthread_mutex_lock(©Stop_mutex);
copyStop = 1;
pthread_mutex_unlock(©Stop_mutex);
pthread_mutex_lock(&specStop_mutex);
specStop = 1;
pthread_mutex_unlock(&specStop_mutex);
pthread_mutex_lock(&fwriteStop_mutex);
fwriteStop = 1;
pthread_mutex_unlock(&fwriteStop_mutex);
pthread_mutex_lock(&ipsStop_mutex);
ipsStop = 1;
pthread_mutex_unlock(&ipsStop_mutex);
pthread_mutex_lock(&mix0Stop_mutex);
mix0Stop = 1;
pthread_mutex_unlock(&mix0Stop_mutex);
pthread_mutex_lock(&mix1Stop_mutex);
mix1Stop = 1;
pthread_mutex_unlock(&mix1Stop_mutex);
pthread_mutex_lock(&mixCalStop_mutex);
mixCalStop = 1;
pthread_mutex_unlock(&mixCalStop_mutex);
pthread_mutex_lock(&fft0Stop_mutex);
fft0Stop = 1;
pthread_mutex_unlock(&fft0Stop_mutex);
pthread_mutex_lock(&fft1Stop_mutex);
fft1Stop = 1;
pthread_mutex_unlock(&fft1Stop_mutex);
pthread_mutex_lock(&corrStop_mutex);
corrStop = 1;
pthread_mutex_unlock(&corrStop_mutex);
pthread_mutex_lock(&corrCalStop_mutex);
corrCalStop = 1;
pthread_mutex_unlock(&corrCalStop_mutex);
pthread_mutex_lock(&dedispStop_mutex);
dedispStop = 1;
pthread_mutex_unlock(&dedispStop_mutex);
pthread_mutex_lock(&bandStop_mutex);
bandStop = 1;
pthread_mutex_unlock(&bandStop_mutex);
pthread_mutex_lock(&foldStop_mutex);
foldStop = 1;
pthread_mutex_unlock(&foldStop_mutex);
pthread_mutex_lock(&vlbiStop_mutex);
vlbiStop = 1;
pthread_mutex_unlock(&vlbiStop_mutex);
pthread_mutex_lock(&gpuStop_mutex);
gpuStop = 1;
pthread_mutex_unlock(&gpuStop_mutex);
}
int stop()
{
pthread_mutex_lock(©Stop_mutex);
copyStop = 0;
pthread_mutex_unlock(©Stop_mutex);
pthread_mutex_lock(&specStop_mutex);
specStop = 0;
pthread_mutex_unlock(&specStop_mutex);
pthread_mutex_lock(&fwriteStop_mutex);
fwriteStop = 0;
pthread_mutex_unlock(&fwriteStop_mutex);
pthread_mutex_lock(&ipsStop_mutex);
ipsStop = 0;
pthread_mutex_unlock(&ipsStop_mutex);
pthread_mutex_lock(&mix0Stop_mutex);
mix0Stop = 0;
pthread_mutex_unlock(&mix0Stop_mutex);
pthread_mutex_lock(&mix1Stop_mutex);
mix1Stop = 0;
pthread_mutex_unlock(&mix1Stop_mutex);
pthread_mutex_lock(&mixCalStop_mutex);
mixCalStop = 0;
pthread_mutex_unlock(&mixCalStop_mutex);
pthread_mutex_lock(&fft0Stop_mutex);
fft0Stop = 0;
pthread_mutex_unlock(&fft0Stop_mutex);
pthread_mutex_lock(&fft1Stop_mutex);
fft1Stop = 0;
pthread_mutex_unlock(&fft1Stop_mutex);
pthread_mutex_lock(&corrStop_mutex);
corrStop = 0;
pthread_mutex_unlock(&corrStop_mutex);
pthread_mutex_lock(&corrCalStop_mutex);
corrCalStop = 0;
pthread_mutex_unlock(&corrCalStop_mutex);
pthread_mutex_lock(&dedispStop_mutex);
dedispStop = 0;
pthread_mutex_unlock(&dedispStop_mutex);
pthread_mutex_lock(&bandStop_mutex);
bandStop = 0;
pthread_mutex_unlock(&bandStop_mutex);
pthread_mutex_lock(&foldStop_mutex);
foldStop = 0;
pthread_mutex_unlock(&foldStop_mutex);
pthread_mutex_lock(&vlbiStop_mutex);
vlbiStop = 0;
pthread_mutex_unlock(&vlbiStop_mutex);
pthread_mutex_lock(&gpuStop_mutex);
gpuStop = 0;
pthread_mutex_unlock(&gpuStop_mutex);
}
| 1
|
#include <pthread.h>
static void *run(void *);
static void good_session(int, FILE *);
static void bad_session(int, FILE *);
struct account {
double balance;
pthread_mutex_t mutex;
};
static account *myacct;
static int version = 0;
void deposit(struct account *acct, double amount)
{
acct->balance += amount;
}
void withdraw(struct account *acct, double amount)
{
acct->balance -= amount;
}
int main(int argc, char **argv)
{
int i;
int num_threads = 0;
int *id;
pthread_t *tids;
if (argc < 3) {
fprintf(stderr, "Usage: %s <num_threads (1-3)> <good|bad>\\n", argv[0]);
exit(1);
}
num_threads = atoi(argv[1]);
if (num_threads > 3) {
fprintf(stderr, "Usage: %s Too many threads. Defaulting to 3.\\n", argv[0]);
num_threads = 3;
}
if(strcmp(argv[2], "good") == 0) {
version = 0;
printf("Running good version...\\n");
} else {
version = 1;
printf("Running bad version...\\n");
}
myacct = (struct account *) malloc(sizeof(struct account));
myacct->balance = 0.0;
printf("initial balance = %lf\\n", myacct->balance);
pthread_mutex_init(&(myacct->mutex), 0);
tids = (pthread_t *) malloc(sizeof(pthread_t)*num_threads);
for(i = 0; i < num_threads; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&tids[i], 0, run, (void *) id);
}
for (i = 0; i < num_threads; i++) {
pthread_join(tids[i], 0);
}
printf("final balance = %lf\\n", myacct->balance);
free(myacct);
free(tids);
exit(0);
}
static void *run(void *arg)
{
int id = *((int *)arg);
char filename[80];
FILE *fp;
sprintf(filename, "transactions_%d.txt", id);
fp = fopen(filename, "r");
if(fp == 0) {
fprintf(stderr, "Can't open input file %s\\n", filename);
exit(1);
}
printf("Thread [%d]: Session started\\n", id);
if(version == 0) {
good_session(id, fp);
} else {
bad_session(id, fp);
}
printf("Thread [%d]: Session ended\\n", id);
free(arg);
pthread_exit(0);
}
void bad_session(int id, FILE *fp)
{
double amount;
pthread_mutex_lock(&(myacct->mutex));
while(fscanf(fp, "%lf", &amount) != EOF) {
if(amount < 1) {
sleep(30);
}
deposit(myacct, amount);
printf("\\tThread [%d]: Deposited: %f\\n", id, amount);
fflush(stdout);
}
pthread_mutex_unlock(&(myacct->mutex));
}
void good_session(int id, FILE *fp)
{
double amount;
while(fscanf(fp, "%lf", &amount) != EOF) {
if(amount < 1) {
sleep(30);
}
pthread_mutex_lock(&(myacct->mutex));
deposit(myacct, amount);
pthread_mutex_unlock(&(myacct->mutex));
printf("\\tThread [%d]: Deposited: %f\\n", id, amount);
fflush(stdout);
}
}
| 0
|
#include <pthread.h>
int collect = 1;
void sighandler(int signum){ collect = 0;}
void main(int argc, char* argv[])
{
FILE * fp = (FILE*) 0;
struct emg_driver* emg_config = (struct emg_driver*) 0;
int i, j;
struct emg_data data;
struct filtered_data filteredData;
struct shared* data_ptr = (struct shared*) 0;
struct iir_state_t iir_state[4];
for(i=0; i < 4; i++){
iir_state[i].x_values = (double *) malloc(X_LEN * sizeof(double));
iir_state[i].x_len = X_LEN;
iir_state[i].y_values = (double *) malloc(Y_LEN * sizeof(double));
iir_state[i].y_len = Y_LEN;
for(j=0; j < iir_state[i].x_len; j++) iir_state[i].x_values[j] = 0.0;
for(j=0; j < iir_state[i].y_len; j++) iir_state[i].y_values[j] = 0.0;
}
int shmid;
size_t filteredData_size = sizeof(filteredData);
if((shmid = shm_open(SHARED_RESOURCE, O_CREAT | O_TRUNC | O_RDWR , 0600)) == -1)
{perror("shm_open"); return;}
ftruncate(shmid, sizeof(struct shared));
data_ptr = (struct shared *) mmap(0, sizeof(struct shared),
PROT_READ | PROT_WRITE, MAP_SHARED, shmid, 0);
if(data_ptr == (struct shared*) (-1)) {perror("mmap"); return;}
data_ptr->filteredData.sec_elapsed = 0;
data_ptr->filteredData.ms_elapsed = 0;
data_ptr->filteredData.us_elapsed = 0;
for(j=0;j<4;j++) data_ptr->filteredData.channels[j] = 0.0;
pthread_mutexattr_t shared_mutex_attr;
pthread_mutexattr_init(&shared_mutex_attr);
pthread_mutexattr_setpshared(&shared_mutex_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&(data_ptr->mutex), &shared_mutex_attr);
double data_array[4];
double filtered_data_array[4];
long sec_elapsed;
int ms_elapsed;
int us_elapsed;
errno = 0;
fp = fopen(OUTPUT_FILE, "w+");
if(fp == 0){
perror("Error opening output file");
return;
}
emg_config = emg_driver_init("/dev/rfcomm0");
if (!emg_config)
{
printf("Error: emg driver not configured, exit!\\n");
return;
}
printf("Collecting and processing EMG data, press Ctrl-C to stop.\\n");
signal(SIGINT, sighandler);
while(collect)
{
emg_driver_get_samples(emg_config, &data);
sec_elapsed = data.sec_elapsed;
ms_elapsed = data.ms_elapsed;
us_elapsed = data.us_elapsed;
pthread_mutex_lock(&(data_ptr->mutex));
data_ptr->filteredData.sec_elapsed = sec_elapsed;
data_ptr->filteredData.ms_elapsed = ms_elapsed;
data_ptr->filteredData.us_elapsed = us_elapsed;
for (j = 0; j < 4; j++)
{
data_array[j] = data.channels[j];
filtered_data_array[j] = iir_filter(data_array[j], &iir_state[j]);
data_ptr->filteredData.channels[j] = filtered_data_array[j];
data_ptr->filteredData.raw_channels[j] = data_array[j];
}
pthread_mutex_unlock(&(data_ptr->mutex));
fprintf(fp, "%ld,%d,%d,%f,%f,%f,%f,%f,%f,%f,%f\\n",
sec_elapsed,
ms_elapsed,
us_elapsed,
data_array[0],
data_array[1],
data_array[2],
data_array[3],
filtered_data_array[0],
filtered_data_array[1],
filtered_data_array[2],
filtered_data_array[3]);
fflush(fp);
}
printf("\\n\\nInterrupt signal caught, closing file and bluetooth controller.\\n");
if(fclose(fp) == -1) {perror("Error closing output file"); return;}
if(munmap(data_ptr, sizeof(struct shared*)) == -1) {perror("munmap"); return;}
if(shm_unlink(SHARED_RESOURCE) == -1) {perror("shm_unlink"); return;}
emg_driver_deinit(emg_config);
printf("Data in '%s'\\nPlease save it as it will be overwritten before re-run.\\n", OUTPUT_FILE);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock_fork;
pthread_mutexattr_t lock_fork_attr;
sem_t lock_fork_req;
sem_t lock_fork_wait;
int lock_fork_forkers_count;
int lock_fork_blockers_count;
int lock_fork_waiting_count;
void scp_lock_init(void)
{
pthread_mutexattr_init(&lock_fork_attr);
pthread_mutex_init(&lock_fork, &lock_fork_attr);
sem_init(&lock_fork_req, 0, 0);
sem_init(&lock_fork_wait, 0, 0);
lock_fork_blockers_count = 0;
lock_fork_waiting_count = 0;
lock_fork_forkers_count = 0;
}
void scp_lock_fork_request(void)
{
pthread_mutex_lock(&lock_fork);
if (lock_fork_blockers_count == 0)
{
sem_post(&lock_fork_req);
}
lock_fork_forkers_count++;
pthread_mutex_unlock(&lock_fork);
sem_wait(&lock_fork_req);
}
void scp_lock_fork_release(void)
{
pthread_mutex_lock(&lock_fork);
lock_fork_forkers_count--;
if (lock_fork_forkers_count > 0)
{
sem_post(&lock_fork_req);
}
for (; lock_fork_waiting_count > 0; lock_fork_waiting_count--)
{
sem_post(&lock_fork_wait);
}
pthread_mutex_unlock(&lock_fork);
}
void scp_lock_fork_critical_section_end(int blocking)
{
pthread_mutex_lock(&lock_fork);
if (blocking == LIBSCP_LOCK_FORK_BLOCKER)
{
lock_fork_blockers_count--;
}
if ((lock_fork_blockers_count == 0) && (lock_fork_forkers_count > 0))
{
sem_post(&lock_fork_req);
}
pthread_mutex_unlock(&lock_fork);
}
int scp_lock_fork_critical_section_start(void)
{
do
{
pthread_mutex_lock(&lock_fork);
if (lock_fork_forkers_count > 0)
{
lock_fork_waiting_count++;
pthread_mutex_unlock(&lock_fork);
sem_wait(&lock_fork_wait);
}
else
{
lock_fork_blockers_count++;
pthread_mutex_unlock(&lock_fork);
return LIBSCP_LOCK_FORK_BLOCKER;
}
}
while (1);
return LIBSCP_LOCK_FORK_WAITING;
}
| 0
|
#include <pthread.h>
pthread_mutex_t esc, lei, prot;
int pilha = 0;
void *leitor(void *argumento){
pthread_mutex_lock(&lei);
pilha++;
if(pilha == 1) pthread_mutex_lock(&esc);
pthread_mutex_unlock(&lei);
int* n = (int*) argumento;
char nome[] = "teste.txt";
FILE *fp = fopen(nome,"rt");
if (!fp) exit(1);
char linha[50];
printf("\\nLeitores no momento: %d \\n", pilha);
while (fgets(linha, 50, fp)){
}
fclose(fp);
pthread_mutex_lock(&prot);
pilha--;
if( pilha == 0) pthread_mutex_unlock(&esc);
pthread_mutex_unlock(&prot);
pthread_exit(0);
}
void *escritor(void *argumento){
pthread_mutex_lock(&lei);
printf("Aguardando %d leitor(es)... \\n", pilha);
pthread_mutex_lock(&esc);
int* n = (int*) argumento;
char nome[] = "teste.txt";
FILE *fp = fopen(nome,"at");
if (!fp) exit(1);
char linha[] = "\\nEscrevi!";
fseek(fp, 0L, 2);
fprintf(fp,"%s",linha);
fclose(fp);
pthread_mutex_unlock(&esc);
pthread_mutex_unlock(&lei);
pthread_exit(0);
}
int main (int argc, char *argv[]){
int num;
printf("Indique o numero de threads a serem criadas:\\n");
scanf("%d",&num);
pthread_t threads[num];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&lei, 0);
pthread_mutex_init(&esc, 0);
pthread_mutex_init(&prot, 0);
int rc, tipo;
long i;
char arquivo[] = "teste.txt";
for(i = 0; i < num; i++){
tipo = rand() % 2;
if (tipo == 0){
rc = pthread_create(&threads[i], &attr, escritor, (void *)i);
}
if (tipo == 1){
rc = pthread_create(&threads[i], &attr, leitor, (void *)i);
}
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i=0; i < num; i++) {
rc = pthread_join(threads[i], 0);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
system("pause");
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void* thr_fn(void *arg){
int err,signo;
for(;;){
err = sigwait(&mask,&signo);
if(err != 0)
err_exit(err,"sigwait falied ");
switch(signo){
case SIGINT:
printf("\\niniterrupt \\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d\\n",signo);
exit(1);
}
}
}
int main(void){
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask,SIGINT);
sigaddset(&mask,SIGQUIT);
if( (err = pthread_sigmask(SIG_BLOCK,&mask,&oldmask)) != 0)
err_exit(err,"SIG_BlOCK error ");
err = pthread_create(&tid,0,thr_fn,0);
if(err != 0 )
err_exit(err,"can't create thread ");
pthread_mutex_lock(&lock);
while(quitflag == 0){
pthread_cond_wait(&waitloc,&lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if(sigprocmask(SIG_SETMASK,&oldmask,0) < 0)
err_sys("SIG_SETMASK error ");
exit(0);
}
| 0
|
#include <pthread.h>
{
KEYPAD_NUM1 = 1,
KEYPAD_NUM2,
KEYPAD_NUM3,
KEYPAD_NUM4,
KEYPAD_NUM5,
KEYPAD_NUM6,
KEYPAD_NUM7,
KEYPAD_NUM8,
KEYPAD_NUM9,
KEYPAD_NUM10,
KEYPAD_NUM11,
KEYPAD_NUM12,
KEYPAD_NUM13,
KEYPAD_NUM14,
KEYPAD_NUM15,
KEYPAD_NUM16,
} KeypadNum_t;
static int keypad_ls = 0;
static pthread_mutex_t mutex;
void num1_handler();
void num2_handler();
void num3_handler();
void num4_handler();
void num5_handler();
void num6_handler();
void num7_handler();
void num8_handler();
void num9_handler();
void num10_handler();
void num11_handler();
void num12_handler();
void num13_handler();
void num14_handler();
void num15_handler();
void num16_handler();
void *keypad_handler(void *arg)
{
int *res = (int *)arg;
while (!keypad_ls)
{
pthread_mutex_lock(&mutex);
switch(*res)
{
case KEYPAD_NUM1: num1_handler(); break;
case KEYPAD_NUM2: num2_handler(); break;
case KEYPAD_NUM3: num3_handler(); break;
case KEYPAD_NUM4: num4_handler(); break;
case KEYPAD_NUM5: num5_handler(); break;
case KEYPAD_NUM6: num6_handler(); break;
case KEYPAD_NUM7: num7_handler(); break;
case KEYPAD_NUM8: num8_handler(); break;
case KEYPAD_NUM9: num9_handler(); break;
case KEYPAD_NUM10: num10_handler(); break;
case KEYPAD_NUM11: num11_handler(); break;
case KEYPAD_NUM12: num12_handler(); break;
case KEYPAD_NUM13: num13_handler(); break;
case KEYPAD_NUM14: num14_handler(); break;
case KEYPAD_NUM15: num15_handler(); break;
case KEYPAD_NUM16: num16_handler(); break;
default: break;
}
}
return 0;
}
int main(int argc, char **argv)
{
int keypad_fd = 0;
int res;
pthread_t thread_kp = 0;
keypad_fd = open("/dev/sc_drv_keypad", O_RDWR);
if(keypad_fd < 0)
{
fprintf(stderr, "open keypad dev failure! %d\\n", keypad_fd);
return -1;
}
pthread_mutex_init(&mutex, 0);
pthread_mutex_lock(&mutex);
pthread_create(&thread_kp, 0, (void *)keypad_handler, &res);
do {
res = read(keypad_fd, 0, 0);
if(res>=KEYPAD_NUM1 && res<=KEYPAD_NUM16)
{
pthread_mutex_unlock(&mutex);
}
} while (!keypad_ls);
close(keypad_fd);
return 0;
}
void num1_handler()
{
printf("function: %s\\n", __func__);
}
void num2_handler()
{
printf("function: %s\\n", __func__);
}
void num3_handler()
{
printf("function: %s\\n", __func__);
}
void num4_handler()
{
printf("function: %s\\n", __func__);
}
void num5_handler()
{
printf("function: %s\\n", __func__);
}
void num6_handler()
{
printf("function: %s\\n", __func__);
}
void num7_handler()
{
printf("function: %s\\n", __func__);
}
void num8_handler()
{
printf("function: %s\\n", __func__);
}
void num9_handler()
{
printf("function: %s\\n", __func__);
}
void num10_handler()
{
printf("function: %s\\n", __func__);
}
void num11_handler()
{
printf("function: %s\\n", __func__);
}
void num12_handler()
{
printf("function: %s\\n", __func__);
}
void num13_handler()
{
printf("function: %s\\n", __func__);
}
void num14_handler()
{
printf("function: %s\\n", __func__);
}
void num15_handler()
{
printf("function: %s\\n", __func__);
}
void num16_handler()
{
printf("function: %s\\n", __func__);
}
void stop_keypad_ls(void)
{
keypad_ls = 1;
}
| 1
|
#include <pthread.h>
struct Message { long type; char option; int time; char text[128]; };
pthread_mutex_t statusMutex;
pthread_cond_t statusCond;
pthread_mutex_t notificationMutex;
pthread_cond_t notificationCond;
int exitLoop = 0;
int showingNotification = 0;
int updateScript = 0;
int statusTime = 10;
int notificationTime = 2;
char scriptPath[128];
char statusString[128];
char notificationString[128];
void fatalsig(int signum) {
exitLoop = 1;
}
void sigusr1(int signum) {
}
void print(char *string) {
Display *dpy = XOpenDisplay(0);
Window root = RootWindow(dpy, DefaultScreen(dpy));
XStoreName(dpy, root, string);
XCloseDisplay(dpy);
}
void readScript() {
updateScript = 0;
FILE *file;
file = popen(scriptPath, "r");
if (file == 0) return;
fgets(statusString, 128, file);
pclose(file);
}
void *statusThread(void *arg) {
pthread_mutex_lock(&statusMutex);
struct timespec timeSpec;
while (!exitLoop) {
readScript();
if (!showingNotification) print(statusString);
clock_gettime(CLOCK_REALTIME, &timeSpec);
timeSpec.tv_sec += (statusTime - (timeSpec.tv_sec - (timeSpec.tv_sec / statusTime) * statusTime));
timeSpec.tv_nsec = 0;
pthread_cond_timedwait(&statusCond, &statusMutex, &timeSpec);
}
pthread_mutex_unlock(&statusMutex);
return 0;
}
void *notificationThread(void *arg) {
pthread_mutex_lock(¬ificationMutex);
while (!exitLoop) {
pthread_cond_wait(¬ificationCond, ¬ificationMutex);
if (exitLoop) break;
showingNotification = 1;
while (!exitLoop) {
print(notificationString);
struct timespec timeSpec;
clock_gettime(CLOCK_REALTIME, &timeSpec);
timeSpec.tv_sec += notificationTime;
if (pthread_cond_timedwait(¬ificationCond, ¬ificationMutex, &timeSpec) == ETIMEDOUT) break;
}
showingNotification = 0;
if (updateScript) readScript();
print(statusString);
}
pthread_mutex_unlock(¬ificationMutex);
return 0;
}
void sendMessage(char option, int time, char *text) {
int messageID = msgget(51705, 0660);
if(messageID < 0) return;
struct Message message;
message.type = 1;
message.option = option;
message.time = time;
strcpy(message.text, text);
msgsnd(messageID, &message, sizeof(struct Message) - sizeof(long), IPC_NOWAIT);
}
void mainLoop() {
struct Message message;
int messageID = msgget(51705, IPC_CREAT | 0660);
if(messageID < 0) return;
struct sigaction action1;
action1.sa_handler = fatalsig;
sigaction(SIGPIPE, &action1, 0);
sigaction(SIGTERM, &action1, 0);
sigaction(SIGINT, &action1, 0);
struct sigaction action2;
action2.sa_handler = sigusr1;
sigaction(SIGUSR1, &action2, 0);
pthread_mutex_init(¬ificationMutex, 0);
pthread_cond_init(¬ificationCond, 0);
pthread_mutex_init(&statusMutex, 0);
pthread_cond_init(&statusCond, 0);
pthread_t threadNotification;
pthread_create(&threadNotification, 0, notificationThread, 0);
pthread_t threadStatus;
pthread_create(&threadStatus, 0, statusThread, 0);
while (!exitLoop) {
if (msgrcv(messageID, &message, sizeof(struct Message) - sizeof(long), 1, 0) < 0) break;
switch (message.option) {
case 'n':
notificationTime = message.time;
strcpy(notificationString, message.text);
pthread_cond_signal(¬ificationCond);
break;
case 'u':
updateScript = 1;
notificationTime = message.time;
strcpy(notificationString, message.text);
pthread_cond_signal(¬ificationCond);
break;
case 's':
statusTime = message.time;
strcpy(scriptPath, message.text);
pthread_cond_signal(&statusCond);
break;
}
}
msgctl(messageID, IPC_RMID, (struct msqid_ds*)0);
pthread_cond_signal(¬ificationCond);
pthread_cond_signal(&statusCond);
pthread_join(threadNotification, 0);
pthread_join(threadStatus, 0);
pthread_cond_destroy(¬ificationCond);
pthread_mutex_destroy(¬ificationMutex);
pthread_cond_destroy(&statusCond);
pthread_mutex_destroy(&statusMutex);
}
int main(int argc, char *argv[]) {
if (argc == 4) {
sendMessage(argv[1][0], atoi(argv[2]), argv[3]);
return 0;
}
if (argc == 3) {
statusTime = atoi(argv[1]);
strcpy(scriptPath, argv[2]);
mainLoop();
return 0;
}
printf("%s\\n%-4s%s %-25s%s\\n%-4s%s %-25s%s\\n%-4s%s %-25s%s\\n%-4s%s %-25s%s\\n",
"usage:",
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t e1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t e2 = PTHREAD_COND_INITIALIZER;
void* behav1 (void *args)
{
pthread_mutex_lock (&mutex1);
pthread_cond_broadcast (&e1);
fprintf (stdout,"broadcast e1\\n");
pthread_mutex_unlock (&mutex1);
pthread_mutex_lock (&mutex2);
fprintf (stdout,"wait e2\\n");
pthread_cond_wait (&e2,&mutex2);
fprintf (stdout,"receive e2\\n");
pthread_mutex_unlock (&mutex2);
fprintf (stdout,"end of behav1\\n");
return 0;
}
void* behav2 (void *args)
{
pthread_mutex_lock (&mutex1);
fprintf (stdout,"wait e1\\n");
pthread_cond_wait (&e1,&mutex1);
fprintf (stdout,"receive e1\\n");
pthread_mutex_unlock (&mutex1);
pthread_mutex_lock (&mutex2);
pthread_cond_broadcast (&e2);
fprintf (stdout,"broadcast e2\\n");
pthread_mutex_unlock (&mutex2);
fprintf (stdout,"end of behav2\\n");
return 0;
}
int main(void)
{
int c, *cell = &c;
pthread_t th1, th2;
pthread_create (&th1,0,behav1,0);
pthread_create (&th2,0,behav2,0);
pthread_join(th1,(void**)&cell);
pthread_join(th2,(void**)&cell);
fprintf (stdout,"exit\\n");
exit (0);
}
| 1
|
#include <pthread.h>
void executeNextTask(struct Reader *r){
struct Task *temp;
int sleepTime = 200;
usleep(50000 + (int) ((double)rand() * (long)50000 / ((double) 32767 +1)));
while(run == TRUE){
int prio = r->tq->NumPriorities-1;
pthread_mutex_lock(&mutex);
temp = popTaskQueue(r->tq,prio);
while( temp == 0 && prio>0){
prio--;
temp = popTaskQueue(r->tq,prio);
}
pthread_mutex_unlock(&mutex);
if(temp != 0){
printf("Reader %02i: Read task with priority %d, id:%05d\\n",r->id,temp->priority,temp->id);
if((sleepTime = (int)(((temp->priority+1)/r->tq->NumPriorities)* 600))<200);
sleepTime = 200;
usleep(sleepTime * 1000);
}else{
printf("There were no tasks in the queue!\\n");
usleep(1000 * 300);
}
free(temp);
}
}
| 0
|
#include <pthread.h>
void* sub(void *arg);
int highRet, highRetId;
pthread_mutex_t m1;
int main(int argc, char *argv[])
{
alarm(60);
int is[4], rc;
int numThreads = atoi(argv[1]);
int section = 100/numThreads;
int* size;
pthread_t thrdid[4];
pthread_mutex_init(&m1, 0);
int y = 0;
for (y; y < 4; y++)
{
is[y] = 0;
}
int i = 0;
for(i=0;i<numThreads;i++)
{
if (numThreads == 3)
{
is[i] = 33*(i + 1);
is[1] = 34;
size = malloc(sizeof(int));
*size = is[i];
rc = pthread_create(&thrdid[i],0,sub,size);
}
else
{
is[i] = section *(i + 1);
size = malloc(sizeof(int));
*size = is[i];
rc = pthread_create(&thrdid[i],0,sub,size);
}
}
for (i = 0; i < numThreads; i++)
{
pthread_join(thrdid[i],0);
}
printf("%d %d\\n",highRetId,highRet);
return 0;
}
void* sub(void*arg)
{
int rc;
int secSize = *((int *) arg);
int x = 100 - secSize;
for (x; x < secSize; x++)
{
rc = p5test(x);
if (rc > highRet)
{
pthread_mutex_lock(&m1);
highRet = rc;
highRetId = x;
pthread_mutex_unlock(&m1);
}
}
}
| 1
|
#include <pthread.h>
double time_diff(const struct timespec *first, const struct timespec *second,
struct timespec *diff)
{
struct timespec tmp;
const struct timespec *tmp_ptr;
if (first->tv_sec > second->tv_sec
|| (first->tv_sec == second->tv_sec
&& first->tv_nsec > second->tv_nsec))
{
tmp_ptr = first;
first = second;
second = tmp_ptr;
}
tmp.tv_sec = second->tv_sec - first->tv_sec;
tmp.tv_nsec = second->tv_nsec - first->tv_nsec;
if (tmp.tv_nsec < 0)
{
tmp.tv_sec -= 1;
tmp.tv_nsec += 1000000000;
}
if (diff != 0 )
{
diff->tv_sec = tmp.tv_sec;
diff->tv_nsec = tmp.tv_nsec;
}
return tmp.tv_sec + tmp.tv_nsec / 1000000000.0;
}
int * random_int_array(long size, int num_swaps, unsigned int seed)
{
srand(seed);
int *a = malloc(size * (long) sizeof(*a));
for (int i = 0; i < size; i++)
a[i] = i;
for (long i = 0; i < num_swaps; i++)
{
long idx0 = rand() % size;
long idx1 = rand() % size;
int tmp = a[idx0];
a[idx0] = a[idx1];
a[idx1] = tmp;
}
return a;
}
void swap(int *a, int *b)
{
int tmp = *a;
*a = *b;
*b = tmp;
}
{
int left;
int right;
} stack_item_t;
int idle_count = 0;
stack_item_t work_stack[2048];
int stack_size = 0;
int *A;
pthread_mutex_t mtex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condv = PTHREAD_COND_INITIALIZER;
void quicksort_task(int left, int right)
{
if(left < right)
{
int x = left, y = (left+right)/2, z =right;
int pivotIdx = (A[x] <= A[y])
? ((A[y] <= A[z]) ? y : ((A[x] < A[z]) ? z : x))
: ((A[x] <= A[z]) ? x : ((A[y] < A[z]) ? z : y));
int pivotVal = A[pivotIdx];
swap(A + pivotIdx, A + right);
int swapIdx = left;
for (int i = left; i < right; i++)
{
if (A[i] <= pivotVal)
{
swap(A + swapIdx, A + i);
swapIdx++;
}
}
swap(A + swapIdx, A + right);
pthread_mutex_lock(&mtex);
if (left < swapIdx - 1)
{
work_stack[stack_size].left = left;
work_stack[stack_size].right = swapIdx - 1;
stack_size++;
}
if (swapIdx + 1 < right)
{
work_stack[stack_size].left = swapIdx + 1;
work_stack[stack_size].right = right;
stack_size++;
}
pthread_cond_broadcast(&condv);
pthread_mutex_unlock(&mtex);
}
}
void *qsort_pthread()
{
stack_item_t local = (stack_item_t) {0,0};
bool idle = 0;
while(1)
{
quicksort_task(local.left, local.right);
pthread_mutex_lock(&mtex);
while (stack_size <= 0 && idle_count < 3 - 1)
{
if(idle == 0)
{
idle = 1;
idle_count++;
}
pthread_cond_wait(&condv, &mtex);
}
if(idle_count == 3 - 1 && stack_size <= 0)
{
pthread_cond_broadcast(&condv);
pthread_mutex_unlock(&mtex);
return 0;
}
if(idle == 1)
{
idle = 0;
idle_count--;
}
stack_size = stack_size - 1;
local = work_stack[stack_size];
pthread_mutex_unlock(&mtex);
}
return 0;
}
void quicksort(int *a, int left, int right)
{
pthread_t *pthreads;
pthreads = malloc((unsigned long)3 * sizeof(*pthreads));
A = a;
work_stack[stack_size] = (stack_item_t) {left, right };
stack_size++;
for (int i = 0; i < 3; i++)
{
pthread_create(pthreads + i, 0, &qsort_pthread, 0);
}
for (int i = 0; i < 3; i++)
pthread_join(pthreads[i], 0 );
}
void print_array(int *a, int elements)
{
for (int i = 0; i < elements; i++)
printf("%4d ", a[i]);
printf("\\n");
}
void main(int argc, char **argv)
{
int elements = 1024;
if (argc > 1)
elements = atoi(argv[1]);
struct timespec start, stop;
int *a = random_int_array(elements, elements / 2, 13);
clock_gettime(CLOCK_MONOTONIC, &start);
quicksort(a, 0, elements - 1);
clock_gettime(CLOCK_MONOTONIC, &stop);
printf("\\nTime = %lf\\n", time_diff(&start, &stop, 0 ));
}
| 0
|
#include <pthread.h>
struct Philosopher {
int courses_left;
};
struct State {
struct Philosopher *philo;
pthread_mutex_t locks[3];
pthread_cond_t conds[3];
bool *forks;
int id;
int num;
};
void *PrintHello(struct State *state) {
int id;
id = state->id;
while (state->philo->courses_left > 0) {
printf("philo %d is trying to get his fork\\n", id);
if (!state->forks[id]) {
continue;
}
pthread_mutex_lock(&(state->locks[id]));
state->forks[id] = 0;
printf("philo %d got his fork\\n", id);
int here, next, prev;
bool right, left;
pthread_mutex_t *lock, *rlock, *llock;
pthread_cond_t *cond, *rcond, *lcond;
next = (id + 1) % state->num;
prev = (id - 1) % state->num;
printf("%d, %d, %d\\n", state->forks[prev], state->forks[id], state->forks[next]);
if (state->forks[next]) {
state->forks[next] = 0;
pthread_mutex_lock(&(state->locks[next]));
state->philo->courses_left -= 1;
printf("philo %d has %d courses_left\\n", id, state->philo->courses_left);
pthread_mutex_unlock(&(state->locks[next]));
state->forks[next] = 1;
}
else if (state->forks[prev]) {
state->forks[prev] = 0;
pthread_mutex_lock(&(state->locks[prev]));
state->philo->courses_left -= 1;
printf("philo %d has %d courses_left\\n", id, state->philo->courses_left);
pthread_mutex_unlock(&(state->locks[prev]));
state->forks[prev] = 1;
}
pthread_mutex_unlock(&(state->locks[id]));
state->forks[id] = 1;
}
return 0;
}
int main(int argc, char *argv[]) {
int num_threads = atoi(argv[1]);
pthread_t threads[num_threads];
int rc;
long t;
struct Philosopher *philos;
pthread_mutex_t *locks;
pthread_cond_t *conds;
bool *forks;
struct State *states;
philos = (struct Philosopher*)malloc(num_threads*sizeof(*philos));
locks = (pthread_mutex_t *)malloc(num_threads*sizeof(*locks));
conds = (pthread_cond_t *)malloc(num_threads*sizeof(*conds));
forks = (bool *)malloc(num_threads*sizeof(*forks));
states = (struct State *)malloc(num_threads*sizeof(*states));
for(t = 0; t < num_threads; t++){
if (pthread_mutex_init(&locks[t], 0) != 0) {
printf("\\n mutex init failed\\n");
return 1;
}
if (pthread_cond_init(&conds[t], 0) != 0) {
printf("\\n cond init failed\\n");
return 1;
}
forks[t] = 1;
philos[t] = (struct Philosopher) {
.courses_left = 3
};
struct State * state = &(struct State) {
.philo = &(philos[t]),
.locks = locks,
.forks = forks,
.id = t,
.num = num_threads
};
states[t] = *state;
rc = pthread_create(&threads[t], 0, PrintHello, &states[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (t = 0; t < num_threads; t++) {
pthread_join(threads[t], 0);
}
for (t = 0; t < num_threads; t++) {
pthread_mutex_destroy(&locks[t]);
}
free(locks);
free(conds);
free(forks);
free(states);
}
| 1
|
#include <pthread.h>
int fd[2];
struct timespec start, end;
int numMaxCli;
FILE *file;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t nlock = PTHREAD_MUTEX_INITIALIZER;
int number;
char currGender = '\\0';
int clientCount = 0;
int pedF = 0, pedM = 0, rejF = 0, rejM = 0, serF = 0, serM = 0;
int p;
char gender;
int dur;
int rej;
} process_t;
int openFIFORead() {
if(mkfifo("/tmp/entrada",0660) < 0){
if(errno == EEXIST){
printf("FIFO '/tmp/entrada' exists already.\\n");
}
else {
printf("Impossible to create FIFO.\\n");
return -1;
}
}
do {
fd[0] = open("/tmp/entrada", O_RDONLY);
} while(fd[0] == -1);
return 0;
}
int openFIFOWrite() {
if(mkfifo("/tmp/rejeitados",0660) < 0){
if(errno == EEXIST){
printf("FIFO '/tmp/rejeitados' exists already.\\n");
}
else {
printf("Impossible to create FIFO.\\n");
return -1;
}
}
do {
fd[1] = open("/tmp/rejeitados", O_WRONLY);
} while(fd[1] == -1);
return 0;
}
void printInFile(process_t *process, int state) {
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
double elapsedTime = (end.tv_sec - start.tv_sec) * 1000000.00 + (end.tv_nsec - start.tv_nsec) / 1000.00;
if(state == 0){
char *msg = "RECEBIDO";
fprintf(file, "%-10.02f - %6d - %-5d: %-3c - %-5d - %-12s\\n", elapsedTime, getpid(), process->p, process->gender, process->dur, msg);
}
else if(state == 1){
char *msg = "SERVIDO";
fprintf(file, "%-10.02f - %6d - %-5d: %-3c - %-5d - %-12s\\n", elapsedTime, getpid(), process->p, process->gender, process->dur, msg);
}
else {
char *msg = "REJEITADO";
fprintf(file, "%-10.02f - %6d - %-5d: %-3c - %-5d - %-12s\\n", elapsedTime, getpid(), process->p, process->gender, process->dur, msg);
}
}
void printStatisticsInFile() {
fprintf(file, "\\nSTATISTICS\\n");
fprintf(file, "Requests:\\nTotal: %d\\t F: %d\\t M: %d\\n", (pedM+pedF),pedF,pedM);
fprintf(file, "Rejected:\\nTotal: %d\\t F: %d\\t M: %d\\n", (rejM+rejF),rejF,rejM);
fprintf(file, "Served:\\nTotal: %d\\t F: %d\\t M: %d\\n", (serM+serF),serF,serM);
}
void * processRequests(void * arg){
process_t *process = (process_t *)malloc(sizeof(process_t));
process = (process_t *) arg;
pthread_mutex_lock(&lock);
printInFile(process,0);
if(process->gender == 'F')
pedF++;
else
pedM++;
pthread_mutex_unlock(&lock);
if(((currGender == process->gender) || (currGender == '\\0')) && (clientCount != numMaxCli)){
pthread_mutex_lock(&lock);
clientCount++;
currGender = process->gender;
if(process->gender == 'F')
serF++;
else
serM++;
printInFile(process,1);
pthread_mutex_unlock(&lock);
sleep(process->dur/1000);
pthread_mutex_lock(&lock);
clientCount--;
if(clientCount == 0)
currGender = '\\0';
pthread_mutex_unlock(&lock);
}
else {
pthread_mutex_lock(&lock);
printInFile(process,-1);
pthread_mutex_unlock(&lock);
process->rej++;
pthread_mutex_lock(&nlock);
if(process->rej < 3)
number++;
pthread_mutex_unlock(&nlock);
pthread_mutex_lock(&lock);
if(process->gender == 'F')
rejF++;
else
rejM++;
pthread_mutex_unlock(&lock);
write(fd[1],process,sizeof(*process));
}
free(process);
return 0;
}
int main(int argc, char const *argv[])
{
clock_gettime(CLOCK_MONOTONIC_RAW, &start);
if(argc != 2){
printf("Wrong number of arguments (2)\\n");
exit(1);
}
numMaxCli = atoi(argv[1]);
char filename[14];
sprintf(filename,"/tmp/bal.%d",getpid());
file = fopen(filename, "w");
openFIFORead();
openFIFOWrite();
pthread_t tid[200000];
process_t *process = (process_t *)malloc(sizeof(process_t));
read(fd[0],process,sizeof(*process));
number = process->dur;
int i = 0;
while(number > 0) {
process_t *process = (process_t *)malloc(sizeof(process_t));
read(fd[0], process, sizeof(*process));
pthread_create(&tid[i], 0, (void * ) processRequests, process);
i++;
pthread_mutex_lock(&nlock);
number--;
pthread_mutex_unlock(&nlock);
}
int c = 0;
while(c < i){
pthread_join(tid[c], 0);
c++;
}
process->p = -1;
write(fd[1],process, sizeof(*process));
printStatisticsInFile();
pthread_mutex_destroy(&lock);
pthread_mutex_destroy(&nlock);
exit(0);
}
| 0
|
#include <pthread.h>
int total_num=0;
int lenght = 0 ;
pthread_mutex_t mutex ;
int n1 = 1000 , n2 = 1000;
char * s1,*s2;
void * Str_Function(void* startpos) ;
int match (char *a,char *b,int pos);
int main(int argc, char *argv[])
{
pthread_mutex_init (&mutex, 0) ;
FILE *fp = fopen("strings.txt","r");
s1 = (char*) malloc( n1 * sizeof( char* ));
s2 = (char*) malloc( n2 *sizeof( char* ));
fgets( s1 , n1 , fp );
fgets( s2, n2, fp );
n1= strlen(s1) - 1 ;
n2= strlen(s2) - 1 ;
lenght = n1 / 5 ;
printf ("s1 %s\\ns2 %s \\nlenght to be processed by each thread %d\\n", s1 , s2 , lenght);
int i = 0 ;
pthread_t worker[5];
for ( i =0 ; i< 5 ; i++)
{
int startpos = (i* (n1/5)) ;
printf ("startpos %d\\n", startpos);
if( pthread_create ( &worker[i] , 0, Str_Function, (void*)startpos) )
{
fprintf(stderr, "Error creating producer thread\\n");
return 1;
}
}
for ( i =0 ; i< 5 ; i++)
{
if( pthread_join ( worker[i] , 0))
{
fprintf(stderr, "Error creating producer thread\\n");
return 2;
}
}
FILE* output = fopen ("strings_result.txt" , "w") ;
fprintf(output,"%d",total_num) ;
fclose(output);
}
void * Str_Function(void* startpos)
{
int pos = ((int)startpos);
printf ("my start pos is<%d>\\n", pos ) ;
int temp = 0 ;
int i = 0 ;
for ( i=pos; i < pos+lenght ; i++)
temp += match(s1,s2, i);
printf ("my start pos is<%d>\\n", pos ) ;
pthread_mutex_lock (&mutex) ;
total_num += temp ;
printf ("total is now<%d>\\n", total_num ) ;
pthread_mutex_unlock (&mutex) ;
pthread_exit (0);
}
int match (char *a,char *b,int pos)
{
int i = 0;
int lenghtb = strlen (b) - 1 ;
int num = 0 ;
for (i =0 ; i < lenghtb ; i++ )
if ( a[pos+i] != '\\0' && b[i] != '\\0' && a[pos+i] == b[i] )
num ++ ;
if ( num == lenghtb )
return 1;
else
return 0;
}
| 1
|
#include <pthread.h>
void ui_helpline__pop(void)
{
}
char ui_helpline__current[512];
void ui_helpline__push(const char *msg)
{
const size_t sz = sizeof(ui_helpline__current);
SLsmg_gotorc(SLtt_Screen_Rows - 1, 0);
SLsmg_set_color(0);
SLsmg_write_nstring((char *)msg, SLtt_Screen_Cols);
SLsmg_refresh();
strncpy(ui_helpline__current, msg, sz)[sz - 1] = '\\0';
}
void ui_helpline__vpush(const char *fmt, va_list ap)
{
char *s;
if (vasprintf(&s, fmt, ap) < 0)
vfprintf(stderr, fmt, ap);
else {
ui_helpline__push(s);
free(s);
}
}
void ui_helpline__fpush(const char *fmt, ...)
{
va_list ap;
__builtin_va_start((ap));
ui_helpline__vpush(fmt, ap);
;
}
void ui_helpline__puts(const char *msg)
{
ui_helpline__pop();
ui_helpline__push(msg);
}
void ui_helpline__init(void)
{
ui_helpline__puts(" ");
}
char ui_helpline__last_msg[1024];
int ui_helpline__show_help(const char *format, va_list ap)
{
int ret;
static int backlog;
pthread_mutex_lock(&ui__lock);
ret = vscnprintf(ui_helpline__last_msg + backlog,
sizeof(ui_helpline__last_msg) - backlog, format, ap);
backlog += ret;
if (ui_helpline__last_msg[backlog - 1] == '\\n') {
ui_helpline__puts(ui_helpline__last_msg);
SLsmg_refresh();
backlog = 0;
}
pthread_mutex_unlock(&ui__lock);
return ret;
}
| 0
|
#include <pthread.h>
{
int v1;
int v2;
int v3;
} laStruct;
laStruct maStruct;
pthread_mutex_t monMutex = PTHREAD_MUTEX_INITIALIZER;
void *fonctionThreadMultiple(void *arg[])
{
int *tabArg = (int *)arg;
printf("Le pid du thread : %d\\nJ'affecte la variable\\n", getpid());
int i;
for(i = 0; i < 3; i++)
{
printf("%d ", tabArg[i]);
}
printf("\\n");
pthread_mutex_lock(&monMutex);
maStruct.v1 = tabArg[0];
maStruct.v2 = tabArg[1];
maStruct.v3 = tabArg[2];
pthread_mutex_unlock(&monMutex);
pthread_exit((void *)"Merci !\\n");
}
int main()
{
pthread_mutex_lock(&monMutex);
maStruct.v1 = 0;
maStruct.v2 = 0;
maStruct.v3 = 0;
pthread_mutex_unlock(&monMutex);
void *thread_result;
pthread_t un_thread;
pthread_t deux_thread;
pthread_t trois_thread;
int result;
int tab1[3] = {1,2,3};
int tab2[3] = {4,5,6};
int tab3[3] = {7,8,9};
result = pthread_create(&un_thread, 0, fonctionThreadMultiple, (void *) tab1);
if (result != 0)
{
perror("Thread creation failed\\n");
exit(1);
}
result = pthread_create(&deux_thread, 0, fonctionThreadMultiple, (void *)tab2);
if (result != 0)
{
perror("Thread creation failed\\n");
exit(1);
}
result = pthread_create(&trois_thread, 0, fonctionThreadMultiple, (void *)tab3);
if (result != 0)
{
perror("Thread creation failed\\n");
exit(1);
}
result = pthread_join(un_thread, &thread_result);
if (result != 0)
{
perror("Thread join failed\\n");
exit(1);
}
else
{
printf("%s", (char *)thread_result);
}
result = pthread_join(deux_thread, &thread_result);
if (result != 0)
{
perror("Thread join failed\\n");
exit(1);
}
else
{
printf("%s", (char *)thread_result);
}
result = pthread_join(trois_thread, &thread_result);
if (result != 0)
{
perror("Thread join failed\\n");
exit(1);
}
else
{
printf("%s", (char *)thread_result);
}
pthread_mutex_lock(&monMutex);
printf("V1 : %d\\n", maStruct.v1);
printf("V2 : %d\\n", maStruct.v2);
printf("V3 : %d\\n", maStruct.v3);
pthread_mutex_unlock(&monMutex);
return 0;
}
| 1
|
#include <pthread.h>
struct entry {
int key;
int value;
struct entry *next;
};
struct entry *table[5];
int keys[100000];
int nthread = 1;
volatile int done;
pthread_mutex_t _locks[5];
double
now()
{
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
static void
print(void)
{
int i;
struct entry *e;
for (i = 0; i < 5; i++) {
printf("%d: ", i);
for (e = table[i]; e != 0; e = e->next) {
printf("%d ", e->key);
}
printf("\\n");
}
}
static void
insert(int key, int value, struct entry **p, struct entry *n)
{
struct entry *e = malloc(sizeof(struct entry));
e->key = key;
e->value = value;
e->next = n;
*p = e;
}
static
void put(int key, int value)
{
pthread_mutex_lock(_locks + (key % 5));
struct entry *n, **p;
for (p = &table[key%5], n = table[key % 5]; n != 0; p = &n->next, n = n->next) {
if (n->key > key) {
insert(key, value, p, n);
goto done;
}
}
insert(key, value, p, n);
done:
pthread_mutex_unlock(_locks + (key % 5));
return;
}
static struct entry*
get(int key)
{
struct entry *e = 0;
for (e = table[key % 5]; e != 0; e = e->next) {
if (e->key == key) break;
}
return e;
}
static void *
thread(void *xa)
{
long n = (long) xa;
int i;
int b = 100000/nthread;
int k = 0;
double t1, t0;
t0 = now();
for (i = 0; i < b; i++) {
put(keys[b*n + i], n);
}
t1 = now();
printf("------------ Thread [%ld] ----------------- \\n", n);
printf("Put %d keys \\n", b);
printf("put time = %f\\n", t1-t0);
__sync_fetch_and_add(&done, 1);
while (done < nthread) ;
t0 = now();
for (i = 0; i < b; ++i) {
struct entry *e = get(keys[b * n + i]);
if (e == 0) ++k;
}
t1 = now();
printf("------------ Thread [%ld] ----------------- \\n", n);
printf("Lookup %d keys \\n", b);
printf("Lookup time = %f\\n", t1-t0);
printf("%d keys missing\\n", k);
}
int
main(int argc, char *argv[])
{
pthread_t *tha;
void *value;
long i;
double t1, t0;
if (argc < 2) {
fprintf(stderr, "%s: %s nthread\\n", argv[0], argv[0]);
exit(-1);
}
nthread = atoi(argv[1]);
tha = malloc(sizeof(pthread_t) * nthread);
int k;
for (k = 0; k < 5; ++k) {
pthread_mutex_init(_locks + k, 0);
}
srandom(0);
assert(100000 % nthread == 0);
for (i = 0; i < 100000; i++) {
keys[i] = random();
}
t0 = now();
for(i = 0; i < nthread; i++) {
assert(pthread_create(&tha[i], 0, thread, (void *) i) == 0);
}
for(i = 0; i < nthread; i++) {
assert(pthread_join(tha[i], &value) == 0);
}
t1 = now();
printf("\\nCompletion time = %f\\n", t1-t0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.