text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
static unsigned int freqScanStartFreq;
static unsigned int freqScanEndFreq;
unsigned char freqScanDriAmp;
unsigned short freqScanRes;
unsigned short freqScanDelay;
static short freqScanAmpBuf[518];
static short freqScanPhaseBuf[518];
void setFreqRange(unsigned int startFreq, unsigned int endFreq)
{
freqScanStartFreq = startFreq;
freqScanEndFreq = endFreq;
}
void setFreqPara(void* para)
{
struct command *pCmd = (struct command *) para;
freqScanDriAmp = pCmd->para1 & 0xFF;
setFreqDriAmp(freqScanDriAmp);
freqScanRes = pCmd->para2;
freqScanDelay = pCmd->para3;
DEBUG1("DriAmp is %d\\n",freqScanDriAmp);
DEBUG1("ScanRes is %d\\n",freqScanRes);
DEBUG1("ScanDelay is %d us\\n",freqScanDelay);
}
void setFreqDriAmp(unsigned char para)
{
int i = 0;
char ctr;
outb(0,DDS_522_CS_ADR);
ctr = 0x23;
for(i = 7; i >= 0; i--)
{
outb(ctr >> i, DDS_522_DATA_ADR);
}
for(i = 7; i >= 0; i--)
{
outb(para >> i, DDS_522_DATA_ADR);
}
outb(1,DDS_522_CS_ADR);
}
void dds_Reset()
{
outb(0x0,DDS_RST_ADR);
outb(0x1,DDS_RST_ADR);
outb(0x0,DDS_RST_ADR);
}
void dds_Out(double freq)
{
const unsigned int DIV = 0xffffffff;
const double Ratio = 125000000.0 / DIV;
unsigned int Data = (unsigned int) (freq / Ratio);
unsigned char* pData = (unsigned char*)(&Data);
outb(0x00, DDS_ADR);
outb(pData[3], DDS_ADR);
outb(pData[2], DDS_ADR);
outb(pData[1], DDS_ADR);
outb(pData[0], DDS_ADR);
inb(DDS_ADR);
}
void* freqScanThread(void* para)
{
int i;
int count = 0;
int currentTask;
pthread_detach(pthread_self());
double startFreq = (double) freqScanStartFreq;
double endFreq = (double) freqScanEndFreq;
double currentFreq;
DEBUG0("STARTING FREQENCY SCANNING ..................................");
freqScanAmpBuf[0] = CMD_FREQ_SCAN;
freqScanAmpBuf[1] = 0;
freqScanPhaseBuf[0] = CMD_FREQ_SCAN;
freqScanPhaseBuf[1] = 1;
for(count = 0; count < 2; count++)
{
for(i = 0; i < freqScanRes; i++)
{
pthread_mutex_lock(&g_current_task_mutex);
currentTask = g_current_task;
pthread_mutex_unlock(&g_current_task_mutex);
if(currentTask == STOP) break;
currentFreq = startFreq + i * (endFreq - startFreq) / freqScanRes;
dds_Out(currentFreq);
udelay(freqScanDelay);
if(count % 2 == 0)
freqScanAmpBuf[6 + i] = read_ad_by_channel(0x3,scanSamplingTimes);
else
freqScanPhaseBuf[6 + i] = read_ad_by_channel(0x4,scanSamplingTimes);
}
}
send(connect_socket_fd, (char*)&freqScanAmpBuf, 1036, 0);
DEBUG0("send(connect_socket_fd, (char*)&freqScanAmpBuf, 1036, 0);");
send(connect_socket_fd, (char*)&freqScanPhaseBuf, 1036, 0);
DEBUG0("send(connect_socket_fd, (char*)&freqScanPhaseBuf, 1036, 0);");
pthread_mutex_lock(&g_current_task_mutex);
g_current_task = STOP;
pthread_mutex_unlock(&g_current_task_mutex);
DEBUG0("End of freq scan thread ......");
return (void*)0;
}
void setTappingSingle(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("choose Amplitude");
break;
case 1:
DEBUG0("choose Phase");
break;
case 2:
DEBUG0("choose Frequency");
break;
}
}
void setTdPidMode(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("auto adjustment");
break;
case 1:
DEBUG0("manual adjustment");
break;
}
}
void setImageScale(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("image scale 1:1");
break;
case 1:
DEBUG0("image scale 1:4");
break;
case 2:
DEBUG0("image scale 1:8");
break;
case 3:
DEBUG0("image scale 1:16");
break;
}
}
void setSlowAxis(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("slow axis on");
break;
case 1:
DEBUG0("slow axis off");
break;
}
}
void setSwitchError(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("switch error off");
break;
case 1:
DEBUG0("switch error on");
break;
}
}
void setSwitchFriction(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("switch friction off");
break;
case 1:
DEBUG0("switch friction on");
break;
}
}
void setSwitchDeflection(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("switch deflection off");
break;
case 1:
DEBUG0("switch deflection on");
break;
}
}
void setSwitchPhase(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("switch phase off");
break;
case 1:
DEBUG0("switch phase on");
break;
}
}
void setSwitchAmplitude(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("switch amplitude off");
break;
case 1:
DEBUG0("swictch amplitude on");
break;
}
}
void setImageDirection(unsigned short para)
{
switch (para)
{
case 0:
DEBUG0("up to down");
break;
case 1:
DEBUG0("down to up");
break;
}
}
| 1
|
#include <pthread.h>
const int NN = 10;
const long TOP = 1000000000;
long sum;
pthread_mutex_t mutex;
long r0;
long r1;
} sum_job;
void*
sum_range_thread(void* arg)
{
sum_job job = *((sum_job*) arg);
free(arg);
for (long ii = job.r0; ii < job.r1; ++ii) {
if (ii % 101 == 0) {
pthread_mutex_lock(&mutex);
sum += ii;
pthread_mutex_unlock(&mutex);
}
}
return 0;
}
pthread_t
spawn_sum_range(long r0, long r1)
{
sum_job* job = malloc(sizeof(sum_job));
job->r0 = r0;
job->r1 = r1;
pthread_t thread;
int rv = pthread_create(&thread, 0, sum_range_thread, job);
assert(rv == 0);
return thread;
}
int
main(int _ac, char* _av[])
{
pthread_t threads[NN];
printf("Summing numbers divisible by 101 from 0 to %ld.\\n", TOP - 1);
sum = 0;
pthread_mutex_init(&mutex, 0);
long step = TOP / NN;
for (int ii = 0; ii < NN; ++ii) {
long start = ii * step;
threads[ii] = spawn_sum_range(ii, ii + step);
}
for (int ii = 0; ii < NN; ++ii) {
int rv = pthread_join(threads[ii], 0);
assert(rv == 0);
}
printf("Sum = %ld\\n", sum);
return 0;
}
| 0
|
#include <pthread.h>
volatile int s = 0;
pthread_mutex_t mutex;
void *ExecutaTarefa (void *threadid) {
int i, tid = *(int*) threadid;
printf("Thread : %d esta executando...\\n", tid);
for (i=0; i<10000000; i++) {
pthread_mutex_lock(&mutex);
s++;
pthread_mutex_unlock(&mutex);
}
printf("Thread : %d terminou!\\n", tid);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t tid[2];
int t, id[2];
double ini, fim;
GET_TIME(ini);
pthread_mutex_init(&mutex, 0);
for(t=0; t<2; t++) {
id[t]=t;
if (pthread_create(&tid[t], 0, ExecutaTarefa, (void *) &id[t])) {
printf("--ERRO: pthread_create()\\n"); exit(-1);
}
}
for (t=0; t<2; t++) {
if (pthread_join(tid[t], 0)) {
printf("--ERRO: pthread_join() \\n"); exit(-1);
}
}
pthread_mutex_destroy(&mutex);
GET_TIME(fim);
printf("Valor de s = %d\\n", s);
printf("Tempo = %lf\\n", fim-ini);
pthread_exit(0);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(
i=0; i<(800); i++)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i]=value;
}
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
void *t2(void *arg)
{
int i;
pthread_mutex_lock(&m);
if (dequeue_flag)
{
for(
i=0; i<(800); i++)
{
if (empty(&queue)!=(-1))
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
const int NUM_THREADS = 64;
const int ITERATIONS = 100;
int x;
int y;
} point;
float best_cost = FLT_MAX;
point* points;
int* best_path;
float** distances;
int num_coords;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void readFile(char* filename) {
FILE* ifp;
char* mode = "r";
ifp = fopen(filename, mode);
int x, y, n = 0;
while(fscanf(ifp, "%d %d", &x, &y) != EOF) {
n++;
points = (point*)realloc(points, n * sizeof(point));
best_path = (int*)realloc(best_path, n * sizeof(int));
best_path[n-1] = n-1;
points[n-1].x = x;
points[n-1].y = y;
}
num_coords = n;
}
void calculate_distances() {
distances = (float**)malloc(num_coords * sizeof(float*));
int i, j;
for(i = 0; i < num_coords; i++) {
distances[i] = (float*)malloc(num_coords * sizeof(float));
}
for(i = 0; i < num_coords; i++)
for(j = 0; j < num_coords; j++) {
int dx = points[i].x - points[j].x;
int dy = points[i].y - points[j].y;
distances[i][j] = sqrt(dx*dx + dy*dy);
}
}
float get_cost(int path[]) {
float cost = 0;
int i;
for(i = 0; i < num_coords - 1; i++) {
cost += distances[path[i]][path[i+1]];
}
cost += distances[0][i];
return cost;
}
void* search(void* t) {
int id = time(0);
int path[num_coords];
int thiscost = best_cost;
int i;
for(i = 0; i < num_coords; i++) {
path[i] = i;
}
for(i = num_coords-1; i > 0; i--) {
int j = rand() % (i+1);
int temp = path[i];
path[i] = path[j];
path[j] = temp;
}
int r1, r2;
for(i = 0; i < ITERATIONS; i++) {
if(best_cost < thiscost) {
pthread_mutex_lock(&mutex);
thiscost = best_cost;
int j;
for(j = 0; j < num_coords; j++) {
path[j] = best_path[j];
}
pthread_mutex_unlock(&mutex);
}
do {
r1 = rand() % num_coords;
r2 = rand() % num_coords;
} while(r1 == r2);
int temp = path[r1];
path[r1] = path[r2];
path[r2] = temp;
thiscost = get_cost(path);
if(thiscost < best_cost) {
pthread_mutex_lock(&mutex);
best_cost = thiscost;
int j;
for(j = 0; j < num_coords; j++) {
best_path[j] = path[j];
}
i = 0;
pthread_mutex_unlock(&mutex);
}
else {
temp = path[r2];
path[r2] = path[r1];
path[r1] = temp;
}
}
pthread_exit(0);
}
int main() {
srand(time(0));
readFile("coordinates.txt");
calculate_distances();
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int i;
for(i = 0; i < NUM_THREADS; i++) {
pthread_create(&threads[i], &attr, search, 0);
}
pthread_attr_destroy(&attr);
for(i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], 0);
}
printf("%i. ", (int)best_cost);
for(i = 0; i < num_coords; i++) {
printf("%d ", best_path[i]);
}
printf("\\n");
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc = PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0)
err_exit(err, "sigwait failed");
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&waitloc);
return(0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0)
err_exit(err, "SIG_BLOCK error");
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
err_exit(err, "can't create thread");
pthread_mutex_lock(&lock);
while (quitflag == 0)
pthread_cond_wait(&waitloc, &lock);
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
err_sys("SIG_SETMASK error");
exit(0);
}
| 0
|
#include <pthread.h>
int read_cnt=0;
int write_flag=1;
pthread_mutex_t read_cnt_mutex,access_mutex,write_flag_mutex;
int cnt=3;
void* write_handler(void* arg);
void* read_handler(void* arg);
int main(){
int type;
srand(getpid());
pthread_mutex_init(&read_cnt_mutex,0);
pthread_mutex_init(&access_mutex,0);
pthread_mutex_init(&write_flag_mutex,0);
while(1){
type=rand();
if(type%2==0){
pthread_t tid;
pthread_create(&tid,0,write_handler,0);
}
else{
pthread_t tid;
pthread_create(&tid,0,read_handler,0);
}
sleep(1);
}
pthread_mutex_destroy(&read_cnt_mutex);
pthread_mutex_destroy(&access_mutex);
pthread_mutex_destroy(&write_flag_mutex);
}
void* write_handler(void* arg){
pthread_detach(pthread_self());
pthread_mutex_lock(&access_mutex);
printf("a writer in before:%d\\n",cnt);
cnt++;
sleep(5);
printf("a write out after:%d \\n",cnt);
pthread_mutex_unlock(&access_mutex);
}
void* read_handler(void* arg){
pthread_detach(pthread_self());
pthread_mutex_lock(&read_cnt_mutex);
if(read_cnt==0){
pthread_mutex_lock(&access_mutex);
}
read_cnt++;
pthread_mutex_unlock(&read_cnt_mutex);
printf("a reader in,id:%u, cnt value:%d\\n",pthread_self(),cnt);
sleep(3);
pthread_mutex_lock(&read_cnt_mutex);
read_cnt--;
printf("a reader leave!id:%u, reader left: %d\\n",pthread_self(),read_cnt);
if(read_cnt==0){
pthread_mutex_unlock(&access_mutex);
}
pthread_mutex_unlock(&read_cnt_mutex);
}
| 1
|
#include <pthread.h>
struct __rbst_node {
char *key;
void *value;
struct __rbst_node *left;
struct __rbst_node *right;
};
static rbst_node* rbst_search(rbst_node* tree, char* key);
static rbst_node* rbst_insert(rbst_node* tree, rbst_node* new_node);
static rbst_node* rbst_deletetree(rbst_node* tree);
static rbst_node* rbst_rootinsert(rbst_node* tree, rbst_node* new_node);
static rbst_node* rbst_rotateleft(rbst_node* node);
static rbst_node* rbst_rotateright(rbst_node* node);
static void rbst_inlineprint(rbst_node* node);
static rbst_node* tree_base;
static unsigned int tree_size;
pthread_mutex_t rbst_mutex = PTHREAD_MUTEX_INITIALIZER;
int rbst_get(char* key, void** value) {
rbst_node* found_node;
pthread_mutex_lock(&rbst_mutex);
found_node = rbst_search(tree_base, key);
pthread_mutex_unlock(&rbst_mutex);
if (found_node == 0) {
return RBST_ENOTFOUND;
}
*value = found_node->value;
return 0;
}
int rbst_add(char* key, void* value) {
rbst_node* new_node;
int err;
unsigned int old_size;
if (rbst_get(key, value) != RBST_ENOTFOUND)
return RBST_EALREADYCACHED;
if ((new_node = malloc(sizeof(rbst_node))) == 0) {return -RBST_ENOMEM;}
if ((new_node->key = strdup(key)) == 0) {return -RBST_ENOMEM;}
new_node->value = value;
new_node->left = 0;
new_node->right = 0;
old_size = tree_size;
pthread_mutex_lock(&rbst_mutex);
tree_base = rbst_insert(tree_base, new_node);
pthread_mutex_unlock(&rbst_mutex);
if (old_size==tree_size) { err = RBST_EADDFAILED; }
else { err = 0; }
return err;
}
void rbst_free(void) {
pthread_mutex_lock(&rbst_mutex);
tree_base = rbst_deletetree(tree_base);
tree_base = 0;
pthread_mutex_unlock(&rbst_mutex);
}
void rbst_dump(void) {
rbst_inlineprint(tree_base);
}
static rbst_node* rbst_deletetree(rbst_node* tree) {
if (tree->left!=0) {
rbst_deletetree(tree->left);
}
if (tree->right!=0) {
rbst_deletetree(tree->right);
}
if (tree->key!=0) { free(tree->key); }
if (tree->value!=0) { free(tree->value); }
if (tree!=0) { free(tree); tree=0; }
return 0;
}
static rbst_node* rbst_search(rbst_node* tree, char* key) {
int cmp;
if (tree == 0){
return 0;
}
cmp = strcmp(tree->key,key);
if (cmp == 0) {
return tree;
}
else if (cmp < 0) {
return rbst_search(tree->right, key);
}
else {
return rbst_search(tree->left, key);
}
}
static rbst_node* rbst_insert(rbst_node* tree, rbst_node* new_node) {
int r;
if (tree==0) {
tree_size++;
return new_node;
}
r = (int)(((double)rand()/(double)32767) * tree_size) +1;
if (r==1) {
tree_size++;
return rbst_rootinsert(tree, new_node);
}
if (strcmp(new_node->key, tree->key) < 0) {
tree->left = rbst_insert(tree->left, new_node);
}
else {
tree->right = rbst_insert(tree->right, new_node);
}
tree_size++;
return tree;
}
static rbst_node* rbst_rootinsert(rbst_node* tree, rbst_node* new_node) {
if (tree == 0) {
return new_node;
}
if (strcmp(new_node->key, tree->key) < 0) {
tree->left = rbst_rootinsert(tree->left, new_node);
return rbst_rotateright(tree);
}
else {
tree->right = rbst_rootinsert(tree->right, new_node);
return rbst_rotateleft(tree);
}
}
static rbst_node* rbst_rotateleft(rbst_node* node) {
rbst_node* right;
right = node->right;
node->right = right->left;
right->left = node;
return right;
}
static rbst_node* rbst_rotateright(rbst_node* node) {
rbst_node* left;
left = node->left;
node->left = left->right;
left->right = node;
return left;
}
static void rbst_inlineprint(rbst_node* node) {
if (node==0) return;
if (node->left != 0)
rbst_inlineprint(node->left);
fprintf(stdout,"%s: %p\\n", node->key, node->value);
if (node->right != 0)
rbst_inlineprint(node->right);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t __atomic_mutex = PTHREAD_MUTEX_INITIALIZER;
int32_t atomic_increment(int32_t *ptr)
{
int32_t r;
pthread_mutex_lock(&__atomic_mutex);
r = ++(*ptr);
pthread_mutex_unlock(&__atomic_mutex);
return(r);
}
int32_t atomic_decrement(int32_t *ptr)
{
int32_t r;
pthread_mutex_lock(&__atomic_mutex);
r = --(*ptr);
pthread_mutex_unlock(&__atomic_mutex);
return(r);
}
int32_t atomic_set(int32_t *ptr, int32_t val)
{
pthread_mutex_lock(&__atomic_mutex);
(*ptr) = val;
pthread_mutex_unlock(&__atomic_mutex);
return(val);
}
int32_t atomic_add(int32_t *ptr, int32_t val)
{
int32_t r;
pthread_mutex_lock(&__atomic_mutex);
r = ((*ptr) += val);
pthread_mutex_unlock(&__atomic_mutex);
return(r);
}
int32_t atomic_cas(int32_t *ptr, int32_t val, int32_t cmp)
{
int32_t r;
pthread_mutex_lock(&__atomic_mutex);
r = *ptr;
if((*ptr) == cmp)
*ptr = val;
pthread_mutex_unlock(&__atomic_mutex);
return(r);
}
int32_t atomic_swap(int32_t *ptr, int32_t val)
{
int32_t r;
pthread_mutex_lock(&__atomic_mutex);
r = *ptr;
*ptr = val;
pthread_mutex_unlock(&__atomic_mutex);
return(r);
}
| 1
|
#include <pthread.h>
static pthread_cond_t main_cond;
static pthread_mutex_t main_lock;
int main(int argc, char** argv)
{
int ret;
int exit = 0;
struct timeval now;
struct timespec outtime;
pthread_mutex_init(&main_lock, 0);
pthread_cond_init(&main_cond, 0);
scorpion_socket_start_server();
stm32_send_version_req();
while(!exit)
{
pthread_mutex_lock(&main_lock);
gettimeofday(&now, 0);
outtime.tv_sec = now.tv_sec + 30;
outtime.tv_nsec = now.tv_usec * 1000;
ret = pthread_cond_timedwait(&main_cond, &main_lock, &outtime);
pthread_mutex_unlock(&main_lock);
ALOGI("scorpion main......\\r\\n");
if(ret == 0)
{
ALOGE("Exit Scorpion");
exit = 1;
continue;
}
else
{
stm32_send_heart_beat();
scorpion_heart_beat_treat();
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* formarCtrl(void *);
void* pasarCtrl(void *);
int sig = -1;
int dir = -1;
int numM = 0;
int numH = 0;
int flagS = 0;
int flagO = 0;
int main(void)
{
pthread_t * threads = (pthread_t*)malloc(sizeof(pthread_t) * 3);
pthread_create(threads, 0, &formarCtrl, 2);
pthread_create(threads + 1, 0, &pasarCtrl, 0);
pthread_create(threads + 2, 0, &pasarCtrl, 1);
pthread_join(*(threads), 0);
pthread_join(*(threads + 1), 0);
pthread_join(*(threads + 2), 0);
free(threads);
return 0;
}
void* formarCtrl(void *arg)
{
while (1)
{
pthread_mutex_lock(&lock2);
pthread_mutex_lock(&lock);
int temp = rand() % 2;
if (temp % 2 == 0)
{
numM++;
printf(" Llega mujer :: %d esperando\\n", numM);
if (flagS == 0)
{
dir = 0;
flagS = 1;
}
}
if (temp % 3 == 0)
{
numH++;
printf("Llega hombre :: %d esperando\\n", numH);
if (flagS == 0)
{
dir = 1;
flagS = 1;
}
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
sig = 1;
}
}
void* pasarCtrl(void * arg)
{
int args = (int)arg;
while (1)
{
int sum = 0;
pthread_mutex_lock(&lock);
while (sig == -1)
pthread_cond_wait(&cond, &lock);
if (flagO == 0)
printf(" Baño vacío\\n");
if (flagO == 1)
printf(" Entra mujer\\n");
if (flagO == 2)
printf(" Entra hombre\\n");
if (args == 0 && dir == 0 && numM > 0)
{
flagO = 1;
numM--;
printf(" Sale mujer :: %d esperando\\n", numM);
}
if (args == 0 && dir == 1 && numH > 0)
{
flagO = 2;
numH--;
printf(" Sale mujer :: %d esperando\\n", numH);
}
if (numH == 0 || numM == 0)
{
flagO = 0;
if (numM == 0)
{
flagO = 2;
dir = 1;
}
if (numH == 0)
{
flagO = 1;
dir = 0;
}
}
pthread_mutex_unlock(&lock);
pthread_mutex_unlock(&lock2);
sleep(1);
}
}
| 1
|
#include <pthread.h>
int dest[8] = { 0 };
int flag[8] = { 0 };
int me, npes;
int errors = 0;
pthread_barrier_t fencebar;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void * thread_main(void *arg) {
int tid = * (int *) arg;
int i, val, expected;
val = me;
for (i = 1; i <= npes; i++)
shmem_int_add(&dest[tid], val, (me + i) % npes);
pthread_barrier_wait(&fencebar);
if (tid == 0) shmem_fence();
pthread_barrier_wait(&fencebar);
for (i = 1; i <= npes; i++)
shmem_int_inc(&flag[tid], (me + i) % npes);
shmem_int_wait_until(&flag[tid], SHMEM_CMP_EQ, npes);
expected = (npes-1) * npes / 2;
if (dest[tid] != expected || flag[tid] != npes) {
printf("Atomic test error: [PE = %d | TID = %d] -- "
"dest = %d (expected %d), flag = %d (expected %d)\\n",
me, tid, dest[tid], expected, flag[tid], npes);
pthread_mutex_lock(&mutex);
++errors;
pthread_mutex_unlock(&mutex);
}
if (0 == tid) shmem_barrier_all();
pthread_barrier_wait(&fencebar);
val = -1;
shmem_int_put(&dest[tid], &val, 1, (me + 1) % npes);
pthread_barrier_wait(&fencebar);
if (0 == tid) shmem_barrier_all();
pthread_barrier_wait(&fencebar);
for (i = 1; i <= npes; i++) {
shmem_int_get(&val, &dest[tid], 1, (me + i) % npes);
expected = -1;
if (val != expected) {
printf("Put/get test error: [PE = %d | TID = %d] -- From PE %d, got %d expected %d\\n",
me, tid, (me + i) % npes, val, expected);
pthread_mutex_lock(&mutex);
++errors;
pthread_mutex_unlock(&mutex);
}
}
pthread_barrier_wait(&fencebar);
if (0 == tid) shmem_barrier_all();
return 0;
}
int main(int argc, char **argv) {
int tl, i;
pthread_t threads[8];
int t_arg[8];
shmemx_init_thread(SHMEMX_THREAD_MULTIPLE, &tl);
if (SHMEMX_THREAD_MULTIPLE != tl) {
printf("Warning: Exiting because threading is disabled, tested nothing\\n");
shmem_finalize();
return 0;
}
me = shmem_my_pe();
npes = shmem_n_pes();
pthread_barrier_init(&fencebar, 0, 8);
if (me == 0) printf("Starting multithreaded test on %d PEs, %d threads/PE\\n", npes, 8);
for (i = 0; i < 8; i++) {
int err;
t_arg[i] = i;
err = pthread_create(&threads[i], 0, thread_main, (void*) &t_arg[i]);
assert(0 == err);
}
for (i = 0; i < 8; i++) {
int err;
err = pthread_join(threads[i], 0);
assert(0 == err);
}
pthread_barrier_destroy(&fencebar);
if (me == 0) {
if (errors) printf("Encountered %d errors\\n", errors);
else printf("Success\\n");
}
shmem_finalize();
return (errors == 0) ? 0 : 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t randMutex = PTHREAD_MUTEX_INITIALIZER;
void *work(void *t) {
double *result = malloc(sizeof(double));
int tid = (int)t;
pthread_mutex_lock(&randMutex);
srand(time(0) + (unsigned int)result - (unsigned int)&tid * 5 * (tid+1));
*result = ((double)rand() / ((double)32767 + 1.0)) * 500000;
pthread_mutex_unlock(&randMutex);
return (void*) result;
}
int main(int argc, char *argv[]) {
pthread_t thread[4];
pthread_attr_t attr;
int rc, i;
double res, total=0.0;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++) {
rc = pthread_create(&thread[i], &attr, work, (void *)i);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i=0; i<4; i++) {
rc = pthread_join(thread[i], &status);
if (rc) {
printf("ERROR return code from pthread_join() is %d\\n", rc);
exit(-1);
}
res = *(double *)status;
total += res;
printf("Joined with thread %d, result = %6.2f\\n", i, res);
}
printf("\\nProgram completed, total = %6.2f\\n", total);
exit(0);
}
| 1
|
#include <pthread.h>
int get_rand_int(int range_min, int range_max) {
if (range_min > range_max) {
fprintf(stderr, "gen_random(): invalid arguments\\n" );
exit(1);
}
return range_min+rand()%(range_max-range_min+1);
}
void* cst_func(void* args) {
int i = 0, cid = 0, st_id = 0, stf_num = 0;
cid = (int) args;
while (cst_val[cid] > 0) {
st_id = get_rand_int(0, STORE_NUM - 1);
stf_num = get_rand_int(0, 512);
stf_num = (cst_val[cid] - stf_num >= 0) ? stf_num : cst_val[cid];
pthread_mutex_lock(&st_mtx[st_id]);
stf_num = (st_val[st_id] - stf_num >= 0) ? stf_num : st_val[st_id];
st_val[st_id] -= stf_num;
cst_val[cid] -= stf_num;
printf("Customer[id = %d]: store id = %d, stuff num = %d, remains = %d\\n", cid, st_id, stf_num, cst_val[cid]);
pthread_mutex_unlock(&st_mtx[st_id]);
sleep(2);
}
pthread_exit(0);
}
void* ldr_func(void* args) {
int i = 0, lid = 0, st_id = 0, stf_num = 0;
lid = (int) args;
while (1) {
st_id = get_rand_int(0, STORE_NUM - 1);
stf_num = get_rand_int(0, 512);
pthread_mutex_lock(&st_mtx[st_id]);
st_val[st_id] += stf_num;
printf("\\nLoader [id = %d]: store id = %d, stuff num = %d, balance = %d\\n\\n", lid, st_id, stf_num, st_val[st_id]);
pthread_mutex_unlock(&st_mtx[st_id]);
sleep(4);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
unsigned long head;
unsigned long tail;
} sem_fifo_t;
void wait(sem_fifo_t *queue)
{
unsigned long position;
pthread_mutex_lock(&queue->mutex);
position = queue->tail++;
while (position != queue->head) {
pthread_cond_wait(&queue->cond, &queue->mutex);
}
pthread_mutex_unlock(&queue->mutex);
}
void signal(sem_fifo_t *queue)
{
pthread_mutex_lock(&queue->mutex);
queue->head++;
pthread_cond_broadcast(&queue->cond);
pthread_mutex_unlock(&queue->mutex);
}
int main(void)
{
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
void sender() {
printf("Sender starts ...\\n");
sleep(1);
pthread_mutex_lock(&lock);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
}
void receiver() {
printf("Receiver starts ...\\n");
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond, &lock);
pthread_mutex_unlock(&lock);
printf("Signal received!\\n");
}
int main(int argc, char **argv) {
pthread_t tid1, tid2;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
pthread_create(&tid1, 0, (void *)sender, 0);
pthread_create(&tid2, 0, (void *)receiver, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long niter;
int nthread;
double pi;
int count;
void* MonteCarlo(void* arg){
int i,t=0;
double z;
t=niter/nthread;
count=0;
for ( i=0; i<t; i++) {
int random_state = rand();
double x = rand_r(&random_state) / ((double)32767 + 1);
double y = rand_r(&random_state) / ((double)32767 + 1);
z = x*x+y*y;
if (z<1) {
pthread_mutex_lock(&mutex);
count++;
pthread_mutex_unlock(&mutex);
}
}
}
main(int argc, const char* argv[])
{
niter=atol(argv[1]);
nthread=atoi(argv[2]);
pthread_t *thread = malloc(sizeof(pthread_t)*nthread);
pthread_attr_t attr;
pthread_attr_init(&attr);
int i;
for (i = 0; i < nthread; i++) {
pthread_create(&thread[i], 0, MonteCarlo, 0);
}
for (i = 0; i < nthread; i++) {
pthread_join(thread[i], 0);
}
free(thread);
pthread_mutex_destroy(&mutex);
pi=(double)count/niter*4;
printf(" estimate of pi is %g \\n",pi);
}
| 1
|
#include <pthread.h>
int *carpark;
int capacity;
int occupied;
int nextin;
int nextout;
int cars_in;
int cars_out;
pthread_mutex_t lock;
pthread_cond_t space;
pthread_cond_t car;
pthread_barrier_t bar;
} cp_t;
static void * car_in_handler(void *cp_in);
static void * car_out_handler(void *cp_in);
static void * monitor(void *cp_in);
static void initialise(cp_t *cp, int size);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s carparksize\\n", argv[0]);
exit(1);
}
cp_t ourpark;
initialise(&ourpark, atoi(argv[1]));
pthread_t car_in, car_out, m;
pthread_t car_in2, car_out2;
pthread_create(&car_in, 0, car_in_handler, (void *)&ourpark);
pthread_create(&car_out, 0, car_out_handler, (void *)&ourpark);
pthread_create(&car_in2, 0, car_in_handler, (void *)&ourpark);
pthread_create(&car_out2, 0, car_out_handler, (void *)&ourpark);
pthread_create(&m, 0, monitor, (void *)&ourpark);
pthread_join(car_in, 0);
pthread_join(car_out, 0);
pthread_join(car_in2, 0);
pthread_join(car_out2, 0);
pthread_join(m, 0);
exit(0);
}
static void initialise(cp_t *cp, int size) {
cp->occupied = cp->nextin = cp->nextout = cp->cars_in = cp->cars_out = 0;
cp->capacity = size;
cp->carpark = (int *)malloc(cp->capacity * sizeof(*cp->carpark));
pthread_barrier_init(&cp->bar, 0, 4);
if (cp->carpark == 0) {
perror("malloc()");
exit(1);
}
srand((unsigned int)getpid());
pthread_mutex_init(&cp->lock, 0);
pthread_cond_init(&cp->space, 0);
pthread_cond_init(&cp->car, 0);
}
static void* car_in_handler(void *carpark_in) {
cp_t *temp;
unsigned int seed;
temp = (cp_t *)carpark_in;
pthread_barrier_wait(&temp->bar);
while (1) {
usleep(rand_r(&seed) % 1000000);
pthread_mutex_lock(&temp->lock);
while (temp->occupied == temp->capacity)
pthread_cond_wait(&temp->space, &temp->lock);
temp->carpark[temp->nextin] = rand_r(&seed) % 10;
temp->occupied++;
temp->nextin++;
temp->nextin %= temp->capacity;
temp->cars_in++;
pthread_cond_signal(&temp->car);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
static void* car_out_handler(void *carpark_out) {
cp_t *temp;
unsigned int seed;
temp = (cp_t *)carpark_out;
pthread_barrier_wait(&temp->bar);
for (; ;) {
usleep(rand_r(&seed) % 1000000);
pthread_mutex_lock(&temp->lock);
while (temp->occupied == 0)
pthread_cond_wait(&temp->car, &temp->lock);
temp->occupied--;
temp->nextout++;
temp->nextout %= temp->capacity;
temp->cars_out++;
pthread_cond_signal(&temp->space);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
static void *monitor(void *carpark_in) {
cp_t *temp;
temp = (cp_t *)carpark_in;
for (; ;) {
sleep(2);
pthread_mutex_lock(&temp->lock);
printf("Delta: %d\\n", temp->cars_in - temp->cars_out - temp->occupied);
printf("Number of cars in carpark: %d\\n", temp->occupied);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t queue, libraryAccess, readcountMutex;
int readersInLibrary = 0;
sem_t maxThreads;
int N, M, T;
int readersMaxWait = 0, writersMaxWait = 0;
void* writer()
{
sem_wait(&maxThreads);
struct timeval tv;
gettimeofday(&tv, 0);
int waitTime = tv.tv_usec;
pthread_mutex_lock(&queue);
pthread_mutex_lock(&libraryAccess);
gettimeofday(&tv, 0);
waitTime = tv.tv_usec - waitTime;
pthread_mutex_unlock(&queue);
long randTime = (rand() % (100 - 10 + 1) + 10) * 1000;
struct timespec tmspc;
tmspc.tv_sec = 0;
tmspc.tv_nsec = randTime;
nanosleep(&tmspc, 0);
pthread_mutex_unlock(&libraryAccess);
sem_post(&maxThreads);
int *retAddr = (int*) calloc(1, sizeof(int));
*retAddr = waitTime;
return retAddr;
}
void* reader()
{
sem_wait(&maxThreads);
struct timeval tv;
gettimeofday(&tv, 0);
int waitTime = tv.tv_usec;
pthread_mutex_lock(&queue);
pthread_mutex_lock(&readcountMutex);
if(readersInLibrary == 0)
pthread_mutex_lock(&libraryAccess);
gettimeofday(&tv, 0);
waitTime = tv.tv_usec - waitTime;
readersInLibrary++;
pthread_mutex_unlock(&queue);
pthread_mutex_unlock(&readcountMutex);
long randTime = (rand() % (100 - 10 + 1) + 10) * 1000;
struct timespec tmspc;
tmspc.tv_sec = 0;
tmspc.tv_nsec = randTime;
nanosleep(&tmspc, 0);
pthread_mutex_lock(&readcountMutex);
readersInLibrary--;
if(readersInLibrary == 0)
pthread_mutex_unlock(&libraryAccess);
pthread_mutex_unlock(&readcountMutex);
sem_post(&maxThreads);
int *retAddr = (int*) calloc(1, sizeof(int));
*retAddr = waitTime;
return retAddr;
}
int main()
{
pthread_mutex_init(&queue, 0);
pthread_mutex_init(&libraryAccess, 0);
pthread_mutex_init(&readcountMutex, 0);
srand(time(0));
printf("Ile wątków ma być tworzone co jakiś czas?\\n");
scanf("%d",&N);
printf("Ile najwięcej wątków może działać jednocześnie?\\n");
scanf("%d",&M);
printf("Ile sumarycznie wątków stworzyć?\\n");
scanf("%d",&T);
pthread_t *threadInfo = calloc(T, sizeof(pthread_t));
int *threadType = calloc(T, sizeof(int));
sem_init(&maxThreads, 0, M);
long randTime;
struct timespec tmspc;
int threadId = 0;
while(threadId < T)
{
randTime = (rand() % (100 - 10 + 1) + 10) * 1000;
tmspc.tv_sec = 0;
tmspc.tv_nsec = randTime;
nanosleep(&tmspc, 0);
for(int i=0; i<N; i++)
{
threadType[threadId] = rand()%2;
if(threadType[threadId] == 0)
{
pthread_create(&threadInfo[threadId], 0, reader, 0);
}
else
{
pthread_create(&threadInfo[threadId], 0, writer, 0);
}
threadId++;
}
}
for(int i=0; i<T; i++)
{
int *retVal;
pthread_join(threadInfo[i], (void **) &retVal);
if(threadType[i] == 0)
{
if(readersMaxWait < *retVal)
readersMaxWait = *retVal;
}
else
{
if(writersMaxWait < *retVal)
writersMaxWait = *retVal;
}
free(retVal);
}
printf("Maksymalny czas oczekiwania czytelnika: %d\\nMaksymalny czas oczekiwania pisarza: %d\\n", readersMaxWait, writersMaxWait);
free(threadInfo);
free(threadType);
return 0;
}
| 1
|
#include <pthread.h>
int arr[10 * 5];
int aindex;
pthread_mutex_t mutex;
void *hello(void *thread_id)
{
int i;
int *id = (int *) thread_id;
for (i=1; i<=10 ; i++) {
pthread_mutex_lock(&mutex);
arr[aindex] = (*id)*100+ i;
sleep(1);
aindex = aindex + 1;
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main()
{
pthread_t tids[5];
int ids[5] = {1, 2, 3, 4, 5};
int ret;
long t;
int i;
pthread_mutex_init(&mutex, 0);
for (i=0 ; i<5; i++) {
ret = pthread_create(&tids[i], 0, hello, &ids[i]);
if (ret) {
printf("unable to create thread! \\n");
exit(-1);
}
}
for (i=0 ; i<5; i++) {
pthread_join(tids[i], 0);
}
printf("Final array : \\n");
for (i=0; i<50; i++)
printf("%d ", arr[i]);
printf("\\n\\n");
pthread_mutex_destroy(&mutex);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int apprS = 0;
int depS = 0;
int apprN = 0;
int depN = 0;
int waiting = NO_DIRECTION;
void stop_other_direction() {
if (waiting != NO_DIRECTION) {
if (waiting == NORTH) {
pthread_mutex_lock(&depN_lock);
while (depN > 0) {
pthread_cond_wait(&depN_cond, &depN_lock);
}
pthread_mutex_unlock(&depN_lock);
}
else {
pthread_mutex_lock(&depS_lock);
while (depS > 0) {
pthread_cond_wait(&depS_cond, &depS_lock);
}
pthread_mutex_unlock(&depS_lock);
}
waiting = (waiting + 1) % 2;
}
}
void Approach(int direction) {
direction = direction;
}
void Depart(int direction) {
direction = direction;
}
int go_this_way(int direction) {
if (direction == waiting) {
stop_other_direction();
}
return direction;
}
int main () {
return 0;
}
| 1
|
#include <pthread.h>
struct LeaderInfo * leader_genLeaderInfo(){
struct LeaderInfo * li = malloc(sizeof( struct LeaderInfo ));
int i;
for( i = 0; i < MAX_SERVERS; i++ ){
li->serverList[i].inUse = 0;
pthread_mutex_init( &(li->serverLocks[i]), 0 );
}
pthread_mutex_init( &(li->serverListLock), 0 );
li->nservers = 0;
return li;
}
int leader_addServer( struct LeaderInfo * li, char * hostname, int port ){
int i, serverId = -1;
if( li->nservers < MAX_SERVERS ){
pthread_mutex_lock( &(li->serverListLock) );
for( i = 0; (i < MAX_SERVERS) && (li->serverList[i].inUse); i++ );
strcpy( li->serverList[i].hostname, hostname );
li->serverList[i].port = port;
li->serverList[i].inUse = 1;
li->nservers++;
pthread_mutex_unlock( &(li->serverListLock) );
serverId = i;
}
return serverId;
}
int leader_removeServer( struct LeaderInfo * li, char * hostname, int port ){
int i, success = 0;
if( li->nservers > 0 ){
pthread_mutex_lock( &(li->serverListLock) );
for( i = 0; (i < MAX_SERVERS) && ((!li->serverList[i].inUse) || (strcmp(li->serverList[i].hostname, hostname)!=0) || (li->serverList[i].port != port)); i++ );
if( i < MAX_SERVERS ){
li->serverList[i].inUse = 0;
success = 1;
li->nservers--;
}
pthread_mutex_unlock( &(li->serverListLock) );
}
return success;
}
int leader_getServerList( struct LeaderInfo * li, char * buffer, int bufferSize ){
if(0)printf( "I'm getting the server list\\n" );
int i, nservers = 0;
buffer[0] = '\\0';
pthread_mutex_lock( &(li->serverListLock) );
for( i=0; i < MAX_SERVERS; i++ )
if( li->serverList[i].inUse ){
sprintf( buffer, "%s%s:%d\\n", buffer, li->serverList[i].hostname, li->serverList[i].port );
if(0)printf( "buffer = %s\\n", buffer );
nservers++;
}
pthread_mutex_unlock( &(li->serverListLock) );
return nservers;
}
int msg_handleUnknown( connfd ){
char response[BUFF_SIZE];
memset( response, '\\0', BUFF_SIZE );
strcpy( response, "LEADER UNKNOWN RESPONSE\\n");
write( connfd, response, strlen(response) );
return 1;
}
int msg_handleRmvServer( struct LeaderInfo * li, char * msg, int connfd ){
char * tok, hostname[NAME_SIZE], response[BUFF_SIZE];
memset( response, '\\0', BUFF_SIZE );
int port, ret;
tok = strtok( msg, "\\n\\r" );
strcpy( hostname, tok );
tok = strtok( 0, "\\n\\r" );
port = atoi(tok);
strcpy( response, "LEADER RMVSERVER RESPONSE\\n" );
if( (ret = leader_removeServer( li, hostname, port ) ) )
strcat( response, "SUCCESS\\n" );
else
strcat( response, "FAILURE: NO SUCH SERVER FOUND\\n" );
write( connfd, response, strlen(response ) );
return ret;
}
int msg_handleGetServers( struct LeaderInfo * li, int connfd ){
if(0)printf( "Got a server list request\\n" );
int writereturn;
int nservers = 0;
char response[BUFF_SIZE], serverList[BUFF_SIZE];
memset( response, '\\0', BUFF_SIZE );
strcpy( response, "LEADER GETSERVERS RESPONSE\\n" );
nservers = leader_getServerList( li, serverList, sizeof(serverList) );
if(0)printf( "got the serverlist\\n" );
sprintf( response, "%s%d\\n%s", response, nservers, serverList );
if(0)printf( "writing to socket: %d\\n" );
writereturn = write( connfd, response, strlen(response) );
if(0)printf( "wrote the serverlist: %d chars, and %d servers\\n", writereturn, nservers );
return nservers;
}
int msg_handleAddServer( struct LeaderInfo * li, char * msg, int connfd ){
char * tok, hostname[NAME_SIZE], response[BUFF_SIZE];
memset( response, '\\0', BUFF_SIZE );
int port, ret;
tok = strtok( msg, "\\n\\r" );
strcpy( hostname, tok );
tok = strtok( 0, "\\n\\r" );
port = atoi(tok);
strcpy( response, "LEADER ADDSERVER RESPONSE\\n" );
if( (ret = leader_addServer( li, hostname, port)) >= 0 )
strcat( response, "SUCCESS\\n" );
else
strcat( response, "FAILURE: NUM SERVERS MAXED\\n" );
write( connfd, response, strlen(response)+1 );
return ret;
}
int msg_stripHeader( char * msg, char **msgPtr ){
char * tok;
int msgType;
*msgPtr = strchr( msg, '\\n' ) + 1;
tok = strtok( msg, "\\n\\r" );
if( strcmp( tok, "ADDSERVER" ) == 0 )
msgType = MSG_ADDSERVER;
else if( strcmp( tok, "RMVSERVER" ) == 0 )
msgType = MSG_RMVSERVER;
else if( strcmp( tok, "GETSERVERS" ) == 0 )
msgType = MSG_GETSERVERS;
else
msgType = MSG_UNKNOWN;
return msgType;
}
int msg_handleMsg( struct LeaderInfo * li, char * msg, int msgType, int connfd ){
int ret_val = 0;
switch( msgType ){
case MSG_ADDSERVER:
ret_val = msg_handleAddServer( li, msg, connfd );
break;
case MSG_RMVSERVER:
ret_val = msg_handleRmvServer( li, msg, connfd );
break;
case MSG_GETSERVERS:
ret_val = msg_handleGetServers( li, connfd );
break;
case MSG_UNKNOWN:
ret_val = msg_handleUnknown( connfd );
break;
}
return ret_val;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
int banheiro_cheio = 0;
int mulher_no_banheiro = 0;
int homem_no_banheiro = 0;
int mulheres_na_fila = 0;
int contador = 0;
void homemQuerEntrar()
{
int aguenta = 0;
do{
pthread_mutex_lock(&mutex);
aguenta = banheiro_cheio || mulher_no_banheiro || (!homem_no_banheiro && mulher_na_fila != 0);
if(aguenta) {
pthread_mutex_unlock(&mutex);
}
} while(aguenta);
homem_no_banheiro = 1;
contador++;
if (contador == 3){
banheiro_cheio = 1;
}
printf("Nesse momento há %d homens no banheiro\\n", contador);
pthread_mutex_unlock(&mutex);
}
void homemSai()
{
pthread_mutex_lock(&mutex);
contador--;
if(contador == 2){
banheiro_cheio = 0;
}
if(contador == 0){
homem_no_banheiro = 0;
}
pthread_mutex_unlock(&mutex);
}
void mulherQuerEntrar()
{
mulheres_na_fila++;
int aguenta = 0;
do{
pthread_mutex_lock(&mutex);
aguenta = banheiro_cheio || homem_no_banheiro;
if(aguenta) {
pthread_mutex_unlock(&mutex);
}
} while(aguenta);
mulheres_na_fila--;
mulher_no_banheiro = 1;
contador++;
if (contador == 3){
banheiro_cheio = 1;
}
printf("Nesse momento há %d mulheres no banheiro\\n", contador);
pthread_mutex_unlock(&mutex);
}
void mulherSai()
{
thread_mutex_lock(&mutex);
contador--;
if(contador == 2){
banheiro_cheio = 0;
}
if(contador == 0){
mulher_no_banheiro = 0;
}
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
int Matrix_Size;
int procs;
const int MAX_THREADS = 100;
int NumThreads;
int min(int a, int b)
{
if (a < b)
return a;
else if ( a == b)
return -1;
else
return b;
}
float A[2000][2000];
float B[2000];
float X[2000];
pthread_t Threads[_POSIX_THREAD_THREADS_MAX];
pthread_mutex_t Mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t CountLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t NextIter = PTHREAD_COND_INITIALIZER;
int Norm, CurrentRow, Count;
void create_threads();
void* gaussPT(void*);
int find_next_row_chunk(int*, int);
void barrier(int*);
void wait_for_threads();
void initialise_inputs();
void print_inputs();
void print_X();
int main()
{
int row, col;
Matrix_Size = 144;
NumThreads = 8;
printf("Matrix dimension N = %d\\n", Matrix_Size);
printf("Number of threads = %d\\n", NumThreads);
initialise_inputs();
print_inputs();
CurrentRow = Norm + 1;
Count = NumThreads - 1;
clock_t start = clock();
create_threads();
wait_for_threads();
for (row = Matrix_Size - 1; row >= 0; row--)
{
X[row] = B[row];
for (col = Matrix_Size - 1; col > row; col--)
X[row] -= A[row][col] * X[col];
X[row] /= A[row][row];
}
clock_t end = clock();
print_X();
printf("Elapsed time: %f seconds\\n", (double) (end - start) / CLOCKS_PER_SEC);
return 0;
}
void initialise_inputs()
{
printf("\\nInitialising...\\n");
int col, row;
for (col = 0; col < Matrix_Size; col++)
{
for (row = 0; row < Matrix_Size; row++)
A[row][col] = (float)rand() / 32767 + 1;
B[col] = (float)rand() / 32767 + 1;
X[col] = 0.0;
}
}
void print_inputs()
{
int row, col;
if (Matrix_Size < 10)
{
printf("\\nA = \\n\\t");
for (row = 0; row < Matrix_Size; row++)
for (col = 0; col < Matrix_Size; col++)
printf("%f6.3 %s", A[row][col], col < (Matrix_Size - 1)?" ":"\\n\\t");
printf("\\nB = [ ");
for (col = 0; col < Matrix_Size; col++)
printf("%f6.3 %s", B[col], col < (Matrix_Size - 1) ? " " : "]\\n");
}
}
void print_X()
{
int row;
if (Matrix_Size < 10)
{
printf("\\nX = [");
for (row = 0; row < Matrix_Size; row++)
printf("%f6.3 %s", X[row], row < (Matrix_Size - 1) ? " " : "]\\n");
}
}
void* gaussPT(void* dummy)
{
int myRow = 0,
row, col;
int myNorm = 0;
float multiplier;
int chunkSize;
while (myNorm < Matrix_Size - 1)
{
while (chunkSize = find_next_row_chunk(&myRow, myNorm))
{
for (row = myRow; row < (min(Matrix_Size, myRow + chunkSize)); row++)
{
multiplier = A[row][myNorm] / A[myNorm][myNorm];
for (col = myNorm; col < Matrix_Size; col++)
A[row][col] -= A[myNorm][col] * multiplier;
B[row] -= B[myNorm] * multiplier;
}
}
barrier(&myNorm);
}
return 0;
}
void barrier(int* myNorm)
{
pthread_mutex_lock(&CountLock);
if (Count == 0)
{
Norm++;
Count = NumThreads - 1;
CurrentRow = Norm + 1;
pthread_cond_broadcast(&NextIter);
}
else
{
Count--;
pthread_cond_wait(&NextIter, &CountLock);
}
*myNorm = Norm;
pthread_mutex_unlock(&CountLock);
}
int find_next_row_chunk(int* myRow, int myNorm)
{
int chunkSize;
pthread_mutex_lock(&Mutex);
*myRow = CurrentRow;
chunkSize = (*myRow < Matrix_Size) ? (Matrix_Size - myNorm - 1) / (2 * NumThreads) + 1 : 0;
CurrentRow += chunkSize;
pthread_mutex_unlock(&Mutex);
return chunkSize;
}
void create_threads()
{
int i;
for (i = 0; i < NumThreads; i++)
pthread_create(&Threads[i], 0, gaussPT, 0);
}
void wait_for_threads()
{
int i;
for (i = 0; i < NumThreads; i++)
pthread_join(Threads[i], 0);
}
| 0
|
#include <pthread.h>
int buffer[10];
int first = 0;
int num = 0;
pthread_mutex_t mon = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t itemCond = PTHREAD_COND_INITIALIZER;
pthread_cond_t slotCond = PTHREAD_COND_INITIALIZER;
static void fail( char const *msg );
void *producer(void *param) {
for ( int i=0; i < 1000; i++ ) {
int item = i;
printf ( "Produced item %d\\n", item ); fflush( stdout );
pthread_mutex_lock( &mon );
while ( num == 10 )
pthread_cond_wait( &slotCond, &mon );
buffer[ ( first + num ) % 10 ] = item;
num++;
pthread_cond_signal( &itemCond );
pthread_mutex_unlock( &mon );
}
return 0;
}
void *consumer(void *param) {
for ( int i = 0; i < 1000; i++ ) {
pthread_mutex_lock( &mon );
while ( num == 0 )
pthread_cond_wait( &itemCond, &mon );
int item = buffer[ first ];
first = ( first + 1 ) % 10;
num--;
pthread_cond_signal( &slotCond );
pthread_mutex_unlock( &mon );
printf ( "Consuming item %d\\n", item ); fflush( stdout );
}
return 0;
}
int main() {
pthread_t tid1, tid2;
if ( pthread_create(&tid1,0,producer,0) != 0 ||
pthread_create(&tid2,0,consumer,0) != 0 )
fail( "Unable to create consumer thread" );
pthread_join( tid1, 0 );
pthread_join( tid2, 0 );
return 0;
}
static void fail( char const *msg ) {
fprintf( stderr, "%s\\n", msg );
exit( -1 );
}
| 1
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
pthread_mutex_lock(&m_trace);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
int main(int argc, char * argv[])
{
int ret;
pthread_mutexattr_t ma;
pthread_mutex_t m;
output_init();
ret = pthread_mutexattr_init(&ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex attribute init failed"); }
ret = pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
if (ret != 0)
{ UNRESOLVED(ret, "Set type recursive failed"); }
ret = pthread_mutex_init(&m, &ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex init failed"); }
ret = pthread_mutex_unlock(&m);
if (ret == 0)
{ FAILED("Unlocking an unlocked recursive mutex succeeded"); }
ret = pthread_mutex_lock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex lock failed"); }
ret = pthread_mutex_lock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex recursive lock failed"); }
ret = pthread_mutex_unlock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex unlock failed"); }
ret = pthread_mutex_unlock(&m);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex recursive unlock failed"); }
ret = pthread_mutexattr_destroy(&ma);
if (ret != 0)
{ UNRESOLVED(ret, "Mutex attribute destroy failed"); }
ret = pthread_mutex_unlock(&m);
if (ret == 0)
{ FAILED("Unlocking an unlocked recursive mutex succeeded"); }
PASSED;
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer=0;
void *producer(void *ptr) {
int i;
for(i=1;i<=100;i++) {
pthread_mutex_lock(&the_mutex);
while (buffer!=0) pthread_cond_wait(&condp, &the_mutex);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer(void *ptr) {
int i;
for(i=1;i<=100;i++) {
pthread_mutex_lock(&the_mutex);
while (buffer==0) pthread_cond_wait(&condc, &the_mutex);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int numThreads = 1;
int available_resources = 100;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t resc_thresh;
void waitForResources(int resc){
while(resc > available_resources){
sleep(.5);
}
}
int decrease_count(int count,long t){
if(available_resources < count){
printf("XXXXXXX Insufficient Resources for thread %lu\\n",t);
printf("XXXXXXX Tried to claim %d resources\\n", count);
printf("XXXXXXX Available: %d\\n\\n", available_resources);
return -1;
}
else{
available_resources -= count;
printf("Thread %lu claimed %d resources\\n",t,count);
printf("Claimed: %d resources\\n", count);
printf("Available: %d\\n", available_resources);
return 0;
}
}
int increase_count(int count,long t){
available_resources += count;
printf("Thread %lu added %d resources\\n",t,count);
printf("There are now %d resources available\\n\\n\\n",available_resources);
return 0;
}
void *getResources(void *t){
long threadID = (long)t;
int resc = rand()%100;
if(resc > 100){
printf("Thread %lu attempted to claim more than max resources.\\n",threadID);
}
else{
int success = decrease_count(resc,threadID);
if(success == 0){increase_count(resc,threadID);}
}
pthread_exit(0);
}
void decrease_countMonitor(int resc,long t){
pthread_mutex_lock(&mutex);
if(available_resources < resc){
printf("Thread %lu WAITING to claim %d resources\\n\\n",t, resc);
pthread_cond_wait(&resc_thresh, &mutex);
}
available_resources -= resc;
printf("Thread %lu\\n",t);
printf("Claimed: %d resources\\n", resc);
printf("Available: %d\\n\\n\\n", available_resources);
pthread_mutex_unlock(&mutex);
}
void increase_countMonitor(int resc, long t){
pthread_mutex_lock(&mutex);
available_resources += resc;
printf("Thread %lu added %d resources\\n",t,resc);
printf("There are now %d resources available\\n\\n\\n",available_resources);
pthread_cond_signal(&resc_thresh);
pthread_mutex_unlock(&mutex);
}
void *getResourcesMonitor(void *t){
long threadID = (long)t;
int resc = rand()%10+90;
if(resc > 100){
printf("Thread %lu attempted to claim more than max resources.\\n",threadID);
}
else{
decrease_countMonitor(resc,threadID);
increase_countMonitor(resc,threadID);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
numThreads = atoi(argv[1]);
printf("Enter A to see race condition or M to see the Monitor: ");
char condition[80];
fgets(condition,80,stdin);
printf("%s",condition);
pthread_cond_init(&resc_thresh,0);
pthread_t threads[numThreads];
int ret;
long t;
if(strcmp(condition,"A\\n") == 0 || strcmp(condition,"a\\n") == 0){
printf("RACE CONDITION:\\n");
for(t = 0; t<numThreads;t++){
ret = pthread_create(&threads[t],0,getResources,(void *)t);
}
for(t = 0; t<numThreads;t++){
pthread_join(threads[t],0);
}
}
else{
if(strcmp(condition,"M\\n") == 0 || strcmp(condition,"m\\n") == 0){
printf("Monitor\\n");
for(t = 0; t<numThreads;t++){
ret = pthread_create(&threads[t],0,getResourcesMonitor,(void *)t);
}
for(t = 0; t<numThreads;t++){
pthread_join(threads[t],0);
}
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
extern char myIP[16];
struct FileNameMap *map = 0;
pthread_mutex_t file_map_lock = PTHREAD_MUTEX_INITIALIZER;
struct FileNameMap* add_entry(char fileName[FILE_PATH_LENGTH]) {
struct FileNameMap* newEntry;
LOG(DEBUG, "Adding entry for %s, %0x", newEntry->fileName, newEntry);
newEntry = (struct FileNameMap*)malloc(sizeof(struct FileNameMap));
strcpy(newEntry->fileName, fileName);
DEBUG(("\\nIn add_entry. Filename = %s\\n",newEntry->fileName));
newEntry->fd = open(fileName, O_CREAT | O_RDWR);
DEBUG(("\\nadd_entry. FD = %d\\n", newEntry->fd));
newEntry->state = OPEN;
newEntry->next = 0;
pthread_mutex_lock(&file_map_lock);
if (map == 0)
map = newEntry;
else {
newEntry->next = map;
map = newEntry;
}
pthread_mutex_unlock(&file_map_lock);
return newEntry;
}
struct FileNameMap* get_entry(char fileName[FILE_PATH_LENGTH]) {
struct FileNameMap * ptr;
pthread_mutex_lock(&file_map_lock);
ptr = map;
while(ptr != 0) {
if(strcmp(ptr->fileName, fileName))
ptr = ptr->next;
else
break;
}
pthread_mutex_unlock(&file_map_lock);
return ptr;
}
int delete_entry(int fd) {
struct FileNameMap *ptr, *prev;
prev = 0;
pthread_mutex_lock(&file_map_lock);
ptr = map;
while((ptr!= 0 ) && (ptr->fd != fd)) {
prev = ptr;
ptr = ptr->next;
}
if(ptr == 0) {
pthread_mutex_unlock(&file_map_lock);
return -1;
}
else {
DEBUG(("\\nEntry found!!\\n"));
LOG(DEBUG, "Deleting entry for %s %0x", ptr->fileName, ptr);
if(ptr == map) {
map = map->next;
free(ptr);
} else {
prev->next = ptr->next;
free(ptr);
}
pthread_mutex_unlock(&file_map_lock);
return 0;
}
}
| 1
|
#include <pthread.h>
unsigned char r,g,b;
} pixel;
int start_idx;
int count;
int colmax;
int image_size;
unsigned tot_threads;
pixel *image;
} th_data;
pthread_mutex_t avg_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t barr;
unsigned avg = 0;
unsigned avg_threads_done = 0;
pixel *allocate_image(int size)
{
pixel *image;
image = (pixel *)malloc(sizeof(pixel)*size);
if (!image) {
fprintf(stderr, "malloc failed");
exit(1);
}
return image;
}
void *filter(void *arg) {
unsigned pval, psum = 0, sum = 0;
th_data *data = (th_data *)arg;
pixel *image = data->image;
int start_idx = data->start_idx;
int count = data->count;
int colmax = data->colmax;
int image_size = data->image_size;
unsigned tot_threads = data->tot_threads;
for (int i = start_idx; i < start_idx + count; i++) {
sum += image[i].r;
sum += image[i].g;
sum += image[i].b;
}
pthread_mutex_lock( &avg_mutex );
avg += sum;
avg_threads_done++;
if(avg_threads_done >= tot_threads){
avg = avg/image_size;
}
pthread_mutex_unlock( &avg_mutex );
int rc = pthread_barrier_wait(&barr);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD)
{
printf("Could not wait on barrier\\n");
exit(-1);
}
for (int i = start_idx; i < start_idx + count; i++) {
psum = image[i].r;
psum += image[i].g;
psum += image[i].b;
if (psum > avg)
pval = colmax;
else
pval = 0;
image[i].r = pval;
image[i].g = pval;
image[i].b = pval;
}
}
int main(int argc, char **argv)
{
FILE *infile, *outfile;
int magic, ok;
int radius;
int xsize, ysize, colmax;
pixel *image;
int threads = 1;
if (argc < 3) {
fprintf(stderr, "Usage: %s infile outfile\\n", argv[0]);
exit(2);
}
if (!(infile = fopen(argv[1], "r"))) {
fprintf(stderr, "Error when opening %s\\n", argv[1]);
exit(1);
}
if (!(outfile = fopen(argv[2], "w"))) {
fprintf(stderr, "Error when opening %s\\n", argv[2]);
exit(1);
}
if (argc == 4) {
threads = atoi(argv[3]);
if(threads == 0){
fprintf(stderr, "Not a valid number of threads\\n");
exit(1);
}
}
magic = ppm_readmagicnumber(infile);
if (magic != 'P'*256+'6') {
fprintf(stderr, "Wrong magic number\\n");
exit(1);
}
xsize = ppm_readint(infile);
ysize = ppm_readint(infile);
colmax = ppm_readint(infile);
if (colmax > 255) {
fprintf(stderr, "Too large maximum color-component value\\n");
exit(1);
}
image = allocate_image(xsize*ysize);
if (!fread(image, sizeof(pixel), xsize*ysize, infile)) {
fprintf(stderr, "error in fread\\n");
exit(1);
}
struct timespec stime, etime;
clock_gettime(CLOCK_REALTIME, &stime);
pthread_t thread_pool[threads];
int rc;
int size = xsize * ysize;
int chunk_size = size / threads;
int last_chunk_pad = size - chunk_size * threads;
int displs[threads];
int scounts[threads];
for( int i = 0; i < threads; i++){
displs[i] = i*chunk_size;
scounts[i] = chunk_size;
}
scounts[threads-1] = (chunk_size + last_chunk_pad);
if(pthread_barrier_init(&barr, 0, threads))
{
printf("Could not create a barrier\\n");
exit(-1);
}
th_data data[threads];
for(int t = 0; t < threads; t++) {
data[t].start_idx = displs[t];
data[t].count = scounts[t];
data[t].colmax = colmax;
data[t].image_size = size;
data[t].tot_threads = threads;
data[t].image = image;
rc = pthread_create(&thread_pool[t], 0, filter, (void *)&data[t]);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for(int t = 0; t < threads; t++) {
pthread_join(thread_pool[t], 0);
}
clock_gettime(CLOCK_REALTIME, &etime);
printf("Filtering took: %g secs\\n", (etime.tv_sec - stime.tv_sec) +
1e-9*(etime.tv_nsec - stime.tv_nsec)) ;
fprintf(outfile, "P6 %d %d %d\\n", xsize, ysize, colmax);
if (!fwrite(image, sizeof(pixel), xsize*ysize, outfile)) {
fprintf(stderr, "error in fwrite");
exit(1);
}
exit(0);
}
| 0
|
#include <pthread.h>
float f(float x)
{
return x;
}
pthread_mutex_t mutex;
long int num_threads;
float a, b, I, h;
long long int n;
void *trapezoidal(void *param){
long int id = (long int) param;
long long int i, chunk = (n - 2) / (long long int) num_threads;
float I_local = 0.0;
for (i = (long long int) id * chunk; i < (long long int) (id + 1) * chunk; i++) {
I_local += f(a + (float)i * h);
}
pthread_mutex_lock(&mutex);
I += I_local;
pthread_mutex_unlock(&mutex);
pthread_exit((void *) 0);
}
int main(int argc, char **argv){
if(flagValueInt(argv, argc, "threads") > 0){
num_threads = flagValueInt(argv, argc, "threads");
}
else{
num_threads = 2;
}
if(checkFlag(argv, argc, "debug")){
printf("Trapezoidal Rule - Pthreads - Threads: %ld - Single Precision\\n", num_threads);
printf("Serpa and Schepke 2015\\n");
printf("Laboratório de Estudos Avançados - UNIPAMPA\\n\\n");
}
if(flagValueLong(argv, argc, "n") > 0)
n = flagValueLong(argv, argc, "n");
else
n = 10;
if(flagValueReal(argv, argc, "a") > 0){
a = flagValueReal(argv, argc, "a");
}
else
a = 1;
if(flagValueReal(argv, argc, "b") > 0)
b = flagValueReal(argv, argc, "b");
else
b = 2;
h = (b - a) / n;
if(checkFlag(argv, argc, "debug")){
printf("[%.2f %.2f] ---- n = %lld --- h = %.10f\\n", a, b, n, h);
}
double timer = 0.0;
long int i;
pthread_t *thread;
pthread_attr_t attr;
int error;
void *status;
if(checkFlag(argv, argc, "debug")){
printf("Begin main loop\\n");
}
thread = (pthread_t *) malloc(num_threads * sizeof(pthread_t));
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&mutex, 0);
I = 0;
timer = crono();
for(i = 0; i < num_threads; ++i){
if(checkFlag(argv, argc, "debug"))
printf("\\tCreating thread %ld\\n", i);
error = pthread_create(&thread[i], &attr, trapezoidal, (void *)i);
if(error)
HANDLE_ERROR();
}
if(checkFlag(argv, argc, "debug"))
printf("\\n");
pthread_attr_destroy(&attr);
for(i = 0; i < num_threads; ++i){
error = pthread_join(thread[i], &status);
if(error)
HANDLE_ERROR();
if(checkFlag(argv, argc, "debug"))
printf("\\tCompleted join with thread %ld having a status of %ld\\n", i, (long int) status);
}
timer = crono() - timer;
I = (h / 2) * (f(a) + 2 * I + f(b));
pthread_mutex_destroy(&mutex);
if(checkFlag(argv, argc, "debug")){
printf("Finish main loop\\n");
printf("\\nTrapezoidal = %.10f\\n", I);
printf("Time\\n");
printf("\\texecution time: %.10lf segs.\\n", timer);
printf("End of the execution\\n\\n");
}
if(checkFlag(argv, argc, "check") && a == 1 && b == 2){
printf("%.10f\\n", I);
printf("OK\\n1.5\\n\\n");
}
fprintf(stderr, "%.10lf\\n", timer);
pthread_exit((void *) 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t theMutex;
pthread_cond_t condc, condp;
int buffer=0;
void* producer(void* ptr)
{
int x;
for(x=0; x<=4; x++)
{
pthread_mutex_lock(&theMutex);
printf("Producer Locked\\n");
while(buffer!=0)
{
printf("Producer waiting\\n");
pthread_cond_wait(&condp, &theMutex);
}
printf("Producer creating widget %d\\n", x);
buffer=x;
printf("Signaling Consumer\\n");
pthread_cond_signal(&condc);
pthread_mutex_unlock(&theMutex);
printf("Producer unlocked\\n");
}
pthread_exit(0);
}
void* consumer(void* ptr)
{
int x;
for(x=1; x<=4; x++)
{
pthread_mutex_lock(&theMutex);
printf("Consumer locked\\n");
while(buffer==0)
{
printf("Consumer waiting\\n");
pthread_cond_wait(&condc, &theMutex);
}
printf("Consumer consuming widget %d\\n", x);
buffer=0;
printf("Signaling Producer\\n");
pthread_cond_signal(&condp);
pthread_mutex_unlock(&theMutex);
printf("Consumer unlocked\\n");
}
pthread_exit(0);
}
int main()
{
pthread_t pro, con;
pthread_mutex_init(&theMutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
printf("Creating Consumer\\n");
pthread_create(&con, 0, consumer, 0);
printf("Creating Producer\\n");
pthread_create(&pro, 0, producer, 0);
printf("Executing Consumer\\n");
pthread_join(con, 0);
printf("Executing Producer\\n");
pthread_join(pro, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&theMutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int nr_pare, nr_impare;
void* f(){
int r;
while(1){
pthread_mutex_lock(&m);
if( (nr_pare * nr_impare)%3 == 0 && nr_pare*nr_impare > 50)
break;
pthread_mutex_unlock(&m);
r=rand()%40+10;
if(r%2 == 0){
pthread_mutex_lock(&m);
nr_pare++;
pthread_mutex_unlock(&m);
}
else{
pthread_mutex_lock(&m);
nr_impare++;
pthread_mutex_unlock(&m);
}
}
pthread_mutex_unlock(&m);
return 0;
}
int main(){
pthread_t t1, t2;
pthread_create(&t1, 0, f, 0);
pthread_create(&t2, 0, f, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("%d, %d", nr_pare, nr_impare);
return 0;
}
| 1
|
#include <pthread.h>
int source[15];
int minBound[4];
int maxBound[4];
int channel[4];
int th_id = 0;
pthread_mutex_t mid;
pthread_mutex_t ms[4];
void sort (int x, int y)
{
int aux = 0;
for (int i = x; i < y; i++)
{
for (int j = i; j < y; j++)
{
if (source[i] > source[j])
{
aux = source[i];
source[i] = source[j];
source[j] = aux;
}
}
}
}
void *sort_thread (void * arg)
{
int id = -1;
int x, y;
pthread_mutex_lock (&mid);
id = th_id;
th_id++;
pthread_mutex_unlock (&mid);
x = minBound[id];
y = maxBound[id];
__VERIFIER_assert (x >= 0);
__VERIFIER_assert (x < 15);
__VERIFIER_assert (y >= 0);
__VERIFIER_assert (y < 15);
printf ("t%d: min %d max %d\\n", id, x, y);
sort (x, y);
pthread_mutex_lock (&ms[id]);
channel[id] = 1;
pthread_mutex_unlock (&ms[id]);
return 0;
}
int main ()
{
pthread_t t[4];
int i;
__libc_init_poet ();
i = __VERIFIER_nondet_int (0, 15 - 1);
source[i] = __VERIFIER_nondet_int (0, 20);
__VERIFIER_assert (source[i] >= 0);
pthread_mutex_init (&mid, 0);
int j = 0;
int delta = 15/4;
__VERIFIER_assert (delta >= 1);
i = 0;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
channel[i] = 0; minBound[i] = j; maxBound[i] = j + delta -1; j += delta; pthread_mutex_init (&ms[i], 0); pthread_create (&t[i], 0, sort_thread, 0); i++;
__VERIFIER_assert (i == 4);
int k = 0;
while (k < 4)
{
i = 0;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
pthread_mutex_lock (&ms[i]); if (channel[i] == 1) { k++; } pthread_mutex_unlock (&ms[i]); i++;
__VERIFIER_assert (i == 4);
}
__VERIFIER_assert (th_id == 4);
__VERIFIER_assert (k == 4);
sort (0, 15);
printf ("==============\\n");
for (i = 0; i < 15; i++)
printf ("m: sorted[%d] = %d\\n", i, source[i]);
i = 0;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
pthread_join (t[i], 0); i++;
__VERIFIER_assert (i == 4);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t g_lock_tnum = PTHREAD_MUTEX_INITIALIZER;
int g_tnum;
struct thread_info {
pthread_t tid;
int tnum;
char *cmd;
uint32_t timeout;
FILE *fp;
char *out;
pthread_mutex_t out_lock;
};
static void * thread_start(void *arg) {
struct thread_info *tinfo = arg;
char *cmd;
char *outp;
char *end;
char line[256];
int s;
cmd = strdup(tinfo->cmd);
assert(cmd);
printf("tnum=%d,cmd=%s\\n", tinfo->tnum, tinfo->cmd);
tinfo->fp = popen(cmd, "r");
assert(tinfo->fp);
outp = tinfo->out;
end = outp + 1024;
while (fgets(line , 256, tinfo->fp) != 0) {
pthread_mutex_lock(&tinfo->out_lock);
outp += snprintf(outp, end - outp, "%s", line);
pthread_mutex_unlock(&tinfo->out_lock);
}
s = pclose(tinfo->fp);
if (s != 0)
do { errno = s; perror("pclose"); exit(1); } while (0);
return;
}
void spawn_thread(struct thread_info tinfo) {
int s;
pthread_attr_t attr;
s = pthread_attr_init(&attr);
if (s != 0)
do { errno = s; perror("pthread_attr_init"); exit(1); } while (0);
s = pthread_create(&tinfo.tid, &attr, &thread_start, &tinfo);
if (s != 0)
do { errno = s; perror("pthread_create"); exit(1); } while (0);
}
void check_thread(struct thread_info tinfo) {
pthread_mutex_lock(&tinfo.out_lock);
printf("%s: %s\\n", __FUNCTION__, tinfo.out);
pthread_mutex_unlock(&tinfo.out_lock);
}
int main() {
char *cmd = calloc(256,sizeof(char));
assert(cmd);
cmd = strncpy(cmd, "ls -1", 256);
int tnum;
int num_threads;
struct thread_info *tinfo;
num_threads = 3;
tinfo = calloc(num_threads, sizeof(struct thread_info));
assert(tinfo);
pthread_mutex_lock(&g_lock_tnum);
tinfo[g_tnum].tnum = g_tnum++;
tnum = g_tnum;
pthread_mutex_unlock(&g_lock_tnum);
tinfo[tnum].cmd = strdup(cmd);
assert(tinfo[tnum].cmd);
tinfo[tnum].timeout = (30*1000);
pthread_mutex_init(&tinfo[tnum].out_lock, 0);
pthread_mutex_lock(&tinfo[tnum].out_lock);
tinfo[tnum].out = calloc(1024,sizeof(char));
pthread_mutex_unlock(&tinfo[tnum].out_lock);
spawn_thread(tinfo[tnum]);
sleep(3);
check_thread(tinfo[tnum]);
}
| 1
|
#include <pthread.h>
int max;
int balance = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void * mythread(void *arg) {
char *letter = arg;
int i;
printf("%s: begin [addr of i: %p]\\n", letter, &i);
for (i = 0; i < max; i++) {
pthread_mutex_lock(&lock);
balance = balance + 1;
pthread_mutex_unlock(&lock);
}
printf("%s: done\\n", letter);
return 0;
}
void * mythreadDecrease(void *arg) {
char *letter = arg;
int i;
printf("%s: begin [addr of i: %p]\\n", letter, &i);
for (i = 0; i < max; i++) {
pthread_mutex_lock(&lock);
balance = balance - 1;
pthread_mutex_unlock(&lock);
}
printf("%s: done\\n", letter);
return 0;
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "usage: main-first <loopcount>\\n");
exit(1);
}
max = atoi(argv[1]);
printf("main: begin [balance = %d] [%p]\\n", balance, &balance);
pthread_t p1, p2;
pthread_t p3, p4;
pthread_create(&p1, 0, mythread, "A");
pthread_create(&p2, 0, mythread, "B");
pthread_create(&p3, 0, mythreadDecrease, "C");
pthread_create(&p4, 0, mythreadDecrease, "D");
pthread_join(p1, 0);
pthread_join(p2, 0);
pthread_join(p3, 0);
pthread_join(p4, 0);
printf("main: done\\n [balance: %d]\\n [should: %d]\\n",
balance, max*2);
return 0;
}
| 0
|
#include <pthread.h>
{
int n;
double sum;
} SQRTSUM;
SQRTSUM sqrtsum;
pthread_mutex_t mutex_sqrtsum;
struct timeval tp1, tp2;
struct timezone tpz1, tpz2;
void *runner(void *param);
int main(int argc, char *argv[])
{
gettimeofday(&tp1, &tpz1);
if (atoi(argv[1]) < 0)
{
fprintf(stderr, "%d must be over >= 0\\n", atoi(argv[1]));
return -1;
}
int i, NUM_THREADS = atoi(argv[2]);
pthread_t tid[NUM_THREADS];
pthread_attr_t attr;
int n = atoi(argv[1])/NUM_THREADS;
sqrtsum.n = n;
pthread_mutex_init(&mutex_sqrtsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i = 0; i < NUM_THREADS; i++)
{
pthread_create(&tid[i], &attr, runner, (void *) (long) i);
}
pthread_attr_destroy(&attr);
for (i=0; i < NUM_THREADS; i++)
{
pthread_join(tid[i],0);
}
printf("sqrtsum = %f\\n", sqrtsum.sum);
pthread_mutex_destroy(&mutex_sqrtsum);
gettimeofday(&tp2, &tpz2);
int time = (tp2.tv_sec - tp1.tv_sec) * 1000 + (tp2.tv_usec - tp1.tv_usec) / 1000;
printf("Total time(ms): %d\\n", time);
time;
return 0;
}
void *runner(void *param)
{
int i, n, start, tid, upper;
double lsqrtsum = 0.0;
n = sqrtsum.n;
tid = (int) (long) param;
start = n * tid + 1;
upper = start + n;
for (i = start; i < upper ; i++)
{
lsqrtsum += sqrt(i);
}
pthread_mutex_lock(&mutex_sqrtsum);
sqrtsum.sum += lsqrtsum;
pthread_mutex_unlock(&mutex_sqrtsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int vlogf(const char *fmt, va_list args);
void append_msg(const char *msg);
void print_info();
void trunc_info();
char *copy_info(char outbuff[], size_t n);
char *copy_info_trunc(char outbuff[], size_t n);
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static char msg_buff[4097];
static const char *msg_buff_end = msg_buff + sizeof(msg_buff);
static char *head = msg_buff, *tail = msg_buff;
static char *get_msg();
inline static void trunc_buff();
inline static int buff_not_empty();
void
print_info()
{
switch (get_log_type()) {
case LDAEMON:
break;
case LCONSOLE:
fflush(stdout);
break;
case LBUFF:
if (pthread_mutex_trylock(&mutex))
pthread_mutex_lock(&mutex);
if (buff_not_empty()) {
fprintf(stdout, get_msg());
trunc_buff();
fflush(stdout);
}
pthread_mutex_unlock(&mutex);
break;
default:
break;
}
}
char *
copy_info(char outbuff[], size_t n)
{
if (pthread_mutex_trylock(&mutex))
pthread_mutex_lock(&mutex);
my_strcpy(outbuff, get_msg(), n);
pthread_mutex_unlock(&mutex);
return outbuff;
}
char *
copy_info_trunc(char outbuff[], size_t n)
{
if (pthread_mutex_trylock(&mutex))
pthread_mutex_lock(&mutex);
my_strcpy(outbuff, get_msg(), n);
trunc_buff();
pthread_mutex_unlock(&mutex);
return outbuff;
}
void
trunc_info()
{
if (pthread_mutex_trylock(&mutex))
pthread_mutex_lock(&mutex);
trunc_buff();
pthread_mutex_unlock(&mutex);
}
void
free_print_info_locks()
{
pthread_mutex_destroy(&mutex);
}
void
append_msg(const char *msg)
{
if (strlen(msg) > sizeof(msg_buff) - 1)
msg += strlen(msg) - (sizeof(msg_buff) - 1);
if (pthread_mutex_trylock(&mutex))
pthread_mutex_lock(&mutex);
int cnt = my_strcpy(tail, msg, msg_buff_end - tail);
if (tail >= head) {
tail += cnt;
if (tail + 1 >= msg_buff_end) {
msg += cnt;
cnt = my_strcpy(msg_buff, msg, head - tail);
tail = msg_buff + cnt;
if (tail >= head)
head = tail + 1;
}
} else {
tail += cnt;
if (tail >= head) {
if (tail + 1 >= msg_buff_end) {
msg += cnt;
cnt = my_strcpy(msg_buff, msg, head - tail);
tail = msg_buff + cnt;
head = tail + 1;
} else {
head = tail + 1;
}
}
}
pthread_mutex_unlock(&mutex);
}
static char *
get_msg()
{
static char buff[4097];
if (tail >= head)
my_strcpy(buff, head, tail - head + 1);
else {
char *p = buff;
p += my_strcpy(p, head, msg_buff_end - head);
my_strcpy(p, msg_buff, tail - msg_buff + 1);
}
return buff;
}
inline static int
buff_not_empty()
{
return tail != head;
}
inline static void
trunc_buff()
{
tail = head;
*head = '\\0';
}
int
vlogf(const char *fmt, va_list args)
{
char buff[4097];
int cnt = vsnprintf(buff, sizeof(buff), fmt, args);
append_msg(buff);
return cnt;
}
| 0
|
#include <pthread.h>
void *thread_func(void *arg);
char buffer[1024];
pthread_mutex_t mutex;
int thread04_main(void)
{
int ret;
pthread_t thread_a;
void *thread_result;
if(0 != (ret = pthread_mutex_init(&mutex, 0))){
perror("mutex init failed");
exit(1);
}
if(0 != (ret = pthread_create(&thread_a, 0, thread_func, 0))){
perror("thread_a creation failed!");
exit(1);
}
printf("input some test . enter 'end' to finish\\n");
while(1){
pthread_mutex_lock(&mutex);
scanf("%s",buffer);
pthread_mutex_unlock(&mutex);
if(0 == strncmp("end", buffer, 3)) break;
usleep(100);
}
if(0 != (ret = pthread_join(thread_a, &thread_result))){
perror("thread_a join failed!");
exit(1);
}
printf("thread joined , it returned : %s\\n",(char *)thread_result);
pthread_mutex_destroy(&mutex);
return 0;
}
void *thread_func(void *arg)
{
printf("thread_fun running...\\n");
while(1){
pthread_mutex_lock(&mutex);
printf("You input %d characters\\n", (int)strlen(buffer));
pthread_mutex_unlock(&mutex);
if(0 == strncmp("end", buffer, 3)) break;
usleep(100);
}
pthread_exit("Thank you for your cpu time");
}
| 1
|
#include <pthread.h>
int nr = 0;
pthread_mutex_t mutex;
void* thread_func(void* arg) {
char* cuvant = (char*)malloc(40);
cuvant = (char*)arg;
int i;
for (i = 0; i < strlen(cuvant); i++) {
if (cuvant[i] == 'a' || cuvant[i] == 'e' || cuvant[i] == 'i' ||
cuvant[i] == 'o' || cuvant[i] == 'u') {
pthread_mutex_lock(&mutex);
nr++;
pthread_mutex_unlock(&mutex);
}
}
free(cuvant);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
printf("Trebuie sa dat parametrii \\n");
}
pthread_t threads[20];
pthread_mutex_init(&mutex,0);
int i;
for (i = 1; i < argc; i++) {
if (pthread_create(&threads[i],0,thread_func,argv[i]) < 0) {
printf("Eroare la thread \\n");
}
}
for (i = 1; i < argc;i++) {
pthread_join(threads[i],0);
}
printf("Au fost %d vocale in argumentele date \\n",nr);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
int socket_fd;
pthread_mutex_t socket_lock = PTHREAD_MUTEX_INITIALIZER;
int init(int portNum) {
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
int enable = 1;
setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable,
sizeof(int));
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htons(INADDR_ANY);
server.sin_port = htons(portNum);
if (bind(socket_fd, (struct sockaddr*) &server, sizeof(server)) < 0) {
perror("Error binding to socket: ");
exit(1);
}
if (listen(socket_fd, 5) < 0) {
perror("Error listening to connection: ");
exit(1);
}
return 0;
}
int accept_connection() {
struct sockaddr_in client_addr;
unsigned int size = sizeof(struct sockaddr);
pthread_mutex_lock(&socket_lock);
int new_socket = accept(socket_fd, (struct sockaddr*) &client_addr, &size);
pthread_mutex_unlock(&socket_lock);
return new_socket;
}
int get_request(int fd, char *filename) {
char buf[1024];
char ** request;
if (read(fd, buf, 1024) < 0) {
perror("Error: Something wrong with requrest from client: \\n");
return -1;
}
if (makeargv(buf, " ", &request) < 0) {
perror("Error: Something wrong parsing request: \\n");
return -1;
}
strncpy(filename, request[1], 1023);
freemakeargv(request);
return 0;
}
int return_error(int fd, char *buf) {
FILE *client = fdopen(fd, "w");
fprintf(client, "HTTP/1.1 404 Not Found\\n");
fprintf(client, "Content-Type: text/html\\n");
fprintf(client, "Content-Length: %d\\n", (int) strlen(buf));
fprintf(client, "Connection: Close\\n\\n");
fflush(client);
write(fd, buf, strlen(buf));
close(fd);
return 0;
}
int return_result(int fd, char *content_type, char *buf, int numbytes) {
FILE *client = fdopen(fd, "w");
if (client == 0) {
perror("Error: Something wrong opening client's FD");
return -1;
}
fprintf(client, "HTTP/1.1 200 OK\\n");
write(fd, "HTTP/1.1 200 OK", strlen("HTTP/1.1 200 OK"));
fprintf(client, "Content-Type: %s\\n", content_type);
fprintf(client, "Content-Length: %d\\n", numbytes);
fprintf(client, "Connection: Close\\n");
fprintf(client, "\\n");
fflush(client);
write(fd, buf, numbytes);
fclose(client);
printf("Wrote to fd %d", fd);
return 0;
}
int makeargv(const char *s, const char *delimiters, char ***argvp) {
int error;
int i;
int numtokens;
const char *snew;
char *savePtr1, *savePtr2;
char *t;
if ((s == 0) || (delimiters == 0) || (argvp == 0)) {
errno = EINVAL;
return -1;
}
*argvp = 0;
snew = s + strspn(s, delimiters);
if ((t = malloc(strlen(snew) + 1)) == 0)
return -1;
strcpy(t, snew);
numtokens = 0;
if (strtok_r(t, delimiters, &savePtr1) != 0)
for (numtokens = 1; strtok_r(0, delimiters, &savePtr1) != 0; numtokens++)
;
if ((*argvp = malloc((numtokens + 1) * sizeof(char *))) == 0) {
error = errno;
free(t);
errno = error;
return -1;
}
if (numtokens == 0)
free(t);
else {
strcpy(t, snew);
**argvp = strtok_r(t, delimiters, &savePtr2);
for (i = 1; i < numtokens; i++)
*((*argvp) + i) = strtok_r(0, delimiters, &savePtr2);
}
*((*argvp) + numtokens) = 0;
return numtokens;
}
void freemakeargv(char **argv) {
if (argv == 0)
return;
if (*argv != 0)
free(*argv);
free(argv);
}
| 1
|
#include <pthread.h>
int count=0;
int counter[8];
int *array;
pthread_mutex_t lock;
void * global_counter_scalar(void *thread_id){
int *int_pt=array+(*((int*)thread_id)*(800000000/8));
int i;
for (i=0;i<800000000/8;i++){
if(int_pt[i]==3){
pthread_mutex_lock(&lock);
count++;
pthread_mutex_unlock(&lock);
}
}
}
void * global_array_counter_scalar(void *thread_id){
int id=*(int*)thread_id;
int *int_pt=array+(id*(800000000/8));
int i;
for (i=0;i<800000000/8;i++){
if(int_pt[i]==3){
counter[id]++;
}
}
pthread_mutex_lock(&lock);
count+=counter[id];
pthread_mutex_unlock(&lock);
}
void * global_array_counter_array(void * thread_id){
int id=*(int*)thread_id;
int *int_pt=array+(id*(800000000/8));
int i;
for (i=0;i<800000000/8;i++){
if(int_pt[i]==3){
counter[id]++;
}
}
}
void * local_counter_global_scalar(void *thread_id){
int id=*(int*)thread_id;
int *int_pt=array+(id*(800000000/8));
int local_count=0;
int i;
for (i=0;i<800000000/8;i++){
if(int_pt[i]==3){
local_count++;
}
}
pthread_mutex_lock(&lock);
count+=local_count;
pthread_mutex_unlock(&lock);
}
void * local_counter_global_array(void * thread_id){
int id=*(int*)thread_id;
int *int_pt=array+(id*(800000000/8));
int i;
int local_count=0;
for (i=0;i<800000000/8;i++){
if(int_pt[i]==3){
local_count++;
}
}
counter[id]=local_count;
}
int main(){
array=create_random_int_array(800000000);
pthread_t threads[8];
int i;
int thread_num[8];
double time;
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
pthread_create(&threads[i],0,global_counter_scalar,(void*)&thread_num[i]);
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
printf("global counter-scalar done. count=%d, time=%f\\n",count,get_time_sec()-time);
count=0;
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
counter[i]=0;
pthread_create(&threads[i],0,global_array_counter_scalar,(void*)(&thread_num[i]));
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
printf("global array scalar done. count=%d, time=%f\\n",count,get_time_sec()-time);
count=0;
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
counter[i]=0;
pthread_create(&threads[i],0,global_array_counter_array,(void*)(&thread_num[i]));
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
for(i=0;i<8;i++)
count+=counter[i];
printf("global array array done. count=%d, time=%f\\n",count,get_time_sec()-time);
count=0;
bzero((void*)counter,(size_t)8);
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
pthread_create(&threads[i],0,local_counter_global_scalar,(void*)(&thread_num[i]));
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
printf("local counter global scalar done. count=%d, time=%f\\n",count,get_time_sec()-time);
count=0;
bzero((void*)counter,8);
time=get_time_sec();
for(i=0;i<8;i++){
thread_num[i]=i;
pthread_create(&threads[i],0,local_counter_global_array,(void*)(&thread_num[i]));
}
for(i=0;i<8;i++){
pthread_join(threads[i],0);
}
for(i=0;i<8;i++)
count+=counter[i];
printf("local counter global array done. count=%d, time=%f\\n",count,get_time_sec()-time);
time=get_time_sec();
count=numOfThree(array,800000000);
printf("sequential done. count=%d, time=%f\\n",count,get_time_sec()-time);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 1
|
#include <pthread.h>
long int cislo, je_nove_cislo=0, precitalo=0;
pthread_mutex_t MUTEX;
pthread_cond_t nove_cislo, vsetci_precitali;
void * generuj(void * param) {
int i;
for(i=0; i < 20; i++) {
pthread_mutex_lock(&MUTEX);
cislo = random() % 100;
printf("Server vygeneroval nove cislo %d\\n", cislo);
je_nove_cislo = 1;
pthread_cond_broadcast(&nove_cislo);
while(precitalo < 5) {
pthread_cond_wait(&vsetci_precitali, &MUTEX);
}
precitalo = 0;
pthread_mutex_unlock(&MUTEX);
printf("vsetci klienti precitali cislo, kolo %d sa skoncilo\\n", i);
sleep(random() % 3);
}
}
void * klient(void * param) {
int i, id;
id = *(int *)param;
for(i = 0; i < 20; i++) {
pthread_mutex_lock(&MUTEX);
while(je_nove_cislo != 1) {
pthread_cond_wait(&nove_cislo, &MUTEX);
}
printf("klient c. %d prevzal cislo %d\\n", id, cislo);
if (++precitalo >= 5) {
je_nove_cislo = 0;
pthread_cond_broadcast(&vsetci_precitali);
}
else {
pthread_cond_wait(&vsetci_precitali, &MUTEX);
}
pthread_mutex_unlock(&MUTEX);
sleep(random() % 3);
}
}
int main(int argc, char * argv[]) {
int poradie[5], i;
pthread_t klienti[5];
pthread_t generator;
precitalo = 0;
if (pthread_mutex_init(&MUTEX, 0) != 0 ) {
perror("chyba pri vytvarani mutexu");
exit(1);
}
pthread_cond_init(&nove_cislo, 0);
pthread_cond_init(&vsetci_precitali, 0);
if (pthread_create(&generator, 0, generuj, 0) != 0) {
perror("nepodarilo sa vytvorit generator");
}
for(i = 0; i < 5; i++) {
poradie[i] = i+1;
if (pthread_create(&klienti[i], 0, klient, &poradie[i]) != 0) {
perror("nepodarilo sa vytvorit klienta ");
exit(1);
}
}
for(i = 0; i < 5; i++) {
if (pthread_join(klienti[i], 0) != 0) {
perror("chyba pri joine!");
exit(1);
}
}
if (pthread_join(generator, 0) !=0) {
perror("chyba pri joine!");
exit(1);
}
pthread_mutex_destroy(&MUTEX);
pthread_cond_destroy(&nove_cislo);
pthread_cond_destroy(&vsetci_precitali);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mx_timersync = PTHREAD_MUTEX_INITIALIZER;
static struct timeval offset_unix_concent = {0, 0};
extern bool exit_sig;
extern bool quit_sig;
extern pthread_mutex_t mx_concent;
int get_concentrator_time(struct timeval *concent_time, struct timeval unix_time) {
struct timeval local_timeval;
if (concent_time == 0) {
MSG("ERROR: %s invalid parameter\\n", __FUNCTION__);
return -1;
}
pthread_mutex_lock(&mx_timersync);
do { (&local_timeval)->tv_sec = (&unix_time)->tv_sec - (&offset_unix_concent)->tv_sec; (&local_timeval)->tv_usec = (&unix_time)->tv_usec - (&offset_unix_concent)->tv_usec; if ((&local_timeval)->tv_usec < 0) { --(&local_timeval)->tv_sec; (&local_timeval)->tv_usec += 1000000; } } while (0);
pthread_mutex_unlock(&mx_timersync);
concent_time->tv_sec = local_timeval.tv_sec;
concent_time->tv_usec = local_timeval.tv_usec;
MSG_DEBUG(DEBUG_TIMERSYNC, " --> TIME: unix current time is %ld,%ld\\n", unix_time.tv_sec, unix_time.tv_usec);
MSG_DEBUG(DEBUG_TIMERSYNC, " offset is %ld,%ld\\n", offset_unix_concent.tv_sec, offset_unix_concent.tv_usec);
MSG_DEBUG(DEBUG_TIMERSYNC, " sx1301 current time is %ld,%ld\\n", local_timeval.tv_sec, local_timeval.tv_usec);
return 0;
}
void thread_timersync(void) {
struct timeval unix_timeval;
struct timeval concentrator_timeval;
uint32_t sx1301_timecount = 0;
struct timeval offset_previous = {0, 0};
struct timeval offset_drift = {0, 0};
while (!exit_sig && !quit_sig) {
gettimeofday(&unix_timeval, 0);
lgw_get_trigcnt(&sx1301_timecount);
concentrator_timeval.tv_sec = sx1301_timecount / 1000000UL;
concentrator_timeval.tv_usec = sx1301_timecount - (concentrator_timeval.tv_sec * 1000000UL);
offset_previous.tv_sec = offset_unix_concent.tv_sec;
offset_previous.tv_usec = offset_unix_concent.tv_usec;
pthread_mutex_lock(&mx_timersync);
do { (&offset_unix_concent)->tv_sec = (&unix_timeval)->tv_sec - (&concentrator_timeval)->tv_sec; (&offset_unix_concent)->tv_usec = (&unix_timeval)->tv_usec - (&concentrator_timeval)->tv_usec; if ((&offset_unix_concent)->tv_usec < 0) { --(&offset_unix_concent)->tv_sec; (&offset_unix_concent)->tv_usec += 1000000; } } while (0);
pthread_mutex_unlock(&mx_timersync);
do { (&offset_drift)->tv_sec = (&offset_unix_concent)->tv_sec - (&offset_previous)->tv_sec; (&offset_drift)->tv_usec = (&offset_unix_concent)->tv_usec - (&offset_previous)->tv_usec; if ((&offset_drift)->tv_usec < 0) { --(&offset_drift)->tv_sec; (&offset_drift)->tv_usec += 1000000; } } while (0);
MSG_DEBUG(DEBUG_TIMERSYNC, " sx1301 = %u (µs) - timeval (%ld,%ld)\\n",
sx1301_timecount,
concentrator_timeval.tv_sec,
concentrator_timeval.tv_usec);
MSG_DEBUG(DEBUG_TIMERSYNC, " unix_timeval = %ld,%ld\\n", unix_timeval.tv_sec, unix_timeval.tv_usec);
MSG("INFO: host/sx1301 time offset=(%lds:%ldµs) - drift=%ldµs\\n",
offset_unix_concent.tv_sec,
offset_unix_concent.tv_usec,
offset_drift.tv_sec * 1000000UL + offset_drift.tv_usec);
wait_ms(60000);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
bool stop = 0;
void *killBySiginal()
{
char c;
printf("Digite o Sinal:\\n");
scanf(" %c",&c);
if(c == "T"){
printf("Parou com o Sinal %s", &c);
stop = 1;
}
stop = 0;
sleep(1);
}
void *producer(void *ptr)
{
int i;
for (i = 1; i < 300000; i++)
{
pthread_mutex_lock(&the_mutex);
while( buffer != 0 )
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
if(killBySiginal())
break;
}
pthread_exit(0);
}
void *cosumer(void *ptr)
{
int i;
for (i = 1; i < 300000; i++)
{
pthread_mutex_lock(&the_mutex);
while( buffer == 0 )
pthread_cond_wait(&condc, &the_mutex);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[])
{
printf("Thiago Gonçalves Cardoso Resnede\\n");
printf("Rafael Abadala Burle\\n");
printf("Matheus Gama\\n");
printf("Marcelo Cézar de almeida Junior\\n");
printf("Matheus Souza Silva\\n");
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, cosumer, 0);
pthread_create(&con, 0, producer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 0
|
#include <pthread.h>
const int MAX_THREADS = 1024;
long thread_count;
double a, b, h;
int n, local_n;
double total_integral;
pthread_mutex_t mutex;
void Get_args(int argc, char* argv[]);
void Usage(char* prog_name);
void* Trap(void* rank);
double f(double x);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
Get_args(argc, argv);
h = (b - a) / n;
local_n = n / thread_count;
pthread_mutex_init(&mutex, 0);
thread_handles = malloc (thread_count * sizeof(pthread_t));
for (thread = 0; thread < thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, Trap, (void*) thread);
}
for (thread = 0; thread < thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
printf("With n = %d trapezoids, our estimate\\n", n);
printf("of the integral from %f to %f = %.15e\\n", a, b, total_integral);
free(thread_handles);
return 0;
}
void* Trap(void* rank) {
long my_rank = (long) rank;
double estimate, x;
double left_endpt = a + my_rank*local_n*h;
double right_endpt = left_endpt + local_n*h;
estimate = (f(left_endpt) + f(right_endpt)) / 2.0;
for (int i = 1; i <= local_n - 1; i++) {
x = left_endpt + i*h;
estimate += f(x);
}
estimate = estimate*h;
pthread_mutex_lock(&mutex);
total_integral += estimate;
pthread_mutex_unlock(&mutex);
return 0;
}
double f(double x) {
return x*x;
}
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 = strtod(argv[2], 0);
b = strtod(argv[3], 0);
n = strtol(argv[4], 0, 10);
if (n <= 0 || (n % thread_count != 0)) Usage(argv[0]);
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads> <a> <b> <n>\\n", prog_name);
fprintf(stderr, " n is the number of trapezoids.\\n");
fprintf(stderr, " n should be evenly divisible by the number of threads\\n");
exit(0);
}
| 1
|
#include <pthread.h>
sem_t pieno;
sem_t vuoto;
pthread_mutex_t mutexS, mutexC;
int porzioni, ngiri;
void* Cuoco(void* arg){
int maxP = *((int*)arg);
while(1){
printf("Il CUOCO si addormenta\\n");
sem_wait(&vuoto);
if(porzioni == 0){
pthread_mutex_lock(&mutexC);
printf("Il cuoco cucina\\n");
porzioni = maxP;
printf("Il pentolone e' pieno\\n");
pthread_mutex_unlock(&mutexC);
sem_post(&pieno);
}
}
}
void *Selvaggio(void* arg){
int iS = *((int*)arg);
int i;
for(i = 0; i < ngiri; i++){
printf("Il selvaggi N %d pensa..\\n", iS);
sleep(2);
pthread_mutex_lock(&mutexS);
printf("Il selvaggio N %d ha fame\\n", iS);
if(porzioni == 0){
printf("Il pentolone e' vuoto, sveglio il cuoco\\n");
sem_post(&vuoto);
printf("Attendo che il cuoco prepari\\n");
printf("Il selvaggio N %d si addormenta\\n", iS);
sem_wait(&pieno);
printf("Il selvaggio N %d e' stato svegliato\\n", iS); ;
}
pthread_mutex_lock(&mutexC);
printf("Prendo una porzione\\n");
printf("IL selvaggio N %d mangia per la %d volta\\n", iS, i+1);
porzioni--;
pthread_mutex_unlock(&mutexC);
printf("porzioni = %d\\n", porzioni);
pthread_mutex_unlock(&mutexS);
}
pthread_exit(0);
}
void main(int argc, char* argv[]){
int maxP, nselvaggi;
int ret, i;
if (argc!=4){
printf("Numero di argomenti non corretto\\n");
printf("Inserie: numero selvaggi, dimensione pentolone, n di volte in cui un selvaggio ha fame\\n");
exit(-1);
}
sem_init(&pieno, 0, 0);
sem_init(&vuoto, 0, 0);
pthread_mutex_init(&mutexS, 0);
pthread_mutex_init(&mutexC, 0);
nselvaggi = atoi(argv[1]);
maxP = atoi(argv[2]);
ngiri = atoi(argv[3]);
pthread_t tcuoco;
pthread_t tselvaggio[nselvaggi - 1];
porzioni = maxP;
ret = pthread_create(&tcuoco, 0, Cuoco, &maxP);
if(ret != 0){
printf("ERRORE creazione cuoco\\n");
exit(-1);
}
for(i = 0; i < nselvaggi; i++){
ret = pthread_create(&tselvaggio[i], 0, Selvaggio, &i);
printf("Arriva il selvaggio N %d --\\n", i);
if(ret != 0){
printf("ERRORE creazione selvaggio\\n");
exit(-1);
}
}
for(i = 0; i < nselvaggi; i++){
ret = pthread_join(tselvaggio[i], 0);
if(ret != 0){
printf("ERRORE\\n");
exit(-1);
}
}
printf("Tutti i selvaggi hanno mangiato\\n");
}
| 0
|
#include <pthread.h>
void and_or(void *not_used){
pthread_barrier_wait(&threads_creation);
int and_result;
int or_result_temp;
while(1){
pthread_mutex_lock(&control_sign);
if(!cs.isUpdated){
while(pthread_cond_wait(&control_sign_wait, &control_sign) != 0);
}
pthread_mutex_unlock(&control_sign);
if(cs.invalidInstruction){
pthread_barrier_wait(&update_registers);
pthread_exit(0);
}
pthread_mutex_lock(&alu_zero_mutex);
if(!alu_zero.isUpdated)
while(pthread_cond_wait(&alu_zero_wait, &alu_zero_mutex) != 0);
pthread_mutex_unlock(&alu_zero_mutex);
if(( (separa_PCWriteCond & cs.value) >> 9) & alu_zero.value)
and_result = 1;
else
and_result = 0;
if( ((separa_PCWrite & cs.value) >> 10) | and_result ) {
or_result_temp = 1;
}
else {
or_result_temp = 0;
}
or_result.value = or_result_temp;
pthread_mutex_lock(&or_result_mutex);
or_result.isUpdated = 1;
pthread_cond_signal(&or_result_wait);
pthread_mutex_unlock(&or_result_mutex);
pthread_barrier_wait(¤t_cycle);
or_result.isUpdated = 0;
pthread_barrier_wait(&update_registers);
}
}
| 1
|
#include <pthread.h>
pthread_t philosophers[5];
pthread_mutex_t mutex_forks = PTHREAD_MUTEX_INITIALIZER;;
int forks[5];
void init()
{
int i;
for(i=0; i<5; i++)
forks[i] = 0;
}
void philosopher(int i)
{
int right = i;
int left = (i - 1 == -1) ? 5 - 1 : (i - 1);
int locked;
while(1)
{
locked = 0;
while(!locked)
{
pthread_mutex_lock(&mutex_forks);
if(forks[right] || forks[left])
{
pthread_mutex_unlock(&mutex_forks);
printf("Philosopher %d cannot take forks. Giving up and thinking.\\n",i);
usleep(random() % 1000);
continue;
}
forks[right] = 1;
forks[left] = 1;
pthread_mutex_unlock(&mutex_forks);
locked = 1;
}
printf("Philosopher %d took both forks. Now eating :)\\n",i);
usleep(random() % 500);
printf("Philosopher %d done with eating. Giving up forks.\\n",i);
pthread_mutex_lock(&mutex_forks);
forks[right] = 0;
forks[left] = 0;
pthread_mutex_unlock(&mutex_forks);
usleep(random() % 1000);
}
}
int main()
{
init();
int i;
for(i=0; i<5; i++)
pthread_create( &philosophers[i], 0, philosopher, (void*)i);
for(i=0; i<5; i++)
pthread_join(philosophers[i],0);
return 0;
}
| 0
|
#include <pthread.h>
{
char info;
int n;
int num;
pthread_mutex_t mutex;
}ThreadInfo;
void *func(void *arg)
{
int cnt = 3;
ThreadInfo *info = (ThreadInfo *)arg;
int result = info->n;
char show = info->info;
while (cnt > 0) {
if (info->num % 3 == result) {
printf("---%c\\n", show);
pthread_mutex_lock(&info->mutex);
info->num++;
cnt--;
pthread_mutex_unlock(&info->mutex);
}
}
return 0;
}
int main(int argc, char **argv)
{
pthread_t t1, t2, t3;
ThreadInfo info;
memset(&info, 0, sizeof(ThreadInfo));
pthread_mutex_init(&(info.mutex), 0);
info.n = 0;
info.info = 'A';
pthread_create(&t1, 0, func, &info);
sleep(1);
info.n = 1;
info.info = 'B';
pthread_create(&t2, 0, func, &info);
sleep(1);
info.n = 2;
info.info = 'C';
pthread_create(&t3, 0, func, &info);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
return 0;
}
| 1
|
#include <pthread.h>
size_t k;
int file;
char* word;
int N;
pthread_t* threads;
sigset_t mask;
pthread_mutex_t mutex;
pthread_t main_thread_id;
struct thread_args {
int id;
} **args;
void exit_program(int status, char* message) {
if(status == 0) {
printf("%s\\n",message);
} else {
perror(message);
}
exit(status);
}
int seek_for_word(char *buffer) {
char id_str[sizeof(int)], text[RECORDSIZE+1];
char *strtok_pointer;
char strtok_buf[RECORDSIZE*k];
strtok_pointer = strtok_buf;
for(int i =0;i<k;++i) {
char *p = strtok_r(buffer, SEPARATOR,&strtok_pointer);
strcpy(id_str, p);
int id = atoi(id_str);
p = strtok_r(0, "\\n",&strtok_pointer);
if(p!=0) {
strncpy(text, p, RECORDSIZE+1);
if (strstr(text, word) != 0) {
return id;
}
}
}
return -1;
}
void signal_handler(int signum) {
pthread_mutex_lock(&mutex);
pthread_t id = pthread_self();
printf("Catched singal %d, my id: %zu", signum, id);
if(id == main_thread_id) {
printf(" I'm main thread\\n");
} else {
printf(" I'm worker thread\\n");
}
fflush(stdin);
pthread_mutex_unlock(&mutex);
}
void init_signals() {
struct sigaction sa;
sigemptyset(&(sa.sa_mask));
sa.sa_flags = 0;
sa.sa_handler = signal_handler;
if(sigaction(SIGUSR1,&sa, 0) == -1) {
exit_program(1,"Couldn't initialize signal handlers for SIGUSR1");
}
struct sigaction sa2;
sigemptyset(&(sa2.sa_mask));
sa2.sa_flags = 0;
sa2.sa_handler = signal_handler;
if(sigaction(SIGTERM,&sa2,0) == -1) {
exit_program(1,"Couldn't initialize signal handlers for SIGTERM");
}
}
void *parallel_reader(void *arg) {
int id;
char buffer[1024*k];
struct thread_args *tmp = arg;
int jump = tmp->id;
long multiplier = RECORDSIZE*jump*k;
while(pread(file,buffer,RECORDSIZE*k,multiplier) > 0) {
if((id = seek_for_word(buffer)) != -1) {
printf("Found the word %s! Record id: %d, thread id: %zu\\n",word,id,pthread_self());
}
multiplier += (N*RECORDSIZE*k);
}
printf("End of thread life.\\n");
while(1);
}
void exit_handler() {
if(file!=0) {
close(file);
}
if(threads != 0) {
free(threads);
}
if(args !=0) {
for (int i = 0; i < N; ++i) {
if (args[i] != 0)
free(args[i]);
}
free(args);
}
}
void init_mask() {
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigaddset(&mask, SIGTERM);
}
int get_signal(int n) {
switch(n) {
case 1:
return SIGUSR1;
case 2:
return SIGTERM;
case 3:
return SIGKILL;
default:
return SIGSTOP;
}
}
char *get_signal_str(int n) {
switch(n) {
case 1:
return "SIGUSR1";
case 2:
return "SIGTERM";
case 3:
return "SIGKILL";
default:
return "SIGSTOP";
}
}
int main(int argc, char ** argv) {
if(argc != 6) {
exit_program(0, "Pass 4 arguments: N - the number of threads, filename - the name of the file to read records from"
"k - the number of records read by a thread in a single access, word - the word we seek in the file for, signal - the type of signal to send "
"1 - SIGUSR1, 2 - SIGTERM, 3 - SIGKILL, 4 - SIGSTOP\\n");
}
atexit(exit_handler);
N = atoi(argv[1]);
char *filename = argv[2];
k = (size_t) atoi(argv[3]);
if(k<=0 || N <= 0) {
exit_program(0,"Pass the N and k parameters > 0");
}
word = argv[4];
init_signals();
if((file = open(filename, O_RDONLY)) == -1) {
exit_program(1, "Couldn't open the file to read records from");
}
main_thread_id = pthread_self();
pthread_mutex_init(&mutex,0);
threads = malloc(sizeof(int)*N);
args = malloc(sizeof(struct thread_args*)*N);
for(int i=0;i<N;++i) {
args[i] = malloc(sizeof(struct thread_args));
args[i]->id = i;
if(pthread_create(&threads[i],0,parallel_reader,args[i])) {
exit_program(1,"Failed to create thread");
}
}
int signal = atoi(argv[5]);
printf("Sending %s to thread...\\n",get_signal_str(signal));
pthread_kill(threads[0],get_signal(signal));
printf("Sent!\\n");
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void* computeRandomPoints (void* input);
int pointsInCircle = 0;
pthread_mutex_t lock;
int main(int argc, const char * argv[])
{
pthread_t thread[1000];
pthread_mutex_init(&lock, 0);
int count;
for (count = 0; count < 1000; count++)
{
pthread_create (&thread[count], 0, computeRandomPoints, 0);
}
for (count = 0; count < 1000; count++)
{
pthread_join (thread[count], 0);
}
float estimatedPi = 4 * ((float)pointsInCircle / 100000000);
printf("The estimated value of Pi after generating %i points with %i threads is %f\\n", 100000000, 1000, estimatedPi);
pthread_mutex_destroy(&lock);
return 0;
}
void* computeRandomPoints (void* input)
{
double x, y;
int count, tempCount = 0;
for (count = 0; count < 100000000 / 1000; count++)
{
x = (double)rand() / 32767;
y = (double)rand() / 32767;
if (((x * x) + (y * y)) <= 1) {
tempCount++;
}
}
pthread_mutex_lock(&lock);
pointsInCircle += tempCount;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int isUsed;
pthread_mutex_t forkLock;
pthread_cond_t forkCond;
int forkId;
}forks;
int numPhilosophers;
int numEats;
forks* forkArray;
int getLeftForkId(int philosopherId){
return philosopherId;
}
int getRightForkId(int philosopherId, int numPhilosophers){
int rightForkId = (philosopherId+1)%(numPhilosophers);
return rightForkId;
}
void pickUpFork(forks* fork,int philosopherId){
pthread_mutex_lock(&(fork->forkLock));
while(fork->isUsed == 1){
pthread_cond_wait(&(fork->forkCond),&(fork->forkLock));
}
if(1){
printf("Philosopher %d is picking up fork %d! \\n",philosopherId,fork->forkId);
}
fork->isUsed = 1;
}
void putDownFork(forks* fork,int philosopherId){
if(1){
printf("Philosopher %d is putting down fork %d! \\n",philosopherId,(fork->forkId));
}
fork->isUsed = 0;
pthread_cond_signal(&(fork->forkCond));
pthread_mutex_unlock(&(fork->forkLock));
}
void *eatFood(void* arg){
int index = (int)arg;
int numEaten = 0;
while(numEaten < numEats){
usleep(random() % 25000);
printf("Philosopher %d is thinking about how great their next meal will be! \\n", index);
if(getRightForkId(index,numPhilosophers) > getLeftForkId(index)){
pickUpFork(&(forkArray[getLeftForkId(index)]),index);
usleep(random() % 25000);
pickUpFork(&(forkArray[getRightForkId(index,numPhilosophers)]),index);
}
else{
pickUpFork(&(forkArray[getRightForkId(index,numPhilosophers)]),index);
usleep(random() % 25000);
pickUpFork(&(forkArray[getLeftForkId(index)]),index);
}
printf("Philosopher %d is eating like there is no tomorrow! \\n", index);
usleep(random() % 25000);
putDownFork(&(forkArray[getRightForkId(index,numPhilosophers)]),index);
putDownFork(&(forkArray[getLeftForkId(index)]),index);
usleep(random() % 25000);
numEaten++;
}
if(1){
printf("Philosopher %d is leaving because he is beyond full after eating %d plates of food. \\n", index,numEats);
}
return 0;
}
int main(int argc, char** argv ){
numPhilosophers = atoi(argv[1]);
numEats = atoi(argv[2]);
int i,j,k;
pthread_t* threadArray = (pthread_t*)malloc(sizeof(pthread_t)*numPhilosophers);
forkArray = (forks*)malloc(sizeof(forks)*numPhilosophers);
for(k = 0; k < numPhilosophers; k++){
struct forks thisFork;
thisFork.isUsed = 0;
pthread_mutex_init(&(thisFork.forkLock), 0);
pthread_cond_init(&(thisFork.forkCond), 0);
thisFork.forkId = k;
forkArray[k] = thisFork;
}
for(i = 0; i < numPhilosophers; i++){
pthread_create(&threadArray[i],0,eatFood,(void*)i);
}
for(j = 0; j < numPhilosophers; j++){
pthread_join(threadArray[j], 0);
}
free(forkArray);
free(threadArray);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t gateaux_prets = PTHREAD_COND_INITIALIZER;
int gateaux = 0;
int stop = 0;
void* enfant(void *arg) {
int id = *((int*) arg);
int mange = 0;
while(1) {
pthread_mutex_lock(&mutex);
if(gateaux == 0 && stop == 0) {
pthread_cond_wait(&gateaux_prets, &mutex);
}
if (stop == 1) {
pthread_mutex_unlock(&mutex);
break;
} else if (gateaux > 0) {
gateaux--;
mange++;
printf("L'enfant %d a mangé un gateau\\n", id);
} else {
printf("L'enfant %d n'a pas eu de gateau\\n", id);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
return *((void**) &mange);
}
void* parent(void *arg) {
int i;
for (i = 0; i < 4; i++) {
pthread_mutex_lock(&mutex);
gateaux += 4;
printf("Le parent a préparé des gateaux\\n");
pthread_cond_broadcast(&gateaux_prets);
pthread_mutex_unlock(&mutex);
sleep(2);
}
pthread_mutex_lock(&mutex);
stop = 1;
pthread_cond_broadcast(&gateaux_prets);
pthread_mutex_unlock(&mutex);
return 0;
}
int main() {
int i, nb[5];
void* ret[5];
pthread_t tid[5 + 1];
for (i = 0; i < 5; i++) {
nb[i] = i;
pthread_create(&tid[i], 0, enfant, (void*) &nb[i]);
}
pthread_create(&tid[i], 0, parent, 0);
for (i = 0; i < 5; i++) {
pthread_join(tid[i], &ret[i]);
printf("L'enfant %d a mangé %d gateaux\\n", i, *((int*) &ret[i]));
}
pthread_join(tid[i], 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
void fhilo1(void *x){
int letra='A';
while(letra<='Z') {
pthread_mutex_lock(&mutex1);
usleep(100000);
write(1,&letra,1);
letra+=2;
pthread_mutex_unlock(&mutex2);
}
pthread_exit(0);
}
void fhilo2(void *x){
int letra='b';
while(letra<='z') {
pthread_mutex_lock(&mutex2);
usleep(100000);
write(1,&letra,1);
letra+=2;
pthread_mutex_unlock(&mutex1);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
pthread_mutex_init(&mutex1,0);
pthread_mutex_init(&mutex2,0);
pthread_mutex_lock(&mutex2);
pthread_t hilo1, hilo2;
pthread_create(&hilo1,0,(void *)fhilo1,0);
pthread_create(&hilo2,0,(void *)fhilo2,0);
pthread_join(hilo1,0);
pthread_join(hilo2,0);
exit(0);
}
| 0
|
#include <pthread.h>
void *(*process) (void *arg);
void *arg;
struct worker *next;
} CThread_worker;
pthread_mutex_t queue_lock;
pthread_cond_t queue_ready;
CThread_worker *queue_head;
int shutdown;
pthread_t *threadid;
int max_thread_num;
int cur_queue_size;
} CThread_pool;
int pool_add_worker (void *(*process) (void *arg), void *arg);
void *thread_routine (void *arg);
static CThread_pool *pool = 0;
void
pool_init (int max_thread_num)
{
pool = (CThread_pool *) malloc (sizeof (CThread_pool));
pthread_mutex_init (&(pool->queue_lock), 0);
pthread_cond_init (&(pool->queue_ready), 0);
pool->queue_head = 0;
pool->max_thread_num = max_thread_num;
pool->cur_queue_size = 0;
pool->shutdown = 0;
pool->threadid =
(pthread_t *) malloc (max_thread_num * sizeof (pthread_t));
int i = 0;
for (i = 0; i < max_thread_num; i++) {
pthread_create (&(pool->threadid[i]), 0, thread_routine,
0);
}
}
int
pool_add_worker (void *(*process) (void *arg), void *arg)
{
CThread_worker *newworker =
(CThread_worker *) malloc (sizeof (CThread_worker));
newworker->process = process;
newworker->arg = arg;
newworker->next = 0;
pthread_mutex_lock (&(pool->queue_lock));
CThread_worker *member = pool->queue_head;
if (member != 0) {
while (member->next != 0) {
member = member->next;
}
member->next = newworker;
} else {
pool->queue_head = newworker;
}
assert (pool->queue_head != 0);
pool->cur_queue_size++;
pthread_cond_signal (&(pool->queue_ready));
pthread_mutex_unlock (&(pool->queue_lock));
return 0;
}
int
pool_destroy ()
{
if (pool->shutdown) {
return -1;
}
pool->shutdown = 1;
pthread_cond_broadcast (&(pool->queue_ready));
int i;
for (i = 0; i < pool->max_thread_num; i++) {
pthread_join (pool->threadid[i], 0);
}
free (pool->threadid);
CThread_worker *head = 0;
while (pool->queue_head != 0) {
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free (head);
}
pthread_mutex_destroy(&(pool->queue_lock));
pthread_cond_destroy(&(pool->queue_ready));
free (pool);
pool=0;
return 0;
}
void *
thread_routine (void *arg)
{
printf ("starting thread 0x%x\\n", (unsigned int)pthread_self ());
while (1) {
pthread_mutex_lock (&(pool->queue_lock));
while (pool->cur_queue_size == 0 && !pool->shutdown) {
printf ("thread 0x%x is waiting\\n", (unsigned int)pthread_self ());
pthread_cond_wait (&(pool->queue_ready), &(pool->queue_lock));
}
if (pool->shutdown) {
pthread_mutex_unlock (&(pool->queue_lock));
printf ("thread 0x%x will exit\\n", (unsigned int)pthread_self ());
pthread_exit (0);
}
printf ("thread 0x%x is starting to work\\n", (unsigned int)pthread_self ());
assert (pool->cur_queue_size != 0);
assert (pool->queue_head != 0);
pool->cur_queue_size--;
CThread_worker *worker = pool->queue_head;
pool->queue_head = worker->next;
pthread_mutex_unlock (&(pool->queue_lock));
(*(worker->process)) (worker->arg);
free (worker);
worker = 0;
}
pthread_exit (0);
}
void *
myprocess (void *arg)
{
printf ("threadid is 0x%x, working on task %d\\n", (unsigned int)pthread_self (), *(int *) arg);
sleep (1);
return 0;
}
int
main (int argc, char **argv)
{
pool_init (3);
int *workingnum = (int *) malloc (sizeof (int) * 10);
int i;
for (i = 0; i < 10; i++)
{
workingnum[i] = i;
pool_add_worker (myprocess, &workingnum[i]);
}
sleep (5);
pool_destroy ();
free (workingnum);
return 0;
}
| 1
|
#include <pthread.h>
int chopstick[5] = {0,0,0,0,0};
int state[5];
pthread_cond_t chopstic_cond[5] = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex_lock = PTHREAD_MUTEX_INITIALIZER;
void pick_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
sleep(1);
if(state[id] == 1 && chopstick[id]==0 && chopstick[(id+1)%5]==0){
pthread_cond_wait(&chopstic_cond[id],&mutex_lock);
chopstick[id] = 1;
printf("philosopher %d is pick up the left chopstick %d .\\n",id,id);
pthread_cond_wait(&chopstic_cond[(id+1)%5],&mutex_lock);
chopstick[(id+1)%5] = 1;
printf("philosopher %d is pick up the right chopstick %d .\\n",id,(id+1)%5);
}
else{
}
pthread_mutex_unlock(&mutex_lock);
}
void take_down_chopstick(int id)
{
pthread_mutex_lock(&mutex_lock);
chopstick[id] = 0;
printf("philosopher %d is take down the left chopstick %d .\\n",id,id);
pthread_cond_signal(&chopstic_cond[id]);
pthread_mutex_unlock(&mutex_lock);
pthread_mutex_lock(&mutex_lock);
chopstick[(id+1)%5] = 0;
printf("philosopher %d is take down the right chopstick %d .\\n",id,(id+1)%5);
pthread_cond_signal(&chopstic_cond[(id+1)%5]);
state[id]= 0;
pthread_mutex_unlock(&mutex_lock);
}
void *philosopher(void* data)
{
int id = (int)data;
while(1){
int sleep_time = (int)((random() % 3) + 1);
printf("Philosopher %d is thinking\\n",id);
sleep(sleep_time);
state[id] = 1;
printf("philosopher %d is hungry.\\n",id);
pick_chopstick(id);
if(chopstick[id] == 1 && chopstick[(id+1)%5] ==1)
{
state[id] = 2;
printf("philosopher %d is eating.\\n",id);
sleep(1);
take_down_chopstick(id);
}
}
}
int main(){
int i=0;
pthread_t pthred_philosopher[5];
for(i=0;i<5;i++){
pthread_create(&pthred_philosopher[i],0,philosopher,i);
state[i]=0;
}
for(i=0;i<5;i++){
pthread_join(pthred_philosopher[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
char** theArray;
int aSize=100;
int usr_port;
pthread_mutex_t* mutexArray;
void* ServerEcho(void *args);
int main(int argc, char * argv []){
int n = atoi(argv[2]);
usr_port = atoi(argv[1]);
if( (n==10)||(n==100)||(n==1000)||(n==10000) ){
aSize=n;
}
theArray=malloc(aSize*sizeof(char*));
for (int i=0; i<aSize;i++){
theArray[i]=malloc(100*sizeof(char));
snprintf(theArray[i],100, "%s%d%s", "String ", i, ": the initial value" );
}
printf("creating mutex array \\n");
mutexArray=malloc(aSize*sizeof(pthread_mutex_t));
for (int i=0; i<aSize;i++){
pthread_mutex_init(&mutexArray[i],0);
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
pthread_t* thread_handles;
thread_handles = malloc(1000*sizeof(pthread_t));
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=usr_port;
sock_var.sin_family=AF_INET;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
printf("socket has been created \\n");
listen(serverFileDescriptor,2000);
while(1){
for(int i=0;i<1000;i++){
clientFileDescriptor=accept(serverFileDescriptor,0,0);
printf("Connect to client %d \\n",clientFileDescriptor);
pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor);
}
for(int i = 0;i<1000;i++){
pthread_join(thread_handles[i],0);
}
printf("All threads have joined. Checking Array \\n");
for(int i=0;i<aSize;i++){
printf("%s\\n",theArray[i]);
free(theArray[i]);
}
free(theArray);
free(thread_handles);
for (int i=0; i<aSize;i++){
pthread_mutex_destroy(&mutexArray[i]);
}
free(mutexArray);
}
}
else{
printf("socket creation failed \\n");
return 1;
}
return 0;
}
void* ServerEcho(void* args){
long clientFileDescriptor = (long) args;
char buff[100];
read(clientFileDescriptor,buff,100);
int pos;
char operation;
int CSerror;
sscanf(buff, "%d %c", &pos,&operation);
printf("Server thread recieved position %d and operation %c from %ld \\n",pos,operation,clientFileDescriptor);
if(operation=='r'){
char msg[100];
pthread_mutex_lock(&mutexArray[pos]);
CSerror=snprintf(msg,100, "%s", theArray[pos] );
pthread_mutex_unlock(&mutexArray[pos]);
if(CSerror<0){
printf("ERROR: could not read from position: %d \\n", pos);
sprintf(msg, "%s %d","Error reading from pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else if(operation=='w'){
char msg[100];
snprintf(msg,100, "%s%d%s","String ", pos, " has been modified by a write request" );
pthread_mutex_lock(&mutexArray[pos]);
CSerror=snprintf(theArray[pos],100, "%s", msg );
pthread_mutex_unlock(&mutexArray[pos]);
if(CSerror<0){
printf("ERROR: could not write position: %d \\n", pos);
sprintf(msg, "%s %d","Error writing to pos: ", pos );
}
write(clientFileDescriptor,msg,100);
close(clientFileDescriptor);
}
else{
printf("ERROR: could not communicate with client \\n");
}
return 0;
}
| 1
|
#include <pthread.h>
struct thrd_data{
int id;
int start;
int end;
};
int count = 0;
pthread_mutex_t count_mtx;
void *do_work(void *thrd_arg)
{
struct thrd_data *t_data;
int i,j,min, max;
int myid;
int mycount = 0;
t_data = (struct thrd_data *) thrd_arg;
myid = t_data->id;
min = t_data->start;
max = t_data->end;
printf ("Thread %d finding prime from %d to %d\\n", myid,min,max-1);
if (myid==0)
{
for (i=2;i<max;i++)
{
for (j=2; j<=i; j++)
{
if (i%j==0)
{
break;
}
else
{
printf("%d is a prime number.\\n",i);
mycount = mycount + 1;
}
}
if (i==j)
{
printf("%d is a prime number.\\n",i);
mycount = mycount + 1;
}
}
pthread_mutex_lock (&count_mtx);
count = count + mycount;
pthread_mutex_unlock (&count_mtx);
pthread_exit(0);
}
else
{
for (i=min;i<max;i++)
{
for (j=2; j<=i; j++)
{
if (i%j==0)
{
break;
}
else
{
printf("%d is a prime number.\\n",i);
mycount = mycount + 1;
}
}
if (i==j)
{
printf("%d is a prime number.\\n",i);
mycount = mycount + 1;
}
}
pthread_mutex_lock (&count_mtx);
count = count + mycount;
pthread_mutex_unlock (&count_mtx);
pthread_exit(0);
}
}
int main(int argc, char *argv[])
{
int i, n, n_threads;
int k, nq, nr;
struct thrd_data *t_arg;
pthread_t *thread_id;
pthread_attr_t attr;
pthread_mutex_init(&count_mtx, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
printf ("enter the range n = ");
scanf ("%d", &n);
printf ("enter the number of threads n_threads = ");
scanf ("%d", &n_threads);
thread_id = (pthread_t *)malloc(sizeof(pthread_t)*n_threads);
t_arg = (struct thrd_data *)malloc(sizeof(struct thrd_data)*n_threads);
nq = n / n_threads;
nr = n % n_threads;
k = 1;
for (i=0; i<n_threads; i++){
t_arg[i].id = i;
t_arg[i].start = k;
if (i < nr)
k = k + nq + 1;
else
k = k + nq;
t_arg[i].end = k;
pthread_create(&thread_id[i], &attr, do_work, (void *) &t_arg[i]);
}
for (i=0; i<n_threads; i++) {
pthread_join(thread_id[i], 0);
}
printf ("Done. Count= %d \\n", count);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mtx);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 0;
void * producer(void *ptr)
{
int i;
for(i = 0; i < 20; i++)
{
printf("producer locking critical region\\n");
pthread_mutex_lock(&the_mutex);
printf("producer producing %d\\n", i);
while(buffer != 0)
{
printf("buffer not empty, producer sleeping\\n");
pthread_cond_wait(&condp, &the_mutex);
}
buffer = i;
printf("producer signaling consumer to wake up\\n");
pthread_cond_signal(&condc);
printf("producer releasing lock on critical region\\n");
pthread_mutex_unlock(&the_mutex);
}
}
void * consumer(void *ptr)
{
int i;
for(i = 1; i < 20; i++)
{
printf("consumer locking critical region\\n");
pthread_mutex_lock(&the_mutex);
printf("consumer consuming %d\\n", i);
while(buffer == 0)
{
printf("buffer is empty, consumer sleeping\\n");
pthread_cond_wait(&condc, &the_mutex);
}
buffer = 0;
printf("consumer signaling producer to wake up\\n");
pthread_cond_signal(&condp);
printf("consumer releasing lock on critical region\\n");
pthread_mutex_unlock(&the_mutex);
}
}
int main()
{
pthread_t pro, con;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&con, 0, consumer, 0);
pthread_create(&pro, 0, producer, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int mediafirefs_getxattr(const char *path, const char *name, char *value,
size_t size)
{
printf("FUNCTION: getxattr. path: %s\\n", path);
(void)path;
(void)name;
(void)value;
(void)size;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
fprintf(stderr, "getxattr not implemented\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOSYS;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int num = 0;
FILE *fp[4];
int file = 1;
void *write_func(void *arg)
{
int i;
int tmp = (int)arg;
int count = tmp;
for(i = 0; i < 12; i++)
{
pthread_mutex_lock(&mutex);
while(tmp != num)
{
pthread_cond_wait(&cond,&mutex);
}
printf("线程%d在操作!写入文件中.....\\n",tmp + 1);
fp[0] = fopen("file1","a+");
fp[1] = fopen("file2","a+");
fp[2] = fopen("file3","a+");
fp[3] = fopen("file4","a+");
putc('A' + tmp, fp[count]);
putc('\\n', fp[count]);
fclose(fp[0]);
fclose(fp[1]);
fclose(fp[2]);
fclose(fp[3]);
file++;
num = (num + 1) % 4;
count = (count + 3) % 4;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
sleep(1);
}
}
int main()
{
int i;
pthread_t fd[4];
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
for(i = 0; i < 4; i++)
{
pthread_create(&fd[i],0,(void *)write_func,(void *)i);
}
for(i = 0; i < 4; i++)
{
pthread_join(fd[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condvar = PTHREAD_COND_INITIALIZER;
void * function1();
void * function2();
int count = 0;
int main (int argc, const char ** argv)
{
pthread_t thread1, thread2;
pthread_create(&thread1, 0, &function1, 0);
pthread_create(&thread2, 0, &function2, 0);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("Final count: %d\\n", count);
return 0;
}
void * function1 (void)
{
for(;;) {
pthread_mutex_lock(&count_mutex);
pthread_cond_wait(&condvar, &count_mutex);
count++;
printf("Counter value in function1: %d\\n", count);
pthread_mutex_unlock(&count_mutex);
if (count >= 10)
return 0;
}
}
void * function2 (void)
{
for(;;) {
pthread_mutex_lock(&count_mutex);
if (count < 3 || count > 6) {
pthread_cond_signal(&condvar);
} else {
count++;
printf("Counter value function2: %d\\n", count);
}
pthread_mutex_unlock(&count_mutex);
if (count >= 10)
return 0;
}
}
| 0
|
#include <pthread.h>
int
ports_count_class (struct port_class *class)
{
int ret;
pthread_mutex_lock (&_ports_lock);
ret = class->count;
class->flags |= PORT_CLASS_NO_ALLOC;
pthread_mutex_unlock (&_ports_lock);
return ret;
}
| 1
|
#include <pthread.h>
int MemoryLookupTable[M];
int PhysicalMemory[M];
int MetaTable[M];
int Disk[10000];
pthread_mutex_t memoryLock;
int seq;
int mode;
int Fetch(int i);
int PageIn(int i);
int obtainMemoryLock();
int releaseMemoryLock();
void removeLeastRecentlyUsed(int val, int i);
void removeMostRecentlyUsed(int val, int i);
void removeRandom(int val, int i);
int memoryIsFull();
int findOpenMemorySlot();
void updateMetaTable(int i);
int PageIn(int i) {
int result;
result = Fetch(i);
if (result == -1) {
int val;
val = Disk[i];
if (memoryIsFull()) {
switch(mode) {
case 1:
removeLeastRecentlyUsed(val, i);
break;
case 2:
removeMostRecentlyUsed(val, i);
break;
case 3:
removeRandom(val, i);
break;
default:
printf("Unkown Eviction Mode\\n");
exit(-1);
}
return val;
} else {
int openSlot = findOpenMemorySlot();
PhysicalMemory[openSlot] = val;
MemoryLookupTable[openSlot] = i;
updateMetaTable(openSlot);
return val;
}
} else {
return result;
}
}
void updateMetaTable(int i) {
if (mode != 3) {
struct timeval tv;
gettimeofday(&tv, 0);
MetaTable[i] = tv.tv_sec;
}
}
int Fetch(int i) {
int j;
for (j = 0; j < M; j++) {
if (i == MemoryLookupTable[j]) {
updateMetaTable(j);
return PhysicalMemory[j];
}
}
return -1;
}
void* thread_1(void* data) {
int i;
int s = 0;
int x;
while (1) {
s = 0;
for (i = 0; i < K; i++) {
obtainMemoryLock();
x = PageIn(i);
releaseMemoryLock();
s += x;
}
obtainMemoryLock();
x = PageIn((int) (rand() % 10000));
releaseMemoryLock();
s += x;
printf("1, %d\\n", seq);
}
}
void* thread_2(void* data) {
int i;
int s;
int x;
int round = 0;
while (1) {
s = 0;
if (round == 10000) {
round = 0;
}
int end;
end = K + round;
for (i = round; i < end; i++) {
obtainMemoryLock();
x = PageIn(i);
releaseMemoryLock();
s += x;
}
printf("2, %d\\n", seq);
}
}
void* thread_3(void* data) {
int i;
int s;
int x;
while (1) {
s = 0;
for (i = 0; i < K; i++) {
obtainMemoryLock();
x = PageIn((int) rand() % K);
releaseMemoryLock();
s += x;
}
printf("3, %d\\n", seq);
}
}
int obtainMemoryLock() {
pthread_mutex_lock (&memoryLock);
seq++;
if ( seq == 100000 ) {
printf("Reached max sequence count, exiting\\n");
exit(0);
}
return 0;
}
int releaseMemoryLock() {
pthread_mutex_unlock(&memoryLock);
return 0;
}
void removeLeastRecentlyUsed(int val, int i) {
int removalIndex;
int j;
removalIndex = 0;
for (j = 0; j < M; j++) {
if (MetaTable[removalIndex] > MetaTable[j]) {
removalIndex = j;
}
}
MemoryLookupTable[removalIndex] = i;
PhysicalMemory[removalIndex] = val;
}
void removeMostRecentlyUsed(int val, int i) {
int removalIndex;
int j;
removalIndex = 0;
for (j = 0; j < M; j++) {
if (MetaTable[removalIndex] < MetaTable[j]) {
removalIndex = j;
}
}
MemoryLookupTable[removalIndex] = i;
PhysicalMemory[removalIndex] = val;
}
void removeRandom(int val, int i) {
int removalIndex;
removalIndex = (int) rand() % M;
MemoryLookupTable[removalIndex] = i;
PhysicalMemory[removalIndex] = val;
}
int findOpenMemorySlot() {
int i;
for (i = 0; i < M; i++) {
if (MemoryLookupTable[i] == -1) {
return i;
}
}
printf("SOMETHING HAS GONE HORRIBLY WRONG\\n");
exit(-1);
}
int memoryIsFull() {
int i;
for (i = 0; i < M; i++){
if (MemoryLookupTable[i] == -1) {
return 0;
}
}
return 1;
}
int main(int argC, char** argV) {
if (argC != 2) {
printf("Usage: <Eviction Mode>\\n");
exit(-1);
}
mode = atoi(argV[1]);
srand (time(0));
int i;
for (i = 0; i < M; i++) {
MemoryLookupTable[i] = -1;
PhysicalMemory[i] = -1;
MetaTable[i] = -1;
}
for (i = 0; i < 10000; i++) {
Disk[i] = (int) rand() % 100;
}
pthread_t thread1, thread2, thread3;
int iret1, iret2, iret3;
pthread_mutex_init(&memoryLock, 0);
iret1 = pthread_create( &thread1, 0, thread_1, (void*) 0);
iret2 = pthread_create( &thread2, 0, thread_2, (void*) 0);
iret3 = pthread_create( &thread3, 0, thread_3, (void*) 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
pthread_join( thread3, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
int var1 =0, var2=0, running = 1;
void *threadFunc1(void *arg)
{
char *str;
str=(char*)arg;
printf("%s\\n", str);
while(running){
pthread_mutex_lock(&lock);
var1++;
var2 = var1;
pthread_mutex_unlock(&lock);
}
return 0;
}
void *threadFunc2(void *arg)
{
char *str;
str=(char*)arg;
printf("%s\\n", str);
for(int i=0; i<20; i++){
pthread_mutex_lock(&lock);
printf("Number 1 is %i , Number 2 is %i\\n", var1, var2);
pthread_mutex_unlock(&lock);
usleep(100000);
}
running = 0;
return 0;
}
int main(int argc, char** argv){
pthread_t thread1, thread2;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
pthread_create(&thread1,0, threadFunc1, "thread1");
pthread_create(&thread2,0, threadFunc2, "thread2");
pthread_join(thread1,0);
pthread_join(thread2,0);
pthread_mutex_destroy(&lock);
printf("THE END\\n");
return 0;
}
| 1
|
#include <pthread.h>
int state[5];
pthread_mutex_t mutex;
sem_t forks[5];
int id[5];
void think(int i) {
state[i] = 0;
}
void test(int i) {
if (state[i] == 1 && state[(i-1) % 5] != 2 && state[(i+1) % 5] != 2) {
state[i] = 2;
sem_post(&forks[i]);
}
}
void pick_sticks(int i) {
pthread_mutex_lock(&mutex);
state[i] = 1;
test(i);
pthread_mutex_unlock(&mutex);
sem_wait(&forks[i]);
}
void put_sticks(int i) {
pthread_mutex_lock(&mutex);
state[i] = 0;
printf("philosopher %d thinking\\n", i);
test((i-1) % 5);
test((i+1) % 5);
pthread_mutex_unlock(&mutex);
}
void eat(int i) {
state[i] = 2;
printf("philosopher %d eating\\n", i);
}
void* philosopher(void* args) {
int id = *((int*)args);
int i;
for (i = 0; i < 10; i++) {
think(id);
pick_sticks(id);
eat(id);
put_sticks(id);
}
pthread_exit(0);
}
int main() {
pthread_mutex_init(&mutex, 0);
int i;
for (i = 0; i < 5; i++) {
sem_init(&forks[i], 0, 0);
id[i] = i;
}
pthread_t philosophers[5];
for (i = 0; i < 5; i++) {
pthread_create(&philosophers[i], 0, philosopher, &id[i]);
}
pthread_exit(0);
return 0;
}
| 0
|
#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_destroy(&attr);
}
int
getenv_t(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][len + 1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
| 1
|
#include <pthread.h>
int count = 0;
pthread_mutex_t lock;
void *ThreadFunction(void* arg)
{
int* id = (int*)arg;
int it = 0;
printf("\\nCalling Function Started: %d\\n", *id);
if (pthread_mutex_trylock(&lock)==0)
{
for ( it = 0; it<100000; it++);
count += 1;
printf("In Calling thread %d: Count:%d\\n", *id, count);
pthread_mutex_unlock(&lock);
}
printf("Calling Function Ended: %d\\n", *id);
pthread_exit(0);
}
void *JoinedThreadFunction(void* argu)
{
pthread_mutex_lock(&lock);
int* idt = (int*)argu;
int i = 0;
printf("\\nJoined Function Started: %d\\n", *idt);
for ( i = 0; i<100000; i++);
count += 1;
printf("In Joined thread %d: Count:%d\\n", *idt, count);
printf("Joined Function Ended: %d\\n", *idt);
pthread_mutex_unlock(&lock);
idt = 0;
pthread_exit(0);
}
void main(int argc, char *argv[])
{
pthread_t thread_to_join[5], calling_thread;
int returnvalue;
int tid = 10;
int n = 0;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("Error: Mutex init failed\\n");
}
returnvalue = pthread_create(&calling_thread, 0, ThreadFunction, (void *)&tid);
if (returnvalue){
printf("ERROR; return code from pthread_create() is %d\\n", returnvalue);
}
for (n = 0; n<5; n++)
{
returnvalue = pthread_create(&thread_to_join[n], 0, JoinedThreadFunction,(void*)&n);
if (returnvalue){
printf("ERROR; return code from pthread_create() is %d\\n", returnvalue);
}
}
for (n = 0; n<5; n++)
{
returnvalue = pthread_join(thread_to_join[n], 0);
}
returnvalue = pthread_join(calling_thread, 0);
pthread_mutex_destroy(&lock);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
int control;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
void my_init( void )
{
int ret = 0;
ret = pthread_mutex_lock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to lock mutex in initializer" );
}
control++;
ret = pthread_mutex_unlock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to unlock mutex in initializer" );
}
return ;
}
void * threaded ( void * arg )
{
int ret;
ret = pthread_once( arg, my_init );
if ( ret != 0 )
{
UNRESOLVED( ret, "pthread_once failed" );
}
return 0;
}
int main( int argc, char * argv[] )
{
int ret, i;
pthread_once_t myctl = PTHREAD_ONCE_INIT;
pthread_t th[ 30 ];
output_init();
control = 0;
for ( i = 0; i < 30; i++ )
{
ret = pthread_create( &th[ i ], 0, threaded, &myctl );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to create a thread" );
}
}
for ( i = 0; i < 30; i++ )
{
ret = pthread_join( th[ i ], 0 );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to join a thread" );
}
}
ret = pthread_mutex_lock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to lock mutex in initializer" );
}
if ( control != 1 )
{
output( "Control: %d\\n", control );
FAILED( "The initializer function did not execute once" );
}
ret = pthread_mutex_unlock( &mtx );
if ( ret != 0 )
{
UNRESOLVED( ret, "Failed to unlock mutex in initializer" );
}
PASSED;
}
| 1
|
#include <pthread.h>
{
int nCount;
int nData;
}FOO,*PFOO;
int main(int argc,char *argv[])
{
FOO *ptr;
pid_t pid;
pthread_mutexattr_t mutexattr;
pthread_mutex_t mutex;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setpshared(&mutexattr,PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mutex,&mutexattr);
ptr = (PFOO)mmap(0,sizeof(FOO),PROT_READ | PROT_WRITE,MAP_SHARED|MAP_ANON,-1,0);
ptr->nCount = 1;
ptr->nData = 2;
printf("init : %d,%d\\n",ptr->nCount,ptr->nData);
if( (pid = fork()) < 0)
{
printf("fork error\\n");
return -1;
}
else if( 0 == pid)
{
while(1) {
show_time();
printf(" child : wait lock\\n");
pthread_mutex_lock(&mutex);
show_time();
printf(" child : get lock\\n");
sleep(2);
show_time();
printf(" child : release lock\\n");
pthread_mutex_unlock(&mutex);
}
int i = 0;
for(i = 0;i<3;i++)
{
while(1) {
if(0 != pthread_mutex_lock(&mutex)) {
usleep(505);
printf("f\\n");
continue;
}
break;
}
ptr->nCount++;
printf("child ++ === %d\\n",ptr->nCount);
pthread_mutex_unlock(&mutex);
usleep(500);
}
}
else
{
while(1) {
show_time();
printf(" parent : wait lock\\n");
pthread_mutex_lock(&mutex);
show_time();
printf(" parent : get lock\\n");
usleep(100000);
show_time();
printf(" parent : release lock\\n");
pthread_mutex_unlock(&mutex);
}
int i = 0;
for(i = 0;i<3;i++)
{
pthread_mutex_lock(&mutex);
ptr->nCount += 2;
printf("parent +2 === %d\\n",ptr->nCount);
usleep(1005);
pthread_mutex_unlock(&mutex);
usleep(1005);
}
}
waitpid(pid,0,0);
munmap(0,sizeof(FOO));
return 0;
}
| 0
|
#include <pthread.h>
extern char **environ;
static pthread_key_t key;
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_destroy(&attr);
pthread_key_create(&key,free);
}
char* mygetenv(const char *name)
{
int i,len;
char *envbuf;
pthread_once(&init_done,thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char*)pthread_getspecific(key);
if(envbuf == 0)
{
envbuf = (char*)malloc(100);
if(envbuf == 0)
{
pthread_mutex_unlock(&env_mutex);
return 0;
}
pthread_setspecific(key,envbuf);
}
len = strlen(name);
for(i=0;environ[i] != 0;i++)
{
if((strncmp(name,environ[i],len) == 0) &&
(environ[i][len] == '='))
{
strcpy(envbuf,&environ[i][len+1]);
pthread_mutex_unlock(&env_mutex);
return envbuf;
}
}
pthread_mutex_unlock(&env_mutex);
return 0;
}
void * thread_func1(void *arg)
{
char *pvalue;
printf("thread 1 start.\\n");
pvalue = mygetenv("HOME");
printf("HOME=%s\\n",pvalue);
printf("thread 1 exit.\\n");
pthread_exit((void*)1);
}
void * thread_func2(void *arg)
{
char *pvalue;
printf("thread 2 start.\\n");
pvalue = mygetenv("SHELL");
printf("SHELL=%s\\n",pvalue);
printf("thread 2 exit.\\n");
pthread_exit((void*)2);
}
int main()
{
pthread_t pid1,pid2;
int err;
void *pret;
pthread_create(&pid1,0,thread_func1,0);
pthread_create(&pid2,0,thread_func2,0);
pthread_join(pid1,&pret);
printf("thread 1 exit code is: %d\\n",(int)pret);
pthread_join(pid2,&pret);
printf("thread 2 exit code is: %d\\n",(int)pret);
exit(0);
}
| 1
|
#include <pthread.h>
int plasicur(void)
{
char c;
int test_enc1_cnt = 0;
pthread_mutex_lock(&mutex_ser);
motc.ascRettaOffset = lround((double)motc1.encY / MAXARCNT - AR_OFFSET / 24.0) * MAXARCNT;
pthread_mutex_unlock(&mutex_ser);
if (!SerCmdGotoEncSync(CNT_LATD, (long)(-MAXLATDCNT*(LATD_SIC-LATD_OFFSET)/360.), 5, 15))
{
lock();
pSharedData->idError = ERR_PLASICUR_GOTOSICUR;
unlock();
return -1;
}
if (!SerCmdGotoEncSync(CNT_AR, (long)(MAXARCNT*AR_OFFSET / 24.0), 150, 15))
{
lock();
pSharedData->idError = ERR_PLASICUR_GOTOSICUR;
unlock();
return -1;
}
do
{
sleep_ms(50);
if (!test_enc1_cnt)
{
test_enc1_cnt = 20;
printf("(SICUR) motc1.encY=%ld, ascRetta=%ld, ascRettaOffset=%ld\\n", motc1.encY, motc.ascRetta, motc.ascRettaOffset);
fflush(stdout);
}
else
test_enc1_cnt--;
updateData();
} while ((fabs(pSharedData->latitude_now - LATD_SIC)>0.5 || fabs(pSharedData->ar_now)>0.5) && !pSharedData->bAbort);
if (pSharedData->bAbort)
{
SerCmdGotoEncSync(CNT_LATD, motc.declinazione, 2, 5);
SerCmdGotoEncSync(CNT_AR, motc.ascRetta, 10, 5);
lock();
pSharedData->bAbort = FALSE;
pSharedData->bSuspend = FALSE;
pSharedData->idError = ERR_ABORTED;
unlock();
}
return 0;
}
| 0
|
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int main()
{
int rc1, rc2;
pthread_t thread1, thread2;
if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc1);
}
if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc2);
}
printf("Hello from main\\n");
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Exit from main\\n");
return 0;
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\\n",counter);
pthread_mutex_unlock( &mutex1 );
}
| 1
|
#include <pthread.h>
uint64_t nb;
FILE * file;
char str[60];
pthread_t thread0;
pthread_t thread1;
pthread_mutex_t lock;
pthread_mutex_t lockScreen;
const int MAX_FACTORS=64;
void print_prime_factors(uint64_t n);
int get_prime_factors(uint64_t n,uint64_t* dest);
void* thread_prime_factors(void * u)
{
pthread_mutex_lock(&lock);
while ( fgets(str, 60, file)!=0 )
{
nb=atol(str);
pthread_mutex_unlock(&lock);
print_prime_factors(nb);
pthread_mutex_lock(&lock);
}
pthread_mutex_unlock(&lock);
return 0;
}
void print_prime_factors(uint64_t n)
{
uint64_t factors[MAX_FACTORS];
int j,k;
k=get_prime_factors(n,factors);
pthread_mutex_lock(&lockScreen);
printf("%ju: ",n);
for(j=0; j<k; j++)
{
printf("%ju ",factors[j]);
}
printf("\\n");
pthread_mutex_unlock(&lockScreen);
}
int get_prime_factors(uint64_t n,uint64_t* dest)
{
int compteur=0;
uint64_t i;
while ( n%2 == 0)
{
n=n/2;
dest[compteur]=(uint64_t)2;
compteur++;
}
while ( n%3 == 0)
{
n=n/3;
dest[compteur]=(uint64_t)3;
compteur++;
}
while ( n%5 == 0)
{
n=n/5;
dest[compteur]=(uint64_t)5;
compteur++;
}
for( i=7; n!=1 ; i++ )
{
while (n%i==0)
{
n=n/i;
dest[compteur]=i;
compteur++;
}
}
if(n!=1)
{
dest[compteur]=n;
compteur++;
}
return compteur;
}
int main(void)
{
file = fopen ("fileQuestion4efficace.txt","r");
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex file init failed\\n");
return 1;
}
if (pthread_mutex_init(&lockScreen, 0) != 0)
{
printf("\\n mutex screen init failed\\n");
return 1;
}
pthread_create(&thread0, 0, thread_prime_factors, 0);
pthread_create(&thread1, 0, thread_prime_factors, 0);
pthread_join(thread0, 0);
pthread_join(thread1, 0);
pthread_mutex_destroy(&lock);
pthread_mutex_destroy(&lockScreen);
return 0;
}
| 0
|
#include <pthread.h>
static struct ubus_context *ctx = 0;
static const char *ubus_path;
static pthread_t tid[1];
static pthread_mutex_t lock;
static long sleep_time = INTERVAL;
void recalc_sleep_time(bool calc, int toms)
{
long dec = toms * 1000;
if (!calc)
sleep_time = INTERVAL;
else if(sleep_time >= dec)
sleep_time -= dec;
}
static void
system_fd_set_cloexec(int fd)
{
}
static void
quest_ubus_add_fd(void)
{
ubus_add_uloop(ctx);
system_fd_set_cloexec(ctx->sock.fd);
}
static void
quest_ubus_reconnect_timer(struct uloop_timeout *timeout)
{
static struct uloop_timeout retry = {
.cb = quest_ubus_reconnect_timer,
};
int t = 2;
if (ubus_reconnect(ctx, ubus_path) != 0) {
printf("failed to reconnect, trying again in %d seconds\\n", t);
uloop_timeout_set(&retry, t * 1000);
return;
}
printf("reconnected to ubus, new id: %08x\\n", ctx->local_id);
quest_ubus_add_fd();
}
static void
quest_ubus_connection_lost(struct ubus_context *ctx)
{
quest_ubus_reconnect_timer(0);
}
static void
quest_add_object(struct ubus_object *obj)
{
int ret = ubus_add_object(ctx, obj);
if (ret != 0)
fprintf(stderr, "Failed to publish object '%s': %s\\n", obj->name, ubus_strerror(ret));
}
static int
quest_ubus_init(const char *path)
{
uloop_init();
ubus_path = path;
ctx = ubus_connect(path);
if (!ctx)
return -EIO;
printf("connected as %08x\\n", ctx->local_id);
ctx->connection_lost = quest_ubus_connection_lost;
quest_ubus_add_fd();
quest_add_object(&system_object);
quest_add_object(&dropbear_object);
quest_add_object(&usb_object);
quest_add_object(&net_object);
quest_add_object(&network_object);
return 0;
}
void *collect_router_info(void *arg)
{
init_db_hw_config();
load_networks();
collect_system_info();
while (1) {
pthread_mutex_lock(&lock);
calculate_cpu_usage();
populate_clients();
pthread_mutex_unlock(&lock);
get_cpu_usage(0);
usleep(sleep_time);
recalc_sleep_time(0, 0);
get_cpu_usage(1);
}
return 0;
}
int main(int argc, char **argv)
{
const char *path = 0;
int pt;
if(argc > 1 && argv[1] && strlen(argv[1]) > 0){
path = argv[1];
}
if (quest_ubus_init(path) < 0) {
fprintf(stderr, "Failed to connect to ubus\\n");
return 1;
}
if (pthread_mutex_init(&lock, 0) != 0)
{
fprintf(stderr, "Failed to initialize mutex\\n");
return 1;
}
if ((pt = pthread_create(&(tid[0]), 0, &collect_router_info, 0) != 0)) {
fprintf(stderr, "Failed to create thread\\n");
return 1;
}
uloop_run();
pthread_mutex_destroy(&lock);
ubus_free(ctx);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mtx = PTHREAD_MUTEX_INITIALIZER;
extern char ** environ;
static void thread_init(void)
{
pthread_key_create(&key, free);
}
char* _getenv(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mtx);
envbuf = (char *)pthread_getspecific(key);
if(envbuf == 0)
{
envbuf = malloc(50);
if(0 == envbuf)
{
pthread_mutex_unlock(&env_mtx);
return 0;
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for(i = 0; environ[i] != 0; i++)
{
if((strncmp(name, environ[i], len) == 0
&& environ[i][len] == '='))
{
strcpy(envbuf, &environ[i][len+1]);
pthread_mutex_unlock(&env_mtx);
return envbuf;
}
}
pthread_mutex_unlock(&env_mtx);
return 0;
}
int main(void)
{
char name[20] = "HOME";
char *value = _getenv(name);
printf("%s\\n", value);
return 0;
}
| 0
|
#include <pthread.h>
int recurso = 20;
void *consumador() {
int i;
for(i=0;i<10;i++) {
printf("Actualmente recurso es %i\\n", recurso);
recurso--;
usleep(rand() % 5);
}
}
void ejemplo_hilos() {
pthread_t hilo1, hilo2;
pthread_create(&hilo1, 0, consumador, 0);
pthread_create(&hilo2, 0, consumador, 0);
pthread_join(hilo1, 0);
pthread_join(hilo2, 0);
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *consumador_mutex() {
int i;
for(i=0;i<10;i++) {
pthread_mutex_lock(&mutex);
printf("Actualmente recurso es %i\\n", recurso);
recurso--;
pthread_mutex_unlock(&mutex);
usleep(rand() % 5);
}
}
void ejemplo_mutex() {
pthread_t hilo1, hilo2;
pthread_create(&hilo1, 0, consumador_mutex, 0);
pthread_create(&hilo2, 0, consumador_mutex, 0);
pthread_join(hilo1, 0);
pthread_join(hilo2, 0);
}
int cola[10];
int cola_indice = -1;
void *consumador_cola() {
int i;
for(i=0;i<10;i++) {
while(1==1) {
pthread_mutex_lock(&mutex);
if(cola_indice >= 0) {
break;
} else {
pthread_mutex_unlock(&mutex);
usleep((rand() % 5) * 100000);
}
}
printf("Mira! Hay un %i\\n", cola[cola_indice]);
cola_indice--;
pthread_mutex_unlock(&mutex);
}
}
void *generador_cola() {
int i;
for(i=0;i<10;i++) {
pthread_mutex_lock(&mutex);
cola[++cola_indice] = rand() % 100;
pthread_mutex_unlock(&mutex);
usleep((rand() % 5) * 100000);
}
}
void ejemplo_cola() {
pthread_t hilo1, hilo2;
pthread_create(&hilo1, 0, consumador_cola, 0);
pthread_create(&hilo2, 0, generador_cola, 0);
pthread_join(hilo1, 0);
pthread_join(hilo2, 0);
}
int main() {
ejemplo_hilos();
ejemplo_mutex();
ejemplo_cola();
}
| 1
|
#include <pthread.h>
int threadCount;
int loopCount;
} clargs_t;
clargs_t clargs;
pthread_mutex_t ticketGeneratorMutex;
int ticketsAssignedCount = 0;
pthread_cond_t cond;
pthread_mutex_t mutex;
int currentTicket;
} ticket_lock_t;
ticket_lock_t csLock;
void printHelp(){
printf("FIT VUT - POS - project 1 | Jan Kubis\\n");
printf("Usage: ./p1 N M\\n");
printf("(N - number of threads; M - number of loops");
}
int parseArgs(int argc, char* argv[], clargs_t* clargs){
if(argc!=3){
return 1;
}
else if(!isdigit(*argv[1])){
return 1;
}
else if(!isdigit(*argv[2])){
return 1;
}
clargs->threadCount=strtol(argv[1],0,10);
clargs->loopCount=strtol(argv[2],0,10);
return 0;
}
void await(int aenter){
pthread_mutex_lock(&csLock.mutex);
while (aenter != csLock.currentTicket){
pthread_cond_wait(&csLock.cond, &csLock.mutex);
}
pthread_mutex_unlock(&csLock.mutex);
}
void advance(){
pthread_mutex_lock(&csLock.mutex);
csLock.currentTicket++;
pthread_cond_broadcast(&csLock.cond);
pthread_mutex_unlock(&csLock.mutex);
}
int getticket(){
pthread_mutex_lock(&ticketGeneratorMutex);
int nth = ticketsAssignedCount;
ticketsAssignedCount++;
pthread_mutex_unlock(&ticketGeneratorMutex);
return nth;
}
void myNanoSleep(int threadId){
struct timeval tv;
gettimeofday(&tv, 0);
unsigned int time_usec = 1000000 * tv.tv_sec + tv.tv_usec;
unsigned int seed = time_usec * threadId;
struct timespec req, rem;
req.tv_sec = 0;
req.tv_nsec = rand_r(&seed) % 500000000;
nanosleep(&req , &rem);
}
void *threadFunc(void *id_voidptr){
int threadId = *((int *)id_voidptr);
int ticket;
while ((ticket = getticket()) < clargs.loopCount) {
myNanoSleep(threadId);
await(ticket);
printf("%d\\t(%d)\\n", ticket, threadId);
advance();
myNanoSleep(threadId);
}
return 0;
}
int main(int argc, char* argv[]){
int errno = 0;
if((errno=parseArgs(argc,argv,&clargs))!=0){
printHelp();
return errno;
}
pthread_mutex_init(&ticketGeneratorMutex,0);
pthread_mutex_init(&csLock.mutex,0);
pthread_cond_init(&csLock.cond,0);
pthread_t threads[clargs.threadCount];
int t_ids[clargs.threadCount];
for(int i=0; i<clargs.threadCount; i++){
t_ids[i] = i+1;
if(pthread_create(&threads[i], 0, &threadFunc, &t_ids[i])) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for(int i=0; i<clargs.threadCount; i++){
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&ticketGeneratorMutex);
pthread_mutex_destroy(&csLock.mutex);
pthread_cond_destroy(&csLock.cond);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t kran;
pthread_mutex_t kufle;
int l_kl, l_kf, l_kr;
void * watek_klient (void * arg);
int kufle_pobrane = 0;;
int main(){
pthread_t *tab_klient;
int *tab_klient_id;
int i;
printf("\\nLiczba klientow: "); scanf("%d", &l_kl);
printf("%d\\n",l_kl);
printf("\\nLiczba kufli: "); scanf("%d", &l_kf);
printf("%d\\n",l_kf);
l_kr = 1;
printf("Liczba kranow:\\n%d\\n",l_kr);
tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t));
tab_klient_id = (int *) malloc(l_kl*sizeof(int));
for(i=0;i<l_kl;i++) tab_klient_id[i]=i;
printf("Otwieramy pub (simple)!\\n");
printf("Liczba wolnych kufli %d\\n", l_kf);
for(i=0;i<l_kl;i++){
pthread_create(&tab_klient[i], 0, watek_klient, &tab_klient_id[i]);
}
for(i=0;i<l_kl;i++){
pthread_join( tab_klient[i], 0);
}
printf("Zamykamy pub!\\n");
}
void * watek_klient (void * arg_wsk){
int brakkufla=0;
int moj_id = * ((int *)arg_wsk);
int i, j, result=0;
int ile_musze_wypic = 2;
int tr;
printf("Klient %d, wchodzę do pubu\\n", moj_id);
for(i=0; i<ile_musze_wypic; ){
tr = pthread_mutex_trylock(&kufle);
if(tr==0){
if(kufle_pobrane<l_kf){
printf("Klient %d, wybieram kufel (%d podejscie)\\n", moj_id,brakkufla);
brakkufla=0;
kufle_pobrane++;
result=1;
}
else{
result=0;
}
pthread_mutex_unlock(&kufle);
}
j=0;
if(result==1){
pthread_mutex_lock(&kran);
printf("Klient %d, nalewam z kranu %d\\n", moj_id, j);
usleep(300);
pthread_mutex_unlock(&kran);
printf("Klient %d, pije\\n", moj_id);
nanosleep((struct timespec[]){{0, 500000000L}}, 0);
pthread_mutex_lock(&kufle);
printf("Klient %d, odkladam kufel\\n", moj_id);
kufle_pobrane--;
pthread_mutex_unlock(&kufle);
i++;
}
else {
brakkufla++;
}
}
printf("Klient %d, wychodzę z pubu\\n", moj_id);
return(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t full, empty;
buffer_item buffer[5];
int counter;
pthread_t prod[10];
pthread_t cons[10];
pthread_t tid;
pthread_attr_t attr;
void *producer(void *param);
void *consumer(void *param);
void initializeData() {
pthread_mutex_init(&mutex, 0);
sem_init(&full, 0, 0);
sem_init(&empty, 0, 5);
pthread_attr_init(&attr);
counter = 0;
}
void *producer(void *param) {
buffer_item item;
printf("I am the producer\\n");
while(1) {
int rNum = rand() % 5;
sleep(rNum);
item = rand();
sem_wait(&empty);
printf("producer enters the buffer\\n");
pthread_mutex_lock(&mutex);
printf("producer acquires the mutex\\n");
if(insert_item(item)) {
fprintf(stderr, " Producer report error condition\\n");
}
else {
printf("producer produced %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *param) {
buffer_item item;
printf("I am the consumer\\n");
while(1) {
int rNum = rand() % 5;
sleep(rNum);
sem_wait(&full);
printf("consumer enters the buffer\\n");
pthread_mutex_lock(&mutex);
printf("consumer acquires the mutex\\n");
if(remove_item(&item)) {
fprintf(stderr, "Consumer report error condition\\n");
}
else {
printf("consumer consumed %d\\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int insert_item(buffer_item item) {
if(counter < 5) {
buffer[counter] = item;
counter++;
return 0;
}
else {
return -1;
}
}
int remove_item(buffer_item *item) {
if(counter > 0) {
*item = buffer[(counter-1)];
counter--;
return 0;
}
else {
return -1;
}
}
int main(int argc, char *argv[]) {
int i;
if(argc != 4) {
fprintf(stderr, "USAGE:./main.out <INT> <INT> <INT>\\n");
}
int mainSleepTime = atoi(argv[1]);
int numProd = atoi(argv[2]);
int numCons = atoi(argv[3]);
initializeData();
for(i = 0; i < numProd; i++) {
pthread_create(&prod[i],&attr,producer,0);
}
for(i = 0; i < numCons; i++) {
pthread_create(&cons[i],&attr,consumer,0);
}
sleep(mainSleepTime);
printf("Exit the program\\n");
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t exec_mutex;
void *thread_for() {
int i=0;
while(1)
{
pthread_mutex_lock(&exec_mutex);
i++;
pthread_mutex_unlock(&exec_mutex);
}
pthread_exit("Thank you for the CPU time");
}
int main(int argc ,char *argv[]) {
float load = atoi(argv[1])*0.01;
int res;
int load_sample_time=atoi(argv[2]);
int busy_time;
int rest_time;
if(load<=0.5)
{
busy_time=load_sample_time*load;
rest_time=load_sample_time-busy_time;
}
else
{
rest_time=load_sample_time*(1-load);
busy_time=load_sample_time-rest_time;
}
pthread_mutex_init(&exec_mutex,0);
printf("load=%f,busy_time=%d,rest_time=%d\\n",load,busy_time,rest_time);
pthread_mutex_lock(&exec_mutex);
pthread_t for_thread;
res = pthread_create(&for_thread, 0, thread_for, 0);
if (res != 0) {
perror("Thread creation failed");
exit(1);
}
while(1)
{
pthread_mutex_unlock(&exec_mutex);
usleep(busy_time*1000);
pthread_mutex_lock(&exec_mutex);
usleep(rest_time*1000);
}
exit(0);
}
| 1
|
#include <pthread.h>
double widthbase;
int rectxworker;
double private_resultado[NUMWORKERS];
pthread_mutex_t mutex;
double total;
void* suma(void* idt) {
int id = (int)idt;
double base = (double)(rectxworker*id*widthbase);
for (int i = 0; i < rectxworker; i++)
private_resultado[id] += function(base + i*widthbase) * widthbase;
pthread_mutex_lock(&mutex);
total = total + private_resultado[id] ;
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char** argv) {
int low = 0;
int high = 1;
clock_t t1, t2;
int j;
pthread_t tid[NUMWORKERS];
widthbase = (double)(high - low)/(double)MAXRECT;
printf("Width of the base %lf\\n\\n",widthbase);
printf("Number of workers %d\\n", NUMWORKERS);
rectxworker = (int)(MAXRECT/NUMWORKERS);
printf("\\tRectangles per worker %d\\n",rectxworker);
t1 = clock();
for (j = 0; j < NUMWORKERS; j++)
pthread_create(&tid[j],0,&suma,(void*)j);
t2 = clock();
printf("Elapsed time starting threads %f ms\\n",elapsedtime(t1,t2));
t1 = clock();
for (int i = 0; i < NUMWORKERS; i++) {
void *status;
int rc;
rc = pthread_join(tid[i], &status);
if (rc) {
printf("ERROR; retrun code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
t2 = clock();
printf("Elapsed time waiting for threads %f ms\\n",elapsedtime(t1,t2));
printf("\\tTotal: %lf\\n\\n", total);
}
| 0
|
#include <pthread.h>
int *array;
int length, count;
pthread_t *ids;
int length_per_thread;
pthread_mutex_t ex = PTHREAD_MUTEX_INITIALIZER;
void * count3s_thread(void *id){
int i,c = 0;
int start = length_per_thread*(int)id;
int end = start + length_per_thread;
for(i=start; i < end; i++){
if(array[i] == 3){
c++;
}
}
pthread_mutex_lock(&ex);
count+=c;
pthread_mutex_unlock(&ex);
return 0;
}
void count3s(int nthreads){
int i;
for(i=0; i < nthreads; i++){
pthread_create(&ids[i], 0, count3s_thread, (void *)i);
}
for(i=0; i < nthreads; i++){
pthread_join(ids[i], 0);
}
}
int main( int argc, char *argv[]){
int i;
struct timeval s,t;
count = 0;
int n = atoi(argv[1]);
ids = (pthread_t *)malloc(n*sizeof(pthread_t));
length_per_thread = 50*1024*1024 / n;
printf("Using %d threads; length_per_thread = %d\\n", n, length_per_thread);
array= (int *)malloc(50*1024*1024*sizeof(int));
length = 50*1024*1024;
srand(0);
for(i=0; i < length; i++){
array[i] = rand() % 4;
}
gettimeofday(&s, 0);
count3s(n);
gettimeofday(&t, 0);
printf("Count of 3s = %d\\n", count);
printf("Elapsed time (us) = %ld\\n",
(t.tv_sec - s.tv_sec)*1000000 + (t.tv_usec - s.tv_usec));
return 0;
}
| 1
|
#include <pthread.h>
_dataType blank[20];
sem_t sem_product;
sem_t sem_consumer;
pthread_mutex_t mutex_product = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_consumer = PTHREAD_MUTEX_INITIALIZER;
void *product(void *arg)
{
int index = 0;
int count = 0;
while(1)
{
sleep(rand()%5);
sem_wait(&sem_product);
pthread_mutex_lock(&mutex_product);
printf("%d thread id doing\\n",(int )arg);
blank[index++] = count ++;
index %= 20;
pthread_mutex_unlock(&mutex_product);
sem_post(&sem_consumer);
}
pthread_exit((void *)1);
}
void* consumer(void * arg)
{
int index = 0;
while(1)
{
sem_wait(&sem_consumer);
pthread_mutex_lock(&mutex_consumer);
printf("%d thread is consumer ,data%d\\n",(int)arg,blank[index++]);
index %= 20;
pthread_mutex_unlock(&mutex_consumer);
sem_post(&sem_product);
}
pthread_exit((void*)1);
}
int main()
{
pthread_t tid1,tid2,tid3,tid4;
sem_init(&sem_product,0,20);
sem_init(&sem_consumer,0,0);
pthread_create(&tid1,0,product,0);
pthread_create(&tid1,0,product,0);
pthread_create(&tid3,0,consumer,0);
pthread_create(&tid4,0,consumer,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
pthread_join(tid4,0);
sem_destroy(&sem_product);
sem_destroy(&sem_consumer);
pthread_mutex_destroy(&mutex_product);
pthread_mutex_destroy(&mutex_consumer);
return 0;
}
| 0
|
#include <pthread.h>
uint32_t COUNTER;
pthread_mutex_t LOCK;
pthread_mutex_t START;
pthread_cond_t CONDITION;
void * threads (
void * unused
) {
pthread_mutex_lock(&START);
pthread_mutex_unlock(&START);
pthread_mutex_lock(&LOCK);
if (COUNTER > 0) {
pthread_cond_signal(&CONDITION);
}
for (;;) {
COUNTER++;
pthread_cond_wait(&CONDITION, &LOCK);
pthread_cond_signal(&CONDITION);
}
phthread_mutex_unlock(&LOCK);
}
int64_t timeInMS ()
{
struct timeval t;
gettimeofday(&t, 0);
return (
(int64_t)t.tv_sec * 1000 +
(int64_t)t.tv_usec / 1000
);
}
int main (
int argc,
char ** argv
) {
int64_t start;
pthread_t t1;
pthread_t t2;
int64_t myTime;
pthread_mutex_init(&LOCK, 0);
pthread_mutex_init(&START, 0);
pthread_cond_init(&CONDITION, 0);
pthread_mutex_lock(&START);
COUNTER = 0;
pthread_create(&t1, 0, threads, 0);
pthread_create(&t2, 0, threads, 0);
pthread_detach(t1);
pthread_detach(t2);
myTime = timeInMS();
pthread_mutex_unlock(&START);
sleep(1);
pthread_mutex_lock(&LOCK);
myTime = timeInMS() - myTime;
COUNTER = (uint32_t)(((uint64_t)COUNTER * 1000) / myTime);
printf("Number of thread switches in about one second was %u\\n", COUNTER);
return 0;
}
| 1
|
#include <pthread.h>
int state = 0;
int isFullShop = 0;
int noCustomer = 0;
int isChair = 0;
int num_chair = 0;
int noMoreCustomer = 10;
pthread_cond_t free_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t wake_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cut_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t next_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t work_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t work_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t do_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t state_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t state1_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t shop_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t c_pthread[10];
pthread_t b_pthread;
void *customer (void*);
void *barber (void*);
int main (int argc, char** argv)
{
int i;
pthread_create(&b_pthread, 0, barber, 0);
for(i = 0; i < 10; i++){
pthread_create(&c_pthread[i], 0, customer, (void *)(intptr_t)i);
}
for(i = 0; i < 10; i++){
pthread_join(c_pthread[i], 0);
}
noCustomer = 1;
printf("rrr");
pthread_join(b_pthread, 0);
return 0;
}
void *barber (void* a)
{
while(noCustomer == 0){
if(state == 0){
pthread_cond_wait(&wake_cond, &state_mutex);
state = 1;
printf("Barber: wake up.\\n");
pthread_mutex_unlock(&state_mutex);
pthread_cond_signal(&work_cond);
}
pthread_cond_wait(&cut_cond, &work_mutex);
printf("Barber: cut hair..\\n");
pthread_mutex_unlock(&work_mutex);
pthread_cond_signal(&free_cond);
if(state == 0 && noMoreCustomer == 0){
break;
}
}
pthread_exit(0);
}
void *customer (void* a)
{
pthread_mutex_lock(&state1_mutex);
if(state == 0){
pthread_mutex_lock(&state_mutex);
printf("Customer[%d]: waking barber up\\n", a);
pthread_cond_signal(&wake_cond);
pthread_cond_wait(&work_cond, &state_mutex);
pthread_mutex_unlock(&state_mutex);
}
pthread_mutex_unlock(&state1_mutex);
pthread_mutex_lock(&shop_mutex);
if(isFullShop == 1){
noMoreCustomer--;
printf("Customer[%d]: exit full shop.\\n", a);
pthread_mutex_unlock(&shop_mutex);
pthread_exit(0);
}
if(num_chair < 5){
num_chair++;
noMoreCustomer--;
printf("Customer[%d]: enter shop.\\n", a);
if(num_chair == 5){
isFullShop = 1;
}
}
pthread_mutex_unlock(&shop_mutex);
pthread_mutex_lock(&do_mutex);
if(num_chair > 1){
pthread_cond_wait(&next_cond, &do_mutex);
}
sleep(1);
printf("Customer[%d]: get hair cut.\\n", a);
sleep(2);
pthread_cond_signal(&cut_cond);
pthread_cond_wait(&free_cond, &do_mutex);
printf("Customer[%d]: done hair cut and exit.\\n", a);
pthread_mutex_lock(&shop_mutex);
num_chair--;
if(isFullShop == 1){
isFullShop = 0;
}
if(num_chair == 0){
state = 0;
printf("Barber: sleeping.\\n");
if(noMoreCustomer == 0){
printf("No more customer.\\n");
raise(SIGINT);
}
}
pthread_mutex_unlock(&shop_mutex);
pthread_cond_signal(&next_cond);
pthread_mutex_unlock(&do_mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int buffer=0;
sem_t empty_sem;
sem_t full_sem;
pthread_mutex_t mutex;
void *product(){
while (1) {
sem_wait(&empty_sem);
pthread_mutex_lock(&mutex);
printf("生产了一个东西\\n" );
buffer=1;
pthread_mutex_unlock(&mutex);
sem_post(&full_sem);
}
}
void *consumer(){
while (1) {
sem_wait(&full_sem);
pthread_mutex_lock(&mutex);
printf("消费了一个东西\\n");
buffer=0;
pthread_mutex_unlock(&mutex);
sem_post(&empty_sem);
}
}
int main(void) {
pthread_t id1;
pthread_t id2;
int ret1;
int ret2;
int ini1=sem_init(&empty_sem,0,1);
int ini2=sem_init(&full_sem,0,0);
if (ini1!=0&&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);
}
ret1=pthread_create(&id1,0,product,0);
if(ret1!=0) printf("failed\\n");
ret2=pthread_create(&id2,0,consumer,0);
if(ret2!=0) printf("failed\\n");
pthread_join(id1,0);
pthread_join(id2,0);
return 0;
}
| 1
|
#include <pthread.h>
int Number;
pthread_mutex_t *pfork;
int *state;
void *EatMeal();
void GetArg(
char* argv[] ,
int* number
);
void main(int argc, char* argv[])
{
int k =0;
while(k<1)
{
int option_index = 0;
int rvalue = 0;
struct option long_option[] = {
{"normal",0,0,0 },
{"method1",0,0,0},
{"method2",0,0,0}
};
rvalue = getopt_long_only(argc,argv, "a:bc::", long_option,&option_index);
switch(option_index)
{
case 0 : printf("%s\\n",long_option[option_index].name);
break;
case 1 : printf("%s\\n",long_option[option_index].name);
break;
case 2 : printf("%s\\n",long_option[option_index].name);
break;
}
k++;
}
GetArg(argv, &Number);
pfork = malloc(Number*sizeof(pthread_mutex_t));
state = malloc(Number*sizeof(int));
pthread_t philosopher[Number];
int i;
for( i = 0; i < Number; i++)
{
pthread_mutex_init(&pfork[i],0);
}
for( i = 0; i < Number; i++)
{
int j = i;
pthread_create(&philosopher[i], 0, EatMeal, &j);
printf("I am philosopher %d\\n", j);
}
for( i=0; i < Number; i++)
{
pthread_join(philosopher[i], 0);
}
pthread_exit(0);
return ;
}
void *EatMeal(int *i)
{
int id = *i;
state[id] = 1;
int leftFork = (id + Number -1) % Number;
int rightFork = (id + Number +1) % Number;
int mealTime = 5;
int mymealTime = 0;
while (mymealTime < mealTime)
{
if(state[id] == 1)
{
printf("Philosopher %d is thinking\\n", id);
sleep(1);
state[id] = 2;
}else if(state[id] == 2)
{
printf("Philosopher %d is Trying\\n", id);
sleep(1);
pthread_mutex_lock(&pfork[leftFork]);
pthread_mutex_lock(&pfork[rightFork]);
state[id] = 3;
}
else
{
printf("Philosopher %d is Eating\\n", id);
sleep(1);
mymealTime++;
pthread_mutex_unlock(&pfork[leftFork]);
pthread_mutex_unlock(&pfork[rightFork]);
}
}
}
void GetArg(
char * argv[],
int* number
)
{
*number = strtol(argv[1], 0, 10);
}
| 0
|
#include <pthread.h>
int buffer[3];
int add = 0;
int rem = 0;
int num = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_reader = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_writer = PTHREAD_COND_INITIALIZER;
void *writer (void *param);
void *reader (void *param);
int main(int argc, char *argv[])
{
pthread_t tid1, tid2;
int i;
if(pthread_create(&tid1, 0, writer, 0) != 0) {
fprintf(stderr,"Unable to create writer thread\\n");
exit(1);
}
if(pthread_create(&tid2, 0, reader, 0) != 0) {
fprintf(stderr, "Unable to create reader thread\\n");
exit(1);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
void *writer(void *param)
{
int i;
for(i = 0; i <= 20; i++) {
pthread_mutex_lock(&m);
if(num > 3) {
exit(1);
}
while(num == 3) {
pthread_cond_wait(&c_writer, &m);
}
buffer[add] = i;
add = (add + 1) % 3;
num++;
pthread_mutex_unlock(&m);
pthread_cond_signal(&c_reader);
printf("writer: wrote to buffer = %d\\n", i);
fflush(stdout);
}
return 0;
}
void *reader(void *param)
{
int i;
while(1) {
pthread_mutex_lock(&m);
if(num < 0) {
exit(1);
}
while(num == 0) {
pthread_cond_wait(&c_reader, &m);
}
i = buffer[rem];
rem = (rem + 1) % 3;
num--;
pthread_mutex_unlock(&m);
pthread_cond_signal(&c_writer);
if(i == 20) {
pthread_exit(0);
}
printf("read: read from buffer = %d\\n", i);
fflush(stdout);
}
return 0;
}
| 1
|
#include <pthread.h>
const static char east[] = "east";
const static char west[] = "west";
const static char car[] = "car";
const static char truck[] = "truck";
int static unsigned number_of_cars;
const static char* bridge_direction;
pthread_mutex_t static bridge_lock;
pthread_mutex_t static count_lock;
pthread_cond_t static cond;
int id;
const char* type;
const char* direction;
} vehicle;
void create_vehicles( vehicle* const v )
{
if( 3 > 10 ){
fprintf( stderr, "TRUCKS must be less than THREADS\\n" );
exit( 1 );
}
int unsigned counter, car_id = 0;
for( counter = 0 ; counter < 10 ; counter++ ){
if( counter < 3 ){
v[counter].type = truck;
v[counter].id = counter;
} else {
v[counter].type = car;
v[counter].id = car_id;
car_id++;
}
if( ( counter % 2 ) == 0 ){
v[counter].direction = east;
} else {
v[counter].direction = west;
}
}
}
void* cars( void* const ptr )
{
const vehicle v = *( (vehicle*)ptr );
sleep( rand() % 20 );
if( 0 ){
printf( "%s %d has arrived at the bridge travelling %s bridge direction is %s\\n", v.type, v.id, v.direction, bridge_direction );
}
pthread_mutex_lock( &count_lock );
if( !( bridge_direction == v.direction ) && !( number_of_cars == 0) ){
pthread_cond_wait( &cond, &count_lock );
}
number_of_cars++;
if( number_of_cars == 1 ){
pthread_mutex_lock( &bridge_lock );
bridge_direction = v.direction;
}
pthread_mutex_unlock( &count_lock );
printf( "%s %d going %s on the bridge\\n", v.type, v.id, v.direction );
sleep( 4 );
printf( "%s %d going %s off the bridge\\n", v.type, v.id, v.direction );
pthread_mutex_lock( &count_lock );
number_of_cars--;
if( number_of_cars == 0 ){
if( 0 )
printf( "%s %d switching bridge direction..\\n", v.type, v.id );
if( bridge_direction == east ){
bridge_direction = west;
} else {
bridge_direction = east;
}
pthread_cond_broadcast( &cond );
pthread_mutex_unlock( &bridge_lock );
}
pthread_mutex_unlock( &count_lock );
pthread_exit( 0 );
}
void* trucks( void* const ptr )
{
const vehicle v = *( (vehicle*)ptr );
sleep( rand() % 20 );
if( 0 ){
printf( "%s %d has arrived at the bridge travelling %s bridge"
" direction is %s\\n", v.type, v.id, v.direction, bridge_direction );
}
pthread_mutex_lock( &bridge_lock );
bridge_direction = v.direction;
printf( "%s %d going %s on the bridge\\n", v.type, v.id, v.direction );
sleep( 4 );
printf( "%s %d going %s off the bridge\\n", v.type, v.id, v.direction );
pthread_mutex_unlock( &bridge_lock );
pthread_exit( 0 );
}
int main( int argc, char* argv[] )
{
int unsigned i;
pthread_t* threads;
vehicle* vehicle_data;
srand( time( 0 ) );
bridge_direction = east;
if( ( pthread_mutex_init( &count_lock, 0 ) ) != 0 ){
fprintf( stderr, "count_lock initialization failed!\\n" );
}
if( ( pthread_mutex_init( &bridge_lock, 0 ) ) != 0 ){
fprintf( stderr, "bridge_lock initialization failed!\\n" );
}
if( ( pthread_cond_init( &cond, 0 ) ) != 0 ){
fprintf( stderr, "condition variable initialization failed\\n" );
}
threads = (pthread_t*)calloc( 10, sizeof( pthread_t ) );
vehicle_data = (vehicle*)calloc( 10, sizeof( vehicle ) );
if( ( vehicle_data == 0 ) || ( threads == 0 ) ){
fprintf( stderr, "calloc failed, sorry!\\n" );
}
create_vehicles( vehicle_data );
for( i = 0 ; i < 10 ; i++ ){
if( vehicle_data[i].type == truck ){
if( ( pthread_create( &threads[i], 0, trucks, &vehicle_data[i] ) ) != 0 ){
fprintf( stderr, "Thread creation failed!\\n" );
}
} else {
if( ( pthread_create( &threads[i], 0, cars, &vehicle_data[i] ) ) != 0 ){
fprintf( stderr, "Thread creation failed!\\n" );
}
}
if( 0 ){
printf( "Main thread: thread %d created.\\n", i );
}
}
for( i = 0 ; i < 10 ; i++ ){
if( ( pthread_join( threads[i], 0 ) ) != 0 ){
fprintf( stderr, "Join failed!\\n" );
}
}
if( ( pthread_cond_destroy( &cond ) ) != 0 ){
printf( "Could not destroy condition variable!\\n" );
}
if( ( pthread_mutex_destroy( &count_lock ) ) != 0 ){
printf( "Cound not destroy count mutex!\\n" );
}
if( ( pthread_mutex_destroy( &bridge_lock ) ) != 0 ){
printf( "Could not destroy bridge mutex!\\n" );
}
free( threads );
free( vehicle_data );
exit( 0 );
}
| 0
|
#include <pthread.h>
void err_quit(const char *api);
void thread_fun(void *arg);
void cnt_plus_one();
int global = 0;
pthread_mutex_t mutex;
int main()
{
if(pthread_mutex_init(&mutex, 0) < 0)
err_quit("pthread_mutex_init");
int i = 0;
for(i = 0; i < 3; i++)
{
pthread_t th;
if(pthread_create(&th, 0, (void *)thread_fun, 0) != 0)
err_quit("pthread_create");
}
while(1)
{
pthread_mutex_lock(&mutex);
if(global > 5000000)
break;
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
void err_quit(const char *api)
{
perror(api);
exit(1);
}
void thread_fun(void *arg)
{
int retval;
pthread_t tid = pthread_self();
pthread_detach(tid);
while(1)
{
cnt_plus_one();
}
printf("tid->%ld exit\\n", tid);
pthread_exit(&retval);
}
void cnt_plus_one()
{
pthread_mutex_lock(&mutex);
global++;
printf("global=%d\\n", global);
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
const int MAX_THREADS = 64;
int thread_count, message_avaliable;
pthread_mutex_t mutex;
void Usage(char* prog_name);
void *Hello(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
if (argc != 2) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0 || thread_count > MAX_THREADS) Usage(argv[0]);
message_avaliable = 0;
thread_handles = malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
Hello, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
free(thread_handles);
return 0;
}
void *Hello(void* rank) {
long my_rank = (long) rank;
while (1) {
pthread_mutex_lock(&mutex);
if(message_avaliable == 0){
printf("Produtor %li criou mensagem\\n",my_rank);
message_avaliable = 1;
pthread_mutex_unlock(&mutex);
break;
}else{
printf("Consumidor %li imprimiu mensagem\\n",my_rank);
message_avaliable = 0;
pthread_mutex_unlock(&mutex);
break;
}
}
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads>\\n", prog_name);
fprintf(stderr, "0 < number of threads <= %d\\n", MAX_THREADS);
exit(0);
}
| 0
|
#include <pthread.h>
struct Node {
char buf[(1024)];
struct Node *next;
};
struct Queue {
pthread_mutex_t mutex;
pthread_cond_t not_empty, not_full;
int count;
struct Node *head, *tail;
};
void queue_init(struct Queue *q) {
pthread_mutex_init(&q->mutex, 0);
pthread_cond_init(&q->not_empty, 0);
pthread_cond_init(&q->not_full, 0);
q->count = 0;
q->head = q->tail = 0;
}
struct Node *queue_dequeue(struct Queue *q) {
struct Node *cur;
assert(q->count > 0);
--q->count;
cur = q->head;
q->head = cur->next;
cur->next = 0;
if (q->count == 0)
q->tail = 0;
return cur;
}
void queue_enqueue(struct Queue *q, struct Node *n) {
assert(q->count < (1024));
++q->count;
if (q->count == 1) {
q->head = q->tail = n;
} else {
q->tail->next = n;
q->tail = n;
}
}
struct Queue tasks;
void *producer(void *arg) {
long n_blocks = (long)arg;
long i;
for (i = 0; i < n_blocks; ++i) {
struct Node *node = (struct Node *)malloc(sizeof(struct Node));
int j;
node->next = 0;
for (j = 0; j < (1024); ++j)
node->buf[j] = rand() % 26 + 'a';
pthread_mutex_lock(&tasks.mutex);
while (tasks.count >= (1024))
pthread_cond_wait(&tasks.not_full, &tasks.mutex);
queue_enqueue(&tasks, node);
pthread_mutex_unlock(&tasks.mutex);
pthread_cond_signal(&tasks.not_empty);
}
return 0;
}
void *consumer(void *arg) {
long n_blocks = (long)arg;
char result = 0;
long i;
for (i = 0; i < n_blocks; ++i) {
int j;
struct Node *node;
pthread_mutex_lock(&tasks.mutex);
while (tasks.count == 0)
pthread_cond_wait(&tasks.not_empty, &tasks.mutex);
node = queue_dequeue(&tasks);
pthread_mutex_unlock(&tasks.mutex);
pthread_cond_signal(&tasks.not_full);
for (j = 0; j < (1024); ++j)
result += node->buf[j];
free(node);
}
printf("result = %d\\n", (int)result);
return 0;
}
int main(int argc, char *argv[]) {
long n_blocks;
pthread_t t_producer, t_consumer;
assert(argc > 1);
n_blocks = atol(argv[1]);
queue_init(&tasks);
pthread_create(&t_producer, 0, producer, (void *)n_blocks);
pthread_create(&t_consumer, 0, consumer, (void *)n_blocks);
pthread_join(t_producer, 0);
pthread_join(t_consumer, 0);
return 0;
}
| 1
|
#include <pthread.h>
static void delay_ms(const int ms)
{
struct timespec ts;
assert(ms >= 0);
ts.tv_sec = ms / 1000;
ts.tv_nsec = (ms % 1000) * 1000 * 1000;
nanosleep(&ts, 0);
}
int main(int argc, char** argv)
{
int interval = 0;
int optchar;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
pthread_rwlock_t rwlock;
while ((optchar = getopt(argc, argv, "i:")) != EOF)
{
switch (optchar)
{
case 'i':
interval = atoi(optarg);
break;
default:
fprintf(stderr, "Usage: %s [-i <interval time in ms>].\\n", argv[0]);
break;
}
}
fprintf(stderr, "Locking mutex ...\\n");
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&mutex, &mutexattr);
pthread_mutexattr_destroy(&mutexattr);
pthread_mutex_lock(&mutex);
delay_ms(interval);
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_destroy(&mutex);
fprintf(stderr, "Locking rwlock exclusively ...\\n");
pthread_rwlock_init(&rwlock, 0);
pthread_rwlock_wrlock(&rwlock);
delay_ms(interval);
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_destroy(&rwlock);
fprintf(stderr, "Locking rwlock shared ...\\n");
pthread_rwlock_init(&rwlock, 0);
pthread_rwlock_rdlock(&rwlock);
delay_ms(interval);
pthread_rwlock_rdlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
pthread_rwlock_destroy(&rwlock);
fprintf(stderr, "Done.\\n");
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>
int q[4];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 4)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 4);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[6];
int sorted[6];
void producer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = findmaxidx (source, 6);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 6; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 6);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 6; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t tid[2];
int counter;
pthread_mutex_t lock;
void* doSomeThing(void *arg)
{
pthread_mutex_lock(&lock);
unsigned long i = 0;
counter += 1;
printf("\\n Job %d started\\n", counter);
for(i=0; i<(0xFFFFFFFF);i++);
printf("\\n Job %d finished\\n", counter);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
int i = 0;
int err;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
while(i < 2)
{
err = pthread_create(&(tid[i]), 0, &doSomeThing, 0);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
i++;
}
pthread_join(tid[0], 0);
pthread_join(tid[1], 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_cond_t onOahu;
pthread_cond_t onBoat;
pthread_cond_t onMolo;
int boatLoc;
int kidsOnBoard;
int adultsOnBoard;
int lastCrossed;
void init() {
pthread_mutex_init(&lock, 0);
pthread_cond_init(&allReady, 0);
pthread_cond_init(&mayStart, 0);
pthread_cond_init(&allDone, 0);
pthread_cond_init(&onOahu, 0);
pthread_cond_init(&onBoat, 0);
pthread_cond_init(&onMolo, 0);
boatLoc = OAHU;
lastCrossed = ADULT;
kidsOnBoard = 0;
adultsOnBoard = 0;
}
void* childThread(void* args) {
pthread_mutex_lock(&lock);
kidsOahu++;
pthread_cond_signal(&allReady);
while (!start) {
pthread_cond_wait(&mayStart, &lock);
}
while(kidsOahu != 0) {
while(adultsOahu != 0) {
while (boatLoc == MOLO || kidsOnBoard == 2 || adultsOnBoard == 1 || lastCrossed == KID) {
pthread_cond_wait(&onOahu, &lock);
}
boardBoat(KID, OAHU);
kidsOahu--;
kidsOnBoard++;
if (kidsOnBoard == 1) {
while (boatLoc == OAHU) {
pthread_cond_wait(&onBoat, &lock);
}
boatCross(MOLO, OAHU);
boatLoc = OAHU;
leaveBoat(KID, OAHU);
kidsOnBoard--;
kidsOahu++;
pthread_cond_signal(&onOahu);
} else {
boatCross(OAHU, MOLO);
lastCrossed = KID;
boatLoc = MOLO;
leaveBoat(KID, MOLO);
printf("got off");
fflush(stdout);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
if(adultsOahu != 0) {
printf("there are stil adults");
fflush(stdout);
while (boatLoc == OAHU || lastCrossed == KID || adultsOnBoard != 0 || kidsOnBoard != 0) {
pthread_cond_wait(&onMolo, &lock);
}
boardBoat(KID, MOLO);
kidsOnBoard++;
boatCross(MOLO, OAHU);
boatLoc = OAHU;
}
pthread_cond_signal(&onOahu);
}
}
while(boatLoc == MOLO || kidsOnBoard > 2) {
pthread_cond_wait(&onOahu, &lock);
}
boardBoat(KID, OAHU);
kidsOahu--;
kidsOnBoard++;
if(kidsOnBoard == 1) {
while(boatLoc == OAHU) {
pthread_cond_wait(&onBoat, &lock);
}
if(kidsOahu == 0) {
leaveBoat(KID, MOLO);
pthread_cond_signal(&allDone);
}
boatCross(MOLO, OAHU);
boatLoc = OAHU;
pthread_cond_signal(&onOahu);
} else {
boatCross(OAHU, MOLO);
boatLoc = MOLO;
leaveBoat(KID, MOLO);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
}
}
pthread_cond_signal(&allDone);
pthread_mutex_unlock(&lock);
return 0;
}
void* adultThread(void* args) {
pthread_mutex_lock(&lock);
adultsOahu++;
pthread_cond_signal(&allReady);
while (!start) {
pthread_cond_wait(&mayStart, &lock);
}
while(boatLoc == MOLO || kidsOnBoard > 0 || adultsOnBoard > 0 || lastCrossed == ADULT) {
pthread_cond_wait(&onOahu, &lock);
}
boardBoat(ADULT, OAHU);
adultsOnBoard++;
adultsOahu--;
boatCross(OAHU, MOLO);
boatLoc = MOLO;
lastCrossed = ADULT;
leaveBoat(ADULT, MOLO);
adultsOnBoard--;
pthread_cond_signal(&onMolo);
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.