text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
unsigned long max;
int num_threads;
unsigned long factor = 1;
unsigned char *bitmap = 0;
pthread_mutex_t mutex_bitmap = PTHREAD_MUTEX_INITIALIZER;
void *isPrime(void *arg);
int main(int argc, char *argv[]) {
int i;
num_threads = 50;
max = 200000;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
bitmap = (unsigned char*) calloc(max, 4);
if (bitmap == 0) {
perror("Bit map creation failed");
exit(1);
}
pthread_t threads[num_threads];
for (i = 0; i < num_threads; ++i)
{
if(pthread_create(&threads[i], &attr, isPrime, (void *) i))
{
perror("Error creating thread");
exit(1);
}
}
for (i = 0; i < num_threads; i++)
pthread_join(threads[i], 0);
free(bitmap);
pthread_attr_destroy(&attr);
pthread_exit(0);
}
void *isPrime(void *arg) {
pthread_mutex_lock(&mutex_bitmap);
unsigned long val;
while (factor * factor <= max)
{
factor += 2;
if (!(bitmap[((factor) / 8)] & (1 << ((factor) % 8))))
for (val = 3 * factor; val < max; val += factor << 1)
(bitmap[((val) / 8)] |= (1 << ((val) % 8)));
}
pthread_mutex_unlock(&mutex_bitmap);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare()
{
printf("prepareing locks..\\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent()
{
printf("parent unlocking..\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child()
{
printf("child unlocking..\\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg)
{
printf("thread started..\\n");
pause();
return 0;
}
int main()
{
int err;
pid_t pid;
pthread_t tid;
if((err = pthread_atfork(prepare, parent, child)) != 0)
err_exit(err, "can't install fork handlers");
err = pthread_create(&tid, 0, thr_fn, 0);
if(err != 0)
err_exit(err, " can't create thread");
sleep(2);
printf("parent about to fork ..\\n");
if((pid = fork()) < 0)
err_quit("fork failed");
else if(pid == 0)
printf("child returned from fork\\n");
else
printf("parent returned from fork\\n");
exit(0);
}
| 0
|
#include <pthread.h>
const int NUM_THREADS = 4;
const int N = 1000;
const int CHUNK_SIZE = N/NUM_THREADS;
static double x[N];
static double y[N];
static double z[N];
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
double sum = 0.0;
void *add(void *threadid)
{
long tid;
tid = (long)threadid;
for (int i=tid*CHUNK_SIZE; i<tid*CHUNK_SIZE+CHUNK_SIZE; i++) {
pthread_mutex_lock(&mymutex);
sum += x[i] + y[i];
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (long t=0; t<NUM_THREADS; t++) {
int rc = pthread_create(&threads[t], &attr, add, (void *)t);
if ( rc ) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for (long t=0; t<NUM_THREADS; t++) {
void *status;
int rc = pthread_join(threads[t], &status);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int buffer[10];
int current_position = 0;
int total_generated = 0;
pthread_mutex_t buffer_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t go_calculate = PTHREAD_COND_INITIALIZER;
pthread_cond_t go_generate = PTHREAD_COND_INITIALIZER;
void printArray(int buffer[]) {
int i;
for (i = 0; i < current_position; i++) {
printf("[%d] ", buffer[i]);
}
printf("\\n");
}
void generateNumbers(){
int random_number, cpos;
int random_seed = time(0);
srand(random_seed);
current_position = 0;
while (total_generated < 20) {
random_number = rand() % 10;
pthread_mutex_lock(&(buffer_lock));
printf("[PRINTING] The Array is: ");
buffer[current_position] = random_number;
current_position++;
printArray(buffer);
cpos = current_position;
total_generated++;
if (random_number == 4 || cpos == 10 || total_generated == 20) {
printf("=====[CONDITION MET]=====\\n");
pthread_cond_broadcast(&(go_calculate));
if (total_generated != 20) {
pthread_cond_wait(&(go_generate), &(buffer_lock));
}
}
pthread_mutex_unlock(&(buffer_lock));
}
printf("Done! We got 20 numbers!\\n");
}
void calculateResult (){
int sum = 0;
while (1) {
printf("[WAITING]\\n");
pthread_mutex_lock(&(buffer_lock));
int i;
pthread_cond_wait(&(go_calculate), &(buffer_lock));
for (i = 0; i < current_position; i++) {
sum += buffer[i];
buffer[i] = 0;
}
printf("[Result] The current sum is %d\\n", sum);
current_position = 0;
if (total_generated == 20) {
printf("[DONE]\\n");
pthread_cond_broadcast(&(go_generate));
return;
}
pthread_cond_broadcast(&(go_generate));
pthread_mutex_unlock(&(buffer_lock));
printf("DONE 2\\n");
}
return;
}
int main(int argc, const char *argv[]) {
pthread_t thread1, thread2;
pthread_create(&thread1, 0, (void *) generateNumbers, 0);
pthread_create(&thread2, 0, (void *) calculateResult, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t hilosEncolar[10];
pthread_t hilosDesencolar[10];
int final;
pthread_cond_t llena, vacia;
pthread_mutex_t mutex;
int contenido[100];
} cola_t;
int numeroAleatorio(){
return rand() % 10;
}
void crearCola(cola_t *cola){
cola->final = -1;
pthread_cond_init(&cola->llena, 0);
pthread_cond_init(&cola->vacia, 0);
pthread_mutex_init(&cola->mutex, 0);
}
void desencolar(cola_t *cola, int *frente){
pthread_mutex_lock(&cola->mutex);
if(cola->final == -1){
printf("COLA_VACIA: espero condicion\\n");
pthread_cond_wait(&cola->vacia, &cola->mutex);
}
*frente = cola->contenido[0];
int i;
for(i = 1; i <= cola->final; i++){
cola->contenido[i-1] = cola->contenido[i];
}
cola->final -= 1;
pthread_cond_signal(&cola->llena);
pthread_mutex_unlock(&cola->mutex);
}
void encolar(cola_t *cola, int valor){
pthread_mutex_lock(&cola->mutex);
if(cola->final == 100 - 1){
printf("COLA_LLENA: espero condicion\\n");
pthread_cond_wait(&cola->llena, &cola->mutex);
}
cola->final += 1;
cola->contenido[cola->final] = valor;
pthread_cond_signal(&cola->vacia);
pthread_mutex_unlock(&cola->mutex);
}
void *funcionHiloDesencola(void *cola){
cola_t *q = (cola_t *)cola;
int frente,
corte = 0;
while(corte < 10){
desencolar(q, &frente);
printf("%d\\n", frente);
usleep(50000);
corte++;
}
pthread_exit((void *)0);
}
void *funcionHiloEncola(void *cola){
cola_t *q = (cola_t*)cola;
int corte = 0;
while(corte < 10){
encolar(q, numeroAleatorio());
corte++;
}
pthread_exit((void *)0);
}
int main(void){
cola_t q;
int i,
retval;
crearCola(&q);
srand(getpid());
for(i = 0; i < 10; i++){
retval = pthread_create(&hilosEncolar[i], 0, &funcionHiloEncola, (void *)&q);
if(retval != 0)
exit(1);
}
for(i = 0; i < 10; i++){
retval = pthread_create(&hilosDesencolar[i], 0, &funcionHiloDesencola, (void *)&q);
if(retval != 0)
exit(1);
}
for(i = 0; i < 10; i++){
pthread_join(hilosEncolar[i], 0);
}
for(i = 0; i < 10; i++){
pthread_join(hilosDesencolar[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
int g_Flag=0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread1(void*);
void* thread2(void*);
int main(int argc, char** argv)
{
printf("enter main\\n");
pthread_t tid1, tid2;
int rc1=0, rc2=0;
rc2 = pthread_create(&tid2, 0, thread2, 0);
if(rc2 != 0)
printf("%s: %d\\n",__func__, strerror(rc2));
rc1 = pthread_create(&tid1, 0, thread1, &tid2);
if(rc1 != 0)
printf("%s: %d\\n",__func__, strerror(rc1));
pthread_cond_wait(&cond, &mutex);
printf("leave main\\n");
exit(0);
}
void* thread1(void* arg)
{
printf("enter thread1\\n");
printf("this is thread1, g_Flag: %d, thread id is %u\\n",g_Flag, (unsigned int)pthread_self());
pthread_mutex_lock(&mutex);
if(g_Flag == 2)
pthread_cond_signal(&cond);
g_Flag = 1;
printf("this is thread1, g_Flag: %d, thread id is %u\\n",g_Flag, (unsigned int)pthread_self());
pthread_mutex_unlock(&mutex);
pthread_join(*(pthread_t*)arg, 0);
printf("leave thread1\\n");
pthread_exit(0);
}
void* thread2(void* arg)
{
printf("enter thread2\\n");
printf("this is thread2, g_Flag: %d, thread id is %u\\n",g_Flag, (unsigned int)pthread_self());
pthread_mutex_lock(&mutex);
if(g_Flag == 1)
pthread_cond_signal(&cond);
g_Flag = 2;
printf("this is thread2, g_Flag: %d, thread id is %u\\n",g_Flag, (unsigned int)pthread_self());
pthread_mutex_unlock(&mutex);
printf("leave thread2\\n");
pthread_exit(0);
}
| 0
|
#include <pthread.h>
double gPi = 0.0;
pthread_mutex_t gLock;
void *Area(void *pArg)
{
int myNum = *((int *)pArg);
double h = 2.0 / 10000000;
double partialSum = 0.0, x;
int i;
for (i = myNum; i < 10000000; i += 4) {
x = -1 + (i + 0.5f) * h;
partialSum += sqrt(1.0 - x*x) * h;
}
pthread_mutex_lock(&gLock);
gPi += partialSum;
pthread_mutex_unlock(&gLock);
return 0;
}
int main(int argc, char **argv)
{
pthread_t tHandles[4];
int tNum[4], i;
pthread_mutex_init(&gLock, 0);
for ( i = 0; i < 4; ++i )
{
tNum[i] = i;
pthread_create(&tHandles[i],
0,
Area,
(void*)&tNum[i]);
}
for ( i = 0; i < 4; ++i )
{
pthread_join(tHandles[i], 0);
}
gPi *= 2.0;
printf("Computed value of Pi: %12.9f\\n", gPi );
pthread_mutex_destroy(&gLock);
return 0;
}
| 1
|
#include <pthread.h>
static struct event_base *my_base=0;
static pthread_t progress_thread;
static bool progress_thread_stop=0;
static int progress_thread_pipe[2];
static pthread_mutex_t lock;
static struct event write_event;
static int my_fd;
static bool fd_written=0;
static void* progress_engine(void *obj);
static void send_handler(int sd, short flags, void *arg);
int main(int argc, char **argv)
{
char byte='a';
struct timespec tp={0, 100};
int count=0;
evthread_use_pthreads();
my_base = event_base_new();
pipe(progress_thread_pipe);
if (pthread_mutex_init(&lock, 0)) {
fprintf(stderr, "pthread_mutex_init failed\\n");
exit(1);
}
if (pthread_create(&progress_thread, 0, progress_engine,
0)) {
fprintf(stderr, "pthread_create failed\\n");
exit(1);
}
while (count < 100) {
nanosleep(&tp, 0);
count++;
}
count=0;
fprintf(stderr, "opening the file");
my_fd = open("foo", O_CREAT | O_TRUNC | O_RDWR, 0644);
if (my_fd <0) {
perror("open");
exit(1);
}
event_assign(&write_event,
my_base,
my_fd,
EV_WRITE|EV_PERSIST,
send_handler,
0);
event_add(&write_event, 0);
if (write(progress_thread_pipe[1], &byte, 1) < 0) {
perror("write");
exit(1);
}
while (!fd_written && count < 1000) {
if (0 == (count % 100)) {
fprintf(stderr, "Waiting...\\n");
}
nanosleep(&tp, 0);
count++;
}
pthread_mutex_lock(&lock);
progress_thread_stop = 1;
pthread_mutex_unlock(&lock);
write(progress_thread_pipe[1], &byte, 1);
pthread_join(progress_thread, 0);
return 0;
}
static struct event stop_event;
static void stop_handler(int sd, short flags, void* cbdata)
{
char byte;
int n;
if ((n = read(progress_thread_pipe[0], &byte, 1)) <= 0) {
if (n == 0)
fprintf(stderr, "got a close\\n");
else
perror("read");
}
event_add(&stop_event, 0);
return;
}
static void* progress_engine(void *obj)
{
event_assign(&stop_event, my_base,
progress_thread_pipe[0], EV_READ, stop_handler, 0);
event_add(&stop_event, 0);
while (1) {
pthread_mutex_lock(&lock);
if (progress_thread_stop) {
fprintf(stderr, "Thread stopping\\n");
pthread_mutex_unlock(&lock);
event_del(&stop_event);
return (void*)1;
}
pthread_mutex_unlock(&lock);
fprintf(stderr, "Looping...\\n");
event_base_loop(my_base, EVLOOP_ONCE);
}
}
static void send_handler(int sd, short flags, void *arg)
{
char *bytes="This is an output string\\n";
fprintf(stderr, "Write event fired\\n");
if (write(my_fd, bytes, strlen(bytes)) < 0) {
perror("write");
exit(1);
}
event_del(&write_event);
fd_written = 1;
}
| 0
|
#include <pthread.h>
float arrFrom[1024 * 1024];
float arrTo[1024 * 1024];
float* ptrFrom;
float* ptrTo;
int steadyState, iterCount, cells50, numThreads;
pthread_barrier_t barrier_first;
pthread_barrier_t barrier_second;
pthread_mutex_t critical_count;
pthread_mutex_t critical_steady;
double When()
{
struct timeval tp;
gettimeofday(&tp, 0);
return ((double) tp.tv_sec + (double) tp.tv_usec * 1e-6);
}
int initArrays()
{
int i, j, rowStart;
for (i = 1; i < 1024 - 1; i++)
{
rowStart = i * 1024;
for (j = 1; j < 1024 - 1; j++)
{
ptrFrom[rowStart + j] = 50;
ptrTo[rowStart + j] = 50;
}
}
for (i = 0; i < 1024; i++)
{
rowStart = i * 1024;
ptrFrom[rowStart] = 0;
ptrFrom[rowStart + 1024 - 1] = 0;
ptrTo[rowStart] = 0;
ptrTo[rowStart + 1024 - 1] = 0;
}
rowStart = (1024 - 1) * 1024;
for (j = 0; j < 1024; j++)
{
ptrFrom[j] = 100;
ptrFrom[rowStart + j] = 0;
ptrTo[j] = 100;
ptrTo[rowStart + j] = 0;
}
for (j = 0; j < 331; j++)
{
ptrFrom[400 * 1024 + j] = 100;
ptrTo[400 * 1024 + j] = 100;
}
ptrFrom[200 * 1024 + 500] = 100;
ptrTo[200 * 1024 + 500] = 100;
return 0;
}
void* iterOverMyRows(void* myNum)
{
int rowStart, i, j, start, roof;
float* flFrom, *flTo;
float total, self;
long t = *((long*)myNum);
start = 1024 / numThreads * t;
roof = start + (1024 / numThreads);
if (start == 0)
start = 1;
if (roof == 1024)
roof = 1024 - 1;
while (1)
{
pthread_barrier_wait(&barrier_first);
for (i = start; i < roof; i++)
{
rowStart = i * 1024;
flFrom = ptrFrom + rowStart;
flTo = ptrTo + rowStart;
for (j = 1; j < 1024 - 1; j++)
{
if (*(flFrom + j) == 100)
continue;
total = *(flFrom - 1024 + j) + *(flFrom + j-1) + *(flFrom + j+1) + *(flFrom + 1024 + j);
self = *(flFrom + j);
*(flTo + j) = (total + 4 * self) / 8;
if (steadyState && !(fabs(self - (total)/4) < 0.1))
{
pthread_mutex_lock(&critical_steady);
steadyState = 0;
pthread_mutex_unlock(&critical_steady);
}
}
}
pthread_barrier_wait(&barrier_second);
}
pthread_exit(0);
}
void * countCells50 (void* arg)
{
long t = *((long*)arg);
int myCells50;
float* flTo;
int i, j;
myCells50 = 0;
for (i = (int)t - 1; i < 1024; i+=numThreads)
{
flTo = ptrTo + i * 1024;
for (j = 0; j < 1024; j++)
{
if (*(flTo + j) > 50)
myCells50++;
}
}
pthread_mutex_lock(&critical_count);
cells50 += myCells50;
pthread_mutex_unlock(&critical_count);
}
int main(int argc, char* argv[])
{
double starttime, finishtime, runtime;
long *taskids[32];
pthread_t threads[32];
int rc;
long t;
float* tempPtr;
starttime = When();
numThreads = atoi(argv[1]);
if (numThreads > 32)
{
printf("\\nCurrent code won't scale above 32 threads.");
}
ptrFrom = &arrFrom[0];
ptrTo = &arrTo[0];
initArrays();
steadyState = 0;
pthread_mutex_init(&critical_steady, 0);
pthread_barrier_init(&barrier_first,0,numThreads+1);
pthread_barrier_init(&barrier_second,0,numThreads+1);
for(t=0; t<numThreads; t++)
{
taskids[t] = (long *) malloc(sizeof(long));
*taskids[t] = t;
rc = pthread_create(&threads[t], 0, iterOverMyRows, (void *) taskids[t]);
}
while (!steadyState)
{
steadyState = 1;
pthread_barrier_wait(&barrier_first);
pthread_barrier_wait(&barrier_second);
iterCount++;
tempPtr = ptrFrom;
ptrFrom = ptrTo;
ptrTo = tempPtr;
}
cells50 = 0;
pthread_mutex_init(&critical_count, 0);
for(t=0; t<numThreads; t++)
{
taskids[t] = (long *) malloc(sizeof(long));
*taskids[t] = t+1;
rc = pthread_create(&threads[t], 0, countCells50, (void *) taskids[t]);
}
for(t=0;t<numThreads;t++)
{
rc = pthread_join(threads[t],0);
}
finishtime = When();
printf("\\nNumber of iterations: %d", iterCount);
printf("\\nNumber of cells w/ temp greater than 50: %d", cells50);
runtime = finishtime - starttime;
printf("\\nTime taken: %f\\n", runtime);
}
| 1
|
#include <pthread.h>
int numOfPassengersOnBus;
int flag;
void* print_message(void* ptr);
pthread_cond_t condFull, condAvailable;
pthread_mutex_t lock;
int main(int argc, char* argv[])
{
pthread_cond_init(&condFull, 0);
pthread_cond_init(&condAvailable, 0);
pthread_mutex_init(&lock, 0);
pthread_t tProducer, tConsumer1, tConsumer2;
const char* msg1 = "Producer";
const char* msg2 = "Consumer_A";
const char* msg3 = "Consumer_B";
numOfPassengersOnBus = 0;
int r1 = pthread_create(&tProducer, 0, print_message, (void*)msg1 );
sleep(1);
int r2 = pthread_create(&tConsumer1, 0, print_message, (void*)msg2 );
sleep(1);
int r3 = pthread_create(&tConsumer2, 0, print_message, (void*)msg3 );
sleep(1);
pthread_join(tProducer, 0);
pthread_join(tConsumer1, 0);
pthread_join(tConsumer2, 0);
return 0;
}
void* print_message(void* ptr)
{
srand(time(0));
char* msg = (char*) ptr;
while(1)
{
if(msg[0]=='P')
{
pthread_mutex_lock(&lock);
while(flag)
{
printf("%s waits flag to become 0...\\n", msg);
pthread_cond_wait(&condFull, &lock);
printf("%s is waken.\\n", msg);
}
int oldVal = numOfPassengersOnBus;
numOfPassengersOnBus++;
printf("%s %d=>%d with flag = %s\\n", msg, oldVal, numOfPassengersOnBus, flag?"1":"0");
flag=1;
printf("%s wakes up sleeping threads with flag = 1.\\n", msg);
pthread_cond_broadcast(&condAvailable);
pthread_mutex_unlock(&lock);
sleep(rand()%2);
}
else
{
pthread_mutex_lock(&lock);
while(!flag)
{
printf("%s waits flag to become 1...\\n", msg);
pthread_cond_wait(&condAvailable, &lock);
printf("%s is waken.\\n", msg);
}
int oldVal = numOfPassengersOnBus;
numOfPassengersOnBus--;
printf("%s %d=>%d with flag = %s\\n", msg, oldVal, numOfPassengersOnBus, flag?"1":"0");
flag = 0;
printf("%s wakes up sleeping threads with flag = 0.\\n", msg);
pthread_cond_broadcast(&condFull);
pthread_mutex_unlock(&lock);
sleep(rand()%4);
}
}
return 0;
}
| 0
|
#include <pthread.h>
struct prodcons
{
char buf[16];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
struct prodcons buffer;
void init(struct prodcons * b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull, 0);
b->readpos = 0;
b->writepos = 0;
}
void put(struct prodcons *p,int num)
{
pthread_mutex_lock(&p->lock);
if((p->writepos+1)%16 == p->readpos)
{
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buf[p->writepos] = num;
p->writepos++;
if(p->writepos >= 16)
p->writepos = 0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
int get(struct prodcons *b)
{
int date;
pthread_mutex_lock(&b->lock);
if(b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty,&b->lock);
}
date = b->buf[b->readpos];
b->readpos++;
if(b->readpos >=16)
b->readpos = 0;
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return date;
}
void * product()
{
int i;
for(i = 0; i<100; i++)
{
printf("%d------>\\n",i);
put(&buffer,i);
}
put(&buffer,(-1));
}
void *consumer()
{
int num = 0;
while(1)
{
num = get(&buffer);
if(num == (-1))
break;
printf("------->%d\\n",num);
}
}
int main()
{
pthread_t pthread_id;
pthread_t pthread_id2;
int ret;
init(&buffer);
ret = pthread_create(&pthread_id, 0, (void*)product,0);
if(ret != 0 )
{
printf("pthread_create error\\n");
return -1;
}
ret = pthread_create(&pthread_id2, 0, (void*)consumer,0);
if(ret != 0 )
{
printf("pthread_create error\\n");
return -1;
}
pthread_join(pthread_id2, 0);
pthread_join(pthread_id, 0);
return 0;
}
| 1
|
#include <pthread.h>
int array[2048*2];
int N=0;
{
int left;
int right;
}parameters;
parameters *para[2048];
int arraySize=0;
pthread_cond_t cv;
pthread_mutex_t lock;
void readArray(char *fileName){
FILE *fp;
int i=0;
fp=fopen(fileName,"r");
if(!fp){
printf("ERROR: Cannot read file %s \\n",fileName);
exit;
}
fscanf(fp,"%d",&array[i]); i++;
while(!feof(fp)){
fscanf(fp," %d",&array[i]); i++;
}
fclose(fp);
arraySize=i;
printf("arraySize = %d \\n",arraySize);
}
void generateRandomNumbers(int n){
int i;
srand(time(0));
for(i=0;i<n;i++){
array[i]=rand()%n;
}
arraySize=n;
}
bool checkArraySize(void){
int n=arraySize;
int i=0;
while(n!=1){
i++;
n=n>>1;
}
n=arraySize;
if(((n>>i)<<i)==n){
printf("valid arraySize \\n");
return 1;
}
else{
printf("Error: invalid arraySize \\n");
return 0;
}
}
void *mergeSort(void *para){
int left,right,mid,i,j,k;
int *leftArray,*rightArray;
parameters *para_=para;
left=para_->left;
right=para_->right;
mid=(left+right)/2;
leftArray=(int *)calloc(sizeof(int),right-left+1);
rightArray=(int *)calloc(sizeof(int),right-left+1);
for(i=left;i<=mid;i++){
leftArray[i-left]=array[i];
}
for(j=mid+1;j<=right;j++){
rightArray[j-mid-1]=array[j];
}
i=left; j=mid+1; k=left;
while(i<=mid&&j<=right){
if(leftArray[i-left]<=rightArray[j-mid-1]){
array[k]=leftArray[i-left];
i++; k++;
}else{
array[k]=rightArray[j-mid-1];
j++; k++;
}
}
while(i<=mid){
array[k]=leftArray[i-left];
i++; k++;
}
while(j<=right){
array[k]=rightArray[j-mid-1];
j++; k++;
}
free(leftArray);
free(rightArray);
pthread_mutex_lock(&lock);
N--; if(N==0)pthread_cond_broadcast(&cv);
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main(int argc,char *argv[]){
int i,j,k;
pthread_t tid[2048];
pthread_mutex_init(&lock,0);
generateRandomNumbers(4096);
if(checkArraySize()){
i=arraySize/2;
while(1){
j=arraySize/i;
printf("layer %d %d \\n",i,j);
N=i;
pthread_cond_init(&cv, 0);
for(k=0;k<i;k++){
para[k]=(parameters*)malloc(sizeof(parameters));
para[k]->left=k*j;
para[k]->right=(k+1)*j-1;
if(pthread_create(&tid[k],0,mergeSort,para[k])){
printf("Could not create thread\\n");
return -1;
}
}
pthread_mutex_lock(&lock);
if(N!=0){
while(N!=0)pthread_cond_wait(&cv, &lock);
}
pthread_mutex_unlock(&lock);
pthread_cond_destroy(&cv);
for(k=0;k<i;k++)free(para[k]);
if(i==1)break;
else i=i/2;
}
}
for(i=0;i<arraySize;i++)printf("%d ",array[i]);
printf("\\n");
pthread_mutex_destroy(&lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lineMutex;
int lineCount=0;
char strContain(char*childstr,char*str);
char strContainDEFINE(char*str);
int countDefine(char*fileName);
int find(char * dirName);
struct task * next;
char* dir;
}task;
int num;
int shutdown;
pthread_t* workThread;
task* taskHead;
task* taskTail;
int taskNum;
pthread_mutex_t mutex;
pthread_cond_t notEmptyCond;
}threadPool;
threadPool *tp;
void* workProcess(void *arg){
int lineNum;
while(1){
pthread_mutex_lock(&tp->mutex);
while( !tp->shutdown&&tp->taskHead==0){
pthread_cond_wait(&tp->notEmptyCond,&tp->mutex);
}
if(tp->shutdown==1){
pthread_mutex_unlock(&tp->mutex);
pthread_exit(0);
}
task *t;
t=tp->taskHead;
tp->taskHead=tp->taskHead->next;
if(tp->taskTail==t){
tp->taskTail=0;
}
tp->taskNum--;
pthread_mutex_unlock(&tp->mutex);
lineNum=0;
printf("%d\\n",tp->taskNum);
lineNum=find(t->dir);
if (lineNum!=0){
pthread_mutex_lock(&lineMutex);
lineCount+=lineNum;
pthread_mutex_unlock(&lineMutex);
}
free(t->dir);
free(t);
}
}
void createThreadPool(int num){
int errorno;
if(num<=0)
exit(1);
tp=(threadPool*)malloc(sizeof(threadPool));
if(tp==0){
exit(1);
}
tp->num=num;
tp->shutdown=0;
tp->workThread=(pthread_t*)malloc(num*sizeof(pthread_t));
if (tp->workThread==0){
free(tp);
exit(1);
}
int i=0;
for(i=0;i<tp->num;i++){
errorno=pthread_create(&tp->workThread[i],0,workProcess,0);
if(errorno!=0){
exit(1);
}
}
tp->taskHead=0;
tp->taskTail=0;
tp->taskNum=0;
pthread_mutex_init(&tp->mutex,0);
pthread_cond_init(&tp->notEmptyCond,0);
}
void addTask(char *dir){
task *t=(task*)malloc(sizeof(task));
if(t==0){
printf("addTadk t=NULL");
exit(1);
}
t->dir=(char*)malloc(strlen(dir));
strcpy(t->dir,dir);
t->next=0;
pthread_mutex_lock(&tp->mutex);
if(tp->taskTail!=0){
tp->taskTail->next=t;
tp->taskTail=t;
}else{
tp->taskHead=t;
tp->taskTail=t;
}
tp->taskNum++;
pthread_cond_broadcast(&tp->notEmptyCond);
pthread_mutex_unlock(&tp->mutex);
}
void destroyThreadPool(){
}
char strContain(char*childstr,char*str){
int clen=strlen(childstr);
int len=strlen(str);
int i=0;
int j=0;
for(i=0;i+clen<=len;i++){
for(j=0;j<clen;j++){
if(childstr[j]!=str[i+j]){
break;
}
}
if(j==clen)
return 1;
}
return 0;
}
char strContainDEFINE(char*str){
int len=strlen(str);
int i=0;
for(i=0;i+6<=len;i++){
if((str[i]=='d')&&(str[i+1]=='e')&&(str[i+2]=='f')&&(str[i+3]=='i')&&(str[i+4]=='n')&&(str[i+5]=='e'))
return 1;
}
return 0;
}
int countDefine(char*fileName){
int lineNum=0;
FILE *fp=fopen(fileName,"r");
if(fp==0){
perror(fileName);
}
char content[200];
while(fgets(content,200,fp)){
if(strContainDEFINE(content)==1){
lineNum++;
}
}
fclose(fp);
return lineNum;
}
int find(char * dirName){
char fileName[80];
int lineNum=0;
int dirLen=strlen(dirName);
int error;
DIR *dir;
struct dirent entry;
struct dirent *result;
struct stat fstat;
strcpy(fileName,dirName);
fileName[dirLen]='/';
dir = opendir(dirName);
if(dir==0)
return 0;
int len;
for (;;) {
fileName[dirLen+1]='\\0';
error = readdir_r(dir, &entry, &result);
if (error != 0) {
perror("readdir");
return 0;
}
if (result == 0)
break;
strcat(fileName,result->d_name);
stat(fileName,&fstat);
if(S_ISDIR(fstat.st_mode)){
if((strcmp(".",result->d_name)==0)||(strcmp("..",result->d_name)==0))
continue;
addTask(fileName);
}else{
lineNum+=countDefine(fileName);
}
}
closedir(dir);
return lineNum;
}
int main()
{
pthread_mutex_init(&lineMutex,0);
createThreadPool(1);
addTask("/usr/include");
sleep(1000);
printf("%d\\n",lineCount);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread1;
pthread_mutex_t lock1;
void *workOne(void *arg) {
pthread_mutex_lock(&lock1);
usleep(100);
pthread_mutex_lock(&lock1);
pthread_mutex_unlock(&lock1);
return arg;
}
int main() {
int ret;
ret = pthread_mutex_init(&lock1, 0);
if (ret) {
fprintf(stderr, "pthread_mutex_init, error: %d\\n", ret);
return ret;
}
ret = pthread_create(&thread1, 0, workOne, 0);
if (ret) {
fprintf(stderr, "pthread_create, error: %d\\n", ret);
return ret;
}
ret = pthread_join(thread1, 0);
if (ret) {
fprintf(stderr, "pthread_join, error: %d\\n", ret);
return ret;
}
ret = pthread_mutex_destroy(&lock1);
if (ret) {
fprintf(stderr, "pthread_mutex_destroy, error: %d\\n", ret);
return ret;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int scholarship = 4000,
total = 0;
void *A(void);
void *B(void);
void *C(void);
void *totalCalc(void);
int main(void){
pthread_t tid1,
tid2,
tid3;
pthread_create(&tid1, 0, (void *(*)(void *))A, 0 );
pthread_create(&tid2, 0, (void *(*)(void *))B, 0 );
pthread_create(&tid3, 0, (void *(*)(void *))C, 0 );
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
totalCalc();
return 0;
}
void *A(void){
float result;
while(scholarship > 0){
sleep(2);
pthread_mutex_lock(&mutex);
result = scholarship * 0.25;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("A = ");
printf("%.2f",result);
printf("\\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread A exited\\n");
return 0;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *B(void){
float result;
while(scholarship > 0){
sleep(1);
pthread_mutex_lock(&mutex);
result = scholarship * 0.25;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("B = ");
printf("%.2f",result);
printf("\\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread B exited\\n");
return 0;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *C(void){
float result;
while(scholarship > 0){
sleep(1);
pthread_mutex_lock(&mutex);
result = scholarship * 0.25;
result = ceil(result);
total = total + result;
scholarship = scholarship - result;
if( result >= 1){
printf("C = ");
printf("%.2f",result);
printf("\\n");
}
if( scholarship < 1){
pthread_exit(0);
printf("Thread C exited\\n");
return 0;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void *totalCalc(void){
printf("Total given out: ");
printf("%d", total);
printf("\\n");
}
| 1
|
#include <pthread.h>
void * handle_clnt(void * arg);
void send_msg(char * msg, int len);
void error_handling(char * msg);
void color();
void printColorString(int color,char *str);
int clnt_cnt=0;
int clnt_socks[256];
pthread_mutex_t mutx;
char addr_arry[256][20];
int colorS=41;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
struct in_addr temp_addr;
char *str_addr;
int clnt_adr_sz;
pthread_t t_id;
if(argc!=2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
printf("\\033[%dmServer is booted\\033[0m\\n",32);
while(1)
{
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);
temp_addr=clnt_adr.sin_addr;
str_addr=inet_ntoa(temp_addr);
pthread_mutex_lock(&mutx);
strcpy(addr_arry[clnt_cnt],str_addr);
clnt_socks[clnt_cnt++]=clnt_sock;
pthread_mutex_unlock(&mutx);
pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock);
pthread_detach(t_id);
printf("\\n\\033[%dm Connected client IP: [%s] \\033[0m\\n", colorS+(clnt_sock-4), inet_ntoa(clnt_adr.sin_addr));
}
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg)
{
int clnt_sock=*((int*)arg);
int str_len=0, i,j;
char msg[100];
char temp[20];
while((str_len=read(clnt_sock, msg, sizeof(msg)))!=0){
send_msg(msg, str_len);
memset(&msg, 0, sizeof(msg));
}
pthread_mutex_lock(&mutx);
for(i=0; i<clnt_cnt; i++)
{
if(clnt_sock==clnt_socks[i])
{
strcpy(temp, addr_arry[i]);
while(i++<clnt_cnt-1)
clnt_socks[i]=clnt_socks[i+1];
for(j=0;j<20;j++)
addr_arry[i][j]=addr_arry[i+1][j];
break;
}
}
printf("\\n\\033[%dmClient disconnected : [%s] \\033[0m\\n", colorS+(clnt_sock-4) ,temp);
clnt_cnt--;
pthread_mutex_unlock(&mutx);
close(clnt_sock);
return 0;
}
void send_msg(char * msg, int len)
{
int i;
FILE *fp=fopen("script.txt","at");
if(fp==0){
puts("fail open");
}
pthread_mutex_lock(&mutx);
fputs(msg, stdout);
fputs(msg,fp);
for(i=0; i<clnt_cnt; i++)
write(clnt_socks[i], msg, len);
pthread_mutex_unlock(&mutx);
fclose(fp);
}
void color()
{
printf("\\n");
printf("\\033[30m FG_BLACK(30) \\033[0m\\n");
printf("\\033[31m FG_RED(31) \\033[0m\\n");
printf("\\033[32m FG_GREEN(32) \\033[0m\\n");
printf("\\033[33m FG_YELLOW(33) \\033[0m\\n");
printf("\\033[34m FG_BLUE(34) \\033[0m\\n");
printf("\\033[35m FG_VIOLET(35) \\033[0m\\n");
printf("\\033[36m FG_VIRDIAN(36) \\033[0m\\n");
printf("\\033[37m FG_WHITE(37) \\033[0m");
printf("\\n");
printf("\\033[40m BG_BLACK(40) \\033[0m\\n");
printf("\\033[41m BG_RED(41) \\033[0m\\n");
printf("\\033[42m BG_GREEN(42) \\033[0m\\n");
printf("\\033[43m BG_YELLOW(43) \\033[0m\\n");
printf("\\033[44m BG_BLUE(44) \\033[0m\\n");
printf("\\033[45m BG_VIOLET(45) \\033[0m\\n");
printf("\\033[46m BG_VIRDIAN(46) \\033[0m\\n");
printf("\\033[47m BG_WHITE(47) \\033[0m\\n");
}
void printColorString(int color,char *str)
{
printf("\\033[%dm %s \\033[0m",color,str);
}
void error_handling(char * msg)
{
fputs(msg, stderr);
fputc('\\n', stderr);
exit(1);
}
| 0
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void * thr_fn (void * arg);
int main (int argc, char * argv[])
{
int err;
sigset_t oldmask;
pthread_t thread;
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 (&thread, 0, thr_fn, 0);
if (err != 0)
err_exit (err, "can't create thread");
pthread_mutex_lock (&lock);
while (quitflag == 0)
pthread_cond_wait (&waitloc, &lock);
pthread_mutex_unlock (&lock);
quitflag = 0;
if (sigprocmask (SIG_SETMASK, &oldmask, 0) < 0)
err_sys ("SIG_SETMASK error");
return 0;
}
void *thr_fn (void * arg)
{
int err, signo;
while (1)
{
err = sigwait (&mask, &signo);
if (err != 0)
err_exit (err, "sigwait failed.");
switch (signo)
{
case SIGINT:
printf ("\\ninterrupt \\n"); break;
case SIGQUIT:
pthread_mutex_lock (&lock);
quitflag = 1;
pthread_mutex_unlock (&lock);
pthread_cond_signal (&waitloc);
return 0;
default:
printf ("unexpected signal %d\\n", signo);
exit (1);
}
}
}
| 1
|
#include <pthread.h>
int global_value = 0;
pthread_mutex_t global_value_mutex = PTHREAD_MUTEX_INITIALIZER;
void *t1_main(void *arg);
void *t2_main(void *arg);
int main(int argc, char **argv)
{
pthread_t t1, t2;
int code;
code = pthread_create(&t1, 0, t1_main, 0);
if (code != 0)
{
fprintf(stderr, "Create new thread t1 failed: %s\\n", strerror(code));
exit(1);
}
else
{
fprintf(stdout, "New thread t1 created.\\n");
}
code = pthread_create(&t2, 0, t2_main, 0);
if (code != 0)
{
fprintf(stderr, "Create new thread t2 failed: %s\\n", strerror(code));
exit(1);
}
else
{
fprintf(stdout, "New thread t2 created.\\n");
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&global_value_mutex);
pthread_exit((void *) 0);
}
void *t1_main(void *arg)
{
int i;
for (i = 0; i < 100000; i++)
{
pthread_mutex_lock(&global_value_mutex);
global_value++;
pthread_mutex_unlock(&global_value_mutex);
sleep(1);
}
pthread_exit((void *) 0);
}
void *t2_main(void *arg)
{
int i;
for (i = 0; i < 100000; i++)
{
pthread_mutex_lock(&global_value_mutex);
global_value += 2;
pthread_mutex_unlock(&global_value_mutex);
sleep(1);
}
pthread_exit((void *) 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t counter_lock;
pthread_cond_t counter_nonzero;
int counter = 0;
int estatus = -1;
void *decrement_counter(void *argv);
void *increment_counter(void *argv);
int main(int argc, char **argv)
{
printf("counter: %d/n", counter);
pthread_t thd1, thd2;
int ret;
pthread_mutex_init(&counter_lock, 0);
pthread_cond_init(&counter_nonzero, 0);
ret = pthread_create(&thd1, 0, decrement_counter, 0);
if(ret){
perror("del:/n");
return 1;
}
ret = pthread_create(&thd2, 0, increment_counter, 0);
if(ret){
perror("inc: /n");
return 1;
}
int counter = 0;
while(counter != 10){
printf("counter(main): %d/n", counter);
sleep(1);
counter++;
}
pthread_exit(0);
return 0;
}
void *decrement_counter(void *argv)
{
printf("counter(decrement): %d/n", counter);
pthread_mutex_lock(&counter_lock);
while(counter == 0)
pthread_cond_wait(&counter_nonzero, &counter_lock);
printf("counter--(before): %d/n", counter);
counter--;
printf("counter--(after): %d/n", counter);
pthread_mutex_unlock(&counter_lock);
return &estatus;
}
void *increment_counter(void *argv)
{
printf("counter(increment): %d/n", counter);
pthread_mutex_lock(&counter_lock);
if(counter == 0)
pthread_cond_signal(&counter_nonzero);
printf("counter++(before): %d/n", counter);
counter++;
printf("counter++(after): %d/n", counter);
pthread_mutex_unlock(&counter_lock);
return &estatus;
}
| 1
|
#include <pthread.h>
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int buffer[11];
int front = 0, rear = 0;
void *produce()
{
int i = 0;
while (1) {
printf("Producer\\n");
fflush(0);
pthread_mutex_lock(&mutex);
while ((front + 1) % 11 == rear) {
printf("Producer: Buffer is full!\\n");
fflush(0);
pthread_cond_wait(&space_available, &mutex);
}
buffer[front] = i;
front = (front + 1) % 11;
pthread_cond_signal(&data_available);
pthread_mutex_unlock(&mutex);
++i;
}
pthread_exit(0);
}
void *consume()
{
int i, v;
for (i = 0; i < 100; ++i) {
printf("Consumer\\n");
fflush(0);
pthread_mutex_lock(&mutex);
while (front == rear) {
printf("Consumer: Buffer is empty!\\n");
fflush(0);
pthread_cond_wait(&data_available, &mutex);
}
v = buffer[rear];
rear = (rear + 1) % 11;
pthread_cond_signal(&space_available);
pthread_mutex_unlock(&mutex);
printf("Got Data: %d\\n", v);
fflush(0);
}
pthread_exit(0);
}
int main()
{
pthread_t producer_thread;
pthread_t consumer_thread;
pthread_create(&producer_thread, 0, produce, 0);
pthread_create(&consumer_thread, 0, consume, 0);
pthread_join(consumer_thread, 0);
}
| 0
|
#include <pthread.h>
{
int id;
int nproc;
} parm;
char message[100];
pthread_mutex_t msg_mutex = PTHREAD_MUTEX_INITIALIZER;
int token = 0;
void* greeting(void *arg)
{
parm *p = (parm *) arg;
int id = p->id;
int i;
if (id != 0)
{
while (1)
{
pthread_mutex_lock(&msg_mutex);
if (token == 0)
{
sprintf(message, "Greetings from process %d!", id);
token++;
pthread_mutex_unlock(&msg_mutex);
break;
}
pthread_mutex_unlock(&msg_mutex);
sleep(1);
}
} else
{
for (i = 1; i < p->nproc; i++)
{
while (1)
{
pthread_mutex_lock(&msg_mutex);
if (token == 1)
{
printf("%s\\n", message);
token--;
pthread_mutex_unlock(&msg_mutex);
break;
}
pthread_mutex_unlock(&msg_mutex);
sleep(1);
}
}
}
return 0;
}
void main(int argc, char *argv[])
{
int my_rank;
int dest;
int tag = 0;
pthread_t *threads;
pthread_attr_t pthread_custom_attr;
parm *p;
int n, i;
if (argc != 2)
{
printf("Usage: %s n\\n where n is no. of thread\\n", argv[0]);
exit(1);
}
n = atoi(argv[1]);
if ((n < 1) || (n > 1000))
{
printf("The no of thread should between 1 and %d.\\n", 1000);
exit(1);
}
threads = (pthread_t *) malloc(n * sizeof(*threads));
pthread_attr_init(&pthread_custom_attr);
p=(parm *)malloc(sizeof(parm)*n);
for (i = 0; i < n; i++)
{
p[i].id = i;
p[i].nproc = n;
pthread_create(&threads[i], &pthread_custom_attr, greeting, (void *)(p+i));
}
for (i = 0; i < n; i++)
{
pthread_join(threads[i], 0);
}
free(p);
}
| 1
|
#include <pthread.h>
char *word;
int count;
struct dict *next;
} dict_t;
pthread_mutex_t mutex;
pthread_mutex_t wordmut;
FILE *infile;
dict_t* wd;
char *
make_word( char *word ) {
return strcpy( malloc( strlen( word )+1 ), word );
}
dict_t *
make_dict(char *word) {
dict_t *nd = (dict_t *) malloc( sizeof(dict_t) );
nd->word = make_word( word );
nd->count = 1;
nd->next = 0;
return nd;
}
void
insert_word(char* word) {
dict_t *nd;
dict_t *pd = 0;
dict_t *di=wd;
while(di && ( strcmp(word, di->word ) >= 0) ) {
if( strcmp( word, di->word ) == 0 ) {
di->count++;
return;
}
pd = di;
di = di->next;
}
nd = make_dict(word);
nd->next = di;
if (pd) {
pd->next = nd;
return;
}
wd=nd;
return;
}
void print_dict(void) {
while (wd) {
printf("[%d] %s\\n", wd->count, wd->word);
wd = wd->next;
}
}
int
get_word( char *buf) {
int inword = 0;
int c;
while( (c = fgetc(infile)) != EOF ) {
if (inword && !isalpha(c)) {
buf[inword] = '\\0';
return 1;
}
if (isalpha(c)) {
buf[inword++] = c;
}
}
return 0;
}
void*
thread_stuff(void* arg){
char word[1024];
int okgo=1;
while (okgo){
pthread_mutex_lock(&wordmut);
okgo=get_word(word);
pthread_mutex_unlock(&wordmut);
if (okgo==0) break;
pthread_mutex_lock(&mutex);
insert_word(word);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void
words() {
wd = 0;
pthread_t threads[4];
pthread_attr_t attr;
int i;
int t_ret;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&wordmut, 0);
for (i=0; i<4; i++){
t_ret = pthread_create(&threads[i],&attr,thread_stuff,0);
if (t_ret){
exit(-1);
}
}
for(i=0; i<4; i++)
{
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&wordmut);
pthread_attr_destroy(&attr);
}
int
main( int argc, char *argv[] ) {
wd = 0;
infile = stdin;
if (argc >= 2) {
infile = fopen (argv[1],"r");
}
if( !infile ) {
printf("Unable to open %s\\n",argv[1]);
exit( 1 );
}
words();
print_dict();
fclose( infile );
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++)
{
a[i]=1.0;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<4; i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<4; i++)
{
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void * test(void * arg)
{
pthread_mutex_lock(&mutex);
for (int i = 0; i < 10; ++i) {
printf("T1 : %d\\n", i);
sleep(1);
if (i == 5) pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
return (void*)0;
}
void * test2(void * arg)
{
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex);
for (int i = 0; i < 10; ++i) {
printf("T2 : %d\\n", i);
sleep(1);
}
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
return (void *)0;
}
int main(int argc, char *argv[])
{
pthread_attr_t p_attr;
pthread_attr_init(&p_attr);
pthread_attr_setdetachstate(&p_attr, PTHREAD_CREATE_DETACHED);
pthread_mutexattr_t m_attr;
pthread_mutexattr_init(&m_attr);
pthread_mutexattr_settype(&m_attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &m_attr);
pthread_cond_init(&cond, 0);
pthread_t tid1, tid2;
pthread_create(&tid1, &p_attr, test, 0);
sleep(1);
pthread_create(&tid2, &p_attr, test2, 0);
pthread_attr_destory(&p_attr);
pthread_mutexattr_destory(&m_attr);
sleep(30);
return 0;
}
| 0
|
#include <pthread.h>
static void dump_line(char * out, const char *addr, const int len)
{
int i;
char temp[5];
strcat(out, "|");
for (i = 0; i < 16; i++) {
if (i < len) {
sprintf(temp, " %02X", ((uint8_t *) addr)[i]);
strcat(out, temp);
} else {
strcat(out, " ..");
}
if (!((i + 1) % 8)) {
strcat(out, " |");
}
}
strcat(out, "\\t");
for (i = 0; i < 16; i++) {
char c = 0x7f & ((uint8_t *) addr)[i];
if (i < len && isprint(c)) {
sprintf(temp, "%c", c);
strcat(out, temp);
} else {
strcat(out, ".");
}
}
}
pthread_mutex_t dump_lock = PTHREAD_MUTEX_INITIALIZER;
void dump_buff(const char *addr, const int len)
{
int i;
const int buf_len = 80;
char buff[buf_len];
pthread_mutex_lock(&dump_lock);
for (i = 0; i < len; i += 16) {
memset(buff, 0, buf_len);
dump_line(buff, addr + i, (len - i) < 16 ? (len - i) : 16);
LOGE("%s", buff);
}
pthread_mutex_unlock(&dump_lock);
}
| 1
|
#include <pthread.h>
struct x_pthread_create_control_block_s {
pthread_mutex_t start_lock;
volatile void *(*start)(void *);
void *arg;
};
static
void
x_pthread_create_commit(void *args, int *result)
{
x_pthread_create_control_block_t *control_block = (x_pthread_create_control_block_t *) args;
int local_result = 0;
pthread_mutex_unlock(&control_block->start_lock);
if (result) {
*result = local_result;
}
}
static
void
x_pthread_create_undo(void *args, int *result)
{
x_pthread_create_control_block_t *control_block = (x_pthread_create_control_block_t *) args;
int local_result = 0;
control_block->start = 0;
pthread_mutex_unlock(&control_block->start_lock);
if (result) {
*result = local_result;
}
}
static
void *
x_pthread_create_start_indirection(void *args)
{
void *(*start_routine)(void *);
void *myarg;
x_pthread_create_control_block_t *control_block = (x_pthread_create_control_block_t *) args;
myarg = control_block->arg;
pthread_mutex_lock(&control_block->start_lock);
start_routine = control_block->start;
FREE(control_block);
if (start_routine) {
return start_routine(myarg);
} else {
return (void *) 0x0;
}
}
int
XCALL_DEF(x_pthread_create)(pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void*),
void *arg,
int *result)
{
txc_tx_t *txd;
int ret;
x_pthread_create_control_block_t *control_block;
int local_result = 0;
txd = txc_tx_get_txd();
switch(txc_tx_get_xactstate(txd)) {
case TXC_XACTSTATE_TRANSACTIONAL_RETRYABLE:
control_block = (x_pthread_create_control_block_t *) MALLOC(sizeof(x_pthread_create_control_block_t));
control_block->arg = arg;
control_block->start = start_routine;
pthread_mutex_init(&control_block->start_lock, 0);
pthread_mutex_lock(&control_block->start_lock);
pthread_create(thread, attr, x_pthread_create_start_indirection, (void *) control_block);
txc_tx_register_commit_action(txd, x_pthread_create_commit,
(void *) control_block, result,
TXC_TX_REGULAR_COMMIT_ACTION_ORDER);
txc_tx_register_undo_action(txd, x_pthread_create_undo,
(void *) control_block, result,
TXC_TX_REGULAR_UNDO_ACTION_ORDER);
ret = 0;
break;
case TXC_XACTSTATE_TRANSACTIONAL_IRREVOCABLE:
case TXC_XACTSTATE_NONTRANSACTIONAL:
if ((ret = pthread_create(thread, attr, start_routine, arg)) != 0) {
local_result = ret;
goto done;
}
}
done:
if (result) {
*result = local_result;
}
return ret;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock_pista = PTHREAD_MUTEX_INITIALIZER;
void * aviao(void * arg){
int i = *((int *) arg);
while(1){
printf("%d: voando\\n",i);
sleep(5);
printf("%d: vai pousar\\n",i);
pthread_mutex_lock(&lock_pista);
printf("%d: pousando - usando a pista\\n",i);
sleep(2);
printf("%d: pousou, liberando a pista\\n",i);
pthread_mutex_unlock(&lock_pista);
sleep(5);
printf("%d: vai decolar\\n",i);
pthread_mutex_lock(&lock_pista);
printf("%d: decolando - usando a pista\\n",i);
sleep(1);
printf("%d: decolou, liberando a pista\\n",i);
pthread_mutex_unlock(&lock_pista);
}
pthread_exit(0);
}
int main() {
pthread_t a[4];
int i;
int *id;
for (i = 0; i < 4 ; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&a[i], 0, aviao, (void *) (id));
}
pthread_join(a[0],0);
return 0;
}
| 1
|
#include <pthread.h>
int num;
pthread_mutex_t mutex;
pthread_cond_t cond;
}my_sem_t;
int queue[5];
my_sem_t blank_number, product_number;
int my_sem_init(my_sem_t *sem, int pshared, int value)
{
sem->num = value;
pthread_mutex_init(&sem->mutex, 0);
pthread_cond_init(&sem->cond, 0);
return 0;
}
int my_sem_destroy(my_sem_t *sem)
{
sem->num = -1;
pthread_mutex_destroy(&sem->mutex);
pthread_cond_destroy(&sem->cond);
return 0;
}
int my_sem_wait(my_sem_t *sem)
{
pthread_mutex_lock(&sem->mutex);
while (sem->num <= 0)
pthread_cond_wait(&sem->cond, &sem->mutex);
sem->num--;
pthread_mutex_unlock(&sem->mutex);
return 0;
}
int my_sem_post(my_sem_t *sem)
{
pthread_mutex_lock(&sem->mutex);
sem->num++;
pthread_mutex_unlock(&sem->mutex);
pthread_cond_broadcast(&sem->cond);
return 0;
}
void *producer(void *arg)
{
static int p = 0;
while(1) {
my_sem_wait(&blank_number);
queue[p] = rand() % 1000;
printf("produce %d\\n", queue[p]);
p = (p + 1) % 5;
sleep(rand() % 5);
my_sem_post(&product_number);
}
}
void *consumer(void *arg)
{
static int c = 0;
while (1) {
my_sem_wait(&product_number);
printf("Consume %d\\n", queue[c]);
c = (c + 1) % 5;
sleep(rand() % 5);
my_sem_post(&blank_number);
}
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
int n;
my_sem_init(&blank_number, 0, 5);
my_sem_init(&product_number, 0, 0);
n = pthread_create(&pid, 0, producer, 0);
if (n != 0)
perror("pthread_create");
n = pthread_create(&cid, 0, consumer, 0);
if (n != 0)
perror("pthread_create");
pthread_join(pid, 0);
pthread_join(cid, 0);
my_sem_destroy(&blank_number);
my_sem_destroy(&product_number);
return 0;
}
| 0
|
#include <pthread.h>
static int ready = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void *
mythr(void *ignore)
{
pthread_mutex_lock(&mutex);
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sigset_t ss;
sigfillset(&ss);
while (1) {
struct timespec ts = {10000, 0};
ppoll(0, 0, &ts, &ss);
}
return 0;
}
int
main()
{
pthread_t thr;
int ret = pthread_create(&thr, 0, mythr, 0);
if (ret != 0) {
fprintf(stderr, "pthread_create failed\\n");
return 1;
}
pthread_mutex_lock(&mutex);
while (ready == 0) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
alarm(1);
while (1)
sleep(1);
return 0;
}
| 1
|
#include <pthread.h>
int in = 0;
int out = 0;
int buff[10] = {0};
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
int producer_id = 0;
int consumer_id = 0;
int now_item = 0;
void print()
{
int i;
for(i = 0; i < 10; i++)
printf("%d ", buff[i]);
printf("\\n");
}
void *producer()
{
int id = ++producer_id;
while(1)
{
sleep(1);
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
in = in % 10;
printf("producer%d produces product in buffer%d repo: \\t", id, in);
buff[in] = 1;
print();
++in;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *consumer()
{
int id = ++consumer_id;
while(1)
{
sleep(1);
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
out = out % 10;
printf("consumer%d consumes product in buffer%d repo: \\t", id, out);
buff[out] = 0;
print();
++now_item;
++out;
if(now_item >= 50)
{
exit(1);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main()
{
pthread_t id1[3];
pthread_t id2[2];
int i;
int pro_thr[3];
int con_thr[2];
int ini1 = sem_init(&empty_sem, 0, 10);
int ini2 = sem_init(&full_sem, 0, 0);
if(ini1 && ini2 != 0)
{
printf("sem init failed \\n");
exit(1);
}
int ini3 = pthread_mutex_init(&mutex, 0);
if(ini3 != 0)
{
printf("mutex init failed \\n");
exit(1);
}
for(i = 0; i < 3; i++)
{
pro_thr[i] = pthread_create(&id1[i], 0, producer, (void *)(&i));
if(pro_thr[i] != 0)
{
printf("producer%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 2; i++)
{
con_thr[i] = pthread_create(&id2[i], 0, consumer, 0);
if(con_thr[i] != 0)
{
printf("consumer%d creation failed \\n", i);
exit(1);
}
}
for(i = 0; i < 3; i++)
{
pthread_join(id1[i],0);
}
for(i = 0; i < 3; i++)
{
pthread_join(id2[i],0);
}
exit(0);
}
| 0
|
#include <pthread.h>
int run_thread = 1;
struct FIFO *f;
void writer(void);
void *writer_thread(void *data);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main() {
pthread_t awriter_thread;
int i,j;
short read_buf[8];
int n_out = 0;
int sucess;
f = fifo_create(1024);
pthread_create(&awriter_thread, 0, writer_thread, 0);
for(i=0; i<1000000; ) {
sucess = (fifo_read(f, read_buf, 8) == 0);
if (sucess) {
for(j=0; j<8; j++) {
if (read_buf[j] != n_out)
printf("error: %d %d\\n", read_buf[j], n_out);
n_out++;
if (n_out == 100)
n_out = 0;
}
i++;
}
}
run_thread = 0;
pthread_join(awriter_thread,0);
return 0;
}
int n_in = 0;
void writer(void) {
short write_buf[10];
int i;
if ((1024 - fifo_used(f)) > 10) {
for(i=0; i<10; i++) {
write_buf[i] = n_in++;
if (n_in == 100)
n_in = 0;
}
fifo_write(f, write_buf, 10);
pthread_mutex_unlock(&mutex);
}
}
void *writer_thread(void *data) {
while(run_thread) {
writer();
}
return 0;
}
| 1
|
#include <pthread.h>
int mouse_hook(int button, int x, int y, void *e)
{
(void)e;
pthread_mutex_lock(&sgt_constructor()->mutex_preview);
mouse(button, x, y);
pthread_mutex_unlock(&sgt_constructor()->mutex_preview);
return (1);
}
| 0
|
#include <pthread.h>
static int block_size = 512;
struct signs {
int length;
char * signs;
};
void append_sign_binary(struct signs * s, char sign){
if(sign == 0){
return;
}
if(sign == 1){
int byte = s->length / 1;
int rem = s->length % 1;
s->signs[byte] = s->signs[byte] | (1 << rem);
}
}
void allocate_space(struct signs * s){
if(s->length == 0){
s->signs = calloc(block_size,sizeof(char));
return;
}
if((s->length % (block_size*1)) == 0){
s->signs = realloc(s->signs, (s->length/1) + block_size);
s->signs[s->length/1] = 0;
return;
}
}
void append_sign(struct signs * s, char sign){
allocate_space(s);
append_sign_binary(s, sign);
s->length = s->length + 1;
}
char read_sign(struct signs s, int position){
if(position >= s.length){
fprintf(stderr, "Attempting to read a sign at an illegal position\\n");
exit(-1);
}else{
int byte = position / 1;
int rem = position % 1;
return ((s.signs[byte] >> rem) & 0b00000001);
}
}
void init_sign(struct signs * s){
s->length = 0;
}
void free_sign(struct signs * s){
s->length = 0;
free(s->signs);
}
void print_sign(struct signs s){
if(s.length == 0)
printf("empty");
else
for(int i = 0; i < s.length; i++)
printf("%d", (int) read_sign(s, i));
}
struct signs extract_sign (struct signs s, int i, int j){
struct signs new;
init_sign(&new);
for(int k = 0; i - k*j >= 0; k++)
append_sign(&new, read_sign(s, i - k*j));
return new;
}
int matches(struct signs a, struct signs b){
if(a.length > b.length)
return 0;
for(int i = 0; i < a.length; i++)
if(read_sign(a, i) != read_sign(b, i))
return 0;
return 1;
}
static struct signs mono0;
static struct signs mono1;
void init_mono(int n){
init_sign(&mono0);
init_sign(&mono1);
for(int i = 0; i < n; i++){
append_sign(&mono0, (char) 0);
append_sign(&mono1, (char) 1);
}
}
void free_mono(){
free_sign(&mono0);
free_sign(&mono1);
}
int matches_waerden(struct signs a){
if(mono0.length == 0 || mono1.length == 0){
fprintf(stderr, "Error: Monochromatic sequence not initialized\\n");
exit(-1);
}
if((matches(mono0, a) == 1) || (matches(mono1, a) == 1)) return 1;
return 0;
}
int check_matches_waerden(struct signs s){
int n = mono0.length;
if(s.length < n) return 0;
for(int j = 1; (n-1)*j < s.length; j++){
struct signs extracted = extract_sign(s, s.length - 1, j);
int matches = matches_waerden(extracted);
free_sign(&extracted);
if(matches == 1) return 1;
}
return 0;
}
struct signs copy_append_sign(struct signs s, char sign){
struct signs new0;
init_sign(&new0);
for(int i = 0; i < s.length; i++){
append_sign(&new0, read_sign(s, i));
}
append_sign(&new0, sign);
return new0;
}
int max(int a, int b){
if(a > b) return a;
return b;
}
sem_t threads_sem;
pthread_mutex_t running_mutex;
static int max_length = 0;
static int counter = 0;
int waerden_length(struct signs * w){
struct signs s;
s.length = w->length;
s.signs = w->signs;
struct signs s0 = copy_append_sign(s, 0);
struct signs s1 = copy_append_sign(s, 1);
int s0matches = check_matches_waerden(s0);
int s1matches = check_matches_waerden(s1);
pthread_mutex_lock(&running_mutex);
if(max_length < s.length){
max_length = s.length;
printf("\\n%d ", max_length);
print_sign(s);
fflush(0);
}
pthread_mutex_unlock(&running_mutex);
int length;
if(s0matches == 1 && s1matches == 1){
length = s0.length;
free_sign(&s0);
free_sign(&s1);
}
if(s0matches == 0 && s1matches == 1){
free_sign(&s1);
pthread_yield();
length = waerden_length(&s0);
free_sign(&s0);
}
if(s0matches == 1 && s1matches == 0){
free_sign(&s0);
pthread_yield();
length = waerden_length(&s1);
free_sign(&s1);
}
if(s0matches == 0 && s1matches == 0){
pthread_t pth_s0;
pthread_t pth_s1;
if(sem_trywait(&threads_sem) == 0){
int ret_s0;
int ret_s1;
pthread_create(&pth_s0, 0, (void *) waerden_length, &s0);
pthread_create(&pth_s1, 0, (void *) waerden_length, &s1);
pthread_join(pth_s0, (void *) &ret_s0);
printf("Thread 1 complete\\n");
pthread_join(pth_s1, (void *) &ret_s1);
printf("Thread 2 complete\\n");
sem_post(&threads_sem);
length = max(ret_s0, ret_s1);
}else{
length = max(waerden_length(&s1), waerden_length(&s0));
}
free_sign(&s1);
free_sign(&s0);
}
return length;
}
int main (int argc, char ** argv){
struct signs s;
int num_cpu = 1;
if(argc < 2){
printf("Usage: %s n num_cpu\\nComputes the n-th van der Waerden number\\n", argv[0]);
return 0;
}
init_sign(&s);
init_mono(atoi(argv[1]));
if(argc > 2){
num_cpu = atoi(argv[2]);
}
sem_init(&threads_sem,0, num_cpu - 1);
printf("\\r%d\\n", waerden_length(&s));
free_mono();
sem_destroy(&threads_sem);
}
| 1
|
#include <pthread.h>
pthread_mutex_t chopstick[5];
pthread_t philos[5];
void initialize()
{
int i;
for(i=0;i<5;i++)
pthread_mutex_init(&chopstick[i],0);
}
void* dinner(void *param)
{
int id=*((int*)param);
int waittime;
while(1)
{
waittime=rand()%5;
printf("Philosopher %d is thinking\\n",id);
sleep(waittime);
printf("Philosopher %d is hungry\\n",id);
waittime=rand()%5;
pthread_mutex_lock(&chopstick[(id-1)%5]);
pthread_mutex_lock(&chopstick[(id+1)%5]);
printf("Philospher %d is eating\\n",id);
sleep(waittime);
pthread_mutex_unlock(&chopstick[(id-1)%5]);
pthread_mutex_unlock(&chopstick[(id+1)%5]);
}
return 0;
}
int main()
{
int i;
int id[5];
for(i=0;i<5;i++)
id[i]=i+1;
initialize();
for(i=0;i<5;i++)
pthread_create(&philos[i],0,dinner,(void *)&id[i]);
for(i=0;i<5;i++)
pthread_join(philos[i],0);
return 0;
}
| 0
|
#include <pthread.h>
void init_matrix (int *matrix, int fils, int cols) {
int i, j;
for (i = 0; i < fils; i++) {
for (j = 0; j < cols; j++) {
matrix[i * cols + j] = 1;
}
}
}
int *matrix1;
int *matrix2;
int *matrixR;
int matrix1_fils;
int matrix1_cols;
int matrix2_fils;
int matrix2_cols;
pthread_t *thread_list;
pthread_mutex_t mutex;
int pending_jobs = 0;
struct job {
int i;
struct job *next;
};
struct job *job_list = 0;
struct job *last_job = 0;
void add_job(int i){
struct job *job = malloc(sizeof(struct job));
job->i = i;
job->next = 0;
if(pending_jobs == 0){
job_list = job;
last_job = job;
}
else{
last_job->next = job;
last_job = job;
}
pending_jobs++;
}
struct job* get_job(){
struct job *job = 0;
if(pending_jobs > 0){
job = job_list;
job_list = job->next;
if(job_list == 0){
last_job = 0;
}
pending_jobs--;
}
return job;
}
void do_job(struct job *job) {
int j, k, acum;
for (j = 0; j < matrix2_cols; j++) {
acum = 0;
for (k = 0; k < matrix1_cols; k++) {
acum += matrix1[job->i * matrix1_cols + k] * matrix2[k * matrix2_cols + j];
}
matrixR[job->i * matrix2_cols + j] = acum;
}
}
void* dispatch_job () {
struct job *job;
while(1) {
pthread_mutex_lock(&mutex);
job = get_job();
pthread_mutex_unlock(&mutex);
if (job) {
do_job(job);
free(job);
}
else {
pthread_exit(0);
}
}
}
int main (int argc, char **argv) {
if (argc > 3) {
printf("\\n%s %s %s %s\\n", argv[0], argv[1], argv[2], argv[3]);
matrix1_fils = strtol(argv[1], (char **) 0, 10);
matrix1_cols = strtol(argv[2], (char **) 0, 10);
matrix2_fils = matrix1_cols;
matrix2_cols = strtol(argv[3], (char **) 0, 10);
int i;
matrix1 = (int *) calloc(matrix1_fils * matrix1_cols, sizeof(int));
matrix2 = (int *) calloc(matrix2_fils * matrix2_cols, sizeof(int));
matrixR = (int *) malloc(matrix1_fils * matrix2_cols * sizeof(int));
init_matrix(matrix1, matrix1_fils, matrix1_cols);
init_matrix(matrix2, matrix2_fils, matrix2_cols);
for (i = 0; i < matrix1_fils; i++) {
add_job(i);
}
thread_list = malloc(sizeof(int) * 3);
pthread_mutex_init(&mutex, 0);
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
for (i = 0; i < 3; i++) {
pthread_create(&thread_list[i], &attr, dispatch_job, 0);
}
for (i = 0; i < 3; i++) {
pthread_join(thread_list[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
free(thread_list);
free(matrix1);
free(matrix2);
free(matrixR);
return 0;
}
fprintf(stderr, "Uso: %s filas_matriz1 columnas_matriz1 columnas_matriz2\\n", argv[0]);
return -1;
}
| 1
|
#include <pthread.h>
int bufer [10];
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
void * productor();
void * consumidor();
int main (){
srand(time(0));
pthread_t h1,h2;
pthread_mutex_lock(&m2);
pthread_create(&h1,0,&productor,0);
pthread_create(&h2,0,&consumidor,0);
pthread_join(h1,0);
pthread_join(h2,0);
printf("BUFFER :\\n");
int i;
for(i = 0; i<10; i++){
printf("%d",bufer[i]);
}
printf("\\n");
}
void * productor(){
int i;
for(i = 0; i<10; i++){
int valor = rand()% 9 + 1;
pthread_mutex_lock(&m1);
bufer[i] = valor;
pthread_mutex_unlock(&m2);
}
}
void * consumidor(){
int dato;
int i;
for(i = 0; i<10; i++){
pthread_mutex_lock(&m2);
dato = bufer[i];
printf("Consume: %d\\n",dato);
bufer[i] = 0;
pthread_mutex_unlock(&m1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int availA, availB;
int *map;
struct timeval start, end;
FILE *fp2;
void *
increment_count(void *arg)
{
int i;
char *letter = arg;
availA = 1;
availB = 0;
int read;
if (strcmp(letter, "A") == 0)
{
pthread_mutex_lock(&lock);
while (availA == 0)
pthread_cond_wait(&cond, &lock);
gettimeofday(&start, 0);
for (i = 0; i < (262144); i++) {
map[i] = 3 ;
}
availB = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
else
{
pthread_mutex_lock(&lock);
while (availB == 0)
pthread_cond_wait(&cond, &lock);
for (i = 0; i < (262144); i++) {
read = map[i];
}
gettimeofday(&end, 0);
pthread_mutex_unlock(&lock);
}
return 0;
}
int
main(int argc, char *argv[])
{
int fd, file_save = 0;
fp2 = fopen("/home/george/Documents/C/mmap-l.txt","a");
fd = open("/home/george/Documents/C/mmapped.bin", O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600);
lseek(fd, ((262144) * sizeof(int))-1, 0);
write(fd, "", 1);
map = mmap(0, ((262144) * sizeof(int)), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
for (file_save; file_save < 1000 ; file_save++)
{
pthread_t p1, p2;
Pthread_create(&p1, 0, increment_count, "A");
Pthread_create(&p2, 0, increment_count, "B");
Pthread_join(p1, 0);
Pthread_join(p2, 0);
long double time = ((long double)(end.tv_sec - start.tv_sec) +
((long double)(end.tv_usec - start.tv_usec)/1000000.0));
fprintf(fp2, "%Lf\\n",time);
fflush(fp2);
}
if (munmap(map, ((262144) * sizeof(int))) == -1) {
perror("Error un-mmapping the file");
}
close(fd);
fclose(fp2);
return 0;
}
| 1
|
#include <pthread.h>
static int get_linkstatu()
{
int fd;
int offset;
int ret=0;
fd = open("/dev/rdm0", O_RDONLY);
offset=0xB0110000;
ioctl(fd, 0x6B0D, &offset);
offset=0x80;
ioctl(fd, 0x6B03, &offset);
if(offset&(3<<28))
{
ret=1;
}
close(fd);
return ret;
}
int setKeepAlive()
{
int keepalive = 1;
int keepidle = 7;
int keepinterval = 1;
int keepcount = 3;
setsockopt(clientModelTCPSocket, SOL_SOCKET, SO_KEEPALIVE, (void *)&keepalive , sizeof(keepalive ));
setsockopt(clientModelTCPSocket, SOL_TCP, TCP_KEEPIDLE, (void*)&keepidle , sizeof(keepidle ));
setsockopt(clientModelTCPSocket, SOL_TCP, TCP_KEEPINTVL, (void *)&keepinterval , sizeof(keepinterval ));
setsockopt(clientModelTCPSocket, SOL_TCP, TCP_KEEPCNT, (void *)&keepcount , sizeof(keepcount ));
return 0;
}
int sendSocket(char *buffer, int bufferLen, char *type)
{
signal( SIGPIPE, SIG_IGN );
int result = -100;
errno = 0;
debug_msg ("type = %s\\n", type);
if (pthread_mutex_trylock(&g_pthTCPSocket) != 0){
debug_msg("result = -2");
result = -2;
}else{
if (g_isCreated) {
if (write(clientModelTCPSocket, buffer, bufferLen) != -1){
result = 0;
debug_msg("0");
pthread_mutex_unlock(&g_pthTCPSocket);
} else {
result = -1;
debug_msg("-1");
pthread_mutex_unlock(&g_pthTCPSocket);
}
} else {
result = -2;
pthread_mutex_unlock(&g_pthTCPSocket);
debug_msg("-2");
}
}
ret:
if (result == -100)
{
result = 2;
}
if (result == -1)
{
if (g_isChecking)
{
debug_msg ("g_bIsChecking is Running, don't start again.\\n");
}
else
{
debug_msg ("g_bIsChecking is not Running, should start it.\\n");
sem_post(&g_semConnectionCheck);
}
}
debug_msg ("sendSocket Result = %d\\n", result);
return result;
}
| 0
|
#include <pthread.h>
int connfd;
int threadId;
} thread_data;
pthread_mutex_t file_lock;
void* processRequest(void* t){
thread_data* t_data = (thread_data*)t;
int connfd = t_data->connfd;
int threadId = t_data->threadId;
char textBuf[160];
int readLen;
while ( (readLen=Read(connfd, textBuf, sizeof(textBuf))) > 0){
if(!strstr(textBuf, "/exit")){
pthread_mutex_lock(&file_lock);
FILE* fp = Fopen("logfile.txt", "a+");
printf("%s",textBuf);
Fwrite(textBuf, sizeof(char), readLen, fp);
bzero(&textBuf, sizeof(textBuf));
Fclose(fp);
pthread_mutex_unlock(&file_lock);
} else {
printf("Finished reading from the client %d\\n", threadId+1);
break;
}
}
Close(connfd);
return 0;
}
int main(int argc, char* argv[]){
int port;
int sockfd;
int enable = 1;
int threadId = 0;
pthread_t threads[25];
thread_data t_data[25];
pthread_mutex_init(&file_lock, 0);
FILE* reset = Fopen("logfile.txt", "w");
Fclose(reset);
if (argc != 2) {
fprintf(stderr, "Usage: %s <port number>\\n", argv[0]);
exit(0);
}
port = atoi(argv[1]);
sockfd = Socket(AF_INET, SOCK_STREAM, 0);
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
perror("setsockopt: ");
struct sockaddr_in servaddr;
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(port);
Bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
Listen(sockfd, LISTENQ);
for(;;threadId++){
printf("Waiting for a new client connection... \\n");
int connfd;
connfd = Accept(sockfd, 0, 0);
printf("Got a connection from a new client\\n");
if(threadId <= 25){
t_data[threadId].connfd = connfd;
t_data[threadId].threadId = threadId;
Pthread_create(&threads[threadId], 0, processRequest, (void*)&t_data[threadId]);
} else {
printf("Thread Limit Reached\\n");
threadId = 0;
int i;
for(i = 0; i < 25; ++i){
Pthread_join(threads[i], 0);
}
}
}
Close(sockfd);
return 0;
}
| 1
|
#include <pthread.h>
int variableCompartidaSuma = 0;
int elementosPitagoricos[4] = {1, 2, 3, 4};
pthread_mutex_t mi_mutex;
void* sumarValor (void* parametro){
int posArray;
posArray = (intptr_t) parametro;
printf("Sumando posicion = %d \\n", posArray);
pthread_mutex_lock(&mi_mutex);
int aux = variableCompartidaSuma;
int microseconds; srand (time(0));
microseconds = rand() % 1000 + 1;
usleep(microseconds);
aux = aux + elementosPitagoricos[posArray];
variableCompartidaSuma=aux;
pthread_mutex_unlock(&mi_mutex);
pthread_exit(0);
}
int main (){
pthread_t threads[4];
pthread_mutex_init ( &mi_mutex, 0);
int rc;
int i;
for( i=0; i < 4; i++ ){
printf("main() : creando thread %d \\n", i);
rc = pthread_create(&threads[i],
0,
sumarValor,
(void *)(intptr_t) i);
if (rc){
printf("Error:unable to create thread, %d \\n", rc);
exit(-1);
}
}
for(i = 0 ; i < 4 ; i++){
pthread_join(threads[i] , 0);
}
printf("El numero de la perfeccion es : %d \\n", variableCompartidaSuma);
pthread_mutex_destroy( &mi_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t error_mutex = PTHREAD_MUTEX_INITIALIZER ;
static pthread_mutex_t debug_mutex = PTHREAD_MUTEX_INITIALIZER ;
static pthread_mutex_t verbose_mutex = PTHREAD_MUTEX_INITIALIZER ;
static int xverbose_max_level=0;
static int xdebug_max_level=0;
static int xerror_max_level=1;
static FILE* xerror_stream = 0;
static FILE* xverbose_stream = 0;
static FILE* xdebug_stream = 0;
void xverbose_base(int level,char* format,va_list args);
void xdebug_base(int level,char* format,va_list args);
void xerror_setstream(FILE* stream){
xerror_stream=stream;
}
void xerror_setmaxlevel(int level){
xerror_max_level=level;
}
void xerror(char* format,...){
char time_string[64];
time_t current_time;
FILE* default_stream=stdout;
FILE* stream;
if(!xerror_max_level)
return;
if(xerror_stream==0)
stream=default_stream;
else
stream=xerror_stream;
va_list args;
__builtin_va_start((args));
time(¤t_time);
ctime_r(¤t_time,time_string);
time_string[strlen(time_string)-1]='\\0';
pthread_mutex_lock(&error_mutex);
fprintf(stream,"%s [ERROR] ",time_string);
vfprintf(stream,format,args);
fprintf(stream,"\\n");
fflush(stream);
pthread_mutex_unlock(&error_mutex);
;
}
void xverbose_setstream(FILE* stream){
xverbose_stream=stream;
}
void xverbose_setmaxlevel(int level){
xverbose_max_level=level;
}
void xverbose_base(int level,char* format,va_list args){
char time_string[64];
time_t current_time;
FILE* default_stream=stdout;
FILE* stream;
if(xverbose_stream==0)
stream=default_stream;
else
stream=xverbose_stream;
if(level<=xverbose_max_level){
time(¤t_time);
ctime_r(¤t_time,time_string);
time_string[strlen(time_string)-1]='\\0';
pthread_mutex_lock(&verbose_mutex);
fprintf(stream,"%s [INFO%d] ",time_string,level);
vfprintf(stream,format,args);
fprintf(stream,"\\n");
fflush(stream);
pthread_mutex_unlock(&verbose_mutex);
}
}
void xverbose(char* format,...){
int level=XVERBOSE_LEVEL_1;
va_list args;
__builtin_va_start((args));
xverbose_base(level,format,args);
;
}
void xverbose2(char* format,...){
int level=XVERBOSE_LEVEL_2;
va_list args;
__builtin_va_start((args));
xverbose_base(level,format,args);
;
}
void xverbose3(char* format,...){
int level=XVERBOSE_LEVEL_3;
va_list args;
__builtin_va_start((args));
xverbose_base(level,format,args);
;
}
void xverboseN(int level,char* format,...){
if(level>9)
level=9;
va_list args;
__builtin_va_start((args));
xverbose_base(level,format,args);
;
}
void xdebug_setmaxlevel(int level){
xdebug_max_level=level;
}
void xdebug_setstream(FILE* stream){
xdebug_stream=stream;
}
void xdebug_base(int level,char* format,va_list args){
char time_string[64];
time_t current_time;
FILE* default_stream=stdout;
FILE* stream;
if(xdebug_stream==0)
stream=default_stream;
else
stream=xdebug_stream;
if(level<=xdebug_max_level){
time(¤t_time);
ctime_r(¤t_time,time_string);
time_string[strlen(time_string)-1]='\\0';
pthread_mutex_lock(&debug_mutex);
fprintf(stream,"%s [DBUG%d] ",time_string,level);
vfprintf(stream,format,args);
fprintf(stream,"\\n");
fflush(stream);
pthread_mutex_unlock(&debug_mutex);
}
}
void xdebug(char* format,...){
int level=XDEBUG_LEVEL_1;
va_list args;
__builtin_va_start((args));
xdebug_base(level,format,args);
;
}
void xdebug2(char* format,...){
int level=XDEBUG_LEVEL_2;
va_list args;
__builtin_va_start((args));
xdebug_base(level,format,args);
;
}
void xdebug3(char* format,...){
int level=XDEBUG_LEVEL_3;
va_list args;
__builtin_va_start((args));
xdebug_base(level,format,args);
;
}
void xdebugN(int level,char* format,...){
if(level>9)
level=9;
va_list args;
__builtin_va_start((args));
xdebug_base(level,format,args);
;
}
| 1
|
#include <pthread.h>
void *func(int n);
void disp_philo_states();
void chopstickStates(int n);
pthread_t philosopher[5];
pthread_mutex_t mutex,chopstickLock[5];
int eatCount[5] = {0,0,0,0,0};
HUNGRY,
EATING,
THINKING
} philos_state;
FREE = 0,
IN_USE = 1
} Sticks;
philos_state state[5];
Sticks chopstick[5];
pthread_cond_t self[5];
int main()
{
int i,k;
pthread_mutex_init(&mutex,0);
for(i=0;i<5;i++){
state[i] = THINKING;
chopstick[i] = FREE;
pthread_mutex_init(&chopstickLock[i],0);
pthread_cond_init(&self[i],0);
}
for(i=0;i<5;i++)
{
k=pthread_create(&philosopher[i],0,(void *)func,(void *)i);
if(k!=0)
{
printf("\\n Thread creation error \\n");
exit(1);
}
}
for(i=0;i<5;i++){
pthread_join(philosopher[i], 0);
}
return 0;
}
void takechopstick(int i){
pthread_mutex_lock(&mutex);
disp_philo_states();
state[i] = HUNGRY;
while(chopstick[i] == IN_USE || chopstick[((i+1)%5)] == IN_USE){
pthread_cond_wait(&self[i], &mutex);
}
state[i] = EATING;
chopstick[i] = IN_USE;
chopstick[((i+1)%5)] = IN_USE;
pthread_mutex_unlock(&mutex);
}
void releasechopstick(int i){
pthread_mutex_lock(&mutex);
disp_philo_states();
state[i] = THINKING;
chopstick[i] = FREE;
chopstick[((i+1)%5)] = FREE;
pthread_cond_signal(&self[((i+5 -1)%5)]);
pthread_cond_signal(&self[((i+1)%5)]);
pthread_mutex_unlock(&mutex);
}
void think(int n){
int i;
printf("%d statrted THINKING \\n",n );
for(i = 0; i < 100000000; i++) {
}
printf("%d ended THINKING \\n",n );
}
void eat(int n){
int i;
eatCount[n]++;
printf("%d statrted EATING \\n",n );
for(i = 0; i < 500000000; i++) {
}
printf("%d ended EATING \\n",n );
}
void *func(int n)
{
while(1){
think(n);
takechopstick(n);
eat(n);
releasechopstick(n);
}
}
char convertStates(philos_state philoState)
{
if(philoState == EATING) {
return 'E';
}
else if(philoState == THINKING) {
return 'T';
}
else {
return 'H';
}
return '-';
}
void disp_philo_states()
{
int i;
for(i = 0; i < 5; i++) {
if(state[i] == EATING && (state[((i+5 -1)%5)] == EATING || state[((i+1)%5)] == EATING)) {
printf("OUPS! Something went wrong...\\n\\n");
break;
}
}
for(i = 0; i < 5; i++) {
printf("%d%c ", i, convertStates(state[i]));
}
printf("\\n");
printf("Current Eat count\\n");
for(i = 0; i < 5; i++) {
printf("%d->%d ", i, eatCount[i]);
}
printf("\\n\\n");
}
char convertChops(Sticks s){
if(s == FREE) return 'F';
else return 'U';
return '-';
}
void chopstickStates(int n){
int i;
printf("called by thread %d \\n",n );
for(i = 0; i < 5; i++) {
printf("%d%c ", i, convertChops(chopstick[i]));
}
printf("\\n\\n");
}
| 0
|
#include <pthread.h>
sem_t sem_producer;
sem_t sem_consumer;
unsigned int count;
unsigned int data[12];
int in;
int out;
pthread_mutex_t mutex;
pthread_cond_t empty;
pthread_cond_t full;
} buffer_t;
static buffer_t shared_buffer = {
.count = 0,
.in = 0,
.out = 0,
.mutex = PTHREAD_MUTEX_INITIALIZER,
.empty = PTHREAD_COND_INITIALIZER,
.full = PTHREAD_COND_INITIALIZER
};
static int
next()
{
static unsigned int cnt = 0;
return ++cnt;
}
static void
check(unsigned int num)
{
static unsigned int cnt = 0;
if (num != ++cnt) {
fprintf(stderr, "oops: expected %u but got %u\\n", cnt, num);
}
}
static void*
producer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while(1){
sem_wait(&(sem_producer));
pthread_mutex_lock(&(buffer->mutex));
while(buffer->count == 12){
printf("Naaahhhahahah! Queue is full!!\\n");
}
buffer->data[buffer->in] = next();
buffer->in = (buffer->in + 1) % 12;
buffer->count++;
printf("Producer:%d\\n", buffer->in);
sleep(1);
pthread_mutex_unlock(&(buffer->mutex));
sem_post(&(sem_consumer));
}
return 0;
}
static void*
consumer(void *data)
{
buffer_t *buffer = (buffer_t *) data;
while(1)
{
sem_wait(&(sem_consumer));
pthread_mutex_lock(&(buffer->mutex));
while(buffer->count == 0){
printf("I NEED MORE ITEMS!!!\\n");
}
check(buffer->data[buffer->out]);
buffer->out = (buffer->out + 1) % 12;
buffer->count--;
printf("Consumer:%d\\n", buffer->out);
pthread_mutex_unlock(&(buffer->mutex));
sem_post(&(sem_producer));
}
return 0;
}
static int
run(int nc, int np)
{
int i, n = nc + np;
pthread_t thread[n];
buffer_t* buffer;
if(sem_init(&(sem_producer),0,1))
{
fprintf(stderr, "Initialization failure of sema_producer");
}
if(sem_init(&(sem_producer),0,1))
{
fprintf(stderr, "Initialization failure of smea_consumer");
}
for (i = 0; i < n; i++) {
if (pthread_create(&thread[i], 0,
i < nc ? consumer : producer, &shared_buffer)) {
fprintf(stderr, "thread creation failed\\n");
return 1;
}
}
for (i = 0; i < n; i++) {
if (thread[i]) pthread_join(thread[i], 0);
}
return 0;
}
int
main(int argc, char **argv)
{
int c, nc = 1, np = 1;
const char *usage
= "Usage: bounded [-c consumers] [-p producers] [-h]\\n";
while ((c = getopt(argc, argv, "c:p:h")) >= 0) {
switch (c) {
case 'c':
if ((nc = atoi(optarg)) <= 0) {
fprintf(stderr, "number of consumers must be > 0\\n");
exit(1);
}
break;
case 'p':
if ((np = atoi(optarg)) <= 0) {
fprintf(stderr, "number of producers must be > 0\\n");
exit(1);
}
break;
case 'h':
printf(usage);
exit(0);
}
}
return run(nc, np);
}
| 1
|
#include <pthread.h>
static struct scap_tasks * scap_tasks = 0;
void scapremedy_process_init()
{
assert ( scap_tasks == 0 );
scap_tasks = rscap_alloc(sizeof ( *scap_tasks ));
scap_tasks->tasks = 0;
scap_tasks->task_id_counter = 1;
pthread_mutex_init(&scap_tasks->mx, 0);
}
struct scap_task * scap_task_new(const char * path, const char * dir)
{
struct scap_task * ret = rscap_zalloc(sizeof(*ret));
pthread_mutex_lock(&scap_tasks->mx);
ret->path = rscap_strdup(path);
ret->dir = rscap_strdup(dir);
ret->task_id = scap_tasks->task_id_counter++;
ret->next = scap_tasks->tasks;
pthread_mutex_init(&ret->mx, 0);
scap_tasks->tasks = ret;
pthread_mutex_unlock(&scap_tasks->mx);
return ret;
}
static void * _scapremedy_job_cleaner(void * arg)
{
struct rscap_hash * cfg = (struct rscap_hash*)arg;
const char * user, * group;
user = rscap_config_get(cfg, "ScapComm.RunAsUser");
group = rscap_config_get(cfg, "ScapComm.RunAsGroup");
if ( group == 0 ) group = user;
for ( ;; )
{
struct scap_task * task;
struct scap_task * prev = 0;
sleep(15);
pthread_mutex_lock(&scap_tasks->mx);
task = scap_tasks->tasks;
while ( task != 0 )
{
pthread_mutex_lock(&task->mx);
if ( task->finished != 0 )
{
char * qpath;
void * unused;
struct scap_task * next;
pthread_join(task->thread, &unused);
qpath = rscap_mk_path(RSCAP_REMEDY_RESULTS_DIR, task->dir, 0);
if ( rscap_rename_dir(task->path, qpath) < 0 )
{
rscap_log("Could not rename %s to %s -- %s\\n", task->path, qpath, rscap_strerror());
rscap_recursive_rmdir(task->path);
}
if ( rscap_chown_dir(qpath, user, group) < 0 )
{
rscap_log("Could not chown %s to %s:%s - %s\\n", qpath, user, group, rscap_strerror());
rscap_recursive_rmdir(qpath);
}
rscap_free(task->path);
rscap_free(task->dir);
if ( prev != 0 ) prev->next = task->next;
else scap_tasks->tasks = task->next;
pthread_mutex_unlock(&task->mx);
pthread_mutex_destroy(&task->mx);
next = task->next;
rscap_free(task);
task = next;
}
else {
pthread_mutex_unlock(&task->mx);
task = task->next;
}
}
pthread_mutex_unlock(&scap_tasks->mx);
}
return 0;
}
void scapremedy_job_cleaner(struct rscap_hash * cfg)
{
pthread_t thr;
void * arg = (void*)cfg;
pthread_create(&thr, 0, _scapremedy_job_cleaner, arg);
pthread_detach(thr);
}
int scapremedy_job_count()
{
struct scap_task * task;
int cnt = 0;
pthread_mutex_lock(&scap_tasks->mx);
task = scap_tasks->tasks;
while (task != 0)
{
cnt ++;
task = task->next;
}
pthread_mutex_unlock(&scap_tasks->mx);
return cnt;
}
int scapremedy_process_entry(struct rscap_signature_cfg * sig_cfg, const char * directory, const char * path)
{
char * qpath = 0;
char * rpath = 0;
char * entry = 0;
struct scap_task * task;
if ( directory == 0 || path == 0 ) return -1;
rscap_log("Received new job -- %s\\n", path);
qpath = rscap_mk_path(directory, path, 0);
rpath = rscap_mk_path(RSCAP_REMEDY_RUNNING_DIR, path, 0);
if ( rscap_rename_dir(qpath, rpath) < 0 )
{
rscap_log("Could not rename %s to %s -- %s\\n", qpath, rpath, rscap_strerror());
goto err;
}
entry = rscap_mk_path(RSCAP_REMEDY_RUNNING_DIR, path, "remediation.tgz", 0);
if ( rscap_file_readable(entry) )
{
rscap_log("%s is an invalid remediation job (%s does not exist) -- deleting it", path, entry);
rscap_recursive_rmdir(rpath);
goto err;
}
rscap_free(entry);
entry = 0;
task = scap_task_new(rpath, path);
task->sig_cfg = sig_cfg;
scapremedy_exec_script(task);
if ( qpath != 0 ) rscap_free(qpath);
if ( rpath != 0 ) rscap_free(rpath);
return 0;
err:
if ( qpath != 0 ) rscap_free(qpath);
if ( rpath != 0 ) rscap_free(rpath);
if ( entry != 0 ) rscap_free(entry);
return -1;
}
| 0
|
#include <pthread.h>
{
int adj_n;
int pre;
int min_d;
int *adj;
int *w;
}vertex;
pthread_mutex_t mutex;
pthread_mutex_t *mutex_v;
vertex *vertices;
int *work_q;
int vertex_n, head, tail, terminate, count, qsize, notused;
double diff(struct timespec start, struct timespec end){
double temp;
temp = end.tv_sec - start.tv_sec + (end.tv_nsec-start.tv_nsec)/1000000000.0;
return temp;
}
void *UpdateD() {
int current, i, j, cur_pos, next, enqueue, new_d;
double t_lock = 0.0;
double t_cal = 0.0;
struct timespec tl1, tl2, tc1, tc2;
while(terminate != 1){
pthread_mutex_lock(&mutex);
current = work_q[head];
cur_pos = head;
if(current != -1)head = (head+1)%qsize;
pthread_mutex_unlock(&mutex);
if(current != -1){
for(i=0; i<vertices[current].adj_n; i++){
next = vertices[current].adj[i];
new_d = vertices[current].w[i] + vertices[current].min_d;
pthread_mutex_lock(&mutex_v[next]);
if(new_d < vertices[next].min_d){
vertices[next].min_d = new_d;
vertices[next].pre = current;
pthread_mutex_unlock(&mutex_v[next]);
enqueue = 1;
pthread_mutex_lock(&mutex);
if(head<=tail){
for(j=head+1; j<tail; j++){
if(work_q[j] == next)enqueue = 0;
}
}
else{
for(j=head+1; j<qsize; j++){
if(work_q[j] == next)enqueue = 0;
}
for(j=0; j<tail; j++){
if(work_q[j] == next)enqueue = 0;
}
}
if(enqueue == 1){
work_q[tail] = next;
tail=(tail+1)%qsize;
}
pthread_mutex_unlock(&mutex);
}
else {
pthread_mutex_unlock(&mutex_v[next]);
}
}
work_q[cur_pos] = -1;
}
}
pthread_exit(0);
}
int main (int argc, char *argv[]) {
int thread_n, vertex_s, edge_n, i, temp;
FILE *fh;
pthread_t *threads;
double t_io = 0.0;
double t_all = 0.0;
struct timespec tio1, tio2, ta1;
thread_n = atof(argv[1]);
vertex_s = atof(argv[4])-1;
fh=fopen(argv[2],"r");
fscanf(fh,"%d%d", &vertex_n, &edge_n);
qsize = thread_n+edge_n;
threads = malloc(thread_n*sizeof(pthread_t));
mutex_v = malloc(vertex_n*sizeof(pthread_mutex_t));
vertices = malloc(vertex_n*sizeof(vertex));
work_q = malloc(qsize*sizeof(int));
for (i=0; i<vertex_n; i++) vertices[i].adj = malloc(vertex_n*sizeof(int));
for (i=0; i<vertex_n; i++) vertices[i].w = malloc(vertex_n*sizeof(int));
for (i=0; i<vertex_n; i++){
vertices[i].adj_n = 0;
vertices[i].min_d = 32767;
pthread_mutex_init(&mutex_v[i], 0);
}
for(i=0; i<qsize; i++)work_q[i]=-1;
vertices[vertex_s].min_d = 0;
vertices[vertex_s].pre = -1;
work_q[0] = vertex_s;
head = 0;
tail = 1;
terminate = 0;
int x, y, z;
for (i=0; i<edge_n; i++){
fscanf(fh,"%d%d%d",&x,&y,&z);
x--;
y--;
vertices[x].adj[vertices[x].adj_n]=y;
vertices[x].w[vertices[x].adj_n]=z;
vertices[x].adj_n++;
vertices[y].adj[vertices[y].adj_n]=x;
vertices[y].w[vertices[y].adj_n]=z;
vertices[y].adj_n++;
}
fclose(fh);
pthread_mutex_init (&mutex, 0);
for(i=0; i<thread_n; i++){
pthread_create(&threads[i], 0, UpdateD, 0);
}
while(terminate != 1){
temp = 1;
pthread_mutex_lock(&mutex);
for(i=0; i<qsize; i++){
if(work_q[i]!=-1) temp = 0;
}
pthread_mutex_unlock(&mutex);
terminate = temp;
}
char buffer [512];
char result [512];
fh=fopen(argv[3],"w");
for(i=0; i<vertex_n; i++){
sprintf(result, "%d",i+1);
vertex now = vertices[i];
if(now.pre==-1)sprintf(result, "%d %d", i+1, i+1);
while(now.pre!=-1){
sprintf(buffer, "%d %s", now.pre+1, result);
strcpy(result, buffer);
now = vertices[now.pre];
}
fprintf(fh,"%s\\n", result);
}
fclose(fh);
pthread_mutex_destroy(&mutex);
for (i=0; i<vertex_n; i++){
pthread_mutex_destroy(&mutex_v[i]);
}
for (i=0; i<vertex_n; i++) free(vertices[i].adj);
for (i=0; i<vertex_n; i++) free(vertices[i].w);
free(vertices);
free(work_q);
free(threads);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t forkLock[10000000];
int numOfTimesToEat;
int philosophers;
void dinning(int numOfPhil, int numOfEating) {
numOfTimesToEat = numOfEating;
philosophers = numOfPhil;
pthread_t people[numOfPhil];
for (long i = 0; i <= numOfPhil; i++) {
pthread_mutex_init(&forkLock[i], 0);
}
for (long i = 0; i < numOfPhil; i++) {
pthread_create(&people[i], 0, readyToEat,(void*)i);
}
for (int j = 0; j < numOfPhil; j++) {
pthread_join(people[j], 0);
}
}
void *readyToEat(void * ID) {
long id;
int i = 0;
id = (long)ID;
printf("Philosopher %ld is thinking.\\n", id+1);
while (i < numOfTimesToEat) {
sleep(1);
int index = 0;
if (id == 0) {
index = philosophers-1;
}
else {
index = id-1;
}
int lock1 = pthread_mutex_lock(&forkLock[id]);
int lock2 = pthread_mutex_lock(&forkLock[index]);
if (lock1 == 0 && lock2 == 0) {
printf("Philosopher %ld is eating.\\n", id+1);
i = i + 1;
sleep(1);
}
printf("Philosopher %ld is thinking.\\n", id+1);
pthread_mutex_unlock(&forkLock[id]);
pthread_mutex_unlock(&forkLock[index]);
}
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int size = 100;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct matrixs
{
int matrixA[500][500];
int matrixB[500][500];
int solution[500][500];
long id;
};
void fillArrays(struct matrixs *);
void printArray(struct matrixs *);
void *multiply( void *param);
int main()
{
srand(1);
pthread_t tids[4];
long t;
void *status;
struct matrixs MyMatrixs;
fillArrays(&MyMatrixs);
for (t = 1; t <= 4; t++)
{
pthread_mutex_lock(&mutex);
MyMatrixs.id = (long) t;
pthread_create( &tids[t], 0, multiply, (void *) &MyMatrixs);
wait(10);
}
for (t = 1; t <= 4; t++)
{
pthread_join( tids[t], &status );
}
printArray(&MyMatrixs);
return 0;
}
void *multiply( void *param)
{
struct matrixs *MyMatrixs = param;
long threadId = MyMatrixs->id;
int i,j,k;
pthread_mutex_unlock(&mutex);
int start, end, temp;
temp = size / 4;
start = (threadId - 1) * temp;
end = (threadId == 4) ? size : threadId * temp;
for(i = start; i < end; i++)
{
for(j = 0;j < size; j++)
{
for(k = 0; k < size; k++)
{
MyMatrixs->solution[i][j] += MyMatrixs->matrixA[i][k] * MyMatrixs->matrixB[k][j];
}
}
}
pthread_exit(0);
}
void fillArrays(struct matrixs *m)
{
int i, j;
for(i=0; i < size; i++)
{
for(j=0; j< size; j++)
{
m->matrixA[i][j] = rand() % 10;
m->matrixB[i][j] = rand() % 10;
}
}
}
void printArray(struct matrixs *m)
{
int i, j;
for(i = 0; i < size; i++)
{
for(j = 0; j < size; j++)
{
printf("%4d ", m->solution[i][j]);
}
printf("\\n");
}
printf("\\n\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t muta;
pthread_cond_t cv;
int cnt;
pthread_t threads[10];
void *inc_cnt(void *arg) {
int i;
int idx = (*(int *) arg);
for (i = 0; i < 10 +10; i++) {
sleep(1);
if (cnt > 10) {
pthread_exit(0);
}
pthread_mutex_lock(&muta);
cnt++;
if (cnt == 10) {
printf("thread %d trigger signal\\n", idx);
pthread_cond_signal(&cv);
printf("Signal!");
}
printf("--\\n");
pthread_mutex_unlock(&muta);
}
pthread_exit(0);
}
void *wait_cnt(void *arg) {
int idx = (*(int *)arg);
printf("thread %d starts waiting\\n", idx);
pthread_mutex_lock(&muta);
pthread_cond_wait(&cv, &muta);
printf("Finally thread %d ends waiting;\\n", idx);
pthread_mutex_unlock(&muta);
pthread_exit(0);
}
int main() {
int i;
int rc = 0;
cnt = 0;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&muta, 0);
pthread_cond_init(&cv, 0);
for (i = 0; i < 10 - 1; i++) {
rc = pthread_create(&threads[i], &attr, inc_cnt, &i);
if (rc) {
printf("create failure, rc = %d\\n", rc);
exit(0);
}
}
rc = pthread_create(&threads[i], &attr, wait_cnt, &i);
for (i = 0; i < 10; i++) {
rc = pthread_join(threads[i], 0);
if (rc) {
printf("pthread_join fails %d\\n", rc);
}
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&muta);
pthread_cond_destroy(&cv);
return 0;
}
| 0
|
#include <pthread.h>
struct atomicqueueitem
{
void *object;
struct atomicqueueitem *next;
};
struct atomicqueue
{
struct atomicqueueitem *head;
pthread_mutex_t mutex;
};
struct atomicqueue *atomicqueue_create()
{
struct atomicqueue *queue = malloc(sizeof(struct atomicqueue));
if (!queue)
return 0;
pthread_mutex_init(&queue->mutex, 0);
queue->head = 0;
return queue;
}
void atomicqueue_destroy(struct atomicqueue *queue)
{
pthread_mutex_lock(&queue->mutex);
while (queue->head != 0)
{
struct atomicqueueitem *next = queue->head->next;
free(queue->head->object);
free(queue->head);
queue->head = next;
}
pthread_mutex_unlock(&queue->mutex);
pthread_mutex_destroy(&queue->mutex);
free(queue);
}
bool atomicqueue_push(struct atomicqueue *queue, void *object)
{
struct atomicqueueitem *tail = malloc(sizeof(struct atomicqueueitem));
if (!tail)
return 0;
tail->object = object;
tail->next = 0;
pthread_mutex_lock(&queue->mutex);
if (queue->head == 0)
queue->head = tail;
else
{
struct atomicqueueitem *item = queue->head;
while (item->next != 0)
item = item->next;
item->next = tail;
}
pthread_mutex_unlock(&queue->mutex);
return 1;
}
void *atomicqueue_pop(struct atomicqueue *queue)
{
pthread_mutex_lock(&queue->mutex);
if (queue->head == 0)
{
pthread_mutex_unlock(&queue->mutex);
return 0;
}
struct atomicqueueitem *head = queue->head;
queue->head = queue->head->next;
pthread_mutex_unlock(&queue->mutex);
void *object = head->object;
free(head);
return object;
}
size_t atomicqueue_length(struct atomicqueue *queue)
{
pthread_mutex_lock(&queue->mutex);
size_t count = 0;
if (queue->head != 0)
{
count++;
struct atomicqueueitem *item = queue->head;
while ((item = item->next) != 0)
count++;
}
pthread_mutex_unlock(&queue->mutex);
return count;
}
| 1
|
#include <pthread.h>
static int si_init_flag = 0;
static int s_conf_fd = -1;
static struct sockaddr_un s_conf_addr ;
static int s_buf_index = 0;
static char s_buf_pool[4][(16384)];
static pthread_mutex_t s_atomic;
static char CONF_LOCAL_NAME[16] = "/tmp/rptClient";
inline int rptSockSetLocal(const char * pLocalName)
{
if (pLocalName)
{
snprintf(CONF_LOCAL_NAME, 15, pLocalName);
return 0;
}
else
return -1;
}
int rptSockInit()
{
if (si_init_flag)
return 0;
s_conf_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
if (s_conf_fd < 0)
{
return -1;
}
if (0 != pthread_mutex_init(&s_atomic, 0))
{
close(s_conf_fd);
s_conf_fd = -1;
return -1;
}
unlink(CONF_LOCAL_NAME);
bzero(&s_conf_addr , sizeof(s_conf_addr));
s_conf_addr.sun_family = AF_UNIX;
snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), CONF_LOCAL_NAME);
bind(s_conf_fd, (struct sockaddr *)&s_conf_addr, sizeof(s_conf_addr));
bzero(&s_conf_addr , sizeof(s_conf_addr));
s_conf_addr.sun_family = AF_UNIX;
snprintf(s_conf_addr.sun_path, sizeof(s_conf_addr.sun_path), "/tmp/rptServer");
si_init_flag = 1;
return 0;
}
int rptSockUninit()
{
if (!si_init_flag)
return 0;
cfgSockSaveFiles();
if (s_conf_fd > 0)
{
close(s_conf_fd);
}
s_conf_fd = -1;
unlink(CONF_LOCAL_NAME);
pthread_mutex_destroy(&s_atomic);
si_init_flag = 0;
return 0;
}
static int rptSockSend(const char *command)
{
int ret = -1 ;
int addrlen = sizeof(s_conf_addr) ;
int len = strlen(command);
if (!si_init_flag)
return -1;
ret = sendto(s_conf_fd , command, len, 0,
(struct sockaddr *)&s_conf_addr , addrlen);
if (ret != len)
{
close(s_conf_fd) ;
s_conf_fd = -1;
ret = -1 ;
si_init_flag = 0;
syslog(LOG_ERR, "send conf message failed , ret = %d , errno %d\\n", ret, errno);
}
return ret ;
}
static int rptSockRecv(char * buf, int len)
{
int ret;
if (!si_init_flag)
return -1;
ret = recv(s_conf_fd , buf, len-1, 0);
if (ret > 0)
buf[ret] = '\\0';
else
buf[0] = '\\0';
return ret;
}
static int rptSockRequest(const char* command, char *recvbuf, int recvlen)
{
int ret;
if (!command || !recvbuf || !recvlen)
return -1;
ret = rptSockSend(command);
if (ret >= 0)
{
ret = rptSockRecv(recvbuf, recvlen);
}
return ret;
}
int rptSockSendInfo(const char *pInfo, const char *pValue, int bSendNow)
{
int nRet = -1;
char *_buf;
if (!si_init_flag || !pInfo || !pValue)
return 0;
pthread_mutex_lock(&s_atomic);
_buf = s_buf_pool[s_buf_index];
s_buf_index += 1;
s_buf_index &= 3;
if (bSendNow)
snprintf(_buf, (16384), "REP %s %s", pInfo, pValue);
else
snprintf(_buf, (16384), "SET %s %s", pInfo, pValue);
rptSockRequest(_buf, _buf, (16384));
pthread_mutex_unlock(&s_atomic);
nRet = strncmp(_buf, "OK", 4);
return (0 == nRet)? 0 : -1;
}
int rptSockClearInfo(const char *pInfo)
{
int nRet = -1;
char *_buf;
if (!si_init_flag || !pInfo)
return -1;
pthread_mutex_lock(&s_atomic);
_buf = s_buf_pool[s_buf_index];
s_buf_index += 1;
s_buf_index &= 3;
snprintf(_buf, (16384), "CLR %s", pInfo);
rptSockRequest(_buf, _buf, (16384));
pthread_mutex_unlock(&s_atomic);
nRet = strncmp(_buf, "OK", 4);
return (0 == nRet)? 0 : -1;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_assume(int);
extern void __VERIFIER_error() ;
void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error();}; return; }
const int SIGMA = 3;
int *array;
int array_index=-1;
pthread_mutex_t mutexes[SIGMA];
pthread_mutex_t mutex_index = PTHREAD_MUTEX_INITIALIZER;
void *thread(void * arg)
{
int i;
pthread_mutex_lock (&mutex_index);
i = array_index;
pthread_mutex_unlock (&mutex_index);
pthread_mutex_lock (mutexes + i);
array[i] = 1;
pthread_mutex_unlock (mutexes + i);
return 0;
}
int main()
{
int tid, sum;
pthread_t *t;
t = (pthread_t *)malloc(sizeof(pthread_t) * SIGMA);
array = (int *)malloc(sizeof(int) * SIGMA);
__VERIFIER_assume(t != 0);
__VERIFIER_assume(array != 0);
for (tid = 0; tid < SIGMA; tid++) pthread_mutex_init (mutexes + tid, 0);
for (tid=0; tid<SIGMA; tid++) {
pthread_mutex_lock (&mutex_index);
array_index++;
pthread_mutex_unlock (&mutex_index);
pthread_create(&t[tid], 0, thread, 0);
}
for (tid=0; tid<SIGMA; tid++) {
pthread_join(t[tid], 0);
}
for (tid=sum=0; tid<SIGMA; tid++) {
sum += array[tid];
}
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t text_message_mutex = PTHREAD_MUTEX_INITIALIZER;
static char text_message[300];
int setup_text_message(void)
{
if (pthread_mutex_init(&text_message_mutex, 0) != 0)
{
return error(ERROR, "Unable to create usb mutex.");
}
pthread_mutex_lock(&text_message_mutex);
*text_message = 0;
pthread_mutex_unlock(&text_message_mutex);
return NOERROR;
}
void send_wfs_text_message(char *fmt, ...)
{
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(&text_message_mutex);
vsprintf(text_message, fmt, args);
pthread_mutex_unlock(&text_message_mutex);
}
void broadcast_text_message(void)
{
struct smessage message;
pthread_mutex_lock(&text_message_mutex);
if (strlen(text_message) == 0)
{
pthread_mutex_unlock(&text_message_mutex);
return;
}
message.type = WFS_TEXT_MESSAGE;
message.data = (unsigned char *)text_message;
message.length = strlen(text_message)+1;
server_send_message_all(&message);
*text_message = 0;
pthread_mutex_unlock(&text_message_mutex);
}
| 0
|
#include <pthread.h>
STACK stack_init(size_t capacity);
bool stack_destroy(STACK *s);
bool stack_push(STACK s, uintptr_t *item);
bool stack_pop(STACK s, uintptr_t *item);
bool stack_look(STACK s, uintptr_t *item);
size_t stack_size(STACK s);
bool stack_empty(STACK s);
bool stack_full(STACK s);
struct StackStruct {
Node top;
pthread_mutex_t mxlock;
size_t capacity;
size_t count;
};
struct NodeStruct {
Node next;
uintptr_t data;
};
STACK stack_init(size_t capacity) {
STACK stack = malloc(sizeof(*stack));
if (stack == 0) {
errno = ENOMEM;
return (0);
}
stack->top = 0;
pthread_mutex_init(&stack->mxlock, 0);
stack->capacity = (capacity == 0) ? (SIZE_MAX) : (capacity);
stack->count = 0;
return (stack);
}
bool stack_destroy(STACK *s) {
pthread_mutex_lock(&(*s)->mxlock);
Node curr = (*s)->top, succ = 0;
while (curr != 0) {
succ = curr->next;
free(curr);
curr = succ;
}
pthread_mutex_unlock(&(*s)->mxlock);
pthread_mutex_destroy(&(*s)->mxlock);
free(*s);
*s = 0;
return (1);
}
bool stack_push(STACK s, uintptr_t *item) {
Node node = malloc(sizeof(*node));
if (node == 0) {
errno = ENOMEM;
return (0);
}
node->data = *item;
pthread_mutex_lock(&s->mxlock);
if (s->count == s->capacity) {
pthread_mutex_unlock(&s->mxlock);
free(node);
errno = EXFULL;
return (0);
}
node->next = s->top;
s->top = node;
s->count++;
pthread_mutex_unlock(&s->mxlock);
return (1);
}
bool stack_pop(STACK s, uintptr_t *item) {
pthread_mutex_lock(&s->mxlock);
Node curr = s->top;
if (curr == 0) {
pthread_mutex_unlock(&s->mxlock);
errno = ENOENT;
return (0);
}
s->top = curr->next;
s->count--;
pthread_mutex_unlock(&s->mxlock);
*item = curr->data;
free(curr);
return (1);
}
bool stack_look(STACK s, uintptr_t *item) {
pthread_mutex_lock(&s->mxlock);
Node curr = s->top;
if (curr == 0) {
pthread_mutex_unlock(&s->mxlock);
errno = ENOENT;
return (0);
}
*item = curr->data;
pthread_mutex_unlock(&s->mxlock);
return (1);
}
size_t stack_size(STACK s) {
pthread_mutex_lock(&s->mxlock);
size_t size = s->count;
pthread_mutex_unlock(&s->mxlock);
return (size);
}
bool stack_empty(STACK s) {
pthread_mutex_lock(&s->mxlock);
bool empty = (s->count == 0);
pthread_mutex_unlock(&s->mxlock);
return (empty);
}
bool stack_full(STACK s) {
pthread_mutex_lock(&s->mxlock);
bool full = (s->count == s->capacity);
pthread_mutex_unlock(&s->mxlock);
return (full);
}
| 1
|
#include <pthread.h>
static void *jit_jni_trampoline(struct compilation_unit *cu)
{
struct vm_method *method = cu->method;
struct buffer *buf;
void *target;
target = vm_jni_lookup_method(method->class->name, method->name, method->type);
if (!target) {
signal_new_exception(vm_java_lang_UnsatisfiedLinkError, "%s.%s%s",
method->class->name, method->name, method->type);
return rethrow_exception();
}
if (add_cu_mapping((unsigned long)target, cu))
return 0;
buf = alloc_exec_buffer();
if (!buf)
return 0;
emit_jni_trampoline(buf, method, target);
cu->entry_point = buffer_ptr(buf);
return cu->entry_point;
}
static void *jit_java_trampoline(struct compilation_unit *cu)
{
int err;
err = compile(cu);
if (err) {
assert(exception_occurred() != 0);
return 0;
}
err = add_cu_mapping((unsigned long)cu_entry_point(cu), cu);
if (err)
return throw_oom_error();
return cu_entry_point(cu);
}
void *jit_magic_trampoline(struct compilation_unit *cu)
{
struct vm_method *method = cu->method;
unsigned long state;
void *ret;
if (opt_debug_stack)
check_stack_align(method);
if (opt_trace_magic_trampoline)
trace_magic_trampoline(cu);
if (vm_method_is_static(method)) {
if (vm_class_ensure_init(method->class))
return rethrow_exception();
}
state = compilation_unit_get_state(cu);
if (state == COMPILATION_STATE_COMPILED) {
ret = cu_entry_point(cu);
goto out_fixup;
}
pthread_mutex_lock(&cu->compile_mutex);
if (cu->state == COMPILATION_STATE_COMPILED) {
ret = cu_entry_point(cu);
goto out_unlock_fixup;
}
assert(cu->state == COMPILATION_STATE_INITIAL);
cu->state = COMPILATION_STATE_COMPILING;
if (vm_method_is_native(cu->method))
ret = jit_jni_trampoline(cu);
else
ret = jit_java_trampoline(cu);
if (ret)
cu->state = COMPILATION_STATE_COMPILED;
else
cu->state = COMPILATION_STATE_INITIAL;
shrink_compilation_unit(cu);
out_unlock_fixup:
pthread_mutex_unlock(&cu->compile_mutex);
out_fixup:
if (!ret)
return rethrow_exception();
fixup_direct_calls(method->trampoline, (unsigned long) ret);
return ret;
}
struct jit_trampoline *build_jit_trampoline(struct compilation_unit *cu)
{
struct jit_trampoline *ret;
ret = alloc_jit_trampoline();
if (!ret)
return 0;
emit_trampoline(cu, jit_magic_trampoline, ret);
add_cu_mapping((unsigned long) buffer_ptr(ret->objcode), cu);
return ret;
}
void jit_no_such_method_stub(void)
{
signal_new_exception(vm_java_lang_NoSuchMethodError, 0);
}
| 0
|
#include <pthread.h>
void update_full_db(double point[], double F, double *G, int n, int surrogate)
{
int PROBDIM = data.Nth;
int i, pos;
pthread_mutex_lock(&full_db.m);
pos = full_db.entries;
full_db.entries++;
pthread_mutex_unlock(&full_db.m);
if (full_db.entry[pos].point == 0) full_db.entry[pos].point = malloc(data.Nth*sizeof(double));
for (i = 0; i < PROBDIM; i++) full_db.entry[pos].point[i] = point[i];
full_db.entry[pos].F = F;
full_db.entry[pos].nG = n;
for (i = 0; i < n; i++) full_db.entry[pos].G[i] = G[i];
full_db.entry[pos].surrogate = surrogate;
}
void init_full_db()
{
pthread_mutex_init(&full_db.m, 0);
full_db.entries = 0;
full_db.entry = calloc(1, data.MaxStages*data.PopSize*sizeof(dbp_t));
}
void update_curgen_db(double point[], double F, double prior)
{
int PROBDIM = data.Nth;
int i, pos;
pthread_mutex_lock(&curgen_db.m);
pos = curgen_db.entries;
curgen_db.entries++;
pthread_mutex_unlock(&curgen_db.m);
if (curgen_db.entry[pos].point == 0) curgen_db.entry[pos].point = malloc(data.Nth*sizeof(double));
for (i = 0; i < PROBDIM; i++) curgen_db.entry[pos].point[i] = point[i];
curgen_db.entry[pos].F = F;
curgen_db.entry[pos].prior = prior;
}
void init_curgen_db()
{
pthread_mutex_init(&curgen_db.m, 0);
curgen_db.entries = 0;
curgen_db.entry = calloc(1, (data.MinChainLength+1)*data.PopSize*sizeof(cgdbp_t));
}
void update_curres_db(double point[EXPERIMENTAL_RESULTS], double F)
{
int i, pos;
return;
pthread_mutex_lock(&curres_db.m);
pos = curres_db.entries;
curres_db.entries++;
pthread_mutex_unlock(&curres_db.m);
if (curres_db.entry[pos].point == 0) curres_db.entry[pos].point = malloc((EXPERIMENTAL_RESULTS+1)*sizeof(double));
for (i = 0; i < EXPERIMENTAL_RESULTS; i++) curres_db.entry[pos].point[i] = point[i];
curres_db.entry[pos].F = F;
}
void init_curres_db()
{
pthread_mutex_init(&curres_db.m, 0);
curres_db.entries = 0;
curgen_db.entry = calloc(1, (data.MinChainLength+1)*data.PopSize*sizeof(cgdbp_t));
}
void print_full_db()
{
int pos, i;
printf("=======\\n");
printf("FULL_DB\\n");
for (pos = 0; pos < full_db.entries; pos++) {
printf("ENTRY %d: POINT(%20.16lf,%20.16lf) F=%20.16lf SG=%d\\n",
pos, full_db.entry[pos].point[0], full_db.entry[pos].point[1],
full_db.entry[pos].F, full_db.entry[pos].surrogate);
printf("\\tG=[");
for (i = 0; i < full_db.entry[pos].nG-1; i++) printf("%20.16lf,", full_db.entry[pos].G[i]);
printf("%20.16lf]\\n", full_db.entry[pos].G[i]);
}
printf("=======\\n");
}
void dump_full_db(int Gen)
{
int PROBDIM = data.Nth;
int pos;
FILE *fp;
char fname[256];
sprintf(fname, "full_db_%03d.txt", Gen);
fp = fopen(fname, "w");
for (pos = 0; pos < full_db.entries; pos++) {
int i;
for (i = 0; i < PROBDIM; i++) {
fprintf(fp, "%20.16lf ", full_db.entry[pos].point[i]);
}
fprintf(fp, "%20.16lf\\n", full_db.entry[pos].F);
}
fclose(fp);
}
void dump_curgen_db(int Gen)
{
int PROBDIM = data.Nth;
int pos;
FILE *fp;
char fname[256];
sprintf(fname, "curgen_db_%03d.txt", Gen);
fp = fopen(fname, "w");
for (pos = 0; pos < curgen_db.entries; pos++) {
int i;
for (i = 0; i < PROBDIM; i++) {
fprintf(fp, "%20.16lf ", curgen_db.entry[pos].point[i]);
}
fprintf(fp, "%20.16lf ", curgen_db.entry[pos].F);
fprintf(fp, "%20.16lf ", curgen_db.entry[pos].prior);
fprintf(fp,"\\n");
}
fclose(fp);
}
int load_curgen_db(int Gen)
{
int PROBDIM = data.Nth;
int pos;
FILE *fp;
char fname[256];
sprintf(fname, "curgen_db_%03d.txt", Gen);
fp = fopen(fname, "r");
if (fp == 0) {
printf("DB file: %s not found!!!\\n", fname);
exit(1);
return 1;
}
curgen_db.entries = 0;
char line[1024];
while (fgets(line, 1024, fp) != 0)
curgen_db.entries++;
fclose(fp);
fp = fopen(fname, "r");
for (pos = 0; pos < curgen_db.entries; pos++) {
int i;
for (i = 0; i < PROBDIM; i++) {
if (curgen_db.entry[pos].point == 0) curgen_db.entry[pos].point = malloc(PROBDIM*sizeof(double));
fscanf(fp, "%lf", &curgen_db.entry[pos].point[i]);
}
fscanf(fp, "%lf", &curgen_db.entry[pos].F);
fscanf(fp, "%lf", &curgen_db.entry[pos].prior);
}
fclose(fp);
return 0;
}
void dump_curres_db(int Gen)
{
int pos;
FILE *fp;
char fname[256];
return;
sprintf(fname, "curres_db_%03d.txt", Gen);
fp = fopen(fname, "w");
for (pos = 0; pos < curres_db.entries; pos++) {
int i;
for (i = 0; i < EXPERIMENTAL_RESULTS; i++) {
fprintf(fp, "%20.16lf ", curres_db.entry[pos].point[i]);
}
fprintf(fp, "%20.16lf\\n", curres_db.entry[pos].F);
}
fclose(fp);
}
| 1
|
#include <pthread.h>
struct gftp_request
{
unsigned int cancel : 1,
stopable : 1;
void *protocol_data;
};
struct gftp_transfer
{
struct gftp_request * fromreq;
unsigned int started : 1,
cancel : 1,
ready : 1,
done : 1;
int numfiles;
pthread_mutex_t statmutex, structmutex;
};
struct gftp_transfer *
gftp_tdata_new (void)
{
struct gftp_transfer * tdata;
tdata = malloc (sizeof (struct gftp_transfer));
pthread_mutex_init (&tdata->statmutex, 0);
pthread_mutex_init (&tdata->structmutex, 0);
return tdata;
}
static void
cancel_get_trans_password (struct gftp_transfer * tdata)
{
start_unpack(tdata);
if (tdata->fromreq->stopable == 0)
return;
pthread_mutex_lock (&tdata->structmutex);
if (tdata->started)
{
tdata->cancel = 1;
tdata->fromreq->cancel = 1;
}
else
tdata->done = 1;
tdata->fromreq->stopable = 0;
tdata->fromreq->protocol_data = 0;
pthread_mutex_unlock (&tdata->structmutex);
end_unpack(tdata);
}
static void
update_file_status (struct gftp_transfer * tdata)
{
int n;
start_unpack(tdata);
pthread_mutex_lock (&tdata->statmutex);
n = tdata->numfiles;
if (n < 1)
{
pthread_mutex_unlock (&tdata->statmutex);
return;
}
tdata->numfiles = 5;
pthread_mutex_unlock (&tdata->statmutex);
end_unpack(tdata);
}
static int doit1(struct gftp_transfer *tdata) {
cancel_get_trans_password(tdata);
return 1;
}
static int doit2(struct gftp_transfer *tdata) {
update_file_status(tdata);
return 1;
}
int main() {
int i = 1;
pthread_t t1, t2;
while (1) {
struct gftp_transfer *tdata = gftp_tdata_new();
tdata->numfiles = 1;
struct gftp_transfer *pdata;
pdata = pack(tdata);
pthread_create(&t1, 0, doit1, pdata);
pthread_create(&t2, 0, doit2, pdata);
}
}
| 0
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t state_cv;
pthread_mutex_t state_mx;
enum {WAITING, WORKING, SHUTTING} state = WAITING;
pthread_t comm;
static struct camera_control_block ccb;
int sfd;
int cfd;
int frame_callback(struct camera_control_block *ccb, struct frame_type *frame)
{
(void) ccb;
unsigned char msg[2048];
size_t size = encode_bloblist(&(frame->bloblist), msg);
assert(cfd > 0);
repeat:
if(write(cfd, &msg, size) < 0){
if(errno == EINTR){
goto repeat;
}else{
ltr_int_my_perror("write:");
return -1;
}
}
return 0;
}
void* the_server_thing(void *param)
{
(void) param;
while(1){
cfd = accept_connection(sfd);
if(cfd == -1){
ltr_int_my_perror("accept:");
continue;
}
char msg[1024];
ssize_t ret;
do{
msg[0] = 255;
repeat:
ret = read(cfd, msg, sizeof(msg));
if(ret==-1){
if(errno == EINTR){
goto repeat;
}else{
ltr_int_my_perror("read");
break;
}
}
if(ret == 0){
log_message("Client disconnected...\\n");
break;
}
switch(msg[0]){
case RUN:
pthread_mutex_lock(&state_mx);
state = WORKING;
pthread_cond_broadcast(&state_cv);
pthread_mutex_unlock(&state_mx);
break;
case SHUTDOWN:
pthread_mutex_lock(&state_mx);
state = SHUTTING;
pthread_cond_broadcast(&state_cv);
pthread_mutex_unlock(&state_mx);
break;
case SUSPEND:
cal_suspend();
break;
case WAKE:
cal_wakeup();
break;
default:
assert(0);
break;
}
}while(msg[0] != SHUTDOWN);
cal_shutdown();
pthread_mutex_lock(&state_mx);
while(state != WAITING){
pthread_cond_wait(&state_cv, &state_mx);
}
pthread_mutex_unlock(&state_mx);
close(cfd);
cfd = -1;
}
return 0;
}
int main(int argc, char *argv[])
{
if(argc != 2){
log_message("Bad args...\\n");
return 1;
}
if(!read_prefs(0, 0)){
log_message("Couldn't load preferences!\\n");
return -1;
}
if((sfd = init_server(atoi(argv[1]))) < 0){
log_message("Have problem....\\n");
return 1;
}
if(pthread_mutex_init(&state_mx, 0)){
log_message("Can't init mutex!\\n");
return 1;
}
if(pthread_cond_init(&state_cv, 0)){
log_message("Can't init cond. var.!\\n");
return 1;
}
pthread_create(&comm, 0, the_server_thing, 0);
while(1){
pthread_mutex_lock(&state_mx);
while(state == WAITING){
pthread_cond_wait(&state_cv, &state_mx);
}
pthread_mutex_unlock(&state_mx);
if(get_device(&ccb) == 0){
log_message("Can't get device category!\\n");
return 1;
}
ccb.diag = 0;
cal_run(&ccb, frame_callback);
pthread_mutex_lock(&state_mx);
state = WAITING;
pthread_cond_broadcast(&state_cv);
pthread_mutex_unlock(&state_mx);
}
pthread_cond_destroy(&state_cv);
return 0;
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++)
{
a[i]=1.0;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<4; i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<4; i++)
{
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static pthread_t tid;
int Loop;
int Debug;
static struct{
char buf[512];
pthread_mutex_t lock;
int len;
} Recv_Buf;
static struct {
int local_fd;
struct sockaddr_in svr_addr;
} Sock;
char name[32];
int pos_x;
int pos_y;
} Player;
static struct {
pthread_mutex_t lock;
uint time;
Player teammate[10];
Player enemy[10];
int x1,y1;
} World_MOUDLE;
int init (uint port,char addr[],int dbg);
int create_loop (void);
void *main_loop (void* args);
void clear (void);
void exit_loop (void);
int update_world_module(char buf[],int size);
int send_to_server (char buf[]);
int init(uint port,char addr[],int dbg){
Debug=dbg;
printf("Init All System Variables...");
memset(&Sock.svr_addr,0,sizeof(Sock.svr_addr));
memset(&World_MOUDLE,0,sizeof(World_MOUDLE));
memset(&Recv_Buf,0,sizeof(Recv_Buf));
memset(&tid,0,sizeof(tid));
Sock.svr_addr.sin_addr.s_addr=inet_addr(addr);
Sock.svr_addr.sin_family=AF_INET;
Sock.svr_addr.sin_port=port;
pthread_mutex_init(&Recv_Buf.lock, 0);
pthread_mutex_init(&World_MOUDLE.lock, 0);
if((Sock.local_fd=socket(PF_INET,SOCK_STREAM,0))<0)
{
printf("[failed]\\n");
perror("socket");
return 1;
}
printf("[Done]\\n");
return 0;
}
int create_loop(void){
printf("Connecting To The Server...");
if(connect(Sock.local_fd,(struct sockaddr *)&Sock.svr_addr,sizeof(struct sockaddr))<0)
{
printf("failed");
perror("connect");
return 1;
}
printf("[Done]\\n");
printf("Creating Recving Thread...");
if (pthread_create(&tid,0,main_loop,0)!=0) {
printf("[failed]\\n");
return 1;
}
printf("[Done]\\n");
return 0;
}
void *main_loop(void *args){
sleep(1);
Loop=1;
while(Loop){
pthread_mutex_lock(&Recv_Buf.lock);
printf("Waiting For Message...");
Recv_Buf.len=recv(Sock.local_fd,Recv_Buf.buf,512,0);
printf("[OK](%1.2fk)\\n",((float)Recv_Buf.len)/1024);
if(Debug)printf("Recv:%s\\n",Recv_Buf.buf);
update_world_module(Recv_Buf.buf,Recv_Buf.len);
memset(Recv_Buf.buf,0,sizeof(Recv_Buf.buf));
pthread_mutex_unlock(&Recv_Buf.lock);
}
pthread_exit(0);
}
void clear(void){
printf("Clearing All System Variables...");
close(Sock.local_fd);
pthread_mutex_destroy(&Recv_Buf.lock);
pthread_mutex_destroy(&World_MOUDLE.lock);
printf("[Done]\\n");
return;
}
void exit_loop(void){
printf("Exiting Loop...");
Loop=0;
sleep(1);
clear();
printf("[Done]\\n");
return;
}
int update_world_module(char buf[],int size){
pthread_mutex_lock(&World_MOUDLE.lock);
pthread_mutex_unlock(&World_MOUDLE.lock);
return 0;
}
int send_to_server(char buf[]){
printf("Sending Message...");
int len=send(Sock.local_fd,buf,strlen(buf),0);
printf("[OK](%1.2fk)\\n",((float)len)/1024);
if(Debug)printf("Send:%s\\n",buf);
return len;
}
| 0
|
#include <pthread.h>
struct button {
int id;
uint16_t x;
uint16_t y;
uint16_t w;
uint16_t h;
char *str;
bool pressed;
struct button *next;
};
static struct button *buttons = 0;
static pthread_mutex_t mutex;
static int current_id = 0;
static void(*user_callback)(int) = 0;
static void gui_callback(uint16_t x, uint16_t y)
{
struct button *cur = 0;
pthread_mutex_lock(&mutex);
cur = buttons;
while (cur) {
if (!(x < cur->x || x > cur->x+cur->w || y < cur->y || y > cur->y + cur->h)) {
cur->pressed = 1;
if (user_callback != 0)
user_callback(cur->id);
} else {
cur->pressed = 0;
}
cur = cur->next;
}
pthread_mutex_unlock(&mutex);
}
void gui_init(void)
{
current_id = 0;
pthread_mutex_init(&mutex, 0);
eve_click_attach_touch_callback(gui_callback);
}
int gui_add_button(uint16_t x, uint16_t y, uint16_t w, uint16_t h, char *str)
{
struct button *button = malloc(sizeof(struct button));
if (button == 0)
return -1;
if (str == 0)
return -1;
button->id = current_id++;
button->x = x;
button->y = y;
button->w = w;
button->h = h;
button->str = str;
button->pressed = 0;
button->next = 0;
struct button *last = buttons;
if (last == 0) {
pthread_mutex_lock(&mutex);
buttons = button;
pthread_mutex_unlock(&mutex);
}
else {
while (last->next)
last = last->next;
pthread_mutex_lock(&mutex);
last->next = button;
pthread_mutex_unlock(&mutex);
}
return button->id;
}
int gui_remove_button(int id)
{
struct button *prev = 0;
struct button *cur = buttons;
while (cur) {
if (cur->id == id) {
pthread_mutex_lock(&mutex);
if (prev)
prev->next = cur->next;
else
buttons = 0;
free(cur);
pthread_mutex_unlock(&mutex);
return id;
}
prev = cur;
cur = cur->next;
}
return -1;
}
void gui_draw(void)
{
struct button *cur = buttons;
eve_click_draw(FT800_FGCOLOR, 0x6f4972);
while (cur) {
eve_click_draw(FT800_BUTTON,
cur->x,
cur->y,
cur->w,
cur->h,
26,
cur->pressed ? FT800_OPT_FLAT : 0,
cur->str);
cur = cur->next;
}
eve_click_draw(FT800_FGCOLOR, 0x003870);
}
void gui_release(void)
{
struct button *cur = 0;
eve_click_attach_touch_callback(0);
pthread_mutex_lock(&mutex);
cur = buttons;
while (cur) {
struct button *tmp = cur->next;
free(cur);
cur = tmp;
}
buttons = 0;
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
}
void gui_set_user_callback(void(*uc)(int))
{
pthread_mutex_lock(&mutex);
user_callback = uc;
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
char glog_dir[LEN];
char* snapTime(char* buf, int len){
time_t curtime;
struct tm *loc_time;
curtime = time (0);
loc_time = localtime (&curtime);
strftime (buf, len, "%H:%M:%S", loc_time);
return buf;
}
char* snapClockTime(char* buf, int len){
struct timespec snap;
clock_gettime(CLOCK_MONOTONIC, &snap);
sprintf(buf,"%d", (int)snap.tv_nsec);
return buf;
}
FILE* initLog(){
char buf[LEN];
char log_dir[LEN];
struct stat st = {0};
int ret = 0;
FILE *fp = 0;
if (stat("logs", &st) == -1) {
if ( (ret = mkdir("logs", ACCESSPERMS)) != OK ){
perror("Error al crear el directorio de logs");
return 0;
}
}
strcpy(log_dir, "logs/");
strcat(log_dir, snapTime(buf, LEN));
strcat(log_dir, ".log");
if ((fp = fopen(log_dir, "w+")) == 0){
perror("Error al abrir/crear el log");
return 0;
}
strcpy(glog_dir, log_dir);
if (fclose(fp) != 0){
perror("ERR al cerrar log creado");
return 0;
}
return fp;
}
int logWrite(char* log_msg, char* type){
FILE* fp = 0;
char buf[LEN];
char bbuf[BIGLEN];
char buf_err[LEN];
if (strlen(log_msg) > BIGLEN){
perror("Mensaje de log supera BIGLEN, abortado");
return ERR;
}
strcpy(bbuf, "[");
strcat(bbuf, snapTime(buf,LEN));
strcat(bbuf, "] ");
strcat(bbuf, "(");
strcat(bbuf, snapClockTime(buf,LEN));
strcat(bbuf, ") ");
strcat(bbuf, type);
strcat(bbuf, log_msg);
if (strcmp(type, "-(!)- ") == 0){
strcat(bbuf, " : ");
strerror_r(errno, buf_err, LEN);
strcat(bbuf, buf_err);
}
pthread_mutex_lock(&loglock);
if ((fp = fopen(glog_dir, "a")) == 0){
perror("Error al abrir log para escritura de evento");
return ERR;
}
if (fprintf(fp, "%s\\n", bbuf) < 0){
perror("Error de escritura en el log");
return ERR;
}
fclose(fp);
pthread_mutex_unlock(&loglock);
return OK;
}
int logEvent(char* log_msg){
if (logWrite(log_msg, "- i - ") == ERR){
return ERR;
}
return OK;
}
int logERR(char* log_msg){
if (logWrite(log_msg, "-(!)- ") == ERR){
return ERR;
}
return OK;
}
| 0
|
#include <pthread.h>
int bb_buf[100];
pthread_mutex_t mutex;
pthread_cond_t EscFromFull;
pthread_cond_t EscFromEmpty;
int point = 0;
int a = 0;
void* bb_get(void* t) {
int i;
pthread_mutex_lock(&mutex);
while(point == 0) {
pthread_cond_wait(&EscFromEmpty, &mutex);
}
printf("%d\\n", bb_buf[0]);
while (point != 100) {
for(i=0; i<(point-1); i++) {
bb_buf[i] = bb_buf[i+1];
}
}
point--;
pthread_cond_signal(&EscFromFull);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void* bb_put(void* i) {
pthread_mutex_lock(&mutex);
int j = a;
a++;
while(point == 100) {
pthread_cond_wait(&EscFromFull, &mutex);
}
if (point == 100 - 1) {
bb_buf[0] = j;
}
else {
bb_buf[point] = j;
}
point++;
pthread_cond_signal(&EscFromEmpty);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
long i;
long j, k;
pthread_t thread[1000];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&EscFromFull, 0);
pthread_cond_init(&EscFromEmpty, 0);
for (i=1; i<51; i++) {
j = 2*i - 2;
if(pthread_create(&thread[j], 0, bb_put, 0) !=0) {
printf("Error: thread number %lu is dead", j);
return 1;
}
}
for (i=1; i<51; i++) {
k = 2*i - 1;
if(pthread_create(&thread[k], 0, bb_get, 0) !=0) {
printf("Error: thread number %lu is dead", k);
return 1;
}
}
for (i=0; i<100; i++)
{
pthread_join(thread[i], 0);
}
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&EscFromFull);
pthread_cond_destroy(&EscFromEmpty);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
const int MAX_BITS = 8;
const int SIGNIFICATIVE_BITS = 6;
const int MAX_RGB = 255;
struct HSV * LUT_RGB2HSV [64][64][64];
int isInitTableHSV;
pthread_mutex_t mutex;
void rgb2hsv_wiki (double r, double g, double b, double *H, double *S, double *V)
{
double min, max;
if ((r <= g) && (r <= b))
min = r;
else if ((g <= r) && (g <= b))
min = g;
else
min = b;
if ((r >= g) && (r >= b))
max = r;
else if ((g >= r) && (g >= b))
max = g;
else
max = b;
if (max==min)
{
*H=.0;
}
else if (max==r && g>=b)
{
*H=60*((g-b)/(max-min));
}
else if (max==r && g<b)
{
*H=60*((g-b)/(max-min))+360;
}
else if (max==g)
{
*H=60*((b-r)/(max-min))+120;
}
else if (max==b)
{
*H=60*((r-g)/(max-min))+240;
}
if (max==0)
*S=0.0;
else
*S= 1-(min/max);
*V=max;
}
void hsv2rgb(double H, double S, double V, double *r, double *g, double *b)
{
double h_aux,f,p,q,t, v_aux;
h_aux = ((int)fabs(H/60.0)) % 6;
f = (H/60.0) - h_aux;
v_aux = V;
p = v_aux * (1-S);
q = v_aux * (1 - f*S);
t = v_aux * (1 - (1-f)*S);
if (((int)h_aux) == 0){
*r = v_aux; *g=t; *b=p;
}
else if (((int)h_aux == 1)){
*r = q; *g=v_aux; *b=p;
}
else if (((int)h_aux == 2)){
*r = p; *g=v_aux; *b=t;
}
else if (((int)h_aux == 3)){
*r = p; *g=q; *b=v_aux;
}
else if (((int)h_aux == 4)){
*r = t; *g=p; *b=v_aux;
}
else if (((int)h_aux == 5)){
*r = v_aux; *g=p; *b=q;
}
}
void print_status_YUV(unsigned long status)
{
unsigned int t = 8;
unsigned int i;
unsigned long int j= 1 << (t - 1);
for (i= t; i > 0; --i)
{
printf("%d", (status & j) != 0);
j>>= 1;
if (i==3)
printf(" ");
}
printf(" (%lu)\\n",status);
}
void RGB2HSV_destroyTable ()
{
int r,g,b;
int pos_r, pos_g, pos_b;
int count = 4;
printf("Destroy Table LUT_RGB2HSV .... OK\\n");
for (b=0;b<=MAX_RGB;b=b+count)
for (g=0;g<=MAX_RGB;g=g+count)
for (r=0;r<=MAX_RGB;r=r+count)
{
if (r==0) pos_r=0; else pos_r = r/4;
if (g==0) pos_g=0; else pos_g = g/4;
if (b==0) pos_b=0; else pos_b = b/4;
if (LUT_RGB2HSV[pos_r][pos_g][pos_b])
{
free(LUT_RGB2HSV[pos_r][pos_g][pos_b]);
}
}
pthread_mutex_lock(&mutex);
isInitTableHSV = 0;
pthread_mutex_unlock(&mutex);
}
void RGB2HSV_init()
{
pthread_mutex_lock(&mutex);
if (isInitTableHSV==1)
{
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
printf("Init %s v%s ... \\n",NAME,COLORSPACES_VERSION);
pthread_mutex_lock(&mutex);
isInitTableHSV = 0;
pthread_mutex_unlock(&mutex);
}
void RGB2HSV_createTable()
{
int r,g,b;
int count, index;
int pos_r, pos_g, pos_b;
struct HSV* newHSV;
pthread_mutex_lock(&mutex);
if (isInitTableHSV==1)
{
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
count = 4;
index = 0;
for (b=0;b<=MAX_RGB;b=b+count)
for (g=0;g<=MAX_RGB;g=g+count)
for (r=0;r<=MAX_RGB;r=r+count)
{
newHSV = (struct HSV*) malloc(sizeof(struct HSV));
if (!newHSV)
{
printf("Allocated memory error\\n");
exit(-1);
}
rgb2hsv_wiki(r,g,b,&(newHSV->H),&(newHSV->S),&(newHSV->V));
if (r==0) pos_r=0; else pos_r = r/4;
if (g==0) pos_g=0; else pos_g = g/4;
if (b==0) pos_b=0; else pos_b = b/4;
LUT_RGB2HSV[pos_r][pos_g][pos_b] = newHSV;
index++;
}
printf("Table 'LUT_RGB2HSV' create with 6 bits (%d values)\\n",index);
pthread_mutex_lock(&mutex);
isInitTableHSV=1;
pthread_mutex_unlock(&mutex);
}
void RGB2HSV_printHSV (struct HSV* hsv)
{
printf("HSV: %.1f,%.1f,%.1f\\n",hsv->H,hsv->S,hsv->V);
}
void RGB2HSV_test (void)
{
int r,g,b;
const struct HSV* myHSV=0;
struct HSV myHSV2;
char line[16];
while (1)
{
printf("\\nIntroduce R,G,B: ");
fgets(line,16,stdin);
if ( sscanf(line,"%d,%d,%d",&r,&g,&b)!= 3)
break;
myHSV = RGB2HSV_getHSV(r,g,b);
if (myHSV==0)
{
printf ("Error in myHSV=NULL\\n");
continue;
}
printf("[Table] RGB: %d,%d,%d -- HSV: %.1f,%.1f,%.1f\\n",r,g,b,myHSV->H,myHSV->S,myHSV->V);
rgb2hsv_wiki(r,g,b,&myHSV2.H,&myHSV2.S,&myHSV2.V);
printf("[Algor] RGB: %d,%d,%d -- HSI: %.1f,%.1f,%.1f\\n",r,g,b,myHSV2.H,myHSV2.S,myHSV2.V);
}
}
| 0
|
#include <pthread.h>
static char wordBuffer[(1000000)][WORD_LENGTH+1];
static int bufferSize = 0;
pthread_mutex_t bufferUse;
bool fileProccessing = 1;
int main(int argc, char* argv[]) {
if(argc != 3) {
printf("Invalid arguments.\\n"
"Number of child threads (1 or greater)\\n"
"File Name - file path\\n");
}else {
struct tsWordTree tree;
init_tswm(&tree);
pthread_mutex_init(&bufferUse, 0);
pthread_t thread0;
pthread_create(&thread0, 0, &wordAddWait, &tree);
pthread_t thread1;
pthread_create(&thread1, 0, &wordAddWait, &tree);
pthread_t thread2;
pthread_create(&thread2, 0, &wordAddWait, &tree);
if(processFile(&tree, argv[2])) {
printTree(&tree);
}
else {
printf("File not found.\\n");
}
fileProccessing = 0;
pthread_join(thread0, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
}
}
bool processFile(struct tsWordTree * tree, char * fileName) {
if(tree != 0 && fileName != 0) {
FILE * file;
int c;
file = fopen(fileName, "r");
if(file != 0) {
char final[WORD_LENGTH+1];
int index = 0;
while((c = getc(file)) != EOF) {
if((c >= 65 && c<=90) || (c>=97 && c<=122)) {
final[index++] = toupper(c);
}
else if(c != '\\'' && c != '-'){
final[index] = '\\0';
if(index > 0) {
addWord_tswm(tree, final);
}
index = 0;
}
}
fclose(file);
return 1;
}
return 0;
}
return 0;
}
void * wordAddWait(struct tsWordTree* tree) {
char wordSave[WORD_LENGTH+1];
while(fileProccessing || bufferSize > 0) {
if(bufferSize == 0) {
continue;
}
pthread_mutex_lock(&bufferUse);
if(bufferSize == 0) {
pthread_mutex_unlock(&bufferUse);
continue;
}
strcpy(wordSave, &wordBuffer[bufferSize-1][0]);
bufferSize--;
pthread_mutex_unlock(&bufferUse);
addWord_tswm(tree, wordSave);
}
return 0;
}
| 1
|
#include <pthread.h>
const int MAX_THREADS = 1024;
void* trap(void* rank);
void get_args(int argc, char* argv[] );
void usage(char* prog_name);
long thread_count;
double global_estimate, a, b, h;
long n;
pthread_mutex_t mutex;
int main(int argc, char* argv[] ) {
long thread;
pthread_t* thread_handles;
get_args(argc, argv);
thread_handles = malloc(thread_count * sizeof(pthread_t) );
pthread_mutex_init(&mutex, 0);
h = (b - a) / n;
for(thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, trap, (void*) thread);
}
for(thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
printf("Trap estimate is:\\n%.9lf\\n", global_estimate);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void* trap(void* rank) {
double local_a, local_b, local_estimate, x;
long local_n, i;
long my_rank;
my_rank = (long) rank;
local_n = n / thread_count;
local_a = a + my_rank * local_n * h;
local_b = local_a + local_n * h;
local_estimate = ( (local_a * local_a) + (local_b * local_b) ) / 2.0;
for(i = 1; i < local_n; i++) {
x = local_a + (i * h);
local_estimate += (x * x);
}
pthread_mutex_lock(&mutex);
global_estimate += local_estimate * h;
pthread_mutex_unlock(&mutex);
return 0;
}
void get_args(int argc, char* argv[] ) {
if (argc != 5) {
usage(argv[0]);
}
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) {
usage(argv[0]);
}
a = strtoll(argv[2], 0, 10);
if (a < 0) {
usage(argv[0]);
}
b = strtoll(argv[3], 0, 10);
if (b <= a) {
usage(argv[0]);
}
n = strtoll(argv[4], 0, 10);
if (n <= 0) {
usage(argv[0]);
}
}
void usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads> <a> <b> <n>\\n", prog_name);
fprintf(stderr, " a is the left end-point of terms and should be >= 0\\n");
fprintf(stderr, " b is the right end-point of terms and should be < a\\n");
fprintf(stderr, " n is the number of trapezoids and should be >= 1\\n");
fprintf(stderr, " n should be evenly divisible by the number of threads\\n");
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
void *odd(void *max)
{
int i;
struct timeval tp;
pthread_mutex_lock(&m);
for (i = 0; i < 10; i++) {
printf("odd %d\\n", i);
sleep(1);
}
pthread_mutex_unlock(&m);
}
void *even(void *max)
{
int i;
struct timeval tp;
pthread_mutex_lock(&m);
for (i = 0; i < 10; i++) {
printf("even %d\\n", i);
sleep(1);
}
pthread_mutex_unlock(&m);
}
main()
{
int max = 50, max1 = 100, max2 = 200, i;
pthread_attr_t attr;
pthread_t *th1, *th2;
void *st1, *st2;
size_t sz;
int policy;
struct timeval tp;
pthread_mutex_init(&m, 0);
pthread_attr_init(&attr);
st1 = (void *) malloc(40960);
pthread_attr_setstacksize(&attr, 40960);
pthread_attr_setstack(&attr, st1, 40960);
pthread_attr_getstacksize(&attr, &sz);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS);
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
th1 = (pthread_t *) malloc(sizeof(pthread_t));
if (pthread_create(th1, &attr, odd, &max1)) {
perror("error creating the first thread");
exit(1);
}
printf("created the first thread\\n");
st2 = (void *)malloc(40960);
pthread_attr_setstacksize(&attr, 40960);
pthread_attr_setstack(&attr, st2, 40960);
th2 = (pthread_t *) malloc(sizeof(pthread_t));
if (pthread_create(th2, &attr, even, &max2)) {
perror("error creating the second thread");
exit(1);
}
printf("created the second thread\\n");
pthread_mutex_lock(&m);
for (i = 0; i < 10; i++) {
printf("main %d\\n", i);
sleep(1);
}
pthread_mutex_unlock(&m);
pthread_join(*th1, 0);
pthread_join(*th2, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t fork_mutex[5];
pthread_mutex_t eat_mutex;
pthread_cond_t space_avail = PTHREAD_COND_INITIALIZER;;
int num_diners=0;
main()
{
int i;
pthread_t diner_thread[5];
int dn[5];
void *diner();
pthread_mutex_init(&eat_mutex, 0);
for (i=0;i<5;i++)
pthread_mutex_init(&fork_mutex[i], 0);
for (i=0;i<5;i++){
dn[i] = i;
pthread_create(&diner_thread[i],0,diner,&dn[i]);
}
for (i=0;i<5;i++)
pthread_join(diner_thread[i],0);
pthread_exit(0);
}
void *diner(int *i)
{
int v;
int eating = 0;
printf("I'm diner %d\\n",*i);
v = *i;
while (eating < 10) {
printf("%d is thinking\\n", v);
sleep( v/2);
printf("%d is hungry\\n", v);
pthread_mutex_lock(&eat_mutex);
if (num_diners == (5 -1))
pthread_cond_wait(&space_avail,&eat_mutex);
num_diners++;
pthread_mutex_unlock(&eat_mutex);
pthread_mutex_lock(&fork_mutex[v]);
pthread_mutex_lock(&fork_mutex[(v+1)%5]);
printf("%d is eating\\n", v);
eating++;
sleep(1);
printf("%d is done eating\\n", v);
pthread_mutex_unlock(&fork_mutex[v]);
pthread_mutex_unlock(&fork_mutex[(v+1)%5]);
pthread_mutex_lock(&eat_mutex);
if (num_diners == (5 -1)) pthread_cond_signal(&space_avail);
num_diners--;
pthread_mutex_unlock(&eat_mutex);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mux;
pthread_cond_t cond;
int is_locked;
int wait_count;
int usage_count;
} _EVENT;
int _tr50_event_create(void **handle) {
_EVENT *evt;
if (handle == 0) {
return ERR_TR50_BADHANDLE;
}
if ((*handle = _memory_malloc(sizeof(_EVENT))) == 0) {
return ERR_TR50_MALLOC;
}
_memory_memset(*handle, 0, sizeof(_EVENT));
evt = *handle;
evt->is_locked = TRUE;
if ((pthread_mutex_init(&evt->mux, 0)) != 0) {
return ERR_TR50_OS;
}
if ((pthread_cond_init(&evt->cond, 0)) != 0) {
return ERR_TR50_OS;
}
return 0;
}
int _tr50_event_wait(void *handle) {
_EVENT *evt = handle;
int ret;
if (handle == 0) {
return ERR_TR50_BADHANDLE;
}
++evt->usage_count;
if ((ret = pthread_mutex_lock(&evt->mux)) != 0) {
return ERR_TR50_OS;
}
while (evt->is_locked) {
++evt->wait_count;
if ((ret = pthread_cond_wait(&evt->cond, &evt->mux)) != 0) {
--evt->wait_count;
pthread_mutex_unlock(&evt->mux);
return ERR_TR50_OS;
}
--evt->wait_count;
}
if ((ret = pthread_mutex_unlock(&evt->mux)) != 0) {
return ERR_TR50_OS;
}
return 0;
}
int _tr50_event_signal(void *handle) {
_EVENT *evt = handle;
if (handle == 0) {
return ERR_TR50_BADHANDLE;
}
if ((pthread_mutex_lock(&evt->mux)) != 0) {
return ERR_TR50_OS;
}
evt->is_locked = FALSE;
if ((pthread_cond_broadcast(&evt->cond)) != 0) {
return ERR_TR50_OS;
}
if ((pthread_mutex_unlock(&evt->mux)) != 0) {
return ERR_TR50_OS;
}
return 0;
}
int _tr50_event_delete(void *handle) {
_EVENT *evt = handle;
int ret;
if (handle == 0) {
return ERR_TR50_TIMEOUT;
}
if ((ret = pthread_cond_destroy(&evt->cond)) != 0) {
log_should_not_happen("event_delete(): pthread_cond_destroy failed[%d]\\n", ret);
}
if ((ret = pthread_mutex_destroy(&evt->mux)) != 0) {
log_should_not_happen("event_delete(): pthread_mutex_destroy failed[%d]\\n", ret);
}
_memory_free(handle);
return 0;
}
| 1
|
#include <pthread.h>
extern void *hash_flows;
extern void *hash_flows2;
void send_debulk_buffer(struct seg6_sock *sk, struct parser_ipv6_sr *bulk_sr, int debulk_len, char *debulk_data, int bulk_hdr_size) {
int len, next_header = 41, offset = 0;
struct parser_ipv6 *ip6hdr;
struct parser_ipv6_sr *ip6hdr_sr;
verbose("Sending debulk buffer\\n");
while (offset < debulk_len) {
if(verbose_flag)
printf("Sending packet \\n read from offset %d\\n",
offset+bulk_hdr_size);
nparse_ipv6(debulk_data, &ip6hdr, offset, &next_header);
nparse_ipv6_sr(debulk_data, &ip6hdr_sr, offset+IP6HDR_SIZE, &next_header);
ip6hdr_sr->seg_left = bulk_sr->seg_left;
len = ntohs(ip6hdr->length) + IP6HDR_SIZE;
send_ip6_packet(sk, len, debulk_data+offset);
offset += len;
if(verbose_flag)
printf("new offset = %d\\n ... Finish\\n",
offset);
}
if(verbose_flag)
printf("... Finish\\n");
}
void debulk_packet(struct seg6_sock *sk, struct nlattr **attrs, struct nlmsghdr *nlh) {
int pkt_len, offset = 0, next_header = 41;
char *pkt_data;
struct parser_ipv6 *ip6hdr;
struct parser_ipv6_sr *ip6hdr_sr;
pkt_len = nla_get_u32(attrs[SEG6_ATTR_PACKET_LEN]);
pkt_data = nla_data(attrs[SEG6_ATTR_PACKET_DATA]);
offset += nparse_ipv6(pkt_data, &ip6hdr, offset, &next_header);
offset += nparse_ipv6_sr(pkt_data, &ip6hdr_sr, offset, &next_header);
send_debulk_buffer(sk, ip6hdr_sr, pkt_len-offset, pkt_data+offset, offset);
}
void bulk_packet(struct seg6_sock *sk, struct nlattr **attrs, struct nlmsghdr *nlh) {
int pkt_len, flow_id=0, offset = 0, next_header = NEXTHDR_IPV6;
char *pkt_data;
struct parser_ipv6 *ip6hdr ;
struct parser_ipv6_sr *ip6hdr_sr;
struct bulk_flow *flow;
struct bulk_buffer *buffer;
pkt_len = nla_get_u32(attrs[SEG6_ATTR_PACKET_LEN]);
pkt_data = nla_data(attrs[SEG6_ATTR_PACKET_DATA]);
offset = find_hdr(NEXTHDR_ROUTING, pkt_data, &ip6hdr_sr, &next_header);
offset += 8 + 8 * ip6hdr_sr->hdr_length;
if(pkt_len >= (int) BUFFER_SIZE) {
fprintf(stderr, "Drop too big packet");
return;
}
if( pkt_data + 40 != (char *) ip6hdr_sr ||
ip6hdr_sr->next_header != NEXTHDR_IPV6 ) {
send_buffer(sk, buffer, OP_BUF_UPDLEN );
add_to_buffer(buffer, pkt_data, offset);
add_to_buffer(buffer, pkt_data, pkt_len);
return;
}
flow_id = (int) do_csum(ip6hdr_sr + 8, 8 * (ip6hdr_sr->hdr_length));
flow = get_bulk_flow_or_create((struct bulk_flow **) &hash_flows2, flow_id);
buffer = flow->b;
pthread_mutex_lock(buffer->lock);
verbose("Lock mutex\\n");
if(available_space(buffer, offset) < pkt_len)
send_buffer(sk, buffer, OP_BUF_UPDLEN );
if( buffer->pos == 0 ) {
verbose("Update pos to offset because no header\\n");
add_to_buffer(buffer, pkt_data, offset);
gettimeofday(&(flow->b->last_send), 0);
}
add_to_buffer(buffer, pkt_data, pkt_len);
verbose("... Unlock mutex\\n");
pthread_mutex_unlock(buffer->lock);
}
| 0
|
#include <pthread.h>
int asientos[10*3*4];
void * threadfunc(void *);
pthread_mutex_t mutexes[10*3*4] = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, const char * argv[]) {
srand(time(0));
pthread_t * compradores = (pthread_t *) malloc (sizeof(pthread_t) * 10);
for (int i = 0; i < 10; i++) {
printf("Creando el comprador %d ---\\n", i+1);
pthread_create(compradores+i, 0, threadfunc, i + 1);
}
;
for (int i = 0; i < 10; i++) {
pthread_join(*(compradores+i), 0);
}
free(compradores);
return 0;
}
void * threadfunc(void * arg)
{
int id = (int) arg;
int complejo;
int sala;
int asiento;
int temp;
int aux = 0;
int cuantos = rand()%3 + 1;
complejo = rand()%4;
sala = rand()%3;
asiento = rand()%10;
temp = complejo * 3 * 10 + (sala * 10) + asiento;
while(aux < cuantos)
{
sleep(rand()%3 + 1);
while(asientos[temp])
{
complejo = rand()%4;
sala = rand()%3;
asiento = rand()%10;
temp = complejo * 3 * 10 + (sala * 10) + asiento;
}
pthread_mutex_lock(&(*(mutexes+temp)));
if(!asientos[temp])
{
printf("[Comprador %d]Comprando el asiento %d, en la sala %d, en el complejo %d\\n", id, asiento, sala, complejo);
asientos[temp]++;
aux++;
}
else
{
printf("[Comprador %d]El asiento que queria ya estaba ocupado (asiento %d, sala %d, complejo %d), comprando otro...\\n", id, asiento, sala, complejo);
}
pthread_mutex_unlock(&(*(mutexes+temp)));
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int p;
int r;
} TInfo;
int THREADS = 0;
double* A;
pthread_mutex_t s;
void mergeSort_intercala(int p, int q, int r){
int i, j, k;
double *B;
B = (double *) malloc(sizeof(double) * (r-p+1));
for(i=p; i<=q; i++) B[i-p] = A[i];
for(j=r; j>q; j--) B[j-p] = A[j];
for(i=p, j=r, k=p; k<=r; k++){
if(B[i-p] <= B[j-p]){
A[k] = B[i-p];
i++;
}
else{
A[k] = B[j-p];
j--;
}
}
free(B);
}
void mergeSort_ordena(int p, int r){
int q;
if(p<r){
q = (p+r)/2;
mergeSort_ordena(p, q);
mergeSort_ordena(q+1, r);
mergeSort_intercala(p, q, r);
}
}
void* mergeSort_ordena_2(void* args){
int p, q, r;
pthread_t t1, t2;
TInfo *aux, info1, info2;
aux = (TInfo*) args;
p = aux->p;
r = aux->r;
if(p<r){
q = (p+r)/2;
if(THREADS < 4){
pthread_mutex_lock(&s);
info1.p = p;
info1.r = q;
pthread_create(&t1, 0, mergeSort_ordena_2, (void*) &info1);
info2.p = q+1;
info2.r = r;
pthread_create(&t2, 0, mergeSort_ordena_2, (void*) &info2);
THREADS += 2;
pthread_mutex_unlock(&s);
pthread_join(t1, 0);
pthread_join(t2, 0);
}
else{
mergeSort_ordena(p, q);
mergeSort_ordena(q+1, r);
}
mergeSort_intercala(p, q, r);
}
}
void mergeSort(int n){
mergeSort_ordena(0, n-1);
}
int main(){
int i;
A = (double*) malloc(sizeof(double)*10000000);
srand(time(0));
for(i=0; i<10000000; i++){
A[i] = rand();
}
mergeSort(10000000);
return 0;
}
| 0
|
#include <pthread.h>
char* fp_src;
char* fp_dest;
int src_fd;
int dest_fd;
char file_name[256];
} FilePair;
int NUM_THREADS;
int count;
FilePair pairs[20];
pthread_cond_t buffer_empty;
pthread_cond_t buffer_full;
pthread_mutex_t lock;
void producerBufferWrite();
void consumerBufferRead();
int main(int argc, char* argv[])
{
if (argc != 2)
{
printf("Please provide number of filecopy consumer threads as an argument\\n");
return 0;
}
char* files[2];
int i;
NUM_THREADS = atoi(argv[1]);
pthread_t producer_thread;
pthread_t comsumer_threads[NUM_THREADS];
count = 0;
pthread_mutex_init(&lock, 0);
producerBufferWrite();
for (i = 0; i < NUM_THREADS; i++)
{
pthread_create(&comsumer_threads[i], 0, (void*)consumerBufferRead, 0);
}
for (i = 0; i < NUM_THREADS; i++)
{
pthread_join(comsumer_threads[i], 0);
}
printf("Reached end of main\\n");
return 0;
}
void consumerBufferRead()
{
int newCount = -1;
char *src, *dest;
int src_fd, dest_fd;
FILE *srcfile, *destfile;
int ch;
pthread_mutex_lock(&lock);
while (count <= 0)
{
pthread_cond_wait(&buffer_empty, &lock);
}
count--;
FilePair fp = pairs[count];
src_fd = fp.src_fd;
dest_fd = fp.dest_fd;
newCount = count;
pthread_cond_signal(&buffer_full);
pthread_mutex_unlock(&lock);
off_t fsize;
fsize = lseek(src_fd, 0, 2);
char temp_buffer[fsize];
read(src_fd, temp_buffer, fsize);
printf("read %d\\n", src_fd);
write(dest_fd, temp_buffer, fsize);
printf("wrote %d\\n", dest_fd);
int src_closed = close(src_fd);
printf("close(src - %d) = %d\\n", src_fd, src_closed);
int dest_closed = close(dest_fd);
printf("close(dest - %d) = %d\\n", dest_fd, dest_closed);
pthread_exit(0);
}
void producerBufferWrite()
{
char src_file[256];
char dest_file[256];
DIR *dp;
struct dirent *ep;
FilePair fp;
dp = opendir("testfiles/");
if (dp != 0)
{
while ((ep = readdir(dp)))
{
if (ep->d_type != DT_REG) continue;
pthread_mutex_lock(&lock);
while (count == 20)
{
pthread_cond_wait(&buffer_full, &lock);
}
char fileName[256] = "";
strcpy(fileName, (char*)ep->d_name);
strcpy(src_file, "testfiles/");
strcpy(dest_file, "copiedfiles/");
strcat(src_file, fileName);
strcat(dest_file, fileName);
int srcFD = open(src_file, O_RDONLY);
int destFD = open(dest_file, O_RDWR | O_CREAT);
fp.src_fd = srcFD;
fp.dest_fd = destFD;
pairs[count++] = fp;
printf("srcFD = %d\\ndestFD = %d\\n\\n", srcFD, destFD);
pthread_cond_signal(&buffer_empty);
pthread_mutex_unlock(&lock);
}
(void) closedir(dp);
}
else
{
perror("Error opening source directory\\n");
}
};
| 1
|
#include <pthread.h>
void * runner (void *arg);
struct args * allocate_struct ( int P );
pthread_t * allocate_tids ( int P );
struct args {
long long start;
long long last;
FILE *fd;
};
pthread_mutex_t lock;
int P;
long long count = 0;
int main (int argc, char ** argv) {
long long i, last;
FILE * fd;
pthread_t *tids;
struct args *args_array;
pthread_mutex_init (&lock, 0);
if (argc != 3)
{
fprintf (stderr, "Wrong number of arguments.\\nUsage %s <limit> <number of threads>\\n", argv[0]);
exit(1);
}
last = atol(argv[1]);
if (last < 2) {
fprintf(stderr, "Incorrect input value, min = 2\\n");
exit (1);
}
P = atoi(argv[2]);
if (P <=0)
{
fprintf (stderr, "The number of threads must be positive\\n");
exit(1);
}
if (P > last)
{
fprintf (stderr, "The number of threads must be smaller than the input number\\n");
exit(1);
}
fd = fopen("primes_threads.list", "w");
if (fd == 0)
{
fprintf (stderr, "Error in file creation\\n");
exit(1);
}
fprintf(fd, "%d\\n", 2);
args_array = allocate_struct ( P );
tids = allocate_tids ( P );
for (i = 0; i < P; i += 1)
{
args_array[i].start = i;
args_array[i].last = last;
args_array[i].fd = fd;
}
for (i = 0; i < P; i += 1)
{
if (pthread_create(&tids[i], 0, runner, (void *) &args_array[i]))
{
fprintf (stderr, "Error during creation of a thread\\n");
exit(1);
}
}
for (i = 0; i < P; i += 1)
{
pthread_join(tids[i], 0);
}
fclose (fd);
return 0;
}
void * runner (void *arg)
{
struct args * args;
long long i;
int prime = 1;
long long start, last, number;
FILE * fd;
args = (struct args *) arg;
fd = args->fd;
start = args->start;
last = args->last;
for (number = 3+start; count < last; number+=P) {
if (number % 2 == 0) {
continue;
}
for ( i = 3; i <= number/i; i+=2 ) {
if (number%i == 0) {
prime = 0;
break;
}
}
if (prime) {
pthread_mutex_lock (&lock);
fprintf(fd, "%lld\\n", number);
count++;
pthread_mutex_unlock (&lock);
}
prime = 1;
}
pthread_exit(0);
}
pthread_t * allocate_tids ( int P ){
pthread_t *np_t;
np_t = (pthread_t *) malloc (sizeof (pthread_t ) * P);
if (np_t == 0)
{
fprintf (stderr, "Error in allocation\\n");
exit(1);
}
return np_t;
}
struct args * allocate_struct ( int P ) {
struct args *np_s;
np_s = (struct args *) malloc (sizeof (struct args) * P);
if (np_s == 0)
{
fprintf (stderr, "Error in allocation\\n");
exit(1);
}
return np_s;
}
| 0
|
#include <pthread.h>
int var, cnt;
pthread_mutex_t mtx;
int randT() {
return rand() % 10;
}
int randTexc(int i) {
int x = randT();
while(x == i)
x = randT();
return x;
}
void* doIt(void* arg) {
int id = *(int*)arg;
while(cnt < 20) {
pthread_mutex_lock(&mtx);
if(var == id && cnt < 20) {
var = randTexc(id);
printf("%d: Thread %d: var = %d\\n", cnt, id, var);
++ cnt;
}
pthread_mutex_unlock(&mtx);
}
free(arg);
return 0;
}
int main() {
pthread_t t[10];
int i;
srand(time(0));
var = randT();
printf("Initially var = %d\\n", var);
pthread_mutex_init(&mtx, 0);
for(i = 0; i < 10; ++ i) {
int* x = (int*) malloc(sizeof(int));
*x = i;
pthread_create(&t[i], 0, doIt, (void*) x);
}
for(i = 0; i < 10; ++ i) {
pthread_join(t[i], 0);
}
pthread_mutex_destroy(&mtx);
return 0;
}
| 1
|
#include <pthread.h>
ssize_t n;
int sockfd;
int TotalNum = 0;
static int Connect = 0;
uint8_t TotalNum_buf[2] = {0};
int poll_flag = 0;
static uint8_t flag[5] = {0};
static uint8_t buf[N] = {0};
char *getip = 0;
const char* ip_1 = "192.168.1.233";
const char* ip_2 = "127.0.0.1";
pthread_t thread_reg;
pthread_t thread_conn;
pthread_mutex_t mut_reg;
int main(int argc, const char *argv[]) {
printf("\\n\\nProgram starts running!!...\\n");
int temp;
uint8_t encryption_buff[N] = {0};
uint8_t decryption_buff[N] = {0};
uint8_t* zc_buf_sp = 0;
struct sockaddr_in servaddr;
uint8_t Mac[17] = {0};
uint8_t buf2[256] = {0};
int i = 0, nbyte;
int a = 0, b = 0, c = 0;
int nRtn = get_mac(Mac, sizeof(Mac));
LOG_PRINT("Get Mac: %s\\n", Mac);
getip = (char *)GetLocalIp();
a = Strcmp(getip, ip_1);
b = Strcmp(getip, ip_2);
GITIP:if((!a)||(!b)||(*getip > '3')){
i++;
sleep(1);
printf("getIp failed; retry times %d\\n", i);
getip = (char *)GetLocalIp();
a = Strcmp(getip, ip_1);
b = Strcmp(getip, ip_2);
goto GITIP;
}
LOG_PRINT("Get IP succeed:%s\\n\\n", getip);
printf("==========Start of registration==========\\n");
zc_buf_sp = (uint8_t *)get_zc_buffer(Mac);
LOG_PRINT("zc_buf: %s\\n", zc_buf_sp);
add_secret(zc_buf_sp, encryption_buff);
LOG_PRINT("send buf: %s\\n", encryption_buff);
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("socket to fail\\n");
exit(-1);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("210.72.224.35");
servaddr.sin_port = htons(8502);
if((temp = pthread_create(&thread_conn, 0, thread_C, 0)) != 0) {
printf("thread_C to failed\\n");
exit(0);
}
if((connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) == -1) {
perror("connect to fail\\n");
exit(0);
}else{
++Connect;
printf("connect server succeed!...\\n");
}
memset(&thread_reg, 0, sizeof(thread_reg));
pthread_mutex_init(&mut_reg, 0);
if((temp = pthread_create(&thread_reg, 0, thread_first, (int *)&sockfd)) != 0) {
printf("thread_reg to failed\\n");
exit(0);
}
sleep(1);
if((send(sockfd, encryption_buff, strlen(encryption_buff)+1, 0)) == -1) {
LOG_PRINT("send to failed\\n");
exit(1);
}else
bzero(encryption_buff, sizeof(encryption_buff));
loop: if(poll_flag <= 0){
sleep(1);
printf("wait poll...\\n");
goto loop;
}
Gateway_Poll();
pthread_join(thread_reg, 0);
close(sockfd);
return 0;;
}
void *thread_C(){
int i = 0;
CONN:if(Connect == 0){
sleep(1);
printf("Please Wait Connect Server, Repeated connection times:%d\\n", ++i);
if(i == 10){
system("./opt/second_program");
kill_program();
}
goto CONN;
}
pthread_exit(0);
}
void *thread_first(void * arg) {
int fd = *((int *)arg);
uint8_t encryption_buff[N] = {0};
uint8_t decryption_buff[N] = {0};
uint8_t send_buf[N] = {0};
uint8_t sz_buf[N] = {0};
pthread_mutex_lock(&mut_reg);
while((n = read(sockfd, buf, N)) > 0){
printf("read buf: %s\\n", buf);
memset(decryption_buff, 0, sizeof(decryption_buff));
Decryption(buf, decryption_buff);
memset(buf, 0, sizeof(buf));
printf("Decryption buf:%d:%s\\n",strlen(decryption_buff), decryption_buff);
if((strlen(decryption_buff)) == 48){
memcpy(flag, decryption_buff+35, 4);
}else{
memcpy(flag, decryption_buff+40, 4);
}
flag[strlen(flag)] = '\\0';
switch (getNum(flag)) {
case 1:
memcpy(TotalNum_buf, decryption_buff+51, 1);
TotalNum = atoi((char *)TotalNum_buf);
get_sz_buffer(decryption_buff, sz_buf);
printf("sz_buf:%s\\n", sz_buf);
add_secret(sz_buf, encryption_buff);
LOG_PRINT("send buf: %s\\n", encryption_buff);
send(fd, encryption_buff, strlen(encryption_buff)+1, 0);
bzero(encryption_buff, sizeof(encryption_buff));
bzero(sz_buf, sizeof(sz_buf));
break;
case 2:
setTime(decryption_buff);
printf("==========End of registration==========\\n\\n");
++poll_flag;
break;
case 3:
Read_A_Single_Device(decryption_buff, send_buf);
add_secret(send_buf, encryption_buff);
send(fd, encryption_buff, strlen(encryption_buff)+1, 0);
bzero(encryption_buff, sizeof(encryption_buff));
bzero(send_buf, sizeof(send_buf));
break;
case 4:
Read_All_Device(decryption_buff, send_buf);
add_secret(send_buf, encryption_buff);
send(fd, encryption_buff, strlen(encryption_buff)+1, 0);
bzero(encryption_buff, sizeof(encryption_buff));
bzero(send_buf, sizeof(send_buf));
break;
case 5:
Read_One_Device(decryption_buff, send_buf);
add_secret(send_buf, encryption_buff);
send(fd, encryption_buff, strlen(encryption_buff)+1, 0);
bzero(encryption_buff, sizeof(encryption_buff));
bzero(send_buf, sizeof(send_buf));
break;
case 6:
Heartbeat_Package(decryption_buff);
break;
case 7:
break_brake(decryption_buff, send_buf);
add_secret(send_buf, encryption_buff);
send(fd, encryption_buff, strlen(encryption_buff)+1, 0);
bzero(encryption_buff, sizeof(encryption_buff));
bzero(send_buf, sizeof(send_buf));
break;
default:
break;
}
}
pthread_mutex_unlock(&mut_reg);
pthread_exit(0);
}
int getNum(uint8_t* s){
if(!strcmp(s,"0021")) return 1;
if(!strcmp(s,"0022")) return 2;
if(!strcmp(s,"0023")) return 3;
if(!strcmp(s,"0024")) return 4;
if(!strcmp(s,"0029")) return 5;
if(!strcmp(s,"0702")) return 6;
if(!strcmp(s,"0030")) return 7;
return -1;
}
void kill_program(void){
char buf[20] = {0};
pid_t pid = getpid();
strcat(buf, "kill -9 ");
sprintf(buf+8, "%d", pid);
buf[strlen(buf)] = '\\0';
system(buf);
}
| 0
|
#include <pthread.h>
int numtasks;
int npoints;
int times;
int debug=0;
pthread_mutex_t* mutex;
pthread_cond_t* cond;
pthread_barrier_t barrier_calc;
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;
}
| 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;
while(1)
{
pthread_mutex_lock(&lock);
printf("%d\\n",lock);
while(0 == head)
{
pthread_cond_wait(&has_product,&lock);
}
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\\n", mp->num);
free(mp);
sleep(rand()%5);
}
}
void *producer(void *p)
{
struct msg *mp;
struct msg *hp;
while(1)
{
mp = malloc(sizeof(struct msg));
mp->num = rand()%1000+1;
printf("Produce %d\\n",mp->num);
pthread_mutex_lock(&lock);
if(0 == head)
{
head = mp;
head->next = 0;
}
else
{
hp = head;
while(0 != hp->next)
{
hp = hp->next;
}
hp->next = mp;
mp->next = 0;
}
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
sleep(rand()%5);
}
}
int main(int argc, const 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>
pthread_t start_thread(void *func, int *arg) {
pthread_t thread_id;
int rc;
printf("In main: creating thread\\n");
rc = pthread_create(&thread_id, 0, func, arg);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
return(thread_id);
}
pthread_mutex_t mutex;
pthread_cond_t cond;
int count;
} semaphore_t;
void init_sem(semaphore_t *s, int i) {
s->count = i;
pthread_mutex_init(&(s->mutex), 0);
pthread_cond_init(&(s->cond), 0);
}
void P(semaphore_t *sem) {
pthread_mutex_lock (&(sem->mutex));
sem->count--;
if (sem->count < 0)
pthread_cond_wait(&(sem->cond), &(sem->mutex));
pthread_mutex_unlock (&(sem->mutex));
}
void V(semaphore_t * sem) {
pthread_mutex_lock (&(sem->mutex));
sem->count++;
if (sem->count <= 0) {
pthread_cond_signal(&(sem->cond));
}
pthread_mutex_unlock (&(sem->mutex));
pthread_yield();
}
semaphore_t mutexT1,mutexT2,mutexT3,mutexM;
void function_1(int *arg)
{
while (1) {
P(&mutexT1);
(*arg)++;
V(&mutexM);
}
}
void function_2(int *arg)
{
while (1) {
P(&mutexT2);
(*arg)++;
V(&mutexM);
}
}
void function_3(int *arg)
{
while (1) {
P(&mutexT3);
(*arg)++;
V(&mutexM);
}
}
int main()
{
init_sem(&mutexT1, 1);
init_sem(&mutexT2, 1);
init_sem(&mutexT3, 1);
init_sem(&mutexM, 0);
int array[3] = {0,0,0};
start_thread(function_1, &(array[0]));
start_thread(function_2, &(array[1]));
start_thread(function_3, &(array[2]));
while(1) {
P(&mutexM);
P(&mutexM);
P(&mutexM);
printf("[ MAIN ] : Array Elements : {%d , %d , %d}\\n", array[0], array[1], array[2]);
sleep(1);
V(&mutexT1);
V(&mutexT2);
V(&mutexT3);
}
return 0;
}
| 1
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void thread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destory(&attr);
}
int getenv_r(const char *name, char *buf, int buflen)
{
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) {
olen = strlen(&environ[i][len+1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSPC);
}
strcpy(buf, &environ[i][lem+1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
| 0
|
#include <pthread.h>
int count =0;
int lastPrime =0;
char *flags;
pthread_mutex_t lock;
void* pp(void *rank);
int main(int argc, char* argv[]){
long n =100;
long p =100;
flags = malloc(sizeof(char) * ((n - 1)/2));
if (!flags) {
printf("Not enough memory.\\n");
exit(1);
}
long thread;
long* pp_Args;
long thread_count = p;
pthread_t* thread_handles;
thread_handles = malloc( p * sizeof (pthread_t));
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
for(thread=0 ; thread < thread_count; thread ++){
pp_Args =(long *)malloc(3 * sizeof(long));
pp_Args[0] = n;
pp_Args[1] = thread_count;
pp_Args[2] = thread;
pthread_create(&thread_handles[thread], 0, pp, (void*) pp_Args);
}
for(thread=0; thread < thread_count ; thread++){
pthread_join(thread_handles[thread], 0);
}
printf("count = %d",count);
printf("last prime = %d", lastPrime);
pthread_mutex_destroy(&lock);
free(thread_handles);
return 0;
}
void* pp(void* pp_Args){
long n = ((long*)pp_Args)[0];
long p = ((long*)pp_Args)[1];
long my_rank = ((long*)pp_Args)[2];
int local_n,local_last_prime;
int div1, div2, rem, prime, last_number;
int local_count = 0;
local_n = ( (n-1)/2 ) / p;
int local_i = my_rank * local_n;
if (( ( (n-1)/2 ) % p) != 0 && my_rank == p-1){
last_number = ( (n-1)/2 ) - 1 ;
}
else{
last_number = ( my_rank + 1 ) * local_n -1;
}
for ( local_i ; local_i <= last_number; local_i++) {
prime = 2*local_i + 3;
div1 = 1;
do {
div1 += 2;
div2 = prime / div1;
rem = prime % div1;
} while (rem != 0 && div1 <= div2);
if (rem != 0 || div1 == prime) {
flags[local_i] = 1;
local_count++;
} else {
flags[local_i] = 0;
}
}
local_last_prime = prime;
if(local_last_prime > lastPrime){
lastPrime = local_last_prime;
}
pthread_mutex_lock(&lock);
count = count + local_count;
pthread_mutex_unlock(&lock);
free(pp_Args);
}
| 1
|
#include <pthread.h>
int cnt;
int pos;
unsigned char buff[1024];
pthread_mutex_t mtx;
pthread_cond_t cv;
} pipe_t;
pipe_t *pipe_open() {
pipe_t *p = malloc(sizeof(pipe_t));
if (p) {
p->pos = 0;
p->cnt = 0;
pthread_mutex_init(&p->mtx, 0);
pthread_cond_init(&p->cv, 0);
}
return p;
}
void pipe_close(pipe_t *p) {
if (p) {
pthread_mutex_destroy(&p->mtx);
pthread_cond_destroy(&p->cv);
free(p);
}
}
unsigned int write_to_pipe(pipe_t *p, char *buff, size_t size)
{
struct timespec t1, t2;
int k = 0;
int rc = 0;
clock_gettime(CLOCK_REALTIME, &t1);
t1.tv_sec += 5;
pthread_mutex_lock(&p->mtx);
while (p->cnt == 1024 && rc == 0) {
rc = pthread_cond_timedwait(&p->cv, &p->mtx, &t1);
}
if (p->cnt < 1024) {
while (size > 0 && p->cnt < 1024) {
p->buff[p->pos ++] = buff[k ++];
p->pos = p->pos % 1024;
p->cnt ++;
size --;
}
} else {
k = -1;
}
pthread_mutex_unlock(&p->mtx);
pthread_cond_signal(&p->cv);
return k;
}
int read_from_pipe(pipe_t *p, char *buff, size_t size)
{
struct timespec t1, t2;
int k = 0;
int rc = 0;
clock_gettime(CLOCK_REALTIME, &t1);
t1.tv_sec += 5;
pthread_mutex_lock(&p->mtx);
while (p->cnt == 0 && rc == 0) {
rc = pthread_cond_timedwait(&p->cv, &p->mtx, &t1);
}
if (p->cnt > 0) {
while (k < size && p->cnt > 0) {
buff[k ++] = p->buff[p->pos ++];
p->pos = p->pos % 1024;
p->cnt --;
}
}
pthread_mutex_unlock(&p->mtx);
pthread_cond_signal(&p->cv);
return k;
}
void *func_write(void *arg) {
pipe_t *p = (pipe_t *)arg;
const int size = 1024 * 10;
char data[size];
unsigned int pos = 0;
int k, i;
for (i = 0; i < sizeof(data); i ++) {
data[i] = 'a' + i % 26;
}
while (pos < size) {
k = write_to_pipe(p, &data[pos], size - pos);
if (k < 0) {
printf("write fail, pipe full.\\n");
return 0;
}
pos += k;
}
return 0;
}
void *func_read(void *arg) {
pipe_t *p = (pipe_t *)arg;
char buff[1024];
int size = 1024;
int i, k = 0;
int cnt = 0;
do {
k = read_from_pipe(p, buff, size);
for (i = 0; i < k; i ++) {
printf("%c", buff[i]);
}
fflush(stdout);
cnt += k;
} while (k > 0);
printf("\\n");
printf("%d\\n", cnt);
return 0;
}
int main(int argc, char *argv[])
{
pipe_t *p;
pthread_t read_thr, write_thr;
int rc = 0;
void *ret;
p = pipe_open();
if (!p) {
printf("failed to open\\n");
rc = -1;
goto cu0;
}
rc = pthread_create(&write_thr, 0, func_write, p);
if (rc != 0) {
goto cu1;
}
rc = pthread_create(&read_thr, 0, func_read, p);
if (rc != 0) {
goto cu2;
}
pthread_join(read_thr, &ret);
cu2:
pthread_join(write_thr, &ret);
cu1:
pipe_close(p);
cu0:
return rc;
}
| 0
|
#include <pthread.h>
void
ports_end_rpc (void *port, struct rpc_info *info)
{
struct port_info *pi = port;
pthread_mutex_lock (&_ports_lock);
if (info->notifies)
_ports_remove_notified_rpc (info);
*info->prevp = info->next;
if (info->next)
info->next->prevp = info->prevp;
pi->class->rpcs--;
_ports_total_rpcs--;
pi->bucket->rpcs--;
if ((pi->flags & PORT_INHIBIT_WAIT)
|| (pi->bucket->flags & PORT_BUCKET_INHIBIT_WAIT)
|| (pi->class->flags & PORT_CLASS_INHIBIT_WAIT)
|| (_ports_flags & _PORTS_INHIBIT_WAIT))
pthread_cond_broadcast (&_ports_block);
ports_self_interrupted ();
freax_check_cancel ();
pthread_mutex_unlock (&_ports_lock);
}
| 1
|
#include <pthread.h>
char string[1000];
char ready_string[1000];
int kill_threads;
int fd;
pthread_mutex_t lock;
pthread_mutex_t lock2;
void* fun1(void* arg){
while(1){
pthread_mutex_lock(&lock);
if(kill_threads == 0){
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
char buf[100];
int bytes_read = read(fd, buf, 100);
int i;
for(i = 0; i < bytes_read; i++){
if (buf[i] == '\\n'){
char null = '\\0';
strcat(string, &null);
pthread_mutex_lock(&lock2);
ready_string[0] = null;
strcat(ready_string, string);
pthread_mutex_unlock(&lock2);
string[0] = null;
continue;
}
char this_char = buf[i];
strncat(string, &this_char, 1);
}
}
return 0;
}
void* fun2(void* arg){
char* on = "o";
char* off = "f";
while(kill_threads == 1){
char input[10];
printf("Enter user input: ");
scanf("%s", input);
switch (input[0]){
case('a'):
write(fd, on, strlen(on));
break;
case('b'):
write(fd, off, strlen(off));
break;
case('q'):
pthread_mutex_lock(&lock);
kill_threads = 0;
pthread_mutex_unlock(&lock);
break;
default:
pthread_mutex_lock(&lock2);
printf("%s\\n", ready_string);
pthread_mutex_unlock(&lock2);
}
}
return 0;
}
int main(){
kill_threads = 1;
pthread_t t1, t2;
pthread_mutex_init(&lock, 0);
pthread_mutex_init(&lock2, 0);
fd = open("/dev/ttyUSB11", O_RDWR);
if(fd == -1){
printf("Couldn't open\\n");
return 0;
}
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, 9600);
cfsetospeed(&options, 9600);
tcsetattr(fd, TCSANOW, &options);
pthread_create(&t1, 0, &fun1, 0);
pthread_create(&t2, 0, &fun2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("Threads are dead!\\n");
close(fd);
return 1;
}
| 0
|
#include <pthread.h>
unsigned long total_io_interval = 0;
unsigned long total_req_inqueue_time = 0;
long total_ios = 0;
long total_req = 0;
pthread_mutex_t statistics_mutex;
pthread_t statistics_thread_id;
long clks_per_sec;
void* log_time_statistics(void* arg){
DPRINTF("Log Statistics Thread Started");
while(1){
sleep(STAT_TIME_MS);
pthread_mutex_lock(&statistics_mutex);
if (total_ios != 0 && total_req != 0)
DPRINTF("Avg I/O operation latency during the last %d s: %lu; Avg request in queue time(clock ticks): %lu; total io ops: %lu; total reqs: %lu",
STAT_TIME_MS, total_io_interval / total_ios, total_req_inqueue_time/total_req, total_ios, total_req);
total_io_interval = 0;
total_req_inqueue_time = 0;
total_ios = 0;
total_req = 0;
pthread_mutex_unlock(&statistics_mutex);
}
return 0;
}
int init_statistics(){
clks_per_sec = sysconf(_SC_CLK_TCK);
return pthread_mutex_init(&statistics_mutex, 0);
}
int start_collecting(){
return pthread_create(&statistics_thread_id, 0, log_time_statistics, 0);
}
void update_io_interval(struct timespec start_time, struct timespec finish_time){
long tv = 0;
pthread_mutex_lock(&statistics_mutex);
if(start_time.tv_sec == finish_time.tv_sec){
tv = finish_time.tv_nsec - start_time.tv_nsec;
}else{
tv = (long)((finish_time.tv_sec - start_time.tv_sec)*(1000000000)) + (long)(finish_time.tv_nsec - start_time.tv_nsec);
}
total_io_interval += tv;
total_ios++;
pthread_mutex_unlock(&statistics_mutex);
}
void update_req_inqueue_time(unsigned long inqueue_time, unsigned long offqueue_time){
pthread_mutex_lock(&statistics_mutex);
total_req_inqueue_time += offqueue_time - inqueue_time;
total_req++;
pthread_mutex_unlock(&statistics_mutex);
}
int stop_collecting(){
return pthread_cancel(statistics_thread_id);
}
int destroy_statistics(){
return pthread_mutex_destroy(&statistics_mutex);
}
| 1
|
#include <pthread.h>
struct netent *getnetbyname(const char *name)
{
char *buf = _net_buf();
if (!buf)
return 0;
return getnetbyname_r(name, (struct netent *) buf,
buf + sizeof(struct netent), NET_BUFSIZE);
}
struct netent *getnetbyname_r(const char *name, struct netent *result,
char *buf, int bufsize)
{
char **alias;
pthread_mutex_lock(&net_iterate_lock);
setnetent(0);
while ((result = getnetent_r(result, buf, bufsize)) != 0) {
if (strcmp(result->n_name, name) == 0)
break;
for (alias = result->n_aliases; *alias != 0; alias++) {
if (strcmp(*alias, name) == 0)
break;
}
}
pthread_mutex_unlock(&net_iterate_lock);
return result;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
{
int min;
int max;
int ligne;
int colonne;
int nLigne;
int somme;
int **matrix;
} arguments;
void *thread(void *arg){
int s=0;
arguments *args = (arguments *) arg;
pthread_mutex_lock(&mutex);
int *newligne=calloc(args->colonne,sizeof(int));
for(int j=0; j<args->colonne; j++){
newligne[j]=rand()%(args->max-args->min+1) + args->min;
s+=newligne[j];
}
args->somme+=s;
pthread_mutex_unlock(&mutex);
pthread_exit(newligne);
}
int createThread(pthread_t *t, arguments *args){
int ret = pthread_create(t, 0, thread, (void *) args);
if( ret == -1) {
perror("pthread_create error");
return 1;
}
return ret;
}
int main(int argc, char *argv[])
{
if(argc<5)
{
printf("Veuillez saisir le bon nombre d'argument de la maniere suivante : \\n ./nomDeLExecutable borneMin borneMax nbLigne nbColonne \\n");
return 1;
}
else if(argc>5) {
printf("Nombre d'argument trop grand veuillez utiliser la syntaxe suivante : \\n ./nomDeLExecutable borneMin borneMax nbLigne nbColonne \\n");
return 1;
}
else {
int arg1=atoi(argv[1]);
int arg2=atoi(argv[2]);
int arg3=atoi(argv[3]);
int arg4=atoi(argv[4]);
arguments args;
args.min=arg1;
args.max=arg2;
args.ligne=arg3;
args.colonne=arg4;
args.somme=0;
args.matrix=calloc(args.ligne,sizeof(args.ligne));
for(int i=0; i<args.ligne; i++){
args.matrix[i]=calloc(args.colonne,sizeof(args.colonne));
}
pthread_t thread[args.ligne];
srand(time(0));
for(int k=0; k<args.ligne; k++){
createThread(&thread[k], &args);
}
for(int l=0; l<args.ligne; l++){
int *ligne;
if (pthread_join(thread[l], (void**) &ligne)){
perror("pthread_join");
return 1;
}
printf("(");
for (int m = 0; m < args.colonne; m++)
{
printf(" %d ", ligne[m] );
}
printf(")");
printf("\\n");
}
printf("La somme de cette matrice carre de taille 4 est de %d\\n", args.somme);
pthread_mutex_destroy(&mutex);
return 0;
}
}
| 1
|
#include <pthread.h>
int thID;
int min;
int max;
} arg;
int **a;
int N, M, T;
pthread_mutex_t mx;
int contador = 0;
void tres (arg *args) {
int i, j;
int c=0;
for (i=args->min; i<args->max; i++){
for (j=0; j<M; j++){
if (a[i][j] == 3)
c=c+1;
}
}
pthread_mutex_lock(&mx);
contador+=c;
pthread_mutex_unlock(&mx);
}
main (int argc, char *argv[]) {
struct timeval ts, tf;
int i, j;
int cl, fr;
pthread_t *th;
arg *args;
if (argc != 4) {printf ("USO: %s <dimX> <dimY> <Ths>\\n", argv[0]); exit (1);}
N = atoi(argv[1]);
M = atoi(argv[2]);
T = atoi(argv[3]);
th = malloc (T * sizeof (pthread_t));
a = malloc (N * sizeof (int *));
args = malloc (T * sizeof (int *));
if (a == 0||th == 0||args == 0) { printf ("Memoria\\n"); exit (1);}
for (i=0; i<N; i++) {
a[i] = malloc (M * sizeof (int));
if (a[i] == 0) { printf ("Memoria\\n"); exit (1);}
}
srandom (177845);
for (i=0; i<N; i++)
for (j=0; j<M; j++)
a[i][j] = random() % 10;
(void) pthread_mutex_init(&mx, 0);
cl = (int)ceil((float)N/(float)T);
fr = (int)floor((float)N/(float)T);
for (i=0;i<N%T;i++){
args[i].thID = i;
args[i].min = i*cl;
args[i].max = (i+1)*cl;
}
for (i=N%T;i<T;i++){
args[i].thID = i;
args[i].min =(N%T)*cl + (i-(N%T))*fr;
args[i].max =(N%T)*cl + (i-(N%T)+1)*fr;
}
gettimeofday (&ts, 0);
for (i=0; i<T; i++)
pthread_create (&th[i], 0, (void *) tres, &args[i]);
for (i=0; i<T; i++)
if (pthread_join (th[i], 0)) {printf ("PJOIN (%d)\\n", i); exit (1);};
gettimeofday (&tf, 0);
printf ("TRES: %d (%f secs)\\n", contador, ((tf.tv_sec - ts.tv_sec)*1000000u +
tf.tv_usec - ts.tv_usec)/ 1.e6);
exit (0);
}
| 0
|
#include <pthread.h>
int buffer[20];
int pointer = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int nitens() {
sleep(1);
return(rand() % 20 + 1);
}
void insere_item(int item) {
buffer[pointer] = item;
printf("\\nitem %d inserido (valor=%d)", pointer, item);
fflush(stdout);
pointer++;
sleep(1);
}
int remove_item() {
pointer--;
printf("\\nitem %d removido (valor=%d)", pointer, buffer[pointer]);
fflush(stdout);
sleep(1);
}
void* produtor(void* in) {
int i, k;
printf("\\nProdutor iniciando...");
fflush(stdout);
while(1) {
pthread_mutex_lock(&mutex);
k = nitens();
printf("\\nNº de itens a tratar no produtor =%d\\n",k);
for(i = 0; i < k; i++) {
if(pointer == 20) {
printf("\\nBuffer cheio -- produtor aguardando..."); fflush(stdout);
pthread_cond_wait(&cond1, &mutex);
printf("\\nProdutor reiniciando..."); fflush(stdout);
}
insere_item(rand() % 100);
}
pthread_cond_signal(&cond2);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void* consumidor(void* in) {
int i, k;
printf("\\nConsumidor iniciando...");
fflush(stdout);
while(1) {
pthread_mutex_lock(&mutex);
k = nitens();
printf("\\nNº de itens a tratar no consumidor =%d\\n",k);
for(i = 0; i < k; i++) {
if(pointer == 0) {
printf("\\nBuffer vazio -- consumidor aguardando..."); fflush(stdout);
pthread_cond_wait(&cond2, &mutex);
printf("\\nConsumidor reiniciando..."); fflush(stdout);
}
remove_item();
}
pthread_cond_signal(&cond1);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread2, 0, &consumidor, 0);
pthread_create(&thread1, 0, &produtor, 0);
pthread_join( thread1, 0);
exit(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock;
pthread_t thread_1;
pthread_t thread_2;
int a = 0;
void* func_1()
{
pthread_mutex_lock(&lock);
pthread_mutex_lock(&lock);
printf("thread fun1() lock\\n");
a = 2;
printf("thread fun1() a= %d\\n", a);
printf("thread fun1() unlock\\n");
pthread_mutex_unlock(&lock);
return 0;
}
void* func_2()
{
pthread_mutex_lock(&lock);
printf("thread fun2() lock\\n");
a = 3;
printf("thread fun2() a= %d\\n", a);
return 0;
}
int main()
{
pthread_mutex_init(&lock, 0);
pthread_mutex_lock(&lock);
a = 1;
printf("Main thread lock, a = %d\\n", a);
if (pthread_create(&thread_1, 0, func_1, 0) != 0)
printf("Create thread_1 failed\\n");
if (pthread_create(&thread_2, 0, func_2, 0) != 0)
printf("Create thread_2 failed\\n");
sleep(1);
printf("Main thread unlock, a = %d \\n",a);
pthread_mutex_unlock(&lock);
pthread_mutex_unlock(&lock);
pthread_join(thread_1,0);
pthread_join(thread_2,0);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
struct prodcons{
int buffer[16];
int read_pos;
int write_pos;
pthread_mutex_t lock;
pthread_cond_t not_empty;
pthread_cond_t not_full;
};
struct prodcons g_buffer;
void init(struct prodcons* buf){
pthread_mutex_init(&buf->lock,0);
pthread_cond_init(&buf->not_empty,0);
pthread_cond_init(&buf->not_full,0);
buf->read_pos = 0;
buf->write_pos = 0;
}
void put_data(struct prodcons* buf,int data){
pthread_mutex_lock(&buf->lock);
printf("mark point 1\\n");
if((buf->write_pos + 1)%16 == buf->read_pos)
pthread_cond_wait(&buf->not_full,&buf->lock);
buf->buffer[buf->write_pos] = data;
buf->write_pos++;
if(buf->write_pos >= 16)
buf->write_pos = 0;
pthread_cond_signal(&buf->not_empty);
pthread_mutex_unlock(&buf->lock);
}
int get_data(struct prodcons* buf){
int data;
pthread_mutex_lock(&buf->lock);
printf("mark point 2\\n");
if(buf->read_pos == buf->write_pos)
pthread_cond_wait(&buf->not_empty,&buf->lock);
data = buf->buffer[buf->read_pos];
buf->read_pos++;
if(buf->read_pos >= 16)
buf->read_pos = 0;
pthread_cond_signal(&buf->not_full);
pthread_mutex_unlock(&buf->lock);
return data;
}
void* producer(void* arg){
int n;
for(n=0;n<100;n++){
printf("%d------->\\n",n);
put_data(&g_buffer,n);
}
put_data(&g_buffer,(-1));
return 0;
}
void* consumer(void* arg){
int data;
while(1){
data = get_data(&g_buffer);
if(data == -1)
break;
printf("------->%d\\n",data);
}
return 0;
}
int main(void) {
pthread_t thr_a,thr_b;
void* retval;
init(&g_buffer);
pthread_create(&thr_a,0,producer,0);
pthread_create(&thr_b,0,consumer,0);
pthread_join(thr_a,&retval);
pthread_join(thr_b,&retval);
puts("Hello World!!!");
return 0;
}
| 1
|
#include <pthread.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* doSomeThing1(void *arg)
{
int j = 0;
printf("%s entering...", __func__);
fflush(stdout);
while(j < 10)
{
pthread_mutex_lock(&lock);
printf("%s done\\n", __func__);
if(j == 5) return 0;
unsigned long i = 0;
counter += 1;
printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j);
for(i=0; i<(0xFFFFFF);i++);
printf("\\n Job %d finished, tid = %ldm i = %d\\n", counter, pthread_self(), j);
pthread_mutex_unlock(&lock);
++j;
sleep(1);
}
return 0;
}
void* doSomeThing2(void *arg)
{
int j = 0;
printf("%s entering...", __func__);
fflush(stdout);
while(j < 10)
{
pthread_mutex_lock(&lock);
printf("%s done\\n", __func__);
unsigned long i = 0;
counter += 1;
printf("\\n Job %d started, tid = %ld, i = %d\\n", counter, pthread_self(), j);
for(i=0; i<(0xFFFFFF);i++);
printf("\\n Job %d finished, tid = %ld, i = %d\\n", counter, pthread_self(), j);
pthread_mutex_unlock(&lock);
++j;
sleep(1);
}
return 0;
}
int main(void)
{
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_create(&tid[0], 0, doSomeThing1, 0);
pthread_create(&tid[1], 0, doSomeThing2, 0);
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 0
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
int f_id;
struct foo *f_next;
};
struct foo *
foo_alloc(int id)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
fp->f_id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return(0);
}
idx = (((unsigned long)id)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return(fp);
}
void
foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *
foo_hold(int id)
{
struct foo *fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id)%29)]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return(fp);
}
void
foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (--fp->f_count == 0) {
idx = (((unsigned long)fp->f_id)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
pthread_mutex_unlock(&hashlock);
}
}
| 1
|
#include <pthread.h>
void prendre(int *c, struct Piece *stock, int i) {
int compt = *c;
int pos = index[i];
if ((compt == 0)
&& ((testOp[i](Anneau[pos], 1)) || (testOp[i](Anneau[pos], 2))
|| (testOp[i](Anneau[pos], 3)))) {
stock[0] = Anneau[pos];
Anneau[pos] = PieceNull;
compt++;
}
else if (testPiece(Anneau[pos], stock[0].numProduit, stock[0].etat)) {
stock[compt] = Anneau[pos];
Anneau[pos] = PieceNull;
compt++;
} else {
}
*c = compt;
}
void poser(struct Piece piece, int index) {
int compt;
if (testPiece(piece, 1, 5))
compt = 10;
else if (testPiece(piece, 2, 5))
compt = 15;
else if (testPiece(piece, 3, 6))
compt = 12;
else if (testPiece(piece, 4, 4))
compt = 8;
else
compt = 1;
while (1) {
pthread_mutex_lock(&lockAnneau);
if (testPiece(Anneau[index], 0, 0)) {
Anneau[index] = piece;
compt--;
pthread_mutex_unlock(&lockAnneau);
if (compt == 0)
return;
}
pthread_mutex_unlock(&lockAnneau);
usleep(10);
}
}
void * Robot(int num) {
int compt = 0;
struct Piece stock[3];
while (1) {
if ((compt == 1) && (testPiece(stock[0], 0, 0))) {
compt = 0;
}
pthread_mutex_lock(&lockAnneau);
prendre(&compt, stock, num);
pthread_mutex_unlock(&lockAnneau);
if (testOp[num](stock[0], compt)) {
usleep(10);
struct Piece tampom = Op[num](stock);
if (!testPiece(tampom, 0, 0)) {
poser(tampom, index[num]);
compt = 0;
}
}
usleep(1000);
}
pthread_exit(0 );
}
| 0
|
#include <pthread.h>
struct ListNode
{
int data;
struct ListNode* next;
struct ListNode* prev;
};
void append(struct ListNode* list, int data);
void printList(struct ListNode* list);
void printElement(struct ListNode* node);
void delete(struct ListNode* node);
struct ListNode * head;
pthread_mutex_t mutex_shared;
void * doAppend(void *threadid)
{
int id;
id = (int)threadid;
append(head,id);
pthread_exit(0);
}
int main(int argc, char** argv)
{
head = Malloc(sizeof(struct ListNode));
head->data = -1;
head->prev = 0;
head->next = 0;
pthread_mutex_init(&mutex_shared, 0);
pthread_t threads[10];
int t, rc;
for(t=0; t<10; t++)
{
rc = pthread_create(&threads[t], 0, doAppend, (void *)t);
if (rc)
{
printf("ERROR: return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
void * status;
for(t=0; t<10; t++)
{
rc = pthread_join(threads[t], &status);
if (rc)
{
printf("ERROR: return code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
printList(head);
pthread_exit(0);
}
void append(struct ListNode* list, int data)
{
pthread_mutex_lock(&mutex_shared);
struct ListNode* iter = list;
while(iter->next != 0)
{
iter = iter->next;
}
struct ListNode* newNode = Malloc(sizeof(struct ListNode));
newNode->data = data;
newNode->prev = iter;
newNode->next = 0;
iter->next = newNode;
pthread_mutex_unlock(&mutex_shared);
}
void printList(struct ListNode* list)
{
struct ListNode* iter = list;
while(iter != 0)
{
printf("%d ",iter->data);
iter = iter->next;
}
printf("\\n");
}
void printElement(struct ListNode* node)
{
if(node != 0)
{
printf("%d",node->data);
}
}
void delete(struct ListNode* node)
{
pthread_mutex_lock(&mutex_shared);
struct ListNode* a = node->prev;
struct ListNode* b = node->next;
if(a != 0)
{
a->next = b;
}
if(b != 0)
{
b->prev = a;
}
Free(node);
pthread_mutex_unlock(&mutex_shared);
}
| 1
|
#include <pthread.h>
struct thread_data
{
pthread_mutex_t *mutex;
pthread_cond_t *cond;
const unsigned trough_capacity;
const unsigned delay;
volatile int trough_quantity;
volatile int iters_rem;
};
static char *app_name_;
static void *
mare_thread_func (void *tdata)
{
static int mares_created = 0;
struct thread_data *data = (struct thread_data *) tdata;
int mare_id = ++mares_created;
while (data->iters_rem > 0)
{
if (data->trough_quantity > 0)
{
pthread_mutex_lock (data->mutex);
printf ("[mare %d] is about to eat...\\n", mare_id);
data->trough_quantity--;
printf ("[mare %d] ate one unit from trough (new quantity = %d)\\n",
mare_id, data->trough_quantity);
if (data->trough_quantity == 0)
{
printf ("\\ttrough doesn't contain sufficient amount of meat\\n");
printf ("[mare %d] is neighing.............\\n", mare_id);
pthread_cond_signal (data->cond);
}
pthread_mutex_unlock (data->mutex);
}
sleep (data->delay);
}
return 0;
}
static void *
farmer_thread_func (void *tdata)
{
struct thread_data *data = (struct thread_data *) tdata;
while (data->iters_rem > 0)
{
pthread_mutex_lock (data->mutex);
while (data->trough_quantity > 0)
{
pthread_cond_wait (data->cond, data->mutex);
}
printf ("[farmer] has just heard the neigh\\n");
printf ("[farmer] is about to refill the trough\\n");
data->trough_quantity = (int) data->trough_capacity;
printf ("\\tnew trough meal quantity = %d\\n", data->trough_quantity);
data->iters_rem--;
pthread_mutex_unlock (data->mutex);
}
return 0;
}
static void
usage ()
{
printf ("Usage: %s [OPTIONS]\\n\\n"
"Options:\\n"
"\\t-h,--help\\t\\tprints this usage\\n"
"\\t-c,--capacity\\t\\ttrough capacity\\n"
"\\t-m,--mares-num\\t\\tnumber of mares\\n"
"\\t-d,--delay\\t\\tnumber of seconds for delay\\n"
"\\t-i,--iterations\\t\\tnumber of iterations (refills)\\n",
app_name_);
}
static void
sim_run (int mares_num, int trough_capacity, int delay, int iterations)
{
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
struct thread_data data =
{ &mutex, &cond, trough_capacity, delay, trough_capacity, iterations };
printf ("starting simulation with parameters:\\n"
"\\ttrough capacity = %d units of meal\\n"
"\\tnumber of mares = %d\\n"
"\\tdelay = %d seconds\\n"
"\\titerations = %d refills\\n"
"\\t\\tnote: use '%s -h' for more information about parameters "
"customization\\n",
trough_capacity, mares_num, delay, iterations, app_name_);
pthread_t farmer_tid;
pthread_t mares_tid[mares_num];
pthread_create (&farmer_tid, 0, &farmer_thread_func, &data);
for (int i = 0; i < mares_num; i++)
{
pthread_create (&mares_tid[i], 0, &mare_thread_func, &data);
}
pthread_join (farmer_tid, 0);
for (int i = 0; i < mares_num; i++)
{
pthread_join (mares_tid[i], 0);
}
pthread_cond_destroy (&cond);
pthread_mutex_destroy (&mutex);
}
int
main (int argc, char *argv[])
{
static struct option long_opts[] =
{
{ "help", no_argument, 0, 'h' },
{ "capacity", required_argument, 0, 'c' },
{ "mares-num", required_argument, 0, 'm' },
{ "delay", required_argument, 0, 'd' },
{ "iterations", required_argument, 0, 'i' },
{ 0, 0, 0, 0 } };
static const char *short_opts = "hc:m:d:i:";
app_name_ = basename (argv[0]);
int trough_capacity = 10;
int mares_num = 3;
int delay = 1;
int iterations = 5;
int opt;
while ((opt = getopt_long (argc, argv, short_opts, long_opts, 0)) != -1)
{
switch (opt)
{
case 'h':
usage ();
return 0;
case 'c':
trough_capacity = atoi (optarg);
break;
case 'm':
mares_num = atoi (optarg);
break;
case 'd':
delay = atoi (optarg);
break;
case 'i':
iterations = atoi (optarg);
break;
default:
usage ();
return 0;
}
}
sim_run (mares_num, trough_capacity, delay, iterations);
printf ("\\nsimulation has ended successfully...\\n");
return 0;
}
| 0
|
#include <pthread.h>
extern FILE *fileout_basicmath;
extern pthread_mutex_t mutex_print;
int main_basicmath(void)
{
double a1 = 1.0, b1 = -10.5, c1 = 32.0, d1 = -30.0;
double a2 = 1.0, b2 = -4.5, c2 = 17.0, d2 = -30.0;
double a3 = 1.0, b3 = -3.5, c3 = 22.0, d3 = -31.0;
double a4 = 1.0, b4 = -13.7, c4 = 1.0, d4 = -35.0;
double x[3];
double X;
int solutions;
int i;
unsigned long l = 0x3fed0169L;
struct int_sqrt q;
long n = 0;
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath,"********* CUBIC FUNCTIONS ***********\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a1, b1, c1, d1, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath," %f",x[i]);
fprintf(fileout_basicmath,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a2, b2, c2, d2, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath," %f",x[i]);
fprintf(fileout_basicmath,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a3, b3, c3, d3, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath," %f",x[i]);
fprintf(fileout_basicmath,"\\n");
pthread_mutex_unlock(&mutex_print);
SolveCubic(a4, b4, c4, d4, &solutions, x);
pthread_mutex_lock(&mutex_print);
for(i=0;i<solutions;i++)
fprintf(fileout_basicmath," %f",x[i]);
fprintf(fileout_basicmath,"\\n");
pthread_mutex_unlock(&mutex_print);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath,"********* ANGLE CONVERSION ***********\\n");
pthread_mutex_unlock(&mutex_print);
double res;
for (X = 0.0; X <= 360.0; X += 1.0)
{
res = deg2rad(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath,"%3.0f degrees = %.12f radians\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
for (X = 0.0; X <= (2 * PI + 1e-6); X += (PI / 180))
{
res = rad2deg(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath,"%.12f radians = %3.0f degrees\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t counter = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t waitLeft = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t waitRight = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t tunnelWaitLeft = PTHREAD_COND_INITIALIZER;
pthread_cond_t tunnelWaitRight = PTHREAD_COND_INITIALIZER;
pthread_mutex_t ownerMutex = PTHREAD_MUTEX_INITIALIZER;
int semafor[2]={0,0};
int carsin,carsWaitLeft,carsWaitRight;
int lastUseRight,lastUseLeft;
int useless;
void* car(void *arg)
{
int direction = *(int*)arg;
if(direction==0)
{
pthread_mutex_lock(&waitLeft);
carsWaitLeft++;
pthread_mutex_unlock(&waitLeft);
}
else
{
pthread_mutex_lock(&waitRight);
carsWaitRight++;
pthread_mutex_unlock(&waitRight);
}
free(arg);
if(direction==0)
{
pthread_mutex_lock(&ownerMutex);
pthread_cond_wait(&tunnelWaitLeft,&ownerMutex);
printf("Car coming from direction LEFT entering tunnel.\\n");
pthread_mutex_unlock(&ownerMutex);
sleep(5);
lastUseLeft=(int)time(0);
pthread_mutex_lock(&counter);
carsin--;
pthread_mutex_unlock(&counter);
printf("Car coming from direction LEFT exiting tunnel.\\n");
return;
}
else
{
pthread_mutex_lock(&ownerMutex);
pthread_cond_wait(&tunnelWaitRight,&ownerMutex);
printf("Car coming from direction RIGHT entering tunnel.\\n");
pthread_mutex_unlock(&ownerMutex);
sleep(5);
lastUseRight=(int)time(0);
pthread_mutex_lock(&counter);
carsin--;
pthread_mutex_unlock(&counter);
printf("Car coming from direction RIGHT exiting tunnel.\\n");
return;
}
}
int otherSideNotStarving(int type)
{
int currTime;
currTime=(int)time(0);
if(type==0)
{
if(carsWaitRight==0)
{
printf("No cars on right side, keeping left semaphore GREEN\\n");
return 1;
}
else
{
if(currTime-lastUseRight<=4)
return 1;
else
return 0;
}
}
else
{
if(carsWaitLeft==0)
{
printf("No cars on left side, keeping right semaphore GREEN\\n");
return 1;
}
else
{
if(currTime-lastUseLeft<=4)
return 1;
else
return 0;
}
}
}
void * controlCenter(void *arg)
{
sleep(3);
semafor[0]=1;
lastUseRight=(int)time(0);
printf("LEFT side semaphore is GREEN\\n");
printf("RIGHT side smeaphore is RED\\n");
while(1)
{
if(semafor[0]==1)
{
while(otherSideNotStarving(0)&&carsWaitLeft!=0)
{
printf("Clearing 1 car coming from LEFT to enter tunnel.\\n");
pthread_mutex_lock(&counter);
carsin++;
pthread_mutex_unlock(&counter);
pthread_mutex_lock(&waitLeft);
carsWaitLeft--;
pthread_mutex_unlock(&waitLeft);
pthread_cond_signal(&tunnelWaitLeft);
sleep(1);
}
semafor[0]=0;
printf("LEFT side semaphore is RED\\n");
while(carsin!=0)
useless++;
if(carsWaitRight!=0)
{
semafor[1]=1;
printf("RIGHT side smeaphore is GREEN\\n");
}
else
if(carsWaitLeft==0)
{
printf("No more cars on either side. Exiting.\\n");
return;
}
}
if(semafor[1]==1)
{
while(otherSideNotStarving(1)&&carsWaitRight!=0)
{
printf("Clearing 1 car coming from RIGHT to enter tunnel.\\n");
pthread_mutex_lock(&counter);
carsin++;
pthread_mutex_unlock(&counter);
pthread_mutex_lock(&waitRight);
carsWaitRight--;
pthread_mutex_unlock(&waitRight);
pthread_cond_signal(&tunnelWaitRight);
sleep(1);
}
printf("RIGHT side smeaphore is RED\\n");
semafor[1]=0;
while(carsin!=0)
useless++;
if(carsWaitLeft!=0)
{
semafor[0]=1;
printf("LEFT side semaphore is GREEN\\n");
}
else
if(carsWaitLeft==0)
{
printf("No more cars on either side. Exiting.\\n");
return;
}
}
}
}
int main()
{
srand(time(0));
pthread_t threads[100];
pthread_t control_center;
pthread_create(&control_center,0,controlCenter,0);
for(int i=0;i<30;i++)
{
int * direction = (int*)malloc (sizeof(int));
if(i<=5)
*direction=0;
else
*direction=1;
pthread_create(&threads[i],0,car,(void*)direction);
}
sleep(300);
return 0;
}
| 0
|
#include <pthread.h>
void* value;
int key;
volatile struct _setos_node* next;
pthread_mutex_t lock;
} setos_node;
setos_node* head;
int setos_init(void)
{
head = (setos_node*) malloc(sizeof(setos_node));
head->next = 0;
head->key = INT_MIN;
if (pthread_mutex_init(&head->lock, 0) != 0)
{
printf("mutex init failed\\n");
return -1;
}
return 1;
}
int setos_free(void)
{
volatile setos_node* node = head;
while (node != 0)
{
pthread_mutex_destroy((void *) &(node->lock));
node = node->next;
}
free(head);
}
int setos_add(int key, void* value)
{
volatile setos_node* prev = head;
if (prev)
{
int rc = pthread_mutex_lock((void *) &(prev->lock));
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
}
volatile setos_node* node = prev->next;
if (node)
{
int rc = pthread_mutex_lock((void *) &(node->lock));
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
}
while ((node != 0) && (node->key < key))
{
pthread_mutex_unlock((void *) &(prev->lock));
prev = node;
node = node->next;
if (node){
int rc = pthread_mutex_lock((void *) &(node->lock));
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
}
}
if ((node != 0) && (node->key == key))
{
if (node){
pthread_mutex_unlock((void *) &(node->lock));
}
pthread_mutex_unlock((void *) &(prev->lock));
return 0;
}
volatile setos_node* new_node = (setos_node*) malloc(sizeof(setos_node));
new_node->key = key;
new_node->value = value;
if (pthread_mutex_init((void *)&new_node->lock, 0) != 0)
{
printf("mutex init failed\\n");
return -1;
}
new_node->next = node;
prev->next = new_node;
if(node){
pthread_mutex_unlock((void *) &(node->lock));
}
pthread_mutex_unlock((void *) &(prev->lock));
return 1;
}
int setos_remove(int key, void** value)
{
volatile setos_node* prev = head;
if (prev)
{
int rc = pthread_mutex_lock((void *) &(prev->lock));
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
}
volatile setos_node* node = head->next;
if (node)
{
int rc = pthread_mutex_lock((void *) &(node->lock));
if (rc != 0)
{
perror("cannot acquire lock\\n");
}
}
while (node != 0)
{
pthread_mutex_unlock((void *) &(prev->lock));
if (node->key == key) {
if (value != 0)
*value = node->value;
prev->next = node->next;
pthread_mutex_destroy((void *) &node->lock);
return 1;
}
prev = node;
node = node->next;
}
return 0;
}
int setos_contains(int key)
{
volatile setos_node* node = head->next;
while (node != 0)
{
if (node->key == key)
{
return 1;
}
node = node->next;
}
return 0;
}
int main(void)
{
printf ("fine\\n" );
int x = 1;
if (setos_init()==-1)
{
return -1;
}
setos_add(1, &x);
setos_add(2, &x);
setos_add(3, &x);
setos_free();
printf ("done\\n" );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t shop_mutex;
pthread_mutex_t nextCustomer_mutex;
pthread_mutex_t barberSleep_mutex;
pthread_cond_t barberSleepStatus_cond;
pthread_cond_t barberWorkStatus_cond;
int numCustomers = 0;
int barberSleeping = 0;
int haircutTime = 0;
void get_hair_cut();
void cut_hair();
void *generate_customer();
void customer();
void *waiting_room();
void *barber_room();
void get_hair_cut(){
printf("Customer is getting a haircut... \\n");
sleep(haircutTime);
}
void cut_hair(){
printf("Barber is cutting hair... \\n");
sleep(haircutTime);
}
void *generate_customer(){
int i = 0;
pthread_t customers[10 + 1];
pthread_attr_t customers_attr[10 + 1];
while(1){
sleep(rand()%6+1);
for(i=0; i < (10 + 1); ++i) {
pthread_attr_init(&customers_attr[i]);
pthread_create(&customers[i], &customers_attr[i], waiting_room, 0);
}
}
}
void customer(){
if(numCustomers < 10){
if(barberSleeping == 1){
printf("The barber is sleeping! The customer pokes the barber to wake him up. \\n");
pthread_cond_signal(&barberSleepStatus_cond);
}
pthread_mutex_unlock(&shop_mutex);
printf("There is a seat! The customer sits down.\\n");
pthread_mutex_lock(&nextCustomer_mutex);
pthread_cond_wait(&barberWorkStatus_cond, &nextCustomer_mutex);
get_hair_cut();
pthread_mutex_unlock(&nextCustomer_mutex);
pthread_exit(0);
numCustomers--;
}
if(numCustomers >= 10){
numCustomers--;
pthread_mutex_unlock(&shop_mutex);
printf("All the seats are filled :( The customer sadly leaves the shop... \\n");
pthread_exit(0);
}
}
void *waiting_room(){
pthread_mutex_lock(&shop_mutex);
numCustomers++;
printf("A customer has entered the waiting room. Checking for available seats...\\n");
customer();
}
void *barber_room(){
while(1){
if(numCustomers == 0){
pthread_mutex_lock(&barberSleep_mutex);
barberSleeping = 1;
printf("The lack of customer is making the barber sleepy. He decides to take a quick snooze.\\n");
pthread_cond_wait(&barberSleepStatus_cond, &barberSleep_mutex);
barberSleeping = 0;
printf("The barber woke up! Time to get back to work.\\n");
}
else{
printf("The barber calls for the next customer.\\n");
srand(time(0));
haircutTime = rand()%10;
pthread_cond_signal(&barberWorkStatus_cond);
cut_hair();
printf("The barber finished cutting the hair!\\n");
}
}
}
int main(int argc, char *argv[]){
pthread_t barber;
pthread_t customersGenerator;
pthread_t timer;
pthread_attr_t barber_attr;
pthread_attr_t customersGenerator_attr;
pthread_attr_t timer_attr;
pthread_attr_init(&barber_attr);
pthread_attr_init(&customersGenerator_attr);
pthread_attr_init(&timer_attr);
pthread_create(&barber, &barber_attr, barber_room, 0);
pthread_create(&customersGenerator, &customersGenerator_attr, generate_customer, 0);
pthread_join(barber, 0);
pthread_join(customersGenerator, 0);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.