text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
enum {ARRAY_SIZE = 1000,};
const unsigned long int LOOP_ITERATIONS = (1 << 25);
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t b;
int global_array[ARRAY_SIZE];
void *reader(void *arg)
{
int tmp = *(int *)&m;
pthread_barrier_wait(&b);
while(tmp != 6)
tmp = *(int *)&m;
return 0;
}
int main(int argc, char **argv)
{
int nthr = 1;
pthread_t r_id;
struct timeval begin;
struct timeval end;
if (argv[1][0] == 'y')
nthr = atoi(argv[2]);
pthread_barrier_init(&b, 0, nthr);
for (int i = 0; i < nthr - 1; i++) {
pthread_create(&r_id, 0, reader, 0);
}
pthread_barrier_wait(&b);
gettimeofday(&(begin), 0);
for (int i = 0; i < LOOP_ITERATIONS; i++) {
pthread_mutex_lock(&m);
global_array[i % ARRAY_SIZE]++;
pthread_mutex_unlock(&m);
}
gettimeofday(&(end), 0);
printf("time %lf\\n", (((double)(end.tv_sec) + (double)(end.tv_usec / 1000000.0)) - ((double)(begin.tv_sec) + (double)(begin.tv_usec / 1000000.0))));
pthread_barrier_destroy(&b);
return 0;
}
| 1
|
#include <pthread.h>
void * runner1(void * args) {
int * a = (int *) args;
int i, sum=0;
for (i = 0; i < *a; i+=2){
sum += i;
}
printf("Even Sum: %d\\n", sum);
}
void * runner2(void * args) {
int * a = (int *) args;
int i, sum=0;
for (i = 1; i < *a; i+=2){
sum += i;
}
printf("Odd Sum: %d\\n", sum);
}
void * runner3(void * args) {
int * a = (int *) args;
int i, sum=0;
for (i = 0; i < *a; i++){
sum += i;
}
printf("Total Sum: %d\\n", sum);
}
pthread_mutex_t lock;
volatile int head=-1, size=0;
struct job_t {
void*(*function)(void *);
void * args;
} job[10000];
void * runner (void * args) {
void*(*func)(void*);
void * args1;
while(1) {
pthread_mutex_lock(&lock);
if(size == 0) {
printf("waiting\\n");
pthread_mutex_unlock(&lock);
sleep(1);
continue;
}
if(head == size-1) {
break;
}
func = job[++head].function;
args1 = job[head].args;
pthread_mutex_unlock(&lock);
func(args1);
sleep(1);
}
}
int main(int argc, char const *argv[]) {
pthread_t pd; int id[10000];
pthread_mutex_init(&lock, 0);
pthread_create(&pd, 0, &runner, 0);
int i=0;
for (int i = 1; i <= 10; ++i) {
id[i] = i+1;
job[size].function = &runner1;
job[size++].args = &id[i];
job[size].function = &runner2;
job[size++].args = &id[i];
job[size].function = &runner3;
job[size++].args = &id[i];
sleep(0.5);
}
pthread_join(pd, 0);
return 0;
}
| 0
|
#include <pthread.h>
int g_Flag = 0;
pthread_t thrdid1,thrdid2;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void* thrd_start_routine(void* v)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
if(g_Flag == 2)
pthread_cond_signal(&cond);
printf("This is thread 1\\n");
g_Flag = 1;
pthread_mutex_unlock(&mutex);
pthread_join(thrdid2,0);
printf("thread 1 exit\\n");
}
void* thrd_start_routine2(void* v)
{
pthread_detach(pthread_self());
pthread_mutex_lock(&mutex);
if(g_Flag == 1)
pthread_cond_signal(&cond);
printf("This is thread 2\\n");
g_Flag = 2;
pthread_mutex_unlock(&mutex);
printf("thread 2 exit\\n");
}
int main()
{
pthread_create(&thrdid1, 0, &thrd_start_routine, 0);
pthread_create(&thrdid2, 0, &thrd_start_routine2, 0);
pthread_cond_wait(&cond,&mutex);
printf("init thread exit\\n");
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int key = 2;
struct arguments {
int threadName;
pthread_mutex_t *lock;
pthread_cond_t *cond;
};
void *do_work(void *arg);
int main(int argc, char **argv) {
int numThreads = atoi(argv[1]);
pthread_t worker_thread[numThreads];
pthread_mutex_t mutex;
pthread_cond_t condition;
struct arguments *arg;
pthread_cond_init(&condition,0);
pthread_mutex_init(&mutex,0);
srand(atoi(argv[2]));
for (int t=0; t < numThreads; t++) {
arg = (struct arguments *)calloc(1, sizeof(struct arguments));
arg->threadName = t;
arg->lock = &mutex;
arg->cond = &condition;
if (pthread_create(&worker_thread[t], 0, do_work, (void *)arg)) {
exit(1);
}
}
for (int t=0; t < 10; t++) {
if (pthread_join(worker_thread[t], 0)) {
exit(1);
}
}
exit(0);
}
void *do_work(void *arg) {
struct arguments *thread;
pthread_mutex_t *mutexLock;
pthread_cond_t *conditionVar;
thread = (struct arguments*)arg;
mutexLock = thread->lock;
conditionVar = thread->cond;
printf("Thread %d has enters the coffee shop\\n" , thread-> threadName);
for(int i = 0; i < 10; i++){
printf("Thread %d is drinking coffee\\n" , thread-> threadName);
usleep(rand()% 3000000 + 2000000);
pthread_mutex_lock(mutexLock);
while(key == 0){
printf("Thread %d is waiting for a key\\n", thread->threadName);
pthread_cond_wait(conditionVar, mutexLock);
}
key--;
pthread_mutex_unlock(mutexLock);
printf("Thread %d got a key\\n", thread-> threadName);
printf("Thread %d is using the bathroom\\n", thread-> threadName);
usleep(rand()% 3000000 + 2000000);
pthread_mutex_lock(mutexLock);
key++;
pthread_mutex_unlock(mutexLock);
printf("Thread %d put a key back on the board\\n", thread-> threadName);
pthread_cond_broadcast(conditionVar);
}
printf("Thread %d leaves the coffee shop\\n", thread-> threadName);
return 0;
}
| 0
|
#include <pthread.h>
struct mtqueue* mtqueue_new()
{
struct mtqueue *mtqueue;
mtqueue = malloc(sizeof(struct mtqueue));
if (!mtqueue)
return 0;
pthread_mutex_init(&mtqueue->lock, 0);
pthread_mutex_init(&mtqueue->mutex, 0);
pthread_cond_init(&mtqueue->cond, 0);
mtqueue->first = 0;
mtqueue->last = 0;
return mtqueue;
}
void mtqueue_free(struct mtqueue *mtqueue)
{
pthread_cond_destroy(&mtqueue->cond);
pthread_mutex_destroy(&mtqueue->mutex);
pthread_mutex_destroy(&mtqueue->lock);
free(mtqueue);
}
static void *mtqueue_getelt(struct mtqueue *mtqueue)
{
struct mtqueueelt *elt = mtqueue->last;
if (elt != 0)
{
if (mtqueue->last->prev != 0)
mtqueue->last = mtqueue->last->prev;
else
mtqueue->last = mtqueue->first = 0;
}
return elt;
}
void *mtqueue_get(struct mtqueue *mtqueue, unsigned int wait)
{
void *data = 0;
struct mtqueueelt *elt;
pthread_mutex_lock(&mtqueue->lock);
elt = mtqueue_getelt(mtqueue);
pthread_mutex_unlock(&mtqueue->lock);
if (elt)
{
data = elt->data;
free(elt);
}
else if (wait)
{
while (!elt)
{
pthread_mutex_lock(&mtqueue->mutex);
pthread_cond_wait(&mtqueue->cond, &mtqueue->mutex);
pthread_mutex_lock(&mtqueue->lock);
elt = mtqueue_getelt(mtqueue);
pthread_mutex_unlock(&mtqueue->lock);
pthread_mutex_unlock(&mtqueue->mutex);
}
assert(elt);
data = elt->data;
free(elt);
return data;
}
return data;
}
static int mtqueue_putelt(struct mtqueue *mtqueue, void *data)
{
struct mtqueueelt *elt;
elt = malloc(sizeof(struct mtqueueelt));
if (elt == 0)
return 0;
elt->data = data;
elt->prev = 0;
if (mtqueue->first != 0)
{
mtqueue->first->prev = elt;
mtqueue->first = elt;
}
else
mtqueue->first = mtqueue->last = elt;
return 1;
}
int mtqueue_put(struct mtqueue *mtqueue, void *data)
{
int rval;
pthread_mutex_lock(&mtqueue->lock);
rval = mtqueue_putelt(mtqueue, data);
pthread_mutex_unlock(&mtqueue->lock);
if (rval)
pthread_cond_signal(&mtqueue->cond);
return rval;
}
| 1
|
#include <pthread.h>
char globalChar;
int state = 0;
int globalFlag = 0;
int printFlag = 0;
pthread_t tid[3];
pthread_mutex_t lock1, lock2, lock3, lockMain;
void* thread1(void *arg)
{
int i = 1;
int tempInt;
FILE *input = fopen("hw5-1.in", "r");
while(i == 1 && globalFlag == 0)
{
pthread_mutex_lock(&lock1);
if(state == 1)
{
i = fscanf(input, "%c\\n", &globalChar);
if(i == -1 || globalChar == '\\0')
{
globalFlag++;
fclose(input);
state++;
pthread_mutex_unlock(&lock2);
return 0;
}
else
{
printFlag = 1;
pthread_mutex_unlock(&lockMain);
}
}
}
fclose(input);
return 0;
}
void* thread2(void *output)
{
int i = 1;
int tempInt;
FILE *input = fopen("hw5-2.in", "r");
while(i == 1 && globalFlag < 2)
{
pthread_mutex_lock(&lock2);
if(state == 2)
{
i = fscanf(input, "%c\\n", &globalChar);
if(i == -1 || globalChar == '\\0')
{
globalFlag++;
fclose(input);
state++;
pthread_mutex_unlock(&lock3);
return 0;
}
else
{
printFlag = 1;
pthread_mutex_unlock(&lockMain);
}
}
}
fclose(input);
return 0;
}
void* thread3(void *output)
{
int i = 1;
int tempInt;
FILE *input = fopen("hw5-3.in", "r");
while(i == 1 && globalFlag < 3)
{
pthread_mutex_lock(&lock3);
if(state == 3)
{
i = fscanf(input, "%c\\n", &globalChar);
if(i == -1 || globalChar == '\\0')
{
globalFlag++;
fclose(input);
state++;
pthread_mutex_unlock(&lockMain);
return 0;
}
else
{
printFlag = 1;
pthread_mutex_unlock(&lockMain);
}
}
}
fclose(input);
return 0;
}
int main(void)
{
FILE* output = fopen("hw5.out", "w");
pthread_create(&(tid[0]), 0, &thread1, 0);
pthread_create(&(tid[1]), 0, &thread2, 0);
pthread_create(&(tid[2]), 0, &thread3, 0);
while(globalFlag < 3)
{
pthread_mutex_lock(&lockMain);
if(printFlag == 1 && globalFlag < 3)
{
if(globalChar == '\\0')
break;
fprintf(output, "%c\\n", globalChar);
printFlag = 0;
}
if(state == 1 && globalFlag < 2)
{
state++;
pthread_mutex_unlock(&lock2);
}
else if(state == 2 && globalFlag < 3)
{
state++;
pthread_mutex_unlock(&lock3);
}
else if((state == 3 || state == 0) && globalFlag < 1)
{
state = 1;
pthread_mutex_unlock(&lock1);
}
else if(state == 4)
break;
}
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_join(tid[2], 0);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
pthread_mutex_destroy(&lock3);
pthread_mutex_destroy(&lockMain);
fclose(output);
return 0;
}
| 0
|
#include <pthread.h>
struct threadArgs{
int* numbers;
long threadId;
int size;
};
struct threadReturnValue{
int number;
long threadId;
struct threadReturnValue* nextPtr;
};
pthread_mutex_t mutexModify;
int selectNumber;
void removeNotPrimes(int selected, int* numbers,int size,long threadId){
if (numbers[selected] != 0)
{
int x = selected * selected;
while (x <= size)
{
numbers[x] = 0;
x = x + selected;
}
}
}
int isnumeric(char *str)
{
while(*str)
{
if(!isdigit(*str))
return 0;
str++;
}
return 1;
}
int isPrime(int number,long threadId) {
int i;
for (i=2; i<number; i++) {
if (number % i == 0 && i != number) return 0;
}
return 1;
}
void* FindPrimes(void* tArgs)
{
struct threadReturnValue *returnValueFirst=0;
struct threadReturnValue *returnValueLast=0;
int selected;
pthread_mutex_lock (&mutexModify);
struct threadArgs *myArgs = (struct threadArgs*)tArgs;
while(selectNumber < myArgs->size){
while( myArgs->numbers[selectNumber] ==0){
if(selectNumber < myArgs->size)
selectNumber++;
}
selected = myArgs->numbers[selectNumber];
selectNumber++;
pthread_mutex_unlock (&mutexModify);
if(isPrime(selected,myArgs->threadId)==1){
if(returnValueFirst==0){
returnValueFirst = malloc(sizeof(struct threadReturnValue));
returnValueFirst->threadId = myArgs->threadId;
returnValueFirst->number = selected;
returnValueFirst->nextPtr = 0;
returnValueLast = returnValueFirst;
}else{
returnValueLast->nextPtr = malloc(sizeof(struct threadReturnValue));
returnValueLast->nextPtr->threadId = myArgs->threadId;
returnValueLast->nextPtr->number = selected;
returnValueLast->nextPtr->nextPtr = 0;
returnValueLast = returnValueLast->nextPtr;
}
}
pthread_mutex_lock (&mutexModify);
}
pthread_mutex_unlock (&mutexModify);
pthread_exit((void*)returnValueFirst);
}
int main(int argc, char **argv){
int i,rc,size,noOfThreads=2;
long t;
void *status;
for (i = 0; i < argc; ++i)
{
printf("argv[%d]: %s\\n", i, argv[i]);
if( argv[1] == 0 || (strcmp(argv[1],"-t") && strcmp(argv[1],"-n"))){
printf("You didn't specify any valid argument \\n");
return;
}
if(!strcmp(argv[i],"-n")){
if(argv[i+1]!=0){
if( isnumeric(argv[i+1]) ){
sscanf(argv[i+1], "%d", &size);
}else{
printf("Your argument is not numeric\\n");
return;
}
}else{
printf("You didn't specify the number interval\\n");
return;
}
}
else if(!strcmp(argv[i],"-t")){
if(argv[i+1]!=0){
if( isnumeric(argv[i+1])){
sscanf(argv[i+1], "%d", &noOfThreads);
}else{
printf("Your argument is not numeric\\n");
return;
}
}else{
printf("You didn't specify the number of threads\\n");
return;
}
}
}
if((argv[5]==0 || argv[6]==0) || strcmp(argv[5],"-o")){
printf("You didn't specify the file name\\n");
return;
}
int numbers[size];
pthread_t threads[noOfThreads];
for (i = 2; i <= size; i++)
numbers[i] = i;
int in;
struct threadArgs * tArgs;
tArgs = malloc(noOfThreads*sizeof(struct threadArgs));
pthread_mutex_init(&mutexModify, 0);
for(t=0;t<noOfThreads;t++){
(tArgs+t)->threadId = t;
(tArgs+t)->size = size;
(tArgs+t)->numbers = numbers;
printf("In main: creating thread %ld\\n", t);
rc = pthread_create(&threads[t], 0, FindPrimes, (void *)(tArgs+t));
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
struct threadReturnValue *firstPtr = 0;
struct threadReturnValue *lastPtr = 0;
struct threadReturnValue *ret;
for(i=0;i<noOfThreads;i++) {
ret = 0;
pthread_join(threads[i], (void**)&ret);
if(firstPtr==0){
firstPtr=ret;
lastPtr = firstPtr;
while(lastPtr->nextPtr!=0){
lastPtr = lastPtr ->nextPtr;
}
}else{
lastPtr->nextPtr = ret;
while(lastPtr->nextPtr!=0){
lastPtr = lastPtr ->nextPtr;
}
}
}
lastPtr = firstPtr;
FILE * fp;
fp = fopen (argv[6], "w+");
while(lastPtr!= 0){
fprintf(fp,"**thread id is : %ld, and prime number is: %d\\n",lastPtr->threadId,lastPtr->number);
printf("**thread id is : %ld, and prime number is: %d\\n",lastPtr->threadId,lastPtr->number);
lastPtr = lastPtr->nextPtr;
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
};
static struct foo *g_fp = 0;
struct foo *foo_alloc(int id) {
struct foo *fp;
if((fp = malloc(sizeof(struct foo))) != 0){
fp->f_count = 1;
fp->f_id = id;
if(pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
}
return(fp);
}
void foo_hold(struct foo *fp) {
int i;
pthread_mutex_lock(&fp->f_lock);
for(i = 0; i < 100; i++){
fp->f_count++;
printf("fp fcount:%d\\n", fp->f_count);
}
pthread_mutex_unlock(&fp->f_lock);
}
void foo_hold_1(struct foo *fp) {
int i;
pthread_mutex_lock(&fp->f_lock);
for(i = 0; i < 5; i++){
fp->f_count++;
printf("thread 1 fp fcount:%d\\n", fp->f_count);
}
pthread_mutex_unlock(&fp->f_lock);
}
void foo_hold_2(struct foo *fp) {
int i;
pthread_mutex_lock(&fp->f_lock);
for(i = 0; i < 5; i++){
fp->f_count++;
printf("thread 2 fp fcount:%d\\n", fp->f_count);
}
pthread_mutex_unlock(&fp->f_lock);
}
void foo_rele(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
if(--fp->f_count == 0) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else {
pthread_mutex_unlock(&fp->f_lock);
}
}
void *thr_func1(void *argv) {
int i;
printf("start thread 1!\\n");
for(i = 0; i < 100; i++){
foo_hold_1(g_fp);
}
printf("end of thread 1!\\n");
}
void *thr_func2(void *argv) {
int i;
printf("start thread 2!\\n");
for(i = 0; i < 100; i++){
foo_hold_2(g_fp);
}
printf("end of thread 2!\\n");
}
int main(void) {
pthread_t tid1,tid2;
g_fp = foo_alloc(1);
pthread_create(&tid1,0,thr_func1, 0);
pthread_create(&tid2, 0, thr_func2, 0);
pause();
foo_rele(g_fp);
pause();
return 0;
}
| 0
|
#include <pthread.h>
int row;
int col;
}parameters;
int sudokoSolution1[9][9] = { {6, 2, 4, 5, 3, 9, 1, 8, 7},
{5, 1, 9, 7, 2, 8, 6, 3, 4},
{8, 3, 7, 6, 1, 4, 2, 9, 5},
{1, 4, 3, 8, 6, 5, 7, 2, 9},
{9, 5, 8, 2, 4, 7, 3, 6, 1},
{7, 6, 2, 3, 9, 1, 4, 5, 8},
{3, 7, 1, 9, 5, 6, 8, 4, 2},
{4, 9, 6, 1, 8, 2, 5, 7, 3},
{2, 8, 5, 4, 7, 3, 9, 1, 6}
};
int validRow[9] = {0};
int validCol[9] = {0};
pthread_mutex_t locker;
void *isValid(void* checkRC);
int main(){
pthread_t thread_ids[9];
pthread_mutex_init(&locker, 0);
int index;
int checkThread;
parameters *data;
for (index = 0; index < 9; index++){
data = (parameters *) malloc(sizeof(parameters));
(*data).row = index;
(*data).col = index;
checkThread = pthread_create(&thread_ids[index], 0, isValid, (void *) data);
if (checkThread != 0) {fprintf(stderr, "FAiled tp create thread %d", index); exit(1);}
}
for(index = 0; index < 9; index++){
checkThread = pthread_join(thread_ids[index], 0);
if(checkThread != 0){fprintf(stderr, "FAiled tp join thread %d", index); exit(1);};
}
printf("Checkin If Valid:\\n");
int isValid = 0;
for(index = 0; index < 9; index++){
if(validRow[index] == 1){
isValid = validRow[index];
printf("Invalid Row %d = %d \\n", index+1, validRow[index]);
}if(validCol[index] == 1){
isValid = validCol[index];
printf("Invalid Col %d = %d \\n", index+1, validCol[index]);
}
}
if (isValid != 0){
printf("\\nNot Valid Solution!\\n");
}else{
printf("\\nValid Solution!\\n");
}
return 0;
}
void *isValid(void* checkRC){
parameters *threadData = (parameters*) checkRC;
int row = (*threadData).row;
int col = (*threadData).col;
int i, j;
int rowSum;
int colSum;
for(i = 0; i < 9; i++){
rowSum += sudokoSolution1[row][i];
}
for(j = 0; j < 9; j++){
colSum += sudokoSolution1[j][col];
}
pthread_mutex_lock(&locker);
if(rowSum != 45){
validRow[row] = 1;
}if(colSum != 45){
validCol[col] = 1;
}
pthread_mutex_unlock(&locker);
free(threadData);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((800)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t threads[4];
sem_t sems[4];
char *file_name[] = {"1.txt", "2.txt", "3.txt", "4.txt"};
FILE *files[4];
int file_id = 0;
int cow = 0;
void * func()
{
for (int m = 0; m < 20; m++)
{
for (int i = 0; i < 4; i++)
{
if (pthread_equal(pthread_self(), threads[i]))
{
sem_wait(&sems[i]);
printf("%s add:%d\\n", file_name[file_id], i + 1);
pthread_mutex_lock(&mutex);
file_id++;
if (file_id == 4)
{
file_id = 0;
cow++;
cow = cow % 4;
sem_post(&sems[cow]);
}
else
sem_post(&sems[(i + 1) % 4]);
pthread_mutex_unlock(&mutex);
}
}
}
}
int main(int argc, char const *argv[])
{
pthread_mutex_init(&mutex, 0);
for (int i = 0; i < 4; i++)
files[i] = fopen(file_name[i], "w");
for (int i = 0; i < 4; i++)
{
if (i == 0)
sem_init(sems + i, 0, 1);
else
sem_init(sems + i, 0, 0);
}
for (int i = 0; i < 4; i++)
pthread_create(threads + i, 0, func, 0);
for (int i = 0; i < 4; i++)
pthread_join(threads[i], 0);
printf("Process eixt\\n");
return 0;
}
| 1
|
#include <pthread.h>
int webSockState;
unsigned long initId;
struct mg_connection *conn;
} tWebSockInfo;
static pthread_mutex_t sMutex;
static tWebSockInfo *socketList[(256)];
static void send_to_all_websockets(const char * data, int data_len) {
int i;
for (i=0;i<(256);i++) {
if (socketList[i] && (socketList[i]->webSockState==2)) {
mg_websocket_write(socketList[i]->conn, WEBSOCKET_OPCODE_TEXT, data, data_len);
}
}
}
void websocket_ready_handler(struct mg_connection *conn) {
int i;
struct mg_request_info * rq = mg_get_request_info(conn);
tWebSockInfo * wsock = malloc(sizeof(tWebSockInfo));
assert(wsock);
wsock->webSockState = 0;
rq->conn_data = wsock;
pthread_mutex_lock(&sMutex);
for (i=0;i<(256);i++) {
if (0==socketList[i]) {
socketList[i] = wsock;
wsock->conn = conn;
wsock->webSockState = 1;
break;
}
}
printf("\\nNew websocket attached: %08lx:%u\\n", rq->remote_ip, rq->remote_port);
pthread_mutex_unlock(&sMutex);
}
static void websocket_done(tWebSockInfo * wsock) {
int i;
if (wsock) {
wsock->webSockState = 99;
for (i=0;i<(256);i++) {
if (wsock==socketList[i]) {
socketList[i] = 0;
break;
}
}
printf("\\nClose websocket attached: %08lx:%u\\n", mg_get_request_info(wsock->conn)->remote_ip, mg_get_request_info(wsock->conn)->remote_port);
free(wsock);
}
}
int websocket_data_handler(struct mg_connection *conn, int flags, char *data, size_t data_len) {
struct mg_request_info * rq = mg_get_request_info(conn);
tWebSockInfo * wsock = (tWebSockInfo*)rq->conn_data;
char msg[128];
pthread_mutex_lock(&sMutex);
if (flags==136) {
websocket_done(wsock);
rq->conn_data = 0;
pthread_mutex_unlock(&sMutex);
return 1;
}
if (((data_len>=5) && (data_len<100) && (flags==129)) || (flags==130)) {
if ((wsock->webSockState==1) && (!memcmp(data,"init ",5))) {
char * chk;
unsigned long gid;
memcpy(msg,data+5,data_len-5);
msg[data_len-5]=0;
gid = strtoul(msg,&chk,10);
wsock->initId = gid;
if (gid>0 && chk!=0 && *chk==0) {
wsock->webSockState = 2;
}
pthread_mutex_unlock(&sMutex);
return 1;
}
if ((wsock->webSockState==2) && (!memcmp(data,"msg ",4))) {
send_to_all_websockets(data, data_len);
pthread_mutex_unlock(&sMutex);
return 1;
}
}
if ((data_len==4) && !memcmp(data,"ping",4)) {
pthread_mutex_unlock(&sMutex);
return 1;
}
pthread_mutex_unlock(&sMutex);
return 0;
}
void connection_close_handler(struct mg_connection *conn) {
struct mg_request_info * rq = mg_get_request_info(conn);
tWebSockInfo * wsock = (tWebSockInfo*)rq->conn_data;
pthread_mutex_lock(&sMutex);
websocket_done(wsock);
rq->conn_data = 0;
pthread_mutex_unlock(&sMutex);
}
static int runLoop = 0;
static void * eventMain(void * _ignored) {
int i;
char msg[256];
runLoop = 1;
while (runLoop) {
time_t t = time(0);
struct tm * timestr = localtime(&t);
sprintf(msg,"title %s",asctime(timestr));
pthread_mutex_lock(&sMutex);
for (i=0;i<(256);i++) {
if (socketList[i] && (socketList[i]->webSockState==2)) {
mg_websocket_write(socketList[i]->conn, WEBSOCKET_OPCODE_TEXT, msg, strlen(msg));
}
}
pthread_mutex_unlock(&sMutex);
usleep((1000) * 1000);
}
return _ignored;
}
void websock_send_broadcast(const char * data, int data_len) {
char buffer[260];
if (data_len<=256) {
strcpy(buffer, "msg ");
memcpy(buffer+4, data, data_len);
pthread_mutex_lock(&sMutex);
send_to_all_websockets(buffer, data_len+4);
pthread_mutex_unlock(&sMutex);
}
}
void websock_init_lib(void) {
int ret;
ret = pthread_mutex_init(&sMutex, 0);
assert(ret==0);
memset(socketList,0,sizeof(socketList));
mg_start_thread(eventMain, 0);
}
void websock_exit_lib(void) {
runLoop = 0;
}
| 0
|
#include <pthread.h>
char** theArray;
pthread_mutex_t **mutexArray;
void* ServerEcho(void *args);
int main(){
printf("creating mutex array \\n");
theArray=malloc(100*sizeof(char));
for (int i=0; i<100;i++){
theArray[i]=malloc(100*sizeof(char));
sprintf(theArray[i], "%s%d%s", "String ", i, ": the initial value" );
}
mutexArray=malloc(100*sizeof(pthread_mutex_t*));
for (int i=0; i<100;i++){
mutexArray[i]=malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(mutexArray[i],0);
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
pthread_t* thread_handles;
thread_handles = malloc(1000*sizeof(pthread_t));
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=3000;
sock_var.sin_family=AF_INET;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
printf("socket has been created \\n");
listen(serverFileDescriptor,2000);
while(1){
for(int i=0;i<1000;i++){
clientFileDescriptor=accept(serverFileDescriptor,0,0);
printf("Connect to client %d \\n",clientFileDescriptor);
pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor);
}
for(int i = 0;i<1000;i++){
pthread_join(thread_handles[i],0);
}
printf("All threads have joined. Checking Array \\n");
for(int i=0;i<100;i++){
printf("%s\\n",theArray[i]);
free(theArray[i]);
}
free(theArray);
free(thread_handles);
for (int i=0; i<100;i++){
pthread_mutex_destroy(mutexArray[i]);
free(mutexArray[i]);
}
}
}
else{
printf("socket creation failed \\n");
return 1;
}
return 0;
}
void* ServerEcho(void* args){
long clientFileDescriptor = (long) args;
char buff[100];
read(clientFileDescriptor,buff,100);
int pos;
char operation;
sscanf(buff, "%d %c", &pos,&operation);
printf("a Server thread recieved position %d and operation %c from %ld \\n",pos,operation,clientFileDescriptor);
if(operation=='r'){
char msg[100];
pthread_mutex_lock(mutexArray[pos]);
sprintf(msg, "%s", theArray[pos] );
pthread_mutex_unlock(mutexArray[pos]);
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else if(operation=='w'){
pthread_mutex_lock(mutexArray[pos]);
sprintf(theArray[pos], "%s%d%s","String ", pos, " has been modified by a write request\\n" );
pthread_mutex_unlock(mutexArray[pos]);
char msg[100];
sprintf(msg, "%s%d%s","String ", pos, " has been modified by a write request \\n" );
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else{
printf("there has been an error communicating with the client \\n");
}
return 0;
}
| 1
|
#include <pthread.h>
void *func(int n);
pthread_t philosopher[5];
pthread_mutex_t chopstick[5];
void *func(int n)
{
printf("Philosopher %d is thinking \\n",n);
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n+1)%5]);
printf("Philosopher %d is eating now\\n",n);
sleep(1);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%5]);
printf("Philosopher %d finished eating \\n",n);
}
int main()
{
int i,k;
void *msg;
for(i=1;i<=5;i++)
{
k=pthread_mutex_init(&chopstick[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 *)func,(int *)i);
if(k!=0)
{
printf("pthread_create error \\n");
exit(1);
}
}
for(i=1;i<=5;i++)
{
k=pthread_join(philosopher[i],&msg);
if(k!=0)
{
printf("\\n pthread_join failed \\n");
exit(1);
}
}
printf("Everyone has finished eating\\n");
for(i=1;i<=5;i++)
{
k=pthread_mutex_destroy(&chopstick[i]);
if(k==0)
{
printf("Mutex of chopstick %d Destroyed \\n",i);
}
}
return 0;
}
| 0
|
#include <pthread.h>
void* clnt_connection(void * arg);
void send_message(char* message, int len);
void error_handling(char * message);
int clnt_number=0; int clnt_socks[10];
pthread_mutex_t mutx;
int main(int argc, char **argv)
{
int serv_sock;
int clnt_sock;
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
int clnt_addr_size;
pthread_t thread;
if(argc != 2)
{
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
if(pthread_mutex_init(&mutx,0))
error_handling("mutex init error");
serv_sock = socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) == -1)
error_handling("bind() error");
if(listen(serv_sock, 5) == -1)
error_handling("listen() error");
while(1) {
clnt_addr_size = sizeof(clnt_addr);
clnt_sock = accept(serv_sock, (struct sockaddr *)&clnt_addr, &clnt_addr_size);
pthread_mutex_lock(&mutx);
clnt_socks[clnt_number++]=clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&thread, 0, clnt_connection, (void*) clnt_sock);
printf(" IP : %s \\n", inet_ntoa(clnt_addr.sin_addr));
}
return 0;
}
void *clnt_connection(void *arg)
{
int clnt_sock = (int) arg;
int str_len=0;
char message[100];
int i;
while((str_len=read(clnt_sock, message, sizeof(message))) != 0 )
send_message(message, str_len);
pthread_mutex_lock(&mutx);
for(i=0;i<clnt_number;i++)
{
if(clnt_sock == clnt_socks[i])
{
for(;i<clnt_number-1;i++) clnt_socks[i] = clnt_socks[i+1]; break;
}
}
clnt_number--;
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void send_message(char * message, int len)
{
int i;
pthread_mutex_lock(&mutx);
for(i=0;i<clnt_number;i++)
write(clnt_socks[i], message, len);
pthread_mutex_unlock(&mutx);
}
void error_handling(char * message)
{
fputs(message, stderr);
fputc('\\n',stderr);
exit(1);
}
| 1
|
#include <pthread.h>
int pwstart(void) {
pthread_attr_t attr_t;
pthread_attr_init(&attr_t);
pthread_attr_setdetachstate(&attr_t, PTHREAD_CREATE_DETACHED);
return pthread_create(&CONTRAL.thread_key, &attr_t, BATTERY.server, 0);
}
void *pwserver(void *args) {
struct timespec timeout;
while (1) {
mktimeout(&timeout, 1);
int r = pthread_cond_timedwait(&BATTERY.sig, &BATTERY.siglock, &timeout);
if (r == 110)
continue;
pthread_mutex_lock(&BATTERY.colock);
switch (BATTERY.state) {
case 1:
set_power_start(1);
usleep(1500 * 1000);
set_power_start(0);
BATTERY.state = 0;
break;
case 2:
set_power_end(1);
usleep(1500 * 1000);
set_power_end(0);
BATTERY.state = 0;
break;
}
pthread_mutex_unlock(&BATTERY.colock);
}
return 0;
}
int pwbegin(void) {
pthread_mutex_trylock(&BATTERY.colock);
BATTERY.state = 1;
pthread_mutex_unlock(&BATTERY.colock);
return pthread_cond_signal(&BATTERY.sig);
}
int pwend(void) {
pthread_mutex_trylock(&BATTERY.colock);
BATTERY.state = 2;
pthread_mutex_unlock(&BATTERY.colock);
return pthread_cond_signal(&BATTERY.sig);
}
| 0
|
#include <pthread.h>
{
int id;
int sleep_time;
} parm;
pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
char message[128];
int token = 0;
void *hello_world(void *arg)
{
parm *p = (parm *) arg;
int id = p->id;
int sleep_time = p->sleep_time;
int i;
if (id != 0) {
while (1) {
pthread_mutex_lock(&msg_mutex);
if (token == 0) {
sprintf(message, "Hello from thread %d!", id);
token++;
pthread_mutex_unlock(&msg_mutex);
break;
}
pthread_mutex_unlock(&msg_mutex);
sleep(sleep_time);
}
}
else {
for (i = 1; i < 5; i++) {
while (1) {
pthread_mutex_lock(&msg_mutex);
if (token == 1) {
printf("Thread 0 receives %s\\n", message);
token--;
pthread_mutex_unlock(&msg_mutex);
break;
}
pthread_mutex_unlock(&msg_mutex);
sleep(sleep_time);
}
}
}
}
int main() {
int i;
int sleep_time;
pthread_t threads[5];
parm p[5];
time_t t1;
int ret;
time(&t1);
srand48((long) t1);
printf("The process is generating %d threads.\\n", 5);
for (i = 0; i < 5; i++) {
sleep_time = 1 + lrand48() % 3;
p[i].id = i;
p[i].sleep_time = sleep_time;
pthread_create(&threads[i], 0, hello_world, (void *)&p[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(threads[i], 0);
}
exit(0);
}
| 1
|
#include <pthread.h>
QUEUE queue_init(size_t capacity);
bool queue_destroy(QUEUE *q);
bool queue_put(QUEUE q, uintptr_t *item);
bool queue_get(QUEUE q, uintptr_t *item);
bool queue_look(QUEUE q, uintptr_t *item);
size_t queue_size(QUEUE q);
bool queue_empty(QUEUE q);
bool queue_full(QUEUE q);
struct QueueStruct {
Node head;
Node tail;
pthread_mutex_t mxlock;
size_t capacity;
size_t count;
};
struct NodeStruct {
Node next;
uintptr_t data;
};
QUEUE queue_init(size_t capacity) {
QUEUE queue = malloc(sizeof(*queue));
if (queue == 0) {
errno = ENOMEM;
return (0);
}
Node sentinel = malloc(sizeof(*sentinel));
if (sentinel == 0) {
errno = ENOMEM;
return (0);
}
sentinel->next = 0;
sentinel->data = 0;
queue->head = sentinel;
queue->tail = sentinel;
pthread_mutex_init(&queue->mxlock, 0);
queue->capacity = (capacity == 0) ? (SIZE_MAX) : (capacity);
queue->count = 0;
return (queue);
}
bool queue_destroy(QUEUE *q) {
pthread_mutex_lock(&(*q)->mxlock);
Node curr = (*q)->head, succ = 0;
while (curr != 0) {
succ = curr->next;
free(curr);
curr = succ;
}
pthread_mutex_unlock(&(*q)->mxlock);
pthread_mutex_destroy(&(*q)->mxlock);
free(*q);
*q = 0;
return (1);
}
bool queue_put(QUEUE q, uintptr_t *item) {
Node node = malloc(sizeof(*node));
if (node == 0) {
errno = ENOMEM;
return (0);
}
node->data = *item;
node->next = 0;
pthread_mutex_lock(&q->mxlock);
if (q->count == q->capacity) {
pthread_mutex_unlock(&q->mxlock);
free(node);
errno = EXFULL;
return (0);
}
q->tail->next = node;
q->tail = node;
q->count++;
pthread_mutex_unlock(&q->mxlock);
return (1);
}
bool queue_get(QUEUE q, uintptr_t *item) {
pthread_mutex_lock(&q->mxlock);
Node prev = q->head, curr = prev->next;
if (curr == 0) {
pthread_mutex_unlock(&q->mxlock);
errno = ENOENT;
return (0);
}
q->head = curr;
*item = curr->data;
q->count--;
pthread_mutex_unlock(&q->mxlock);
free(prev);
return (1);
}
bool queue_look(QUEUE q, uintptr_t *item) {
pthread_mutex_lock(&q->mxlock);
Node curr = q->head->next;
if (curr == 0) {
pthread_mutex_unlock(&q->mxlock);
errno = ENOENT;
return (0);
}
*item = curr->data;
pthread_mutex_unlock(&q->mxlock);
return (1);
}
size_t queue_size(QUEUE q) {
pthread_mutex_lock(&q->mxlock);
size_t size = q->count;
pthread_mutex_unlock(&q->mxlock);
return (size);
}
bool queue_empty(QUEUE q) {
pthread_mutex_lock(&q->mxlock);
bool empty = (q->count == 0);
pthread_mutex_unlock(&q->mxlock);
return (empty);
}
bool queue_full(QUEUE q) {
pthread_mutex_lock(&q->mxlock);
bool full = (q->count == q->capacity);
pthread_mutex_unlock(&q->mxlock);
return (full);
}
| 0
|
#include <pthread.h>
pthread_cond_t taxiCond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t taxiMutex = PTHREAD_MUTEX_INITIALIZER;
int travelerCount = 0;
void *traveler_arrive(void *name){
printf("Traveler %s needs a taxi now!\\n", (char *)name);
pthread_mutex_lock(&taxiMutex);
travelerCount++;
pthread_cond_wait(&taxiCond, &taxiMutex);
pthread_mutex_unlock(&taxiMutex);
printf("Traveler %s now got a taxi!\\n", (char *)name);
pthread_exit(0);
}
void *taxi_arrive(void *name){
printf("Taxi %s arrives\\n", (char *)name);
while(1){
pthread_mutex_lock(&taxiMutex);
if(travelerCount > 0){
pthread_cond_signal(&taxiCond);
pthread_mutex_unlock(&taxiMutex);
break;
}
pthread_mutex_unlock(&taxiMutex);
}
pthread_exit(0);
}
int main(){
pthread_t thread;
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_create(&thread, &threadAttr, taxi_arrive, (void *)("Jack"));
sleep(1);
pthread_create(&thread, &threadAttr, traveler_arrive, (void *)("Susan"));
sleep(1);
pthread_create(&thread, &threadAttr, taxi_arrive, (void *)("Mike"));
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
volatile int running_threads = 0;
void *library;
void push(struct Stack **head, char name[])
{
struct Stack *tmp = (struct Stack *)malloc(sizeof(struct Stack));
if (tmp == 0)
{
exit(1);
}
tmp->next = *head;
strcpy(tmp->fileName, "./Files/");
strcat(tmp->fileName, name);
*head = tmp;
}
void pop(struct Stack **head)
{
struct Stack *out;
if (*head == 0)
{
exit(1);
}
out = *head;
*head = (*head)->next;
free(out);
}
void SearchFiles(struct Stack **stack)
{
DIR *dfd;
struct dirent *dp;
dfd = opendir("./Files/");
while((dp = readdir(dfd)) != 0)
{
size_t len = strlen(dp->d_name);
if (!strcmp(dp->d_name, "All files.txt"))
{
continue;
}
else if (len > 4 && strcmp(dp->d_name + len - 4, ".txt") == 0)
{
push(stack, dp->d_name);
}
}
closedir(dfd);
}
void SendData(char *fileName, int typeOfMessage)
{
if (typeOfMessage == 1)
{
strcpy(message, "Reader: Content of the file '");
strcat(message, fileName);
strcat(message, "' is read and is ready to record\\n");
}
else
{
strcpy(message, "Writer: Content of the file '");
strcat(message, fileName);
strcat(message, "' is write in output file\\n");
}
}
void* ThreadReader(void *arg)
{
struct Data *data = (struct Data *)arg;
void (*readDataFromFile)(int, char*);
*(void **) (&readDataFromFile) = dlsym(library, "ReadDataFromFile");
while (1)
{
pthread_mutex_lock(&(data->pMutex));
puts(message);
if (data->stack == 0)
{
break;
}
int fd = open(data->stack->fileName, O_RDONLY);
(*readDataFromFile)(fd, buffer);
SendData(data->stack->fileName, 1);
close(fd);
pthread_mutex_unlock(&(data->pMutex));
usleep(1);
}
running_threads--;
return 0;
}
void* ThreadWriter(void *arg)
{
struct Data *data = (struct Data *)arg;
pthread_mutex_lock(&(data->pMutex));
int fd = open("./Files/All files.txt", O_WRONLY | O_CREAT | O_TRUNC | O_APPEND);
void (*writeDataInFile)(int, char*);
*(void **) (&writeDataInFile) = dlsym(library, "WriteDataInFile");
pthread_mutex_unlock(&(data->pMutex));
usleep(1);
do
{
pthread_mutex_lock(&(data->pMutex));
puts(message);
(*writeDataInFile)(fd, buffer);
SendData(data->stack->fileName, 0);
pop(&(data->stack));
pthread_mutex_unlock(&(data->pMutex));
usleep(1);
} while (data->stack != 0);
close(fd);
running_threads--;
return 0;
}
void CreateThreads(struct Data *data)
{
pthread_create(&(data->pReader), 0, &ThreadReader, data);
running_threads++;
pthread_create(&(data->pWriter), 0, &ThreadWriter, data);
running_threads++;
}
void CreateMutexForThreads(struct Data *data)
{
pthread_mutex_init(&(data->pMutex), 0);
}
void CloseApp(struct Data *data)
{
pthread_mutex_destroy(&(data->pMutex));
dlclose(library);
}
void WaitThreads(struct Data *data)
{
while (running_threads > 0)
{
usleep(1);
}
}
void LoadLib()
{
library = dlopen("./myfun.so", RTLD_LAZY);
}
| 0
|
#include <pthread.h>
static int log_level = SLOG_DEBUG;
static const char *month[] = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};
static char *log_data = 0;
static int log_in, log_out, log_size;
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
int slog_init(int level)
{
log_level = level;
log_in = 0;
log_out = 0;
log_size = 4096*16;
log_data = malloc(log_size);
return 0;
}
void slog_level(int level)
{
pthread_mutex_lock(&log_mutex);
log_level = level;
pthread_mutex_unlock(&log_mutex);
}
void slog_send_buffer(int fd)
{
pthread_mutex_lock(&log_mutex);
if (log_in < log_out) {
write(fd, log_data + log_out, log_size - log_out);
write(fd, log_data, log_in);
} else {
write(fd, log_data + log_out, log_in - log_out);
}
pthread_mutex_unlock(&log_mutex);
}
void slog(int level, char *format, ...)
{
va_list ap;
char newfmt[512], line[1024];
struct tm tm;
time_t t;
int i, len, overwrite = 0;
__builtin_va_start((ap));
time(&t);
localtime_r(&t, &tm);
snprintf(newfmt, 512, "[%04d-%02d-%02d %02d:%02d:%02d] %s\\n",
tm.tm_year+1900, tm.tm_mon, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec,
format);
len = vsnprintf(line, sizeof(line), newfmt, ap);
;
if (level >= log_level) {
fputs(line, stderr);
}
pthread_mutex_lock(&log_mutex);
for (i = 0; i < len; ++i) {
log_data[log_in++] = line[i];
if (log_in == log_size) {
log_in = 0;
}
if (log_in == log_out) {
overwrite = 1;
}
}
if (overwrite) {
log_out = log_in;
while (log_data[log_out] != '\\n') {
if (++log_out == log_size)
log_out = 0;
}
if (++log_out == log_size)
log_out = 0;
}
pthread_mutex_unlock(&log_mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t help_mutex;
pthread_mutex_t count_mutex;
sem_t TA_sem;
sem_t student_sem;
int number_waiting;
int go_home;
long nsecSleep;
int numberOfIterations;
} sleepAndCount;
void* simulate_student(void* param);
void* simulate_TA(void* param);
int main(int argc, char** argv) {
if (argc != 2) {
printf("Usage: ./organize <number of students>\\n");
return 1;
}
int numberOfStudents = atoi(argv[1]);
if (numberOfStudents <= 0) {
printf("Error: Number of students must be a positive integer.\\n");
return 2;
}
sem_init(&TA_sem, 0, 0);
sem_init(&student_sem, 0, 0);
number_waiting = 0;
go_home = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&help_mutex, 0);
pthread_mutex_init(&count_mutex, 0);
pthread_t tid_TA;
pthread_create(&tid_TA, &attr, simulate_TA, 0);
pthread_t* tid_students[numberOfStudents];
sleepAndCount* params[numberOfStudents];
int i;
for (i = 0; i < numberOfStudents; ++i) {
srand(time(0) + i);
tid_students[i] = malloc(sizeof(pthread_t));
params[i] = malloc(sizeof(sleepAndCount));
params[i]->nsecSleep = (long) rand() % 1000000000;
params[i]->numberOfIterations = 10;
pthread_create(tid_students[i], &attr, simulate_student, params[i]);
}
for (i = 0; i < numberOfStudents; ++i) {
pthread_join(*tid_students[i], 0);
free(tid_students[i]);
free(params[i]);
}
go_home = 1;
sem_post(&TA_sem);
pthread_join(tid_TA, 0);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&help_mutex);
pthread_mutex_destroy(&count_mutex);
sem_destroy(&TA_sem);
sem_destroy(&student_sem);
return 0;
}
void* simulate_TA(void* param) {
srand(time(0) / 2);
struct timespec time;
time.tv_sec = 0;
time.tv_nsec = (long) rand() % 1000000000;
while (1) {
printf("tid = 0x%08x, TA sleeping, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
sem_wait(&TA_sem);
if (go_home) break;
printf("tid = 0x%08x, TA awake, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
pthread_mutex_lock(&help_mutex);
sem_post(&student_sem);
pthread_mutex_lock(&count_mutex);
number_waiting--;
pthread_mutex_unlock(&count_mutex);
printf("tid = 0x%08x, TA helping student, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
nanosleep(&time, 0);
pthread_mutex_unlock(&help_mutex);
}
pthread_exit(0);
}
void* simulate_student(void* param) {
struct timespec time;
time.tv_sec = 0;
time.tv_nsec = ((sleepAndCount*)param)->nsecSleep;
int count = ((sleepAndCount*)param)->numberOfIterations;
int i;
for (i = 0; i < count; ++i) {
printf("tid = 0x%08x, student programming, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
nanosleep(&time, 0);
pthread_mutex_lock(&count_mutex);
if (number_waiting >= 3) {
printf("tid = 0x%08x, student waiting for chair, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
pthread_mutex_unlock(&count_mutex);
} else {
number_waiting++;
pthread_mutex_unlock(&count_mutex);
sem_post(&TA_sem);
printf("tid = 0x%08x, student waiting for TA, number_waiting = %d\\n",
(unsigned)pthread_self(), number_waiting);
sem_wait(&student_sem);
pthread_mutex_lock(&help_mutex);
pthread_mutex_unlock(&help_mutex);
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
extern void send_msg(const char* ip, int port, const char* msg);
extern volatile sig_atomic_t interrupt;
extern const char* RESPONSE;
extern void LLclear();
extern void LLfixDuplicateIPs();
extern pthread_mutex_t ll_mutex;
void* sendRequest(void* arg){
char ip[IP_MAX]="172.16.5.";
sprintf(ip+strlen(ip), "%d", *((int*)arg));
send_msg(ip, REQ_PORT, RESPONSE);
return 0;
}
void discover(){
int i, j, arr[254];
pthread_t threads[254];
fprintf(stderr, "discover start\\n");
pthread_mutex_lock(&ll_mutex);
LLclear();
pthread_mutex_unlock(&ll_mutex);
for(i=0; i<254 && !interrupt; ++i){
arr[i] = i+1;
pthread_create(threads+i, 0, sendRequest, (void*)(arr+i));
}
for(j=0; j<i; ++j)
pthread_join(threads[j], 0);
pthread_mutex_lock(&ll_mutex);
LLfixDuplicateIPs();
pthread_mutex_unlock(&ll_mutex);
fprintf(stderr, "discover done\\n");
}
| 1
|
#include <pthread.h>
int runStatus = RUN;
int receivedDataStatus = NO_NEW_DATA;
char sentData[DATA_LEN] = {'\\0'};
char receivedData[DATA_LEN] = {'\\0'};
pthread_mutex_t mutexData;
pthread_mutex_t mutexStop;
void destroyMutexes()
{
pthread_mutex_destroy(&mutexStop);
pthread_mutex_destroy(&mutexData);
}
void initMutexes()
{
pthread_mutex_init(&mutexStop, 0);
pthread_mutex_init(&mutexData, 0);
}
char* getSentData()
{
return sentData;
}
void setSentData(const char *dataStr)
{
pthread_mutex_lock(&mutexData);
if(strlen(sentData) != 0)
bzero(sentData, DATA_LEN);
strcpy(sentData, dataStr);
pthread_mutex_unlock(&mutexData);
}
void setReceivedData(const char *dataStr)
{
pthread_mutex_lock(&mutexData);
strcpy(receivedData, dataStr);
pthread_mutex_unlock(&mutexData);
}
char* getReceivedData()
{
pthread_mutex_lock(&mutexData);
if(receivedDataStatus == HAS_NEW_DATA)
{
receivedDataStatus = NO_NEW_DATA;
pthread_mutex_unlock(&mutexData);
return receivedData;
}
pthread_mutex_unlock(&mutexData);
return "";
}
void setRunStatus(const int status)
{
pthread_mutex_lock (&mutexStop);
runStatus = status;
pthread_mutex_unlock(&mutexStop);
}
const int getRunStatus()
{
int cur_status = STOP;
pthread_mutex_lock (&mutexStop);
cur_status = runStatus;
pthread_mutex_unlock(&mutexStop);
return cur_status;
}
void setReceivedDataStatus(const int status)
{
pthread_mutex_lock (&mutexData);
receivedDataStatus = status;
pthread_mutex_unlock(&mutexData);
}
| 0
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buff[100000];
int nput;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};
void * produce(void *);
void * consume(void *);
void consume_wait(int);
int main(int argc, char ** argv) {
int i, nthreads, count[100];
pthread_t tid_produce[100], tid_consume;
if (argc != 3) {
return -1;
}
nitems = min(atoi(argv[1]), 100000);
nthreads = min(atoi(argv[2]), 100);
pthread_setconcurrency(nthreads + 1);
for (i = 0; i < nthreads; ++i) {
count[i] = 0;
pthread_create(&tid_produce[i], 0, produce, &count[i]);
}
pthread_create(&tid_consume, 0, consume, 0);
for (i = 0; i < nthreads; ++i) {
pthread_join(tid_produce[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_join(tid_consume, 0);
return 0;
}
void consume_wait(int i) {
for (;;) {
pthread_mutex_lock(&shared.mutex);
if (i < shared.nput) {
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void * produce(void * arg) {
for (;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int*)arg) += 1;
}
return 0;
}
void * consume(void * arg) {
int i;
for (i = 0; i < nitems; ++i) {
consume_wait(i);
if (shared.buff[i] != i) {
printf("buff[%d] = %d\\n", i, shared.buff[i]);
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void *thread_func1(void *ignored_argument)
{
int s;
printf("\\n %s: \\n",__func__);
pthread_mutex_lock(&mutex);
printf("Thread 1 acquire mutex \\n");
pthread_mutex_unlock(&mutex);
printf("Thread 1 releases mutex \\n");
return 0;
}
static void *thread_func2(void *ignored_argument)
{
int s;
printf("\\n %s: \\n",__func__);
sleep(5);
printf("Thread 2 , waiting for mutex\\n");
pthread_mutex_lock(&mutex);
printf("Thread 2 acquire mutex \\n");
pthread_mutex_unlock(&mutex);
printf("Thread 2 releases mutex \\n");
return 0;
}
int main(void)
{
pthread_t thr1,thr2;
void *res;
int s;
s = pthread_create(&thr1, 0, &thread_func1, 0);
if (s != 0) {
perror("pthread_create");
exit(1);
}
s = pthread_create(&thr2, 0, &thread_func2, 0);
if (s != 0) {
perror("pthread_create");
exit(1);
}
sleep(2);
printf("main(): sending cancellation request\\n");
s = pthread_cancel(thr1);
if (s != 0) {
perror("pthread_cancel");
exit(1);
}
s = pthread_join(thr1, &res);
if (s != 0) {
perror("pthread_join");
exit(1);
}
if (res == PTHREAD_CANCELED)
printf("main(): thread was canceled\\n");
else
printf("main(): thread wasn't canceled (shouldn't happen!)\\n");
s = pthread_join(thr2, &res);
if (s != 0) {
perror("pthread_join");
exit(1);
}
exit(0);
}
| 0
|
#include <pthread.h>
void terminal_init ( void ) {
return;
}
void terminal_exit ( void ) {
return;
}
void terminal_update ( void ) {
float timestamp;
if( DEBUG ) {
printf("\\r");
if( datalog.enabled ) printf( " Log %s: ", datalog.dir );
else printf( " - - - - " );
timestamp = (float) ( timer_terminal.start_sec + ( timer_terminal.start_usec / 1000000.0f ) - datalog.offset );
printf( "%6.1f ", timestamp );
if( TERMINAL_IO ) terminal_io();
if( TERMINAL_ACC ) terminal_acc();
if( TERMINAL_GYR ) terminal_gyr();
if( TERMINAL_MAG ) terminal_mag();
if( TERMINAL_BARO ) terminal_baro();
if( TERMINAL_HEALTH ) terminal_health();
printf( " " );
fflush(stdout);
}
return;
}
void terminal_io ( void ) {
ushort i;
pthread_mutex_lock( &input.mutex );
for( i=0; i<4; i++ ) printf( "%06.3f ", input.ch[i] ); printf( " " );
pthread_mutex_unlock( &input.mutex );
pthread_mutex_lock( &output.mutex );
for( i=0; i<4; i++ ) printf( "%6.3f ", output.ch[i] ); printf( " " );
pthread_mutex_unlock( &output.mutex );
return;
}
void terminal_acc ( void ) {
ushort i;
pthread_mutex_lock( &acc.mutex );
for( i=0; i<3; i++ ) printf( "%05d ", acc.raw[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%05.2f ", acc.scaled[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%05.2f ", acc.filter[i] ); printf( " " );
pthread_mutex_unlock( &acc.mutex );
return;
}
void terminal_gyr ( void ) {
ushort i;
pthread_mutex_lock( &gyr.mutex );
for( i=0; i<3; i++ ) printf( "%05d ", gyr.raw[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%5.2f ", gyr.scaled[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%5.2f ", gyr.filter[i] ); printf( " " );
pthread_mutex_unlock( &gyr.mutex );
return;
}
void terminal_mag ( void ) {
ushort i;
pthread_mutex_lock( &mag.mutex );
for( i=0; i<3; i++ ) printf( "%05d ", mag.raw[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%5.2f ", mag.scaled[i] ); printf( " " );
for( i=0; i<3; i++ ) printf( "%5.2f ", mag.filter[i] ); printf( " " );
pthread_mutex_unlock( &mag.mutex );
return;
}
void terminal_baro ( void ) {
pthread_mutex_lock( &baro.mutex );
printf( "%5.2f ", baro.temp );
printf( "%6.2f ", baro.pres );
printf( "%6.2f ", baro.alt );
printf( " " );
pthread_mutex_unlock( &baro.mutex );
return;
}
void terminal_health ( void ) {
pthread_mutex_lock( &health.mutex );
printf( "%4.2f ", health.cpu );
printf( "%4.2f ", health.volt );
printf( " " );
pthread_mutex_unlock( &health.mutex );
return;
}
| 1
|
#include <pthread.h>
int arg_port, numthreads;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int sockfds[256];
int numsock = 0;
int numconns = 0;
char whois_greet[] = "% This is the RIPE Database query service.\\n% The objects are in RPSL format.\\n\\n";
void *startup(void *arg) {
int sock;
size_t len;
char buf[1024];
while (1) {
pthread_mutex_lock(&lock);
while (numsock <= 0) {
pthread_cond_wait(&cond, &lock);
}
numsock--;
sock = sockfds[numsock];
numconns++;
if (numconns > 100) {
numconns -= 100;
fprintf(stderr, ".");
}
pthread_mutex_unlock(&lock);
write(sock, whois_greet, sizeof(whois_greet)-1);
if (len = read(sock, &buf, 1024)) {
write(sock, buf, len);
}
if (close(sock) < 0) {
perror("close");
}
}
}
int main(int argc, char **argv) {
int i, mainsock;
pthread_attr_t attr;
if (argc < 3) {
printf("%s <numthreads> <serverport>\\n\\n", argv[0]);
exit(1);
}
numthreads = strtol(argv[1], 0, 10);
arg_port = strtol(argv[2], 0, 10);
mainsock = SK_getsock(0, arg_port, SOCK_STREAM, 1024);
if (mainsock < 0) {
fprintf(stderr, "SK_getsock(): couldn't allocate socket");
exit(0);
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_attr_setstacksize(&attr, 1048576);
printf("Creating %d threads, listening on port %d...\\n", numthreads, arg_port);
for (i = 0; i < numthreads; i++) {
pthread_t dummy;
int res = pthread_create(&dummy, &attr, startup, 0);
if (res != 0) {
perror("pthread_create");
exit(1);
}
}
printf("Thread creation done. Each . represents 100 served queries.\\nPress ctrl-c to exit.\\n");
while (1) {
int actsock = SK_accept_connection(mainsock);
if (actsock < 0) {
sleep(1);
continue;
}
pthread_mutex_lock(&lock);
if (numsock < 256) {
sockfds[numsock++] = actsock;
pthread_cond_signal(&cond);
} else {
fprintf(stderr, "Dropping connection (queue full)");
close(actsock);
sleep(1);
}
pthread_mutex_unlock(&lock);
}
return 0;
}
| 0
|
#include <pthread.h>
struct thd_data_t {
pthread_mutex_t mutex;
int found;
int val;
int start, stop;
};
struct thd_data_t data_x = {
.mutex = PTHREAD_MUTEX_INITIALIZER,
.found = 0,
.val = -1,
.start = 10000,
.stop = 20000,
};
struct thd_data_t data_y = {
.mutex = PTHREAD_MUTEX_INITIALIZER,
.found = 0,
.val = -1,
.start = 20000,
.stop = 30000,
};
static int factorial(int n)
{
int i;
int p = 1;
for (i = 0; i < n; i++)
p *= i;
return p;
}
static int is_super_number(int n)
{
return (factorial(n) % 123123 == 12345);
}
void *thread_routine_y(void * arg)
{
int i;
int finished = 0;
for (i = data_y.start; i < data_y.stop && !finished; i++) {
if (i % 100 == 0) {
printf("thread_Y: %d\\n", i);
}
int local_found = is_super_number(i);
pthread_mutex_lock(&data_y.mutex);
if (local_found) {
finished = 1;
data_y.found = 1;
data_y.val = i;
}
pthread_mutex_unlock(&data_y.mutex);
if (!local_found){
pthread_mutex_lock(&data_x.mutex);
if (data_x.found)
finished = 1;
pthread_mutex_unlock(&data_x.mutex);
}
}
return 0;
}
void *thread_routine_x(void *arg)
{
int finished = 0;
int i;
for (i = data_x.start; i < data_x.stop && !finished; i++) {
if (i % 100 == 0) {
printf("thread_X: %d\\n", i);
}
int local_found = is_super_number(i);
pthread_mutex_lock(&data_x.mutex);
if (local_found) {
finished = 1;
data_x.found = 1;
data_x.val = i;
}
pthread_mutex_unlock(&data_x.mutex);
if (!local_found) {
pthread_mutex_lock(&data_y.mutex);
if (data_y.found)
finished = 1;
pthread_mutex_unlock(&data_y.mutex);
}
}
return 0;
}
int main(void)
{
pthread_t tid_x;
pthread_t tid_y;
pthread_create(&tid_x, 0, thread_routine_x, (void *) 0);
pthread_create(&tid_y, 0, thread_routine_y, (void *) 1);
pthread_join(tid_y, 0);
pthread_join(tid_x, 0);
if (data_x.found) {
printf("Threadul X found the magic value %d\\n", data_x.val);
} else if (data_y.found) {
printf("Threadul Y found the magic value %d\\n", data_y.val);
} else {
printf("No thread found the magic value\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
struct products{
int buffer[2];
pthread_mutex_t lock;
int writepos;
int readpos;
pthread_cond_t not_full;
pthread_cond_t not_empty;
};
struct products buffer;
void init(struct products *prodc){
pthread_mutex_init(&(prodc->lock), 0);
pthread_cond_init(&(prodc->not_empty), 0);
pthread_cond_init(&(prodc->not_full), 0);
prodc->writepos = 0;
prodc->readpos = 0;
}
void put(struct products *prodc, int data){
pthread_mutex_lock(&(prodc->lock));
while((prodc->writepos+1)%2 == prodc->readpos){
printf("\\tproducer wait for condition : not_full\\n");
pthread_cond_wait(&(prodc->not_full), &(prodc->lock));
}
prodc->buffer[prodc->writepos] = data;
prodc->writepos++;
if(prodc->writepos >= 2){
prodc->writepos = 0;
}
pthread_cond_signal(&(prodc->not_empty));
pthread_mutex_unlock(&(prodc->lock));
}
int get(struct products *prodc){
int data;
pthread_mutex_lock(&(prodc->lock));
while(prodc->writepos == prodc->readpos){
printf("consumer wait for condition : not_empty\\n");
pthread_cond_wait(&(prodc->not_empty), &(prodc->lock));
}
data = prodc->buffer[prodc->readpos];
prodc->readpos++;
if(prodc->readpos == 2){
prodc->readpos = 0;
}
pthread_cond_signal(&(prodc->not_full));
pthread_mutex_unlock(&(prodc->lock));
return data;
}
void *producer(void *data){
int num;
for(num = 0; num < 5; num++){
printf("\\tproducer sleep 1 second...\\n");
sleep(1);
printf("\\tput the %dth product\\n", num);
put(&buffer, num);
}
for(num = 5; num < 5*2; num++){
printf("\\tproducer sleep 3 seconds...\\n");
sleep(3);
printf("\\tput the %dth product\\n", num);
put(&buffer, num);
}
put(&buffer, (-1));
printf("producer stopped\\n");
return 0;
}
void *consumer(void *data){
int pd = 0;
while(1){
printf("consumer sleep 2 seconds\\n");
sleep(2);
pd = get(&buffer);
printf("get the %dth product\\n", pd);
if(pd == (-1)){
break;
}
}
printf("consumer stopped\\n");
return 0;
}
int main(int argc, char *argv[]){
pthread_t tid1, tid2;
void *retval;
init(&buffer);
pthread_create(&tid1, 0, producer, 0);
pthread_create(&tid2, 0, consumer, 0);
pthread_join(tid1, &retval);
pthread_join(tid2, &retval);
return 0;
}
| 0
|
#include <pthread.h>
static int num = 0;
static pthread_mutex_t mut_num = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond_num = PTHREAD_COND_INITIALIZER;
void *is_prime(void *p)
{
int i, n, flag;
while(1)
{
pthread_mutex_lock(&mut_num);
while(num == 0)
{
pthread_cond_wait(&cond_num, &mut_num);
}
if(num == -1)
{
pthread_mutex_unlock(&mut_num);
break;
}
n = num;
num = 0;
pthread_cond_broadcast(&cond_num);
pthread_mutex_unlock(&mut_num);
for(i = 2, flag = 0; (i<= n/2)&&(!flag); i++)
{
if((n % i) == 0)
flag = 1;
}
if(!flag)
printf("[%d] --> %d\\n", (int)p, n);
}
pthread_exit(0);
}
int main()
{
int i, errno;
pthread_t tid[4];
for(i = 0; i < 4; i++){
errno = pthread_create(tid+i, 0, is_prime, (void *)i);
if(errno){
fprintf(stderr, "thread create err: %s\\n", strerror(errno));
exit(1);
}
}
for(i = 3000000; i <= 3002000; i++)
{
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_cond_wait(&cond_num, &mut_num);
}
num = i;
pthread_cond_signal(&cond_num);
pthread_mutex_unlock(&mut_num);
}
pthread_mutex_lock(&mut_num);
while(num != 0)
{
pthread_cond_wait(&cond_num, &mut_num);
}
num = -1;
pthread_cond_broadcast(&cond_num);
pthread_mutex_unlock(&mut_num);
for(i = 0; i < 4; i++)
pthread_join(tid[i], 0);
pthread_mutex_destroy(&mut_num);
pthread_cond_destroy(&cond_num);
exit(0);
}
| 1
|
#include <pthread.h>
int nbLignes;
int nbMsg;
} Parametres;
int nbThreads;
pthread_mutex_t mutex[20];
void thdErreur(int codeErr, char *msgErr, void *codeArret) {
fprintf(stderr, "%s: %d soit %s \\n", msgErr, codeErr, strerror(codeErr));
pthread_exit(codeArret);
}
void demanderAcces(int i) {
pthread_mutex_lock(&mutex[i]);
};
void libererAcces(int i) {
pthread_mutex_unlock(&mutex[(i+1)%nbThreads]);
};
void *thd_afficher (void *arg) {
int i, j, etat;
Parametres param = *(Parametres *)arg;
int s1, s2;
for (i = 0; i < param.nbMsg; i++) {
demanderAcces(param.nbLignes - 2);
for (j = 0; j < param.nbLignes; j++) {
printf("Afficheur(%lu), j'affiche Ligne %d/%d - Msg %d/%d \\n",
pthread_self(), j, param.nbLignes, i, param.nbMsg);
usleep(10);
}
libererAcces(param.nbLignes - 2);
}
printf("Thread %lu, je me termine \\n", pthread_self());
pthread_exit((void *)0);
}
int main(int argc, char*argv[]) {
pthread_t idThdAfficheurs[20];
Parametres param[20];
int i, etat;
if (argc != 2) {
printf("Usage : %s <Nb de threads>\\n", argv[0]);
exit(1);
}
for(int i = 0;i<20;i++)
pthread_mutex_init(&mutex[i],0);
for(int i = 1;i<20;i++)
demanderAcces(i);
nbThreads = atoi(argv[1]);
if (nbThreads > 20)
nbThreads = 20;
for (i = 0; i < nbThreads; i++) {
param[i].nbLignes = 2 + i;
param[i].nbMsg = 5;
if ((etat = pthread_create(&idThdAfficheurs[i], 0, thd_afficher, ¶m[i])) != 0)
thdErreur(etat, "Creation afficheurs", 0);
}
for (i = 0; i < nbThreads; i++) {
if ((etat = pthread_join(idThdAfficheurs[i], 0)) != 0)
thdErreur(etat, "Join threads afficheurs", 0);
}
printf ("\\nFin de l'execution du thread principal \\n");
return 0;
}
| 0
|
#include <pthread.h>
struct rotation_history_ring_buffer_t {
uint32_t ring_index;
uint32_t ring_size;
struct pose_t ring_data[1024];
};
struct rotation_history_ring_buffer_t location_history;
pthread_mutex_t pose_mutex;
struct pose_t get_rotation_at_timestamp(uint32_t timestamp)
{
pthread_mutex_lock(&pose_mutex);
uint32_t index_history = 0;
uint32_t closestTimeDiff = abs(timestamp - location_history.ring_data[0].timestamp);
uint32_t closestIndex = 0;
for (index_history = 0; index_history < location_history.ring_size; index_history++) {
uint32_t diff = abs(timestamp - location_history.ring_data[index_history].timestamp);
if (diff < closestTimeDiff) {
closestIndex = index_history;
closestTimeDiff = diff;
}
}
struct pose_t closest_pose;
closest_pose.eulers = location_history.ring_data[closestIndex].eulers;
closest_pose.rates = location_history.ring_data[closestIndex].rates;
pthread_mutex_unlock(&pose_mutex);
return closest_pose;
}
void pose_init()
{
location_history.ring_index = 0;
location_history.ring_size = 1024;
}
void pose_periodic()
{
uint32_t now_ts = get_sys_time_usec();
pthread_mutex_lock(&pose_mutex);
struct pose_t *current_time_and_rotation = &location_history.ring_data[location_history.ring_index];
current_time_and_rotation->eulers = *stateGetNedToBodyEulers_f();
current_time_and_rotation->rates = *stateGetBodyRates_f();
current_time_and_rotation->timestamp = now_ts;
location_history.ring_index = (location_history.ring_index + 1) % location_history.ring_size;
pthread_mutex_unlock(&pose_mutex);
}
| 1
|
#include <pthread.h>
bool not_end = 1;
char buffer[513];
char* args[64];
bool background = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
pid_t back_pid = -1;
pid_t front_pid = -1;
void end_process(){
if (front_pid == -1 && back_pid == -1)
{
printf ("\\n$ ");
fflush(stdout);
}
if (front_pid > 0 ){
kill(front_pid, SIGKILL);
printf ("Foreground child: %d.\\n", front_pid);
fflush(stdout);
front_pid = -1;
}
}
void proc_exit()
{
int wstat;
pid_t pid;
while (1)
{
pid = wait3 (&wstat, WNOHANG, (struct rusage *)0 );
if (pid == 0)
return;
else if (pid == -1)
return;
else{
printf ("Background child: %d.\\n", pid);
fflush(stdout);
if (back_pid == pid){
back_pid = -1;}
if (front_pid == -1){
printf("$ ");
fflush(stdout);}
}
}
}
void parse(char *input){
char *pch;
int filedesc = -1;
int in_filedesc = -1;
pch = strchr(input, '>');
if (pch != 0)
{
input[pch-input-1] = '\\0';
pch +=2;
filedesc = open(pch, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if(filedesc < 0){
return;
}
close(1);
if (dup(filedesc) < 0){
fprintf(stderr, "Chyba vytvorenia filedesc\\n");
return;
}
}
pch = strchr(input, '<');
if (pch != 0)
{
input[pch-input] = ' ';
pch +=2;
in_filedesc = open(pch, O_RDONLY, 0666);
if(in_filedesc < 0){
return;
}
close(0);
if (dup(in_filedesc) < 0){
fprintf(stderr, "Chyba vytvorenia filedesc\\n");
return;
}
}
pch = strtok(input, " \\t");
args[0] = pch;
if (pch != 0)
{
int i;
for (i = 0; pch != 0; i++)
{
args[i] = pch;
pch = strtok (0, " \\t");
}
args[i] = 0;
}
if (execvp(args[0], args) < 0) {
fprintf(stderr, "Prikaz \\"%s\\" neznamy\\n", args[0]);
if (filedesc >= 0)
close(filedesc);
exit(-1);
}
if (filedesc >= 0)
close(filedesc);
}
void *read_function()
{
int count = 0;
char *pch;
while(not_end){
pthread_mutex_lock( &mutex );
count = 0;
while (count < 1){
printf("$ ");
fflush(stdout);
count = read(0, buffer, 513);
if (count > 512){
fprintf(stderr, "Prilis velky vstup\\n");
continue;
}
pch = strchr(buffer, '\\n');
if(pch == 0){
printf("\\n");
fflush(stdout);
count++;
}
}
buffer[count-1] = '\\0';
if (strcmp(buffer, "exit") == 0){
not_end = 0;
}
pthread_cond_signal(&condition_cond);
pthread_mutex_unlock( &condition_mutex );
}
return 0;
}
void *run_function()
{
pthread_mutex_lock( &condition_mutex );
while(not_end)
{
pthread_cond_wait( &condition_cond, &condition_mutex );
if(!not_end)
break;
char* pch = strchr(buffer, '&');
if (pch != 0){
buffer[pch-buffer-1] = '\\0';
background = 1;
}
int status;
pid_t pid;
if ((pid = fork()) < 0) {
printf("Chyba fork()\\n");
exit(1);
}
else if (pid == 0) {
parse(buffer);
}
else
{
if (!background){
front_pid = pid;
while (wait(&status) != pid) ;
front_pid = -1;
}
else{
back_pid = pid;
}
background = 0;
}
pthread_mutex_unlock( &mutex );
}
return 0;
}
int main()
{
signal(SIGINT, end_process);
signal(SIGCHLD, proc_exit);
pthread_t thread[2];
void *result;
int res;
res = pthread_create( &thread[0], 0, run_function, 0);
if (res) {
printf("pthread_create() error %d\\n", res);
return 1;
}
res = pthread_create( &thread[1], 0, read_function, 0);
if (res) {
printf("pthread_create() error %d\\n", res);
return 1;
}
for (int i = 0; i < 2; i++)
{
if ((res = pthread_join(thread[i], &result)) != 0) {
printf("pthread_attr_init() err %d\\n",res);
return 1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t* mutexes;
char** messages;
void* Send_msg(void* rank);
int* messages_available;
long thread_count;
void Get_args(int argc, char* argv[]);
void Usage(char* prog_name);
int main(int argc, char* argv[]) {
long thread;
long mutex_index;
pthread_t* thread_handles;
Get_args(argc, argv);
messages = malloc(thread_count * sizeof(char *));
mutexes = malloc(thread_count * sizeof(pthread_mutex_t));
messages_available = malloc(thread_count * sizeof(int));
for (int i = 0; i < thread_count; i++) {
messages_available[i] = 0;
}
for (mutex_index = 0; mutex_index < thread_count; mutex_index++) {
pthread_mutex_init(&mutexes[mutex_index], 0);
}
thread_handles = malloc (thread_count * sizeof ( pthread_t) );
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, Send_msg, (void*) thread);
}
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
free(messages);
free(mutexes);
free(messages_available);
free(thread_handles);
return 0;
}
void* Send_msg(void* rank) {
long my_rank = (long) rank;
long source = (my_rank - 1 + thread_count) % thread_count;
long dest = (my_rank + 1) % thread_count;
char* my_msg = malloc(1024 * sizeof (char));
while (1) {
pthread_mutex_lock(&mutexes[dest]);
sprintf(my_msg, "Hello to thread %ld from thread %ld", dest, my_rank);
messages[dest] = my_msg;
messages_available[dest] = 1;
pthread_mutex_unlock(&mutexes[dest]);
break;
}
while (1) {
pthread_mutex_lock(&mutexes[my_rank]);
if (messages_available[my_rank] == 1) {
printf("Thread %ld > %s\\n", my_rank, messages[my_rank]);
pthread_mutex_unlock(&mutexes[my_rank]);
break;
}
pthread_mutex_unlock(&mutexes[my_rank]);
}
return 0;
}
void Get_args(int argc, char* argv[]) {
if (argc != 2) Usage(argv[0]);
thread_count = strtoll(argv[1], 0, 10);
if (thread_count <= 0) Usage(argv[0]);
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s < number of threads > 0 >\\n", prog_name);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_t prod[8];
pthread_t kons[8];
pthread_mutex_t blokada;
int bufor;
int produkcja;
void *producent (void *i)
{
int prod=0;
int nr=((int) i) + 1;
while(1)
{
if (produkcja==800 && bufor == 0)
{
printf("Producent %d wyprodukowal %d produktow.\\n",nr,prod);
return 0;
}
pthread_mutex_lock(&blokada);
if (bufor<15 && produkcja<800)
{
bufor++;
produkcja++;
prod++;
printf("Producent %d tworzy produkt nr %d.\\n", nr, bufor);
}
pthread_mutex_unlock(&blokada);
}
}
void *konsument (void *i)
{
int kons=0;
int nr=((int) i) + 1;
while(1)
{
if (produkcja==800 && bufor==0)
{
printf("Konsument %d skonsumowal %d produktow.\\n",nr,kons);
return 0;
}
pthread_mutex_lock(&blokada);
if (bufor>0)
{
printf("Konument %d komnsumuje produkt nr %d.\\n",nr,bufor);
bufor--;
kons++;
}
pthread_mutex_unlock(&blokada);
}
}
int main()
{
int i;
bufor=0;
produkcja=0;
pthread_mutex_init(&blokada,0);
for(i=0;i<8;i++)
pthread_create(&prod[i], 0, producent, (void*) i);
for(i=0;i<8;i++)
pthread_create(&kons[i], 0, konsument, (void*) i);
for(i=0;i<8;i++)
pthread_join(prod[i],0);
for(i=0;i<8;i++)
pthread_join(kons[i],0);
}
| 0
|
#include <pthread.h>
void *method_thread_1(void *);
void *method_thread_2(void *);
void *method_thread_3(void *);
pthread_t thread_3;
void sig_handler(int sig);
int isStopNow = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cv;
pthread_t thread_1, thread_2;
int
main(){
sigset_t set, old_set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
pthread_sigmask(SIG_BLOCK, &set, 0);
printf("main: going to create threads\\n");
pthread_create(&thread_1, 0, (void *)method_thread_1, &old_set);
pthread_create(&thread_2, 0, (void *)method_thread_2, &old_set);
pthread_create(&thread_3, 0, (void *)method_thread_3, &old_set);
pthread_sigmask(SIG_UNBLOCK, &set, 0);
struct sigaction act;
memset(&act, '\\0', sizeof(act));
act.sa_sigaction = (void *)sig_handler;
sigaction(SIGINT,&act, 0);
pthread_join(thread_1, 0);
pthread_join(thread_2, 0);
pthread_join(thread_3, 0);
return 0;
}
void sig_handler(int sig){
printf("I just received the signal\\n");
pthread_mutex_lock(&m);
isStopNow = 1;
pthread_mutex_unlock(&m);
}
void *method_thread_1(void *arg){
for(;;){
pthread_mutex_lock(&m);
if(isStopNow == 1){
printf("thread1: I am terminating myself..\\n");
pthread_mutex_unlock(&m);
pthread_cancel(thread_3);
printf("thread1: unlocked the mutex, sent a cancellation request to thread_3\\n");
pthread_exit(0);
}
pthread_mutex_unlock(&m);
printf("thrad1: I just woke up\\n");
pthread_mutex_lock(&m);
if(isStopNow == 1){
printf("thread1: I am terminating myself..\\n");
pthread_mutex_lock(&m);
pthread_cancel(thread_3);
printf("thread1: unlocked the mutex, sent a cancellation request to thread_3\\n");
pthread_exit(0);
}
pthread_mutex_unlock(&m);
}
}
void *method_thread_2(void *arg){
for(;;){
pthread_mutex_lock(&m);
if(isStopNow == 1){
printf("thread2:I am going to be terminated now\\n");
pthread_mutex_unlock(&m);
printf("thread2:unlocked the mutex..about to die\\n");
pthread_exit(0);
}
pthread_mutex_unlock(&m);
printf("thrad2: I jst work up\\n");
pthread_mutex_lock(&m);
if(isStopNow == 1){
printf("thread2:I am going to be terminated now\\n");
pthread_mutex_unlock(&m);
printf("thread2:unlocked the mutex..about to die\\n");
pthread_exit(0);
}
pthread_mutex_unlock(&m);
}
}
void *clean(int *i){
printf("clean: i=%d\\n",*i);
pthread_mutex_unlock(&m);
}
void *method_thread_3(void *arg){
int i=1;
int localStop = 0;
for(;;){
pthread_mutex_lock(&m);
pthread_cleanup_push((void *)clean,(void *)&i);
while(1){
pthread_cond_wait(&cv, &m);
}
pthread_cleanup_pop(1);
pthread_mutex_lock(&m);
if(isStopNow == 1){
localStop = 1;
}
pthread_mutex_unlock(&m);
printf("thrad3: I jst work up\\n");
if(localStop == 1){
pthread_mutex_unlock(&m);
printf("thread3:I am going to be terminated now\\n");
pthread_exit(0);
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t finished_mutex = PTHREAD_MUTEX_INITIALIZER;
{
int thread;
int nr;
} msg_t;
msg_t finished = {-1, -1};
void *func(void *arg)
{
int thread_number = *((int *)arg),
limit = 20,
current = 3,
a = 1,
b = 1,
c = a + b;
while (current < limit)
{
if (finished.thread != -1)
{
printf("Thread %d lost\\n", thread_number);
free(arg);
return 0;
}
a = b;
b = c;
c = a + b;
current++;
}
pthread_mutex_lock(&finished_mutex);
finished.thread = thread_number;
finished.nr = c;
printf("Thread %d finished and the 100'th fibonacii nr is %d\\n", thread_number, c);
pthread_mutex_unlock(&finished_mutex);
free(arg);
return 0;
}
int main(int argc, char *argv[])
{
int i, n;
printf("N = "); scanf("%d", &n);
pthread_t *array_threads = malloc(sizeof(pthread_t) * n);
for (i = 0; i < n; i++)
{
int *temp_i = malloc(sizeof(int));
*temp_i = i;
pthread_create (&array_threads[i], 0, func, temp_i);
}
for (i = 0; i < n; i++)
{
pthread_join(array_threads[i] , 0) ;
}
free(array_threads);
return 0;
}
| 0
|
#include <pthread.h>
long long n = 100000;
int flag;
double sum;
int num_of_threads;
pthread_mutex_t mutex;
void* thread_sum(void* rank);
int main(int argc,char* argv[])
{
num_of_threads = strtol(argv[1],0,10);
pthread_t* threads = (pthread_t*) malloc(sizeof(pthread_t)*num_of_threads);
pthread_mutex_init(&mutex, 0);
sum = 0.0;
int i;
for(i=0;i<num_of_threads;i++)
{
pthread_create(&threads[i],0,thread_sum,(void*)i);
}
for(i=0;i<num_of_threads;i++)
{
pthread_join(threads[i],0);
}
sum = 4*sum;
printf("Pi: %f\\n",sum);
pthread_mutex_destroy(&mutex);
free(threads);
return 0;
}
void* thread_sum(void* rank) {
long my_rank = (long) rank;
double factor;
long long i;
long long my_n = n/num_of_threads;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
double my_sum = 0.0;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
my_sum += factor/(2*i+1);
}
pthread_mutex_lock(&mutex);
sum += my_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
sem_t empty,full;
pthread_mutex_t mutex;
struct prodcons
{
int buf[5];
int tid[5];
char *time[5];
int readpos, writepos;
};
struct prodcons buffer;
void init(struct prodcons *b)
{
b->readpos = 0;
b->writepos = 0;
}
int producer_id=0,consumer_id=0;
void *Producer()
{
int n=0;
time_t timep;
time(&timep);
char *tem;
int nn=30;
while(nn--)
{
sleep(3);
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer.buf[buffer.writepos] = n;
buffer.tid[buffer.writepos] = syscall(SYS_gettid);
tem = asctime(gmtime(&timep));
buffer.time[buffer.writepos] = tem;
printf("data:%d ,tid: %ld ,time_in: %s --->\\n", n,syscall(SYS_gettid),tem);
buffer.writepos++;
if (buffer.writepos >= 5)
buffer.writepos = 0;
pthread_mutex_unlock(&mutex);
sem_post(&full);
n++;
}
}
void *Consumer()
{
int d;
int gettid;
char *tt;
while(1)
{
sleep(3);
sem_wait(&full);
pthread_mutex_lock(&mutex);
d = buffer.buf[buffer.readpos];
gettid = buffer.tid[buffer.readpos];
tt = buffer.time[buffer.readpos];
buffer.readpos++;
if (buffer.readpos >= 5)
buffer.readpos = 0;
printf("--->data:%d ,tid: %d ,time_in: %s \\n", d,gettid,tt);
if (d == ( - 1))
break;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int main()
{
init(&buffer);
int rthread[18],i;
pthread_t producer[15];
pthread_t consumer[10];
int sinit1=sem_init(&empty,0,5);
int sinit2=sem_init(&full,0,0);
int minit =pthread_mutex_init(&mutex,0);
if(sinit1 && sinit2)
{
printf("sem initialize failed /n");
exit(1);
}
if(minit)
{
printf("sem initialize failed /n");
exit(1);
}
for(i=0;i<15;i++)
{
rthread[i]=pthread_create(&producer[i], 0, Producer, 0);
if(rthread[i])
{
printf("producer %d create failed /n", i);
exit(1);
}
}
for(i=0;i<10;i++)
{
rthread[i]=pthread_create(&consumer[i], 0, Consumer,0);
if(rthread[i])
{
printf("consumer %d create failed /n", i);
exit(1);
}
}
for(i=0;i<15;i++)
{
pthread_join(producer[i],0);
}
for(i=0;i<10;i++)
{
pthread_join(consumer[i],0);
}
exit(0);
}
| 0
|
#include <pthread.h>
struct buffer
{
int array[10];
unsigned int front;
unsigned int rear;
pthread_mutex_t m;
}queue;
pthread_cond_t queue_full = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_empty = PTHREAD_COND_INITIALIZER;
void *puta(void*arg)
{
int i=2000;
static int j=10;
srand(1092);
int value =0;
while (1)
{
i=200;
pthread_mutex_lock(&queue.m);
while (((queue.rear+1)%10 )== (queue.front%10))
{
printf("\\n %s 0x%x producer thread rear %d front %d waititng for queue to be empty",__func__,pthread_self(),(queue.rear)%10, queue.front%10);
sched_yield();
}
value =rand()%20;
printf("\\n %s 0x%x going to insert at %d value %d",__func__,pthread_self(),(queue.rear+1)%10, value);
sleep(1);
queue.array[(++queue.rear)%10]=value;
pthread_mutex_unlock(&queue.m);
sched_yield();
}
return 0;
}
void *eata(void*arg)
{
int value=0;
while (1)
{
pthread_mutex_lock(&queue.m);
printf("\\n %s 0x%x consumer thread going to the evaluate the condition ",__func__,pthread_self());
while (((queue.rear)%10 ) == (queue.front%10))
{
printf("\\n %s 0x%x consumer thread rear %d front %d waiting for producer to fill the buffer",__func__,pthread_self(),(queue.rear)%10, queue.front%10);
}
value = queue.array[(++queue.front)%10];
printf("\\n %s 0x%x going to print at %d value %d",__func__,pthread_self(),(queue.front%10), value);
sleep(1);
pthread_mutex_unlock(&queue.m);
sched_yield();
}
return 0;
}
func_type_t func_arr[]={puta,eata,puta,eata};
int main()
{
pthread_t tid[4];
int ret=0;
int i=0;
pthread_mutex_init(&queue.m,0);
queue.rear=10 -1;
queue.front=10 -1;
for(i=0;i<4;i++)
if( ret=pthread_create(&tid[i],0,func_arr[i],0))
{
return -1;
}
for(i=0;i<2;i++)
pthread_join(tid[i],0);
return 0;
}
| 1
|
#include <pthread.h>
struct s {
int datum;
struct s *next;
} *A, *B;
void init (struct s *p, int x) {
p -> datum = x;
p -> next = 0;
}
pthread_mutex_t A_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B_mutex = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&A_mutex);
A->next->datum++;
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&B_mutex);
B->next->datum++;
pthread_mutex_unlock(&B_mutex);
return 0;
}
int main () {
pthread_t t1;
struct s *p = malloc(sizeof(struct s));
init(p,9);
A = malloc(sizeof(struct s));
init(A,3);
A->next = p;
B = malloc(sizeof(struct s));
init(B,5);
p = malloc(sizeof(struct s));
init(p,9);
B->next = p;
pthread_create(&t1, 0, t_fun, 0);
pthread_mutex_lock(&A_mutex);
p = A->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&B_mutex);
p = B->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&B_mutex);
return 0;
}
| 0
|
#include <pthread.h>
void instruction_register(void *not_used){
pthread_barrier_wait(&threads_creation);
while(1){
pthread_mutex_lock(&control_sign);
if(!cs.isUpdated){
while(pthread_cond_wait(&control_sign_wait,&control_sign) != 0);
}
pthread_mutex_unlock(&control_sign);
if(cs.invalidInstruction){
pthread_barrier_wait(&update_registers);
pthread_exit(0);
}
pthread_barrier_wait(¤t_cycle);
if((( (separa_IRWrite & cs.value) >> IRWrite_POS) & 0x01) == 1){
ir = mem_data;
}
pthread_barrier_wait(&update_registers);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t* mutex_pth;
void* threadProcess(void *arg){
int* alea_test ;
*alea_test = (int) (10*((double)rand())/ 32767);
int* arg_test = (int*) arg;
pthread_t thread_tmp= pthread_self();
pthread_mutex_lock(mutex_pth);
*arg_test += *alea_test;
printf("%d | %d | %d\\n",*arg_test,*alea_test,(int)thread_tmp);
pthread_mutex_unlock(mutex_pth);
pthread_exit(arg);
return 0;
}
int main(int argc, char** args){
if(argc!=2){
perror("erreur de saisie des arguments\\n");
return -1;
}
mutex_pth=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_init(mutex_pth,0);
int* retour;
retour = 0;
int N = atoi(args[1]);
int *ret[N];
pthread_t tab_id[N];
for(int i=0;i<N;i++){
if(pthread_create(&tab_id[i],0,threadProcess,&retour)<0){
perror("erreur de creation de thread \\n ");
return -1;
}
printf("%d\\n",i);
}
for(int j=0;j<N;j++){
pthread_join(tab_id[j],&ret[j]);
printf("%d\\n",*ret[j]);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock;
static void *threadfunc(void *arg)
{
pthread_mutex_lock(&lock);
printf("locked and thread over\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int retcode = 0;
pthread_t thid;
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST);
pthread_mutex_init(&lock, &attr);
pthread_create(&thid, 0, threadfunc, 0);
pthread_join(thid, 0);
if ((retcode = pthread_mutex_lock(&lock)) == EOWNERDEAD)
{
pthread_mutex_consistent(&lock);
pthread_mutex_unlock(&lock);
}
printf("retcode = %d\\n", retcode);
printf("EOWNERDEAD = %d\\n", EOWNERDEAD);
if ((retcode = pthread_mutex_lock(&lock)) == EOWNERDEAD)
{
fprintf(stderr, "pthread_mutex_consistent failure\\n");
return 1;
}
printf("pthread_mutex_consistent success\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct mon_time_entry {
void *(*callback)(void *);
void *args;
int flags;
time_t time;
int iter;
int delay;
struct mon_time_entry *next;
struct mon_time_entry *prev;
};
static void *mon_time_run(void *args);
static void mon_time_dump(void);
static pthread_t t;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static struct mon_time_entry *list = 0;
static int running = 0;
static void *mon_time_run(void *args)
{
struct mon_time_entry *p, *e;
time_t now;
pthread_t ct;
while(1) {
pthread_mutex_lock(&m);
if(!list) {
running = 0;
pthread_mutex_unlock(&m);
return 0;
}
now = time(0);
p = list;
while(p) {
if(p->time <= now) {
pthread_create(&ct, 0, p->callback, p->args);
pthread_detach(ct);
if((p->flags & MON_FLAG_PERM) && (!p->iter || (p->iter-- > 1))) {
p->time = now + p->delay;
p = p->next;
} else {
if(p == list) list = p->next;
if(p->next) p->next->prev = p->prev;
if(p->prev) p->prev->next = p->next;
e = p;
p = p->next;
free(e);
}
} else {
p = p->next;
}
}
mon_time_dump();
pthread_mutex_unlock(&m);
sleep(1);
}
}
void mon_time_start(void *args) {
pthread_mutex_lock(&m);
if(!running) if(!pthread_create(&t, 0, mon_time_run, 0)) running = 1;
pthread_mutex_unlock(&m);
}
void *mon_time_addwatch(void *(*callback)(void *), void *args, int flags, ...)
{
struct mon_time_entry *p = 0;
va_list va;
pthread_mutex_lock(&m);
do {
if(!list) {
if(!(list = malloc(sizeof(struct mon_time_entry)))) break;
list->prev = 0;
p = list;
} else {
for(p = list; p->next; p = p->next);
if(!(p->next = malloc(sizeof(struct mon_time_entry)))) break;
p->next->prev = p;
p = p->next;
}
p->next = 0;
p->callback = callback;
p->args = args;
p->flags = flags;
__builtin_va_start((va));
p->time = __builtin_va_arg((va));
if((p->delay = __builtin_va_arg((va))) < 1) p->delay = 1;
if((p->iter = __builtin_va_arg((va))) < 0) p->iter = 0;
;
if(!running) if(!pthread_create(&t, 0, mon_time_run, 0)) running = 1;
} while(0);
mon_time_dump();
pthread_mutex_unlock(&m);
return p;
}
void mon_time_delwatch(void *entry)
{
struct mon_time_entry *p = 0, *e = (struct mon_time_entry *)entry;
if(!list || !e) return;
pthread_mutex_lock(&m);
for(p = list; p && (p != e); p = p->next);
if(p) {
if(p == list) list = p->next;
if(p->next) p->next->prev = p->prev;
if(p->prev) p->prev->next = p->next;
free(p);
}
pthread_mutex_unlock(&m);
return;
}
void mon_time_dump(void)
{
return;
}
| 0
|
#include <pthread.h>
int stoj = 0;
pthread_mutex_t stoj_mutex = PTHREAD_MUTEX_INITIALIZER;
int krabice = 0;
sem_t krabice_sem;
int prenesene = 0;
pthread_mutex_t prenesene_mutex = PTHREAD_MUTEX_INITIALIZER;
int ulozene = 0;
pthread_mutex_t ulozene_mutex = PTHREAD_MUTEX_INITIALIZER;
int skladnici = 0;
pthread_mutex_t skladnici_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t skladnici_sem;
void prines(void) {
usleep(1);
sem_wait(&skladnici_sem);
krabice++;
sem_post(&krabice_sem);
sem_post(&skladnici_sem);
pthread_mutex_lock(&prenesene_mutex);
prenesene++;
pthread_mutex_unlock(&prenesene_mutex);
}
void uloz(void) {
sem_wait(&krabice_sem);
pthread_mutex_lock(&skladnici_mutex);
if (skladnici == 0)
sem_wait(&skladnici_sem);
skladnici++;
pthread_mutex_unlock(&skladnici_mutex);
pthread_mutex_lock(&ulozene_mutex);
krabice--;
ulozene++;
pthread_mutex_unlock(&ulozene_mutex);
usleep(1);
pthread_mutex_lock(&skladnici_mutex);
skladnici--;
if (skladnici == 0)
sem_post(&skladnici_sem);
pthread_mutex_unlock(&skladnici_mutex);
}
void *skladnik( void *ptr ) {
while(1) {
pthread_mutex_lock(&stoj_mutex);
if (stoj)
{
pthread_mutex_unlock(&stoj_mutex);
return 0;
}
pthread_mutex_unlock(&stoj_mutex);
uloz();
}
return 0;
}
void *brigadnik( void *ptr ) {
while(1) {
pthread_mutex_lock(&stoj_mutex);
if (stoj)
{
pthread_mutex_unlock(&stoj_mutex);
return 0;
}
pthread_mutex_unlock(&stoj_mutex);
prines();
}
return 0;
}
int main(void) {
int i;
sem_init(&krabice_sem, 0, 0);
sem_init(&skladnici_sem, 0, 1);
pthread_t skladnici[2];
pthread_t brigadnici[10];
for (i=0;i<2;i++) pthread_create( &skladnici[i], 0, &skladnik, 0);
for (i=0;i<10;i++) pthread_create( &brigadnici[i], 0, &brigadnik, 0);
usleep(30);
stoj = 1;
for (i=0;i<2;i++) pthread_join( skladnici[i], 0);
for (i=0;i<10;i++) pthread_join( brigadnici[i], 0);
printf("Prenesene: %d\\n", prenesene);
printf("Ulozene: %d\\n", ulozene);
exit(0);
}
| 1
|
#include <pthread.h>
{
int value;
struct cell *next;
}
*cell;
{
int length;
cell first;
cell last;
}
*list;
list add (int v, list l)
{
cell c = (cell) malloc (sizeof (struct cell));
c->value = v;
c->next = 0;
if (l == 0){
l = (list) malloc (sizeof (struct list));
l->length = 0;
l->first = c;
}else{
l->last->next = c;
}
l->length++;
l->last = c;
return l;
}
void put (int v,list *l)
{
(*l) = add (v,*l);
}
int get (list *l)
{
int res;
list file = *l;
if (l == 0) {
fprintf (stderr, "get error!\\n");
return 0;
}
res = file->first->value;
file->length--;
if (file->last == file->first){
file = 0;
}else{
file->first = file->first->next;
}
return res;
}
int size (list l)
{
if (l==0) return 0;
return l->length;
}
list file = 0;
pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t new_elem = PTHREAD_COND_INITIALIZER;
int processed = 0;
void process_value (int v)
{
int i,j;
for (i=0;i<PROCESSING;i++) j++;
pthread_mutex_lock(&file_mutex);
put(v+1,&file);
pthread_cond_signal (&new_elem);
pthread_mutex_unlock(&file_mutex);
}
void* process (void *args)
{
pthread_mutex_lock(&file_mutex);
while (1) {
if (size(file) > 0){
int res = get (&file);
pthread_mutex_unlock(&file_mutex);
if (res == CYCLES){
PRINT("result: %d\\n",res);
processed++;
if (processed == PRODUCED) exit (0);
}else{
process_value(res);
}
pthread_mutex_lock(&file_mutex);
}else{
pthread_cond_wait (&new_elem,&file_mutex);
}
}
return 0;
}
void* produce (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock (&file_mutex);
if (size(file) < FILE_SIZE){
put (0,&file);
PRINT("%d produced\\n",0);
pthread_cond_signal (&new_elem);
v++;
pthread_mutex_unlock (&file_mutex);
}else{
pthread_mutex_unlock(&file_mutex);
sched_yield();
}
}
return 0;
}
int main(void)
{
int i;
pthread_t producer;
pthread_t thread_array[MAX_THREADS];
for (i=0; i<MAX_THREADS; i++){
pthread_create (&thread_array[i],0,process,0);
}
pthread_create (&producer,0,produce,0);
pthread_exit (0);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static void *func(void *arg)
{
struct timespec spec = {0};
clock_gettime(CLOCK_REALTIME, &spec);
spec.tv_sec += 10;
sleep (1);
pthread_mutex_timedlock(&lock, &spec);
printf("slave thread\\n");
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_create(&tid, 0, func, 0);
pthread_mutex_lock(&lock);
printf("master thread\\n");
sleep(10);
printf("ETIMEDOUT = %d\\n", ETIMEDOUT);
printf("time of day\\n");
pthread_mutex_unlock(&lock);
sleep(2);
printf("master over\\n");
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
static FILE *log;
static pthread_mutex_t log_mutex = PTHREAD_MUTEX_INITIALIZER;
void log_init(void)
{
log = fopen(joinfs_context.logpath, "w+");
if(!log) {
printf("---ERROR---Open log file failed, path:%s\\n", joinfs_context.logpath);
exit(1);
}
}
void log_destroy(void)
{
fclose(log);
}
void log_error(const char * format, ...)
{
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(&log_mutex);
fprintf(log, "---ERROR---");
vfprintf(log, format, args);
pthread_mutex_unlock(&log_mutex);
;
}
void log_msg(const char * format, ...)
{
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(&log_mutex);
fprintf(log, "----MSG----");
vfprintf(log, format, args);
pthread_mutex_unlock(&log_mutex);
;
}
| 0
|
#include <pthread.h>
int duree_sommeil;
int do_wakeup;
pthread_cond_t cond;
} simu_proc_t;
static simu_proc_t *simu_procs;
static pthread_mutex_t simu_mutex;
static int simu_nbprocs;
static int current_timespeed = 1;
static int system_ticks = 1;
static int running = 1;
void simu_sleep (int noproc, int duree)
{
pthread_mutex_lock (&simu_mutex);
simu_procs[noproc].duree_sommeil = duree;
simu_procs[noproc].do_wakeup = 0;
while (! simu_procs[noproc].do_wakeup) {
pthread_cond_wait (&(simu_procs[noproc].cond), &simu_mutex);
}
pthread_mutex_unlock (&simu_mutex);
}
static void simu_wakeup_internal (int noproc)
{
simu_procs[noproc].do_wakeup = 1;
pthread_cond_signal (&(simu_procs[noproc].cond));
}
void simu_wakeup (int noproc)
{
pthread_mutex_lock (&simu_mutex);
simu_wakeup_internal (noproc);
pthread_mutex_unlock (&simu_mutex);
}
void ticker(int unused)
{
pthread_mutex_lock(&simu_mutex);
if (running) {
if (system_ticks==0) {
int i;
for (i=0; i<simu_nbprocs; i++) {
if (simu_procs[i].duree_sommeil==0) {
simu_wakeup_internal(i);
}
simu_procs[i].duree_sommeil--;
}
system_ticks = 1000/current_timespeed;
}
else {
system_ticks --;
}
}
pthread_mutex_unlock(&simu_mutex);
signal(SIGALRM, ticker);
alarm(1);
}
void simu_init (int nbprocs)
{
int i;
pthread_mutex_init (&simu_mutex, 0);
simu_nbprocs = nbprocs;
simu_set_timespeed (500);
simu_procs = malloc (nbprocs * sizeof (simu_proc_t));
for (i = 0; i < nbprocs; i++) {
pthread_cond_init (&(simu_procs[i].cond), 0);
simu_procs[i].duree_sommeil = -1;
}
signal(SIGALRM, ticker);
alarm(1);
}
int simu_get_running (void)
{
int res;
pthread_mutex_lock (&simu_mutex);
res = running;
pthread_mutex_unlock (&simu_mutex);
return res;
}
void simu_set_running (int _running)
{
pthread_mutex_lock (&simu_mutex);
running = _running;
pthread_mutex_unlock (&simu_mutex);
}
void simu_swap_running (void)
{
pthread_mutex_lock (&simu_mutex);
running = !running;
pthread_mutex_unlock (&simu_mutex);
}
void simu_set_timespeed (int _timespeed)
{
pthread_mutex_lock (&simu_mutex);
current_timespeed = _timespeed;
system_ticks = 1000 / current_timespeed;
pthread_mutex_unlock (&simu_mutex);
}
int simu_get_timespeed (void)
{
int res;
pthread_mutex_lock (&simu_mutex);
res = current_timespeed;
pthread_mutex_unlock (&simu_mutex);
return res;
}
static int previous_running;
void simu_suspend_time (void)
{
pthread_mutex_lock (&simu_mutex);
previous_running = running;
running = 0;
pthread_mutex_unlock (&simu_mutex);
}
void simu_resume_time (void)
{
pthread_mutex_lock (&simu_mutex);
running = previous_running;
pthread_mutex_unlock (&simu_mutex);
}
| 1
|
#include <pthread.h>
double *in_circle;
pthread_mutex_t *in_circle_lock;
int threadID;
long long num_tosses;
}thread_data;
void *toss_thread(void *threadD);
int main(int argc, char const *argv[])
{
int i;
double in_circle = 0;
long long number_of_tosses;
if (argc == 2) {
number_of_tosses = atoi(argv[1]);
}
else {
number_of_tosses = 100000001;
}
int NUM_OF_THREADS = get_nprocs();
long long tosses_of_thread = number_of_tosses / NUM_OF_THREADS;
long long tosses_of_remain = number_of_tosses % NUM_OF_THREADS;
pthread_t* threads;
thread_data* threadD;
pthread_mutex_t in_circle_lock;
threads = (pthread_t*)malloc(sizeof(pthread_t)* NUM_OF_THREADS);
threadD = (thread_data*)malloc(sizeof(thread_data)* NUM_OF_THREADS);
pthread_mutex_init(&in_circle_lock, 0);
for (i = 0; i < NUM_OF_THREADS; i++) {
threadD[i].in_circle = &in_circle;
threadD[i].in_circle_lock = &in_circle_lock;
threadD[i].threadID = i;
if (i == 0) threadD[i].num_tosses = tosses_of_thread + tosses_of_remain;
else threadD[i].num_tosses = tosses_of_thread;
pthread_create(&threads[i], 0, toss_thread, (void*)&threadD[i]);
}
for (i = 0; i < NUM_OF_THREADS; i++) {
pthread_join(threads[i], 0);
}
double pi_estimate = 4 * in_circle / (double)number_of_tosses;
printf("%.15lf\\n", pi_estimate);
return 0;
}
void *toss_thread(void *threadD)
{
long long toss;
double x, y;
double distance_square;
long long local_in_circle = 0;
unsigned seed = (unsigned)time(0);
thread_data* tData = (thread_data*)threadD;
for (toss = 0; toss < tData->num_tosses; toss++) {
x = 2 * (rand_r(&seed) / (double)32767) - 1;
y = 2 * (rand_r(&seed) / (double)32767) - 1;
distance_square = x*x + y*y;
if (distance_square <= 1.0) {
local_in_circle++;
}
}
pthread_mutex_lock(tData->in_circle_lock);
*(tData->in_circle) += local_in_circle;
pthread_mutex_unlock(tData->in_circle_lock);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct arg{
int numThreads;
int port;
char * ip;
int index;
FILE *fp;
};
pthread_mutex_t lock;
void *run(void * arg){
int con_fd = 0;
int ret = 0;
struct sockaddr_in serv_addr;
struct arg * pt = (struct arg *)arg;
int numThreads = pt->numThreads;
int port = pt->port;
char * ip = pt->ip;
int index = pt->index;
FILE *fp = pt->fp;
printf("%d\\n", index);
int loc = index;
int bytesReceived = 1;
char recvBuff[1024];
char sendIn[5];
while(bytesReceived!=0){
con_fd = socket(PF_INET, SOCK_STREAM, 0);
if (con_fd == -1) {
perror("Socket Error\\n");
return 0;
}
memset(&serv_addr, 0, sizeof(struct sockaddr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr(ip);;
ret = connect(con_fd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr));
if (ret < 0) {
perror("Connect error\\n");
return 0;
}
memset(recvBuff, '0', sizeof(recvBuff));
pthread_mutex_lock(&lock);
snprintf(sendIn, 128, "%d", loc);
send(con_fd, sendIn, strlen(sendIn), 0);
bytesReceived = recv(con_fd, recvBuff, 1024, 0);
if(bytesReceived !=0){
fseek(fp, loc * 1024, 0);
fwrite(recvBuff, 1,bytesReceived,fp);
}
loc = loc + numThreads;
pthread_mutex_unlock(&lock);
close(con_fd);
}
return 0;
}
int main(int argc, char ** argv) {
int numThreads = (argc - 1)/2;
FILE *fp;
fp = fopen("output.txt", "a");
if(0 == fp)
{
printf("Error opening file");
return 0;
}
pthread_t threads[numThreads];
int cnt = 0;
int argScn = 1;
printf("numthreads: %d\\n", numThreads);
for(int i = 0; i<numThreads; i++){
struct arg *temp;
temp = malloc(sizeof(struct arg));
temp->numThreads = numThreads;
temp->ip = argv[argScn];
argScn++;
temp->port = atoi(argv[argScn]);
argScn++;
printf("sending port %d\\n", temp->port);
temp->index = cnt;
cnt++;
temp->fp = fp;
printf("creating thread %d\\n", i);
pthread_create(&threads[i], 0, run, temp);
printf("thread created %d\\n", i);
}
for(int i = 0; i< numThreads; i++){
pthread_join(threads[i], 0);
}
}
| 1
|
#include <pthread.h>
float var_promedio=0;
int var_minimo=0;
int var_maximo=0;
int longitud=0;
pthread_mutex_t bloqueo;
void *minimo(void *array)
{
int *ptr = (int*)array;
int cont=0;
pthread_mutex_lock(&bloqueo);
var_minimo=ptr[0];
while(cont<longitud){
if (var_minimo>ptr[cont]){
var_minimo=ptr[cont];
}
cont++;
}
pthread_mutex_unlock(&bloqueo);
pthread_exit(0);
}
void *maximo(void *array)
{
int *ptr = (int*)array;
int cont=0;
pthread_mutex_lock(&bloqueo);
while(cont<longitud){
if (var_maximo<ptr[cont]){
var_maximo=ptr[cont];
}
cont++;
}
pthread_mutex_unlock(&bloqueo);
pthread_exit(0);
}
void *promedio(void *array)
{
int *ptr = (int*)array;
int cont=0;
pthread_mutex_lock(&bloqueo);
while(cont<longitud){
var_promedio=var_promedio+ptr[cont];
cont++;
}
pthread_mutex_unlock(&bloqueo);
var_promedio=var_promedio/cont;
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int cont,tmp,t;
pthread_t threads[3];
pthread_mutex_init(&bloqueo,0);
printf("Ingrese la cantidad de numeros");
scanf("%d",&longitud);
int array[longitud];
for (cont=0;cont<longitud;cont++){
printf("Ingrese un numero: ");
scanf("%d",&tmp);
array[cont]=tmp;
}
pthread_create(&threads[0], 0, minimo, (void *)&array);
pthread_create(&threads[1], 0, maximo, (void *)&array);
pthread_create(&threads[2], 0, promedio, (void *)&array);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
pthread_join(threads[2], 0);
printf("\\n");
printf("The average value is %f\\n",var_promedio );
printf("The minimum value is %d\\n",var_minimo );
printf("The maximum value is %d\\n",var_maximo );
pthread_mutex_destroy(&bloqueo);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int source[30];
int minBound[3];
int maxBound[3];
int channel[3];
int th_id = 0;
pthread_mutex_t mid;
pthread_mutex_t ms[3];
void sort (int x, int y)
{
int aux = 0;
for (int i = x; i < y; i++)
{
for (int j = i; j < y; j++)
{
if (source[i] > source[j])
{
aux = source[i];
source[i] = source[j];
source[j] = aux;
}
}
}
}
void *sort_thread (void * arg)
{
int id = -1;
int x, y;
pthread_mutex_lock (&mid);
id = th_id;
th_id++;
pthread_mutex_unlock (&mid);
x = minBound[id];
y = maxBound[id];
__VERIFIER_assert (x >= 0);
__VERIFIER_assert (x < 30);
__VERIFIER_assert (y >= 0);
__VERIFIER_assert (y < 30);
printf ("t%d: min %d max %d\\n", id, x, y);
sort (x, y);
pthread_mutex_lock (&ms[id]);
channel[id] = 1;
pthread_mutex_unlock (&ms[id]);
return 0;
}
int main ()
{
pthread_t t[3];
int i;
__libc_init_poet ();
i = __VERIFIER_nondet_int (0, 30 - 1);
source[i] = __VERIFIER_nondet_int (0, 20);
__VERIFIER_assert (source[i] >= 0);
pthread_mutex_init (&mid, 0);
int j = 0;
int delta = 30/3;
__VERIFIER_assert (delta >= 1);
i = 0;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
__VERIFIER_assert (i == 3);
int k = 0;
while (k < 3)
{
i = 0;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
__VERIFIER_assert (i == 3);
}
__VERIFIER_assert (th_id == 3);
__VERIFIER_assert (k == 3);
sort (0, 30);
printf ("==============\\n");
for (i = 0; i < 30; i++)
printf ("m: sorted[%d] = %d\\n", i, source[i]);
i = 0;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
__VERIFIER_assert (i == 3);
return 0;
}
| 1
|
#include <pthread.h>
int numtasks;
int npoints;
int times;
int debug=0;
pthread_mutex_t* mutex;
pthread_cond_t* cond;
pthread_t thread_id;
int thread_num;
int thread_step;
int thread_first;
} ThreadData;
int **states;
double *values, *oldval, *newval;
int** create_array( int X, int Y ){
int **array,i;
array = (int**) malloc( X * sizeof(int*) );
for(i=0; i< X; i++)
array[i] = (int*) malloc( Y* sizeof(int) );
return array;
}
void update(int id, int first, int step){
int j;
double dtime = 0.3;
double c = 1.0;
double dx = 1.0;
double tau = (c * dtime / dx);
double sqtau = tau * tau;
for (int i = 0; i < times; i++){
for (j = first-1; j <= (first-1+step); j++){
if(j==(first-2+step)){
pthread_mutex_lock(&mutex[id]);
states[id][i]=1;
pthread_mutex_unlock(&mutex[id]);
pthread_cond_signal(&cond[id]);
}
if(j==(first-1) && j!=0){
while(states[id-1][i]==0){
pthread_cond_wait(&cond[id-1], &mutex[id-1]);
states[id-1][i]=1;
}
}
}
if(j==0){
newval[j] = (2.0 * values[j]) - oldval[j]
+ (sqtau * (values[j] - (2.0 * values[j]) + values[j+1]));
}
else if(j==npoints-1){
newval[j] = (2.0 * values[j]) - oldval[j]
+ (sqtau * (values[j-1] - (2.0 * values[j]) + values[j]));
}
else{
newval[j] = (2.0 * values[j]) - oldval[j]
+ (sqtau * (values[j-1] - (2.0 * values[j]) + values[j+1]));
}
}
}
void *thread_start(void *thread)
{
ThreadData *my_data = (ThreadData*)thread;
int id=my_data->thread_num;
int step=my_data->thread_step;
int first=my_data->thread_first;
int j;
double x, fac = 2.0 * 3.14159265;
for (j=first; j <= (first+step); j++){
x = (double)j/(double)(npoints - 1);
values[j] = sin (fac * x);
}
for (j=first; j <= (first+step); j++){
oldval[j] = values[j];
}
update(id,first,step);
if(debug)
printf("Termina el thread %d \\n", id);
return 0;
}
int main(int argc, char *argv[])
{
if( argc != 5){
printf("faltan args\\n");
exit(0);
}
else{
npoints = atoi(argv[1]);
numtasks = atoi(argv[2]);
times = atoi(argv[3]);
debug = atoi(argv[4]);
}
ThreadData thread[numtasks];
int i, first, npts;
int k=0;
int nmin = npoints/numtasks;
int nleft = npoints%numtasks;
mutex = (pthread_mutex_t*) malloc (numtasks*sizeof(pthread_mutex_t));
cond = (pthread_cond_t*) malloc (numtasks*sizeof(pthread_cond_t));
values = (double*) malloc (npoints*sizeof(double));
oldval = (double*) malloc (npoints*sizeof(double));
newval = (double*) malloc (npoints*sizeof(double));
int X = numtasks;
int Y = times;
states = create_array(X,Y);
for(int i=0; i< X; i++){
for(int j=0; j< Y; j++){
if(j==0){
states[i][j] = 1;
}
states[i][j] = 0;
}
}
for(i=0; i<numtasks; i++){
int iRC = pthread_mutex_init (&mutex[i], 0);
int iRCc = pthread_cond_init (&cond[i], 0);
if (iRC != 0 || iRCc !=0){
printf("Problema al iniciar mutex\\n");
return 0;
}
}
for(i=0; i<numtasks; i++){
npts = (i < nleft) ? nmin + 1 : nmin;
first = k + 1;
npoints = npts;
k += npts;
thread[i].thread_num=i;
thread[i].thread_step=npoints;
thread[i].thread_first=first;
pthread_create(&(thread[i].thread_id), 0, thread_start, (void *)(thread+i));
}
for (i = 0; i < numtasks; i++)
pthread_join(thread[i].thread_id, 0);
free(mutex);
free(cond);
for(int i=0; i< X; i++)
free(states[i]);
free(states);
free(values);
free(oldval);
free(newval);
return 0;
}
| 0
|
#include <pthread.h>
struct element{
void* value;
element *next;
};
struct queue{
llist in;
llist out;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_t id1, id2;
struct queue* queue_new(void){
struct queue* new_queue = 0;
new_queue = malloc(sizeof(struct queue));
new_queue->in = 0;
new_queue->out = 0;
return new_queue;
}
void queue_free(struct queue *queue){
llist temp;
while (queue->in != 0){
temp = queue->in->next;
free(queue->in);
queue->in = temp;
}
while (queue->out != 0){
temp = queue->out->next;
free(queue->out);
queue->out = temp;
}
free(queue);
}
void queue_push(struct queue *q, void *value){
element *new_element = malloc(sizeof(element));
pthread_mutex_lock(&mutex);
new_element->value = value;
new_element->next = q->in;
q->in = new_element;
pthread_mutex_unlock(&mutex);
}
void* queue_pop(struct queue *q){
void* ret;
llist temp;
pthread_mutex_lock(&mutex);
if (q->out == 0){
if (q->in == 0)
return 0;
while (q->in != 0){
temp = q->in;
q->in = q->in->next;
if (q->out == 0){
q->out = temp;
q->out->next = 0;
}
else{
temp->next = q->out;
q->out = temp;
}
}
q->in = 0;
}
ret = q->out->value;
temp = q->out->next;
free(q->out);
q->out = temp;
pthread_mutex_unlock(&mutex);
return ret;
}
void test_q1(void){
struct queue *q = 0;
int a = 2, b = 3, c = 1, d = 6;
q = queue_new();
queue_push(q, (void*)&a);
queue_push(q, (void*)&b);
queue_push(q, (void*)&c);
printf("%d\\n", (*(int*)queue_pop(q)));
printf("%d\\n", (*(int*)queue_pop(q)));
queue_push(q, (void*)&d);
printf("%d\\n", (*(int*)queue_pop(q)));
printf("%d\\n", (*(int*)queue_pop(q)));
queue_free(q);
}
void* thread1(void *arg){
int i;
struct queue *q = (struct queue*)arg;
for (i = 0; i < 10000; i++){
queue_push(q, (void*)i);
}
return 0;
}
void test_q2(void){
struct queue *q = 0;
int i;
q = queue_new();
pthread_create(&id1, 0, thread1, (void*)q);
usleep(100);
for (i = 0; i < 10000; i++){
printf("%d\\n", (int)queue_pop(q));
}
queue_free(q);
}
int main(void){
test_q1();
test_q2();
}
| 1
|
#include <pthread.h>
{
struct LinkTableNode * pNext;
}tLinkTableNode;
tLinkTableNode *pHead;
tLinkTableNode *pTail;
int SumOfNode;
pthread_mutex_t mutex;
}tLinkTable;
tLinkTable * CreateLinkTable()
{
tLinkTable * pLinkTable = (tLinkTable *)malloc(sizeof(tLinkTable));
if(pLinkTable == 0)
{
return 0;
}
pLinkTable->pHead = 0;
pLinkTable->pTail = 0;
pLinkTable->SumOfNode = 0;
pthread_mutex_init(&(pLinkTable->mutex), 0);
return pLinkTable;
}
int DeleteLinkTable(tLinkTable *pLinkTable)
{
if(pLinkTable == 0)
{
return FAILURE;
}
while(pLinkTable->pHead != 0)
{
tLinkTableNode * p = pLinkTable->pHead;
pthread_mutex_lock(&(pLinkTable->mutex));
pLinkTable->pHead = pLinkTable->pHead->pNext;
pLinkTable->SumOfNode -= 1 ;
pthread_mutex_unlock(&(pLinkTable->mutex));
free(p);
}
pLinkTable->pHead = 0;
pLinkTable->pTail = 0;
pLinkTable->SumOfNode = 0;
pthread_mutex_destroy(&(pLinkTable->mutex));
free(pLinkTable);
return SUCCESS;
}
int AddLinkTableNode(tLinkTable *pLinkTable,tLinkTableNode * pNode)
{
if(pLinkTable == 0 || pNode == 0)
{
return FAILURE;
}
pNode->pNext = 0;
pthread_mutex_lock(&(pLinkTable->mutex));
if(pLinkTable->pHead == 0)
{
pLinkTable->pHead = pNode;
}
if(pLinkTable->pTail == 0)
{
pLinkTable->pTail = pNode;
}
else
{
pLinkTable->pTail->pNext = pNode;
pLinkTable->pTail = pNode;
}
pLinkTable->SumOfNode += 1 ;
pthread_mutex_unlock(&(pLinkTable->mutex));
return SUCCESS;
}
int DelLinkTableNode(tLinkTable *pLinkTable,tLinkTableNode * pNode)
{
if(pLinkTable == 0 || pNode == 0)
{
return FAILURE;
}
pthread_mutex_lock(&(pLinkTable->mutex));
if(pLinkTable->pHead == pNode)
{
pLinkTable->pHead = pLinkTable->pHead->pNext;
pLinkTable->SumOfNode -= 1 ;
if(pLinkTable->SumOfNode == 0)
{
pLinkTable->pTail = 0;
}
pthread_mutex_unlock(&(pLinkTable->mutex));
return SUCCESS;
}
tLinkTableNode * pTempNode = pLinkTable->pHead;
while(pTempNode != 0)
{
if(pTempNode->pNext == pNode)
{
pTempNode->pNext = pTempNode->pNext->pNext;
pLinkTable->SumOfNode -= 1 ;
if(pLinkTable->SumOfNode == 0)
{
pLinkTable->pTail = 0;
}
pthread_mutex_unlock(&(pLinkTable->mutex));
return SUCCESS;
}
pTempNode = pTempNode->pNext;
}
pthread_mutex_unlock(&(pLinkTable->mutex));
return FAILURE;
}
tLinkTableNode * SearchLinkTableNode(tLinkTable *pLinkTable, int Conditon(tLinkTableNode * pNode, void * args), void * args)
{
if(pLinkTable == 0 || Conditon == 0)
{
return 0;
}
tLinkTableNode * pNode = pLinkTable->pHead;
while(pNode != 0)
{
if(Conditon(pNode, args) == SUCCESS)
{
return pNode;
}
pNode = pNode->pNext;
}
return 0;
}
tLinkTableNode * GetLinkTableHead(tLinkTable *pLinkTable)
{
if(pLinkTable == 0)
{
return 0;
}
return pLinkTable->pHead;
}
tLinkTableNode * GetNextLinkTableNode(tLinkTable *pLinkTable,tLinkTableNode * pNode)
{
if(pLinkTable == 0 || pNode == 0)
{
return 0;
}
tLinkTableNode * pTempNode = pLinkTable->pHead;
while(pTempNode != 0)
{
if(pTempNode == pNode)
{
return pTempNode->pNext;
}
pTempNode = pTempNode->pNext;
}
return 0;
}
| 0
|
#include <pthread.h>
void handle_connection(int connfd)
{
char buffer[100];
int n, i = 0, fd;
char c;
while ((n = read(connfd, &c, 1)) > 0 && c!='\\n')
buffer[i++] = c;
buffer[i] = '\\0';
if ((fd = open(buffer, O_RDONLY))<0) {
printf("file open error %s\\n", buffer);
return;
}
while ((n = read(fd, buffer, 100))>0) {
write(connfd, buffer, n);
}
close(connfd);
}
void *server_handler(void *t)
{
int listenfd = create_server(8000), connfd, i, pid;
if (listenfd < 0) {
printf("COULDNT CREATE server\\n");
return;
}
for (;;) {
if ((connfd = accept(listenfd, (struct sockaddr *)0, 0))<0) {
perror("accept error : ");
return;
}
handle_connection(connfd);
close(connfd);
}
}
void try_getting_file(char *filename, char *ip)
{
char request[100], buffer[100];
int connfd = create_socket(ip, 8000), n, fd;
strcpy(request, filename);
strcat(request, "\\n");
if (connfd<0) {
printf("client socket creation error : ");
return;
}
write(connfd, request, strlen(request));
if ((fd = creat(filename, 0666))<0) {
perror("file creation error : ");
return;
}
while ((n = read(connfd, buffer, 100)) > 0) {
write(fd, buffer, n);
}
close(fd);
close(connfd);
}
void get_searched_file(char *filename)
{
char buffer[100], ip_address[100];
int fd, i = 0, n;
char c;
strcpy(buffer, filename);
strcat(buffer, ".meta");
retrieve_index(buffer);
if ((fd = open(buffer, O_RDONLY))<0) {
printf("file open error : %s\\n", buffer);
return;
}
while ((n = read(fd, &c, 1)) > 0) {
if (c=='\\n') {
ip_address[i] = '\\0';
try_getting_file(filename, ip_address);
i = 0;
} else {
ip_address[i++] = c;
}
}
close(fd);
}
void *do_init(void *t)
{
boot_me_up();
read_write_start();
}
int main()
{
char buffer[100], action[100];
int n, rc, in;
pthread_t thread_id, in_id;
strcpy(booter_main, "152.14.93.61");
strcpy(index_meta_file, ".local_meta_file");
pthread_mutex_init(&search_mutex, 0);
in = pthread_create(&in_id, 0, do_init, (void *)0);
rc = pthread_create(&thread_id, 0, server_handler, (void *)0);
index_init();
printf("Booted up and running\\n");
while (scanf("%s %s", action, buffer)!=EOF) {
printf(".... %s %s", action, buffer);
fflush(0);
if (strcmp(action, "search")==0) {
pthread_mutex_lock(&search_mutex);
do_search(buffer);
pthread_mutex_unlock(&search_mutex);
continue;
}
if (strcmp(action,"get")==0) {
printf("getting the file %s\\n", buffer);
get_searched_file(buffer);
continue;
}
if (strcmp(action,"print")==0) {
print_route();
continue;
}
if (strcmp(action, "q")==0) {
fflush(0);
printf("quitting in a second\\n");
sleep(2);
return 0;
}
printf("invalid commands %s %s\\n", action, buffer);
}
}
| 1
|
#include <pthread.h>
int putenv_r(char *string);
extern char **environ;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
int
main(int argc, char *argv[]) {
int ret = putenv_r("key1=myvalue friend");
printf("%d: mykey = %s\\n", ret, getenv("key1"));
ret = putenv_r("key2=myvalue dog");
ret = putenv_r("key3=myvalue dog");
ret = putenv_r("key4=myvalue dog");
ret = putenv_r("key5=myvalue dog");
ret = putenv_r("key6=myvalue dog");
ret = putenv_r("key7=myvalue dog");
ret = putenv_r("key8=myvalue dogs");
printf("%d: mykey = %s\\n", ret, getenv("key8"));
return 0;
}
int
putenv_r(char *string)
{
int len;
int key_len = 0;
int i;
sigset_t block;
sigset_t old;
sigfillset(&block);
pthread_sigmask(SIG_BLOCK, &block, &old);
len = strlen(string);
for (int i=0; i < len; i++) {
if (string[i] == '=') {
key_len = i;
break;
}
}
if (key_len == 0) {
errno = EINVAL;
return -1;
}
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if (strncmp(string, environ[i], key_len) == 0) {
environ[i] = string;
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
int n = sizeof(environ)/sizeof(environ[0]);
printf("%d %s\\n", n, environ[i-1]);
environ[i] = malloc(sizeof(char *));
environ[i] = string;
environ[i+1] = 0;
pthread_mutex_unlock(&env_mutex);
pthread_sigmask(SIG_SETMASK, &old, 0);
return(0);
}
| 0
|
#include <pthread.h>
int num;
unsigned long total;
int flag;
pthread_mutex_t m;
pthread_cond_t empty, full;
void *thread1(void *arg)
{
int i;
i = 0;
while (i < 2){
pthread_mutex_lock(&m);
while (num > 0)
pthread_cond_wait(&empty, &m);
num++;
pthread_mutex_unlock(&m);
pthread_cond_signal(&full);
i++;
}
return 0;
}
void *thread2(void *arg)
{
int j;
j = 0;
while (j < 2){
pthread_mutex_lock(&m);
while (num == 0)
pthread_cond_wait(&full, &m);
num--;
pthread_mutex_unlock(&m);
pthread_cond_signal(&empty);
j++;
total=total+j;
}
flag=1;
return 0;
}
int main()
{
pthread_t t1, t2;
num = 0;
total = 0;
pthread_mutex_init(&m, 0);
pthread_cond_init(&empty, 0);
pthread_cond_init(&full, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
if (flag)
assert(total==((2*(2 +1))/2));
return 0;
}
| 1
|
#include <pthread.h>
static struct termios old, new;
static struct termios g_old_kbd_mode;
static char *device = "default";
float buffer_null[1024];
int main(void)
{
int err;
int j,k;
num_det = 0;
send = 0;
Fs = 44100;
durationdefaultsize = 0;
mode = 2;
num_jef[0] = 8;
num_jef[1] = 3;
num_jef[2] = 1;
num_jef[3] = 1;
num_jef[4] = 9;
num_jef[5] = 0;
num_jef[6] = 5;
num_jef[7] = 1;
digit = num_jef[0];
for(j = 0; j < 1024; j++) {
buffer_null[j] = 0;
}
buffer_2048 = (float **) malloc(sizeof(float*) * 16);
buffer_11793 = (float **) malloc(sizeof(float*) * 16);
buffer_22562 = (float **) malloc(sizeof(float*) * 16);
buffer_33331 = (float **) malloc(sizeof(float*) * 16);
buffer_44100 = (float **) malloc(sizeof(float*) * 16);
for(k=0; k<16;k++){
buffer_2048[k] = (float *) malloc(sizeof(float) * 2048 );
buffer_11793[k] = (float *) malloc(sizeof(float) * 11793 );
buffer_22562[k] = (float *) malloc(sizeof(float) * 22562 );
buffer_33331[k] = (float *) malloc(sizeof(float) * 33331 );
buffer_44100[k] = (float *) malloc(sizeof(float) * 44100 );
}
gen_tones(buffer_2048, 2048);
gen_tones(buffer_11793, 11793);
gen_tones(buffer_22562, 22562);
gen_tones(buffer_33331, 33331);
gen_tones(buffer_44100, 44100);
set_station();
pthread_create( &thread1, 0, finding_freq, 0);
pthread_create(&tkc, 0, menu, 0);
while (ch1 != 'q') {
if ((err = snd_pcm_open(&handle_w, device, SND_PCM_STREAM_PLAYBACK, 0)) < 0) {
printf("Playback open error: %s\\n", snd_strerror(err));
exit(1);
}
if ((err = snd_pcm_set_params(handle_w,
SND_PCM_FORMAT_FLOAT,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
Fs,
1,
100000)) < 0) {
printf("Playback open error: %s\\n", snd_strerror(err));
exit(1);
}
while((mode==1) & (ch1 != 'q')) {
if(send){
switch( durationdefaultsize ) {
case 0:
(void) snd_pcm_writei(handle_w, buffer_2048[digit_], 2048);
break;
case 1:
(void) snd_pcm_writei(handle_w, buffer_11793[digit_], 11793);
break;
case 2:
(void) snd_pcm_writei(handle_w, buffer_22562[digit_], 22562);
break;
case 3:
(void) snd_pcm_writei(handle_w, buffer_33331[digit_], 33331);
break;
case 4:
(void) snd_pcm_writei(handle_w, buffer_44100[digit_], 44100);
break;
default:
break;
}
send = 0;
}
else (void) snd_pcm_writei(handle_w, buffer_null, 1024);
}
snd_pcm_close(handle_w);
usleep(100000);
if ((err = snd_pcm_open (&handle_r, device, SND_PCM_STREAM_CAPTURE, 0)) < 0) {
exit (1);
}
if ((err = snd_pcm_set_params(handle_r,
SND_PCM_FORMAT_FLOAT,
SND_PCM_ACCESS_RW_INTERLEAVED,
1,
Fs,
1,
100000)) < 0) {
printf("Playback open error: %s\\n", snd_strerror(err));
exit(1);
}
digit = num_jef[0];
num_det = 0;
while((mode==0) & (ch1 != 'q')) {
pthread_mutex_lock(&mutex_f);
pthread_mutex_unlock(&mutex_s);
pthread_mutex_lock(&mutex_w1);
(void) snd_pcm_readi(handle_r, buffer_f, 2048);
pthread_mutex_unlock(&mutex_w1);
pthread_mutex_lock(&mutex_s);
pthread_mutex_unlock(&mutex_f);
(void) snd_pcm_readi(handle_r, buffer_s, 2048);
}
snd_pcm_close(handle_r);
usleep(100000);
}
return 0;
}
| 0
|
#include <pthread.h>
enum PhilState { THINKING, HUNGRY, EATING };
pthread_t thread;
int id;
int prio;
int state;
sem_t *forkLeft, *forkRight;
struct philosopher_t *philLeft, *philRight;
} Philosopher;
sem_t *forks;
sem_t forkLock;
Philosopher *phils;
int numPhils;
void setTheTable();
void invitePhilosophers();
void serveDinner();
void cleanDishes();
void killPhilosophers();
void * philDine(void *args);
void philThink(Philosopher *p);
void philHungry(Philosopher *p);
void philEat(Philosopher *p);
void philChangeState(Philosopher *p, int state);
void philPrintStates();
void philGrabForks(Philosopher *p);
int philCanEat(Philosopher *p);
void philReleaseForks(Philosopher *p);
int randomInt(int rangeMin, int rangeSize);
int main(int argc, char *argv[]) {
if(argc < 2) {
fprintf(stderr, "Usage: %s [numPhils]\\n", argv[0]);
exit(1);
}
numPhils = atoi(argv[1]);
setTheTable();
invitePhilosophers();
serveDinner();
cleanDishes();
killPhilosophers();
return 0;
}
void setTheTable() {
forks = malloc(sizeof(sem_t) * numPhils);
for(int i = 0; i < numPhils; i++)
sem_init(&forks[i], 0, 1);
sem_init(&forkLock, 0, 1);
}
void invitePhilosophers() {
phils = malloc(sizeof(Philosopher) * numPhils);
for(int i = 0; i < numPhils; i++) {
Philosopher *p = &phils[i];
p->state = THINKING;
p->id = i;
p->prio = 0;
p->forkLeft = &forks[i];
p->forkRight = &forks[(i+1) % numPhils];
p->philLeft = &phils[(i+numPhils-1) % numPhils];
p->philRight = &phils[(i+1) % numPhils];
}
srand(time(0));
}
void cleanDishes() {
free(forks);
}
void killPhilosophers() {
free(phils);
}
void serveDinner() {
philPrintStates();
for(int i = 0; i < numPhils; i++) {
pthread_create(&phils[i].thread, 0, philDine, &phils[i]);
}
for(int i = 0; i < numPhils; i++) {
pthread_join(phils[i].thread, 0);
}
}
void *philDine(void *args) {
Philosopher *myself = (Philosopher *) args;
while(1) {
philThink(myself);
philHungry(myself);
philEat(myself);
}
return 0;
}
void philThink(Philosopher *p) {
int thinkingTime = randomInt(1, 10);
sleep(thinkingTime);
}
void philHungry(Philosopher *p) {
philGrabForks(p);
}
void philEat(Philosopher *p) {
int eatingTime = randomInt(1, 10);
sleep(eatingTime);
philReleaseForks(p);
}
void philChangeState(Philosopher *p, int state) {
static pthread_mutex_t smutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&smutex);
p->state = state;
p->prio = 0;
philPrintStates();
pthread_mutex_unlock(&smutex);
}
void philPrintStates() {
static const char stateToChar[] = { 'T', 'H', 'E' };
for(int i = 0; i < numPhils; i++) {
printf("%c ", stateToChar[phils[i].state]);
}
printf("\\n");
}
void philGrabForks(Philosopher *p) {
philChangeState(p, HUNGRY);
while(!philCanEat(p))
sem_wait(&forkLock);
sem_wait(p->forkLeft);
sem_wait(p->forkRight);
philChangeState(p, EATING);
sem_post(&forkLock);
}
int philCanEat(Philosopher *p) {
int selfPrio = p->prio;
int leftState = p->philLeft->state;
int leftPrio = p->philLeft->prio;
int rightState = p->philRight->state;
int rightPrio = p->philRight->prio;
int canEat = leftState != EATING && rightState != EATING;
int shouldEat = (leftState == THINKING || (leftState == HUNGRY && selfPrio >= leftPrio)) &&
(rightState == THINKING || (rightState == HUNGRY && selfPrio >= rightPrio));
if(!canEat)
p->prio++;
if(!shouldEat)
sem_post(&forkLock);
return canEat && shouldEat;
}
void philReleaseForks(Philosopher *p) {
sem_post(p->forkLeft);
sem_post(p->forkRight);
philChangeState(p, THINKING);
}
int randomInt(int rangeMin, int rangeSize) {
return rand() % rangeSize + rangeMin;
}
| 1
|
#include <pthread.h>
void malloc_and_forget(int size)
{
assert(size >= 0);
(void)malloc(size);
}
static inline void strrev(char *str)
{
register int i;
for (i = 0; i < strlen(str) / 2; i++) {
str[i] ^= str[strlen(str) - i - 1];
str[strlen(str) - i - 1] ^= str[i];
str[i] ^= str[strlen(str) - i - 1];
}
}
void strrevrev(char* str)
{
strrev(str);
strrev(str);
}
char *strstrstr(char* s1, char* s2, char* s3)
{
}
long long llll(long long l1, long long l2)
{
}
void* id(void* ptr)
{
return (void *)(uintptr_t)ptr;
}
int itoi(int value)
{
char buf[32];
int result;
result = snprintf(buf, sizeof(buf), "%d", value);
assert(result < sizeof(buf));
return atoi(buf);
}
char *atoa(char* str)
{
}
int tweet(char* str)
{
}
static void* _deadlock_helper(void* param)
{
pthread_mutex_t* mutexes = (pthread_mutex_t*)param;
int deadlocked = 0;
while (!deadlocked) {
int mtx = rand() % 2;
pthread_mutex_lock(&mutexes[mtx]);
pthread_mutex_lock(&mutexes[!mtx]);
pthread_mutex_unlock(&mutexes[0]);
pthread_mutex_unlock(&mutexes[1]);
}
}
void deadlock(void)
{
pthread_t other_thread;
pthread_mutex_t mutexes[] = { PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER };
int deadlocked = 0;
pthread_create(&other_thread, 0, _deadlock_helper, mutexes);
_deadlock_helper(mutexes);
assert(0);
}
int return4(void)
{
return 010 - 4;
}
void* memdntcpy (void* destination, void* source, size_t num)
{
void* buf = malloc(num);
assert(buf);
memcpy(buf, source, num);
memcpy(destination, buf, num);
free(buf);
return destination;
}
int bsort(void *base, size_t nel, size_t width, int (*compar)(void *, void *))
{
}
void* bsearch(void* key, void* base, size_t num, size_t size, int (*compar)(void*,void*))
{
}
void rbubblesort (void* base, size_t num, size_t size, int (*compar)(const void*,const void*))
{
}
void segfault(void)
{
char stack[0];
int i;
for (i = 0; ; i++)
stack[i] = '\\xcc';
}
void* wwkd(struct KEITH* htiek, ...)
{
}
int rand_gam(void)
{
static int recent_buf[32];
static int recent_fill = 0;
static int recent_index = 0;
int i;
int ok = 0;
int result;
while (!ok) {
result = rand();
ok = 1;
for (i = 0; i < recent_fill; i++) {
if (result == recent_buf[i]) {
ok = 0;
break;
}
}
}
recent_buf[recent_index++] = result;
recent_index = recent_index % 32;
if (recent_fill < 32)
recent_fill++;
return result;
}
void resolve_arguments(struct VIEWPOINT* v1, struct VIEWPOINT* v2)
{
memset(v1, 0, sizeof(*v1));
memset(v2, 0, sizeof(*v2));
}
pid_t ndfork(void)
{
}
void intr_disable_permanently(void)
{
}
void do_nothing(void)
{
}
void rfree(void* ptr, double p) {
long int threshold = lround(p * ((long)32767 + 1));
if (randrand() < threshold)
free(ptr);
}
int freeall(void)
{
}
uintptr_t vtov (void *va)
{
}
static int good_rand()
{
int mask;
int result = 0;
mask = (2 << (int)ceil(log2(32767))) - 1;
do {
RAND_bytes((unsigned char*)&result, sizeof(result));
result &= mask;
} while (result < 0 || result > 32767);
}
int randrand(void)
{
unsigned char good_meta_rng = good_rand() & 1;
for (;;) {
unsigned char good_rng;
if (good_meta_rng)
good_rng = good_rand() & 1;
else
good_rng = rand() & 1;
if (good_rng == good_meta_rng) {
if (good_rng)
return good_rand();
else
return rand();
}
good_meta_rng = good_rng;
}
}
| 0
|
#include <pthread.h>
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
char operacion_a_realizar[4];
char mensaje_verificado[3];
char solucion[2];
int numero_clientes = 0;
int rec;
int sock_srv;
pthread_mutex_t lock;
void catchHijo() {
printf("he pillado a un hijo muriendose \\n");
while (waitpid(-1, 0, WNOHANG) > 0) {
pthread_mutex_lock(&lock);
numero_clientes--;
pthread_mutex_unlock(&lock);
}
}
int main(int argc, char *argv[]) {
int udp_flag = 0;
int tcp_flag = 0;
int port_number = 7777;
char *port_arg_value = 0;
int opcion;
if (argc == 1) {
printf("Usage calculadora_IP_server [-u|-t] [ -p port ]\\n");
exit(1);
}
opterr = 0;
while ((opcion = getopt(argc, argv, "tup:")) != -1)
switch (opcion) {
case 't':
tcp_flag = 1;
break;
case 'u':
udp_flag = 1;
break;
case 'p':
port_arg_value = optarg;
break;
default:
printf("Usage calculadora_IP_server [-u|-t] [ -p port ]\\n");
exit(1);
;
}
if (port_arg_value != 0) {
int length = strlen(port_arg_value);
for (int i = 0; i < length; i++)
if (!isdigit(port_arg_value[i])) {
printf("Entered port is not a number\\n");
exit(1);
}
port_number = atoi(port_arg_value);
if (!((port_number > 1024) && (port_number < 65535))) {
printf("puerto fuera de rango\\n");
exit(1);
}
}
if ((tcp_flag == udp_flag) && (udp_flag == 1)) {
printf("Especifique UDP o TCP \\n");
exit(1);
}
if ((tcp_flag == 0) && (udp_flag == 0)) {
tcp_flag = 1;
}
printf("udp_flag = %d, tcp_flag = %d, port_number = %s\\n", udp_flag,
tcp_flag, port_arg_value);
printf("udp_flag = %d, tcp_flag = %d\\n", udp_flag, tcp_flag);
printf("port_number = %d\\n", port_number);
if (tcp_flag) {
sock_srv = socket(AF_INET, SOCK_STREAM, 0);
} else {
sock_srv = socket(AF_INET, SOCK_DGRAM, 0);
}
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port_number);
if (bind(sock_srv, &server_addr, sizeof(server_addr)) < 0) {
perror("no se puede hacer bind en server, se sale");
exit(-1);
}
if (tcp_flag) {
struct sigaction act;
memset (&act, 0, sizeof(act));
act.sa_handler = catchHijo;
if (sigaction(SIGCHLD, &act, 0)) {
perror ("sigaction");
return 1;
}
listen(sock_srv, 2);
}
while (1) {
bzero(&client_addr, sizeof(client_addr));
int tam = sizeof(client_addr);
int socket_efimero;
retorno_fallo_accept:
retorno_task_server:
if (tcp_flag) {
do {
printf("aceptando conexion %d....\\n", numero_clientes);
socket_efimero = accept(sock_srv, &client_addr, &tam);
} while ((socket_efimero == -1) && (errno == EINTR));
if (socket_efimero < 0) {
perror("error en accept en servidor");
goto retorno_fallo_accept;
}
signal (SIGCHLD,catchHijo);
signal (SIGKILL,catchHijo);
if (numero_clientes < MAX_HIJOS) {
int pid = fork();
if (pid == 0) {
close(sock_srv);
task_server_tcp(socket_efimero);
close(socket_efimero);
exit(0);
} else {
close(socket_efimero);
numero_clientes++;
printf("numero de clientes %d: \\n",numero_clientes);
}
}
} else {
if (task_server_udp(sock_srv) == -1)
goto retorno_task_server;
}
}
close(sock_srv);
}
| 1
|
#include <pthread.h>
struct reconos_resource res[4];
struct reconos_hwt hwt;
pthread_mutex_t mutex_a, mutex_b;
pthread_cond_t condvar_a, condvar_b;
pthread_t swthread;
void * wait_on_condvar(void * arg){
while(1)
{
pthread_mutex_lock(&mutex_b);
pthread_cond_wait(&condvar_b, &mutex_b);
printf("condition b\\n");
pthread_mutex_unlock(&mutex_b);
}
}
int main(int argc, char ** argv)
{
int i=0,j;
printf("%d\\n",argc);
assert(argc == 1);
res[0].type = RECONOS_TYPE_MUTEX;
res[0].ptr = &mutex_a;
res[1].type = RECONOS_TYPE_COND;
res[1].ptr = &condvar_a;
res[2].type = RECONOS_TYPE_MUTEX;
res[2].ptr = &mutex_b;
res[3].type = RECONOS_TYPE_COND;
res[3].ptr = &condvar_b;
printf("begin condvar_test_posix\\n");
pthread_mutex_init(&mutex_a, 0);
pthread_mutex_init(&mutex_b, 0);
pthread_cond_init(&condvar_a, 0);
pthread_cond_init(&condvar_b, 0);
pthread_create(&swthread,0,wait_on_condvar,0);
printf("creating hw thread... ");
reconos_init_autodetect();
reconos_hwt_setresources(&hwt,res,4);
reconos_hwt_create(&hwt,0,0);
printf("ok\\n");
for(j=0; j<10; j++)
{
usleep(1000);
}
for(i = 0; i < 10; i++){
pthread_mutex_lock(&mutex_a);
printf("signaling condition a\\n");
pthread_cond_signal(&condvar_a);
pthread_mutex_unlock(&mutex_a);
for(j=0; j<10; j++)
{
usleep(1000);
}
}
printf("condvar_test_posix done.\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t cs_is_logging = PTHREAD_MUTEX_INITIALIZER;
void cs_log_msg(int on_syslog, const char* format_s, va_list argv)
{
char msg[CS_MAX_LOG_MSG];
pthread_mutex_lock(&cs_is_logging);
vsnprintf(msg, CS_MAX_LOG_MSG, format_s, argv);
if(on_syslog) {
syslog( LOG_INFO | LOG_DAEMON, msg);
}
else {
fflush(stderr);
fputs(msg, stderr);
fflush(stderr);
}
pthread_mutex_unlock(&cs_is_logging);
}
void cs_log_exit(int on_syslog, const char* format_s, ...)
{
va_list argv;
__builtin_va_start((argv));
cs_log_msg(on_syslog, format_s, argv);
;
exit(-1);
}
void cs_log_err(int on_syslog, const char* format_s, ...)
{
va_list argv;
__builtin_va_start((argv));
cs_log_msg(on_syslog, format_s, argv);
;
}
| 1
|
#include <pthread.h>
int pbs_asyrunjob_err(
int c,
char *jobid,
char *location,
char *extend,
int *local_errno)
{
int rc;
struct batch_reply *reply;
unsigned int resch = 0;
int sock;
struct tcp_chan *chan = 0;
if ((c < 0) || (jobid == 0) || (*jobid == '\\0'))
{
return(PBSE_IVALREQ);
}
if (location == 0)
location = "";
pthread_mutex_lock(connection[c].ch_mutex);
sock = connection[c].ch_socket;
if ((chan = DIS_tcp_setup(sock)) == 0)
{
rc = PBSE_PROTOCOL;
return rc;
}
else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_AsyrunJob, pbs_current_user))
|| (rc = encode_DIS_RunJob(chan, jobid, location, resch))
|| (rc = encode_DIS_ReqExtend(chan, extend)))
{
connection[c].ch_errtxt = strdup(dis_emsg[rc]);
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(PBSE_PROTOCOL);
}
if (DIS_tcp_wflush(chan))
{
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(PBSE_PROTOCOL);
}
reply = PBSD_rdrpy(local_errno, c);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
PBSD_FreeReply(reply);
DIS_tcp_cleanup(chan);
return(rc);
}
int pbs_asyrunjob(
int c,
char *jobid,
char *location,
char *extend)
{
pbs_errno = 0;
return(pbs_asyrunjob_err(c, jobid, location, extend, &pbs_errno));
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int avail=0;
int consumed=0;
int pause_thread(int pause_count){
int total=0;
for(int i=0;i<pause_count;++i){
total++;
}
return total;
}
void * produce(void * arg){
int id = *((int *)arg);
for(int i=0;i<50;++i){
pause_thread(5000000);
pthread_mutex_lock(&mutex);
avail+=5;
printf("PRODUCED: thread %d pid: %d val %d\\n", id, getpid(), avail);
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
return 0;
}
void * consume(void * arg){
int id = *((int *)arg);
for(int i=0;i<50;++i){
pause_thread(1000);
pthread_mutex_lock(&mutex);
while(avail<=0){
pthread_cond_wait(&cond, &mutex);
}
avail--;
++consumed;
printf("CONSUMED: thread %d pid %d val %d consumed %d\\n", id, getpid(), avail, consumed);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(){
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_t producers[1];
int producer_ids[1];
for (int i=0;i<1;++i){
producer_ids[i]=i;
pthread_create(&producers[i], 0, produce, &producer_ids[i]);
}
pthread_t consumers[5];
int consumer_ids[5];
for (int i=0;i<5;++i){
consumer_ids[i]=i+1;
pthread_create(&consumers[i], 0, consume, &consumer_ids[i]);
}
for (int i=0;i<1;++i){
pthread_join(producers[i],0);
}
for (int i=0;i<5;++i){
pthread_join(consumers[i],0);
}
if (consumed==5*50 && avail==0){
fprintf(stderr, "condvar_broadcast: SUCCEEDED\\n");
}
else{
fprintf(stderr, "condvar_broadcast: FAILED, consumed %d, avail %d\\n", consumed, avail);
}
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct node
{
int n_number;
struct node *n_next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("Cleanup handler of second thread./n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
pthread_cleanup_push(cleanup_handler, p);
while (1)
{
pthread_mutex_lock(&mtx);
while (head == 0)
{
pthread_cond_wait(&cond, &mtx);
p = head;
head = head->n_next;
printf("Got %d from front of queue/n", p->n_number);
free(p);
}
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, 0, thread_func, 0);
sleep(1);
for (i = 0; i < 10; i++)
{
p = (struct node*)malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel thread 2./n");
pthread_cancel(tid);
pthread_join(tid, 0);
printf("All done -- exiting/n");
return 0;
}
| 0
|
#include <pthread.h>
int A [3][3] = { {1,1,1}, {2,2,2}, {3,3,3} };
int B [3][3] = { {1,1,1}, {2,2,2}, {3,3,3} };
int C [3][3];
struct v
{
int i;
int j;
}*data, param;
static pthread_mutex_t mutex_matris;
void *hesapla(void *param)
{
data = (struct v *)param;
int satir = data->i;
int sutun = data->j;
pthread_mutex_lock(&mutex_matris);
C[satir][sutun] = (A[satir][0]*B[0][sutun]) + (A[satir][1]*B[1][sutun]);
pthread_mutex_unlock(&mutex_matris);
pthread_exit(0);
}
int main() {
pthread_t thread[3][3];
int i,j;
pthread_mutex_init(&mutex_matris, 0);
for (i=0;i<3;i++){
for(j=0;j<3;j++){
struct v *data = (struct v *) malloc(sizeof(struct v));
data->i = i;
data->j = j;
pthread_create(&thread[i][j], 0, hesapla,(void*) data);
}
}
for (i=0;i<3;i++){
for(j=0;j<3;j++){
pthread_join( thread[i][j],0);
}
}
for (i=0;i<3;i++){
for(j=0;j<3;j++){
printf("%4d ",C[i][j]);
}
printf("\\n");
}
pthread_mutex_destroy(&mutex_matris);
return 0;
}
| 1
|
#include <pthread.h>
struct msg {
struct msg *next;
int num;
};
struct msg *head;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&lock);
while (head == 0)
pthread_cond_wait(&has_product, &lock);
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\\n", mp->num);
free(mp);
int sec = rand() % 5;
printf("consumer gonna sleep %d secs.\\n", sec);
sleep(sec);;
}
}
void *producer(void *p)
{
struct msg *mp;
for (;;) {
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce %d\\n", mp->num);
pthread_mutex_lock(&lock);
mp->next = head;
head = mp;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
int sec = rand() % 5;
printf("producer gonna sleep %d secs.\\n", sec);
sleep(sec);;
}
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
| 0
|
#include <pthread.h>
void *write_msg(void* num_thread);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int k = 0;
int fd;
int main() {
printf("Criando pipe para escrita...\\n");
mkfifo("pipe", 0644);
fd = open("pipe", O_WRONLY);
printf("Descritor do pipe: %d\\n\\n", fd);
printf("Escrevendo mensagens no pipe...\\n");
pthread_t *writer;
writer = (pthread_t*) calloc(5, sizeof(pthread_t));
int num_thread[5];
int i;
for(i = 0; i < 5; i++) {
num_thread[i] = i+1;
pthread_create(&writer[i], 0, write_msg, &num_thread[i]);
}
for(i = 0; i < 5; i++)
pthread_join(writer[i],0);
printf("Escrita finalizada.\\n\\n");
free(writer);
return 0;
}
void *write_msg(void* num_thread)
{
char msg[10];
int num = *((int*) num_thread);
while(k < 1000)
{
pthread_mutex_lock(&mutex);
sprintf(msg, "%d-MSG-%.3d", num, k);
write(fd, msg, 10);
k++;
pthread_mutex_unlock(&mutex);
sleep(1);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queue_not_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t queue_free_places = PTHREAD_COND_INITIALIZER;
int queue[3];
int qlen = 0;
void *producer( void *p)
{
int r;
while(1) {
r = rand() % 10;
printf( "generated: %d\\n", r);
pthread_mutex_lock( &mutex);
while(qlen == 3) {
pthread_cond_wait( &queue_free_places, &mutex);
}
queue[qlen] = r;
qlen++;
pthread_cond_broadcast( &queue_not_empty);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int do_something_complex(int r)
{
sleep(1);
printf( "square of %d is %d\\n", r, r*r);
}
void *consumer( void *p)
{
int r;
while(1) {
pthread_mutex_lock( &mutex);
while( qlen == 0) {
pthread_cond_wait( &queue_not_empty, &mutex);
}
r = queue[0];
qlen--;
if( qlen)
memmove(queue, queue+1, qlen*sizeof(int));
printf( "received: %d\\n", r);
pthread_cond_broadcast(&queue_free_places);
pthread_mutex_unlock(&mutex);
do_something_complex(r);
}
return 0;
}
int main()
{
pthread_t t1, t2, t3;
pthread_create( &t1, 0, producer, 0);
pthread_create( &t2, 0, consumer, 0);
pthread_create( &t3, 0, consumer, 0);
pthread_create( &t3, 0, consumer, 0);
pthread_create( &t3, 0, consumer, 0);
pthread_create( &t3, 0, consumer, 0);
pthread_create( &t3, 0, consumer, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexLock;
int ascendNo[40] = {0};
static void *i_Write_Data(void *pData);
static void *i_Print_Data(void *pData);
int main(void)
{
unsigned char retVal = 0;
int idx = 0;
pthread_t threadId[2];
pthread_mutex_init(&mutexLock, 0);
retVal = pthread_create(&threadId[idx], 0, i_Write_Data, (void *)idx);
if (0 != retVal)
{
printf("Thread creation failed !!!\\n");
return (-1);
}
idx++;
retVal = pthread_create(&threadId[idx], 0, i_Print_Data, (void *)idx);
if (0 != retVal)
{
printf("Thread creation failed !!!\\n");
return (-1);
}
for (idx = 0; idx < 2; idx++)
{
if (0 != pthread_join(threadId[idx], 0))
{
printf("Thread join failed !!!\\n");
return (-1);
}
}
printf("Main: program completed. Exiting.\\n");
pthread_mutex_destroy(&mutexLock);
return (0);
}
static void *i_Write_Data(void *pData)
{
unsigned int idx = (unsigned int)pData;
pthread_mutex_lock(&mutexLock);
printf("This is thread with no %d\\n", idx);
for (idx = 0; idx < 40; idx++)
{
ascendNo[idx] = idx;
if (idx == (40 / 2))
{
printf("Delay of 1ms\\n");
usleep(1000);
}
}
pthread_mutex_unlock(&mutexLock);
return (0);
}
static void *i_Print_Data(void *pData)
{
unsigned int idx = (unsigned int)pData;
pthread_mutex_lock(&mutexLock);
printf("This is thread with no %d\\n", idx);
for (idx = 0; idx < 40; idx++)
{
printf("Data Element = %d\\n", ascendNo[idx]);
}
pthread_mutex_unlock(&mutexLock);
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 failed");
switch(signo)
{
case SIGINT:
printf("\\ninterrupt sigint\\n");
break;
case SIGQUIT:
printf("\\ninterupt\\n");
pthread_mutex_lock(&lock);
quitflag=1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return 0;
default:
printf("unexpected signal %d \\n",signo);
break;
}
}
}
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,"creatre pthread error");
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("SIGSETMASK error");
exit(0);
}
| 0
|
#include <pthread.h>
void *create_physics_update(void* arg)
{
float engine_torque = 0.0;
float torque_drive = 0.0;
float f_drive = 0.0;
float f_drag = 0.0;
float f_rr = 0.0;
float f_long = 0.0;
float acc = 0.0;
float old_gear_ratio = 0.0;
float v_max = compute_v_max();
struct car_t *c = (struct car_t *) arg;
struct timespec T_input = msec_to_timespec(PERIOD_UPDATE_THREAD);
struct timespec t, t_next;
clock_gettime(CLOCK_MONOTONIC, &t);
t_next = t;
while(c->state_car == ON)
{
pthread_mutex_lock(&c->mutex_car);
if(c->fuel_level > 0.0)
{
if((c->gear_mode == D) || (c->gear_mode == R))
{
if((c->rpm == RPM_START) && (c->brake == 0))
{
engine_torque = TORQUE_START;
}
else
{
engine_torque = compute_torque_engine(c);
}
}
else
{
engine_torque = 0.0;
}
torque_drive = (engine_torque)*(c->cartype->gear_ratio)*(c->cartype->differential_ratio);
f_drive = (float)(torque_drive/c->cartype->wheel_radius);
f_drag = compute_f_drag(c->speed);
f_rr = compute_f_rr(c->speed, c->cartype->mass);
f_long = f_drive - f_drag - f_rr;
if(c->cruise_control == OFF)
{
acc = (float)(f_long/c->cartype->mass);
}
else
{
acc = 0.0;
}
c->speed += acc*delta_t;
if(c->speed > v_max)
c->speed = v_max;
if(c->speed < 0.0)
c->speed = 0.0;
c->position += c->speed*delta_t;
c->fuel_path = c->speed*delta_t;
if(c->speed > 0.0)
c->fuel_level = compute_fuel_consumption(c->fuel_path, c->fuel_level, c->fuel_efficiency);
if(c->fuel_level < 0.0)
c->fuel_level = 0.0;
c->rpm = (c->speed*60.0*c->cartype->gear_ratio*c->cartype->differential_ratio)/(2.0*M_PI*c->cartype->wheel_radius);
if(c->rpm < MIN_RPM)
c->rpm = MIN_RPM;
if(c->rpm > MAX_RPM)
c->rpm = MAX_RPM;
if(c->gear_mode == D)
compute_gear(c);
}
else
{
c->rpm = 0.0;
c->speed = 0.0;
c->fuel_path = 0.0;
}
pthread_mutex_unlock(&c->mutex_car);
t_next = timespec_add(&t_next, &T_input);
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &t_next, 0);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void send_ready_signal()
{
pthread_mutex_lock(&configs->lock);
configs->flag = 1;
pthread_cond_signal(&configs->cond);
pthread_mutex_unlock(&configs->lock);
}
void load_configs()
{
int j = 0, i=0;
char line[1024];
char *search = " ;\\n\\0", *token;
FILE *file = fopen("config.txt", "r");
if(file!=0)
{
while(i<4)
{
fgets(line, sizeof(line), file);
switch(i)
{
case(0):
token = strtok(line, search);
token = strtok(0, search);
token = strtok(0, search);
configs->num_threads = atoi(token);
break;
case(1):
token = strtok(line, search);
token = strtok(0, search);
token = strtok(0, search);
while(token!=0)
{
strcpy(configs->domains[j], token);
j++;
token = strtok(0, search);
}
configs->domains[j][strlen(configs->domains[j])-1]='\\0';
configs->num_domains = j;
break;
case(2):
token = strtok(line, search);
token = strtok(0, search);
token = strtok(0, search);
token[strlen(token)-1] = '\\0';
strcpy(configs->local_domain, token);
break;
case(3):
token = strtok(line, search);
token = strtok(0, search);
token = strtok(0, search);
strcpy(configs->name_to_stats, token);
break;
}
i++;
}
}
fclose(file);
}
void process_config()
{
signal(SIGUSR1, handle_signals);
load_configs();
send_ready_signal();
printf("CONFIGS READY!\\n");
while(1)
pause();
}
| 0
|
#include <pthread.h>
pthread_mutex_t sleepMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t sleepBarrier;
void * lockSleepUnlock(void * c);
void * sleepLockSleepUnlock(void * c);
void * sleepTryLockSleepUnlock(void * c);
int main(int argc, char *argv[]) {
printf("Allocating memory for pthread_ts\\r\\n");
pthread_t lockSleepUnlockThreadId;
pthread_t sleepLockSleepUnlockThreadId;
pthread_t sleepTryLockSleepUnlockThreadId;
printf("Initializing a pthread barrier to not quit until 3 waits\\r\\n");
pthread_barrier_init(&sleepBarrier, 0, 3);
printf("Spawning thread for function lockSleepUnlock\\r\\n");
pthread_create(&lockSleepUnlockThreadId, 0, lockSleepUnlock, 0);
printf("Spawning thread for function sleepLockSleepUnlock\\r\\n");
pthread_create(&sleepLockSleepUnlockThreadId, 0, sleepLockSleepUnlock, 0);
printf("Spawning thread for function sleepTryLockSleepUnlock\\r\\n");
pthread_create(&sleepTryLockSleepUnlockThreadId, 0, sleepTryLockSleepUnlock, 0);
printf("Starting process to join lockSleepUnlock thread with the main thread\\r\\n");
pthread_join(lockSleepUnlockThreadId, 0);
printf("Main thread waiting at the barrier\\r\\n");
pthread_barrier_wait(&sleepBarrier);
return 0;
}
void * lockSleepUnlock(void * c) {
printf("Starting lockSleepUnlock\\r\\n");
printf("lockSleepUnlock thread waiting for sleepMutex lock\\r\\n");
pthread_mutex_lock(&sleepMutex);
printf("lockSleepUnlock thread acquired lock on sleepMutex\\r\\n");
sleep(5);
printf("lockSleepUnlock finished work and is unlocking sleepmMutex\\r\\n");
pthread_mutex_unlock(&sleepMutex);
printf("lockSleepUnlock has finished unlocking sleepMutex\\r\\n");
printf("lockSleepUnlock ending\\r\\n");
return 0;
}
void * sleepLockSleepUnlock(void * c) {
printf("Starting sleepLockSleepUnlock\\r\\n");
sleep(1);
printf("sleepLockSleepUnlock thread waiting for sleepMutex lock\\r\\n");
pthread_mutex_lock(&sleepMutex);
printf("sleepLockSleepUnlock thread acquired lock on sleepMutex\\r\\n");
sleep(5);
printf("sleepLockSleepUnlock finished work and is unlocking sleepmMutex\\r\\n");
pthread_mutex_unlock(&sleepMutex);
printf("sleepLockSleepUnlock has finished unlocking sleepMutex\\r\\n");
printf("sleepLockSleepUnlock waiting at the barrier\\r\\n");
pthread_barrier_wait(&sleepBarrier);
printf("sleepLockSleepUnlock ending\\r\\n");
return 0;
}
void * sleepTryLockSleepUnlock(void * c) {
printf("Starting sleepTryLockSleepUnlock\\r\\n");
sleep(2);
printf("sleepTryLockSleepUnlock thread trying to lock mutex\\r\\n");
int res = pthread_mutex_trylock(&sleepMutex);
if (res == EOK) {
printf("sleepTryLockSleepUnlock locked sleepMutex\\r\\n");
sleep(2);
pthread_mutex_unlock(&sleepMutex);
}
else {
printf("sleepTryLockSleepUnlock couldn't lock sleepMutex\\r\\n");
}
printf("sleepTryLockSleepUnlock waiting at the barrier\\r\\n");
pthread_barrier_wait(&sleepBarrier);
printf("sleepTryLockSleepUnlock ending\\r\\n");
return 0;
}
| 1
|
#include <pthread.h>
uint32_t speed;
uint32_t mode;
uint8_t bits;
int fd;
uint8_t chip_select;
pthread_mutex_t lock;
} SPIState;
SPIState *spi_init(char *device, uint32_t mode, uint8_t bits, uint32_t speed, uint8_t chip_select) {
int ret;
SPIState *spi = (SPIState *) malloc(sizeof(SPIState));
if (spi == 0) return 0;
do { spi->mode = mode; spi->bits = bits; spi->speed = speed; spi->chip_select = chip_select;} while (0);
printf("SPI config: mode %d, %d bit, %dMhz\\n",spi->mode, spi->bits, (spi->speed)/1000000);
spi->fd = open(device, O_RDWR);
if (spi->fd < 0) {
perror("ERROR: Can't open SPI device");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_WR_MODE, &(spi->mode));
if (ret == -1) {
perror("ERROR: Can't set spi wr mode");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_RD_MODE, &(spi->mode));
if (ret == -1) {
perror("ERROR: Can't set spi rd mode");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_WR_BITS_PER_WORD, &(spi->bits));
if (ret == -1) {
perror("ERROR: Can't set bits per word");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_RD_BITS_PER_WORD, &(spi->bits));
if (ret == -1) {
perror("ERROR: Can't set bits per word");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_WR_MAX_SPEED_HZ, &(spi->speed));
if (ret == -1) {
perror("ERROR: Can't set max speed hz");
return 0;
}
ret = ioctl(spi->fd, SPI_IOC_RD_MAX_SPEED_HZ, &(spi->speed));
if (ret == -1) {
perror("ERROR: Can't set max speed hz");
return 0;
}
gpio_open(spi->chip_select, GPIO_OUT);
spi_disable(spi);
pthread_mutex_init(&(spi->lock), 0);
return spi;
}
void spi_enable(SPIState *spi){
pthread_mutex_lock(&(spi->lock));
gpio_write(spi->chip_select, GPIO_LOW);
}
uint8_t spi_transfer(SPIState *spi, uint8_t val, uint8_t *rx) {
if (spi == 0) {
perror("ERROR: NULL spi state");
return 0;
}
int ret;
uint8_t tx[1] = {val};
uint8_t rx_val[1] = {0};
struct spi_ioc_transfer tr;
memset(&tr, 0, sizeof(struct spi_ioc_transfer));
tr.tx_buf = (unsigned long)tx;
tr.rx_buf = (unsigned long)rx_val;
tr.len = 1;
tr.delay_usecs = 0;
tr.cs_change = 0;
tr.speed_hz = spi->speed;
tr.bits_per_word = spi->bits;
ret = ioctl(spi->fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1) {
perror("ERROR: can't send spi message");
return 0;
}
if (rx != 0) memcpy(rx, rx_val, 1);
return 1;
}
uint8_t spi_transfer_bulk(SPIState *spi, uint8_t *tx, uint8_t *rx, uint8_t len) {
if (spi == 0) {
perror("ERROR: NULL spi state");
return 0;
}
int ret;
uint8_t rx_val[len];
memset(rx_val, 0, len);
struct spi_ioc_transfer tr;
tr.tx_buf = (unsigned long)tx;
tr.rx_buf = (unsigned long)rx_val;
tr.len = len;
tr.delay_usecs = 0;
tr.cs_change = 0;
tr.speed_hz = spi->speed;
tr.bits_per_word = spi->bits;
ret = ioctl(spi->fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1) {
perror("ERROR: can't send spi message");
return 0;
}
if (rx != 0) memcpy(rx, rx_val, len);
return 1;
}
void spi_disable(SPIState *spi){
gpio_write(spi->chip_select, GPIO_HIGH);
pthread_mutex_unlock(&(spi->lock));
}
void spi_close(SPIState *spi){
pthread_mutex_lock(&(spi->lock));
close(spi->fd);
pthread_mutex_unlock(&(spi->lock));
}
| 0
|
#include <pthread.h>
struct _results_t {
size_t print_frequency_in_page_accesses;
size_t expected_num_page_accesses;
size_t test_file_size;
int num_passes;
int num_threads;
char *mmap_advice_desc;
char *desc;
pthread_mutex_t mutex;
size_t total_bytes_copied;
size_t total_pages_accessed;
size_t bytes_copied_since_last_print;
size_t pages_accessed_since_last_print;
struct timeval prev;
struct timeval cur;
};
static void results_print(struct _results_t *results) {
time_t elapsed_time_us = results->cur.tv_usec - results->prev.tv_usec;
elapsed_time_us += 1000000l * (results->cur.tv_sec - results->prev.tv_sec);
double time_in_seconds = elapsed_time_us / 1e6;
double pages_per_second = results->pages_accessed_since_last_print / time_in_seconds;
double bytes_per_second = results->bytes_copied_since_last_print / time_in_seconds;
double percent_complete = (double)results->total_pages_accessed / (double)results->expected_num_page_accesses * 100;
printf("%ld,%d,%d,%s,%s,%ld,%ld,%lf,%lf\\n",
results->test_file_size,
results->num_passes,
results->num_threads,
results->mmap_advice_desc,
results->desc,
results->total_bytes_copied,
results->bytes_copied_since_last_print,
time_in_seconds,
bytes_per_second);
fprintf(stderr, " %5.1lf complete (%9.3lf MBps, %10.1lf pages/sec)\\n",
percent_complete,
bytes_per_second / 1024 / 1024,
pages_per_second);
results->pages_accessed_since_last_print = 0;
results->bytes_copied_since_last_print = 0;
}
int results_init(struct _results_t **results, size_t print_frequency_in_page_accesses, size_t test_file_size, int num_passes, int num_threads, char *mmap_advice_desc, char *desc) {
*results = malloc(sizeof((*results)[0]));
if(*results == 0) {
fprintf(stderr, "Failed to malloc results struct\\n");
return 1;
}
if(pthread_mutex_init(&((*results)->mutex), 0) != 0) {
perror("Failed to initialize mutex");
free(*results);
}
long page_size = sysconf(_SC_PAGE_SIZE);
size_t num_pages = test_file_size / page_size;
(*results)->print_frequency_in_page_accesses = print_frequency_in_page_accesses;
(*results)->expected_num_page_accesses = num_pages * num_passes;
(*results)->test_file_size = test_file_size;
(*results)->num_passes = num_passes;
(*results)->num_threads = num_threads;
(*results)->mmap_advice_desc = mmap_advice_desc;
(*results)->desc = desc;
(*results)->total_bytes_copied = 0;
(*results)->total_pages_accessed = 0;
(*results)->bytes_copied_since_last_print = 0;
(*results)->pages_accessed_since_last_print = 0;
gettimeofday(&(*results)->prev, 0);
gettimeofday(&(*results)->cur, 0);
return 0;
}
void results_log(struct _results_t *results, size_t bytes_copied, size_t num_pages_accessed) {
pthread_mutex_lock(&(results->mutex));
results->total_bytes_copied += bytes_copied;
results->total_pages_accessed += num_pages_accessed;
results->bytes_copied_since_last_print += bytes_copied;
results->pages_accessed_since_last_print += num_pages_accessed;
if(results->pages_accessed_since_last_print >= results->print_frequency_in_page_accesses) {
gettimeofday(&results->cur, 0);
results_print(results);
results->prev = results->cur;
}
pthread_mutex_unlock(&(results->mutex));
}
int results_finished(struct _results_t *results) {
if(results->pages_accessed_since_last_print > 0) {
gettimeofday(&results->cur, 0);
results_print(results);
results->prev = results->cur;
}
if(results->total_pages_accessed != results->expected_num_page_accesses) {
fprintf(stderr, "Accessed %ld pages; expected %ld accesses\\n",
results->total_pages_accessed,
results->expected_num_page_accesses);
return 1;
}
return 0;
}
int results_destroy(struct _results_t *results) {
if(pthread_mutex_destroy(&(results->mutex)) != 0) {
perror("Failed to destroy mutex");
return 1;
}
free(results);
return 0;
}
| 1
|
#include <pthread.h>
int num_threads = 1;
int keys[100000];
pthread_mutex_t lock;
int key;
int val;
struct _bucket_entry *next;
} bucket_entry;
bucket_entry *table[5];
void panic(char *msg) {
printf("%s\\n", msg);
exit(1);
}
double now() {
struct timeval tv;
gettimeofday(&tv, 0);
return tv.tv_sec + tv.tv_usec / 1000000.0;
}
void insert(int key, int val) {
pthread_mutex_lock(&lock);
int i = key % 5;
bucket_entry *e = (bucket_entry *) malloc(sizeof(bucket_entry));
if (!e) panic("No memory to allocate bucket!");
e->next = table[i];
e->key = key;
e->val = val;
table[i] = e;
pthread_mutex_unlock(&lock);
}
bucket_entry * retrieve(int key) {
bucket_entry *b;
for (b = table[key % 5]; b != 0; b = b->next) {
if (b->key == key)
return b;
}
return 0;
}
void * put_phase(void *arg) {
long tid = (long) arg;
int key = 0;
for (key = tid ; key < 100000; key += num_threads) {
insert(key, tid);
}
pthread_exit(0);
}
void * get_phase(void *arg) {
long tid = (long) arg;
int key = 0;
long lost = 0;
for (key = tid ; key < 100000; key += num_threads) {
if (retrieve(key) == 0) lost++;
}
printf("[thread %ld] %ld keys lost!\\n", tid, lost);
pthread_exit((void *)lost);
}
int main(int argc, char **argv) {
long i;
pthread_t *threads;
double start, end;
if (argc != 2) {
panic("usage: ./parallel_hashtable <num_threads>");
}
if ((num_threads = atoi(argv[1])) <= 0) {
panic("must enter a valid number of threads to run");
}
srandom(time(0));
for (i = 0; i < 100000; i++)
keys[i] = random();
threads = (pthread_t *) malloc(sizeof(pthread_t)*num_threads);
if (!threads) {
panic("out of memory allocating thread handles");
}
start = now();
for (i = 0; i < num_threads; i++) {
pthread_create(&threads[i], 0, put_phase, (void *)i);
}
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], 0);
}
end = now();
printf("[main] Inserted %d keys in %f seconds\\n", 100000, end - start);
memset(threads, 0, sizeof(pthread_t)*num_threads);
start = now();
for (i = 0; i < num_threads; i++) {
pthread_create(&threads[i], 0, get_phase, (void *)i);
}
long total_lost = 0;
long *lost_keys = (long *) malloc(sizeof(long) * num_threads);
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], (void **)&lost_keys[i]);
total_lost += lost_keys[i];
}
end = now();
printf("[main] Retrieved %ld/%d keys in %f seconds\\n", 100000 - total_lost, 100000, end - start);
return 0;
}
| 0
|
#include <pthread.h>
int init(void);
int transmit(int,char*,char*);
void* receive(void*);
pthread_mutex_t count_mutex;
int init()
{
int uart0_filestream = -1;
uart0_filestream = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
if (uart0_filestream == -1)
{
printf("Error: Unable to open UART\\n");
return -1;
}
else
{
printf("Successfully opened UART port\\n");
struct termios options;
tcgetattr(uart0_filestream, &options);
options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
options.c_iflag = IGNPAR;
options.c_oflag = 0;
options.c_lflag = 0;
tcflush(uart0_filestream, TCIFLUSH);
tcsetattr(uart0_filestream, TCSANOW, &options);
return uart0_filestream;
}
}
int transmit(int serial, char* buffer_base, char* p_buffer)
{
int count = write(serial, buffer_base, (p_buffer - buffer_base));
if(count < 0)
{
printf("Transmit Error\\n");
return -1;
}
return 0;
}
void* receive(void* arg)
{
int serial = *((int*)arg);
free(arg);
if(serial != -1)
{
unsigned char rx_buffer[256];
int i;
for(i = 0; i < 256; i++)
rx_buffer[i] = 0;
int rx_length = 0;
while(1)
{
rx_length = read(serial, (void*) rx_buffer, 256 - 1);
if(rx_length > 0)
{
rx_buffer[rx_length] = '\\0';
pthread_mutex_lock(&count_mutex);
printf("%s", rx_buffer);
if(rx_buffer[rx_length-1] == 0x0D)
printf("\\nCommand:");
fflush(stdout);
pthread_mutex_unlock(&count_mutex);
bzero(&rx_buffer, 256);
}
}
}
}
int main()
{
int i, serial = init();
int *arg = malloc(sizeof(*arg));
*arg = serial;
pthread_t recv_t, tran_t;
if(pthread_create(&recv_t, 0, receive,(void*)arg) != 0)
{
printf("Failed to create thread");
return -1;
}
unsigned char tx_buffer[20], c;
unsigned char *p_tx_buffer_cur, *p_tx_buffer_base;
for(i = 0; i < 20; i++)
tx_buffer[i] = 0;
p_tx_buffer_base = &tx_buffer[0];
p_tx_buffer_cur = p_tx_buffer_base;
printf("Command:");
while((c = getchar()) != 'q')
{
if((c != 0x00))
{
if(c != '\\n')
*p_tx_buffer_cur++ = c;
if(c == '\\n' && (p_tx_buffer_cur != p_tx_buffer_base))
{
*p_tx_buffer_cur++ = 0x0D;
transmit(serial, p_tx_buffer_base, p_tx_buffer_cur);
bzero(p_tx_buffer_base, (p_tx_buffer_cur - p_tx_buffer_base));
p_tx_buffer_cur = &tx_buffer[0];
}
}
}
printf("Closing serial...");
close(serial);
printf("closed\\n");
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t socketMutex;
static pthread_mutex_t strBufMutex;
static sem_t signaller;
static sem_t socketListSemaphore;
static int* socketList;
static char* buffer;
static size_t strBufLen;
static size_t socketListCursor = 0;
static volatile int interrupted = 0;
static int init(size_t maxSocketCount, size_t buflen){
strBufLen = buflen;
socketList = malloc(maxSocketCount * sizeof(int));
buffer = malloc(buflen*sizeof(char));
if (buffer == 0 || socketList == 0){
printf("One or both of the buffers could not be created. Process cannot continue\\n");
return 1;
}
int retCode;
pthread_mutexattr_t attr;
retCode = pthread_mutexattr_init(&attr);
if (retCode != 0){
printf("Failed to initialize mutex atrributes. Errorcode: %d (%s)\\n", retCode, strerror(retCode));
return 1;
}
retCode = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
if (retCode != 0){
printf("Failed to change mutex attributes. Errorcode: %d (%s)\\n", retCode, strerror(retCode));
return 1;
}
retCode = pthread_mutex_init(&socketMutex, &attr);
if (retCode != 0){
printf("Failed to initialize mutex. Errorcode: %d (%s)\\n", retCode, strerror(retCode));
return 1;
}
retCode = pthread_mutex_init(&strBufMutex, &attr);
if (retCode != 0){
printf("Failed to initialize mutex. Errorcode: %d (%s)\\n", retCode, strerror(retCode));
return 1;
}
if (sem_init(&signaller, 0, 0) == -1){
printf("Failed to initialize semaphore. Errorcode: %d (%s)\\n", errno, strerror(errno));
return 1;
}
if (sem_init(&socketListSemaphore, 0, maxSocketCount) == -1){
printf("Failed to initialize semaphore. Errorcode: %d (%s)\\n", errno, strerror(errno));
return 1;
}
return 0;
}
void* socketDistributorMain(void* socketParamSet){
struct SocketParamSet* param = (struct SocketParamSet*) socketParamSet;
if (init(param->maxConnCount, param->buflen) != 0){
sem_post(¶m->errorNotifier);
sem_post(¶m->initCompleteNotifier);
pthread_exit((void*)1);
}
sem_post(¶m->initCompleteNotifier);
while(!interrupted){
if (sem_wait(&signaller) == -1 && errno == EINTR) continue;
pthread_mutex_lock(&strBufMutex);
pthread_mutex_lock(&socketMutex);
for (size_t i = 0; i < socketListCursor; ++i){
int acc_con = socketList[i];
ssize_t writelen = write(acc_con, buffer, strlen(buffer));
if (writelen == -1){
if (errno == EPIPE){
memmove(&socketList[i], &socketList[i+1], (socketListCursor - i - 1)*sizeof(int));
socketListCursor--;
sem_post(&socketListSemaphore);
i--;
} else {
printf("Error while processing pipes: %d (%s)\\n", errno, strerror(errno));
}
}
}
pthread_mutex_unlock(&socketMutex);
pthread_mutex_unlock(&strBufMutex);
}
return 0;
}
int addSocket(int acc_con){
if (sem_trywait(&socketListSemaphore) == -1){
if (errno != EAGAIN){
return -1;
}
return 0;
}
int retcode = pthread_mutex_lock(&socketMutex);
if (retcode){
printf("Failed to set mutex: %d (%s)", retcode, strerror(retcode));
return -1;
}
socketList[socketListCursor++] = acc_con;
retcode = pthread_mutex_unlock(&socketMutex);
if (retcode){
printf("Failed to set mutex: %d (%s)", retcode, strerror(retcode));
return -1;
}
if (sem_getvalue(&socketListSemaphore, &retcode)){
return -1;
}
return retcode;
}
void waitForSocketSpace(void){
sem_wait(&socketListSemaphore);
sem_post(&socketListSemaphore);
}
int distributeMessageToSockets(char* mes){
int retcode = pthread_mutex_lock(&strBufMutex);
if (retcode != 0){
return retcode;
}
size_t stringLength = strlen(mes);
if (stringLength >= strBufLen){
memcpy(buffer, mes, strBufLen*sizeof(char)-1);
buffer[strBufLen - 1] = 0;
} else {
memcpy(buffer, mes, stringLength);
}
sem_post(&signaller);
retcode = pthread_mutex_unlock(&strBufMutex);
if (retcode != 0){
return retcode;
}
return 0;
}
void stopSocketDistributor(void){
interrupted = 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t no_wait, no_acc, counter;
int no_of_readers=0;
void reader(void *arg)
{
int id=*((int*)arg);
printf("reader %d started\\n", id);
while(1)
{
sleep(rand()%4);
check_and_wait(id);
read(id);
}
}
void writer(void* arg)
{
int id=*((int*)arg);
printf("writer %d started\\n", id);
while(1)
{
sleep(rand()%5);
check_and_wait_if_busy(id);
write(id);
}
}
void check_and_wait_if_busy(int id)
{
if(pthread_mutex_trylock(&no_wait)!=0){
printf("Writer %d Waiting\\n", id);
pthread_mutex_lock(&no_wait);
}
}
void check_and_wait(int id)
{
if(pthread_mutex_trylock(&no_wait)!=0){
printf("Reader %d Waiting\\n", id);
pthread_mutex_lock(&no_wait);
}
}
void read(int id)
{
pthread_mutex_lock(&counter);
no_of_readers++;
pthread_mutex_unlock(&counter);
if(no_of_readers==1)
pthread_mutex_lock(&no_acc);
pthread_mutex_unlock(&no_wait);
printf("reader %d reading...\\n", id);
sleep(rand()%5);
printf("reader %d finished reading\\n", id);
pthread_mutex_lock(&counter);
no_of_readers--;
pthread_mutex_unlock(&counter);
if(no_of_readers==0)
pthread_mutex_unlock(&no_acc);
}
void write(int id)
{
pthread_mutex_lock(&no_acc);
pthread_mutex_unlock(&no_wait);
printf("Writer %d writing...\\n", id);
sleep(rand()%4+2);
printf("Writer %d finished writing\\n", id);
pthread_mutex_unlock(&no_acc);
}
int main(int argc, char* argv[])
{
pthread_t R[5],W[5];
int ids[5];
for(int i=0; i<5; i++)
{
ids[i]=i+1;
pthread_create(&R[i], 0, (void*)&reader, (void*)&ids[i]);
pthread_create(&W[i], 0, (void*)&writer, (void*)&ids[i]);
}
pthread_join(R[0], 0);
exit(0);
}
| 1
|
#include <pthread.h>
int quitflags;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *thr_fun(void *arg);
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask);
if(err != 0)
err_quit("SIG_BLOCK error: %s\\n", strerror(err));
err = pthread_create(&tid, 0, thr_fun, 0);
if(err != 0)
err_quit("can't create thread: %s\\n", strerror(err));
pthread_mutex_lock(&lock);
while(quitflags == 0)
pthread_cond_wait(&wait, &lock);
pthread_mutex_unlock(&lock);
quitflags = 0;
if(sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
void *thr_fun(void *arg)
{
int err, signo;
for(; ;)
{
err = sigwait(&mask, &signo);
if(err != 0)
err_quit("sigwait error: %s\\n", strerror(err));
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflags = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
| 0
|
#include <pthread.h>
static pthread_t sp_tid;
static int is_joined = 1;
static int is_running = 0;
struct sp_params {
sigset_t sigmask;
func_t processor;
int copied;
pthread_mutex_t mutex;
pthread_cond_t cond;
};
static void
cleanup_sp_thread (void * arg)
{
extern int is_running;
is_running = 0;
}
static void
sp_thread (struct sp_params * params)
{
sigset_t sigmask = params->sigmask;
func_t processor = params->processor;
int error, signal;
pthread_mutex_lock(¶ms->mutex);
params->copied = 1;
is_running = 1;
pthread_cond_signal(¶ms->cond);
pthread_mutex_unlock(¶ms->mutex);
pthread_cleanup_push(&cleanup_sp_thread, 0);
for (;;) {
if ((error = sigwait(&sigmask, &signal))) {
PRINT_ERROR_ERRNO("sigwait", error);
abort();
}
processor(signal);
}
pthread_cleanup_pop(0);
}
extern void
start_sp_thread (sigset_t sigmask, void
(*processor)(int), int detach_thread)
{
pthread_attr_t attr;
int error;
struct sp_params params = {
.mutex = PTHREAD_MUTEX_INITIALIZER,
.cond = PTHREAD_COND_INITIALIZER,
.copied = 0
};
params.sigmask = sigmask;
params.processor = processor;
if ((error = pthread_attr_init(&attr))) {
PRINT_ERROR_ERRNO("pthread_attr_init", error);
abort();
}
if (detach_thread) {
error = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (error) {
PRINT_ERROR_ERRNO("pthread_attr_setdetachstate", error);
abort();
}
}
error = pthread_sigmask(SIG_SETMASK, ¶ms.sigmask, 0);
if (error) {
PRINT_ERROR_ERRNO("pthread_sigmask", error);
abort();
}
error = pthread_create(&sp_tid, &attr, (void * (*)(void *))&sp_thread,
(void *)¶ms);
if (error) {
PRINT_ERROR_ERRNO("pthread_create", error);
abort();
}
pthread_mutex_lock(¶ms.mutex);
while (!params.copied) pthread_cond_wait(¶ms.cond, ¶ms.mutex);
pthread_mutex_unlock(¶ms.mutex);
pthread_mutex_destroy(¶ms.mutex);
pthread_cond_destroy(¶ms.cond);
if (!detach_thread) {
is_joined = 0;
}
}
extern void
stop_sp_thread (void)
{
extern pthread_t sp_tid;
extern int is_joined;
extern int is_running;
void * return_value;
if (is_running) pthread_cancel(sp_tid);
if (!is_joined) pthread_join(sp_tid, &return_value);
is_joined = 1;
}
extern void
clear_sigmask (void)
{
sigset_t sigmask;
sigemptyset(&sigmask);
sigprocmask(SIG_SETMASK, &sigmask, 0);
}
| 1
|
#include <pthread.h>
int num;
unsigned long total;
int flag;
pthread_mutex_t m;
pthread_cond_t empty, full;
void *thread1(void *arg)
{
int i;
i = 0;
while (i < 3){
pthread_mutex_lock(&m);
while (num > 0)
pthread_cond_wait(&empty, &m);
num++;
printf ("produce ....%d\\n", i);
pthread_mutex_unlock(&m);
pthread_cond_signal(&full);
i++;
}
}
void *thread2(void *arg)
{
int j;
j = 0;
while (j < 3){
pthread_mutex_lock(&m);
while (num == 0)
pthread_cond_wait(&full, &m);
total=total+j;
printf("total ....%ld\\n",total);
num--;
printf("consume ....%d\\n",j);
pthread_mutex_unlock(&m);
pthread_cond_signal(&empty);
j++;
}
total=total+j;
printf("total ....%ld\\n",total);
flag=1;
}
int main(void)
{
pthread_t t1, t2;
num = 0;
total = 0;
pthread_mutex_init(&m, 0);
pthread_cond_init(&empty, 0);
pthread_cond_init(&full, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
if (flag)
assert(total!=((3*(3 +1))/2));
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
extern int __VERIFIER_nondet_int();
int idx=0;
int ctr1=1, ctr2=0;
int readerprogress1=0, readerprogress2=0;
pthread_mutex_t mutex;
void __VERIFIER_atomic_use1(int myidx) {
__VERIFIER_assume(myidx <= 0 && ctr1>0);
ctr1++;
}
void __VERIFIER_atomic_use2(int myidx) {
__VERIFIER_assume(myidx >= 1 && ctr2>0);
ctr2++;
}
void __VERIFIER_atomic_use_done(int myidx) {
if (myidx <= 0) { ctr1--; }
else { ctr2--; }
}
void __VERIFIER_atomic_take_snapshot(int readerstart1, int readerstart2) {
readerstart1 = readerprogress1;
readerstart2 = readerprogress2;
}
void __VERIFIER_atomic_check_progress1(int readerstart1) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void __VERIFIER_atomic_check_progress2(int readerstart2) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void *qrcu_reader1() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress1 = 1;
readerprogress1 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void *qrcu_reader2() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress2 = 1;
readerprogress2 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void* qrcu_updater() {
int i;
int readerstart1, readerstart2;
int sum;
__VERIFIER_atomic_take_snapshot(readerstart1, readerstart2);
if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; };
if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; }
else {}
if (sum > 1) {
pthread_mutex_lock(&mutex);
if (idx <= 0) { ctr2++; idx = 1; ctr1--; }
else { ctr1++; idx = 0; ctr2--; }
if (idx <= 0) { while (ctr1 > 0); }
else { while (ctr2 > 0); }
pthread_mutex_unlock(&mutex);
} else {}
__VERIFIER_atomic_check_progress1(readerstart1);
__VERIFIER_atomic_check_progress2(readerstart2);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, 0);
pthread_create(&t1, 0, qrcu_reader1, 0);
pthread_create(&t2, 0, qrcu_reader2, 0);
pthread_create(&t3, 0, qrcu_updater, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
{
int first;
int last;
int validItems;
char* data[40];
pthread_mutex_t lock;
} circularQueue_t;
void mvos_webToolsInitializeQueue(circularQueue_t *theQueue);
int mvos_webToolsIsEmpty(circularQueue_t *theQueue);
int mvos_webToolsPutItem(circularQueue_t *theQueue, const char* theItemValue);
int mvos_webToolsGetItem(circularQueue_t *theQueue, char **theItemValue);
void mvos_webToolsPrintQueue(circularQueue_t *theQueue);
void mvos_webToolsRemoveQueue(circularQueue_t *theQueue);
int main(void) {
puts("!!!Hello World!!!");
circularQueue_t circular_log;
int i;
char line[256] = {0};
mvos_webToolsInitializeQueue(&circular_log);
for(i=0; i < 10000; i++)
{
snprintf(line, 256, "Ala ma kota to jest testowy [log][mineva]:123 %s - %s, %d", "circular_log.c", __FUNCTION__, i);
if (-1 != mvos_webToolsPutItem(&circular_log, line))
{
mvos_webToolsPrintQueue(&circular_log);
}
else
{
printf("Failed %d\\n", i);
}
usleep(250000);
}
return 0;
}
void mvos_webToolsRemoveQueue(circularQueue_t *theQueue)
{
int i;
pthread_mutex_lock(&theQueue->lock);
theQueue->validItems = 0;
theQueue->first = 0;
theQueue->last = 0;
for(i=0; i<40; i++)
{
free(theQueue->data[i]);
}
pthread_mutex_unlock(&theQueue->lock);
}
void mvos_webToolsInitializeQueue(circularQueue_t *theQueue)
{
int i;
if (pthread_mutex_init(&theQueue->lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return;
}
pthread_mutex_lock(&theQueue->lock);
theQueue->validItems = 0;
theQueue->first = 0;
theQueue->last = 0;
for(i=0; i<40; i++)
{
theQueue->data[i] = malloc(sizeof(char)*256);
if( theQueue->data[i] == 0 )
{
printf("ERROR alocating memory for %d item\\n", i);
mvos_webToolsRemoveQueue(theQueue);
break;
}
}
pthread_mutex_unlock(&theQueue->lock);
return;
}
int mvos_webToolsIsEmpty(circularQueue_t *theQueue)
{
int ret = 0;
pthread_mutex_lock(&theQueue->lock);
if(theQueue->validItems==0)
ret = 1;
pthread_mutex_unlock(&theQueue->lock);
return ret;
}
int mvos_webToolsPutItem(circularQueue_t *theQueue, const char* theItemValue)
{
pthread_mutex_lock(&theQueue->lock);
if(theQueue->validItems >= 40)
{
theQueue->first = (theQueue->first+1)%40;
}
else
{
theQueue->validItems++;
}
strncpy(theQueue->data[theQueue->last], theItemValue, 256);
theQueue->last = (theQueue->last+1)%40;
pthread_mutex_unlock(&theQueue->lock);
return 0;
}
int mvos_webToolsGetItem(circularQueue_t *theQueue, char **theItemValue)
{
int ret = -1;
pthread_mutex_lock(&theQueue->lock);
if(mvos_webToolsIsEmpty(theQueue))
{
ret = (-1);
}
else
{
*theItemValue = theQueue->data[theQueue->first];
theQueue->first=(theQueue->first+1)%40;
theQueue->validItems--;
ret = 0;
}
pthread_mutex_unlock(&theQueue->lock);
return ret;
}
void mvos_webToolsPrintQueue(circularQueue_t *theQueue)
{
int aux, aux1;
pthread_mutex_lock(&theQueue->lock);
aux = theQueue->first;
aux1 = theQueue->validItems;
printf("\\n-----\\nBuffer size %d, item list:\\n", theQueue->validItems);
while(aux1>0)
{
aux=(aux+1)%40;
aux1--;
}
pthread_mutex_unlock(&theQueue->lock);
return;
}
| 0
|
#include <pthread.h>
void *iniciarTesteEnlace() {
int te, tr;
pthread_t threadEnviarDatagramas, threadReceberDatagramas;
te = pthread_create(&threadEnviarDatagramas, 0, enviarDatagramas, 0);
if (te) {
printf("ERRO: impossivel criar a thread : enviarDatagramas\\n");
exit(-1);
}
tr = pthread_create(&threadReceberDatagramas, 0, receberDatagramas, 0);
if (tr) {
printf("ERRO: impossivel criar a thread : receberDatagramas\\n");
exit(-1);
}
pthread_join(threadEnviarDatagramas, 0);
pthread_join(threadReceberDatagramas, 0);
}
void *enviarDatagramas() {
char charopt[128];
while (1) {
pthread_mutex_lock(&mutex_env1);
usleep(300);
fpurge(stdin);
fflush(stdin);
pthread_mutex_lock(&mutex_env3);
if (shm_env.tam_buffer != 0) {
printf("Teste_enlace.c (Enviar - Retorno) = > Type: '%d', Num nó: '%d', Data: '%s', Tamanho : '%d'\\n", shm_env.type, shm_env.env_no, shm_env.buffer, shm_env.tam_buffer);
if (shm_env.erro == 0) {
printf("Teste_enlace.c (Enviar - Retorno) = > OK\\n\\n");
} else if (shm_env.erro == -1) {
printf("Teste_enlace.c (Enviar - Retorno) = > Não há ligacao do nó: '%d'!\\n\\n", shm_env.env_no);
} else if (shm_env.erro > 0) {
printf("Teste_enlace.c (Enviar - Retorno) = > MTU excedido dividir o pacote no MAX em '%d' bytes\\n\\n", shm_env.erro);
} else
printf("Teste_enlace.c (Enviar - Retorno) = > Erro desconhecido\\n\\n");
shm_env.tam_buffer = 0;
shm_env.env_no = 0;
strcpy(shm_env.buffer, "");
shm_env.erro = 0;
}
printf("Teste_enlace.c (Enviar) = > Digite o Conteudo de data: ");
fgets(charopt, 127, stdin);
charopt[strlen(charopt) - 1] = '\\0';
strcpy(shm_env.buffer, charopt);
shm_env.type = 2;
shm_env.tam_buffer = strlen(shm_env.buffer);
shm_env.env_no = 2;
pthread_mutex_unlock(&mutex_env3);
pthread_mutex_unlock(&mutex_env2);
}
}
void *receberDatagramas() {
while (TRUE) {
pthread_mutex_lock(&mutex_rcv2);
pthread_mutex_lock(&mutex_rcv3);
if (shm_rcv.tam_buffer != 0) {
printf("Teste_enlace.c (Receber) = > Type: '%d', Tam_buffer: '%d' Bytes, Buffer: '%s'\\n", shm_rcv.type, shm_rcv.tam_buffer,
shm_rcv.buffer);
shm_rcv.erro = -1;
}
pthread_mutex_unlock(&mutex_rcv3);
pthread_mutex_unlock(&mutex_rcv1);
}
}
| 1
|
#include <pthread.h>
int count;
pthread_mutex_t cont_mutex= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
void *inc_thread (void *data)
{
while(1)
{
pthread_mutex_lock (&cont_mutex);
pthread_mutex_lock (&cont_mutex);
count++;
printf("Inc: %d\\n", count);
pthread_mutex_unlock (&cont_mutex);
pthread_mutex_unlock (&cont_mutex);
}
}
void *dec_thread (void *data)
{
while(1)
{
pthread_mutex_lock (&cont_mutex);
pthread_mutex_lock (&cont_mutex);
count--;
printf("Dec: %d\\n", count);
pthread_mutex_unlock (&cont_mutex);
pthread_mutex_unlock (&cont_mutex);
}
}
int main()
{
pthread_t inc_tid, dec_tid;
pthread_create(&inc_tid, 0, inc_thread, 0);
pthread_create(&dec_tid, 0, dec_thread, 0);
pthread_join(inc_tid,0);
pthread_join(dec_tid,0);
pthread_mutex_destroy (&cont_mutex);
return 0;
}
| 0
|
#include <pthread.h>
void *sender_threads(void *arg) {
unsigned char *packet;
int len;
int id, pid;
id = *((int *) arg);
for (;;) {
sem_wait(&sem_queue);
pthread_mutex_lock (&lock_queue);
packet = dequeue(&p_queue, &len, &pid);
pthread_mutex_unlock (&lock_queue);
usleep(UDELAY);
pthread_mutex_lock (&lock_qh);
nfq_set_verdict(qh, pid, NF_ACCEPT, len, packet);
pthread_mutex_unlock (&lock_qh);
}
}
int send_packet(int rawsock, unsigned char *packet, int len) {
int i;
struct ip *iph = (struct ip *) packet;
struct tcphdr *tcph = (struct tcphdr *) ( packet + sizeof(struct ip) );
struct sockaddr_in dsin;
dsin.sin_family = AF_INET;
dsin.sin_port = ntohs(tcph->th_dport);
dsin.sin_addr.s_addr = iph->ip_dst.s_addr;
i=sendto(rawsock, packet, len, 0, (struct sockaddr *) &dsin, sizeof (dsin));
if ( i == -1 ) {
fprintf(stderr, "sending to %s failed!\\n", inet_ntoa(dsin.sin_addr));
} else {
printf("Outgoing packet: \\n");
printf("%u bytes sent to %s \\n", i, inet_ntoa(dsin.sin_addr));
fprintf(stderr, "Src IP: %s ==>", inet_ntoa(iph->ip_src));
fprintf(stderr, "Dst IP: %s\\n", inet_ntoa(iph->ip_dst));
fprintf(stderr, "Src port: %d ==>", ntohs(tcph->th_sport));
fprintf(stderr, "Dst port: %d\\n\\n", dsin.sin_port);
fflush(stderr);
}
return i;
}
| 1
|
#include <pthread.h>
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex;
int storage = 0;
int finish = 0;
void* consumer(void* arg)
{
printf("Consumer[%x] thread started\\n", pthread_self());
while(1)
{
pthread_mutex_lock(&mutex);
while(storage < 100)
pthread_cond_wait(&condition, &mutex);
printf("Consumer[%x] storage at max, consuming %d\\n", pthread_self(), 95);
storage -= 95;
printf("Consumer[%x] storage = %d\\n", pthread_self(), storage);
finish++;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* producer(void* arg)
{
printf("Producer thread started\\n");
while(1)
{
if (finish == 5)
{
printf("[+]All consumers recieved their data\\n");
exit(0);
}
usleep(50000);
pthread_mutex_lock(&mutex);
storage += 25;
printf("Storage = %d\\n", storage);
if (storage >= 100)
{
printf("Producer storage max\\n");
pthread_cond_signal(&condition);
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(void)
{
int i;
pthread_t producer_tid;
pthread_t consumer_tid[5];
if (pthread_create(&producer_tid, 0, producer, 0) != 0)
printf("[-]Can't create producer thread\\n");
for (i = 0; i < 5; i++)
if (pthread_create(&consumer_tid[i], 0, consumer, 0) != 0)
printf("[-]Can't create consumer[%d] thread\\n", i);
pthread_join(producer_tid, 0);
for (i = 0; i < 5; i++)
pthread_join(consumer_tid[i], 0);
return 0;
}
| 0
|
#include <pthread.h>
struct video_listener *listener = 0;
void bepoppy8_init() {
listener = cv_add_to_device(&front_camera, vision_func);
STARTED = 0;
NumWindows = 5;
ForwardShift = 1.0;
FOV = 100.0;
WindowAngle = FOV/NumWindows;
windowThreshold = 30;
pthread_mutex_init(&navWindow_mutex,0);
}
void bepoppy8_periodic() {
if (STARTED) {
pthread_mutex_lock(&navWindow_mutex);
{
HeadingDeflection = NavWindow*WindowAngle*M_PI/180;
NavWindow = 0;
}
pthread_mutex_unlock(&navWindow_mutex);
bepoppy8_AdjustWaypointBearing(WP_GOAL, ForwardShift, HeadingDeflection);
}
}
void bepoppy8_logTelemetry(char* msg, int nb_msg) {
DOWNLINK_SEND_INFO_MSG(DefaultChannel, DefaultDevice, nb_msg, msg);
printf("%s", msg);
}
void bepoppy8_start(uint8_t waypoint){
STARTED = 1;
}
void bepoppy8_stop() {
STARTED = 0;
}
void bepoppy8_moveWaypointBy(uint8_t waypoint, struct EnuCoor_i *shift){
struct EnuCoor_i new_coor;
struct EnuCoor_i *pos = stateGetPositionEnu_i();
new_coor.x = pos->x + shift->x;
new_coor.y = pos->y + shift->y;
coordinateTurn(shift);
waypoint_set_xy_i(waypoint, new_coor.x, new_coor.y);
}
void bepoppy8_moveWaypointForward(uint8_t waypoint, float distance){
struct EnuCoor_i shift;
struct Int32Eulers *eulerAngles = stateGetNedToBodyEulers_i();
float sin_heading = sinf(ANGLE_FLOAT_OF_BFP(eulerAngles->psi));
float cos_heading = cosf(ANGLE_FLOAT_OF_BFP(eulerAngles->psi));
shift.x = POS_BFP_OF_REAL(sin_heading * distance);
shift.y = POS_BFP_OF_REAL(cos_heading * distance);
bepoppy8_moveWaypointBy(waypoint, &shift);
}
void bepoppy8_resetWaypoint(uint8_t waypoint){
bepoppy8_moveWaypointForward(waypoint, 0.5);
}
void bepoppy8_AdjustWaypointBearing(uint8_t waypoint, float distance, float HeadingDefl){
struct EnuCoor_i shift;
struct Int32Eulers *eulerAngles = stateGetNedToBodyEulers_i();
float sin_heading = sinf(ANGLE_FLOAT_OF_BFP(eulerAngles->psi) + HeadingDefl);
float cos_heading = cosf(ANGLE_FLOAT_OF_BFP(eulerAngles->psi) + HeadingDefl);
shift.x = POS_BFP_OF_REAL(sin_heading*distance);
shift.y = POS_BFP_OF_REAL(cos_heading*distance);
bepoppy8_moveWaypointBy(waypoint, &shift);
}
void coordinateTurn(struct EnuCoor_i *shift){
float heading_f = atan2f(POS_FLOAT_OF_BFP(shift->x), POS_FLOAT_OF_BFP(shift->y));
nav_heading = ANGLE_BFP_OF_REAL(heading_f);
}
uint8_t increase_nav_heading(int32_t *heading, float incrementDegrees){
struct Int32Eulers *eulerAngles = stateGetNedToBodyEulers_i();
int32_t newHeading = eulerAngles->psi + ANGLE_BFP_OF_REAL( incrementDegrees / 180.0 * M_PI);
INT32_ANGLE_NORMALIZE(newHeading);
*heading = newHeading;
return 0;
}
| 1
|
#include <pthread.h>
int sem_getvalue(sem_t *restrict sem, int *restrict sval)
{
int result = 0;
if (!sem || !sval)
{
result = EINVAL;
}
else if (!pthread_mutex_lock(&sem->mutex))
{
*sval = sem->value;
pthread_mutex_unlock(&sem->mutex);
}
else
{
result = EINVAL;
}
if (result)
{
errno = result;
return -1;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t verrou = PTHREAD_MUTEX_INITIALIZER;
struct data {
int *Tab1;
int *Tab2;
int *Resultat;
int taille;
int i;
};
void * Som(void * par){
int *somme=(int *)malloc(sizeof(int));
pthread_t moi = pthread_self();
struct data *mon_D1 = (struct data*)par;
printf("Je suis le thread %lu, je fais la somme\\n",moi);
pthread_mutex_lock(&verrou);
printf("J'ai verrouillé 1er fois \\n");
while( ((*mon_D1).i)!=(*mon_D1).taille ){
pthread_mutex_unlock(&verrou);
pthread_mutex_lock(&verrou);
}
printf("Tous les calculs ont été fait je peux commencer la somme\\n");
for(int z=0; z<(*mon_D1).taille;z++){
*somme=*somme+(*mon_D1).Resultat[z];
}
pthread_mutex_unlock(&verrou);
pthread_exit(somme);
}
void * Mul(void * par){
pthread_t moi = pthread_self();
int resultat;
struct data *mon_D1 = (struct data*)par;
pthread_mutex_lock(&verrou);
resultat=(*mon_D1).Tab1[(*mon_D1).i] * (*mon_D1).Tab2[(*mon_D1).i] ;
(*mon_D1).Resultat[(*mon_D1).i]=resultat;
(*mon_D1).i++;
pthread_mutex_unlock(&verrou);
pthread_exit(0);
}
int main(){
float temps;
clock_t t1, t2;
t1 = clock();
FILE * fp;
fp = fopen ("file.txt", "r");
int taille=0;
int somme=5;
printf("Entrez la taille de vos vecteurs\\n");
fscanf(fp, "%d",&taille);
int *T1=malloc(sizeof(int)*taille), *T2=malloc(sizeof(int)*taille), *T3=malloc(sizeof(int)*taille);
printf("Entrez la valeur du premier vecteur\\n");
for(int i=0;i<taille;i++){
fscanf(fp, "%d",&T1[i]);
}
printf("Entrez la valeur du deuxieme vecteur\\n");
for(int i=0;i<taille;i++){
fscanf(fp, "%d",&T2[i]);
}
struct data D1; D1.Tab1=T1; D1.Tab2=T2; D1.Resultat=T3; D1.taille=taille; D1.i=0;
pthread_t ThreadDeSomme; pthread_create(&ThreadDeSomme,0,Som,&D1);
pthread_t *TabDeThread = malloc(taille*sizeof(pthread_t));
for(int i=0;i<taille;i++){
pthread_create(&(TabDeThread[i]),0,Mul,&D1);
}
for(int i=0;i<taille;i++){
pthread_join(TabDeThread[i],0);
}
void *vptr_return;
pthread_join(ThreadDeSomme,&vptr_return);
somme= *((int *)vptr_return);
printf("La somme des vecteurs : V1(");
for(int i=0;i<taille-1;i++){
printf("%i,",T1[i]);
}
printf("%i) et V2(",T1[taille-1]);
for(int i=0;i<taille-1;i++){
printf("%i,",T2[i]);
}
printf("%i) a pour resultat : %i\\n",T2[taille-1], somme);
t2 = clock();
temps = (float)(t2-t1)/CLOCKS_PER_SEC;
printf("Calul fait en temps = %f\\n", temps);
return 0;
}
| 1
|
#include <pthread.h>
int listenfd;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void web_child(int i, int sockfd)
{
int ntowrite, nread;
char line[64], result[16384];
memset(line, 0, 64);
for ( ; ; )
{
if ((nread = read(sockfd, line, 64 - 1)) == 0)
{
printf("thread %d receive read = 0\\n", i);
return;
}
ntowrite = atoi(line);
printf("thread %d write %d bytes\\n", i, ntowrite);
write(sockfd, result, ntowrite);
}
}
sighandler_t Signal(int signo, sighandler_t handler)
{
struct sigaction act, oact;
sigset_t set;
sigemptyset(&set);
act.sa_handler = handler;
act.sa_flags = 0;
act.sa_flags |= SA_RESTART;
act.sa_mask = set;
if (sigaction(signo, &act, &oact) < 0)
{
perror("sigaction error");
exit(1);
}
return oact.sa_handler;
}
void pr_cpu_time(void)
{
double user, sys;
struct rusage myusage, childusage;
if (getrusage(RUSAGE_SELF, &myusage) < 0)
{
perror("getrusage error");
exit(1);
}
if (getrusage(RUSAGE_CHILDREN, &childusage) < 0)
{
perror("getrusage error");
exit(1);
}
user = (double) myusage.ru_utime.tv_sec +
myusage.ru_utime.tv_usec / 1000000.0;
user += (double) childusage.ru_utime.tv_sec +
childusage.ru_utime.tv_usec / 1000000.0;
sys = (double) myusage.ru_stime.tv_sec +
myusage.ru_stime.tv_usec / 1000000.0;
sys += (double) childusage.ru_stime.tv_sec +
childusage.ru_stime.tv_usec / 1000000.0;
printf("\\nuser time = %g, sys time = %g\\n", user, sys);
}
void sig_int(int signo)
{
pr_cpu_time();
exit(0);
}
void* thread_main(void *arg)
{
struct sockaddr_in cliaddr;
int clilen, connfd;
pthread_detach(pthread_self());
for ( ; ; )
{
pthread_mutex_lock(&mutex);
connfd = accept(listenfd, (struct sockaddr*)&cliaddr, &clilen);
pthread_mutex_unlock(&mutex);
web_child((int)arg, connfd);
close(connfd);
}
}
void thread_make(int i)
{
pthread_t tid;
pthread_create(&tid, 0, thread_main, (void*)i);
}
int main(int argc, char const *argv[])
{
struct sockaddr_in cliaddr, servaddr;
int connfd;
int clilen, addrlen;
int i, nchildren;
pthread_t tid;
if (argc != 3)
{
exit(1);
}
if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket error");
exit(1);
}
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(atoi(argv[1]));
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
nchildren = atoi(argv[2]);
if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
{
perror("bind error");
exit(1);
}
if (listen(listenfd, 16) < 0)
{
perror("listen error");
exit(1);
}
Signal(SIGINT, sig_int);
for (i = 0; i < nchildren; ++i)
thread_make(i);
for ( ; ; )
pause();
return 0;
}
| 0
|
#include <pthread.h>
extern void init_scheduler(int);
extern int scheduleme(float, int, int, int);
FILE *fd;
struct _thread_info
{
int id;
float arrival_time;
int required_time;
int priority;
};
double _global_time;
float _last_event_time;
pthread_mutex_t _time_lock;
pthread_mutex_t _last_event_lock;
void set_last_event(float last_event)
{
pthread_mutex_lock(&_last_event_lock);
if (last_event > _last_event_time)
_last_event_time = last_event;
pthread_mutex_unlock(&_last_event_lock);
}
float get_global_time()
{
return _global_time;
}
void advance_global_time(float next_arrival)
{
pthread_mutex_lock(&_time_lock);
float next_ms = floor(_global_time + 1.0);
if ((next_arrival < next_ms) && (next_arrival > 0))
_global_time = next_arrival;
else
_global_time = next_ms;
pthread_mutex_unlock(&_time_lock);
}
float read_next_arrival(float *arrival_time, int *id, int *required_time, int *priority)
{
*arrival_time = -1.0;
char c[15];
fscanf(fd, "%f.1", arrival_time);
fgets(c, 1, fd);
fscanf(fd, "%d", id);
fgets(c, 1, fd);
fscanf(fd, "%d", required_time);
fgets(c, 1, fd);
fscanf(fd, "%d", priority);
fgets(c, 10, fd);
return *arrival_time;
}
int open_file(char *filename)
{
char mode = 'r';
fd = fopen(filename, &mode);
if (fd == 0)
{
printf("Invalid input file specified: %s\\n", filename);
return -1;
}
else
{
return 0;
}
}
void close_file()
{
fclose(fd);
}
void *worker_thread(void *arg)
{
_thread_info_t *myinfo = (_thread_info_t *)arg;
float time_remaining = myinfo->required_time * 1.0;
float scheduled_time;
set_last_event(myinfo->arrival_time);
scheduled_time = scheduleme(myinfo->arrival_time, myinfo->id, time_remaining, myinfo->priority);
while (time_remaining > 0)
{
set_last_event(scheduled_time);
printf("%3.0f - %3.0f: T%d\\n", scheduled_time, scheduled_time + 1.0, myinfo->id);
while(get_global_time() < scheduled_time + 1.0)
{
sched_yield();
}
time_remaining -= 1.0;
scheduled_time = scheduleme(get_global_time(), myinfo->id, time_remaining, myinfo->priority);
}
free(myinfo);
pthread_exit(0);
}
int _pre_init(int sched_type)
{
pthread_mutex_init(&_time_lock, 0);
pthread_mutex_init(&_last_event_lock, 0);
init_scheduler(sched_type);
_global_time = 0.0;
_last_event_time = -1.0;
}
int main(int argc, char *argv[])
{ argc = 3;
argv[1] = "0";
argv[2] = "input_0";
int inactivity_timeout = 50;
if (argc < 3)
{
printf ("Not enough parameters specified. Usage: a.out <scheduler_type> <input_file>\\n");
printf (" Scheduler type: 0 - First Come, First Served (Non-preemptive)\\n");
printf (" Scheduler type: 1 - Shortest Remaining Time First (Preemptive)\\n");
printf (" Scheduler type: 2 - Priority-based Scheduler (Preemptive)\\n");
printf (" Scheduler type: 3 - Multi-Level Feedback Queue w/ Aging (Preemptive)\\n");
return -1;
}
if (open_file(argv[2]) < 0)
return -1;
_pre_init(atoi(argv[1]));
int this_thread_id = 0;
_thread_info_t *ti;
float next_arrival_time;
pthread_t pt;
ti = (_thread_info_t *)malloc(sizeof(_thread_info_t));
next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority));
if (next_arrival_time < 0)
return -1;
pthread_create(&pt, 0, worker_thread, ti);
while (_last_event_time != ti->arrival_time)
sched_yield();
ti = (_thread_info_t *)malloc(sizeof(_thread_info_t));
next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority));
while ((get_global_time() - _last_event_time) < inactivity_timeout)
{
advance_global_time(next_arrival_time);
if (get_global_time() == next_arrival_time)
{
pthread_create(&pt, 0, worker_thread, ti);
while (_last_event_time < ti->arrival_time)
{
sched_yield();
}
ti = (_thread_info_t *)malloc(sizeof(_thread_info_t));
next_arrival_time = read_next_arrival(&(ti->arrival_time), &(ti->id), &(ti->required_time), &(ti->priority));
if (next_arrival_time < 0)
{
free(ti);
}
}
else
{
int loop_counter = 0;
while ((_last_event_time < get_global_time()) && (loop_counter < 100000))
{
loop_counter++;
sched_yield();
}
}
}
close_file();
return 0;
}
| 1
|
#include <pthread.h>
int start, end, threadID;
} Param;
int isPrime(int x){
if(x<=1){
return 0;
}
for(int i=2;i<x;i++){
if(x%i==0){
return 0;
}
}
printf("%i is prime\\n",x);
return 1;
}
int totalPrimes = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *thread_func(void * paramP){
Param* param = (Param*)paramP;
printf("Thread %i: start = %i, end = %i\\n",param->threadID,param->start, param->end);
int localPrimeCount = 0;
for(int i=param->start;i<=param->end;i++){
if(isPrime(i)){
localPrimeCount++;
}
}
pthread_mutex_lock(&lock);
totalPrimes += localPrimeCount;
pthread_mutex_unlock(&lock);
free(param);
pthread_exit(0);
}
int main(){
int max = 33;
int interval = max / 5;
pthread_t threads[5];
for(int i=0;i<5 -1;i++){
Param* param = (Param*)malloc(sizeof(Param));
param->start = i*interval;
param->end = (i*interval)+interval-1;
param->threadID = i;
pthread_create(&threads[i],0,thread_func,(void*)param);
}
Param* param = (Param*)malloc(sizeof(Param));
param->threadID = 5 -1;
param->start = (5 -1)*interval;
param->end = max;
pthread_create(&threads[5 -1],0,thread_func,(void*)param);
for(int i=0;i<5;i++){
pthread_join(threads[i],0);
}
printf("Total Number of primes = %i\\n",totalPrimes);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.