text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
unsigned short ADPAL[256];
static char pathbuf[4096];
int isIphone5;
void *_psg;
static void *_spu;
static pthread_mutex_t lckobj = PTHREAD_MUTEX_INITIALIZER;
extern struct VgsKeyInfo _vgskey;
int vgsint_init(const char *rompath)
{
char log[1024];
static char *rom = 0;
char *bin;
FILE *fp;
int fsize;
int i, j, size;
int cn, pn, bn;
unsigned char s[4];
char path[80];
struct stat stbuf;
_psg = vgsdec_create_context();
if (0 == _psg) {
return -1;
}
stat(rompath, &stbuf);
fsize = (int)stbuf.st_size;
fp = fopen(rompath, "rb");
if (0 == fp) {
return -1;
}
rom = (char *)malloc(fsize);
if (0 == rom) {
fclose(fp);
return -1;
}
fread(rom, fsize, 1, fp);
fclose(fp);
bin = rom;
memcpy(&BN, bin, 4);
bin += 4;
BR = (struct _BINREC *)malloc(BN * sizeof(struct _BINREC));
if (0 == BR) {
return -1;
}
memset(BR, 0, BN * sizeof(struct _BINREC));
for (i = 0; i < BN; i++) {
memset(BR[i].name, 0, 16);
memcpy(BR[i].name, bin, 16);
bin += 16;
for (j = 0; '\\0' != BR[i].name[j]; j++) {
if (15 == j) {
return -1;
}
BR[i].name[j] ^= 0xAA;
}
}
for (i = 0; i < BN; i++) {
memcpy(s, bin, 4);
bin += 4;
size = s[0];
size <<= 8;
size |= s[1];
size <<= 8;
size |= s[2];
size <<= 8;
size |= s[3];
BR[i].size = size;
BR[i].data = (char *)malloc(BR[i].size);
if (0 == BR[i].data) {
return -1;
}
memcpy(BR[i].data, bin, BR[i].size);
bin += BR[i].size;
}
cn = 0;
pn = 0;
bn = 0;
for (i = 0; i < 256; i++) {
sprintf(path, "GSLOT%03d.CHR", i);
if (0 == gload(i, path)) cn++;
sprintf(path, "ESLOT%03d.PCM", i);
if (0 == eload(i, path)) pn++;
sprintf(path, "BSLOT%03d.BGM", i);
if (0 == bload(i, path)) bn++;
}
sprintf(log, "Data has extracted. (CHR=%d, PCM=%d, BGM=%d)", cn, pn, bn);
puts(log);
vgs2_pallet(7);
if (0 != vgs2_init()) {
return -1;
}
make_pallet();
_spu = vgsspu_start2(22050, 16, 1, 2048, sndbuf);
if (0 == _spu) {
return -1;
}
return 0;
}
void make_pallet()
{
int i, j;
int r, g, b;
for (j = 0, i = 0; i < 256; i++) {
r = (_PAL[i] & 0x00FF0000) >> 16;
g = (_PAL[i] & 0x0000FF00) >> 8;
b = (_PAL[i] & 0x000000FF);
r &= 0xF8;
r >>= 3;
g &= 0xFC;
g >>= 3;
b &= 0xF8;
b >>= 3;
ADPAL[i] = r;
ADPAL[i] <<= 5;
ADPAL[i] |= g;
ADPAL[i] <<= 5;
ADPAL[i] |= b;
}
ADPAL[0] = 0x5;
}
void vgsint_setdir(const char *dir)
{
strcpy(pathbuf, dir);
strcat(pathbuf, "/");
}
FILE *vgs2_fopen(const char *fname, const char *mode)
{
char path[4096];
strcpy(path, pathbuf);
strcat(path, fname);
return fopen(path, mode);
}
void vgs2_deleteAds()
{
;
}
void vgs2_showAds()
{
;
}
void lock()
{
pthread_mutex_lock(&lckobj);
}
void unlock()
{
pthread_mutex_unlock(&lckobj);
}
void vgs2_unlink(const char *filename)
{
unlink(filename);
}
| 1
|
#include <pthread.h>
{
pthread_mutex_t mutex;
struct timespec *queue;
int s_queue;
int i_queue;
int n_queue;
pthread_cond_t not_empty;
pthread_cond_t not_full;
int max_send;
int n_sent;
} queue_t;
{
queue_t *queue;
int id;
pthread_t pid;
} args_t;
void *sender(void *arg)
{
args_t *args = (args_t *)arg;
queue_t *q = args->queue;
int n_sent =0;
int have_data = 0;
pthread_mutex_lock(&q->mutex);
while (q->n_sent < q->max_send) {
if (!have_data) {
pthread_mutex_unlock(&q->mutex);
sched_yield();
pthread_mutex_lock(&q->mutex);
have_data = 1;
}
while(q->n_sent < q->max_send && q->n_queue >= q->s_queue)
pthread_cond_wait(&q->not_full, &q->mutex);
if (q->n_sent < q->max_send && q->n_queue < q->s_queue){
int i = (q->i_queue + q->n_queue) % q->s_queue;
clock_gettime(CLOCK_MONOTONIC, &q->queue[i]);
q->n_queue++;
q->n_sent++;
n_sent++;
have_data = 0;
pthread_cond_signal(&q->not_empty);
if (q->n_sent == q->max_send) {
pthread_cond_broadcast(&q->not_full);
pthread_cond_broadcast(&q->not_empty);
}
}
}
pthread_mutex_unlock(&q->mutex);
printf("sender %d sent %d\\n", args->id, n_sent);
return 0;
}
void *receiver(void *arg)
{
args_t *args = (args_t *)arg;
queue_t *q = args->queue;
int n_got =0;
int have_data = 0;
float time, sum_time=0.0, sum_time2=0.0;
struct timespec data, now;
pthread_mutex_lock(&q->mutex);
while (q->n_sent < q->max_send || q->n_queue) {
if (have_data) {
pthread_mutex_unlock(&q->mutex);
now.tv_sec -= data.tv_sec;
now.tv_nsec -= data.tv_nsec;
if (now.tv_nsec < 0) {
now.tv_sec --;
now.tv_nsec += 1000000000;
}
time = (float)now.tv_sec + (float)now.tv_nsec * 1e-9f;
sum_time += time;
sum_time2 += time * time;
sched_yield();
pthread_mutex_lock(&q->mutex);
have_data = 0;
}
while(q->n_sent < q->max_send && !q->n_queue)
pthread_cond_wait(&q->not_empty, &q->mutex);
if (q->n_queue){
clock_gettime(CLOCK_MONOTONIC, &now);
data = q->queue[q->i_queue];
q->i_queue = (q->i_queue + 1) % q->s_queue;
q->n_queue--;
n_got++;
have_data = 1;
pthread_cond_signal(&q->not_full);
}
}
pthread_mutex_unlock(&q->mutex);
{
float avg=0.0f, sigma=0.0f;
if (n_got) {
avg = sum_time / (float)n_got;
sigma = sqrtf((float)n_got * sum_time - sum_time2) / (float)n_got;
}
printf("receiver %d got %d latency avg %e stdev %e\\n", args->id, n_got, avg, sigma);
}
return 0;
}
int main(int argc, char*argv[])
{
int n_data = 1000;
int n_senders = 1;
int n_receivers = 1;
int s_queue = 10;
queue_t q;
int i;
args_t *senders, *receivers;
void *retval;
if (argc > 1)
n_data = atoi(argv[1]);
if (argc > 2)
n_senders = atoi(argv[2]);
if (argc > 3)
s_queue = atoi(argv[3]);
n_receivers = n_senders;
q.i_queue = q.n_queue = 0;
q.s_queue = s_queue;
q.queue = (struct timespec *)malloc(s_queue * sizeof(struct timespec));
q.n_sent = 0;
q.max_send = n_data;
pthread_mutex_init(&q.mutex, 0);
pthread_cond_init(&q.not_empty, 0);
pthread_cond_init(&q.not_full, 0);
receivers = (args_t*)malloc(n_receivers * sizeof(args_t));
for(i=0; i<n_receivers; i++) {
receivers[i].id = i;
receivers[i].queue = &q;
pthread_create(&receivers[i].pid, 0, &receiver, (void*)&receivers[i]);
}
senders = (args_t*)malloc(n_senders * sizeof(args_t));
for(i=0; i<n_senders; i++) {
senders[i].id = i;
senders[i].queue = &q;
pthread_create(&senders[i].pid, 0, &sender, (void*)&senders[i]);
}
for(i=0; i<n_receivers; i++)
pthread_join(receivers[i].pid, &retval);
for(i=0; i<n_senders; i++)
pthread_join(senders[i].pid, &retval);
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 1
|
#include <pthread.h>
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count = 0;
void * decrement_count(void *arg){
while(1){
pthread_mutex_lock(&count_lock);
printf("decrement_count get count_lock ^-^-%d-^-^\\n", count);
while (count == 0){
printf("decrement_count before cond_wait ^-^-%d-^-^\\n", count);
pthread_cond_wait( &count_nonzero, &count_lock);
printf("decrement_count after cond_wait ^-^-%d-^-^\\n", count);
}
count = count - 1;
pthread_mutex_unlock(&count_lock);
}
return 0;
}
void * increment_count(void *arg){
while(1){
pthread_mutex_lock(&count_lock);
if(count == 0){
printf("increment_count get count_lock ^-^-%d-^-^\\n", count);
printf("increment_count before cond_signal ^-^-%d-^-^\\n", count);
pthread_cond_signal(&count_nonzero);
printf("increment_count after cond_signal ^-^-%d-^-^\\n", count);
count = count + 1;
}
pthread_mutex_unlock(&count_lock);
sleep(1);
}
return 0;
}
int main(void){
pthread_t tid1, tid2;
pthread_mutex_init(&count_lock, 0);
pthread_cond_init(&count_nonzero, 0);
pthread_create(&tid1, 0, decrement_count, 0);
sleep(1);
pthread_create(&tid2, 0, increment_count, 0);
sleep(2);
getchar();
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
struct node *head = 0;
struct node *create_node(int value) {
struct node *newnode = malloc(sizeof(struct node));
newnode->value = value;
newnode->next = 0;
return newnode;
}
void insert(struct list *L, int value){
struct node *newnode = create_node(value);
pthread_mutex_lock( &(L->lock));
struct node *cur = L->head;
if(L->head == 0) {
L->head = newnode;
pthread_mutex_unlock( &(L->lock));
return;
} else if(L->head->value > value) {
newnode->next = L->head;
L->head = newnode;
pthread_mutex_unlock( &(L->lock));
return;
}
while(cur->next != 0 && cur->next->value <= value) {
cur = cur->next;
}
newnode->next = cur->next;
cur->next = newnode;
pthread_mutex_unlock( &(L->lock));
return;
}
int length(struct list *L) {
pthread_mutex_lock( &(L->lock));
struct node *cur = L->head;
int count = 0;
while(cur != 0) {
count++;
cur = cur->next;
}
pthread_mutex_unlock(&(L->lock));
return count;
}
void print_list(struct list *L) {
pthread_mutex_lock( &(L->lock));
struct node *cur = L->head;
while(cur != 0) {
printf("%d -> ", cur->value);
cur = cur->next;
}
printf("\\n");
pthread_mutex_unlock( &(L->lock));
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t thread;
unsigned data;
unsigned acks;
unsigned tests_total, tests_failed;
bool done;
void report(const char* name, bool passed)
{
static const char* status[] = { "FAIL", "PASS" };
printf("%s: %s\\n", status[passed], name);
tests_total += 1;
tests_failed += !passed;
}
void wait_for_ack(unsigned n)
{
pthread_mutex_lock(&mutex);
while (acks != n) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
}
void post_ack()
{
++acks;
pthread_cond_signal(&cond);
}
void* secondary(void *ignore)
{
struct timespec ts;
struct timeval tv;
int r;
printf("starting secondary\\n");
pthread_mutex_lock(&mutex);
r = 0;
while (data != 1 && r == 0) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
report("pthread_cond_wait", r == 0);
post_ack(1);
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec + 1000000;
ts.tv_nsec = 0;
pthread_mutex_lock(&mutex);
r = 0;
while (data != 2 && r == 0) {
r = pthread_cond_timedwait(&cond, &mutex, &ts);
}
pthread_mutex_unlock(&mutex);
report("pthread_cond_timedwait (long)", r == 0);
post_ack(2);
gettimeofday(&tv, 0);
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000 + 1000000;
pthread_mutex_lock(&mutex);
r = 0;
while (data != 666 && r == 0) {
r = pthread_cond_timedwait(&cond, &mutex, &ts);
}
pthread_mutex_unlock(&mutex);
report("pthread_cond_timedwait (short)", r == ETIMEDOUT);
post_ack(3);
done = 1;
pthread_cond_signal(&cond);
return 0;
}
int main(void)
{
printf("starting pthread test\\n");
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&cond, 0);
pthread_create(&thread, 0, secondary, 0);
pthread_mutex_lock(&mutex);
data = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
wait_for_ack(1);
pthread_mutex_lock(&mutex);
data = 2;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
wait_for_ack(2);
wait_for_ack(3);
pthread_mutex_lock(&mutex);
while (!done) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
void* ret;
pthread_join(thread, &ret);
printf("SUMMARY: %u tests / %u failures\\n", tests_total, tests_failed);
return tests_failed == 0 ? 0 : 1;
}
| 0
|
#include <pthread.h>
void initEventQueue(){
pthread_mutex_init(&SlicEvntQueueLenMutex, 0);
pthread_mutex_lock (&SlicEvntQueueLenMutex);
struct SlicEvntQueue *tmp = (struct SlicEvntQueue*)malloc(sizeof(struct SlicEvntQueue));
SlicEvntQueueLen = 0;
HeadSlicEvntQueue = tmp;
EndSlicEvntQueue = HeadSlicEvntQueue;
pthread_mutex_unlock (&SlicEvntQueueLenMutex);
}
void addEvent(enum slic_event evt){
pthread_mutex_lock (&SlicEvntQueueLenMutex);
struct SlicEvntQueue *newElement = (struct SlicEvntQueue*)malloc(sizeof(struct SlicEvntQueue));
SlicEvntQueueLen++;
EndSlicEvntQueue->data = evt;
EndSlicEvntQueue->next = newElement;
EndSlicEvntQueue = newElement;
pthread_mutex_unlock (&SlicEvntQueueLenMutex);
}
enum slic_event getSlicEvent(){
pthread_mutex_lock (&SlicEvntQueueLenMutex);
enum slic_event ret = HeadSlicEvntQueue->data;
struct SlicEvntQueue *tmp = HeadSlicEvntQueue;
SlicEvntQueueLen--;
HeadSlicEvntQueue = HeadSlicEvntQueue->next;
free(tmp);
pthread_mutex_unlock (&SlicEvntQueueLenMutex);
return ret;
}
void *SlicMon(void *threadarg) {
char str[64];
unsigned char IntSt2, IntSt3;
int nfds = 1;
unsigned char dtmf_digit, hookSt;
while (!stop_thread) {
lseek(fdset[0].fd, 0, 0);
read(fdset[0].fd, str, 64);
poll(fdset, nfds, -1);
IntSt2 = readDirectReg (19);
IntSt3 = readDirectReg (20);
if (IntSt2&0x02) {
hookSt=readDirectReg(68);
if (hookSt==0x04)
addEvent(onhook);
else
addEvent(offhook);
};
if (IntSt3&0x01) {
dtmf_digit=readDirectReg(24)&0x0f;
switch(dtmf_digit) {
case 1 : addEvent(dtmf1); break;
case 2 : addEvent(dtmf2); break;
case 3 : addEvent(dtmf3); break;
case 4 : addEvent(dtmf4); break;
case 5 : addEvent(dtmf5); break;
case 6 : addEvent(dtmf6); break;
case 7 : addEvent(dtmf7); break;
case 8 : addEvent(dtmf8); break;
case 9 : addEvent(dtmf9); break;
case 10 : addEvent(dtmf0); break;
case 11 : addEvent(dtmf_star); break;
case 12 : addEvent(dtmf_hash); break;
}
};
clearInterrupts();
}
pthread_exit(0);
return 0;
}
int slic_init(char *spi_device) {
char int_device[] = "/sys/class/gpio/slic_int/value";
char int_edge[] = "/sys/class/gpio/slic_int/edge";
int gpio_fd, rc;
FILE *edgef;
InitSpi(spi_device);
syslog(LOG_DEBUG, "init slic");
version();
syslog(LOG_DEBUG, "starting slic");
slicStart();
enablePCMhighway();
clearInterrupts();
goActive();
syslog(LOG_DEBUG, "setting gpio slic_int");
edgef=fopen(int_edge, "w");
fprintf(edgef, "rising\\n");
fclose(edgef);
gpio_fd=open(int_device, O_RDONLY);
memset((void*)fdset, 0, sizeof(fdset));
fdset[0].fd = gpio_fd;
fdset[0].events = POLLPRI;
syslog(LOG_DEBUG, "setting slic event queue");
initEventQueue();
syslog(LOG_DEBUG, "starting slic monitor thread");
rc = pthread_create(&slic_mon_thr, 0, SlicMon, 0);
if (rc){
syslog(LOG_ERR, "return code from slic pthread_create() is %d\\n", rc);
stop_thread=1;
}
}
void powerDown() {
writeDirectReg(8, 0x02);
writeDirectReg(11, 0x33);
writeDirectReg(64, 0x00);
writeDirectReg(14, 0x10);
}
int slic_close() {
pthread_join(slic_mon_thr, 0);
pthread_mutex_destroy(&SlicEvntQueueLenMutex);
close(fdset[0].fd);
disablePCMhighway();
powerDown();
DestroySpi();
}
| 1
|
#include <pthread.h>
long i, N, paralelism;
long double timetick;
long *vector;
long debug = 0, power;
struct My_threads {
long init;
long fin;
pthread_t thread;
int id;
};
struct My_threads *p_threads;
pthread_mutex_t count_lock;
pthread_cond_t ok_to_proceed;
int count;
} mylib_barrier_t;
mylib_barrier_t *barriers;
void mylib_init_barrier (mylib_barrier_t* b) {
b->count = 0;
pthread_mutex_init(&(b->count_lock), 0);
pthread_cond_init(&(b->ok_to_proceed), 0);
}
void mylib_barrier (mylib_barrier_t *b, int num_threads) {
pthread_mutex_lock(&(b->count_lock));
b->count++;
if (b->count == num_threads) {
b->count = 0;
pthread_cond_broadcast(&(b->ok_to_proceed));
} else {
pthread_cond_wait(&(b->ok_to_proceed),&(b->count_lock));
}
pthread_mutex_unlock(&(b->count_lock));
}
long double dwalltime() {
long double sec;
struct timeval tv;
gettimeofday(&tv,0);
sec = tv.tv_sec + tv.tv_usec/1000000.0;
return sec;
}
void printVector(long* vector) {
for (long i = 0; i < N; i++) {
printf("%ld, ", vector[i]);
}
printf("\\n");
}
void qs(long *vector,long limite_izq,long limite_der)
{
int izq, der, temporal, pivote;
izq = limite_izq;
der = limite_der;
if (der == izq) {
return;
}
pivote = vector[(izq+der)/2];
do {
while(vector[izq] < pivote && izq < limite_der) izq++;
while(pivote < vector[der] && der > limite_izq) der--;
if(izq <= der)
{
temporal = vector[izq];
vector[izq] = vector[der];
vector[der] = temporal;
izq++;
der--;
}
} while(izq <= der);
if(limite_izq < der) qs(vector, limite_izq, der);
if(limite_der > izq) qs(vector, izq, limite_der);
}
void quickSort(long *vector, long inicio, long fin) {
qs(vector, inicio, fin);
}
void merge(long init, long fin) {
long N = (fin - init + 1);
long *vectorTemp = (long*)malloc(sizeof(long)*(N));
long actLeft = init;
long actRight = init + ( N / 2);
for(long i=0;i<N;i++){
if (actLeft == init + ( N / 2)) {
vectorTemp[i] = vector[actRight];
actRight++;
}
else {
if (actRight == fin+1) {
vectorTemp[i] = vector[actLeft];
actLeft++;
} else {
if (vector[actLeft] < vector[actRight]) {
vectorTemp[i] = vector[actLeft];
actLeft++;
} else {
vectorTemp[i] = vector[actRight];
actRight++;
}
}
}
}
for(long i=0;i<N;i++) vector[init+i] = vectorTemp[i];
free (vectorTemp);
}
void *ordenarInicial(void* args) {
int p_id = *((int *)args);
quickSort(vector, p_threads[p_id].init, p_threads[p_id].fin);
int cant = log2(paralelism);
if ((p_id%2) == 0) {
for (int i = 1; i <= cant; i++) {
if (p_id%(2*i) == 0) {
int nextMergeId = (int)(p_id+(pow(2, i-1)));
printf("p_id: %d\\twait thread: %d\\n",p_id,nextMergeId);
mylib_barrier(&barriers[nextMergeId], 2);
p_threads[p_id].fin = p_threads[nextMergeId].fin;
printf("p_id: %d -\\tthread %d: finish\\tfin: %ld\\n",p_id, nextMergeId, p_threads[p_id].fin);
merge(p_threads[p_id].init, p_threads[p_id].fin);
} else {
printf("p_id: %d\\tIm wait\\n",p_id);
mylib_barrier(&barriers[p_id], 2);
}
}
} else {
printf("p_id: %d\\tIm wait\\n",p_id);
mylib_barrier(&barriers[p_id], 2);
}
}
int main(long argc, char*argv[]) {
const char* help ="\\nCompilar:\\n\\tgcc -o tp2-ej2 tp2-ej2.c -lm -std=c99 -pthread\\nArgumentos:\\n\\t<E> = 2^E elementos del vector.\\n\\t<P> = Paralelismo a utilizar.\\n\\t<S> = Cantidad de muestras a ejecutar.";
if (argc < 4) {
printf("%s\\n", help);
return -1;
}
if (argc > 4) {
debug = atoi(argv[4]);
}
power = atoi(argv[1]);
N = pow(2, power);
paralelism = atoi(argv[2]);
p_threads = malloc(sizeof(struct My_threads) * paralelism);
barriers = malloc(sizeof(mylib_barrier_t) * (paralelism));
pthread_attr_t attr;
pthread_attr_init (&attr);
printf("CANTIDAD DE THREADS: %ld.\\n", paralelism);
printf("N: %ld.\\n", N);
vector=(long*)malloc(sizeof(long)*N);
for(i=0;i<N;i++){
vector[i] = N - i;
}
if (debug) {
printVector(vector);
}
timetick = dwalltime();
long cantThreads = paralelism;
for(i = 0; i < paralelism; i++){
mylib_init_barrier(&barriers[i]);
p_threads[i].id = i;
p_threads[i].init = N/paralelism * i;
p_threads[i].fin = (N/paralelism * (i+1))-1;
}
for(i=0; i < paralelism; i++) {
pthread_create(&p_threads[i].thread, 0, ordenarInicial, &p_threads[i].id);
}
pthread_join(p_threads[0].thread, 0);
long double tiempo = dwalltime() - timetick;
for(i=1; i < paralelism; i++) {
pthread_join(p_threads[i].thread, 0);
}
printf("Tiempo en segundos %LF \\n", tiempo);
if (debug) {
printVector(vector);
}
}
| 0
|
#include <pthread.h>
pthread_cond_t cond;
pthread_mutex_t mutex;
void* p_func(void* p)
{
pthread_mutex_lock(&mutex);
int ret;
int i=( int)p;
printf(" i am child %d,this is wait entrance\\n",i );
ret=pthread_cond_wait(&cond,&mutex);
if(0!=ret)
{
printf("pthread_cond_wait ret is %d\\n" ,ret);
}
printf(" i am child thread %d,i am wake\\n",i);
pthread_mutex_unlock(&mutex);
pthread_exit( 0);
}
int main( )
{
int ret;
ret=pthread_cond_init(&cond,0);
if( 0!=ret)
{
printf("pthread_cond_init ret is %d\\n" ,ret);
return -1;
}
ret=pthread_mutex_init(&mutex,0);
if( 0!=ret)
{
printf("pthread_mutex_init ret is %d\\n" ,ret);
return -1;
}
pthread_t thid[2];
int i;
for(i=0;i<2;i++)
{
pthread_create( &thid[i],0,p_func,( void*)i);
}
sleep( 1);
pthread_cond_broadcast(&cond);
for(i=0;i<2;i++)
{
ret=pthread_join(thid[i],0);
if( 0!=ret)
{
printf("pthread_join ret is %d\\n" ,ret);
return -1;
}
}
ret=pthread_cond_destroy(&cond);
if( 0!=ret)
{
printf("pthread_cond_destroy ret is %d\\n" ,ret);
return -1;
}
ret=pthread_mutex_destroy(&mutex);
if( 0!=ret)
{
printf("pthread_mutex_destroy ret is %d\\n" ,ret);
return -1;
}
return 0;
}
| 1
|
#include <pthread.h>
int a[8];
int b[8];
int c[4];
pthread_t mc[4];
pthread_t display;
pthread_mutex_t mc_lock[4] =
{
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER,
PTHREAD_MUTEX_INITIALIZER
};
void *thr_mc(void *arg)
{
printf("MC%d: tid %u\\n", (int)arg, (unsigned int)pthread_self());
c[(int)arg] = 0;
int i;
for (i = 0; i < 4; i++)
{
c[(int)arg] += a[i + 4 * ((int)arg / 2)] * b[i * 2 + (int)arg % 2];
}
printf("MC%d: exiting\\n", (int)arg);
pthread_mutex_unlock(&mc_lock[(int)arg]);
return 0;
}
void *thr_display(void *arg)
{
int i;
printf("Display: tid - %u\\n", (unsigned int)pthread_self());
for (i = 0; i < 4; i++)
{
pthread_mutex_lock(&mc_lock[i]);
}
printf("\\nThe first row of the resulting matrix is: %d\\t%d\\n", c[0], c[1]);
printf("\\nThe second row of the resulting matrix is: %d\\t%d\\n\\n", c[2], c[3]);
for (i = 0; i < 4; i++)
{
pthread_mutex_unlock(&mc_lock[i]);
}
printf("Exiting\\n");
return 0;
}
int main (int argc, char *argv[])
{
int booleanprint = 0;
int i;
int j;
for (i = 1; i < argc; i++)
{
j = 0;
if (argv[i][j] == '+')
{
j++;
}
else if (argv[i][j] == '-')
{
j++;
}
for (; argv[i][j] != 0; j++)
{
if (!isdigit(argv[i][j]))
{
booleanprint = 1;
}
}
}
if (argc != 17)
{
booleanprint = 2;
}
if (booleanprint != 0)
{
if (booleanprint == 1)
{
printf("Incorrect type of input.\\n");
}
else if (booleanprint == 2)
{
printf("Incorrect number of input.\\n");
}
exit(0);
}
for (i = 0; i < 8; i++)
{
a[i] = atoi(argv[i + 1]);
b[i] = atoi(argv[i + 9]);
}
for (i = 0; i < 4; i++)
{
printf("Thread Created MC%d\\n", i);
pthread_create(&mc[i], 0, thr_mc, (void *) i);
}
sleep(1);
printf("Display created by thread\\n");
pthread_create(&display, 0, thr_display, (void *) 0);
printf("Waiting for threads\\n");
for (i = 0; i < 4; i++)
{
pthread_join(mc[i], 0);
printf("Waited for MC%d\\n", i);
}
pthread_join(display, 0);
printf("Waiting for Display\\n");
printf("Finished\\n");
exit(0);
}
| 0
|
#include <pthread.h>
long int c1,c2,c3,c4;
pthread_mutex_t m1,m2,m3,m4;
void * th1(void * p)
{
long int i,j,n;
pthread_mutex_lock(&m1);
for(n=3;n<=4000000;n+=2)
{
j=sqrt(n);
for(i=2;i<=j+1;i++)
if(n%i==0)
break;
if(i>=j)
{
c1++;
printf("%ld\\n",n);
}
}
pthread_mutex_unlock(&m1);
pthread_exit(0);
}
void * th2(void * p)
{
long int i,j,n;
pthread_mutex_lock(&m2);
for(n=4000001;n<=8000000;n+=2)
{
j=sqrt(n);
for(i=2;i<=j+1;i++)
if(n%i==0)
break;
if(i>=j)
{
c2++;
printf("\\t%ld\\n",n);
}
}
pthread_mutex_unlock(&m2);
pthread_exit(0);
}
void * th3(void * p)
{
long int i,n,j;
pthread_mutex_lock(&m3);
for(n=8000001;n<=12000000;n+=2)
{
j=sqrt(n);
for(i=2;i<=j+1;i++)
if(n%i==0)
break;
if(i>=j)
{
c3++;
printf("\\t\\t%ld\\n",n);
}
}
pthread_mutex_unlock(&m3);
pthread_exit(0);
}
void * th4(void * p)
{
long int i,j,n;
pthread_mutex_lock(&m4);
for(n=12000001;n<=16000000;n+=2)
{
j=sqrt(n);
for(i=2;i<=j+1;i++)
if(n%i==0)
break;
if(i>=j)
{
c4++;
printf("\\t\\t\\t%ld\\n",n);
}
}
pthread_mutex_unlock(&m4);
pthread_exit(0);
}
void * th5(void *p)
{
clock_t start, end;
double cpu_time_used;
start = clock();
pthread_mutex_lock(&m1);
pthread_mutex_lock(&m2);
pthread_mutex_lock(&m3);
pthread_mutex_lock(&m4);
end = clock();
cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
printf("total time=%lfsec\\n",cpu_time_used);
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
pthread_mutex_unlock(&m3);
pthread_mutex_unlock(&m4);
pthread_exit(0);
}
void thread_init(void)
{
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_mutex_init(&m3,0);
pthread_mutex_init(&m4,0);
}
void thread_dest(void)
{
pthread_mutex_destroy(&m1);
pthread_mutex_destroy(&m2);
pthread_mutex_destroy(&m3);
pthread_mutex_destroy(&m4);
}
main()
{
pthread_t t1,t2,t3,t4,t5;
thread_init();
pthread_create(&t1,0,th1,0);
pthread_create(&t2,0,th2,0);
pthread_create(&t3,0,th3,0);
pthread_create(&t4,0,th4,0);
pthread_create(&t5,0,th5,0);
pthread_join(t1,0);
pthread_join(t2,0);
pthread_join(t3,0);
pthread_join(t4,0);
pthread_join(t5,0);
thread_dest();
printf("total no to primes=%ld\\n",c1+c2+c3+c4);
}
| 1
|
#include <pthread.h>
void
diskfs_nrele (struct node *np)
{
int locked = FALSE;
struct references result;
refcounts_demote (&np->refcounts, &result);
if (result.hard == 0)
{
locked = TRUE;
pthread_mutex_lock (&np->lock);
diskfs_lost_hardrefs (np);
if (!np->dn_stat.st_nlink)
{
diskfs_try_dropping_softrefs (np);
}
}
refcounts_deref_weak (&np->refcounts, &result);
if (result.hard == 0 && result.weak == 0)
{
if (! locked)
pthread_mutex_lock (&np->lock);
diskfs_drop_node (np);
}
else if (locked)
pthread_mutex_unlock (&np->lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER, cond_baby = PTHREAD_COND_INITIALIZER;
int finish = 0;
int foodbits = 0;
struct checkerarg {
int f;
long r;
int *working;
int *eating;
pthread_mutex_t *mut;
};
struct parentarg {
int f;
long r;
int *working;
};
struct babyarg {
int id;
int *eating;
};
void *checker(void *);
void *parent(void *);
void *baby(void *);
int main(int argc, char *argv[]) {
setbuf(stdout, 0);
int B;
int F;
long R;
int working = 0;
int eating = 0;
struct parentarg pa;
struct checkerarg ca;
struct babyarg ba[100];
pthread_t tchecker, tparent, tbaby[100];
if( argc != 4) {
printf("Program invoked with wrong number of arguments.\\n");
printf("Program usage: %s <n. babybirds> <n. food portions> <n. refills>\\n", argv[0]);
exit(-1);
}
else {
B = atoi(argv[1]);
F = atoi(argv[2]);
R = atoi(argv[3]);
}
printf("\\nSimulation started\\n");
int i=0;
ca.f = F;
ca.r = R;
ca.working = &working;
ca.eating = &eating;
ca.mut = 0;
pthread_create(&tchecker,0,checker,&ca);
pa.f = F;
pa.r = R;
pa.working= &working;
pthread_create(&tparent,0,parent,&pa);
for(i=0;i<B;i++){
ba[i].id = i;
ba[i].eating = &eating;
pthread_create(&tbaby[i],0,baby,&ba[i]);
}
pthread_join(tparent,0);
long *pbits_eaten = (long*) malloc(sizeof(long)*B);
for(i=0;i<B;i++){
pthread_join(tbaby[i],(void **)(pbits_eaten+i));
printf ("\\nNumber of bits of food eaten by baby %d / total of bits: %ld / %ld ",ba[i].id , pbits_eaten[i], F*R );
}
printf("\\nSimulation finished\\n");
exit (0);
}
void *parent(void *arg) {
struct parentarg *pa;
printf ("\\n\\tParent starting");
pa= (struct parentarg*) arg;
long int resupply=0;
printf ("\\n\\tParent received args f (%d), r (%ld), working (%d)", pa->f, pa->r, *(pa->working));
while(resupply != pa->r){
pthread_mutex_lock(&lock);
while(foodbits > 0)
pthread_cond_wait(&cond,&lock);
*(pa->working) = 1;
foodbits = pa->f;
resupply++;
*(pa->working) = 0;
pthread_mutex_unlock(&lock);
}
finish=1;
printf ("\\n\\tParent finishing");
return 0;
}
void *baby(void *arg){
struct babyarg *ba;
ba = (struct babyarg *)arg;
long int comidos = 0;
printf("\\n Baby bird %d beginning",ba->id);
printf("\\n Baby received args id (%d), eating (%d)", ba->id , *(ba->eating) );
while(!finish || foodbits > 0 ){
if(((*(ba->eating)) == 0)){
if(foodbits == 0)
pthread_cond_signal(&cond);
else{
*(ba->eating)++;
pthread_mutex_lock(&lock);
foodbits--;
(comidos)++;
pthread_mutex_unlock(&lock);
*(ba->eating)--;
}
}
}
printf("\\n Baby bird %d finishing", ba->id );
return (void*)comidos;
}
| 1
|
#include <pthread.h>
int mediafirefs_setxattr(const char *path, const char *name,
const char *value, size_t size, int flags)
{
printf("FUNCTION: setxattr. path: %s\\n", path);
(void)path;
(void)name;
(void)value;
(void)size;
(void)flags;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
fprintf(stderr, "setxattr not implemented\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOSYS;
}
| 0
|
#include <pthread.h>
struct list_node **head_p;
struct argument_list arguments;
pthread_mutex_t lock;
struct list_node
{
int data;
struct list_node* next;
};
struct argument_list {
int m;
float mOps[3];
struct list_node** head_p;
int threads;
};
int member(int value, struct list_node* head_p);
int insert(int value, struct list_node** head_pp);
int delete(int value, struct list_node** head_pp);
void *callOperations(void *arguments);
int insed = 0;
int main(){
while(1){
int n,m,samples,i,threads,thread_count;
float mOperations[3];
clock_t begin, end;
pthread_t* thread_handles;
printf("Enter the number of samples ");
scanf("%d",&samples);
printf("Enter the initial size of linked list (n) ");
scanf("%d",&n);
printf("Enter the number of operations (m) ");
scanf("%d",&m);
printf("Fraction of Member operations ");
scanf("%f",&mOperations[0]);
printf("Fraction of Insert operations ");
scanf("%f",&mOperations[1]);
printf("Fraction of Delete operations ");
scanf("%f",&mOperations[2]);
printf("Enter the number of threads ");
scanf("%d",&threads);
double time_list[samples];
double time_spent, total_time = 0,mean;
srand(time(0));
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
for(i=0; i< samples;i++){
head_p = 0;
head_p = malloc( sizeof(struct list_node));
populate_linked_list(n,head_p);
setArguments(m,mOperations,head_p,threads);
thread_handles = malloc(threads*sizeof(pthread_t));
begin = clock();
for(thread_count=0; thread_count < threads; thread_count++){
pthread_create(&thread_handles[thread_count], 0, callOperations, (void*) &arguments);
}
for(thread_count=0; thread_count < threads; thread_count++){
pthread_join(thread_handles[thread_count], 0);
}
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
time_list[i] = time_spent;
total_time += time_spent;
free(thread_handles);
free(head_p);
}
mean = total_time / samples;
calculateSTD(time_list, samples, mean);
pthread_mutex_destroy(&lock);
}
}
int setArguments(int m, float mOps[3], struct list_node** head_p, int threads){
int count;
(arguments).m = m;
(arguments).head_p = head_p;
(arguments).threads = threads;
for(count=0; count < 3; count++){
(arguments).mOps[count] = mOps[count];
}
return 0;
}
void *callOperations(void *arguments)
{
struct argument_list *args = arguments;
int m = args -> m,i;
float mOps[3];
struct list_node** head_p = args -> head_p;
int threads = args -> threads;
for(i=0; i<3;i++){
mOps[i] = args -> mOps[i];
}
opearations(m,mOps,head_p,threads);
}
int calculateSTD(double time_list[], int samples, double mean){
int i;
float std=0;
float temp=0.0;
float min_samples;
for(i=0; i<samples; i++){
time_list[i] -= mean;
temp = time_list[i]*time_list[i];
std += temp;
}
std = std/samples;
std = sqrt(std);
min_samples = pow((100*1.96*std)/(5*mean),2);
printf("Average time spent = %f\\n",mean);
printf("Standard Deviation = %f\\n",(std));
return 0;
}
int opearations(int m, float mOps[3], struct list_node** head_p, int threads){
int ops[3];
int i,num,success;
for(i=0; i<3; i++){
ops[i] = m*mOps[i]/threads;
}
while(ops[0]!= 0|| ops[1] != 0 || ops[2] != 0){
if(ops[0] != 0){
num = rand() % 65535;
pthread_mutex_lock(&lock);
member(num, *head_p);
pthread_mutex_unlock(&lock);
ops[0]--;
}
if(ops[1] != 0){
num = rand() % 65535;
pthread_mutex_lock(&lock);
insert(num, head_p);
pthread_mutex_unlock(&lock);
ops[1]--;
}
if(ops[2] != 0){
num = rand() % 65535;
pthread_mutex_lock(&lock);
delete(num, head_p);
pthread_mutex_unlock(&lock);
ops[2]--;
}
}
}
int populate_linked_list(int n, struct list_node** head_p)
{
int num,i=0;
int inserted;
*head_p = 0;
*head_p = malloc( sizeof(struct list_node));
for(i=0; i<n; ){
num = rand() % 65535;
if(i==0){
(*head_p)->data = num;
i++;
}else
inserted = insert(num, head_p);
if(inserted == 1){
i++;
}
}
}
int getLinkedList(struct list_node* head_p)
{
struct list_node* curr_p = head_p;
int count =0,i=0;
while(curr_p != 0){
curr_p = curr_p->next;
count++;
}
return count;
}
int member(int value, struct list_node* head_p)
{
struct list_node* curr_p = head_p;
while(curr_p != 0 && curr_p->data < value )
curr_p = curr_p->next;
if (curr_p == 0 || curr_p->data > value)
return 0;
else
return 1;
}
int insert(int value, struct list_node** head_pp)
{
struct list_node* curr_p = *head_pp;
struct list_node* pred_p = 0;
struct list_node* temp_p ;
while(curr_p != 0 && curr_p->data < value)
{
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p ==0 || curr_p->data > value)
{
temp_p = malloc(sizeof(struct list_node));
temp_p->data = value;
temp_p->next = curr_p;
if(pred_p == 0)
*head_pp = temp_p;
else
pred_p->next = temp_p;
return 1;
}else{
return 0;
}
}
int delete(int value, struct list_node** head_pp)
{
struct list_node* curr_p = *head_pp;
struct list_node* pred_p = 0;
while(curr_p != 0 && curr_p->data < value){
pred_p = curr_p;
curr_p = curr_p->next;
}
if(curr_p != 0 && curr_p->data == value)
{
if(pred_p == 0)
{
*head_pp = curr_p->next;
free(curr_p);
}else{
pred_p->next = curr_p->next;
free(curr_p);
}
return 1;
}else{
return 0;
}
}
| 1
|
#include <pthread.h>
void
ports_enable_bucket (struct port_bucket *bucket)
{
pthread_mutex_lock (&_ports_lock);
bucket->flags &= ~PORT_BUCKET_NO_ALLOC;
if (bucket->flags & PORT_BUCKET_ALLOC_WAIT)
{
bucket->flags &= ~PORT_BUCKET_ALLOC_WAIT;
pthread_cond_broadcast (&_ports_block);
}
pthread_mutex_unlock (&_ports_lock);
}
| 0
|
#include <pthread.h>
struct wonk{
int a;
} *shrdPtr, *symb_shrdPtr;
pthread_mutex_t lock;
struct wonk *getNewVal(struct wonk**old){
*old = 0;
struct wonk *newval = (struct wonk*)malloc(sizeof(struct wonk));
newval->a = 1;
return newval;
}
void *updaterThread(void *arg){
int i;
for(i = 0; i < 10; i++){
pthread_mutex_lock(&lock);
struct wonk *newval = getNewVal(&symb_shrdPtr);
pthread_mutex_unlock(&lock);
usleep(20);
pthread_mutex_lock(&lock);
shrdPtr = newval; symb_shrdPtr = newval;
pthread_mutex_unlock(&lock);
}
}
void swizzle(int *result){
pthread_mutex_lock(&lock);
if(symb_shrdPtr != 0)
{
pthread_mutex_unlock(&lock);
pthread_mutex_lock(&lock);
assert(symb_shrdPtr!=0);
*result += shrdPtr->a;
pthread_mutex_unlock(&lock);
}else{
pthread_mutex_unlock(&lock);
}
}
void *accessorThread(void *arg){
int *result = (int*)malloc(sizeof(int)); klee_make_symbolic(result, sizeof(int), "result");
*result = 0;
while(*result < 1000){
swizzle(result);
usleep(10 + (rand() % 100) );
}
pthread_exit(result);
}
int main(int argc, char *argv[]){
int res = 0;
shrdPtr = (struct wonk*)malloc(sizeof(struct wonk)); symb_shrdPtr = shrdPtr; klee_make_symbolic(shrdPtr, sizeof(struct wonk), "shrdPtr->a"); klee_make_symbolic(&symb_shrdPtr, sizeof(symb_shrdPtr), "shrdPtr");
shrdPtr->a = 1;
pthread_mutex_init(&lock,0);
pthread_t acc[4],upd;
pthread_create(&acc[0],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[1],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[2],0,accessorThread,(void*)shrdPtr);
pthread_create(&acc[3],0,accessorThread,(void*)shrdPtr);
pthread_create(&upd,0,updaterThread,(void*)shrdPtr);
pthread_join(upd,0);
pthread_join(acc[0],(void**)&res);
pthread_join(acc[1],(void**)&res);
pthread_join(acc[2],(void**)&res);
pthread_join(acc[3],(void**)&res);
fprintf(stderr,"Final value of res was %d\\n",res);
}
| 1
|
#include <pthread.h>
int sock;
struct sockaddr_in servAddr;
int port;
char *ipAddr;
char parametersList[1024];
uint32_t key[4] = { 31231234, 412334, 12341, 657657 };
pthread_mutex_t lock;
char *event = 0;
suseconds_t lastUpdate = 0;
struct per_session_data__event {
suseconds_t timeOfLastEventSent;
};
void createUDPSocket() {
sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
bzero(&servAddr, sizeof(servAddr));
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = inet_addr(ipAddr);
servAddr.sin_port = htons(port);
}
void *_threadSubscribe(void *arg) {
char eventMsg[512];
char buffer[1024];
int blocks;
while (1) {
sprintf(eventMsg,
"{ \\"type\\": \\"subscribe\\", \\"condition\\": \\"True\\", \\"which\\": \\"last\\", \\"attributes\\": "
"[ %s ] }", parametersList);
blocks = encipherEvent(eventMsg, buffer);
sendto(sock, buffer, blocks * 8, 0, (const struct sockaddr*) &servAddr,
sizeof(servAddr));
sleep(3600 * 2 + 10);
}
return 0;
}
void *_threadMessage(void *arg) {
char buffer[1024], bufferInput[1024];
int blocks;
struct sockaddr_in cliAddr;
int len, lenString, lenBuffer;
struct timeval timeValue;
len = sizeof(cliAddr);
while (1) {
lenString = recvfrom(sock, buffer, sizeof buffer, 0,
(struct sockaddr*) &cliAddr, &len);
if (lenString <= 0) {
sleep(1);
continue;
}
lenBuffer = decipherEvent(buffer, bufferInput, sizeof(bufferInput));
bufferInput[lenBuffer] = 0;
pthread_mutex_lock(&lock);
if (event != 0) {
free(event);
}
event = strdup(bufferInput);
gettimeofday(&timeValue, 0);
lastUpdate = timeValue.tv_usec;
pthread_mutex_unlock(&lock);
}
return 0;
}
static int callback_http(struct libwebsocket_context * this,
struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len) {
return 0;
}
static int callback_event(struct libwebsocket_context * this,
struct libwebsocket *wsi, enum libwebsocket_callback_reasons reason,
void *user, void *in, size_t len) {
unsigned char buf[LWS_SEND_BUFFER_PRE_PADDING
+ 512 +
LWS_SEND_BUFFER_POST_PADDING];
unsigned char *p;
struct per_session_data__event *userSession;
p = &buf[LWS_SEND_BUFFER_PRE_PADDING];
userSession = (struct per_session_data__event *) user;
switch (reason) {
case LWS_CALLBACK_ESTABLISHED:
libwebsocket_callback_on_writable(this, wsi);
userSession->timeOfLastEventSent = 0;
break;
case LWS_CALLBACK_SERVER_WRITEABLE: {
int n;
pthread_mutex_lock(&lock);
if (event != 0 && userSession->timeOfLastEventSent < lastUpdate) {
userSession->timeOfLastEventSent = lastUpdate;
n = sprintf((char*) p, "%s", event);
libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
libwebsocket_callback_on_writable(this, wsi);
}
pthread_mutex_unlock(&lock);
break;
}
}
return 0;
}
static struct libwebsocket_protocols protocols[] = {
{ "http-only",
callback_http,
0,
0
},
{
"event-protocol",
callback_event,
sizeof(struct per_session_data__event),
0
},
{
0, 0, 0, 0
}
};
int main(int argc, char **argv) {
struct libwebsocket_context *context;
struct lws_context_creation_info info;
pthread_t threadMessage;
pthread_t threadSubscribe;
char bufferParam[512];
int portWS, i;
unsigned int oldus;
int poll_ret;
ipAddr = strdup(argv[1]);
port = atoi(argv[2]);
portWS = atoi(argv[3]);
strcpy(parametersList, "");
for (i = 4; i < argc; i++) {
if (i == (argc - 1)) {
sprintf(bufferParam, "\\"%s\\"", argv[i]);
} else {
sprintf(bufferParam, "\\"%s\\", ", argv[i]);
}
strcat(parametersList, bufferParam);
}
info.port = portWS;
info.extensions = 0;
info.iface = 0;
info.protocols = protocols;
info.ssl_ca_filepath = 0;
info.ssl_private_key_filepath = 0;
info.ssl_cert_filepath = 0;
info.gid = -1;
info.uid = -1;
info.options = 0;
info.user = 0;
info.ka_interval = info.ka_probes = info.ka_time = 0;
pthread_mutex_init(&lock, 0);
event = 0;
createUDPSocket();
pthread_create(&threadMessage, 0, _threadMessage, 0);
pthread_create(&threadSubscribe, 0, _threadSubscribe, 0);
context = libwebsocket_create_context(&info);
if (context == 0) {
fprintf(stderr, "libwebsocket init failed\\n");
return -1;
}
oldus = 0;
while (1) {
struct timeval tv;
gettimeofday(&tv, 0);
if (oldus == 0) {
oldus = tv.tv_sec;
}
if (((unsigned int) tv.tv_sec - oldus) > 5) {
oldus = tv.tv_sec;
libwebsocket_callback_on_writable_all_protocol(&protocols[1]);
}
poll_ret = libwebsocket_service(context, 50);
if (poll_ret < 0)
{
fprintf(stderr, "Poll error! %d, %s\\n", errno, strerror(errno));
break;
}
}
libwebsocket_context_destroy(context);
return 0;
}
| 0
|
#include <pthread.h>
struct thread_data{
char *str1;
char *str2;
};
int total = 0;
int n1,n2;
char *s1,*s2;
FILE *fp;
pthread_mutex_t mutexsum;
volatile int running_threads = 0;
int readf(FILE *fp)
{
if((fp=fopen("strings.txt", "r"))==0){
printf("ERROR: can't open message.txt!\\n");
return 0;
}
s1=(char *)malloc(sizeof(char)*1024);
if(s1==0){
printf("ERROR: Out of memory!\\n");
return -1;
}
s2=(char *)malloc(sizeof(char)*1024);
if(s1==0){
printf("ERROR: Out of memory\\n");
return -1;
}
s1=fgets(s1, 1024, fp);
s2=fgets(s2, 1024, fp);
n1=strlen(s1);
n2=strlen(s2)-1;
if(s1==0 || s2==0 || n1<n2)
return -1;
}
void *thread_substring(void *arg)
{
int i,j,k,count,c1,c2;
struct thread_data *thread_data;
thread_data = (struct thread_data *)arg;
c1 = (strlen(thread_data->str1));
c2 = (strlen(thread_data->str2))-1;
char *st1, *st2;
st1 = thread_data->str1;
st2 = thread_data->str2;
for (i = 0; i <= (c1-c2); i++){
count=0;
for(j = i,k = 0; k < c2; j++,k++){
if (*(st1+j)!=*(st2+k)){
break;
}
else
count++;
if(count==c2){
pthread_mutex_lock (&mutexsum);
total++;
pthread_mutex_unlock (&mutexsum);
}
}
}
pthread_mutex_lock (&mutexsum);
running_threads--;
pthread_mutex_unlock (&mutexsum);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t threads[4];
readf(fp);
int rc,i;
int charcurrent = 0;
int charoffset = n1/4 +1;
struct thread_data thread_data_array[4];
pthread_mutex_init(&mutexsum, 0);
for(i=0; i<4 +1; i++){
char *str;
str=strndup(s1+charcurrent, charoffset);
thread_data_array[i].str1 = str;
thread_data_array[i].str2 = s2;
pthread_mutex_lock (&mutexsum);
running_threads++;
pthread_mutex_unlock (&mutexsum);
rc = pthread_create(&threads[i], 0, thread_substring, (void *) &thread_data_array[i]);
if (rc){
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
charcurrent += (charoffset-1);
}
while (running_threads > 0) {
sleep(1);
}
printf("The number of substrings is: %d\\n", total);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
double integral = 0.0;
pthread_mutex_t soma;
{
double a;
double b;
int N;
} Targumentos;
double AreaTrapezio(double dx, double h1, double h2)
{
return (dx*(h1+h2)/2);
}
double f(double x)
{
return (4*sqrt(1-x*x));
}
void ThreadCalculaArea(Targumentos *argumentos)
{
int i;
double area, dx, x1, x2, f1, f2;
Targumentos arg;
arg = *argumentos;
double a=arg.a; double b=arg.b; int N=arg.N;
printf("a=%10.2lf\\tb=%10.2lf\\tN=%d\\n", a, b, N);
dx = (b-a)/N;
area = 0.0;
for (i=0; i<N; i++)
{
x1 = a + dx * i;
x2 = a + dx * (i+1);
f1 = f(x1);
f2 = f(x2);
area += AreaTrapezio(dx, f1, f2);
}
pthread_mutex_lock(&soma);
integral += area;
pthread_mutex_unlock(&soma);
}
int main(int argc, char **argv)
{
double a, b, dx;
int N, n_proc = get_nprocs(), i;
Targumentos args[n_proc];
if (argc<4)
{
printf("Numero de argumentos insuficiente...\\n");
exit(-1);
}
a = (double) atof(argv[1]);
b = (double) atof(argv[2]);
N = atoi(argv[3]);
dx = (a+b)/n_proc;
args[0].a = a;
args[0].b = dx;
args[0].N = N/n_proc;
for(i=1; i < n_proc; i++){
args[i].a = args[i-1].b;
args[i].b = args[i-1].b + dx;
args[i].N = N/n_proc;
}
for(i=0; i < n_proc; i++){
pthread_create(&threads[i], 0, (void*)ThreadCalculaArea, &args[i]);
}
for(i=0; i<n_proc; i++){
pthread_join(threads[i], 0);
}
printf("Area= %.15lf\\n", integral);
return 0;
}
| 0
|
#include <pthread.h>
size_t size;
size_t align;
union {
uintptr_t index;
void* address;
} object;
void* value;
} __emutls_control;
static inline void* emutls_memalign_alloc(size_t align, size_t size) {
void *base;
char* object;
if ((object = malloc((align - 1 + sizeof(void*)) + size)) == 0)
abort();
base = (void*)(((uintptr_t)(object + (align - 1 + sizeof(void*))))
& ~(uintptr_t)(align - 1));
((void**)base)[-1] = object;
return base;
}
static inline void emutls_memalign_free(void* base) {
free(((void**)base)[-1]);
}
static inline void* emutls_allocate_object(__emutls_control* control) {
COMPILE_TIME_ASSERT(sizeof(size_t) == sizeof(gcc_word));
COMPILE_TIME_ASSERT(sizeof(uintptr_t) == sizeof(gcc_pointer));
COMPILE_TIME_ASSERT(sizeof(uintptr_t) == sizeof(void*));
size_t size = control->size;
size_t align = control->align;
if (align < sizeof(void*))
align = sizeof(void*);
if ((align & (align - 1)) != 0)
abort();
void* base = emutls_memalign_alloc(align, size);
if (control->value)
memcpy(base, control->value, size);
else
memset(base, 0, size);
return base;
}
static pthread_mutex_t emutls_mutex = PTHREAD_MUTEX_INITIALIZER;
static size_t emutls_num_object = 0;
uintptr_t size;
void* data[];
} emutls_address_array;
static pthread_key_t emutls_pthread_key;
static void emutls_key_destructor(void* ptr) {
emutls_address_array* array = (emutls_address_array*)ptr;
uintptr_t i;
for (i = 0; i < array->size; ++i) {
if (array->data[i])
emutls_memalign_free(array->data[i]);
}
free(ptr);
}
static void emutls_init(void) {
if (pthread_key_create(&emutls_pthread_key, emutls_key_destructor) != 0)
abort();
}
static inline uintptr_t emutls_get_index(__emutls_control* control) {
uintptr_t index = __atomic_load_n(&control->object.index, 2);
if (!index) {
static pthread_once_t once = PTHREAD_ONCE_INIT;
pthread_once(&once, emutls_init);
pthread_mutex_lock(&emutls_mutex);
index = control->object.index;
if (!index) {
index = ++emutls_num_object;
__atomic_store_n(&control->object.index, index, 3);
}
pthread_mutex_unlock(&emutls_mutex);
}
return index;
}
static inline void emutls_check_array_set_size(emutls_address_array* array,
uintptr_t size) {
if (array == 0)
abort();
array->size = size;
pthread_setspecific(emutls_pthread_key, (void*)array);
}
static inline uintptr_t emutls_new_data_array_size(uintptr_t index) {
return ((index + 1 + 15) & ~((uintptr_t)15)) - 1;
}
static inline emutls_address_array* emutls_get_address_array(uintptr_t index) {
emutls_address_array* array = pthread_getspecific(emutls_pthread_key);
if (array == 0) {
uintptr_t new_size = emutls_new_data_array_size(index);
array = calloc(new_size + 1, sizeof(void*));
emutls_check_array_set_size(array, new_size);
} else if (index > array->size) {
uintptr_t orig_size = array->size;
uintptr_t new_size = emutls_new_data_array_size(index);
array = realloc(array, (new_size + 1) * sizeof(void*));
if (array)
memset(array->data + orig_size, 0,
(new_size - orig_size) * sizeof(void*));
emutls_check_array_set_size(array, new_size);
}
return array;
}
void* __emutls_get_address(__emutls_control* control) {
uintptr_t index = emutls_get_index(control);
emutls_address_array* array = emutls_get_address_array(index);
if (array->data[index - 1] == 0)
array->data[index - 1] = emutls_allocate_object(control);
return array->data[index - 1];
}
| 1
|
#include <pthread.h>
static void alarm_handler(int signo);
static void *logger_start(void *arg);
static struct {
int curr;
char log[MAX_LOG_ENTRY][MAX_STRING_LENGTH];
pthread_mutex_t mutex;
} buff;
void init_buffer()
{
printf("RING BUFFER: Initializing the ring buffer\\n");
int i, id;
pthread_t tid;
id = pthread_create(&tid, 0, logger_start,(void *)0);
if(id != 0){
printf("Did not create thread with id: %x\\n", (unsigned int)tid);
}
else{
printf("RING BUFFER: Successfully started the backup thread %x\\n", (unsigned int)tid);
}
for(i = 0; i < MAX_LOG_ENTRY; i++) {
buff.log[i][0]='\\0';
}
buff.curr = 0;
signal(SIGALRM, alarm_handler);
alarm(alarm_interval);
}
static char *getTimeString()
{
time_t myTime;
myTime = time(0);
char *timeString = ctime(&myTime);
timeString[strlen(timeString)-1] = '\\0';
return timeString;
}
void log_msg(char *entry)
{
if (entry == 0) {
printf("Skipping null log entry!\\n");
return;
}
pthread_mutex_lock(&(buff.mutex));
char *timeString = getTimeString();
int idx = buff.curr % MAX_LOG_ENTRY;
snprintf(buff.log[idx], MAX_STRING_LENGTH, "%s -- %s", timeString, entry);
buff.curr++;
pthread_mutex_unlock(&(buff.mutex));
if(0 == 1){
buff.curr = 32767;
if(entry == 0){
printf("Skipping the NULL log entry!\\n");
return;
}
pthread_mutex_lock(&(buff.mutex));
char *timeString = getTimeString();
int idx = buff.curr % MAX_LOG_ENTRY;
snprintf(buff.log[idx], MAX_STRING_LENGTH, "%s -- %s", timeString, entry);
buff.curr++;
pthread_mutex_unlock(&(buff.mutex));
}
}
static void dump_buffer()
{
FILE *fileP = fopen(log_name, "w");
if(fileP == 0){
exit(1);
}
int i, j;
j = 0;
for(i = buff.curr; i < buff.curr + MAX_LOG_ENTRY; i++) {
fprintf(fileP,"log %d: %s\\n",j, buff.log[i%MAX_LOG_ENTRY]);
j++;
}
fclose(fileP);
}
static void *logger_start(void *arg)
{
while(1)
{
printf("RING_BUFFER: [Thread %x] dumping ring buffer to log file ring.log\\n", (unsigned int)pthread_self());
sleep(alarm_interval);
pthread_mutex_lock(&(buff.mutex));
dump_buffer();
pthread_mutex_unlock(&(buff.mutex));
}
pthread_exit(0);
}
static void alarm_handler(int sig)
{
alarm(alarm_interval);
}
| 0
|
#include <pthread.h>
uint32_t counter;
pthread_t threads[2];
pthread_mutex_t _lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t _start = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t _cond = PTHREAD_COND_INITIALIZER;
void *thread_function (void *thread_data) {
pthread_mutex_lock(&_start);
pthread_mutex_unlock(&_start);
pthread_mutex_lock(&_lock);
if (counter > 0) {
pthread_cond_signal(&_cond);
}
while (1) {
counter++;
pthread_cond_signal(&_cond);
pthread_cond_wait(&_cond, &_lock);
}
pthread_mutex_unlock(&_lock);
pthread_exit(0);
}
int main (void) {
struct timeval start_time, end_time;
pthread_mutex_lock(&_start);
pthread_create(&threads[0], 0, thread_function, 0);
pthread_create(&threads[1], 0, thread_function, 0);
pthread_detach(threads[0]);
pthread_detach(threads[1]);
gettimeofday(&start_time, 0);
pthread_mutex_unlock(&_start);
sleep(1);
pthread_mutex_lock(&_lock);
gettimeofday(&end_time, 0);
double context_switch_speed = ((double) (1000000 * end_time.tv_sec + end_time.tv_usec) - (1000000 * start_time.tv_sec + start_time.tv_usec)) / (double) counter;
printf("Context switch takes %f microseconds, %u elapsed in %lu microseconds.\\n", context_switch_speed, counter, (1000000 * end_time.tv_sec + end_time.tv_usec) - (1000000 * start_time.tv_sec + start_time.tv_usec));
return 0;
}
| 1
|
#include <pthread.h>
struct screen_in_t {
int up, down, left, right;
int a;
};
struct screen_tty_t {
const struct screen_ops_t *ops;
pthread_t thread;
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int ev;
} event;
struct map_t map;
struct screen_in_t in;
struct {
struct map_t map;
struct screen_in_t in;
} frame;
};
static void *screen_tty_thread(void *parm);
static struct screen_t *screen_tty_new(int *argcp, char **argv)
{
struct screen_tty_t *w = malloc(sizeof *w);
memset(w, 0, sizeof *w);
w->ops = &screen_tty_ops;
pthread_mutex_init(&w->event.mutex, 0);
pthread_cond_init(&w->event.cond, 0);
pthread_create(&w->thread, 0, screen_tty_thread, w);
return (struct screen_t *) w;
}
static void *screen_tty_thread(void *parm)
{
struct screen_tty_t *w = parm;
initscr();
cbreak();
noecho();
timeout(0);
nonl();
intrflush(stdscr, FALSE);
keypad(stdscr, TRUE);
while (1) {
pthread_mutex_lock(&w->event.mutex);
while (!w->event.ev)
pthread_cond_wait(&w->event.cond, &w->event.mutex);
w->event.ev = 0;
pthread_mutex_unlock(&w->event.mutex);
while (1) {
int ch = getch();
if (ch == ERR)
break;
switch (ch) {
case KEY_UP:
w->in.up = 1;
break;
case KEY_DOWN:
w->in.down = 1;
break;
case KEY_RIGHT:
w->in.right = 1;
break;
case KEY_LEFT:
w->in.left = 1;
break;
case 'z':
w->in.a = 1;
break;
}
}
for (int y = 0; y < MAP_HEIGHT; y++) {
for (int x = 0; x < MAP_WIDTH; x++) {
int c = ' ';
switch (w->map.data[y][x].type) {
case TYPE_NONE:
break;
case TYPE_BLOCK:
c = '*';
break;
case TYPE_GANG:
c = 'o';
break;
case TYPE_BALL:
if (w->map.data[y][x].ball_dir < 0)
c = '<';
else
c = '>';
break;
}
mvprintw(y, x, "%c", c);
}
}
refresh();
}
return 0;
}
static void screen_tty_notify(struct screen_t *scr)
{
struct screen_tty_t *w = (struct screen_tty_t *) scr;
pthread_mutex_lock(&w->event.mutex);
w->event.ev = 1;
pthread_cond_signal(&w->event.cond);
w->map = w->frame.map;
w->frame.in = w->in;
memset(&w->in, 0, sizeof w->in);
pthread_mutex_unlock(&w->event.mutex);
}
static void screen_tty_set_map(struct screen_t *scr, const struct map_t *map)
{
struct screen_tty_t *w = (struct screen_tty_t *) scr;
w->frame.map = *map;
}
static unsigned long screen_tty_in(struct screen_t *scr)
{
struct screen_tty_t *w = (struct screen_tty_t *) scr;
return w->frame.in.a * SCREEN_IN_A |
w->frame.in.up * SCREEN_IN_UP |
w->frame.in.down * SCREEN_IN_DOWN |
w->frame.in.left * SCREEN_IN_LEFT |
w->frame.in.right * SCREEN_IN_RIGHT;
}
struct screen_ops_t screen_tty_ops = {
.new = screen_tty_new,
.notify = screen_tty_notify,
.set_map = screen_tty_set_map,
.in = screen_tty_in,
};
| 0
|
#include <pthread.h>
const int capacity = 100;
const int round_max = 50000;
int capacity;
int size;
item_t* space;
pthread_mutex_t lock;
pthread_cond_t some_space;
pthread_cond_t some_items;
} storage_t;
void* produce(void* param) {
storage_t* storage = (storage_t*) param;
int round = 0;
int notification = 0;
while (round < round_max) {
++round;
printf("P %d:%d: S\\n", round, notification);
int error;
item_t product = random();
printf("P %d:%d: %ld\\n", round, notification, product);
printf("P %d:%d: L...\\n", round, notification);
error = pthread_mutex_lock(&storage->lock);
assert(error == 0);
printf("P %d:%d: L\\n", round, notification);
int put = 0;
while (!put) {
if (storage->size < storage->capacity) {
*(storage->space + storage->size) = product;
++storage->size;
pthread_cond_signal(&storage->some_items);
++notification;
printf("P %d:%d: consumer notified\\n", round, notification);
pthread_mutex_unlock(&storage->lock);
printf("P %d:%d: notifying U\\n", round, notification);
put = 1;
}
else {
printf("P %d:%d: space L...\\n", round, notification);
pthread_cond_wait(&storage->some_space, &storage->lock);
printf("P %d:%d: space L\\n", round, notification);
}
}
}
printf("P %d:%d: completed\\n", round, notification);
}
void* consume(void* param) {
storage_t* storage = (storage_t*) param;
int round = 0;
int notification = 0;
while (round < round_max) {
++round;
printf("C %d:%d: S\\n", round, notification);
int error;
item_t product;
printf("C %d:%d: L...\\n", round, notification);
error = pthread_mutex_lock(&storage->lock);
assert(error == 0);
printf("C %d:%d: L\\n", round, notification);
int get = 0;
while (!get) {
if (storage->size > 0) {
--storage->size;
product = *(storage->space + storage->size);
pthread_cond_signal(&storage->some_space);
++notification;
printf("C %d:%d: notifying U\\n", round, notification);
pthread_mutex_unlock(&storage->lock);
get = 1;
}
else {
printf("C %d:%d: items L...\\n", round, notification);
pthread_cond_wait(&storage->some_items, &storage->lock);
printf("C %d:%d: items L\\n", round, notification);
}
}
printf("C %d:%d: %ld\\n", round, notification, product);
}
printf("C %d:%d: completed\\n", round, notification);
}
int main(int argc, char** argv) {
storage_t storage;
pthread_t producer;
pthread_t consumer;
storage.capacity = capacity;
storage.size = 0;
storage.space = malloc(sizeof(item_t) * capacity);
pthread_mutex_init(&storage.lock, 0);
pthread_cond_init(&storage.some_space, 0);
pthread_cond_init(&storage.some_items, 0);
pthread_create(&producer, 0, produce, &storage);
pthread_create(&consumer, 0, consume, &storage);
printf("Main thread waiting for producer...\\n");
pthread_join(producer, 0);
printf("Main thread waiting for consumer...\\n");
pthread_join(consumer, 0);
printf("Main thread exit\\n");
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void* thread(void* p)
{
int *q=(int*)p;
int i;
for(i=0;i<10000000;i++)
{
pthread_mutex_lock(&mutex);
*q+=1;
pthread_mutex_unlock(&mutex);
}
printf("the thread %d creat success,\\n",*q);
return 0;
}
int main()
{
pthread_t id;
int i,ret;
int *p=(int*)malloc(4);
*p=0;
pthread_mutexattr_t mattr;
pthread_mutexattr_init(&mattr);
pthread_mutexattr_settype(&mattr,PTHREAD_MUTEX_RECURSIVE);
ret=pthread_mutex_init(&mutex,&mattr);
if(ret!=0)
{
printf("pthread_mutex_init=%i\\n",ret);
exit(-1);
}
ret=pthread_create(&id,0,thread,p);
if(ret!=0)
{
printf("pthread_creat ret=%i\\n",ret);
exit(-1);
}
for(i=0;i<10000000;i++)
{
pthread_mutex_lock(&mutex);
pthread_mutex_lock(&mutex);
*p+=1;
pthread_mutex_unlock(&mutex);
}
pthread_join(id,0);
printf("*p=%d\\n",*p);
printf("main thread input here\\n");
return 0;
}
| 0
|
#include <pthread.h>
int G_CHUNK_SIZE;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
large_uint G_current_start;
large_uint G_subset_count;
int G_terminated_flag;
large_uint G_steps;
void increment_step() {
pthread_mutex_lock(&mutex);
G_steps++;
pthread_mutex_unlock(&mutex);
}
struct solution {
large_int* subset;
int size;
};
large_uint get_next_start() {
pthread_mutex_lock(&mutex);
large_uint start = G_current_start;
G_current_start = start + G_CHUNK_SIZE;
pthread_mutex_unlock(&mutex);
return start;
}
void print_set(large_int* set, int size, FILE* out) {
int i;
fprintf(out, "{");
for (i = 0; i < size; i++) {
if (i > 0) {
fprintf(out, ", ");
}
fprintf(out, "%lld", set[i]);
}
fprintf(out, "}\\n");
}
large_int* generate_subset(large_int* set, large_uint elements, int* subset_size) {
large_uint max_elements = round(log(elements) / log(2)) + 1;
large_int* subset = malloc(sizeof(large_int) * max_elements);
int i;
int current_index = 0;
for (i = 0; i < max_elements; i++) {
large_uint val = (elements >> i) & 1;
if (val == 1) {
subset[current_index] = set[i];
current_index++;
}
}
*subset_size = current_index;
return subset;
}
large_int calculate_set_sum(large_int* set, int size) {
large_int sum = 0;
int i;
for (i = 0; i < size; i++) {
sum += set[i];
}
return sum;
}
void* find_zero_subset(void* data) {
large_int* set = (large_int*) data;
while (1) {
large_uint start = get_next_start();
large_uint i;
for (i = start; i < start + G_CHUNK_SIZE; i++) {
if (i >= G_subset_count || G_terminated_flag == 1) {
return 0;
}
int size;
large_int* subset = generate_subset(set, i, &size);
large_int sum = calculate_set_sum(subset, size);
if (sum == 0) {
struct solution* sol = (struct solution*) malloc(sizeof(struct solution));
sol->subset = subset;
sol->size = size;
printf("Solution found!\\n");
pthread_mutex_lock(&mutex);
G_terminated_flag = 1;
pthread_mutex_unlock(&mutex);
return ((void*) sol);
}
free(subset);
}
}
return 0;
}
large_int* generate_set(unsigned int set_size, large_int range) {
int i;
large_int* set = malloc(sizeof(large_int) * set_size);
for (i = 0; i < set_size; i++) {
double val = (((double) pcg32_boundedrand(range)) / (range / 2.0)) - 1;
large_int value = val * range;
set[i] = value;
}
return set;
}
void test_multithread(FILE* file, int num_threads, int set_size, large_int range, int chunk_size) {
G_CHUNK_SIZE = chunk_size;
pthread_t threads[num_threads];
clock_t start = clock();
large_int* set = generate_set(set_size, range);
G_subset_count = round(pow(2, set_size));
G_current_start = 1;
G_terminated_flag = 0;
G_steps = 0;
int i;
for (i = 0; i < num_threads; i++) {
pthread_create(&threads[i], 0, find_zero_subset, (void*) set);
}
struct solution* sol = 0;
for (i = 0; i < num_threads; i++) {
void* ret;
pthread_join(threads[i], &ret);
if (ret != 0) {
printf("Thread %d found a solution!\\n", i);
sol = ret;
} else {
printf("Thread %d was not able to find a solution.\\n", i);
}
}
clock_t end = clock();
double delta = (((double) (end - start)) / CLOCKS_PER_SEC);
printf("%.5f\\n", delta);
printf("Joined with result %x and %d executions\\n", sol, G_steps);
if (sol != 0) {
print_set(sol->subset, sol->size, stdout);
free(sol);
}
fprintf(file, "%d,%d,%d,%.6f\\n", G_CHUNK_SIZE, num_threads, set_size, delta);
fflush(file);
}
void test_single(FILE* file, int set_size, large_int range) {
G_CHUNK_SIZE = 32767;
clock_t start = clock();
large_int* set = generate_set(set_size, range);
G_subset_count = round(pow(2, set_size));
G_current_start = 1;
G_terminated_flag = 0;
G_steps = 0;
struct solution* sol = find_zero_subset((void*) set);
if (sol != 0) {
print_set(sol->subset, sol->size, stdout);
free(sol);
}
clock_t end = clock();
double delta = (((double) (end - start)) / CLOCKS_PER_SEC);
fprintf(file, "%d,%.6f\\n", set_size, delta);
fflush(file);
}
int main(int argc, char** argv) {
int rounds = atoi(argv[0]);
pcg32_srandom(time(0), (intptr_t) &rounds);
FILE* file = fopen("out_single.csv", "w");
fprintf(file, "setsize,time\\n");
int ch, th, k, it;
for (k = 0; k < 13; k++) {
for (it = 0; it < 100; it++) {
int set_size = (k + 1) * 4;
large_int range = round(pow(2, set_size / 2));
printf("k = %d, it = %d\\n", k, it);
test_single(file, set_size, range);
}
}
return 0;
}
| 1
|
#include <pthread.h>
void *heartbeater(void);
void timer_handler(void);
void setup_timer(void);
int *old_seq;
int *new_seq;
int seq_size;
int sequence_num;
pthread_t heartbeat_thread;
pthread_mutex_t suspend_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
struct sigaction sa;
struct itimerval timer;
void multicast_init(void) {
unicast_init();
seq_size = 0;
sequence_num = 0;
new_seq = 0;
pthread_create(&heartbeat_thread, 0, (void*)heartbeater, 0);
}
void timer_handler(){
pthread_cond_signal(&suspend_cond);
debugprintf(" waking up heartbeat \\n");
}
void setup_timer(){
memset(&sa, 0, sizeof(sa));
sa.sa_handler = &timer_handler;
sigaction(SIGALRM, &sa, 0);
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 10000;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 10000;
setitimer(ITIMER_REAL, &timer, 0);
}
void *heartbeater(void){
int i=0;
while(1){
pthread_mutex_lock(&member_lock);
for(i=0;i<mcast_num_members; i++){
if(mcast_members[i] == my_id)
continue;
sequence_num++;
char message[256];
sprintf(message, "%d", sequence_num);
usend(mcast_members[i], message, strlen(message));
}
pthread_mutex_unlock(&member_lock);
debugprintf("Checking arrays...\\n");
for(i=0; i<seq_size; i++){
if(new_seq[i] <= old_seq[i] && new_seq[i]!=-1){
printf("--------------[%d]: Process %d has failed.\\n", my_id, mcast_members[i]);
}
old_seq[i] = new_seq[i];
}
debugprintf("Pausing heartbeat thread \\n");
sleep(15);
}
}
void receive(int source, const char *message, int len) {
assert(message[len-1] == 0);
pthread_mutex_lock(&member_lock);
if(seq_size != mcast_num_members){
old_seq = realloc(old_seq, sizeof(int)* mcast_num_members);
new_seq = realloc(new_seq, sizeof(int)* mcast_num_members);
int i=0;
for(i=seq_size; i<mcast_num_members; i++){
old_seq[i] = -1;
new_seq[i] = 0;
}
seq_size = mcast_num_members;
}
int index = 0;
int i=0;
for(i=0;i<mcast_num_members; i++){
if(source == mcast_members[i]){
index = i;
break;
}
}
new_seq[index] = atoi(message);
pthread_mutex_unlock(&member_lock);
}
| 0
|
#include <pthread.h>
sem_t tob_paper;
sem_t match_paper;
sem_t tob_match;
pthread_mutex_t table_mutex;
pthread_cond_t condition_var;
void serve_tob_paper();
void serve_match_paper();
void serve_tob_match();
void consumer_tob_paper();
void consumer_match_paper();
void consumer_tob_match();
void smoker_fn(void*);
void agent_fn();
int tobacco = 0,match = 0, paper = 0;
int main()
{
int i = 0;
pthread_t smoker_thread[3],agent_thread;
pthread_mutex_init(&table_mutex,0);
pthread_cond_init(&condition_var,0);
sem_init(&tob_paper, 0 , 0);
sem_init(&match_paper, 0 , 0);
sem_init(&tob_match, 0 , 0);
if(pthread_create(&agent_thread,0,agent_fn,0) != 0){
perror("Agent thread can't be created\\n");
return 1;
}
for(i=0;i<3;i++){
if(pthread_create(&smoker_thread[i],0,smoker_fn,(void*)i) != 0){
perror("Smoker threads can't be created\\n");
return 2;
}
}
pthread_join(agent_thread,0);
for(i=0;i<3;i++){
pthread_join(smoker_thread[i],0);
}
return 0;
}
void agent_fn(){
int i;
for(i=0;i<5;i++){
printf("----------------------ROUND %d-----------------------\\n",i);
pthread_mutex_lock(&table_mutex);
serve_tob_paper();
printf("Tobacco & Paper are kept on table\\n");
sem_post(&tob_paper);
pthread_cond_wait(&condition_var, &table_mutex);
serve_match_paper();
printf("Match & Paper are kept on table\\n");
sem_post(&match_paper);
pthread_cond_wait(&condition_var, &table_mutex);
serve_tob_match();
printf("Tobacco & Match are kept on table\\n");
sem_post(&tob_match);
pthread_cond_wait(&condition_var, &table_mutex);
pthread_mutex_unlock(&table_mutex);
}
}
void smoker_fn(void* index)
{
int num,i;
num = (int)index;
for(i=0;i<5;i++){
switch(num){
case 0:
printf("[Round %d][Smoker %d]Waiting...\\n",i,num);
sem_wait(&tob_paper);
printf("[Smoker %d]Got signal for tob_paper\\n",num);
pthread_mutex_lock(&table_mutex);
printf("[Smoker %d]Locked table for tob_paper\\n",num);
consume_tob_paper();
printf("[Smoker %d]Consumed tob_paper\\n",num);
pthread_cond_signal(&condition_var);
printf("[Smoker %d]Signalled Agent\\n",num);
pthread_mutex_unlock(&table_mutex);
break;
case 1:
printf("[Round %d][Smoker %d]Waiting...\\n",i,num);
sem_wait(&match_paper);
printf("[Smoker %d]Got signal for match_paper\\n",num);
pthread_mutex_lock(&table_mutex);
printf("[Smoker %d]Locked table for match_paper\\n",num);
consume_match_paper();
printf("[Smoker %d]Consumed match_paper\\n",num);
pthread_cond_signal(&condition_var);
printf("[Smoker %d]Signalled Agent\\n",num);
pthread_mutex_unlock(&table_mutex);
break;
case 2:
printf("[Round %d][Smoker %d]Waiting...\\n",i,num);
sem_wait(&tob_match);
printf("[Smoker %d]Got signal for tob_match\\n",num);
pthread_mutex_lock(&table_mutex);
printf("[Smoker %d]Locked table for tob_match\\n",num);
consume_tob_match();
printf("[Smoker %d]Consumed tob_match\\n",num);
pthread_cond_signal(&condition_var);
printf("[Smoker %d]Signalled Agent\\n",num);
pthread_mutex_unlock(&table_mutex);
break;
}
}
}
void serve_tob_paper(){
tobacco++;
paper++;
}
void serve_match_paper(){
match++;
paper++;
}
void serve_tob_match(){
tobacco++;
match++;
}
void consume_tob_paper(){
tobacco--;
paper--;
}
void consume_match_paper(){
match--;
paper--;
}
void consume_tob_match(){
tobacco--;
match--;
}
| 1
|
#include <pthread.h>
unsigned int TEST_TMP;
unsigned int TEST_VALUE_CA[8][3] = {
{CMD_READ, REG_MC34704_GENERAL1, &TEST_TMP},
{CMD_SUB, 2, 0},
{CMD_READ, REG_MC34704_GENERAL2, &TEST_TMP},
{CMD_SUB, 0, 0},
{CMD_READ, REG_MC34704_FAULTS, &TEST_TMP},
{CMD_UNSUB, 0, 0},
{CMD_UNSUB, 2, 0}
};
int VT_mc34704_CA_setup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc34704_CA_cleanup(void) {
int rv = TFAIL;
rv = TPASS;
return rv;
}
int VT_mc34704_test_CA(void) {
int rv = TPASS, fd, i = 0;
fd = open(MC34704_DEVICE, O_RDWR);
if (fd < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to open %s", MC34704_DEVICE);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
for (i = 0; i < 8; i++) {
if (VT_mc34704_opt
(fd, TEST_VALUE_CA[i][0], TEST_VALUE_CA[i][1],
&(TEST_VALUE_CA[i][2])) != TPASS) {
rv = TFAIL;
}
}
if (close(fd) < 0) {
pthread_mutex_lock(&mutex);
tst_resm(TFAIL, "Unable to close file descriptor %d",
fd);
pthread_mutex_unlock(&mutex);
return TFAIL;
}
return rv;
}
| 0
|
#include <pthread.h>
int limite = 650000;
int contatore = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condizione = PTHREAD_COND_INITIALIZER;
void *somma (){
printf("T somma: %d partito\\n",(int)pthread_self());
int sum = 0;
for(int i = 0; i < 1000; i++){
int generato = 1 + rand() % 10;
sum = sum + generato;
pthread_mutex_lock(&mutex);
contatore++;
pthread_mutex_unlock(&mutex);
if(contatore >= limite){
pthread_cond_signal(&condizione);
pthread_exit(0);
}
}
return 0;
}
void *verifica(){
printf("T verifica: %d partito\\n",(int)pthread_self());
pthread_cond_wait(&condizione, &mutex);
printf("Limite di %d raggiunto.\\n", limite);
pthread_exit(0);
}
int main(int argc, char *argv[]){
pthread_t threads[3];
if(argc < 2){
printf("Devi fornire valore limite.\\n");
return 1;
}
limite = atoi(argv[1]);
pthread_create(&threads[0],0,somma,0);
pthread_create(&threads[1],0,somma,0);
pthread_create(&threads[2],0,verifica,0);
pthread_join(threads[0],0);
pthread_join(threads[1],0);
pthread_join(threads[2],0);
return 0;
}
| 1
|
#include <pthread.h>
int somme_alea;
int cpt;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_cpt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_cpt = PTHREAD_COND_INITIALIZER;
void* thread_rand(void * arg){
int random_val = (int) ((float) 10 * rand() /(32767 + 1.0));
printf("Mon num d'ordre : %d \\t mon tid %d \\t valeur generee : %d\\n", (*(int *)arg), (int)pthread_self(), random_val);
pthread_mutex_lock(&mutex);
somme_alea += random_val;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex_cpt);
cpt++;
if (cpt == 5){
pthread_cond_signal(&cond_cpt);
}
pthread_mutex_unlock(&mutex_cpt);
pthread_exit((void *)0);
}
void * print_thread(void * arg){
pthread_mutex_lock(&mutex_cpt);
pthread_cond_wait(&cond_cpt, &mutex_cpt);
pthread_mutex_unlock(&mutex_cpt);
printf("La somme des valeurs generees par les threads est : %d \\n", somme_alea);
pthread_exit((void *)0);
}
int main(int argc, char * argv[]){
int i, p,status;
int tab[5];
pthread_t tid[5];
pthread_t pt_print_tid;
somme_alea = 0;
cpt = 0;
srand(time(0));
if (pthread_create(&pt_print_tid, 0, print_thread, 0) != 0){
perror("pthread_create");
exit(1);
}
for(i=0; i<5; i++){
tab[i]=i;
if((p=pthread_create(&(tid[i]), 0, thread_rand, &tab[i])) != 0){
perror("pthread_create");
exit(1);
}
if(pthread_detach(tid[i]) != 0){
perror("pthread_detach");
exit(1);
}
}
if(pthread_join( pt_print_tid,(void**) &status) != 0){
perror("pthread_join");
exit(1);
}
return 0;
}
| 0
|
#include <pthread.h>
void * additionneur(void *);
pthread_t tid[2];
int nombre = 0;
pthread_mutex_t lock;
main( int argc, char *argv[] )
{
int i;
for (i=0; i<2; i++) {
pthread_create(&tid[i], 0, additionneur, 0);
}
for ( i = 0; i < 2; i++)
pthread_join(tid[i], 0);
printf("main signale que les %d threads ont terminé\\n", i);
printf("Je suis main ! nombre=%d\\n", nombre);
}
void * additionneur(void * parm)
{
int i;
printf("Je suis une nouvelle thread !\\n");
pthread_mutex_lock(&lock);
for(i=0;i<200000;i++) {
nombre++;
}
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
double _glfwPlatformGetTime( void )
{
struct timeval tv;
gettimeofday( &tv, 0 );
return tv.tv_sec + (double) tv.tv_usec / 1000000.0 - _glfwLibrary.Timer.t0;
}
void _glfwPlatformSetTime( double time )
{
struct timeval tv;
gettimeofday( &tv, 0 );
_glfwLibrary.Timer.t0 = tv.tv_sec + (double) tv.tv_usec / 1000000.0 - time;
}
void _glfwPlatformSleep( double time )
{
if( time == 0.0 )
{
sched_yield();
return;
}
struct timeval currenttime;
struct timespec wait;
pthread_mutex_t mutex;
pthread_cond_t cond;
long dt_sec, dt_usec;
gettimeofday( ¤ttime, 0 );
dt_sec = (long) time;
dt_usec = (long) ((time - (double)dt_sec) * 1000000.0);
wait.tv_nsec = (currenttime.tv_usec + dt_usec) * 1000L;
if( wait.tv_nsec > 1000000000L )
{
wait.tv_nsec -= 1000000000L;
dt_sec ++;
}
wait.tv_sec = currenttime.tv_sec + dt_sec;
pthread_mutex_init( &mutex, 0 );
pthread_cond_init( &cond, 0 );
pthread_mutex_lock( &mutex );
pthread_cond_timedwait( &cond, &mutex, &wait );
pthread_mutex_unlock( &mutex );
pthread_mutex_destroy( &mutex );
pthread_cond_destroy( &cond );
}
| 0
|
#include <pthread.h>
int work_id = 0;
struct Job {
int id;
pthread_t tid;
pthread_cond_t cond;
pthread_mutex_t mutex;
int time;
char c;
struct Job* next;
};
void do_job(struct Job* jp) {
printf("%c", jp->c);
jp->time--;
work_id++;
if (work_id == 4)
work_id = 0;
pthread_mutex_unlock(&jp->mutex);
pthread_cond_signal(&jp->next->cond);
}
void* job_thread(void *arg) {
struct Job *jp = (struct Job *) arg;
while(jp->time > 0) {
pthread_mutex_lock(&jp->mutex);
if (work_id == jp->id) {
do_job(jp);
}
else {
pthread_cond_wait(&jp->cond, &jp->mutex);
do_job(jp);
}
}
}
int main() {
struct Job job[4];
char s[] = "ABCD";
for (int i = 0; i < 4; i++) {
job[i].id = i;
pthread_mutex_init(&(job[i].mutex), 0);
pthread_cond_init(&(job[i].cond),0);
job[i].c = s[i];
job[i].time = 10;
if (i != 3) {
job[i].next = &job[i+1];
}
else {
job[i].next = &job[0];
}
}
for (int i = 0; i < 4; i++) {
pthread_create(&(job[i].tid), 0, job_thread, &(job[i]));
}
for (int i = 0; i < 4; i++) {
pthread_join(job[i].tid, 0);
}
return 0;
}
| 1
|
#include <pthread.h>
void* passenger_arrive(void* arg){
pthread_mutex_lock(&station.station_key);
station.waiting_passenger_count+=1;
printf("\\npassenger arrived, \\twaiting list = %d", station.waiting_passenger_count);
while(1){
if((station.available_seat_count<=0)||(station.train_left==1)){
pthread_cond_wait(&station.train_arrived, &station.station_key);
continue;
}else{
station.available_seat_count-=1;
station.boarded_passenger_count+=1;
station.waiting_passenger_count-=1;
if((station.boarded_passenger_count==station.max_allowed_passengers)||(station.waiting_passenger_count==0)){
station.train_left=1;
pthread_cond_signal(&station.train_loaded);
}
printf("\\n\\t\\tpassenger boarded");
pthread_mutex_unlock(&station.station_key);
pthread_exit(0);;
}
}
}
void* train_arrive(void* arg){
int count=TRAIN_AVAILABLE_SEATS;
pthread_mutex_lock(&station.station_key);
printf("\\n****************************************************************");
printf("\\nTRAIN ARRIVED");
printf("\\n****************************************************************");
station.train_left=0;
station.available_seat_count=count;
station.boarded_passenger_count=0;
station.max_allowed_passengers=count;
pthread_cond_broadcast(&station.train_arrived);
if(station.waiting_passenger_count==0||count==0){
station.train_left=1;
printf("\\n****************************************************************");
printf("\\nTRAIN LEFT");
printf("\\n****************************************************************");
pthread_mutex_unlock(&station.station_key);
pthread_exit(0);
}
while(1){
if((station.waiting_passenger_count==0)||(station.available_seat_count==0)){
station.train_left=1;
printf("\\n****************************************************************");
printf("\\nTRAIN LEFT");
printf("\\n****************************************************************");
pthread_mutex_unlock(&station.station_key);
pthread_exit(0);
}else{
pthread_cond_wait(&station.train_loaded, &station.station_key);
continue;
}
}
}
| 0
|
#include <pthread.h>
void vegas_thread_args_init(struct vegas_thread_args *a, int instance_id) {
a->instance_id = instance_id;
a->priority=0;
a->finished=0;
pthread_cond_init(&a->finished_c,0);
pthread_mutex_init(&a->finished_m,0);
}
void vegas_thread_args_destroy(struct vegas_thread_args *a) {
a->finished=1;
pthread_cond_destroy(&a->finished_c);
pthread_mutex_destroy(&a->finished_m);
}
void vegas_thread_set_finished(struct vegas_thread_args *a) {
pthread_mutex_lock(&a->finished_m);
a->finished=1;
pthread_cond_broadcast(&a->finished_c);
pthread_mutex_unlock(&a->finished_m);
}
int vegas_thread_finished(struct vegas_thread_args *a,
float timeout_sec) {
struct timeval now;
struct timespec twait;
int rv;
pthread_mutex_lock(&a->finished_m);
gettimeofday(&now,0);
twait.tv_sec = now.tv_sec + (int)timeout_sec;
twait.tv_nsec = now.tv_usec * 1000 +
(int)(1e9*(timeout_sec-floor(timeout_sec)));
if (a->finished==0)
rv = pthread_cond_timedwait(&a->finished_c, &a->finished_m, &twait);
rv = a->finished;
pthread_mutex_unlock(&a->finished_m);
return(rv);
}
| 1
|
#include <pthread.h>
int printflag = 1;
pthread_mutex_t gmutex = PTHREAD_MUTEX_INITIALIZER;
void s_handler(int signum)
{
pthread_mutex_lock(&gmutex);
printf("Enter signal handler function for : %d\\n", signum);
if (printflag)
printflag = 0;
else
printflag = 1;
printf("Exit signal handler function for : %d\\n", signum);
pthread_mutex_unlock(&gmutex);
}
main() {
int sigret = 0;
pthread_t thread1;
signal(SIGINT,s_handler);
if (errno != 0) {
printf("SIGINT set error %d \\n", errno);
}
while(1) {
pthread_mutex_lock(&gmutex);
sleep(2);
if (printflag)
printf("printing in while loop if printflag is true\\n");
pthread_mutex_unlock(&gmutex);
}
printf("can't print this \\n");
}
| 0
|
#include <pthread.h>
int nlibre = 123;
void* ALL_IS_OK = (void*)123456789L;
pthread_cond_t c;
pthread_mutex_t mutex;
void* allouer(void* n){
int i;
int* p_n = (int*)n;
for(i=0; i<100; i++){
pthread_mutex_lock(&mutex);
while(*p_n > nlibre){
pthread_cond_wait(&c, &mutex);
pthread_cond_signal(&c);
}
nlibre = nlibre - *p_n;
printf("ALLOCATION : %d\\n", nlibre);
pthread_mutex_unlock(&mutex);
}
return ALL_IS_OK;
}
void* liberer(void* m){
int i;
int* p_m = (int*)m;
for(i=0; i<100; i++){
pthread_mutex_lock(&mutex);
nlibre = nlibre + *p_m;
printf(" LIBERATION : %d\\n", nlibre);
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&c);
}
return ALL_IS_OK;
}
void main(){
pthread_t p1, p2;
void* status;
int* p_n = malloc(sizeof(int));
int* p_m = malloc(sizeof(int));
*p_n = 10;
*p_m = 2;
pthread_cond_init(&c, 0);
pthread_mutex_init(&mutex, 0);
pthread_create(&p1, 0, allouer, (void*)p_n);
pthread_create(&p2, 0, liberer, (void*)p_m);
pthread_join(p1, &status);
if (status == ALL_IS_OK) printf("Thread %lx completed ok \\n", p1);
pthread_join(p2, &status);
if (status == ALL_IS_OK) printf("Thread %lx completed ok \\n", p2);
free(p_n);
free(p_m);
}
| 1
|
#include <pthread.h>
const char *test_doc = "Check that shared FS is migrated properly";
const char *test_author = "Stanislav Kinsburskiy <skinsbursky@virtuozzo.com>";
enum kcmp_type {
KCMP_FILE,
KCMP_VM,
KCMP_FILES,
KCMP_FS,
KCMP_SIGHAND,
KCMP_IO,
KCMP_SYSVSEM,
KCMP_TYPES,
};
static int kcmp(int type, pid_t pid1, pid_t pid2, unsigned long idx1, unsigned long idx2)
{
int ret;
ret = syscall(SYS_kcmp, pid1, pid2, type, idx1, idx2);
switch (ret) {
case 0:
break;
case 1:
case 2:
test_msg("FS for pids %d and %d doesn't match: %d\\n", pid1, pid2, ret);
break;
case -1:
pr_perror("kcmp (type: %d, pid1: %d, pid2: %d, "
"idx1: %ld, idx2: %ld) failed: %d\\n",
type, pid1, pid2, idx1, idx2, errno);
break;
default:
pr_perror("kcmp (type: %d, pid1: %d, pid2: %d, "
"idx1: %ld, idx2: %ld) returned %d\\n\\n",
type, pid1, pid2, idx1, idx2, ret);
break;
}
return ret;
}
static pthread_mutex_t init_lock;
static pthread_mutex_t exit_lock;
static void *thread_func(void *tid2)
{
*(int *)tid2 = syscall(__NR_gettid);
pthread_mutex_unlock(&init_lock);
pthread_mutex_lock(&exit_lock);
return 0;
}
int main(int argc, char **argv)
{
pid_t tid;
int ret;
pthread_t th;
test_init(argc, argv);
pthread_mutex_init(&init_lock, 0);
pthread_mutex_lock(&init_lock);
pthread_mutex_init(&exit_lock, 0);
pthread_mutex_lock(&exit_lock);
if (pthread_create(&th, 0, thread_func, &tid)) {
fail("Can't pthread_create");
return 1;
}
pthread_mutex_lock(&init_lock);
ret = kcmp(KCMP_FS, syscall(__NR_gettid), tid, 0, 0);
if (ret)
exit(1);
test_daemon();
test_waitsig();
ret = kcmp(KCMP_FS, syscall(__NR_gettid), tid, 0, 0);
if (ret) {
fail();
exit(1);
}
pthread_mutex_unlock(&exit_lock);
pthread_join(th, 0);
pass();
return 0;
}
| 0
|
#include <pthread.h>
static unsigned long rnd = 11;
int buffer[10];
int out = 0;
int in = 0;
int count = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_threshold;
void *producer(void *param);
void *consumer(void *param);
int genrnd(unsigned int n);
void printbuf();
int main(int argc, const char *argv[])
{
pthread_t tid1;
pthread_t tid2[5];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_cond_init(&count_threshold, 0);
pthread_create(&tid1, &attr, producer, 0);
int k;
for (k = 0; k < 5; k++)
pthread_create(&tid2[k], &attr, consumer, 0);
for (k = 0; k < 5; k++)
pthread_join(tid2[k], 0);
pthread_join(tid1, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&count_threshold);
return 0;
}
void *producer(void *param)
{
printf("start producer...\\n");
while(1){
pthread_mutex_lock(&mutex);
while (count == 10)
pthread_cond_wait(&count_threshold, &mutex);
int d = genrnd(10);
in = (in + 1) % 10;
buffer[in] = d;
count++;
printf("produce %d ", d);
printbuf();
pthread_cond_broadcast(&count_threshold);
pthread_mutex_unlock(&mutex);
usleep(genrnd(10000));
}
}
void *consumer(void *param)
{
printf("start consumer...\\n");
while(1){
pthread_mutex_lock(&mutex);
while (count == 0)
pthread_cond_wait(&count_threshold, &mutex);
out = (out + 1) % 10;
int d = buffer[out];
buffer[out] = -1;
count--;
printf("consume %d ", d);
printbuf();
pthread_cond_signal(&count_threshold);
pthread_mutex_unlock(&mutex);
usleep(genrnd(10000));
}
}
void printbuf()
{
int i;
for (i = 0; i < 10; i++){
usleep(100);
if ((in > out && i > out && i <= in) || (in < out && (i <= in || i > out))){
printf("%d",buffer[i]);
} else{
printf("-");
}
}
printf(" \\n");
}
int genrnd(unsigned int n)
{
rnd = (1103515245 * rnd) % 45901 ;
return (n * rnd)/45901;
}
| 1
|
#include <pthread.h>
int buf[10];
pthread_mutex_t m;
sem_t pro,cust;
int count;
int index1,index2;
void* pro1(void* p)
{
while(1)
{
sleep(rand()%5);
sem_wait(&pro);
pthread_mutex_lock(&m);
buf[index1]=count;
index1=(index1+1)%10;
printf("pro:%d put %d\\n",(int)p,count);
count++;
pthread_mutex_unlock(&m);
sem_post(&cust);
}
return 0;
}
void *cust1(void* p)
{
while(1)
{
sleep(rand()%5);
sem_wait(&cust);
pthread_mutex_lock(&m);
printf("cust:%d fetch %d\\n",(int)p,buf[index2]);
index2=(index2+1)%10;
pthread_mutex_unlock(&m);
sem_post(&pro);
}
return 0;
}
int main()
{
pthread_t tid[10];
sem_init(&pro,0,10);
sem_init(&cust,0,0);
pthread_mutex_init(&m,0);
int i;
for(i=0;i<5;i++)
{
pthread_create(&tid[i],0,pro1,(void*)i);
}
for(i=0;i<5;i++)
{
pthread_create(&tid[i+5],0,cust1,(void*)i);
}
for(i=0;i<10;i++)
{
pthread_join(tid[i],0);
}
sem_destroy(&pro);
sem_destroy(&cust);
pthread_mutex_destroy(&m);
}
| 0
|
#include <pthread.h>
void* original(void* filename){
FILE* aux;
printf("\\nEl fichero que quiero leer. <%s>\\n", (char*)filename);
if((aux = fopen((char*)filename, "r")) == 0){
printf("\\nFichero no encontrado.");
exit(1);
}
do{
pthread_mutex_lock(&escritor);
printf("\\nLeyendo!...\\n");
bytes = fread(linea, sizeof(char), 1024, aux);
if(bytes > 0){
pthread_cond_broadcast(&leido);
pthread_cond_wait(&escritos, &escritor);
hebras_leidas = 0;
}
else
pthread_cond_broadcast(&leido);
pthread_mutex_unlock(&escritor);
}while(bytes > 0);
fclose(aux);
pthread_exit(0);
}
void* copia(void* fichero_hebras){
FILE* aux;
char* filename = (char*)malloc(20*sizeof(char));
strcpy(filename, (char*) fichero_hebras);
if((aux = fopen(filename, "a")) == 0){
printf("\\nFichero no encontrado.\\n");
exit(1);
}
do{
pthread_mutex_lock(&escritor);
while(!bytes > 0){
printf("\\nEstoy aqui(funcion copia, esperando)\\n");
pthread_cond_wait(&leido, &escritor);
}
pthread_mutex_unlock(&escritor);
if(bytes > 0){
fprintf(aux, "%s",linea);
fflush(aux);
pthread_mutex_lock(&escritor);
hebras_leidas++;
printf("\\nHebras_leidas puestas a %d \\n", hebras_leidas);
if(hebras_leidas == nhebras){
pthread_cond_signal(&escritos);
}
pthread_cond_wait(&leido, &escritor);
pthread_mutex_unlock(&escritor);
}
}while(bytes > 0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int numCookies =0;
int tid;
} thread_param;
pthread_mutex_t mutex;
pthread_cond_t emptyCond;
pthread_cond_t fullCond;
void* thread_consumer_func(void* pthread_arg)
{
thread_param* myParam = (thread_param*) pthread_arg;
int cookiesRetrieved =0;
while(cookiesRetrieved<15)
{
pthread_mutex_lock(&mutex);
if(numCookies>0)
{
numCookies--;
cookiesRetrieved++;
}
else
{
pthread_cond_signal(&fullCond);
pthread_cond_wait(&emptyCond,&mutex);
}
pthread_mutex_unlock(&mutex);
}
}
void* thread_producer_func(void* pthread_arg)
{
int cookiesPlaced =0;
while(cookiesPlaced<30)
{
pthread_mutex_lock(&mutex);
if(numCookies<9)
{
numCookies+=2;
cookiesPlaced+=2;
if(numCookies>0)
{
pthread_cond_broadcast(&emptyCond);
}
}
else if(numCookies ==9)
{
numCookies++;
cookiesPlaced++;
}
else if(numCookies == 10)
{
pthread_cond_wait(&fullCond,&mutex);
}
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&mutex,0);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_cond_init(&emptyCond,0);
pthread_cond_init(&fullCond,0);
thread_param *thread_params = (thread_param* ) malloc(sizeof(thread_param)*3);
pthread_t * threads = (pthread_t*)malloc(sizeof(pthread_t)*3);
int i,rc;
for(i=0; i<3; i++)
{
thread_param* input = &thread_params[i];
input->tid = i;
if(i==0)
{
rc = pthread_create(&threads[i],&attr, thread_producer_func,(void*) &thread_params[i]);
}
else
{
rc = pthread_create(&threads[i],&attr, thread_consumer_func,(void*) &thread_params[i]);
}
if(rc!=0)
{
printf("creating thread failed\\n");
}
}
pthread_attr_destroy(&attr);
for(i=0; i<3; i++)
{
rc = pthread_join(threads[i],0);
if(rc!=0)
{
printf("joining thread failed\\n");
}
}
pthread_cond_destroy(&emptyCond);
pthread_cond_destroy(&fullCond);
pthread_mutex_destroy(&mutex);
free(thread_params);
free(threads);
return 0;
}
| 0
|
#include <pthread.h>
struct thread_data {
long long soffset, foffset, offset;
pthread_t tid;
};
struct thread_data wthread[(1024)];
int nthreads;
unsigned int bwritten = 0;
pthread_mutex_t bwritten_mutex = PTHREAD_MUTEX_INITIALIZER;
long long fake_read(char *buffer, size_t size) ;
long long fake_write(char *buffer, size_t size, size_t offset)
;
long long fake_read(char *buffer, size_t size) {
size_t i;
for (i = 0; i < size; ++i)
buffer[i] = rand() % 26 + 'a';
return size;
}
long long fake_write(char *buffer, size_t size, size_t offset) {
size_t i;
for (i = 0; i < size; ++i)
fprintf(stderr, "%lu: %c\\n", offset + i, buffer[i]);
return size;
}
void *http_get(struct thread_data *td) {
long long foffset;
char *rbuf;
pthread_t tid;
tid = pthread_self();
rbuf = (char *)calloc((8192), sizeof(char));
foffset = td->foffset;
td->offset = td->soffset;
while (td->offset < foffset) {
long long dr, dw;
memset(rbuf, (8192), 0);
dr = fake_read(rbuf, (8192));
if (td->offset + dr > foffset)
dw = fake_write(rbuf, foffset - td->offset, td->offset);
else
dw = fake_write(rbuf, dr, td->offset);
td->offset += dw;
pthread_mutex_lock(&bwritten_mutex);
bwritten += dw;
pthread_mutex_unlock(&bwritten_mutex);
}
return 0;
}
long long calc_offset(long long total, int part, int nthreads) {
return (part * (total / nthreads));
}
int main(int argc, char *argv[]) {
int i;
long long clength;
if (argc < 3) {
return 1;
}
clength = atoi(argv[1]);
nthreads = atoi(argv[2]);
for (i = 0; i < nthreads; ++i) {
long long soffset = calc_offset(clength, i, nthreads);
long long foffset = calc_offset(clength, i + 1, nthreads);
wthread[i].soffset = soffset;
wthread[i].foffset = (i == nthreads - 1 ? clength : foffset);
pthread_create(&(wthread[i].tid), 0,
(void *(*)(void *))http_get, &(wthread[i]));
}
for (i = 0; i < nthreads; ++i)
pthread_join(wthread[i].tid, 0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t patron[90], theaterMan;
pthread_mutex_t Entrance, Exit;
sem_t Seats;
void wander () { sleep (2 + (rand() % 4)); }
void *patronJob (void *id) {
long myNo = (long)id;
int gotSeat;
while (1) {
do {
wander ();
} while (0 != pthread_mutex_trylock (&Entrance));
printf ("%-16ld: %-6ld: Got lock on Entrance\\n", time (0), myNo);
gotSeat = sem_trywait (&Seats);
pthread_mutex_unlock (&Entrance);
printf ("%-16ld: %-6ld: Released lock on Entrance\\n", time (0), myNo);
if (gotSeat == 0) {
printf ("%-16ld: %-6ld: Got a Seat\\n", time (0), myNo);
pthread_mutex_lock (&Exit);
printf ("%-16ld: %-6ld: Exit is Open\\n", time (0), myNo);
sem_post (&Seats);
pthread_mutex_unlock (&Exit);
printf ("%-16ld: %-6ld: Out of Hall\\n", time (0), myNo);
} else {
printf ("%-16ld: %-6ld: Failed to get a seat\\n", time (0), myNo);
}
}
}
void *theaterManJob (void *id) {
int i, emptySeats = 10;
for (i=0; i<5; i++) {
pthread_mutex_unlock (&Entrance);
printf ("%-16ld: %-6s: Opened the Entrance\\n", time (0), "Owner");
while (emptySeats > 0) {
sem_getvalue (&Seats, &emptySeats);
sleep (2);
}
printf ("%-16ld: %-6s: Theater is full\\n", time (0), "Owner");
pthread_mutex_lock (&Entrance);
printf ("%-16ld: %-6s: Show %d Started\\n", time (0), "Owner", i);
sleep (0);
printf ("%-16ld: %-6s: Show %d finished\\n", time (0), "Owner", i);
pthread_mutex_unlock (&Exit);
printf ("%-16ld: %-6s: Opened Exit\\n", time (0), "Owner");
while (emptySeats < 10) {
sem_getvalue (&Seats, &emptySeats);
sleep (2);
}
printf ("%-16ld: %-6s: Theater is empty\\n", time (0), "Owner");
pthread_mutex_lock (&Exit);
printf ("%-16ld: %-6s: Closed Exit\\n", time (0), "Owner");
}
}
int main (void) {
int i;
srand (time(0));
sem_init (&Seats, 0, 10);
pthread_mutex_init (&Entrance, 0);
pthread_mutex_init (&Exit, 0);
pthread_mutex_lock (&Entrance);
pthread_mutex_lock (&Exit);
pthread_create (&theaterMan, 0, theaterManJob, 0);
for (i=0; i<90; i++)
pthread_create ((patron+i), 0, patronJob, (void *)(long)i);
pthread_join (theaterMan, 0);
for (i=0; i<90; i++) {
pthread_cancel (patron[i]);
pthread_join (patron[i], 0);
}
sem_destroy (&Seats);
pthread_mutex_destroy (&Entrance);
pthread_mutex_destroy (&Exit);
return 0;
}
| 0
|
#include <pthread.h>
int available_resources = 5;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *partC(void*);
void increase_count(int);
void decrease_count(int);
int main(int argc, char *argv[]){
if (argc != 2){
printf("incorrect number of arguments.");
return -1;
}
int num_threads = atoi(argv[1]);
int i = 0;
int resources_requested = 0;
pthread_t threads[num_threads];
pthread_attr_t threadAttributes;
pthread_attr_init(&threadAttributes);
for(i=0;i<num_threads;i++){
resources_requested = (rand()%5)+1;
pthread_create(&threads[i],&threadAttributes,partC,(void *)resources_requested);
}
for(i=0;i<num_threads;i++){
pthread_join(threads[i],0);
}
pthread_mutex_destroy(&mutex);
pthread_exit(0);
return 0;
}
void* partC(void *resources){
pthread_mutex_lock(&mutex);
decrease_count((int)resources);
printf("Taking %d resources current count = %d\\n",(int)resources,(int)available_resources);
sleep(rand()%5);
increase_count((int)resources);
printf("Returning %d resources current count = %d\\n",(int)resources,(int)available_resources);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void increase_count(int count)
{
available_resources = available_resources + count;
pthread_cond_broadcast(&cond);
}
void decrease_count(int count)
{
if (available_resources < count)
{
pthread_cond_wait(&cond, &mutex);
}
available_resources = available_resources - count;
}
| 1
|
#include <pthread.h>
pthread_cond_t cond_tick;
pthread_mutex_t mutex_tick;
int capture_state = 2;
extern struct branch branches[BRANCH_NUM];
timer_t timerid;
int sync()
{
int retval = 0;
struct itimerspec its;
int i;
int expected_fn;
int current_fn;
unsigned long expire;
for (i = 0; i < BRANCH_NUM; i++) {
if (branches[i].is_connected == FALSE)
continue;
retval = ioctl(branches[i].devfd, USB_SEMG_GET_EXPECTED_FRAME_NUMBER, 0);
if (retval < 0) {
branches[i].is_connected = FALSE;
DebugError("branches%d ioctl: get expected_fn failed in %s, retval: %d\\n", i, __func__, retval);
exit(1);
} else {
expected_fn = retval;
retval = ioctl(branches[i].devfd, USB_SEMG_GET_CURRENT_FRAME_NUMBER, 0);
if (retval < 0) {
branches[i].is_connected = FALSE;
DebugError("branches%d ioctl: get current_fn failed in %s, retval: %d\\n", i, __func__, retval);
exit(1);
} else {
current_fn = retval;
break;
}
}
}
if (i == BRANCH_NUM) {
DebugError("get no expected_fn failed in%s\\n", __func__);
exit(1);
}
expire = (expected_fn + 1028 - current_fn) % 1024;
expire = expire * 1000000;
its.it_value.tv_sec = expire / 1000000000;
its.it_value.tv_nsec = expire % 1000000000;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
if ((expire/1000000) < root_dev.period/2) {
DebugError("not enough time to process, skip this turn\\n");
retval = -2;
}
printf("expected_fn:%4d, current_fn:%4d,expire: %3ldms\\n", expected_fn, current_fn, expire/1000000);
if (timer_settime (timerid, 0, &its, 0) == -1) {
perror("timer_settime2 error");
retval = -1;
return retval;
}
return retval;
}
void timeout_info(int signo)
{
if (sync() < 0 )
return;
pthread_mutex_lock(&mutex_tick);
if (capture_state == 1) {
DebugError("danger:still proccessing\\n");
}
if (capture_state == 0) {
DebugError("fatal:why no processing\\n");
}
capture_state = 0;
pthread_cond_signal(&cond_tick);
pthread_mutex_unlock(&mutex_tick);
}
void init_sigaction(void)
{
struct sigaction act;
act.sa_handler = timeout_info;
act.sa_flags = 0;
act.sa_flags |= SA_RESTART;
sigemptyset(&act.sa_mask);
sigaction(SIGUSR1, &act, 0);
}
int init_timer(void)
{
int retval = -1;
struct sigevent sev;
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = SIGUSR1;
sev.sigev_value.sival_ptr = &timerid;
sev.sigev_notify_attributes = 0;
if ((retval = timer_create (CLOCK_REALTIME, &sev, &timerid)) < 0)
{
perror("timer_create, error");
return retval;
}
struct itimerspec its;
its.it_value.tv_sec = 1;
its.it_value.tv_nsec = 0;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
if ((retval = timer_settime (timerid, 0, &its, 0) == -1)) {
perror("timer_settime error");
return retval;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mymutex2 ;
pthread_cond_t mycond2 ;
pthread_mutex_t mymutex3 ;
pthread_cond_t mycond3 ;
void *thread1(void *);
void *thread2(void *);
int i=1;
void maketimeout(struct timespec *tsp, long seconds)
{
struct timeval now;
gettimeofday(&now, 0);
tsp->tv_sec = now.tv_sec;
tsp->tv_nsec = now.tv_usec * 1000;
tsp->tv_sec += seconds;
}
void *thread1(void *junk)
{
for(i=1;i<=6;i++)
{
pthread_mutex_lock(&mutex);
printf("thread1: lock %d\\n", 36);
if(i%3==0){
printf("thread1:signal 1 %d\\n", 38);
pthread_cond_signal(&cond);
printf("thread1:signal 2 %d\\n", 40);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("thread1: unlock %d\\n\\n", 44);
sleep(1);
}
}
void *thread2(void *junk)
{
while(i<6)
{
pthread_mutex_lock(&mutex);
printf("thread2: lock %d\\n", 54);
if(i%3!=0){
printf("thread2: wait 1 %d\\n", 56);
pthread_cond_wait(&cond,&mutex);
printf("thread2: wait 2 %d\\n", 58);
}
pthread_mutex_unlock(&mutex);
printf("thread2: unlock %d\\n\\n", 61);
sleep(1);
}
}
void *thread3(void *junk)
{
printf("thread3: sleep 1s \\n");
sleep(1);
pthread_mutex_lock(&mymutex2);
printf("thread3: locked and signaling\\n");
pthread_cond_signal(&mycond2);
pthread_mutex_unlock(&mymutex2);
printf("thread3: unlocked \\n");
}
void *thread4(void *junk)
{
pthread_mutex_lock(&mymutex2);
printf("thread4: locked and wait cond...\\n");
pthread_cond_wait(&mycond2,&mymutex2);
printf("thread4: condition to be true \\n");
pthread_mutex_unlock(&mymutex2);
printf("thread4: unlocked \\n");
}
void *thread5(void *junk)
{
int ret;
printf("thread5: sleep 1s sleeping... \\n");
sleep(1);
pthread_mutex_lock(&mymutex3);
printf("thread5: locked, cond signaling... \\n");
ret = pthread_cond_signal(&mycond3);
pthread_mutex_unlock(&mymutex3);
printf("thread5: unlocked cond ret:%d\\n",ret);
}
void *thread6(void *junk)
{
struct timespec timeout;
int ret;
printf("thread6: sleep 2s sleeping... \\n");
sleep(2);
pthread_mutex_lock(&mymutex3);
printf("thread6: locked and wait cond(timeout 3s)... \\n");
maketimeout(&timeout,3);
ret = pthread_cond_timedwait(&mycond3,&mymutex3,&timeout);
if(0 == ret) {
printf("thread6: condition to be true \\n");
} else {
if(ETIMEDOUT == ret)
printf("thread6: condition timeout \\n");
}
pthread_mutex_unlock(&mymutex3);
printf("thread6: unlocked cond ret:%d\\n",ret);
}
int pthread_cond_eg01(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a,0,thread1,(void *)0);
pthread_create(&t_b,0,thread2,(void *)0);
pthread_join(t_a, 0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
return 0;
}
int pthread_cond_eg02(void)
{
pthread_t t_a;
pthread_t t_b;
printf("\\n----> pthread cond test 2 \\n");
pthread_mutex_init(&mymutex2, 0);
pthread_cond_init(&mycond2, 0);
pthread_create(&t_a,0,thread3,(void *)0);
pthread_create(&t_b,0,thread4,(void *)0);
pthread_join(t_a, 0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mymutex2);
pthread_cond_destroy(&mycond2);
return 0;
}
int pthread_cond_eg03(void)
{
pthread_t t_a;
pthread_t t_b;
printf("\\n----> pthread cond test 3 \\n");
pthread_mutex_init(&mymutex3, 0);
pthread_cond_init(&mycond3, 0);
pthread_create(&t_a,0,thread5,(void *)0);
pthread_create(&t_b,0,thread6,(void *)0);
pthread_join(t_a, 0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mymutex3);
pthread_cond_destroy(&mycond3);
return 0;
}
int main()
{
pthread_cond_eg02();
pthread_cond_eg03();
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutexattr_t mutex_attr;
pthread_mutex_t mutex;
struct to_info{
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
static void object_fun(void *arg)
{
printf("%d\\n", 21);
pthread_mutex_lock(&mutex);
printf("%d\\n", 23);
pthread_mutex_lock(&mutex);
printf("%d\\n", 25);
printf("%s\\n", (char *)arg);
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&mutex);
}
static void *timeout_helper(void *arg)
{
int ret;
struct to_info *tip;
tip = (struct to_info*)arg;
printf("clock_nanosleep will be wait -->sec:%ld nsec:%ld\\n", tip->to_wait.tv_sec,
tip->to_wait.tv_nsec);
ret = clock_nanosleep(CLOCK_REALTIME, 0, &(tip->to_wait), 0);
(*tip->to_fn)(tip->to_arg);
free(arg);
return 0;
}
static int makedetachpthread(void *(*fn)(void *), void *arg)
{
int err;
pthread_t tid;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if(err != 0){
return err;
}
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if(err == 0)
pthread_create(&tid, &attr, fn, arg);
pthread_attr_destroy(&attr);
return err;
}
static void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct to_info *tip;
int err;
clock_gettime(CLOCK_REALTIME, &now);
if((when->tv_sec > now.tv_sec) || ((when->tv_sec > now.tv_sec) && (when->tv_nsec > now.tv_nsec))){
tip = (struct to_info*)malloc(sizeof(struct to_info));
if(tip != 0){
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if(when->tv_nsec >= now.tv_nsec)
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_sec;
else{
tip->to_wait.tv_sec--;
tip->to_wait.tv_nsec = 100000000 + when->tv_nsec - now.tv_nsec;
}
}
err = makedetachpthread(timeout_helper, (void *)tip);
if(err == 0)
return;
else
free(tip);
return;
}
(*func)(arg);
}
int main(int argc, char const *argv[])
{
int err;
char *arg = "hello world!";
struct timespec when;
if((err = pthread_mutexattr_init(&mutex_attr)) != 0){
perror("pthread_mutexattr_init error");
return -1;
}
if((err = pthread_mutexattr_settype(&mutex_attr, PTHREAD_MUTEX_RECURSIVE)) != 0){
perror("pthread_mutexattr_settype error");
return -1;
}
if((err = pthread_mutex_init(&mutex, &mutex_attr)) != 0){
perror("pthread_mutex_init error");
return -1;
}
pthread_mutex_lock(&mutex);
clock_gettime(CLOCK_REALTIME, &when);
when.tv_sec += 6;
timeout(&when, object_fun, (void *)arg);
pthread_mutex_unlock(&mutex);
sleep(10);
return 0;
}
| 0
|
#include <pthread.h>
int BUFF_SIZE = 512;
int QUEUE_SIZE = 32;
char *queue;
char *next_pop;
char *next_push;
pthread_mutex_t lock;
int inc_pop()
{
pthread_mutex_lock(&lock);
if (next_pop >= queue + (BUFF_SIZE * QUEUE_SIZE)) {
next_pop = queue;
} else {
next_pop += BUFF_SIZE;
}
pthread_mutex_unlock(&lock);
}
int inc_push()
{
pthread_mutex_lock(&lock);
if (next_push >= queue + (BUFF_SIZE * QUEUE_SIZE)) {
next_push = queue;
} else {
next_push += BUFF_SIZE;
}
pthread_mutex_unlock(&lock);
}
int is_cmd_avail()
{
int res;
pthread_mutex_lock(&lock);
res = (next_pop == next_push);
pthread_mutex_unlock(&lock);
}
char *next_command()
{
char *res;
pthread_mutex_lock(&lock);
if (next_pop == next_push)
{
res =0;
} else {
res = next_pop;
next_pop += BUFF_SIZE;
}
pthread_mutex_unlock(&lock);
return res;
}
void* worker(void *arg){
static FILE *CmdFile;
char *CmdLine;
static double CmdTime = 0.0;
long NewCmdProcessed;
while (CmdTime >= 0.0) {
CmdLine = next_push;
printf("loop a\\n");
CmdFile = fopen("cmdfifo","rt");
int fd = fileno(CmdFile);
fgets(CmdLine,BUFF_SIZE,CmdFile);
sscanf(CmdLine,"%lf",&CmdTime);
printf("Cmdtime: %f \\n", CmdTime);
fclose(CmdFile);
inc_push();
}
return 0;
}
void main(int argc, char **argv)
{
pthread_mutex_init(&lock, 0);
queue = (char *)malloc(sizeof(char) * BUFF_SIZE * QUEUE_SIZE);
next_push = queue;
next_pop = queue;
pthread_t t;
pthread_create(&t, 0, &worker, 0);
while(1) {
printf("mainloop\\n");
sleep(1);
char *next_cmd = next_command();
printf("checked next cmd\\n");
if (next_cmd){
printf("nextcmd: %s\\n", next_cmd);
}
}
}
| 1
|
#include <pthread.h>
void *produce(void* arg) {
for (;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nputs >= nitems) {
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.nputs] = shared.nval;
shared.nputs++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int*) arg) += 1;
}
return 0;
}
void *consume(void* arg) {
int i;
for (i = 0; i< nitems; i++) {
if (shared.buff[i] != i) {
printf("consume thread check failed: %d is an error number\\n", i);
}
}
return 0;
}
| 0
|
#include <pthread.h>
int A[10*3], B[10*3], LOG[3];
int RIS;
pthread_mutex_t lock;
void * single_thread(void * t)
{
int tid = (int) t;
int start = tid * 10;
int somma = 0;
for(int i = start; i < start + 10; i++)
somma += A[i] * B[i];
pthread_mutex_lock(&lock);
RIS+=somma;
LOG[tid] = tid;
pthread_mutex_unlock(&lock);
return 0;
}
int main(int argc, const char * argv[])
{
int i;
void* status;
int result;
pthread_t threads[3];
printf("Thread principale avviato con valori: M = %d, K = %d, N = %d\\n", 3, 10, 10*3);
srand((unsigned int)time(0));
printf("Creo i vettori\\n");
for(i = 0; i < 10*3; i++)
{
A[i] = rand() % 100;
B[i] = rand() % 100;
}
if(pthread_mutex_init(&lock, 0)!=0)
{
printf("Failed to create mutex\\n");
exit(-1);
}
for(i = 0; i < 3; i++)
{
result = pthread_create(&threads[i], 0, single_thread, (void *)(intptr_t) i);
if(result)
{
printf("ERRORE codice: %d\\n", result);
exit(-1);
}
}
for(i = 0; i < 3; i++)
{
result = pthread_join(threads[i], &status);
if(result)
printf("Errore nel join del thread %d\\n",i);
}
pthread_mutex_destroy(&lock);
printf("Contenuto di LOG: ");
for(i = 0; i < 3; i++)
printf("LOG[%d] = %d, ", i, LOG[i]);
printf("\\nRisultato del prodotto scalare tra A e B = %d\\n", RIS);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int cnt;
void espera_activa( int tiempo) {
time_t t;
t = time(0) + tiempo;
while(time(0) < t);
}
void *tareaA( void * args) {
printf("tareaA::voy a dormir\\n");
sleep(3);
printf("tareaA::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("tareaA::incremento valor\\n");
++cnt;
printf("tareaA::desbloqueo mutex\\n");
pthread_mutex_unlock(&mutex);
printf("tareaA::FINISH\\n");
}
void *tareaM( void * args) {
printf("\\ttareaM::me voy a dormir\\n");
sleep(5);
printf("\\ttareaM::me despierto y hago espera activa\\n");
espera_activa(15);
printf("\\ttareaM::FINSIH\\n");
}
void *tareaB( void * args) {
printf("\\t\\ttareaB::me voy a dormir\\n");
sleep(1);
printf("\\t\\ttareaB::me despierto y pillo mutex\\n");
pthread_mutex_lock(&mutex);
printf("\\t\\ttareaB::espera activa\\n");
espera_activa(7);
printf("\\t\\ttareaB::incremento cnt\\n");
++cnt;
printf("\\t\\ttareaB::suelto mutex\\n");
pthread_mutex_unlock(&mutex);
printf("\\t\\ttareaB::FINISH\\n");
}
int main() {
pthread_t hebraA, hebraM, hebraB;
pthread_attr_t attr;
pthread_mutexattr_t attrM;
struct sched_param prio;
cnt = 0;
pthread_mutexattr_init(&attrM);
if( pthread_mutexattr_setprotocol(&attrM, PTHREAD_PRIO_PROTECT) != 0) {
printf("ERROR en __set_protocol\\n");
exit(-1);
}
if( pthread_mutexattr_setprioceiling(&attrM, 3) != 0){
printf("ERROR en __setprioceiling\\n");
}
pthread_mutex_init(&mutex, &attrM);
if( pthread_attr_init( &attr) != 0) {
printf("ERROR en __attr_init\\n");
exit(-1);
}
if( pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED) != 0){
printf("ERROR __setinheritsched\\n");
exit(-1);
}
if( pthread_attr_setschedpolicy( &attr, SCHED_FIFO) != 0) {
printf("ERROR __setschedpolicy\\n");
exit(-1);
}
int error;
prio.sched_priority = 1;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam %d\\n", error);
exit(-1);
}
if( (error=pthread_create(&hebraB, &attr, tareaB, 0)) != 0) {
printf("ERROR __pthread_create \\ttipo: %d\\n", error);
exit(-1);
}
prio.sched_priority = 2;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraM, &attr, tareaM, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
prio.sched_priority = 3;
if( pthread_attr_setschedparam(&attr, &prio) != 0) {
printf("ERROR __attr_setschedparam\\n");
exit(-1);
}
if( pthread_create(&hebraA, &attr, tareaA, 0) != 0) {
printf("ERROR __pthread_create\\n");
exit(-1);
}
pthread_join(hebraA, 0);
pthread_join(hebraM, 0);
pthread_join(hebraB, 0);
return 0;
}
| 0
|
#include <pthread.h>
int quitflag;sigset_t mask;
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait1=PTHREAD_COND_INITIALIZER;
void* thr_fn(void*arg)
{
int err,signo;
while(1)
{
if((err=sigwait(&mask,&signo))!=0) err_quit("sigwait failed\\n");
switch(signo)
{
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
printf("quit\\n");
pthread_mutex_lock(&lock);
quitflag=1;printf("quit2\\n");
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait1);
return 0;
default:
printf("unexpected signal %d\\n",signo);
exit(1);
}
}
}
int main()
{
int err;sigset_t oldmask;pthread_t tid;
sigemptyset(&mask);sigaddset(&mask,SIGINT);sigaddset(&mask,SIGQUIT);
if((err=pthread_sigmask(SIG_BLOCK,&mask,&oldmask))!=0) err_quit("SIGBLOCK error\\n");
if((err=pthread_create(&tid,0,thr_fn,0))!=0) err_quit("can't create thread\\n");
pthread_mutex_lock(&lock);
printf("enter %d\\n",quitflag);
while(quitflag==0) pthread_cond_wait(&wait1,&lock);
pthread_mutex_unlock(&lock);
quitflag=0;
if(sigprocmask(SIG_SETMASK,&oldmask,0)<0) err_sys("SIG_SETMASK error\\n");
exit(0);
}
| 1
|
#include <pthread.h>
void *Producer(void *);
void *Consumer(void *);
pthread_cond_t condp;
pthread_cond_t condc;
pthread_mutex_t mutex;
int g_data[10];
int g_idx;
int main(void) {
pthread_t pid, cid;
pthread_cond_init(&condp, 0);
pthread_cond_init(&condc, 0);
pthread_mutex_init(&mutex,0);
printf("main started\\n");
pthread_create(&pid, 0, Producer, 0);
pthread_create(&cid, 0, Consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
printf("main done\\n");
return 0;
}
void *Producer(void *arg) {
int i=0,j;
while(i < 200) {
usleep(rand()%100000);
pthread_mutex_lock(&mutex);
while(g_idx==10 -1)
pthread_cond_wait(&condp,&mutex);
g_data[g_idx]=1;
g_idx++;
j=0; printf("(Producer, buffer index is %d)\\t", g_idx);
while(j < g_idx) { j++; printf("="); } printf("\\n");
pthread_cond_signal(&condc);
pthread_mutex_unlock(&mutex);
i++;
}
return 0;
}
void *Consumer(void *arg) {
int i=0,j;
while(i < 200) {
usleep(rand()%100000);
pthread_mutex_lock(&mutex);
while(g_idx==0)
pthread_cond_wait(&condc,&mutex);
g_data[g_idx-1]=0;
g_idx--;
j=0; printf("(Consumer, buffer index is %d)\\t", g_idx);
while(j < g_idx) { j++; printf("="); } printf("\\n");
pthread_cond_signal(&condp);
pthread_mutex_unlock(&mutex);
i++;
}
return 0;
}
| 0
|
#include <pthread.h>
buffer_item buffer[6];
int index_counter = 0;
void *thread_Insert(void *arg);
void *thread_Remove(void *arg);
sem_t bin_sem;
pthread_mutex_t mutx;
char thread1[]="Thread A";
char thread2[]="Thread B";
char thread3[]="Thread C";
int main(int argc, char **argv)
{
pthread_t t1, t2, t3;
void *thread_result;
int state1, state2;
state1 = pthread_mutex_init(&mutx, 0);
state2 = sem_init(&bin_sem, 0 ,0);
if(state1||state2!=0)
puts("Error mutex & semaphore initialization!!!");
pthread_create(&t1, 0, thread_Insert, &thread1);
pthread_create(&t2, 0, thread_Remove, &thread2);
pthread_create(&t3, 0, thread_Remove, &thread3);
pthread_join(t1, &thread_result);
pthread_join(t2, &thread_result);
pthread_join(t3, &thread_result);
printf("Terminate => %s, %s, %s!!!\\n", &thread1, &thread2, &thread3);
printf("Final Index: %d\\n", index_counter);
sem_destroy(&bin_sem);
pthread_mutex_destroy(&mutx);
return 0;
}
void *thread_Insert(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0;i<6;i++)
{
pthread_mutex_lock(&mutx);
if(index_counter<6)
{
buffer[index_counter] = index_counter;
index_counter++;
printf("%s: INSERT item to BUFFER %d\\n", (char*)arg, index_counter);
sem_post(&bin_sem);
}
else
{
sleep(2);
}
pthread_mutex_unlock(&mutx);
}
}
void *thread_Remove(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0;i<6/2;i++)
{
sem_wait(&bin_sem);
pthread_mutex_lock(&mutx);
sleep(1);
printf("%s: REMOVE item from BUFFER %d\\n", (char*)arg, index_counter);
buffer[index_counter] = 0;
index_counter--;
pthread_mutex_unlock(&mutx);
}
}
| 1
|
#include <pthread.h>
static void * SafeQueue_head(struct SafeQueue * self) {
pthread_mutex_lock(& self->mutex);
void * head = self->queue->head(self->queue);
pthread_mutex_unlock(& self->mutex);
return head;
}
static bool SafeQueue_pop(struct SafeQueue * self, void ** head) {
pthread_mutex_lock(& self->mutex);
bool b = self->queue->pop(self->queue, head);
pthread_mutex_unlock(& self->mutex);
return b;
}
static bool SafeQueue_push(struct SafeQueue * self, void * elem) {
pthread_mutex_lock(& self->mutex);
bool b = self->queue->push(self->queue, elem);
pthread_mutex_unlock(& self->mutex);
return b;
}
static int SafeQueue_size(struct SafeQueue * self) {
pthread_mutex_lock(& self->mutex);
int s = self->queue->size(self->queue);
pthread_mutex_unlock(& self->mutex);
return s;
}
static bool SafeQueue_is_empty(struct SafeQueue * self) {
pthread_mutex_lock(& self->mutex);
bool e = self->queue->is_empty(self->queue);
pthread_mutex_unlock(& self->mutex);
return e;
}
static bool SafeQueue_is_full(struct SafeQueue * self) {
pthread_mutex_lock(& self->mutex);
bool f = self->queue->is_full(self->queue);
pthread_mutex_unlock(& self->mutex);
return f;
}
static void * SafeQueue_constructor(void * _self, va_list * args) {
struct SafeQueue * self = _self;
self->head = SafeQueue_head;
self->pop = SafeQueue_pop;
self->push = SafeQueue_push;
self->size = SafeQueue_size;
self->is_empty = SafeQueue_is_empty;
self->is_full = SafeQueue_is_full;
int type = __builtin_va_arg((* args));
int size = __builtin_va_arg((* args));
self->queue = new(Queue, type, size);
pthread_mutex_init(& self->mutex, 0);
return self;
}
static void * SafeQueue_destructor(void * _self) {
struct SafeQueue * self = _self;
delete(self->queue);
pthread_mutex_destroy(& self->mutex);
return self;
}
static bool SafeQueue_equals(void * self, void * other) {
return self == other;
}
static const struct Class _SafeQueue = {
sizeof(struct SafeQueue),
SafeQueue_constructor,
SafeQueue_destructor,
SafeQueue_equals
};
const void * SafeQueue = & _SafeQueue;
| 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 *idp)
{
int j,i;
double result=0.0;
int *my_id = idp;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %d, count = %d Threshold reached.\\n", *my_id, count);
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\\n", *my_id, count);
pthread_mutex_unlock(&count_mutex);
for (j=0; j<1000; j++)
result = result + (double)random();
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
int *my_id = idp;
printf("Starting watch_count(): thread %d\\n", *my_id);
pthread_mutex_lock(&count_mutex);
if (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal received.\\n", *my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int gift_count = 26000;
pthread_mutex_t gift_count_lock = PTHREAD_MUTEX_INITIALIZER;
void* bring_gifts(void* box)
{
int i = 0;
int limit = 1000;
for (; i < limit; i++) {
pthread_mutex_lock(&gift_count_lock);
gift_count -= 1;
pthread_mutex_unlock(&gift_count_lock);
}
printf("Gifts - %i\\n", gift_count);
return 0;
}
int main(int argc, char const *argv[])
{
pthread_t threads[20];
int t = 0;
int limit = 20;
printf("%i gifts are in the shop.\\n", gift_count);
for (; t < limit; t++) {
pthread_create(&threads[t], 0, bring_gifts, 0);
}
t = 0;
void* result;
for(; t < limit; t++) {
pthread_join(threads[t], &result);
}
printf("Many customers buy boxes with gifts.\\nNow there are just %i gifts in the shop.\\n", gift_count);
return 0;
}
| 0
|
#include <pthread.h>
enum reorder { SORT, SHUFFLE };
struct int_list_s *next_node;
int val;
} int_list;
int_list *first_node;
} int_list_head;
int_list_head *head;
pthread_mutex_t *mutex;
int val;
unsigned int sleep_time;
} pthread_push_context;
void *_pthread_push(void *arg)
{
pthread_push_context *ctx;
int_list_head *head;
int_list *node;
ctx = (pthread_push_context *)arg;
head = ctx->head;
sleep(ctx->sleep_time);
pthread_mutex_lock(ctx->mutex);
if (head->first_node == 0) {
node = (int_list *)malloc(sizeof(int_list));
node->next_node = 0;
head->first_node = node;
} else {
node = head->first_node;
while (node->next_node) {
node = node->next_node;
}
node->next_node = (int_list *)malloc(sizeof(int_list));
node->next_node->next_node = 0;
node = node->next_node;
}
node->val = ctx->val;
pthread_mutex_unlock(ctx->mutex);
free(arg);
return 0;
}
void _sleep_reorder(enum reorder order, int *elements, size_t num_elements)
{
size_t i;
int rv;
pthread_push_context *ctx;
pthread_t *threads;
int_list_head *pos_list, *neg_list;
int_list *node;
pthread_mutex_t *mutex;
const pthread_mutexattr_t *attr = 0;
threads = (pthread_t *) malloc(num_elements * sizeof(pthread_t));
if (!threads) {
exit(1);
}
pos_list = (int_list_head *)malloc(sizeof(int_list_head));
if (!pos_list) {
exit(1);
}
pos_list->first_node = 0;
neg_list = (int_list_head *)malloc(sizeof(int_list_head));
if (!neg_list) {
exit(1);
}
neg_list->first_node = 0;
mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (!mutex) {
exit(1);
}
rv = pthread_mutex_init(mutex, attr);
if (rv) {
fprintf(stderr, "pthread_mutex_init() returned: %d\\n", rv);
exit(1);
}
for (i = 0; i < num_elements; i++) {
ctx = (pthread_push_context *)
malloc(sizeof(pthread_push_context));
ctx->mutex = mutex;
ctx->val = elements[i];
switch (order) {
case SHUFFLE:
ctx->head = pos_list;
ctx->sleep_time = rand() % num_elements;
break;
case SORT:
if (elements[i] >= 0) {
ctx->head = pos_list;
ctx->sleep_time = elements[i];
} else {
ctx->head = neg_list;
ctx->sleep_time = -1 * elements[i];
}
break;
}
rv = pthread_create(&(threads[i]), 0, _pthread_push, ctx);
if (rv) {
fprintf(stderr, "pthread_create() returned: %d\\n", rv);
exit(1);
}
}
for (i = 0; i < num_elements; i++) {
pthread_join(threads[i], 0);
}
free(threads);
rv = pthread_mutex_destroy(mutex);
if (rv) {
fprintf(stderr, "pthread_mutex_destroy() returned: %d\\n", rv);
}
free(mutex);
while (neg_list->first_node) {
node = neg_list->first_node;
neg_list->first_node = node->next_node;
node->next_node = pos_list->first_node;
pos_list->first_node = node;
}
free(neg_list);
if (pos_list->first_node) {
node = pos_list->first_node;
for (i = 0; i < num_elements; i++) {
elements[i] = node->val;
node = node->next_node;
}
while (pos_list->first_node->next_node) {
node = pos_list->first_node->next_node;
pos_list->first_node->next_node = node->next_node;
free(node);
}
free(pos_list->first_node);
}
free(pos_list);
}
void sleep_sort(int *elements, size_t num_elements)
{
_sleep_reorder(SORT, elements, num_elements);
}
void _sleep_shuffle(int *elements, size_t num_elements)
{
_sleep_reorder(SHUFFLE, elements, num_elements);
}
void _shuffle(int *elements, size_t num_elements)
{
size_t i, pos;
int swap;
for (i = 0; i < num_elements; i++) {
pos = rand() % num_elements;
swap = elements[i];
elements[i] = elements[pos];
elements[pos] = swap;
}
}
void _random_sort(void (*shuffle_func) (int *elements, size_t num_elements),
int *elements, size_t num_elements)
{
size_t i;
int last;
int sorted = 0;
while (!sorted) {
shuffle_func(elements, num_elements);
sorted = 1;
last = INT_MIN;
for (i = 0; i < num_elements; i++) {
if (elements[i] < last) {
sorted = 0;
}
last = elements[i];
}
}
}
void random_sort(int *elements, size_t num_elements)
{
_random_sort(_shuffle, elements, num_elements);
}
void random_sleep_sort(int *elements, size_t num_elements)
{
_random_sort(_sleep_shuffle, elements, num_elements);
}
| 1
|
#include <pthread.h>
void
ports_resume_bucket_rpcs (struct port_bucket *bucket)
{
pthread_mutex_lock (&_ports_lock);
assert_backtrace (bucket->flags & PORT_BUCKET_INHIBITED);
bucket->flags &= ~PORT_BUCKET_INHIBITED;
if (bucket->flags & PORT_BUCKET_BLOCKED)
{
bucket->flags &= ~PORT_BUCKET_BLOCKED;
pthread_cond_broadcast (&_ports_block);
}
pthread_mutex_unlock (&_ports_lock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int i=1;
int main(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a,0,thread1,(void *)0);
pthread_create(&t_b,0,thread2,(void *)0);
pthread_join(t_a, 0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *junk)
{
sleep(2);
for(i=1;i<=6;i++)
{
printf("thread1, [%d]\\n", i);
pthread_mutex_lock(&mutex);
printf("thread1: lock %d\\n", 33);
if(i%3==0){
printf("thread1:signal 1 %d\\n", 35);
pthread_cond_signal(&cond);
printf("thread1:signal 2 %d\\n", 37);
sleep(1);
}
pthread_mutex_unlock(&mutex);
printf("thread1: unlock %d\\n\\n", 41);
sleep(1);
}
}
void *thread2(void *junk)
{
while(i<6)
{
printf("thread2, [%d]\\n", i);
pthread_mutex_lock(&mutex);
printf("thread2: lock %d\\n", 52);
if(i%3!=0){
printf("thread2: wait 1 %d\\n", 54);
pthread_cond_wait(&cond,&mutex);
printf("thread2: wait 2 %d\\n", 56);
}
pthread_mutex_unlock(&mutex);
printf("thread2: unlock %d\\n\\n", 59);
sleep(1);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
long long sum = 0;
void * counting_thread(void *arg)
{
int offset = *(int *) arg;
pthread_mutex_lock(&mutex);
for (int i = 0; i < 100000000; i++)
{
sum += offset;
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main (void)
{
pthread_t id1;
int offset1 = 1;
pthread_create(&id1, 0, counting_thread, &offset1);
pthread_t id2;
int offset2 = -1;
pthread_create(&id2, 0, counting_thread, &offset2);
pthread_join(id1,0);
pthread_join(id2,0);
printf("Sum = %lld\\n",sum);
return 0;
}
| 0
|
#include <pthread.h>
struct arg_struct{
int lower;
int upper;
};
int NUMOFTHREADS;
double sum;
void *runner(void *param);
int arg;
pthread_mutex_t mutexSum;
int main(int argc, char *argv[])
{
pthread_attr_t attr;
sum = 0.0;
arg = atoi(argv[1]);
int NUMOFTHREADS = 4;
struct arg_struct argsArray[NUMOFTHREADS];
if (argc == 2) {
printf("Call like this: ./FastSum <input> [<num of threads>]\\n\\n");
}
if (argc == 3) {
NUMOFTHREADS = atoi(argv[2]);
}
if (arg < 0) {
fprintf(stderr,"%d must be >= 0\\n", arg);
return -1;
}
struct timeval begin, end;
gettimeofday(&begin, 0);
if(arg > NUMOFTHREADS){
printf("Calculating the sum of sqrt from 1 to %d will be distributed among %d thread(s)\\n", arg, NUMOFTHREADS);
pthread_t joinables[NUMOFTHREADS];
int rest = arg % NUMOFTHREADS;
int evenAmount = (arg - rest) / NUMOFTHREADS;
pthread_mutex_init(&mutexSum, 0);
int i;
for ( i = 0; i < NUMOFTHREADS; i++ )
{
if(i == 0){
argsArray[i].upper = arg;
argsArray[i].lower = arg - ( evenAmount + rest ) + 1;
}else{
argsArray[i].upper = ( arg - rest ) - ( i * evenAmount );
argsArray[i].lower = ( ( arg - rest ) - ( ( ( i + 1 ) * evenAmount ) ) ) + 1;
}
pthread_create(
&joinables[i],
0,
runner,
(void *)&argsArray[i]
);
}
int k;
for(k = 0; k < NUMOFTHREADS; k++){
pthread_join(joinables[k] ,0);
}
pthread_mutex_destroy(&mutexSum);
}else{
printf("Calculating the sum of sqrt from 1 to %d will be performed by 1 thread\\n", arg);
pthread_t tid;
struct arg_struct args;
args.lower = 1;
args.upper = arg;
pthread_create(
&tid,
0,
runner,
(void *)&args
);
pthread_join(tid ,0);
}
gettimeofday(&end, 0);
double diff = (end.tv_sec - begin.tv_sec) + ((end.tv_usec - begin.tv_usec)/1000000.0);
printf("FINAL sum = %f\\n",sum);
printf("Calculations done in %f sec\\n\\n", diff);
}
void *runner(void *param)
{
struct arg_struct *limit;
limit = (struct arg_struct *) param;
int lower = limit->lower;
int upper = limit->upper;
int i;
double tempSum = 0.0;
for (i = lower; i <= upper; i++){
tempSum += sqrt(i);
}
printf("Sum from %d to %d: %f\\n", lower, upper, tempSum);
pthread_mutex_lock(&mutexSum);
sum += tempSum;
pthread_mutex_unlock(&mutexSum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t * mutex_measurements;
pthread_mutex_t * mutex_alerts;
pthread_mutex_t mutex_file = PTHREAD_MUTEX_INITIALIZER;
pthread_t UCR;
pthread_t * list_of_UADS;
int * measurements;
int * alerts;
FILE * f;
void * start_reading(void * attr);
void * start_monitoring();
void write_measurements(int sig_id);
void write_alert(int sig_id);
void quit (int sig_id);
int main(){
printf("------- To Quit press Ctrl-C --------- \\n");
signal(SIGINT,quit);
srand(time(0));
list_of_UADS = (pthread_t *) malloc(5 * sizeof(pthread_t));
mutex_measurements = (pthread_mutex_t *) malloc(5 * sizeof(pthread_mutex_t));
mutex_alerts = (pthread_mutex_t *) malloc(5 * sizeof(pthread_mutex_t));
measurements = (int *) malloc (5 * sizeof(int));
alerts = (int *) malloc (5 * sizeof(int));
f = fopen("measurements.txt", "w+");
int i,j;
pthread_create(&UCR,0,start_monitoring,0);
for(i = 0; i < 5; ++i){
pthread_create(list_of_UADS + i,0,start_reading,(void *) i);
pthread_mutex_init(mutex_measurements + i,0);
*(measurements + i) = 0;
*(alerts + i) = 0;
}
for(j = 0; j < 5; ++j)
pthread_join(*(list_of_UADS+j),0);
fclose(f);
free(list_of_UADS);
free(mutex_measurements);
free(mutex_alerts);
free(measurements);
free(alerts);
return 0;
}
void quit(int sig_id){
fclose(f);
free(list_of_UADS);
free(mutex_measurements);
free(mutex_alerts);
free(measurements);
free(alerts);
exit(0);
}
void * start_monitoring(){
signal(SIGUSR1,write_alert);
signal(SIGALRM,write_measurements);
alarm(rand() % 2 + 4);
while(1){
}
pthread_exit(0);
}
void * start_reading(void * attr){
int measurement;
int UAD = (int) attr;
while(1){
measurement = rand() % (10 + 2) + 1;
pthread_mutex_lock(mutex_measurements + UAD);
*(measurements + UAD) = measurement;
if(measurement >= 10){
pthread_mutex_lock(mutex_alerts + UAD);
*(alerts + UAD) = 1;
pthread_mutex_unlock(mutex_alerts + UAD);
pthread_kill(UCR,SIGUSR1);
}
pthread_mutex_unlock(mutex_measurements + UAD);
sleep(2);
}
pthread_exit(0);
}
void write_measurements(int sig_id){
pthread_mutex_lock(&mutex_file);
if (f == 0)
{
printf("Error opening file!\\n");
return;
}
int i;
for(i = 0; i < 5; ++i){
pthread_mutex_lock(mutex_measurements + i);
printf("Writing measurements\\n");
fprintf(f, "The latest reading on UAD %d is: %d.\\n", i + 1,*(measurements + i));
pthread_mutex_unlock(mutex_measurements + i);
}
pthread_mutex_unlock(&mutex_file);
}
void write_alert(int sig_id){
pthread_mutex_lock(&mutex_file);
if (f == 0)
{
printf("Error opening file!\\n");
return;
}
int i;
for(i = 0; i < 5; ++i){
pthread_mutex_lock(mutex_measurements + i);
pthread_mutex_lock(mutex_alerts + i);
if(*(alerts + i) == 1){
printf("Writing alert\\n");
fprintf(f, "The UAD %d raised an alert: (Measurement is %d) \\n", i + 1,*(measurements+i));
*(alerts+i) = 0;
}
pthread_mutex_unlock(mutex_alerts + i);
pthread_mutex_unlock(mutex_measurements + i);
}
pthread_mutex_unlock(&mutex_file);
alarm(rand() % 2 + 4);
}
| 0
|
#include <pthread.h>
void *log_thread_function(void *arg);
int type;
int len;
}log_item;
int fd;
int total;
int curr;
char* buf;
pthread_mutex_t buf_lock;
pthread_cond_t log_cond;
}log_queue;
log_queue log_que = {-1, 0, 0, 0, PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER};
int init_log(const char* log_file)
{
int ret;
pthread_t tid;
int fd = open(log_file, O_WRONLY | O_CREAT | O_APPEND, 00600);
if(fd < 0) {
syslog(LOG_ERR, "open log file:%s failed", log_file);
return T_FTP_FAIL;
}
syslog(LOG_DEBUG, "in init_log\\n");
log_que.fd = fd;
log_que.buf = (char*)malloc(4 * 1024);
if(log_que.buf == 0) {
syslog(LOG_ERR, "malloc log buf failed");
return T_FTP_FAIL;
}
log_que.total = 4 * 1024;
log_que.curr = 0;
if((ret = pthread_create(&tid, 0, log_thread_function, 0)) != 0) {
syslog(LOG_ERR, "phtread_create:%s\\n", strerror(ret));
return T_FTP_FAIL;
}
return T_FTP_SUCCESS;
}
void* log_thread_function(void* arg)
{
log_item* item;
int len;
int done;
int total_size;
time_t now;
char* p = 0;
char* time_str;
struct iovec iv[3];
char end = '\\n';
char log_type_info[6][12] = {{"LOG_INFO\\t"}, {"LOG_WARING\\t"}, {"LOG_NOTICE\\t"}, {"LOG_ERROR\\t"}, {"LOG_DEBUG\\t"}, {"LOG_CRIT\\t"}};
syslog(LOG_DEBUG, "log thread start\\n");
assert(log_que.fd > 0 && log_que.buf);
while(1) {
pthread_mutex_lock(&log_que.buf_lock);
while(log_que.curr == 0)
pthread_cond_wait(&log_que.log_cond, &log_que.buf_lock);
done = 0;
while(done < log_que.curr) {
p = log_que.buf + done;
item = (log_item*)p;
now = time(0);
time_str = ctime(&now);
len = strlen(time_str);
time_str[len-1] = '\\0';
strcat(time_str, "\\t");
iv[0].iov_len = len;
iv[0].iov_base = (void*)time_str;
iv[1].iov_len = strlen(log_type_info[item->type]);
iv[1].iov_base = (void*)log_type_info[item->type];
iv[2].iov_len = item->len;
iv[2].iov_base = p + sizeof(log_item);
if(iv[2].iov_len <= 0) {
iv[2].iov_len = 1;
iv[2].iov_base = &end;
}
total_size = iv[0].iov_len + iv[1].iov_len + iv[2].iov_len;
while(total_size > 0) {
if((len = writev(log_que.fd, iv, 3)) < 0) {
if(errno == EINTR)
continue;
syslog(LOG_WARNING, "error occured:%s when write log", strerror(errno));
pthread_mutex_unlock(&log_que.buf_lock);
return 0;
}
total_size -= len;
}
done += sizeof(log_item) + item->len;
}
log_que.curr = 0;
pthread_mutex_unlock(&log_que.buf_lock);
}
return 0;
}
void tftp_log(int log_mod, const char* str, ...)
{
int len;
char* p;
va_list list;
pthread_mutex_lock(&log_que.buf_lock);
p = log_que.buf + log_que.curr;
*((int*)p) = log_mod;
__builtin_va_start((list));
len = vsprintf(p + sizeof(log_item), str, list);
;
*((int*)(p + sizeof(int))) = len;
if(log_que.curr == 0)
pthread_cond_signal(&log_que.log_cond);
log_que.curr += len + sizeof(log_item);
pthread_mutex_unlock(&log_que.buf_lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mx, my;
int x=2, y=2;
void *thread1() {
int a;
pthread_mutex_lock(&mx);
a = x;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
a = a + 1;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
x = x + x + a;
pthread_mutex_unlock(&mx);
assert(x!=207);
return 0;
}
void *thread2() {
pthread_mutex_lock(&mx);
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
pthread_mutex_unlock(&mx);
return 0;
}
void *thread3() {
pthread_mutex_lock(&my);
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
pthread_mutex_unlock(&my);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mx, 0);
pthread_mutex_init(&my, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_create(&t3, 0, thread3, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mx);
pthread_mutex_destroy(&my);
return 0;
}
| 0
|
#include <pthread.h>
static int bloom_table[1000000] = {0};
pthread_mutex_t bt_lock = PTHREAD_MUTEX_INITIALIZER;
static unsigned int encrypt(char *key, unsigned int id)
{
unsigned int val = 0;
switch(id){
case 0:
val = times33(key); break;
case 1:
val = timesnum(key,31); break;
case 2:
val = aphash(key); break;
case 3:
val = hash16777619(key); break;
case 4:
val = mysqlhash(key); break;
case 5:
val = crc32((unsigned char *)key, strlen(key));
break;
case 6:
val = timesnum(key,131); break;
case 7:
val = timesnum(key,1313); break;
default:
abort();
}
return val;
}
int search(char *url)
{
unsigned int h, i, index, pos;
int res = 0;
pthread_mutex_lock(&bt_lock);
for (i = 0; i < 8; i++) {
h = encrypt(url, i);
h %= (1000000 * 32);
index = h / 32;
pos = h % 32;
if (bloom_table[index] & (0x80000000 >> pos))
res++;
else
bloom_table[index] |= (0x80000000 >> pos);
}
pthread_mutex_unlock(&bt_lock);
return (res == 8);
}
| 1
|
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\\n",counter);
pthread_mutex_unlock( &mutex1 );
}
main()
{
int rc1, rc2;
pthread_t thread1, thread2;
if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc1);
}
if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc2);
}
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex0 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
int NR_JOBS =0;
int jobID = 0;
struct job {
int job_id;
int nr_phases;
int jobTime;
int current_phase;
int phasetype_and_duration[2][2];
int is_completed;
};
struct QNode
{
struct job *currentJob;
struct QNode *next;
};
struct Queue
{
struct QNode *front, *rear;
int size;
};
struct QNode* newNode(struct job *j)
{
struct QNode *temp = (struct QNode*)malloc(sizeof(struct QNode));
temp->currentJob = j;
temp->next = 0;
return temp;
}
struct Queue *createQueue()
{
struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = 0;
return q;
}
void enQueue(struct Queue *q,struct job* k)
{
struct QNode *temp = newNode(k);
if (q->rear == 0)
{
q->front = q->rear = temp;
return;
}
q->rear->next = temp;
q->rear = temp;
q->size++;
}
struct QNode *deQueue(struct Queue *q)
{
printf("DEQUEUE THE JOB \\n");
if (q->front == 0)
return 0;
struct QNode *temp = q->front;
q->front = q->front->next;
if (q->front == 0){
q->rear = 0;
}
q->size--;
return temp;
}
struct Queue* cpuQ;
struct Queue* ioQ;
struct Queue* fQ;
void *JobCreation()
{
printf("job init");
while (NR_JOBS<20){
if (jobID < 20){
int k;
int i;
pthread_mutex_lock( &mutex0 );
struct job *j = (struct job*)malloc(sizeof(struct job));
j->job_id = jobID;
j->current_phase = 0;
j->nr_phases = 2;
for (k = 0; k < 2; k++){
j->phasetype_and_duration[0][k] = (rand()%2);
j->phasetype_and_duration[1][k] = (1);
}
jobID++;
printf("Job CREATED %d\\n", j->job_id);
enQueue(cpuQ,j);
printf("Job is ENTERING CPU QUEUE \\n");
if(fQ->size>0){
printf("dequeueing off FinalQ /n");
struct QNode *temp = deQueue(fQ);
NR_JOBS++;
free(temp->currentJob);
}
pthread_mutex_unlock( &mutex0 );
sleep(2);
}else {
if (fQ->size > 0){
printf("dequeueing off FinalQ \\n");
struct QNode *temp = deQueue(fQ);
NR_JOBS++;
free(temp->currentJob);
}
}
}
}
void *CpuProcess(){
printf("COU init");
while(NR_JOBS<20){
if(cpuQ->size != 0){
pthread_mutex_lock( &mutex1 );
struct QNode* temp = deQueue(cpuQ);
int currPhase =temp->currentJob->current_phase;
if(currPhase == (2 -1)){
printf("JOB IS FINISHED");
enQueue(fQ,temp->currentJob);
}
else{
int phaseType =temp->currentJob->phasetype_and_duration[0][currPhase];
if(phaseType == 1){
int waitTime = temp->currentJob->phasetype_and_duration[1][currPhase];
printf("Waiting for JOB");
sleep(waitTime);
temp->currentJob->current_phase++;
enQueue(cpuQ,temp->currentJob);
}
if(phaseType == 2){
enQueue(ioQ,temp->currentJob);
printf("Entering ioQueue");
}
}
free(temp);
pthread_mutex_unlock( &mutex1 );
}
}
}
void *IOProcess(){
printf("io init");
while (NR_JOBS<20){
if ( ioQ->size > 0){
pthread_mutex_lock( &mutex2 );
struct QNode *temp=deQueue(ioQ);
int dur;
int currPhase = temp->currentJob->current_phase;
dur = temp->currentJob->phasetype_and_duration[1][currPhase];
sleep(dur*.0001);
temp->currentJob->current_phase++;
enQueue(cpuQ,temp->currentJob);
printf("ENTERING BACK TO CPU QUEUE");
free(temp);
pthread_mutex_unlock( &mutex2 );
}
}
}
int main()
{
pthread_mutex_init (&mutex0,0);
pthread_mutex_init (&mutex1,0);
pthread_mutex_init (&mutex2,0);
int i;
cpuQ = createQueue();
ioQ = createQueue();
fQ = createQueue();
cpuQ->size = 0;
ioQ->size = 0;
fQ->size = 0;
pthread_t t[16];
for (i = 0; i < 8; i++){
pthread_create(&t[i], 0, CpuProcess, 0);
}
for (; i < 12; i++){
pthread_create(&t[i], 0, IOProcess, 0);
}
for (; i < 16; i++){
pthread_create(&t[i], 0, JobCreation, 0);
}
for (i = 0; i < 16; i++){
pthread_join(t[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_a;
pthread_mutex_t mutex_b;
void*
thread_a(void* arg)
{
printf("Hello from Thread A.\\n");
pthread_mutex_lock(&mutex_a);
sleep(1);
pthread_mutex_lock(&mutex_b);
printf("Doing important work in Thread A.\\n");
pthread_mutex_unlock(&mutex_b);
pthread_mutex_unlock(&mutex_a);
return 0;
}
void*
thread_b(void* arg)
{
printf("Hello from Thread B.\\n");
pthread_mutex_lock(&mutex_b);
sleep(1);
pthread_mutex_lock(&mutex_a);
printf("Doing important work in Thread A.\\n");
pthread_mutex_unlock(&mutex_a);
pthread_mutex_unlock(&mutex_b);
return 0;
}
int
main(int _ac, char* _av[])
{
int rv;
pthread_t tt_a, tt_b;
printf("Spawning some threads.\\n");
pthread_mutex_init(&mutex_a, 0);
pthread_mutex_init(&mutex_b, 0);
pthread_create(&tt_a, 0, thread_a, 0);
pthread_create(&tt_b, 0, thread_b, 0);
printf("Threads spawned.\\n");
pthread_join(tt_a, 0);
pthread_join(tt_b, 0);
printf("Threads done.\\n");
return 0;
}
| 0
|
#include <pthread.h>extern int __VERIFIER_nondet_int(void);
extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
value = __VERIFIER_nondet_int();
if (enqueue(&queue,value)) {
goto ERROR;
}
stored_elements[0]=value;
if (empty(&queue)) {
goto ERROR;
}
pthread_mutex_unlock(&m);
for(i=0; i<((800)-1); i++)
{
pthread_mutex_lock(&m);
if (enqueue_flag)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i+1]=value;
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
ERROR:__VERIFIER_error();
}
void *t2(void *arg)
{
int i;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (dequeue_flag)
{
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:__VERIFIER_error();
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
}
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int consumers;
size_t buffer_size;
char* buffer;
pthread_cond_t* read_lock;
pthread_mutex_t* write_lock;
bool eof;
} buffer_t;
int id;
FILE* fd;
buffer_t* buffer;
} thread_spec;
void* writer (void* arg) {
thread_spec* specs = (thread_spec*) arg;
int id = specs->id;
buffer_t* buffer = specs->buffer;
while (!buffer->eof) {
pthread_mutex_lock(&buffer->write_lock[id]);
pthread_cond_wait(&buffer->read_lock[id], &buffer->write_lock[id]);
if (buffer->eof) {
break;
}
fprintf(specs->fd, "%s", buffer->buffer);
pthread_cond_signal(&buffer->read_lock[id]);
pthread_mutex_unlock(&buffer->write_lock[id]);
}
return 0;
}
void* reader (void* arg) {
thread_spec* specs = (thread_spec*) arg;
buffer_t* buffer = specs->buffer;
size_t buffer_size = buffer->buffer_size;
char* tmpbuffer = malloc(buffer_size+1);
char* tmpvar;
char* read = "initial value";
memset(tmpbuffer, 0, buffer_size+1);
while(read != 0) {
read = fgets(tmpbuffer, buffer_size, specs->fd);
tmpvar = buffer->buffer;
for (int i = 0; i < buffer->consumers; i++) {
pthread_mutex_lock(&buffer->write_lock[i]);
}
buffer->buffer = tmpbuffer;
for (int i = 0; i < buffer->consumers; i++) {
pthread_cond_signal(&buffer->read_lock[i]);
}
for (int i = 0; i < buffer->consumers; i++) {
pthread_cond_wait(&buffer->read_lock[i], &buffer->write_lock[i]);
pthread_mutex_unlock(&buffer->write_lock[i]);
}
tmpbuffer = tmpvar;
memset(tmpbuffer, 0, buffer_size+1);
}
for (int i = 0; i < buffer->consumers; i++) {
pthread_mutex_lock(&buffer->write_lock[i]);
}
buffer->eof = 1;
for (int i = 0; i < buffer->consumers; i++) {
pthread_cond_signal(&buffer->read_lock[i]);
pthread_mutex_unlock(&buffer->write_lock[i]);
}
return 0;
}
pthread_attr_t attr;
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Usage: %s <filename>\\n", argv[0]);
exit(-1);
}
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
buffer_t buffer = {
.consumers = 2,
.buffer_size = 32,
.eof = 0
};
buffer.read_lock = malloc(sizeof(pthread_cond_t)*buffer.consumers);
buffer.write_lock = malloc(sizeof(pthread_mutex_t)*buffer.consumers);
buffer.buffer = malloc(buffer.buffer_size+1);
memset(buffer.buffer, 0, buffer.buffer_size+1);
for (int i = 0; i < buffer.consumers; i++) {
pthread_mutex_init(&buffer.write_lock[i], 0);
pthread_cond_init(&buffer.read_lock[i], 0);
}
FILE* out_file = fopen(argv[1], "w");
thread_spec filewriter = {.id = 1,
.fd = out_file,
.buffer = &buffer};
thread_spec stdoutwriter = {.id = 0,
.fd = stdout,
.buffer = &buffer};
thread_spec stdinreader = {.fd = stdin,
.buffer = &buffer};
pthread_t in, out, file;
pthread_create(&file, &attr, writer, (void *) &filewriter);
pthread_create(&out, &attr, writer, (void *) &stdoutwriter);
pthread_create(&in, &attr, reader, (void *) &stdinreader);
pthread_join(file, 0);
pthread_join(out, 0);
pthread_join(in, 0);
}
| 0
|
#include <pthread.h>
double nanotime()
{
struct timespec now;
if (clock_gettime(CLOCK_MONOTONIC, &now)) {
do { fprintf(stderr, "Can't read clock.\\n"); perror(""); exit(1); } while (0);
}
return (double)now.tv_sec + 1e-9 * (double)now.tv_nsec;
}
struct incrementer_input
{
int32_t *ints;
int iterations;
int offset;
pthread_mutex_t *go_lock;
};
void *incrementer(void *void_input)
{
struct incrementer_input *input =
(struct incrementer_input *)void_input;
pthread_mutex_lock(input->go_lock);
int i, j, iterations = input->iterations;
int32_t *ints = input->ints;
int offset = input->offset;
for (i = 0; i < 1 * iterations; ++i) {
j = (i + offset) % 1;
__sync_fetch_and_add(&ints[j], 1);
}
return 0;
}
int main(int argc, char **argv)
{
long int iterations = 1024;
if (argc == 2) {
iterations = 1024 * strtol(argv[1], 0, 10);
if (errno) {
do { fprintf(stderr, "Can't parse %s as a number.\\n", argv[1]); perror(""); exit(1); } while (0);
}
if (iterations < 0) {
do { fprintf(stderr, "I'd like a *positive* number, please.\\n"); perror(""); exit(1); } while (0);
}
}
int32_t *ints = malloc(1 * sizeof(int32_t));
int i;
for (i = 0; i < 1; ++i) {
ints[i] = 0;
}
pthread_t *threads = malloc(sizeof(pthread_t) * 2);
pthread_mutex_t *locks = malloc(sizeof(pthread_mutex_t) * 2);
struct incrementer_input *inputs =
malloc(sizeof(struct incrementer_input) * 2);
for (i = 0; i < 2; ++i) {
if (pthread_mutex_init(locks + i, 0)) {
do { fprintf(stderr, "Can't init lock.\\n"); perror(""); exit(1); } while (0);
}
inputs[i].go_lock = &locks[i];
inputs[i].offset = i * (1 / 2);
inputs[i].ints = ints;
inputs[i].iterations = iterations;
pthread_mutex_lock(&locks[i]);
pthread_create(&threads[i], 0, &incrementer, &inputs[i]);
}
double time_begin = nanotime();
for (i = 0; i < 2; ++i) {
pthread_mutex_unlock(&locks[i]);
}
for (i = 0; i < 2; ++i) {
if (pthread_join(threads[i], 0)) {
do { fprintf(stderr, "pthread_join failed.\\n"); perror(""); exit(1); } while (0);
}
}
double time_end = nanotime();
double time_taken = time_end - time_begin;
printf("Ran %ld iterations in %f.\\n", iterations, time_taken);
printf("Nanoseconds/lock = %f.\\n",
1e9 * time_taken / 1 / (double)iterations);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condC;
pthread_cond_t condP;
int bufferSize = 10;
int buffer = 0;
int total = 0;
void *producer1(void *ptr)
{
printf("pro1\\n");
for(int i = 0; i < 50; i++)
{
pthread_mutex_lock(&the_mutex);
if(total == 50){
exit(0);
}
while(buffer == bufferSize)
{
printf("The buffer is full! Producer1 is waiting.\\n");
pthread_cond_wait(&condP, &the_mutex);
}
buffer++;
printf("Producer1 produced a pizza......%d\\n", i);
sleep(1);
pthread_cond_broadcast(&condP);
pthread_cond_broadcast(&condC);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *producer2(void *ptr)
{
printf("pro2\\n");
for(int i = 0; i < 50; i++)
{
pthread_mutex_lock(&the_mutex);
if(total == 50){
exit(0);
}
while(buffer == bufferSize)
{
printf("The buffer is full! Producer2 is waiting.\\n");
pthread_cond_wait(&condP, &the_mutex);
}
buffer++;
printf("Producer2 produced a pizza......%d\\n", i);
sleep(1);
pthread_cond_broadcast(&condP);
pthread_cond_broadcast(&condC);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *producer3(void *ptr)
{
printf("pro3\\n");
for(int i = 0; i < 50; i++)
{
pthread_mutex_lock(&the_mutex);
if(total == 50){
exit(0);
}
while(buffer == bufferSize)
{
printf("The buffer is full! Producer3 is waiting.\\n");
pthread_cond_wait(&condP, &the_mutex);
}
buffer++;
printf("Producer3 produced a pizza......%d\\n", i);
sleep(1);
pthread_cond_broadcast(&condP);
pthread_cond_broadcast(&condC);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void *consumer1(void *ptr)
{
printf("con1\\n");
for(int i =0; i < 50; i++)
{
pthread_mutex_lock(&the_mutex);
if(total == 50){
exit(0);
}
while(buffer == 0)
{
printf("The buffer is empty! Consumer1 is waiting.\\n");
pthread_cond_wait(&condC, &the_mutex);
}
buffer--;
total++;
printf("Consumer1 retrived a pizza......%d\\n", i);
sleep(1);
pthread_mutex_unlock(&the_mutex);
pthread_cond_broadcast(&condC);
pthread_cond_broadcast(&condP);
}
pthread_exit(0);
}
void *consumer2(void *ptr)
{
printf("con2\\n");
for(int i =0; i < 50; i++)
{
pthread_mutex_lock(&the_mutex);
if(total == 50){
exit(0);
}
while(buffer == 0)
{
printf("The buffer is empty! Consumer2 is waiting.\\n");
pthread_cond_wait(&condC, &the_mutex);
}
buffer--;
total++;
printf("Consumer2 retrived a pizza......%d\\n", i);
sleep(1);
pthread_cond_broadcast(&condC);
pthread_cond_broadcast(&condP);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
pthread_t pro1, con1, pro2, con2, pro3;
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condC, 0);
pthread_cond_init(&condP, 0);
pthread_create(&con2, 0, consumer2, 0);
printf("Have create con2\\n");
sleep(1);
pthread_create(&con1, 0, consumer1, 0);
printf("Have create con1\\n");
sleep(1);
pthread_create(&pro3, 0, producer3, 0);
printf("Have create pro3\\n");
pthread_create(&pro2, 0, producer2, 0);
printf("Have create pro2\\n");
pthread_create(&pro1, 0, producer1, 0);
printf("Have create pro1\\n");
pthread_join(pro1, 0);
pthread_join(pro2, 0);
pthread_join(pro3, 0);
pthread_join(con2, 0);
pthread_join(con1, 0);
pthread_cond_destroy(&condC);
pthread_cond_destroy(&condP);
}
| 0
|
#include <pthread.h>
double *a_t;
double *b_t;
double sum;
pthread_mutex_t mutex;
double two_norm(double *a, double *b, long length){
double ret_val = 0.0;
for(long i = 0; i < length; ++i){
ret_val += a[i] * b[i];
}
return ret_val;
}
void *two_norm_thread(void *arg)
{
long id = (long)arg;
long length = 300000000;
double partial_sum = 0.0;
for(long i = id * (length / 512); i < (id + 1) * (length / 512) && i < length; ++i){
partial_sum += a_t[i] * b_t[i];
}
pthread_mutex_lock(&mutex);
sum += partial_sum;
pthread_mutex_unlock(&mutex);
return (void *)0;
}
int main(int argc, char **argv)
{
pthread_t thread[512];
clock_t start;
clock_t stop;
double total_time;
long ncpus;
double norm2;
double serial_time;
double serial_overhead;
pthread_mutex_init(&mutex, 0);
sum = 0.0;
init_genrand(47u);
a_t = malloc(300000000 * sizeof(double));
b_t = malloc(300000000 * sizeof(double));
for(long i = 0; i < 300000000; ++i){
a_t[i] = genrand_res53();
b_t[i] = genrand_res53();
}
start = clock();
for (long i = 1; i < 512; i++) {
if (pthread_create(&thread[i],
0,
two_norm_thread,
(void*) (i)) != 0) {
perror("Cannot create the thread.");
exit(-1);
}
}
two_norm_thread((void *)0);
for (int i = 1; i < 512; i++) {
pthread_join(thread[i], 0);
}
stop = clock();
total_time = (double)(stop - start) / (double)CLOCKS_PER_SEC;
start = clock();
norm2 = two_norm(a_t, b_t, 300000000);
stop = clock();
serial_time = ((double)stop - (double)start) / (double)CLOCKS_PER_SEC;
printf("two norm is \\t\\t%f, took %f seconds\\n", norm2, serial_time);
printf("two norm (threaded) is \\t%f, took %f seconds\\n", sum, total_time);
free(a_t);
free(b_t);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t cs0, cs1;
int globalX = 0;
int globalY = 0;
void
print_safe()
{
printf("-------- safe\\n");
}
void
print_deadlock()
{
printf("------------- could deadlock\\n");
}
void * work0 (void *arg)
{
pthread_mutex_lock (&cs0);
printf("work0: got lock 0\\n");
globalX++;
pthread_mutex_lock (&cs1);
printf("work0: got lock 1\\n");
globalY++;
pthread_mutex_unlock (&cs1);
printf("work0: released lock 1\\n");
pthread_mutex_unlock (&cs0);
printf("work0: released lock 0\\n");
return 0;
}
void * work1 (void *arg)
{
int r = 0;
if(r)
{
pthread_mutex_lock (&cs0);
printf("work1: got lock 0\\n");
globalX++;
pthread_mutex_lock (&cs1);
printf("work1: got lock 1\\n");
print_safe();
globalY++;
}
else
{
pthread_mutex_lock (&cs1);
printf("work1: got lock 1\\n");
globalX++;
pthread_mutex_lock (&cs0);
printf("work1: got lock 0\\n");
print_deadlock();
globalY++;
}
if(r)
{
pthread_mutex_unlock (&cs1);
print_safe();
pthread_mutex_unlock (&cs0);
}
else
{
pthread_mutex_unlock (&cs0);
printf("work1: released lock 0\\n");
print_deadlock();
pthread_mutex_unlock (&cs1);
printf("work1: released lock 1\\n");
}
return 0;
}
int main (int argc, char *argv[])
{
pthread_t t0, t1;
int rc;
srand(time(0));
if(argc != 1)
return 1;
pthread_mutex_init (&cs0, 0);
pthread_mutex_init (&cs1, 0);
printf ("START\\n");
printf("t0 = %u \\n", (unsigned int) t0);
rc = pthread_create (&t0, 0, work0, 0);
rc = pthread_create (&t1, 0, work1, 0);
pthread_join(t0, 0);
pthread_join(t1, 0);
printf ("TOTAL = (%d,%d)\\n", globalX, globalY);
printf ("STOP\\n");
return 0;
}
| 0
|
#include <pthread.h>
sem_t chopsticks[5];
pthread_mutex_t mutex;
void *philosopher(void *arg){
int id = (int) arg;
int state = 1;
int right = (id + 1) % 5;
int left = (id + 5 - 1) % 5;
char ptrState[32];
while(1){
switch(state){
case 1:
usleep(3000);
state = 2;
printf("Philosopher %d is thinking \\n",id);
break;
case 2:
if(sem_wait(&chopsticks[left]) == 0){
if(sem_trywait(&chopsticks[right]) == 0){
printf("Philosopher %d is eating.\\n",id);
state = 3;
}else{
state = 1;
sem_post(&chopsticks[left]);
printf("Philosopher %d right chopsticks is busy,right=%d\\n",id,right);
}
}else{
printf("Philosopher %d left chopsticks is busy,left=%d\\n",id,left);
}
break;
case 3:
printf("Philosopher %d fetch left and right chopsticks: (%d,%d)\\n",id,left,right);
sem_post(&chopsticks[left]);
sem_post(&chopsticks[right]);
printf("Philosopher %d release left and right chopsticks: (%d,%d)\\n",id,left,right);
usleep(500);
state = 1;
break;
}
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
usleep(1000);
}
pthread_exit((void*)0);
sleep(5000);
}
int main(){
pthread_t tid[5];
int i;
pthread_mutex_init(&mutex,0);
for(i = 0 ; i < 5 ; i ++){
sem_init(&chopsticks[i],0,1);
}
for(i = 0 ; i < 5 ; i ++){
pthread_create(&tid[i],0,philosopher,(void*)i);
}
for(i = 0 ; i < 5 ; i ++){
pthread_join(tid[i],0);
}
return 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;
rtn=pthread_create(&pthread_id,0,(void *)thread_worker,0);
if(rtn!=0){
printf("thread create failed\\n");
return -1;
}
for(i=0;i<10000;i++){
pthread_mutex_lock(&mutex1);
pthread_mutex_lock(&mutex2);
critical_section(1,i);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
}
pthread_mutex_destroy(&mutex1);
pthread_mutex_destroy(&mutex2);
}
void *thread_worker(void *p){
int i;
for(i=0;i<10000;i++){
pthread_mutex_lock(&mutex2);
pthread_mutex_lock(&mutex1);
critical_section(2,i);
pthread_mutex_unlock(&mutex1);
pthread_mutex_unlock(&mutex2);
}
}
void critical_section(int pthread_num,int i){
printf("thread:%d:%d\\n",pthread_num,i);
}
| 0
|
#include <pthread.h>
struct foo {
int id;
int refs;
pthread_mutex_t mutex;
};
struct foo* alloc(int id) {
struct foo* p;
if ((p = (struct foo*)malloc(sizeof(struct foo))) != 0) {
p->id = id;
p->refs = 1;
if (pthread_mutex_init(&p->mutex, 0) != 0) {
free(p);
return 0;
}
}
return p;
}
void hold(struct foo* p) {
pthread_mutex_lock(&p->mutex);
p->refs++;
pthread_mutex_unlock(&p->mutex);
}
void release(struct foo* p) {
pthread_mutex_lock(&p->mutex);
if (--p->refs == 0) {
pthread_mutex_unlock(&p->mutex);
pthread_mutex_destroy(&p->mutex);
free(p);
} else {
pthread_mutex_unlock(&p->mutex);
}
}
void* thread_task(void* arg) {
struct foo* p = (struct foo*)arg;
int i;
for (i = 0; i < 100; i++) {
hold(p);
printf("task pid %ld tid %ld hold %d with %dth\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), p->id, i + 1);
}
for (i = 0; i < 100; i++) {
release(p);
printf("task pid %ld tid %ld release %d with %dth\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), p->id, i + 1);
}
}
int main(int argc, char* argv[]) {
pthread_t tid;
int err;
int i;
struct foo* p = alloc(22);
err = pthread_create(&tid, 0, thread_task, (void*)p);
if (err != 0) {
err_exit(err, "can't create thread");
}
for (i = 0; i < 100; i++) {
hold(p);
printf("main pid %ld tid %ld hold %d with %dth\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), p->id, i + 1);
}
for (i = 0; i < 100; i++) {
release(p);
printf("main pid %ld tid %ld release %d with %dth\\n", (unsigned long)getpid(), (unsigned long)pthread_self(), p->id, i + 1);
}
pthread_join(tid, 0);
release(p);
return 0;
}
| 1
|
#include <pthread.h>
{
char request_type;
int account;
int target;
int amount;
} request;
pthread_mutex_t lock;
int shared_balance = 0;
void *withdraw_money_thread(int amount)
{
pthread_mutex_lock(&lock);
printf("\\n Processing withdraw request.. current balance %d", shared_balance);
if (shared_balance >= amount)
printf("\\n Withdraw amount of %d is Authorized", amount);
else
{
printf("\\n Request denied");
return 0;
}
shared_balance = shared_balance - amount;
printf("\\n Updated balance %d", shared_balance);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
int k = 2,n = 2,m = 10;
request rqs[m + n];
FILE *fp;
char line[100];
fp = fopen("./input.txt","r");
if (fp == 0)
{
printf("Input file cannot be found");
return 0;
}
int count = 0;
while(fgets(line,sizeof(line),fp))
{
printf("Line: %s\\n", line);
char *str = strtok(line," ");
str = strtok(0," ");
int str_count = 0;
while (str != 0 && str[0] != ' ')
{
printf(" Type: %s\\n",str);
rqs[count].request_type = str[0];
str = strtok(0," ");
rqs[count].account = str[3];
printf(" Account: %s\\n",str);
if (rqs[count].request_type == 't')
{
str = strtok(0," ");
printf(" Target: %s\\n",str);
rqs[count].target = atoi(str);
}
str = strtok(0," ");
printf(" Amount: %s\\n\\n",str);
if (str == 0)
printf("Hi\\n");
rqs[count].amount = atoi(str);
str = strtok(0," ");
count ++;
}
}
}
| 0
|
#include <pthread.h>
int fork[2];
pthread_mutex_t lock[2];
int meals[2];
int take_up(int pid, int fid)
{
pthread_mutex_lock(lock + fid);
int success = 0;
if (fork[fid] == 1) {
fork[fid] = 0;
success = 1;
}
pthread_mutex_unlock(lock + fid);
return success;
}
void put_down(int pid, int fid)
{
pthread_mutex_lock(lock + fid);
fork[fid] = 1;
pthread_mutex_unlock(lock + fid);
}
void *philosopher(void *arg)
{
int id = *(int*) arg;
int left = id;
int right = (id+1) % 2;
int first = left;
int second = right;
if (take_up(id, first) == 1) {
if (take_up(id, second) == 1) {
meals[id]++;
put_down(id, first);
put_down(id, second);
} else {
put_down(id, first);
}
} else {
}
pthread_exit(0);
}
int main()
{
pthread_t phils[2];
int pid[2];
void *status;
for (int i = 0; i < 2; ++i) {
pid[i] = i;
fork[i] = 1;
meals[i] = 0;
pthread_mutex_init(lock + i, 0);
}
for (int i = 0; i < 2; ++i) {
pthread_create(phils + i, 0, philosopher, pid + i);
}
for (int i = 0; i < 2; ++i) {
pthread_join(phils[i], &status);
}
return(0);
}
| 1
|
#include <pthread.h>
int balanco=10000;
pthread_t threads[2];
pthread_mutex_t mutex_balanco;
void *deposita(void *valor)
{
int i,*a= (int *) valor;
pthread_mutex_lock(&mutex_balanco);
balanco += *a;
pthread_mutex_unlock(&mutex_balanco);
pthread_exit(0);
}
void *saque(void *valor)
{
int i, *b= (int *) valor;
pthread_mutex_lock(&mutex_balanco);
balanco -= *b;
pthread_mutex_unlock(&mutex_balanco);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i,s,estado,depositar=6000,sacar=5000;
pthread_mutex_init(&mutex_balanco, 0);
pthread_create(&threads[0],0,deposita,(void *)&depositar);
pthread_create(&threads[1],0,saque,(void *)&sacar);
for(i=0; i<2; i++)
{
s=pthread_join(threads[i], (void **) &estado);
if (s) {
perror("Erro no join");
exit(-1);
}
printf("O thread %d terminou com o estado %d\\n",i,estado);
}
printf("O balanco eh = %d\\n",balanco);
pthread_mutex_destroy(&mutex_balanco);
pthread_exit(0);
system("pause");
}
| 0
|
#include <pthread.h>
const int MAX_PRODUCER = 20;
const int MAX_CONSUMER = 20;
int head = 0;
int tail = 0;
int buffer[5];
pthread_mutex_t mutex;
sem_t emptyBuffers;
sem_t fullBuffer;
void initialize_locks()
{
pthread_mutex_init(&mutex,0);
sem_init(&emptyBuffers,0,5);
sem_init(&fullBuffer,0,0);
}
void *producer(void *param)
{
int item;
while(1)
{
item = rand();
sem_wait(&emptyBuffers);
pthread_mutex_lock(&mutex);
buffer[tail] = item ;
tail = (tail+1) % 5;
printf ("producer: (%d)inserted t:%d h:%d \\n",item,tail,head);
fflush (stdout);
pthread_mutex_unlock(&mutex);
sem_post(&fullBuffer);
}
printf ("producer quiting\\n"); fflush (stdout);
}
void *consumer(void *param)
{
int item;
while (1)
{
sem_wait(&fullBuffer);
pthread_mutex_lock(&mutex);
item = buffer[head];
head = ( head + 1) % 5;
printf ("consumer: (%d)removed t:%d h:%d \\n",item,tail,head);
fflush (stdout);
sleep(2);
pthread_mutex_unlock(&mutex);
sem_post(&emptyBuffers);
}
}
int main( int argc, char *argv[])
{
int i, sleep_time = 100, no_of_consumer_threads = 10, no_of_producer_threads = 2;
pthread_t producer_id[MAX_PRODUCER], consumer_id[MAX_CONSUMER];
initialize_locks();
for(i = 0; i < no_of_producer_threads; i++)
{
if (pthread_create(&producer_id[i],0,producer,0) != 0)
{
fprintf (stderr, "Unable to create producer thread\\n");
return -1;
}
}
for(i = 0; i < no_of_consumer_threads; i++)
{
if (pthread_create(&consumer_id[i],0,consumer,0) != 0)
{
fprintf (stderr, "Unable to create consumer thread\\n");
}
}
sleep(sleep_time);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t proc[2];
pthread_t id[2];
pthread_cond_t condn[2];
int clock_t_1, clock_t_2=0, clock_t_3=0;
void * increment_1(void * arg)
{
int * interval;
interval=(int *)arg;
while(1)
{
sleep(1);
clock_t_1 = clock_t_1 + (*interval);
printf("\\nclock 1 = %d", clock_t_1);
}
}
void * increment_2(void * arg)
{
int * interval;
interval=(int *)arg;
while(1)
{
sleep(1);
clock_t_2 = clock_t_2 + (*interval);
printf("\\nclock 1 = %d", clock_t_2);
}
}
void * increment_3(void * arg)
{
int * interval;
interval=(int *)arg;
while(1)
{
sleep(1);
clock_t_3 = clock_t_3 + (*interval);
printf("\\nclock 1 = %d", clock_t_3);
}
}
void * clock_1(void * arg)
{
int * interval;
interval = (int *)arg;
pthread_t id1;
pthread_create(&id1, 0, &increment_1, (void *)interval);
pthread_mutex_lock(&proc[0]);
pthread_cond_wait(&condn[0], &proc[0]);
pthread_mutex_unlock(&proc[0]);
printf("\\nThread 1 received message at %d", clock_t_1);
clock_t_1 = clock_t_2 + 1;
printf("\\nThread 1 updated it's clock to %d", clock_t_1);
}
void * clock_2(void * arg)
{
int * interval;
interval = (int *)arg;
pthread_t id2;
pthread_create(&id2, 0, &increment_2, (void *)interval);
pthread_mutex_lock(&proc[1]);
pthread_cond_wait(&condn[1], &proc[1]);
pthread_mutex_unlock(&proc[1]);
printf("\\nThread 2 received message at %d", clock_t_2);
clock_t_2 = clock_t_3 + 1;
printf("\\nThread 2 updated it's clock to %d", clock_t_2);
while(clock_t_2 < 20);
printf("\\nThread 2 sent message at %d", clock_t_2);
pthread_mutex_lock(&proc[0]);
pthread_cond_signal(&condn[0]);
pthread_mutex_unlock(&proc[0]);
pthread_join(id2, 0);
}
void * clock_3(void * arg)
{
int * interval;
interval = (int *)arg;
pthread_t id3;
pthread_create(&id3, 0, &increment_3, (void *)interval);
while(clock_t_3 < 30);
printf("\\nThread 3 sent message at %d", clock_t_3);
pthread_mutex_lock(&proc[1]);
pthread_cond_signal(&condn[1]);
pthread_mutex_unlock(&proc[1]);
pthread_join(id3, 0);
}
int main()
{
int interval[3];
interval[0]=6;
printf("\\nClock Synchronization using Lamport's Clock");
pthread_create(&id[0], 0, &clock_1, (void *)&interval[0]);
interval[1]=8;
pthread_create(&id[1], 0, &clock_2, (void *)&interval[1]);
interval[2]=10;
pthread_create(&id[2], 0, &clock_3, (void *)&interval[2]);
pthread_join(id[0], 0);
printf("\\n\\n");
return 0;
}
| 0
|
#include <pthread.h>
void *worker(void *param);
pthread_mutex_t mutex;
int circle_count = 0;
double random_double()
{
return random() / ((double)32767 + 1);
}
int main (int argc, const char * argv[]) {
int darts_per_thread = 50000000/ 2;
int i;
double estimated_pi;
pthread_t tids[2];
srandom((unsigned)time(0));
for (i = 0; i < 2; i++) {
pthread_create(&tids[i], 0, worker, 0);
}
estimated_pi = 4.0 * circle_count / 50000000;
printf("Pi = %f\\n",estimated_pi);
return 0;
}
void *worker(void *param)
{
pthread_mutex_init(&mutex, 0);
int number_of_darts;
number_of_darts = *((int *)param);
int i;
int hit_count = 0;
double x,y;
printf("help");
pthread_mutex_lock(&mutex);
for (i = 0; i < 50000000; i++) {
y = random_double();
x = random_double();
if(x <= 1.0 || x >= -1.0){
if(y <= 1.0 || y >= -1.0){
if(sqrt(x*x + y*y) <= 1){
printf ("%f",sqrt(x*x + y*y));
hit_count ++;
circle_count ++;
}
}
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int thread_count;
pthread_mutex_t thread_count_mutex;
pthread_cond_t thread_count_condvar;
void
incr_thread_count (void)
{
pthread_mutex_lock (&thread_count_mutex);
++thread_count;
if (thread_count == 4)
pthread_cond_signal (&thread_count_condvar);
pthread_mutex_unlock (&thread_count_mutex);
}
void
cond_wait (pthread_cond_t *cond, pthread_mutex_t *mut)
{
pthread_mutex_lock (mut);
pthread_cond_wait (cond, mut);
pthread_mutex_unlock (mut);
}
void
noreturn (void)
{
pthread_mutex_t mut;
pthread_cond_t cond;
pthread_mutex_init (&mut, 0);
pthread_cond_init (&cond, 0);
cond_wait (&cond, &mut);
}
void *
forever_pthread (void *unused)
{
incr_thread_count ();
noreturn ();
}
void
hand_call (void)
{
}
void
wait_all_threads_running (void)
{
pthread_mutex_lock (&thread_count_mutex);
if (thread_count == 4)
{
pthread_mutex_unlock (&thread_count_mutex);
return;
}
pthread_cond_wait (&thread_count_condvar, &thread_count_mutex);
if (thread_count == 4)
{
pthread_mutex_unlock (&thread_count_mutex);
return;
}
pthread_mutex_unlock (&thread_count_mutex);
printf ("failed waiting for all threads to start\\n");
abort ();
}
void
all_threads_running (void)
{
}
int
main (void)
{
pthread_t forever[4];
int i;
pthread_mutex_init (&thread_count_mutex, 0);
pthread_cond_init (&thread_count_condvar, 0);
for (i = 0; i < 4; ++i)
pthread_create (&forever[i], 0, forever_pthread, 0);
wait_all_threads_running ();
all_threads_running ();
return 0;
}
| 0
|
#include <pthread.h>
{
char estado;
pthread_t thread;
} filosofo_t;
filosofo_t * filosofos;
{
char estado;
sem_t semaphore;
} garfo_t;
garfo_t * garfos;
int numFG = 0;
pthread_mutex_t mutexImpressao;
pthread_cond_t filosofosInicializados;
pthread_mutex_t mutexFilosofosInicializados;
int numFilosofosInicializados;
void * trocaEstadoFilosofo(int idFilosofo, char novoEstado);
void * comportamentoFilosofo(void * arg);
int main (int argc, char ** argv)
{
int i;
if (argc != 2)
{
fprintf(stderr, "\\nUso: ./jantar_semaforos n \\nn: numero de filosofos e garfos.\\n");
return 0;
}
numFG = atoi(argv[1]);
if (numFG == 0)
{
fprintf(stderr, "\\nNumero de filosofos e garfos invalido. Uso: ./jantar_semaforos n \\nn: numero de filosofos e garfos.\\n");
return 0;
}
pthread_mutex_init(&mutexImpressao,0);
garfos = (garfo_t *) malloc(sizeof(garfo_t) * numFG);
for (i = 0; i < numFG; i++)
sem_init(&(garfos[i].semaphore), 0, 1);
filosofos = (filosofo_t *) malloc(sizeof(filosofo_t) * numFG);
numFilosofosInicializados = 0;
for (i=0; i < numFG; i++)
{
filosofos[i].estado = 'I';
numFilosofosInicializados += 1;
pthread_create(&(filosofos[i].thread), 0, comportamentoFilosofo, (void*)i );
}
while (1)
{
sleep(100);
}
}
void * comportamentoFilosofo(void * arg)
{
pthread_mutex_lock(&mutexFilosofosInicializados);
while(numFilosofosInicializados < numFG)
pthread_cond_wait(&filosofosInicializados, &mutexFilosofosInicializados);
pthread_cond_signal(&filosofosInicializados);
pthread_mutex_unlock(&mutexFilosofosInicializados);
int id = (int) arg;
int garfoEsq, garfoDir;
garfoEsq = id;
garfoDir = (id + 1) % numFG;
while(1)
{
if (filosofos[id].estado == 'I')
{
trocaEstadoFilosofo(id, 'T');
sleep(rand() % 10 + 1);
}
else if (filosofos[id].estado == 'E')
{
trocaEstadoFilosofo(id, 'T');
sem_post(&(garfos[garfoEsq].semaphore));
sem_post(&(garfos[garfoDir].semaphore));
sleep(rand() % 10 + 1);
}
else if (filosofos[id].estado == 'T')
{
trocaEstadoFilosofo(id, 'H');
if(id == 0)
{
sem_wait(&(garfos[garfoDir].semaphore));
sem_wait(&(garfos[garfoEsq].semaphore));
}
else
{
sem_wait(&(garfos[garfoEsq].semaphore));
sem_wait(&(garfos[garfoDir].semaphore));
}
}
else if (filosofos[id].estado == 'H')
{
trocaEstadoFilosofo(id, 'E');
sleep(rand() % 10 + 1);
}
}
}
void * trocaEstadoFilosofo(int idFilosofo, char novoEstado)
{
int i;
pthread_mutex_lock(&mutexImpressao);
filosofos[idFilosofo].estado = novoEstado;
for (i = 0; i < numFG; i++)
fprintf(stderr, "%c ", filosofos[i].estado);
fprintf(stderr, "\\n");
pthread_mutex_unlock(&mutexImpressao);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutexl = PTHREAD_MUTEX_INITIALIZER;
int global_data = 0;
void read_data();
void set_data();
int main(void)
{
pthread_t thread1, thread2;
int thread_return1, thread_return2;
int i;
for (i = 0; i < 5; i++)
{
thread_return1 = pthread_create(&thread1, 0, (void *)&set_data, 0);
thread_return2 = pthread_create(&thread2, 0, (void *)&read_data, 0);
}
pthread_join(thread1, 0);
pthread_join(thread2, 0);
printf("exiting\\n");
exit(0);
}
void set_data()
{
pthread_mutex_lock(&mutexl);
printf("Setting data\\t");
global_data = rand();
pthread_mutex_unlock(&mutexl);
}
void read_data()
{
int data;
pthread_mutex_lock(&mutexl);
data = global_data;
printf("Data = %d\\n", data);
pthread_mutex_unlock(&mutexl);
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(800)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(800)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (800))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (800))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (800))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(
i=0; i<(800); i++)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i]=value;
}
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
void *t2(void *arg)
{
int i;
pthread_mutex_lock(&m);
if (dequeue_flag)
{
for(
i=0; i<(800); i++)
{
if (empty(&queue)!=(-1))
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int **A; int **W; int size; int number_threads;
pthread_mutex_t **mutex;
pthread_cond_t Condition;
pthread_cond_t **CondMatrix;
int DEBUG = 0;
int main(int argc, char * argv[]){
Lab2_loadinput(&A, &size);
number_threads = parse_number_threads(argc, argv, size);
create_mutex_matrix(size);
create_weight_matrix(size);
create_data_cube(size);
create_condvar_matrix(size);
pthread_t threads[number_threads];
pthread_cond_init(&Condition, 0);
double start_time;
double end_time;
GET_TIME(start_time);
int i;
for (i = 0; i < number_threads; i++){
if (pthread_create(&threads[i], 0, thread, (void *) i)){
element_creation_error("Thread");
}
}
for (i = 0; i < number_threads; i++){
pthread_join(threads[i], 0);
}
GET_TIME(end_time);
printf("Ellapsed Time: %f\\n", end_time - start_time);
Lab2_saveoutput(W, size, end_time - start_time);
return 0;
}
void* thread(void* thread_id){
int id = (int) thread_id;
int rows = (size/number_threads);
int offset = id * rows;
int i;
int j;
int k;
for (k = 0; k < size; k++){
for (i = offset; i < offset + rows; i++){
for (j = 0; j < size; j++){
if (k > 0){
if (DEBUG) printf("%d: checking: i j k \\n", id);
previous_iteration_complete(i, j, k, id);
if (DEBUG) printf("%d: checking: i k k \\n", id);
previous_iteration_complete(i, k, k, id);
if (DEBUG) printf("%d: checking: k j k \\n", id);
previous_iteration_complete(k, j, k, id);
}
pthread_mutex_t *lock = &mutex[i][j];
pthread_mutex_lock(lock);
if (W[i][k] + W[k][j] < W[i][j]){
W[i][j] = W[i][k] + W[k][j];
}
if (DEBUG) printf("%d: set [i=%d][j=%d] = %d\\n", id, i, j, k);
set_value(i, j, k);
pthread_mutex_unlock(lock);
pthread_cond_broadcast(&CondMatrix[i][j]);
}
}
}
return 0;
}
void create_condvar_matrix(int size){
CondMatrix = malloc(size * sizeof(pthread_cond_t *));
int i;
int j;
for(i =0; i < size; i++){
CondMatrix[i] = malloc(size * sizeof(pthread_cond_t));
}
for(i =0; i < size; i++){
for(j =0; j < size; j++){
pthread_cond_init(&CondMatrix[i][j], 0);
}
}
}
void create_weight_matrix(int size){
W = malloc(size * sizeof(int *));
int i;
int j;
for (i = 0; i < size; i++){
W[i] = malloc (size * sizeof(int));
}
for (i = 0; i < size; i++){
for (j = 0; j < size; j++){
W[i][j] = A[i][j];
}
}
}
void create_mutex_matrix(int size){
mutex = malloc(size * sizeof(pthread_mutex_t *));
int i;
int j;
for (i = 0; i < size; i++){
mutex[i] = malloc (size * sizeof(pthread_mutex_t));
}
for(i = 0; i < size; i++){
for (j = 0; j < size; j++){
if (pthread_mutex_init(&mutex[i][j], 0)){
element_creation_error("Mutex");
}
}
}
}
void previous_iteration_complete(int i, int j, int k, int tid){
if (DEBUG) printf("%d: locking mutex[%d][%d]\\n", tid, i, j);
pthread_mutex_lock(&mutex[i][j]);
while ( get_value(i, j) < k-1) {
if (DEBUG) printf("%d: got value[%d][%d] = %d \\n", tid, i, j, get_value(i,j));
if (DEBUG) printf("%d: waiting on cond[%d][%d]\\n", tid, i, j);
pthread_cond_wait (&CondMatrix[i][j], &mutex[i][j]);
}
if (DEBUG) printf("%d: unlocking mutex[%d][%d]\\n", tid, i, j);
pthread_mutex_unlock(&mutex[i][j]);
}
| 0
|
#include <pthread.h>
void tcp_setaddress(struct tcp_socket* inputsocket, char* inputstring) {
inputsocket->servaddr.sin_addr.s_addr = inet_addr(inputstring);
}
void tcp_setport(struct tcp_socket* inputsocket, int port) {
inputsocket->servaddr.sin_port = htons(port);
}
void tcp_createsocket(struct tcp_socket* inputsocket) {
inputsocket->sockfd = socket(AF_INET, SOCK_STREAM, 0);
inputsocket->servaddr.sin_family = AF_INET;
struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec = 0;
setsockopt(inputsocket->sockfd, SOL_SOCKET, SO_RCVTIMEO, (char*) &tv, sizeof(struct timeval));
}
int tcp_opensocket(struct tcp_socket* inputsocket) {
bool returnFlag = -1;
if (bind(inputsocket->sockfd, (struct sockaddr *) &inputsocket->servaddr, sizeof(inputsocket->servaddr)) == 0) {
returnFlag = 0;
}
return returnFlag;
}
void tcp_closesocket(struct tcp_socket* inputsocket) {
close(inputsocket->sockfd);
}
void tcp_listen(struct tcp_socket* inputsocket, struct rtlsdrstruct* sdr, struct liquidobjects* dsp) {
listen(inputsocket->sockfd, 50);
inputsocket->clilen = sizeof(inputsocket->cli_addr);
while (sdr->receiverexitflag == 0) {
bool connected = 0;
inputsocket->newsockfd = accept(inputsocket->sockfd, (struct sockaddr *) &inputsocket->cli_addr,
&inputsocket->clilen);
if (inputsocket->newsockfd < 0) {
} else {
printf("Client Accepted!\\n");
connected = 1;
}
while ((connected == 1) && (sdr->receiverexitflag == 0)) {
int n;
bzero(inputsocket->receivebuffer, (100 * sizeof(uint32_t)));
n = read(inputsocket->newsockfd, inputsocket->receivebuffer, (1000 * sizeof(char)));
if (n < 0) {
} else {
uint32_t part1;
uint32_t part2;
memcpy(&part1, inputsocket->receivebuffer, 4);
memcpy(&part2, inputsocket->receivebuffer + 4, 4);
printf("Command received; %d:%d\\n", part1, part2);
connected = processcommand(inputsocket, sdr, dsp, part1, part2);
}
}
}
}
bool processcommand(struct tcp_socket* inputsocket, struct rtlsdrstruct* sdr, struct liquidobjects* dsp, uint32_t part1,
uint32_t part2) {
bool returnFlag;
if (part1 == 1) {
tune_sdr(sdr, part2, dsp);
printf("SDR Tuned to frequency %d\\n", part2);
returnFlag = 1;
}
else if (part1 == 2) {
set_cb_freq_sdr(sdr, part2, dsp);
printf("SDR Tuned to CB channel %d\\n", part2);
returnFlag = 1;
} else if (part1 == 3) {
if (part2 == 0) {
printf("Modulation type set to FM-mono\\n");
dsp->demodtype = mono_FM;
} else if (part2 == 2) {
printf("Modulation type set to CB-AM\\n");
dsp->demodtype = cb_AM;
}
dsp->buffercounter = 0;
returnFlag = 1;
} else if (part1 == 4) {
printf("Receiver has exited, waiting for new receivers\\n");
returnFlag = 0;
} else if (part1 == 5) {
if (part2 == 0) {
printf("Now sending PCM Audio\\n");
pthread_mutex_lock(&sdr->sdrlock);
sdr->sendaudio = 1;
pthread_mutex_unlock(&sdr->sdrlock);
} else if (part2 == 1) {
printf("Now sending RAW IQ data\\n");
pthread_mutex_lock(&sdr->sdrlock);
sdr->sendaudio = 0;
pthread_mutex_unlock(&sdr->sdrlock);
}
returnFlag = 1;
} else if ((part1 == 0) && (part2 == 0)) {
printf("FIN Command received\\n");
returnFlag = 0;
}
return returnFlag;
}
| 1
|
#include <pthread.h>
pthread_mutex_t foodLock, forkLock;
pthread_cond_t forkCond;
pthread_mutex_t forks[10];
pthread_t philosophers[10];
int id;
} param;
void get_forks(int phil, int fork1, int fork2){
pthread_mutex_lock(&forkLock);
printf("locking forks %d\\n", phil);
int res1, res2;
int busy = 0;
do{
if(busy){
printf("sleep %d\\n", phil);
pthread_cond_wait(&forkCond,&forkLock);
printf("wake up %d\\n", phil);
}
busy = 0;
res1 = pthread_mutex_trylock(&forks[fork1]);
if(0 == res1){
res2 = pthread_mutex_trylock(&forks[fork2]);
if(EBUSY == res2){
pthread_mutex_unlock(&forks[fork1]);
busy = 1;
}
}
else if(EBUSY == res1){
busy = 1;
}
else{
printf("error in trylock\\n");
}
}while(busy);
pthread_mutex_unlock(&forkLock);
printf("unlocking forks %d\\n", phil);
}
void down_forks(int f1, int f2){
pthread_mutex_unlock(&forks[f2]);
pthread_mutex_unlock(&forks[f1]);
pthread_mutex_lock(&forkLock);
pthread_cond_broadcast(&forkCond);
pthread_mutex_unlock(&forkLock);
}
int food_on_table(){
static int food = 40;
pthread_mutex_lock(&foodLock);
if(food > 0){
food--;
}
int my = food;
pthread_mutex_unlock(&foodLock);
return my;
}
void *philosopher(void* paramet){
int id = ((param*)paramet)->id;
int left_fork = id % 10;
int right_fork = (id + 1) % 10;
int f;
int eaten = 0;
while(0 != (f = food_on_table())){
get_forks(id, right_fork, left_fork);
printf("Philosopher %d: eating.\\n", id);
usleep(300000 * (40 - f + 1));
down_forks(left_fork, right_fork);
printf("down %d\\n", id);
eaten++;
}
printf("philosopher %d eat %d dishes\\n", id, eaten);
}
int main(int argc, char const *argv[])
{
pthread_mutex_init(&foodLock, 0);
pthread_mutex_init(&forkLock, 0);
pthread_cond_init(&forkCond, 0);
param parametr[10];
int i, j;
int error;
for (i = 0; i < 10; ++i)
{
error = pthread_mutex_init(&forks[i], 0);
if(error){
printf("error in mutex init\\n");
for (j = 0; j < i; ++j)
{
error = pthread_mutex_destroy(&forks[j]);
if(error){
printf("error in mutex destroy\\n");
exit(1);
}
}
exit(1);
}
}
for (i = 0; i < 10; ++i){
parametr[i].id = i;
error = pthread_create(&philosophers[i], 0, philosopher, ¶metr[i]);
if(error){
printf("error in threads creating\\n");
for(j = 0; j < i; ++j){
pthread_join(philosophers[j], 0);
}
exit(1);
}
}
for (i = 0; i < 10; ++i)
{
error = pthread_join(philosophers[i], 0);
if(error){
printf("error in joining\\n");
exit(1);
}
}
for (i = 0; i < 10; ++i)
{
error = pthread_mutex_destroy(&forks[i]);
if (error)
{
printf("error in destroy mutex\\n");
exit(1);
}
}
pthread_cond_destroy(&forkCond);
pthread_mutex_destroy(&foodLock);
pthread_mutex_destroy(&forkLock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mx, my;
int x=2, y=2;
void *thread1() {
int a;
pthread_mutex_lock(&mx);
a = x;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
a = a + 1;
pthread_mutex_lock(&my);
y = y + a;
y = y + a;
y = y + a;
y = y + a;
y = y + a;
pthread_mutex_unlock(&my);
x = x + x + a;
pthread_mutex_unlock(&mx);
assert(x!=27);
}
void *thread2() {
pthread_mutex_lock(&mx);
x=x+2;
x=x+2;
x=x+2;
x=x+2;
x=x+2;
pthread_mutex_unlock(&mx);
}
void *thread3() {
pthread_mutex_lock(&my);
y=y+2;
y=y+2;
y=y+2;
y=y+2;
y=y+2;
pthread_mutex_unlock(&my);
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mx, 0);
pthread_mutex_init(&my, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_create(&t3, 0, thread3, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mx);
pthread_mutex_destroy(&my);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_count;
pthread_cond_t cond_produce;
pthread_cond_t cond_consume;
int count = 0;
void *produce(void *arg)
{
srand((int)time(0));
while (1)
{
pthread_mutex_lock(&mutex_count);
while (5 == count)
{
pthread_cond_wait(&cond_produce, &mutex_count);
}
count++;
printf("producer %d: items remain %d\\n", (int)arg, count);
pthread_cond_signal(&cond_consume);
pthread_mutex_unlock(&mutex_count);
if (rand() % 2 == (int)arg)
{
sleep(1);
}
}
pthread_exit(0);
}
void *consume(void *arg)
{
srand((int)time(0));
while (1)
{
pthread_mutex_lock(&mutex_count);
while (0 == count)
{
pthread_cond_wait(&cond_consume, &mutex_count);
}
count--;
printf("consumer %d: items remain %d\\n", (int)arg, count);
pthread_cond_signal(&cond_produce);
pthread_mutex_unlock(&mutex_count);
if (rand() % 3 == (int)arg)
{
sleep(1);
}
}
pthread_exit(0);
}
int main()
{
pthread_t producer[2];
pthread_t consumer[3];
pthread_mutex_init(&mutex_count, 0);
pthread_cond_init(&cond_produce, 0);
pthread_cond_init(&cond_consume, 0);
int i;
for (i = 0; i != 2; ++i)
{
pthread_create(&producer[i], 0, produce, (void *)i);
}
for (i = 0; i != 3; ++i)
{
pthread_create(&consumer[i], 0, consume, (void *)i);
}
for (i = 0; i != 2; ++i)
{
pthread_join(producer[i], 0);
}
for (i = 0; i != 3; ++i)
{
pthread_join(consumer[i], 0);
}
pthread_mutex_destroy(&mutex_count);
pthread_cond_destroy(&cond_produce);
pthread_cond_destroy(&cond_consume);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t s[5];
state_t state[5];
int done;
int eatcount[5];
void philosopher(void *);
void think(int i);
void take_forks(int i);
void eat(int i);
void put_forks(int i);
void test(int i);
void mysleep(int milliseconds);
int main(int argc, char **argv)
{
int i;
pthread_t thread[5];
done = 0;
pthread_mutex_init(&mutex, 0);
for (i = 0; i < 5; i++) {
pthread_mutex_init(&s[i], 0);
pthread_mutex_lock(&s[i]);
eatcount[i] = 0;
}
for (i = 0; i < 5; i++) {
if (pthread_create(&thread[i], 0, (void *) philosopher, (void *) i)
!= 0) {
perror("pthread_create");
return 1;
}
}
mysleep(10*1000);
done = 1;
for (i = 0; i < 5; i++) {
if (pthread_join(thread[i], 0) != 0) {
perror("pthread_join");
return 2;
}
}
pthread_mutex_destroy(&mutex);
for (i = 0; i < 5; i++) {
pthread_mutex_destroy(&s[i]);
}
printf("\\n");
for (i = 0; i < 5; i++) {
printf("Philosopher %d got to eat %d times\\n", i, eatcount[i]);
}
return 0;
}
void philosopher(void *pi)
{
int i = (int) pi;
printf("philosopher thread %d starting...\\n", i);
while (!done) {
think(i);
take_forks(i);
eat(i);
put_forks(i);
}
}
void take_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = HUNGRY;
test(i);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&s[i]);
}
void put_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = THINKING;
test((((i)+5 -1)%5));
test((((i)+1)%5));
pthread_mutex_unlock(&mutex);
}
void test(int i)
{
if (state[i] == HUNGRY &&
state[(((i)+5 -1)%5)] != EATING && state[(((i)+1)%5)] != EATING) {
state[i] = EATING;
pthread_mutex_unlock(&s[i]);
}
}
void think(int i)
{
int milliseconds = random() % 1000;
printf("philosopher %d is thinking for %d milliseconds...\\n", i,
milliseconds);
mysleep(milliseconds);
}
void eat(int i)
{
int milliseconds = random() % 1000;
eatcount[i]++;
printf("\\tphilosopher %d is eating for %d milliseconds...\\n", i,
milliseconds);
mysleep(milliseconds);
}
void mysleep(int milliseconds)
{
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000;
nanosleep(&ts, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t monitor;
pthread_cond_t red[3];
int santaClaus=0;
int reindeer=1;
int consultations=2;
int reindeerNum=0;
int elvesNum=0;
void *Elf(){
printf("Elf is waiting at the door\\n");
pthread_mutex_lock(&monitor);
elvesNum++;
if (elvesNum==3){
pthread_cond_signal(&red[santaClaus]);
}
pthread_cond_wait(&red[consultations],&monitor);
pthread_mutex_unlock(&monitor);
}
void *Reindeer(){
printf("Reindeer has come\\n");
pthread_mutex_lock(&monitor);
reindeerNum++;
if(reindeerNum==10){
pthread_cond_signal(&red[santaClaus]);
}
pthread_cond_wait(&red[reindeer],&monitor);
pthread_mutex_unlock(&monitor);
}
void *SantaClaus(){
int i;
pthread_mutex_lock(&monitor);
do{
pthread_cond_wait(&red[santaClaus],&monitor);
printf("Santa Claus is awake!\\n");
if(reindeerNum==10 && elvesNum>0){
printf("Gifts delivery\\n");
sleep(2);
pthread_cond_broadcast(&red[reindeer]);
printf("Children received gifts! d^_^b\\n");
printf("Reindeer are going on vacation\\n");
reindeerNum=0;
}
if(reindeerNum==10){
printf("Feeding the reindeer\\n");
sleep(2);
}
while (elvesNum>=3){
printf("Consultation with elves\\n");
sleep(2);
for(i=0;i<3;i++){
pthread_cond_signal(&red[consultations]);
}
elvesNum-=3;
}
} while(1);
pthread_mutex_unlock(&monitor);
}
void *NorthPole(){
int reindeerProbability, elfProbability,doWait;
pthread_t reindeer;
pthread_t patuljci;
srand((unsigned)time(0));
do{
doWait=rand()%(3-1+1)+1;
sleep(doWait);
reindeerProbability=rand()%(100-0+1);
elfProbability=rand()%(100-0+1);
if((reindeerProbability>50) && (reindeerNum<10)){
if (pthread_create(&reindeer,0,Reindeer,0)){
printf("Can't create new thread!\\n");
exit(1);
}
}
if(elfProbability>50){
if (pthread_create(&patuljci,0,Elf,0)){
printf("Can't create new thread!\\n");
exit(1);
}
}
} while(1);
}
int main(int argc, char *argv[]) {
pthread_mutex_init (&monitor,0);
pthread_cond_init (red,0);
pthread_t thread1;
pthread_t thread2;
if (pthread_create(&thread1,0,NorthPole,0)){
printf("Can't create new thread!\\n");
exit(1);
}
if (pthread_create(&thread2,0,SantaClaus,0)){
printf("Can't create new thread!\\n");
exit(1);
}
pthread_join(thread1,0);
pthread_join(thread1,0);
system("PAUSE");
return 0;
}
| 0
|
#include <pthread.h>
struct log_head head_table[HASH_SIZE];
void debug(char *p, int len)
{
while(len--)
printf("%c",*p++);
printf("\\n");
}
void hash_init()
{
int i;
for(i=0; i<HASH_SIZE; ++i)
{
pthread_mutex_init(&head_table[i].head_lock, 0);
head_table[i].head = 0;
}
}
static void _each_node(struct log_info *log_node,void (*func)(void *))
{
struct log_info *p = log_node;
while(p)
{
log_node = p->next;
func(p);
p = log_node;
}
}
static void _each_list(void (*func)(void *))
{
int i;
for(i=0; i<HASH_SIZE; ++i)
{
if(head_table[i].head != 0)
{
_each_node(head_table[i].head, func);
}
}
}
void hash_unint()
{
int i;
for(i=0; i<HASH_SIZE; ++i)
{
head_table[i].head = 0;
}
_each_list(free);
}
int hash_put(struct log_info *log_info_p)
{
struct log_info *p ,*q,*node;
unsigned int pos = hash(log_info_p->ip.int_ip, HASH_SIZE);
pthread_mutex_lock(&head_table[pos].head_lock);
p = head_table[pos].head;
if(p == 0)
{
node = (struct log_info *)malloc(sizeof(struct log_info));
if(node == 0)
{
DBG_ERR("no memory\\n");
pthread_mutex_unlock(&head_table[pos].head_lock);
return -1;
}
node->ip.int_ip = log_info_p->ip.int_ip;
node->access_times = 1;
node->ip_flow += log_info_p->ip_flow;
node->next = 0;
head_table[pos].head = node;
pthread_mutex_unlock(&head_table[pos].head_lock);
return 0;
}
while(p)
{
if(p->ip.int_ip == log_info_p->ip.int_ip)
{
p->access_times++;
p->ip_flow += log_info_p->ip_flow;
pthread_mutex_unlock(&head_table[pos].head_lock);
return 0;
}
q = p;
p = p->next;
}
node = (struct log_info *)malloc(sizeof(struct log_info));
if(node == 0)
{
DBG_ERR("no memory\\n");
pthread_mutex_unlock(&head_table[pos].head_lock);
return -1;
}
node->ip.int_ip = log_info_p->ip.int_ip;
node->access_times++;
node->ip_flow += log_info_p->ip_flow;
node->next = 0;
q->next = node;
pthread_mutex_unlock(&head_table[pos].head_lock);
return 0;
}
int hash_get(union ip_type ip, struct log_info *log_get)
{
struct log_info *p;
p=head_table[hash(ip.int_ip, HASH_SIZE)].head;
if(p == 0)
{
return -1;
}
while(p)
{
if(p->ip.int_ip == ip.int_ip)
{
log_get->ip.int_ip = p->ip.int_ip;
log_get->access_times = p->access_times;
break;
}
p = p->next;
}
return 0;
}
static void print_node(void *node_p)
{
struct log_info *p = node_p;
printf("%s\\t%d\\t%ld\\n",inet_ntoa(p->ip.net_ip), p->access_times, p->ip_flow);
}
void hash_list_all()
{
_each_list(print_node);
}
| 1
|
#include <pthread.h>
struct arg_set {
char *fname;
int count;
struct arg_set **mailboxp;
pthread_mutex_t *lockp;
pthread_cond_t *flagp;
};
static void *count_words(void *a);
static int do_count(char *filename);
static void mnarrate(char *str);
static void cnarrate(char *str);
int main(int ac, char *av[])
{
pthread_t t1, t2;
struct arg_set args1, args2;
void *count_words(void *);
int reports_in = 0;
int total_words = 0;
struct arg_set *mailbox = 0;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
if ( ac != 3 ){
printf("usage: %s file1 file2\\n", av[0]);
exit(1);
}
pthread_mutex_lock(&lock);
args1.mailboxp = &mailbox;
args1.lockp = &lock;
args1.flagp = &flag;
args1.count = 0;
args1.fname = av[1];
pthread_create(&t1, 0, count_words, (void *) &args1);
args2 = args1;
args2.fname = av[2];
pthread_create(&t2, 0, count_words, (void *) &args2);
while( reports_in < 2 ){
mnarrate("waiting for signal on flag");
pthread_cond_wait(&flag, &lock);
mnarrate("flag signaled, MAIN has the lock");
printf("%7d: %s\\n", mailbox->count, mailbox->fname);
total_words += mailbox->count;
if ( mailbox == &args1)
pthread_join(t1,0);
if ( mailbox == &args2)
pthread_join(t2,0);
mnarrate("clearing box and signaling flag");
mailbox = 0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%7d: total words\\n", total_words);
return 0;
}
static void *count_words(void *a)
{
struct arg_set *args = a;
args->count = do_count(args->fname);
cnarrate("count done, waiting to get lock");
pthread_mutex_lock(args->lockp);
cnarrate("have lock");
if ( *(args->mailboxp) != 0 ){
cnarrate("oops..box is not empty, will wait..");
pthread_cond_wait(args->flagp,args->lockp);
}
cnarrate("storing pointer to args in mailbox");
*(args->mailboxp) = args;
cnarrate("signaling flag to wake main");
pthread_cond_signal(args->flagp);
cnarrate("unlocking box");
pthread_mutex_unlock(args->lockp);
return 0;
}
static int do_count(char *filename)
{
FILE *fp;
int c, prevc = '\\0';
int rv = 0;
if ( (fp = fopen(filename, "r")) != 0 )
{
while( ( c = getc(fp)) != EOF ){
if ( !isalnum(c) && isalnum(prevc) )
rv++;
prevc = c;
}
fclose(fp);
} else
perror(filename);
return rv;
}
static void mnarrate(char *str)
{
printf("MAIN: %s\\n", str);
}
static void cnarrate(char *str)
{
printf("COUNT: %s\\n", str);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.