text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
void * watek_klient (void * arg);
int l_kf;
pthread_mutex_t mutex_kf, mutex_kr;
main(){
pthread_t *tab_klient;
int *tab_klient_id;
int l_kl, l_kr, i;
pthread_mutex_init(&mutex_kf, 0);
pthread_mutex_init(&mutex_kr, 0);
printf("\\nLiczba klientow: "); scanf("%d", &l_kl);
printf("\\nLiczba kufli: "); scanf("%d", &l_kf);
l_kr = 1;
tab_klient = (pthread_t *) malloc(l_kl*sizeof(pthread_t));
tab_klient_id = (int *) malloc(l_kl*sizeof(int));
for(i=0;i<l_kl;i++) tab_klient_id[i]=i;
printf("\\nOtwieramy pub (simple)!\\n");
printf("\\nLiczba wolnych kufli %d\\n", l_kf);
for(i=0;i<l_kl;i++){
pthread_create(&tab_klient[i], 0, watek_klient, &tab_klient_id[i]);
}
for(i=0;i<l_kl;i++){
pthread_join( tab_klient[i], 0);
}
printf("\\nLiczba wolnych kufli %d\\n", l_kf);
printf("\\nZamykamy pub!\\n");
}
void * watek_klient (void * arg_wsk){
int moj_id = * ((int *)arg_wsk);
int i, j, kufel=0, result;
int ile_musze_wypic = 2;
printf("\\nKlient %d, wchodzę do pubu\\n", moj_id);
for(i=0; i<ile_musze_wypic; i++){
while(kufel < 1) {
result = pthread_mutex_lock(&mutex_kf);
if (result == EBUSY) {
usleep(100);
continue;
}
if (l_kf > 0) {
kufel = l_kf--;
}
pthread_mutex_unlock(&mutex_kf);
}
printf("\\nKlient %d, wybieram kufel %d\\n", moj_id, kufel);
j=0;
pthread_mutex_lock(&mutex_kr);
printf("\\nKlient %d, nalewam z kranu %d\\n", moj_id, j);
usleep(300);
pthread_mutex_unlock(&mutex_kr);
printf("\\nKlient %d, pije\\n", moj_id);
nanosleep((struct timespec[]){{0, 500000000L}}, 0);
pthread_mutex_lock(&mutex_kf);
kufel = ++l_kf;
pthread_mutex_unlock(&mutex_kf);
printf("\\nKlient %d, odkladam kufel. Pozostało: %d\\n", moj_id, kufel);
kufel = 0;
}
printf("\\nKlient %d, wychodzę z pubu\\n", moj_id);
return(0);
}
| 1
|
#include <pthread.h>
int tests_run = 0;
int threadpool_should_be_initialized(void);
int task_should_be_submitted(void);
static void *test_thread_func(void *arg);
static uint16_t task_processed = 32;
static pthread_mutex_t task_processed_mutex;
static pthread_cond_t task_processed_cv;
int threadpool_should_be_initialized(void)
{
const uint32_t attempts = 12;
uint32_t i;
for (i = 0; i < attempts; i++) {
pthread_t threads[16];
void *q_array[32];
struct MSIM_Queue q;
struct MSIM_ThreadPool pool;
struct MSIM_ThreadPoolQueue pool_queue;
enum MSIM_ThreadPoolRes res;
MSIM_InitQueue(&q, q_array, 32);
res = MSIM_InitThreadPoolQueue(&pool_queue, &q);
_mu_test(res == THREADPOOL_SUCCESS);
_mu_test(pool_queue.q == &q);
res = MSIM_InitThreadPool(&pool, &pool_queue,
16, threads);
_mu_test(res == THREADPOOL_SUCCESS);
_mu_test(pool.q == &pool_queue);
_mu_test(pool.nthreads == 16);
_mu_test(pool.threads == threads);
MSIM_DestroyThreadPool(&pool);
MSIM_DestroyThreadPoolQueue(&pool_queue);
}
return 0;
}
int task_should_be_submitted(void)
{
pthread_t threads[16];
void *q_array[32];
struct MSIM_Queue q;
struct MSIM_ThreadPool pool;
struct MSIM_ThreadPoolQueue pool_queue;
struct MSIM_ThreadPoolTask pool_tasks[32];
int i;
pthread_mutex_init(&task_processed_mutex, 0);
pthread_cond_init(&task_processed_cv, 0);
MSIM_InitQueue(&q, q_array, 32);
MSIM_InitThreadPoolQueue(&pool_queue, &q);
MSIM_InitThreadPool(&pool, &pool_queue, 16, threads);
for (i = 0; i < 32; i++) {
pool_tasks[i].func = test_thread_func;
pool_tasks[i].arg = 0;
MSIM_SubmitThreadPool(&pool, &pool_tasks[i]);
}
pthread_mutex_lock(&task_processed_mutex);
while (task_processed > 0) {
pthread_cond_wait(&task_processed_cv, &task_processed_mutex);
}
pthread_mutex_unlock(&task_processed_mutex);
MSIM_DestroyThreadPool(&pool);
MSIM_DestroyThreadPoolQueue(&pool_queue);
pthread_cond_destroy(&task_processed_cv);
pthread_mutex_destroy(&task_processed_mutex);
return 0;
}
int all_tests(void)
{
_mu_verify(threadpool_should_be_initialized);
_mu_verify(task_should_be_submitted);
return 0;
}
char *suite_name(void)
{
return "threadpool_test";
}
void setup_tests(void)
{
}
static void *test_thread_func(void *arg)
{
pthread_mutex_lock(&task_processed_mutex);
printf(" test_thread_func: task %d finished\\n", task_processed);
task_processed--;
pthread_cond_broadcast(&task_processed_cv);
pthread_mutex_unlock(&task_processed_mutex);
return 0;
}
| 0
|
#include <pthread.h>
void *philosopher(void *);
void think(int);
void pickUp(int);
void eat(int);
void putDown(int);
pthread_mutex_t chopsticks[5];
pthread_t philosophers[5];
pthread_attr_t attributes[5];
int main() {
int i;
srand(time(0));
for (i = 0; i < 5; ++i) {
pthread_mutex_init(&chopsticks[i], 0);
}
for (i = 0; i < 5; ++i) {
pthread_attr_init(&attributes[i]);
}
for (i = 0; i < 5; ++i) {
pthread_create(&philosophers[i], &attributes[i], philosopher, (void *)(i));
}
for (i = 0; i < 5; ++i) {
pthread_join(philosophers[i], 0);
}
return 0;
}
void *philosopher(void *philosopherNumber) {
while (1) {
think(philosopherNumber);
pickUp(philosopherNumber);
eat(philosopherNumber);
putDown(philosopherNumber);
}
}
void think(int philosopherNumber) {
int sleepTime = rand() % 3 + 1;
printf("Philosopher %d will think for %d seconds\\n", philosopherNumber, sleepTime);
sleep(sleepTime);
}
void pickUp(int philosopherNumber) {
int right = (philosopherNumber + 1) % 5;
int left = (philosopherNumber + 5) % 5;
if (philosopherNumber & 1) {
printf("Philosopher %d is waiting to pick up chopstick %d\\n", philosopherNumber, right);
pthread_mutex_lock(&chopsticks[right]);
printf("Philosopher %d picked up chopstick %d\\n", philosopherNumber, right);
printf("Philosopher %d is waiting to pick up chopstick %d\\n", philosopherNumber, left);
pthread_mutex_lock(&chopsticks[left]);
printf("Philosopher %d picked up chopstick %d\\n", philosopherNumber, left);
}
else {
printf("Philosopher %d is waiting to pick up chopstick %d\\n", philosopherNumber, left);
pthread_mutex_lock(&chopsticks[left]);
printf("Philosopher %d picked up chopstick %d\\n", philosopherNumber, left);
printf("Philosopher %d is waiting to pick up chopstick %d\\n", philosopherNumber, right);
pthread_mutex_lock(&chopsticks[right]);
printf("Philosopher %d picked up chopstick %d\\n", philosopherNumber, right);
}
}
void eat(int philosopherNumber) {
int eatTime = rand() % 3 + 1;
printf("Philosopher %d will eat for %d seconds\\n", philosopherNumber, eatTime);
sleep(eatTime);
}
void putDown(int philosopherNumber) {
printf("Philosopher %d will will put down her chopsticks\\n", philosopherNumber);
pthread_mutex_unlock(&chopsticks[(philosopherNumber + 1) % 5]);
pthread_mutex_unlock(&chopsticks[(philosopherNumber + 5) % 5]);
}
| 1
|
#include <pthread.h>
struct resend_queue *firefly_resend_queue_new()
{
struct resend_queue *rq;
rq = malloc(sizeof(*rq));
if (rq) {
rq->next_id = 1;
rq->first = 0;
rq->last = 0;
pthread_cond_init(&rq->sig, 0);
pthread_mutex_init(&rq->lock, 0);
}
return rq;
}
void firefly_resend_queue_free(struct resend_queue *rq)
{
struct resend_elem *re = rq->first;
struct resend_elem *tmp;
while(re != 0) {
tmp = re->prev;
firefly_resend_elem_free(re);
re = tmp;
}
pthread_cond_destroy(&rq->sig);
pthread_mutex_destroy(&rq->lock);
free(rq);
}
static inline void timespec_add_ms(struct timespec *t, long d)
{
long long tmp;
tmp = t->tv_nsec + d * 1000000LL;
if (tmp >= 1000000000) {
t->tv_sec += tmp / 1000000000;
tmp %= 1000000000;
}
t->tv_nsec = tmp;
}
unsigned char firefly_resend_add(struct resend_queue *rq,
unsigned char *data, size_t size, long timeout_ms,
unsigned char retries, struct firefly_connection *conn)
{
struct resend_elem *re = malloc(sizeof(*re));
if (re == 0) {
return 0;
}
re->data = data;
re->size = size;
clock_gettime(CLOCK_REALTIME, &re->resend_at);
timespec_add_ms(&re->resend_at, timeout_ms);
re->num_retries = retries;
re->conn = conn;
re->timeout = timeout_ms;
re->prev = 0;
pthread_mutex_lock(&rq->lock);
re->id = rq->next_id++;
if (rq->next_id == 0) {
rq->next_id = 1;
}
if (rq->last == 0) {
rq->first = re;
} else {
rq->last->prev = re;
}
rq->last = re;
pthread_cond_signal(&rq->sig);
pthread_mutex_unlock(&rq->lock);
return re->id;
}
static inline struct resend_elem *firefly_resend_pop(
struct resend_queue *rq, unsigned char id)
{
struct resend_elem *re = rq->first;
if (re == 0)
return 0;
if (re->id == id) {
rq->first = re->prev;
if (rq->last == re) {
rq->last = 0;
}
return re;
}
while (re->prev != 0) {
if (re->prev->id == id) {
struct resend_elem *tmp = re->prev;
re->prev = re->prev->prev;
if (rq->last == tmp) {
rq->last = re;
}
return tmp;
} else {
re = re->prev;
}
}
return 0;
}
void firefly_resend_readd(struct resend_queue *rq, unsigned char id)
{
pthread_mutex_lock(&rq->lock);
struct resend_elem *re = firefly_resend_pop(rq, id);
pthread_mutex_unlock(&rq->lock);
if (re == 0)
return;
re->num_retries--;
timespec_add_ms(&re->resend_at, re->timeout);
re->prev = 0;
pthread_mutex_lock(&rq->lock);
if (rq->last == 0) {
rq->first = re;
} else {
rq->last->prev = re;
}
rq->last = re;
pthread_cond_signal(&rq->sig);
pthread_mutex_unlock(&rq->lock);
}
void firefly_resend_remove(struct resend_queue *rq, unsigned char id)
{
pthread_mutex_lock(&rq->lock);
struct resend_elem *re = firefly_resend_pop(rq, id);
if (re != 0)
firefly_resend_elem_free(re);
pthread_cond_signal(&rq->sig);
pthread_mutex_unlock(&rq->lock);
}
void firefly_resend_elem_free(struct resend_elem *re)
{
free(re->data);
free(re);
}
struct resend_elem *firefly_resend_top(struct resend_queue *rq)
{
struct resend_elem *re = 0;
pthread_mutex_lock(&rq->lock);
re = rq->first;
pthread_mutex_unlock(&rq->lock);
return re;
}
static inline bool timespec_past(struct timespec *fixed, struct timespec *var)
{
return fixed->tv_sec == var->tv_sec ?
var->tv_nsec <= fixed->tv_nsec : var->tv_sec < fixed->tv_sec;
}
int firefly_resend_wait(struct resend_queue *rq,
unsigned char **data, size_t *size,
struct firefly_connection **conn,
unsigned char *id)
{
int result;
struct resend_elem *res = 0;
struct timespec now;
pthread_mutex_lock(&rq->lock);
clock_gettime(CLOCK_REALTIME, &now);
res = rq->first;
while (res == 0 || !timespec_past(&now, &res->resend_at)) {
if (res == 0) {
pthread_cond_wait(&rq->sig, &rq->lock);
} else {
struct timespec at = res->resend_at;
pthread_cond_timedwait(&rq->sig, &rq->lock, &at);
}
clock_gettime(CLOCK_REALTIME, &now);
res = rq->first;
}
*conn = res->conn;
if (res->num_retries <= 0) {
firefly_resend_pop(rq, res->id);
firefly_resend_elem_free(res);
*data = 0;
*id = 0;
*size = 0;
result = -1;
} else {
*data = malloc(res->size);
memcpy(*data, res->data, res->size);
*size = res->size;
*id = res->id;
result = 0;
}
pthread_mutex_unlock(&rq->lock);
return result;
}
static void firefly_resend_cleanup(void *arg)
{
struct firefly_resend_loop_args *largs;
struct resend_queue *rq;
largs = arg;
rq = largs->rq;
pthread_mutex_unlock(&rq->lock);
free(arg);
}
void *firefly_resend_run(void *args)
{
struct firefly_resend_loop_args *largs;
struct resend_queue *rq;
unsigned char *data;
size_t size;
struct firefly_connection *conn;
unsigned char id;
int res;
largs = args;
pthread_cleanup_push(firefly_resend_cleanup, args);
rq = largs->rq;
while (1) {
int prev_state;
res = firefly_resend_wait(rq, &data, &size, &conn, &id);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &prev_state);
if (res < 0) {
if (largs->on_no_ack)
largs->on_no_ack(conn);
} else {
conn->transport->write(data, size, conn,
0, 0);
free(data);
firefly_resend_readd(rq, id);
}
pthread_setcancelstate(prev_state, 0);
}
pthread_cleanup_pop(1);
return 0;
}
| 0
|
#include <pthread.h>
struct producers
{
int buffer[4];
pthread_mutex_t lock;
int readpos, writepos;
pthread_cond_t notempty;
pthread_cond_t notfull;
};
void init(struct producers *b)
{
pthread_mutex_init(&b->lock,0);
pthread_cond_init(&b->notempty,0);
pthread_cond_init(&b->notfull,0);
b->readpos=0;
b->writepos=0;
}
void put(struct producers *b, int data)
{
pthread_mutex_lock(&b->lock);
while((b->writepos+1)%4 == b->readpos)
{
pthread_cond_wait(&b->notfull,&b->lock);
}
b->buffer[b->writepos] = data;
b->writepos++;
if(b->writepos >= 4)
{
b->writepos=0;
}
pthread_cond_signal(&b->notempty);
pthread_mutex_unlock(&b->lock);
}
int get(struct producers *b)
{
int data;
pthread_mutex_lock(&b->lock);
while(b->writepos == b->readpos)
{
pthread_cond_wait(&b->notempty,&b->lock);
}
data = b->buffer[b->readpos];
b->readpos++;
if(b->readpos >= 4)
{
b->readpos = 0;
}
pthread_cond_signal(&b->notfull);
pthread_mutex_unlock(&b->lock);
return data;
}
struct producers buffer;
void *producer(void *data)
{
int n;
for(n=0;n<10;n++)
{
printf("生产者: %d-->\\n",n);
put(&buffer,n);
}
put(&buffer,(-1));
return 0;
}
void *consumer(void *data)
{
int d;
while(1)
{
d = get(&buffer);
if(d == (-1))
{
break;
}
printf("消费者: --> %d\\n",d);
}
return 0;
}
int main(int argc,char *argv[])
{
pthread_t thproducer,thconsumer;
void *retval;
init(&buffer);
pthread_create(&thproducer,0,producer,0);
pthread_create(&thconsumer,0,consumer,0);
pthread_join(thproducer,&retval);
pthread_join(thconsumer,&retval);
return 0;
}
| 1
|
#include <pthread.h>
extern int identifier;
extern int SPF_INTERVAL;
extern int NUMBER_OF_ROUTERS;
extern int MAX_POSSIBLE_DIST;
extern int*** every_node_lsa_details;
extern int* every_node_neighbors;
extern int NUMBER_OF_NEIGHBORS;
extern int** actual_link_costs;
extern FILE* ofp;
extern char outfile[1000];
extern pthread_mutex_t lock;
int allFixed(int* fixed){
int i = 0;
for(i = 0; i < NUMBER_OF_ROUTERS ; i++){
if(fixed[i] == 0){
return 0;
}
}
return 1;
}
void dijkstras(int time, int** distMatrix){
int present = identifier;
int i,j;
int fixed[NUMBER_OF_ROUTERS];
int dist[NUMBER_OF_ROUTERS];
int prev[NUMBER_OF_ROUTERS];
for(i = 0 ; i < NUMBER_OF_ROUTERS ; i++){
fixed[i] = 0;
dist[i] = 10000000;
prev[i] -1;
}
int update;
fixed[identifier] = 1;
dist[identifier] = 0;
int min, next;
while(!allFixed(fixed)){
min = 10000000;
for(i = 0 ; i < NUMBER_OF_ROUTERS; i++){
if(fixed[i] == 0){
update = dist[present] + distMatrix[present][i];
if(dist[i] == -1 || update < dist[i]){
dist[i] = update;
prev[i] = present;
}
if(min > dist[i]){
min = dist[i];
next = i;
}
}
}
present = next;
fixed[present] = 1;
}
ofp = fopen(outfile, "a");
fprintf(ofp,"Rounting table at time %d\\n", time);
fprintf(ofp,"Destination\\tPath\\tCost\\n");
int now, counter;
int path[2 * NUMBER_OF_ROUTERS + 1];
for(i = 0 ; i < NUMBER_OF_ROUTERS ; i++){
counter = 0;
if(i == identifier){
continue;
}
fprintf(ofp,"%d ", i);
now = i;
path[counter++] = i;
while(prev[now] != identifier){
path[counter++] = prev[now];
now = prev[now];
}
path[counter] = identifier;
for(j = counter ; j > 0 ; j--){
fprintf(ofp,"%d-", path[j]);
}
fprintf(ofp,"%d ", path[0]);
fprintf(ofp,"%d\\n", dist[i]);
}
fprintf(ofp, "\\n" );
fclose(ofp);
}
void* spf(void* param){
int i = 1, j;
int time = 0;
int **distMatrix;
while(1){
sleep(SPF_INTERVAL);
distMatrix = (int**)malloc(sizeof(int*) * NUMBER_OF_ROUTERS);
for( i = 0 ; i < NUMBER_OF_ROUTERS ; i++){
distMatrix[i] = (int*)malloc(sizeof(int) * NUMBER_OF_ROUTERS);
for(j = 0 ; j < NUMBER_OF_ROUTERS ; j++){
distMatrix[i][j] = 10000000;
}
}
pthread_mutex_lock(&lock);
for(i = 0 ; i < NUMBER_OF_ROUTERS ; i++){
if(i == identifier)
continue;
for(j = 0 ; j < every_node_neighbors[i] ; j++){
distMatrix[i][every_node_lsa_details[i][j][0]] = every_node_lsa_details[i][j][1];
}
}
for(i = 0 ; i < NUMBER_OF_NEIGHBORS ; i++){
distMatrix[identifier][actual_link_costs[i][0]] = actual_link_costs[i][1];
}
pthread_mutex_unlock(&lock);
dijkstras(time, distMatrix);
for(i = 0 ; i < NUMBER_OF_ROUTERS ; i++){
free(distMatrix[i]);
}
free(distMatrix);
time++;
}
}
| 0
|
#include <pthread.h>
void SayiUret();
void *Siralama(void *parametre);
void *Birlesme(void *parametre);
void ThreadYarat();
void DosyayaYaz();
pthread_mutex_t lock;
int liste[1000];
int sonuc[1000];
FILE *dosya;
{
int baslangic;
int bitis;
} parametreler;
int main (int argc, const char * argv[])
{
dosya = fopen("dizileriGoster.txt", "w+");
if(dosya == 0)
{
printf("dizileriGoster.txt açılamadı..\\n");
exit(1);
}
SayiUret();
ThreadYarat();
DosyayaYaz();
return 0;
}
void SayiUret()
{
int rnd;
int flag;
int i, j;
printf("***RANDOM DİZİ***\\n");
fprintf(dosya,"%s","****RANDOM DİZİ***");
fputc('\\n',dosya);
for(i = 0; i < 1000; i++) {
do {
flag = 1;
rnd = rand() % (1000) + 1;
for (j = 0; j < i && flag == 1; j++) {
if (liste[j] == rnd) {
flag = 0;
}
}
} while (flag != 1);
liste[i] = rnd;
printf("%d.sayi : %d\\t",i+1,liste[i]);
if(i % 10 == 0)
printf("\\n");
fprintf(dosya,"%d %s %d" ,i+1,".eleman:",liste[i]);
fputc('\\n',dosya);
}
}
void ThreadYarat()
{
int i;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex başlatılamadı\\n");
exit(0);
}
pthread_t threadler[3];
parametreler *veri = (parametreler *) malloc (sizeof(parametreler));
veri->baslangic = 0;
veri->bitis = (1000/2) - 1;
pthread_create(&threadler[0], 0, Siralama, veri);
parametreler *veri2 = (parametreler *) malloc (sizeof(parametreler));
veri2->baslangic = (1000/2);
veri2->bitis = 1000 - 1;
pthread_create(&threadler[1], 0, Siralama, veri2);
for (i = 0; i < 3 -1; i++)
{
pthread_join(threadler[i], 0);
}
pthread_mutex_destroy(&lock);
parametreler *veri3 = (parametreler *) malloc(sizeof(parametreler));
veri3->baslangic = 0;
veri3->bitis = 1000;
pthread_create(&threadler[2], 0, Birlesme, veri3);
pthread_join(threadler[2], 0);
}
void *Siralama(void *parametre)
{
parametreler *p = (parametreler *)parametre;
int ilk = p->baslangic;
int son = p->bitis+1;
int z;
fprintf(dosya,"%s","****SIRALANMAMIŞ ELEMANLAR***");
fputc('\\n',dosya);
for(z = ilk; z < son; z++){
fprintf(dosya,"%d %s %d" ,z+1,".eleman:",liste[z]);
fputc('\\n',dosya);
}
printf("\\n");
int i,j,t,k;
pthread_mutex_lock(&lock);
for(i=ilk; i< son; i++)
{
for(j=ilk; j< son-1; j++)
{
if(liste[j] > liste[j+1])
{
t = liste[j];
liste[j] = liste[j+1];
liste[j+1] = t;
}
}
}
pthread_mutex_unlock(&lock);
fprintf(dosya,"%s","****SIRALANMIŞ ELEMANLAR***");
fputc('\\n',dosya);
for(k = ilk; k< son; k++){
fprintf(dosya,"%d %s %d" ,k+1,".eleman:",liste[k]);
fputc('\\n',dosya);
}
int x;
for(x=ilk; x<son; x++)
{
sonuc[x] = liste[x];
}
printf("\\n");
return 0;
}
void *Birlesme(void *parametre)
{
parametreler *p = (parametreler *)parametre;
int ilk = p->baslangic;
int son = p->bitis-1;
int i,j,t;
for(i=ilk; i< son; i++)
{
for(j=ilk; j< son-i; j++)
{
if(sonuc[j] > sonuc[j+1])
{
t = sonuc[j];
sonuc[j] = sonuc[j+1];
sonuc[j+1] = t;
}
}
}
int d;
pthread_exit(0);
}
void DosyayaYaz()
{
int i = 0;
FILE *fp ;
fp = fopen("son.txt","w+");
fprintf(fp,"%s","****SIRALANMIŞ ELEMANLAR***");
fputc('\\n',fp);
for(i = 0; i<1000; i++)
{
fprintf(fp,"%d %s %d" ,i+1,".eleman:",sonuc[i]);
fputc('\\n',fp);
}
fclose(fp);
}
| 1
|
#include <pthread.h>
{
int value;
struct cell *next;
}
*cell;
{
int length;
cell first;
cell last;
}
*list;
list add (int v, list l)
{
cell c = (cell) malloc (sizeof (struct cell));
c->value = v;
c->next = 0;
if (l == 0){
l = (list) malloc (sizeof (struct list));
l->length = 0;
l->first = c;
}else{
l->last->next = c;
}
l->length++;
l->last = c;
return l;
}
void put (int v,list *l)
{
(*l) = add (v,*l);
}
int get (list *l)
{
int res;
list file = *l;
if (l == 0) {
fprintf (stderr, "get error!\\n");
return 0;
}
res = file->first->value;
file->length--;
if (file->last == file->first){
file = 0;
}else{
file->first = file->first->next;
}
return res;
}
int size (list l)
{
if (l==0) return 0;
return l->length;
}
list file = 0;
pthread_mutex_t file_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t new_elem = PTHREAD_COND_INITIALIZER;
int processed = 0;
void process_value (int v)
{
int i,j;
for (i=0;i<PROCESSING;i++) j++;
pthread_mutex_lock(&file_mutex);
put(v+1,&file);
pthread_cond_signal (&new_elem);
pthread_mutex_unlock(&file_mutex);
}
void* process (void *args)
{
pthread_mutex_lock(&file_mutex);
while (1) {
if (size(file) > 0){
int res = get (&file);
pthread_mutex_unlock(&file_mutex);
if (res == CYCLES){
PRINT("result: %d\\n",res);
processed++;
if (processed == PRODUCED) exit (0);
}else{
process_value(res);
}
pthread_mutex_lock(&file_mutex);
}else{
pthread_cond_wait (&new_elem,&file_mutex);
}
}
return 0;
}
void* produce (void *args)
{
int v = 0;
while (v < PRODUCED) {
pthread_mutex_lock (&file_mutex);
if (size(file) < FILE_SIZE){
put (0,&file);
PRINT("%d produced\\n",0);
pthread_cond_signal (&new_elem);
v++;
pthread_mutex_unlock (&file_mutex);
}else{
pthread_mutex_unlock(&file_mutex);
sched_yield();
}
}
return 0;
}
int main(void)
{
int i;
pthread_t producer;
pthread_t thread_array[MAX_THREADS];
for (i=0; i<MAX_THREADS; i++){
pthread_create (&thread_array[i],0,process,0);
}
pthread_create (&producer,0,produce,0);
pthread_exit (0);
return 0;
}
| 0
|
#include <pthread.h>
char *
strtok(s, delim)
register char *s;
register const char *delim;
{
static pthread_mutex_t strtok_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_key_t strtok_key = -1;
char **lasts;
pthread_mutex_lock(&strtok_mutex);
if (strtok_key < 0) {
if (pthread_key_create(&strtok_key, free) < 0) {
pthread_mutex_unlock(&strtok_mutex);
return(0);
}
}
pthread_mutex_unlock(&strtok_mutex);
if ((lasts = pthread_getspecific(strtok_key)) == 0) {
if ((lasts = (char **)malloc(sizeof(char *))) == 0) {
return(0);
}
pthread_setspecific(strtok_key, lasts);
}
return(strtok_r(s, delim, lasts));
}
char *
strtok_r(s, delim, lasts)
register char *s;
register const char *delim;
register char **lasts;
{
register char *spanp;
register int c, sc;
char *tok;
if (s == 0 && (s = *lasts) == 0)
return (0);
cont:
c = *s++;
for (spanp = (char *)delim; (sc = *spanp++) != 0;) {
if (c == sc)
goto cont;
}
if (c == 0) {
*lasts = 0;
return (0);
}
tok = s - 1;
for (;;) {
c = *s++;
spanp = (char *)delim;
do {
if ((sc = *spanp++) == c) {
if (c == 0)
s = 0;
else
s[-1] = 0;
*lasts = s;
return (tok);
}
} while (sc != 0);
}
}
| 1
|
#include <pthread.h>
int MaxLoop = 50000;
int NumProcs;
volatile int startCounter;
pthread_mutex_t threadLock;
unsigned sig[33] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32 };
union {
char b[64];
int value;
} m[64];
unsigned mix(unsigned i, unsigned j) {
return (i + j * 103995407) % 103072243;
}
void* ThreadBody(void* tid)
{
int threadId = *(int *) tid;
int i;
for(i=0; i<0x07ffffff; i++) {};
pthread_mutex_lock(&threadLock);
startCounter--;
if(startCounter == 0) {
}
pthread_mutex_unlock(&threadLock);
while(startCounter) {};
for(i = 0 ; i < MaxLoop; i++) {
unsigned num = sig[threadId];
unsigned index1 = num%64;
unsigned index2;
num = mix(num, m[index1].value);
index2 = num%64;
num = mix(num, m[index2].value);
m[index2].value = num;
sig[threadId] = num;
getuid();
if (i % (MaxLoop/200) == 0) {
const int wr = PROT_READ|PROT_WRITE;
const int rd = PROT_READ;
int k,*x = (int*)mmap(0, 4096, wr, MAP_ANONYMOUS|MAP_PRIVATE, 0, 0);
*x = 10;
mprotect(x, 4096, rd);
k = *x;
mprotect(x, 4096, PROT_NONE);
}
}
return 0;
}
int
main(int argc, char* argv[])
{
pthread_t* threads;
int* tids;
pthread_attr_t attr;
int ret;
int mix_sig, i;
if(argc < 2) {
fprintf(stderr, "%s <numProcesors> <maxLoop>\\n", argv[0]);
exit(1);
}
NumProcs = atoi(argv[1]);
assert(NumProcs > 0 && NumProcs <= 32);
if (argc >= 3) {
MaxLoop = atoi(argv[2]);
assert(MaxLoop > 0);
}
for(i = 0; i < 64; i++) {
m[i].value = mix(i,i);
}
startCounter = NumProcs;
threads = (pthread_t *) malloc(sizeof(pthread_t) * NumProcs);
assert(threads != 0);
tids = (int *) malloc(sizeof (int) * NumProcs);
assert(tids != 0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
ret = pthread_mutex_init(&threadLock, 0);
assert(ret == 0);
for(i=0; i < NumProcs; i++) {
tids[i] = i+1;
ret = pthread_create(&threads[i], &attr, ThreadBody, &tids[i]);
assert(ret == 0);
}
for(i=0; i < NumProcs; i++) {
ret = pthread_join(threads[i], 0);
assert(ret == 0);
}
mix_sig = sig[0];
for(i = 1; i < NumProcs ; i++) {
mix_sig = mix(sig[i], mix_sig);
}
printf("\\n\\nShort signature: %08x @ %p @ %p\\n\\n\\n",
mix_sig, &mix_sig, (void*)malloc((1 << 10)/5));
fflush(stdout);
usleep(5);
pthread_mutex_destroy(&threadLock);
pthread_attr_destroy(&attr);
return 0;
}
| 0
|
#include <pthread.h>
int stoj = 0;
int zameranie[4] = {0, 0, 1, 1};
int pocetVypisov[4] = {0};
int cakaju = 0;
int vsetciCakaju = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condCakaju = PTHREAD_COND_INITIALIZER;
void hadz(int murar) {
pthread_mutex_lock(&mutex);
if(stoj){
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
if(zameranie[murar] == 0){
pthread_mutex_lock(&mutex);
printf("MURAR %d: zacinam HADZAT\\n", murar);
pocetVypisov[murar]++;
pthread_mutex_unlock(&mutex);
sleep(2);
pthread_mutex_lock(&mutex);
printf("MURAR %d: skoncil somm HADZANIE\\n", murar);
pocetVypisov[murar]++;
pthread_mutex_unlock(&mutex);
}
}
void zarovnavaj(int murar) {
pthread_mutex_lock(&mutex);
if(stoj){
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
if(zameranie[murar] == 1){
pthread_mutex_lock(&mutex);
printf("MURAR %d: zacinam ZAROVNAVAT\\n", murar);
pocetVypisov[murar]++;
pthread_mutex_unlock(&mutex);
sleep(2);
pthread_mutex_lock(&mutex);
printf("MURAR %d: skoncil somm ZAROVNAVANIE\\n", murar);
pocetVypisov[murar]++;
pthread_mutex_unlock(&mutex);
}
}
void *murar(void *ptr) {
int murar = (int) ptr;
int i;
while(!stoj) {
hadz(murar);
zarovnavaj(murar);
pthread_mutex_lock(&mutex);
cakaju++;
if(cakaju == 4){
for(i=0; i<4; i++){
zameranie[i] = zameranie[i] == 0 ? 1 : 0;
}
vsetciCakaju = 1;
printf("Novy cyklus !!!\\n");
pthread_cond_broadcast(&condCakaju);
} else {
while(!vsetciCakaju){
if(stoj){
pthread_mutex_unlock(&mutex);
return 0;
}
pthread_cond_wait(&condCakaju, &mutex);
}
}
cakaju--;
if(cakaju == 0){
vsetciCakaju = 0;
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(void) {
int i;
pthread_t murari[4];
for (i=0;i<4;i++) pthread_create(&murari[i], 0, &murar, (void *) i);
sleep(27);
pthread_mutex_lock(&mutex);
stoj = 1;
printf("Koniec Simulacie !!!!\\n");
pthread_cond_broadcast(&condCakaju);
pthread_mutex_unlock(&mutex);
for (i=0;i<4;i++) pthread_join(murari[i], 0);
for (i=0;i<4;i++) printf("Murar %d vypisal: %dkrat\\n", i, pocetVypisov[i]);
exit(0);
}
| 1
|
#include <pthread.h>
int PBSD_manager(
int c,
int function,
int command,
int objtype,
char *objname,
struct attropl *aoplp,
char *extend,
int *local_errno)
{
int rc;
struct batch_reply *reply;
rc = PBSD_mgr_put(
c,
function,
command,
objtype,
objname,
aoplp,
extend);
if (rc != 0)
{
return(rc);
}
pthread_mutex_lock(connection[c].ch_mutex);
reply = PBSD_rdrpy(local_errno, c);
PBSD_FreeReply(reply);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
return(rc);
}
| 0
|
#include <pthread.h>
void *thread_function(void *);
pthread_mutex_t mutex1;
int counter = 0;
main() {
pthread_mutex_init(&mutex1, 0);
pthread_t thread_id[10];
int i, j;
printf("EBUSY:%d", EBUSY);
for (i = 0; i < 10; i++) {
pthread_create(&thread_id[i], 0, thread_function, 0);
}
for (j = 0; j < 10; j++) {
pthread_join(thread_id[j], 0);
}
printf("Final counter value: %d\\n", counter);
pthread_exit(0);
}
void *thread_function(void *dummyPtr) {
printf("Thread number %ld\\n", pthread_self());
pthread_mutex_lock(&mutex1);
counter++;
pthread_mutex_unlock(&mutex1);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int graph[100][100];
int dist[100][100];
int n,m;
int k;
pthread_mutex_t read_mutex;
pthread_mutex_t write_mutex;
int readers = 0;
int checker;
void *check_func(void *t)
{
long i = (long)t;
for(int j=0;j<n;j++)
{
pthread_mutex_lock(&read_mutex);
readers++;
if(readers == 1)
pthread_mutex_lock(&write_mutex);
pthread_mutex_unlock(&read_mutex);
checker = dist[i][k] + dist[k][j] < dist[i][j];
pthread_mutex_lock(&read_mutex);
readers--;
if(readers == 0)
{
pthread_mutex_unlock(&write_mutex);
}
pthread_mutex_unlock(&read_mutex);
if(checker)
{
pthread_mutex_lock(&write_mutex);
dist[i][j]=dist[i][k]+dist[k][j];
pthread_mutex_unlock(&write_mutex);
}
}
pthread_exit(0);
}
int main()
{
printf("Enter the no. of Nodes and no. of Undirected Edges\\n");
scanf("%d %d",&n,&m);
int u,v,w;
for(int i=0;i<m;i++)
{
scanf("%d %d %d",&u,&v,&w);
graph[u-1][v-1] = w;
graph[v-1][u-1] = w;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(i!=j && graph[i][j]==0)
{
graph[i][j] = 99999;
}
}
}
printf("\\n------- Initial Matrix --------\\n\\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (graph[i][j] == 99999)
{
printf("%7s", "INF");
}
else
{
printf ("%7d", graph[i][j]);
}
}
printf("\\n");
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
dist[i][j] = graph[i][j];
}
pthread_t mythread[100];
pthread_mutex_init(&read_mutex, 0);
pthread_mutex_init(&write_mutex, 0);
for(k=0;k<n;k++)
{
for(long i=0;i<n;i++)
{
if(pthread_create(&mythread[i], 0, check_func,(void *)i))
{
perror("Create Thread Failed:");
exit(0);
}
}
for(int i=0;i<n;i++)
{
if(pthread_join(mythread[i], 0))
{
perror("Joining Thread Failed:");
exit(0);
}
}
}
pthread_mutex_destroy(&read_mutex);
pthread_mutex_destroy(&read_mutex);
printf("\\n------- Final Distance Matrix --------\\n\\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (dist[i][j] == 99999)
{
printf("%7s", "INF");
}
else
{
printf ("%7d", dist[i][j]);
}
}
printf("\\n");
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
volatile int eR1 = 1;
volatile int eR2 = 0;
void* travail(void* _num){
int ressource;
pthread_mutex_lock(&mutex);
while (!eR1 && !eR2) {
pthread_cond_wait(&condition, &mutex);
}
if(eR1) {
eR1 = 0;
ressource = 1;
} else {
eR2 = 0;
ressource = 2;
}
pthread_mutex_unlock(&mutex);
printf("La ressource %d est utilisée par le thread n°%d\\n", ressource, _num);
sleep(1);
pthread_mutex_lock(&mutex);
if(ressource == 1)
eR1 = 1;
else
eR2 = 1;
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&mutex);
return 0;
}
int testTravail(void){
pthread_t filsA, filsB, filsC, filsD;
if (pthread_create(&filsA, 0, travail, (int*)1 )) perror("thread");
if (pthread_create(&filsB, 0, travail, (int*)2 )) perror("thread");
if (pthread_create(&filsC, 0, travail, (int*)3 )) perror("thread");
if (pthread_create(&filsD, 0, travail, (int*)4 )) perror("thread");
if (pthread_join(filsA, 0)) perror("pthread_join");
if (pthread_join(filsB, 0)) perror("pthread_join");
if (pthread_join(filsC, 0)) perror("pthread_join");
if (pthread_join(filsD, 0)) perror("pthread_join");
return (0);
}
volatile int FOUR[(4)];
void* philo(void * _phil){
long phil = (long) _phil;
long num_gauche = phil;
long num_droit;
num_droit = (phil+1) % (4);
pthread_mutex_lock(&mutex);
while (!(FOUR[num_gauche] && FOUR[num_droit])) {
pthread_cond_wait(&condition, &mutex);
}
FOUR[num_gauche] = 0;
FOUR[num_droit] = 0;
pthread_mutex_unlock(&mutex);
printf("Le philosophe %d utilise les fourchettes (%d et %d)\\n", phil, num_gauche, num_droit);
printf("Le philosophe %d mange\\n", phil);
sleep(1);
pthread_mutex_lock(&mutex);
printf("Le philosophe %d repose les fourchettes\\n", phil);
FOUR[num_gauche] = 1;
FOUR[num_droit] = 1;
printf("Le philosophe %d pense\\n", phil);
pthread_cond_broadcast(&condition);
pthread_mutex_unlock(&mutex);
return 0;
}
int main(){
pthread_t fils[(4)];
int j;
for(j = 0; j < (4); j++){
FOUR[j] = 1;
}
long i;
for(i = 0; i < (4); i++){
if (pthread_create(&fils[i], 0, philo, (void*) i )) perror("thread");
}
for(i = 0; i < (4); i++)
if (pthread_join(fils[i], 0)) perror("pthread_join");
return (0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t s_mutex;
static void cleanup_handler(void* param)
{
fprintf(stderr, "Cleanup handler has been called.\\n");
pthread_mutex_unlock(&s_mutex);
}
static void* f(void *p)
{
if (pthread_mutex_lock(&s_mutex) != 0)
{
fprintf(stderr, "pthread_mutex_lock()\\n");
exit(1);
}
pthread_cleanup_push(cleanup_handler, 0);
pthread_exit(0);
pthread_cleanup_pop(1);
}
int main()
{
pthread_t pt1, pt2;
alarm(20);
if (pthread_mutex_init(&s_mutex, 0) != 0)
{
fprintf(stderr, "pthread_mutex_init()\\n");
exit(1);
}
if (pthread_create(&pt1, 0, f, 0) != 0)
{
fprintf(stderr, "pthread_create()\\n");
exit(1);
}
if (pthread_create(&pt2, 0, f, 0) != 0)
{
fprintf(stderr, "pthread_create()\\n");
exit(1);
}
pthread_join(pt1, 0);
pthread_join(pt2, 0);
fprintf(stderr, "Test succeeded.\\n");
return 0;
}
| 0
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error();
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(5))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (get_top()==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(5);
if (push(arr,tmp)==(-1))
error();
flag=(1);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (flag)
{
if (!(pop(arr)!=(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int done;
pthread_cond_t *conds;
pthread_mutex_t *mtxs;
void *f( void *p )
{
long i = (long)p;
pthread_mutex_lock( &mtxs[i] );
while( !done )
{
pthread_cond_wait( &conds[i], &mtxs[i] );
}
pthread_mutex_unlock( &mtxs[i] );
}
int main( int argc, char ** argv )
{
long limit, i;
for( limit = 1; limit < 1000000000; limit *= 2 )
{
printf( "Lets try spawning %ld threads\\n", limit ); fflush( stdout );
pthread_t *threads = (pthread_t *)malloc( limit * sizeof( threads[0] ) );
conds = (pthread_cond_t *)malloc( limit * sizeof( conds[0] ) );
mtxs = (pthread_mutex_t *)malloc( limit * sizeof( mtxs[0] ) );
done = 0;
for( i = 0; i < limit; ++i )
{
pthread_mutex_init( &mtxs[i], 0 );
pthread_cond_init( &conds[i], 0 );
pthread_create( &threads[i], 0, f, (void *)i );
}
done = 1;
for( i = 0; i < limit; ++i )
{
pthread_mutex_lock( &mtxs[i] );
pthread_mutex_unlock( &mtxs[i] );
pthread_cond_signal( &conds[i] );
pthread_join( threads[i], 0 );
}
free( threads );
free( conds );
free( mtxs );
}
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
pthread_mutex_t mutexsum;
DOTDATA dotstr;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",
offset,start,end,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
int NUMTHRDS = atoi(argv[1]);
int VECLEN = atoi(argv[2]);
pthread_t callThd[NUMTHRDS];
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));
b = (double*) malloc (NUMTHRDS*VECLEN*sizeof(double));
for (i=0; i<VECLEN*NUMTHRDS; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = VECLEN;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<NUMTHRDS;i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<NUMTHRDS;i++) {
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
enum log_level {
DEBUG = 0,
INFO = 1,
ERROR = 2
};
pthread_t tid[1];
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int g_isRunning = 1;
int g_logLevel = DEBUG;
struct mpd_connection *conn;
void
INT_handler(){
g_isRunning = 0;
}
void
log_message(int level, char *format, ...)
{
if(level >= g_logLevel) {
va_list arglist;
__builtin_va_start((arglist));
vfprintf( stderr, format, arglist );
;
fprintf(stderr,"\\n");
}
}
static int
handle_error(struct mpd_connection *c)
{
int err = mpd_connection_get_error(c);
assert(err != MPD_ERROR_SUCCESS);
log_message(DEBUG, "%i --> %s\\n", mpd_connection_get_error_message(c));
mpd_connection_free(c);
return 1;
}
bool
run_play_pos(struct mpd_connection *c, int pos)
{
if(!mpd_run_play_pos(c,pos)) {
if(mpd_connection_get_error(c) != MPD_ERROR_SERVER)
return handle_error(c);
}
return 1;
}
void
finish_command(struct mpd_connection *conn)
{
if (!mpd_response_finish(conn))
handle_error(conn);
}
struct mpd_status *
get_status(struct mpd_connection *conn)
{
struct mpd_status *ret = mpd_run_status(conn);
if (ret == 0)
handle_error(conn);
return ret;
}
bool
set_mute_state(struct mpd_connection *conn,bool mute)
{
static int lastVolume = -1;
int volume = -1;
struct mpd_status *status;
if(mute)
{
status = get_status(conn);
lastVolume = mpd_status_get_volume(status);
mpd_run_set_volume(conn,0);
}
else
{
if(lastVolume >= 0 && lastVolume <= 100)
{
mpd_run_set_volume(conn,lastVolume);
}
}
}
void* monitor(void *arg)
{
pthread_t id = pthread_self();
unsigned long cnt=0;
while(g_isRunning) {
log_message(INFO,"%i: thread keepalive %10ld",id,cnt);
pthread_mutex_lock( &mutex1 );
if(!mpd_run_change_volume(conn,0))
if(!mpd_connection_clear_error(conn))
handle_error(conn);
cnt++;
pthread_mutex_unlock( &mutex1 );
usleep(5000000);
}
log_message(INFO,"%i: leaving thread",id);
pthread_exit(0);
}
int main()
{
char devname[] = "/dev/input/event0";
int device;
struct input_event ev;
struct mpd_status* mpd_state_ptr;
int rc;
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
conn = mpd_connection_new(0, 0, 30000);
if (mpd_connection_get_error(conn) != MPD_ERROR_SUCCESS)
return handle_error(conn);
rc = pthread_create(&(tid[0]), &attr, &monitor, 0);
pthread_attr_destroy(&attr);
device = open(devname, O_RDONLY);
signal(SIGINT, INT_handler);
while(g_isRunning!=0)
{
read(device, &ev, sizeof(ev));
if(ev.type != EV_KEY)
continue;
pthread_mutex_lock( &mutex1 );
switch(ev.code) {
case KEY_POWER:
log_message(INFO,">>> POWER");
break;
case KEY_MUTE:
if(ev.value == 1) {
if(!mpd_run_change_volume(conn,-1))
if(!mpd_connection_clear_error(conn))
handle_error(conn);
log_message(INFO,">>> MUTE");
}
break;
case KEY_STOP:
if(ev.value == 1) {
mpd_state_ptr = get_status(conn);
if(mpd_status_get_state(mpd_state_ptr) == MPD_STATE_PLAY ||
mpd_status_get_state(mpd_state_ptr) == MPD_STATE_PAUSE) {
if(!mpd_run_stop(conn))
handle_error(conn);
log_message(INFO,">>> STOP");
}
mpd_status_free(mpd_state_ptr);
}
break;
case KEY_PLAYPAUSE:
if(ev.value == 1) {
mpd_state_ptr = get_status(conn);
switch(mpd_status_get_state(mpd_state_ptr)) {
case MPD_STATE_PLAY:
mpd_send_pause(conn,1);
finish_command(conn);
break;
case MPD_STATE_PAUSE:
if(!mpd_run_play(conn))
handle_error(conn);
break;
case MPD_STATE_STOP:
if(!mpd_run_play(conn))
handle_error(conn);
break;
default:
break;
}
mpd_status_free(mpd_state_ptr);
log_message(INFO,">>> PLAYPAUSE");
}
break;
case KEY_VOLUMEUP:
if(ev.value == 1 || ev.value == 2) {
if(!mpd_run_change_volume(conn,1))
if(!mpd_connection_clear_error(conn))
handle_error(conn);
log_message(INFO,">>> VOLUMEUP");
}
break;
case KEY_VOLUMEDOWN:
if(ev.value == 1 || ev.value == 2) {
if(!mpd_run_change_volume(conn,-1))
if(!mpd_connection_clear_error(conn))
handle_error(conn);
log_message(INFO,">>> VOLUMEDOWN");
}
break;
case KEY_NEXT:
if(ev.value == 1) {
if(!mpd_run_next(conn))
handle_error(conn);
log_message(INFO,">>> NEXT");
}
break;
case KEY_PREVIOUS:
if(ev.value == 1) {
if(!mpd_run_previous(conn))
handle_error(conn);
log_message(INFO,">>> PREVIOUS");
}
break;
case KEY_1:
if(ev.value == 1)
run_play_pos(conn, 0);
break;
case KEY_2:
if(ev.value == 1)
run_play_pos(conn, 1);
break;
case KEY_3:
if(ev.value == 1)
run_play_pos(conn, 2);
break;
case KEY_4:
if(ev.value == 1)
run_play_pos(conn, 3);
break;
case KEY_5:
if(ev.value == 1)
run_play_pos(conn, 4);
break;
case KEY_6:
if(ev.value == 1)
run_play_pos(conn, 5);
break;
case KEY_7:
if(ev.value == 1)
run_play_pos(conn, 6);
break;
case KEY_8:
if(ev.value == 1)
run_play_pos(conn, 7);
break;
case KEY_9:
if(ev.value == 1)
run_play_pos(conn, 8);
break;
default:
continue;
}
log_message(DEBUG,"\\tKey: %i/0x%x Type: %i State: %i",ev.code,ev.code,ev.type,ev.value);
pthread_mutex_unlock( &mutex1 );
}
pthread_mutex_destroy(&mutex1);
rc = pthread_join(tid[0], &status);
log_message(DEBUG,"%i: thread join (rc=%i)",tid[0],rc);
mpd_connection_free(conn);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int nitems;
struct
{
pthread_mutex_t mutex;
int buff[100000];
int nput;
int nval;
}shared = {PTHREAD_MUTEX_INITIALIZER};
void *produce(void *);
void *consume(void *);
int main(int argc, char const *argv[])
{
int i,nthreads,count[100];
pthread_t tid_produce[100],tid_consume;
if (3 != argc)
{
printf("Usage :produce items threads\\n");
exit(-1);
}
nitems = ((atoi(argv[1]))<(100000) ?(atoi(argv[1])):(100000));
nthreads = ((atoi(argv[2]))<(100) ?(atoi(argv[2])):(100));
pthread_setconcurrency(nthreads);
for (i = 0; i < nthreads; ++i)
{
count[i] = 0;
pthread_create(&tid_produce[i],0,produce,&count[i]);
}
for (i = 0; i < nthreads; ++i)
{
pthread_join(tid_produce[i],0);
printf("count[%d] = %d\\n", i,count[i]);
}
pthread_create(&tid_consume,0,consume,0);
pthread_join(tid_consume,0);
return 0;
}
void * produce(void *arg)
{
for (;;)
{
pthread_mutex_lock(&shared.mutex);
if (shared.nput >= nitems)
{
pthread_mutex_unlock(&shared.mutex);
return 0;
}
shared.buff[shared.nput] = shared.nval;
shared.nput++;
shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*((int*)arg) +=1;
}
}
void * consume(void *arg)
{
int i;
for (i = 0; i < nitems; ++i)
{
if (shared.buff[i] != i)
{
printf("buff[%d] = %d\\n", i,shared.buff[i]);
}
}
return 0;
}
| 1
|
#include <pthread.h>
void eroare (int check, char* mesaj) {
if (check < 0) {
printf("%s\\n", mesaj);
exit(1);
}
}
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
char sir[105];
int len = 0;
int checkSolve(){
if (strstr(sir,"succes"))
return 1;
return 0;
}
void* deservireClient(void* arg) {
int c = (int)arg;
char ch;
recv(c, &ch, sizeof(ch), 0);
if (!isalpha(ch))
{
printf("Nu am primit un caracter.\\n");
}
else {
pthread_mutex_lock(&mtx);
sir[len++] = ch;
printf("Sir = %s\\n", sir);
if(checkSolve() == 1)
{
printf("Felicitari\\n");
exit(0);
}
pthread_mutex_unlock(&mtx);
}
return 0;
}
int main(int argc, char* argv[]) {
struct sockaddr_in server, client;
int s, c, port, l;
if (argc != 2) eroare(-1, "Use : ./t1s.exe port");
for (int i = 0; i < strlen(argv[1]); ++i)
if (!isdigit(argv[1][i]))
{
printf("Port incorect.\\n" );
return 0;
}
port = atoi(argv[1]);
s = socket(AF_INET, SOCK_STREAM, 0);
eroare(s, "Eroare la socket server.");
memset(&server, 0, sizeof(server));
memset(&client, 0, sizeof(client));
l = sizeof(client);
server.sin_port = htons(port);
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
eroare(bind(s, (struct sockaddr *) &server, sizeof(server)), "Eroare la bind server.");
listen(s, 5);
while(1) {
pthread_t thread;
c = accept(s, (struct sockaddr *) &client, &l);
eroare(pthread_create(&thread, 0, deservireClient, (void*)c), "Eroare la crearea threadului.");
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void *pthread_fun(void *arg)
{
void *ret;
int i;
int j;
pthread_mutex_lock(&mutex);
for(j = 0; j < 3; j++)
{
if(0 == (int)arg)
{
printf("thread %d is working.\\n", (int)arg);
sleep(1);
}
else if(1 == (int)arg)
{
printf("thread %d is working.\\n", (int)arg);
sleep(1);
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
void *pthread_fun1(void *arg)
{
void *ret;
int i;
int j;
if(0 == (int)arg)
{
pthread_mutex_lock(&mutex);
printf("thread %d is working.\\n", (int)arg);
sleep(1);
pthread_mutex_unlock(&mutex);
}
else if(1 == (int)arg)
{
pthread_mutex_lock(&mutex);
printf("thread %d is working.\\n", (int)arg);
sleep(1);
pthread_mutex_unlock(&mutex);
}
}
int main(int argc, const char *argv[])
{
pthread_t pthread[3];
int i = 0;
void *retval;
pthread_mutex_init(&mutex, 0);
for(i = 0; i < 2; i++)
{
if(pthread_create(&pthread[i], 0, pthread_fun, (void *)i) != 0 )
{
perror("pthread_create error");
exit(-1);
}
printf("thread %d is created, waiting to finish...\\n", i);
}
for(i = 0; i < 2; i++)
{
if(pthread_join(pthread[i], &retval) != 0)
printf("thread %d is joined failed\\n", i);
else
printf("thread %d is joined\\n", i);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
static int top=0;
static unsigned int arr[(6)];
pthread_mutex_t m;
int flag=(0);
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(6))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
int j;
for(i=0; i<(6); i++)
{
pthread_mutex_lock(&m);
j=push(arr,55);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
top=top;
make_taint(&top);
for(i=0; i<(6); i++)
{
pthread_mutex_lock(&m);
if (top>0)
pop(arr);
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct servent *getservbyname(const char *name, const char *proto)
{
char *buf = _serv_buf();
if (!buf)
return 0;
return getservbyname_r(name, proto, (struct servent *) buf,
buf + sizeof(struct servent), SERV_BUFSIZE);
}
struct servent *getservbyname_r(const char *name, const char *proto,
struct servent *result, char *buf, int bufsize)
{
char **alias;
pthread_mutex_lock(&serv_iterate_lock);
setservent(0);
while ((result = getservent_r(result, buf, bufsize)) != 0) {
if (strcmp(result->s_name, name) != 0) {
for (alias = result->s_aliases; *alias != 0; alias++) {
if (strcmp(*alias, name) == 0)
break;
}
if (*alias == 0)
continue;
}
if (proto == 0 || strcmp(result->s_proto, proto) == 0)
break;
}
pthread_mutex_unlock(&serv_iterate_lock);
return result;
}
| 1
|
#include <pthread.h>
struct screen_gtk_t {
const struct screen_ops_t *ops;
pthread_t thread;
struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
int ev;
} event;
};
static void *screen_gtk_thread(void *parm);
static struct screen_t *screen_gtk_new(int *argcp, char **argv)
{
struct screen_gtk_t *w = malloc(sizeof *w);
if (!gtk_init_check(argcp, &argv))
return 0;
memset(w, 0, sizeof *w);
w->ops = &screen_gtk_ops;
pthread_mutex_init(&w->event.mutex, 0);
pthread_cond_init(&w->event.cond, 0);
pthread_create(&w->thread, 0, screen_gtk_thread, w);
return (struct screen_t *) w;
}
static void *screen_gtk_thread(void *parm)
{
struct screen_gtk_t *w = parm;
GtkWidget *top;
top = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_show_all(top);
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);
printf("screen update.\\n");
}
return 0;
}
static void screen_gtk_notify_update(struct screen_t *scr)
{
struct screen_gtk_t *w = (struct screen_gtk_t *) scr;
pthread_mutex_lock(&w->event.mutex);
w->event.ev = 1;
pthread_cond_signal(&w->event.cond);
pthread_mutex_unlock(&w->event.mutex);
}
struct screen_ops_t screen_gtk_ops = {
.new = screen_gtk_new,
.notify_update = screen_gtk_notify_update,
};
| 0
|
#include <pthread.h>
struct Seller* createSeller(char priority, int ordinal, struct BuyerQueue* bqs, struct Seatmap* map)
{
struct Seller* s = (struct Seller*)malloc(sizeof(struct Seller));
s->priority = priority;
s->ordinal = ordinal;
s->q = bqs;
strcat(s->name, &s->priority);
char cord[2];
sprintf(cord,"%d",ordinal);
strcat(s->name, cord);
s->map = map;
return s;
}
void* sell(void * seller)
{
struct Seller* s = (struct Seller*)seller;
char* name = s->name;
struct Seatmap* map = s->map;
pthread_mutex_t* mutex = map->mutex;
pthread_cond_t* cond = map->cond;
pthread_mutex_lock(mutex);
pthread_cond_wait(cond, mutex);
pthread_mutex_unlock(mutex);
time_t start_time = time(0);
int do_work = 1;
struct BuyerQueue* q = s->q;
struct Buyer* b = BuyerQueue_dequeue (s->q);
int next_op = b->arrival_time;
while(do_work == 1)
{
if(get_time(start_time) > 60)
{
end_thread(s,get_time(start_time));
return 0;
}
if(next_op <= get_time(start_time))
{
pthread_mutex_lock(mutex);
int seat = sell_seat(map, b);
int wait_time = 0;
switch(b->priority){
case 'H': wait_time = (rand() % 2) + 1;
break;
case 'M': wait_time = (rand() % 3) + 2;
break;
default: wait_time = (rand() % 4) + 4;
}
sleep(wait_time);
if(seat == -1)
{
printf("00:%02d Customer %s didn't get a seat. no more seats for seller %s\\n",(int)get_time(start_time), b->name, name);
}else{
printf("00:%02d Customer %s got seat %d\\n",(int)get_time(start_time), b->name,seat);
}
print_seatmap(map);
pthread_mutex_unlock(mutex);
b = BuyerQueue_dequeue ( s->q);
if(b == 0)
{
do_work = 0;
end_thread(seller,get_time(start_time));
}else{
next_op = b->arrival_time;
}
}
}
return 0;
}
time_t get_time(time_t from)
{
return time(0) - from;
}
void end_thread(struct Seller* s, time_t end_time)
{
printf("00:%02d Seller %s closing out\\n",(int) end_time, s->name);
}
| 1
|
#include <pthread.h>
struct circqueue {
unsigned int head;
unsigned int tail;
unsigned int count;
unsigned int max_entries;
unsigned int array_elements;
void **entries;
};
struct event_mq {
int push_fd;
int pop_fd;
int unlock_between_callbacks;
struct event queue_ev;
pthread_mutex_t lock;
void (*callback)(void *, void *);
void *cbarg;
struct circqueue *queue;
};
static unsigned int nextpow2(unsigned int num) {
--num;
num |= num >> 1;
num |= num >> 2;
num |= num >> 4;
num |= num >> 8;
num |= num >> 16;
return ++num;
}
static struct circqueue *circqueue_new(unsigned int size) {
struct circqueue *cq;
if (!(cq = calloc(1, sizeof(struct circqueue))))
return(0);
cq->max_entries = size;
if (!size || !(cq->array_elements = nextpow2(size)))
cq->array_elements = 1024;
cq->entries = malloc(sizeof(void *) * cq->array_elements);
if (!cq->entries) {
free(cq);
return(0);
}
return(cq);
}
static void circqueue_destroy(struct circqueue *cq) {
free(cq->entries);
free(cq);
}
static int circqueue_grow(struct circqueue *cq) {
void **newents;
unsigned int newsize = cq->array_elements << 1;
unsigned int headchunklen = 0, tailchunklen = 0;
if (!(newents = malloc(sizeof(void *) * newsize)))
return(-1);
if (cq->head < cq->tail)
headchunklen = cq->tail - cq->head;
else {
headchunklen = cq->array_elements - cq->head;
tailchunklen = cq->tail;
}
memcpy(newents, &cq->entries[cq->head], sizeof(void *) * headchunklen);
if (tailchunklen)
memcpy(&newents[headchunklen], cq->entries, sizeof(void *) * tailchunklen);
cq->head = 0;
cq->tail = headchunklen + tailchunklen;
cq->array_elements = newsize;
free(cq->entries);
cq->entries = newents;
return(0);
}
static int circqueue_push_tail(struct circqueue *cq, void *elem) {
if (cq->max_entries) {
if (cq->count == cq->max_entries)
return(-1);
} else if (((cq)->count == (cq)->array_elements) && circqueue_grow(cq) != 0)
return(-1);
cq->count++;
cq->entries[cq->tail++] = elem;
cq->tail &= cq->array_elements - 1;
return(0);
}
static void *circqueue_pop_head(struct circqueue *cq) {
void *data;
if (!cq->count)
return(0);
cq->count--;
data = cq->entries[cq->head++];
cq->head &= cq->array_elements - 1;
return(data);
}
static void emq_pop(int fd, short flags, void *arg) {
struct event_mq *msgq = arg;
char buf[64];
recv(fd, buf, sizeof(buf),0);
pthread_mutex_lock(&msgq->lock);
while(!(!((msgq->queue)->count))) {
void *qdata;
qdata = circqueue_pop_head(msgq->queue);
if (msgq->unlock_between_callbacks)
pthread_mutex_unlock(&msgq->lock);
msgq->callback(qdata, msgq->cbarg);
if (msgq->unlock_between_callbacks)
pthread_mutex_lock(&msgq->lock);
}
pthread_mutex_unlock(&msgq->lock);
}
struct event_mq *emq_new(struct event_base *base, unsigned int max_size, void (*callback)(void *, void *), void *cbarg) {
struct event_mq *msgq;
struct circqueue *cq;
int fds[2];
if (!(cq = circqueue_new(max_size)))
return(0);
if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) {
circqueue_destroy(cq);
return(0);
}
if (!(msgq = malloc(sizeof(struct event_mq)))) {
circqueue_destroy(cq);
close(fds[0]);
close(fds[1]);
return(0);
}
msgq->push_fd = fds[0];
msgq->pop_fd = fds[1];
msgq->queue = cq;
msgq->callback = callback;
msgq->cbarg = cbarg;
pthread_mutex_init(&msgq->lock, 0);
event_set(&msgq->queue_ev, msgq->pop_fd, EV_READ | EV_PERSIST, emq_pop, msgq);
event_base_set(base, &msgq->queue_ev);
event_add(&msgq->queue_ev, 0);
msgq->unlock_between_callbacks = 1;
return(msgq);
}
void emq_destroy(struct event_mq *msgq)
{
for( ; emq_length(msgq) > 0; ) {
sleep( 1 );
}
event_del(&msgq->queue_ev);
circqueue_destroy(msgq->queue);
close(msgq->push_fd);
close(msgq->pop_fd);
free(msgq);
}
int emq_push(struct event_mq *msgq, void *msg) {
const char buf[1] = { 0 };
int r = 0;
pthread_mutex_lock(&msgq->lock);
if ((r = circqueue_push_tail(msgq->queue, msg)) == 0) {
if (((msgq->queue)->count) == 1)
send(msgq->push_fd, buf, 1,0);
}
pthread_mutex_unlock(&msgq->lock);
return(r);
}
unsigned int emq_length(struct event_mq *msgq) {
unsigned int len;
pthread_mutex_lock(&msgq->lock);
len = ((msgq->queue)->count);
pthread_mutex_unlock(&msgq->lock);
return(len);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
void *thread1(void *args)
{
pthread_mutex_lock(&m1);
sleep(1);
pthread_mutex_lock(&m2);
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
printf("thread1 finish\\n");
}
void *thread2(void *args)
{
pthread_mutex_lock(&m2);
sleep(1);
pthread_mutex_lock(&m1);
pthread_mutex_unlock(&m1);
pthread_mutex_unlock(&m2);
printf("thread2 finish\\n");
}
int main(void)
{
int rc,t = 0;
pthread_t t1, t2;
printf("Creating thread...\\n");
pthread_create(&t1, 0, thread1, (void *)t);
pthread_create(&t2, 0, thread2, (void *)t);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("Create thread finish\\n");
pthread_mutex_destroy(&m1);
pthread_mutex_destroy(&m2);
return 0;
}
| 1
|
#include <pthread.h>
int mutex_get_int(pthread_mutex_t *mutex, int *i)
{
int ret;
pthread_mutex_lock(mutex);
ret = *i;
pthread_mutex_unlock(mutex);
return (ret);
}
| 0
|
#include <pthread.h>
char* key;
char* value;
size_t value_len;
struct hash_item** pprev;
struct hash_item* next;
} hash_item;
hash_item* hash[1024];
pthread_mutex_t hash_mutex[1024];
hash_item* hash_get(const char* key, int create) {
unsigned b = string_hash(key) % 1024;
hash_item* h = hash[b];
while (h != 0 && strcmp(h->key, key) != 0) {
h = h->next;
}
if (h == 0 && create) {
h = (hash_item*) malloc(sizeof(hash_item));
h->key = strdup(key);
h->value = 0;
h->value_len = 0;
h->pprev = &hash[b];
h->next = hash[b];
hash[b] = h;
if (h->next != 0) {
h->next->pprev = &h->next;
}
}
return h;
}
void* connection_thread(void* arg) {
int cfd = (int) (uintptr_t) arg;
FILE* fin = fdopen(cfd, "r");
FILE* f = fdopen(cfd, "w");
pthread_detach(pthread_self());
char buf[1024], key[1024];
size_t sz;
while (fgets(buf, 1024, fin)) {
if (sscanf(buf, "get %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
fprintf(f, "VALUE %s %zu %p\\r\\n",
key, h->value_len, h);
fwrite(h->value, 1, h->value_len, f);
fprintf(f, "\\r\\n");
}
fprintf(f, "END\\r\\n");
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 1);
free(h->value);
h->value = (char*) malloc(sz);
h->value_len = sz;
fread(h->value, 1, sz, fin);
fprintf(f, "STORED %p\\r\\n", h);
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "delete %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
free(h->key);
free(h->value);
*h->pprev = h->next;
if (h->next) {
h->next->pprev = h->pprev;
}
free(h);
fprintf(f, "DELETED %p\\r\\n", h);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (remove_trailing_whitespace(buf)) {
fprintf(f, "ERROR\\r\\n");
fflush(f);
}
}
if (ferror(fin)) {
perror("read");
}
fclose(fin);
(void) fclose(f);
return 0;
}
int main(int argc, char** argv) {
for (int i = 0; i != 1024; ++i) {
pthread_mutex_init(&hash_mutex[i], 0);
}
int port = 6168;
if (argc >= 2) {
port = strtol(argv[1], 0, 0);
assert(port > 0 && port <= 65535);
}
int fd = open_listen_socket(port);
assert(fd >= 0);
while (1) {
int cfd = accept(fd, 0, 0);
if (cfd < 0) {
perror("accept");
exit(1);
}
pthread_t t;
int r = pthread_create(&t, 0, connection_thread,
(void*) (uintptr_t) cfd);
if (r != 0) {
perror("pthread_create");
exit(1);
}
}
}
| 1
|
#include <pthread.h>
int fibonacci(int);
int factorial(int);
int greater(int);
int less(int);
void * parallel_kernel(void * arg);
int (*function)(int);
int result;
} Register;
struct repository {
Register * registers;
};
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int SHARED_INDEX = 0;
struct repository * repo;
int main() {
int i = 0;
repo = (struct repository *) malloc (sizeof(struct repository));
Register A = {(void *) fibonacci, 0};
Register B = {(void *) factorial, 0};
Register C = {(void *) greater, 0};
Register D = {(void *) less, 0};
repo->registers = (Register *) malloc (4 * sizeof(Register));
repo->registers[0] = A;
repo->registers[1] = B;
repo->registers[2] = C;
repo->registers[3] = D;
pthread_t * ptr_thread = (pthread_t *) malloc (2 * sizeof(pthread_t));
for (i = 0; i < 2; i++) {
pthread_create(&ptr_thread[i], 0, ¶llel_kernel, (void *) repo);
}
for (i = 0; i < 2; i++) {
pthread_join(ptr_thread[i], 0);
}
printf(" *****************************\\n");
for (i = 0; i < 4; i++) {
printf("REG[%d] - RESULT[%d]\\n", i, repo->registers[i].result);
}
return 0;
}
void * parallel_kernel(void *arg) {
struct repository *p = (struct repository *) arg;
int idx = 0;
int result = 0;
while (1) {
pthread_mutex_lock(&mutex);
idx = SHARED_INDEX;
SHARED_INDEX++;
pthread_mutex_unlock(&mutex);
if (idx < 4) {
result = p->registers[idx].function(10);
printf("IDX[%d] - RESULT[%d]\\n", idx, result);
p->registers[idx].result = result;
} else {
pthread_exit(0);
}
}
return 0;
};
int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
int factorial(int n) {
if (n <= 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int greater(int n) {
return n;
}
int less(int n) {
return n;
}
| 0
|
#include <pthread.h>
int available[3];
int maximum[5][3];
int allocation[5][3];
int need[5][3];
pthread_mutex_t mutex;
void sleep_rand(void) {
sleep(rand() % 5 + 1);
}
int is_safe(void) {
int work[3], finish[5], i, j;
for (i = 0; i < 3; i++) {
work[i] = available[i];
}
for (i = 0; i < 5; i++) {
finish[i] = 0;
}
for (i = 0; i < 5; i++) {
int leseq_to_work = 1;
for (j = 0; j < 3; j++) {
if (need[i][j] > work[j]) {
leseq_to_work = 0;
break;
}
}
if (!finish[i] && leseq_to_work) {
for (j = 0; j < 3; j++) {
work[j] += allocation[i][j];
finish[i] = 1;
i = 0;
}
}
}
for (i = 0; i < 5; i++) {
if (!finish[i]) {
return 0;
}
}
return 1;
}
int request_resources(int customer_num, int request[]) {
pthread_mutex_lock(&mutex);
int i;
for (i = 0; i < 3; i++) {
if (request[i] > need[customer_num][i]) {
printf("Exceeded maximum claim!\\n");
pthread_mutex_unlock(&mutex);
return -1;
}
}
for (i = 0; i < 3; i++) {
if (request[i] > available[i]) {
printf("Customer %d should wait...\\n", customer_num);
pthread_mutex_unlock(&mutex);
return -1;
}
}
for (i = 0; i < 3; i++) {
available[i] -= request[i];
allocation[customer_num][i] += request[i];
need[customer_num][i] -= request[i];
}
if (is_safe()) {
printf("Customer %d completed a transaction!\\n", customer_num);
pthread_mutex_unlock(&mutex);
return 1;
} else {
printf("Customer %d requested to an unsafe state, thus is denied\\n", customer_num);
for (i = 0; i < 3; i++) {
available[i] += request[i];
allocation[customer_num][i] -= request[i];
need[customer_num][i] += request[i];
}
pthread_mutex_unlock(&mutex);
return -1;
}
}
int release_resources(int customer_num, int release[]) {
int i;
pthread_mutex_lock(&mutex);
for (i = 0; i < 3; i++) {
allocation[customer_num][i] -= release[i];
available[i] += release[i];
if (allocation[customer_num][i] < 0) {
return -1;
}
}
pthread_mutex_unlock(&mutex);
return 1;
}
int is_all_zero(int len, int * arr) {
int i;
for (i = 0; i < len; i++) {
if (arr[i] != 0) {
return 0;
}
}
return 1;
}
void *customer(void *param) {
int id = *((int *) param);
int resource[3];
while (1) {
if (is_all_zero(3, need[id])) {
break;
}
sleep_rand();
int i;
for (i = 0; i < 3; i++) {
if (need[id][i] == 0) {
resource[i] = 0;
continue;
}
resource[i] = rand() % need[id][i] + 1;
}
if (request_resources(id, resource) == -1) {
continue;
}
sleep_rand();
if (release_resources(id, resource) == -1) {
fprintf(stderr, "Error Occur While Releasing Resources!\\n");
pthread_exit(0);
}
}
pthread_exit(0);
}
int main(int argc, char *argv[]) {
if (argc != 3 + 1) {
fprintf(stderr, "You should enter %d integers indicating the instances of resource types.\\n", 3);
return 1;
}
srand(time(0));
int i, j;
for (i = 0; i < 3; i++) {
available[i] = atoi(argv[i+1]);
}
for (i = 0; i < 5; i++) {
for (j = 0; j < 3; j++) {
scanf("%d", &maximum[i][j]);
need[i][j] = maximum[i][j];
allocation[i][j] = 0;
}
}
pthread_mutex_init(&mutex, 0);
pthread_t tid[5];
pthread_attr_t attr;
int customer_id[5];
pthread_attr_init(&attr);
for (i = 0; i < 5; i++) {
customer_id[i] = i;
pthread_create(&tid[i], &attr, customer, (void *) &customer_id[i]);
}
for (i = 0; i < 5; i++) {
pthread_join(tid[i], 0);
}
printf("DONE!\\n");
return 0;
}
| 1
|
#include <pthread.h>
sem_t tofu, bread, BBQSauce, agent_semaphore, tofu_semaphore, bread_semaphore, BBQSauce_semaphore;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int loaves = 0, bottles = 0, tofu_blocks = 0;
void eat_sandwich(void) {
sleep(4);
}
void *bread_baker(void *_ ) {
while (1) {
printf("Baker is waiting to eat.\\n");
sem_wait(&bread_semaphore);
printf("Baker is eating.\\n");
eat_sandwich();
printf("Baker is done eating.\\n\\n");
sem_post(&agent_semaphore);
}
}
void *BBQSauce_mixer(void *_ ) {
while (1) {
printf("BBQSauce mixer is waiting to eat.\\n");
sem_wait(&BBQSauce_semaphore);
printf("BBQSauce mixer is eating.\\n");
eat_sandwich();
printf("BBQSauce is done eating.\\n\\n");
sem_post(&agent_semaphore);
}
}
void *tofu_coagulator(void *_ ) {
while (1) {
printf("Tofu coagulator is waiting to eat.\\n");
sem_wait(&tofu_semaphore);
printf("Tofu coagulator is eating.\\n");
eat_sandwich();
printf("Tofu coagulator is done eating.\\n\\n");
sem_post(&agent_semaphore);
}
}
void sauceless_agent(void) {
sem_wait(&agent_semaphore);
printf("Agent puts tofu on the table.\\n");
sem_post(&tofu);
printf("Agent puts bread on the table.\\n");
sem_post(&bread);
}
void tofuless_agent(void) {
sem_wait(&agent_semaphore);
printf("Agent puts bread on the table.\\n");
sem_post(&bread);
printf("Agent puts BBQSauce on the table.\\n");
sem_post(&BBQSauce);
}
void breadless_agent(void) {
sem_wait(&agent_semaphore);
printf("Agent puts tofu on the table.\\n");
sem_post(&tofu);
printf("Agent puts BBQSauce on the table.\\n");
sem_post(&BBQSauce);
}
void *tofuman_nudges(void *_ ) {
while (1) {
sem_wait(&tofu);
pthread_mutex_lock(&mutex);
if (loaves) {
loaves--;
printf("Tofu nudger nudges BBQSauce mixer.\\n");
sem_post(&BBQSauce_semaphore);
} else if (bottles) {
bottles--;
printf("Tofu nudger nudges baker.\\n");
sem_post(&bread_semaphore);
} else {
printf("Tofu nudger got tofu.\\n");
tofu_blocks++;
}
pthread_mutex_unlock(&mutex);
}
}
void *baker_nudges(void *_ ) {
while (1) {
sem_wait(&bread);
pthread_mutex_lock(&mutex);
if (tofu_blocks) {
tofu_blocks--;
printf("Bread nudger nudges BBQSauce mixer.\\n");
sem_post(&BBQSauce_semaphore);
} else if (bottles) {
bottles--;
printf("Bread nudger nudges tofu coagulator.\\n");
sem_post(&tofu_semaphore);
} else {
printf("Bread nudger got bread.\\n");
loaves++;
}
pthread_mutex_unlock(&mutex);
}
}
void *saucer_nudges(void *_ ) {
while (1) {
sem_wait(&BBQSauce);
pthread_mutex_lock(&mutex);
if (tofu_blocks) {
tofu_blocks--;
printf("Sauce nudger nudges baker.\\n");
sem_post(&bread_semaphore);
} else if (loaves) {
loaves--;
printf("Sauce nudger nudges tofu coagulator.\\n");
sem_post(&tofu_semaphore);
} else {
printf("Sauce nudger got BBQSauce.\\n");
bottles++;
}
pthread_mutex_unlock(&mutex);
}
}
void *agent_main(void *_ ) {
void (*agents[])(void) = {sauceless_agent, tofuless_agent, breadless_agent};
while (1) {
agents[rand() % 3]();
sleep(2);
}
}
int main() {
srand(time(0));
printf("This concurrency demonstration applies the same concurrency concepts as \\"The Smokers Problem\\", but uses a medium of sandwich-making instead of cigarette-making to encourage healthy habits.\\n\\n");
pthread_t agent_thr, tofuman_nudges_thr, baker_nudges_thr, saucer_nudges_thr, baker_thr, mixer_thr, coagulator_thr;
sem_init(&tofu, 0, 0);
sem_init(&bread, 0, 0);
sem_init(&BBQSauce, 0, 0);
sem_init(&agent_semaphore, 0, 1);
sem_init(&tofu_semaphore, 0, 0);
sem_init(&BBQSauce_semaphore, 0, 0);
sem_init(&bread_semaphore, 0, 0);
pthread_create(&agent_thr, 0, agent_main, 0);
pthread_create(&baker_thr, 0, bread_baker, 0);
pthread_create(&mixer_thr, 0, BBQSauce_mixer, 0);
pthread_create(&coagulator_thr, 0, tofu_coagulator, 0);
pthread_create(&tofuman_nudges_thr, 0, tofuman_nudges, 0);
pthread_create(&baker_nudges_thr, 0, baker_nudges, 0);
pthread_create(&saucer_nudges_thr, 0, saucer_nudges, 0);
pthread_join(agent_thr, 0);
}
| 0
|
#include <pthread.h>
int nthreads = 4;
char buffer[10000000][40];
int b = 20;
int iProduced = 0;
int iConsumed = 0;
pthread_mutex_t mutexP[4] = {PTHREAD_MUTEX_INITIALIZER};
int bufferSize;
int count[4] = {0};
int max = 0;
char *key;
int count;
struct word *next;
} word;
word* linkedListArray[4];
word cBuffer[4][18];
int done[4];
void *mapreader(void* threadNo) {
int ithread = (int)threadNo;
int readStart = ithread*bufferSize/nthreads;
printf("Read start: %d\\n", readStart);
int iterator = readStart;
int readMax = bufferSize/nthreads;
max = readMax;
int readAmount = 0;
int in = 0;
while(1) {
if(count[ithread] == b) {
pthread_mutex_unlock(&mutexP[ithread]);
} else if(count[ithread] < b) {
pthread_mutex_lock(&mutexP[ithread]);
cBuffer[ithread][in].key = buffer[iterator];
cBuffer[ithread][in].count = 1;
iterator++;
iProduced++;
readAmount++;
count[ithread]++;
in = (in+1)%b;
pthread_mutex_unlock(&mutexP[ithread]);
}
if(readAmount > readMax) {
done[ithread] = 1;
pthread_mutex_unlock(&mutexP[ithread]);
break;
}
}
return 0;
}
void *mapadder(void* threadNo) {
int out = 0;
int ithread = (int)threadNo;
int writeAmount = 0;
int writeMax = max;
while(1) {
if(count[ithread] == 0) {
pthread_mutex_unlock(&mutexP[ithread]);
} else if(count[ithread] > 0) {
pthread_mutex_lock(&mutexP[ithread]);
linkedListArray[ithread] = (word*)malloc(sizeof(struct word));
linkedListArray[ithread]->key = cBuffer[ithread][out].key;
printf("Consumed word: %s\\n", linkedListArray[ithread]->key);
linkedListArray[ithread]->count = cBuffer[ithread][out].count;
writeAmount++;
linkedListArray[ithread]->next = 0;
iConsumed++;
out = (out+1)%b;
count[ithread]--;
pthread_mutex_unlock(&mutexP[ithread]);
}
if(writeAmount > writeMax) {
break;
}
}
return 0;
}
void mapreducer() {
printf("Map reducer called");
}
int main(int argc, char *argv[]) {
pthread_t *map_reader_i = malloc(sizeof(pthread_t)*nthreads);
pthread_t *map_adder_i = malloc(sizeof(pthread_t)*nthreads);
char c;
FILE *fp1 = fopen("100kb.txt","r");
int i=0;
do {
c = fscanf(fp1,"%s",buffer[i]);
i = i + 1;
} while (c != EOF);
bufferSize = i-1;
for(int i = 0; i < nthreads; i++) {
pthread_create(&map_reader_i[i], 0, mapreader, (void*)i);
pthread_create(&map_adder_i[i], 0, mapadder, (void*)i);
}
for(int i = 0; i < nthreads; i++) {
pthread_join(map_reader_i[i], 0);
pthread_join(map_adder_i[i], 0);
}
printf("Threads returned");
mapreducer();
printf("Items Produced %d \\n", iProduced);
printf("Items Consumed %d \\n", iConsumed);
free(map_adder_i);
free(map_reader_i);
return 0;
}
| 1
|
#include <pthread.h>
struct s {
int datum;
struct s *next;
} *A, *B;
void init (struct s *p, int x) {
p -> datum = x;
p -> next = 0;
}
pthread_mutex_t A_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t B_mutex = PTHREAD_MUTEX_INITIALIZER;
void *t_fun(void *arg) {
pthread_mutex_lock(&A_mutex);
A->next->datum++;
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&B_mutex);
B->next->datum++;
pthread_mutex_unlock(&B_mutex);
return 0;
}
int main () {
pthread_t t1;
struct s *p = malloc(sizeof(struct s));
init(p,9);
A = malloc(sizeof(struct s));
init(A,3);
A->next = p;
B = malloc(sizeof(struct s));
init(B,5);
B->next = p;
pthread_create(&t1, 0, t_fun, 0);
pthread_mutex_lock(&A_mutex);
p = A->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&A_mutex);
pthread_mutex_lock(&B_mutex);
p = B->next;
printf("%d\\n", p->datum);
pthread_mutex_unlock(&B_mutex);
return 0;
}
| 0
|
#include <pthread.h>
int set_priority(int priority)
{
int policy;
struct sched_param param;
if (priority < 1 || priority > 63) return -1;
pthread_getschedparam(pthread_self(), &policy, ¶m);
param.sched_priority = priority;
return pthread_setschedparam(pthread_self(), policy, ¶m);
}
int get_priority()
{
int policy;
struct sched_param param;
pthread_getschedparam(pthread_self(), &policy, ¶m);
return param.sched_curpriority;
}
void *send_msg1(void *arg)
{
set_priority(6);
int pid = *arg;
int buffer[255];
int data[255];
int channelId = ConnectAttach(0, pid, 1, 0, 0);
MsgSend(channelId, data, sizeof(data), buffer, sizeof(buffer));
printf("%d\\n", buffer);
return 0;
}
void *send_msg2(void *arg)
{
set_priority(5);
int pid = *arg;
int buffer[255];
int data[255];
int channelId = ConnectAttach(0, pid, 1, 0, 0);
MsgSend(channelId, data, sizeof(data), buffer, sizeof(buffer));
printf("%d\\n", buffer);
return 0;
}
void *send_msg3(void *arg)
{
set_priority(14);
int pid = *arg;
int buffer[255];
int data[255];
int channelId = ConnectAttach(0, pid, 1, 0, 0);
MsgSend(channelId, data, sizeof(data), buffer, sizeof(buffer));
printf("%d\\n", buffer);
return 0;
}
void *send_msg4(void *arg)
{
set_priority(13);
int pid = *arg;
int buffer[255];
int data[255];
int channelId = ConnectAttach(0, pid, 1, 0, 0);
MsgSend(channelId, data, sizeof(data), buffer, sizeof(buffer));
printf("%d\\n", buffer);
return 0;
}
int main(int argc, char const *argv[])
{
struct pid_data {
pthread_mutex_t pid_mutex;
pid_t pid;
};
int pid;
int data[255];
int buffer[255];
int shm = shm_open("/sharepid", O_RDWR , S_IRWXU);
pthread_mutex_lock(ptr->pid_mutex);
pid = ptr->pid;
printf("%d\\n", pid);
pthread_mutex_unlock(ptr->pid_mutex);
set_priority(50);
pthread_t thread[4];
pthread_create(&thread[0], 0, send_msg1, &pid);
pthread_create(&thread[1], 0, send_msg2, &pid);
pthread_create(&thread[2], 0, send_msg3, &pid);
pthread_create(&thread[3], 0, send_msg4, &pid);
for (int i = 0; i < 4; ++i)
{
pthread_join(thread[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
static long seed = 123456789;
double dt, dt_old;
double Random(void)
{
const long Q = 2147483647 / 48271;
const long R = 2147483647 % 48271;
long t;
t = 48271 * (seed % Q) - R * (seed / Q);
if (t > 0)
seed = t;
else
seed = t + 2147483647;
return ((double) seed / 2147483647);
}
double x, y, z;
double mass;
} Particle;
double xold, yold, zold;
double fx, fy, fz;
} ParticleV;
void InitParticles( int );
void* initParticlesAction();
double ComputeForces( Particle [], Particle [], ParticleV [], int );
double ComputeNewPos( Particle [], ParticleV [], int, double);
Particle * particles;
ParticleV * pv;
int npart, iteration_num;
pthread_mutex_t initParticles_mutex;
int main(int argc, char **argv)
{
int i, j, threads_number;
int cnt;
double sim_t;
int tmp;
if (argc != 4) {
printf("Wrong number of parameters.\\nUsage: nbody num_bodies timesteps\\n");
exit(1);
}
npart = atoi(argv[1]);
cnt = atoi(argv[2]);
threads_number = atoi(argv[3]);
dt = 0.001;
dt_old = 0.001;
iteration_num = npart;
particles = (Particle *) malloc(sizeof(Particle)*npart);
pv = (ParticleV *) malloc(sizeof(ParticleV)*npart);
InitParticles(threads_number);
sim_t = 0.0;
while (cnt--) {
double max_f;
max_f = ComputeForces( particles, particles, pv, npart );
sim_t += ComputeNewPos( particles, pv, npart, max_f);
}
for (i = 0; i < npart; i++)
fprintf(stdout,"%.5lf %.5lf\\n", particles[i].x, particles[i].y);
return 0;
}
void InitParticles(int threads_number)
{
pthread_t thread[threads_number];
pthread_mutex_init(&initParticles_mutex, 0);
for (int i = 0; i < threads_number; i++) {
pthread_create(&thread[i], 0, initParticlesAction, 0);
}
for (int i = 0; i < threads_number; i++) {
pthread_join(thread[i], 0);
}
pthread_mutex_destroy(&initParticles_mutex);
}
void* initParticlesAction()
{
while (iteration_num != 0) {
pthread_mutex_lock(&initParticles_mutex);
iteration_num--;
int i = iteration_num;
pthread_mutex_unlock(&initParticles_mutex);
particles[i].x = Random();
particles[i].y = Random();
particles[i].z = Random();
particles[i].mass = 1.0;
pv[i].xold = particles[i].x;
pv[i].yold = particles[i].y;
pv[i].zold = particles[i].z;
pv[i].fx = 0;
pv[i].fy = 0;
pv[i].fz = 0;
}
}
double ComputeForces( Particle myparticles[], Particle others[], ParticleV pv[], int npart )
{
double max_f;
int i;
max_f = 0.0;
for (i=0; i<npart; i++) {
int j;
double xi, yi, mi, rx, ry, mj, r, fx, fy, rmin;
rmin = 100.0;
xi = myparticles[i].x;
yi = myparticles[i].y;
fx = 0.0;
fy = 0.0;
for (j=0; j<npart; j++) {
rx = xi - others[j].x;
ry = yi - others[j].y;
mj = others[j].mass;
r = rx * rx + ry * ry;
if (r == 0.0) continue;
if (r < rmin) rmin = r;
r = r * sqrt(r);
fx -= mj * rx / r;
fy -= mj * ry / r;
}
pv[i].fx += fx;
pv[i].fy += fy;
fx = sqrt(fx*fx + fy*fy)/rmin;
if (fx > max_f) max_f = fx;
}
return max_f;
}
double ComputeNewPos( Particle particles[], ParticleV pv[], int npart, double max_f)
{
int i;
double a0, a1, a2;
double dt_new;
a0 = 2.0 / (dt * (dt + dt_old));
a2 = 2.0 / (dt_old * (dt + dt_old));
a1 = -(a0 + a2);
for (i=0; i<npart; i++) {
double xi, yi;
xi = particles[i].x;
yi = particles[i].y;
particles[i].x = (pv[i].fx - a1 * xi - a2 * pv[i].xold) / a0;
particles[i].y = (pv[i].fy - a1 * yi - a2 * pv[i].yold) / a0;
pv[i].xold = xi;
pv[i].yold = yi;
pv[i].fx = 0;
pv[i].fy = 0;
}
dt_new = 1.0/sqrt(max_f);
if (dt_new < 1.0e-6) dt_new = 1.0e-6;
if (dt_new < dt) {
dt_old = dt;
dt = dt_new;
}
else if (dt_new > 4.0 * dt) {
dt_old = dt;
dt *= 2.0;
}
return dt_old;
}
| 0
|
#include <pthread.h>
struct file
{
int f_fd;
int f_flags;
pthread_t f_tid;
}file[1 +2];
struct thread_args
{
struct file *fptr;
struct SMAP* map;
};
void stop_thr(struct file *fptr);
void *getmap(void *argv);
void *insert_map(void *argv);
void *del_map(void *argv);
int ndone;
pthread_mutex_t ndone_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ndone_cond = PTHREAD_COND_INITIALIZER;
int nconn;
pthread_mutex_t wdb_mutex = PTHREAD_MUTEX_INITIALIZER;
char buf[3000000*2][64];
int sh = 0;
int main()
{
struct SMAP* map;
int i, rc, ret;
pthread_t ntid;
struct thread_args *thr_arg;
struct PAIR pair;
for (i = 0; i < 3000000 *2; i++) {
sprintf(buf[i], "%07d", i);
}
map = smap_init(3000000*2,
DEFAULT_LOAD_FACTOR, 128, 3000000/100, 1);
if (map == 0)
printf("smap_init failed! \\n");
for (i = 0; i < 3000000; i++) {
if (i%2)
SMAP_SET_NUM_PAIR(&pair, i, buf[i], 8);
else
SMAP_SET_STR_PAIR(&pair, buf[i], 7, buf[i], 8);
rc = smap_put(map, &pair, 1);
if (rc < 0){
printf("put: i: %d, error: %d\\n", i, rc);
exit(1);
}
}
nconn = 0;
for (i = 0; i < 1; i++)
{
file[i].f_flags = 0;
}
for (i = 0; i < 1; i++) {
if ((thr_arg = (struct thread_args *)malloc(sizeof(struct thread_args))) == 0)
{
perror("malloc");
exit(1);
}
thr_arg->fptr = &file[i];
thr_arg->map = map;
file[i].f_flags = 1;
ret = pthread_create(&ntid, 0, getmap, (void *)thr_arg);
if (ret != 0)
{
perror("pthread_create");
exit(1);
}
nconn++;
file[i].f_tid = ntid;
}
if ((thr_arg = (struct thread_args *)malloc(sizeof(struct thread_args))) == 0)
{
perror("malloc");
exit(1);
}
thr_arg->fptr = &file[i];
thr_arg->map = map;
file[i].f_flags = 1;
ret = pthread_create(&ntid, 0, insert_map, (void *)thr_arg);
nconn++;
i++;
if ((thr_arg = (struct thread_args *)malloc(sizeof(struct thread_args))) == 0)
{
perror("malloc");
exit(1);
}
thr_arg->fptr = &file[i];
thr_arg->map = map;
file[i].f_flags = 1;
ret = pthread_create(&ntid, 0, del_map, (void *)thr_arg);
nconn++;
while (nconn != 0)
{
pthread_mutex_lock(&ndone_mutex);
while(ndone == 0)
pthread_cond_wait(&ndone_cond, &ndone_mutex);
for (i = 0; i < 1 +2; i++)
{
if (file[i].f_flags & 4)
{
pthread_join(file[i].f_tid, 0);
file[i].f_flags = 0;
ndone--;
nconn--;
}
}
pthread_mutex_unlock(&ndone_mutex);
}
return 0;
}
void stop_thr(struct file *fptr)
{
pthread_mutex_lock(&ndone_mutex);
fptr->f_flags = 4;
ndone++;
pthread_cond_signal(&ndone_cond);
pthread_mutex_unlock(&ndone_mutex);
return;
}
void *insert_map(void *argv)
{
struct timeval tvafter,tvpre;
struct timezone tz;
struct SMAP* map = ((struct thread_args *)argv)->map;
struct file *fptr = ((struct thread_args *)argv)->fptr;
int i, j, s,z;
void *ret;
int rc;
struct PAIR pair;
gettimeofday (&tvpre , &tz);
for (i = 3000000; i < 3000000*2; i++) {
if (i%2)
SMAP_SET_NUM_PAIR(&pair, i, buf[i], 8);
else
SMAP_SET_STR_PAIR(&pair, buf[i], 7, buf[i], 8);
rc = smap_put(map, &pair, 1);
}
gettimeofday (&tvafter , &tz);
printf("put: %dms\\n", (tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000);
stop_thr(fptr);
}
void *del_map(void *argv)
{
struct timeval tvafter1,tvpre1;
struct timezone tz;
struct SMAP* map = ((struct thread_args *)argv)->map;
struct file *fptr = ((struct thread_args *)argv)->fptr;
int i, j, s,z;
void *ret;
int rc;
struct PAIR pair;
gettimeofday (&tvpre1 , &tz);
for (i = 0; i < 3000000; i++) {
if (i%2)
SMAP_SET_NUM_KEY(&pair, i);
else
SMAP_SET_STR_KEY(&pair, buf[i], 7);
rc = smap_delete(map, &pair);
if (rc != SMAP_OK){
printf("i: %d, delete error\\n", i);
} else {
}
}
gettimeofday (&tvafter1 , &tz);
printf("del: %dms\\n", (tvafter1.tv_sec-tvpre1.tv_sec)*1000+(tvafter1.tv_usec-tvpre1.tv_usec)/1000);
stop_thr(fptr);
}
int c = 0;
void *getmap(void *argv)
{
struct timeval tvafter,tvpre;
struct timezone tz;
struct SMAP* map = ((struct thread_args *)argv)->map;
struct file *fptr = ((struct thread_args *)argv)->fptr;
int i, j, s,z;
void *ret;
struct PAIR pair;
z = c++;
s = (3000000/1) * z;
free(argv);
gettimeofday (&tvpre , &tz);
for (j = 0 ; j < 1; j++) {
for (i = s; i < s + 3000000/1; i++) {
if (i%2)
SMAP_SET_NUM_KEY(&pair, i);
else
SMAP_SET_STR_KEY(&pair, buf[i], 7);
ret = smap_get(map, &pair, 0);
}
}
gettimeofday (&tvafter , &tz);
printf("get %d: %dms\\n", z, (tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000);
stop_thr(fptr);
return;
}
| 1
|
#include <pthread.h>
int estado_filosofo[5];
int palillo[5];
pthread_mutex_t mutex;
pthread_cond_t espera[5];
char comiendo[] = "comiendo";
char pensando[] = "pensando";
char esperando[] = "esperando";
char *estado(int i)
{
if(i == 0)
return pensando;
if(i == 1)
return esperando;
if(i == 2)
return comiendo;
return 0;
}
void print_estado()
{
printf("Estado: 0 => %s\\t1 => %s\\t2 => %s\\t3 => %s\\t4 => %s\\n", estado(estado_filosofo[0]), estado(estado_filosofo[1]), estado(estado_filosofo[2]), estado(estado_filosofo[3]), estado(estado_filosofo[4]));
}
void *filosofo(void *num) {
int fil_id = *(int *)num;
while (1) {
estado_filosofo[fil_id] = 0;
printf("Filósofo %d pensando\\n", fil_id);
print_estado();
sleep((rand() % 2) + 1);
estado_filosofo[fil_id] = 1;
printf("Filósofo %d quiere comer\\n", fil_id);
print_estado();
pthread_mutex_lock(&mutex);
while((palillo[fil_id]) || (palillo[(fil_id+1)%5]))
pthread_cond_wait(&espera[fil_id], &mutex);
palillo[fil_id] = 1;
palillo[(fil_id+1)%5] = 1;
pthread_mutex_unlock(&mutex);
estado_filosofo[fil_id] = 2;
printf("Filósofo %d comiendo\\n", fil_id);
print_estado();
sleep( (rand() % 2) + 1);
pthread_mutex_lock(&mutex);
palillo[fil_id] = 0;
palillo[(fil_id+1)%5] = 0;
pthread_cond_signal(&espera[fil_id]);
pthread_cond_signal(&espera[(fil_id+1)%5]);
pthread_mutex_unlock(&mutex);
}
}
int main(void) {
pthread_t th;
int i;
int fil_id[5];
pthread_mutex_init(&mutex,0);
for(i = 0; i < 5; i++) {
palillo[i] = 0;
pthread_cond_init(&espera[i], 0);
fil_id[i] = i;
pthread_create(&th,0,filosofo,(void*)&fil_id[i]);
}
while(1);
}
| 0
|
#include <pthread.h>
struct x11_state {
Display *display;
pthread_mutex_t lock;
int display_opened_here;
int ref_num;
bool initialized;
};
struct x11_state *get_state(void);
struct x11_state *get_state() {
struct x11_state *state;
rm_lock();
state = (struct x11_state *) rm_get_shm("X11-state", sizeof(struct x11_state));
if(!state->initialized) {
state->display = 0;
pthread_mutex_init(&state->lock, 0);
state->display_opened_here = TRUE;
state->ref_num = 0;
state->initialized = 1;
}
rm_unlock();
return state;
}
void x11_set_display(void *disp)
{
struct x11_state *s = get_state();
Display *d = disp;
if (d == 0)
return;
pthread_mutex_lock(&s->lock);
if(s->display != 0) {
fprintf(stderr, "x11_common.c" ": Fatal error: Display already set.\\n");
abort();
}
s->display = d;
s->display_opened_here = FALSE;
pthread_mutex_unlock(&s->lock);
}
void * x11_acquire_display(void)
{
struct x11_state *s = get_state();
if(!s->display) {
s->display = XOpenDisplay(0);
s->display_opened_here = TRUE;
}
if ( !s->display )
{
fprintf(stderr, "Failed to open X display\\n" );
return 0;
}
s->ref_num++;
return s->display;
}
void * x11_get_display(void)
{
struct x11_state *s = get_state();
return s->display;
}
void x11_release_display() {
struct x11_state *s = get_state();
s->ref_num--;
if(s->ref_num < 0) {
fprintf(stderr, "x11_common.c" ": WARNING: Unpaired glx_free call.");
}
if(s->display_opened_here && s->ref_num == 0) {
fprintf(stderr, "Display closed (last client disconnected)\\n");
XCloseDisplay( s->display );
s->display = 0;
}
}
void x11_lock(void)
{
struct x11_state *s = get_state();
pthread_mutex_lock(&s->lock);
}
void x11_unlock(void)
{
struct x11_state *s = get_state();
pthread_mutex_unlock(&s->lock);
}
| 1
|
#include <pthread.h>
struct BO_ITEM_FIFO_OUT {
char ip[16];
char val[BO_FIFO_ITEM_VAL];
int size;
};
static struct FIFO {
int itemN;
struct BO_ITEM_FIFO_OUT *mem;
int head;
int tail;
int last;
int count;
int free;
} fifo = {0};
static int bo_getPos_fifo_out(char *ip);
static pthread_mutex_t fifo_out_mut = PTHREAD_MUTEX_INITIALIZER;
int bo_init_fifo_out(int itemN)
{
int ans = -1;
pthread_mutex_lock(&fifo_out_mut);
fifo.mem = (struct BO_ITEM_FIFO_OUT *)
malloc(sizeof(struct BO_ITEM_FIFO_OUT)*itemN);
if(fifo.mem == 0) goto exit;
memset(fifo.mem, 0, sizeof(struct BO_ITEM_FIFO_OUT)*itemN);
fifo.itemN = itemN;
fifo.head = 0;
fifo.tail = 0;
fifo.last = itemN - 1;
fifo.count = 0;
fifo.free = itemN;
ans = 1;
exit:
pthread_mutex_unlock(&fifo_out_mut);
return ans;
}
int bo_add_fifo_out(unsigned char *val, int size, char *ip)
{
int ans = -1, pos = -1, temp = 0, i = 0;
unsigned char len[2] = {0};
struct BO_ITEM_FIFO_OUT *ptr = 0;
pthread_mutex_lock(&fifo_out_mut);
if(size >= BO_FIFO_ITEM_VAL) goto exit;
if(size < 1) goto exit;
if(val == 0) goto exit;
pos = bo_getPos_fifo_out(ip);
if(pos != -1) {
ptr = fifo.mem + pos;
temp = ptr->size + size + 4;
if(temp > BO_FIFO_ITEM_VAL) {
bo_log("FIFO OUT fifo.free[%d] fifo.count[%d]",
fifo.free, fifo.count);
if(fifo.count > 0) {
i = fifo.head;
while(i != fifo.tail ) {
ptr = fifo.mem + i;
bo_log("FIFO OUT IP[%s] SIZE[%d]",
ptr->ip, ptr->size);
if(i == fifo.last) i = 0;
else i++;
}
}
ans = 0;
goto exit;
}
boIntToChar(size, len);
memcpy(ptr->val + ptr->size, len, 2);
ptr->size += 2;
memcpy(ptr->val + ptr->size, val, size);
ptr->size += size;
ans = 1;
} else {
if(fifo.free == 0) {
bo_log("FIFO OUT fifo.free = 0 fifo.count[%d]", fifo.count);
if(fifo.count > 0) {
i = fifo.head;
while(i != fifo.tail ) {
ptr = fifo.mem + i;
bo_log("FIFO OUT IP[%s] SIZE[%d]",
ptr->ip, ptr->size);
if(i == fifo.last) i = 0;
else i++;
}
}
ans = 0;
goto exit;
}
ptr = fifo.mem + fifo.tail;
boIntToChar(size, len);
memcpy(ptr->val, len, 2);
ptr->size += 2;
memcpy(ptr->val + ptr->size, val, size);
ptr->size += size;
memcpy(ptr->ip, ip, strlen(ip));
if(fifo.count == 0) fifo.head = fifo.tail;
if(fifo.tail == fifo.last) fifo.tail = 0;
else fifo.tail++;
fifo.count++;
fifo.free--;
ans = 1;
}
exit:
pthread_mutex_unlock(&fifo_out_mut);
return ans;
}
int bo_get_fifo_out(unsigned char *buf, int bufSize, char *ip)
{
int ans = -1;
struct BO_ITEM_FIFO_OUT *ptr = 0;
pthread_mutex_lock(&fifo_out_mut);
if(fifo.count != 0) {
ptr = fifo.mem + fifo.head;
if(bufSize >= ptr->size) {
memcpy(buf, ptr->val, ptr->size);
memcpy(ip, ptr->ip, strlen(ptr->ip));
ans = ptr->size;
memset(ptr->ip, 0, 16);
ptr->size = 0;
fifo.count--;
fifo.free++;
if(fifo.head == fifo.last) fifo.head = 0;
else fifo.head++;
}
}
pthread_mutex_unlock(&fifo_out_mut);
return ans;
}
static int bo_getPos_fifo_out(char *ip)
{
int ans = -1, i = 0, n = 0;
struct BO_ITEM_FIFO_OUT *ptr = 0;
if(ip == 0) goto exit;
if(fifo.count != 0) {
i = fifo.head;
while(i != fifo.tail ) {
ptr = fifo.mem + i;
if(strstr(ptr->ip, ip)) {
ans = i;
goto exit;
}
if(i == fifo.last) i = 0;
else i++;
}
}
exit:
return ans;
}
| 0
|
#include <pthread.h>
pthread_attr_t attr;
pthread_mutex_t stdout_lock, fileout_lock;
struct Node {
Node *next;
char *data;
};
Node *stdout_tail, *stdout_head;
Node *fileout_tail, *fileout_head;
bool finished_reading = 0;
void print_and_free_node(Node *node) {
if(node->data != 0)
printf("%s", node->data);
free(node->data);
free(node);
}
bool at_head(Node * node, Node * head_to_compare,pthread_mutex_t *lock) {
bool is_head;
pthread_mutex_lock(lock);
is_head = node == head_to_compare;
pthread_mutex_unlock(lock);
return is_head;
}
void *write_stdout() {
Node *curr = stdout_tail;
Node *next;
while (1) {
if (!at_head(curr,stdout_head, &stdout_lock)) {
next = curr->next;
print_and_free_node(curr);
curr = next;
} else if (finished_reading) {
print_and_free_node(curr);
break;
}
}
}
void write_and_free_node(Node *node, FILE *fp) {
if(node->data != 0) {
fputs(node->data,fp);
}
free(node->data);
free(node);
}
void *write_fileout(void *void_filename) {
char * filename = (char *)void_filename;
Node *curr = fileout_tail;
Node *next;
FILE *fp = fopen(filename,"w+");
while (1) {
if (!at_head(curr, fileout_head ,&fileout_lock)) {
next = curr->next;
write_and_free_node(curr,fp);
curr = next;
} else if (finished_reading) {
write_and_free_node(curr,fp);
break;
}
}
fclose(fp);
}
void tee(char filename[]) {
pthread_attr_init(&attr);
void * a;
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&stdout_lock, 0);
pthread_mutex_init(&fileout_lock, 0);
stdout_tail = malloc(sizeof (Node));
stdout_head = stdout_tail;
fileout_tail = malloc(sizeof (Node));
fileout_head = fileout_tail;
pthread_t w_stdout,w_fileout;
pthread_create(&w_stdout, &attr, write_stdout, a);
pthread_create(&w_fileout,&attr,write_fileout,(void *) filename);
int i;
bool done = 0;
Node *node;
char *buf;
while (!done) {
buf = malloc(sizeof (char) * 80);
for (i = 0; i < sizeof (buf) - 1; i++) {
int c = getchar();
if (c == EOF) {
buf[i] = '\\0';
done = 1;
break;
}
buf[i] = c;
}
buf[sizeof (buf) - 1] = '\\0';
node = malloc(sizeof (Node));
node->next = 0;
node->data = buf;
pthread_mutex_lock(&stdout_lock);
stdout_head->next = node;
stdout_head = node;
pthread_mutex_unlock(&stdout_lock);
node = malloc(sizeof (Node));
node->next = 0;
node->data = malloc(sizeof buf);
memcpy(node->data,buf,sizeof(buf));
pthread_mutex_lock(&fileout_lock);
fileout_head->next = node;
fileout_head = node;
pthread_mutex_unlock(&fileout_lock);
}
finished_reading = 1;
pthread_join(w_stdout, 0);
pthread_join(w_fileout,0);
}
int main(int argc, char** argv) {
char* filename;
if (argc > 1)
filename = argv[1];
else
filename = "tee.out";
tee(filename);
}
| 1
|
#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,thread2,(void*)0);
pthread_create(&t_b,0,thread1,(void*)0);
pthread_join(t_b,0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *junk){
for(i = 1;i<= 9; i++){
pthread_mutex_lock(&mutex);
printf("call thread1 \\n");
if(i%3 == 0)
pthread_cond_signal(&cond);
else
printf("thread1: %d\\n",i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *thread2(void*junk){
while(i < 9)
{
pthread_mutex_lock(&mutex);
printf("call thread2 \\n");
if(i%3 != 0)
pthread_cond_wait(&cond,&mutex);
printf("thread2: %d\\n",i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 0
|
#include <pthread.h>
void
_libc_private_storage_lock(mutex)
pthread_mutex_t *mutex;
{
if (__isthreaded && pthread_mutex_lock(mutex) != 0)
PANIC("_libc_private_storage_lock");
}
void
_libc_private_storage_unlock(mutex)
pthread_mutex_t *mutex;
{
if (__isthreaded && pthread_mutex_unlock(mutex) != 0)
PANIC("_libc_private_storage_unlock");
}
void *
_libc_private_storage(volkey, init, initsz, error)
volatile struct _thread_private_key_struct * volkey;
void * init;
size_t initsz;
void * error;
{
void *result;
void (*cleanfn)(void *);
struct _thread_private_key_struct * key;
if (!__isthreaded)
return init;
key = (struct _thread_private_key_struct *)volkey;
if (volkey->once.state == PTHREAD_NEEDS_INIT) {
if (pthread_mutex_lock(&key->once.mutex) != 0)
return error;
if (volkey->once.state == PTHREAD_NEEDS_INIT) {
if (key->cleanfn == 0)
cleanfn = free;
else
cleanfn = key->cleanfn;
if (pthread_key_create(&key->key, cleanfn) != 0) {
pthread_mutex_unlock(&key->once.mutex);
return error;
}
key->once.state = PTHREAD_DONE_INIT;
}
pthread_mutex_unlock(&key->once.mutex);
}
result = pthread_getspecific(key->key);
if (result == 0) {
result = malloc(initsz);
if (result == 0)
return error;
if (pthread_setspecific(key->key, result) != 0) {
free(result);
return error;
}
memcpy(result, init, initsz);
}
return result;
}
| 1
|
#include <pthread.h>
sig_atomic_t directions[N_PLAYERS] = {RIGHT, LEFT};
sem_t can_we_play[N_PLAYERS];
sem_t can_continue;
pthread_t threads[N_PLAYERS+2];
struct key_map
{
int player;
int key;
sig_atomic_t direction;
};
const struct key_map mapping[] = {
{1, 'w', UP},
{1, 's', DOWN},
{1, 'd', RIGHT},
{1, 'a', LEFT},
{2, KEY_UP, UP},
{2, KEY_DOWN, DOWN},
{2, KEY_RIGHT, RIGHT},
{2, KEY_LEFT, LEFT},
{0, 0, 0}
};
void* worm(void *num)
{
int id = (int) num, move, old_move = 0;
int row = basis.heads[id][0], col = basis.heads[id][1];
while (1)
{
sem_wait(&can_we_play[id]);
if ((basis.status == STATUS_PAUSE) ||
(basis.status == STATUS_END_MATCH))
{
sem_post(&can_continue);
continue;
}
move = directions[id];
move = (move == -old_move) ? old_move : move;
old_move = move;
switch (move)
{
case UP:
row--;
break;
case DOWN:
row++;
break;
case RIGHT:
col++;
break;
case LEFT:
col--;
break;
}
if ((row <= 0) || (col <= 0)
|| (row >= basis.size_row-1) || (col >= basis.size_col-1))
{
pthread_mutex_lock(&mutex_sts);
basis.status = STATUS_GAME_OVER;
basis.losers = (!basis.losers)? id+1 : DRAW;
pthread_mutex_unlock(&mutex_sts);
}
else
{
pthread_mutex_lock(&basis.l_field[row][col]);
if (basis.field[row][col] == 0)
basis.field[row][col] = id+1;
else
{
pthread_mutex_lock(&mutex_sts);
basis.status = STATUS_GAME_OVER;
basis.losers = (!basis.losers)? id+1 : DRAW;
pthread_mutex_unlock(&mutex_sts);
}
pthread_mutex_unlock(&basis.l_field[row][col]);
pthread_mutex_lock(&basis.l_heads);
basis.heads[id][0] = row;
basis.heads[id][1] = col;
pthread_mutex_unlock(&basis.l_heads);
}
sem_post(&can_continue);
}
return 0;
}
void* read_key(void *arg)
{
int i, c, paused = 0;
while (1)
{
c = getch();
if ((paused > 0) && (c != PAUSED) && (c != KEY_F(1)))
continue;
pthread_mutex_lock(&mutex_sts);
if ((basis.status == STATUS_END_MATCH) &&
(c != KEY_F(1)) && (c != RESTART))
{
pthread_mutex_unlock(&mutex_sts);
continue;
}
switch(c)
{
case (KEY_F(1)):
refresh_exit();
pthread_mutex_unlock(&mutex_sts);
break;
case (KEY_RESIZE):
basis.status = STATUS_RESIZE;
pthread_mutex_unlock(&mutex_sts);
break;
case (PAUSED):
paused++;
if (paused == 1)
{
basis.status = STATUS_PAUSE;
pthread_mutex_unlock(&mutex_sts);
}
else
{
paused = 0;
basis.status = STATUS_NORMAL;
pthread_mutex_unlock(&mutex_sts);
}
break;
default:
pthread_mutex_unlock(&mutex_sts);
for (i = 0; mapping[i].player; i++)
if (c == mapping[i].key)
{
directions[mapping[i].player-1]=
mapping[i].direction;
}
break;
}
}
return arg;
}
int diff (struct timespec start, struct timespec end)
{
struct timespec temp;
int ret;
if ((end.tv_nsec - start.tv_nsec) < 0)
{
temp.tv_sec = end.tv_sec - start.tv_sec - 1;
temp.tv_nsec = 1e9 + end.tv_nsec - start.tv_nsec;
}
else
{
temp.tv_sec = end.tv_sec - start.tv_sec;
temp.tv_nsec = end.tv_nsec - start.tv_nsec;
}
ret = spec_to_usec(temp);
return (ret > REFRESH_US) ? REFRESH_US : ret;
}
int spec_to_usec(struct timespec time)
{
int temp;
temp = time.tv_nsec / 1e3;
temp += time.tv_sec * 1e6;
return temp;
}
void check_draw()
{
int i, j;
for (i = 0; i < N_PLAYERS; i++)
for (j = 1; j < N_PLAYERS; j++)
if ((i != j) &&
(basis.heads[i][0] == basis.heads[j][0]) &&
(basis.heads[i][1] == basis.heads[j][1]))
{
pthread_mutex_lock(&mutex_sts);
basis.status = STATUS_GAME_OVER;
basis.losers = DRAW;
pthread_mutex_unlock(&mutex_sts);
}
}
void initvar_pthread()
{
for (int i = 0; i < N_PLAYERS; i++)
sem_init(&can_we_play[i], 0, 0);
sem_init(&can_refresh, 0, 0);
sem_init(&can_continue, 0, 0);
sem_init(&screen_ready, 0, 0);
pthread_mutex_init(&mutex_sts, 0);
pthread_mutex_init(&basis.l_heads, 0);
}
void create_threads()
{
int i;
if (pthread_create(&threads[2], 0, &refresh_game, 0))
{
fprintf(stderr, "Cannot create thread refresh_game\\n");
exit(-1);
}
if (pthread_create(&threads[3], 0, &read_key, 0))
{
fprintf(stderr, "Cannot create thread read_key\\n");
exit(-1);
}
for (i = 0; i < N_PLAYERS; i++)
{
if (pthread_create(&threads[i], 0, &worm, (void *) i))
{
fprintf(stderr, "Cannot create thread worm %d\\n", i);
exit(-1);
}
}
}
void* judge(void *arg)
{
int i;
initvar_pthread();
create_threads();
while(1)
{
sem_wait(&screen_ready);
for (i = 0; i < N_PLAYERS; i++)
sem_post(&can_we_play[i]);
for (i = 0; i < N_PLAYERS; i++)
sem_wait(&can_continue);
check_draw();
sem_post(&can_refresh);
usleep(REFRESH_US);
sem_post(&can_refresh);
}
return arg;
}
| 0
|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
void main()
{
pthread_t thread1, thread2;
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionCount1()
{
for(;;) {
pthread_mutex_lock( &count_mutex );
if ( count % 2 != 0 ) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_cond_signal( &condition_var );
if ( count >= 200 ) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
void *functionCount2()
{
for(;;) {
pthread_mutex_lock( &count_mutex );
if ( count % 2 == 0 ) {
pthread_cond_wait( &condition_var, &count_mutex );
}
count++;
printf("Counter value functionCount2: %d\\n",count);
pthread_cond_signal( &condition_var );
if( count >= 200 ) {
pthread_mutex_unlock( &count_mutex );
return(0);
}
pthread_mutex_unlock( &count_mutex );
}
}
| 1
|
#include <pthread.h>
int sum = 0;
pthread_cond_t slots = PTHREAD_COND_INITIALIZER;
pthread_cond_t items = PTHREAD_COND_INITIALIZER;
pthread_mutex_t slot_lock = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t item_lock = PTHREAD_MUTEX_INITIALIZER;
int nslots = 8;
int producer_done = 0;
int nitems = 0;
void *producer(void *arg1)
{
int i;
for(i = 1; i <= 100; i++) {
pthread_mutex_lock(&slot_lock);
{
while (nslots <= 0)
pthread_cond_wait(&slots, &slot_lock);
nslots--;
}
pthread_mutex_unlock(&slot_lock);
put_item(i*i);
pthread_mutex_lock(&item_lock);
{
nitems++;
pthread_cond_signal(&items);
}
pthread_mutex_unlock(&item_lock);
}
pthread_mutex_lock(&item_lock);
{
producer_done = 1;
pthread_cond_broadcast(&items);
}
pthread_mutex_unlock(&item_lock);
return 0;
}
void *consumer(void *arg2)
{
int myitem;
for( ; ; ) {
pthread_mutex_lock(&item_lock);
{
while((nitems <= 0) && (!producer_done))
pthread_cond_wait(&items, &item_lock);
if((nitems <= 0) && (producer_done)) {
pthread_mutex_unlock(&item_lock);
break;
}
nitems--;
}
pthread_mutex_unlock(&item_lock);
get_item(&myitem);
sum += myitem;
pthread_mutex_lock(&slot_lock);
{
nslots++;
pthread_cond_signal(&slots);
}
pthread_mutex_unlock(&slot_lock);
}
return 0;
}
int main(void)
{
pthread_t prodid;
pthread_t consid;
int i, total;
total = 0;
for(i = 1; i <= 100; i++)
total += i*i;
printf("the checksum should is %d\\n", total);
if(pthread_create(&consid, 0, consumer, 0))
perror("Could not create consumer");
else if(pthread_create(&prodid, 0, producer, 0))
perror("Could not create producer");
pthread_join(prodid, 0);
pthread_join(consid, 0);
printf("The threads producer the sum %d\\n", sum);
exit(0);
}
| 0
|
#include <pthread.h>
struct TErrNode {
struct TErrNode *next;
pthread_t thread;
size_t used;
size_t size;
struct LineInfo {
char file[64];
char function[64];
size_t line;
} *stack;
} ;
static struct TErrNode *top = 0;
static pthread_mutex_t mutex;
static struct TErrNode *getnode();
static void errchkinit(void) ;
void errchkinit(void) {
pthread_mutex_init(&mutex, 0);
}
struct TErrNode *getnode() {
pthread_t thread;
struct TErrNode *node;
thread = pthread_self();
for (node = top; node != 0; node = node->next) {
if (node->thread == thread) {
return node;
}
}
assert((node = (struct TErrNode *)malloc(sizeof(struct TErrNode))) != 0);
node->thread = thread;
node->next = top;
node->used = 0;
node->size = 1;
assert((node->stack =
(struct LineInfo *)malloc(node->size*sizeof(struct LineInfo))) != 0);
return node;
}
void errchkcleanup() {
pthread_t thread;
struct TErrNode **prev, *node;
thread = pthread_self();
pthread_mutex_lock(&mutex);
for (prev = &top, node = top; node != 0; prev = &node->next, node = node->next) {
if (pthread_equal(node->thread, thread)) {
*prev = node->next;
free(node->stack);
free(node);
}
}
pthread_mutex_unlock(&mutex);
}
void pushlineinfo(const char *file, const char *function, size_t line) {
struct TErrNode *node;
pthread_mutex_lock(&mutex);
node = getnode();
if (node->used + 1 > node->size) {
node->size *= 2;
assert((node->stack = realloc(node->stack, node->size*sizeof(struct LineInfo))) != 0);
}
strncpy(node->stack[node->used].file, file, sizeof(node->stack[node->used].file) - 1);
strncpy(node->stack[node->used].function, function, sizeof(node->stack[node->used].function) - 1);
node->stack[node->used].line = line;
node->used++;
pthread_mutex_unlock(&mutex);
}
void printlineinfo() {
struct TErrNode *node;
size_t i;
pthread_mutex_lock(&mutex);
node = getnode();
assert(fprintf(stderr, "Error Trace:\\n") >= 0);
for (i = 0; i < node->used; i++) {
assert(fprintf(stderr, "file:%s:%s:%ld\\n", node->stack[i].file,
node->stack[i].function, node->stack[i].line) >= 0);
}
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
struct queue* new_queue(size_t capacity, int mt) {
struct queue* queue = xmalloc(sizeof(struct queue));
queue->capacity = capacity;
queue->data = xmalloc((capacity == 0 ? 1 : capacity) * sizeof(void*));
queue->rc = capacity == 0 ? 1 : 0;
queue->start = 0;
queue->end = 0;
queue->size = 0;
queue->mt = mt;
if (mt) {
if (pthread_mutex_init(&queue->data_mutex, 0)) {
xfree(queue->data);
queue->data = 0;
xfree(queue);
return 0;
}
if (pthread_cond_init(&queue->out_cond, 0)) {
xfree(queue->data);
queue->data = 0;
pthread_mutex_destroy(&queue->data_mutex);
xfree(queue);
return 0;
}
if (pthread_cond_init(&queue->in_cond, 0)) {
xfree(queue->data);
queue->data = 0;
pthread_mutex_destroy(&queue->data_mutex);
pthread_cond_destroy(&queue->out_cond);
xfree(queue);
return 0;
}
}
return queue;
}
int del_queue(struct queue* queue) {
if (queue == 0 || queue->data == 0) return -1;
if (queue->mt) {
if (pthread_mutex_destroy(&queue->data_mutex)) return -1;
if (pthread_cond_destroy(&queue->out_cond)) return -1;
if (pthread_cond_destroy(&queue->in_cond)) return -1;
}
xfree(queue->data);
queue->data = 0;
xfree(queue);
return 0;
}
int add_queue(struct queue* queue, void* data) {
if (queue->mt) pthread_mutex_lock(&queue->data_mutex);
if (queue->size == queue->rc && queue->capacity == 0) {
size_t orc = queue->rc;
queue->rc += 1024 / sizeof(void*);
void** ndata = xmalloc(queue->rc * sizeof(void*));
if (queue->start < queue->end) {
memcpy(ndata, queue->data + queue->start, (queue->end - queue->start) * sizeof(void*));
} else {
memcpy(ndata, queue->data + queue->start, (orc - queue->start) * sizeof(void*));
memcpy(ndata + (orc - queue->start), queue->data + queue->end, (queue->start - queue->end) * sizeof(void*));
}
xfree(queue->data);
queue->data = ndata;
} else if (queue->capacity == 0) {
} else {
while (queue->size == queue->capacity) {
if (!queue->mt) return 1;
pthread_cond_wait(&queue->in_cond, &queue->data_mutex);
}
}
queue->data[queue->end++] = data;
size_t rp = queue->capacity > 0 ? queue->capacity : queue->rc;
if (queue->end >= rp) {
if (queue->end - rp == queue->start) {
size_t orc = queue->rc;
queue->rc += 1024 / sizeof(void*);
void** ndata = xmalloc(queue->rc * sizeof(void*));
if (queue->start < queue->end) {
memcpy(ndata, queue->data + queue->start, (queue->end - queue->start) * sizeof(void*));
} else {
memcpy(ndata, queue->data + queue->start, (orc - queue->start) * sizeof(void*));
memcpy(ndata + (orc - queue->start), queue->data + queue->end, (queue->start - queue->end) * sizeof(void*));
}
xfree(queue->data);
queue->data = ndata;
} else queue->end -= rp;
}
queue->size++;
if (queue->mt) {
pthread_mutex_unlock(&queue->data_mutex);
pthread_cond_signal(&queue->out_cond);
}
return 0;
}
void* pop_queue(struct queue* queue) {
if (queue->mt) {
pthread_mutex_lock(&queue->data_mutex);
while (queue->size == 0) {
pthread_cond_wait(&queue->out_cond, &queue->data_mutex);
}
} else if (queue->size == 0) {
return 0;
}
void* data = queue->data[queue->start++];
size_t rp = queue->capacity > 0 ? queue->capacity : queue->rc;
if (queue->start >= rp) {
queue->start -= rp;
}
queue->size--;
if (queue->mt) {
pthread_mutex_unlock(&queue->data_mutex);
pthread_cond_signal(&queue->in_cond);
}
return data;
}
void* peek_queue(struct queue* queue) {
if (queue->mt) {
pthread_mutex_lock(&queue->data_mutex);
while (queue->size == 0) {
pthread_cond_wait(&queue->out_cond, &queue->data_mutex);
}
} else if (queue->size == 0) {
return 0;
}
void* data = queue->data[queue->start];
if (queue->mt) {
pthread_mutex_unlock(&queue->data_mutex);
pthread_cond_signal(&queue->in_cond);
}
return data;
}
void* timedpop_queue(struct queue* queue, struct timespec* abstime) {
if (queue->mt) {
pthread_mutex_lock(&queue->data_mutex);
while (queue->size == 0) {
int x = pthread_cond_timedwait(&queue->out_cond, &queue->data_mutex, abstime);
if (x) {
pthread_mutex_unlock(&queue->data_mutex);
errno = x;
return 0;
}
}
} else if (queue->size == 0) {
return 0;
}
void* data = queue->data[queue->start++];
size_t rp = queue->capacity > 0 ? queue->capacity : queue->rc;
if (queue->start >= rp) {
queue->start -= rp;
}
queue->size--;
if (queue->mt) {
pthread_mutex_unlock(&queue->data_mutex);
pthread_cond_signal(&queue->in_cond);
}
return data;
}
| 0
|
#include <pthread.h>
const int thread_count = 20;
int item;
pthread_cond_t produce_ok, consume_ok;
pthread_mutex_t mutex;
int consumed_array[20];
int consumed = 20 -1;
int produced = 0;
unsigned int seed;
void* thread_work(void* rank);
int main(int argc, char *argv[])
{
long thread;
pthread_t* thread_handles;
for (thread=0; thread<thread_count; thread++) {
consumed_array[thread] = 0;
}
seed = time(0);
thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_cond_init(&produce_ok, 0);
pthread_cond_init(&consume_ok, 0);
pthread_mutex_init(&mutex, 0);
for (thread=0; thread<thread_count; thread++) {
pthread_create(&thread_handles[thread], 0, thread_work, (void*) thread);
}
for (thread=0; thread<thread_count; thread++) {
pthread_join(thread_handles[thread], 0);
}
pthread_cond_destroy(&produce_ok);
pthread_cond_destroy(&consume_ok);
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void* thread_work(void* rank)
{
long my_rank = (long) rank;
int i, j;
for (i=0; i<2; i++) {
if (my_rank == 0) {
pthread_mutex_lock(&mutex);
while (consumed < thread_count-1) {
pthread_cond_wait(&produce_ok, &mutex);
}
consumed = 0;
item = rand_r(&seed)%100;
printf("Produced %d\\n", item);
produced = 1;
for (j=1; j<thread_count; j++) {
consumed_array[j] = 0;
}
pthread_cond_broadcast(&consume_ok);
pthread_mutex_unlock(&mutex);
}
else {
pthread_mutex_lock(&mutex);
while (produced < 1 || consumed_array[my_rank] == 1) {
pthread_cond_wait(&consume_ok, &mutex);
}
printf("Thread %ld got %d\\n", my_rank, item);
consumed++;
consumed_array[my_rank] = 1;
if (consumed == thread_count-1) {
produced = 0;
pthread_cond_signal(&produce_ok);
}
pthread_mutex_unlock(&mutex);
}
}
return 0;
}
| 1
|
#include <pthread.h>
void *wolfThread(){
int i;
int color[3] = {0xFF1F05,0xAF2A00,0xDF3800};
int setcolor;
int lednum = 0;
int ledcolor = 0;
int sleeptime = 1;
int sleepmin = 2000000;
int sleepmax = 3000000;
for(i=0;i<(LEDANZ-1);i=i+2){
setcolor = color[rand()%3];
setLED(i,setcolor);
setLED(i+1,setcolor);
printf("led:%d,%d color:%d\\n",i,i+1,setcolor);}
while(1){
while(sleeptime < sleepmin)
sleeptime = rand()%sleepmax;
usleep(sleeptime);
lednum=rand() % (LEDANZ-1);
if(lednum%2 != 0)
lednum++;
ledcolor = getLEDcolor(lednum);
setLED(lednum,0);
setLED(lednum+1,0);
printf("lednum:%d,%d\\n",lednum,lednum+1);
usleep(100000);
setLED(lednum,ledcolor);
setLED(lednum+1,ledcolor);
pthread_mutex_lock(&mutexRun);
if(!WolfRun) {
pthread_mutex_unlock(&mutexRun);
break;}
pthread_mutex_unlock(&mutexRun);
usleep(1000);
}
setLEDsOFF();
return;
}
void *starThread(){
int i;
int color[3] = {0xFFFFA5,0xCFFAFF,0x9FFFFF};
int setcolor;
int lednum = 0;
int ledcolor = 0;
int sleeptime = 1;
int sleepmin = 2000000;
int sleepmax = 3000000;
for(i=0;i<(LEDANZ-1);i=i+2){
setcolor = color[rand()%3];
setLED(i,setcolor);
printf("led:%d,%d color:%d\\n",i,i+1,setcolor);}
setLED(22,0);
setLED(8,0);
while(1){
pthread_mutex_lock(&mutexStarRun);
if(!StarRun) {
pthread_mutex_unlock(&mutexStarRun);
break;}
pthread_mutex_unlock(&mutexStarRun);
usleep(500000);
}
setLEDsOFF();
return;
}
int main(int argc, char*argv[]){
int i,rc;
int brt=50;
int opt;
char recvmsg[BUFSIZE];
int port = DEFAULTPORT;
int endexit = 1;
pthread_t wolfPThread,starPThread;
pthread_mutex_init(&mutexRun, 0);
pthread_mutex_init(&mutexStarRun, 0);
WolfRun = 1;
StarRun = 1;
if(initLEDs(LEDANZ)){
printf("ERROR: initLED\\n");
return -1;}
while ((opt = getopt(argc, argv, "p:dhb:")) != -1) {
switch (opt) {
case 'p':
if(optarg != 0)
port = atoi(optarg);
break;
case 'd':
debug = 1;
break;
case 'b':
if(optarg != 0)
brt = atoi(optarg);
break;
case 'h':
printf("Help for TaPWolfServer\\n");
printf("Usage: %s [-p port number] [-d] debug mode [-h] show Help\\n", argv[0]);
return 0;
break;
default:
printf("Usage: %s [-p portnumber] [-d] debug mode [-i] invert pwm output [-h] show Help\\n", argv[0]);
return -2;
}
}
if(setBrightness(brt)){
printf("ERROR setBrightnes\\n");
return -1;}
if(setLEDsOFF()){
printf("ERROR setLEDsOFF\\n");
return -1;}
if(initUDPServer(port) != 0){
printf("ERROR whil init UDP-Server\\n");
return -1;
}
while(!(strcmp(recvmsg,"TaPWolf;exit") == 0)){
bzero(recvmsg, BUFSIZE);
printf("wait for Connection\\n");
waitForClient(recvmsg);
if(parseCommand(recvmsg) != 0){
printf("ERROR wrong Syntax\\n");
continue;
}
if(strcmp(Mode, "WolfON") == 0){
WolfRun = 1;
rc = pthread_create( &wolfPThread, 0, &wolfThread, 0 );
if( rc != 0 ) {
printf("Konnte WolfThread nicht erzeugen\\n");
return -1;
}
}
if(strcmp(Mode, "WolfOFF") == 0){
pthread_mutex_lock(&mutexRun);
WolfRun = 0;
pthread_mutex_unlock(&mutexRun);}
if(strcmp(Mode, "StarON") == 0){
StarRun = 1;
rc = pthread_create( &starPThread, 0, &starThread, 0 );
if( rc != 0 ) {
printf("Konnte StarThread nicht erzeugen\\n");
return -1;
}
}
if(strcmp(Mode, "StarOFF") == 0){
pthread_mutex_lock(&mutexRun);
StarRun = 0;
pthread_mutex_unlock(&mutexRun);}
}
endexit = 0;
if(setLEDsOFF()){
printf("ERROR setLEDsOFF\\n");
return -1;}
pthread_join( wolfPThread, 0 );
pthread_join( starPThread, 0 );
ws2811_fini(&myledstring);
return 0;
}
int parseCommand(char command[BUFSIZE]){
int i;
char copycommand[BUFSIZE];
char *splitCommand;
for(i=0;i<BUFSIZE;i++)
copycommand[i] = command[i];
splitCommand=strtok(copycommand,";");
if(strcmp(splitCommand, "TaPWolf") != 0)
return -1;
splitCommand=strtok(0,";");
if(strcmp(splitCommand, "WolfON") == 0 || strcmp(splitCommand, "WolfOFF") == 0 || strcmp(splitCommand, "StarON") == 0 || strcmp(splitCommand, "StarOFF") == 0 || strcmp(splitCommand, "exit") == 0)
Mode = splitCommand;
else
return -1;
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mx;
int x=0;
void *thread1() {
pthread_mutex_lock(&mx);
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
x=x+1;
pthread_mutex_unlock(&mx);
return 0;
}
void *thread2() {
pthread_mutex_lock(&mx);
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
x=x-1;
pthread_mutex_unlock(&mx);
return 0;
}
void *thread3() {
int a = x;
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mx, 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);
assert(x!=1);
pthread_mutex_destroy(&mx);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void enter_main_lock()
{
pthread_mutex_lock(&mutex);
}
void worker_enter_main_lock()
{
pthread_mutex_lock(&mutex);
}
int worker_try_enter_main_lock()
{
if(!pthread_mutex_trylock(&mutex))
return 1;
else
return 0;
}
void leave_main_lock()
{
pthread_mutex_unlock(&mutex);
}
void worker_leave_main_lock()
{
pthread_mutex_unlock(&mutex);
}
void create_main_lock()
{
pthread_mutex_init(&mutex, 0);
}
void destroy_main_lock()
{
pthread_mutex_destroy(&mutex);
}
struct surface_t *leave_main_lock_and_rotate_surface(struct surface_t *in_surface,
int scale_width, int scale_height, double theta)
{
struct surface_t *duplicate, *rotated;
duplicate = duplicate_surface(in_surface);
leave_main_lock();
rotated = rotate_surface(duplicate, scale_width, scale_height, theta);
free_surface(duplicate);
return rotated;
}
struct surface_t *leave_main_lock_and_resize_surface(struct surface_t *in_surface,
int width, int height)
{
struct surface_t *duplicate, *resized;
duplicate = duplicate_surface(in_surface);
leave_main_lock();
resized = resize(duplicate, width, height);
free_surface(duplicate);
return resized;
}
| 0
|
#include <pthread.h>
int start;
int len;
char* a;
int n;
pthread_mutex_t* mutex;
} thr_struct;
void* thr_func(void* arg) {
int start = ((thr_struct*)arg)->start;
char* a = ((thr_struct*)arg)->a;
int n = ((thr_struct*)arg)->n;
pthread_mutex_t* mutex = ((thr_struct*)arg)->mutex;
int len = ((thr_struct*)arg)->len;
for(int k = 0; k < len; ++k) {
if(a[k] == 'o') {
int i = (k + start) / n;
int j = (k + start) % n;
pthread_mutex_lock(mutex);
printf("(%d, %d)\\n", i, j);
pthread_mutex_unlock(mutex);
}
}
}
int main(int argc, char **argv) {
int P, M, N;
pthread_t* thr_idx;
thr_struct* thr_str;
pthread_mutex_t mutex;
if(argc != 5) {
fprintf(stderr, "usage: %s P M N a.txt\\n", argv[0]);
return 1;
}
if((P = atoi(argv[1])) <= 0 || (M = atoi(argv[2])) <= 0 || (N = atoi(argv[3])) <= 0) {
fprintf(stderr, "Number of threads and both dimensions of the board must be positive integers.\\n");
return 1;
}
char* a;
if((a = (char*)malloc((M * N + 1) * sizeof(char))) == 0) {
fprintf(stderr, "Error alocating memory.\\n");
return 1;
}
a[0] = '\\0';
FILE* file =fopen(argv[4], "r");
if(file) {
char *tmp = a;
while(1) {
if(fscanf(file, "%s", tmp) <= 0) {
break;
}
tmp += strlen(tmp);
}
} else {
fprintf(stderr, "error opening file.\\n");
free(a);
return 1;
}
if((thr_idx = (pthread_t*)malloc(P * sizeof(pthread_t))) == 0) {
fprintf(stderr, "Error alocating memory.\\n");
free(a);
return 1;
}
if ((thr_str = (thr_struct*)malloc(P * sizeof(thr_struct))) == 0) {
fprintf(stderr, "Error alocating memory.\\n");
free(thr_idx);
free(a);
return 1;
}
pthread_mutex_init(&mutex, 0);
for(int i = 0; i < P; ++i) {
thr_str[i].len = ((((i+1) * (M * N)) / (P)) - (((i) * (M * N)) / (P)));
thr_str[i].n = N;
int start = (((i) * (M * N)) / (P));
thr_str[i].start = start;
thr_str[i].a = a + start;
thr_str[i].mutex = &mutex;
if(pthread_create(&thr_idx[i], 0, thr_func, (void*) &thr_str[i])) {
fprintf(stderr, "Error creating thread.\\n");
free(a);
free(thr_str);
free(thr_idx);
return 1;
}
}
for(int i = 0; i < P; ++i) {
if(pthread_join(thr_idx[i], 0)) {
fprintf(stderr, "Error joining thread number %d.\\n", i);
free(a);
free(thr_idx);
free(thr_str);
return 1;
}
}
pthread_mutex_destroy(&mutex);
free(a);
free(thr_idx);
free(thr_str);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t recordlock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t recordcon=PTHREAD_COND_INITIALIZER;
int readr=0,writer=0;
int *record;
struct nodeInfo *array;
pthread_barrier_t barrier;
char *filename;
char *path;
int scale;
int filesize;
char *recordpath;
int recordfile;
void wRecordLock(){
pthread_mutex_lock(&recordlock);
writer=1;
if(readr>0)pthread_cond_wait(&recordcon,&recordlock);
pthread_mutex_unlock(&recordlock);
}
void wRecordUnlock(){
pthread_mutex_lock(&recordlock);
writer=0;
pthread_cond_broadcast(&recordcon);
pthread_mutex_unlock(&recordlock);
}
void rRecordLock(){
pthread_mutex_lock(&recordlock);
if(writer>0)pthread_cond_wait(&recordcon,&recordlock);
readr++;
pthread_mutex_unlock(&recordlock);
}
void rRecordUnlock(){
pthread_mutex_lock(&recordlock);
readr--;
if(read==0&&writer>0)pthread_cond_signal(&recordcon);
pthread_mutex_unlock(&recordlock);
}
void getInfo(int sk,struct nodeInfo *array,int scale){
struct package buf;
struct nodeInfo *node;
int i=0;
while(i<scale){
recvn(sk,&buf);
node=(struct nodeInfo *)buf.data;
array[i].num=node->num;
array[i].port=node->port;
strcpy(array[i].ip,node->ip);
strcpy(array[i].path,node->path);
i++;
}
}
void writeRecord(int *record,int count,int fd){
wRecordLock();
lseek(fd,0,0);
write(fd,record,sizeof(int)*count);
wRecordUnlock();
}
void readRecord(int *record,int count,int fd){
read(fd,(char *)record,sizeof(int)*count);
}
int linkSever(struct nodeInfo *node,int start,int index){
int s=con(node->ip,node->port);
sendn(s,node->path,2,strlen(node->path)+1);
return s;
}
int download(int sk,int fd,int *record,char *buff,int num,int buffsize){
int count=0,n,filesize=0;
struct package buf;
while(1){
recvn(sk,&buf);
if(buf.sum==-1){
write(fd,buff,count);
rRecordLock();
record[num]=filesize;
rRecordUnlock();
break;
}
memcpy(&buff[count],buf.data,buf.sum);
count+=buf.sum;
filesize+=buf.sum;
if(buffsize-count<1024){
write(fd,buff,count);
rRecordLock();
record[num]=filesize;
rRecordUnlock();
count=0;
}
}
return 0;
}
int fusion(char *filename,int sum,char *path){
int origin,index,n;
char *num;
char *file=(char *)malloc(sizeof(char)*512);
char *filecopy=(char *)malloc(sizeof(char)*512);
char *databuff=(char *)malloc(sizeof(char)*4096);
strcpy(file,path);
strcat(file,"/");
strcat(file,filename);
strcpy(filecopy,file);
origin=open(file,O_RDWR|O_CREAT,0600);
for(int i=0;i<sum;i++){
strcpy(file,filecopy);
num=itoa(i+1);
strcat(file,num);
index=open(file,O_RDWR);
while((n=read(index,databuff,4096))>0){
write(origin,databuff,n);
}
free(num);
unlink(file);
}
free(file);
free(filecopy);
free(databuff);
return 1;
}
int comDown(int sk,int *mark,int *record,int scale){
return 0;
}
int reconstruction(int *mark,int scale,int *record,int filesize){
int size=filesize/scale;
int count=0;
scale--;
for(int i=0;i<scale;i++){
if(record[i]<scale){
mark[i]=1;
count++;
}else{
mark[i]=0;
}
}
if(record[scale]<filesize-size*scale){
record[scale]=1;
count++;
}else record[scale]=0;
return count;
}
void* getFile(void *args){
int index=(int)args;
char *file=(char *)malloc(sizeof(char)*1024);
char *buff=(char *)malloc(sizeof(char)*20480);
char *num=itoa(index+1);
int start=record[index];
int fd,sk;
strcpy(file,path);
strcat(file,"/");
strcat(file,filename);
strcat(file,num);
fd=open(file,O_CREAT|O_RDWR,0600);
sk=linkSever(&array[index],record[index],index);
sendn(sk,(char *)&start,1,sizeof(int));
download(sk,fd,record,buff,index,20480);
pthread_barrier_wait(&barrier);
close(fd);
free(num);
free(file);
free(buff);
}
int reDonwn(int sk){
int *mark=(int *)malloc(sizeof(int)*10);
int count;
pthread_t ph;
readRecord(record,scale,recordfile);
count=reconstruction(mark,scale,record,filesize);
getInfo(sk,array,scale);
pthread_barrier_init(&barrier,0,count);
for(int i=0;i<scale;i++){
if(mark[i]>0)
pthread_create(&ph,0,getFile,(void *)i);
}
pthread_barrier_wait(&barrier);
pthread_barrier_destroy(&barrier);
fusion(filename,scale,path);
free(mark);
return 1;
}
void recordFile(char *path,char *filename){
char *file=(char *)malloc(sizeof(char)*1024);
strcpy(file,path);
strcat(file,"/");
strcat(file,filename);
strcat(file,"-record");
recordpath=file;
recordfile=open(file,O_CREAT|O_RDWR,0600);
}
void init(int sk,int scal,char *pa){
filename=(char *)malloc(sizeof(char)*1024);
path=(char *)malloc(sizeof(char)*1024);
array=(struct nodeInfo *)malloc(sizeof(struct nodeInfo)*scal);
record=(int *)malloc(sizeof(int)*1024);
scale=scal;
recvMsg(sk,&filesize,filename);
recordFile(pa,filename);
strcpy(path,pa);
}
void clear(){
close(recordfile);
unlink(recordpath);
free(recordpath);
free(record);
free(path);
free(array);
free(array);
}
int downloads(int sk){
pthread_t ph;
char data[32]="end";
getInfo(sk,array,scale);
pthread_barrier_init(&barrier,0,scale+1);
for(int i=0;i<scale;i++){
record[i]=0;
pthread_create(&ph,0,getFile,(void *)i);
}
pthread_barrier_wait(&barrier);
pthread_barrier_destroy(&barrier);
fusion(filename,scale,path);
sendn(sk,data,2,32);
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m_start;
pthread_cond_t start_info_updater;
int task_type;
unsigned int task_value;
pthread_mutex_t m_result;
pthread_cond_t result_info_updater;
unsigned long long result;
int task_completet;
unsigned long long calc_factorial(unsigned what){
unsigned long long result = 1;
while(what > 0){
result *= what;
--what;
}
return result;
}
void* worker_func(void* arg){
int return_code;
while(1){
pthread_mutex_lock(&m_start);
do{
if(task_type != 0){
break;
}
printf("waiting for new task\\n");
return_code = pthread_cond_wait(&start_info_updater, &m_start);
if(return_code != 0){
perror("cond var error");
exit(1);
}
}while(1);
if(task_type == -1){
pthread_mutex_unlock(&m_start);
break;
}
if(task_type == 1){
unsigned local_task = task_value;
task_type = 0;
pthread_mutex_unlock(&m_start);
unsigned long long res = calc_factorial(local_task);
pthread_mutex_lock(&m_result);
task_completet = 1;
result = res;
pthread_cond_signal(&result_info_updater);
pthread_mutex_unlock(&m_result);
}
}
return 0;
}
int main(){
pthread_mutex_init(&m_start, 0);
pthread_mutex_init(&m_result, 0);
pthread_cond_init(&start_info_updater, 0);
pthread_cond_init(&result_info_updater, 0);
task_completet = 0;
task_type = 0;
int return_code;
pthread_t worker;
return_code = pthread_create(&worker, 0, worker_func, 0);
if(return_code != 0){
perror("failed to create worker");
exit(1);
}
unsigned int task_var;
while(scanf("%ud", &task_var) == 1){
pthread_mutex_lock(&m_start);
task_type = 1;
task_value = task_var;
pthread_cond_signal(&start_info_updater);
pthread_mutex_unlock(&m_start);
printf("waiting for computation\\n");
pthread_mutex_lock(&m_result);
do{
if(task_completet == 1){
break;
}
printf("waiting for computation in cycle\\n");
return_code = pthread_cond_wait(&result_info_updater, &m_result);
if(return_code != 0){
perror("cond var error");
exit(1);
}
} while(1);
task_completet = 0;
unsigned long long res = result;
pthread_mutex_unlock(&m_result);
printf("result of last task is: %llu \\n", res);
}
pthread_mutex_lock(&m_start);
task_type = -1;
pthread_cond_signal(&start_info_updater);
pthread_mutex_unlock(&m_start);
pthread_join(worker, 0);
return 0;
}
| 1
|
#include <pthread.h>
{
long int timeout;
void *(*func)(void*);
void *arg;
} timeout_func_t;
static pthread_mutex_t mutex;
static void register_timeout(timeout_func_t *func)
{
pthread_t thid;
struct timespec spec = {0};
clock_gettime(CLOCK_REALTIME, &spec);
spec.tv_sec += func->timeout;
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &spec, 0);
if (pthread_create(&thid, 0, func->func, func->arg) != 0)
{
fprintf(stderr, "create thread failure\\n");
return ;
}
}
static void *thread(void* arg)
{
pthread_mutex_lock(&mutex);
if (arg == 0)
{
printf("timeout now time is 0\\n");
}
else
{
printf("output base infomation\\n");
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_mutexattr_t attr = {0};
timeout_func_t func = {10, thread, 0};
if (pthread_mutexattr_init(&attr) != 0)
{
fprintf(stderr, "mutex attr init failure\\n");
return 1;
}
if (pthread_mutexattr_settype(&attr,PTHREAD_MUTEX_RECURSIVE) != 0)
{
fprintf(stderr, "mutex attr set recursive failure\\n");
return 1;
}
if (pthread_mutex_init(&mutex, &attr) != 0)
{
fprintf(stderr, "mutex init failure\\n");
return 1;
}
pthread_mutex_lock(&mutex);
register_timeout(&func);
pthread_mutex_unlock(&mutex);
pthread_mutexattr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int evict_time = 2;
void evict_from_cache(struct file_cache* cache){
pthread_mutex_lock(&(cache->fc_mutex_lock));
int free_files = cache->max_entries - (cache->num_files_pinned_dirty + cache->num_files_pinned_clean + cache->num_files_unpinned_clean + cache->num_files_unpinned_dirty);
struct file_cache_entry* entry;
int cur_time;
if (cache->num_files_free < cache->water_mark){
entry = cache->unpinned_clean->head;
while (cache->num_files_free < cache->water_mark && cache->unpinned_clean->head!=cache->unpinned_clean->tail){
entry->unpinned_clean = 0;
entry->valid = 1;
cache->num_files_unpinned_clean--;
cache->num_files_free++;
entry = entry->unpinned_clean_next;
remove_queue(entry, cache->unpinned_clean);
insert_queue(entry, cache->freeq);
}
if (cache->num_files_free < cache->water_mark && cache->unpinned_dirty->head!=cache->unpinned_dirty->tail){
entry = cache->unpinned_dirty->head;
while (cache->num_files_free < cache->water_mark){
entry->unpinned_dirty = 0;
entry->valid = 1;
cache->num_files_unpinned_dirty--;
cache->num_files_free++;
entry = entry->unpinned_clean_next;
flush_data_to_file(entry->alloc_data);
remove_queue(entry, cache->unpinned_dirty);
insert_queue(entry, cache->freeq);
}
}
}
entry = cache->unpinned_clean->head;
cur_time = get_time_stamp();
while(entry != cache->unpinned_clean->tail){
if ((cur_time - entry->last_accessed) > evict_time){
entry->unpinned_clean = 0;
entry->valid = 1;
cache->num_files_unpinned_clean--;
cache->num_files_free++;
entry = entry->unpinned_clean_next;
remove_queue(entry, cache->unpinned_clean);
insert_queue(entry, cache->freeq);
}
else break;
}
if (cache->num_files_free > 0)
pthread_cond_signal(&(cache->cv));
pthread_mutex_unlock(&(cache->fc_mutex_lock));
}
| 1
|
#include <pthread.h>
void pickup(int j);
void putdown(int i);
void test(int k);
void philosopher(int * id);
pthread_mutex_t lock;
char state[50];
pthread_cond_t self;
int num_phil;
int main(int argc,char *argv[]){
int n, *who;
pthread_t phils[50];
void * retval;
if(argc != 2) {
printf("error!!!!\\n");
puts("usage: phil number_of_philosophers, ex phil 5\\n");
exit(0);
}
num_phil = atoi(argv[1]);
pthread_mutex_init(&lock, 0);
for (n = 0;n<num_phil;n++){
state[n] = 't';
}
pthread_cond_init(&self, 0);
for (n = 0;n<num_phil;n++){
who = (int *)malloc(sizeof(int));
*who = n;
if (pthread_create(&(phils[n]), 0, (void *)philosopher, who) != 0) {
perror("pthread_create");
exit(1);
}
}
pthread_join(phils[0],0);
return 0;
}
void pickup(int j){
printf("phil %d is trying to pickup\\n",j);
pthread_mutex_lock(&lock);
state[j] = 'h';
test(j);
while( state[j] != 'e'){
pthread_cond_wait(&self, &lock);
}
pthread_mutex_unlock(&lock);
return;
}
void putdown(int i){
printf("phil %d is putting down\\n",i);
state[i] = 't';
test((i+(num_phil-1)) % num_phil);
test((i+1) % num_phil);
}
void test(int k){
while( (state[(k+(num_phil-1)) % num_phil] != 'e') && ( state[k] == 'h') && (state[(k+1) % num_phil] != 'e') ){
state[k] = 'e';
pthread_cond_broadcast(&self);
}
}
void philosopher(int * id){
int n=0;
printf("i am phil %d\\n",*id);
sleep(1);
while(n < 10){
pickup(*id);
printf("Philosopher %d is eating\\n",*id);
sleep(1);
putdown(*id);
printf("Philosopher %d is thinking\\n",*id);
sleep(1);
n++;
}
return;
}
| 0
|
#include <pthread.h>
void *Producer();
void *Consumer();
pthread_mutex_t the_mutex;
pthread_cond_t condc, condp;
int buffer = 1;
int numIters;
int main(int argc, char **argv) {
double begin, end, time_spent;
begin = clock();
pthread_t pid, cid;
numIters = atoi(argv[1]);
pthread_mutex_init(&the_mutex, 0);
pthread_cond_init(&condc, 0);
pthread_cond_init(&condp, 0);
pthread_create(&cid, 0, Consumer, 0);
pthread_create(&pid, 0, Producer, 0);
pthread_join(cid, 0);
pthread_join(pid, 0);
pthread_mutex_destroy(&the_mutex);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%f\\n", time_spent);
return 0;
}
void* Producer() {
int i;
for (i = 1; i < numIters; i++) {
pthread_mutex_lock(&the_mutex);
while (buffer != 0)
pthread_cond_wait(&condp, &the_mutex);
buffer = i;
pthread_cond_signal(&condc);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
void* Consumer() {
int i;
for (i = 1; i < numIters; i++) {
pthread_mutex_lock(&the_mutex);
while (buffer == 0)
pthread_cond_wait(&condc, &the_mutex);
buffer = 0;
pthread_cond_signal(&condp);
pthread_mutex_unlock(&the_mutex);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct propset {
char *str;
int row;
int col;
int delay;
int dir;
int vert;
int prevr;
};
pthread_mutex_t myLock = PTHREAD_MUTEX_INITIALIZER;
int main(int argc, const char *argv[])
{
void *animate(void *);
int setup(int, char **, struct propset *);
int ch;
int numMsg;
pthread_t thrds[10];
struct propset props[10];
numMsg = setup(argc - 1, argv + 1, props);
for (int i = 0; i < numMsg; ++i) {
pthread_create(&thrds[i], 0, animate, (void *)&props[i]);
}
while (1) {
ch = getch();
if (ch == 'q') break;
if (ch == ' ') {
for (int i = 0; i < numMsg; ++i) {
props[i].dir = -props[i].dir;
}
}
if (ch >= '0' && ch <= '9') {
if ( ch - '0' < numMsg)
props[ch - '0'].dir = -props[ch - '0'].dir;
}
}
for (int i = 0; i < numMsg; ++i) {
pthread_cancel(thrds[i]);
}
endwin();
return 0;
}
int setup(int numOfStr, char *mStr[], struct propset props[]) {
int numOfMsg = numOfStr > 10 ? 10 : numOfStr;
srand(getpid());
initscr();
for (int i = 0; i < numOfMsg; ++i) {
props[i].str = mStr[i];
props[i].row = i;
props[i].col = rand() % (LINES - strlen(mStr[i]) - 2);
props[i].delay = 100 + (rand() % 100);
props[i].dir = ((rand() % 2) ? 1 : -1);
props[i].prevr = -1;
props[i].vert = (rand() % 2) ? 1 : -1;
}
crmode();
noecho();
clear();
mvprintw(LINES - 1, 0, "'q' to quit, '0'..'%d' to bounce", numOfMsg - 1);
return numOfMsg;
}
void *animate(void *arg) {
struct propset *info = arg;
int len = strlen(info->str) + 2;
while (1) {
usleep(info->delay * 1000);
pthread_mutex_lock(&myLock);
if (info->vert == 1) {
if (info->prevr != -1) {
move(info->prevr, info->col);
printw("%*s", strlen(info->str), "");
}
move(info->row, info->col);
addstr(info->str);
info->prevr = info->row;
} else {
move(info->row, info->col);
addch(' ');
addstr(info->str);
addch(' ');
}
move(LINES - 1, COLS - 1);
refresh();
pthread_mutex_unlock(&myLock);
if (info ->vert == 1) {
info->row += info->dir;
if (info->row >= LINES - 2 && 1 == info->dir)
info->dir = -1;
else if (info->row <= 0 && -1 == info->dir)
info->dir = 1;
} else {
info->col += info->dir;
if (info->col <= 0 && -1 == info->dir)
info->dir = 1;
else if (info->col + len >= COLS && 1 == info->dir)
info->dir = -1;
}
}
return 0;
}
| 0
|
#include <pthread.h>
int _RW = 0;
pthread_mutex_t clk_mtx;
pthread_cond_t pulse;
pthread_mutex_t pause_mtx = PTHREAD_MUTEX_INITIALIZER;
void init();
void shutdown_cpu();
void pause_cpu();
void *cpu_clock(void *arg);
void disp__IWRF();
int main(int argc, char **argv)
{
FILE *stderr_out;
pthread_t clk, iiu, iu;
char **titles = (char **)calloc(4, sizeof(char *));
titles[0] = "Instruction Issue unit";
titles[1] = "Integer Working Register File";
titles[2] = "Integer unit";
titles[3] = "Float unit";
assert(argc > 1);
stderr_out = freopen("stderr.out", "w", stderr);
setbuf(stderr_out, 0);
init_ncurses(4, titles);
init_key_ctrls(2, 27, shutdown_cpu, ' ', pause_cpu);
pthread_mutex_init(&clk_mtx, 0);
pthread_mutex_init(&pause_mtx, 0);
pthread_cond_init(&pulse, 0);
init();
pthread_create(&clk, 0, cpu_clock, 0);
pthread_create(&iiu, 0, instruction_issue, argv[1]);
pthread_create(&iu, 0, integer, 0);
pthread_join(clk, 0);
pthread_join(iiu, 0);
pthread_join(iu, 0);
return 0;
}
void init()
{
int i;
for (i = 0; i < 32; i++) {
_IWRF[i] = 0;
}
}
void shutdown_cpu()
{
fclose(stderr);
end_ncurses();
pthread_mutex_destroy(&pause_mtx);
pthread_mutex_destroy(&clk_mtx);
pthread_cond_destroy(&pulse);
printf("Shutdown CPU\\n");
exit(0);
}
void pause_cpu()
{
static int state;
if (state == 0) {
pthread_mutex_lock(&pause_mtx);
} else {
pthread_mutex_unlock(&pause_mtx);
}
state = (state + 1) % 2;
}
void *cpu_clock(void *arg)
{
static int cur_clk;
pthread_mutex_lock(&clk_mtx);
while(1) {
pthread_mutex_unlock(&pause_mtx);
sleep(1);
fprintf(stderr, "\\n{%d}<--clock-----------------\\n", cur_clk);
disp__IWRF();
pthread_cond_broadcast(&pulse);
cur_clk++;
pthread_mutex_lock(&pause_mtx);
}
}
void clk_cycle()
{
pthread_cond_wait(&pulse, &clk_mtx);
}
void disp__IWRF()
{
int i;
nreset(0);
for (i = 0; i < 32; i++) {
nprintf(1, "[%d] %d\\n", i, _IWRF[i]);
}
}
| 1
|
#include <pthread.h>
int ret_count;
void *producer (void *args);
void *consumer (void *args);
int buf[10];
long head, tail;
int full, empty;
pthread_mutex_t *mut;
pthread_cond_t *notFull, *notEmpty;
} queue;
queue *queueInit (void);
void queueDelete (queue *q);
void queueAdd (queue *q, int in);
void queueDel (queue *q, int *out);
int main ()
{
queue *fifo;
pthread_t pro, con;
fifo = queueInit ();
if (fifo == 0)
{
fprintf (stderr, "main: Queue Init failed.\\n");
exit (1);
}
ret_count=pthread_create (&pro, 0, producer, fifo);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_create() is %d ",ret_count);
exit(-1);
}
ret_count=pthread_create (&con, 0, consumer, fifo);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_create() is %d ",ret_count);
exit(-1);
}
ret_count=pthread_join (pro, 0);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_join() is %d ",ret_count);
exit(-1);
}
ret_count=pthread_join (con, 0);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_join() is %d ",ret_count);
exit(-1);
}
queueDelete (fifo);
return 0;
}
void *producer (void *q)
{
queue *fifo;
int i;
fifo = (queue *)q;
for (i = 0; i < 20; i++)
{
pthread_mutex_lock (fifo->mut);
while (fifo->full)
{
printf ("producer: queue FULL.\\n");
pthread_cond_wait (fifo->notFull, fifo->mut);
}
queueAdd (fifo, i);
pthread_mutex_unlock (fifo->mut);
pthread_cond_signal (fifo->notEmpty);
printf ("producer: add %d \\n",i);
usleep (100000);
}
return (0);
}
void *consumer (void *q)
{
queue *fifo;
int i, d;
fifo = (queue *)q;
for (i = 0; i < 20; i++)
{
pthread_mutex_lock (fifo->mut);
while (fifo->empty)
{
printf ("consumer: queue EMPTY.\\n");
pthread_cond_wait (fifo->notEmpty, fifo->mut);
}
queueDel (fifo, &d);
pthread_mutex_unlock (fifo->mut);
pthread_cond_signal (fifo->notFull);
printf ("consumer: received %d.\\n", d);
usleep(500000);
}
return (0);
}
queue *queueInit (void)
{
queue *q;
q = (queue *)malloc (sizeof (queue));
if (q == 0) return (0);
q->empty = 1;
q->full = 0;
q->head = 0;
q->tail = 0;
q->mut = (pthread_mutex_t *) malloc (sizeof (pthread_mutex_t));
ret_count=pthread_mutex_init (q->mut, 0);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_mutex_init() is %d ",ret_count);
exit(-1);
}
q->notFull = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->notFull, 0);
q->notEmpty = (pthread_cond_t *) malloc (sizeof (pthread_cond_t));
pthread_cond_init (q->notEmpty, 0);
return (q);
}
void queueDelete (queue *q)
{
ret_count=pthread_mutex_destroy (q->mut);
if(ret_count)
{
printf("\\n ERROR : Return code from pthread_mutex_destroy() is %d ",ret_count);
exit(-1);
}
free (q->mut);
pthread_cond_destroy (q->notFull);
free (q->notFull);
pthread_cond_destroy (q->notEmpty);
free (q->notEmpty);
free (q);
}
void queueAdd (queue *q, int in)
{
q->buf[q->tail] = in;
q->tail++;
if (q->tail == 10)
q->tail = 0;
if (q->tail == q->head)
q->full = 1;
q->empty = 0;
return;
}
void queueDel (queue *q, int *out)
{
*out = q->buf[q->head];
q->head++;
if (q->head == 10)
q->head = 0;
if (q->head == q->tail)
q->empty = 1;
q->full = 0;
return;
}
| 0
|
#include <pthread.h>
void
netfs_nrele (struct node *np)
{
struct references result;
int locked = FALSE;
refcounts_demote (&np->refcounts, &result);
if (result.hard == 0)
{
pthread_mutex_lock (&np->lock);
netfs_try_dropping_softrefs (np);
locked = TRUE;
}
refcounts_deref_weak (&np->refcounts, &result);
if (result.hard == 0 && result.weak == 0)
{
if (! locked)
pthread_mutex_lock (&np->lock);
netfs_drop_node (np);
} else if (locked)
pthread_mutex_unlock (&np->lock);
}
void
netfs_nrele_light (struct node *np)
{
struct references result;
refcounts_deref_weak (&np->refcounts, &result);
if (result.hard == 0 && result.weak == 0)
{
pthread_mutex_lock (&np->lock);
netfs_drop_node (np);
}
}
| 1
|
#include <pthread.h>
struct LOGUTIL_THREAD *pnext;
pthread_t tid;
char tag[LOGUTIL_TAG_LENGTH];
} LOGUTIL_THREAD_T;
LOGUTIL_THREAD_T arr[64];
LOGUTIL_THREAD_T *tids_free;
LOGUTIL_THREAD_T *tids;
pthread_mutex_t mtx;
} LOGUTIL_THREAD_CTXT_T;
static LOGUTIL_THREAD_CTXT_T _g_logutil_tidctxt;
static LOGUTIL_THREAD_CTXT_T *g_plogutil_tidctxt = &_g_logutil_tidctxt;
void *logutil_tid_getContext() {
return g_plogutil_tidctxt;
}
int logutil_tid_setContext(void *pCtxt) {
if(g_plogutil_tidctxt && g_plogutil_tidctxt->tids) {
return -1;
}
g_plogutil_tidctxt = pCtxt;
return 0;
}
void logutil_tid_init() {
unsigned int idx;
pthread_mutex_init(&g_plogutil_tidctxt->mtx, 0);
memset(g_plogutil_tidctxt->arr, 0, sizeof(g_plogutil_tidctxt->arr));
for(idx = 1; idx < 64; idx++) {
g_plogutil_tidctxt->arr[idx - 1].pnext = &g_plogutil_tidctxt->arr[idx];
}
g_plogutil_tidctxt->tids_free = &g_plogutil_tidctxt->arr[0];
g_plogutil_tidctxt->tids = 0;
}
int logutil_tid_add(pthread_t tid, const char *tag) {
int rc = -1;
LOGUTIL_THREAD_T *pTidCtxt;
if(tid == 0 || !tag || tag[0] == '\\0') {
return -1;
}
pthread_mutex_lock(&g_plogutil_tidctxt->mtx);
pTidCtxt = g_plogutil_tidctxt->tids;
while(pTidCtxt) {
if(tid == pTidCtxt->tid) {
strncpy(pTidCtxt->tag, tag, sizeof(pTidCtxt->tag) - 1);
rc = 0;
break;
}
pTidCtxt = pTidCtxt->pnext;
}
if(rc != 0 && (pTidCtxt = g_plogutil_tidctxt->tids_free)) {
g_plogutil_tidctxt->tids_free = g_plogutil_tidctxt->tids_free->pnext;
if(g_plogutil_tidctxt->tids) {
pTidCtxt->pnext = g_plogutil_tidctxt->tids;
} else {
pTidCtxt->pnext = 0;
}
g_plogutil_tidctxt->tids = pTidCtxt;
pTidCtxt->tid = tid;
strncpy(pTidCtxt->tag, tag, sizeof(pTidCtxt->tag) - 1);
rc = 0;
} else {
rc = -1;
}
pthread_mutex_unlock(&g_plogutil_tidctxt->mtx);
return rc;
}
int logutil_tid_remove(pthread_t tid) {
int rc = -1;
LOGUTIL_THREAD_T *pTidCtxt, *pTidCtxtPrev = 0;
pthread_mutex_lock(&g_plogutil_tidctxt->mtx);
pTidCtxt = g_plogutil_tidctxt->tids;
while(pTidCtxt) {
if(tid == pTidCtxt->tid) {
if(pTidCtxtPrev) {
pTidCtxtPrev->pnext = pTidCtxt->pnext;
} else {
g_plogutil_tidctxt->tids = pTidCtxt->pnext;
}
pTidCtxt->pnext = g_plogutil_tidctxt->tids_free;
g_plogutil_tidctxt->tids_free = pTidCtxt;
rc = 0;
break;
}
pTidCtxtPrev = pTidCtxt;
pTidCtxt = pTidCtxt->pnext;
}
pthread_mutex_unlock(&g_plogutil_tidctxt->mtx);
return rc;
}
const char *logutil_tid_lookup(pthread_t tid, int update) {
const char *tag = 0;
LOGUTIL_THREAD_T *pTidCtxt, *pTidCtxtPrev = 0;
pthread_mutex_lock(&g_plogutil_tidctxt->mtx);
pTidCtxt = g_plogutil_tidctxt->tids;
while(pTidCtxt) {
if(tid == pTidCtxt->tid) {
tag = pTidCtxt->tag;
if(update && pTidCtxtPrev) {
pTidCtxtPrev->pnext = pTidCtxt->pnext;
pTidCtxt->pnext = g_plogutil_tidctxt->tids;
g_plogutil_tidctxt->tids = pTidCtxt;
}
break;
}
pTidCtxtPrev = pTidCtxt;
pTidCtxt = pTidCtxt->pnext;
}
pthread_mutex_unlock(&g_plogutil_tidctxt->mtx);
return tag ? tag : "";
}
| 0
|
#include <pthread.h>
struct timeval start, end;
long mtime, seconds, useconds;
pthread_mutex_t mutex;
pthread_cond_t waitBarber;
pthread_cond_t waitCustomers;
pthread_cond_t waitCutting;
int waiting = 0;
int customer_cutting;
void cutHair() {
pthread_cond_wait(&waitCutting,&mutex);
pthread_mutex_unlock(&mutex);
printf("Barber: I'm cutting Hair to customer %d\\n",customer_cutting);
usleep(rand()%1000+100000);
}
void receiveHairCut(int id) {
customer_cutting = id;
pthread_cond_signal(&waitCutting);
printf("Customer %d: and I'm receiving a hair cut\\n",id);
usleep(rand()%1000+100000);
}
void* barberThread( void* param ) {
printf("Barber: I'll wait for customers\\n");
while(1) {
pthread_mutex_lock(&mutex);
while(waiting==0) pthread_cond_wait(&waitCustomers,&mutex);
waiting--;
pthread_mutex_unlock(&mutex);
printf("Barber: hello customer\\n");
pthread_cond_signal(&waitBarber);
cutHair();
printf("Barber: I have finished\\n");
}
}
void* customerThread( void* param ) {
int id = *((int*)param);
free(param);
pthread_mutex_lock(&mutex);
if(waiting < 8) {
printf("Customer %d: arrived and I'll stay\\n",id);
waiting++;
pthread_cond_signal(&waitCustomers);
pthread_cond_wait(&waitBarber,&mutex);
pthread_mutex_unlock(&mutex);
receiveHairCut(id);
printf("Customer %d: Leaving\\n",id);
}
else {
printf("Customer %d: go without haircut\\n",id);
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
gettimeofday(&start, 0);
if (pthread_mutex_init(&mutex, 0) != 0) { printf("mutex error\\n"); }
if (pthread_cond_init(&waitBarber, 0) != 0) { printf("error initializing condition\\n"); }
if (pthread_cond_init(&waitCustomers, 0) != 0) { printf("error initializing condition\\n"); }
if (pthread_cond_init(&waitCutting, 0) != 0) { printf("error initializing condition\\n"); }
pthread_t* tid;
tid = malloc(10 * sizeof(pthread_t));
pthread_create(&tid[i], 0, barberThread, 0);
int *id;
for(i=0;i<10/2;i++) {
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&tid[i], 0, customerThread, (void*)id);
}
for(i=10/2;i<10;i++) {
usleep(100000 + rand()%100000);
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&tid[i], 0, customerThread, (void*)id);
}
printf("Main waiting for threads...\\n");
for(i=0;i<10;i++) pthread_join(tid[i], 0);
usleep(10000);
gettimeofday(&end, 0);
seconds = end.tv_sec - start.tv_sec;
useconds = end.tv_usec - start.tv_usec;
mtime = ((seconds) * 1000 + useconds/1000.0) + 0.5;
printf("Elapsed time: %ld milliseconds\\n", mtime);
return 0;
}
| 1
|
#include <pthread.h>
double suma;
pracuji,
ukoncen,
prazdne
}stavVlakna;
int dejVolnyIndexZeSeznamu(stavVlakna* stavyVlaken,int size);
int pridejVlaknoDoSeznamu(stavVlakna* stavyVlaken,pthread_t** vlakna,pthread_t* vlakno, int size, int indexVlakna);
void inicializujSeznam(stavVlakna* stavyVlaken, int size);
void pockejDokudVseNeskonci(stavVlakna* stavyVlaken,pthread_t** vlakna,int size);
int ukonciVlakno(stavVlakna* stavyVlaken,int size,int index);
pthread_t *seznamVlaken[64000];
stavVlakna stavyVlaken[64000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexSeznamu = PTHREAD_MUTEX_INITIALIZER;
sem_t threads_limiter;
void* procesVlakna(void* vstupniArgumenty){
char adresaSouboru[250];
pthread_mutex_lock(&mutexSeznamu);
strcpy(adresaSouboru,(char*)(((void**)vstupniArgumenty)[0]));
int indexVlakna = *(((int**)vstupniArgumenty)[1]);
pthread_mutex_unlock(&mutexSeznamu);
printf("Thread%d: Cekam na povoleni cinnosti...\\n",indexVlakna);
fflush(stdout);
sem_wait(&threads_limiter);
printf("Thread%d: Povoleni k cinnosti udeleno... \\n",indexVlakna);
fflush(stdout);
FILE* file = fopen(adresaSouboru, "r");
if (file == 0) {
fprintf(stderr, "Thread%d: File %s can't be opened\\n",indexVlakna,adresaSouboru);
exit(1);
}
printf("Thread%d: Nacitam soubor... %s \\n",indexVlakna,adresaSouboru);
fflush(stdout);
char data[250];
while(fgets(data, sizeof(data), file))
{
usleep(1);
char *cntrl;
double cislo = strtod (data, &cntrl);
pthread_mutex_lock(&mutex);
suma += cislo;
pthread_mutex_unlock(&mutex);
}
printf("Thread%d: Soubor je zcela precten... \\n",indexVlakna);
printf("Thread%d0: Ukoncuji se... \\n",indexVlakna);
fflush(stdout);
fclose(file);
pthread_mutex_lock(&mutexSeznamu);
ukonciVlakno(stavyVlaken,64000,indexVlakna);
pthread_mutex_unlock(&mutexSeznamu);
sem_post(&threads_limiter);
return 0;
}
int main(){
void* dataProVlakno[2];
int idVlakna;
char fileAdress[250];
pthread_t thread;
suma = 0;
if (sem_init(&threads_limiter, 0, 2) < 0) {
perror("sem_init");
exit(1);
}
inicializujSeznam(stavyVlaken,64000);
while(1){
printf("Main: Zadejte nazev soubrou\\n");
moje_gets(fileAdress,sizeof(fileAdress));
if(fileAdress[0]==0) {
printf("Main: Ukoncuji program..\\n");
break;
}
dataProVlakno[0] = fileAdress;
printf("Main: Zakladam vlakno...\\n");
pthread_mutex_lock(&mutexSeznamu);
idVlakna = dejVolnyIndexZeSeznamu(stavyVlaken,64000);
if(idVlakna <0){
printf("ID ERROR \\n");exit(1);
}
dataProVlakno[1] = &idVlakna;
pthread_create(&thread, 0, procesVlakna, dataProVlakno);
pridejVlaknoDoSeznamu(stavyVlaken,seznamVlaken,&thread,64000,idVlakna);
pthread_mutex_unlock(&mutexSeznamu);
}
pockejDokudVseNeskonci(stavyVlaken,seznamVlaken,64000);
printf("Main: Finalni suma je %f$ \\n",suma);
printf("Main: Konec programu \\n");
return 0;
}
int dejVolnyIndexZeSeznamu(stavVlakna* stavyVlaken,int size){
for(int i =0;i<size;i++){
if(stavyVlaken[i]==prazdne){return i;}
}
return -1;
}
int pridejVlaknoDoSeznamu(stavVlakna* stavyVlaken,pthread_t** vlakna,pthread_t* vlakno, int size, int indexVlakna){
if(indexVlakna==-1){return -1;}
if(indexVlakna>=size){return -1;}
if(stavyVlaken[indexVlakna]==pracuji || stavyVlaken[indexVlakna]==ukoncen){return -1;}
vlakna[indexVlakna] = vlakno;
stavyVlaken[indexVlakna] = pracuji;
return indexVlakna;
}
void inicializujSeznam(stavVlakna* stavyVlaken, int size){
for(int i =0;i<size;i++){
stavyVlaken[i] = prazdne;
}
}
void pockejDokudVseNeskonci(stavVlakna* stavyVlaken,pthread_t** vlakna,int size){
int vseUkonceno=0;
while(!vseUkonceno){
vseUkonceno=1;
for(int i =0;i<size;i++){
if(stavyVlaken[i]==ukoncen)
{
pthread_join(*(vlakna[i]),0);
stavyVlaken[i]=prazdne;
}
else if(stavyVlaken[i]==pracuji)
{
vseUkonceno = 0;
}
}
usleep(1000);
}
}
int ukonciVlakno(stavVlakna* stavyVlaken,int size,int index){
if(index >= size ){return -1;}
stavyVlaken[index] = ukoncen;
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t can_write = PTHREAD_COND_INITIALIZER;
pthread_cond_t can_read = PTHREAD_COND_INITIALIZER;
char arr[10] = {0};
int in_pos = 0;
int out_pos = 0;
void* do_it_a(void* p)
{
char c = 'a';
for(; c <= 'z'; c++)
{
pthread_mutex_lock(&lock);
if(((in_pos + 1)%10) == out_pos)
{
printf("queue is full(a)\\n");
pthread_mutex_lock(&lock);
}
pthread_cond_wait(&can_write,&lock);
arr[in_pos] = c;
in_pos = (in_pos + 1) % 10;
pthread_cond_signal(&can_read);
pthread_mutex_unlock(&lock);
}
}
void* do_it_b(void* p)
{
char c = 'A';
for(; c <= 'Z'; c++)
{
pthread_mutex_lock(&lock);
if(((in_pos + 1)%10) == out_pos)
{
printf("%d\\n",(in_pos+1)%10);
printf("%d\\n",out_pos);
printf("queue is full(b)\\n");
pthread_mutex_unlock(&lock);
}
arr[in_pos] = c;
in_pos = (in_pos + 1) % 10;
pthread_cond_signal(&can_read);
pthread_mutex_unlock(&lock);
}
}
void* do_it_c(void* p)
{
int i = 0;
char c = 'A';
char box;
for(; i <= 52; i++)
{
pthread_mutex_lock(&lock);
if(in_pos == out_pos)
{
printf("queue is empty\\n");
pthread_mutex_unlock(&lock);
}
pthread_cond_wait(&can_read,&lock);
for(; c <= 'Z'; c++)
{
if(arr[out_pos] == c)
{
printf("big printf:%c\\n",c);
fflush(stdout);
out_pos = ((out_pos + 1) % 10);
}
}
pthread_cond_signal(&can_write);
pthread_mutex_unlock(&lock);
}
}
void* do_it_d(void* p)
{
int i = 0;
char c = 'a';
char box;
for(; i <= 52; i++)
{
pthread_mutex_lock(&lock);
if(in_pos == out_pos)
{
printf("queue is empty\\n");
pthread_mutex_unlock(&lock);
}
pthread_cond_wait(&can_read,&lock);
for(; c <= 'z'; c++)
{
if(arr[out_pos] == c)
{
printf("small printf:%c\\n",c);
fflush(stdout);
out_pos = ((out_pos + 1) % 10);
}
}
pthread_cond_signal(&can_write);
pthread_mutex_unlock(&lock);
}
}
int main()
{
printf("%d\\n",1%10);
pthread_t t1;
pthread_t t2;
pthread_t t3;
pthread_t t4;
pthread_create(&t1,0,do_it_a,0);
pthread_create(&t1,0,do_it_b,0);
pthread_create(&t1,0,do_it_c,0);
pthread_create(&t1,0,do_it_d,0);
pthread_join(t1,0);
pthread_join(t2,0);
pthread_join(t3,0);
pthread_join(t4,0);
return 0;
}
| 1
|
#include <pthread.h>
double start_time, end_time;
long size;
int *inputArray;
int size;
struct thread_data nextTask;
} thread_data;
thread_data * nextTaskInLine;
void *quickSort(void *);
void swap(int *inputArray, int leftIndex, int rightIndex);
double read_timer();
thread_data master;
int numWorkers;
pthread_mutex_t mutex;
pthread_mutex_t arrayLock;
int main(int argc, char *argv[]) {
int i, l, threads;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&arrayLock, 0);
size = (argc > 1)? atoi(argv[1]) : 50000000;
if (size > 50000000){ size = 50000000; }
if (size < 2){
printf("Array is only one element!\\n");
return 0;
}
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (numWorkers > 10) { numWorkers = 10; }
int *inputArray;
inputArray = malloc(sizeof(int) * size);
srand(time(0));
for (i = 0; i < size; i++) {
inputArray[i] = rand()%99999;
}
start_time = read_timer();
thread_data_pointer master = malloc(sizeof(thread_data));
master.inputArray = (int *)inputArray;
master.size = size;
master.nextTask = 0;
for (l = 0; l < numWorkers; l++) {
pthread_create(&workerid[l], &attr, quickSort, (void *) l);
}
for(threads = 0; threads < numWorkers; threads++){
pthread_join(workerid[threads], 0);
}
end_time = read_timer();
for (i = 1; i < size; i++) {
if (!(inputArray[i-1] <= inputArray[i])) {
printf("NOT SORTED!!!!!!!!!!!!!!!!!!!!!\\n");
}
}
free(inputArray);
free(master);
printf("The execution time is %g sec\\n", end_time - start_time);
return 0;
}
bool first = 1;
bool sorted = 0;
void *quickSort(void *a){
int pivot, leftIndex, rightIndex;
int *inputArray;
int size;
thread_data nextTask;
pthread_mutex_lock(&mutex);
if (first) {
thread_data *myData = (thread_data *) master;
inputArray = myData->inputArray;
size = myData->size;
nextTask = myData->nextTask;
first = 0;
}
pthread_mutex_unlock(&mutex);
while(1){
if (sorted) {
pthread_exit(0);
}
pthread_mutex_lock(&mutex);
if (nextTask == 0 && !sorted) {
nextTask = nextTaskInLine;
}
pthread_mutex_unlock(&mutex);
if(nextTask != 0 && !sorted) {
if (size <= 1) { break; }
pivot = inputArray[size/2];
for(leftIndex = 0, rightIndex = size -1;; leftIndex++, rightIndex--) {
while(inputArray[leftIndex] < pivot){
leftIndex++;
}
while(pivot < inputArray[rightIndex]){
rightIndex--;
}
if(rightIndex <= leftIndex){
break;
}
swap(inputArray, leftIndex, rightIndex);
}
thread_data task1, task2;
thread_data_pointer task1 = malloc(sizeof(thread_data));
thread_data_pointer task2 = malloc(sizeof(thread_data));
task1.inputArray = (int *) inputArray;
task1.size = leftIndex;
task1.nextTask = (thread_data *) task2;
task2.inputArray = (int *) inputArray + rightIndex + 1;
task2.size = size - rightIndex -1;
task2.nextTask = 0;
pthread_mutex_lock(&arrayLock);
nextTaskInLine = &task1;
pthread_mutex_unlock(&arrayLock);
}
}
}
void swap(int *inputArray, int leftIndex, int rightIndex){
int temp;
temp = inputArray[leftIndex];
inputArray[leftIndex] = inputArray[rightIndex];
inputArray[rightIndex] = temp;
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized ) {
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexOne;
pthread_mutex_t mutexTwo;
void *lockMutexOne(void *args)
{
pthread_mutex_lock(&mutexOne);
sleep(1);
pthread_mutex_lock(&mutexTwo);
pthread_mutex_unlock(&mutexOne);
pthread_mutex_unlock(&mutexTwo);
return 1;
}
void *lockMutexTwo(void *args)
{
pthread_mutex_lock(&mutexTwo);
sleep(1);
pthread_mutex_lock(&mutexOne);
pthread_mutex_unlock(&mutexTwo);
printf("All threads are done!\\n");
pthread_mutex_unlock(&mutexOne);
return 1;
}
int main()
{
int threadOne, threadTwo;
pthread_t threadOneId, threadTwoId;
void *threadOnePointer, *threadTwoPointer;
pthread_mutex_init(&mutexOne, 0);
pthread_mutex_init(&mutexTwo, 0);
threadOne = pthread_create(&threadOneId, 0, lockMutexOne, 1);
threadOne = pthread_create(&threadTwoId, 0, lockMutexTwo, 2);
pthread_join(threadOneId, &threadOnePointer);
pthread_join(threadTwoId, &threadTwoPointer);
pthread_mutex_destroy(&mutexOne);
pthread_mutex_destroy(&mutexTwo);
return 1;
}
| 1
|
#include <pthread.h>
long thread_count;
long long n;
double sum;
pthread_mutex_t mutex;
void* Thread_sum(void* rank);
void Get_args(int argc, char* argv[]);
void Usage(char* prog_name);
double Serial_pi(long long n);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
double start, finish;
Get_args(argc, argv);
thread_handles = (pthread_t*) malloc (thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
GET_TIME(start);
sum = 0.0;
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
Thread_sum, (void*)thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
sum = 4.0*sum;
GET_TIME(finish);
printf("With n = %lld terms,\\n", n);
printf(" Our estimate of pi = %.15f\\n", sum);
printf("The elapsed time is %.5f seconds\\n", finish - start);
GET_TIME(start);
sum = Serial_pi(n);
GET_TIME(finish);
printf(" Single thread est = %.15f\\n", sum);
printf("The elapsed time is %e seconds\\n", finish - start);
printf(" pi = %.15f\\n", 4.0*atan(1.0));
pthread_mutex_destroy(&mutex);
free(thread_handles);
return 0;
}
void* Thread_sum(void* rank) {
long my_rank = (long) rank;
double factor;
long long i;
long long my_n = n/thread_count;
long long my_first_i = my_n*my_rank;
long long my_last_i = my_first_i + my_n;
double my_sum = 0.0;
if (my_first_i % 2 == 0)
factor = 1.0;
else
factor = -1.0;
for (i = my_first_i; i < my_last_i; i++, factor = -factor) {
my_sum += factor/(2*i+1);
}
pthread_mutex_lock(&mutex);
sum += my_sum;
pthread_mutex_unlock(&mutex);
return 0;
}
double Serial_pi(long long n) {
double sum = 0.0;
long long i;
double factor = 1.0;
for (i = 0; i < n; i++, factor = -factor) {
sum += factor/(2*i+1);
}
return 4.0*sum;
}
void Get_args(int argc, char* argv[]) {
if (argc != 3) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
if (thread_count <= 0) Usage(argv[0]);
n = strtoll(argv[2], 0, 10);
if (n <= 0) Usage(argv[0]);
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <number of threads> <n>\\n", prog_name);
fprintf(stderr, " n is the number of terms and should be >= 1\\n");
fprintf(stderr, " n should be evenly divisible by the number of threads\\n");
exit(0);
}
| 0
|
#include <pthread.h>
int sharedvar;
int count = 0;
pthread_mutex_t sumlock;
pthread_mutex_t countlock;
void simplethread(int argc, char** argv)
{
int numthreads = parseargs(argc, argv);
int i;
pthread_t * pthreads = malloc(sizeof(pthread_t) * numthreads);
for(i = 0 ; i < numthreads ; i++)
{
int notOK = pthread_create(&(pthreads[i]), 0, counting, (void*)i);
if(notOK)
{
printf("Could not create thread.\\n");
exit(-3);
}
}
for(i = 0 ; i < numthreads ; i++)
{
pthread_join(pthreads[i], 0);
}
}
void *counting(void * which)
{
increment(&count);
int num, val;
for(num = 0 ; num < 20 ; num++)
{
if(rand() > 32767 / 2)
{
usleep(10);
}
pthread_mutex_lock(&sumlock);
val = sharedvar;
printf("*** thread %d sees value %d\\n", (int)which, val);
sharedvar = val + 1;
pthread_mutex_unlock(&sumlock);
}
decrement(&count);
wait(&count);
val = sharedvar;
printf("Thread %d sees final value %d\\n", (int)which, val);
pthread_exit((void*) 0);
}
void increment(int * count)
{
pthread_mutex_lock(&countlock);
(*count)++;
pthread_mutex_unlock(&countlock);
}
void decrement(int * count)
{
pthread_mutex_lock(&countlock);
(*count)--;
pthread_mutex_unlock(&countlock);
}
void wait(int * count)
{
while(getcount() > 0){ usleep(20); }
}
int getcount()
{
int cnt = 0 ;
pthread_mutex_lock(&countlock);
cnt = count;
pthread_mutex_unlock(&countlock);
return cnt;
}
| 1
|
#include <pthread.h>
int b[10];
int cont = 0;
pthread_cond_t prod_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t cons_cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mp = PTHREAD_MUTEX_INITIALIZER;
int prod_pos = 0;
int cons_pos = 0;
void * produtor(void * arg){
while(1){
printf("Proutor - Vai produzir\\n");
int p = (int)(drand48()*1000);
pthread_mutex_lock(&mp);
while (cont == 10) {
printf("Produtor - Dormindo\\n");
pthread_cond_wait(&prod_cond,&mp);
}
b[prod_pos]=p;
prod_pos = (prod_pos+1)%10;
printf("Produtor - produzindo\\n");
sleep(2);
printf("Produtor - Produziu\\n");
cont++;
if(cont == 1){
pthread_cond_signal(&cons_cond);
}
pthread_mutex_unlock(&mp);
}
}
void * consumidor(void * arg){
int id = (int) arg;
while(1){
printf("Consumidor %d - Quer Consumir\\n", id);
pthread_mutex_lock(&mp);
while (cont == 0) {
printf("Consumidor %d - Esperando\\n",id);
pthread_cond_wait(&cons_cond,&mp);
}
int c = b[cons_pos];
cons_pos = (cons_pos+1)%10;
cont--;
if(cont == (10 -1)){
pthread_cond_signal(&prod_cond);
}
pthread_mutex_unlock(&mp);
printf("Consumidor %d - Consumindo\\n",id);
sleep(5);
printf("Consumidor %d - Consumiu\\n",id );
}
}
int main() {
pthread_t c[10];
int i;
int *id;
srand48(time(0));
for(i = 0; i < 10; i++){
id = (int*)malloc(sizeof(int));
*id = i;
pthread_create(&c[i],0,consumidor,(void*)(id));
}
pthread_join(c[0],0);
return 0;
}
| 0
|
#include <pthread.h>
int x = 0;
pthread_mutex_t x_mutex;
pthread_cond_t x_cond;
void *A (void *t) {
int i; int my_id = (int)t;
int boba1, boba2;
printf("A: Comecei: thread %d\\n", my_id);
for (i=0; i < 10; i++) {
printf("A: thread %d vai pedir mutex\\n", my_id);
pthread_mutex_lock(&x_mutex);
printf("A: thread %d, x = %d, conseguiu mutex\\n", my_id, x);
x++;
if ((x%10) == 0) {
printf("A: thread %d, x = %d, encontrou padrao \\n", my_id, x);
pthread_cond_signal(&x_cond);
printf("... e enviou sinal.\\n");
}
printf("A: thread %d, x = %d, liberou mutex\\n", my_id, x);
pthread_mutex_unlock(&x_mutex);
}
pthread_exit(0);
}
void *B (void *t) {
int my_id = (int)t;
printf("B: Comecei: thread %d\\n", my_id);
printf("B: thread %d vai pedir mutex\\n", my_id);
pthread_mutex_lock(&x_mutex);
printf("B: thread %d, x = %d, conseguiu mutex\\n", my_id, x);
while ((x % 10) != 0) {
printf("B: thread %d x= %d, vai se bloquear...\\n", my_id, x);
pthread_cond_wait(&x_cond, &x_mutex);
printf("B: thread %d, sinal recebido e mutex realocado. x = %d\\n", my_id, x);
}
printf("X=%d\\n", x);
printf("B: thread %d, vai liberar mutex e terminar\\n", my_id);
pthread_mutex_unlock(&x_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[]) {
int i;
int t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_mutex_init(&x_mutex, 0);
pthread_cond_init (&x_cond, 0);
pthread_create(&threads[0], 0, A, (void *)t1);
pthread_create(&threads[1], 0, A, (void *)t2);
pthread_create(&threads[2], 0, B, (void *)t3);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("FIM.\\n");
pthread_mutex_destroy(&x_mutex);
pthread_cond_destroy(&x_cond);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t more_pizza = PTHREAD_COND_INITIALIZER;
pthread_cond_t pizza_available = PTHREAD_COND_INITIALIZER;
int size = 0;
void* all_night_long_pizza(void *arg) {
int slices;
slices = *( (int *) arg );
printf("All night long pizza starting...\\n");
while (1) {
pthread_mutex_lock(&mutex);
if (size != 0) {
pthread_cond_wait(&more_pizza, &mutex);
}
printf("All night long pizza send pizza...\\n");
size += slices;
pthread_cond_signal(&pizza_available);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void* student(void *arg) {
int i,v;
printf("student starting...\\n");
while (1) {
pthread_mutex_lock(&mutex);
if (size == 0) {
pthread_cond_wait(&pizza_available, &mutex);
}
size--;
printf("student getting a slice...\\n");
pthread_cond_signal(&more_pizza);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main(int argc, char* argv[]) {
int i, rebanadas, estudiantes;
if (argc != 3) {
fprintf(stderr, "Forma de uso: %s num_estudiantes num_rebanadas\\n", argv[0]);
return -1;
}
rebanadas = atoi(argv[2]);
estudiantes = atoi(argv[1]);
if (rebanadas <= 0 || estudiantes <= 0) {
fprintf(stderr, "Error: el programa recibe un numero entero positivo mayor a 0\\n");
return -1;
}
pthread_t all_night_long_pizza_thread;
pthread_t student_thread[estudiantes];
pthread_create(&all_night_long_pizza_thread, 0, all_night_long_pizza, (void *) &rebanadas);
for (i = 0; i < estudiantes; i++) {
pthread_create(&student_thread[i], 0, student, 0);
}
for (i = 0; i < estudiantes; i++) {
pthread_join(student_thread[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void pthread_init(void)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int putenv_r(char *envbuf)
{
int i;
int len;
pthread_once(&init_done, pthread_init);
for (i = 0; envbuf[i] != '\\0'; i++) {
if (envbuf[i] == '=')
break;
}
if (envbuf[i] == '\\0') {
return 1;
}
pthread_mutex_lock(&env_mutex);
len = i;
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(envbuf, environ[i], len) == 0) &&
(environ[i][len] == '='))
{
if (strcmp(&envbuf[len+1], &environ[i][len+1]) == 0) {
return 0;
}
strcpy(environ[i], envbuf);
return 0;
}
}
if (environ[i] == 0)
environ[i] = envbuf;
pthread_mutex_unlock(&env_mutex);
return 0;
}
void *thd(void *arg)
{
putenv_r((char *)arg);
pthread_exit((void *)0);
}
int main(void)
{
pthread_t tid1, tid2, tid3, tid4, tid5;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&tid1, &attr, thd, (void *)"TEST1=a");
pthread_create(&tid2, &attr, thd, (void *)"TEST2=b");
sleep(2);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&env_mutex);
printf("TEST1 = %s\\n", getenv("TEST1"));
printf("TEST2 = %s\\n", getenv("TEST2"));
printf("TEST3 = %s\\n", getenv("TEST3"));
printf("TEST4 = %s\\n", getenv("TEST4"));
printf("TEST5 = %s\\n", getenv("TEST5"));
return 0;
}
| 1
|
#include <pthread.h>
static void thread_create(pthread_t *tid,void *(*fun)(void *));
static void thread_wait(pthread_t tid);
void * fun1(void *arg);
void * fun2(void *arg);
pthread_mutex_t lock;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int sum = 0;
int main(int argc, char const *argv[])
{
int ret = 0;
pthread_mutex_init(&lock,0);
pthread_t tid1;
pthread_t tid2;
thread_create(&tid1,fun1);
thread_create(&tid2,fun2);
thread_wait(tid1);
thread_wait(tid2);
ret = pthread_cond_destroy(&cond);
if (ret == 0)
printf("pthread_cond_destroy success\\n");
else
perror("pthread_cond_destroy");
return 0;
}
static void thread_create(pthread_t *tid,void *(*fun)(void *))
{
int res = 0;
res = pthread_create(tid,0,fun,0);
if (res == 0)
printf("successfully create");
sleep(1);
}
static void thread_wait(pthread_t tid)
{
int res = 0;
int status = 0;
res = pthread_join(tid,(void *)&status);
if (res == 0){
printf("wait thread %lu successfully\\n",tid);
printf("the return val:%d\\n",status );
}
else
perror("join thread");
}
void * fun1(void *arg)
{
printf(" thread 1\\n");
int i = 0;
for (; ; ) {
pthread_mutex_lock(&lock);
sum +=i;
pthread_mutex_unlock(&lock);
i++;
pthread_mutex_lock(&lock);
printf("thread 1 sum:%d\\n",sum );
if (sum >100) {
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit((void *)0);
}
void * fun2(void *arg)
{
int i =0;
printf(" thread 2\\n");
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond,&lock);
while(sum >0)
{
printf("thread 2 sum:%d\\n", sum);
sum -=i;
i++;
}
pthread_mutex_unlock(&lock);
sleep(3);
pthread_exit((void *)0);
}
| 0
|
#include <pthread.h>
pthread_cond_t condQEmpty, condQFull;
pthread_mutex_t taskQCondLock;
int taskAvailable, tasksCount, tasksFinished;
void* producer(void*);
void* consumer(void*);
int main(int argc, char **argv) {
int i;
int numThreads;
int* data = (int*) 0;
pthread_t pThreads[512];
pthread_attr_t attr;
taskAvailable = 0;
printf("Enter number of threads: ");
scanf("%d", &numThreads);
printf("Enter number of tasks: ");
scanf("%d", &tasksCount);
pthread_cond_init(&condQEmpty, 0);
pthread_cond_init(&condQFull, 0);
pthread_mutex_init(&taskQCondLock, 0);
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
data = (int*)malloc(numThreads * sizeof(int));
memset(data, 0, numThreads * sizeof(int));
for (i = 0; i < numThreads; i++) {
if (i%2 == 0) {
pthread_create(&pThreads[i], &attr, producer, data + i);
} else {
pthread_create(&pThreads[i], &attr, consumer, data + i);
}
}
for (i = 0; i < numThreads; i++) {
pthread_join(pThreads[i], 0);
}
printf("\\nTasks finished count: %d\\n", tasksFinished);
return 0;
}
int done() {
if (tasksFinished >= tasksCount) {
return 1;
} else {
return 0;
}
}
void* producer(void* producerThreadData) {
while (!done()) {
pthread_mutex_lock(&taskQCondLock);
while (taskAvailable == 1 && !done()) {
pthread_cond_wait(&condQEmpty, &taskQCondLock);
}
if (taskAvailable == 0 && !done()) {
printf(" \\n task inserted... \\n");
}
taskAvailable = 1;
pthread_cond_signal(&condQFull);
pthread_mutex_unlock(&taskQCondLock);
}
return (void*)0;
}
void* consumer(void* consumerThreadData) {
while(!done()) {
pthread_mutex_lock(&taskQCondLock);
while (taskAvailable == 0 && !done()) {
pthread_cond_wait(&condQFull, &taskQCondLock);
}
if (taskAvailable > 0 && !done()) {
printf(" \\n task consumed... \\n");
tasksFinished++;
}
taskAvailable = 0;
pthread_cond_signal(&condQEmpty);
pthread_mutex_unlock(&taskQCondLock);
}
return (void*)0;
}
| 1
|
#include <pthread.h>
void xerror(const char *msg);
static void *thread_main(void *arg);
static void thread_cleanup(void *arg);
{
int thread_num;
FILE *fp;
} thread_info;
static pthread_t threadId[10];
static pthread_mutex_t threadMutex[10];
static thread_info *threadInfo;
int main(void)
{
fprintf(stdout, "[MAIN] Starting...\\n");
struct stat st = {0};
if(stat("/tmp/Task1", &st) == -1)
{
fprintf(stdout, "[MAIN] Create \\"/tmp/Task1\\" Directory...\\n");
if(mkdir("/tmp/Task1", 0777) != 0)
xerror("Could not create directory \\"/tmp/Task1\\".");
}
srand(time(0));
fprintf(stdout, "[MAIN] Allocate ThreadInfo...\\n");
threadInfo = (thread_info*)malloc(sizeof(thread_info) * 10);
for(int i = 0; i < 10; i++)
{
threadInfo[i].thread_num = i;
if(pthread_create(&threadId[i], 0, thread_main, (threadInfo + i)))
pthread_mutex_init(&threadMutex[i], 0);
int ret = 0;
if(rand() % 2)
{
ret = pthread_cancel(threadId[i]);
}
if(ret != 0)
}
for(int i = (10 - 1); i >= 0; i--)
{
if(pthread_join(threadId[i], 0) != 0)
}
free(threadInfo);
exit(0);
}
static void *thread_main(void *arg)
{
fprintf(stdout, "[THREAD] Thread started...\\n");
thread_info *threadInfo = arg;
int tNum = threadInfo->thread_num;
fprintf(stdout, "[THREAD] Install Handler and set cancel type/state...\\n");
pthread_cleanup_push(thread_cleanup, threadInfo);
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, 0);
fprintf(stdout, "[THREAD] Sleep for some seconds...\\n");
sleep(rand() % 3);
fprintf(stdout, "[THREAD] Lock Mutex for Thread %d...\\n", tNum);
pthread_mutex_lock(&threadMutex[tNum]);
char fileNameBuf[30];
sprintf(fileNameBuf, "/tmp/Task1/thread%d.txt", tNum);
fprintf(stdout, "[THREAD] Write ID into File \\"%s\\"...\\n", fileNameBuf);
threadInfo->fp = fopen(fileNameBuf, "w+");
if(threadInfo->fp == 0)
{
char buf[2048];
xerror(buf);
}
fprintf(stdout, "[THREAD] Write ID into File...\\n");
fprintf(threadInfo->fp, "%d", (rand() % 1048576));
fprintf(stdout, "[THREAD] Unlock Mutex and free ressources for Thread %d...\\n", tNum);
pthread_cleanup_pop(1);
exit(0);
}
void thread_cleanup(void *arg)
{
thread_info *threadInfo = arg;
int tNum = threadInfo->thread_num;
fclose(threadInfo->fp);
pthread_mutex_unlock(&threadMutex[tNum]);
pthread_mutex_destroy(&threadMutex[tNum]);
}
void xerror(const char *msg)
{
char output[2048];
strcpy(output, msg);
strcat(output, "\\n");
perror(output);fflush(stderr);
exit(1);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
void default_http_response(const int client_sockfd, const char * msg)
{
static char outbuf[out_to_browser_buf_size] = { 0 };
static char method[accept_method_buf_size] = { 0 };
static char url[accept_url_buf_size] = { 0 };
static char protocol[accept_protocol_buf_size] = { 0 };
size_t i = 0;
size_t j = 0;
pthread_mutex_lock(&mutex1);
memset(outbuf, 0, out_to_browser_buf_size);
memset(method, 0, accept_method_buf_size);
memset(url, 0, accept_url_buf_size);
memset(protocol, 0, accept_protocol_buf_size);
while (!isspace((int)(msg[i])) && (i < accept_method_buf_size))
{
method[i] = msg[i];
i++;
}
if (strcasecmp(method, "GET") && strcasecmp(method, "POST"))
{
memset(method, 0, accept_method_buf_size);
strcpy(method, "Unknown");
}
else
{
j = i;
while (isspace((int)(msg[j])) && j < accept_line_buf_size)
{
j++;
}
i = 0;
while (!isspace((int)(msg[j])) && (j < accept_line_buf_size) && (i < accept_url_buf_size))
{
url[i] = msg[j];
i++;
j++;
}
while (isspace((int)(msg[j])) && j < accept_line_buf_size)
{
j++;
}
i = 0;
while (!isspace((int)(msg[j])) && (j < accept_line_buf_size) && (i < accept_protocol_buf_size))
{
protocol[i] = msg[j];
i++;
j++;
}
}
strcat(outbuf, "HTTP/1.0 200 OK\\r\\n");
strcat(outbuf, SERVER_STRING);
strcat(outbuf, "Content-Type: text/html\\r\\n");
strcat(outbuf, "\\r\\n");
strcat(outbuf, "<HTML><HEAD><TITLE>HTTP Response</TITLE></HEAD>\\r\\n");
strcat(outbuf, "<BODY><h1>Your request:</h1><hr /><p> Method: ");
strcat(outbuf, method);
strcat(outbuf, " <br /> URL: ");
strcat(outbuf, url);
strcat(outbuf, " <br /> protocol: ");
strcat(outbuf, protocol);
strcat(outbuf, " </p><pre>");
strcat(outbuf, msg);
strcat(outbuf, "</pre><hr />\\r\\n");
strcat(outbuf, "</BODY></HTML>\\r\\n");
send(client_sockfd, outbuf, strlen(outbuf), 0);
pthread_mutex_unlock(&mutex1);
}
| 1
|
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
int flag = 1;
void *thread1 (void *arg);
void *thread2 (void *arg);
void *thread3 (void *arg);
void *thread1 (void *arg)
{
int ret;
pthread_t th;
(void) arg;
ret = pthread_create (&th, 0, thread3, 0);
pthread_mutex_lock(&m);
if (flag)
{
ret = pthread_join (th, 0);
assert (ret == 0);
}
pthread_mutex_unlock(&m);
ret = pthread_create (&th, 0, thread3, 0);
assert (ret == 0);
return 0;
}
void *thread2 (void *arg)
{
(void) arg;
pthread_mutex_lock(&m);
flag = 0;
pthread_mutex_unlock(&m);
return 0;
}
void *thread3 (void *arg)
{
(void) arg;
return 0;
}
int main (int argc, char ** argv)
{
int ret;
pthread_t th;
(void) argc;
(void) argv;
ret = pthread_mutex_init (&m, 0);
assert (ret == 0);
ret = pthread_create (&th, 0, thread1, 0);
assert (ret == 0);
ret = pthread_create (&th, 0, thread2, 0);
assert (ret == 0);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
{
struct D_CRITICAL_SECTION *next;
pthread_mutex_t cs;
} D_CRITICAL_SECTION;
static D_CRITICAL_SECTION *dcs_list;
static D_CRITICAL_SECTION critical_section;
static pthread_mutexattr_t _criticals_attr;
void _STI_critical_init(void);
void _STD_critical_term(void);
void _d_criticalenter(D_CRITICAL_SECTION *dcs)
{
if (!dcs_list)
{ _STI_critical_init();
atexit(_STD_critical_term);
}
if (!dcs->next)
{
pthread_mutex_lock(&critical_section.cs);
if (!dcs->next)
{
dcs->next = dcs_list;
dcs_list = dcs;
pthread_mutex_init(&dcs->cs, &_criticals_attr);
}
pthread_mutex_unlock(&critical_section.cs);
}
pthread_mutex_lock(&dcs->cs);
}
void _d_criticalexit(D_CRITICAL_SECTION *dcs)
{
pthread_mutex_unlock(&dcs->cs);
}
void _STI_critical_init()
{
if (!dcs_list)
{
pthread_mutexattr_init(&_criticals_attr);
pthread_mutexattr_settype(&_criticals_attr, PTHREAD_MUTEX_RECURSIVE_NP);
pthread_mutex_init(&critical_section.cs, 0);
dcs_list = &critical_section;
}
}
void _STD_critical_term()
{
if (dcs_list)
{
while (dcs_list)
{
pthread_mutex_destroy(&dcs_list->cs);
dcs_list = dcs_list->next;
}
}
}
| 1
|
#include <pthread.h>
int table[128];
pthread_mutex_t cas_mutex[128];
pthread_t tids[13];
int cas(int * tab, int h, int val, int new_val)
{
int ret_val = 0;
pthread_mutex_lock(&cas_mutex[h]);
if ( tab[h] == val ) {
tab[h] = new_val;
ret_val = 1;
}
pthread_mutex_unlock(&cas_mutex[h]);
return ret_val;
}
void * thread_routine(void * arg)
{
int tid;
int m = 0, w, h;
tid = *((int *)arg);
while(1){
if ( m < 4 ){
w = (++m) * 11 + tid;
}
else{
pthread_exit(0);
}
h = (w * 7) % 128;
while ( cas(table, h, 0, w) == 0){
h = (h+1) % 128;
}
}
}
int main()
{
int i, arg;
for (i = 0; i < 128; i++)
pthread_mutex_init(&cas_mutex[i], 0);
for (i = 0; i < 13; i++){
arg=i;
pthread_create(&tids[i], 0, thread_routine, &arg);
}
for (i = 0; i < 13; i++){
pthread_join(tids[i], 0);
}
for (i = 0; i < 128; i++){
pthread_mutex_destroy(&cas_mutex[i]);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t cupcake_mutex;
pthread_mutex_t donut_mutex;
int cupcakes = 1;
int donuts = 1;
void removeCupcake(){
pthread_mutex_lock(&cupcake_mutex);
printf("A customer purchases a cupcake.\\n");
printf("The number of cupcakes was %d\\n", cupcakes);
cupcakes = cupcakes - 1;
printf("The number of cupcakes is now %d\\n\\n", cupcakes);
pthread_mutex_unlock(&cupcake_mutex);
}
void addCupcake(){
pthread_mutex_lock(&cupcake_mutex);
printf("A cupcake was baked.\\n");
printf("The number of cupcakes was %d\\n", cupcakes);
cupcakes = cupcakes + 1;
printf("The number of cupcakes is now %d\\n\\n", cupcakes);
pthread_mutex_unlock(&cupcake_mutex);
}
void removeDonut(){
pthread_mutex_lock(&donut_mutex);
printf("A customer purchases a donut.\\n");
printf("The number of donuts was %d\\n", donuts);
donuts = donuts - 1;
printf("The number of donuts is now %d\\n\\n", donuts);
pthread_mutex_unlock(&donut_mutex);
}
void addDonut(){
pthread_mutex_lock(&donut_mutex);
printf("A donut was baked.\\n");
printf("The number of donuts was %d\\n", donuts);
donuts = donuts + 1;
printf("The number of donuts is now %d\\n\\n", donuts);
pthread_mutex_unlock(&donut_mutex);
}
void *purchase(void *arg) {
int numCustomers, i, custChoice;
while ((cupcakes > 0) || (donuts > 0)) {
numCustomers = rand() % 6;
for (i = 0; i < numCustomers; i++){
custChoice = rand() % 3 + 1;
if ((custChoice == 1) && (cupcakes > 0)) {
removeCupcake();
}
else if ((custChoice == 2) && (donuts > 0)) {
removeDonut();
}
else if ((cupcakes > 0) && (donuts > 0)){
removeCupcake();
removeDonut();
}
else {
printf("We don't have what the customer wants.\\n");
printf("The customer left the store.\\n\\n");
}
sleep(1);
}
sleep(1);
}
printf("=======Customer thread complete, cupcakes = %d and donuts = %d=======\\n", cupcakes, donuts);
}
void *makeCupcake(void *arg) {
while (cupcakes < 10) {
addCupcake();
if (cupcakes == 10) sleep(10);
else sleep(2);
}
printf("=======Cupcake Baker thread complete, cupcakes = %d=======\\n", cupcakes);
}
void *makeDonut(void *arg) {
while (donuts < 15) {
addDonut();
if (donuts == 15) sleep(15);
else sleep(1);
}
printf("=======Donut Baker thread complete, donuts = %d=======\\n", donuts);
}
int main(){
pthread_t cupcakeBaker, donutBaker, customer;
pthread_create(&cupcakeBaker, 0, makeCupcake,0);
pthread_create(&donutBaker, 0, makeDonut, 0);
pthread_create(&customer, 0, purchase,0);
pthread_join(cupcakeBaker, 0);
pthread_join(donutBaker, 0);
pthread_join(customer, 0);
printf("=======Main thread complete, cupcakes = %d and donuts = %d=======\\n", cupcakes, donuts);
return 0;
}
| 1
|
#include <pthread.h>
struct workqueue
{
int item[64];
int idx;
int cnt;
pthread_mutex_t mutex;
pthread_cond_t cv;
} *wq;
void *tfunc_a(void *);
void *tfunc_b(void *);
void *start_sigthread(void *);
struct thread_arg
{
pthread_t tid;
int idx;
void *(*func)(void *);
} t_arg[10] = {
{ 0, 0, tfunc_a },
{ 0, 0, tfunc_b },
{ 0, 0, tfunc_b },
{ 0, 0, tfunc_b },
{ 0, 0, start_sigthread },
{ 0, 0, 0 }
};
int push_item(struct workqueue *wq, const char *item, int cnt);
int pop_item(struct workqueue *wq, int *item);
int process_job(int *);
void clean_thread(struct thread_arg *);
int main()
{
int i;
if ((wq = calloc(1, sizeof(struct workqueue))) == 0) {
exit(1);
}
sigset_t sigset_mask;
sigfillset(&sigset_mask);
sigdelset(&sigset_mask, SIGINT);
pthread_sigmask(SIG_SETMASK, &sigset_mask, 0);
pthread_mutex_init(&wq->mutex, 0);
pthread_cond_init(&wq->cv, 0);
for (i = 0; i < 10 && t_arg[i].func != 0; i++) {
t_arg[i].idx = i;
if (pthread_create(&t_arg[i].tid, 0,
t_arg[i].func, (void *)&t_arg[i])) {
return 1;
}
pr_out("pthread_create : tid = %lu", t_arg[i].tid);
}
clean_thread(t_arg);
return 0;
}
void *tfunc_a(void *arg)
{
int fd, ret_read = 0;
char buf[64 / 2];
pr_out(" >> Thread (A) Started!");
if (mkfifo("/tmp/my_fifo", 0644) == -1) {
if (errno != EEXIST) {
pr_err("[A] FAIL: mkfifo : %s", strerror(errno));
exit(1);
}
}
if ((fd = open("/tmp/my_fifo", O_RDONLY, 0644)) == -1) {
pr_err("[A] FAIL: open : %s", strerror(errno));
exit(1);
}
while (1) {
if ((ret_read = read(fd, buf, sizeof(buf))) == -1) {
pr_err("[A] FAIL: read : %s", strerror(errno));
exit(1);
}
if (ret_read == 0) {
pr_err("[A] broken pipe : %s", strerror(errno));
exit(1);
}
push_item(wq, buf, ret_read);
pr_out("[A] cond_signal");
pthread_cond_broadcast(&wq->cv);
}
return 0;
}
void *tfunc_b(void *arg)
{
int item;
union sigval si_val;
pr_out(" >> Thread (B) Started!");
while (1) {
pop_item(wq, &item);
process_job(&item);
si_val.sival_ptr = arg;
if (sigqueue(getpid(), SIGRTMIN, si_val)) {
exit(1);
}
}
return 0;
}
void *start_sigthread(void *arg)
{
struct thread_arg *thr;
sigset_t sigset_mask;
siginfo_t info;
int ret_signo;
printf("* Start signal thread (tid = %lu) \\n", (long)pthread_self());
sigemptyset(&sigset_mask);
sigaddset(&sigset_mask, SIGRTMIN);
while (1) {
if ((ret_signo = sigwaitinfo(&sigset_mask, &info)) == -1) {
pr_err("FAIL: sigwaitinfo(%s)\\n", strerror(errno));
}
if (ret_signo == SIGRTMIN) {
thr = (struct thread_arg *)info.si_value.sival_ptr;
printf("\\t[RTS] notification from (%lu).\\n", thr->tid);
} else {
printf("\\t[RTS] others.\\n");
}
}
return t_arg;
}
int push_item(struct workqueue *wq, const char *item, int cnt)
{
int i, j;
pthread_mutex_lock(&wq->mutex);
for (i = 0, j = (wq->idx + wq->cnt) % 64; i < cnt; i++, j++, wq->cnt++) {
if (wq->cnt == 64) {
pr_err("[Q:%d,%d] queue full : wq(idx,cnt=%d,%d)",
i, j, wq->idx, wq->cnt);
break;
}
if (j == 64)
j = 0;
wq->item[j] = (int)item[i];
pr_out("[Q:%d,%d] push(idx,cnt=%d,%d) : item=(%c)", i, j, wq->idx, wq->cnt, item[i]);
}
pthread_mutex_unlock(&wq->mutex);
return i;
}
int pop_item(struct workqueue *wq, int *item)
{
pthread_mutex_lock(&wq->mutex);
while (1) {
if (wq->cnt > 0) {
if (wq->idx == 64)
wq->idx = 0;
*item = wq->item[wq->idx];
wq->idx++;
wq->cnt--;
pr_out("[B] pop(%d,%d) item(%c) (tid=%ld)",
wq->idx, wq->cnt, (char)*item, pthread_self());
break;
} else {
pr_out("[B] cond_wait (tid=%ld)", pthread_self());
pthread_cond_wait(&wq->cv, &wq->mutex);
pr_out("[B] Wake up (tid=%ld)", pthread_self());
}
}
pthread_mutex_unlock(&wq->mutex);
return 0;
}
int process_job(int *item)
{
pr_out("[B] item=%d", *item);
sleep(*item % 5 + 1);
return 0;
}
void clean_thread(struct thread_arg *t_arg)
{
int i;
struct thread_arg *t_arg_ret;
for (i = 0; i < 10; i++, t_arg++) {
pthread_join(t_arg->tid, (void **)&t_arg_ret);
pr_out("pthread_join : %d - %lu", t_arg->idx, t_arg->tid);
}
}
| 0
|
#include <pthread.h>
struct job{
double data;
struct job* next;
};
struct job* job_queue;
unsigned int job_queue_count;
pthread_mutex_t job_queue_count_mutex;
pthread_mutex_t job_queue_mutex;
pthread_cond_t pcond_var;
void initialize_vars()
{
job_queue_count = 0 ;
pthread_mutex_init(&job_queue_mutex,0);
pthread_mutex_init(&job_queue_count_mutex,0);
pthread_cond_init(&pcond_var,0);
}
void*
thread_callback_enqueue(void *arg)
{
unsigned int thread_id = *((unsigned int*)arg);
struct job* new_job = 0;
new_job = (struct job*)calloc(1,sizeof(struct job));
if(0 == new_job){
perror("Memory Allocation failed.");
}
else{
new_job->data = 100.0+thread_id;
}
pthread_mutex_lock(&job_queue_mutex);
pthread_mutex_lock(&job_queue_count_mutex);
if(0 == job_queue){
job_queue = new_job;
}
else{
new_job->next = job_queue;
job_queue = new_job;
}
job_queue_count++;
pthread_cond_signal(&pcond_var);
pthread_mutex_unlock(&job_queue_count_mutex);
pthread_mutex_unlock(&job_queue_mutex);
printf("INSIDE thread [%d], enqued job with data = [%f]\\n",
thread_id,new_job->data);
}
void*
thread_callback_dequeue(void* arg)
{
int thread_id = *((int*)arg);
struct job* next_job = 0;
pthread_mutex_lock(&job_queue_count_mutex);
while(!job_queue_count){
pthread_cond_wait(&pcond_var,&job_queue_count_mutex);
}
pthread_mutex_unlock(&job_queue_count_mutex);
pthread_mutex_lock(&job_queue_mutex);
pthread_mutex_lock(&job_queue_count_mutex);
if(job_queue_count > 0){
next_job = job_queue;
job_queue = job_queue->next;
job_queue_count--;
}
pthread_mutex_unlock(&job_queue_count_mutex);
pthread_mutex_unlock(&job_queue_mutex);
printf("INSIDE thread [%d], processed job with data = [%f]\\n",
thread_id,next_job->data);
free(next_job);
}
void usage(){
printf("Invalid Argument... [TDB]\\n");
}
main(int argc, char* argv[])
{
char ch = '\\0';
int count = 0;
int ind = 0;
int ret = 0;
int status = 0;
pthread_t thread_list[400];
int thread_list_int[400];
unsigned int max_thr_count = 0;
unsigned int init_thr_count = 0;
while(-1 != (ch = getopt(argc,argv,"t:h"))){
switch(ch){
case 'h':
usage(); exit(0);
break;
case 't':
max_thr_count = atoi(optarg);
if (max_thr_count > 400){
printf("Max supported thread = %d\\n",400);
printf("Please specify thread count < %d\\n",400);
exit(0);
}
break;
default:
usage();exit(1);
break;
}
}
initialize_vars();
job_queue = 0;
job_queue_count = 0;
init_thr_count = (rand()%(max_thr_count - 1)) + 1;
for(count=0;count< init_thr_count;count++){
thread_list_int[count] = count;
ret = pthread_create(&thread_list[count],0,
thread_callback_dequeue,&thread_list_int[count]);
if(ret!=0){
fprintf(stderr,"[%d] thread creation failed...\\n",count);
perror("Exiting...");
}
}
for(;count<max_thr_count;count++){
thread_list_int[count] = count;
ret = pthread_create(&thread_list[count],0,
thread_callback_enqueue,&thread_list_int[count]);
if(ret!=0){
fprintf(stderr,"[%d] thread creation failed...\\n",count);
perror("Exiting...");
}
}
printf("Waiting for all children threads to be terminated...\\n");
for(ind=0;ind<max_thr_count;ind++){
if(0 != pthread_join(thread_list[ind],(void*)&status))
perror("Thread Join failed.");
printf("Completed thread [%d] with ret = [%d]\\n",ind,status);
}
return 0;
}
| 1
|
#include <pthread.h>
int aleatorio (int range, int teste)
{
int x;
if (teste)
{
while (range < 2)
{
printf("função random: o range %d passado é inválido, por favor digite um valor < 2 para range:\\n", range);
scanf("%d", &range);
}
}
else if (range < 2)
{
range = 10;
}
while (x >= (32767 - (32767 % range)))
{
srand(time(0));
x = rand();
}
x %= range;
return x;
}
void *alocaVetor (size_t tam, size_t size)
{
void *vetor;
if (!(vetor = calloc(tam, size)))
{
printf("função alocaVetor: erro ao alocar memória do vetor com calloc\\n");
exit(-1);
}
return vetor;
}
void **alocaMatriz (size_t n, size_t m, size_t size)
{
int i;
void **matriz;
if (!(matriz = calloc(n, sizeof(void*))))
{
printf("função alocaMatriz: erro ao alocar espaço das linhas na memória\\n");
exit(-1);
}
for (i = 0; i < n; ++i)
{
if (!(matriz[i] = calloc(m, size)))
{
printf("função alocaMatriz: erro ao alocar espaço da coluna %d na memória\\n", i);
exit(-1);
}
}
return matriz;
}
void barreira (int qtdThreads)
{
static int threadsCount = 0;
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condition;
pthread_mutex_lock(&lock);
threadsCount++;
if (threadsCount < qtdThreads)
{
pthread_cond_wait(&condition, &lock);
}
else
{
threadsCount = 0;
pthread_cond_broadcast(&condition);
}
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&condition);
}
int calcNucleosProcess (void)
{
return sysconf(_SC_NPROCESSORS_ONLN);
}
int calcTamNumeros (int *numeros, int qtdNumeros)
{
int i, num, tam = 0;
for (i = 0; i < qtdNumeros; ++i)
{
num = numeros[i];
while (num)
{
tam++;
num /= 10;
}
}
return tam;
}
double calculaPi (int qtdParcelasPrecisao)
{
int i;
double pi = 0;
if (qtdParcelasPrecisao < 0)
{
qtdParcelasPrecisao = 10;
}
for (i = 0; i < qtdParcelasPrecisao; ++i)
{
pi += pow(-1, i)/(2*i+1);
}
pi *= 4;
return pi;
}
void comoUsar(char* progName, char* argumentos)
{
fprintf(stderr, "como usar: ./%s %s\\n", progName, argumentos);
exit(0);
}
int defineQtdThreads (int n)
{
if (n > 0)
{
return n;
}
else
{
return calcNucleosProcess();
}
}
double getMaiorDouble (double n1, double n2)
{
if (n1 > n2)
{
return n1;
}
else
{
return n2;
}
}
float getMaiorFloat (float n1, float n2)
{
if (n1 > n2)
{
return n1;
}
else
{
return n2;
}
}
int getMaiorInteiro (int n1, int n2)
{
if (n1 > n2)
{
return n1;
}
else
{
return n2;
}
}
void imprimeVetorDouble (double *vetor, int tam)
{
int i;
for (i = 0; i < tam; ++i)
{
printf("%e\\t", vetor[i]);
}
printf("\\n");
}
void imprimeVetorFloat (float *vetor, int tam)
{
int i;
for (i = 0; i < tam; ++i)
{
printf("%f\\t", vetor[i]);
}
printf("\\n");
}
void imprimeVetorInteiro (int *vetor, int tam)
{
int i;
for (i = 0; i < tam; ++i)
{
printf("%d\\t", vetor[i]);
}
printf("\\n");
}
void iniVetorDouble (double *vetor, int tam, double valorInicial)
{
int i;
for (i = 0; i < tam; ++i)
{
vetor[i] = valorInicial;
}
}
void iniVetorFloat (float *vetor, int tam, float valorInicial)
{
int i;
for (i = 0; i < tam; ++i)
{
vetor[i] = valorInicial;
}
}
void iniVetorInteiro (int *vetor, int tam, int valorInicial)
{
int i;
for (i = 0; i < tam; ++i)
{
vetor[i] = valorInicial;
}
}
void liberaMemo (void *ptr)
{
if (ptr)
{
free(ptr);
ptr = 0;
}
}
void printaMatrizDouble (double **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; ++j)
{
printf("%e\\t", matriz[i][j]);
}
printf("\\n");
}
}
void printaMatrizFloat (float **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; ++j)
{
printf("%f\\t", matriz[i][j]);
}
printf("\\n");
}
}
void printaMatrizInteiro (int **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < m; ++j)
{
printf("%d\\t", matriz[i][j]);
}
printf("\\n");
}
}
void setMatrizDouble (double **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
scanf("%lf", &matriz[i][j]);
}
}
}
void setMatrizFloat (float **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
scanf("%f", &matriz[i][j]);
}
}
}
void setMatrizInteiro (int **matriz, int n, int m)
{
int i, j;
for (i = 0; i < n; ++i)
{
for (j = 0; j < m; ++j)
{
scanf("%d", &matriz[i][j]);
}
}
}
void threadCreate (pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void*), void *arg)
{
int id;
if ((id = pthread_create(thread, attr, *start_routine, arg)))
{
printf("--ERRO: pthread_create()\\n");
printf("error number %d\\n", id);
exit(-1);
}
}
void threadJoin (int qtdThreads, pthread_t *threads)
{
int i, erro;
for (i = 0; i < qtdThreads; ++i)
{
if ((erro = pthread_join(threads[i], 0)))
{
printf("--ERRO: pthread_join()\\n");
printf("error number %d\\n", erro);
exit(-1);
}
}
}
| 0
|
#include <pthread.h>
pthread_attr_t thrd_attr;
pthread_mutex_t mtx_one;
pthread_mutex_t mtx_two;
pthread_cond_t cnd_one;
pthread_cond_t cnd_two;
int one_run, two_run;
int tmp_cnt;
int main_started;
void message_handler(const char *str);
void init();
void uninit();
void * agent_one(void *arg);
void * agent_two(void *arg);
void agent_send(int receiver, int cmd);
void sigint_handler(int sig);
int main(int argc, const char *argv[])
{
int recver, cmd;
struct sigaction sa;
pthread_t thrd_one, thrd_two;
sa.sa_handler = sigint_handler;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
if (sigaction(SIGINT, &sa, 0) < 0)
{
perror("sigaction!");
return -1;
}
init();
pthread_create(&thrd_one, &thrd_attr, agent_one, 0);
pthread_create(&thrd_two, &thrd_attr, agent_two, 0);
main_started = 1;
while (main_started)
{
printf("Enter Receiver(1, 2) and Cmd(1[run], 3[exit]), ([0, 0] to exit):");
scanf("%d %d", &recver, &cmd);
if (recver + cmd > 0)
{
agent_send(recver, cmd);
}
else
{
main_started = 0;
agent_send(1, 3);
agent_send(2, 3);
}
}
uninit();
return 0;
}
void sigint_handler(int sig)
{
agent_send(1, 3);
agent_send(2, 3);
main_started = 0;
}
void uninit()
{
pthread_attr_destroy(&thrd_attr);
pthread_mutex_destroy(&mtx_one);
pthread_mutex_destroy(&mtx_two);
pthread_cond_destroy(&cnd_one);
pthread_cond_destroy(&cnd_two);
}
void init()
{
pthread_mutex_init(&mtx_one, 0);
pthread_mutex_init(&mtx_two, 0);
pthread_cond_init(&cnd_one, 0);
pthread_cond_init(&cnd_two, 0);
pthread_attr_init(&thrd_attr);
pthread_attr_setdetachstate(&thrd_attr, PTHREAD_CREATE_JOINABLE);
}
void agent_send(int receiver, int cmd)
{
switch (receiver)
{
case 1:
pthread_mutex_lock(&mtx_one);
one_run = cmd;
pthread_cond_signal(&cnd_one);
pthread_mutex_unlock(&mtx_one);
break;
case 2:
pthread_mutex_lock(&mtx_two);
two_run = cmd;
pthread_cond_signal(&cnd_two);
pthread_mutex_unlock(&mtx_two);
break;
}
}
void * agent_two(void *arg)
{
int started = 1;
while (started)
{
pthread_mutex_lock(&mtx_two);
if (!two_run)
{
pthread_cond_wait(&cnd_two, &mtx_two);
if(two_run == 1)
{
message_handler("agent_two's turn!");
two_run = 0;
}
else if (two_run == 3)
{
started = 0;
}
else
{
two_run = 0;
}
}
pthread_mutex_unlock(&mtx_two);
}
write(0, "agent_two exit!\\n", 16);
pthread_exit(0);
}
void * agent_one(void *arg)
{
int started = 1;
while (started)
{
pthread_mutex_lock(&mtx_one);
if (!one_run)
{
pthread_cond_wait(&cnd_one, &mtx_one);
if (one_run == 1)
{
message_handler("agent_one's turn!");
one_run = 0;
}
else if (one_run == 3)
{
started = 0;
}
else
{
one_run = 0;
}
}
pthread_mutex_unlock(&mtx_one);
}
write(0, "agent_one exit!\\n", 16);
pthread_exit(0);
}
void message_handler(const char *str)
{
puts(str);
}
| 1
|
#include <pthread.h>
static pthread_cond_t *cv = 0;
static pthread_mutex_t *mutex = 0;
static volatile long solution = 0;
static volatile int resources_available = 0;
static volatile int cv_hits = 0;
static void print_solution() {
printf("Solution is: %ld\\n", solution);
}
static void initialize_cond_objects()
{
cv = (pthread_cond_t *)malloc(sizeof(pthread_cond_t));
if (cv == 0) {
perror("malloc");
exit(1);
}
mutex = (pthread_mutex_t *)malloc(sizeof(pthread_mutex_t));
if (mutex == 0) {
perror("malloc");
exit(1);
}
pthread_cond_init(cv, 0);
pthread_mutex_init(mutex, 0);
}
static void destroy_cond_objects()
{
pthread_mutex_destroy(mutex);
pthread_cond_destroy(cv);
free(mutex);
free(cv);
}
static void *worker(void *arg)
{
long id = (long)arg;
printf("Starting watcher %ld.\\n", id);
while (1) {
pthread_mutex_lock(mutex);
while (resources_available == 0) {
pthread_cond_wait(cv, mutex);
}
if (cv_hits > (15 * 1000)) {
printf("!!! Watcher %ld exiting.\\n", id);
pthread_mutex_unlock(mutex);
pthread_exit(0);
}
cv_hits++;
solution += id;
resources_available--;
pthread_mutex_unlock(mutex);
}
}
static void *resource_generator(void *arg)
{
printf("Starting resource generator thread.\\n");
while (1) {
pthread_mutex_lock(mutex);
if (cv_hits > (15 * 1000)) {
printf("!!! Resource generator thread exiting.\\n");
pthread_mutex_unlock(mutex);
pthread_exit(0);
}
resources_available += 2;
pthread_cond_broadcast(cv);
pthread_mutex_unlock(mutex);
}
}
int main()
{
pthread_t threads[15 +1];
long i = 0;
int rc = 0;
initialize_cond_objects();
for (i = 0; i < 15; i++) {
rc = pthread_create(&threads[i], 0, worker, (void *)i);
if (rc) {
perror("pthread_create");
return 1;
}
}
rc = pthread_create(&threads[15], 0,
resource_generator, 0);
if (rc) {
perror("pthread_create");
return 1;
}
for (i = 0; i < 15 + 1; i++) {
rc = pthread_join(threads[i], 0);
if (rc) {
perror("pthread_join");
return 1;
}
}
destroy_cond_objects();
print_solution();
return 0;
}
| 0
|
#include <pthread.h>
int ring[128];
sem_t sem_space;
sem_t sem_data;
pthread_mutex_t pro_lock;
pthread_mutex_t con_lock;
void* product(void* arg)
{
int index = 0;
while (1)
{
sem_wait(&sem_space);
int val = rand() % 100;
pthread_mutex_lock(&pro_lock);
ring[index++] = val;
pthread_mutex_unlock(&pro_lock);
index %= 128;
printf("product done ... , %d, %lu\\n", val, pthread_self());
sem_post(&sem_data);
sleep(1);
}
}
void* consume(void* arg)
{
int index = 0;
while (1)
{
sem_wait(&sem_data);
pthread_mutex_lock(&con_lock);
int val = ring[index++];
pthread_mutex_unlock(&con_lock);
index %= 128;
printf("consume done...%d, %lu\\n", val, pthread_self());
sem_post(&sem_space);
sleep(1);
}
}
int main()
{
pthread_t pro, pro2;
pthread_t con, con2;
sem_init(&sem_space, 0, 128);
sem_init(&sem_data, 0, 0);
pthread_mutex_init(&pro_lock, 0);
pthread_mutex_init(&con_lock, 0);
pthread_create(&pro, 0, product, 0);
pthread_create(&con, 0, consume, 0);
pthread_create(&pro2, 0, product, 0);
pthread_create(&con2, 0, consume, 0);
pthread_join(pro, 0);
pthread_join(con, 0);
pthread_join(pro2, 0);
pthread_join(con2, 0);
return 0;
}
| 1
|
#include <pthread.h>
int q[4];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 4)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 4);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[7];
int sorted[7];
void producer ()
{
int i, idx;
for (i = 0; i < 7; i++)
{
idx = findmaxidx (source, 7);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 7);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 7; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 7);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 7; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 0
|
#include <pthread.h>
int global_value = 0;
pthread_mutex_t global_value_mutex;
void *t1_main(void *arg);
void *t2_main(void *arg);
int main(int argc, char **argv)
{
pthread_t t1, t2;
int code;
pthread_mutex_init(&global_value_mutex, 0);
code = pthread_create(&t1, 0, t1_main, 0);
if (code != 0)
{
fprintf(stderr, "Create new thread t1 failed: %s\\n", strerror(code));
exit(1);
}
else
{
fprintf(stdout, "New thread t1 created.\\n");
}
code = pthread_create(&t2, 0, t2_main, 0);
if (code != 0)
{
fprintf(stderr, "Create new thread t2 failed: %s\\n", strerror(code));
exit(1);
}
else
{
fprintf(stdout, "New thread t2 created.\\n");
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&global_value_mutex);
pthread_exit((void *) 0);
}
void *t1_main(void *arg)
{
int i;
for (i = 0; i < 100000; i++)
{
pthread_mutex_lock(&global_value_mutex);
global_value++;
pthread_mutex_unlock(&global_value_mutex);
sleep(1);
}
pthread_exit((void *) 0);
}
void *t2_main(void *arg)
{
int i;
for (i = 0; i < 100000; i++)
{
pthread_mutex_lock(&global_value_mutex);
global_value += 2;
pthread_mutex_unlock(&global_value_mutex);
sleep(1);
}
pthread_exit((void *) 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t * ssl_locks;
int ssl_num_locks;
static unsigned long
get_thread_id_cb(void)
{
return (unsigned long)pthread_self();
}
static void
thread_lock_cb(int mode, int which, const char * f, int l)
{
if (which < ssl_num_locks) {
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&(ssl_locks[which]));
} else {
pthread_mutex_unlock(&(ssl_locks[which]));
}
}
}
int
init_ssl_locking(void)
{
int i;
ssl_num_locks = CRYPTO_num_locks();
ssl_locks = malloc(ssl_num_locks * sizeof(pthread_mutex_t));
if (ssl_locks == 0)
return -1;
for (i = 0; i < ssl_num_locks; i++) {
pthread_mutex_init(&(ssl_locks[i]), 0);
}
CRYPTO_set_id_callback(get_thread_id_cb);
CRYPTO_set_locking_callback(thread_lock_cb);
return 0;
}
| 0
|
#include <pthread.h>
{
WDOG_IDLE,
WDOG_BUSY,
WDOG_DESTROY,
} dog_stat_t;
{
pthread_t thread_loop;
pthread_mutex_t cmd_mutex;
dog_stat_t stat;
int snap_cnt;
long long last_tickle_time;
char last_tickle_info[128];
} dog_t;
static void *watch_dog_loop(void *param)
{
dog_t *dog_param = (dog_t *)param;
long long current_time;
long long delta_time;
while(1)
{
pthread_mutex_lock(&dog_param->cmd_mutex);
if(WDOG_BUSY == dog_param->stat)
{
dog_param->snap_cnt++;
if(dog_param->snap_cnt > WDOG_WARN_SNAP_NUM)
{
current_time = get_current_time();
delta_time = current_time - dog_param->last_tickle_time;
OMXDBUG(OMXDBUG_PARAM, "dog warning, %s, %lld(us)\\n", dog_param->last_tickle_info, delta_time);
if(delta_time > WDOG_TIME_OUT * 1000)
{
OMXDBUG(OMXDBUG_ERR, "dog timeout, %s!\\n", dog_param->last_tickle_info);
dog_param->last_tickle_time = current_time;
dog_param->snap_cnt = 0;
}
}
}
else if(WDOG_DESTROY == dog_param->stat)
{
OMXDBUG(OMXDBUG_PARAM, "dog stopped, loop out\\n");
pthread_mutex_unlock(&dog_param->cmd_mutex);
break;
}
pthread_mutex_unlock(&dog_param->cmd_mutex);
usleep(WDOG_SNAP_TIME * 1000);
}
return 0;
}
int tickle_watch_dog(void *handle, char *info)
{
dog_t *dog_param = (dog_t *)handle;
if(0 == dog_param)
{
OMXDBUG(OMXDBUG_ERR, "not open yet!\\n");
return -1;
}
pthread_mutex_lock(&dog_param->cmd_mutex);
dog_param->last_tickle_time = get_current_time();
dog_param->snap_cnt = 0;
memcpy(dog_param->last_tickle_info, info, strlen(info) + 1);
pthread_mutex_unlock(&dog_param->cmd_mutex);
OMXDBUG(OMXDBUG_VERB, "%s in %s\\n", __func__, dog_param->last_tickle_info);
return 0;
}
void *open_watch_dog(void)
{
pthread_attr_t thread_attr;
struct sched_param thread_params;
dog_t *dog_param = (dog_t *)calloc(1, sizeof(dog_t));
if(0 == dog_param)
{
OMXDBUG(OMXDBUG_ERR, "alloc failed!\\n");
return 0;
}
dog_param->stat = WDOG_IDLE;
pthread_mutex_init(&dog_param->cmd_mutex, 0);
pthread_attr_init(&thread_attr);
pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_JOINABLE);
pthread_attr_getschedparam(&thread_attr, &thread_params);
thread_params.sched_priority = (int) - 9;
pthread_attr_setschedparam(&thread_attr, &thread_params);
pthread_create(&dog_param->thread_loop, 0 , watch_dog_loop, dog_param);
{
}
OMXDBUG(OMXDBUG_PARAM, "watch dog opened!\\n");
return (void *)dog_param;
}
int close_watch_dog(void *handle)
{
dog_t *dog_param = (dog_t *)handle;
if(0 == dog_param)
{
OMXDBUG(OMXDBUG_ERR, "not open yet!\\n");
return -1;
}
pthread_mutex_lock(&dog_param->cmd_mutex);
dog_param->stat = WDOG_DESTROY;
pthread_mutex_unlock(&dog_param->cmd_mutex);
pthread_join(dog_param->thread_loop, 0);
pthread_mutex_destroy(&dog_param->cmd_mutex);
free(dog_param);
OMXDBUG(OMXDBUG_PARAM, "watch dog closed!\\n");
return 0;
}
int start_watch_dog(void *handle)
{
dog_t *dog_param = (dog_t *)handle;
if(0 == dog_param)
{
OMXDBUG(OMXDBUG_ERR, "not open yet!\\n");
return -1;
}
pthread_mutex_lock(&dog_param->cmd_mutex);
dog_param->last_tickle_time = get_current_time();
dog_param->snap_cnt = 0;
dog_param->stat = WDOG_BUSY;
dog_param->last_tickle_info[0] = '\\0';
pthread_mutex_unlock(&dog_param->cmd_mutex);
OMXDBUG(OMXDBUG_PARAM, "watch dog started!\\n");
return 0;
}
int stop_watch_dog(void *handle)
{
dog_t *dog_param = (dog_t *)handle;
if(0 == dog_param)
{
OMXDBUG(OMXDBUG_ERR, "not open yet!\\n");
return -1;
}
pthread_mutex_lock(&dog_param->cmd_mutex);
dog_param->stat = WDOG_IDLE;
pthread_mutex_unlock(&dog_param->cmd_mutex);
OMXDBUG(OMXDBUG_PARAM, "watch dog stopped!\\n");
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t barrier;
pthread_cond_t go;
int numWorkers;
int numArrived = 0;
struct Partial {
int value[10];
int column[10];
int row[10];
};
void Barrier() {
pthread_mutex_lock(&barrier);
numArrived++;
if (numArrived == numWorkers) {
numArrived = 0;
pthread_cond_broadcast(&go);
} else
pthread_cond_wait(&go, &barrier);
pthread_mutex_unlock(&barrier);
}
double read_timer() {
static bool initialized = 0;
static struct timeval start;
struct timeval end;
if( !initialized )
{
gettimeofday( &start, 0 );
initialized = 1;
}
gettimeofday( &end, 0 );
return (end.tv_sec - start.tv_sec) + 1.0e-6 * (end.tv_usec - start.tv_usec);
}
double start_time, end_time;
int size, stripSize;
int sums[10];
struct Partial Max;
struct Partial Min;
int matrix[10000][10000];
void *Worker(void *);
int main(int argc, char *argv[]) {
int i, j;
long l;
pthread_attr_t attr;
pthread_t workerid[10];
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
pthread_mutex_init(&barrier, 0);
pthread_cond_init(&go, 0);
size = (argc > 1)? atoi(argv[1]) : 10000;
numWorkers = (argc > 2)? atoi(argv[2]) : 10;
if (size > 10000) size = 10000;
if (numWorkers > 10) numWorkers = 10;
stripSize = size/numWorkers;
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
matrix[i][j] = rand() %99;
}
}
start_time = read_timer();
for (l = 0; l < numWorkers; l++)
pthread_create(&workerid[l], &attr, Worker, (void *) l);
pthread_exit(0);
}
void *Worker(void *arg) {
long myid = (long) arg;
int total, maxID, minID, max, min, i, j, first, last;
first = myid*stripSize;
last = (myid == numWorkers - 1) ? (size - 1) : (first + stripSize - 1);
total = 0;
Max.value[myid] = -1;
Min.value[myid] = 100;
for (i = first; i <= last; i++){
for (j = 0; j < size; j++){
total += matrix[i][j];
if(Max.value[myid] < matrix[i][j]){
Max.value[myid] = matrix[i][j];
Max.column[myid] = j;
Max.row[myid] = i;
}
if(Min.value[myid] > matrix[i][j]){
Min.value[myid] = matrix[i][j];
Min.column[myid] = j;
Min.row[myid] = i;
}
}
}
sums[myid] = total;
Barrier();
if (myid == 0) {
total = 0;
max = 0;
min = 99;
maxID = 0;
minID = 0;
for (i = 0; i < numWorkers; i++){
total += sums[i];
if(max < Max.value[i]){
max = Max.value[i];
maxID = i;
}
if(min > Min.value[i]){
min = Min.value[i];
minID = i;
}
}
end_time = read_timer();
printf("The total is %d\\n", total);
printf("The maximum value is %d and its matrix position is [%d] [%d]\\n", Max.value[maxID], Max.column[maxID], Max.row[maxID]);
printf("The minimum value is %d and its matrix position is [%d] [%d]\\n", Min.value[minID], Min.column[minID], Min.row[minID]);
printf("The execution time is %g sec\\n", end_time - start_time);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
sem_t students_sem;
sem_t ta_sem;
int waiting_students = 0;
int ta_asleep = 0;
int seeds[5] = {12315, 36462, 63252, 87273, 21573};
pthread_t student_threads[4];
pthread_t ta_thread_ptr;
void *student_thread(void *num);
void *ta_thread(void *staaanddyyyy);
int main(void){
printf("CS149 SleepingTA from Malik Khalil");
pthread_mutex_init(&mutex_lock, 0);
sem_init(&students_sem, 0, 0);
sem_init(&ta_sem, 0, 1);
int *s_id;
int i;
pthread_create(&ta_thread_ptr, 0, ta_thread, 0);
for (i = 0; i < 4; i++){
s_id = i;
pthread_create(&student_threads[i], 0, student_thread, s_id);
}
for (i = 0; i < 4; i++){
pthread_join(student_threads[i], 0);
}
pthread_cancel(ta_thread_ptr);
sem_destroy(&students_sem);
sem_destroy(&ta_sem);
printf("\\n");
return 0;
}
void *ta_thread(void *staaanddyyyy){
int ta_seed = 4;
int rand_wait = (rand_r(&seeds[ta_seed]) % 3) + 1;
while(1){
rand_wait = (rand_r(&seeds[ta_seed]) % 3) + 1;
sem_wait(&students_sem);
while (waiting_students > 0){
rand_wait = (rand_r(&seeds[ta_seed]) % 3) + 1;
sem_post(&ta_sem);
pthread_mutex_lock(&mutex_lock);
waiting_students--;
pthread_mutex_unlock(&mutex_lock);
rand_wait, waiting_students);
sleep(rand_wait);
}
}
}
void *student_thread(void *num){
int helps = 0;
int student_number = (int *) num;
int rand_wait = (rand_r(&seeds[student_number]) % 3) + 1;
printf("\\n\\tStudent %d programming for %d seconds.", student_number, rand_wait);
sleep(rand_wait);
while (helps < 2){
pthread_mutex_lock(&mutex_lock);
if (waiting_students < 2){
sem_post(&students_sem);
waiting_students++;
pthread_mutex_unlock(&mutex_lock);
waiting_students);
sem_wait(&ta_sem);
printf("\\nStudent %d receiving help", student_number);
rand_wait = (rand_r(&seeds[student_number]) % 3) + 1;
sleep(rand_wait);
helps++;
}
else{
pthread_mutex_unlock(&mutex_lock);
rand_wait = (rand_r(&seeds[student_number]) % 3) + 1;
printf("\\n\\t\\t\\tStudent %d will try later", student_number);
printf("\\n\\tStudent %d programming for %d seconds.", student_number, rand_wait);
sleep(rand_wait);
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int queue[50];
int rear=-1;
int front=-1;
pthread_mutex_t m;
void *insert()
{
int num,i;
if (rear==50 -1)
printf("Queue Overflow \\n");
else
{
if(front==-1)
front=0;
for(i=0;i<49;i++)
{
queue[rear]=i;
rear=rear+1;
}
printf("\\nElements %d\\n",i);
}
}
void *delete()
{
pthread_mutex_lock(&m);
if (front==-1||front>rear) {
printf("Queue Underflow \\n");
return ;
}
else
{
printf("\\nDeleted element %d\\n",queue[front]);
front=front+1;
}
pthread_mutex_unlock(&m);
}
void display()
{
int i;
if (front==-1)
printf("Queue is empty \\n");
else
{
printf("Queue is : \\n");
for(i=front;i<=rear;i++)
printf("%d ",queue[i]);
printf("\\n");
}
}
int main()
{
int ch, i;
pthread_t tid1,tid2,tid3;
display();
pthread_create(&tid1,0,insert,0);
pthread_create(&tid2,0,delete,0);
pthread_create(&tid3,0,delete,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
}
| 0
|
#include <pthread.h>
extern unsigned char dev_led_mask;
extern int dev_led_fd;
extern pthread_mutex_t mutex_led;
extern pthread_cond_t cond_led;
void *pthread_led (void *arg)
{
int led_no;
char * buff = 0;
unsigned char led_set;
if ((dev_led_fd = open ("/sys/class/leds/led2/brightness", O_RDWR)) < 0)
{
printf ("Cann't open file /sys/class/leds/led2/brightness\\n");
exit (-1);
}
printf ("pthread_led is ok\\n");
while (1)
{
pthread_mutex_lock (&mutex_led);
pthread_cond_wait (&cond_led, &mutex_led);
led_set = dev_led_mask;
pthread_mutex_unlock (&mutex_led);
printf ("pthread_led is wake up\\n");
if (led_set == 0x11)
{
if ((dev_led_fd = open ("/sys/class/leds/led2/brightness", O_RDWR)) < 0)
{
printf ("Cann't open file /sys/class/leds/led2/brightness\\n");
exit (-1);
}
buff = "1";
write(dev_led_fd, buff, 1);
printf("fs4412 led2 on\\n");
close(dev_led_fd);
}
if (led_set == 0x10)
{
if ((dev_led_fd = open ("/sys/class/leds/led2/brightness", O_RDWR)) < 0)
{
printf ("Cann't open file /sys/class/leds/led2/brightness\\n");
exit (-1);
}
buff = "0";
write(dev_led_fd, buff, 1);
printf("fs4412 led2 off\\n");
close(dev_led_fd);
}
if (led_set == 0x22)
{
if ((dev_led_fd = open ("/sys/class/leds/led3/brightness", O_RDWR)) < 0)
{
printf ("Cann't open file /sys/class/leds/led3/brightness\\n");
exit (-1);
}
buff = "1";
write(dev_led_fd, buff, 1);
printf("fs4412 led3 on\\n");
close(dev_led_fd);
}
if (led_set == 0x20)
{
if ((dev_led_fd = open ("/sys/class/leds/led3/brightness", O_RDWR)) < 0)
{
printf ("Cann't open file /sys/class/leds/led3/brightness\\n");
exit (-1);
}
buff = "0";
write(dev_led_fd, buff, 1);
printf("fs4412 led3 off\\n");
close(dev_led_fd);
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
int y;
void *inc_x(void *x_void_ptr)
{
int *x_pt = (int *)x_void_ptr;
while(y < 10000) {
pthread_mutex_lock(&mutex);
if(y < 10000) {
y++;
}
pthread_mutex_unlock(&mutex);
}
return 0;
}
int main(int argc, char **argv)
{
stopwatch_start();
int *x, i;
int num_threads = 2;
if(pthread_mutex_init(&mutex, 0)) {
fprintf(stderr, "error initializing mutex");
return 3;
}
y = 0;
if(argc > 1) {
num_threads = atoi(argv[1]);
}
x = (int *) malloc(num_threads * sizeof(int));
for(i = 0; i < num_threads; i++) {
x[i] = i + 1;
}
pthread_t *inc_x_thread;
inc_x_thread = (pthread_t *) malloc(num_threads * sizeof(pthread_t));
for(i = 0; i < num_threads; i++) {
if(pthread_create(&inc_x_thread[i], 0, inc_x, &x[i])) {
fprintf(stderr, "Error creating thread\\n");
return 1;
}
}
for(i = 0; i < num_threads; i++) {
fprintf(stdout, "JOINING THREAD\\n");
if(pthread_join(inc_x_thread[i], 0)) {
fprintf(stderr, "Error joining thread\\n");
return 2;
}
}
pthread_mutex_destroy(&mutex);
if(y != 10000) {
fprintf(stderr, "Internal Error: Result (%d) different than expected (%d)", y, 10000);
return 3;
}
printf("All threads joined.\\n");
free(x);
free(inc_x_thread);
stopwatch_stop();
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.