text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int fd;
int flag=0;
pthread_mutex_t lock;
pthread_t even_thd,odd_thd;
pthread_cond_t cond;
void attr_func(pthread_attr_t *attr)
{
int ret=pthread_attr_init(attr);
if(ret!=0)
perror("pthread_attr_init");
ret=pthread_attr_setdetachstate(attr,PTHREAD_CREATE_JOINABLE);
if(ret!=0)
perror("pthread_attr_setdeatchstate");
}
void * even( )
{
char a='A';
int i=0;
while(i<5)
{
if(flag==0)
{
printf("even\\n");
pthread_mutex_lock(&lock);
write(fd,&a,1);
a++;
i++;
flag=1;
pthread_mutex_unlock(&lock);
}
}
}
void * odd( )
{
char a='0';
int i=0,s=2;
while(i<5)
{
if(flag)
{
printf("odd\\n");
pthread_mutex_lock(&lock);
write(fd,&a,1);
a++;
i++;
pthread_mutex_unlock(&lock);
flag=0;
}
}
}
int main()
{
pthread_attr_t attr;
if(pthread_mutex_init(&lock,0)!=0)
{
perror("init");
exit(0);
}
pthread_cond_init (&cond , 0);
printf("%s_Thread_running\\n",__func__);
fd=open("even_oddfile",O_CREAT|O_RDWR|O_TRUNC);
if(fd==-1)
{
perror("open");
exit(1);
}
attr_func(&attr);
pthread_create(&even_thd,&attr,even,0);
pthread_create(&odd_thd,&attr,odd,0);
pthread_join(even_thd,0);
pthread_join(odd_thd,0);
printf("%s_Thread_exiting\\n",__func__);
return 0;
}
| 1
|
#include <pthread.h>
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1)) {
fprintf(stderr, "Bug found!\\n");
ERROR: goto ERROR;
;
}
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
if (argc != 1) {
if (argc != 3) {
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
} else {
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0))) {
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 0
|
#include <pthread.h>
const char *stristr(const char *haystack, const char *needle)
{
if(!*needle)
return haystack;
for(; *haystack; ++haystack) {
if(toupper(*haystack) == toupper(*needle)) {
const char *h, *n;
for (h = haystack, n = needle; *h && *n; ++h, ++n) {
if(toupper(*h) != toupper(*n))
break;
}
if (!*n)
return haystack;
}
}
return 0;
}
char *random_string(char *buf, size_t size)
{
long val[4];
int x;
for (x = 0; x < 4; x++)
val[x] = random();
snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
return buf;
}
unsigned long int msrp_new_identifier()
{
pthread_mutex_lock(&counter_lock);
counter++;
pthread_mutex_unlock(&counter_lock);
return counter;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(20)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(20)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (20))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (20))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (20))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((20)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(20); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
int head = 0;
int tail = 0;
int size = 0;
char queue [8][1023];
void inc(int* posi) {
if (*posi + 1 == 8) {
*posi = 0;
}
else {
++*posi;
}
}
void *send_msg(void* arg) {
int fake_tid = *(int*) arg;
int cnt = 0;
char buff [1023];
do {
pthread_mutex_lock (&queue_mutex);
if (size != 8) {
++cnt;
sprintf(buff, "time: %4d iter: %d tid: %d",
(int) clock(), cnt, fake_tid);
strcpy(queue[head], buff);
inc(&head);
++size;
}
else {
printf("Queue full, tid: %d\\n", fake_tid);
}
pthread_mutex_unlock (&queue_mutex);
usleep(rand() % 977 + 1);
} while (cnt < 5);
return 0;
}
void *read_msg(void* arg) {
int fake_tid = *(int*) arg;
int cnt = 0;
while(cnt < 3) {
pthread_mutex_lock (&queue_mutex);
if (size > 0) {
++cnt;
printf("%s\\n", queue[tail]);
inc(&tail);
--size;
}
else {
printf("Queue empty, tid: %d\\n", fake_tid);
}
pthread_mutex_unlock (&queue_mutex);
usleep(rand() % 13254 + 1);
}
return 0;
}
int fake_tid1 = 1;
int fake_tid2 = 2;
int fake_tid3 = 3;
int fake_tid4 = 4;
int fake_tid5 = 5;
int fake_tid6 = 6;
int fake_tid7 = 7;
int fake_tid8 = 8;
int main(int argc, char **argv) {
srand (time(0));
pthread_t thread1_id;
pthread_t thread2_id;
pthread_t thread3_id;
pthread_t thread4_id;
pthread_t thread5_id;
pthread_t thread6_id;
pthread_t thread7_id;
pthread_t thread8_id;
pthread_create (&thread1_id, 0, &send_msg, (void*)&fake_tid1);
pthread_create (&thread2_id, 0, &send_msg, (void*)&fake_tid2);
pthread_create (&thread3_id, 0, &send_msg, (void*)&fake_tid3);
pthread_create (&thread4_id, 0, &read_msg, (void*)&fake_tid4);
pthread_create (&thread5_id, 0, &read_msg, (void*)&fake_tid5);
pthread_create (&thread6_id, 0, &read_msg, (void*)&fake_tid6);
pthread_create (&thread7_id, 0, &read_msg, (void*)&fake_tid7);
pthread_create (&thread8_id, 0, &read_msg, (void*)&fake_tid8);
pthread_join (thread1_id, 0);
pthread_join (thread2_id, 0);
pthread_join (thread3_id, 0);
pthread_join (thread4_id, 0);
pthread_join (thread5_id, 0);
pthread_join (thread6_id, 0);
pthread_join (thread7_id, 0);
pthread_join (thread8_id, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct jc_type_file_rand_null {
struct jc_type_file_comm_hash *comm_hash;
};
static struct jc_type_file_rand_null global_null;
static int jc_type_file_rand_null_init( struct jc_comm *jcc
)
{
return global_null.comm_hash->init(global_null.comm_hash, jcc);
}
static int
jc_type_file_rand_null_execute(
struct jc_comm *jcc
)
{
return global_null.comm_hash->execute(global_null.comm_hash, jcc);
}
static int
jc_type_file_rand_null_copy(
unsigned int data_num
)
{
return global_null.comm_hash->copy(global_null.comm_hash, data_num);
}
static int
jc_type_file_rand_null_comm_init(
struct jc_type_file_comm_node *fcn
)
{
srand(time(0));
return JC_OK;
}
static int
jc_type_file_rand_null_comm_copy(
struct jc_type_file_comm_node *fcn,
struct jc_type_file_comm_var_node *cvar
)
{
return JC_OK;
}
static char *
jc_type_file_rand_null_comm_execute(
char separate,
struct jc_type_file_comm_node *fsn,
struct jc_type_file_comm_var_node *svar
)
{
if (svar->last_val)
free(svar->last_val);
pthread_mutex_lock(&svar->mutex);
svar->last_val = jc_file_val_get(fsn->col_num,
random() % svar->line_num,
separate, svar->cur_ptr,
&svar->cur_ptr);
pthread_mutex_unlock(&svar->mutex);
return svar->last_val;
}
static int
jc_type_file_rand_null_comm_destroy(
struct jc_type_file_comm_node *fcn
)
{
}
static int
jc_type_file_rand_null_comm_var_destroy(
struct jc_type_file_comm_var_node *cvar
)
{
}
int
json_type_file_rand_null_uninit()
{
struct jc_type_file_manage_oper oper;
struct jc_type_file_comm_hash_oper comm_oper;
memset(&comm_oper, 0, sizeof(comm_oper));
comm_oper.comm_hash_execute = jc_type_file_rand_null_comm_execute;
comm_oper.comm_hash_init = jc_type_file_rand_null_comm_init;
comm_oper.comm_hash_copy = jc_type_file_rand_null_comm_copy;
comm_oper.comm_node_destroy = jc_type_file_rand_null_comm_destroy;
comm_oper.comm_var_node_destroy =
jc_type_file_rand_null_comm_var_destroy;
global_null.comm_hash =
jc_type_file_comm_create(0, 0, &comm_oper);
if (!global_null.comm_hash)
return JC_ERR;
memset(&oper, 0, sizeof(oper));
oper.manage_init = jc_type_file_rand_null_init;
oper.manage_copy = jc_type_file_rand_null_copy;
oper.manage_execute = jc_type_file_rand_null_execute;
return jc_type_file_rand_module_add("rand_null", &oper);
}
int
json_type_file_rand_null_init()
{
if (global_null.comm_hash)
return jc_type_file_comm_destroy(global_null.comm_hash);
return JC_OK;
}
| 0
|
#include <pthread.h>
void *Allen(void *arg);
void *Bob(void *arg);
pthread_mutex_t book1;
pthread_mutex_t book2;
pthread_cond_t Allenfinish;
int main() {
pthread_t tid1, tid2;
pthread_create(&tid1, 0, &Allen, 0);
pthread_create(&tid2, 0, &Bob, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
void *Allen(void *arg) {
pthread_mutex_lock(&book1);
sleep(5);
pthread_mutex_lock(&book2);
printf("Allen has collected all books he need, he is going to do homework!\\n");
sleep(5);
printf("Allen has finished his homework, he has returned all books he borrowed!\\n");
pthread_mutex_unlock(&book2);
pthread_mutex_unlock(&book1);
pthread_cond_signal(&Allenfinish);
}
void *Bob(void *arg) {
pthread_mutex_lock(&book2);
pthread_cond_wait(&Allenfinish, &book2);
printf("Bob knows he can borrow those two books now!\\n");
pthread_mutex_lock(&book1);
sleep(5);
printf("Bob has finished his homework now!\\n");
pthread_mutex_unlock(&book1);
pthread_mutex_unlock(&book2);
}
| 1
|
#include <pthread.h>
struct foo *fp[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITILIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo *foo_alloc(void)
{
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
fp = 0;
return (0);
}
idx = (((unsigned int)fp) % 29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return (fp);
}
void foo_hold(struct foo *fp)
{
pthread_mutex_lock(&hashlock);
fp->f_count++;
pthread_mutex_unlock(&hashlock);
}
struct foo *foo_find(int id)
{
struct foo *fp;
int idx;
idx = (((unsigned int)fp) % 29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
++fp->f_count;
break;
}
}
pthread_mutex_unlock(&hashlock);
return (fp);
}
void foo_rele(struct foo *fp)
{
struct foo *tfp;
int idx;
pthread_mutex_lock(&hashlock);
if (0 == --fp->f_count) {
idx = (((unsigned int)fp) % 29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
}
else {
while (tfp->f_next != fp) {
tfp = tfp->f_next;
}
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else {
pthread_mutex_unlock(&hashlock);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t sumLock;
int numWorkers;
int numArrived = 0;
int sums = 0;
int maxInd[3] = {0, 0, 0};
int minInd[3] = {32767, 0, 0};
void sum(int partialsum, int max, int maxI, int maxJ, int min, int minI, int minJ){
pthread_mutex_lock(&sumLock);
sums += partialsum;
if(max >maxInd[0]){
maxInd[0] = max;
maxInd[1] = maxI;
maxInd[2] = maxJ;
}
if(min <minInd[0]){
minInd[0] = min;
minInd[1] = minI;
minInd[2] = minJ;
}
pthread_mutex_unlock(&sumLock);
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized ){
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
double start_time, end_time;
int size, stripSize;
int matrix[10000][10000];
int maxi[10][3];
int mini[10][3];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&sumLock, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand()%99;
}
}
for (i = 0; i < size; i++) {
printf("[ ");
for (j = 0; j < size; j++) {
printf(" %d", matrix[i][j]);
}
printf(" ]\\n");
}
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
for(l; l>0;l--)
pthread_join(workerid[l], 0);
end_time = read_timer();
printf("The maximum element is %i with index %i %i\\n", maxInd[0], maxInd[1], maxInd[2]);
printf("The minimum element is %i with index %i %i\\n", minInd[0], minInd[1], minInd[2]);
printf("The total is %d\\n", sums);
printf("The execution time is %g sec\\n", end_time - start_time);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, i, j, first, last;
int maxIndex[2], minIndex[2], max, min;
printf("worker %d (pthread id %d) has started\\n", myid, pthread_self());
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
max = 0;
min = 32767;
for (i = first; i <= last; i++)
for (j = 0; j < size; j++){
total += matrix[i][j];
if(matrix[i][j]>max){
max = matrix[i][j];
maxIndex[0] = i;
maxIndex[1] = j;
}
if(matrix[i][j]<min){
min = matrix[i][j];
minIndex[0] = i;
minIndex[1] = j;
}
}
printf("%i %i %i\\n", max, maxIndex[0], maxIndex[1]);
printf("%i %i %i\\n", min, minIndex[0], minIndex[1]);
sum(total, max, maxIndex[0], maxIndex[1], min, minIndex[0], minIndex[1]);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_t prod[20],cons[20];
sem_t full,empty;
int buffer[20];
int size=10;
int counter=0,i;
int num[11]={0,1,2,3,4,5,6,7,8,9,10};
void * producer (void * x)
{
while(1){
int waittime,item;
int *i=x;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
printf("\\nProducer %d has produced an item ",*i);
buffer[counter++]=1;
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
}
void * consumer (void * y)
{
while(1){
int waittime,item;
int *i=y;
sem_wait(&full);
pthread_mutex_lock(&mutex);
counter--;
printf("\\nConsumer %d has consumed an item",*i);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
}
void main()
{
int n,m;
pthread_mutex_init(&mutex,0);
sem_init(&full,1,0);
sem_init(&empty,1,size);
printf("Enter the no of producers: ");
scanf("%d",&n);
printf("Enter the no of consumers: ");
scanf("%d",&m);
for(i=0;i<n;i++)
pthread_create(&prod[i],0,producer,&num[i]);
for(i=0;i<m;i++)
pthread_create(&cons[i],0,consumer,&num[i]);
for(i=0;i<n;i++)
pthread_join(prod[i],0);
for(i=0;i<m;i++)
pthread_join(cons[i],0);
}
| 0
|
#include <pthread.h>
void *handle;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *
load (void *u)
{
pthread_mutex_lock (&m);
handle = dlopen ("$ORIGIN/tst-tls-atexit-lib.so", RTLD_LAZY);
if (!handle)
{
printf ("Unable to load DSO: %s\\n", dlerror ());
return (void *) (uintptr_t) 1;
}
void (*foo) (void) = (void (*) (void)) dlsym(handle, "do_foo");
if (!foo)
{
printf ("Unable to find symbol: %s\\n", dlerror ());
exit (1);
}
foo ();
dlclose (handle);
pthread_mutex_unlock (&m);
return 0;
}
int
main (void)
{
pthread_t t;
int ret;
void *thr_ret;
if ((ret = pthread_create (&t, 0, load, 0)) != 0)
{
printf ("pthread_create failed: %s\\n", strerror (ret));
return 1;
}
if ((ret = pthread_join (t, &thr_ret)) != 0)
{
printf ("pthread_create failed: %s\\n", strerror (ret));
return 1;
}
if (thr_ret != 0)
return 1;
dlclose (handle);
FILE *f = fopen ("/proc/self/maps", "r");
if (f == 0)
{
perror ("Failed to open /proc/self/maps");
fprintf (stderr, "Skipping verification of DSO unload\\n");
return 0;
}
char *line = 0;
size_t s = 0;
while (getline (&line, &s, f) > 0)
{
if (strstr (line, "tst-tls-atexit-lib.so"))
{
printf ("DSO not unloaded yet:\\n%s", line);
return 1;
}
}
free (line);
return 0;
}
| 1
|
#include <pthread.h>
struct monitor {
int count;
struct server_monitor ** m;
pthread_cond_t cond;
pthread_mutex_t mutex;
int sleep;
int quit;
};
struct worker_parm {
struct monitor *m;
int id;
};
static void
create_thread(pthread_t *thread, void *(*start_routine) (void *), void *arg) {
if (pthread_create(thread,0, start_routine, arg)) {
fprintf(stderr, "Create thread failed");
exit(1);
}
}
static void
wakeup(struct monitor *m, int busy) {
if (m->sleep >= m->count - busy) {
pthread_cond_signal(&m->cond);
}
}
static void
free_monitor(struct monitor *m) {
int i;
int n = m->count;
for (i=0;i<n;i++) {
server_monitor_delete(m->m[i]);
}
pthread_mutex_destroy(&m->mutex);
pthread_cond_destroy(&m->cond);
server_free(m->m);
server_free(m);
}
static void *
_monitor(void *p) {
struct monitor * m = p;
int i;
int n = m->count;
server_initthread(THREAD_MONITOR);
server_error(0, "THREAD monitor running");
for (;;) {
if (server_context_total()==0) break;
for (i=0;i<n;i++) {
server_monitor_check(m->m[i]);
}
for (i=0;i<5;i++) {
if (server_context_total()==0) break;
sleep(1);
}
}
return 0;
}
static void *
_timer(void *p) {
struct monitor * m = p;
server_initthread(THREAD_TIMER);
server_error(0, "THREAD timer running");
for (;;) {
server_timer_updatetime();
if (server_context_total()==0) break;
wakeup(m, m->count-1);
usleep(5000);
}
server_socket_exit();
pthread_mutex_lock(&m->mutex);
m->quit = 1;
pthread_cond_broadcast(&m->cond);
pthread_mutex_unlock(&m->mutex);
return 0;
}
static void *
_socket(void *p) {
struct monitor * m = p;
server_initthread(THREAD_SOCKET);
server_error(0, "THREAD socket running");
for (;;) {
int r = server_socket_poll();
if (r==0)
break;
if (r<0) {
if (server_context_total()==0) break;
continue;
}
wakeup(m, 0);
}
return 0;
}
static void *
_worker(void *p) {
struct worker_parm *wp = p;
int id = wp->id;
struct monitor *m = wp->m;
struct server_monitor *sm = m->m[id];
server_initthread(THREAD_WORKER);
server_error(0, "THREAD worker:%d running", id);
struct message_queue * q = 0;
while (!m->quit) {
q = server_context_message_dispatch(sm, q);
if (q == 0) {
if (pthread_mutex_lock(&m->mutex) == 0) {
++ m->sleep;
if (!m->quit) {
pthread_cond_wait(&m->cond, &m->mutex);
}
-- m->sleep;
if (pthread_mutex_unlock(&m->mutex)) {
fprintf(stderr, "unlock mutex error");
exit(1);
}
}
}
}
return 0;
}
static void
_start(int thread) {
pthread_t pid[thread+3];
struct monitor *m = server_malloc(sizeof(*m));
memset(m, 0, sizeof(*m));
m->count = thread;
m->sleep = 0;
m->m = server_malloc(thread * sizeof(struct server_monitor *));
int i;
for (i=0;i<thread;i++) {
m->m[i] = server_monitor_new();
}
if (pthread_mutex_init(&m->mutex, 0)) {
fprintf(stderr, "Init mutex error");
exit(1);
}
if (pthread_cond_init(&m->cond, 0)) {
fprintf(stderr, "Init cond error");
exit(1);
}
create_thread(&pid[0], _monitor, m);
create_thread(&pid[1], _timer, m);
create_thread(&pid[2], _socket, m);
struct worker_parm wp[thread];
for (i=0;i<thread;i++) {
wp[i].m = m;
wp[i].id = i;
create_thread(&pid[i+3], _worker, &wp[i]);
}
for (i=0; i<(thread+3); i++) {
pthread_join(pid[i], 0);
}
free_monitor(m);
}
static void
bootstrap(const char * cmdline) {
int sz = strlen(cmdline);
char name[sz+1];
char args[sz+1];
sscanf(cmdline, "%s %s", name, args);
struct server_context *ctx = server_context_new(name, args);
if (ctx == 0) {
server_error(0, "Bootstrap error : %s\\n", cmdline);
exit(1);
}
}
void
server_start(struct server_config * config) {
server_harbor_init(config->harbor);
server_handle_init(config->harbor);
server_timer_init();
server_socket_init();
server_mq_init();
server_module_init(config->module_path);
struct server_context * loggerctx = server_context_new("logger", config->logger);
if (loggerctx == 0) {
fprintf(stderr, "Can't launch logger service\\n");
exit(1);
}
bootstrap(config->bootstrap);
_start(config->thread);
server_harbor_exit();
server_socket_free();
}
| 0
|
#include <pthread.h>
int *a;
pthread_mutex_t *mutex;
} args;
void *thread(void *arg){
int *a = ((args*)arg)->a;
int i;
for(i=0; i < 1000; i++) {
pthread_mutex_lock(mutex);
(*a)++;
pthread_mutex_unlock(mutex);
}
pthread_exit(0);
}
int main(){
clock_t begin, end;
double time_spent;
begin = clock();
int count = 0;
int numOfThreads = 1000;
pthread_t tid[numOfThreads];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
args args1;
args1.a = &count;
args1.mutex = &mutex;
int threadCount = 0;
for(threadCount = 0; threadCount < numOfThreads; threadCount++){
Pthread_create(&tid[threadCount], 0, thread, &args1);
}
int joinCount;
for(joinCount = 0; joinCount < threadCount; joinCount++){
Pthread_join(tid[joinCount],0);
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("*********************\\n");
printf("* Lock Inside for *\\n");
printf("*********************\\n");
printf("Threads created: %d\\n", threadCount);
printf("count= %d\\n",count);
printf("Time = %f\\n",time_spent);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void
_ports_complete_deallocate (struct port_info *pi)
{
assert_backtrace ((pi->flags & PORT_HAS_SENDRIGHTS) == 0);
if (MACH_PORT_VALID (pi->port_right))
{
struct references result;
pthread_rwlock_wrlock (&_ports_htable_lock);
refcounts_references (&pi->refcounts, &result);
if (result.hard > 0 || result.weak > 0)
{
assert_backtrace (! "reacquired reference w/o send rights");
pthread_rwlock_unlock (&_ports_htable_lock);
return;
}
freax_ihash_locp_remove (&_ports_htable, pi->ports_htable_entry);
freax_ihash_locp_remove (&pi->bucket->htable, pi->hentry);
pthread_rwlock_unlock (&_ports_htable_lock);
mach_port_mod_refs (mach_task_self (), pi->port_right,
MACH_PORT_RIGHT_RECEIVE, -1);
pi->port_right = MACH_PORT_NULL;
}
pthread_mutex_lock (&_ports_lock);
pi->bucket->count--;
pi->class->count--;
pthread_mutex_unlock (&_ports_lock);
if (pi->class->clean_routine)
(*pi->class->clean_routine)(pi);
free (pi);
}
| 0
|
#include <pthread.h>
int **matrice = 0;
int minimo = 1000;
int rows = 0,cols = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *somma_col(void *col){
int colonna = *(int *)col;
printf("T: %d\\n COL: %d\\n",(int)pthread_self(),colonna);
for(int rig=0; rig<rows; rig++){
pthread_mutex_lock(&mutex);
if( matrice[rig][colonna] < minimo ){
minimo = matrice[rig][colonna];
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char *argv[]){
if(argc < 2){
printf("USO %s <num_col>\\n", argv[0]);
return -1;
}
rows = cols = atoi(argv[1]);
matrice = malloc( rows * sizeof(int *));
for(int row = 0; row < rows; row++){
matrice[row] = malloc(cols * sizeof(int));
for(int col = 0; col < cols; col++){
int valore = 1 + rand() % 10;
matrice[row][col] = valore;
}
}
for (int row = 0; row < rows ; row++) {
for (int col = 0; col < cols; col++) {
printf("%d \\t",matrice[row][col]);
}
printf("\\n");
}
pthread_t *threads = malloc(cols * sizeof(pthread_t));
for (int i=0; i < cols; i++) {
int *col=malloc(sizeof(int));
*col=i;
pthread_create(&threads[i],0,somma_col,col);
}
for (int i=0; i < cols; i++) {
pthread_join(threads[i],0);
}
printf("Il minimo Γ¨: %d\\n", minimo);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(void)
{
pthread_key_create(&key, free);
}
char *
getenv(const char *name)
{
int i = 0;
int len = 0;
char *envbuf = 0;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0)
{
envbuf = (char *)malloc(4096);
if (envbuf == 0)
{
pthread_mutex_unlock(&env_mutex);
return 0;
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++)
{
if ((strncmp(name, environ[i], len) == 0)
&& (environ[i][len] == '='))
{
strncpy(envbuf, &environ[i][len + 1], 4096 - 1);
return envbuf;
}
}
pthread_mutex_unlock(&env_mutex);
return 0;
}
| 0
|
#include <pthread.h>
static int n;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static int cont = 0;
static pthread_cond_t cond_thread1 = PTHREAD_COND_INITIALIZER;
static pthread_mutex_t mutex_thread1 = PTHREAD_MUTEX_INITIALIZER;
static int cond = 0;
void *rand_thread(void *arg){
int result;
int fd;
pthread_mutex_lock(&mutex);
cont++;
result = (int)arg + (int) (10*((double)rand())/ 32767);
pthread_mutex_unlock(&mutex);
if ((fd = open("pipe", O_WRONLY)) == -1) {
remove("pipe");
perror("open error O_WRONLY");
exit(1);
}
if (write(fd, &result, sizeof(int)) == -1){
perror("write pipe");
remove("pipe");
exit(1);
}
pthread_mutex_lock(&mutex_thread1);
if (cont==n){
printf("I'm the unlocker.\\n");
pthread_cond_signal(&cond_thread1);
}
pthread_mutex_unlock(&mutex_thread1);
}
void sig_hand(int sig){
printf("Signal %d.\\n", sig);
pthread_cond_signal(&cond_thread1);
cond = 1;
}
void *other_thread(void *arg){
int fd;
int tmp;
int i;
struct sigaction action, old;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = sig_hand;
sigaction(SIGALRM, &action, &old);
if ((fd = open("pipe", O_RDONLY)) == -1) {
perror("open error O_RDONLY");
exit(1);
}
pthread_mutex_lock(&mutex_thread1);
alarm(3);
pthread_cond_wait(&cond_thread1, &mutex_thread1);
printf("I've been unlocked.\\n");
fflush(stdout);
pthread_mutex_unlock(&mutex_thread1);
for (int i = 0; i < (int)arg; i++) {
if (read(fd, &tmp, sizeof(tmp)) == -1){
perror("read pipe");
exit(1);
}
printf("%d\\n", tmp);
}
pthread_mutex_lock(&mutex);
cont++;
pthread_mutex_unlock(&mutex);
if (cond == 0){
pthread_exit(0);
} else {
remove("pipe");
pthread_exit(0);
}
}
int main(int argc, char *argv[])
{
if (argc != 2){
printf("an argument (N) is required\\n");
return 1;
}
n = atoi(argv[1]);
pthread_t other;
pthread_t tid[n];
int var = 0;
int i;
int* status;
int fd;
char *pipename = "pipe";
srand((int)time(0));
if (mkfifo(pipename, S_IRUSR|S_IWUSR) == -1){
perror("mkfifo error");
exit(1);
}
if (pthread_create(&other, 0, other_thread, (void*)n) != 0) {
printf("pthread_create\\n");
}
for (i = 0; i < n; i++) {
if (pthread_create(&tid[i], 0, rand_thread, (void*)var) != 0) {
printf("pthread_create\\n");
}
pthread_detach(tid[i]);
}
pthread_mutex_lock(&mutex);
cont++;
pthread_mutex_unlock(&mutex);
pthread_join(other, 0);
printf("cont : %d\\n", cont);
remove(pipename);
return 0;
}
| 1
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[8];
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;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum);
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 (8*12500*sizeof(double));
b = (double*) malloc (8*12500*sizeof(double));
for (i=0; i<12500*8; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 12500;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
clock_t tic = clock();
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<8;i++) {
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<8;i++) {
pthread_join(callThd[i], &status);
}
clock_t toc = clock();
printf("Elapsed: %f seconds\\n", (double)(toc - tic) / CLOCKS_PER_SEC);
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void * thread_read_rx()
{
int ret_val =0;
unsigned char buffer;
sleep(1);
while(1)
{
while( ioctl(fd_spi,READ_GPIO,0) < 0)
{
printf("\\n GPIO FAILED");
sleep(1);
}
do
{
ret_val = read_data_spi(&buffer,1);
if(ret_val == -1)
{
printf("\\n GPIO READ FAILED");
fflush(stdout);
}
}while(ret_val < 0);
while( ioctl(fd_spi,READ_MSG,0) < 0)
{
printf("\\n IOCTL READ FAILED");
sleep(1);
}
while( ioctl(fd_spi,NUMBR_OF_BITS_8,0) < 0)
{
printf("\\n IOCTL FAILED");
sleep(1);
}
pthread_mutex_lock(&lock);
do
{
ret_val = read_data_spi(&buffer,1);
if(ret_val == -1)
{
printf("\\n DATA READ FAILED");
fflush(stdout);
}
}while(ret_val < 0);
pthread_mutex_unlock(&lock);
printf(" \\n DATA READ SUCCESSFULLY %d",buffer);
}
}
| 1
|
#include <pthread.h>
int num=0;
pthread_mutex_t mylock = PTHREAD_MUTEX_INITIALIZER;
void *add(void *arg)
{
int i = 0,tmp = 0;
for(i=0;i<500;i++)
{
pthread_mutex_lock(&mylock);
tmp = num+1;
num = tmp;
printf("add+1,result is :%d\\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
void *sub(void *arg)
{
int i = 0,tmp = 0;
for(i=0;i<500;i++)
{
pthread_mutex_lock(&mylock);
tmp = num-1;
num = tmp;
printf("sub-1,result is :%d\\n",num);
pthread_mutex_unlock(&mylock);
}
return ((void *)0);
}
int main(int argc, char** argv)
{
pthread_t tid1,tid2;
int err;
void *tret;
err = pthread_create(&tid1, 0, add ,0);
if(0 != err)
{
printf("pthread_create error:%s\\n",strerror(err));
exit(-1);
}
err = pthread_create(&tid2, 0, sub ,0);
if(0 != err)
{
printf("pthread_create error:%s\\n",strerror(err));
exit(-1);
}
err = pthread_join(tid1,&tret);
if(0 != err)
{
printf("pthread_create error:%s\\n",strerror(err));
exit(-1);
}
err = pthread_join(tid2,&tret);
if(0 != err)
{
printf("pthread_create error:%s\\n",strerror(err));
exit(-1);
}
printf("thread 2 exit code %d\\n",(int)tret);
return 0;
}
| 0
|
#include <pthread.h>
void pr_cpu_time(void);
void sig_int(int);
void * thread_start(void *);
pthread_t tid;
long nConn;
} Thread;
int cliSocks[32], cliGet, cliPut;
pthread_mutex_t cliMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cliCond = PTHREAD_COND_INITIALIZER;
static int nThreads;
Thread *threads;
int main(int argc, char *argv[]) {
int i, srvSock, cliSock, *tNum;
if (argc < 3)
srvSock = tcpListen(argv[1]);
nThreads = atoi(argv[2]);
threads = calloc(nThreads,sizeof(Thread));
for (i = 0; i < nThreads; i++) {
tNum = malloc(sizeof(int));
*tNum = i;
if (pthread_create(&threads[0].tid, 0, &thread_start, (void *) tNum))
exitError("ERROR: pthread_create", 1);
}
signal(SIGINT, sig_int);
cliGet = cliPut = 0;
while(1){
cliSock = accept(srvSock, 0,0);
if(cliSock==-1)
exitError("ERROR: could not accept new connection on socket",1);
pthread_mutex_lock(&cliMutex);
cliSocks[cliPut] = cliSock;
if (++cliPut == 32)
cliPut = 0;
if (cliPut == cliGet)
exitError("ERROR: cliPut = cliGet = %d", cliPut);
pthread_cond_signal(&cliCond);
pthread_mutex_unlock(&cliMutex);
}
}
void * thread_start(void * args) {
int cliSock;
int tNum = *((int*) args);
free(args);
pthread_detach(pthread_self());
printf("Pre-created worker thread %d\\n", tNum);
while(1){
pthread_mutex_lock(&cliMutex);
while (cliGet == cliPut)
pthread_cond_wait(&cliCond, &cliMutex);
cliSock = cliSocks[cliGet];
if (++cliGet == 32)
cliGet = 0;
pthread_mutex_unlock(&cliMutex);
threads[tNum].nConn++;
handleHttpRequest(cliSock);
closeWriteSock(cliSock);
}
return 0;
}
void sig_int(int signo){
int i;
pr_cpu_time();
for (i = 0; i < nThreads; i++)
printf("Worker thread %d, handled %ld connections\\n", i, threads[i].nConn);
exit(0);
}
| 1
|
#include <pthread.h>
sem_t emptyPot;
sem_t fullPot;
void *savage (void*);
void *cook (void*);
static pthread_mutex_t servings_mutex;
static pthread_mutex_t print_mutex;
static int servings = 15;
int getServingsFromPot(void) {
int retVal;
if (servings <= 0)
{
sem_post (&emptyPot);
retVal = 0;
}
else
{
servings--;
printf(" Servings-->%d\\n", servings);
retVal = 1;
}
pthread_mutex_unlock (&servings_mutex);
return retVal;
}
void putServingsInPot (int num)
{
servings += num;
sem_post (&fullPot);
}
void *cook (void *id) {
int cook_id = *(int *)id;
int meals = 2;
int i;
while ( meals ) {
sem_wait (&emptyPot);
putServingsInPot (15);
meals--;
pthread_mutex_lock(&print_mutex);
printf ("\\nCook filled pot\\n\\n");
pthread_mutex_unlock(&print_mutex);
for (i=0; i<3; i++)
sem_post (&fullPot);
}
return 0;
}
void *savage (void *id) {
int savage_id = *(int *)id;
int myServing;
int meals = 15;
while ( meals ) {
pthread_mutex_lock (&servings_mutex);
myServing = getServingsFromPot();
if (servings == 0)
{
sem_wait(&fullPot);
myServing = getServingsFromPot();
}
pthread_mutex_unlock (&servings_mutex);
meals--;
pthread_mutex_lock (&print_mutex);
printf ("Savage: %i is eating\\n", savage_id);
pthread_mutex_unlock (&print_mutex);
sleep(2);
pthread_mutex_lock (&print_mutex);
printf ("Savage: %i is DONE eating\\n", savage_id);
pthread_mutex_unlock (&print_mutex);
}
return 0;
}
int main() {
int i, id[3];
pthread_t tid[3];
pthread_mutex_init(&servings_mutex, 0);
pthread_mutex_init(&print_mutex, 0);
sem_init(&emptyPot, 0, 0);
sem_init(&fullPot, 0, 0);
for (i=0; i<3; i++)
{
id[i] = i;
pthread_create (&tid[i], 0, savage, (void *)&id[i]);
printf("Hello--->1\\n");
}
pthread_create (&tid[i], 0, cook, (void *)&id[i]);
for (i=0; i<3; i++)
pthread_join(tid[i], 0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int bottles = 99;
void *takeonedownandpassitaround(void *ptr) {
struct timespec sleeptime;
int *thread_id = (int *)ptr;
while (1) {
pthread_mutex_lock(&mutex);
if (bottles>0) {
fprintf(stderr, "Thread %d: ", *thread_id);
printf("%d bottle%s of beer on the wall, %d bottle%s of beer.\\n", bottles, (bottles>1) ? "s" : "",
bottles, (bottles>1) ? "s" : "");
fprintf(stderr, "Thread %d: ", *thread_id);
printf("Take one down and pass it around, ");
if (bottles==1)
printf("no more bottles of beer on the wall.\\n");
else
printf("%d bottle%s of beer on the wall.\\n", bottles-1, (bottles>1) ? "s" : "");
} else if (bottles==0) {
fprintf(stderr, "Thread %d: ", *thread_id);
printf("No more bottles of beer on the wall, no more bottles of beer.\\n");
fprintf(stderr, "Thread %d: ", *thread_id);
printf("Go to the store and buy some more, 99 bottles of beer on the wall.\\n");
} else {
pthread_mutex_unlock(&mutex);
break;
}
bottles--;
pthread_mutex_unlock(&mutex);
sleeptime.tv_nsec = 0;
sleeptime.tv_sec = rand() % 10;
fprintf(stderr, "Thread %d: sleeps for %d ms\\n", *thread_id, sleeptime.tv_sec);
nanosleep(&sleeptime, 0);
}
}
int main(void) {
pthread_t thread[10];
int threadid[10];
int i;
srand(time(0));
for (i=0; i<10; i++) {
threadid[i] = i;
pthread_create(&thread[i], 0, takeonedownandpassitaround, &threadid[i]);
}
for (i=0; i<10; i++)
pthread_join(thread[i], 0);
exit(0);
}
| 1
|
#include <pthread.h>
int a[10], count = 0;
pthread_t thread[10];
pthread_mutex_t lock[10 + 1];
void *sort (void *index);
void *check (void * temp);
int main()
{
int i;
for(i = 0; i < 10; i++)
a[i] = i;
for(i = 0; i < 10; i++)
{
if (pthread_mutex_init(&lock[i], 0) != 0)
{
printf("\\nMutex init failed\\n");
return 1;
}
}
while(1)
{
for(i = 1; i < 10; i++)
{
int ret = pthread_create(&thread[i - 1], 0, sort, (void *) &i);
if (ret != 0)
printf("\\nCan't create thread :[%s]", strerror(ret));
pthread_join( thread[i], 0);
}
int ret = pthread_create(&thread[10 - 1], 0, check, 0);
if (ret != 0)
printf("\\nCan't create thread :[%s]", strerror(ret));
pthread_join( thread[10 - 1], 0);
for(i = 0; i < 10 - 1; i++)
pthread_join( thread[i], 0);
}
for(i = 0; i < 10; i++)
pthread_mutex_destroy(&lock[i]);
return 0;
}
void *sort(void *index)
{
int right = *((int *) index), left = right - 1;
pthread_mutex_lock(&lock[left]);
pthread_mutex_lock(&lock[right]);
count++;
if((a[left] < a[right]) && (left >= 0) && (right < 10))
{
int temp = a[left];
a[left] = a[right];
a[right] = temp;
}
pthread_mutex_unlock(&lock[right]);
pthread_mutex_unlock(&lock[left]);
pthread_exit(0);
}
void *check (void * temp)
{
pthread_mutex_lock(&lock[10]);
for(int i = 0; i < 10 - 1; i++)
if(a[i] < a[i + 1])
pthread_exit(0);
for(int i = 0; i < 10; i++)
printf("%d ", a[i]);
printf("\\n Sorted; Count = %d \\n", count/10);
exit(0);
pthread_mutex_unlock(&lock[10]);
}
| 0
|
#include <pthread.h>
int q[2];
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 < 2)
{
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 < 2);
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[8];
int sorted[8];
void producer ()
{
int i, idx;
for (i = 0; i < 8; i++)
{
idx = findmaxidx (source, 8);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 8);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 8; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 8);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 8; 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;
}
| 1
|
#include <pthread.h>
int val;
pthread_mutex_t mutex;
void updateVal(int d) {
int i;
int tmp = val;
for (i = 0; i < tmp + 100; i++);
tmp += d;
val = tmp;
}
void *readLetters(void *buffer) {
char *c = (char*)buffer;
while (*c != 0) {
if (isalpha(*c)) {
pthread_mutex_lock(&mutex);
updateVal(1);
pthread_mutex_unlock(&mutex);
}
c++;
}
pthread_exit(0);
}
void *readDigits(void *buffer) {
char *c = (char*)buffer;
while (*c != 0) {
if (isdigit(*c)) {
updateVal(2);
}
c++;
}
pthread_exit(0);
}
void *readOther(void *buffer) {
char *c = (char*)buffer;
while (*c != 0) {
if (!isalnum(*c) && !isspace(*c)) {
pthread_mutex_lock(&mutex);
updateVal(10);
}
c++;
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
char buffer[1024];
pthread_t letterThread;
pthread_t digitThread;
pthread_t otherThread;
pthread_mutex_init(&mutex, 0);
val = 0;
do {
int num = fread(buffer, 1, 1023, stdin);
buffer[num] = 0;
if(num == 0) {
break;
}
if (pthread_create(&letterThread,
0,
readLetters,
(void*) buffer)) {
fprintf(stderr, "error creating thread\\n");
exit(-1);
}
if (pthread_create(&digitThread,
0,
readDigits,
(void*) buffer)) {
fprintf(stderr, "error creating thread\\n");
exit(-1);
}
if (pthread_create(&otherThread,
0,
readOther,
(void*) buffer)) {
fprintf(stderr, "error creating thread\\n");
exit(-1);
}
pthread_join(digitThread, 0);
pthread_join(letterThread, 0);
pthread_join(otherThread, 0);
} while(1);
pthread_mutex_destroy(&mutex);
printf("%d\\n", val);
return 0;
}
| 0
|
#include <pthread.h>
sem_t customer_sem;
sem_t barber_sem;
sem_t leaving_sem;
pthread_cond_t barber_cv;
pthread_mutex_t seat_mutex;
pthread_mutex_t barber_mutex;
pthread_mutex_t print_mutex;
pthread_mutex_t count_mutex;
int barber_working;
int free_seat_count;
int max_seat_count;
int barber_count;
int customer_count;
int customers_visited;
void* customer_run(void* arg)
{
int check_in_time = (rand()%10) + 1;
printf("Customer %d! I will appear in %d time\\n", syscall(SYS_gettid), check_in_time);
sleep(check_in_time);
pthread_mutex_lock(&seat_mutex);
if (free_seat_count > 0)
{
free_seat_count--;
pthread_mutex_unlock(&seat_mutex);
sem_post(&customer_sem);
pthread_mutex_lock(&barber_mutex);
printf("\\nCustomer %d is sitting in seat %d\\n", syscall(SYS_gettid), (free_seat_count + 1));
while(!barber_working)
{
pthread_cond_wait(&barber_cv, &barber_mutex);
}
pthread_mutex_unlock(&barber_mutex);
sem_wait(&barber_sem);
pthread_mutex_lock(&count_mutex);
customers_visited++;
pthread_mutex_unlock(&count_mutex);
time_t t;
time(&t);
pthread_mutex_lock(&print_mutex);
printf("\\n---Customer %d hair is cut. The time is %s", syscall(SYS_gettid), ctime(&t));
pthread_mutex_unlock(&print_mutex);
sem_post(&leaving_sem);
}
else
{
pthread_mutex_unlock(&seat_mutex);
pthread_mutex_lock(&print_mutex);
printf("\\n---No more seats! I am Customer %d\\n", syscall(SYS_gettid));
pthread_mutex_unlock(&print_mutex);
pthread_mutex_lock(&count_mutex);
customers_visited++;
pthread_mutex_unlock(&count_mutex);
}
}
void* barber_run(void* arg)
{
int cut_time = (rand()%3) + 1;
printf("Barber %d! It takes me %d time to cut hair\\n\\n", syscall(SYS_gettid), cut_time);
while(customers_visited < customer_count)
{
pthread_mutex_unlock(&count_mutex);
sem_wait(&customer_sem);
pthread_mutex_lock(&seat_mutex);
free_seat_count++;
pthread_mutex_unlock(&seat_mutex);
pthread_mutex_lock(&barber_mutex);
barber_working = 1;
pthread_cond_signal(&barber_cv);
pthread_mutex_unlock(&barber_mutex);
sleep(cut_time);
pthread_mutex_lock(&barber_mutex);
barber_working = 0;
pthread_cond_signal(&barber_cv);
pthread_mutex_unlock(&barber_mutex);
sem_post(&barber_sem);
sem_wait(&leaving_sem);
pthread_mutex_lock(&count_mutex);
}
printf("I QUIT! Barber helped %d people\\n", customers_visited);
}
int main(int argc, char** argv)
{
if (argc == 3)
{
customers_visited = 0;
srand(time(0));
char* endptr;
barber_count = 1;
customer_count = (int)strtol(argv[1], &endptr, 10);
free_seat_count = (int)strtol(argv[2], &endptr, 10);
max_seat_count = free_seat_count;
printf(" Barbers %d\\n Customers %d\\n Free Seats %d \\n", barber_count, customer_count, free_seat_count);
pthread_mutex_init(&count_mutex, 0);
pthread_mutex_init(&print_mutex, 0);
sem_init(&customer_sem, 0, 0);
sem_init(&barber_sem, 0, 0);
sem_init(&leaving_sem, 0, 0);
pthread_t barber;
pthread_t customer[customer_count];
pthread_mutex_init(&barber_mutex, 0);
pthread_cond_init(&barber_cv, 0);
pthread_mutex_init(&seat_mutex, 0);
int i;
pthread_create(&barber, 0, &barber_run, 0);
for (i = 0; i < customer_count; i++)
{
pthread_create(&customer[i], 0, &customer_run, 0);
}
for (i = 0; i < customer_count; i++)
{
pthread_join(customer[i], 0);
}
pthread_join(barber, 0);
}
else
{
printf("This version uses one barber\\n");
printf("Please enter the number of: customers and free seats respectively as arguments\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
void *piCalculate(void *ptr);
void *piPrint(void *ptr);
pthread_mutex_t mutexPi = PTHREAD_MUTEX_INITIALIZER;
double piVal = 0;
int iteration = 0;
bool print = 1;
int main(int argc, char *argv[])
{
if (argc != 3) {
printf("usage: %s iterations seconds.\\n", argv[0]);
exit(1);
}
int var[] = {0,0};
var[0] = atoi(argv[1]);
var[1] = atoi(argv[2]);
pthread_t calcThread, printThread;
pthread_mutex_init(&mutexPi, 0);
if (pthread_create(&calcThread, 0, &piCalculate, (void*) var) != 0) {
printf("Could not create calculation.\\n");
}
if (pthread_create(&printThread, 0, &piPrint, 0) != 0) {
printf("Could not create print.\\n");
}
pthread_join(printThread, 0);
pthread_join(calcThread, 0);
pthread_mutex_destroy(&mutexPi);
exit(0);
}
void *piCalculate(void *ptr)
{
int maxIteration = ((int*) ptr)[0];
int maxSeconds = ((int*) ptr)[1];
double num = 1;
int add = 1;
struct timeval tim;
gettimeofday(&tim, 0);
unsigned long stopTime = 1000000 * tim.tv_sec + tim.tv_usec + (1000000 * maxSeconds);
unsigned long time_in_micros = 1000000 * tim.tv_sec + tim.tv_usec;
while (iteration < maxIteration && time_in_micros < stopTime) {
pthread_mutex_lock(&mutexPi);
iteration++;
if (add) {
piVal += 4/num;
add = 0;
} else {
piVal -= 4/num;
add = 1;
}
num+=2;
int i;
for (i = 0; i < 10000; i++) {
}
pthread_mutex_unlock(&mutexPi);
gettimeofday(&tim, 0);
time_in_micros = 1000000 * tim.tv_sec + tim.tv_usec;
}
print = 0;
printf("Finished calculation\\n");
return 0;
}
void *piPrint(void *ptr)
{
printf("Start print Thread.\\n");
struct timeval tim;
gettimeofday(&tim, 0);
unsigned long stopTime = 1000000 * tim.tv_sec + tim.tv_usec + 1000000;
while(print) {
gettimeofday(&tim, 0);
unsigned long time_in_micros = 1000000 * tim.tv_sec + tim.tv_usec;
if (time_in_micros > stopTime) {
pthread_mutex_lock(&mutexPi);
printf("Iteration: %d, PI: %f\\n", iteration, piVal);
pthread_mutex_unlock(&mutexPi);
stopTime = 1000000 * tim.tv_sec + tim.tv_usec + 1000000;
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t gPresetsMutex = PTHREAD_MUTEX_INITIALIZER;
struct ae_preset gPresets[AE_BANK_COUNT][AE_PRESET_COUNT];
int aeffects_init(struct ae_preset presets[AE_BANK_COUNT][AE_PRESET_COUNT]) {
int ret;
PRINT("aeffects: Initializing library.\\n");
memcpy(gPresets, presets, sizeof(presets[0][0]) * AE_BANK_COUNT * AE_PRESET_COUNT);
ret = control_init();
if (ret != 0) {
PRINT("aeffects: Failed to initialize library.\\n");
return -1;
}
PRINT("aeffects: Finished initializing library.\\n");
return 0;
}
int aeffects_update(struct ae_preset *preset) {
int ret;
PRINT("aeffects: Updating bank %d preset %d.\\n", preset->bank, preset->preset);
ret = pthread_mutex_lock(&gPresetsMutex);
if (ret != 0) {
PRINTE("pthread_mutex_lock() failed!");
return -1;
}
memcpy(&gPresets[preset->bank][preset->preset], preset, sizeof(*preset));
pthread_mutex_unlock(&gPresetsMutex);
ret = control_notify_update(preset->bank, preset->preset);
return 0;
}
int aeffects_uninit() {
int ret;
PRINT("aeffects: Uninitializing library.\\n");
ret = pthread_mutex_lock(&gPresetsMutex);
if (ret != 0) {
PRINTE("pthread_mutex_lock() failed!");
return -1;
}
ret = control_uninit();
if (ret != 0) {
PRINT("aeffects: Failed to uninitialize library.\\n");
return -1;
}
memset(gPresets, 0, sizeof(gPresets));
pthread_mutex_unlock(&gPresetsMutex);
pthread_mutex_destroy(&gPresetsMutex);
PRINT("aeffects: Finished uninitializing library.\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct arg{
int* pids;
int* replies;
int known;
int* toReply;
pthread_mutex_t* replyLock;
};
void Individual(struct arg* a){
int toSend = rand() % 5;
int sendTo;
int sleepTime;
int status = 0;
int received = 0;
int k;
for (k = toSend; k > 0; k--){
sendTo = rand() % a->known;
int sendstatus = SendMsg(a->pids[sendTo], a->pids, a->known*sizeof(int), 1);
if(sendstatus == 0){
pthread_mutex_lock(a->replyLock);
a->replies[*a->toReply] = a->pids[sendTo];
(*a->toReply)++;
pthread_mutex_unlock(a->replyLock);
}
else{
}
sleepTime = rand() % 2000;
usleep(sleepTime);
while (status == 0){
int sender;
int len;
int* msg = malloc(128);
status = RcvMsg(&sender, msg, &len, 0);
if (status == 0){
received++;
pthread_mutex_lock(a->replyLock);
int i;
int flag = 0;
int j = *a->toReply;
for(i = 0; i < j; i++){
if (flag == 0){
if (a->replies[i] == sender){
flag = 1;
a->replies[i] = a->replies[i+1];
(*a->toReply)--;
}
}
else{
a->replies[i] = a->replies[i+1];
}
}
pthread_mutex_unlock(a->replyLock);
if (flag == 0){
SendMsg(sender, a->pids, len, 1);
}
}
free(msg);
}
}
printf("I am a thread from pid: %d\\n", getpid());
printf("Number of messages sent: %d\\n", toSend);
printf("Number of messages received: %d\\n", received);
return;
}
int spawn(int spawnwidth, int treedepth, int oldknown, int* oldpids, int avgthreads){
treedepth--;
int known = oldknown;
int* pids = malloc(32*sizeof(int));
if(oldpids != 0){
memcpy(pids, oldpids, 32*sizeof(int));
}
if(known < 32){
pids[known] = getpid();
known++;
}
else{
int i = 0;
for(i = 0; i<31; i++){
pids[i] = pids[i+1];
}
pids[31] = getpid();
}
if(treedepth > 0){
int tospawn = spawnwidth;
while(tospawn != 0){
tospawn--;
int childPID = fork();
if(childPID == 0){
spawn(spawnwidth, treedepth, known, pids, avgthreads);
return 0;
}
else{
printf("I am %d and I just spawned %d \\n", getpid(), childPID);
if(known < 32){
pids[known] = childPID;
known++;
}
else{
int i = 0;
for(i = 0; i<31; i++){
pids[i] = pids[i+1];
}
pids[31] = childPID;
}
}
}
}
double a = drand48();
double b = drand48();
double y = sqrt(-2 * log(a)) * cos(2 * M_PI * b);
int threads = avgthreads/2 + y * (avgthreads/2);
if(threads == 0){
threads = 1;
}
pthread_t* thread_array = malloc(threads * sizeof(pthread_t));
int* replies = malloc(sizeof(int) * 100);
struct arg* arguments = malloc(sizeof(struct arg));
arguments->replies = replies;
arguments->pids = pids;
arguments->known = known;
pthread_mutex_t theMutex;
arguments->replyLock = &theMutex;
int R = 0;
arguments->toReply = &R;
pthread_mutex_init(arguments->replyLock, 0);
int total_threads = threads;
int j = 0;
while (threads > 0){
threads--;
pthread_create(&thread_array[j], 0, (void *)&Individual, arguments);
j++;
}
for (j = 0; j < total_threads; j++){
pthread_join(thread_array[j], 0);
}
while (R > 0){
int sender;
int len;
int* msg = malloc(128);
RcvMsg(&sender, msg, &len, 1);
int i;
int flag = 0;
int j = R;
for(i = 0; i < j; i++){
if (flag == 0){
if (arguments->replies[i] == sender){
flag = 1;
arguments->replies[i] = arguments->replies[i+1];
R--;
}
}
else{
arguments->replies[i] = arguments->replies[i+1];
}
}
if (flag == 0){
SendMsg(sender, pids, len, 1);
}
free(msg);
}
sleep(2);
int count;
ManageMailbox(1, &count);
while(count > 0){
int sender;
int len;
int* msg = malloc(128);
RcvMsg(&sender, msg, &len, 1);
SendMsg(sender, pids, len, 1);
count--;
}
ManageMailbox(1, &count);
printf("%d received all replies and is terminating, PASSED \\n", getpid());
free(replies);
pthread_mutex_destroy(arguments->replyLock);
free(arguments);
free(pids);
free(thread_array);
return 0;
}
int main(int argc, char* argv[]){
int spawnwidth = atoi(argv[1]);
int treedepth = atoi(argv[2]);
int avgthreads = atoi(argv[3]);
int i;
double processes;
for(i = 0; i < treedepth; i++){
processes = processes + pow(spawnwidth, i);
}
printf("This call will spawn on average %.0lf threads.\\n", processes*(avgthreads+1));
printf("I am the master thread %d \\n", getpid());
spawn(spawnwidth, treedepth, 0, 0, avgthreads);
return 0;
}
| 0
|
#include <pthread.h>
int mediafirefs_write(const char *path, const char *buf, size_t size,
off_t offset, struct fuse_file_info *file_info)
{
printf("FUNCTION: write. path: %s\\n", path);
(void)path;
ssize_t retval;
struct mediafirefs_context_private *ctx;
struct mediafirefs_openfile *openfile;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
openfile = (struct mediafirefs_openfile *)(uintptr_t) file_info->fh;
retval = pwrite(openfile->fd, buf, size, offset);
openfile->is_flushed = 0;
pthread_mutex_unlock(&(ctx->mutex));
return retval;
}
| 1
|
#include <pthread.h>
void *Producer(void *);
void *Consumer(void *);
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int g_data[20];
int main (int argc, char *argv[]) {
int N = atoi(argv[1]);
printf("%d", N);
pthread_t pid[N], cid[N];
sem_init(&empty, 0, 20);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex,0);
int id[N*2];
printf("main started\\n");
int i;
for(i = 0; i<N; i++)
{
id[i*2] = i*2;
pthread_create(&pid[i], 0, Producer, (void*) &id[i*2]);
id[(i*2)+1]=(i*2)+1;
pthread_create(&cid[i], 0, Consumer, (void*) &id[(i*2)+1]);
}
for(i = 0; i<N; i++)
{
pthread_join(pid[i], 0);
pthread_join(cid[i], 0);
}
printf("main done\\n");
return 0;
}
void *Producer(void *arg) {
int semvalem,i=0,j;
int *x = (int*) arg;
int navn = *x;
while(i < 100) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
sem_getvalue(&empty, &semvalem);
g_data[20 -(semvalem-1)]=1;
j=20; printf("(Producer %d, semaphore empty is %d) \\t", navn, semvalem);
while(j > semvalem) { j--; printf("="); } printf("\\n");
pthread_mutex_unlock(&mutex);
sem_post(&full);
i++;
}
return 0;
}
void *Consumer(void *arg) {
int semvalfu,i=0,j;
int *x = (int*) arg;
int navn = *x;
while(i < 100) {
sem_wait(&full);
pthread_mutex_lock(&mutex);
sem_getvalue(&full, &semvalfu);
g_data[semvalfu]=0;
j=0; printf("(Consumer %d, semaphore full is %d) \\t", navn, semvalfu);
while(j < semvalfu) { j++; printf("="); } printf("\\n");
pthread_mutex_unlock(&mutex);
sem_post(&empty);
i++;
}
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(400)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(400)];
_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 == (400))
{
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 == (400))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (400))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(
i=0; i<((400)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:
__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(400); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct data_queue socket_queue;
char* OK = " OK\\n";
char* MISSPELLED = " MISSPELLED\\n";
char* NEXT_WORD = "Enter next word or EOF to quit.\\n";
char ** dictionary;
int main(int argc, char** argv)
{
socket_queue.current_pos = 0;
socket_queue.top = 0;
socket_queue.Q_count = 0;
sem_init(&(socket_queue.full), 0, Q_SIZE);
sem_init(&(socket_queue.empty), 0, 0);
pthread_mutex_init(&socket_queue.mutex_dict, 0);
struct sockaddr_in client;
unsigned int clientlen = sizeof(client);
int port, listener, connfd;
int validport ,validdict;
validport = validdict = 0;
if(argc == 1){
dictionary = load_dictionary(DEFAULT_DICTIONARY);
port = DEFAULT_PORT;
printf("No dictionary or port number specified, using default port and dictionary.\\n");
validport = validdict = 1;
}
else{
int i;
for(i = 0; i != argc - 1; i++){
if(strcmp(argv[i], "-p") == 0){
port = atoi(argv[i+1]);
if(port < 10000 || port > 65536){
printf("Invalid port, using default.\\n");
port = DEFAULT_PORT;
}
validport = 1;
}
else if(strcmp(argv[i], "-d") == 0){
if((dictionary = load_dictionary(argv[i+1])) == 0){
printf("invalid dictionary, using default.\\n");
dictionary = load_dictionary(DEFAULT_DICTIONARY);
}
validdict = 1;
}
}
}
if(!validport || !validdict){
printf("Error loading dictionary or getting port number. format: -p PORT -d DICTIONARY.\\n");
return 0;
}
listener = open_listenfd(port);
while(1){
connfd = accept(listener, (struct sockaddr *) &client, &clientlen);
add_to_queue(connfd, &socket_queue);
pthread_t worker_thread;
pthread_create(&worker_thread, 0, worker, 0);
}
free_dictionary(dictionary);
}
void * worker(){
int connfd = remove_from_queue(&socket_queue);
char buffer[200];
char buffer2[200];
int j = 0;
printf("worker has received socket %d to consume.\\n", connfd);
int rec_size = 0;
while(1){
j = 0;
memset(buffer, 0, 200);
memset(buffer2, 0, 200);
rec_size = recv(connfd, buffer, 200,0);
if(buffer[0] == EOF){break;}
if(rec_size == 2){
while(buffer[0] != '\\n'){
buffer2[j] = buffer[0];
recv(connfd, buffer,1,0);
j++;
}
buffer2[j-1] = '\\0';
}else if(rec_size > 2){
while(buffer[j] != '\\n'){
buffer2[j] = buffer[j];
j++;
}
buffer2[j-1] = '\\0';
}
printf("%s\\n", buffer);
pthread_mutex_lock(&socket_queue.mutex_dict);
int result = search_dictionary(dictionary, buffer2);
pthread_mutex_unlock(&socket_queue.mutex_dict);
if(result == 1){
strcat(buffer2, OK);
send(connfd, buffer2, strlen(buffer2),0);
}
else{
strcat(buffer2, MISSPELLED);
send(connfd, buffer2, strlen(buffer2), 0);
}
send(connfd, NEXT_WORD, strlen(NEXT_WORD), 0);
}
printf("Closing %d.\\n", connfd);
close(connfd);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
sleep(5);
if(count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 1
|
#include <pthread.h>
int buffer[10];
int inicio = 0, final = 0, cont = 0;
pthread_mutex_t bloqueio;
pthread_cond_t nao_vazio, nao_cheio;
void* produtor(void *v) {
int i, aux;
for (i = 0; i < 2 * 10; i++) {
pthread_mutex_lock(&bloqueio);
while (cont == 10) {
pthread_cond_wait(&nao_cheio, &bloqueio);
}
final = (final + 1) % 10;
buffer[final] = i;
printf("Produtor, item = %d, posiΓ§Γ£o = %d.\\n", i, final);
aux = cont;
printf("Produtor leu total = %d.\\n", cont);
sleep(random() % 3);
cont = aux + 1;
printf("Produtor atualizou total = %d.\\n", cont);
pthread_cond_signal(&nao_vazio);
pthread_mutex_unlock(&bloqueio);
sleep(random() % 3);
}
printf("ProduΓ§Γ£o encerrada.\\n");
return 0;
}
void* consumidor(void *v) {
int i, aux;
for (i = 0; i < 2 * 10; i++) {
pthread_mutex_lock(&bloqueio);
while (cont == 0) {
pthread_cond_wait(&nao_vazio, &bloqueio);
}
inicio = (inicio + 1) % 10;
aux = buffer[inicio];
printf("Consumidor, item = %d, posiΓ§Γ£o = %d.\\n", aux, inicio);
aux = cont;
printf("Consumidor leu total = %d.\\n", cont);
sleep(random() % 3);
cont = aux - 1;
printf("Consumidor atualizou total = %d.\\n", cont);
pthread_cond_signal(&nao_cheio);
pthread_mutex_unlock(&bloqueio);
sleep(random() % 3);
}
printf("Consumo encerrado.\\n");
return 0;
}
int main() {
int i;
pthread_t thr_produtor, thr_consumidor;
pthread_mutex_init(&bloqueio, 0);
pthread_cond_init(&nao_cheio, 0);
pthread_cond_init(&nao_vazio, 0);
for (i = 0; i < 10; i++)
buffer[i] = 0;
pthread_create(&thr_produtor, 0, produtor, 0);
pthread_create(&thr_consumidor, 0, consumidor, 0);
pthread_join(thr_produtor, 0);
pthread_join(thr_consumidor, 0);
return 0;
}
| 0
|
#include <pthread.h>
int value;
int divisors;
} result_t;
int g_max;
int g_next;
pthread_mutex_t g_next_mtx;
int g_step = 1;
result_t g_best;
int g_processed;
pthread_mutex_t g_best_mtx;
pthread_cond_t g_best_cnd;
int num_divisors(int v) {
int cnt = 0;
for (int i = 1; i <= v; i++)
if (v % i == 0)
cnt++;
return (cnt);
}
int inc_value() {
int r;
pthread_mutex_lock(&g_next_mtx);
r = g_next;
g_next += g_step;
pthread_mutex_unlock(&g_next_mtx);
return (r);
}
void update_best(result_t *res) {
pthread_mutex_lock(&g_best_mtx);
g_processed += g_step;
if (g_best.divisors < res->divisors) {
g_best = *res;
}
pthread_cond_signal(&g_best_cnd);
pthread_mutex_unlock(&g_best_mtx);
}
void *thread(void *p) {
result_t res, best;
int end;
bzero(&best, sizeof (result_t));
while ((res.value = inc_value()) <= g_max) {
end = ((res.value + g_step) < (g_max + 1) ? (res.value + g_step) : (g_max + 1));
for (; res.value < end; res.value++) {
res.divisors = num_divisors(res.value);
if (res.divisors > best.divisors) {
best = res;
}
}
update_best(&best);
}
return (0);
}
int main(int argc, char *argv[]) {
pthread_t thread_pool[5];
void *r;
int value;
if (argc < 2) {
fprintf(stderr, "chybi argument\\n");
return (1);
}
if (argc > 2) {
g_step = ((atoi(argv[2])) > (1) ? (atoi(argv[2])) : (1));
}
bzero(&g_best, sizeof (result_t));
value = 0;
g_max = atoi(argv[1]);
g_next = 0;
g_processed = 0;
pthread_mutex_init(&g_next_mtx, 0);
pthread_mutex_init(&g_best_mtx, 0);
pthread_cond_init(&g_best_cnd, 0);
for (int i = 0; i < 5; i++)
pthread_create(&thread_pool[i], 0, thread, 0);
pthread_mutex_lock(&g_best_mtx);
do {
pthread_cond_wait(&g_best_cnd, &g_best_mtx);
if (g_best.value != value) {
printf("\\nNovy nejlepsi vysledek [%d]: %d\\n", g_best.value, g_best.divisors);
value = g_best.value;
}
printf("\\r%3.02f%%", 100.0f * ((float) g_processed / (float) g_max));
} while (g_processed < g_max);
pthread_mutex_unlock(&g_best_mtx);
printf("\\nNejvice delitelu ma %d: %d\\n", g_best.value, g_best.divisors);
for (int i = 0; i < 5; i++)
pthread_join(thread_pool[i], &r);
pthread_cond_destroy(&g_best_cnd);
pthread_mutex_destroy(&g_best_mtx);
pthread_mutex_destroy(&g_next_mtx);
return (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_mutex;
int count;
int buffer[100];
int produce_item() {
return rand();
}
void consume_item(int item) {
return;
}
void *producer() {
int item;
while(1) {
item = produce_item();
if(count < 100) {
pthread_mutex_lock(&count_mutex);
buffer[count++] = item;
pthread_mutex_unlock(&count_mutex);
}else{
printf("Buffer Full\\n");
sched_yield();
}
}
}
void *consumer() {
int item;
while(1) {
if(count > 0) {
pthread_mutex_lock(&count_mutex);
item = buffer[--count];
consume_item(item);
pthread_mutex_unlock(&count_mutex);
}else {
printf("Buffer empty\\n");
sched_yield();
}
}
}
int main() {
int iret1, iret2;
count = 0;
pthread_mutex_init(&count_mutex, 0);
srand(time(0));
pthread_t producerThread;
iret1 = pthread_create(&producerThread, 0, producer, (void *) 0);
if(iret1) {
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret1);
exit(1);
}
pthread_t consumerThread;
iret2 = pthread_create(&consumerThread, 0, consumer, (void *) 0);
if(iret1) {
fprintf(stderr,"Error - pthread_create() return code: %d\\n",iret2);
exit(1);
}
pthread_join(producerThread, 0);
pthread_join(consumerThread, 0);
return 0;
}
| 0
|
#include <pthread.h>
void init_recursos_jugadores() {
ronda_jugada = 1;
poner_manos = 0;
quitar_manos = 0;
manos_en_centro = 0;
cartas_recogidas = 0;
pthread_mutex_init( &manotazo , 0 );
pthread_mutex_init( &poner_mano , 0 );
pthread_mutex_init( &quitar_mano , 0 );
pthread_cond_init( &cond_poner_manos , 0 );
pthread_cond_init( &cond_juego , 0 );
pthread_cond_init( &cond_quitar_manos , 0 );
pthread_mutex_unlock( &manotazo );
pthread_mutex_unlock( &poner_mano );
pthread_mutex_unlock( &quitar_mano );
}
void liberar_recursos_jugadores() {
pthread_mutex_destroy( &manotazo );
pthread_mutex_destroy( &poner_mano );
pthread_mutex_destroy( &quitar_mano );
pthread_cond_destroy( &cond_poner_manos );
pthread_cond_destroy( &cond_quitar_manos );
pthread_cond_destroy( &cond_juego );
}
void * manos(void * param) {
long me = ( long ) param;
pthread_t los_ojos;
int estado_hilo = pthread_create( &los_ojos, 0, ojos , (void *) me );
if( estado_hilo ){
fprintf( stderr, "%s" , crear_ojos_error);
liberar_recursos();
exit(1);
}
while( !fin_del_juego ){
pthread_mutex_lock( &mtx_jugadores[me] );
int carta_a_poner;
if( !fin_del_juego ){
if( cuenta_cartas[me] ){
carta_siguiente = ( carta_siguiente + 1 ) % CARTAS_EN_PINTA;
carta_a_poner = cartas_jugadores[me][cuenta_cartas[me] -1];
cartas[ cartas_centro ] = carta_a_poner;
++cartas_centro;
cartas_jugadores[me][cuenta_cartas[me] -1] = NO_CARTA;
--cuenta_cartas[me];
if( carta_siguiente == carta_a_poner ){
pthread_mutex_lock( &manotazo );
cartas_recogidas = 0;
poner_manos = 1;
imprimir_juego( ronda_jugada );
++ronda_jugada;
pthread_cond_broadcast ( &cond_poner_manos );
pthread_cond_wait ( &cond_juego , &manotazo );
pthread_mutex_unlock ( &manotazo );
}
}
}else{
break;
}
int i;
for( i = 0; i < num_jugadores; ++i){
if( ( cuenta_cartas[i] == 0 && cartas_centro == 0 ) || cartas_centro == 52 ){
pthread_mutex_lock ( &manotazo);
fin_del_juego = 1;
poner_manos = 1;
pthread_mutex_unlock ( &manotazo);
pthread_cond_broadcast ( &cond_poner_manos );
break;
}
}
pthread_mutex_unlock( &mtx_jugadores[SIGUIENTE] );
}
pthread_join( los_ojos , 0 );
return 0;
}
void * ojos(void * param) {
long me = (long) param;
while( !fin_del_juego ){
pthread_mutex_lock( &manotazo );
while( poner_manos != 1) pthread_cond_wait( &cond_poner_manos , &manotazo );
if (fin_del_juego) {
pthread_mutex_unlock( &manotazo );
break;
}
usleep( arc4random() % 500 );
pthread_mutex_lock( &poner_mano );
++manos_en_centro;
if( manos_en_centro == num_jugadores ){
tomar_cartas(me);
manos_en_centro = 0;
poner_manos = 0;
cartas_recogidas = 1;
int i;
for(i=0; i < num_jugadores; ++i){
if( cuenta_cartas[i] == 0 ){
fin_del_juego = 1;
}
}
}
pthread_mutex_unlock( &poner_mano );
pthread_mutex_unlock( &manotazo );
pthread_mutex_lock( &quitar_mano );
++quitar_manos;
if( quitar_manos < num_jugadores ){
pthread_cond_wait( &cond_quitar_manos ,&quitar_mano );
}else if (quitar_manos == num_jugadores) {
quitar_manos = 0;
pthread_cond_broadcast( &cond_quitar_manos );
pthread_cond_signal ( &cond_juego );
}
pthread_mutex_unlock( &quitar_mano );
}
return 0;
}
void * tomar_cartas(long me) {
fprintf( stdout , "%s %ld\\n" , jugador_pierde , me + 1 );
int mazo_aux[CARTAS], i;
for(i=0; i < CARTAS; ++i ) mazo_aux[i] = NO_CARTA;
for(i=0; i < cartas_centro; ++i){
mazo_aux[i] = cartas[i];
cartas[i] = NO_CARTA;
}
for(i=0; i < cuenta_cartas[me]; ++i)
mazo_aux[cartas_centro + i] = cartas_jugadores[me][i];
cuenta_cartas[me] += cartas_centro;
cartas_centro = 0;
for(i=0; i < cuenta_cartas[me]; ++i)
cartas_jugadores[me][i] = mazo_aux[i];
return 0;
}
void forzar_salida() {
fin_del_juego = 1;
cartas_recogidas = 1;
pthread_mutex_unlock( &poner_mano );
}
| 1
|
#include <pthread.h>
enum pattern_status pattern_port_sched_init(struct pattern * p) {
pthread_mutex_init(&p->port.mutex_running, 0);
pthread_mutex_init(&p->port.mutex_yielded, 0);
return pattern_ok;
}
enum pattern_status pattern_port_create_task(struct pattern_task * t) {
struct pattern * const sched = t->pat;
pthread_mutex_init(&t->port.mutex_run, 0);
pthread_mutex_lock(&t->port.mutex_run);
pthread_mutex_lock(&sched->port.mutex_yielded);
pthread_create(
&t->port.thread, 0,
(void *(*)(void *))t->entry, t);
pthread_mutex_lock(&sched->port.mutex_yielded);
pthread_mutex_unlock(&sched->port.mutex_running);
pthread_mutex_unlock(&sched->port.mutex_yielded);
return pattern_ok;
}
enum pattern_status pattern_port_run_task(struct pattern_task * t) {
struct pattern * const sched = t->pat;
pthread_mutex_lock(&sched->port.mutex_running);
pthread_mutex_lock(&sched->port.mutex_yielded);
pthread_mutex_unlock(&t->port.mutex_run);
pthread_mutex_lock(&sched->port.mutex_running);
pthread_mutex_lock(&sched->port.mutex_yielded);
pthread_mutex_unlock(&sched->port.mutex_running);
pthread_mutex_unlock(&sched->port.mutex_yielded);
return pattern_ok;
}
enum pattern_status pattern_port_task_yield(struct pattern_task * t) {
struct pattern * const sched = t->pat;
pthread_mutex_unlock(&sched->port.mutex_yielded);
pthread_mutex_lock(&t->port.mutex_run);
pthread_mutex_unlock(&sched->port.mutex_running);
return pattern_ok;
}
| 0
|
#include <pthread.h>
struct data_array {
int count;
pthread_mutex_t lock;
} data[5];
void *threadFunc(void *id){
int num = *((int*)id);
for(int a=0; a<5; a++){
int rand_count = (rand() %100);
int rand_ptr = (rand() %5);
pthread_mutex_lock(&data[rand_ptr].lock);
printf("[%d]: Locked struct %d\\n",num,rand_ptr);
printf("[%d]: Updating struct %d , adding %d to count\\n",num,rand_ptr,rand_count);
data[rand_ptr].count = data[rand_ptr].count + rand_count;
pthread_mutex_unlock(&data[rand_ptr].lock);
}
}
int main(){
pthread_t tid[10];
srand((unsigned) time(0));
for ( int i=0; i<5; i++ ){
data[i].count = 0;
}
for ( int i=0; i<5; i++ ) {
pthread_mutex_init(&data[i].lock, 0);
}
int thread_num[10];
for ( int i=0; i<10; i++) {
thread_num[i] = i+1;
pthread_create(&tid[i], 0, threadFunc, &thread_num[i]);
}
for ( int i=0; i<10; i++) {
pthread_join(tid[i], 0);
}
for ( int i=0; i<5; i++) {
printf("Data[%d] count = %d\\n",i,data[i].count);
}
exit(0);
}
| 1
|
#include <pthread.h>
int stack[100][2];
int size=0;
sem_t sem;
pthread_mutex_t mutex;
void ReadData1(void){
FILE *fp=fopen("1.dat","r");
while(!feof(fp)){
pthread_mutex_lock(&mutex);
fscanf(fp,"%d %d",&stack[size][0],&stack[size][1]);
printf("%d\\n", size);
sem_post(&sem);
++size;
pthread_mutex_unlock(&mutex);
}
fclose(fp);
}
void ReadData2(void){
FILE *fp=fopen("2.dat","r");
while(!feof(fp)){
pthread_mutex_lock(&mutex);
printf("%d\\n", size);
fscanf(fp,"%d %d",&stack[size][0],&stack[size][1]);
sem_post(&sem);
++size;
pthread_mutex_unlock(&mutex);
}
fclose(fp);
}
void HandleData1(void){
while(1){
sem_wait(&sem);
pthread_mutex_lock(&mutex);
--size;
printf("Plus(%d):%d+%d=%d\\n",size, stack[size][0],stack[size][1],
stack[size][0]+stack[size][1]);
pthread_mutex_unlock(&mutex);
}
}
void HandleData2(void){
while(1){
sem_wait(&sem);
pthread_mutex_lock(&mutex);
--size;
printf("Multiply(%d):%d*%d=%d\\n", size, stack[size][0],stack[size][1],
stack[size][0]*stack[size][1]);
pthread_mutex_unlock(&mutex);
}
}
int main(void){
pthread_t t1,t2,t3,t4;
sem_init(&sem,0,0);
pthread_create(&t1,0,(void *)HandleData1,0);
pthread_create(&t2,0,(void *)HandleData2,0);
pthread_create(&t3,0,(void *)ReadData1,0);
pthread_create(&t4,0,(void *)ReadData2,0);
pthread_join(t1,0);
}
| 0
|
#include <pthread.h>
struct thread_info {
pthread_cond_t cond;
pthread_mutex_t mux;
void *p;
};
void *
thread_func(void *p)
{
struct thread_info *info = p;
for (;;) {
pthread_mutex_lock(&info->mux);
pthread_cond_wait(&info->cond, &info->mux);
free(info->p);
pthread_mutex_unlock(&info->mux);
}
}
int
main(int argc, char *argv[])
{
struct thread_info *infos;
pthread_t *threads;
size_t nthreads = 4, niters = 1000000, alloc_sz = 64, i;
int ch, e;
const char *errstr;
struct timespec start, end;
long long dur;
while ((ch = getopt(argc, argv, "n:s:t:")) != -1) {
switch (ch) {
case 'n':
niters = strtonum(optarg, 1, LLONG_MAX, &errstr);
if (errstr != 0)
errx(1, "number of iterations is %s: %s", errstr, optarg);
break;
case 's':
alloc_sz = strtonum(optarg, 1, LLONG_MAX, &errstr);
if (errstr != 0)
errx(1, "allocation size is %s: %s", errstr, optarg);
break;
case 't':
nthreads = strtonum(optarg, 1, LLONG_MAX, &errstr);
if (errstr != 0)
errx(1, "number of threads is %s: %s", errstr, optarg);
break;
default:
errx(1, "%s: [-n niters] [-s alloc_size] [-t nthreads]", getprogname());
}
}
infos = reallocarray(0, nthreads, sizeof(struct thread_info));
if (infos == 0)
err(1, 0);
threads = reallocarray(0, nthreads, sizeof(pthread_t));
if (threads == 0)
err(1, 0);
for (i = 0; i < nthreads; i++) {
if ((e = pthread_cond_init(&infos[i].cond, 0)) != 0)
errx(1, "pthread_cond_init: %s", strerror(e));
if ((e = pthread_mutex_init(&infos[i].mux, 0)) != 0)
errx(1, "pthread_mutex_init: %s", strerror(e));
if ((e = pthread_create(&threads[i], 0, thread_func, &infos[i].cond)) != 0)
errx(1, "pthread_create: %s", strerror(e));
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start);
for (i = 0; i < niters; i++) {
pthread_mutex_lock(&infos[i % nthreads].mux);
if ((infos[i % nthreads].p = malloc(alloc_sz)) == 0)
err(1, 0);
pthread_mutex_unlock(&infos[i % nthreads].mux);
if ((e = pthread_cond_signal(&infos[i % nthreads].cond)) != 0)
errx(1, "pthread_cond_signal: %s", strerror(e));
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end);
dur = (end.tv_sec * 1000000000 + end.tv_nsec) -
(start.tv_sec * 1000000000 + start.tv_nsec);
printf("nthreads = %zu\\tniters = %zu\\talloc_sz = %zu\\tCPU time (nsecs): %lld\\n",
nthreads, niters, alloc_sz, dur);
return 0;
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *
thr_fn(void *arg)
{
int err, signo;
fprintf(stdout, "cat interrupt thread id: %d\\n", (int )pthread_self());
fprintf(stdout, "process id: %d\\n", getpid());
for (; ; )
{
err = sigwait(&mask, &signo);
if (err != 0)
{
fprintf(stderr, "sigwait failed\\n");
exit(1);
}
switch (signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return (0);
default:
printf("unexpected signal %d\\n", signo);
exit(1);
}
}
}
int
main(int argc, char *argv[])
{
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)
{
fprintf(stderr, "pthread_sigmask SIG_BLOCK error!\\n");
exit(1);
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0)
{
fprintf(stderr, "pthread_create error\\n");
exit(1);
}
else
{
fprintf(stdout, "main thread id: %d\\n", (int )pthread_self());
fprintf(stdout, "process id: %d\\n", getpid());
}
pthread_mutex_lock(&lock);
while (quitflag == 0)
{
pthread_cond_wait(&wait, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0)
{
fprintf(stderr, "SIG_SETMASK error\\n");
exit(1);
}
exit(0);
}
| 0
|
#include <pthread.h>
const int round_max = 50000;
const int readers_max = 5;
const int writers_max = 10;
const int sleep_ms = 100;
item_t value;
int readers;
pthread_mutex_t write_lock;
pthread_mutex_t read_lock;
} data_t;
data_t* data;
int id;
} thread_t;
void* read_loop (void* param) {
thread_t* thread = (thread_t*) param;
data_t* data = thread->data;
int round = 0;
int error;
printf("R%d [%d] %d: START\\n", thread->id, data->readers, round);
while (round < round_max) {
++round;
printf("R%d [%d] %d: RL...\\n", thread->id, data->readers, round);
pthread_mutex_lock(&data->read_lock);
printf("R%d [%d] %d: RL\\n", thread->id, data->readers, round);
++data->readers;
if (data->readers == 1) {
printf("R%d [%d] %d: WL...\\n", thread->id, data->readers, round);
pthread_mutex_lock(&data->write_lock);
printf("R%d [%d] %d: WL\\n", thread->id, data->readers, round);
}
pthread_mutex_unlock(&data->read_lock);
printf("R%d [%d] %d: RU\\n", thread->id, data->readers, round);
printf("R%d [%d] %d: = %d\\n", thread->id, data->readers, round, data->value);
printf("R%d [%d] %d: RL...\\n", thread->id, data->readers, round);
pthread_mutex_lock(&data->read_lock);
printf("R%d [%d] %d: RL\\n", thread->id, data->readers, round);
--data->readers;
if (data->readers == 0) {
pthread_mutex_unlock(&data->write_lock);
printf("R%d [%d] %d: WU\\n", thread->id, data->readers, round);
}
pthread_mutex_unlock(&data->read_lock);
printf("R%d [%d] %d: RU\\n", thread->id, data->readers, round);
usleep(sleep_ms);
}
printf("R%d [%d] %d: FINISH\\n", thread->id, data->readers, round);
}
void* write_loop (void* param) {
thread_t* thread = (thread_t*) param;
data_t* data = thread->data;
int round = 0;
int error;
printf("W%d [%d] %d: START\\n", thread->id, data->readers, round);
while (round < round_max) {
++round;
printf("W%d [%d] %d: WL...\\n", thread->id, data->readers, round);
pthread_mutex_lock(&data->write_lock);
printf("W%d [%d] %d: WL\\n", thread->id, data->readers, round);
data->value = random();
printf("W%d [%d] %d: = %ld\\n", thread->id, data->readers, round, data->value);
pthread_mutex_unlock(&data->write_lock);
printf("W%d [%d] %d: WU\\n", thread->id, data->readers, round);
usleep(sleep_ms);
}
printf("W%d [%d] %d: FINISH\\n", thread->id, data->readers, round);
}
int main(int argc, char** argv) {
int i;
int error;
data_t data;
thread_t readers[readers_max];
thread_t writers[writers_max];
pthread_t reader_threads[readers_max];
pthread_t writer_threads[writers_max];
data.value = -1;
data.readers = 0;
pthread_mutex_init(&data.read_lock, 0);
pthread_mutex_init(&data.write_lock, 0);
for (i = 0; i < readers_max; ++i) {
readers[i].id = i;
readers[i].data = &data;
pthread_create(&reader_threads[i], 0, read_loop, &readers[i]);
}
for (i = 0; i < writers_max; ++i) {
writers[i].id = i;
writers[i].data = &data;
pthread_create(&writer_threads[i], 0, write_loop, &writers[i]);
}
for (i = 0; i < readers_max; ++i) {
printf("Main thread waiting for reader %d...\\n", i);
pthread_join(reader_threads[i], 0);
}
for (i = 0; i < writers_max; ++i) {
printf("Main thread waiting for writer %d...\\n", i);
pthread_join(writer_threads[i], 0);
}
printf("Program finished\\n");
}
| 1
|
#include <pthread.h>
void exitfunc(int sig)
{
_exit(0);
}
void compfunc(int a,int b,int c){
printf("There are %d signals that have been changed.\\n",a);
printf("There are %d signals that have been changed from 0 to 1.\\n",b);
printf("There are %d signals that have been detected.\\n",c);
if(b==c){
printf("All signals that changed from 0 to 1, have been detected so far!\\n\\n");
}
};
volatile int *signalArray;
volatile int *prevArray;
struct timeval *timeStamp;
int N,T,split;
int Asignals=0,Bsignals=0,Csignals=0;
FILE *f;
pthread_mutex_t SignalMutex = PTHREAD_MUTEX_INITIALIZER;
void *SensorSignalReader (void *args);
void *ChangeDetector (void *args);
int main(int argc, char **argv)
{
int i,temp,Tstart;
f = fopen("log.txt","w+");
fprintf(f,"Detection Time (in seconds)\\r\\n\\r\\n");fflush(f);
N = atoi(argv[1]);
if (argc != 2) {
printf("\\nUsage: %s N \\n"
" where\\n"
" N : number of signals to monitor\\n"
, argv[0]);
return (1);
}
if (N>=1 && N<=600){
T=1;
}
if (N>600 && N<=1100){
T=2;
}
if (N>1100 && N<=4400){
T=4;
}
if (N>4400){
printf ("\\n\\nThe current system cant handle over 4400 Signals in order to achieve time lower than 1usec\\n\\n ");
return(1);
}
split=N/T;
printf("\\n\\nNumber of Signals : %d \\n\\n"
"Number of Threads : %d \\n\\n"
"Number of Signal per Thread : %d \\n\\n\\n",N,T,split);
signal(SIGALRM, exitfunc);
alarm(20);
signalArray = (int *) malloc(N*sizeof(int));
timeStamp = (struct timeval *) malloc(N*sizeof(struct timeval));
prevArray = (int *) malloc(N*sizeof(int));
pthread_t sigGen;
pthread_t sigDet[T];
for (i=0; i<N; i++) {
signalArray[i] = 0;
prevArray[i]=0;
}
pthread_mutex_init(&SignalMutex, 0);
for (i=0; i<T; i++){
pthread_create (&sigDet[i], 0, ChangeDetector, (void *)(intptr_t) i);
}
pthread_create (&sigGen, 0, SensorSignalReader, 0);
for (i=0; i<T; i++){
pthread_join (sigDet[i], 0);
}
fclose (f);
return 0;
}
void *SensorSignalReader (void *arg)
{
char buffer[30];
struct timeval tv;
time_t curtime;
srand(time(0));
while (1) {
int t = rand() % 10 + 1;
usleep(t*100000);
int r = rand() % N;
pthread_mutex_lock(&SignalMutex);
signalArray[r] ^= 1;
Asignals+=1;
if (signalArray[r]) {
Bsignals+=1;
gettimeofday(&tv, 0);
timeStamp[r] = tv;
curtime = tv.tv_sec;
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
printf("Changed %5d at Time %s%ld\\n",r,buffer,tv.tv_usec);
}
pthread_mutex_unlock(&SignalMutex);
}
}
void *ChangeDetector (void *arg)
{
char buffer[30];
struct timeval tv;
time_t curtime;
int i,Tnum,Tstart,Tend,x,y;
Tnum=(intptr_t)arg;
Tstart=Tnum*split;
Tend=(Tnum+1)*split;
while (1) {
for(i=Tstart; i<Tend; i++)
{
x=prevArray[i];
y=signalArray[i];
if(x != y)
{
if(y == 1)
{
Csignals+=1;
gettimeofday(&tv, 0);
curtime = tv.tv_sec;
strftime(buffer,30,"%d-%m-%Y %T.",localtime(&curtime));
pthread_mutex_lock(&SignalMutex);
printf("Detected %5d at Time %s%ld after %ld.%06ld sec\\n", i, buffer, tv.tv_usec,
tv.tv_sec - timeStamp[i].tv_sec,
tv.tv_usec - timeStamp[i].tv_usec);
pthread_mutex_unlock(&SignalMutex);
pthread_mutex_lock(&SignalMutex);
fprintf(f,"\\n%ld.%06ld\\r\\n",tv.tv_sec - timeStamp[i].tv_sec,tv.tv_usec - timeStamp[i].tv_usec); fflush(f);
pthread_mutex_unlock(&SignalMutex);
compfunc(Asignals,Bsignals,Csignals);
prevArray[i]=1;
}
else
{
prevArray[i]=0;
}
}
}
}
}
| 0
|
#include <pthread.h>
int Q[20];
int front = -1;
int rear = -1;
int c = 0;
pthread_mutex_t mutex;
sem_t full;
sem_t empty;
void *Supervisor(void *arg){
while( c < -5) {
int student = (int)arg;
pthread_detach(pthread_self());
sem_wait(&empty);
pthread_mutex_lock(&mutex);
rear = rear + 1;
if (rear >= 20){
rear = 0;
}
Q[rear] = student;
printf("%4d.Student was called to the presentation \\n", student+1);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
c--;
printf(" Counting value c after decremented by Supervisor : %d\\n",c);
}
void *Student(void *arg){
int student = 0;
int studentRemoved= 0;
printf("Presentations started \\n");
while (studentRemoved < 80){
sem_wait(&full);
pthread_mutex_lock(&mutex);
front = front + 1;
if (front >= 20 ) front = 0;
student = Q[front];
printf("%4d. Student is done. He was removed from the queue \\n", student+1);
studentRemoved++;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
c++;
printf("Counting value after the c incremented by the Student : %d \\n",c);
usleep((int)(drand48()*500000));
}
}
int main(int argc,char *argv[]){
int i;
pthread_t supervisorid;
pthread_t queueId;
srand48(time(0));
pthread_mutex_init(&mutex,0);
sem_init(&full, 0, 5);
sem_init(&empty, 0, 20);
pthread_create(&queueId, 0, Student, 0);
for(i=0; i < 80;i++){
pthread_create(&supervisorid, 0, Supervisor , (void *)i);
}
pthread_join(queueId, 0);
}
| 1
|
#include <pthread.h>
struct pp_thread_info {
int *msgcount;
pthread_mutex_t *mutex;
pthread_cond_t *cv;
char *msg;
int modval;
};
void *
pp_thread(void *arg)
{
struct pp_thread_info *infop;
int c;
infop = arg;
while (*infop->msgcount < 50) {
pthread_mutex_lock(infop->mutex);
while (*infop->msgcount % 2 != infop->modval)
pthread_cond_wait(infop->cv, infop->mutex);
printf("%s\\n", infop->msg);
c = *infop->msgcount;
usleep(10);
c = c + 1;
*infop->msgcount = c;
pthread_cond_broadcast(infop->cv);
pthread_mutex_unlock(infop->mutex);
}
return (0);
}
int
main(void)
{
int msgcount;
pthread_cond_t cv;
pthread_mutex_t mutex;
pthread_t ping_id1, pong_id1;
pthread_t ping_id2, pong_id2;
struct pp_thread_info ping, pong;
msgcount = 0;
if (pthread_mutex_init(&mutex, 0) != 0) {
fprintf(stderr, "Pingpong: Mutex init failed %s\\n", strerror(errno));
exit(1);
}
if (pthread_cond_init(&cv, 0) != 0) {
fprintf(stderr, "Pingpong: CV init failed %s\\n", strerror(errno));
exit(1);
}
ping.msgcount = &msgcount;
ping.mutex = &mutex;
ping.cv = &cv;
ping.msg = "ping";
ping.modval = 0;
pong.msgcount = &msgcount;
pong.mutex = &mutex;
pong.cv = &cv;
pong.msg = "pong";
pong.modval = 1;
if ((pthread_create(&ping_id1, 0, &pp_thread, &ping) != 0) ||
(pthread_create(&pong_id1, 0, &pp_thread, &pong) != 0) ||
(pthread_create(&ping_id2, 0, &pp_thread, &ping) != 0) ||
(pthread_create(&pong_id2, 0, &pp_thread, &pong) != 0)) {
fprintf(stderr, "pingpong: pthread_create failed %s\\n", strerror(errno));
exit(1);
}
pthread_join(ping_id1, 0);
pthread_join(pong_id1, 0);
pthread_join(ping_id2, 0);
pthread_join(pong_id2, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cv);
printf("Main thread exiting\\n");
}
| 0
|
#include <pthread.h>
struct library_context context;
pthread_mutex_t services_mutex, remotes_mutex;
uint8_t init() {
DEBUG("init %d", context.initialized);
if (context.initialized)
return 1;
srand(time(0));
memset(context.services, 0, UINT16_MAX * sizeof(struct service_id *));
memset(context.remotes, 0, UINT16_MAX * sizeof(struct remote_context *));
netarch_init();
pthread_mutex_init(&services_mutex, 0);
pthread_mutex_init(&remotes_mutex, 0);
pthread_mutex_init(&used_list_mutex, 0);
pthread_mutex_init(&free_list_mutex, 0);
pthread_mutex_init(&recv_window_mutex, 0);
pthread_mutex_init(&rdma_connect_mutex, 0);
pthread_mutex_init(&resolver_mutex, 0);
resolver_init();
return 0;
}
uint16_t ripc_register_random_service_id(void) {
init();
uint16_t service_id;
do {
service_id = rand() % UINT16_MAX;
} while (ripc_register_service_id(service_id) == 0);
return service_id;
}
uint8_t ripc_register_service_id(int service_id) {
init();
DEBUG("Allocating service ID %u", service_id);
struct service_id *service_context;
uint32_t i;
pthread_mutex_lock(&services_mutex);
if (context.services[service_id] != 0) {
pthread_mutex_unlock(&services_mutex);
DEBUG("Tried to allocate service ID %u which was already allocated");
return 0;
}
context.services[service_id] =
(struct service_id *)malloc(sizeof(struct service_id));
memset(context.services[service_id],0,sizeof(struct service_id));
service_context = context.services[service_id];
service_context->number = service_id;
alloc_queue_state(service_context);
pthread_mutex_unlock(&services_mutex);
return 1;
}
uint8_t ripc_register_multicast_service_id(int service_id) {
init();
DEBUG("Allocating multicast service ID %u", service_id);
struct service_id *service_context;
uint32_t i;
pthread_mutex_lock(&services_mutex);
if (context.services[service_id] != 0) {
pthread_mutex_unlock(&services_mutex);
DEBUG("Tried to allocate service ID %u which was already allocated");
return 0;
}
context.services[service_id] =
(struct service_id *)malloc(sizeof(struct service_id));
memset(context.services[service_id],0,sizeof(struct service_id));
service_context = context.services[service_id];
service_context->number = service_id;
service_context->is_multicast = 1;
alloc_queue_state(service_context);
pthread_mutex_unlock(&services_mutex);
return 1;
}
| 1
|
#include <pthread.h>
int Buf1_num=0;
int Buf2_num=0;
int Buf1[10];
int Buf2[10];
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void *thread_fun1(void *args);
void *thread_fun2(void *args);
void *thread_fun3(void *args);
int main(void)
{
pthread_t thread1;
pthread_t thread2;
pthread_t thread3;
if (pthread_create(&thread1,0,thread_fun1,0))
{
fprintf(stderr,"Create pthread_fun1 error!\\n");
exit(-1);
}
if (pthread_create(&thread2,0,thread_fun2,0))
{
fprintf(stderr,"Create pthread_fun2 error!\\n");
exit(-1);
}
if (pthread_create(&thread3,0,thread_fun3,0))
{
fprintf(stderr,"Create pthread_fun3 error!\\n");
exit(-1);
}
pthread_join(thread1,0);
pthread_join(thread2,0);
pthread_join(thread3,0);
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
void * thread_fun1(void *args)
{
char ch;
FILE *in1 =fopen("1.dat","r");
if(in1==0)
{
printf("Failed to open file!");
exit (0);
}
while (!feof(in1))
{
pthread_mutex_lock(&mutex1);
fscanf(in1, "%d", &Buf1[Buf1_num++]);
pthread_mutex_unlock(&mutex1);
}
fclose(in1);
return 0;
}
void *thread_fun2(void *args)
{
char ch;
FILE *in2=fopen("2.dat","r");
if(in2==0)
{
printf("Failed to open file!");
exit (0);
}
while (!feof(in2))
{
pthread_mutex_lock(&mutex1);
fscanf(in2, "%d", &Buf2[Buf2_num++]);
pthread_mutex_unlock(&mutex1);
}
fclose(in2);
return 0;
}
void *thread_fun3(void *args)
{
int i=0;
while (i < 10)
{
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
if(i<Buf1_num && i<Buf2_num)
{
fprintf(stderr,"%d+%d=%d,%d*%d=%d\\n", Buf1[i], Buf2[i], Buf1[i] + Buf2[i], Buf1[i], Buf2[i], Buf1[i] * Buf2[i]);
i++;
}
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
time_t t = time(0);
char tmp[200];
strftime(tmp, sizeof(tmp), "%c",localtime(&t) );
printf("%s\\n", tmp);
return 0;
}
| 0
|
#include <pthread.h>
void usage(){
fprintf(stderr,"Usage: ./make_threads <no_threads> <sum_up_to>\\n");
}
unsigned long long global_sum;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
void * up_to_n(void *args){
int *n = args;
int i;
unsigned long long local_sum = 0;
for (i =1 ; i <= *n; i++){
local_sum += i;
}
pthread_mutex_lock(&mut);
global_sum += local_sum;
pthread_mutex_unlock(&mut);
return 0;
}
int main(int argc, char ** argv){
int t, n, i, s;
pthread_t* threads;
pthread_attr_t attr;
void * res;
if (argc < 2) {
fprintf(stderr,"Need to specify two arguments to the command line\\n");
usage();
exit(1);
}
t = atoi(argv[1]);
n = atoi(argv[2]);
threads = calloc(t,sizeof(*threads));
global_sum = 0;
s= pthread_attr_init(&attr);
if ( s != 0)
do { errno = s; perror("pthread_attr_init"); exit(1); } while (0);
s = pthread_attr_destroy(&attr);
if (s != 0)
do { errno = s; perror("pthread_attr_destroy"); exit(1); } while (0);
for (i = 0; i < t; i ++){
pthread_create(&threads[i], &attr, &up_to_n, (void *) &n);
}
for (i = 0; i < t; i++){
s = pthread_join(threads[i], &res);
if ( s != 0 )
do { errno = s; perror("pthread_join"); exit(1); } while (0);
}
printf("%lld\\n", global_sum);
free(threads);
exit(0);
}
| 1
|
#include <pthread.h>
struct testdata
{
pthread_mutex_t mutex;
pthread_cond_t cond;
} td;
int t1_start = 0;
int signaled = 0;
void *t1_func(void *arg)
{
int rc;
struct timespec timeout;
struct timeval curtime;
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Thread1: Fail to acquire mutex\\n");
exit(PTS_UNRESOLVED);
}
fprintf(stderr,"Thread1 started\\n");
t1_start = 1;
if (gettimeofday(&curtime, 0) !=0 ) {
fprintf(stderr,"Fail to get current time\\n");
exit(PTS_UNRESOLVED);
}
timeout.tv_sec = curtime.tv_sec;
timeout.tv_nsec = curtime.tv_usec * 1000;
timeout.tv_sec += 5;
fprintf(stderr,"Thread1 is waiting for the cond\\n");
rc = pthread_cond_timedwait(&td.cond, &td.mutex, &timeout);
if(rc != 0) {
if (rc == ETIMEDOUT) {
fprintf(stderr,"Thread1 stops waiting when time is out\\n");
exit(PTS_UNRESOLVED);
}
else {
fprintf(stderr,"pthread_cond_timedwait return %d\\n", rc);
exit(PTS_UNRESOLVED);
}
}
fprintf(stderr,"Thread1 wakened up\\n");
if(signaled == 0) {
fprintf(stderr,"Thread1 did not block on the cond at all\\n");
printf("Test FAILED\\n");
exit(PTS_FAIL);
}
pthread_mutex_unlock(&td.mutex);
return 0;
}
int main()
{
pthread_t thread1;
if (pthread_mutex_init(&td.mutex, 0) != 0) {
fprintf(stderr,"Fail to initialize mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_cond_init(&td.cond, 0) != 0) {
fprintf(stderr,"Fail to initialize cond\\n");
return PTS_UNRESOLVED;
}
if (pthread_create(&thread1, 0, t1_func, 0) != 0) {
fprintf(stderr,"Fail to create thread 1\\n");
return PTS_UNRESOLVED;
}
while(!t1_start)
usleep(100);
if (pthread_mutex_lock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to acquire mutex\\n");
return PTS_UNRESOLVED;
}
if (pthread_mutex_unlock(&td.mutex) != 0) {
fprintf(stderr,"Main: Fail to release mutex\\n");
return PTS_UNRESOLVED;
}
sleep(1);
fprintf(stderr,"Time to wake up thread1 by signaling a condition\\n");
signaled = 1;
if (pthread_cond_signal(&td.cond) != 0) {
fprintf(stderr,"Main: Fail to signal cond\\n");
return PTS_UNRESOLVED;
}
pthread_join(thread1, 0);
printf("Test PASSED\\n");
return PTS_PASS;
}
| 0
|
#include <pthread.h>
uint32_t hash64(uint64_t a)
{
a = a ^ (a>>32);
a = (a+0x7ed55d16) + (a<<12);
a = (a^0xc761c23c) ^ (a>>19);
a = (a+0x165667b1) + (a<<5);
a = (a+0xd3a2646c) ^ (a<<9);
a = (a+0xfd7046c5) + (a<<3);
a = (a^0xb55a4f09) ^ (a>>16);
return (uint32_t)a;
}
int hashtbl_init(struct hash_table *hashtbl, size_t size)
{
pthread_mutex_init(&hashtbl->hmutex, 0);
hashtbl->size = size;
if ((hashtbl->table = calloc(size, sizeof(struct hash_entry*))) == 0)
return -1;
if ((hashtbl->entries = calloc(size, sizeof(struct hash_entry))) == 0)
return -1;
hashtbl->empty_entry = hashtbl->entries;
int i;
for (i = 0; i < size-1; ++i) {
(((struct hash_entry*)hashtbl->entries)+i)->next = (((struct hash_entry*)hashtbl->entries)+i+1);
}
return 0;
}
int hashtbl_put(struct hash_table *hashtbl, struct message_t *msg)
{
pthread_mutex_lock(&hashtbl->hmutex);
if (!hashtbl->empty_entry) {
pthread_mutex_unlock(&hashtbl->hmutex);
return 0;
}
struct hash_entry *hentry, *phe, **pphe;
size_t idx;
hentry = hashtbl->empty_entry;
hentry->hash = hash64(msg->id);
hashtbl->empty_entry = hashtbl->empty_entry->next;
hentry->next = 0;
memcpy(&hentry->value, msg, sizeof(*msg));
idx = hentry->hash % hashtbl->size;
for (pphe = hashtbl->table+idx; (phe = *pphe);) {
if (hentry->hash == phe->hash) {
*pphe = phe->next;
phe->next = hashtbl->empty_entry;
hashtbl->empty_entry = phe;
} else {
pphe = &phe->next;
}
}
hentry->next = hashtbl->table[idx];
hashtbl->table[idx] = hentry;
pthread_mutex_unlock(&hashtbl->hmutex);
return 1;
}
int hashtbl_get(struct hash_table *hashtbl, uint64_t id, struct message_t *val)
{
struct hash_entry **pphe, *phe;
uint32_t hash;
size_t idx;
hash = hash64(id);
idx = hash % hashtbl->size;
pthread_mutex_lock(&hashtbl->hmutex);
for (pphe = hashtbl->table+idx; (phe = *pphe);) {
if (phe->hash == hash) {
memcpy(val, &phe->value, sizeof(*val));
pthread_mutex_unlock(&hashtbl->hmutex);
return 1;
} else {
pphe = &phe->next;
}
}
pthread_mutex_unlock(&hashtbl->hmutex);
return 0;
}
void hashtbl_print(struct hash_table *hashtbl)
{
int i;
struct hash_entry *entry;
struct message_t *msg;
printf("table size: %lu\\n", hashtbl->size);
for (i = 0; i < hashtbl->size; ++i){
entry = hashtbl->table[i];
if (entry){
while (entry) {
msg = &entry->value;
printf("msg| size:%d, type:%d, id:%llu, data:%llu\\n",
msg->size,msg->type,(unsigned long long)msg->id,(unsigned long long)msg->data);
entry=entry->next;
}
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
void decrement_count(int iter);
void increment_count(int iter);
void * thread_body(void * param) {
int i;
pthread_mutex_lock(&lock);
for(i = 0; i <= 10; ++i){
pthread_cond_signal(&cond);
printf("Child %d\\n", i);
if(i != 10){
pthread_cond_wait(&cond, &lock);
}
}
pthread_mutex_unlock(&lock);
return 0;
}
int main(int argc, char *argv[]) {
pthread_t thread;
int code;
int i;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_lock(&lock);
code = pthread_create(&thread, 0, thread_body, 0);
if (code!=0) {
char buf[256];
strerror_r(code, buf, sizeof buf);
fprintf(stderr, "%s: creating thread: %s\\n", argv[0], buf);
exit(1);
}
for(i = 0; i <= 10; ++i){
pthread_cond_signal(&cond);
printf("Parent %d\\n", i);
if(i != 10){
pthread_cond_wait(&cond, &lock);
}
}
pthread_mutex_unlock(&lock);
pthread_join(thread, 0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
| 0
|
#include <pthread.h>
void buffered_queue_init(struct buffered_queue *queue, int size){
queue->size = size+1;
queue->buf = malloc(sizeof(void *) * (size+1));
queue->start_index = 0;
queue->end_index = 0;
pthread_mutex_init(&(queue->lock), 0);
pthread_cond_init(&(queue->cond), 0);
}
void buffered_queue_push(struct buffered_queue *queue, void *item){
pthread_mutex_lock(&(queue->lock));
while((queue->end_index+1)%queue->size == queue->start_index)
pthread_cond_wait(&(queue->cond), &(queue->lock));
queue->buf[queue->end_index] = item;
queue->end_index = (queue->end_index+1)%queue->size;
if((queue->start_index+1)%queue->size == queue->end_index)
pthread_cond_broadcast(&(queue->cond));
pthread_mutex_unlock(&(queue->lock));
}
void* buffered_queue_pop(struct buffered_queue *queue){
void *ret = 0;
pthread_mutex_lock(&(queue->lock));
while(queue->end_index == queue->start_index)
pthread_cond_wait(&(queue->cond), &(queue->lock));
ret = queue->buf[queue->start_index];
queue->start_index = (queue->start_index+1)%queue->size;
if((queue->end_index+2)%queue->size == queue->start_index)
pthread_cond_broadcast(&(queue->cond));
pthread_mutex_unlock(&(queue->lock));
return ret;
}
void buffered_queue_destroy(struct buffered_queue *queue){
free(queue->buf);
pthread_mutex_destroy(&(queue->lock));
pthread_cond_destroy(&(queue->cond));
}
| 1
|
#include <pthread.h>
pthread_mutex_t chopstick_mutexes[PHIL_COUNT];
pthread_mutex_t footman_mutex = PTHREAD_MUTEX_INITIALIZER;;
pthread_cond_t footman_cond = PTHREAD_COND_INITIALIZER;
int footman_count = 0;
void Init(void) {
int i;
for (i=0;i<PHIL_COUNT;i++)
pthread_mutex_init(&chopstick_mutexes[i], 0);
pthread_mutex_init(&footman_mutex, 0);
pthread_cond_init(&footman_cond, 0);
}
void Close(void) {
int i;
for (i=0;i<PHIL_COUNT;i++)
pthread_mutex_destroy(&chopstick_mutexes[i]);
pthread_mutex_destroy(&footman_mutex);
pthread_cond_destroy(&footman_cond);
}
void Philosopher(int phil) {
Think(phil);
int first = phil;
int second = (phil+1)%PHIL_COUNT;
pthread_mutex_lock(&footman_mutex);
while (footman_count == (PHIL_COUNT-1)) pthread_cond_wait(&footman_cond, &footman_mutex);
footman_count++;
pthread_mutex_unlock(&footman_mutex);
pthread_mutex_lock(&chopstick_mutexes[first]);
pthread_mutex_lock(&chopstick_mutexes[second]);
Eat(phil);
pthread_mutex_unlock(&chopstick_mutexes[first]);
pthread_mutex_unlock(&chopstick_mutexes[second]);
pthread_mutex_lock(&footman_mutex);
footman_count--;
pthread_cond_signal(&footman_cond);
pthread_mutex_unlock(&footman_mutex);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void *worker_task(void *args)
{
pthread_mutex_lock(&mutex);
int id = *(int *)(args);
pthread_mutex_unlock(&mutex);
void *context = zmq_ctx_new();
printf("%d zmq_ctx_new\\n", id);
assert(context != 0);
void *worker = zmq_socket(context, ZMQ_REQ);
printf("%d zmq_socket\\n", id);
assert(worker != 0);
s_set_id(worker);
zmq_connect(worker, "tcp://localhost:5671");
printf("%d zmq_connect\\n", id);
int total = 0;
while (1) {
s_send(worker, "Hi Boss");
printf("%d s_send\\n", id);
char *order = s_recv(worker);
printf("%d s_recv\\n", id);
int finished = (strcmp(order, "Fired!") == 0);
free(order);
if (finished) {
printf("[%d] Completed: %d tasks\\n", id, total);
break;
}
total++;
int workload = randof(500) + 1;
s_sleep(workload);
}
zmq_close(worker);
zmq_ctx_destroy(context);
return 0;
}
int main(void)
{
void *context = zmq_ctx_new();
void *broker = zmq_socket(context, ZMQ_ROUTER);
zmq_bind(broker, "tcp://*:5671");
srandom((unsigned int)time(0));
int worker_nbr;
for (worker_nbr = 0; worker_nbr < (10); worker_nbr++) {
pthread_t worker;
pthread_mutex_lock(&mutex);
int rc = pthread_create(&worker, 0, worker_task, &worker_nbr);
pthread_mutex_unlock(&mutex);
assert(0 == rc);
}
int64_t end_time = s_clock() + 5000;
int workers_fired = 0;
while (1) {
char *identity = s_recv(broker);
s_sendmore(broker, identity);
free(identity);
free(s_recv(broker));
free(s_recv(broker));
s_sendmore(broker, "");
if (s_clock() < end_time) {
s_send(broker, "Work harder");
} else {
s_send(broker, "Fired!");
if (++workers_fired == (10)) {
break;
}
}
}
zmq_close(broker);
zmq_ctx_destroy(context);
PAUSE();
return 0;
}
| 1
|
#include <pthread.h>
struct tm *getIsoTm(const struct timeval *t) {
return localtime((time_t*)(&(t->tv_sec)));
}
int getHundredthOfSeconds(const struct timeval *t) {
return (int)(t->tv_usec / 10000);
}
static FILE *openCoverageFile() {
char timestamp[128];
char name[6 + 128 + 6 + 1];
FILE *file = 0;
struct timeval val;
gettimeofday(&val,0);
const struct tm * const ts = getIsoTm(&val);
snprintf(timestamp, 128, "%02d_%02d_%02d_%02d_%02d_%02d_%02d",ts->tm_year % 100, ts->tm_mon, ts->tm_mday, ts->tm_hour, ts->tm_min, ts->tm_sec,getHundredthOfSeconds(&val));
strcpy(name, "synch_");
strcat(name, timestamp);
strcat(name, ".trace");
file = fopen(name, "w");
if (file == 0) {
fprintf(stderr,"\\nERROR : UNABLE TO OPEN FILE\\n");
exit(1);
}
return file;
}
static void reportTask(const char *str) {
static bool fileErrorOccured = FALSE;
if ( ! fileErrorOccured) {
static FILE *covFile = 0;
if (covFile == 0) {
covFile = openCoverageFile();
if (covFile == 0) {
fileErrorOccured = TRUE;
return;
}
}
if (fprintf(covFile, "%s \\n", str) == EOF || fflush(covFile)) {
fprintf(stderr, "fprintf or fflush failed\\n");
fileErrorOccured = TRUE;
}
}
}
static unsigned int hash_value(const char *str)
{
unsigned int hash_value=0;
for(;*str;str++)
{
hash_value+= *str;
}
return hash_value;
}
static int taskEncountered(const char *str)
{
{struct taskListCell *next; const char *str;}
taskListCell;
static int capacity = 64;
static taskListCell **taskSet = 0;
static int setSize;
taskListCell *iter, *newOne;
int hashCode = hash_value(str);
int index = hashCode % capacity;
if (taskSet == 0) {
taskSet = (taskListCell**)calloc(capacity,sizeof(taskListCell*));
if (taskSet == 0)
{
fprintf(stderr, "error while allocating memory\\n");
return -1;
}
setSize = 0;
}
for (iter = taskSet[index]; iter != 0; iter = iter->next) {
if (!strcmp(iter->str, str)) {
return 0;
}
}
reportTask(str);
newOne = (taskListCell*)malloc(sizeof(taskListCell));
newOne->str = strdup(str);
newOne->next = taskSet[index];
taskSet[index] = newOne;
setSize++;
if (setSize > 0.75 * capacity) {
int newCapacity = capacity * 2;
int i;
taskListCell **newHashTable;
newHashTable = (taskListCell**)calloc(newCapacity,sizeof(taskListCell*));
for (i=0; i<capacity; i++) {
for (iter = taskSet[i]; iter != 0; ) {
taskListCell* next = iter->next;
hashCode = hash_value(iter->str);
index = hashCode % newCapacity;
iter->next = newHashTable[index];
newHashTable[index] = iter;
iter = next;
}
}
free(taskSet);
taskSet = newHashTable;
capacity = newCapacity;
}
return 0;
}
void coverageTraceFunc1(const char* FileMethod)
{
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&lock);
taskEncountered(FileMethod);
pthread_mutex_unlock(&lock);
return;
}
| 0
|
#include <pthread.h>
double pi = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *work(void *arg)
{
int start;
int end;
int i;
start = (2000000/2) * ((int )arg) ;
end = start + 2000000/2;
for (i = start; i < end; i++) {
pthread_mutex_lock(&mutex);
pi += 1.0/(i*4.0 + 1.0);
pi -= 1.0/(i*4.0 + 3.0);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int
main(int argc, char** argv) {
int i;
pthread_t tids[2 -1];
for (i = 0; i < 2 - 1 ; i++) {
pthread_create(&tids[i], 0, work, (void *)i);
}
i = 2 -1;
work((void *)i);
for (i = 0; i < 2 - 1 ; i++) {
pthread_join(tids[i], 0);
}
pi = pi * 4.0;
printf("pi done - %f \\n", pi);
return (0);
}
| 1
|
#include <pthread.h>
uint16_t timestamp;
uint16_t state;
uint16_t magic;
} Data;
uint16_t time;
uint16_t timestamp;
uint16_t last_timestamp;
uint16_t first_timestamp;
uint8_t event;
} Channel;
uint8_t recognized[MAX_SENSOR];
inline uint16_t calc_timestamp_diff ( uint16_t time, uint16_t time0 );
static void analyse_data( Data* data );
void* analyse_stream( void* arg );
static void setRunning( uint8_t run );
static uint8_t isRunning( void );
Channel channel[MAX_SENSOR];
pthread_t thread;
pthread_mutex_t LOCK;
int file_handle;
uint8_t running;
int initializeSensorDetection( void (*callback_fnctl)( int, int ) ){
if( 0 == callback_fnctl ) {
return SD_INVALID_ARGUMENT;
}
file_handle = open( "/dev/ttyS0", O_RDONLY, O_NONBLOCK );
if( file_handle < 0 ) {
return SD_DEVICE_ACCESS_FAILED;
}
if( pthread_mutex_init( &LOCK, 0 ) ) {
close( file_handle );
return SD_SYNCHRONIZE_FAILED;
}
uint8_t i;
for( i = 0; i < MAX_SENSOR; i++ ) {
channel[i].time = 0;
channel[i].timestamp = 0;
channel[i].last_timestamp = 0;
channel[i].first_timestamp = 0;
channel[i].event = 0;
recognized[i] = 0xFF;
}
callback = callback_fnctl;
running = 1;
int tret = pthread_create( &thread, 0, analyse_stream, &file_handle );
if( tret ) {
close(file_handle);
pthread_mutex_destroy( &LOCK );
return SD_SYNCHRONIZE_FAILED;
}
return 0;
}
void releaseSensonrDetection(){
setRunning( 0 );
pthread_join( thread, 0 );
pthread_mutex_destroy( &LOCK );
close( file_handle );
}
inline uint16_t calc_timestamp_diff ( uint16_t time, uint16_t time0 ) {
return ( time >= time0 ) ? ( time - time0 ) : ( (0x3FFF - time0) + time );
}
static void analyse_data( Data* data ) {
uint8_t i = 0;
uint16_t time_dif;
uint8_t carId;
if( data-> magic != 0xDEAF ) {
printf("Invalid Magic Number %d\\n", data->magic);
return;
}
for( i = 0; i < MAX_SENSOR; i++ ){
if( data->state & ( 1 << (i) ) ) {
channel[i].event++;
time_dif = calc_timestamp_diff( data->timestamp, channel[i].timestamp );
if( time_dif >= 40 ) {
channel[i].event = 0;
channel[i].time = 0;
} else {
channel[i].time += time_dif;
if( channel[i].event == 1 ) {
channel[i].first_timestamp = data->timestamp;
} else if( channel[i].event == 0 ){
} else if( calc_timestamp_diff( data->timestamp, channel[i].first_timestamp ) > 60 ) {
carId = channel[i].time / channel[i].event /2;
if ( recognized[carId-1] != i ) {
callback( (int) carId, (int) i+1 );
recognized[carId-1] = i;
}
}
}
channel[i].last_timestamp = channel[i].timestamp;
channel[i].timestamp = data->timestamp;
}
}
}
void* analyse_stream( void* arg ) {
Data data;
byte stream[6 + 1];
int fd = *( (int*) arg );
while( isRunning() ) {
if( read( fd, &stream[6], 1 ) == 1 ) {
if( stream[6] == 0xDE && stream[6 -1] == 0xAF ) {
memmove( &data, &stream[1], 6 );
analyse_data( &data );
} else {
memmove( stream, &stream[1], 6 );
}
}
}
return 0;
}
static uint8_t isRunning( ){
uint8_t run;
pthread_mutex_lock( &LOCK );
run = running;
pthread_mutex_unlock( &LOCK );
return run;
}
static void setRunning( uint8_t run ){
pthread_mutex_lock( &LOCK );
running = run;
pthread_mutex_unlock( &LOCK );
}
| 0
|
#include <pthread.h>
pthread_mutex_t m_lock;
void *t_func(void *data)
{
int *count = (int*)data;
int tmp;
pthread_t thread_id = pthread_self();
while(1)
{
pthread_mutex_lock(&m_lock);
tmp = *count;
tmp++;
sleep(1);
*count = tmp;
printf("%lu %d\\n", thread_id, *count);
pthread_mutex_unlock(&m_lock);
}
}
int main(int argc, char *argv[])
{
pthread_t thread_id[2];
int i=0;
int count = 0;
if(pthread_mutex_init(&m_lock, 0) != 0)
{
perror("Mutex init failed");
return 1;
}
for(i=0; i<2; i++)
{
pthread_create(&thread_id[i], 0, t_func, (void*)&count);
usleep(5000);
}
while(1)
{
printf("Main Thread : %d\\n", count);
sleep(2);
}
for(i=0; i<2;i++)
{
pthread_join(thread_id[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
double **A, **B, **C;
int number_of_threads = 1;
int* matrix_part_size;
int** matrix_part;
int rowsA, rowsB, columnsA, columnsB;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double matrix_norm;
void *ThreadFunction(void* arg)
{
int i, x;
int thread_id = *((int*)arg);
int current_matrix_part_size;
int row, column;
double vectorA[columnsA];
double vectorB[rowsB];
double sum = 0;
pthread_mutex_lock(&mutex);
current_matrix_part_size = (int)matrix_part_size[thread_id];
pthread_mutex_unlock(&mutex);
for (x = 0; x < current_matrix_part_size; x++)
{
sum = 0;
pthread_mutex_lock(&mutex);
row = matrix_part[thread_id][x*2];
column = matrix_part[thread_id][(x*2)+1];
for (i = 0; i < columnsA; i++)
{
vectorA[i] = A[row][i];
vectorB[i] = B[i][column];
}
pthread_mutex_unlock(&mutex);
for (i = 0; i < columnsA; i++)
{
sum += vectorA[i] * vectorB[i];
}
pthread_mutex_lock(&mutex);
C[row][column] = sum;
matrix_norm += sum*sum;
pthread_mutex_unlock(&mutex);
}
free(arg);
}
void MultiplyMatrix(double**A, int a, int b, double**B, int c, int d, double**C)
{
int i, j, k;
int current_thread = 0;
pthread_t threads[number_of_threads];
for(i=0; i<number_of_threads; i++)
{
int *thread_function_arg = malloc(sizeof(int));
*thread_function_arg = current_thread;
if (pthread_create(&(threads[current_thread]), 0, ThreadFunction, thread_function_arg) != 0)
{
printf("Thread creation error.");
abort();
}
else{
printf("Thread created - nr %d\\n",current_thread);
}
current_thread++;
}
for (i = 0; i < number_of_threads; i++)
{
if (pthread_join(threads[i], 0))
{
printf("Error with threads ending.");
abort();
}
}
}
PrintMatrix(double**A, int m, int n)
{
int i, j;
printf("[");
for(i =0; i< m; i++)
{
for(j=0; j<n; j++)
{
printf("%f ", A[i][j]);
}
printf("\\n");
}
printf("]\\n");
}
int main(int argc, char *argv[])
{
FILE *fileA = fopen("A.txt", "r");
FILE *fileB = fopen("B.txt", "r");
int i, j, k;
double x;
number_of_threads = atoi(argv[1]);
if( fileA == 0 || fileB == 0 )
{
printf("File Error");
exit(-10);
}
fscanf (fileA, "%d", &rowsA);
fscanf (fileA, "%d", &columnsA);
fscanf (fileB, "%d", &rowsB);
fscanf (fileB, "%d", &columnsB);
if(columnsA != rowsB)
{
printf("Bad Matrix Size!\\n");
return 1;
}
printf("1st Matrix: %d x %d\\n 2nd Matrix: %d x %d\\n", rowsA, columnsA, rowsB, columnsB);
printf("1st Solved Matrix size %d x %d\\n\\n", rowsA, columnsB);
int cells_count = rowsA * columnsB;
int cells_per_thread = cells_count / number_of_threads;
int cells_remainder = cells_count - (cells_per_thread * number_of_threads);
printf("Cells Number %d\\n", cells_count);
printf("Threads number %d\\n", number_of_threads);
printf("Average cells number per 1 thread %d ( + %d bonus )\\n\\n", cells_per_thread, cells_remainder);
matrix_part_size = malloc(sizeof(int) * number_of_threads);
matrix_part = malloc(sizeof (int*) * number_of_threads);
for (i = 0; i < number_of_threads; i++)
{
if (i == 0)
{
matrix_part[i] = malloc(sizeof(int) * (cells_per_thread + cells_remainder) * 2);
matrix_part_size[i] = (cells_per_thread + cells_remainder);
}
else
{
matrix_part[i] = malloc(sizeof(int) * cells_per_thread * 2);
matrix_part_size[i] = cells_per_thread;
}
}
j = 0;
for (i = 0; i < number_of_threads; i++)
{
for (k = 0; k < matrix_part_size[i]; k++)
{
matrix_part[i][k*2] = j / columnsB;
matrix_part[i][(k*2)+1] = j % columnsB;
j++;
}
}
A = malloc(rowsA*sizeof(double));
for(i=0; i< rowsA; i++) A[i] = malloc(columnsA*sizeof(double));
B = malloc(rowsB*sizeof(double));
for(i=0; i< rowsB; i++) B[i] = malloc(columnsB*sizeof(double));
C = malloc(rowsA*sizeof(double));
for(i=0; i< rowsA; i++) C[i] = malloc(columnsB*sizeof(double));
for(i =0; i< rowsA; i++)
{
for(j = 0; j<columnsA; j++)
{
fscanf( fileA, "%lf", &x );
A[i][j] = x;
}
}
printf("Matrix A:\\n");
PrintMatrix(A, rowsA, rowsB);
for(i =0; i< rowsB; i++)
{
for(j = 0; j<columnsB; j++)
{
fscanf( fileB, "%lf", &x );
B[i][j] = x;
}
}
printf("Matrix B:\\n");
PrintMatrix(B, rowsB, columnsB);
MultiplyMatrix(A, rowsA, columnsA, B, rowsB, columnsB, C);
printf("\\n Result:\\n");
printf("Frobenius Equation: %f\\n", sqrt(matrix_norm));
printf("Matrix C:\\n");
PrintMatrix(C, rowsA, columnsB);
for(i=0; i<columnsA; i++) free(A[i]);
free(A);
for(i=0; i<columnsB; i++) free(B[i]);
free(B);
for(i=0; i<columnsB; i++) free(C[i]);
free(C);
for(i=0; i< number_of_threads; i++) free(matrix_part[i]);
free(matrix_part);
free(matrix_part_size);
fclose(fileA);
fclose(fileB);
return 0;
}
| 0
|
#include <pthread.h>
long int n_threads=0,n_iter = 0,sum=0;
long int i;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* runner(void* arg) {
double x,y;
unsigned int value;
long int ctr = 0,k=0;
for(k=0;k<n_iter/n_threads;k++){
x = rand_r(&value)/(double)32767;
y = rand_r(&value)/(double)32767;
if(x*x+y*y<=1) ctr ++;
}
pthread_mutex_lock(&mutex);
sum = sum + ctr;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char *argv[])
{
n_iter = atol(argv[1]);
n_threads = atol(argv[2]);
pthread_t *threads;
threads = malloc(n_threads*sizeof(pthread_t));
for (i = 0; i < n_threads; i++) {
pthread_create(&threads[i], 0, runner, 0);
}
for (i = 0; i < n_threads; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&mutex);
free(threads);
printf("pi = %g\\n", (double)4*sum/n_iter);
return 0;
}
| 1
|
#include <pthread.h>
int nbr_wait=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void wait_barrier(int n){
pthread_mutex_lock(&mutex);
nbr_wait++;
if (nbr_wait<10) {
pthread_cond_wait(&cond, &mutex);
}
else {
pthread_cond_broadcast(&cond);
}
pthread_mutex_unlock(&mutex);
}
void* thread_func (void *arg) {
printf ("avant barrière\\n");
wait_barrier(10);
printf ("après barrière\\n");
pthread_exit ( (void*)0);
}
int main(int argc, char ** argv){
pthread_t tid[10 +1];
int i;
int* status;
int* pt_ind;
for (i=1;i<10 +1;i++) {
pt_ind=(int*)malloc(sizeof(i));
*pt_ind=i;
if (pthread_create(&tid[i],0,thread_func,(void *)pt_ind)!=0) {
printf("ERREUR:creation\\n");
exit(1);
}
}
for (i=1;i<10 +1;i++) {
if(pthread_join(tid[i],(void **)&status)!=0) {
printf("ERREUR:joindre\\n");
exit(2);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t total_grade_mutex;
pthread_mutex_t total_bellcurve_mutex;
pthread_barrier_t barrier;
float total_grade = 0;
float total_bellcurve = 0;
float grades[10];
void * save_bellcurve(void * grade);
void * read_grades();
int main(void){
pthread_t tid[10];
pthread_barrier_init(&barrier, 0, 2);
pthread_create(&tid[0], 0, read_grades, 0);
pthread_barrier_wait(&barrier);
for(int i = 0; i < 10; i++){
pthread_create(&tid[i], 0, save_bellcurve, (void*)&grades[i]);
}
for(int i = 0; i < 10; i++){
pthread_join(tid[i], 0);
}
printf("Total grade: %f\\n", total_grade);
printf("Average before bellcurve: %f\\n", total_grade/10);
printf("Average after bellcurve: %f\\n", total_bellcurve/10);
pthread_barrier_destroy(&barrier);
}
void * save_bellcurve(void * grade){
FILE *fp;
fp = fopen("bellcurve.txt", "a");
float bellcurve;
pthread_mutex_lock(&total_grade_mutex);
total_grade += *(float*)grade;
pthread_mutex_unlock(&total_grade_mutex);
pthread_mutex_lock(&total_bellcurve_mutex);
bellcurve = *(float*)grade * 1.5;
total_bellcurve += bellcurve;
fprintf(fp, "%f\\n", bellcurve);
pthread_mutex_unlock(&total_bellcurve_mutex);
fclose(fp);
}
void * read_grades(){
FILE *fp;
float grade;
int i = 0;
fp = fopen("grades.txt", "r");
while(fscanf(fp, "%f", &grade) > 0){
grades[i++] = grade;
}
pthread_barrier_wait(&barrier);
fclose(fp);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutexLock;
double v[100];
int i2c_fd;
void ctrl_c(int sig)
{
close(i2c_fd);
exit(-1);
}
void *function_media()
{
double total = 0;
while(1)
{
sleep(1);
pthread_mutex_lock(&mutexLock);
for (int i = 0; i < 100; i++)
total += v[i];
pthread_mutex_unlock(&mutexLock);
printf("Media: %f\\n", total/100);
}
return 0;
}
int main(void)
{
unsigned char user_input=1, msp430_ret, rpi_addr = 0xDA, slave_addr=0x0F;
signal(SIGINT, ctrl_c);
i2c_fd = open("/dev/i2c-1", O_RDWR);
ioctl(i2c_fd, I2C_SLAVE, slave_addr);
for (int i = 0; i < 100; i++)
v[i] = 0.0;
int i = 0;
pthread_t media;
pthread_create(&media, 0, function_media, 0);
while(1)
{
read(i2c_fd, &msp430_ret, 1);
if(msp430_ret == 0x55)
{
usleep(100);
read(i2c_fd, &msp430_ret, 1);
pthread_mutex_lock(&mutexLock);
v[i] += (double) msp430_ret << 8;
v[i] += (double) msp430_ret;
pthread_mutex_unlock(&mutexLock);
i++;
if(i == 100)
i = 0;
usleep(10000);
}
}
}
| 0
|
#include <pthread.h>
int costumersWaiting = 0;
int barbeiroOcupado = 0;
pthread_cond_t loja_cheia = PTHREAD_COND_INITIALIZER;
pthread_cond_t loja_vazia = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *barbeiro(void *args) {
while(1) {
pthread_mutex_lock(&mutex);
barbeiroOcupado = 0;
if (costumersWaiting == 0) {
printf("Nenhum cliente esperando, vou dormir!!\\n");
pthread_cond_wait(&loja_vazia, &mutex);
}
barbeiroOcupado = 1;
costumersWaiting--;
printf("Cortando o cabelo de alguem!\\n");
if (costumersWaiting == 0) {
pthread_cond_signal(&loja_cheia);
}
pthread_mutex_unlock(&mutex);
}
}
void *cliente(void *args) {
while(1) {
pthread_mutex_lock(&mutex);
if (costumersWaiting != 5) {
printf("Tem uma cadeira livre! Vou esperar!\\n");
costumersWaiting++;
if (costumersWaiting == 1) {
pthread_cond_signal(&loja_vazia);
}
if (barbeiroOcupado == 1) {
pthread_cond_wait(&loja_cheia, &mutex);
}
} else {
printf("Ta cheio! Vou embora!\\n");
}
pthread_mutex_unlock(&mutex);
}
}
int main() {
pthread_t barber;
pthread_t costumer;
pthread_create(&barber, 0, barbeiro, 0);
pthread_create(&costumer, 0, cliente, 0);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
static char send_buffer[2][1024];
static char receive_buffer[1024];
static pthread_mutex_t send_buffer_access;
static pthread_cond_t send_buffer_0_cv;
static pthread_cond_t send_buffer_1_cv;
static int sock_fd = 0;
int check_parameters_count(int argc){
if(argc != 2)
{
printf("\\n Usage: cliemt <server address> [<server port>] \\n");
return 1;
}
return 0;
}
int setup_server_address_struct(struct sockaddr_in *serv_addr_struct, char *server_address, unsigned short server_port){
memset(serv_addr_struct, '0', sizeof(*serv_addr_struct));
serv_addr_struct->sin_family = AF_INET;
serv_addr_struct->sin_port = htons(server_port);
if(inet_pton(AF_INET, server_address, &(serv_addr_struct->sin_addr))<=0)
{
printf("\\n Cannot resolve server address\\n");
return 1;
}
}
int check_connect_status(int s){
if (s < 0){
printf("status %d errno %d\\n",s, errno);
return 1;
}
return 0;
}
void *inputThreadRoutine(void *threadid)
{
int tid = *((int*)(threadid));
unsigned char c;
unsigned long index = 0;
synch_printf("%d ok\\n", tid);
do{
c = getchar();
if ((c == 8) && (index>0)){
index--;
send_buffer[1][index] = 0;
}
send_buffer[1][index] = c;
if (index<sizeof(send_buffer[1])){
index++;
}
if( c == '\\n'){
int len;
send_buffer[1][index] = 0;
pthread_mutex_lock(&send_buffer_access);
len = strlen(send_buffer[1]);
synch_printf("\\nbuffer:\\n%s\\nsize\\n%d\\n",send_buffer[1], len);
memcpy(&(send_buffer[0]), &(send_buffer[1]), len+1);
memset(&(send_buffer[1]), 0, len);
pthread_cond_signal(&send_buffer_0_cv);
printf("Signalled to write. Input thread falling asleep\\n");
pthread_cond_wait(&send_buffer_1_cv, &send_buffer_access);
pthread_mutex_unlock(&send_buffer_access);
index = 0;
}
}while(1);
pthread_exit(0);
}
void *receiveThreadRoutine(void *threadid)
{
int tid = *((int*)(threadid));
char receive_buffer[1024];
int n = 0;
synch_printf("%d ok\\n", tid);
while (1){
while ( (receive_buffer[strlen(receive_buffer)-1] != '\\n') &&
((n = read(sock_fd, receive_buffer, sizeof(receive_buffer)-1)) > 0))
{
receive_buffer[n] = 0;
write (1, receive_buffer, strlen(receive_buffer));
}
}
if(n < 0)
{
printf("\\n Read error \\n");
}
}
int main(int argc, char *argv[])
{
int *tid;
int status;
int n, last_n, n_sum;
int n_size;
int try_count;
struct sockaddr_in serv_addr;
unsigned short server_port = 5000;
pthread_t receive_thread;
pthread_t input_thread;
if (check_parameters_count(argc)){
return 1;
}
memset(receive_buffer, 0, sizeof(receive_buffer));
memset(send_buffer[0], 0, sizeof(send_buffer[0]));
pthread_mutex_init(&send_buffer_access, 0);
pthread_cond_init (&send_buffer_0_cv, 0);
pthread_cond_init (&send_buffer_1_cv, 0);
if((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\\n Error : Could not create socket \\n");
return 1;
}
if (argc > 2){
server_port = atoi(argv[2]);
}
setup_server_address_struct(&serv_addr, argv[1], server_port);
printf("connecting %s %d\\n", argv[1], server_port);
if(connect(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\\n Error : Connect Failed \\n");
return 1;
}
init_synch_printing();
tid = (int *)malloc(sizeof(int));
if (!tid){
return 1;
}
*tid = 1;
pthread_create(&input_thread, 0, inputThreadRoutine,(void *)(tid));
tid = (int *)malloc(sizeof(int));
if (!tid){
return 1;
}
*tid = 2;
pthread_create(&receive_thread, 0, receiveThreadRoutine, (void*)(tid));
while (1){
pthread_mutex_lock(&send_buffer_access);
printf ("main thread falling asleep\\n");
pthread_cond_wait(&send_buffer_0_cv, &send_buffer_access);
printf ("sending message: \\n%s\\n", send_buffer[0]);
n_size = strlen(send_buffer[0]);
n_sum = 0;
try_count = 0;
do{
n = write (sock_fd, send_buffer[0], n_size-n_sum);
printf ("Write returned %d\\n", n);
if (n < 0){
printf("Socket failed. Attempt to reconnect\\n");
status = connect(sock_fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
if (check_connect_status(status)){
return 1;
}
}else{
if (!n){
try_count++;
}else{
if (try_count >= 3){
printf("Resend failed %d times. Terminating.\\n", 3);
return 1;
}else{
n_sum+=n;
}
}
}
}while(n_sum<n_size);
synch_printf("write complete\\n");
pthread_cond_signal(&send_buffer_1_cv);
pthread_mutex_unlock(&send_buffer_access);
}
return 0;
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
char username[32];
int fd;
pid_t tid;
} chat_client_t;
chat_client_t clients[5];
int usercount = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct client_handler_params {
int fd;
char username[32];
};
void show_client_list() {
int i;
pthread_mutex_lock(&mutex);
for (i = 0; i<5; i++) {
if (clients[i].fd != 0)
printf("Username: %s FD: %d TID: %d\\n", clients[i].username, clients[i].fd, clients[i].tid);
}
pthread_mutex_unlock(&mutex);
}
int contains_user(chat_client_t *client) {
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < 5; i++) {
if(!strcmp(client->username, clients[i].username) && clients[i].fd!=0) {
pthread_mutex_unlock(&mutex);
return 1;
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
int add_user(chat_client_t *client) {
int i;
pthread_mutex_lock(&mutex);
for(i = 0; i < 5; i++) {
if (clients[i].fd == 0) {
clients[i].fd = client->fd;
clients[i].tid = client->tid;
strcpy(clients[i].username, client->username);
usercount++;
pthread_mutex_unlock(&mutex);
return i;
}
}
pthread_mutex_unlock(&mutex);
return -1;
}
int receive_until_null_or_linefeed(int target_fd, char *buffer, int buffer_size) {
int rdbytes = 0;
char currentByte;
while ((recv(target_fd, ¤tByte, 1, MSG_WAITALL) > 0) && (rdbytes < buffer_size)) {
if (currentByte == '\\0') {
buffer[rdbytes] = '\\0';
return rdbytes;
} else if (currentByte == '\\n') {
buffer[rdbytes] = '\\0';
return rdbytes + 1;
} else {
buffer[rdbytes] = currentByte;
rdbytes++;
}
}
return rdbytes;
}
void message_all_clients(char *message, chat_client_t *client) {
int i;
show_client_list();
pthread_mutex_lock(&mutex);
for (i = 0; i < 5; i++) {
if (clients[i].fd != 0) {
write(clients[i].fd, client->username, strlen(client->username));
write(clients[i].fd, ": ", 2);
write(clients[i].fd, message, strlen(message)+1);
}
}
pthread_mutex_unlock(&mutex);
}
void *client_handler(void *args)
{
struct client_handler_params *params = args;
int rdbytes;
int index = 0;
chat_client_t client;
char message[1024];
char user_taken[] = "Username already in use!";
char user_limit_exceeded[] = "User limit exceeded! Try again later.";
pid_t tid = syscall(__NR_gettid);
client.fd = params->fd;
client.tid = tid;
strcpy(client.username, params->username);
if(usercount) {
if(contains_user(&client)) {
write(client.fd, user_taken, sizeof(user_taken));
return 0;
}
if(usercount > 5) {
write(client.fd, user_limit_exceeded, sizeof(user_limit_exceeded));
return 0;
}
}
if((index = add_user(&client)) == -1) {
printf("Fehler beim Speichern des Benutzers in der Liste!\\n");
}
else {
printf("Added user %s (fd=%d) on index %d\\n", clients[index].username, clients[index].fd, index);
}
pthread_mutex_unlock(&mutex);
show_client_list();
for (;;) {
rdbytes = receive_until_null_or_linefeed(client.fd, message, 1024);
if (rdbytes == -1) {
fprintf(stderr, "Error in Receive from Client!\\n");
break;
}
if (rdbytes == 0) {
printf("SERVER-Info: Client %s closed the connection!\\n", client.username);
break;
}
printf("Read %d bytes from Client %s\\n", rdbytes, client.username);
pthread_mutex_lock(&mutex);
printf("Thread working: %d\\n", client.tid);
printf("Client (%s) sagt: %s\\n", client.username, message);
pthread_mutex_unlock(&mutex);
message_all_clients(message, &client);
}
pthread_mutex_lock(&mutex);
printf("Removing Client %s from the list\\n", client.username);
close(client.fd);
clients[index].fd = 0;
usercount--;
pthread_mutex_unlock(&mutex);
return 0;
}
void init_clients() {
int i;
for (i = 0; i<5; i++) {
clients[i].fd = 0;
}
}
int main()
{
int sock, client_sock_fd;
unsigned sock_addr_size;
int err;
char username[32];
int rdbytes;
pthread_t thr_id;
struct sockaddr sock_addr;
struct sockaddr_in srv_sock_addr;
struct client_handler_params params;
srv_sock_addr.sin_addr.s_addr = INADDR_ANY;
srv_sock_addr.sin_port = htons(SRV_PORT);
srv_sock_addr.sin_family = AF_INET;
if ( (sock=socket(PF_INET,SOCK_STREAM, 0)) == -1)
{
perror("socket");
exit(1);
}
if ( bind(sock, (struct sockaddr*)&srv_sock_addr, sizeof(srv_sock_addr) ) == -1)
{
perror("bind");
exit(1);
}
if ( listen(sock,6) ==-1 )
{
perror("listen");
exit(1);
}
init_clients();
printf("Server running on %d\\n", SRV_PORT);
for (;;)
{
sock_addr_size=sizeof(sock_addr);
if ( (client_sock_fd=accept(sock,&sock_addr,&sock_addr_size)) == -1)
{
perror("accept");
exit(1);
}
if((rdbytes = read(client_sock_fd, username, sizeof(username))) == -1) {
fprintf(stderr, "Cannot read username");
exit(1);
}
printf ("%s hat sich verbunden\\n", username);
params.fd = client_sock_fd;
strcpy(params.username, username);
err=pthread_create(&thr_id, 0, client_handler, ¶ms);
if (err)
printf("Threaderzeugung: %s\\n", strerror(err));
}
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int block;
int busy;
int inode;
pthread_mutex_t m_inode;
pthread_mutex_t m_busy;
void *allocator(){
pthread_mutex_lock(&m_inode);
if(inode == 0){
pthread_mutex_lock(&m_busy);
busy = 1;
pthread_mutex_unlock(&m_busy);
inode = 1;
}
block = 1;
if (!(block == 1)) ERROR: __VERIFIER_error();;
pthread_mutex_unlock(&m_inode);
return 0;
}
void *de_allocator(){
pthread_mutex_lock(&m_busy);
if(busy == 0){
block = 0;
if (!(block == 0)) ERROR: __VERIFIER_error();;
}
pthread_mutex_unlock(&m_busy);
return ((void *)0);
}
int main() {
pthread_t t1, t2;
__VERIFIER_assume(inode == busy);
pthread_mutex_init(&m_inode, 0);
pthread_mutex_init(&m_busy, 0);
pthread_create(&t1, 0, allocator, 0);
pthread_create(&t2, 0, de_allocator, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&m_inode);
pthread_mutex_destroy(&m_busy);
return 0;
}
| 1
|
#include <pthread.h>
int ** bigMatrix[200];
int producerTotal = 0;
int consumerTotal = 0;
int buffer[200];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
int producerSum = 0;
int consumerSum = 0;
int loops = 1200000;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int ** AllocMatrix(int r, int c)
{
int ** a;
int i;
a = (int**) malloc(sizeof(int *) * r);
assert(a != 0);
for (i = 0; i < r; i++)
{
a[i] = (int *) malloc(c * sizeof(int));
assert(a[i] != 0);
}
return a;
}
void FreeMatrix(int ** a, int r, int c)
{
int i;
for (i=0; i<r; i++)
{
free(a[i]);
}
free(a);
}
void GenMatrix(int ** matrix, const int height, const int width)
{
int i, j;
for (i = 0; i < height; i++)
{
for (j = 0; j < width; j++)
{
int * mm = matrix[i];
mm[j] = rand() % 10;
}
}
}
int SumMatrix(int ** matrix, const int height, const int width)
{
int sum = 0;
int i, j;
for (i=0; i<height; i++)
for (j=0; j<width; j++)
{
sum += matrix[i][j];
}
return sum;
}
int put() {
int **mat = AllocMatrix(5, 5);
GenMatrix(mat, 5, 5);
int sum = SumMatrix(mat ,5 , 5);
bigMatrix[fill_ptr] = mat;
fill_ptr = (fill_ptr + 1) % 200;
count++;
return sum;
}
int get() {
int sum = SumMatrix(bigMatrix[use_ptr], 5, 5);
FreeMatrix(bigMatrix[use_ptr], 5, 5);
use_ptr = (use_ptr + 1) % 200;
count--;
return sum;
}
void *producer(void *arg) {
int producerSum = 0;
while(producerTotal < 1200000) {
pthread_mutex_lock(&mutex);
while (count == 200) {
if(producerTotal == 1200000) {
break;
}
pthread_cond_wait(&empty, &mutex);
}
if (producerTotal < 1200000) {
producerSum += put();
producerTotal++;
}
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
return producerSum;
}
void *consumer(void *arg) {
int consumerSum = 0;
while(consumerTotal < 1200000) {
pthread_mutex_lock(&mutex);
while (count == 0) {
if(consumerTotal == 1200000) {
break;
}
pthread_cond_wait(&fill, &mutex);
}
if (consumerTotal < 1200000) {
int tmp = get();
consumerSum += tmp;
consumerTotal++;
}
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
return consumerSum;
}
int main() {
int producerSumGlobal = 0;
int consumerSumGlobal = 0;
int prReturn[22];
int coReturn[22];
int i = 0;
pthread_t prThread[22];
pthread_t coThread[22];
srand(time(0));
for(i = 0; i < 22; i++) {
pthread_create(&prThread[i], 0, producer, 0);
pthread_create(&coThread[i], 0, consumer, 0);
}
for(i = 0; i < 22; i++) {
pthread_join(prThread[i], &prReturn[i]);
pthread_join(coThread[i], &coReturn[i]);
}
for (i = 0; i < 22; i++) {
producerSumGlobal += prReturn[i];
consumerSumGlobal += coReturn[i];
}
printf("producer: %d\\nconsumer: %d\\n", producerSumGlobal,
consumerSumGlobal);
return 0;
}
| 0
|
#include <pthread.h>
int fd, op;
char word[32];
pthread_t *tids;
size_t n, nrec;
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
int sig_num;
void *thread_func(void *arg) {
if(op == 4) {
sigset_t set;
sigemptyset(&set);
sigaddset(&set, sig_num);
pthread_sigmask(SIG_BLOCK, &set, 0);
}
char *id = calloc(2, sizeof(char));
char **record = calloc(nrec, sizeof(char *));
for(int i = 0; i<nrec; i++) {
record[i] = calloc(1024, sizeof(char));
}
ssize_t bytes_read = 0;
do {
pthread_mutex_lock(&mtx);
for (int i = 0; i < nrec; i++) {
if ((bytes_read = read(fd, record[i], 1024)) == -1) {
perror("read");
}
}
pthread_mutex_unlock(&mtx);
for (int i = 0; i < nrec && bytes_read; i++) {
if (strstr(record[i], word) != 0) {
strncpy(id, record[i], 2);
printf("%ld found word in record: %s\\n", pthread_self(), id);
bytes_read = 0;
}
printf("%ld %c%c\\n", pthread_self(), record[i][0], record[i][1]);
}
} while(bytes_read);
free(id);
for(int i=0; i<nrec; i++) {
free(record[i]);
}
free(record);
return 0;
}
void signal_handler(int signum) {
printf("Caught signal %d, PID: %d, TID: %ld\\n", signum, getpid(), pthread_self());
}
int main(int argc, char **argv) {
if(argc!=6) {
printf("Wrong number of arguments!\\n");
return 1;
}
sig_num = atoi(argv[5]);
printf("Wpisz\\n"
"1 - do procesu, brak zamaskowanych sygnalow\\n"
"2 - do procesu, glowny watek ma zamaskowany sygnal\\n"
"3 - do procesu, wszystkie watki maja procedure obslugi\\n"
"4 - do watku z zamaskowanym sygnalem\\n"
"5 - do watku z obsluga sygnalu\\n"
);
scanf("%d", &op);
if(op == 3 || op ==5) {
struct sigaction act;
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(sig_num, &act, 0);
}
printf("Main thread: %ld\\n", pthread_self());
n = (size_t) atoi(argv[1]);
char name[32];
nrec =(size_t) atoi(argv[3]);
strcpy(name, argv[2]);
strcpy(word, argv[4]);
if((fd = open(name, O_RDONLY))==-1) {
perror("open");
return 1;
}
if(op == 2) {
sigset_t set;
sigemptyset(&set);
sigaddset(&set, sig_num);
pthread_sigmask(SIG_BLOCK, &set, 0);
}
tids = calloc(n, sizeof(pthread_t));
for(int i = 0; i<n; i++) {
pthread_create(&tids[i], 0, thread_func, 0);
}
if(op<=3)
kill(getpid(), sig_num);
else
pthread_kill(tids[0], sig_num);
void *status;
for(int i=0; i<n; i++) {
if(pthread_join(tids[i], &status)!=0) {
printf("Error with pthread_join");
}
}
free(tids);
return 0;
}
| 1
|
#include <pthread.h>
struct thd_s {
int running;
pthread_t thd;
void (*func)(void);
pthread_mutex_t mutex;
pthread_cond_t cond;
};
static struct thd_s thread_handle[YAB_NUM_THREADS];
static pthread_key_t hnd_key;
static pthread_once_t hnd_key_once;
static void make_key() {
pthread_key_create(&hnd_key, 0);
}
static void *wrapper(void *hnd) {
struct thd_s *hnds = (struct thd_s *)hnd;
pthread_mutex_lock(&hnds->mutex);
pthread_setspecific(hnd_key, hnd);
hnds->func();
pthread_mutex_unlock(&hnds->mutex);
return 0;
}
int YabThreadStart(unsigned int id, void (*func)(void)) {
pthread_once(&hnd_key_once, make_key);
if(thread_handle[id].running) {
fprintf(stderr, "YabThreadStart: Thread %u is already started!\\n", id);
return -1;
}
if(pthread_mutex_init(&thread_handle[id].mutex, 0)) {
fprintf(stderr, "YabThreadStart: Error creating mutex\\n");
return -1;
}
if(pthread_cond_init(&thread_handle[id].cond, 0)) {
fprintf(stderr, "YabThreadStart: Error creating condvar\\n");
pthread_mutex_destroy(&thread_handle[id].mutex);
return -1;
}
thread_handle[id].func = func;
if(pthread_create(&thread_handle[id].thd, 0, wrapper,
&thread_handle[id])) {
fprintf(stderr, "YabThreadStart: Couldn't start thread\\n");
pthread_cond_destroy(&thread_handle[id].cond);
pthread_mutex_destroy(&thread_handle[id].mutex);
return -1;
}
thread_handle[id].running = 1;
return 0;
}
void YabThreadWait(unsigned int id) {
if(!thread_handle[id].running)
return;
pthread_join(thread_handle[id].thd, 0);
pthread_cond_destroy(&thread_handle[id].cond);
pthread_mutex_destroy(&thread_handle[id].mutex);
thread_handle[id].thd = 0;
thread_handle[id].func = 0;
thread_handle[id].running = 0;
}
void YabThreadYield(void) {
sched_yield();
}
void YabThreadSleep(void) {
struct thd_s *thd = (struct thd_s *)pthread_getspecific(hnd_key);
pthread_cond_wait(&thd->cond, &thd->mutex);
}
void YabThreadWake(unsigned int id) {
if(!thread_handle[id].running)
return;
pthread_cond_signal(&thread_handle[id].cond);
}
| 0
|
#include <pthread.h>
int producerTotal = 0;
int consumerTotal = 0;
int buffer[100];
int fill_ptr = 0;
int use_ptr = 0;
int count = 0;
int producerSum = 0;
int consumerSum = 0;
int loops = 10000;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void put(int value) {
buffer[fill_ptr] = value;
fill_ptr = (fill_ptr + 1) % 100;
count++;
}
int get() {
int tmp = buffer[use_ptr];
use_ptr = (use_ptr + 1) % 100;
count--;
return tmp;
}
void *producer(void *arg) {
int producerSum = 0;
while(producerTotal < 10000) {
pthread_mutex_lock(&mutex);
while (count == 100) {
if(producerTotal == 10000) {
break;
}
pthread_cond_wait(&empty, &mutex);
}
if (producerTotal < 10000) {
int random = rand();
put(random);
producerSum += random;
producerTotal++;
}
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
return producerSum;
}
void *consumer(void *arg) {
int consumerSum = 0;
while(consumerTotal < 10000) {
pthread_mutex_lock(&mutex);
while (count == 0) {
if(consumerTotal == 10000) {
break;
}
pthread_cond_wait(&fill, &mutex);
}
if (consumerTotal < 10000) {
int tmp = get();
consumerSum += tmp;
consumerTotal++;
}
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
}
return consumerSum;
}
int main() {
int producerSumGlobal = 0;
int consumerSumGlobal = 0;
int prReturn[9222];
int coReturn[9222];
int i = 0;
pthread_t prThread[9222];
pthread_t coThread[9222];
srand(time(0));
for(i = 0; i < 9222; i++) {
pthread_create(&prThread[i], 0, producer, 0);
pthread_create(&coThread[i], 0, consumer, 0);
}
for(i = 0; i < 9222; i++) {
pthread_join(prThread[i], &prReturn[i]);
pthread_join(coThread[i], &coReturn[i]);
}
for (i = 0; i < 9222; i++) {
producerSumGlobal += prReturn[i];
consumerSumGlobal += coReturn[i];
}
printf("producer: %d\\nconsumer: %d\\n", producerSumGlobal,
consumerSumGlobal);
return 0;
}
| 1
|
#include <pthread.h>
struct session_slot_table *new_session_slot_table()
{
int i;
struct session_slot_table *sst;
sst = malloc(sizeof(*sst));
if (!sst) {
return 0;
}
sst->free_slots = new_bitset(SESSION_SLOT_TABLE_CAPACITY);
if (!sst->free_slots) {
free(sst);
return 0;
}
bs_set_all(sst->free_slots);
for (i = 0; i < SESSION_SLOT_TABLE_CAPACITY; ++i) {
sst->slots[i] = 1;
}
pthread_mutex_init(&sst->mutex, 0);
pthread_cond_init(&sst->slot_cv, 0);
sst->highest_used_slotid_plus1 = 0;
sst->server_highest_slotid = SESSION_SLOT_TABLE_CAPACITY - 1;
sst->target_highest_slotid = SESSION_SLOT_TABLE_CAPACITY - 1;
return sst;
}
void del_session_slot_table(struct session_slot_table **sst)
{
if (*sst) {
assert((*sst)->highest_used_slotid_plus1 == 0);
del_bitset((*sst)->free_slots);
free(*sst);
*sst = 0;
}
}
int alloc_session_slot(struct session_slot_table *sst, uint32_t *sequence,
uint32_t *highest_slotid)
{
int slotid = -1;
pthread_mutex_lock(&sst->mutex);
slotid = bs_ffs(sst->free_slots);
while (slotid == -1 || slotid > sst->target_highest_slotid) {
pthread_cond_wait(&sst->slot_cv, &sst->mutex);
slotid = bs_ffs(sst->free_slots);
}
bs_reset(sst->free_slots, slotid);
if (slotid >= sst->highest_used_slotid_plus1) {
sst->highest_used_slotid_plus1 = slotid + 1;
}
*sequence = sst->slots[slotid];
*highest_slotid = sst->highest_used_slotid_plus1 - 1;
pthread_mutex_unlock(&sst->mutex);
return slotid;
}
void free_session_slot(struct session_slot_table *sst, int slotid,
uint32_t server_highest, uint32_t target_highest,
bool sent)
{
pthread_mutex_lock(&sst->mutex);
assert(!bs_get(sst->free_slots, slotid));
bs_set(sst->free_slots, slotid);
if (slotid + 1 == sst->highest_used_slotid_plus1) {
int s = slotid - 1;
while (s >= 0 && bs_get(sst->free_slots, s))
--s;
sst->highest_used_slotid_plus1 = s + 1;
}
if (sent) {
assert(server_highest + 1 >= sst->highest_used_slotid_plus1);
sst->server_highest_slotid = server_highest;
sst->target_highest_slotid = target_highest;
atomic_inc_uint32_t(sst->slots + slotid);
}
if (slotid <= target_highest) {
pthread_cond_signal(&sst->slot_cv);
}
pthread_mutex_unlock(&sst->mutex);
}
| 0
|
#include <pthread.h>
double ff_get_sync_clock(struct ff_clock *clock)
{
return clock->sync_clock(clock->opaque);
}
int64_t ff_clock_start_time(struct ff_clock *clock)
{
int64_t start_time = AV_NOPTS_VALUE;
pthread_mutex_lock(&clock->mutex);
if (clock->started)
start_time = clock->start_time;
pthread_mutex_unlock(&clock->mutex);
return start_time;
}
bool ff_clock_start(struct ff_clock *clock, enum ff_av_sync_type sync_type,
const bool *abort)
{
bool release = 0;
bool aborted = 0;
if (clock->sync_type == sync_type && !clock->started) {
pthread_mutex_lock(&clock->mutex);
if (!clock->started) {
clock->start_time = av_gettime();
clock->started = 1;
}
pthread_cond_signal(&clock->cond);
pthread_mutex_unlock(&clock->mutex);
} else {
while (!clock->started) {
pthread_mutex_lock(&clock->mutex);
int64_t current_time = av_gettime()
+ 100;
struct timespec sleep_time = {
.tv_sec = current_time / AV_TIME_BASE,
.tv_nsec = (current_time % AV_TIME_BASE) * 1000
};
pthread_cond_timedwait(&clock->cond, &clock->mutex,
&sleep_time);
aborted = *abort;
if (clock->retain == 1)
release = 1;
pthread_mutex_unlock(&clock->mutex);
if (aborted || release) {
av_log(0, AV_LOG_ERROR, "could not start "
"slave clock as master clock "
"was never started before "
"being released or aborted");
break;
}
}
}
if (release)
ff_clock_release(&clock);
return !release && !aborted;
}
struct ff_clock *ff_clock_init(struct ff_clock *clock)
{
clock = av_mallocz(sizeof(struct ff_clock));
if (clock == 0)
return 0;
if (pthread_mutex_init(&clock->mutex, 0) != 0)
goto fail;
if (pthread_cond_init(&clock->cond, 0) != 0)
goto fail1;
return clock;
fail1:
pthread_mutex_destroy(&clock->mutex);
fail:
av_free(clock);
return 0;
}
struct ff_clock *ff_clock_retain(struct ff_clock *clock)
{
ff_atomic_inc_long(&clock->retain);
return clock;
}
struct ff_clock *ff_clock_move(struct ff_clock **clock)
{
struct ff_clock *retained_clock = ff_clock_retain(*clock);
ff_clock_release(clock);
return retained_clock;
}
void ff_clock_release(struct ff_clock **clock)
{
if (ff_atomic_dec_long(&(*clock)->retain) == 0) {
pthread_cond_destroy(&(*clock)->cond);
pthread_mutex_destroy(&(*clock)->mutex);
av_free(*clock);
}
*clock = 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void* thread_worker(void*);
void critical_section(int thread_num, int i);
int main(void) {
int rtn, i;
pthread_t pthread_id = 0;
rtn = pthread_create(&pthread_id, 0,
thread_worker, 0 );
if(rtn != 0){
printf("pthread_create ERROR!\\n");
return -1;
}
for (i=0; i<10000; i++) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1, i);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
return 0;
}
void* thread_worker(void* p){
int i;
for (i=0; i<10000; i++) {
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(2, i);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
}
void critical_section(int thread_num, int i) {
printf("Thread%d: %d\\n", thread_num, i);
}
| 0
|
#include <pthread.h>
static int buffer[16];
static pthread_mutex_t lock;
static pthread_cond_t empty;
static pthread_cond_t full;
static int counter = 0;
static int number_of_items;
static int number_consumers;
static int number_producers;
int thread_number;
int number_produced;
} producer_info;
void *produce(void *param) {
int count;
producer_info pi = *(producer_info*) param;
for (count = 0; count < number_of_items; count++) {
pthread_mutex_lock(&lock);
while (counter == 16)
pthread_cond_wait(&empty, &lock);
buffer[counter] = pi.thread_number * pi.number_produced + count;
printf("\\nProduced %d at location %d", buffer[counter], counter);
pi.number_produced++;
counter++;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&full);
}
pthread_exit(0);
}
void *consume(void *param) {
int count;
for (count = 0; count < (number_of_items*number_producers)/number_consumers; count++) {
pthread_mutex_lock(&lock);
while (counter == 0)
pthread_cond_wait(&full, &lock);
counter--;
printf("\\nConsumed %d at location %d", buffer[counter], counter);
buffer[counter] = 0;
pthread_mutex_unlock(&lock);
pthread_cond_broadcast(&empty);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
if (argc != 4) {
printf("Usage: ./%s <producers> <consumers> <items>", argv[0]);
return 1;
}
int i;
number_producers = pow(2, atoi(argv[1]));
number_consumers = pow(2, atoi(argv[2]));
number_of_items = pow(2, atoi(argv[3]));
printf("Number of producers: %d\\nNumber of consumers: %d\\nNumber of items: %d", number_producers, number_consumers, number_of_items);
pthread_mutex_init(&lock, 0);
pthread_cond_init(&full, 0);
pthread_cond_init(&empty, 0);
pthread_t producers[number_producers];
pthread_t consumers[number_consumers];
producer_info pi[number_producers];
printf("\\n---Begin producing & consuming!---");
for (i = 0; i < number_producers; i++) {
pi[i].thread_number = i;
pi[i].number_produced = 0;
pthread_create(&producers[i], 0, produce, &pi[i]);
}
for (i = 0; i < number_consumers; i++)
pthread_create(&consumers[i], 0, consume, 0);
for (i = 0; i < number_producers; i++)
pthread_join(producers[i], 0);
for (i = 0; i < number_consumers; i++)
pthread_join(consumers[i], 0);
printf("\\n---Done!---\\n");
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t n_thread;
static pthread_t w_thread;
static pthread_t s_thread;
static pthread_t e_thread;
static pthread_mutex_t monitor;
static pthread_cond_t activeN;
static pthread_cond_t activeW;
static pthread_cond_t activeS;
static pthread_cond_t activeE;
static pthread_barrier_t barrier;
char activeDir;
char *dirs;
char next_dir(char dir) {
int pos = (int)(strchr(dirs, dir) - dirs);
return dirs[(pos + 1) % strlen(dirs)];
}
void del_dir(char dir) {
int i;
for(i = 0; i < strlen(dirs); i++ )
if( dirs[i] == dir )
strcpy( dirs + i, dirs + i + 1 );
}
pthread_cond_t *dir_cond(char dir) {
pthread_cond_t *cond;
switch(dir) {
case Q_NORTH:
cond = &activeN;
break;
case Q_WEST:
cond = &activeW;
break;
case Q_SOUTH:
cond = &activeS;
break;
case Q_EAST:
cond = &activeE;
break;
}
return cond;
}
void *traffic(void *params) {
char dir = *((char *)params);
char nextDir;
pthread_cond_t *cond;
pthread_cond_t *nextDirCond;
struct cart_t *cart;
cond = dir_cond(dir);
fprintf(stderr, "Thread for direction %c starts\\n", dir);
cart = q_getCart(dir);
while (cart != 0) {
fprintf(stderr, "Thread for direction %c gets cart %i\\n", dir, cart->num);
pthread_mutex_lock(&monitor);
while(activeDir != dir){
pthread_cond_wait(cond, &monitor);
printf("Thread for direction %c must wait for entering\\n", dir);
}
printf("Thread for direction %c is allowed to enter\\n", dir);
monitor_arrive(cart);
monitor_cross(cart);
monitor_leave(cart);
nextDir = next_dir(dir);
nextDirCond = dir_cond(nextDir);
activeDir = nextDir;
pthread_cond_signal(nextDirCond);
printf("Thread for direction %c signal thread for direction %c\\n", dir, nextDir);
pthread_mutex_unlock(&monitor);
cart = q_getCart(dir);
}
q_cartHasEntered(dir);
del_dir(dir);
pthread_barrier_wait(&barrier);
fprintf(stderr, "Thread for direction %c exits\\n", dir);
return (void *)0;
}
int main(int argc, char **argv) {
int i;
char dirN = Q_NORTH;
char dirS = Q_SOUTH;
char dirW = Q_WEST;
char dirE = Q_EAST;
dirs = calloc(5, sizeof(char));
strcpy(dirs, "nwse");
if (argc < 2) {
printf("usage: ./trafficmgr <cart string>\\n");
} else {
for (i = 0; i < strlen(argv[1]); i++){
q_putCart(argv[1][i]);
}
}
pthread_barrier_init(&barrier, 0, 4);
q_print(dirN);
q_print(dirS);
q_print(dirW);
q_print(dirE);
activeDir = Q_EAST;
if (pthread_create(&n_thread, 0, traffic, (void *)&dirN) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&w_thread, 0, traffic, (void *)&dirW) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&s_thread, 0, traffic, (void *)&dirS) != 0)
perror("pthread_create"), exit(1);
if (pthread_create(&e_thread, 0, traffic, (void *)&dirE) != 0)
perror("pthread_create"), exit(1);
if (pthread_join(n_thread, 0) != 0) {
perror("pthread_join"), exit(1);
}
if (pthread_join(w_thread, 0) != 0) {
perror("pthread_join"), exit(1);
}
if (pthread_join(s_thread, 0) != 0) {
perror("pthread_join"), exit(1);
}
if (pthread_join(e_thread, 0) != 0) {
perror("pthread_join"), exit(1);
}
q_shutdown();
monitor_shutdown();
if(pthread_barrier_destroy(&barrier))
perror("pthread_barrier_destroy"), exit(1);
return 0;
}
| 0
|
#include <pthread.h>
float hypotenuse;
pthread_mutex_t mutexsum;
void *square_side (void *);
int main (int argc, char **argv)
{
int i;
float sides[2];
pthread_t *thr_ids;
switch (argc)
{
case 3:
sides[0] = atof (argv[1]);
sides[1] = atof (argv[2]);
if ((sides[0] < 1) || (sides[1] < 1))
{
fprintf (stderr, "Error: wrong values for triangle sides.\\n"
"Usage:\\n"
" %s <side_a> <side_b>\\n"
"values of sizes should be > 0\\n",
argv[0]);
exit (1);
}
break;
default:
fprintf (stderr, "Error: wrong number of parameters.\\n"
"Usage:\\n"
" %s <side_a> <side_b>\\n",
argv[0]);
exit (1);
}
thr_ids = (pthread_t *) malloc (2 * sizeof (pthread_t));
if (thr_ids == 0)
{
fprintf (stderr, "File: %s, line %d: Can't allocate memory.",
"pythagoras.c", 80);
exit (1);
}
printf ("\\nPythagoras' theorem | a^2 + b^2 = c^2 \\n");
hypotenuse = 0;
pthread_mutex_init (&mutexsum, 0);
pthread_create (&thr_ids[0], 0, square_side, &sides[0]);
pthread_create (&thr_ids[1], 0, square_side, &sides[1]);
for (i = 0; i < 2; i++)
{
pthread_join (thr_ids[i], 0);
}
printf ("Hypotenuse is %.2f\\n", sqrt(hypotenuse));
pthread_mutex_destroy (&mutexsum);
free (thr_ids);
return 0;
}
void *square_side (void *arg)
{
float side;
side = *( ( float* )arg );
printf ("%.2f^2 = %.2f\\n", side, side * side);
pthread_mutex_lock (&mutexsum);
hypotenuse += side * side;
pthread_mutex_unlock (&mutexsum);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct free_mem * free_list;
int mymalloc_init() {
struct free_mem * head;
pthread_mutex_lock(&lock);
if ((head = sbrk(PAGE)) == (void *) -1){
pthread_mutex_unlock(&lock);
return 1;
}
else{
head->size = PAGE- sizeof(struct free_mem);
head->next = 0;
free_list = head;
pthread_mutex_unlock(&lock);
return 0;
}
}
void *mymalloc(unsigned int size) {
pthread_mutex_lock(&lock);
int buffer = size % ALIGNMENT;
int reqSize = size + (ALIGNMENT - buffer);
struct free_mem * current = free_list;
struct free_mem * previous = free_list;
if(current->size > (reqSize + sizeof(struct header))){
previous = 0;
}
else{
current = current->next;
while((current != 0) &&
(current->size <= (reqSize + sizeof(struct header)))){
current = current->next;
previous = previous->next;
}
if ((previous->size <= (reqSize + sizeof(struct header))) &&
(current == 0)){
struct free_mem * head;
if((head = sbrk(PAGE)) == (void *)-1){
pthread_mutex_unlock(&lock);
return 0;
}
head->size = PAGE - sizeof(struct free_mem);
head->next = 0;
current = head;
}
}
const void * src = (void *)current;
void * free_node_dest = (void *)((char*)src + reqSize);
if (previous == 0){
free_list = memmove(free_node_dest, src, sizeof(struct free_mem));
free_list->size = free_list->size - reqSize;
}else{
previous->next = memmove(free_node_dest, src, sizeof(struct free_mem));
previous->next->size = previous->next->size - reqSize;
}
struct header * new_head = (struct header *)src;
new_head->size = size;
new_head->magic = MAGICNUMBER;
pthread_mutex_unlock(&lock);
return (void *)((char*)new_head + sizeof(struct header));
}
unsigned int myfree(void *ptr) {
struct header * head = (void*)((char*)ptr - sizeof(struct header));
int free_mem_size = head->size + sizeof(struct header);
if(head->magic != MAGICNUMBER){
return 1;
}
else{
pthread_mutex_lock(&lock);
struct free_mem * current = free_list->next;
struct free_mem * previous = free_list;
if(current != 0){
while((previous->size >= free_mem_size) &&
((current == 0) || (current->size <= free_mem_size))){
current = current->next;
previous = previous->next;
}
}
struct free_mem * new_node = (void *) head;
new_node->size = free_mem_size - sizeof(struct free_mem);
new_node->next = current;
previous->next = new_node;
pthread_mutex_unlock(&lock);
}
return 0;
}
| 0
|
#include <pthread.h>
extern FILE *fileout_basicmath_conversion;
extern pthread_mutex_t mutex_print;
int main_basicmath_conversion(void)
{
double a1 = 1.0, b1 = -10.5, c1 = 32.0, d1 = -30.0;
double a2 = 1.0, b2 = -4.5, c2 = 17.0, d2 = -30.0;
double a3 = 1.0, b3 = -3.5, c3 = 22.0, d3 = -31.0;
double a4 = 1.0, b4 = -13.7, c4 = 1.0, d4 = -35.0;
double x[3];
double X;
int solutions;
int i;
unsigned long l = 0x3fed0169L;
struct int_sqrt q;
long n = 0;
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_conversion,"********* ANGLE CONVERSION ***********\\n");
pthread_mutex_unlock(&mutex_print);
double res;
for (X = 0.0; X <= 360.0; X += 1.0)
{
res = deg2rad(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_conversion,"%3.0f degrees = %.12f radians\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
for (X = 0.0; X <= (2 * PI + 1e-6); X += (PI / 180))
{
res = rad2deg(X);
pthread_mutex_lock(&mutex_print);
fprintf(fileout_basicmath_conversion,"%.12f radians = %3.0f degrees\\n", X, res);
pthread_mutex_unlock(&mutex_print);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t timer_mutex;
pthread_cond_t timer_expired_cv;
void *wait_thread(void *time)
{
int time_to_wait = *((int*)time);
printf("wait_thread started\\n");
while (time_to_wait > 0)
{
usleep(1000000);
pthread_mutex_lock(&timer_mutex);
--time_to_wait;
if (time_to_wait == 0)
{
pthread_cond_signal(&timer_expired_cv);
}
pthread_mutex_unlock(&timer_mutex);
}
pthread_exit(0);
}
void *print_thread(void *t)
{
printf("print_thread started\\n");
pthread_mutex_lock(&timer_mutex);
pthread_cond_wait(&timer_expired_cv, &timer_mutex);
pthread_mutex_unlock(&timer_mutex);
printf("Timer expired!\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t waiter, printer;
pthread_attr_t attr;
int timeout = 0;
printf("Enter seconds to wait: ");
scanf("%d", &timeout);
pthread_mutex_init(&timer_mutex, 0);
pthread_cond_init (&timer_expired_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&waiter, &attr, wait_thread, (void*)&timeout);
pthread_create(&printer, &attr, print_thread, 0);
pthread_join(waiter, 0);
pthread_join(printer, 0);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&timer_mutex);
pthread_cond_destroy(&timer_expired_cv);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
int needQuit(pthread_mutex_t *mtx) {
switch (pthread_mutex_trylock(mtx)) {
case 0:
pthread_mutex_unlock(mtx);
return 1;
case EBUSY:
return 0;
}
return 1;
}
void *thread_do(void *arg) {
pthread_mutex_t *mx = arg;
int i = 0;
while (!needQuit(mx)) {
printf("%d\\n", ++i);
sleep(1);
}
return 0;
}
int main(int argc, char *argv[]) {
pthread_t th;
pthread_mutex_t mxq;
pthread_mutex_init(&mxq, 0);
pthread_mutex_lock(&mxq);
pthread_create(&th, 0, thread_do, &mxq);
sleep(2);
pthread_mutex_unlock(&mxq);
pthread_join(th, 0);
sleep(2);
return 0;
}
| 1
|
#include <pthread.h>
int main(int argc, char* argv[]) {
int out1 = 0;
int out2 = 0;
int id;
SharedMem *ptr;
id = shmget (atoi(argv[1]), 0, 0);
if (id == -1){
perror ("child shmget failed");
exit (1);
}
ptr = shmat (id, (void *) 0, 1023);
if (ptr == (void *) -1){
perror ("child shmat failed");
exit (2);
}
int file;
if ((file = open("output.txt", O_WRONLY)) <= -1)
exit(1);
int i = -1;
do {
pthread_mutex_lock(&ptr->lock);
while (ptr->count1 == 0 && ptr->count2 == 0)
while (pthread_cond_wait(&ptr->ItemAvailable, &ptr->lock) != 0);
if (ptr->count1 > 0) {
write(file, ptr->Buffer1[out1], strlen(ptr->Buffer1[out1]));
out1 = (out1 + 1) % bufferSize;
ptr->count1--;
} else if (ptr->count2 > 0) {
write(file, ptr->Buffer2[out2], strlen(ptr->Buffer2[out2]));
out2 = (out2 + 1) % bufferSize;
ptr->count2--;
}
i = ptr->count2 + ptr->count1;
pthread_mutex_unlock(&ptr->lock);
pthread_cond_signal(&ptr->SpaceAvailable);
if (i == 0){
pthread_mutex_lock(&ptr->lock2);
i = ptr->end + 2;
pthread_mutex_unlock(&ptr->lock2);
}
} while (i != 0);
close(file);
return 0;
}
| 0
|
#include <pthread.h>
struct file_counter {
char *filename;
int words_count;
int id;
};
struct file_counter *mailbox = 0;
pthread_mutex_t mailbox_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mailbox_cond = PTHREAD_COND_INITIALIZER;
void *count_words(void *file_counter_a);
int main(int argc, char *argv[]) {
struct file_counter counter1 = {0};
struct file_counter counter2 = {0};
int reporter_num = 0;
int total_counter = 0;
pthread_t tid1, tid2;
if (argc != 3) {
printf("usage: a.out file1 file2.\\n");
exit(-1);
}
pthread_mutex_lock(&mailbox_lock);
counter1.filename = argv[1];
counter1.words_count = 0;
counter1.id = 1;
pthread_create(&tid1, 0, count_words, (void*)&counter1);
counter2.filename = argv[2];
counter2.words_count = 0;
counter2.id = 2;
pthread_create(&tid2, 0, count_words, (void*)&counter2);
while (reporter_num < 2) {
while (mailbox == 0) {
pthread_cond_wait(&mailbox_cond, &mailbox_lock);
}
printf("MAIN: get the mailbox.\\n");
if (mailbox == &counter1)
pthread_join(tid1, 0);
if (mailbox == &counter2)
pthread_join(tid2, 0);
total_counter += mailbox->words_count;
printf("MAIN: get mailmsg: id:%d, words:%d\\n", mailbox->id,
mailbox->words_count);
mailbox = 0;
pthread_cond_signal(&mailbox_cond);
++reporter_num;
}
printf("MAIN: file: %s, %s 's words total num : %d\\n", argv[1],
argv[2], total_counter);
exit(0);
}
void *count_words(void *file_counter_a) {
struct file_counter *counter = (struct file_counter *)file_counter_a;
FILE *fp = 0;
char c, prevc = '\\0';
if ((fp=fopen(counter->filename, "r")) != 0) {
while ((c = fgetc(fp)) != EOF) {
if (!isalnum(c) && isalnum(prevc))
++counter->words_count;
prevc = c;
}
} else
printf("open the file failed\\n", counter->filename);
pthread_mutex_lock(&mailbox_lock);
while (mailbox != 0) {
printf("COUNT %d : mailbox is not NULL, cond_wait it\\n", counter->id);
pthread_cond_wait(&mailbox_cond, &mailbox_lock);
}
mailbox = counter;
printf("COUNT %d : signal the mailbox_cond\\n", counter->id);
pthread_cond_signal(&mailbox_cond);
pthread_mutex_unlock(&mailbox_lock);
return 0;
}
| 1
|
#include <pthread.h>
FILE *logfile = 0;
int open_logfile(char *filepath) {
logfile = fopen(filepath, "we");
if(!logfile) {
print(ERROR, "fopen: %s", strerror(errno));
return -1;
}
return 0;
}
void file_logger(int level, char *fmt, ...) {
va_list argptr;
if(!logfile)
return;
pthread_mutex_lock(&print_lock);
__builtin_va_start((argptr));
switch(level) {
case DEBUG:
fprintf(logfile, "[DEBUG ] ");
break;
case INFO:
fprintf(logfile, "[INFO ] ");
break;
case WARNING:
fprintf(logfile, "[WARNING] ");
break;
case ERROR:
fprintf(logfile, "[ERROR ] ");
break;
case FATAL:
fprintf(logfile, "[FATAL ] ");
break;
default:
fprintf(logfile, "[UNKNOWN] ");
break;
}
vfprintf(logfile, fmt, argptr);
fprintf(logfile, "\\n");
fflush(logfile);
;
pthread_mutex_unlock(&print_lock);
}
| 0
|
#include <pthread.h>
struct foo* fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo
{
int f_count;
pthread_mutex_t f_lock;
int id;
struct foo* next;
};
struct foo* foo_alloc(int id)
{
int idx;
struct foo* fp;
if ((fp = malloc(sizeof(struct foo))) != 0)
{
fp->f_count = 1;
fp->id = id;
if (pthread_mutex_init(&fp->f_lock, 0) != 0)
{
free(fp);
return 0;
}
idx = (((unsigned long)id) % 29);
pthread_mutex_lock(&hashlock);
fp->next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo* fp)
{
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo* foo_find(int id)
{
struct foo* fp;
pthread_mutex_lock(&hashlock);
for (fp = fh[(((unsigned long)id) % 29)]; fp != 0; fp = fp->next)
{
if (fp->id == id)
{
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo* fp)
{
struct foo* tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1)
{
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1)
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return ;
}
idx = (((unsigned long)fp->id) % 29);
tfp = fh[idx];
if (tfp == fp)
fh[idx] = fp->next;
else
{
while (tfp->next != fp)
tfp = tfp->next;
tfp->next = fp->next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
}
else
{
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
| 1
|
#include <pthread.h>
int globalInt = 0;
sem_t mySem;
pthread_mutex_t lock;
int running = 1;
int var1 = 0;
int var2 = 0;
void processTestVFork()
{
globalInt = 0;
printf("%s\\n", "************vfork*************");
int localInt = 0;
pid_t pid = vfork();
if(pid == 0){
for (int i = 0; i < 10; i++)
{
globalInt++;
localInt++;
}
printf("Global: %i Local: %i\\n",globalInt, localInt);
_exit(0);
}
else if(pid > 0){
for (int i = 0; i < 10; i++)
{
globalInt++;
localInt++;
}
printf("Global: %i Local: %i\\n",globalInt, localInt);
}
else{
}
}
void processTestFork()
{
globalInt = 0;
printf("%s\\n", "************fork*************");
int localInt = 0;
pid_t pid = fork();
if(pid == 0){
for (int i = 0; i < 10; i++)
{
globalInt++;
localInt++;
}
printf("Global: %i Local: %i\\n",globalInt, localInt);
_exit(0);
}
else if(pid > 0){
for (int i = 0; i < 10; i++)
{
globalInt++;
localInt++;
}
printf("Global: %i Local: %i\\n",globalInt, localInt);
}
else{
}
}
void pthredTest(){
globalInt = 0;
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1, 0, myThreadFunction1, 0);
pthread_join(tid1, 0);
pthread_create(&tid2, 0, myThreadFunction1, 0);
pthread_join(tid2, 0);
}
void semaphoresTest(){
pthread_t threads[5];
if( sem_init(&mySem,0,3) < 0);
{
perror("semaphore initilitzation");
}
for (int i = 0; i < 5; i++)
{
pthread_create(&threads[i], 0, myThreadFunction2, (void*)i);
}
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
pthread_join(threads[2], 0);
pthread_join(threads[3], 0);
pthread_join(threads[4], 0);
}
void mutexTestWithoutMutex(){
pthread_t tid3;
pthread_t tid4;
pthread_create(&tid3, 0, myThreadFunction3, 0);
pthread_create(&tid4, 0, myThreadFunction4, 0);
pthread_join(tid4, 0);
}
void mutexTestWithMutex(){
running = 1;
var1 = 0;
var2 = 0;
if (pthread_mutex_init(&lock, 0) != 0)
{
perror("mutex initilization");
}
pthread_t tid3;
pthread_t tid4;
pthread_create(&tid3, 0, myThreadFunction5, 0);
pthread_create(&tid4, 0, myThreadFunction6, 0);
pthread_join(tid3, 0);
pthread_join(tid4, 0);
pthread_mutex_destroy(&lock);
}
void *myThreadFunction1(void *vargp)
{
printf("%s\\n", "************thread*************");
int localInt = 0;
for (int i = 0; i < 1000000; i++)
{
globalInt++;
localInt++;
}
printf("Global: %i Local: %i\\n",globalInt, localInt);
}
void *myThreadFunction2(void* id){
while(1){
sem_wait(&mySem);
printf("%i\\n", (int)id);
sleep(1);
sem_post(&mySem);
}
}
void *myThreadFunction3(void *vargp){
while(running){
var1++;
var2 = var1;
}
}
void *myThreadFunction4(void *vargp){
for (int i = 0; i < 20; i++){
printf("Number 1 is %i, number 2 is %i\\n",var1,var2);
usleep(100000);
}
running = 0;
}
void *myThreadFunction5(void *vargp){
while(running){
pthread_mutex_lock(&lock);
var1++;
var2 = var1;
pthread_mutex_unlock(&lock);
}
}
void *myThreadFunction6(void *vargp){
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;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
pthread_cond_t cv;
pthread_key_t key;
int jobInfo[50];
int jobAvail = 0;
int i = 0;
int jobCount = 0;
void *slave(void *threadID)
{
int threadNum = *(int *)threadID;
int *local_job;
while(jobCount < 25)
{
pthread_mutex_lock(&m);
while(jobAvail < 1 )
pthread_cond_wait(&cv,&m);
local_job = (int *)malloc(4);
pthread_setspecific(key, (void *)local_job);
*local_job = jobInfo[jobCount];
jobCount++;
jobAvail--;
pthread_mutex_unlock(&m);
threadNum, *local_job);
}
pthread_exit(0);
}
main()
{
pthread_t thd1, thd2, thd3;
int j = 1;
pthread_mutex_init(&m, 0);
pthread_cond_init(&cv, 0);
pthread_create(&thd1, 0, slave, (void*)&j);
j++;
pthread_create(&thd2, 0, slave, (void*)&j);
j++;
pthread_create(&thd3, 0, slave, (void*)&j);
while(i<25)
{
jobInfo[i] = i;
i++;
pthread_mutex_lock(&m);
jobAvail++;
pthread_cond_signal(&cv);
pthread_mutex_unlock(&m);
}
printf("simulate waiting for others to finish\\n");
sleep(5);
pthread_join(thd1, 0);
pthread_join(thd2, 0);
pthread_join(thd3, 0);
pthread_mutex_destroy(&m);
pthread_cond_destroy(&cv);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_t handles[16];
int nprimes= 0;
int lower = 0;
int biggest = 10000000;
int chunk_size = 1000;
pthread_mutex_t prime_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lower_lock = PTHREAD_MUTEX_INITIALIZER;
void *func(void *s)
{
struct subrange range;
int fd, n;
fd = *(int *)s;
while(1) {
pthread_mutex_lock(&lower_lock);
range.min = lower;
range.max = lower + chunk_size;
lower += chunk_size;
pthread_mutex_unlock(&lower_lock);
if (range.min >= biggest)
pthread_exit(0);
write(fd, &range, sizeof range);
read(fd, &n, sizeof(int));
pthread_mutex_lock(&prime_lock);
nprimes += n;
pthread_mutex_unlock(&prime_lock);
}
}
int main(int argc, char *argv[])
{
int i, sock, nsrv = 0;
struct hostent *host_info;
struct sockaddr_in server;
int opt;
while ((opt = getopt(argc, argv, "n:c:")) != -1) {
switch(opt) {
case 'n': biggest = atoi(optarg); break;
case 'c': chunk_size = atoi(optarg); break;
}
}
argc -= optind;
argv += optind;
printf("biggest = %d, chunk_size = %d\\n", biggest, chunk_size);
if (argc == 0) {
printf("no servers specified -- giving up!\\n");
exit(1);
}
for (i = 0; i < argc; i ++) {
host_info = gethostbyname(argv[i]);
if (host_info == 0) {
printf("cannot resolve %s -- ignoring\\n", argv[i]);
continue;
}
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("creating stream socket");
exit(1);
}
server.sin_family = AF_INET;
memcpy(&server.sin_addr, host_info->h_addr, host_info->h_length);
server.sin_port = htons(PRIME_PORT);
if (connect(sock, (struct sockaddr*)&server, sizeof server) < 0) {
printf("Cannot connect to server %s -- ignoring\\n", argv[i]);
continue;
}
printf("connected to %s\\n", argv[i]);
pthread_create(&handles[nsrv], 0, func, &sock);
nsrv++;
}
if (nsrv == 0) {
printf("no servers found -- giving up!\\n");
exit(3);
}
printf("using %d servers\\n", nsrv);
for (i=0; i < nsrv; i++) {
pthread_join(handles[i], 0);
}
printf("found %d primes\\n", nprimes);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mem_lock;
unsigned mem_request_tag[MAX_DUMP_MEM_NUM];
unsigned mem_response_tag[MAX_DUMP_MEM_NUM];
struct http_request_header *mem_request_header[MAX_DUMP_MEM_NUM];
struct http_response_header *mem_response_header[MAX_DUMP_MEM_NUM];
void init_mem_mgt(){
pthread_mutex_init(&mem_lock,0);
int i=0;
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
mem_request_tag[i]=0;
mem_response_tag[i]=0;
mem_request_header[i]=0;
mem_response_header[i]=0;
}
mem_request_header[0]=calloc(sizeof(struct http_request_header),MAX_DUMP_MEM_NUM);
if(mem_request_header[0]==0){
fprintf(stderr,"εε§εει
ε
εεΊι");
exit(-1);
}
mem_response_header[0]=calloc(sizeof(struct http_response_header),MAX_DUMP_MEM_NUM);
if(mem_response_header[0]==0){
fprintf(stderr,"εε§εει
ε
εεΊι");
exit(-1);
}
for(i=1;i<MAX_DUMP_MEM_NUM;i++){
mem_request_header[i]=mem_request_header[0]+i;
mem_response_header[i]=mem_response_header[0]+i;
}
printf("ε
εει
ζε!\\n");
}
struct http_request_header *malloc_request(){
int i=0;
pthread_mutex_lock(&mem_lock);
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
if(mem_request_tag[i]==0){
mem_request_tag[i]=1;
memset(mem_request_header[i],0,sizeof(struct http_request_header));
pthread_mutex_unlock(&mem_lock);
return mem_request_header[i];
}
}
pthread_mutex_unlock(&mem_lock);
return 0;
}
void mdestory_request(struct http_request_header *data){
int i=0;
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
if(mem_request_header[i]==data){
mem_request_tag[i]=0;
}
}
}
struct http_response_header *malloc_response(){
int i=0;
pthread_mutex_lock(&mem_lock);
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
if(mem_response_tag[i]==0){
mem_response_tag[i]=1;
memset(mem_response_header[i],0,sizeof(struct http_response_header));
pthread_mutex_unlock(&mem_lock);
return mem_response_header[i];
}
}
pthread_mutex_unlock(&mem_lock);
return 0;
}
void mdestory_response(struct http_response_header *data){
int i=0;
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
if(mem_response_header[i]==data){
mem_response_tag[i]=0;
}
}
}
void mdestory_all(){
int i=0;
for(i=0;i<MAX_DUMP_MEM_NUM;i++){
free(mem_request_header[i]);
mem_request_header[i]=0;
free(mem_response_header[i]);
mem_response_header[i]=0;
}
}
| 1
|
#include <pthread.h>
buffer_item buffer[5];
pthread_mutex_t mutex;
sem_t full;
sem_t empty;
int start;
int end;
int insert_item(buffer_item item){
int pos;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
pos = start;
start = (start + 1)%5;
pthread_mutex_unlock(&mutex);
sem_post(&full);
buffer[pos] = item;
return 0;
}
int remove_item(buffer_item *item){
int pos;
sem_wait(&full);
pthread_mutex_lock(&mutex);
pos = end;
end = (end + 1)%5;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
*item = buffer[pos];
return 0;
}
void *producer(void *param){
buffer_item rand_item;
while(1){
usleep(rand()%1000000);
rand_item = rand();
printf("producer[%d]\\tproduced\\t%d\\n", *(int *)param, rand_item);
if(insert_item(rand_item)){
fprintf(stderr, "report error condition\\n");
}
}
}
void *consumer(void *param){
buffer_item rand_item;
while(1){
usleep(rand()%1000000);
rand_item = rand();
if(remove_item(&rand_item))
fprintf(stderr, "report error condition\\n");
else
printf("consumer[%d]\\tconsumed\\t%d\\n", *(int *)param ,rand_item);
}
}
int main(int argc, char *argv[]){
srand((unsigned)time(0));
int producer_num,consumer_num,run_time;
run_time=atoi(argv[1]);
producer_num=atoi(argv[2]);
consumer_num=atoi(argv[3]);
pthread_mutex_init(&mutex,0);
sem_init(&full,0,0);
sem_init(&empty,0,5);
start = end = 0;
pthread_t *producer_t = (pthread_t *)malloc(producer_num*sizeof(pthread_t));
int *producer_id = (int *)malloc((producer_num+1)*sizeof(int));
for(int i=0; i<producer_num; ++i, producer_id[i]=i)
pthread_create(&producer_t[i], 0, producer, &producer_id[i+1]);
pthread_t *consumer_t = (pthread_t *)malloc(consumer_num*sizeof(pthread_t));
int *consumer_id = (int *)malloc((consumer_num+1)*sizeof(int));
for(int i=0; i<consumer_num; ++i, consumer_id[i]=i)
pthread_create(&consumer_t[i], 0, consumer, &consumer_id[i+1]);
sleep(run_time);
return 0;
}
| 0
|
#include <pthread.h>
volatile int x;
volatile int y;
volatile int past_x;
pthread_mutex_t lock_one;
pthread_mutex_t lock_two;
pthread_barrier_t barrier;
pthread_t threads[2];
void random_hog()
{
volatile unsigned long i, x;
unsigned long count = random() / (1 << 20) + 10000;
for (i = 0; i < count; i++)
x++;
}
void * worker_foo(void *data)
{
while(1) {
random_hog();
pthread_mutex_lock(&lock_one);
pthread_mutex_lock(&lock_two);
pthread_barrier_wait(&barrier);
x = ++y;
printf("foo %d\\n", x);
pthread_mutex_unlock(&lock_one);
pthread_mutex_unlock(&lock_two);
}
return 0;
}
void * worker_bar(void *data)
{
while(1) {
random_hog();
pthread_mutex_lock(&lock_two);
pthread_mutex_lock(&lock_one);
pthread_barrier_wait(&barrier);
x = ++y;
printf("bar %d\\n", x);
pthread_mutex_unlock(&lock_two);
pthread_mutex_unlock(&lock_one);
}
return 0;
}
void init_seed(void)
{
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
srandom(ts.tv_nsec);
srandom(time(0));
}
static void watchdog(int signr)
{
past_x = x;
(void) signr;
if(x == past_x) {
printf("watchdog\\n");
exit(0);
}
}
void timer_start() {
struct itimerval timer;
struct sigaction action;
sigset_t set;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 100000;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 100000;
sigemptyset(&action.sa_mask);
action.sa_handler = watchdog;
action.sa_flags = 0;
sigaction(SIGALRM, &action, 0);
setitimer(ITIMER_REAL, &timer, 0);
}
void timer_stop() {
struct itimerval timer;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &timer, 0);
}
int main(int argc, char **argv)
{
init_seed();
pthread_barrier_init(&barrier, 0, 2);
timer_start();
pthread_create(&threads[0], 0, worker_foo, 0);
pthread_create(&threads[1], 0, worker_bar, 0);
pthread_join(threads[0], 0);
pthread_join(threads[1], 0);
timer_stop();
printf("done\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_t fid[1],cid[20];
pthread_mutex_t cpu=PTHREAD_MUTEX_INITIALIZER,s[20];
int num;
int remain;
int state;
int prio;
}pcb;
int prio;
int index;
}temp;
pcb thread[20],nThread[20];
temp pcbIns[20];
int total=0;
int first=0;
int waitTime=0;
void insertionSort(n){
int j=1;
for(j=1;j<n;j++){
int key=pcbIns[j].prio;
int i=j-1;
while((i>=0)&&(pcbIns[i].prio>key)){
pcbIns[i+1].prio=pcbIns[i].prio;
int tempIdx=pcbIns[i+1].index;
pcbIns[i+1].index=pcbIns[i].index;
pcbIns[i].index=tempIdx;
i--;
}
pcbIns[i+1].prio=key;
}
}
void* child(void* vargp){
int i = *(int*)vargp;
pthread_mutex_lock(&s[i]);
pthread_mutex_lock(&cpu);
waitTime+=total;
while(nThread[i].remain>0){
printf("ThreadId is:%d Round:%d Remain:%d Prio:%d \\n",nThread[i].num,total,nThread[i].remain,nThread[i].prio);
total++;
nThread[i].remain--;
}
pthread_mutex_unlock(&cpu);
pthread_mutex_unlock(&s[i]);
}
void* father(void* vargp){
srand(time(0));
int i=0;
int it1=0;
for(i=0;i<20;i++){
pthread_mutex_lock(&s[i]);
thread[i].num=i;
thread[i].remain=rand()%5+1;
thread[i].prio=rand()%5+1;
thread[i].state=0;
pcbIns[i].prio=thread[i].prio;
pcbIns[i].index=i;
}
for(i=0;i<20;i++){
thread[i].state=1;
pthread_mutex_unlock(&s[i]);
}
insertionSort(20);
first=pcbIns[0].index;
for(it1=0;it1<20;it1++){
nThread[it1]=thread[pcbIns[20 -it1-1].index];
}
int inum[20];
for(it1=0;it1<20;it1++){
inum[it1]=it1;
}
for(it1=0;it1<20;it1++){
pthread_create(&cid[it1],0,child,(void*)(&inum[it1]));
sleep(1);
}
for(i=0;i<20;i++){
pthread_join(cid[i],0);
}
printf("\\nAverage WaitTime = %f s\\n",waitTime*1.0/20);
}
int main(){
int i=0,j=0;
for(j=0;j<20;j++){
s[j]=cpu;
}
pthread_create(&fid[i],0,father,(void*)(&i));
pthread_join(fid[i],0);
return 0;
}
| 0
|
#include <pthread.h>
int K;
struct Node
{
int data;
struct Node* next;
};
struct list
{
struct Node * header;
struct Node * tail;
};
pthread_mutex_t mutex_lock;
struct list *List;
struct Node* generate_data_node(int n)
{
struct Node *ptr;
ptr = (struct Node *)malloc(sizeof(struct Node)*n);
if (ptr == 0)
{
perror("Node allocation failed!\\n");
}
struct Node *tmp;
tmp = ptr;
int i;
for(i = 0; i < n - 1; i++)
{
tmp->data = 1;
tmp->next = tmp+1;
tmp++;
}
tmp->data = 1;
tmp->next = 0;
return ptr;
}
void * producer_thread(void *arg)
{
struct Node * ptr, tmp;
int counter = 0;
ptr = generate_data_node(K);
if( 0 != ptr )
{
pthread_mutex_lock(&mutex_lock);
if( List->header == 0 )
{
List->header = List->tail = ptr;
}
else
{
List->tail->next = ptr;
List->tail = ptr + K - 1;
}
pthread_mutex_unlock(&mutex_lock);
}
++counter;
}
int main(int argc, char* argv[])
{
int i, num_threads;
struct Node *tmp,*next;
struct timeval starttime, endtime;
num_threads = atoi(argv[1]);
K = atoi(argv[2]);
pthread_t producer[num_threads];
pthread_mutex_init(&mutex_lock, 0);
List = (struct list *)malloc(sizeof(struct list));
if( 0 == List )
{
printf("End here\\n");
exit(0);
}
List->header = List->tail = 0;
gettimeofday(&starttime,0);
for( i = 0; i < num_threads; i++ )
{
pthread_create(&(producer[i]), 0, (void *) producer_thread, 0);
}
for( i = 0; i < num_threads; i++ )
{
if(producer[i] != 0)
{
pthread_join(producer[i],0);
}
}
gettimeofday(&endtime,0);
if( List->header != 0 )
{
next = List->header;
while(next)
{
tmp = next;
next = (tmp + K - 1)->next;
free(tmp);
}
}
printf("Total run time is %ld microseconds.\\n", (endtime.tv_sec-starttime.tv_sec) * 1000000+(endtime.tv_usec-starttime.tv_usec));
return 0;
}
| 1
|
#include <pthread.h>
struct spectrum_buffer* spectrum_input_buffers_head;
struct spectrum_buffer* spectrum_input_buffers_tail;
sem_t spectrum_input_buffer_sem;
int spectrum_input_sequence=0;
int spectrum_input_buffers=0;
pthread_mutex_t spectrum_input_buffer_mutex;
struct spectrum_buffer* spectrum_free_buffers_head;
struct spectrum_buffer* spectrum_free_buffers_tail;
pthread_mutex_t spectrum_free_buffer_mutex;
void free_spectrum_buffer(struct spectrum_buffer* buffer);
void put_spectrum_free_buffer(struct spectrum_buffer* buffer) {
pthread_mutex_lock(&spectrum_free_buffer_mutex);
if(spectrum_free_buffers_tail==0) {
spectrum_free_buffers_head=spectrum_free_buffers_tail=buffer;
} else {
spectrum_free_buffers_tail->next=buffer;
spectrum_free_buffers_tail=buffer;
}
pthread_mutex_unlock(&spectrum_free_buffer_mutex);
if(debug_buffers) fprintf(stderr,"put_spectrum_free_buffer: %08X\\n",(unsigned int)buffer);
}
struct spectrum_buffer* get_spectrum_free_buffer(void) {
struct spectrum_buffer* buffer;
if(spectrum_free_buffers_head==0) {
fprintf(stderr,"get_spectrum_free_buffer: NULL\\n");
return 0;
}
pthread_mutex_lock(&spectrum_free_buffer_mutex);
buffer=spectrum_free_buffers_head;
spectrum_free_buffers_head=buffer->next;
if(spectrum_free_buffers_head==0) {
spectrum_free_buffers_tail=0;
}
buffer->size=SPECTRUM_BUFFER_SIZE;
pthread_mutex_unlock(&spectrum_free_buffer_mutex);
if(debug_buffers) fprintf(stderr,"get_spectrum_free_buffer: %08X\\n",(unsigned int)buffer);
return buffer;
}
void put_spectrum_input_buffer(struct spectrum_buffer* buffer) {
pthread_mutex_lock(&spectrum_input_buffer_mutex);
buffer->sequence=spectrum_input_sequence++;
if(spectrum_input_buffers_tail==0) {
spectrum_input_buffers_head=spectrum_input_buffers_tail=buffer;
} else {
spectrum_input_buffers_tail->next=buffer;
spectrum_input_buffers_tail=buffer;
}
pthread_mutex_unlock(&spectrum_input_buffer_mutex);
if(debug_buffers) fprintf(stderr,"put_spectrum_input_buffer: %08X\\n",(unsigned int)buffer);
}
struct spectrum_buffer* get_spectrum_input_buffer(void) {
struct spectrum_buffer* buffer;
if(spectrum_input_buffers_head==0) {
fprintf(stderr,"get_spectrum_input_buffer: NULL\\n");
return 0;
}
pthread_mutex_lock(&spectrum_input_buffer_mutex);
buffer=spectrum_input_buffers_head;
spectrum_input_buffers_head=buffer->next;
if(spectrum_input_buffers_head==0) {
spectrum_input_buffers_tail=0;
}
pthread_mutex_unlock(&spectrum_input_buffer_mutex);
if(debug_buffers) fprintf(stderr,"get_spectrum_input_buffer: %08X\\n",(unsigned int)buffer);
return buffer;
}
struct spectrum_buffer* new_spectrum_buffer() {
struct spectrum_buffer* buffer;
buffer=malloc(sizeof(struct spectrum_buffer));
buffer->next=0;
buffer->size=SPECTRUM_BUFFER_SIZE;
if(debug_buffers) fprintf(stderr,"new_spectrum_buffer: %08X size=%d\\n",(unsigned int)buffer,buffer->size);
return buffer;
}
void create_spectrum_buffers(int n) {
struct spectrum_buffer* buffer;
int i;
pthread_mutex_init(&spectrum_input_buffer_mutex, 0);
pthread_mutex_init(&spectrum_free_buffer_mutex, 0);
for(i=0;i<n;i++) {
buffer=new_spectrum_buffer();
put_spectrum_free_buffer(buffer);
}
}
void free_spectrum_buffer(struct spectrum_buffer* buffer) {
if(debug) fprintf(stderr,"free_spectrum_buffer: %08X\\n",(unsigned int)buffer);
put_spectrum_free_buffer(buffer);
}
| 0
|
#include <pthread.h>
extern struct destroyerRocket destRocket;
static void animateDestRocket();
static void initDestRocket(struct destroyer *);
void *shootDestRocket(void *args) {
struct destroyer *ship = args;
srand(getpid());
while (1) {
if (!destRocket.isAlive && destRocket.hit < 1) {
sleep(1 + (rand()%3));
initDestRocket(ship);
animateDestRocket();
}
}
}
void initDestRocket(struct destroyer *ship) {
strncpy(destRocket.message, DESTROYER_ROCKET, DESTROYER_ROCKET_LEN);
destRocket.length = DESTROYER_ROCKET_LEN;
destRocket.row = ship->row + 2;
destRocket.col = ship->col + 2;
destRocket.dir = 1;
destRocket.delay = 2;
destRocket.hit = 0;
destRocket.isAlive = 1;
}
void animateDestRocket() {
pthread_mutex_lock(&mx);
move(destRocket.row, destRocket.col);
addstr(destRocket.message);
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
while (destRocket.isAlive) {
usleep(destRocket.delay * 20000);
pthread_mutex_lock(&mx);
move(destRocket.row, destRocket.col);
addnstr(" ", DESTROYER_ROCKET_LEN);
destRocket.row += destRocket.dir;
move(destRocket.row, destRocket.col);
addnstr(destRocket.message, DESTROYER_ROCKET_LEN);
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
if (destRocket.row >= LINES-2) {
eraseDestroyerRocket();
destRocket.isAlive = 0;
} else if (destRocket.hit > 0) {
eraseDestroyerRocket();
destRocket.isAlive = 0;
}
}
}
void eraseDestroyerRocket() {
pthread_mutex_lock(&mx);
move(destRocket.row, destRocket.col);
addnstr(" ",
DESTROYER_ROCKET_LEN);
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
}
| 1
|
#include <pthread.h>
sem_t sem1;
pthread_mutex_t m1;
int contador = 0;
void func(int i){
int tid;
tid = i;
printf("Soy el Hilo %d\\n", tid);
sleep(tid*2);
pthread_mutex_lock(&m1);
contador = contador + 1;
if(contador != 5){
pthread_mutex_unlock(&m1);
sem_wait(&sem1);
printf("Soy el hilo %d paso la barrera\\n", tid);
}else{
printf("Hilos en la barrera\\n");
sleep(tid);
for (i = 0; i < 5; ++i)
sem_post(&sem1);
pthread_mutex_unlock(&m1);
}
}
int main(){
int i;
pthread_t hilo[5];
pthread_mutex_init(&m1, 0);
for (i = 0; i < 5; ++i)
pthread_create(&hilo[i],0,(void *)&func,(void *)i);
for (i = 0; i < 5; ++i)
pthread_join(hilo[i],0);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.