text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
extern int verbose;
extern int ddssock;
extern pthread_mutex_t dds_comm_lock;
void dds_exit(void *arg)
{
int *sockfd = (int *) arg;
pthread_t tid;
tid = pthread_self();
}
void *dds_register_seq(void *arg)
{
struct DriverMsg msg;
struct ControlProgram *control_program;
struct timeval t0,t1;
int index;
control_program=arg;
pthread_mutex_lock(&dds_comm_lock);
msg.type=DDS_REGISTER_SEQ;
msg.status=1;
send_data(ddssock, &msg, sizeof(struct DriverMsg));
send_data(ddssock, control_program->parameters, sizeof(struct ControlPRM));
index=control_program->parameters->current_pulseseq_index;
send_data(ddssock, &index, sizeof(index));
send_data(ddssock,control_program->state->pulseseqs[index], sizeof(struct TSGbuf));
send_data(ddssock,control_program->state->pulseseqs[index]->rep,
sizeof(unsigned char)*control_program->state->pulseseqs[index]->len);
send_data(ddssock,control_program->state->pulseseqs[index]->code,
sizeof(unsigned char)*control_program->state->pulseseqs[index]->len);
recv_data(ddssock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&dds_comm_lock);
pthread_exit(0);
}
void *dds_rxfe_settings(void *arg)
{
struct DriverMsg msg;
struct SiteSettings *site_settings;
site_settings=arg;
pthread_mutex_lock(&dds_comm_lock);
if (site_settings!=0) {
msg.type=DDS_RXFE_SETTINGS;
msg.status=1;
send_data(ddssock, &msg, sizeof(struct DriverMsg));
send_data(ddssock, &site_settings->ifmode, sizeof(site_settings->ifmode));
send_data(ddssock, &site_settings->rf_settings, sizeof(struct RXFESettings));
send_data(ddssock, &site_settings->if_settings, sizeof(struct RXFESettings));
recv_data(ddssock, &msg, sizeof(struct DriverMsg));
}
pthread_mutex_unlock(&dds_comm_lock);
}
void *dds_ready_controlprogram(void *arg)
{
struct DriverMsg msg;
struct ControlProgram *control_program;
struct timeval t0,t1;
control_program=arg;
pthread_mutex_lock(&dds_comm_lock);
if (control_program!=0) {
if (control_program->state->pulseseqs[control_program->parameters->current_pulseseq_index]!=0) {
msg.type=DDS_CtrlProg_READY;
msg.status=1;
send_data(ddssock, &msg, sizeof(struct DriverMsg));
send_data(ddssock, control_program->parameters, sizeof(struct ControlPRM));
recv_data(ddssock, &msg, sizeof(struct DriverMsg));
}
}
pthread_mutex_unlock(&dds_comm_lock);
pthread_exit(0);
};
void *dds_end_controlprogram(void *arg)
{
struct DriverMsg msg;
struct timeval t0,t1;
pthread_mutex_lock(&dds_comm_lock);
msg.type=DDS_CtrlProg_END;
msg.status=1;
send_data(ddssock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&dds_comm_lock);
pthread_exit(0);
};
void *dds_pretrigger(void *arg)
{
struct DriverMsg msg;
struct ControlProgram *control_program;
struct timeval t0,t1;
int total=0;
control_program=arg;
pthread_mutex_lock(&dds_comm_lock);
msg.type=DDS_PRETRIGGER;
msg.status=1;
send_data(ddssock, &msg, sizeof(struct DriverMsg));
total=recv_data(ddssock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&dds_comm_lock);
pthread_exit(0);
};
void *dds_posttrigger(void *arg)
{
struct timeval t0,t1;
pthread_mutex_lock(&dds_comm_lock);
pthread_mutex_unlock(&dds_comm_lock);
};
| 1
|
#include <pthread.h>
int beers = 2000000;
pthread_mutex_t beers_lock = PTHREAD_MUTEX_INITIALIZER;
void* drink_lots(void *a)
{
int i;
if (2 == 1) {
pthread_mutex_lock(&beers_lock);
for (i = 0; i < 100000; i++) {
beers -= 1;
}
pthread_mutex_unlock(&beers_lock);
printf("beers = %d\\n", beers);
}
if (2 == 2) {
for (i = 0; i < 100000; i++) {
pthread_mutex_lock(&beers_lock);
beers -= 1;
pthread_mutex_unlock(&beers_lock);
}
printf("beers = %d\\n", beers);
}
return 0;
}
void error(char *msg)
{
fprintf(stderr, "%s: %s\\n", msg, strerror(errno));
exit(1);
}
int main(int argc, char *argv[])
{
pthread_t threads[20];
int t;
printf("%d bottles of beer on the wall\\n%d bottles of beer\\n", beers,
beers);
for (t = 0; t < 20; t++) {
if (pthread_create(&threads[t], 0, drink_lots, 0) == -1)
error("Unable to create thread t0");
}
void* result;
for (t = 0; t < 20; t++) {
pthread_join(threads[t], &result);
}
printf("There are now %d bottles of beer on the wall\\n", beers);
return 0;
}
| 0
|
#include <pthread.h>
int cmpfunc (const void * a, const void * b)
{
if (*(double*)a > *(double*)b) return 1;
else if (*(double*)a < *(double*)b) return -1;
else return 0;
}
int checkForDuplicate(struct threaddata* thread_data_array, int noElevators, int floor, int direction)
{
int i;
for(i=0; i<noElevators; i++) {
pthread_mutex_lock(thread_data_array[i].mutex);
struct tasklist* task = thread_data_array[i].taskList;
while(task != 0) {
if(task->floor == floor && task->type == direction) {
pthread_mutex_unlock(thread_data_array[i].mutex);
return 1;
}
task = task->next;
}
pthread_mutex_unlock(thread_data_array[i].mutex);
}
return 0;
}
int assignToElevator(struct threaddata* threaddata, int noElevators, int floor, int direction)
{
if(checkForDuplicate(threaddata, noElevators, floor, direction))
return -2;
int i, j, gotAssigned = 0;
double arrayvalues[noElevators];
for(i=0; i<noElevators; i++) {
pthread_mutex_lock(threaddata[i].mutex);
double distance = fabs(threaddata[i].position - floor);
pthread_mutex_unlock(threaddata[i].mutex);
arrayvalues[i] = distance;
}
qsort(arrayvalues, noElevators, sizeof(arrayvalues[0]), cmpfunc);
for(i=0; i<noElevators; i++) {
double distance = arrayvalues[i];
for(j=0; j<noElevators; j++) {
pthread_mutex_lock(threaddata[j].mutex);
if(fabs(threaddata[j].position - floor) == distance) {
if(!threaddata[j].isStopped) {
if(threaddata[j].taskList == 0) {
struct tasklist* tmptask = (struct tasklist*) malloc(sizeof(struct tasklist));
tmptask->next = 0;
tmptask->floor = floor;
tmptask->type = direction;
threaddata[j].taskList = tmptask;
gotAssigned = 1;
} else {
if(( direction == MotorUp && threaddata[j].position < floor && threaddata[j].taskList->floor > floor) ||
(direction == MotorDown && threaddata[j].position > floor && threaddata[j].taskList->floor < floor)) {
struct tasklist* tmptask = (struct tasklist*) malloc(sizeof(struct tasklist));
tmptask->next = threaddata[j].taskList;
tmptask->floor = floor;
tmptask->type = direction;
threaddata[j].taskList = tmptask;
gotAssigned = 1;
}
}
}
}
pthread_mutex_unlock(threaddata[j].mutex);
if(gotAssigned)
break;
}
if(gotAssigned)
break;
}
if(gotAssigned)
return j;
return -1;
}
| 1
|
#include <pthread.h>
void subsec(void);
void second(void);
void minute(void);
void display(void);
pthread_mutex_t countmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t count_threshold_subsec;
pthread_cond_t count_threshold_second;
struct Watch {
int minute;
int second;
int subsec;
} watch_counter = {0, 0, 0};
int main(void) {
pthread_mutex_init(&countmutex, 0);
pthread_cond_init (&count_threshold_subsec, 0);
pthread_cond_init (&count_threshold_second, 0);
pthread_t subsec_thread;
pthread_t second_thread;
pthread_t minute_thread;
pthread_t display_thread;
if(pthread_create(&subsec_thread, 0, (void *)subsec, 0)) {
fprintf(stderr, "Error creating subsec thread\\n");
return 1;
}
if(pthread_create(&second_thread, 0, (void *)second, 0)) {
fprintf(stderr, "Error creating second thread\\n");
return 1;
}
if(pthread_create(&minute_thread, 0, (void *)minute, 0)) {
fprintf(stderr, "Error creating minute thread\\n");
return 1;
}
if(pthread_create(&display_thread, 0, (void *)display, 0)) {
fprintf(stderr, "Error creating display thread\\n");
return 1;
}
while(1);
return 0;
}
void subsec(void) {
while(1) {
usleep(10000);
pthread_mutex_lock (&countmutex);
watch_counter.subsec++;
if (watch_counter.subsec == 100) {
watch_counter.subsec = 0;
pthread_cond_signal(&count_threshold_subsec);
}
pthread_mutex_unlock (&countmutex);
}
}
void second(void) {
while(1) {
pthread_mutex_lock (&countmutex);
pthread_cond_wait(&count_threshold_subsec, &countmutex);
watch_counter.second++;
watch_counter.subsec = 0;
if (watch_counter.second == 60) {
watch_counter.second = 0;
pthread_cond_signal(&count_threshold_second);
}
pthread_mutex_unlock (&countmutex);
}
}
void minute(void) {
while(1) {
pthread_mutex_lock (&countmutex);
pthread_cond_wait(&count_threshold_second, &countmutex);
watch_counter.minute++;
watch_counter.second = 0;
watch_counter.subsec = 0;
pthread_mutex_unlock (&countmutex);
}
}
void display(void) {
while(1) {
printf("\\r%02d:%02d:%02d", watch_counter.minute, watch_counter.second,
watch_counter.subsec);
fflush(0);
usleep(10000);
}
}
| 0
|
#include <pthread.h>
struct mq_s {
mq_t *next;
int data;
};
mq_t *wq;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t c_lock = PTHREAD_MUTEX_INITIALIZER;
void* process_msg(void *arg) {
mq_t *mp;
for ( ; ; ) {
pthread_mutex_lock(&c_lock);
printf("process_msg: got the lock\\n");
while (wq == 0) {
pthread_cond_wait(&cond, &c_lock);
}
printf("process_msg: got the cond\\n");
mp = wq;
wq = mp->next;
printf("process_msg: releasing the lock\\n");
pthread_mutex_unlock(&c_lock);
mp->data += 1;
printf("process_msg: msg data = %d\\n",mp->data);
}
}
void* eq_msg(void *arg) {
for (int i = 1; i < 5; ++i) {
int r = 0;
pthread_mutex_lock(&c_lock);
printf("eq_msg: got the lock\\n");
mq_t *mp = (mq_t *)malloc(sizeof(mq_t));
mp->data = i;
mp->next = wq;
wq = mp;
printf("eq_msg: releasing the lock\\n");
pthread_mutex_unlock(&c_lock);
printf("eq_msg: signal the cond\\n");
pthread_cond_signal(&cond);
r = sched_yield();
if (r != 0) {
perror("sched_yield");
}
}
}
void posix_cond() {
int r1, r2;
pthread_t t1, t2;
wq = (mq_t *)malloc(sizeof(mq_t));
wq->data = 0;
wq->next = 0;
r1 = pthread_create(&t1, 0, process_msg, 0);
r2 = pthread_create(&t2, 0, eq_msg, 0);
if (r1 != 0) {
perror("pthread_create");
}
if (r2 != 0) {
perror("pthread_create");
}
pthread_join(t1, 0);
pthread_join(t2, 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t* lock;
pthread_mutex_t lock2;
pthread_mutex_t lock3;
pthread_t *SCV;
int workers = 5;
int minerals = 5000;
int remaining_minerals = 5000;
int collected_minerals = 0;
int soldiers = 0;
int scv_alloc_counter = 6;
int mutex_alloc_counter = 2;
void* thread_func(void* param) {
int index = (intptr_t)param;
int flag = 0;
int i;
index+=1;
while(remaining_minerals != 0 ){
if(flag != 1) {
flag = 1;
pthread_mutex_lock(&lock2);
printf("SCV %d is mining\\n",index);
remaining_minerals-=8;
pthread_mutex_unlock(&lock2);
printf("SCV %d is transporting minerals\\n",index);
sleep(2);
}
for(i = 0; i < mutex_alloc_counter-1; i++) {
if(pthread_mutex_trylock(&lock[i]) == 0) {
pthread_mutex_lock(&lock3);
collected_minerals+=8;
pthread_mutex_unlock(&lock3);
pthread_mutex_unlock(&lock[i]);
printf("SCV %d delivered minerals to Command center %d\\n",index,i+1);
flag = 2;
break;
}
}
if(flag != 2) {
sleep(1);
}
}
return 0;
}
void training_soldier() {
if(collected_minerals >= 50){
pthread_mutex_lock(&lock3);
collected_minerals-=50;
pthread_mutex_unlock(&lock3);
sleep(1);
soldiers+=1;
printf("You wanna piece of me, boy ?\\n");
if(soldiers == 20) {
int tmp = minerals - remaining_minerals;
printf("All minerals: %d, Remaining minerals: %d, Collected minerals: %d\\n",minerals,remaining_minerals,tmp);
exit(1);
}
}
else{
printf("Not enough minerals.\\n");
}
}
void add_center() {
if(collected_minerals >= 400){
pthread_mutex_lock(&lock3);
collected_minerals-=400;
pthread_mutex_unlock(&lock3);
sleep(2);
mutex_alloc_counter++;
lock = realloc(lock,mutex_alloc_counter*(sizeof(pthread_mutex_t)));
printf("Command center %d created.\\n",mutex_alloc_counter-1);
}
else {
printf("Not enough minerals.\\n");
}
}
void training_worker() {
if(collected_minerals >= 50) {
pthread_mutex_lock(&lock3);
collected_minerals -=50;
pthread_mutex_unlock(&lock3);
sleep(1);
if(workers != 0 ){
scv_alloc_counter++;
SCV = realloc(SCV,(scv_alloc_counter*sizeof(pthread_t)));
int rc = pthread_create(&SCV[workers],0,thread_func,(void *)(intptr_t)workers);
if(rc) {
printf("ERROR: pthread_create() return %d\\n",rc);
exit(-1);
}
workers++;
}
printf("SCV good to go, sir.\\n");
}
else {
printf("Not enough minerals.\\n");
}
}
void* st_input(void* arg) {
char c;
while(read(STDIN_FILENO, &c, 1) > 0) {
if(c == 'm') {
training_soldier();
}
else if(c == 's') {
training_worker();
}
else if(c == 'c') {
add_center();
}
}
return 0;
}
int main() {
pthread_t st_input_thread;
int rc;
SCV = malloc(scv_alloc_counter*sizeof(pthread_t));
lock = malloc(mutex_alloc_counter*sizeof(pthread_mutex_t));
rc = pthread_mutex_init(lock,0);
if(rc) {
printf("ERROR: pthread_mutex_init() return %d\\n",rc);
exit(-1);
}
rc = pthread_mutex_init(&lock2,0);
if(rc) {
printf("ERROR: pthread_mutex_init() return %d\\n",rc);
exit(-1);
}
rc = pthread_mutex_init(&lock3,0);
if(rc) {
printf("ERROR: pthread_mutex_init() return %d\\n",rc);
exit(-1);
}
for(int i = 0; i < workers; ++i) {
rc = pthread_create(&SCV[i],0,thread_func,(void *)(intptr_t)i);
if(rc) {
printf("ERROR: pthread_create() return %d\\n",rc);
exit(-1);
}
}
rc = pthread_create(&st_input_thread,0,st_input,0);
if(rc) {
printf("ERROR: pthread_create() return %d\\n",rc);
exit(-1);
}
for(int i = 0; i < workers; ++i) {
pthread_join(SCV[i],0);
}
workers = 0;
pthread_join(st_input_thread,0);
rc = pthread_mutex_destroy(lock);
if(rc){
printf("ERROR: pthread_mutex_destroy() return %d\\n",rc);
exit(-1);
}
rc = pthread_mutex_destroy(&lock2);
if(rc){
printf("ERROR: pthread_mutex_destroy() return %d\\n",rc);
exit(-1);
}
rc = pthread_mutex_destroy(&lock3);
if(rc){
printf("ERROR: pthread_mutex_destroy() return %d\\n",rc);
exit(-1);
}
free(SCV);
free(lock);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int message[] = {79,59,12,2,79,35,8,28,20,2,3,68,8,9,68,45,0,12,9,67,68,4,7,5,23,27,1,21,79,85,78,79,85,71,38,10,71,27,12,2,79,6,2,8,13,9,1,13,9,8,68,19,7,1,71,56,11,21,11,68,6,3,22,2,14,0,30,79,1,31,6,23,19,10,0,73,79,44,2,79,19,6,28,68,16,6,16,15,79,35,8,11,72,71,14,10,3,79,12,2,79,19,6,28,68,32,0,0,73,79,86,71,39,1,71,24,5,20,79,13,9,79,16,15,10,68,5,10,3,14,1,10,14,1,3,71,24,13,19,7,68,32,0,0,73,79,87,71,39,1,71,12,22,2,14,16,2,11,68,2,25,1,21,22,16,15,6,10,0,79,16,15,10,22,2,79,13,20,65,68,41,0,16,15,6,10,0,79,1,31,6,23,19,28,68,19,7,5,19,79,12,2,79,0,14,11,10,64,27,68,10,14,15,2,65,68,83,79,40,14,9,1,71,6,16,20,10,8,1,79,19,6,28,68,14,1,68,15,6,9,75,79,5,9,11,68,19,7,13,20,79,8,14,9,1,71,8,13,17,10,23,71,3,13,0,7,16,71,27,11,71,10,18,2,29,29,8,1,1,73,79,81,71,59,12,2,79,8,14,8,12,19,79,23,15,6,10,2,28,68,19,7,22,8,26,3,15,79,16,15,10,68,3,14,22,12,1,1,20,28,72,71,14,10,3,79,16,15,10,68,3,14,22,12,1,1,20,28,68,4,14,10,71,1,1,17,10,22,71,10,28,19,6,10,0,26,13,20,7,68,14,27,74,71,89,68,32,0,0,71,28,1,9,27,68,45,0,12,9,79,16,15,10,68,37,14,20,19,6,23,19,79,83,71,27,11,71,27,1,11,3,68,2,25,1,21,22,11,9,10,68,6,13,11,18,27,68,19,7,1,71,3,13,0,7,16,71,28,11,71,27,12,6,27,68,2,25,1,21,22,11,9,10,68,10,6,3,15,27,68,5,10,8,14,10,18,2,79,6,2,12,5,18,28,1,71,0,2,71,7,13,20,79,16,2,28,16,14,2,11,9,22,74,71,87,68,45,0,12,9,79,12,14,2,23,2,3,2,71,24,5,20,79,10,8,27,68,19,7,1,71,3,13,0,7,16,92,79,12,2,79,19,6,28,68,8,1,8,30,79,5,71,24,13,19,1,1,20,28,68,19,0,68,19,7,1,71,3,13,0,7,16,73,79,93,71,59,12,2,79,11,9,10,68,16,7,11,71,6,23,71,27,12,2,79,16,21,26,1,71,3,13,0,7,16,75,79,19,15,0,68,0,6,18,2,28,68,11,6,3,15,27,68,19,0,68,2,25,1,21,22,11,9,10,72,71,24,5,20,79,3,8,6,10,0,79,16,8,79,7,8,2,1,71,6,10,19,0,68,19,7,1,71,24,11,21,3,0,73,79,85,87,79,38,18,27,68,6,3,16,15,0,17,0,7,68,19,7,1,71,24,11,21,3,0,71,24,5,20,79,9,6,11,1,71,27,12,21,0,17,0,7,68,15,6,9,75,79,16,15,10,68,16,0,22,11,11,68,3,6,0,9,72,16,71,29,1,4,0,3,9,6,30,2,79,12,14,2,68,16,7,1,9,79,12,2,79,7,6,2,1,73,79,85,86,79,33,17,10,10,71,6,10,71,7,13,20,79,11,16,1,68,11,14,10,3,79,5,9,11,68,6,2,11,9,8,68,15,6,23,71,0,19,9,79,20,2,0,20,11,10,72,71,7,1,71,24,5,20,79,10,8,27,68,6,12,7,2,31,16,2,11,74,71,94,86,71,45,17,19,79,16,8,79,5,11,3,68,16,7,11,71,13,1,11,6,1,17,10,0,71,7,13,10,79,5,9,11,68,6,12,7,2,31,16,2,11,68,15,6,9,75,79,12,2,79,3,6,25,1,71,27,12,2,79,22,14,8,12,19,79,16,8,79,6,2,12,11,10,10,68,4,7,13,11,11,22,2,1,68,8,9,68,32,0,0,73,79,85,84,79,48,15,10,29,71,14,22,2,79,22,2,13,11,21,1,69,71,59,12,14,28,68,14,28,68,9,0,16,71,14,68,23,7,29,20,6,7,6,3,68,5,6,22,19,7,68,21,10,23,18,3,16,14,1,3,71,9,22,8,2,68,15,26,9,6,1,68,23,14,23,20,6,11,9,79,11,21,79,20,11,14,10,75,79,16,15,6,23,71,29,1,5,6,22,19,7,68,4,0,9,2,28,68,1,29,11,10,79,35,8,11,74,86,91,68,52,0,68,19,7,1,71,56,11,21,11,68,5,10,7,6,2,1,71,7,17,10,14,10,71,14,10,3,79,8,14,25,1,3,79,12,2,29,1,71,0,10,71,10,5,21,27,12,71,14,9,8,1,3,71,26,23,73,79,44,2,79,19,6,28,68,1,26,8,11,79,11,1,79,17,9,9,5,14,3,13,9,8,68,11,0,18,2,79,5,9,11,68,1,14,13,19,7,2,18,3,10,2,28,23,73,79,37,9,11,68,16,10,68,15,14,18,2,79,23,2,10,10,71,7,13,20,79,3,11,0,22,30,67,68,19,7,1,71,8,8,8,29,29,71,0,2,71,27,12,2,79,11,9,3,29,71,60,11,9,79,11,1,79,16,15,10,68,33,14,16,15,10,22,73};
int max = 17576;
int indexes[8];
void* printKey(void* arg)
{
char *key = (char *) arg;
for (int i = 0; i < 3; i++) {
printf("%c", key[i]);
}
printf("\\n");
}
char * getKey(int index)
{
char key[3] = {'a', 'a', 'a'};
key[2] += (index % 26);
index = index / 26;
key[1] += (index % 26);
index = index / 26;
key[0] += index;
return key;
}
void* decode(void *arg)
{
int threadIndex = *(int *) arg;
int startIndex = indexes[threadIndex];
char *cipher = getKey(startIndex);
pthread_mutex_lock(&mutex);
printf("Thread: %d, Index: %d\\n", threadIndex, startIndex);
printKey(cipher);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
char key[3];
int nums[8] = {0};
for (int i = 0; i < 8; i++) {
indexes[i] = (max * i) / 8;
}
pthread_t strand[8];
for (int i = 0; i < 8; i++) {
nums[i] = i;
}
for (int i = 0; i < 8; i++) {
pthread_create(&strand[i], 0, decode, &nums[i]);
}
for (int i = 0; i < 8; i++) {
pthread_join(strand[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
char buffer[128];
int buffer_has_data=0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void write_buffer(char *data)
{
pthread_mutex_lock(&mutex);
if(buffer_has_data==0)
{
sprintf(buffer,"%s",data);
buffer_has_data=1;
pthread_cond_signal(&cond);
}
printf("write mutex unlock\\n");
pthread_mutex_unlock(&mutex);
}
void read_buffer(void)
{
while(1)
{
pthread_mutex_lock(&mutex);
while(!buffer_has_data)
{
printf("read cond wait \\n");
pthread_cond_wait(&cond,&mutex);
}
printf("read buffer,data = %s\\n",buffer);
buffer_has_data=0;
pthread_mutex_unlock(&mutex);
}
}
test1()
{
while(1)
{
pthread_cond_wait(&cond,&mutex);
printf("test1 run\\n");
buffer_has_data=0;
pthread_mutex_unlock(&mutex);
}
}
test2()
{
while(1)
{
pthread_cond_wait(&cond,&mutex);
printf("test2 run\\n");
buffer_has_data=0;
pthread_mutex_unlock(&mutex);
}
}
int main(int argc,char **argv)
{
char input[128];
pthread_t reader,t1,t2;
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&reader,0,(void*)(read_buffer),0);
pthread_create(&t1,0,(void*)(test1),0);
pthread_create(&t2,0,(void*)(test2),0);
while(1)
{
scanf("%s",input);
write_buffer(input);
}
pthread_join(reader,0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t chopstick[5];
void *thread_func(int n);
int main()
{
int i,res;
pthread_t a_thread[5];
for(i=0;i<5;++i)
{
res=pthread_mutex_init(&chopstick[i],0);
if(res==-1)
{
perror("mutex initialization failed");
exit(1);
}
}
for(i=0;i<5;++i)
{
res=pthread_create(&a_thread[i],0,thread_func,(int)i);
if(res!=0)
{
perror("mutex creation failed");
exit(1);
}
}
for(i=0;i<5;++i)
{
res=pthread_join(a_thread[i],0);
if(res!=0)
{
perror("mutex join failed");
exit(1);
}
}
printf("thread join successful\\n");
for(i=0;i<5;++i)
{
res=pthread_mutex_destroy(&chopstick[i]);
if(res==-1)
{
perror("mutex destruction failed");
exit(1);
}
}
exit(0);
}
void *thread_func(int n)
{
int i,iteration=5;
for(i=0;i<iteration;++i)
{
sleep(1);
pthread_mutex_lock(&chopstick[n]);
pthread_mutex_lock(&chopstick[(n+1)%5]);
printf("\\n Begin eating :%d",n);
sleep(1);
printf("\\n Finish eating: %d ",n);
pthread_mutex_unlock(&chopstick[n]);
pthread_mutex_unlock(&chopstick[(n+1)%5]);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
int printers = 0;
void * print_job_requester(void * printjobno){
pthread_mutex_lock(&mutex1);
if(printers == 3)
pthread_cond_wait(&condition_var, &mutex1);
printers++;
pthread_mutex_unlock(&mutex1);
printf("Printing...%d\\n", (int) printjobno);
sleep((rand() % 6));
printf("Completed %d\\n", (int) printjobno);
pthread_mutex_lock(&mutex1);
printers--;
pthread_cond_signal(&condition_var);
pthread_mutex_unlock(&mutex1);
return 0;
}
int main()
{
pthread_t threads[10];
srand(time(0));
int rc,i;
for (i = 0; i < 10; i++) {
rc = pthread_create(&threads[i], 0, print_job_requester, (void *) i);
sleep(rand()%3);
}
for (i = 0; i < 10; i++) {
rc = pthread_join(threads[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_t notifier_tid = 0;
static void print_host_event( char etype, uint32_t ip) {
char mac_str[17 + 1],
ip_str[INET_ADDRSTRLEN + 1],
*etype_str,
*name,
next_etype;
struct host *h;
if(!inet_ntop(AF_INET, &(ip), ip_str, INET_ADDRSTRLEN)) {
print( ERROR, "inet_ntop(%u): %s\\n", ip, strerror(errno));
return;
}
name = 0;
mac_str[0] = '\\0';
if(etype != MAC_LOST) {
pthread_mutex_lock(&(hosts.control.mutex));
h = get_host(ip);
if(h) {
snprintf(mac_str, 17 + 1, "%02hhX:%02hhX:%02hhX:%02hhX:%02hhX:%02hhX",
h->mac[0], h->mac[1], h->mac[2], h->mac[3], h->mac[4], h->mac[5] );
if(h->name) {
name = strdup(h->name);
}
}
pthread_mutex_unlock(&(hosts.control.mutex));
}
if(mac_str[0] == '\\0') {
strncpy(mac_str, "00:00:00:00:00:00", 17 + 1);
}
again:
next_etype = NONE;
switch(etype) {
case NEW_MAC:
etype_str = "HOST_ADD ";
break;
case MAC_CHANGED:
next_etype = NEW_MAC;
case MAC_LOST:
etype_str = "HOST_DEL ";
break;
case NAME_CHANGED:
case NEW_NAME:
etype_str = "HOST_EDIT";
break;
default:
print(WARNING, "unknown event 0x%02hhX", etype);
return;
}
if ( etype == MAC_LOST || etype == MAC_CHANGED ) {
printf("%s { ip: %s }\\n", etype_str, ip_str);
} else {
printf("%s { mac: %s, ip: %s, name: %s }\\n",
etype_str, mac_str, ip_str, ( name ? name : "" ) );
}
if(next_etype != NONE) {
etype = next_etype;
goto again;
}
if(name) {
free(name);
}
}
void *notifier(void *arg) {
struct event *e;
pthread_mutex_lock(&(events.control.mutex));
while(events.control.active) {
while(!events.list.head && events.control.active)
pthread_cond_wait(&(events.control.cond), &(events.control.mutex));
e = (struct event *) queue_get(&(events.list));
if(!e) continue;
print_host_event(e->type, e->ip);
free(e);
fflush(stdout);
}
pthread_mutex_unlock(&(events.control.mutex));
return 0;
}
int start_notifier() {
if(pthread_create(¬ifier_tid, 0, notifier, 0)) {
print( ERROR, "pthread_create: %s\\n", strerror(errno));
return -1;
}
return 0;
}
void stop_notifier() {
pthread_t tid;
if(notifier_tid) {
tid = notifier_tid;
notifier_tid = 0;
control_deactivate(&(events.control));
pthread_join(tid, 0);
}
}
| 1
|
#include <pthread.h>
int sem_init(sem_t * sem, int pshared, unsigned int value)
{
sem->count=value;
pthread_cond_init(&sem->cond, 0);
pthread_mutex_init(&sem->mutex, 0);
return 0;
}
int sem_destroy(sem_t * sem)
{
int err1,err2;
err1=pthread_cond_destroy(&sem->cond);
err2=pthread_mutex_destroy(&sem->mutex);
if (err1 || err2)
{
errno=err1 ? err1 : err2;
return -1;
}
return 0;
}
int sem_wait(sem_t * sem)
{
if ((errno=pthread_mutex_lock(&sem->mutex)))
return -1;
while (!sem->count)
pthread_cond_wait(&sem->cond, &sem->mutex);
if (errno)
return -1;
sem->count--;
pthread_mutex_unlock(&sem->mutex);
return 0;
}
int sem_trywait(sem_t * sem)
{
if ((errno=pthread_mutex_lock(&sem->mutex)))
return -1;
if (sem->count)
sem->count--;
else
errno=EAGAIN;
pthread_mutex_unlock(&sem->mutex);
return errno ? -1 : 0;
}
int sem_post(sem_t * sem)
{
if ((errno=pthread_mutex_lock(&sem->mutex)))
return -1;
sem->count++;
pthread_mutex_unlock(&sem->mutex);
pthread_cond_signal(&sem->cond);
return 0;
}
int sem_post_multiple(sem_t * sem, unsigned int count)
{
if ((errno=pthread_mutex_lock(&sem->mutex)))
return -1;
sem->count+=count;
pthread_mutex_unlock(&sem->mutex);
pthread_cond_broadcast(&sem->cond);
return 0;
}
int sem_getvalue(sem_t * sem, unsigned int *sval)
{
if ((errno=pthread_mutex_lock(&sem->mutex)))
return -1;
*sval=sem->count;
pthread_mutex_unlock(&sem->mutex);
return 0;
}
| 0
|
#include <pthread.h>
int (* lock) (pthread_mutex_t *mutex);
int (* unlock) (pthread_mutex_t *mutex);
}cts_thread_fns;
static cts_thread_fns cts_thread_funtions =
{
pthread_mutex_lock,
pthread_mutex_unlock
};
static pthread_mutex_t conn_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t sockfd_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t trans_mutex = PTHREAD_MUTEX_INITIALIZER;
static inline pthread_mutex_t* cts_pthread_get_mutex(int type)
{
pthread_mutex_t *ret_val;
switch (type) {
case CTS_MUTEX_CONNECTION:
ret_val = &conn_mutex;
break;
case CTS_MUTEX_SOCKET_FD:
ret_val = &sockfd_mutex;
break;
case CTS_MUTEX_TRANSACTION:
ret_val = &trans_mutex;
break;
default:
ERR("unknown type(%d)", type);
ret_val = 0;
}
return ret_val;
}
void cts_mutex_lock(int type)
{
int ret;
pthread_mutex_t *mutex;
mutex = cts_pthread_get_mutex(type);
if (cts_thread_funtions.lock) {
ret = cts_thread_funtions.lock(mutex);
warn_if(ret, "pthread_mutex_lock Failed(%d)", ret);
}
}
void cts_mutex_unlock(int type)
{
int ret;
pthread_mutex_t *mutex;
mutex = cts_pthread_get_mutex(type);
if (cts_thread_funtions.unlock) {
ret = cts_thread_funtions.unlock(mutex);
warn_if(ret, "pthread_mutex_unlock Failed(%d)", ret);
}
}
void contacts_svc_thread_init(void)
{
cts_thread_funtions.lock = pthread_mutex_lock;
cts_thread_funtions.unlock = pthread_mutex_unlock;
}
| 1
|
#include <pthread.h>
pthread_cond_t enterLounge;
pthread_mutex_t lock;
int occupancy;
int waitingDeans;
void init() {
pthread_mutex_init(&lock, 0);
pthread_cond_init(&enterLounge, 0);
occupancy = 0;
waitingDeans = 0;
sign = 0;
return;
}
void mathProfArrive() {
pthread_mutex_lock(&lock);
while((sign != 1 && sign != 0) || waitingDeans != 0) {
pthread_cond_wait(&enterLounge, &lock);
}
if (sign == 0) {
sign = 1;
}
occupancy++;
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
void csProfArrive() {
pthread_mutex_lock(&lock);
while((sign != 2 && sign != 0) || waitingDeans != 0) {
pthread_cond_wait(&enterLounge, &lock);
}
if (sign == 0) {
sign = 2;
}
occupancy++;
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
void deanArrive() {
pthread_mutex_lock(&lock);
waitingDeans++;
while(sign != 3 && sign != 0) {
pthread_cond_wait(&enterLounge, &lock);
}
if (sign == 0) {
sign = 3;
}
occupancy++;
waitingDeans--;
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
void mathProfLeave() {
pthread_mutex_lock(&lock);
occupancy--;
if(occupancy == 0) {
sign = 0;
}
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
void csProfLeave() {
pthread_mutex_lock(&lock);
occupancy--;
if(occupancy == 0) {
sign = 0;
}
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
void deanLeave() {
pthread_mutex_lock(&lock);
occupancy--;
if(occupancy == 0) {
sign = 0;
}
pthread_cond_broadcast(&enterLounge);
pthread_mutex_unlock(&lock);
return;
}
| 0
|
#include <pthread.h>
struct randgen_msgbuf {
long type;
double number;
};
int randgen_buffer_size = -1;
int randgen_qid;
pthread_t randgen_supplier_tid;
pthread_mutex_t randgen_supplier_lock;
int randgen_supplier_status;
void* randgen_supplier(void* context) {
if (context != 0) {
return 0;
}
struct msqid_ds qid_rand_supply_info;
struct randgen_msgbuf buffer;
buffer.type = 1;
while (1) {
pthread_mutex_lock(&randgen_supplier_lock);
if (randgen_supplier_status == -1) {
pthread_mutex_unlock(&randgen_supplier_lock);
break;
}
pthread_mutex_unlock(&randgen_supplier_lock);
msgctl(randgen_qid, IPC_STAT, &qid_rand_supply_info);
for (int i = 0;
i < randgen_buffer_size - qid_rand_supply_info.msg_qnum;
i++) {
buffer.number = drand48();
msgsnd(randgen_qid, &buffer, sizeof(double), 0);
}
}
return 0;
}
int randgen_init(unsigned int buffer_size, unsigned int eseed) {
if ((randgen_buffer_size != -1) || (buffer_size == 0)) {
return -1;
}
randgen_buffer_size = (int)buffer_size;
if ((randgen_qid = msgget(IPC_PRIVATE, 0666)) < 0) {
randgen_buffer_size = -1;
return -1;
}
srand48((long)time(0) + (long)eseed * 256);
randgen_supplier_status = 0;
pthread_mutex_init(&randgen_supplier_lock, 0);
if ((pthread_create(&randgen_supplier_tid, 0, randgen_supplier, 0) != 0)) {
msgctl(randgen_qid, IPC_RMID, 0);
randgen_buffer_size = -1;
return -1;
}
return 0;
}
double randgen_get(void) {
if (randgen_buffer_size == -1) {
return -1.0;
}
struct randgen_msgbuf buffer;
if (msgrcv(randgen_qid, &buffer, sizeof(double), 0, 0) < 0) {
return -1.0;
}
return buffer.number;
}
void randgen_stop(void) {
if (randgen_buffer_size == -1) {
return;
}
pthread_mutex_lock(&randgen_supplier_lock);
randgen_supplier_status = -1;
pthread_mutex_unlock(&randgen_supplier_lock);
pthread_join(randgen_supplier_tid, 0);
msgctl(randgen_qid, IPC_RMID, 0);
errno = 0;
randgen_buffer_size = -1;
}
| 1
|
#include <pthread.h>
struct jobcontrol;
struct jobarg
{
int number;
int running;
struct jobcontrol *jc;
int result;
int N;
char *box1;
char *box2;
};
struct jobcontrol
{
FILE *in, *out;
pthread_cond_t jobdone;
pthread_mutex_t lock;
int next_job;
struct jobarg *arg;
pthread_t *tid;
int T;
};
int same_box (int N, char *b1, char *b2)
{
int a;
for (a=0; a<N; a++)
{
if (
!memcmp (b1+a, b2, N-a) &&
!memcmp (b1, b2+N-a, a)
)
return 1;
}
return 0;
}
void * jobthread (void *arg)
{
struct jobarg *j = arg;
int a;
j->result = same_box (j->N, j->box1, j->box2);
if (!j->result)
{
char *rev;
rev = malloc (j->N);
for (a=0; a<j->N; a++)
{
int sign_index;
sign_index = j->N-2-a;
if (sign_index < 0)
sign_index += j->N;
if (j->box2[sign_index] < 0)
rev[a] = abs (j->box2[j->N-1-a]);
else
rev[a] = -1 * abs (j->box2[j->N-1-a]);
do{}while(0);
}
j->result = same_box (j->N, j->box1, rev);
free (rev);
}
pthread_mutex_lock (&j->jc->lock);
j->running = 0;
printf ("%d. %d\\n", j->number, j->result);
pthread_mutex_unlock (&j->jc->lock);
pthread_cond_signal (&j->jc->jobdone);
return 0;
}
int more_job (struct jobcontrol *jc)
{
struct jobarg *j;
int jn;
int i;
if (jc->next_job >= jc->T)
return 0;
jn = jc->next_job ++;
j = jc->arg + jn;
fscanf (jc->in, "%d\\n", &j->N);
printf ("%d. new job. N %d\\n", jn, j->N);
j->box1 = malloc (j->N);
j->box2 = malloc (j->N);
for (i=0; i<j->N; i++)
{
fscanf (jc->in, "%d ", &j->box1[i]);
do{}while(0);
}
for (i=0; i<j->N; i++)
{
fscanf (jc->in, "%d ", &j->box2[i]);
do{}while(0);
}
j->number = jn;
j->running = 1;
j->jc = jc;
pthread_create (jc->tid+jn, 0, jobthread, jc->arg+jn);
pthread_detach (jc->tid[jn]);
return 0;
}
int now_running (struct jobcontrol *jc)
{
int i;
int running = 0;
for (i=0; i<jc->T; i++)
if (jc->arg[i].running)
running ++;
return running;
}
int main (int argc, char **argv)
{
char *_in, *_out, *p;
struct jobcontrol _jc;
struct jobcontrol *jc = &_jc;
int i;
if (argc < 2)
{
printf("%s.%d.""no input\\n",__func__, 161);
return 1;
}
_in = argv[1];
_out = malloc (strlen (_in) + 5);
strcpy (_out, _in);
p = strrchr (_out, '.');
if (!p)
p = _out+strlen (_in);
strcpy (p, ".out");
do{}while(0);
jc->in = fopen (_in, "r");
jc->out = fopen (_out, "w");
if (!jc->in || !jc->out)
{
printf("%s.%d.""no input or output\\n",__func__, 178);
return 1;
}
pthread_mutex_init (&jc->lock, 0);
pthread_cond_init (&jc->jobdone, 0);
fscanf (jc->in, "%d\\n", &jc->T);
printf ("T %d\\n", jc->T);
jc->arg = calloc (jc->T, sizeof (jc->arg[0]));
jc->tid = calloc (jc->T, sizeof (jc->tid[0]));
if (!jc->arg || !jc->tid)
{
printf("%s.%d.""no mem for arg or tid\\n",__func__, 192);
return 1;
}
while (1)
{
int running;
pthread_mutex_lock (&jc->lock);
running = now_running (jc);
if (running >= 4)
pthread_cond_wait (&jc->jobdone, &jc->lock);
else if (jc->next_job >= jc->T)
{
if (running == 0)
{
do{}while(0);
pthread_mutex_unlock (&jc->lock);
break;
}
pthread_cond_wait (&jc->jobdone, &jc->lock);
}
pthread_mutex_unlock (&jc->lock);
more_job (jc);
}
for (i=0; i<jc->T; i++)
{
printf ("%d. result %d\\n", i, jc->arg[i].result);
fprintf (jc->out, "%d\\n", jc->arg[i].result);
}
return 0;
}
| 0
|
#include <pthread.h>
static char running = 1;
static unsigned long counter = 0;
static useconds_t micsec = 1000;
pthread_mutex_t c_mutex;
int i;
void *process(void *arg)
{
while (running)
{
pthread_mutex_lock(&c_mutex);
if (i > 4)
{
pthread_exit(0);
}
counter++;
pthread_mutex_unlock(&c_mutex);
usleep(micsec);
}
pthread_exit(0);
}
int main (int argc, char *argv[])
{
pthread_t threadID;
void *retval;
pthread_mutex_init(&c_mutex, 0);
if (pthread_create(&threadID, 0, process, "0"))
{
{ perror("pthread_create"); exit(errno); }
}
for (i = 0; i < 10; i++)
{
pthread_mutex_unlock(&c_mutex);
pthread_mutex_lock(&c_mutex);
printf("Counter: %lu, \\n", counter);
pthread_mutex_unlock(&c_mutex);
fflush(stdout);
sleep(1);
}
running = 0;
if (pthread_join(threadID, &retval))
{
{ perror("pthread_join"); exit(errno); };
}
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error();
static int iTThreads = 2;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t *data1Lock;
pthread_mutex_t *data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param)
{
pthread_mutex_lock(data1Lock);
data1Value = 1;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(data2Lock);
return 0;
}
void *funcB(void *param)
{
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(data1Lock);
if (data1Value == 0)
{
pthread_mutex_unlock(data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(data1Lock);
pthread_mutex_lock(data2Lock);
t2 = data2Value;
pthread_mutex_unlock(data2Lock);
if (t2 != (t1 + 1))
{
fprintf(stderr, "Bug found!\\n");
ERROR:
__VERIFIER_error();
;
}
return 0;
}
int main(int argc, char *argv[])
{
int i;
int err;
if (argc != 1)
{
if (argc != 3)
{
fprintf(stderr, "./twostage <param1> <param2>\\n");
exit(-1);
}
else
{
sscanf(argv[1], "%d", &iTThreads);
sscanf(argv[2], "%d", &iRThreads);
}
}
data1Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
data2Lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
if (0 != (err = pthread_mutex_init(data1Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
if (0 != (err = pthread_mutex_init(data2Lock, 0)))
{
fprintf(stderr, "pthread_mutex_init error: %d\\n", err);
exit(-1);
}
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (((-1) + argc) >= 0)) && (i >= 0));
{
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0)))
{
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0)))
{
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iTThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(tPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
for (i = 0; i < iRThreads; i++)
{
__CPROVER_assume((((3 - argc) >= 0) && (i >= 0)) && (((-1) + argc) >= 0));
{
if (0 != (err = pthread_join(rPool[i], 0)))
{
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
}
return 0;
}
void lock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_lock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock)
{
int err;
if (0 != (err = pthread_mutex_unlock(lock)))
{
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 0
|
#include <pthread.h>
size_t const thread_no = 64000000;
char mess[] = "This is a test";
void *message_print(void *ptr){
int error = 0;
int signal_exit = (SIGRTMIN+10);
sigset_t signal_set;
siginfo_t info;
struct timespec timer;
timer.tv_sec = 10;
timer.tv_nsec = 0;
int status;
struct timeval current_time;
int day,usec;
error = pthread_detach(pthread_self());
gettimeofday(¤t_time, 0);
day = (int)current_time.tv_sec;
usec = (int)current_time.tv_usec;
printf("%d.%06d THREAD: [created ] pid %d tid %d\\n",day,usec, getpid(), syscall(SYS_gettid));
sleep(10);
gettimeofday(¤t_time, 0);
day = (int)current_time.tv_sec;
usec = (int)current_time.tv_usec;
printf("%d.%06d THREAD: [sig isn't received] pid %d tid %d\\n",day,usec, getpid(), syscall(SYS_gettid));
pthread_exit(0);
}
struct pthread
{
union
{
void *__padding[24];
};
struct list_head
{
struct list_head *next;
struct list_head *prev;
} list;
pid_t tid;
pid_t pid;
};
int main(void) {
int error = 0;
size_t i = 0;
pthread_t thr, old_thr;
int cancel_status;
struct pthread *pthr;
int kill_status;
sigset_t signal_set;
pthread_t hoge=0;
pthread_mutex_t *lock;
pthread_mutex_t mutex;
int j=0;
int signal_exit = (SIGRTMIN+10);
sigemptyset ( &signal_set );
sigaddset ( &signal_set, signal_exit );
pthread_sigmask ( SIG_BLOCK, &signal_set, 0 );
thr = 0;
mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
lock = &mutex;
for(i = 0; i < thread_no; i++) {
pthread_mutex_lock(lock);
old_thr=thr;
pthread_mutex_unlock(lock);
if((error = pthread_create( &thr, 0, message_print, (void *) mess)) != 0) {
printf("thread creation error no.%d (EAAIN %d) thread num %d\\n",error,EAGAIN,i);
exit(1);
} else {
pthr = (struct pthread *)thr;
printf("thread(%d) creation SUCESS pid %d tid %d\\n",i,pthr->pid, pthr->tid);
}
printf("sizeof pthread t %d struct pthread %d\\n",sizeof(pthread_t), sizeof(struct pthread));
if(i%3==0) {
if((kill_status = pthread_kill(thr, signal_exit)) != 0) {
printf("kill failed status % d;\\n",kill_status);
exit(1);
}
printf("old_thr = %x\\n",old_thr);
if(old_thr != 0) {
kill_status = pthread_kill(old_thr,signal_exit );
printf(" send signal \\n", old_thr);
}
}
sleep(1);
}
printf("MAIN: Thread Message: %s\\n", mess);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int n, m;
int *v;
int *e;
int *w;
int *c;
int *f;
int *u;
int mssp;
int work_mssp;
pthread_mutex_t lock_c = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock_work_mssp = PTHREAD_MUTEX_INITIALIZER;
int min(int a, int b) {
if (a > b)
return b;
else
return a;
}
void parallel_do(void *(*start_routine)(void *), int n) {
pthread_t threads[n];
for (int i = 0; i < n; i++) {
int *arg = malloc(sizeof(int));
*arg = i;
pthread_create(&(threads[i]), 0, start_routine, arg);
}
for (int i = 0; i < n; i++) {
pthread_join(threads[i], 0);
}
}
void *relax_helper(void *arg) {
int i = *((int *) arg);
if (f[i]) {
int start = v[i];
int end = v[i+1];
for (int j = start; j < end; j++) {
int to = e[j];
if (u[to]) {
pthread_mutex_lock(&lock_c);
c[to] = min(c[to], c[i] + w[j]);
pthread_mutex_unlock(&lock_c);
}
}
}
free(arg);
return 0;
}
void relax(void) {
parallel_do(relax_helper, n);
}
void *minimum_helper(void *arg) {
int i = *((int *) arg);
if (!u[i]) {
int start = v[i];
int end = v[i+1];
for (int j = start; j < end; j++) {
int to = e[j];
if (u[to]) {
pthread_mutex_lock(&lock_work_mssp);
work_mssp = min(work_mssp, c[to]);
pthread_mutex_unlock(&lock_work_mssp);
}
}
}
free(arg);
return 0;
}
int minimum(void) {
work_mssp = 32767;
parallel_do(minimum_helper, n);
return work_mssp;
}
void *update_helper(void *arg) {
int i = *((int *) arg);
f[i] = 0;
if (c[i] == mssp) {
u[i] = 0;
f[i] = 1;
}
free(arg);
return 0;
}
void update(void) {
parallel_do(update_helper, n);
}
void init(void) {
for (int i = 0; i < n; i++) {
c[i] = 32767;
f[i] = 0;
u[i] = 1;
}
c[0] = 0;
f[0] = 1;
u[0] = 0;
}
void da2cf(void) {
init();
mssp = 0;
while (1) {
relax();
mssp = minimum();
if (mssp == 32767)
break;
update();
}
}
void print_result(){
for (int i = 0; i < n; i++) {
printf("%d %d\\n", i, c[i]);
}
}
int main(void) {
scan();
da2cf();
print_result();
}
| 0
|
#include <pthread.h>
static pthread_mutex_t log_mutex_lock_ = PTHREAD_MUTEX_INITIALIZER;
static char log_msg_buf_[256];
void ixsys_print_init()
{
}
void ixsys_print(int err_flag, char *format, ...)
{
va_list args;
pthread_mutex_lock(&log_mutex_lock_);
__builtin_va_start((args));
vsprintf(log_msg_buf_, (char*)format, args);
;
if (err_flag)
fprintf(stderr, "%s", log_msg_buf_);
else
printf("%s", log_msg_buf_);
pthread_mutex_unlock(&log_mutex_lock_);
}
void ixsys_print_dump(char *title, uint8_t *data, size_t size)
{
int n;
char str[12], line[80], txt[28];
uint8_t *p;
if (!data || !size)
return;
ixsys_print(0, "[%s|%u]\\n", title, size);
n = 0;
p = data;
line[0] = '\\0';
while ((uint16_t)(p - data) < size) {
sprintf(str, "%02x ", *p);
strcat(line, str);
txt[n++] = ((*p >= 0x20) && (*p < 0x7f)) ? *p : '.';
if (n == 16) {
txt[n] = '\\0';
ixsys_print(0, "%s %s\\n", line, txt);
n = 0;
line[0] = '\\0';
}
++p;
}
if (n) {
txt[n] = '\\0';
do {
strcat(line, " ");
} while (++n < 16);
ixsys_print(0, "%s %s\\n", line, txt);
}
}
| 1
|
#include <pthread.h>
static int ft_fd = -1;
static pthread_mutex_t cmd_mutex;
void ft_send_cmd(const char *fmt, ...)
{
char cmdBuffer[80] = {0,};
va_list args;
pthread_mutex_lock(&cmd_mutex);
__builtin_va_start((args));
vsnprintf(cmdBuffer,sizeof(cmdBuffer),fmt, args);
;
ALOGE("fm_put_cmd: \\"%s\\"\\n", cmdBuffer);
write(ft_fd, cmdBuffer, sizeof(cmdBuffer));
memset(cmdBuffer, 0, sizeof(cmdBuffer));
read(ft_fd, cmdBuffer, sizeof(cmdBuffer));
ALOGE("fm_put_cmd: \\"retval = %s\\"\\n", cmdBuffer);
pthread_mutex_unlock(&cmd_mutex);
return ;
}
void ft_init()
{
char dev[PROPERTY_VALUE_MAX];
ALOGD("ft_init\\n");
do {
property_get("init.svc.ft_svc", dev, "stopped");
sleep(1);
} while(strcmp(dev, "running") == 0);
if (property_set("ctl.start", "ft_svc") < 0) {
ALOGE("Failed to start fm service\\n");
return;
}
do {
property_get("ft_pts_dev", dev, "ondev");
sleep(1);
} while(strcmp(dev, "ondev") == 0);
ALOGE("find device: %s\\n", dev);
ft_fd = open(dev, O_RDWR);
if (ft_fd < 0) {
ALOGE("open device failed.\\n");
}
}
void wifi_drv_load()
{
ft_send_cmd("wifi_drv_load");
}
void wifi_drv_unload()
{
ft_send_cmd("wifi_drv_unload");
}
void wifi_drv_load_wcn36x0()
{
ft_send_cmd("wcn36x0_wifi_drv_load");
}
void wifi_drv_unload_wcn36x0()
{
ft_send_cmd("wcn36x0_wifi_drv_unload");
}
void wifi_connect_ap()
{
ft_send_cmd("wifi_connect_ap");
}
void wifi_tx_test(struct wifi_opt wo)
{
char opt_cmd[100];
sprintf(opt_cmd,"athtestcmd -i wlan0 --tx %s --txfreq %s --txrate %s --%s",
wo.tx,wo.txfreq,wo.txrate,wo.pwr);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
}
void wifi_tx_test_36x0(struct wifi_opt wo)
{
char opt_cmd[100];
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 ftm 1");
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 set_cb %s",wo.set_cb);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 set_channel %s",wo.txfreq);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 ena_chain 2");
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 pwr_cntl_mode %s",wo.pwr_cntl_mode);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 set_txpower %s",wo.pwr);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 set_txrate %s",wo.txrate);
ft_send_cmd("wifi_tx_test %s",opt_cmd);
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 tx 1");
ft_send_cmd("wifi_tx_test %s",opt_cmd);
}
void wifi_tx_test_36x0_stop(struct wifi_opt wo)
{
char opt_cmd[100];
sprintf(opt_cmd,"iwmulticall iwpriv wlan0 tx 0");
ft_send_cmd("wifi_tx_test %s",opt_cmd);
}
void ft_exit()
{
ft_send_cmd("exit");
}
void bt_dev_open()
{
ft_send_cmd("bt_dev_open");
}
void bt_dev_close()
{
ft_send_cmd("bt_dev_close");
}
void bt_tx_test(struct wifi_opt wo)
{
char opt_cmd[100];
sprintf(opt_cmd,"btconfig /dev/smd3 rawcmd 0x3F 0x004 0x05 %s %s %s 0x20 0x00 0x00 0x00 0x00",
wo.txfreq,wo.pwr,wo.tx);
ft_send_cmd("bt_tx_test %s",opt_cmd);
}
void bt_tx_burst(struct wifi_opt wo)
{
char opt_cmd[200];
sprintf(opt_cmd,"btconfig /dev/smd3 rawcmd 0x3F 0x0004 0x04 %s %s %s %s %s 0x04 %s 0x00 0x09 0x01 0x9C 0x35 0xBD 0x9C 0x35 0xBD 0x00 %s %s 0x00",
wo.txfreq,wo.txfreq,wo.txfreq,wo.txfreq,wo.txfreq,wo.pck_type,wo.pck_length1,wo.pck_length2);
ft_send_cmd("bt_tx_test %s",opt_cmd);
}
void bt_tx_test_stop()
{
ft_send_cmd("bt_tx_test_stop");
}
void bt_test_mode()
{
ft_send_cmd("bt_test_mode");
}
void lcd_test()
{
ft_send_cmd("lcd_test");
}
void lcd_test_stop()
{
ft_send_cmd("lcd_stop_test");
}
| 0
|
#include <pthread.h>
struct thermal_sensor_data {
pthread_t thermal_sensor_thread;
pthread_mutex_t thermal_sensor_mutex;
pthread_cond_t thermal_sensor_condition;
int threshold_reached;
int sensor_shutdown;
struct sensor_info *sensor;
};
static void *thermal_sensor_uevent(void *data)
{
int err = 0;
struct sensor_info *sensor = (struct sensor_info *)data;
struct pollfd fds;
int fd;
char uevent[MAX_PATH] = {0};
char buf[MAX_PATH] = {0};
struct thermal_sensor_data *sensor_data = 0;
if (0 == sensor ||
0 == sensor->data) {
msg("%s: unexpected NULL", __func__);
return 0;
}
sensor_data = (struct thermal_sensor_data *) sensor->data;
snprintf(uevent, MAX_PATH, TZ_TYPE, sensor_data->sensor->tzn);
fd = open(uevent, O_RDONLY);
if (fd < 0) {
msg("Unable to open %s to receive notifications.\\n", uevent);
return 0;
};
while (!sensor_data->sensor_shutdown) {
fds.fd = fd;
fds.events = POLLERR|POLLPRI;
fds.revents = 0;
err = poll(&fds, 1, -1);
if (err == -1) {
msg("Error in uevent poll.\\n");
break;
}
read(fd, buf, sizeof(buf));
lseek(fd, 0, 0);
dbgmsg("thermal sensor uevent :%s", buf);
pthread_mutex_lock(&(sensor_data->thermal_sensor_mutex));
sensor_data->threshold_reached = 1;
pthread_cond_broadcast(&(sensor_data->thermal_sensor_condition));
pthread_mutex_unlock(&(sensor_data->thermal_sensor_mutex));
}
close(fd);
return 0;
}
void thermal_sensor_interrupt_wait(struct sensor_info *sensor)
{
struct thermal_sensor_data *sensor_data;
if (0 == sensor ||
0 == sensor->data) {
msg("%s: unexpected NULL", __func__);
return;
}
sensor_data = (struct thermal_sensor_data *) sensor->data;
if (sensor->interrupt_enable) {
pthread_mutex_lock(&(sensor_data->thermal_sensor_mutex));
while (!sensor_data->threshold_reached) {
pthread_cond_wait(&(sensor_data->thermal_sensor_condition),
&(sensor_data->thermal_sensor_mutex));
}
sensor_data->threshold_reached = 0;
pthread_mutex_unlock(&(sensor_data->thermal_sensor_mutex));
}
}
int thermal_sensor_setup(struct sensor_info *sensor)
{
int fd = -1;
int sensor_count = 0;
int tzn = 0;
char name[MAX_PATH] = {0};
struct thermal_sensor_data *sensor_data = 0;
if (sensor == 0) {
msg("thermal_sensor_tz:unexpected NULL");
return 0;
}
tzn = get_tzn(sensor->name);
if (tzn < 0) {
msg("No thermal zone device found in the kernel for sensor %s\\n", sensor->name);
return sensor_count;
}
sensor->tzn = tzn;
snprintf(name, MAX_PATH, TZ_TEMP, sensor->tzn);
fd = open(name, O_RDONLY);
if (fd < 0) {
msg("%s: Error opening %s\\n", __func__, name);
return sensor_count;
}
sensor_data = (struct thermal_sensor_data *) malloc(sizeof(struct thermal_sensor_data));
if (0 == sensor_data) {
msg("%s: malloc failed", __func__);
close(fd);
return sensor_count;
}
memset(sensor_data, 0, sizeof(struct thermal_sensor_data));
sensor->data = (void *) sensor_data;
sensor->fd = fd;
sensor_count++;
pthread_mutex_init(&(sensor_data->thermal_sensor_mutex), 0);
pthread_cond_init(&(sensor_data->thermal_sensor_condition), 0);
sensor_data->sensor_shutdown = 0;
sensor_data->threshold_reached = 0;
sensor_data->sensor = sensor;
if (sensor->interrupt_enable) {
pthread_create(&(sensor_data->thermal_sensor_thread), 0,
thermal_sensor_uevent, sensor);
}
return sensor_count;
}
int thermal_sensor_get_temperature(struct sensor_info *sensor)
{
char buf[10] = {0};
int temp = 0;
if (0 == sensor) {
msg("%s: unexpected NULL", __func__);
return 0;
}
if (read(sensor->fd, buf, sizeof(buf)) != -1)
temp = atoi(buf);
lseek(sensor->fd, 0, 0);
return temp;
}
void thermal_sensor_shutdown(struct sensor_info *sensor)
{
struct thermal_sensor_data *sensor_data;
if (0 == sensor ||
0 == sensor->data) {
msg("%s: unexpected NULL", __func__);
return;
}
sensor_data = (struct thermal_sensor_data *) sensor->data;
sensor_data->sensor_shutdown = 1;
if (sensor->fd > -1)
close(sensor->fd);
if (sensor->interrupt_enable)
pthread_join(sensor_data->thermal_sensor_thread, 0);
free(sensor_data);
}
| 1
|
#include <pthread.h>
int q_main,flag_main;
pthread_mutex_t mtx_main;
pthread_mutex_t cond_main;
int q_roll, flag_roll;
pthread_mutex_t mtx_roll;
pthread_mutex_t cond_roll;
int q_pass, flag_pass;
pthread_mutex_t mtx_pass;
pthread_mutex_t cond_pass;
int wait_pas = 0;
void *passenger();
void *roller_coaster();
int main(int argc, char *argv[]) {
int check, k, i;
int number;
char command[10];
pthread_t p_rc, *p_pass;
k = 0;
q_main = 0;
flag_main = 0;
pthread_mutex_init(&mtx_main,0);
pthread_mutex_init(&cond_main, 0);
pthread_mutex_lock(&cond_main);
q_roll = 0;
flag_roll = 0;
pthread_mutex_init(&mtx_roll,0);
pthread_mutex_init(&cond_roll, 0);
pthread_mutex_lock(&cond_roll);
q_pass = 0;
flag_pass = 0;
pthread_mutex_init(&mtx_pass,0);
pthread_mutex_init(&cond_pass, 0);
pthread_mutex_lock(&cond_pass);
check = pthread_create(&p_rc, 0, &roller_coaster, 0);
if(check!=0) {
printf("Problem to create roller_coaster thread\\n");
return(7);
}
while(1) {
printf("For new passengers press 'new' and the number of passengers\\n");
printf("Else for exit press 'exit'\\n");
printf("wait_pas: %d\\n",wait_pas);
scanf(" %9s",command);
if(strcmp(command,"new")==0){
scanf("%d",&number);
wait_pas = wait_pas + number;
p_pass = (pthread_t *)malloc(sizeof(pthread_t)*number);
if(p_pass==0){
printf("Problem with memory allocation\\n");
return(2);
}
for(i=0;i<number;i++){
pthread_mutex_lock(&mtx_main);
k++;
check = pthread_create(&p_pass[i], 0, &passenger, &k);
if(check!=0) {
printf("Problem to create %d thread\\n", i);
free(p_pass);
return(7);
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
q_main++;
pthread_mutex_unlock(&mtx_main);
pthread_mutex_lock(&cond_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
free(p_pass);
}
else if(strcmp(command,"exit")==0){
printf("Roller coaster has closed for today!\\n");
break;
}
else{
printf("Try again!\\n");
continue;
}
printf("wait_pas: %d\\n",wait_pas);
pthread_mutex_lock(&mtx_roll);
if(q_roll>0) {
flag_roll ++;
}
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
else{
pthread_mutex_unlock(&mtx_roll);
}
pthread_mutex_lock(&mtx_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
q_main++;
pthread_mutex_unlock(&mtx_main);
pthread_mutex_lock(&cond_main);
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
return (0);
}
void *roller_coaster(){
int i;
int count;
count = 0;
while(1) {
pthread_mutex_lock(&mtx_roll);
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
q_roll++;
pthread_mutex_unlock(&mtx_roll);
pthread_mutex_lock(&cond_roll);
if(flag_roll>0){
flag_roll--;
q_roll--;
pthread_mutex_unlock(&cond_roll);
}
else{
pthread_mutex_unlock(&mtx_roll);
}
while(wait_pas>=10){
printf("The roller coaster is ready for new ride!\\n");
for(i=0; i<10; i++) {
count++;
pthread_mutex_lock(&mtx_pass);
if(q_pass>0) {
flag_pass ++;
}
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
else{
pthread_mutex_unlock(&mtx_pass);
}
}
wait_pas = wait_pas - 10;
sleep(1);
printf("The roller coaster begin!\\n");
sleep(2);
printf("Passengers abord the roller_coaster!\\n");
sleep(1);
}
pthread_mutex_lock(&mtx_main);
if(q_main>0) {
flag_main ++;
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
}
return (0);
}
void *passenger(void *num_p){
int k;
pthread_mutex_lock(&mtx_main);
k = *(int *)(num_p);
if(q_main>0) {
flag_main ++;
}
if(flag_main>0){
flag_main--;
q_main--;
pthread_mutex_unlock(&cond_main);
}
else{
pthread_mutex_unlock(&mtx_main);
}
pthread_mutex_lock(&mtx_pass);
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
q_pass++;
pthread_mutex_unlock(&mtx_pass);
pthread_mutex_lock(&cond_pass);
if(flag_pass>0){
flag_pass--;
q_pass--;
pthread_mutex_unlock(&cond_pass);
}
else{
pthread_mutex_unlock(&mtx_pass);
}
printf("i am passenger %d\\n", k);
return (0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_spinlock_t lock;
pthread_cond_t cond;
pthread_mutex_t mutex_cond;
void exit_handler(void *voidptr) {
int argument = *((int *)voidptr);
}
void* thread_function(void *voidptr) {
int argument = *((int *)voidptr);
pthread_cleanup_push(&exit_handler, &argument);
pid_t tid = syscall(SYS_gettid);
pthread_t id = pthread_self();
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
pthread_spin_trylock(&lock);
pthread_spin_unlock(&lock);
pthread_mutex_lock(&mutex_cond);
pthread_cond_wait(&cond, &mutex_cond);
pthread_mutex_unlock(&mutex_cond);
pthread_cond_signal(&cond);
pthread_cleanup_pop(0);
pthread_exit((void*)0);
}
int main() {
int number[10000];
pthread_t threads[10000];
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex_cond, 0);
pthread_spin_init(&lock, PTHREAD_PROCESS_PRIVATE);
pthread_cond_init(&cond, 0);
for(int i=0; i<10000; i++) {
number[i] = i;
pthread_create(threads+i, 0, &thread_function, number+i);
}
pthread_cond_signal(&cond);
for(int i=0; i<10000; i++)
if(pthread_join(threads[i], 0) != 0)
perror("waiing for thread failed");
pthread_mutex_destroy(&mutex);
pthread_spin_destroy(&lock);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&mutex_cond);
}
| 1
|
#include <pthread.h>
pthread_cond_t empty_slot = PTHREAD_COND_INITIALIZER;
pthread_cond_t avail_item = PTHREAD_COND_INITIALIZER;
pthread_mutex_t buflock = PTHREAD_MUTEX_INITIALIZER;
char buffer[10][12];
int in = 0, out = 0, count = 0;
FILE *inputfile, *outputfile;
pthread_t t[2];
void* producer();
void* consumer();
int main(int argc, char const *argv[])
{
if (argc != 3) {
printf("%s\\n", "Correct usage: $> ./a.out inputfile outputfile");
return 0;
} else {
inputfile = fopen(argv[1], "rb");
outputfile = fopen(argv[2], "wb");
if ((inputfile == 0) && (outputfile == 0)) {
printf("%s\\n", "Error opening files");
return 0;
} else {
pthread_create(&t[0], 0, producer, (void*) 0);
pthread_create(&t[1], 0, consumer, (void*) 1);
pthread_join(t[0], 0); pthread_join(t[1], 0);
printf("Main thread finished\\n");
fclose(inputfile); fclose(outputfile);
pthread_exit(0);
}
}
}
void* producer()
{
char tempbuff[12];
strncpy(tempbuff, "TempBuffer", sizeof(tempbuff));
printf("Hello, I am a producer\\n");
while(1) {
if (fgets(tempbuff, 12, inputfile) != 0) {
pthread_mutex_lock(&buflock);
if(count == 10) {
pthread_cond_wait(&empty_slot, &buflock);
}
strncpy(buffer[in], tempbuff, 12);
count++;
in = (in + 1) % 10;
pthread_cond_signal(&avail_item);
pthread_mutex_unlock(&buflock);
} else {
pthread_exit(0);
}
}
pthread_exit(0);
}
void* consumer()
{
char tempbuff[12];
strncpy(tempbuff, "TempBuffer", sizeof(tempbuff));
printf("Hello, I am a consumer\\n");
while (1) {
pthread_mutex_lock(&buflock);
if(count == 0) {
pthread_cond_wait(&avail_item, &buflock);
}
strncpy(tempbuff, buffer[out], sizeof(tempbuff));
out = (out + 1) % 10;
count--;
pthread_cond_signal(&empty_slot);
pthread_mutex_unlock(&buflock);
fputs(tempbuff, outputfile);
if ((feof(inputfile) != 0) && (count == 0)) {
pthread_exit(0);
}
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static const size_t INITIAL_CAPACITY = 1024;
unsigned int* array;
unsigned int* front;
unsigned int* back;
size_t capacity;
size_t size;
} Sockets;
static Sockets sockets = { 0, 0, 0, 0, 0 };
static pthread_mutex_t m_qaccess;
static pthread_cond_t c_isItem;
static pthread_cond_t c_isSpace;
int ml_safeq_initialize(void)
{
sockets.array = (unsigned int*) malloc (sizeof(unsigned int) * INITIAL_CAPACITY);
sockets.front = sockets.back = sockets.array;
sockets.capacity = INITIAL_CAPACITY;
sockets.size = 0;
if (sockets.array == 0) return (SAFEQ_ERROR);
return (SUCCESS);
}
int ml_safeq_teardown(void)
{
free(sockets.array);
sockets.array = sockets.front = sockets.back = 0;
sockets.capacity = 0;
sockets.size = 0;
return (SUCCESS);
}
int ml_safeq_put(unsigned int socket)
{
pthread_mutex_lock(&m_qaccess);
{
assert(sockets.array != 0);
while (sockets.size == sockets.capacity)
pthread_cond_wait(&c_isSpace, &m_qaccess);
*(sockets.back) = socket;
++(sockets.size);
++(sockets.back);
if (sockets.back == (sockets.array + sockets.capacity))
sockets.back = sockets.array;
pthread_cond_broadcast(&c_isItem);
}
pthread_mutex_unlock(&m_qaccess);
return (SUCCESS);
}
int ml_safeq_get(void)
{
int socket;
pthread_mutex_lock(&m_qaccess);
{
assert(sockets.array != 0);
while(sockets.size == 0)
pthread_cond_wait(&c_isItem, &m_qaccess);
socket = *(sockets.front);
--(sockets.size);
++(sockets.front);
if (sockets.front == (sockets.array + sockets.capacity))
sockets.front = sockets.array;
pthread_cond_signal(&c_isSpace);
}
pthread_mutex_unlock(&m_qaccess);
return socket;
}
| 1
|
#include <pthread.h>
int matrixSize, num, thr;
double matrix[15][15];
double result[1000], sum;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
double calDet(double **matrix, int size) {
if (size == 1)
return matrix[0][0];
int subk;
double result = 0.0;
double **submatrix = (double **)malloc(sizeof(double *) * (size - 1));
for (int i = 0; i < size - 1; i++)
submatrix[i] = (double *)malloc(sizeof(double) * (size - 1));
for (int i = 0; i < size; i++) {
for (int j = 1; j < size; j++) {
for (int k = 0; k < size; k++) {
if (k < i) subk = k;
else if (k > i) subk = k - 1;
else continue;
submatrix[j-1][subk] = matrix[j][k];
}
}
if (i % 2 == 0)
result += matrix[0][i] * calDet(submatrix, size - 1);
else
result -= matrix[0][i] * calDet(submatrix, size - 1);
}
for (int i = 0; i < size - 1; i++)
free(submatrix[i]);
free(submatrix);
return result;
}
void *thread(void *data) {
int n = (long)data;
int subk;
double **submatrix = (double **)malloc(sizeof(double *) * (matrixSize - 1));
for (int i = 0; i < matrixSize - 1; i++)
submatrix[i] = (double *)malloc(sizeof(double) * (matrixSize - 1));
for (int i = n*num; i < (n+1)*num; i++) {
for (int j = 1; j < matrixSize; j++) {
for (int k = 0; k < matrixSize; k++) {
if (k < i) subk = k;
else if (k > i) subk = k - 1;
else continue;
submatrix[j-1][subk] = matrix[j][k];
}
}
if (i % 2 == 0)
result[n] += matrix[0][i] * calDet(submatrix, matrixSize - 1);
else
result[n] -= matrix[0][i] * calDet(submatrix, matrixSize - 1);
}
if(matrixSize-(n+1)*num > 0 && n == thr-1) {
for (int i = (n+1)*num; i < matrixSize; i++) {
for (int j = 1; j < matrixSize; j++) {
for (int k = 0; k < matrixSize; k++) {
if (k < i) subk = k;
else if (k > i) subk = k - 1;
else continue;
submatrix[j-1][subk] = matrix[j][k];
}
}
if (i % 2 == 0)
result[n] += matrix[0][i] * calDet(submatrix, matrixSize - 1);
else
result[n] -= matrix[0][i] * calDet(submatrix, matrixSize - 1);
}
}
pthread_mutex_lock(&mutex);
sum += result[n];
pthread_mutex_unlock(&mutex);
for (int i = 0; i < matrixSize - 1; i++)
free(submatrix[i]);
free(submatrix);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
struct timeval start,end;
matrixSize = atoi(argv[1]);
char *input = argv[2];
thr = atoi(argv[3]);
num = matrixSize / thr;
freopen(input, "r", stdin);
for (int i = 0; i < matrixSize; i++) {
for (int j = 0; j < matrixSize; j++) {
scanf("%lf", &matrix[i][j]);
}
}
pthread_t array[thr];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
sum = 0;
gettimeofday(&start, 0);
for(long i = 0; i < thr; i++) {
pthread_create(&array[i], &attr, thread, (void *)i);
}
for(int i = 0; i < thr; i++) {
pthread_join(array[i], 0);
}
gettimeofday(&end,0);
printf("%.3lf\\n", sum);
double duration = 1000000*(end.tv_sec - start.tv_sec )+end.tv_usec - start.tv_usec;
duration /= 1000000;
printf("It takes %.3fs to get answer.\\n",duration);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void prepare()
{
pthread_mutex_lock(&mutex);
printf("I'm prepare\\n");
}
void parent()
{
pthread_mutex_unlock(&mutex);
printf("I'm parent\\n");
}
void child()
{
pthread_mutex_unlock(&mutex);
printf("I'm child\\n");
}
void *thread_fun(void *arg)
{
sleep(1);
pid_t pid;
pthread_atfork(prepare, parent, child);
pid = fork();
if(pid==0)
{
pthread_mutex_lock(&mutex);
printf("child process\\n");
pthread_mutex_unlock(&mutex);
}
if(pid>0)
{
pthread_mutex_lock(&mutex);
printf("parent process\\n");
pthread_mutex_unlock(&mutex);
}
}
int main()
{
pthread_t tid;
if(pthread_create(&tid, 0, thread_fun, 0))
{
printf("create new thread failed\\n");
return;
}
pthread_mutex_lock(&mutex);
sleep(2);
printf("main\\n");
pthread_mutex_unlock(&mutex);
pthread_join(tid, 0);
pthread_mutex_destroy(&mutex);
return;
}
| 1
|
#include <pthread.h>
pthread_mutex_t regiao_critica = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t buffer_cheio = PTHREAD_COND_INITIALIZER;
pthread_cond_t buffer_vazio = PTHREAD_COND_INITIALIZER;
int posicoes_ocupadas=0;
int valor=0;
int buffer[50];
void *produtor(void *argumentos){
while (1){
pthread_mutex_lock(®iao_critica);
if (posicoes_ocupadas==50){
printf("!!! Produtor Esperando !!!\\n");
pthread_cond_wait(&buffer_cheio, ®iao_critica);
}
buffer[posicoes_ocupadas] = valor;
printf("Valor produzido: %d\\n", buffer[posicoes_ocupadas]);
valor++;
posicoes_ocupadas++;
if (posicoes_ocupadas==1){
pthread_cond_signal(&buffer_vazio);
}
pthread_mutex_unlock(®iao_critica);
}
pthread_exit(0);
}
void *consumidor(void *argumentos){
int leitura;
while(1){
pthread_mutex_lock(®iao_critica);
if (posicoes_ocupadas==0){
printf("!!! Consumidor Esperando !!!\\n");
pthread_cond_wait(&buffer_vazio,®iao_critica);
}
leitura = buffer[posicoes_ocupadas];
printf("Valor lido: %d\\n", leitura);
posicoes_ocupadas--;
if (posicoes_ocupadas== 50 -1){
pthread_cond_signal(&buffer_cheio);
}
pthread_mutex_unlock(®iao_critica);
}
pthread_exit(0);
}
int main (){
pthread_t thread_produtor;
pthread_t thread_consumidor;
pthread_create(&thread_produtor, 0, produtor, 0);
pthread_create(&thread_consumidor, 0, consumidor, 0);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
enum estados_signo{VACIO,MUJERES,HOMBRES};
enum estados_signo signo = VACIO;
enum generos{MUJER,HOMBRE};
sem_t capbano_sem, espmujeres_sem, esphombres_sem;
pthread_mutex_t mujespc_mutex, homespc_mutex, persc_mutex,signo_mutex;
int mujespc,homespc,persc;
void *persona(void* args);
int main(){
int i,*num;
srand(time(0));
sem_init(&capbano_sem,0,5);
sem_init(&espmujeres_sem,0,0);
sem_init(&esphombres_sem,0,0);
pthread_mutex_init(&mujespc_mutex,0);
pthread_mutex_init(&homespc_mutex,0);
pthread_mutex_init(&persc_mutex,0);
pthread_mutex_init(&signo_mutex,0);
mujespc = 0;
homespc = 0;
persc = 0;
pthread_t personas[15];
for(i = 0;i < 15;i++){
num = (int*)malloc(sizeof(int));
*num = i;
pthread_create(&personas[i],0,persona,(void*)num);
}
for(i = 0;i < 15;i++){
pthread_join(personas[i],0);
}
return 0;
}
void *persona(void* args){
sleep(rand()%5);
int i;
enum generos genero = rand()%2;
while(1){
pthread_mutex_lock(&signo_mutex);
if((signo == VACIO) || (signo == genero+1)){
signo = genero+1;
pthread_mutex_unlock(&signo_mutex);
sem_wait(&capbano_sem);
pthread_mutex_lock(&persc_mutex);
persc++;
pthread_mutex_unlock(&persc_mutex);
switch(genero){
case MUJER:
printf("MUJER EN EL BANO\\n");
break;
case HOMBRE:
printf("HOMBRE EN EL BANO\\n");
break;
}
sleep(rand()%10+1);
sem_post(&capbano_sem);
pthread_mutex_lock(&persc_mutex);
persc--;
if(!persc){
pthread_mutex_unlock(&persc_mutex);
pthread_mutex_lock(&signo_mutex);
signo = VACIO;
pthread_mutex_unlock(&signo_mutex);
switch(genero){
case MUJER:
printf("ULTIMA MUJER EN EL BANO\\n");
pthread_mutex_lock(&homespc_mutex);
for(i = 0;i < homespc;i++) sem_post(&esphombres_sem);
pthread_mutex_unlock(&homespc_mutex);
break;
case HOMBRE:
printf("ULTIMO HOMBRE EN EL BANO\\n");
pthread_mutex_lock(&mujespc_mutex);
for(i = 0;i < mujespc;i++) sem_post(&espmujeres_sem);
pthread_mutex_unlock(&mujespc_mutex);
break;
}
}else{
pthread_mutex_unlock(&persc_mutex);
}
printf("Me voy!\\n");
pthread_exit(0);
}else{
pthread_mutex_unlock(&signo_mutex);
switch(genero){
case MUJER:
pthread_mutex_lock(&mujespc_mutex);
mujespc++;
pthread_mutex_unlock(&mujespc_mutex);
sem_wait(&espmujeres_sem);
pthread_mutex_lock(&mujespc_mutex);
mujespc--;
pthread_mutex_unlock(&mujespc_mutex);
break;
case HOMBRE:
pthread_mutex_lock(&homespc_mutex);
homespc++;
pthread_mutex_unlock(&homespc_mutex);
sem_wait(&esphombres_sem);
pthread_mutex_lock(&homespc_mutex);
homespc--;
pthread_mutex_unlock(&homespc_mutex);
break;
}
}
}
}
| 1
|
#include <pthread.h>
struct rs_mutex {
pthread_mutex_t mutex;
pthread_mutexattr_t attr;
};
struct rs_mutex *rs_mutex_alloc() {
struct rs_mutex *rmtx = (struct rs_mutex *) malloc(sizeof(struct rs_mutex));
if (rmtx == 0) return 0;
if (pthread_mutexattr_init(&rmtx->attr)) {
free(rmtx);
return 0;
}
if (pthread_mutexattr_settype(&rmtx->attr, PTHREAD_MUTEX_RECURSIVE)) {
pthread_mutexattr_destroy(&rmtx->attr);
free(rmtx);
return 0;
}
if (pthread_mutex_init(&rmtx->mutex, &rmtx->attr)) {
pthread_mutexattr_destroy(&rmtx->attr);
free(rmtx);
return 0;
}
return rmtx;
}
void rs_mutex_acquire(struct rs_mutex *rmtx) {
pthread_mutex_lock(&rmtx->mutex);
}
void rs_mutex_release(struct rs_mutex *rmtx) {
pthread_mutex_unlock(&rmtx->mutex);
}
void rs_mutex_free(struct rs_mutex *rmtx) {
pthread_mutexattr_destroy(&rmtx->attr);
pthread_mutex_destroy(&rmtx->mutex);
free(rmtx);
}
| 0
|
#include <pthread.h>
void do_one_thing(int *);
void do_another_thing(int *);
void do_wrap_up(int, int);
int r1 = 0, r2 = 0, r3 = 0;
pthread_mutex_t r3_mutex=PTHREAD_MUTEX_INITIALIZER;
extern int
main(int argc, char **argv)
{
pthread_t thread1, thread2;
if (argc > 1)
r3 = atoi(argv[1]);
if (pthread_create(&thread1,
0,
(void *) do_one_thing,
(void *) &r1) != 0)
perror("pthread_create"),exit(1);
if (pthread_create(&thread2,
0,
(void *) do_another_thing,
(void *) &r2) != 0)
perror("pthread_create"),exit(1);
if (pthread_join(thread1, 0) != 0)
perror("pthread_join"), exit(1);
if (pthread_join(thread2, 0) != 0)
perror("pthread_join"), exit(1);
do_wrap_up(r1, r2);
return 0;
}
void do_one_thing(int *pnum_times)
{
int i, j, x;
pthread_mutex_lock(&r3_mutex);
if(r3 > 0) {
x = r3;
r3--;
} else {
x = 1;
}
pthread_mutex_unlock(&r3_mutex);
for (i = 0; i < 4; i++) {
printf("doing one thing\\n");
for (j = 0; j < 100000; j++) x = x + i;
(*pnum_times)++;
}
}
void do_another_thing(int *pnum_times)
{
int i, j, x;
pthread_mutex_lock(&r3_mutex);
if(r3 > 0) {
x = r3;
r3--;
} else {
x = 1;
}
pthread_mutex_unlock(&r3_mutex);
for (i = 0; i < 4; i++) {
printf("doing another \\n");
for (j = 0; j < 100000; j++) x = x + i;
(*pnum_times)++;
}
}
void do_wrap_up(int one_times, int another_times)
{
int total;
total = one_times + another_times;
printf("All done, one thing %d, another %d for a total of %d\\n",
one_times, another_times, total);
}
| 1
|
#include <pthread.h>
pthread_mutex_t queueMutex;
pthread_mutex_t secOneMutex;
pthread_mutex_t secTwoMutex;
pthread_mutex_t secThreeMutex;
sem_t removeAlarm;
int ID_BASE = 100;
int first_Section[20];
int firstSecCounter = 0;
int second_Section[20];
int third_Section[20];
int GS_front = -1, RS_front = -1, EE_front = -1;
int GS_rear = -1, RS_rear = -1, EE_rear = -1;
time_t startTime;
struct Student_struct{
int id;
studentType type;
int time_in_Queue;
int section_pref;
int max_wait_time;
int arrival_time;
}; typedef struct Student_struct Student;
struct info* Students;
Student remove_from_Queue(Student *queue, int *front, int *rear);
void add_to_Queue(Student s, Student *queue, int *front, int *rear);
Student GS_students[75];
Student RS_students[75];
Student EE_students[75];
void enroll(Student *potentialStudent)
{
if(potentialStudent->type == GS)
{
add_to_Queue(*potentialStudent, GS_students, &GS_front, &GS_rear);
if(GS_rear == GS_front)
{
remove_from_Queue(GS_students, &GS_front, &GS_rear);
sleep(rand()*2);
}
}
pthread_mutex_lock(&secOneMutex);
if(potentialStudent->section_pref == 1)
{
if ((sizeof(first_Section) / 4) <= 20)
{
first_Section[firstSecCounter] = potentialStudent->id;
firstSecCounter++;
}
}
pthread_mutex_unlock(&secOneMutex);
}
void *student(void *param)
{
Student potentialStudent;
potentialStudent.id = *((int *)param);
potentialStudent.section_pref = rand() % 3;
potentialStudent.max_wait_time = 10;
int wakeUpTime = rand() % 120;
sleep(wakeUpTime);
time_t now;
time(&now);
potentialStudent.arrival_time = now;
enroll(&potentialStudent);
return 0;
}
void *stopwatch(void *param)
{
time(&startTime);
sleep(120);
return 0;
}
int main()
{
int id = 0;
pthread_t stopWatchId;
pthread_attr_t stopWatchAttr;
pthread_attr_init(&stopWatchAttr);
pthread_create(&stopWatchId, &stopWatchAttr, stopwatch, &id);
int threadId[75];
int i;
for (i = 0; i<1; i++)
{
threadId[i] = ID_BASE + i;
pthread_t testThreadId;
pthread_attr_t testThreadAttr;
pthread_attr_init(&testThreadAttr);
pthread_create(&testThreadId, &testThreadAttr, student, &threadId[i]);
}
pthread_join(stopWatchId, 0);
return 0;
}
void add_to_Queue(Student s, Student *queue, int *front, int *rear)
{
pthread_mutex_lock(&queueMutex);
if (*rear == sizeof(GS_students)/12 - 1){
printf("\\n Queue is Full!");
return;
}
if (*front == -1){
*front = 0;
}
*rear = *rear + 1;
queue[*rear] = s;
pthread_mutex_unlock(&queueMutex);
}
Student remove_from_Queue(Student *queue, int *front, int *rear)
{
pthread_mutex_lock(&queueMutex);
Student removed;
if (*front == -1 || *front == *rear + 1){
printf("Queue is empty \\n");
return;
}
removed = queue[*front];
pthread_mutex_unlock(&queueMutex);
return removed;
}
void display(){
}
| 0
|
#include <pthread.h>
void synchronize (int total_threads)
{
static pthread_mutex_t mutex
= PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t condvar_in
= PTHREAD_COND_INITIALIZER;
static pthread_cond_t condvar_out
= PTHREAD_COND_INITIALIZER;
static int threads_in = 0;
static int threads_out = 0;
pthread_mutex_lock (&mutex);
threads_in++;
if (threads_in >= total_threads)
{
threads_out = 0;
pthread_cond_broadcast (&condvar_in);
}
else
{
while (threads_in < total_threads)
{
pthread_cond_wait (&condvar_in, &mutex);
}
}
threads_out++;
if (threads_out >= total_threads)
{
threads_in = 0;
pthread_cond_broadcast (&condvar_out);
}
else
{
while (threads_out < total_threads)
{
pthread_cond_wait (&condvar_out, &mutex);
}
}
pthread_mutex_unlock (&mutex);
}
| 1
|
#include <pthread.h>
void RowSwitch_pthread(int **A, int row);
void *FindMax(void *thr_arg);
void RowSwitch_sequential(int **A, int row);
void PrintArray(int **A);
struct thread_data {
int st;
int ed;
int column_num;
};
struct thread_data thread_data_array[2];
uint64_t time_findmaxp = 0;
uint64_t time_findmaxs = 0;
int maxrow= 0;
pthread_t pthrd_id[2];
pthread_mutex_t mutexcomp;
int **A;
void main()
{
int i, j;
A = (int **) malloc (32768 * sizeof(int *));
for ( i = 0; i < 32768; i++ )
A[i] = (int *) malloc (32768 * sizeof(int));
srand(3);
for ( i = 0; i < 32768; i++ )
for ( j = 0; j < 32768; j++ )
A[i][j] = rand()%100 - 50;
for (i = 0; i < 32768 -1; i++ )
RowSwitch_pthread( A, i );
printf("Time elapsed to find all pivots in entire matrix with pthread is %15llu ns\\n", (long long unsigned)time_findmaxp);
for ( i = 0; i < 32768; i++ )
for ( j = 0; j < 32768; j++ )
A[i][j] = rand()%100 - 50;
for (i = 0; i < 32768 -1; i++ )
RowSwitch_sequential( A, i );
printf("Time elapsed to find all pivots in entire matrix without pthread is %15llu ns\\n", (long long unsigned)time_findmaxs);
for ( i = 0; i < 32768; i++ )
free(A[i]);
free(A);
return;
}
void *FindMax(void *thr_arg) {
int i, j;
int max_row_num;
struct thread_data *thr_data;
thr_data = (struct thread_data *) thr_arg;
max_row_num = thr_data->st;
for (i = thr_data->st; i <= thr_data->ed; i++)
if ( abs(A[i][thr_data->column_num]) > abs(A[max_row_num][thr_data->column_num]) )
max_row_num = i;
pthread_mutex_lock (&mutexcomp);
if ( abs(A[max_row_num][thr_data->column_num]) > abs(A[maxrow][thr_data->column_num]) )
maxrow = max_row_num;
pthread_mutex_unlock (&mutexcomp);
pthread_exit(0);
}
void RowSwitch_pthread(int **A, int row) {
int i;
int thread_num = 2;
int max_row_num;
void *status;
int temp;
while ((32768 -row)/thread_num < 2)
thread_num = thread_num-1;
pthread_attr_t attr;
uint64_t diff;
struct timespec start, end;
maxrow = row;
pthread_mutex_init(&mutexcomp, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
clock_gettime(CLOCK_MONOTONIC, &start);
for ( i = 0; i < thread_num; i++ ) {
thread_data_array[i].st = row + i * (32768 -row)/thread_num;
thread_data_array[i].ed = thread_data_array[i].st + (32768 -row)/thread_num -1;
if ( i >= thread_num - (32768 -row)%thread_num )
thread_data_array[i].ed = thread_data_array[i].ed + 1;
thread_data_array[i].column_num = row;
int err = pthread_create(&pthrd_id[i], &attr, FindMax, (void *) &thread_data_array[i]);
}
pthread_attr_destroy(&attr);
for(i = 0; i < thread_num; i++)
{
pthread_join(pthrd_id[i], &status);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
time_findmaxp = time_findmaxp + diff;
pthread_mutex_destroy(&mutexcomp);
if ( row != maxrow )
for ( i = 0; i < 32768; i++ ) {
temp = A[row][i];
A[row][i] = A[maxrow][i];
A[maxrow][i] = temp;
}
return;
}
void RowSwitch_sequential(int **A, int row) {
int i = 0;
int max_row_num = row;
int temp;
uint64_t diff;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
for ( i = row; i < 32768; i++ )
if ( abs(A[i][row]) > abs(A[max_row_num][row]) )
max_row_num = i;
clock_gettime(CLOCK_MONOTONIC, &end);
diff = 1000000000L * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
time_findmaxs = time_findmaxs + diff;
if (row != max_row_num )
for ( i = 0; i < 32768; i++ ) {
temp = A[row][i];
A[row][i] = A[max_row_num][i];
A[max_row_num][i] = temp;
}
return;
}
void PrintArray(int **A)
{
int i,j;
for ( i = 0; i < 32768; i++ ) {
for ( j = 0; j < 32768; j++ )
printf ("%3d ", A[i][j]);
printf("\\n");
}
printf("\\n");
return;
}
| 0
|
#include <pthread.h>
pthread_t gRubyThread;
pthread_mutex_t gMainLock;
pthread_cond_t gRubyDone;
void* the_ruby_thread(void* aRubyProgram)
{
printf("Ruby thread is starting interpreter\\n");
ruby_run_node(aRubyProgram);
printf("Ruby thread is done, waking up C program...\\n");
pthread_mutex_lock(&gMainLock);
pthread_cond_signal(&gRubyDone);
pthread_mutex_unlock(&gMainLock);
pthread_exit(0);
}
void the_c_program()
{
char* file = "hello.rb";
int fake_argc = 2;
char* fake_args[fake_argc];
fake_args[0] = "ruby";
fake_args[1] = file;
char** fake_argv = fake_args;
printf("C program is calling ruby_sysinit()\\n");
ruby_sysinit(&fake_argc, &fake_argv);
printf("C program is calling RUBY_INIT_STACK()\\n");
RUBY_INIT_STACK;
printf("C program is calling ruby_init()\\n");
ruby_init();
rb_evalstring("puts \\"Boy\\"");
printf("C program is calling ruby_init_loadpath()\\n");
ruby_init_loadpath();
printf("C program is loading file: %s\\n", file);
void* rubyProgram = ruby_options(fake_argc, fake_argv);
pthread_mutex_init(&gMainLock, 0);
pthread_cond_init(&gRubyDone, 0);
pthread_create(&gRubyThread, 0,
the_ruby_thread, rubyProgram);
printf("C program is putting Ruby thread in control...\\n");
pthread_mutex_lock(&gMainLock);
pthread_cond_wait(&gRubyDone, &gMainLock);
pthread_mutex_unlock(&gMainLock);
printf("C program is back in control, exiting...\\n");
pthread_mutex_destroy(&gMainLock);
pthread_cond_destroy(&gRubyDone);
pthread_exit(0);
}
int main(int argc, char** argv)
{
the_c_program();
return 0;
}
| 1
|
#include <pthread.h>
void wrightchanger_nomutex();
void edgeworthchanger_nomutex();
void wrightchanger_mutex();
void edgeworthchanger_mutex();
char *firstname;
char *lastname;
pthread_mutex_t attorneymutex;
int main(int argc, char *argv[]) {
int i;
pthread_t t1,t2;
firstname=malloc(32);
lastname=malloc(32);
printf("The attorney mixer\\n");
printf("Demonstrating the usage of mutexes\\n");
printf("\\nStarting threads WITHOUT mutex usage!!\\n");
pthread_create(&t1, 0,(void*) &wrightchanger_nomutex, 0);
pthread_create(&t2, 0,(void*) &edgeworthchanger_nomutex, 0);
pthread_detach(t1);
pthread_detach(t2);
pthread_abort(t1);
pthread_abort(t2);
printf("\\nNow invoking functions WITH mutex usage!!\\n");
pthread_mutex_init(&attorneymutex, 0);
pthread_create(&t1, 0,(void*) &wrightchanger_mutex, 0);
pthread_create(&t2, 0,(void*) &edgeworthchanger_mutex, 0);
for (i=0; i<20; i++) {
delay(500);
pthread_mutex_lock(&attorneymutex);
printf("attorney: %s %s\\n",firstname,lastname);
pthread_mutex_unlock(&attorneymutex);
}
printf("End program.\\n");
return 0;
}
void wrightchanger_nomutex() {
while (1) {
strcpy(firstname, "Phoenix");
delay(55);
strcpy(lastname, "Wright");
delay(55);
}
}
void edgeworthchanger_nomutex() {
while (1) {
strcpy(firstname, "Miles");
delay(77);
strcpy(lastname, "Edgeworth");
delay(77);
}
}
void wrightchanger_mutex() {
while (1) {
pthread_mutex_lock(&attorneymutex);
strcpy(firstname, "Phoenix");
delay(55);
strcpy(lastname, "Wright");
pthread_mutex_unlock(&attorneymutex);
delay(55);
}
}
void edgeworthchanger_mutex() {
while (1) {
pthread_mutex_lock(&attorneymutex);
strcpy(firstname, "Miles");
delay(77);
strcpy(lastname, "Edgeworth");
pthread_mutex_unlock(&attorneymutex);
delay(77);
}
}
| 0
|
#include <pthread.h>
void *connection_handler(void* socket_desc){
int client_socket = *(int*)socket_desc;
while(1){
uint8_t client_message[2000];
int recv_value;
recv_value = recv(client_socket, client_message, sizeof(client_message),0);
if(recv_value==0){
if(isGameLeader(client_socket)){
pthread_mutex_lock(&mutex_struct.socket_mutex);
for(int i=0;i<4;i++){
if(allsockets.clientSocket[i]!=0){
sendERR(1,"Spielleiter hat das Spiel verlassen.", allsockets.clientSocket[i]);
if(myconfig.send){
debugHexdump("Spielleiter hat das Spiel verlassen.", 3, "C==>S");
}
}
}
pthread_mutex_lock(&mutex_struct.sem_mutex);
mutex_struct.sem++;
pthread_mutex_unlock(&mutex_struct.sem_mutex);
pthread_mutex_unlock(&mutex_struct.socket_mutex);
server_data[0].gameOver=1;
}
pthread_mutex_lock (&mutex_struct.playerlist_mutex);
sortPlayerList(client_socket);
mutex_struct.sem++;
pthread_mutex_unlock (&mutex_struct.playerlist_mutex);
int activePlayers = getPlayerAmount(server_data);
if(server_data[0].gameOver!=1 && activePlayers < 2 && server_data[0].gameRunning==1){
errorPrint("Zu wenig aktive Spieler, das Spiel wird beendet.");
sendERR(1,"Zu wenig aktive Spieler im Spiel, das Spiel wird beendet.", allsockets.clientSocket[0]);
server_data[0].gameOver=1;
}
pthread_mutex_lock (&mutex_struct.playerlist_mutex);
sem_post(&score_semaphore);
pthread_mutex_unlock (&mutex_struct.playerlist_mutex);
if(server_data[0].finPlayers==activePlayers){
infoPrint("Der letzte aktive Spieler hat das Spiel verlassen. Ergebnisse werden ausgewertet.");
sendGOV();
server_data[0].gameOver=1;
}
pthread_exit(0);
}
if(recv_value<0){
errorPrint("Fehler beim Empfangen der Nachrichten im Client-Thread");
server_data[0].gameOver=1;
pthread_exit(0);
}
encodeMessage(client_message, client_socket);
}
}
| 1
|
#include <pthread.h>
int shmd;
long shimid;
key_t key = 66607;
int LEN = 1024;
struct ipcstruct *mystruct;
struct ipcstruct {
int value;
int size;
int cachesending;
int proxysending;
pthread_mutex_t memMutex;
pthread_cond_t cvProxyGo;
pthread_cond_t cvCacheGo;
};
static void _sig_handler(int signo){
if (signo == SIGINT || signo == SIGTERM){
printf("Interrupted\\n");
munmap(mystruct, LEN);
shm_unlink("555");
exit(signo);
}
}
int main(){
if (signal(SIGINT, _sig_handler) == SIG_ERR){
fprintf(stderr,"Can't catch SIGINT...exiting.\\n");
exit(1);
}
if (signal(SIGTERM, _sig_handler) == SIG_ERR){
fprintf(stderr,"Can't catch SIGTERM...exiting.\\n");
exit(1);
}
printf("OK\\n");
char memName[15];
sprintf(memName, "%d", 555);
shmd = shm_open(memName, O_CREAT | O_RDWR, 0666);
printf("File handle is %d\\n", shmd);
ftruncate(shmd, sizeof(struct ipcstruct));
mystruct = (struct ipcstruct *)mmap(0, sizeof(struct ipcstruct),
PROT_READ | PROT_WRITE, MAP_SHARED, shmd, 0);
mystruct->value = 23;
pthread_mutexattr_t mattr;
pthread_mutexattr_init(&mattr);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&(mystruct->memMutex), &mattr);
pthread_condattr_t cond_attr;
pthread_condattr_init(&cond_attr);
pthread_condattr_setpshared(&cond_attr, PTHREAD_PROCESS_SHARED);
pthread_cond_init(&(mystruct->cvProxyGo), &cond_attr);
pthread_cond_init(&(mystruct->cvCacheGo), &cond_attr);
pthread_condattr_destroy(&cond_attr);
mystruct->cachesending = 1;
mystruct->proxysending = 0;
while ( 1 ) {
pthread_mutex_lock(&(mystruct->memMutex));
while( mystruct->cachesending == 1){
printf("Waiting....\\n");
pthread_cond_wait(&(mystruct->cvProxyGo), &(mystruct->memMutex) );
}
printf("We got the lock doing work....\\n");
mystruct->proxysending = 1;
sleep(5);
mystruct->proxysending = 0;
mystruct->cachesending = 1;
pthread_mutex_unlock(&(mystruct->memMutex));
pthread_cond_signal(&(mystruct->cvCacheGo));
}
return 0;
}
| 0
|
#include <pthread.h>
int i;
int acount=0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condVar = PTHREAD_COND_INITIALIZER;
int accessible = 1;
void waitMySemaphor(int amountToWithdraw);
void signalMySemphor();
void *threadClientWithdrawer(void* args);
void *threadClientDeposit(void* args);
void *threadAccount();
void *threadClientWithdrawer(void* args)
{
char* name = (char*) args;
int amountToWithdraw = atoi(name);
int i;
for (i = 0; i< 10; ++i)
{
waitMySemaphor(amountToWithdraw);
if (acount >= amountToWithdraw)
{
printf("%d - %d\\n", acount, amountToWithdraw);
acount -= amountToWithdraw;
}
else
printf("%s : To little in account\\n",name);
int sleepTime = rand()%500;
usleep((sleepTime + 1250) * 1000);
signalMySemphor();
sleepTime = rand()%500;
usleep((sleepTime + 1000) * 1000);
}
printf("%s : end of thread -- acount: %d\\n",name,acount);
}
void *threadClientDeposit(void* args)
{
char* name = (char*) args;
int amountToDeposit = atoi(name);
int i;
for (i = 0; i< 110; ++i)
{
int sleepTime = rand()%500;
usleep((sleepTime + 250) * 1000);
acount += amountToDeposit;
signalMySemphor();
}
printf("%s : end of thread -- acount: %d\\n",name,acount);
}
void *threadAccount()
{
int i;
int oldAcount;
while(1)
{
if (oldAcount != acount)
{
printf("Acount amount: %d\\n",acount);
oldAcount = acount;
}
}
}
void waitMySemaphor(int amountToWithdraw)
{
pthread_mutex_lock(&mutex);
while (accessible == 0 || acount < amountToWithdraw)
pthread_cond_wait(&condVar, &mutex);
accessible = 0;
pthread_mutex_unlock(&mutex);
}
void signalMySemphor()
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&condVar);
accessible = 1;
pthread_mutex_unlock(&mutex);
}
int main(int argc, char* argv[])
{
pthread_t a,b,c,d,e,f,g,h,j;
char* buff1 = (char*) malloc(15);
char* buff2 = (char*) malloc(15);
char* buff3 = (char*) malloc(15);
char* buff4 = (char*) malloc(15);
char* buff5 = (char*) malloc(15);
char* buff6 = (char*) malloc(15);
char* buff7 = (char*) malloc(15);
char* buff8 = (char*) malloc(15);
sprintf(buff1,"10");
sprintf(buff2,"20");
sprintf(buff3,"30");
sprintf(buff4,"40");
sprintf(buff5,"110");
sprintf(buff6,"220");
sprintf(buff7,"330");
sprintf(buff8,"440");
srand(time(0));
pthread_create(&a,0,threadAccount,0);
pthread_create(&b,0,threadClientDeposit,buff1);
pthread_create(&c,0,threadClientDeposit,buff2);
pthread_create(&d,0,threadClientDeposit,buff3);
pthread_create(&e,0,threadClientDeposit,buff4);
pthread_create(&f,0,threadClientWithdrawer,buff5);
pthread_create(&g,0,threadClientWithdrawer,buff6);
pthread_create(&h,0,threadClientWithdrawer,buff7);
pthread_create(&j,0,threadClientWithdrawer,buff8);
pthread_join(a,0);
pthread_join(b,0);
pthread_join(c,0);
pthread_join(d,0);
pthread_join(e,0);
pthread_join(f,0);
pthread_join(g,0);
pthread_join(h,0);
pthread_join(j,0);
}
| 1
|
#include <pthread.h>
void callback(int op, int arg1, int arg2)
{
printf("callback(%d, %d, %d) called\\n", op, arg1, arg2);
}
int ile = 0;
pthread_mutex_t mutex;
void *watek (void *data)
{
pid_t pid = getpid();
pid_t id = pthread_self();
pthread_mutex_lock(&mutex);
ile++;
pthread_mutex_unlock(&mutex);
int r = rand() % 3;
printf ("Jestem %d watek. Moj PID=%d moje ID=%d pojde spac na %ds\\n", ile, pid, id, r);
sleep(r);
printf ("Jestem %d watek. Moj PID=%d moje ID=%d wlasnie sie obudzilem\\n", ile, pid, id);
page_sim_get(id, &ile);
return (void *) ile;
}
int main()
{
srand(time(0));
printf("simple_test is starting\\n");
if(page_sim_init(0, 1, 2, 3, 4, &callback) != -1)
printf("succesfull page_sim_init call\\n");
else
printf("unsuccesfull page_sim_init call\\n");
pthread_t th[10];
pthread_attr_t attr;
int i, wynik;
int blad;
pid_t pid = getpid();
printf("Proces %d tworzy watki\\n", pid);
if ((blad = pthread_attr_init(&attr)) != 0 )
syserr(blad, "attrinit");
if ((blad = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) != 0)
syserr(blad, "setdetach");
for (i = 0; i < 10; i++)
if ((blad = pthread_create(&th[i], &attr, watek, 0)) != 0)
syserr(blad, "create");
sleep(3 + 1);
printf("KONIEC\\n");
if ((blad = pthread_attr_destroy (&attr)) != 0)
syserr(blad, "attrdestroy");
page_sim_end();
return 0;
}
| 0
|
#include <pthread.h>
int value;
int th;
pthread_mutex_t mutex;
}Best;
pthread_mutex_t mutex;
sem_t sem;
int count;
}Barrier;
Barrier barrier;
Best best;
sem_t sem;
void sigfunc(int signo);
void fill_rand(int *vektor, int size, int max, int flag);
void *thFunc(void *arg);
int main(){
signal(SIGUSR1, sigfunc);
int rank[10],i,selected[10 -3];
pthread_t th[10];
best.value = 0;
pthread_mutex_init(&(best.mutex), 0);
pthread_mutex_init(&(barrier.mutex), 0);
sem_init(&sem, 0, 0);
sem_init(&(barrier.sem), 0, 0);
fill_rand(rank, 10, 100, 0);
for(i=0; i<10; i++){
int *j = (int *)malloc(sizeof(int));
*j = rank[i];
pthread_create(&th[i], 0, thFunc, (void *)j);
}
while(1){
printf("\\n");
sleep(2 + (rand() % 3));
fill_rand(selected, 10 -3, 10 -1, 1);
for(i=0; i<10 -3; i++){
pthread_kill(th[selected[i]], SIGUSR1);
}
}
printf("Main exit\\n");
pthread_exit(0);
}
void *thFunc(void *arg){
pthread_detach(pthread_self());
int *rankPtr = (int *)arg;
int rank = *rankPtr;
int bestRank;
int bestTh;
int i;
while(1){
sem_wait(&sem);
while(1){
pthread_mutex_lock(&(best.mutex));
if(best.value < rank){
best.value = rank;
best.th = (int)pthread_self();
}
bestRank = best.value;
bestTh = best.th;
pthread_mutex_unlock(&(best.mutex));
pthread_mutex_lock(&(barrier.mutex));
barrier.count++;
if(barrier.count == 10 -3){
printf("Thread %d rank = %d, Best rank = %d Best Th = %d\\n", (int)pthread_self(), rank, bestRank, bestTh);
barrier.count = 0;
bestRank = 0;
bestTh = 0;
best.th = 0;
best.value = 0;
for(i=0; i<10 -3; i++)
sem_post(&(barrier.sem));
sem_wait(&(barrier.sem));
pthread_mutex_unlock(&(barrier.mutex));
break;
}
else{
pthread_mutex_unlock(&(barrier.mutex));
sem_wait(&(barrier.sem));
break;
}
}
}
}
void fill_rand(int *vektor, int size, int max, int flag){
int in=0, im=0, i=0;
srand(time(0));
im = 0;
for (in = 0; in < max && im < size; ++in) {
int rn = max - in;
int rm = size - im;
if (rand() % rn < rm){
if(flag == 0){
vektor[im++] = in + 1;
}
else{
vektor[im++] = in;
}
}
}
for (i = 0; i < size; i++) {
int temp = vektor[i];
int randomIndex = rand() % size;
vektor[i] = vektor[randomIndex];
vektor[randomIndex] = temp;
}
return;
}
void sigfunc(int signo){
sem_post(&sem);
}
| 1
|
#include <pthread.h>
static double a[1024][1024];
static double b[1024][1024];
static double c[1024][1024];
pthread_mutex_t locks[1024][1024];
pthread_t threads[8];
static void
init_matrix(void)
{
int i, j;
for (i = 0; i < 1024; i++)
for (j = 0; j < 1024; j++) {
a[i][j] = 1.0;
b[i][j] = 1.0;
c[i][j] = 0.0;
}
}
struct matmul_par_block_calc_args {
int k;
int j;
};
static void matmul_par_block_calc(void* data){
struct matmul_par_block_calc_args* args = (struct matmul_par_block_calc_args*) data;
int kk, jj;
int i;
int k = args->k;
int j = args->j;
free(data);
for (i = 0; i < 1024; ++i){
for (jj = j; jj < (((j + 256) < (1024)) ? (j + 256) : (1024)); ++jj){
for (kk = k; kk < (((k + 512) < (1024)) ? (k + 512) : (1024)); ++kk){
pthread_mutex_lock(&locks[i][jj]);
c[i][jj] += a[i][kk] * b[kk][jj];
pthread_mutex_unlock(&locks[i][jj]);
}
}
}
}
static void
matmul_par_block()
{
int j, k;
int ti = 0;
for (k = 0; k < 1024; k += 512){
for (j = 0; j < 1024; j += 256){
struct matmul_par_block_calc_args* args = malloc(sizeof(struct matmul_par_block_calc_args));
args->k = k;
args->j = j;
pthread_create(&threads[ti], 0, (void*) matmul_par_block_calc, (void*) args);
ti++;
}
}
for (int ti = 0; ti < 8; ti++)
pthread_join(threads[ti], 0);
}
static void
matmul_seq_block()
{
int i, j, k, kk, jj;
for (k = 0; k < 1024; k += 512)
for (j = 0; j < 1024; j += 512)
for (i = 0; i < 1024; ++i)
for (jj = j; jj < (((j + 512) < (1024)) ? (j + 512) : (1024)); ++jj)
for (kk = k; kk < (((k + 512) < (1024)) ? (k + 512) : (1024)); ++kk)
c[i][jj] += a[i][kk] * b[kk][jj];
}
static void
matmul_seq()
{
int i, j, k;
for (i = 0; i < 1024; i++) {
for (j = 0; j < 1024; j++) {
c[i][j] = 0.0;
for (k = 0; k < 1024; k++)
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
static void
print_matrix(void)
{
int i, j;
for (i = 0; i < 1024; i++) {
for (j = 0; j < 1024; j++)
printf(" %7.2f", c[i][j]);
printf("\\n");
}
}
int
main(int argc, char **argv)
{
init_matrix();
if (8 <= 1)
matmul_seq_block();
else
matmul_par_block();
}
| 0
|
#include <pthread.h>
extern pthread_attr_t pthread_attr_default;
pthread_mutex_t lock;
long lmsize = 102400;
unsigned long long ll;
long syscalls = 300;
void sighand(int sig)
{
unsigned long i;
switch(sig){
case SIGDANGER:{
printf("Received sigdanger - System low on paging space!!\\n");
exit(1);
}
default:
printf("Received unknown signal\\n");
}
}
int *tab;
pthread_t t_id;
char* buf;
pthread_mutex_t lock;
long long ll;
long long oll;
} mstruct ;
void* new_thread(void* arg0)
{
long csyscalls = syscalls;
mstruct *ms = (mstruct*) arg0;
long i,j;
long lsizebuf = lmsize;
char* buf = ms->buf;
pid_t t;
char* mybuf;
if ((mybuf = malloc(lsizebuf)) == 0)
{
perror ("malloc");
exit(2);
}
while (1) {
for (i=0;i<1000;i++) {
memcpy(mybuf, buf, lsizebuf);
}
pthread_mutex_lock(&ms->lock);
ms->ll++;
pthread_mutex_unlock(&ms->lock);
}
pthread_exit((void *) 0);
}
void usage(char* argv0)
{
fprintf(stderr,"%s [-m size] [-p count]\\n", argv0);
fprintf(stderr," -m : memory allocated per thread (default 1024000 bytes)\\n");
fprintf(stderr," -c : number of threads (default 8)\\n");
fprintf(stderr," -t : iteration delay in seconds (default 5 sec)\\n");
errno = 0;
}
main(int argc, char **argv)
{
int rval;
struct timeval starttime, endtime;
pthread_t *thread_id;
long *t_id;
long count = 8;
long delay=5;
int debug = 0;
long i;
long long ll;
mstruct* mstab;
char word[256];
extern int optind, opterr;
extern char *optarg;
char scale[10];
while ((word[0] = getopt(argc, argv, "m:c:t:?")) != (char)EOF) {
switch (word[0]) {
case 'm':
sscanf(optarg, "%ld%s", &lmsize, scale);
switch (scale[0]) {
case 'm': ; case 'M' : lmsize*=1024L*1024L; break;
case 'k': ; case 'K' : lmsize*=1024L; break;
case 'g': ; case 'G' : lmsize*=1024L*1024L*1024L; break;
default :;
}
break;
case 't':
delay = atol(optarg);
if (delay == 0) {
usage(argv[0]);
return(-1);
}
break;
case 'c':
count = atol(optarg);
break;
case '?':
usage(argv[0]);
return(0);
default:
usage(argv[0]);
return(-1);
}
}
ll = 0;
signal(SIGDANGER,sighand);
if ((tab = malloc (count*lmsize*sizeof(char))) == 0 ||
(thread_id = malloc (count*sizeof(pthread_t))) == 0 ||
(mstab = malloc (count*sizeof(mstruct))) == 0 ||
(t_id = malloc (count*sizeof(int))) == 0) {
perror ("malloc");
exit (2);
}
pthread_mutex_init(&lock, 0);
for (i = 0; i < count; i++) {
mstab[i].t_id=i;
mstab[i].ll=0;
mstab[i].oll=0;
mstab[i].buf=(char*) ((long)tab+(long)(i*sizeof(char)));
pthread_mutex_init(&mstab[i].lock, 0);
if ((rval = pthread_create(&thread_id[i], 0, new_thread, (char*) &mstab[i]))) {
printf("Bad pthread create routine (%d)\\n", rval);
exit(1);
}
}
while (1)
{
sleep (delay);
ll = 0;
for (i = 0; i < count; i++) {
pthread_mutex_lock(&mstab[i].lock);
if (mstab[i].oll > mstab[i].ll)
{
ll += ~0 - mstab[i].oll + mstab[i].ll;
mstab[i].oll = mstab[i].ll;
} else {
ll += mstab[i].ll - mstab[i].oll;
mstab[i].oll = mstab[i].ll;
}
pthread_mutex_unlock(&mstab[i].lock);
}
printf ("%lld\\n", ll);
}
return 0;
}
| 1
|
#include <pthread.h>
void * taquillas(void *);
void * web(void *);
void * movil(void *);
pthread_mutex_t *mutex_silla;
int* sillas;
int main(int argc, const char * argv[]) {
int i;
mutex_silla = (pthread_mutex_t*)malloc(10*sizeof(pthread_mutex_t));
for (i=0;i<10;++i){
pthread_mutex_init(mutex_silla+i,0);
}
for (i=0;i<10;++i){
*(sillas+i) = 0;
}
int movil_web, total;
movil_web = 4 + 4;
total = 2 + movil_web;
pthread_t * aux;
pthread_t * dispositivos = (pthread_t *) malloc (sizeof(pthread_t) * total);
int indice=0;
for (aux = dispositivos; aux < (dispositivos+4); ++aux) {
printf("--- Creando el Dispositivo Web %d ---\\n", ++indice);
pthread_create(aux, 0, web, (void *) indice);
}
indice = 0;
for (aux = dispositivos; aux < (dispositivos+movil_web); ++aux) {
printf("--- Creando el Dispositivo Movil %d ---\\n", ++indice);
pthread_create(aux, 0, movil, (void *) indice);
}
indice = 0;
for (aux = dispositivos; aux < (dispositivos+total); ++aux) {
printf("--- Creando el Dispositivo Taquilla %d ---\\n", ++indice);
pthread_create(aux, 0, taquillas, (void *) indice);
}
for (aux = dispositivos; aux < (dispositivos+total); ++aux) {
pthread_join(*aux, 0);
}
free(dispositivos);
free(sillas);
free(mutex_silla);
return 0;
};
void * taquillas(void * arg){
int salida=1;
int quieroSilla;
int id = (int) arg;
while(salida==1){
srand(time(0));
quieroSilla = rand() % 10;
pthread_mutex_lock(mutex_silla+quieroSilla);
if(*(sillas+quieroSilla)==0){
*(sillas+quieroSilla)==1;
printf("El Disp Taquilla %d ocupo una silla.",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
}
else{
printf("El Disp Taquilla %d encontro una silla ocupada... Buscando otra silla",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
}
}
}
void * web(void * arg){
int salida=1;
int quieroSilla;
int id = (int) arg;
while(salida==1){
srand(time(0));
quieroSilla = rand() % 10;
pthread_mutex_lock(mutex_silla+quieroSilla);
if(*(sillas+quieroSilla)==0){
*(sillas+quieroSilla)==1;
printf("El Disp Web %d ocupo una silla.",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
salida = 0;
}
else{
printf("El Disp Web %d encontro una silla ocupada... Buscando otra silla",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
}
}
}
void * movil(void * arg){
int salida=1;
int quieroSilla;
int id = (int) arg;
while(salida==1){
srand(time(0));
quieroSilla = rand() % 10;
pthread_mutex_lock(mutex_silla+quieroSilla);
if(*(sillas+quieroSilla)==0){
*(sillas+quieroSilla)==1;
printf("El Disp Movil %d ocupo una silla.",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
salida = 0;
}
else{
printf("El Disp Movil %d encontro una silla ocupada... Buscando otra silla",id);
pthread_mutex_unlock(mutex_silla+quieroSilla);
}
}
}
| 0
|
#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;
int totalproduced = 0;
int producer_shutdown = 0;
void spinit(void)
{
int i;
for(i = 0; i < 1000000; i++)
;
}
void *sigusr1_thread(void *arg)
{
sigset_t intmask;
struct sched_param param;
int policy, sigrec;
sigemptyset(&intmask);
sigaddset(&intmask, SIGUSR1);
pthread_getschedparam(pthread_self(), &policy, ¶m);
fprintf(stderr, "sigusr1_thread entered with policy %d and priority %d\\n",
policy, param.sched_priority);
sigwait(&intmask, &sigrec);
fprintf(stderr, "sigusr1_thread returned from sigwait (sigrec=%d)\\n", sigrec);
pthread_mutex_lock(&slot_lock);
{
producer_shutdown = 1;
pthread_cond_broadcast(&slots);
}
pthread_mutex_unlock(&slot_lock);
return 0;
}
void *producer(void *arg1)
{
int i;
for(i = 1; ; i++) {
spinit();
pthread_mutex_lock(&slot_lock);
{
while ((nslots <= 0) && (!producer_shutdown))
pthread_cond_wait(&slots, &slot_lock);
if(producer_shutdown) {
pthread_mutex_unlock(&slot_lock);
break;
}
nslots--;
}
pthread_mutex_unlock(&slot_lock);
spinit();
put_item(i*i);
pthread_mutex_lock(&item_lock);
{
nitems++;
pthread_cond_signal(&items);
}
pthread_mutex_unlock(&item_lock);
spinit();
totalproduced = i;
}
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;
pthread_t sighandid;
double total;
double tp;
sigset_t set;
pthread_attr_t high_prio_attr;
struct sched_param param;
fprintf(stderr, "Process ID id %ld\\n", (long) getpid());
sleep(5);
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sigprocmask(SIG_BLOCK, &set, 0);
fprintf(stderr, "Signal blocked\\n");
pthread_attr_init(&high_prio_attr);
pthread_attr_getschedparam(&high_prio_attr, ¶m);
param.sched_priority++;
pthread_attr_setschedparam(&high_prio_attr, ¶m);
if(pthread_create(&sighandid, &high_prio_attr, sigusr1_thread, 0))
perror("Could not create consumer");
else 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");
fprintf(stderr, "Producer ID = %ld, Consumer ID = %ld, Sigusr1 = %ld\\n",
(long) prodid, (long) consid, (long) sighandid);
pthread_join(prodid, 0);
pthread_join(consid, 0);
printf("The threads produced the sum %d\\n", sum);
total = 0.0;
tp = (double) totalproduced;
total = tp*(tp+1)*(2*tp+1)/6.0;
if(tp > 1861)
fprintf(stderr, "*** Overflow ocurrs for more than %d items\\n",
1861);
printf("The checksum for %4d items is %1.0f\\n",
totalproduced, total);
exit(0);
}
| 1
|
#include <pthread.h>
{
int lines;
int columns;
int position;
long ** matrix;
pthread_mutex_t MTX;
} matrix_attr;
long SortAndReturnMedian(long * array, int size);
long ** Read(int m, int n);
void Print(long ** matrix, int m, int n);
void CalculateOneLine(matrix_attr * M);
int main()
{
srand((unsigned int)time(0));
matrix_attr M;
printf("Enter matrix size (minimum is 3x3): ");
scanf("%d %d", &M.lines , &M.columns);
if (M.lines < 3 || M.columns < 3)
{
printf("Wrong matrix size, try again: ");
scanf("%d %d", &M.lines , &M.columns);
if (M.lines < 3 || M.columns < 3)
{
printf("OMG..\\n");
return 0;
}
}
printf("Enter matrix\\n");
M.matrix = Read(M.lines, M.columns);
M.position = 0;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
M.MTX = mut;
Print(M.matrix, M.lines, M.columns);
printf("\\n");
int thread_max = 0;
printf("Enter number of max threads: ");
scanf("%d", &thread_max);
if (thread_max <= 0)
return 0;
int MAX_THREADS_NEEDED = M.lines / 2;
int k;
printf("Enter number of filtrations: ");
scanf("%d", &k);
if (k <= 0)
{
printf("Wrong k, try again: ");
scanf("%d", &k);
if (k <= 0)
{
printf("OMG..\\n");
return 0;
}
}
pthread_t ThreadStorage[thread_max];
void * xxx = 0;
for (int i = 0; i < k; i++)
{
if (thread_max >= MAX_THREADS_NEEDED)
{
int MagicVariable = 0;
for (int j = 0; j < MAX_THREADS_NEEDED; j++)
{
M.position = MagicVariable * 2;
int Median = pthread_create(&ThreadStorage[j], 0, (void*)CalculateOneLine, &M);
if (Median != 0)
return 1;
MagicVariable++;
}
for (int j = 0; j < MAX_THREADS_NEEDED; j++)
{
pthread_join(ThreadStorage[j], xxx);
}
}
else
{
int ThreadsRemained = MAX_THREADS_NEEDED;
int MagicVariable = 0;
while (ThreadsRemained > 0) {
for (int j = 0; j < thread_max; j++)
{
M.position = MagicVariable * 2;
int Median = pthread_create(&ThreadStorage[j], 0, (void*)CalculateOneLine, &M);
if (Median != 0)
return 1;
MagicVariable++;
}
for (int j = 0; j < thread_max; j++)
{
pthread_join(ThreadStorage[j], xxx);
}
ThreadsRemained -= thread_max;
}
}
}
Print(M.matrix, M.lines, M.columns);
printf("\\n");
return 0;
}
void CalculateOneLine(matrix_attr * M)
{
pthread_mutex_lock(&M->MTX);
int pos = M->position;
pthread_mutex_unlock(&M->MTX);
int limit_m = M->lines - 2;
int limit_n = M->columns - 2;
for (int i = pos; i < limit_m && i < pos + 3; i++)
{
for (int j = 0; j < limit_n; j++)
{
int k = 0;
long array[9];
for (int x = 0; x < 3; x++)
for (int y = 0; y < 3; y++)
array[k++] = M->matrix[i + x][j + y];
M->matrix[i + 1][j + 1] = SortAndReturnMedian(array, 9);
}
}
}
long SortAndReturnMedian(long * array, int size)
{
for(int i = 0; i < size; i++)
for(int j = size - 1; j > i; j--)
if (array[j - 1] > array[j])
{
array[j - 1] = array[j - 1] ^ array[j];
array[j] = array[j - 1] ^ array[j];
array[j - 1] = array[j] ^ array[j - 1];
}
return size == 9 ? array[4] : array[1];
}
long ** Read(int m, int n)
{
long ** matrix = (long**)malloc(sizeof(long*) * m);
for (int i = 0; i < m; i++)
{
matrix[i] = (long*)malloc(sizeof(long) * n);
}
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
matrix[i][j] = rand() % 2;
}
}
return matrix;
}
void Print(long ** matrix, int m, int n)
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%ld\\t", matrix[i][j]);
}
printf("\\n");
}
}
| 0
|
#include <pthread.h>
struct msg {
int id;
struct msg* next;
};
pthread_cond_t ready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct msg* queue;
void walk() {
struct msg* q = queue;
while (q) {
printf("%d->", q->id);
q = q->next;
}
printf("\\n");
}
void offer(struct msg* item) {
pthread_mutex_lock(&mutex);
item->next = queue;
queue = item;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&ready);
}
struct msg* poll() {
struct msg* item;
pthread_mutex_lock(&mutex);
while (queue == 0) {
pthread_cond_wait(&ready, &mutex);
}
item = queue;
queue = item->next;
pthread_mutex_unlock(&mutex);
return item;
}
void* thread_task(void* arg) {
for (;;) {
struct msg* item = poll();
printf("poll msg: id %d addr %lx\\n", item->id, (unsigned long)item);
free(item);
walk();
sleep(3);
}
}
int main(int argc, char* argv[]) {
pthread_t tid;
pthread_create(&tid, 0, thread_task, (void*)(queue));
long count = 0;
for (;;) {
struct msg* item = (struct msg*)malloc(sizeof(struct msg));
item->id = (++count % 10000);
offer(item);
printf("offer msg: id %d addr %lx\\n", item->id, (unsigned long)item);
walk();
sleep(1);
}
return 0;
}
| 1
|
#include <pthread.h>
{
int data;
struct node *next;
}node_t,*node_p,**node_pp;
node_p head=0;
void alloc_node(node_pp node,int data)
{
*node=(node_p)malloc(sizeof(node_t));
node_p newnode=*node;
newnode->data=data;
newnode->next=0;
}
void init()
{
alloc_node(&head,0);
}
int is_empty()
{
if(head->next==0)
{
return 0;
}
else
return -1;
}
int push_front(node_p head,int data)
{
node_p tmp;
alloc_node(&tmp,data);
if(tmp==0)
{
return -1;
}
tmp->next=head->next;
head->next=tmp;
return 0;
}
void pop_front(node_p head,int *data)
{
if(is_empty()==0)
{
return;
}
node_p tmp=head->next;
*data=tmp->data;
head->next=tmp->next;
free(tmp);
}
void show(node_p head)
{
node_p phead=head->next;
while(phead)
{
printf("%d ",phead->data);
phead=phead->next;
}
printf("\\n");
}
pthread_cond_t cond1;
pthread_mutex_t lock1,lock2,lock3;
void *consumer(void *arg)
{
while(1)
{
pthread_mutex_lock(&lock1);
while(is_empty(head)==0)
{
printf("consumer is not ready!\\n");
pthread_cond_wait(&cond1,&lock1);
printf("consumer is ready!\\n");
}
int data=0;
pop_front(head,&data);
printf("consumer is done...%d\\n",data);
pthread_mutex_unlock(&lock1);
sleep(1);
}
}
void *producter(void *arg)
{
while(1)
{
pthread_mutex_lock(&lock1);
int data=rand()%1234;
push_front(head,data);
pthread_mutex_unlock(&lock1);
printf("producter is done ...%d\\n",data);
sleep(1);
pthread_cond_signal(&cond1);
}
}
int main()
{
init(head);
pthread_t id1,id2,id3,id4;
pthread_cond_init(&cond1,0);
pthread_mutex_init(&lock1,0);
pthread_mutex_init(&lock2,0);
pthread_mutex_init(&lock3,0);
pthread_create(&id1,0,consumer,(void *)1);
pthread_create(&id2,0,producter,(void*)1);
pthread_join(id1,0);
pthread_join(id2,0);
pthread_cond_destroy(&cond1);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
pthread_mutex_destroy(&lock3);
}
| 0
|
#include <pthread.h>
pthread_t pong_thread;
pthread_t ping_thread;
struct thread_arg ta;
void start_pong()
{
int err = pthread_create(&pong_thread, 0, pong_main_thread, &ta);
if (err == -1) {
fprintf(stderr, "Could not create pong_main_thread thread.\\n");
exit(1);
}
}
void start_ping()
{
int err = pthread_create(&ping_thread, 0, ping_main_thread, 0);
if (err == -1) {
fprintf(stderr, "Could not create ping_main_thread thread.\\n");
exit(1);
}
}
int main(int argc, char **argv)
{
pthread_mutex_t cm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ct = PTHREAD_COND_INITIALIZER;
ta.m = cm;
ta.t = ct;
ta.started = 0;
if (argc == 1) {
start_pong();
pthread_mutex_lock(&ta.m);
while (!ta.started) {
pthread_cond_wait(&ta.t, &ta.m);
}
pthread_mutex_unlock(&ta.m);
start_ping();
pthread_join(ping_thread, 0);
pthread_join(pong_thread, 0);
return 0;
} else if (argc == 2 ) {
if (strcmp(argv[1], "pong") == 0) {
start_pong();
pthread_join(pong_thread, 0);
return 0;
} else if (strcmp(argv[1], "ping") == 0) {
start_ping();
pthread_join(ping_thread, 0);
return 0;
} else {
fprintf(stderr,
"Bad paramter."
" Valid names are \\"pong\\" and \\"ping\\".\\n");
return 1;
}
} else {
fprintf(stderr,
"Too many arguments given. None or one expected.\\n");
return 1;
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t shopLock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t customerReady = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberReady = PTHREAD_COND_INITIALIZER;
int waiting_customers = 0;
int wartenummer = 1;
int abgearbeitet = 0;
int chair_count;
struct thread_args {
int thread_count;
int curthread_nr;
};
int irand( int a, int e) {
double r = e - a + 1;
return a + (int)(r * rand()/(32767 +1.0));
}
void *barber(void *targs)
{
while (1) {
pthread_mutex_lock(&shopLock);
if (waiting_customers == 0) {
pthread_mutex_unlock(&shopLock);
sleep(1);
continue;
}
printf("frise: kunde eingetroffen\\n");
waiting_customers--;
abgearbeitet++;
printf("frise: Haarschnitt gegeben: %d\\n", abgearbeitet);
pthread_mutex_unlock(&shopLock);
pthread_cond_signal(&barberReady);
sleep(1);
}
return 0;
}
void *customer(void *targs)
{
struct thread_args *args = (struct thread_args *) targs;
int lokale_wartenummer;
while (1) {
pthread_mutex_lock(&shopLock);
if (waiting_customers > chair_count) {
pthread_mutex_unlock(&shopLock);
sleep(2);
continue;
} else {
lokale_wartenummer = wartenummer;
wartenummer++;
waiting_customers++;
printf("customer: hingesetzt %d\\n", lokale_wartenummer);
pthread_mutex_unlock(&shopLock);
break;
}
}
while (1) {
pthread_mutex_lock(&shopLock);
if (abgearbeitet >= lokale_wartenummer) {
printf("cutomer: neuer Haarschnitt %d\\n", lokale_wartenummer);
break;
}
pthread_mutex_unlock(&shopLock);
sleep(2);
}
pthread_mutex_unlock(&shopLock);
return 0;
}
int main(int argc, char const* argv[])
{
int i;
int frise_cnt, customer_limit;
int threadRet;
pthread_t *customers;
pthread_t *barberThread;
struct thread_args *targs;
srand(time(0));
if (argc != 4) {
printf("Bitte anz. der Friseure, Stühle und Kunden angeben");
exit(1);
}
frise_cnt = atoi(argv[1]);
chair_count = atoi(argv[2]);
customer_limit = atoi(argv[3]);
if (!frise_cnt || !chair_count || !customer_limit) {
printf("Bitte eine sinnvole Anz. aller drei Werte angeben\\n");
}
customers = (pthread_t *) calloc(customer_limit, sizeof(pthread_t));
barberThread = (pthread_t *) malloc(sizeof(pthread_t));
pthread_create(barberThread, 0, barber, 0);
for (i = 0; i < customer_limit; i++) {
targs = (struct thread_args *) malloc(sizeof(struct thread_args));
targs->curthread_nr = i;
targs->thread_count = chair_count;
pthread_create(&customers[i], 0, customer, (void *) targs);
printf("erschuf kunde %d\\n", i);
}
pthread_join(*barberThread, (void **) &threadRet);
for (i = 0; i < chair_count; i++) {
pthread_join(customers[i], (void **) &threadRet);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m_access;
pthread_mutex_t m_read_num;
pthread_mutex_t is_write;
int read_num = 0;
char buf[1024];
void *read_hand(void * arg)
{
pthread_detach(pthread_self());
pthread_mutex_lock( &is_write);
pthread_mutex_unlock( &is_write );
pthread_mutex_lock(&m_read_num);
if( read_num == 0 )
{
pthread_mutex_lock(&m_access );
}
pthread_mutex_unlock(&m_read_num);
pthread_mutex_lock(&m_read_num);
++read_num;
pthread_mutex_unlock(&m_read_num);
printf("a reader start!!\\n");
FILE *fp_rd = fopen("./a.txt","rb");
if( 0 == fp_rd )
{
perror("read error\\n");
exit(-1);
}
char buf_read[1024];
while( memset(buf_read,0,1024),fgets(buf_read,1024,fp_rd) != 0)
{
fputs(buf_read,stdout);
}
sleep(3);
pthread_mutex_lock(&m_read_num);
--read_num;
if( 0 == read_num )
{
pthread_mutex_unlock(&m_access);
}
pthread_mutex_unlock( &m_read_num );
fclose(fp_rd);
}
void *write_hand(void * arg )
{
pthread_detach(pthread_self());
FILE* fp_wr = fopen("./a.txt","a");
pthread_mutex_lock( &is_write );
pthread_mutex_lock( &m_access);
printf("a write start!!\\n");
if( 0 == fp_wr )
{
perror("write error\\n");
exit(-1);
}
char buf[1024];
while(memset(buf,0,1024),fgets(buf,1024,stdin)!=0 )
{
fprintf(fp_wr,"%s",buf);
fflush(fp_wr);
}
sleep(3);
pthread_mutex_unlock( &m_access );
pthread_mutex_unlock( &is_write );
fclose(fp_wr);
}
int main()
{
int i =1 ;
pthread_mutex_init(&m_access,0);
pthread_mutex_init(&m_read_num,0);
pthread_mutex_init(&is_write,0);
srand(getpid());
while(1)
{
if( i % 2 != 0)
{
pthread_t tid;
pthread_create(&tid,0,read_hand,0);
}
else
{
pthread_t tid;
pthread_create(&tid,0,write_hand,0);
sleep(5);
}
++i;
}
pthread_mutex_destroy(&m_access);
pthread_mutex_destroy(&m_read_num);
pthread_mutex_destroy(&is_write);
}
| 1
|
#include <pthread.h>
int val = 0;
pthread_mutex_t m;
void recurse(int arg)
{
int ret = pthread_mutex_lock(&m);
if (ret) {
printf("child: mutex already locked\\n");
return;
}
if (arg) {
val += 1;
recurse(arg - 1);
}
pthread_mutex_unlock(&m);
}
void *child_fn(void *arg)
{
printf("child: recursing\\n");
recurse((int)arg);
printf("child: done\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
printf("TEST: recursive\\n\\n");
pthread_t thread;
pthread_mutexattr_t ma;
pthread_mutexattr_init(&ma);
pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&m, &ma);
printf("main: creating child\\n");
int ret = pthread_create(&thread, 0, child_fn, (void *)42);
if (ret) {
fprintf(stderr, "Error, pthread_create() returned: %d [%s]\\n", ret, strerror(ret));
return 1;
}
printf("main: joining child\\n");
ret = pthread_join(thread, 0);
if (ret) {
printf("Error, pthread_join returned: %d [%s]\\n", ret, strerror(ret));
return 1;
}
printf("main: joined child\\n");
printf("main: locking mutex\\n");
pthread_mutex_unlock(&m);
if (val == 42) {
printf("SUCCESS! Value was %d\\n", val);
} else {
printf("FAIL! Value was %d\\n", val);
}
printf("\\n\\nTEST: error check\\n\\n");
val = 0;
pthread_mutex_destroy(&m);
pthread_mutexattr_settype(&ma, PTHREAD_MUTEX_ERRORCHECK);
pthread_mutex_init(&m, &ma);
printf("main: creating child\\n");
ret = pthread_create(&thread, 0, child_fn, (void *)42);
if (ret) {
fprintf(stderr, "Error, pthread_create() returned: %d [%s]\\n", ret, strerror(ret));
return 1;
}
printf("main: joining child\\n");
ret = pthread_join(thread, 0);
if (ret) {
printf("Error, pthread_join returned: %d [%s]\\n", ret, strerror(ret));
return 1;
}
printf("main: joined child\\n");
printf("main: locking mutex\\n");
pthread_mutex_unlock(&m);
if (val == 1) {
printf("SUCCESS! Value was %d\\n", val);
} else {
printf("FAIL! Value was %d\\n", val);
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond_var;
int chopstick[6]={1};
void pickup_forks(int philosopherNumber){
pthread_mutex_lock(&mutex);
while (!(chopstick[philosopherNumber] && chopstick[(philosopherNumber+1)%5])) {
pthread_cond_wait(&cond_var, &mutex);
printf("The philosopher %d picked up both of the chopsticks.\\n", philosopherNumber);
pthread_mutex_unlock(&mutex);
}
}
void return_forks(int philosopherNumber){
pthread_mutex_lock(&mutex);
chopstick[philosopherNumber]=1;
chopstick[(philosopherNumber+1)%5]=1;
pthread_cond_signal(&cond_var);
printf("The philosopher %d returned both of the chopsticks.\\n", philosopherNumber);
pthread_mutex_unlock(&mutex);
}
void *eating(int philosopherNumber){
printf("The philosopher %d wishes to eat dinner!\\n", philosopherNumber);
pickup_forks(philosopherNumber);
return_forks(philosopherNumber);
pthread_exit(0);
}
void *thinking(int duration, int philosopherNumber){
printf("The philosopher %d is gonna think for a while.\\n", philosopherNumber);
sleep(duration);
eating(philosopherNumber);
}
int main(){
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond_var,0);
srand(time(0));
pthread_t philosopher[6];
for(int i=1; i<6; i++){
pthread_create(&philosopher[i], 0, thinking((rand()%3)+1, i), 0);
pthread_join(philosopher[i],0);
}
return 0;
}
| 1
|
#include <pthread.h>
char coup_tcp[13];
char coup_part[13];
char rdy = 0;
pthread_mutex_t synchro_mutex;
pthread_cond_t synchro_cv;
char * send_plateau_a()
{
static int player = 0;
static int first = 1;
static pthread_t th;
int retour = 0;
if (first)
{
first = 0;
coup_part[0] = 0;
coup_tcp[0] = 0;
pthread_mutex_init(&synchro_mutex, 0);
pthread_cond_init (&synchro_cv, 0);
retour = pthread_create(&th, 0, jouer_radio_VS, 0 );
if (retour != 0)
{
perror(strerror(errno));
exit(1);
}
pthread_mutex_lock(&synchro_mutex);
while (!rdy)
pthread_cond_wait(&synchro_cv, &synchro_mutex);
rdy = 0;
pthread_mutex_unlock(&synchro_mutex);
return string_plat();
}
if (player)
{
pthread_mutex_lock(&synchro_mutex);
while (coup_tcp[0] == 0)
{
pthread_cond_wait(&synchro_cv, &synchro_mutex);
}
strcpy(coup_part, coup_tcp);
coup_tcp[0] = 0;
pthread_cond_signal(&synchro_cv);
rdy = 0;
pthread_mutex_unlock(&synchro_mutex);
}
else
{
pthread_mutex_lock(&synchro_mutex);
send_coup_a();
pthread_cond_signal(&synchro_cv);
rdy = 0;
pthread_mutex_unlock(&synchro_mutex);
}
pthread_mutex_lock(&synchro_mutex);
while (!rdy)
pthread_cond_wait(&synchro_cv, &synchro_mutex);
send_msg_to_diff(coup_part);
rdy = 0;
coup_part[0] = 0;
pthread_mutex_unlock(&synchro_mutex);
player = !player;
return string_plat();
}
void send_coup_a()
{
char * coup = get_best();
strcpy(coup_part, coup);
raz_vote();
}
int process_input_client_gounki_a(char * buff, int descSock, char * address_caller)
{
int set = 1;
setsockopt(descSock, SOL_SOCKET, 13, (void *)&set, sizeof(int));
int retour = 0;
char mess[TAILLE_MAX_TCP];
if (strncmp(buff, "INFO", 4) == 0)
{
format_mess_desc(mess, "Un serveur de jeu Gounki communautaire ou vous affronter une IA !");
send(descSock, mess, strlen(mess), 0);
send(descSock, "VOTE\\r\\n", strlen("VOTE\\r\\n"), 0);
retour = send(descSock, "ENDM\\r\\n", strlen("ENDM\\r\\n"), 0);
if (retour == -1)
{
perror(strerror(errno));
}
return 1;
}
else if (strncmp(buff, "HELP", 4) == 0)
{
if (strncmp(buff + 5, "VOTE", 4) == 0)
{
format_mess_help(mess, "Comande pour participer au jeu VOTE suivit du coup : VOTE a1-b1", "VOTE");
retour = send(descSock, mess, strlen(mess), 0);
if (retour == -1)
{
perror(strerror(errno));
}
return 1;
}
}
else if (strncmp(buff, "VOTE", 4) == 0)
{
receive_vote(buff + 5);
return 1;
}
return 0;
}
int process_input_diffu_gounki_a(char * buf)
{
if (strncmp(buf, "PLAY", 4) == 0)
{
pthread_mutex_lock(&synchro_mutex);
strcpy(coup_tcp, buf + 5);
pthread_cond_broadcast(&synchro_cv);
pthread_mutex_unlock(&synchro_mutex);
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
struct mt
{
int num;
pthread_mutex_t mutex;
pthread_mutexattr_t mutexattr;
};
void sys_err(char *arg) {
perror(arg);
}
int main(int argc, char const *argv[])
{
int fd, i, err;
struct mt *mm;
pid_t pid;
fd = open("mt_test", O_CREAT | O_RDWR, 0644);
ftruncate(fd, sizeof(*mm));
mm = mmap(0, sizeof(*mm), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
memset(mm, 0, sizeof(*mm));
pthread_mutexattr_init(&mm->mutexattr);
pthread_mutexattr_setpshared(&mm->mutexattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&mm->mutex, &mm->mutexattr);
pid = fork();
if (pid == 0) {
for (i = 0; i < 10; ++i) {
pthread_mutex_lock(&mm->mutex);
(mm->num)++;
printf("num+1=: %d\\n", mm->num);
pthread_mutex_unlock(&mm->mutex);
sleep(1);
}
} else if (pid > 0) {
for (i = 0; i < 10; ++i) {
pthread_mutex_lock(&mm->mutex);
mm->num += 2;
printf("num+2=: %d\\n", mm->num);
pthread_mutex_unlock(&mm->mutex);
sleep(1);
}
wait(0);
}
err = pthread_mutex_destroy(&mm->mutex);
if (err)
sys_err("pthread_mutex_destroy");
err = pthread_mutexattr_destroy(&mm->mutexattr);
if (err)
sys_err("pthread_mutexattr_destroy");
err = munmap(mm, sizeof(*mm));
if (err)
sys_err("munmap");
err = unlink("mt_test");
if (err)
sys_err("unlink");
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static int *pipes;
static int num_pipes, num_active, num_threads, num_evts;
static int epfd;
static int epet;
static int stop;
static unsigned long long getustime(void) {
struct timeval tm;
gettimeofday(&tm, 0);
return (unsigned long long) tm.tv_sec * 1000000ULL + (unsigned long long) tm.tv_usec;
}
static void *thproc(void *data) {
long thn = (long) data, nevt, i, idx, widx, fd;
unsigned int rseed = (unsigned int) thn;
struct epoll_event *events;
struct epoll_event ev;
char ch;
events = calloc(num_evts, sizeof(struct epoll_event));
if (!events) {
perror("malloc");
exit(1);
}
pthread_mutex_lock(&mtx);
pthread_mutex_unlock(&mtx);
;
for (; !stop;) {
nevt = epoll_wait(epfd, events, num_evts, 500);
;
for (i = 0; i < nevt; i++) {
idx = (int) events[i].data.u32;
widx = rand_r(&rseed) % num_pipes;
fd = pipes[2 * idx];
epoll_ctl(epfd, EPOLL_CTL_DEL, fd, 0);
ev.events = EPOLLIN | epet;
ev.data.u32 = idx;
epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &ev);
read(fd, &ch, 1);
write(pipes[2 * widx + 1], "e", 1);
}
}
free(events);
;
return (void *) 0;
}
static void sig_int(int sig) {
++stop;
signal(sig, sig_int);
}
static void usage(char const *prg) {
fprintf(stderr,
"use: %s [-atnveh]\\n\\n"
"\\t-t NTHREADS : Number of threads\\n"
"\\t-a NACTIVE : Number of active threads\\n"
"\\t-n NPIPES : Number of pipes\\n"
"\\t-v NEVENTS : Max number of events per wait\\n\\n"
"\\t-e : Use epoll ET\\n"
"\\t-h : Usage screen\\n", prg);
}
int main (int argc, char **argv) {
int i, c;
unsigned long long tr;
int *cp;
struct epoll_event ev;
extern char *optarg;
pthread_t *thid;
struct rlimit rl;
num_pipes = 100;
num_evts = -1;
num_active = 1;
num_threads = 2;
while ((c = getopt(argc, argv, "n:a:t:v:eh")) != -1) {
switch (c) {
case 'n':
num_pipes = atoi(optarg);
break;
case 'a':
num_active = atoi(optarg);
break;
case 't':
num_threads = atoi(optarg);
break;
case 'v':
num_evts = atoi(optarg);
break;
case 'e':
epet = EPOLLET;
break;
default:
usage(argv[0]);
return 1;
}
}
if (num_evts < 0)
num_evts = num_pipes / 5 + 1;
rl.rlim_cur = rl.rlim_max = num_pipes * 2 + 50;
if (setrlimit(RLIMIT_NOFILE, &rl) == -1) {
perror("setrlimit");
return 1;
}
pipes = calloc(num_pipes * 2, sizeof(int));
thid = calloc(num_threads, sizeof(pthread_t));
if (!pipes || !thid) {
perror("malloc");
return 1;
}
signal(SIGINT, sig_int);
if ((epfd = epoll_create(num_pipes)) == -1) {
perror("epoll_create");
return 2;
}
for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
if (pipe(cp) == -1) {
perror("pipe");
return 3;
}
fcntl(cp[0], F_SETFL, fcntl(cp[0], F_GETFL) | O_NONBLOCK);
}
for (cp = pipes, i = 0; i < num_pipes; i++, cp += 2) {
ev.events = EPOLLIN | epet;
ev.data.u32 = i;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, cp[0], &ev) < 0) {
perror("epoll_ctl");
return 4;
}
}
pthread_mutex_lock(&mtx);
;
for (i = 0; i < num_threads; i++) {
if (pthread_create(&thid[i], 0, thproc,
(void *) (long) i) != 0) {
perror("pthread_create()");
return 5;
}
}
;
for (i = 0; i < num_active; i++)
write(pipes[2 * i + 1], "e", 1);
pthread_mutex_unlock(&mtx);
for (; !stop;)
sleep(1);
for (i = 0; i < num_threads; i++)
pthread_join(thid[i], 0);
;
return 0;
}
| 0
|
#include <pthread.h>
int mediafirefs_mknod(const char *path, mode_t mode, dev_t dev)
{
printf("FUNCTION: mknod. path: %s\\n", path);
(void)path;
(void)mode;
(void)dev;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
fprintf(stderr, "mknod not implemented\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOSYS;
}
| 1
|
#include <pthread.h>
extern int timingsock;
extern pthread_mutex_t timing_comm_lock;
extern int verbose;
extern struct TRTimes bad_transmit_times;
void *timing_ready_controlprogram(struct ControlProgram *arg)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
if (arg!=0) {
if (arg->state->pulseseqs[arg->parameters->current_pulseseq_index]!=0) {
msg.type=TIMING_CtrlProg_READY;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
send_data(timingsock, arg->parameters, sizeof(struct ControlPRM));
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
}
}
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
void *timing_end_controlprogram(void *arg)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
msg.type=TIMING_CtrlProg_END;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
void *timing_register_seq(struct ControlProgram *control_program)
{
struct DriverMsg msg;
int index;
pthread_mutex_lock(&timing_comm_lock);
msg.type=TIMING_REGISTER_SEQ;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
send_data(timingsock, control_program->parameters, sizeof(struct ControlPRM));
index=control_program->parameters->current_pulseseq_index;
send_data(timingsock, &index, sizeof(index));
send_data(timingsock,control_program->state->pulseseqs[index], sizeof(struct TSGbuf));
send_data(timingsock,control_program->state->pulseseqs[index]->rep,
sizeof(unsigned char)*control_program->state->pulseseqs[index]->len);
send_data(timingsock,control_program->state->pulseseqs[index]->code,
sizeof(unsigned char)*control_program->state->pulseseqs[index]->len);
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
}
void *timing_pretrigger(void *arg)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
msg.type=TIMING_PRETRIGGER;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
if(bad_transmit_times.start_usec!=0) free(bad_transmit_times.start_usec);
if(bad_transmit_times.duration_usec!=0) free(bad_transmit_times.duration_usec);
bad_transmit_times.start_usec=0;
bad_transmit_times.duration_usec=0;
recv_data(timingsock, &bad_transmit_times.length, sizeof(bad_transmit_times.length));
if (bad_transmit_times.length>0) {
bad_transmit_times.start_usec=malloc(sizeof(unsigned int)*bad_transmit_times.length);
bad_transmit_times.duration_usec=malloc(sizeof(unsigned int)*bad_transmit_times.length);
} else {
bad_transmit_times.start_usec=0;
bad_transmit_times.duration_usec=0;
}
recv_data(timingsock, bad_transmit_times.start_usec, sizeof(unsigned int)*bad_transmit_times.length);
recv_data(timingsock, bad_transmit_times.duration_usec, sizeof(unsigned int)*bad_transmit_times.length);
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
void *timing_trigger(int trigger_type)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
switch(trigger_type) {
case 0:
msg.type=TIMING_TRIGGER;
break;
case 1:
msg.type=TIMING_TRIGGER;
break;
case 2:
msg.type=TIMING_GPS_TRIGGER;
break;
}
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
void *timing_wait(void *arg)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
msg.type=TIMING_WAIT;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
void *timing_posttrigger(void *arg)
{
struct DriverMsg msg;
pthread_mutex_lock(&timing_comm_lock);
msg.type=TIMING_POSTTRIGGER;
msg.status=1;
send_data(timingsock, &msg, sizeof(struct DriverMsg));
recv_data(timingsock, &msg, sizeof(struct DriverMsg));
pthread_mutex_unlock(&timing_comm_lock);
pthread_exit(0);
};
| 0
|
#include <pthread.h>
void *thread_function (void *arg);
int test_ready = 0;
int can_terminate = 0;
int hw_watch_count = 0;
static int watched_data[4];
pthread_mutex_t data_mutex;
int
main ()
{
int res;
pthread_t threads[4];
int i;
pthread_mutex_init (&data_mutex, 0);
for (i = 0; i < 4; i++)
{
res = pthread_create (&threads[i],
0, thread_function,
(void *) (intptr_t) i);
if (res != 0)
{
fprintf (stderr, "error in thread %d create\\n", i);
abort ();
}
}
for (i = 0; i < 4; ++i)
{
res = pthread_join (threads[i], 0);
if (res != 0)
{
fprintf (stderr, "error in thread %d join\\n", i);
abort ();
}
}
exit (0);
}
void
thread_started (void)
{
}
void *
thread_function (void *arg)
{
int i, j;
long thread_number = (long) arg;
thread_started ();
while (!test_ready)
usleep (1);
pthread_mutex_lock (&data_mutex);
for (i = 0; i < NR_TRIGGERS_PER_THREAD; i++)
{
for (j = 0; j < hw_watch_count; j++)
{
printf ("Thread %ld changing watch_thread[%d] data"
" from %d -> %d\\n", thread_number, j,
watched_data[j], watched_data[j] + 1);
watched_data[j]++;
}
}
pthread_mutex_unlock (&data_mutex);
while (!can_terminate)
usleep (100);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t mutex;
static pthread_cond_t teller_available;
int id;
int checked_in;
int doing_service;
pthread_cond_t done;
pthread_t thread;
struct teller_info_t *next;
struct teller_info_t *end;
} *p_teller;
static p_teller teller_list = 0;
void teller_check_in(p_teller teller)
{
teller->checked_in = 1;
teller->doing_service = 0;
pthread_mutex_lock(&mutex);
if(!teller_list){
teller_list = teller;
teller_list->next = 0;
teller_list->end = teller;
}else{
teller_list->end->next = teller;
teller_list->end = teller;
}
pthread_cond_signal(&teller_available);
pthread_mutex_unlock(&mutex);
}
void teller_check_out(p_teller teller)
{
pthread_mutex_lock(&mutex);
while(teller->doing_service){
pthread_cond_wait(&teller->done, &mutex);
}
p_teller tmp;
tmp = teller_list;
if(tmp == teller){
teller_list = tmp->next;
tmp->next = 0;
}else{
while(tmp->next != teller){
tmp = tmp->next;
}
tmp->next = teller->next;
}
teller->checked_in = 0;
pthread_mutex_unlock(&mutex);
}
p_teller do_banking(int customer_id)
{
pthread_mutex_lock(&mutex);
while(!teller_list){
pthread_cond_wait(&teller_available, &mutex);
}
p_teller teller;
teller = teller_list;
teller_list = teller_list->next;
teller->next = 0;
printf("Customer %d is served by teller %d\\n", customer_id, teller->id);
teller->doing_service = 1;
pthread_mutex_unlock(&mutex);
return teller;
}
void finish_banking(int customer_id, p_teller teller)
{
pthread_mutex_lock(&mutex);
printf("Customer %d is done with teller %d\\n", customer_id, teller->id);
teller->doing_service = 0;
if(teller_list == 0){
teller_list = teller;
teller_list->next = 0;
}else{
p_teller temp = teller_list;
while(temp->next != 0){
temp = temp->next;
}
temp->next = teller;
}
pthread_cond_signal(&teller->done);
pthread_cond_signal(&teller_available);
pthread_mutex_unlock(&mutex);
}
void* teller(void *arg)
{
p_teller me = (p_teller) arg;
teller_check_in(me);
while(1)
{
int r = rand();
if (r < (0.05 * 32767))
{
if (me->checked_in)
{
printf("teller %d checks out\\n", me->id);
teller_check_out(me);
} else {
printf("teller %d checks in\\n", me->id);
teller_check_in(me);
}
}
}
}
void* customer(void *arg)
{
int id = (uintptr_t) arg;
while (1)
{
int r = rand();
if (r < (0.1 * 32767))
{
p_teller teller = do_banking(id);
sleep(r % 4);
finish_banking(id, teller);
}
}
}
int main(void)
{
srand(time(0));
struct teller_info_t tellers[3];
int i;
for (i=0; i<3; i++)
{
tellers[i].id = i;
tellers[i].next = 0;
pthread_create(&tellers[i].thread, 0, teller, (void*) &tellers[i]);
}
pthread_t thread;
for (i=0; i<5; i++)
{
pthread_create(&thread, 0, customer, (void*) (uintptr_t) i);
}
for (i=0; i<3; i++)
{
pthread_join(tellers[i].thread, 0);
}
return 0;
}
| 0
|
#include <pthread.h>
static int const buff_size = 1024;
unsigned int convert(char* string){
int a = atoi(strtok(string, "."));
int b = atoi(strtok(0, "."));
int c = atoi(strtok(0, "."));
int d = atoi(strtok(0, "."));
unsigned int ipInteger = a * pow(256, 3) + b * pow(256, 2) + c * pow(256, 1) + d;
return ipInteger;
}
char* intToIp(int n){
struct in_addr addr = {htonl(n)};
return inet_ntoa( addr );
}
{
unsigned int ip;
int range;
int portNum;
} data;
{
unsigned int ip;
int range;
int port;
int thread_num;
int sock;
} thdata;
int isOpen(int sockfd, int ip, int port){
struct sockaddr_in addr;
struct in_addr ip_addr;
inet_pton(AF_INET, intToIp(ip), &ip_addr);
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr = ip_addr;
if (connect (sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in))==0){
return 1;
}
return 0;
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int* arr;
void scanner ( void *ptr )
{
thdata *data;
data = (thdata *) ptr;
int range = data->range;
int ip = data->ip;
int port = data->port;
int tn = data->thread_num;
int sockfd = data->sock;
int i;
char buff[buff_size];
pthread_mutex_lock(&mutex);
for(i = 0; i < range; i++){
ip = ip + 1;
int check = isOpen(sockfd, ip, port);
if(check == 1){
snprintf(buff, sizeof(buff), "%s port: %i is open\\n", intToIp(ip), port);
}else{
snprintf(buff, sizeof(buff), "%s port: %i is closed\\n", intToIp(ip), port);
}
write(sockfd, &buff, sizeof(buff));
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char* argv[])
{
int sockfd;
int i;
data recData;
struct sockaddr_in addr;
struct in_addr ip_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
perror("Couldn't create the socket");
inet_pton(AF_INET, argv[1], &ip_addr);
addr.sin_family = AF_INET;
int port = atoi( argv[2] );
addr.sin_port = htons(port);
addr.sin_addr = ip_addr;
if (connect (sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in)) == -1){
perror("Connection problem.");
exit(0);
}
read(sockfd, &recData, sizeof(recData));
int portNum = recData.portNum;
pthread_t *threads;
threads = (pthread_t*)calloc(portNum, sizeof(pthread_t));
thdata thread_data;
thread_data.ip = recData.ip;
thread_data.range = recData.range;
thread_data.sock = sockfd;
for(i = 0; i < portNum; i++){
read(sockfd, &thread_data.port, sizeof(int));
thread_data.thread_num = i+1;
int e = pthread_create (&threads[i], 0, (void *) &scanner, (void *) &thread_data);
if(e == 0){
printf("port sent to thread %i\\n", thread_data.port);
}
}
for(i = 0; i < portNum; i++){
pthread_join(threads[i], 0);
}
free(threads);
close(sockfd);
}
| 1
|
#include <pthread.h>
void *functionC();
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int main()
{
int rc1, rc2;
pthread_t thread1, thread2;
if( (rc1=pthread_create( &thread1, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc1);
}
if( (rc2=pthread_create( &thread2, 0, &functionC, 0)) )
{
printf("Thread creation failed: %d\\n", rc2);
}
printf("Hello from main\\n");
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Exit from main\\n");
return 0;
exit(0);
}
void *functionC()
{
pthread_mutex_lock( &mutex1 );
counter++;
printf("Counter value: %d\\n",counter);
pthread_mutex_unlock( &mutex1 );
}
| 0
|
#include <pthread.h>
int numberOfThreads = 2;
int numberOfBarriers = 100;
pthread_mutex_t lock;
{
int receivingCount;
int sentCount;
int threadID;
}Thread;
void disseminationBarrier(Thread* thread,Thread** threadList,int threadId)
{
int r,s = 0,t,neighborIndex;
int numOfRounds = ceil(log(numberOfThreads)/log(2));
while(s < 9999)
s++;
for(t=0;t<numOfRounds;t++) {
pthread_mutex_lock(&lock);
neighborIndex = fmod((threadId + pow(2,t)),numberOfThreads);
printf("Thread %d has neighbor index %d in round %d\\n",threadId, neighborIndex, t);
Thread* neighborThread = *(threadList + neighborIndex);
thread->sentCount = thread->sentCount + 1;
neighborThread->receivingCount = neighborThread->receivingCount + 1;
printf("%d thread's receiving count is %d\\n",thread->threadID,thread->receivingCount);
printf("%d Neighbor thread's receiving count is %d\\n",neighborThread->threadID,neighborThread->receivingCount);
printf("%d thread's sent count is %d\\n",thread->threadID,thread->sentCount);
pthread_mutex_unlock(&lock);
while((*(threadList+threadId))->receivingCount < t+1);
while((*(threadList+threadId))->sentCount != t+1);
}
printf("%d exit check begin\\n", thread->threadID);
while((*(threadList+threadId))->receivingCount != numOfRounds);
while((*(threadList+threadId))->sentCount != numOfRounds);
(*(threadList+threadId))->receivingCount = 0;
(*(threadList+threadId))->sentCount = 0;
printf("%d exit check end\\n", thread->threadID);
}
int main(int argc, char** argv)
{
double startTime,endTime;
if(numberOfThreads <=0 || numberOfBarriers <= 0) {
printf("\\nERROR: Number of threads/barriers cannot be negative!");
exit(1);
}
pthread_mutex_init(&lock,0);
int k,l;
int barrierArray[numberOfBarriers];
omp_set_num_threads(numberOfThreads);
int rounds = ceil(log(numberOfThreads)/log(2));
Thread** threadList = malloc(numberOfThreads*sizeof(Thread*));
for(k = 0; k < numberOfThreads; k++){
Thread* thread;
thread = (Thread*) malloc(sizeof(Thread));
thread->receivingCount = 0;
thread->sentCount = 0;
thread->threadID = k;
*(threadList + k) = thread;
}
for(l = 0;l < numberOfBarriers; l++)
barrierArray[l] = 0;
{
int i = 0,j;
numberOfThreads = omp_get_num_threads();
int threadId = omp_get_thread_num();
Thread* thread = *(threadList + threadId);
for(i = 0; i <numberOfBarriers; i++) {
j = 0;
while(j < 9999){
j++;
}
printf("Entered thread %d of %d threads at barrier %d\\n", thread->threadID, numberOfThreads-1, i);
startTime = omp_get_wtime();
disseminationBarrier(thread,threadList,threadId);
printf("Completed thread %d of %d threads at barrier %d\\n", thread->threadID, numberOfThreads-1, i);
pthread_mutex_lock(&lock);
barrierArray[i] = barrierArray[i] + 1;
printf("barrierCheck is %d\\n", barrierArray[i]);
pthread_mutex_unlock(&lock);
while(barrierArray[i]!= numberOfThreads);
endTime = omp_get_wtime();
}
printf("Time spent in barrier by thread %d is %f\\n",thread->threadID, endTime-startTime);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_t barman, firstDude, secondDude, thirdDude;
pthread_mutex_t fridge;
int bottleInFridge = 10;
int visit[3][3];
int stage = 0;
bool barmanIsBusy = 0;
void *barmanOps(){
pthread_mutex_init(&fridge, 0);
srand((unsigned int)time(0));
while(1){
if(rand()%25 + 1 == 1){
barmanIsBusy = 1;
pthread_mutex_init(&fridge, 0);
pthread_mutex_lock(&fridge);
sleep(30);
pthread_mutex_unlock(&fridge);
bottleInFridge+=3;
barmanIsBusy = 0;
}
sleep(1);
}
}
void *firstDudeOps(){
while(1)
{
visit[1][1] = 1;
pthread_mutex_lock(&fridge);
visit[1][1] = 2;
sleep(5);
if(!barmanIsBusy){
pthread_mutex_unlock(&fridge);
}
visit[1][1] = 3;
sleep(20);
bottleInFridge--;
visit[1][2]++;
if(visit[1][2] == 10){
visit[1][1] = 4;
sleep(120);
}
}
}
void *secondDudeOps(){
while(1)
{
visit[2][1] = 1;
pthread_mutex_lock(&fridge);
visit[2][1] = 2;
sleep(5);
if(!barmanIsBusy){
pthread_mutex_unlock(&fridge);
}
visit[2][1] = 3;
sleep(20);
bottleInFridge--;
visit[2][2]++;
if(visit[2][2] == 10){
visit[2][1] = 4;
sleep(120);
}
}
}
void *thirdDudeOps(){
while(1)
{
visit[3][1] = 1;
pthread_mutex_lock(&fridge);
visit[3][1] = 2;
sleep(5);
if(!barmanIsBusy){
pthread_mutex_unlock(&fridge);
}
visit[3][1] = 3;
sleep(20);
bottleInFridge--;
visit[3][2]++;
if(visit[3][2] == 10){
visit[3][1] = 4;
sleep(120);
}
}
}
int main(){
pthread_create(&barman, 0, barmanOps, 0);
pthread_create(&firstDude, 0, firstDudeOps, 0);
pthread_create(&secondDude, 0, secondDudeOps , 0);
pthread_create(&thirdDude, 0, thirdDudeOps, 0);
visit[1][2] = 0;
visit[2][2] = 0;
visit[3][2] = 0;
while(1)
{
stage++;
printf("===STAGE %d===\\n", stage);
for(int i=1; i<=3; i++)
{
sleep(2);
if(i==1)printf("First Dude ");
if(i==2)printf("Second Dude ");
if(i==3)printf("Third Dude ");
printf("drank %d bottles. \\nHe ", visit[i][2]);
if(visit[i][1]==1) printf("standing in line to fridge.");
if(visit[i][1]==2) printf("takes a bottle of beer.");
if(visit[i][1]==3) printf("is drinking beer.");
if(visit[i][1]==4) printf("sleeps.");
printf("\\n\\n");
}
if(!barmanIsBusy) printf("Barman puts 3 new bootle\\n");
if(barmanIsBusy) printf("Barman is abcent\\n\\n");
printf("Bottles in the fridge = %d\\n", bottleInFridge);
sleep(1);
printf("\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n");
if(bottleInFridge == 0){
printf("The party is over!");
sleep(60);
}
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
{
int data;
struct node *next;
}node_t,*node_p,**node_pp;
node_p head = 0;
static node_p alloc_node(int data)
{
node_p temp = (node_p)malloc(sizeof(node_t));
if(0 == temp)
{
perror("malloc");
return 0;
}
temp->data = data;
temp->next = 0;
return temp;
}
static void init(node_pp _list)
{
node_p temp = alloc_node(0);
if(0 == temp)
{
return ;
}
*_list = temp;
}
static void push_front(node_p _list,int data)
{
node_p temp = alloc_node(data);
node_p node = _list->next;
_list->next = temp;
temp->next = node;
}
static int is_empty_list(node_p _list)
{
return (_list->next == 0) ? 1 : 0;
}
static void pop_front(node_p _list, int *data)
{
if(is_empty_list(_list))
{
return ;
}
node_p temp = _list->next;
*data = temp->data;
_list->next = temp->next;
free(temp);
temp = 0;
}
void show_list(node_p _list)
{
node_p start = _list->next;
while(start)
{
printf("%d -> ",start->data);
start = start->next;
}
printf("\\n");
}
void *product(void *arg)
{
int data = 0;
while(1)
{
pthread_mutex_lock(&lock);
data = rand()%11111;
push_front(head,data);
pthread_mutex_unlock(&lock);
printf("producter done.... : %d \\n",data);
pthread_cond_signal(&cond);
sleep(1);
}
}
void *consumer(void *arg)
{
int data = 0;
while(1)
{
pthread_mutex_lock(&lock);
while(is_empty_list(head))
{
printf("consumer wait.... \\n");
pthread_cond_wait(&cond,&lock);
}
pop_front(head,&data);
pthread_mutex_unlock(&lock);
printf("consumer done.... : %d \\n",data);
}
}
int main()
{
init(&head);
pthread_mutex_init(&lock,0);
pthread_cond_init(&cond,0);
pthread_t th1 , th2;
pthread_create(&th1,0,product,0);
pthread_create(&th2,0,consumer,0);
pthread_join(th1,0);
pthread_join(th2,0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
return 0;
}
| 1
|
#include <pthread.h>
void *ssu_thread1(void *arg);
void *ssu_thread2(void *arg);
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
int count = 0;
int input = 0;
int t1 = 0, t2 = 0;
int main(void) {
pthread_t tid1, tid2;
int status;
if(pthread_create(&tid1, 0, ssu_thread1, 0) != 0) {
fprintf(stderr, "pthread_create error\\n");
exit(1);
}
if(pthread_create(&tid2, 0, ssu_thread2, 0) != 0) {
fprintf(stderr, "pthread_create error\\n");
exit(1);
}
while(1) {
printf("2개 이상의 개수 입력 : ");
scanf("%d", &input);
if(input >= 2) {
pthread_cond_signal(&cond1);
break;
}
}
pthread_join(tid1, (void *)&status);
pthread_join(tid2, (void *)&status);
printf("complete\\n");
exit(0);
}
void *ssu_thread1(void *arg) {
while(1) {
pthread_mutex_lock(&mutex1);
if(input < 2)
pthread_cond_wait(&cond1, &mutex1);
if(input == count) {
pthread_cond_signal(&cond2);
break;
}
if(count == 0) {
t2++;
count++;
printf("Thread 1 : %d\\n", t1);
}
else if(count % 2 == 0) {
t1 += t2;
count++;
printf("Thread 1 : %d\\n", t1);
}
pthread_cond_signal(&cond2);
pthread_cond_wait(&cond1, &mutex1);
pthread_mutex_unlock(&mutex1);
}
return 0;
}
void *ssu_thread2(void *arg) {
while(1) {
pthread_mutex_lock(&mutex2);
if(input < 2)
pthread_cond_wait(&cond2, &mutex2);
if(input == count) {
pthread_cond_signal(&cond1);
break;
}
if(count == 1) {
count++;
printf("Thread 2 : %d\\n", t2);
}
else if(count % 2 == 1) {
t2 += t1;
count++;
printf("Thread 2 : %d\\n", t2);
}
pthread_cond_signal(&cond1);
pthread_cond_wait(&cond2, &mutex2);
pthread_mutex_unlock(&mutex2);
}
return 0;
}
| 0
|
#include <pthread.h>
static pthread_barrier_t barrier;
int Global;
pthread_mutex_t mtx;
void *Thread1(void *x) {
barrier_wait(&barrier);
pthread_mutex_lock(&mtx);
Global++;
pthread_mutex_unlock(&mtx);
return 0;
}
void *Thread2(void *x) {
Global--;
barrier_wait(&barrier);
return 0;
}
int main() {
barrier_init(&barrier, 2);
pthread_mutex_init(&mtx, 0);
pthread_t t[2];
pthread_create(&t[0], 0, Thread1, 0);
pthread_create(&t[1], 0, Thread2, 0);
pthread_join(t[0], 0);
pthread_join(t[1], 0);
pthread_mutex_destroy(&mtx);
return 0;
}
| 1
|
#include <pthread.h>
struct service {
int req[64];
int res[64];
int status;
};
struct service *queue[32];
int rqueue, wqueue, nr_queue;
pthread_mutex_t mtx1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mtx2 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mtx3 = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
FILE *logfile;
void log_setup_strings(char *buf, const char *func)
{
struct timeval now;
gettimeofday(&now, 0);
sprintf(buf, "[%d.%06d]:%s\\n", now.tv_sec, now.tv_usec, func);
}
void log_error(const char *func)
{
char *logbuf;
logbuf = malloc(256);
usleep(100000);
log_setup_strings(logbuf, func);
pthread_mutex_lock(&mtx3);
fputs(logbuf, logfile);
fflush(logfile);
pthread_mutex_unlock(&mtx3);
free(logbuf);
}
int queue_service_req(struct service *sv)
{
int ret = -1;
pthread_mutex_lock(&mtx1);
if (nr_queue >= 32)
goto out;
queue[wqueue] = sv;
nr_queue++;
wqueue++;
if (wqueue >= 32)
wqueue = 0;
pthread_cond_signal(&cond1);
ret = 0;
out:
pthread_mutex_unlock(&mtx1);
return ret;
}
struct service *deq_service_req(void)
{
struct service *sv;
sv = 0;
pthread_mutex_lock(&mtx1);
while (nr_queue <= 0)
pthread_cond_wait(&cond1, &mtx1);
sv = queue[rqueue];
nr_queue--;
rqueue++;
if (rqueue >= 32)
rqueue = 0;
pthread_mutex_unlock(&mtx1);
return sv;
}
int proc_req(void)
{
struct service sv;
struct timeval now;
struct timespec timeout;
int i, ret;
sv.status = 1;
for (i = 0; i < 64; i++)
sv.req[i] = 0;
ret = queue_service_req(&sv);
if (ret == -1)
return -1;
gettimeofday(&now, 0);
timeout.tv_sec = now.tv_sec + 1;
timeout.tv_nsec = now.tv_usec * 1000;
pthread_mutex_lock(&mtx2);
ret = pthread_cond_timedwait(&cond2, &mtx2, &timeout);
pthread_mutex_unlock(&mtx2);
if (ret == ETIMEDOUT)
return -1;
if (sv.status == 2)
return 0;
return -1;
}
int proc_res(void)
{
struct timeval now;
struct service *sv;
int i;
sv = deq_service_req();
if (!sv)
return -1;
pthread_mutex_lock(&mtx2);
usleep(900000);
for (i = 0; i < 64; i++) {
gettimeofday(&now, 0);
sv->res[i] = now.tv_usec;
}
sv->status = 2;
pthread_mutex_unlock(&mtx2);
return 0;
}
void *th_req(void *p)
{
for (;;) {
if (proc_req() == -1)
log_error("Request");
usleep(100000);
}
return 0;
}
void *th_res(void *p)
{
for (;;) {
if (proc_res() == -1)
log_error("Response");
usleep(100000);
}
return 0;
}
int main(int argc, char **argv)
{
pthread_t reqs[64], resp[16];
int i;
logfile = fopen("error.log", "w");
for (i = 0; i < 16; i++)
pthread_create(&resp[i], 0, th_res, 0);
for (i = 0; i < 64; i++)
pthread_create(&reqs[i], 0, th_req, 0);
for (;;)
sleep(1);
fclose(logfile);
return 0;
}
| 0
|
#include <pthread.h>
int main(int argc, char ** argv) {
inicializar_variables();
inicializar_semaforos();
nombreMapa = string_duplicate(argv[1]);
crear_archivo_log();
signal(SIGUSR2, signal_handler);
signal(SIGINT, signal_handler);
signal(SIGUSR1, signal_handler);
if (chequear_argumentos(argc, TOTAL_ARGS) == -1) {
pthread_mutex_lock(&mutex_log);
log_error(logger, "Numero incorrecto de argumentos ingresados. Deben ser ./mapa.so <nombre del mapa> <punto de montaje del pkdx cliente>");
pthread_mutex_unlock(&mutex_log);
return 1;
}
nivel_gui_inicializar();
int filas = __FILAS, columnas = __COLUMNAS;
nivel_gui_get_area_nivel(&filas, &columnas);
ruta_directorio = string_duplicate(argv[2]);
leer_metadata_mapa(argv[2]);
cargar_pokenests();
socket_servidor = -1;
nivel_gui_dibujar(items_mapa, nombreMapa);
pthread_create(&hilo_planificador, 0, (void *) run_scheduler_thread, 0);
pthread_create(&hilo_servidor, 0, (void *) run_trainer_server, 0);
pthread_create(&hilo_bloqueados, 0, (void *) atender_bloqueados, 0);
pthread_create(&hilo_deadlock, 0, (void *) run_deadlock_thread, 0);
pthread_join(hilo_planificador, 0);
pthread_join(hilo_servidor, 0);
pthread_join(hilo_bloqueados, 0);
pthread_join(hilo_deadlock, 0);
pthread_detach(hilo_planificador);
pthread_detach(hilo_servidor);
pthread_detach(hilo_bloqueados);
pthread_detach(hilo_deadlock);
destruir_semaforos();
destruir_variables();
nivel_gui_terminar();
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t thereAreOxygen, thereAreHydrogen;
int numberOxygen = 0 , numberHydrogen=0;
int activeOxygen = 0 , activeHydrogen=0;
long currentOxygen = 0 , currentHydrogen=0;
void startOxygen(){
pthread_mutex_lock(&lock);
++activeOxygen;
++currentOxygen;
while (activeHydrogen<2) {
pthread_cond_wait(&thereAreOxygen, &lock);
}
--numberOxygen;
pthread_mutex_unlock(&lock);
}
void doneOxygen() {
pthread_mutex_lock(&lock);
pthread_cond_broadcast(&thereAreHydrogen);
--activeOxygen;
pthread_mutex_unlock(&lock);
}
void startHydrogen(){
pthread_mutex_lock(&lock);
++activeHydrogen;
while (activeOxygen<1 && activeHydrogen<2) {
pthread_cond_wait(&thereAreHydrogen, &lock);
}
--numberHydrogen;
pthread_mutex_unlock(&lock);
}
void doneHydrogen() {
pthread_mutex_lock(&lock);
pthread_cond_signal(&thereAreOxygen);
--activeHydrogen;
++currentHydrogen;
pthread_mutex_unlock(&lock);
}
void *Oxigeno(void *id) {
long tid = (long)id;
printf("oxigeno[%ld] preparado para ser H2O \\n", tid);
startOxygen();
printf("oxigeno[%ld] convirtiendose \\n",tid);
sleep(rand()%5);
printf("oxigeno[%ld] es H2O \\n", tid);
doneOxygen();
sleep(rand()%5);
pthread_exit(0);
}
void *Hidrogeno(void *id) {
long tid = (long)id;
startHydrogen();
sleep(rand()%5);
doneHydrogen();
sleep(rand()%5);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
int n_oxygen=-3;
int n_hydrogen=-3;
pthread_t oxygen, hydrogen[2];
long i=0;
srand(time(0));
while (n_oxygen<-1){
printf("Ingrese numero de Oxigeno: ");
scanf("%d",&n_oxygen);
}
numberOxygen+=n_oxygen;
while (n_hydrogen<-1) {
printf("Ingrese numero de hidrogeno:");
scanf("%d",&n_hydrogen);
}
numberHydrogen+=n_hydrogen;
while ( numberOxygen>0) {
for (i=0; i<2; i++) {
if (pthread_create(&hydrogen[i], 0, Hidrogeno, (void *)(i))) {
printf("Error creando thread hidrogeno[%ld]\\n", i);
exit(1);
}
}
i=0;
if (pthread_create(&oxygen, 0,Oxigeno, (void *)currentOxygen)) {
printf("Error creando thread oxigeno[%ld]\\n", i);
exit(1);
}
void *status;
for (i=0; i<2; i++)
{
pthread_join(hydrogen[i],&status);
}
pthread_join(oxygen,&status);
}
return 0;
}
| 0
|
#include <pthread.h>
int readers;
int writer;
pthread_cond_t readers_proceed;
pthread_cond_t writer_proceed;
int pending_writers;
pthread_mutex_t read_write_lock;
} mylib_rwlock_t;
void mylib_rwlock_init (mylib_rwlock_t *l) {
l -> readers = l -> writer = l -> pending_writers = 0;
pthread_mutex_init(&(l -> read_write_lock), 0);
pthread_cond_init(&(l -> readers_proceed), 0);
pthread_cond_init(&(l -> writer_proceed), 0);
}
void mylib_rwlock_rlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> pending_writers > 0) || (l -> writer > 0))
pthread_cond_wait(&(l -> readers_proceed),
&(l -> read_write_lock));
l -> readers ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_wlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> writer > 0) || (l -> readers > 0)) {
l -> pending_writers ++;
pthread_cond_wait(&(l -> writer_proceed),
&(l -> read_write_lock));
l -> pending_writers --;
}
l -> writer ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_unlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
if (l -> writer > 0)
l -> writer = 0;
else if (l -> readers > 0)
l -> readers --;
pthread_mutex_unlock(&(l -> read_write_lock));
if ((l -> readers == 0) && (l -> pending_writers > 0))
pthread_cond_signal(&(l -> writer_proceed));
else if (l -> readers > 0)
pthread_cond_broadcast(&(l -> readers_proceed));
}
int n;
struct FD_Thread {
int fd;
int thread;
};
char **theArray;
double times[1000];
mylib_rwlock_t *read_write_locks;
void *ServerEcho(void *args)
{
struct FD_Thread *fd_thread = (struct FD_Thread*)args;
char str[50];
int pos, mode;
double start, end;
read(fd_thread->fd, str, 50);
GET_TIME(start);
sscanf(str, "%d %d", &mode, &pos);
if(mode == 0) {
mylib_rwlock_rlock(&read_write_locks[pos]);
char * temp = theArray[pos];
mylib_rwlock_unlock(&read_write_locks[pos]);
GET_TIME(end);
write(fd_thread->fd, theArray[pos], 50);
}
else if(mode == 1) {
mylib_rwlock_wlock(&read_write_locks[pos]);
sprintf(theArray[pos], "String %d has been modifed by a write request", pos);
mylib_rwlock_unlock(&read_write_locks[pos]);
write(fd_thread->fd, theArray[pos], 50);
GET_TIME(end);
}
times[fd_thread->thread] = end - start;
close(fd_thread->fd);
}
int main(int argc, char* argv[])
{
double start, middle, end;
end = -1;
int port_num = atoi(argv[1]);
n = atoi(argv[2]);
int i;
theArray = (char **) malloc(sizeof(char *) * n);
read_write_locks = (mylib_rwlock_t *) malloc(sizeof(mylib_rwlock_t) * n);
for(i = 0; i < n; i++) {
theArray[i] = (char *) malloc(sizeof(char) * 50);
sprintf(theArray[i], "String %d: the initial value", i);
mylib_rwlock_init(&read_write_locks[i]);
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
pthread_t t[1000];
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=port_num;
sock_var.sin_family=AF_INET;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
listen(serverFileDescriptor,2000);
while(1)
{
double total;
for(i = 0; i < n; i++)
mylib_rwlock_init(&read_write_locks[i]);
for(i=0;i<1000;i++)
{
clientFileDescriptor=accept(serverFileDescriptor,0,0);
if(end == -1) {
GET_TIME(start);
end = 0;
}
struct FD_Thread *fd_thread = (struct FD_Thread*)malloc(sizeof(struct FD_Thread));
fd_thread->fd = clientFileDescriptor;
fd_thread->thread = i;
pthread_create(&t[i],0,ServerEcho,(void *)fd_thread);
}
for (i = 0; i < 1000; i++) {
pthread_join(t[i],0);
total += times[i];
}
GET_TIME(end);
printf("Total time: %f\\n", total);
end = -1;
}
close(serverFileDescriptor);
}
else{
printf("socket creation failed\\n");
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t x,wsem;
pthread_t tidC[20],tidP[20];
int readcount;
void intialize()
{ printf("\\nhello\\n");
pthread_mutex_init(&x,0);
pthread_mutex_init(&wsem,0);
readcount=0;
}
void *reader (void *param)
{
int waittime;
int *ind = (int *)param;
printf("\\nReader %d is trying to enter",*ind);
pthread_mutex_lock(&x);
readcount++;
if(readcount==1)
pthread_mutex_lock(&wsem);
printf("\\n Reader %d is inside ",*ind);
pthread_mutex_unlock(&x);
pthread_mutex_lock(&x);
readcount--;
if(readcount==0)
pthread_mutex_unlock(&wsem);
pthread_mutex_unlock(&x);
printf("\\nReader %d is Leaving",*ind);
}
void *writer (void *param)
{
int waittime;
int *ind = (int *)param;
waittime=rand() % 3;
printf("\\nWriter %d is trying to enter",*ind);
pthread_mutex_lock(&wsem);
printf("\\nWriter %d has entered",*ind);
pthread_mutex_unlock(&wsem);
printf("\\nWriter %d is leaving",*ind);
}
int main()
{
int n1,n2,i;
printf("\\nEnter the no of readers: ");
scanf("%d",&n1);
printf("\\nEnter the no of writers: ");
scanf("%d",&n2);
for(i=0;i<n1;i++)
{ int *p = (int*) malloc(sizeof(int));
*p = i+1;
pthread_create(&tidP[i],0,reader,p);
pthread_join(tidP[i],0);
}
for(i=0;i<n2;i++)
{ int *p = (int*) malloc(sizeof(int));
*p = i+1;
pthread_create(&tidC[i],0,writer,p);
pthread_join(tidC[i],0);
}
exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
float Vals[1000];
float **s;
int tid;
}sumArgs;
float **s;
float avg;
int tid;
}stdArgs;
void *calcAverage(void *param){
pthread_mutex_lock(&lock);
sumArgs *args = (sumArgs *)param;
while(args->tid < 1000){
args->s[0][0] += Vals[args->tid];
args->tid += 8;
}
pthread_mutex_unlock(&lock);
}
void *calcStandardDev(void *param){
pthread_mutex_lock(&lock);
stdArgs *args = (stdArgs *)param;
while(args->tid < 1000){
args->s[0][0] += powf((Vals[args->tid] - args->avg), 2.f);
args->tid += 8;
}
pthread_mutex_unlock(&lock);
}
int main(int argc, char** argv){
pthread_t threads[8];
sumArgs *avgCalcArgs = malloc(8 * sizeof(sumArgs));
if(avgCalcArgs == 0){
perror("Malloc encountered an error");
exit(1);
}
stdArgs *stdCalcArgs = malloc(8 * sizeof(stdArgs));
if(stdCalcArgs == 0){
perror("Malloc encountered an error");
exit(1);
}
float *sum = malloc(sizeof(float));
if(sum == 0){
perror("Malloc encountered an error");
exit(1);
}
float avg;
float e_sum = 0.f;
float e_avg = 0.f;
float e_std;
int i;
int err;
err = pthread_mutex_init(&lock, 0);
sum[0] = 0.f;
srand(7);
for(i = 0; i < 1000; i++){
Vals[i] = (float)(rand() % 15);
printf("%f\\n", Vals[i]);
}
for(i = 0; i < 8; i++){
avgCalcArgs[i].s = ∑
avgCalcArgs[i].tid = i;
err = pthread_create(&threads[i], 0, calcAverage, (void *)&avgCalcArgs[i]);
if(err != 0){
errno = err;
perror("pthread_create");
exit(1);
}
}
for(i = 0; i < 8; i++){
err = pthread_join(threads[i], 0);
if(err != 0){
errno = err;
perror("pthread_join");
exit(1);
}
}
for(i = 0; i < 1000; i++){
e_sum += Vals[i];
}
printf("e_sum: %f\\tsum: %f\\n", e_sum, sum[0]);
avg = sum[0] / 1000.f;
e_avg = e_sum / 1000.f;
printf("e_avg: %f\\t\\tavg: %f\\n", e_avg, avg);
sum[0] = 0.f;
e_sum = 0.f;
for(i = 0; i < 8; i++){
stdCalcArgs[i].s = ∑
stdCalcArgs[i].tid = i;
stdCalcArgs[i].avg = avg;
err = pthread_create(&threads[i], 0, calcStandardDev, (void *)&stdCalcArgs[i]);
if(err != 0){
errno = err;
perror("pthread_create");
exit(1);
}
}
for(i = 0; i < 8; i++){
err = pthread_join(threads[i], 0);
if(err != 0){
errno = err;
perror("pthread_join");
exit(1);
}
}
for(i = 0; i < 1000; i++){
e_sum += powf(Vals[i] - e_avg, 2.f);
}
printf("e_sum: %f\\tsum: %f\\n", e_sum, sum[0]);
avg = sqrtf(sum[0] / 1000.f);
e_avg = sqrtf(e_sum / 1000.f);
printf("e_std: %f\\tstd: %f\\n", e_avg, avg);
free(avgCalcArgs);
free(stdCalcArgs);
free(sum);
err = pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t build_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t build_cond = PTHREAD_COND_INITIALIZER;
static uint64_t dirtyPaths;
static char **paths;
static int pathCount;
extern char **environ;
static int WatchSubdirs_printHelp;
static int WatchSubdirs_printVersion;
static const char *WatchSubdirs_makefile = "Makefile";
static struct option WatchSubdirs_longOptions[] =
{
{ "makefile", required_argument, 0, 'm' },
{ "help", no_argument, &WatchSubdirs_printHelp, 1 },
{ "version", no_argument, &WatchSubdirs_printVersion, 1 },
{ 0, 0, 0, 0 }
};
static void *
WatchSubdirs_BuildThread (void *arg)
{
for (;;)
{
pid_t child;
int status, pathIndex;
pthread_mutex_lock (&build_mutex);
while (!dirtyPaths)
pthread_cond_wait (&build_cond, &build_mutex);
pthread_mutex_unlock (&build_mutex);
usleep (100000);
while (0 != (pathIndex = ffs (dirtyPaths)))
{
--pathIndex;
if (-1 == (child = fork ()))
err (1, "fork failed");
if (!child)
{
char *args[7];
args[0] = "/usr/bin/make";
args[1] = "-s";
args[2] = "-f";
args[3] = (char *) WatchSubdirs_makefile;
args[4] = "-C";
args[5] = paths[pathIndex];
args[6] = 0;
execve (args[0], args, environ);
exit (1);
}
waitpid (child, &status, 0);
pthread_mutex_lock (&build_mutex);
dirtyPaths &= ~(1 << pathIndex);
pthread_mutex_unlock (&build_mutex);
}
}
}
static void
WatchSubdirs_StartBuildThread (void)
{
pthread_t threadHandle;
pthread_create (&threadHandle, 0, WatchSubdirs_BuildThread, 0);
pthread_detach (threadHandle);
}
int
main (int argc, char **argv)
{
int i, inotifyFD;
char buffer[4096];
size_t bufferFill = 0;
ssize_t result;
int *watchDescriptors;
if (-1 == (inotifyFD = inotify_init1(IN_CLOEXEC)))
err (1, "inotify_init1 failed");
while(-1 != (i = getopt_long(argc, argv, "", WatchSubdirs_longOptions, 0)))
{
switch(i)
{
case 0:
break;
case 'm':
WatchSubdirs_makefile = optarg;
break;
case '?':
fprintf(stderr, "Try `%s --help' for more information.\\n", argv[0]);
return 1;
}
}
if(WatchSubdirs_printHelp)
{
fprintf(stdout,
"Usage: %s [OPTION]... [DIRECTORY]...\\n"
"\\n"
" -m, --makefile=<filename> set path of Makefile\\n"
" --help display this help and exit\\n"
" --version display version information\\n"
"\\n"
"Report bugs to <morten.hustveit@gmail.com>\\n", argv[0]);
return 0;
}
paths = argv + optind;
pathCount = argc - optind;
if (!(watchDescriptors = calloc (pathCount, sizeof (*watchDescriptors))))
err (1, "calloc failed");
for (i = 0; i < pathCount; ++i)
{
if(-1 == (watchDescriptors[i] = inotify_add_watch (inotifyFD, paths[i], IN_CLOSE_WRITE | IN_MOVED_TO | IN_ONLYDIR)))
err (1, "inotify_add_watch: failed to start watching `%s'", paths[i]);
}
WatchSubdirs_StartBuildThread ();
for (;;)
{
if (-1 == (result = read (inotifyFD, buffer + bufferFill, sizeof (buffer) - bufferFill)))
err (1, "read failed on inotify descriptor");
bufferFill += result;
while (bufferFill > sizeof (struct inotify_event))
{
struct inotify_event *event;
size_t eventSize;
event = (struct inotify_event *) buffer;
eventSize = sizeof(*event) + event->len;
if (event->name[0] != '.')
{
int pathIndex;
for (pathIndex = 0; pathIndex < pathCount; ++pathIndex)
{
if (watchDescriptors[pathIndex] == event->wd)
{
pthread_mutex_lock (&build_mutex);
dirtyPaths |= (1 << pathIndex);
pthread_cond_signal (&build_cond);
pthread_mutex_unlock (&build_mutex);
break;
}
}
}
bufferFill -= eventSize;
memmove (buffer, buffer + eventSize, bufferFill);
}
}
}
| 0
|
#include <pthread.h>
{
int add;
int take;
int buffer[10];
}product;
product proBuff = {0,0,{0}};
unsigned int proId = 1;
pthread_mutex_t mutex;
sem_t full;
sem_t empty;
void *Gen(void *id)
{
while(1)
{
pthread_mutex_lock(&mutex);
if(!(((proBuff.add + 1) % 10 ) == proBuff.take))
{
proBuff.buffer[proBuff.add] = proId++;
proBuff.add = (proBuff.add + 1) % 10;
}
else
{
printf("no place to enter \\n",(long*)id);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
sleep(1);
}
}
void *Take(void *id)
{
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(!(proBuff.add == proBuff.take))
{
proBuff.buffer[proBuff.take] = 0;
proBuff.take = (proBuff.take + 1) % 10 ;
}
else
{
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
sleep(1);
}
}
int main(int argc, char *argv[])
{
unsigned int buyers = 6;
unsigned int providers = 1;
pthread_t pro[providers];
pthread_t* bu;
int t1 = pthread_mutex_init(&mutex, 0);
int t2 = sem_init(&full, 0, 0);
if(t1!=0||t2!=0)
printf("Intialization Error");
bu = malloc(buyers*sizeof(pthread_t));
long i;
for(i=0;i<providers;i++)
pthread_create(&pro[i], 0, Gen, (void*) i);
for(i=0;i<buyers;i++)
pthread_create(&bu[i], 0, Take, (void*) i);
for(i=0;i<providers;i++)
pthread_join(pro[i], 0);
for(i=0;i<buyers;i++)
pthread_join(bu[i], 0);
pthread_mutex_destroy(&mutex);
sem_destroy(&full);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t turno;
pthread_mutex_t mutex;
pthread_mutex_t db;
int rc = 0;
void* reader(void *arg);
void* writer(void *arg);
void read_data_base();
void use_data_read();
void think_up_data();
void write_data_base();
int main() {
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&db, 0);
pthread_mutex_init(&turno, 0);
pthread_t r[20], w[10];
int i;
int *id;
for (i = 0; i < 20 ; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&r[i], 0, reader, (void *) (id));
}
for (i = 0; i< 10; i++) {
id = (int *) malloc(sizeof(int));
*id = i;
pthread_create(&w[i], 0, writer, (void *) (id));
}
pthread_join(r[0],0);
return 0;
}
void* reader(void *arg) {
int i = *((int *) arg);
while(1) {
pthread_mutex_lock(&turno);
pthread_mutex_lock(&mutex);
rc = rc + 1;
if (rc == 1) {
pthread_mutex_lock(&db);
}
pthread_mutex_unlock(&mutex);
pthread_mutex_unlock(&turno);
read_data_base(i);
pthread_mutex_lock(&mutex);
rc = rc - 1;
if (rc == 0) {
pthread_mutex_unlock(&db);
}
pthread_mutex_unlock(&mutex);
use_data_read(i);
}
pthread_exit(0);
}
void* writer(void *arg) {
int i = *((int *) arg);
while(1) {
think_up_data(i);
pthread_mutex_lock(&turno);
pthread_mutex_lock(&db);
write_data_base(i);
pthread_mutex_unlock(&db);
pthread_mutex_unlock(&turno);
}
pthread_exit(0);
}
void read_data_base(int i) {
printf("Leitor %d está lendo os dados! Número de leitores = %d \\n", i,rc);
sleep( rand() % 5);
}
void use_data_read(int i) {
printf("Leitor %d está usando os dados lidos!\\n", i);
sleep(rand() % 5);
}
void think_up_data(int i) {
printf("Escritor %d está pensando no que escrever!\\n", i);
sleep(rand() % 5);
}
void write_data_base(int i) {
printf("Escritor %d está escrevendo os dados!\\n", i);
sleep( rand() % 5);
}
| 0
|
#include <pthread.h>
int g_buffer[5];
unsigned short in = 0;
unsigned short out = 0;
unsigned short produce_id = 0;
unsigned short consume_id = 0;
sem_t g_sem_full;
sem_t g_sem_empty;
pthread_mutex_t g_mutex;
pthread_t g_thread[2 + 2];
void *consume(void *arg){
int i;
int num = (int)arg;
while (1){
printf("%d wait buffer not empty\\n", num);
sem_wait(&g_sem_empty);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 5; i++){
printf("%02d ", i);
if (g_buffer[i] == -1)
printf("%s", "null");
else
printf("%d", g_buffer[i]);
if (i == out)
printf("\\t<--consume");
printf("\\n");
}
consume_id = g_buffer[out];
printf("%d begin consume product %d\\n", num, consume_id);
g_buffer[out] = -1;
out = (out + 1) % 5;
printf("%d end consume product %d\\n", num, consume_id);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_full);
sleep(1);
}
return 0;
}
void *produce(void *arg){
int num = (int)arg;
int i;
while (1){
printf("%d wait buffer not full\\n", num);
sem_wait(&g_sem_full);
pthread_mutex_lock(&g_mutex);
for (i = 0; i < 5; i++){
printf("%02d ", i);
if (g_buffer[i] == -1)
printf("%s", "null");
else
printf("%d", g_buffer[i]);
if (i == in)
printf("\\t<--produce");
printf("\\n");
}
printf("%d begin produce product %d\\n", num, produce_id);
g_buffer[in] = produce_id;
in = (in + 1) % 5;
printf("%d end produce product %d\\n", num, produce_id++);
pthread_mutex_unlock(&g_mutex);
sem_post(&g_sem_empty);
sleep(5);
}
return 0;
}
int main(void){
int i;
for (i = 0; i < 5; i++)
g_buffer[i] = -1;
sem_init(&g_sem_full, 0, 5);
sem_init(&g_sem_empty, 0, 0);
pthread_mutex_init(&g_mutex, 0);
for (i = 0; i < 2; i++)
pthread_create(&g_thread[i], 0, consume, (void *)i);
for (i = 0; i < 2; i++)
pthread_create(&g_thread[2 + i], 0, produce, (void *)i);
for (i = 0; i < 2 + 2; i++)
pthread_join(g_thread[i], 0);
sem_destroy(&g_sem_full);
sem_destroy(&g_sem_empty);
pthread_mutex_destroy(&g_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int input[MAX_NUMS];
int output[100];
int inC=0;
int no=0;
pthread_t tid,producer_thread[2],consumer_thread[3];
pthread_mutex_t Lock;
sem_t full,empty;
pthread_attr_t defattr;
void* producer(void* var){
int item,i;
for(i=0;i<MAX_NUMS;i++){
item=(rand()%100)+1;
sem_wait(&empty);
pthread_mutex_lock(&Lock);
if(inC<MAX_NUMS){
printf("\\nproduce: %d",item);
input[inC]=item;
inC++;
}
else{
fprintf(stderr,"\\nProducer error");
}
pthread_mutex_unlock(&Lock);
sleep(1);
sem_post(&full);
sleep(1);
}
printf("\\nproducer exiting\\n");
}
void* consumer(void* var){
int item,i;
for(i=0;i<MAX_NUMS;i++){
sem_wait(&full);
pthread_mutex_lock(&Lock);
if(inC>0){
item=input[inC-1];
inC--;
printf("\\nConsumer consumed: %d",item);
}
else{
fprintf(stderr,"\\nConsumer error");
}
pthread_mutex_unlock(&Lock);
sleep(1);
sem_post(&empty);
sleep(1);
}
printf("\\nConsumer exiting too\\n");
}
int main()
{
pthread_mutex_init(&Lock,0);
sem_init(&full,0,0);
sem_init(&empty,0,MAX_NUMS);
pthread_attr_init(&defattr);
pthread_create(&producer_thread[0],&defattr,producer,0);
pthread_create(&producer_thread[1],0,producer,0);
pthread_create(&consumer_thread[0],&defattr,consumer,0);
pthread_create(&consumer_thread[1],0,consumer,0);
pthread_join(producer_thread[0],0);
pthread_join(producer_thread[1],0);
pthread_join(consumer_thread[0],0);
pthread_join(consumer_thread[1],0);
pthread_exit(0);
printf("\\nEnding it \\n");
exit(0);
}
| 0
|
#include <pthread.h>
struct int_channel{
int queue[100];
int front;
int back;
int MAX_SIZE;
int size;
bool poisoned;
pthread_mutex_t lock;
pthread_cond_t write_ready;
pthread_cond_t read_ready;
};
int init_int_channel(struct int_channel *channel){
if(pthread_mutex_init(&channel->lock, 0) != 0){
printf("Mutex init failed");
return 1;
}
if(pthread_cond_init(&channel->write_ready, 0) +
pthread_cond_init(&channel->read_ready, 0 ) != 0){
printf("Cond init failed");
return 1;
}
channel->MAX_SIZE = 100;
channel->front = 0;
channel->back = 0;
channel->poisoned = 0;
return 0;
}
void enqueue_int(int element, struct int_channel *channel){
pthread_mutex_lock(&channel->lock);
while(channel->size >= channel->MAX_SIZE)
pthread_cond_wait(&channel->write_ready, &channel->lock);
assert(channel->size < channel->MAX_SIZE);
assert(!(channel->poisoned));
channel->queue[channel->back] = element;
channel->back = (channel->back + 1) % channel->MAX_SIZE;
channel->size++;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
int dequeue_int(struct int_channel *channel){
pthread_mutex_lock(&channel->lock);
assert(channel->size != 0);
int result = channel->queue[channel->front];
channel->front = (channel->front + 1) % channel->MAX_SIZE;
channel->size--;
pthread_cond_signal(&channel->write_ready);
pthread_mutex_unlock(&channel->lock);
return result;
}
void poison(struct int_channel *channel) {
pthread_mutex_lock(&channel->lock);
channel->poisoned = 1;
pthread_cond_signal(&channel->read_ready);
pthread_mutex_unlock(&channel->lock);
}
bool wait_for_more(struct int_channel *channel) {
pthread_mutex_lock(&channel->lock);
while(channel->size == 0) {
if(channel->poisoned){
pthread_mutex_unlock(&channel->lock);
return 0;
}
else {
pthread_cond_wait(&channel->read_ready, &channel->lock);
}
}
pthread_mutex_unlock(&channel->lock);
return 1;
}
struct _token_gen_for_array_size_five_args {
struct int_channel *ochan;
int *input;
};
void *token_gen_for_array_size_five(void *_args) {
struct int_channel *ochan = ((struct _token_gen_for_array_size_five_args *) _args)->ochan;
int *input = ((struct _token_gen_for_array_size_five_args *) _args)->input;
for (int i = 0; i < 5; i++) {
enqueue_int(input[i], ochan);
}
poison(ochan);
return 0;
}
struct _print_int_args {
struct int_channel *chan;
};
void *print_int(void *_args) {
struct int_channel *chan = ((struct _print_int_args *) _args)->chan;
while (wait_for_more(chan)) {
printf("%d\\n", dequeue_int(chan));
}
return 0;
}
struct _interleaver_args {
struct int_channel *chan1;
struct int_channel *chan2;
struct int_channel *ochan;
};
void *interleaver(void *_args) {
struct int_channel *chan1 = ((struct _interleaver_args *) _args)->chan1;
struct int_channel *chan2 = ((struct _interleaver_args *) _args)->chan2;
struct int_channel *ochan = ((struct _interleaver_args *) _args)->ochan;
while(wait_for_more(chan1) || wait_for_more(chan2)) {
if (wait_for_more(chan1)) enqueue_int(dequeue_int(chan1), ochan);
if (wait_for_more(chan2)) enqueue_int(dequeue_int(chan2), ochan);
}
poison(ochan);
return 0;
}
struct pthread_node{
pthread_t thread;
struct pthread_node *next;
};
struct pthread_node* head = 0;
pthread_mutex_t thread_list_lock;
pthread_t* make_pthread_t(){
pthread_mutex_lock(&thread_list_lock);
struct pthread_node *new_pthread = (struct pthread_node *) malloc(sizeof(struct pthread_node));
new_pthread->next = head;
head = new_pthread;
pthread_mutex_unlock(&thread_list_lock);
return &(new_pthread->thread);
}
void wait_for_finish(){
struct pthread_node* curr = head;
while(curr){
pthread_join(curr->thread, 0);
curr = curr->next;
}
}
int main() {
pthread_mutex_init(&thread_list_lock, 0);
struct int_channel *chan1 = (struct int_channel *) malloc(sizeof(struct int_channel));
struct int_channel *chan2 = (struct int_channel *) malloc(sizeof(struct int_channel));
struct int_channel *ochan = (struct int_channel *) malloc(sizeof(struct int_channel));
init_int_channel(chan1);
init_int_channel(chan2);
init_int_channel(ochan);
int array1[5] = {1, 2, 3, 4, 5};
int array2[5] = {0, 10, 0, 10, 0};
{
pthread_t* _t = make_pthread_t();
struct _token_gen_for_array_size_five_args _args = {
chan1,
array1,
};
pthread_create(_t, 0, token_gen_for_array_size_five, (void *) &_args);
};
{
pthread_t* _t = make_pthread_t();
struct _token_gen_for_array_size_five_args _args = {
chan2,
array2,
};
pthread_create(_t, 0, token_gen_for_array_size_five, (void *) &_args);
};
{
pthread_t* interleaver_t = make_pthread_t();
struct _interleaver_args interleaver_t_args = {
chan1,
chan2,
ochan,
};
pthread_create(interleaver_t, 0, interleaver, (void *) &interleaver_t_args);
};
{
pthread_t* print_int_t = make_pthread_t();
struct _print_int_args print_int_t_args = {
ochan,
};
pthread_create(print_int_t, 0, print_int, (void *) &print_int_t_args);
}
wait_for_finish();
return 0;
}
| 1
|
#include <pthread.h>
const int THREAD_COUNT=100000;
pthread_mutex_t ex_mutex;
void *threadFunc(void *threadId)
{
int tid = (int)(threadId);
fprintf(stdout,"Performing task inside thread %d\\n",tid);
if(tid % 2 == 0)
{
pthread_mutex_lock(&ex_mutex);
if(tid % 50 == 0)
{
pthread_mutex_destroy(&ex_mutex);
pthread_exit(0);
}
}
pthread_mutex_unlock(&ex_mutex);
pthread_exit(0);
}
int main(void) {
int idStore[THREAD_COUNT];
int i; void *status;
pthread_t threads[THREAD_COUNT];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_mutex_init(&ex_mutex, 0);
for( i = 0; i < THREAD_COUNT;i++)
{
idStore[i] = i;
pthread_create(&threads[i], &attr,threadFunc,idStore[i]);
}
for( i = 1; i < THREAD_COUNT;i++)
{
pthread_join(threads[i], &status);
}
return 0;
}
| 0
|
#include <pthread.h>
int available_resources = 5;
pthread_mutex_t mutex;
sem_t empty;
sem_t full;
int increase_count(int count);
int decrease_count(int count);
void* producer(void *a);
void* consumer(void *a);
int main() {
int NUM_PRODUCER,NUM_CONSUMER, SLEEP;
srand(time(0));
NUM_CONSUMER = rand()%10+5;
NUM_PRODUCER = rand()%10+5;
SLEEP = 10;
printf("\\n\\nProducers : %d\\nConsumers : %d\\nSleep Time : %d\\n\\n\\n", NUM_PRODUCER, NUM_CONSUMER, SLEEP);
pthread_t producer_thread[NUM_PRODUCER], consumer_thread[NUM_CONSUMER];
int i;
sem_init(&empty,0,5);
sem_init(&full,0,0);
pthread_mutex_init(&mutex,0);
int rc;
for(i=0; i<NUM_PRODUCER; i++) {
rc = pthread_create(&producer_thread[i],0,producer,(void *) i);
if(rc==-1)
printf("Trouble creating producer thread!! \\n\\n");
}
for(i=0; i<NUM_CONSUMER; i++) {
rc = pthread_create(&consumer_thread[i],0,consumer,(void *) i);
if(rc==-1)
printf("Trouble creating consumer thread!! \\n\\n");
}
sleep(SLEEP);
return;
for(i=0; i<NUM_PRODUCER; i++)
pthread_join(producer_thread[i],0);
for(i=0; i<NUM_CONSUMER; i++)
pthread_join(consumer_thread[i],0);
pthread_exit(0);
return 0;
}
int decrease_count(int count) {
if (available_resources < count) {
printf("Subtracted 0\\nCount = %d\\n\\n", available_resources);
return -1;
}
else {
available_resources -= count;
printf("Subtracted %d\\nCount = %d\\n\\n", count, available_resources);
return 0;
}
}
int increase_count(int count) {
available_resources += count;
printf("Added %d\\nCount = %d\\n\\n", count, available_resources);
return 0;
}
void* producer(void *a){
int thread_id= (int) a;
int count = rand()%5;
while(1){
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(decrease_count(count)<0)
sleep(rand()%3);
increase_count(count);
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void* consumer(void *a){
int thread_id = (int) a;
int count = rand()%5;
while(1){
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(decrease_count(count)<0)
sleep(rand()%3);
increase_count(count);
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
| 1
|
#include <pthread.h>
int myglobal;
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
void *thread_function(void *arg) {
int i,j;
for ( i=0; i<20; i++ ) {
pthread_mutex_lock(&mymutex);
j=myglobal;
j=j+1;
printf(".");
fflush(stdout);
sleep(1);
myglobal=j;
pthread_mutex_unlock(&mymutex);
}
return 0;
}
int main(void) {
pthread_t mythread;
int i;
if ( pthread_create( &mythread, 0, thread_function, 0) ) {
printf("error creating thread.");
abort();
}
if ( pthread_join ( mythread, 0 ) ) {
printf("error joining thread.");
abort();
}
printf("\\nmyglobal equals %d\\n",myglobal);
exit(0);
}
| 0
|
#include <pthread.h>
static void *producerFunc(void *info);
static void *consumerFunc(void *info);
sem_t full;
sem_t empty;
pthread_mutex_t lock;
int pIndex = 0;
int cIndex = 0;
struct producerInfo {
int threadNumber;
int counter;
int toProduce;
int *buff;
int bufferSize;
};
struct consumerInfo {
int threadNumber;
int toConsume;
int *buff;
int bufferSize;
};
int main(int arc, char **argv)
{
int bufferSize = atoi(argv[1]);
int numProducers = atoi(argv[2]);
int numConsumers = atoi(argv[3]);
int amountProduced = atoi(argv[4]);
printf("Buffer size = %d, ", bufferSize);
printf("number of producer threads = %d, ", numProducers);
printf("number of consumer threads = %d, ", numConsumers);
printf("and each producer produces %d\\n", amountProduced);
int buffer[bufferSize];
if(sem_init(&full, 0, 0) == -1) {
printf("workz!! %d\\n",errno);
}
if(sem_init(&empty, 0, bufferSize) == -1) {
printf("workz!! %d\\n",errno );
}
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_t producers[numProducers];
pthread_t consumers[numConsumers];
struct producerInfo pInfo[numProducers];
struct consumerInfo cInfo[numConsumers];
int i;
for(i=0; i<numProducers; i++) {
pInfo[i].threadNumber = i+1;
pInfo[i].counter = 0;
pInfo[i].toProduce = amountProduced;
pInfo[i].buff = &buffer;
pInfo[i].bufferSize = bufferSize;
}
for(i=0; i<numConsumers; i++) {
cInfo[i].threadNumber = i+1;
cInfo[i].toConsume = (numProducers * amountProduced) / numConsumers;
cInfo[i].buff = &buffer;
cInfo[i].bufferSize = bufferSize;
}
int remainder = (numProducers*amountProduced)%numConsumers;
for(i=0; i<remainder; i++) {
cInfo[i].toConsume++;
}
for(i=0; i<numProducers; i++) {
pthread_create(&producers[i], &attr, producerFunc, &pInfo[i]);
}
for(i=0; i<numConsumers; i++) {
pthread_create(&consumers[i], &attr, consumerFunc, &cInfo[i]);
}
pthread_attr_destroy(&attr);
for(i=0; i<numProducers; i++) {
pthread_join(producers[i], 0);
}
for(i=0; i<numConsumers; i++) {
pthread_join(consumers[i], 0);
}
pthread_mutex_destroy(&lock);
sem_destroy(&full);
sem_destroy(&empty);
printf("****All jobs finished***\\n");
}
static void *consumerFunc(void *info) {
struct consumerInfo *cInfo = info;
int value;
while(cInfo->toConsume > 0) {
sem_wait(&full);
pthread_mutex_lock(&lock);
printf("Consumer %d consumed: %d\\n", cInfo->threadNumber, cInfo->buff[cIndex]);
cInfo->toConsume--;
cIndex = (cIndex + 1) % cInfo->bufferSize;
fflush(stdout);
pthread_mutex_unlock(&lock);
sem_post(&empty);
}
pthread_exit(0);
}
static void *producerFunc(void *info) {
struct producerInfo *pInfo = info;
int value;
while(pInfo->counter < pInfo->toProduce) {
sem_wait(&empty);
pthread_mutex_lock(&lock);
pInfo->buff[pIndex] = pInfo->threadNumber * 1000000 + pInfo->counter;
printf("Producer %d produced: %d\\n", pInfo->threadNumber, pInfo->buff[pIndex]);
pInfo->counter++;
pIndex = (pIndex + 1) % pInfo->bufferSize;
fflush(stdout);
pthread_mutex_unlock(&lock);
sem_post(&full);
}
pthread_exit(0);
}
| 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;
int totalproduced = 0;
int producer_shutdown = 0;
void spinit(void)
{
int i;
for(i = 0; i < 10000; i++)
;
}
void catch_sigusr1(int signo)
{
pthread_mutex_lock(&slot_lock);
{
producer_shutdown = 1;
}
pthread_mutex_unlock(&slot_lock);
}
void *producer(void *arg1)
{
int i;
sigset_t intmask;
sigemptyset(&intmask);
sigaddset(&intmask, SIGUSR1);
for(i = 1; ; i++) {
spinit();
pthread_sigmask(SIG_BLOCK, &intmask, 0);
pthread_mutex_lock(&slot_lock);
{
spinit();
while ((nslots <= 0) && (!producer_shutdown))
pthread_cond_wait(&slots, &slot_lock);
if(producer_shutdown) {
pthread_mutex_unlock(&slot_lock);
break;
}
nslots--;
}
pthread_mutex_unlock(&slot_lock);
pthread_sigmask(SIG_UNBLOCK, &intmask, 0);
spinit();
put_item(i*i);
pthread_mutex_lock(&item_lock);
{
nitems++;
totalproduced++;
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);
spinit();
get_item(&myitem);
spinit();
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;
double total;
double tp;
struct sigaction act;
sigset_t set;
fprintf(stderr, "Process ID id %ld\\n", (long) getpid());
sleep(5);
act.sa_handler = catch_sigusr1;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGUSR1, &act, 0);
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
sigprocmask(SIG_BLOCK, &set, 0);
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");
fprintf(stderr, "Producer ID = %ld, Consumer ID = %ld\\n",
(long) prodid, (long) consid);
pthread_join(prodid, 0);
pthread_join(consid, 0);
printf("The threads produced the sum %d\\n", sum);
total = 0.0;
tp = (double) totalproduced;
total = tp*(tp+1)*(2*tp+1)/6.0;
if(tp > 1861)
fprintf(stderr, "*** Overflow ocurrs for more than %d items\\n",
1861);
printf("The checksum for %4d items is %1.0f\\n",
totalproduced, total);
exit(0);
}
| 0
|
#include <pthread.h>
pthread_t *threads;
int thread_count;
} thread_pool;
thread_pool *tids;
pthread_mutex_t lock;
void* doSomeThing(int *pId)
{
pthread_mutex_lock(&lock);
unsigned long i = 0;
const char progress[] = "|/-\\\\";
for (i = 0; i < 100; i += 10) {
printf("Processing: %3d%%\\r",i);
fflush(stdout);
usleep(1*1000);
}
printf("\\n");
fflush(stdout);
printf("Processing: ");
for (i = 0; i < 100; i += 10) {
printf("%c\\b", progress[(i/10)%sizeof(progress)]);
fflush(stdout);
usleep(1*1000);
}
printf("\\n");
fflush(stdout);
printf("\\nThread %d processing done\\n",pId);
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
int i = 0;
int err;
tids=(thread_pool *)malloc(1 * sizeof(thread_pool ));
tids->threads=(pthread_t *)malloc(1 * sizeof(pthread_t ));
tids->thread_count = 0;
if (pthread_mutex_init(&lock, 0) != 0)
{
printf("\\n mutex init failed\\n");
return 1;
}
while(i < 9)
{
if(tids->thread_count!=0)
{
tids->threads =(pthread_t *)realloc(tids->threads,sizeof ( pthread_t )*(tids->thread_count+1)) ;
if(tids==0)
printf("error with realloc");
}
err = pthread_create(&(tids->threads[tids->thread_count]), 0, &doSomeThing, tids->thread_count);
if (err != 0)
printf("\\ncan't create thread :[%s]", strerror(err));
else
printf("\\n Thread %d created successfully\\n",tids->thread_count);
tids->thread_count++;
i++;
}
i = 0;
while(i < tids->thread_count)
{
pthread_join(tids->threads[i], 0);
pthread_join(tids->threads[i], 0);
i++;
}
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int num;
pthread_mutex_t m;
pthread_cond_t empty, full;
void * thread1(void * arg)
{
pthread_mutex_lock(&m);
while (num > 0)
pthread_cond_wait(&empty, &m);
num++;
pthread_mutex_unlock(&m);
pthread_cond_signal(&full);
}
void * thread2(void * arg)
{
pthread_mutex_lock(&m);
while (num == 0)
pthread_cond_wait(&full, &m);
num--;
pthread_mutex_unlock(&m);
pthread_cond_signal(&empty);
}
int main()
{
pthread_t t1, t2;
num = 1;
pthread_mutex_init(&m, 0);
pthread_cond_init(&empty, 0);
pthread_cond_init(&full, 0);
pthread_create(&t1, 0, thread1, 0);
pthread_create(&t2, 0, thread2, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
if (num!=1)
{
ERROR:
__VERIFIER_error();
;
}
return 0;
}
| 0
|
#include <pthread.h>
int fd_ir = -1;
unsigned char ir_buf[4] = { 0 };
unsigned char flag_ir_thd_exit;
pthread_mutex_t irbuf_mutex;
int IrDeviceCreate(void)
{
if(fd_ir > 0)
{
return -2;
}
if((fd_ir = open("/dev/ir", O_RDWR)) <= 0)
{
LIBHAL_ERROR("open ir devices failed");
return -1;
}
return 0;
}
void *ir_process_thd(void *arg)
{
pthread_detach(pthread_self());
while(1)
{
if(flag_ir_thd_exit == 0)
{
pthread_mutex_lock(&irbuf_mutex);
if(read(fd_ir, ir_buf, 4) < 4)
{
pthread_mutex_unlock(&irbuf_mutex);
uint_msleep(500);
continue;
}
else
{
pthread_mutex_unlock(&irbuf_mutex);
LIBHAL_DEBUG("read result is 0x%x,0x%x,0x%x,0x%x\\n", ir_buf[0]
, ir_buf[1], ir_buf[2], ir_buf[3]);
uint_msleep(500);
}
}
else
{
break;
}
}
pthread_exit(0);
}
int IrDeviceInit(void)
{
pthread_t ir_process_tid;
flag_ir_thd_exit = 0;
pthread_mutex_init(&irbuf_mutex, 0);
if(pthread_create(&ir_process_tid, 0, ir_process_thd, 0) != 0)
{
LIBHAL_ERROR("Fail to create device automaton thread error: %d", errno);
return -1;
}
else
{
return 0;
}
}
int IrDeviceRead(unsigned char *pbuf)
{
memcpy(pbuf, ir_buf, sizeof(ir_buf));
return 0;
}
int IrDeviceWrite(unsigned char *pbuf)
{
return 0;
}
int IrDeviceClose(void)
{
flag_ir_thd_exit = 1;
return 0;
}
int IrDeviceDestory(void)
{
close(fd_ir);
return 0;
}
| 1
|
#include <pthread.h>
int *carpark;
int capacity;
int occupied;
int nextin;
int nextout;
int cars_in;
int cars_out;
pthread_mutex_t lock;
pthread_cond_t space;
pthread_cond_t car;
pthread_barrier_t bar;
} cp_t;
static void * car_in_handler(void *cp_in);
static void * car_out_handler(void *cp_in);
static void * monitor(void *cp_in);
static void initialise(cp_t *cp, int size);
int main(int argc, char *argv[]) {
if (argc != 2) {
printf("Usage: %s carparksize\\n", argv[0]);
exit(1);
}
cp_t ourpark;
initialise(&ourpark, atoi(argv[1]));
pthread_t car_in, car_out, m;
pthread_t car_in2, car_out2;
pthread_create(&car_in, 0, car_in_handler, (void *)&ourpark);
pthread_create(&car_out, 0, car_out_handler, (void *)&ourpark);
pthread_create(&car_in2, 0, car_in_handler, (void *)&ourpark);
pthread_create(&car_out2, 0, car_out_handler, (void *)&ourpark);
pthread_create(&m, 0, monitor, (void *)&ourpark);
pthread_join(car_in, 0);
pthread_join(car_out, 0);
pthread_join(car_in2, 0);
pthread_join(car_out2, 0);
pthread_join(m, 0);
exit(0);
}
static void initialise(cp_t *cp, int size) {
cp->occupied = cp->nextin = cp->nextout = cp->cars_in = cp->cars_out = 0;
cp->capacity = size;
cp->carpark = (int *)malloc(cp->capacity * sizeof(*cp->carpark));
pthread_barrier_init(&cp->bar, 0, 4);
if (cp->carpark == 0) {
perror("malloc()");
exit(1);
}
srand((unsigned int)getpid());
pthread_mutex_init(&cp->lock, 0);
pthread_cond_init(&cp->space, 0);
pthread_cond_init(&cp->car, 0);
}
static void* car_in_handler(void *carpark_in) {
cp_t *temp;
unsigned int seed;
temp = (cp_t *)carpark_in;
pthread_barrier_wait(&temp->bar);
while (1) {
usleep(rand_r(&seed) % 1000000);
pthread_mutex_lock(&temp->lock);
while (temp->occupied == temp->capacity)
pthread_cond_wait(&temp->space, &temp->lock);
temp->carpark[temp->nextin] = rand_r(&seed) % 10;
temp->occupied++;
temp->nextin++;
temp->nextin %= temp->capacity;
temp->cars_in++;
pthread_cond_signal(&temp->car);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
static void* car_out_handler(void *carpark_out) {
cp_t *temp;
unsigned int seed;
temp = (cp_t *)carpark_out;
pthread_barrier_wait(&temp->bar);
for (; ;) {
usleep(rand_r(&seed) % 1000000);
pthread_mutex_lock(&temp->lock);
while (temp->occupied == 0)
pthread_cond_wait(&temp->car, &temp->lock);
temp->occupied--;
temp->nextout++;
temp->nextout %= temp->capacity;
temp->cars_out++;
pthread_cond_signal(&temp->space);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
static void *monitor(void *carpark_in) {
cp_t *temp;
temp = (cp_t *)carpark_in;
for (; ;) {
sleep(2);
pthread_mutex_lock(&temp->lock);
printf("Delta: %d\\n", temp->cars_in - temp->cars_out - temp->occupied);
printf("Number of cars in carpark: %d\\n", temp->occupied);
pthread_mutex_unlock(&temp->lock);
}
return ((void *)0);
}
| 0
|
#include <pthread.h>
{
int data;
struct _Node* next;
}Node,*Node_p,**Node_pp;
Node_p head=0;
static Node_p Alloc_Node(int x)
{
Node_p node=(Node_p)malloc(sizeof(node));
if(node==0)
{
perror("malloc");
exit(0);
}
node->data=x;
node->next=0;
return node;
}
static int IsEmpty(Node_p head)
{
return head->next==0?1:0;
}
void PushHead(Node_p head,int x)
{
Node_p node=Alloc_Node(x);
node->next=head->next;
head->next=node;
}
void PopHead(Node_p head,int* data)
{
if(!IsEmpty(head))
{
Node_p del=head->next;
*data=del->data;
head->next=del->next;
free(del);
del=0;
}
}
void InitList(Node_pp head)
{
*head=Alloc_Node(0);
}
void Destroy(Node_p head)
{
int data=-1;
while(!IsEmpty(head))
{
PopHead(head,&data);
}
free(head);
head=0;
}
void Show(Node_p head)
{
Node_p cur=head->next;
while(cur)
{
printf("%d ",cur->data);
cur=cur->next;
}
printf("\\n");
}
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void* product(void* arg)
{
int data=-1;
while(1)
{
pthread_mutex_lock(&lock);
if(!IsEmpty(head))
{
pthread_cond_wait(&cond,&lock);
}
sleep(1);
data=rand()%1234;
PushHead(head,data);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
return 0;
}
void* consume(void* arg)
{
int data=-1;
while(1)
{
pthread_mutex_lock(&lock);
if(IsEmpty(head))
{
pthread_cond_wait(&cond,&lock);
}
PopHead(head,&data);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&cond);
}
return 0;
}
int main()
{
InitList(&head);
pthread_t consumer,producter;
pthread_create(&producter,0,product,0);
pthread_create(&consumer,0,consume,0);
pthread_join(consumer,0);
pthread_join(producter,0);
pthread_cond_destroy(&cond);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t job_queue_mutex = PTHREAD_MUTEX_INITIALIZER;
sem_t job_queue_count;
struct node *next;
char job;
}N;
N* header;
N* tail;
N* current;
N* num;
}Q;
void initialize_job_queue(Q *job_queue)
{
job_queue->header = 0;
job_queue->tail = 0;
job_queue->current = 0;
job_queue->num = 0;
sem_init(&job_queue_count, 0, 0);
}
void* job_handle(void* arg)
{
Q *job_list = (Q*)arg;
while(1) {
N *job;
sem_wait(&job_queue_count);
pthread_mutex_lock(&job_queue_mutex);
job = job_list->header;
job_list->header = job_list->header->next;
pthread_mutex_unlock(&job_queue_mutex);
if(job == 0)
printf("DONE\\n");
else {
printf("Process job %c\\n", job->job);
free(job);
}
}
return 0;
}
void equeue_job(Q *job_queue, char job)
{
N *new_node = (N*)malloc(sizeof(N));
if (new_node == 0){
fprintf(stderr, "malloc new job fail\\n");
return;
}
new_node->job = job;
pthread_mutex_lock(&job_queue_mutex);
if(job_queue->header == 0) {
new_node->next = 0;
job_queue->tail = new_node;
job_queue->num++;
}
else {
new_node->next = job_queue->header;
job_queue->num++;
}
job_queue->header = new_node;
sem_post(&job_queue_count);
pthread_mutex_unlock(&job_queue_mutex);
}
void print_job_queue(Q *q){
printf("Job Queue:\\n");
if (q->header == 0) {
printf("No job exit\\n");
}
else {
q->current = q->header;
while (q->current) {
printf("->%c", q->current->job);
q->current = q->current->next;
}
}
printf("\\n");
}
int
main(int argc, char **argv)
{
int i;
Q job_queue;
pthread_t job_thread[2];
char jobs[5] = {'A', 'B', 'C', 'D', 'E'};
initialize_job_queue(&job_queue);
for (i=0; i<5; i++) {
equeue_job(&job_queue, jobs[i]);
}
printf("equeue job number %d\\n", job_queue_count);
print_job_queue(&job_queue);
for(i=0; i<1; i++) {
pthread_create(&job_thread[i], 0, job_handle, &job_queue);
pthread_join(job_thread[i], 0);
}
print_job_queue(&job_queue);
return 0;
}
| 0
|
#include <pthread.h>
char *archivo;
char *ip;
int num_threads;
int num_ciclos;
char * port;
int *pthread_tim_wait;
int contador = 0;
pthread_mutex_t bloqueo;
void *llamada(void * param)
{
int ciclos;
struct timeval tinicio, tfinal;
int duration;
gettimeofday(&tinicio, 0);
for (ciclos = 0; num_ciclos > ciclos; ciclos++) {
int sockfd, bindfd;
char *ptr;
char getrequest[1024];
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
sprintf(getrequest, "GET %s HTTP/1.1\\nHOST: %s\\nConnection:close\\n\\n", archivo, ip);
if ( getaddrinfo(ip, port, &hints, &res) != 0 ) {
fprintf(stderr, "Host or IP not valid\\n");
exit(0);
}
sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
bindfd = bind(sockfd, res->ai_addr, res->ai_addrlen);
if ( connect(sockfd, res->ai_addr, res->ai_addrlen) != 0 ) {
fprintf(stderr, "Connection error\\n");
exit(0);
}
int optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval);
write(sockfd, getrequest, strlen(getrequest));
bool flag = 1;
while(flag) {
char *s;
int i = 0;
s = (char *) malloc (1000*sizeof(char));
while(read(sockfd, s+i, 1) != 0){
if (i > 998){
break;
}
i++;
}
if(i<999) {
flag = 0;
}
}
close(sockfd);
}
gettimeofday(&tfinal, 0);
sleep(1);
duration = ((tfinal.tv_usec - tinicio.tv_usec) + ((tfinal.tv_sec - tinicio.tv_sec) * 1000000.0f));
if(contador < sizeof pthread_tim_wait) {
pthread_tim_wait[contador] = duration;
}
printf("Termino un cliente\\n");
return 0;
}
int main(int argc, char *argv[])
{
if(argc != 7){
printf("Usage: -n <N-threads> -u <url> -p <port>\\n");
return 1;
}
char *ptr, *host, path[100], *dns;
dns = argv[4];
ptr = strstr(dns, "/");
strcpy(path, ptr);
host = strtok(dns, "/");
archivo = path;
ip = dns;
port= argv[6];
num_threads = atoi(argv[2]);
num_ciclos = 1;
int creardor,cerrar, indicador;
int tiempoPromedio;
pthread_t thread_id[num_threads];
double a[num_threads];
pthread_tim_wait = a;
printf(" Accediendo ...\\n");
for(creardor=0; creardor < num_threads; creardor++){
printf("Conexión: %d\\n",creardor);
pthread_create( &thread_id[creardor], 0, llamada, 0 );
sleep(1);
}
contador = 0;
for(cerrar=0; cerrar < num_threads; cerrar++) {
pthread_join( thread_id[cerrar], 0);
}
for(indicador= 0; indicador < num_threads; indicador++) {
pthread_mutex_lock (&bloqueo);
tiempoPromedio = tiempoPromedio + pthread_tim_wait[indicador];
pthread_mutex_unlock (&bloqueo);
}
tiempoPromedio = tiempoPromedio/ num_threads;
printf("Listo !!\\n");
return 0;
}
| 1
|
#include <pthread.h>
void* TCPechodd(void*);
void* prstats(void*);
struct{
pthread_mutex_t st_mutex;
unsigned int st_concount;
unsigned int st_contotal;
unsigned long st_contime;
unsigned long st_bytecount;
} stats;
int TCPechoThread(const char *service, int len){
pthread_t th;
pthread_attr_t ta;
struct sockaddr_in fsin;
unsigned int alen;
int msock;
int ssock;
int* fsock;
fsock = malloc(sizeof(int));
msock = passiveTCP(service, len);
pthread_attr_init(&ta);
pthread_attr_setdetachstate(&ta, PTHREAD_CREATE_DETACHED);
pthread_mutex_init(&stats.st_mutex, 0);
pthread_create(&th, &ta, prstats, 0);
while(1){
alen = sizeof(fsin);
ssock = accept(msock, (struct sockaddr*)&fsin, &alen);
if(ssock < 0){
if(errno == EINTR)
continue;
errexit("accept: %s\\n", strerror(errno));
}
*fsock = ssock;
pthread_create(&th, &ta, TCPechodd, fsock);
}
return 0;
}
void* TCPechodd(void* fsock){
time_t start;
char buf[1024];
int cc;
int fd = *(int*)fsock;
start = time(0);
pthread_mutex_lock(&stats.st_mutex);
stats.st_concount++;
pthread_mutex_unlock(&stats.st_mutex);
while (cc = read(fd, buf, sizeof(buf))) {
if(cc < 0)
errexit("echo read: %s\\n", strerror(errno));
if(write(fd, buf, cc) < 0)
errexit("echo write: %s\\n", strerror(errno));
pthread_mutex_lock(&stats.st_mutex);
stats.st_bytecount += cc;
pthread_mutex_unlock(&stats.st_mutex);
}
close(fd);
pthread_mutex_lock(&stats.st_mutex);
stats.st_contime += time(0) - start;
stats.st_concount--;
stats.st_contotal++;
pthread_mutex_unlock(&stats.st_mutex);
return 0;
}
void* prstats(void* somthing){
time_t now;
while (1) {
pthread_mutex_lock(&stats.st_mutex);
now = time(0);
printf("--- %s", ctime(&now));
printf("%-32s: %u\\n", "Completed connections",
stats.st_contotal);
if(stats.st_contotal){
printf("-%32s: %.2f (secs)\\n",
"Average complete connection time",
(float)stats.st_contime /
(float)stats.st_contotal);
printf("%-32s: %.2f\\n",
"Average byte count",
(float)stats.st_bytecount /
(float)(stats.st_contotal +
stats.st_concount));
}
printf("%-32s: %lu\\n\\n", "Total byte count",
stats.st_bytecount);
pthread_mutex_unlock(&stats.st_mutex);
}
}
| 0
|
#include <pthread.h>
int ind = 0;
int arr[50];
pthread_mutex_t mutexvar;
pthread_cond_t condvar;
void *myFuncA(void *data)
{
char t = *((char *)data);
int i;
for(i = 0; i < sizeof(arr)/sizeof(int); i++)
{
pthread_mutex_lock(&mutexvar);
if(ind >= sizeof(arr)/sizeof(int))
{
printf("\\n No storage: Array full \\n");
pthread_cond_signal(&condvar);
pthread_mutex_unlock(&mutexvar);
break;
}
if(i == 35)
{
printf("Going to sleep.... \\n");
sleep(1);
printf("Woke up! \\n");
}
arr[ind] = i;
printf("ThreadA %c: - The index value is: %d and the array value is: %d\\n", t, ind, arr[ind]);
ind++;
pthread_cond_signal(&condvar);
pthread_mutex_unlock(&mutexvar);
}
pthread_exit(0);
}
void *myFuncB(void *data)
{
char t = *((char *)data);
int i;
for(i = 0; i < sizeof(arr)/sizeof(int); i++)
{
pthread_mutex_lock(&mutexvar);
while(ind < 0 || ind > 50)
pthread_cond_wait(&condvar, &mutexvar);
if(i == 1 || i == 25 || i == 40)
{
printf("Going to sleep.... \\n");
sleep(1);
printf("Woke up! \\n");
}
ind--;
printf("ThreadB %c: - The index value is: %d and the array value is: %d\\n", t, ind, arr[ind]);
arr[ind] = -1;
if(ind < 0)
{
printf("\\n Nothing stored: Array empty \\n");
pthread_mutex_unlock(&mutexvar);
break;
}
pthread_mutex_unlock(&mutexvar);
}
pthread_exit(0);
}
int main()
{
pthread_t thread[2];
int thread_id;
int status;
pthread_mutex_init(&mutexvar, 0);
pthread_cond_init(&condvar, 0);
char a = '1', b = '2';
thread_id = pthread_create(&thread[1], 0, (void *)myFuncB, (void *)&b);
if(thread_id < 0)
{
perror("Thread create error");
exit(0);
}
thread_id = pthread_create(&thread[0], 0, (void *)myFuncA, (void *)&a);
if(thread_id < 0)
{
perror("Thread create error");
exit(0);
}
printf("Hello! Just before joining..... \\n");
pthread_join(thread[1], (void **)&status);
printf("return thread 1 %d\\n", status);
pthread_join(thread[0], (void **)&status);
printf("return thread 0 %d\\n", status);
pthread_mutex_destroy(&mutexvar);
pthread_cond_destroy(&condvar);
return 0;
}
| 1
|
#include <pthread.h>extern int __VERIFIER_nondet_int();
int idx=0;
int ctr1=1, ctr2=0;
int readerprogress1=0, readerprogress2=0;
pthread_mutex_t mutex;
void __VERIFIER_atomic_use1(int myidx) {
__VERIFIER_assume(myidx <= 0 && ctr1>0);
ctr1++;
}
void __VERIFIER_atomic_use2(int myidx) {
__VERIFIER_assume(myidx >= 1 && ctr2>0);
ctr2++;
}
void __VERIFIER_atomic_use_done(int myidx) {
if (myidx <= 0) { ctr1--; }
else { ctr2--; }
}
void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) {
*readerstart1 = readerprogress1;
*readerstart2 = readerprogress2;
}
void __VERIFIER_atomic_check_progress1(int readerstart1) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1);
if (!(0)) ERROR: goto ERROR;;
}
return;
}
void __VERIFIER_atomic_check_progress2(int readerstart2) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1);
if (!(0)) ERROR: goto ERROR;;
}
return;
}
void *qrcu_reader1() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress1 = 1;
readerprogress1 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void *qrcu_reader2() {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress2 = 1;
readerprogress2 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void* qrcu_updater() {
int i;
int readerstart1, readerstart2;
int sum;
__VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2);
if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; };
if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; }
else {}
if (sum > 1) {
pthread_mutex_lock(&mutex);
if (idx <= 0) { ctr2++; idx = 1; ctr1--; }
else { ctr1++; idx = 0; ctr2--; }
if (idx <= 0) { while (ctr1 > 0); }
else { while (ctr2 > 0); }
pthread_mutex_unlock(&mutex);
} else {}
__VERIFIER_atomic_check_progress1(readerstart1);
__VERIFIER_atomic_check_progress2(readerstart2);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, 0);
pthread_create(&t1, 0, qrcu_reader1, 0);
pthread_create(&t2, 0, qrcu_reader2, 0);
pthread_create(&t3, 0, qrcu_updater, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void* register_read(void* data)
{
int clock_start = 0;
int new_instruction = 1;
CLOCK_ZERO_READ[0] = 1;
while (1)
{
if (STOP_THREAD == 1)
{
pipeline[0].instr.Itype = NO_OP;
pipeline[0].instr.Ctype = NO_OP;
temp_pipeline[0].instr.Itype = NO_OP;
temp_pipeline[0].instr.Ctype = NO_OPERATION;
ACTIVE_STAGE[1] = 0;
break;
}
pthread_mutex_lock(&CLOCK_LOCK);
if (CLOCK == 1)
{
clock_start = 1;
CLOCK_ZERO_READ[0] = 0;
}
if (CLOCK == 0)
{
new_instruction = 1;
clock_start = 0;
CLOCK_ZERO_READ[0] = 1;
}
pthread_mutex_unlock(&CLOCK_LOCK);
if (clock_start && new_instruction)
{
temp_pipeline[0] = pipeline[0];
CURR_INSTR[1] = temp_pipeline[0].instr;
if (temp_pipeline[0].instr.Itype != NO_OP)
{
if ((pipeline[1].instr.Itype == LDR_BYTE ||
pipeline[1].instr.Itype == LDR_WORD) &&
(pipeline[1].instr.rt == temp_pipeline[0].instr.rs ||
pipeline[1].instr.rt == temp_pipeline[0].instr.rt))
{
control_signal.stall = 1;
STALL_COUNT++;
}
else
{
control_signal.stall = 0;
}
ACTIVE_STAGE[1] = 1;
}
else
{
control_signal.stall = 0;
ACTIVE_STAGE[1] = 0;
}
pthread_mutex_lock(&READ_LOCK);
NUM_THREADS_READ++;
pthread_mutex_unlock(&READ_LOCK);
while (1)
{
usleep(DELAY);
pthread_mutex_lock(&READ_LOCK);
if (NUM_THREADS_READ == (NUM_THREADS - 1))
{
pthread_mutex_unlock(&READ_LOCK);
break;
}
pthread_mutex_unlock(&READ_LOCK);
}
if (temp_pipeline[0].instr.Itype != NO_OP)
{
if ((pipeline[1].instr.Itype == LDR_BYTE ||
pipeline[1].instr.Itype == LDR_WORD) &&
(pipeline[1].instr.rt == temp_pipeline[0].instr.rs ||
pipeline[1].instr.rt == temp_pipeline[0].instr.rt))
{
PC -= 4;
pipeline[1].instr.Itype = NO_OP;
pipeline[1].instr.Ctype = NO_OPERATION;
}
else
{
pipeline[1].instr = temp_pipeline[0].instr;
pipeline[1].pc = temp_pipeline[0].pc;
pipeline[1].rs_val = register_file[temp_pipeline[0].instr.rs];
pipeline[1].rt_val = register_file[temp_pipeline[0].instr.rt];
pipeline[1].rd_val = register_file[temp_pipeline[0].instr.rd];
pipeline[1].LO = register_file[32];
pipeline[1].HI = register_file[33];
}
}
else
{
pipeline[1] = temp_pipeline[0];
}
pthread_mutex_lock(&WRITE_LOCK);
NUM_THREADS_WRITE++;
pthread_mutex_unlock(&WRITE_LOCK);
new_instruction = 0;
}
usleep(DELAY);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex_lock;
sem_t students_sem;
sem_t ta_sem;
int waiting_students = 0;
volatile int seats[2] = {0};
volatile int empty_chair;
volatile int next_stud;
int occupied=0;
void initialize()
{
sem_init(&ta_sem,1,0);
sem_init(&students_sem,1,0);
pthread_mutex_init(&mutex_lock,0);
empty_chair=0;
next_stud=0;
}
void* teacher(void *arg)
{
int help_time = 0;
int v;
printf("\\nTA thread started");
while(1){
sem_wait(&students_sem);
help_time = rand() % 3 + 1;
pthread_mutex_lock(&mutex_lock);
printf("\\n\\tTA has %d students waiting for help.",occupied);
occupied--;
next_stud = (next_stud + 1)%2;
pthread_mutex_unlock(&mutex_lock);
sleep(help_time);
printf("\\n\\tTA is avaiable for help.");
sem_post(&ta_sem);
}
pthread_exit(0);
}
void* student(void *thread_id)
{
int id=pthread_self();
int help_count=0;
int v;
int coding_time;
int can_wait;
printf("\\n Started student %d",id);
while(1)
{
printf("\\nStudent %d coding ...",id);
coding_time= rand() % 3 + 1;
sleep(coding_time);
pthread_mutex_lock(&mutex_lock);
if(occupied==2)
{
printf("\\nNo seat avaiable for student %d. Going back to coding.",id);
pthread_mutex_unlock(&mutex_lock);
continue;
}
else
{
seats[empty_chair]=id;
occupied++;
empty_chair = (empty_chair + 1)%2;
pthread_mutex_unlock(&mutex_lock);
sem_post(&students_sem);
pthread_mutex_unlock(&mutex_lock);
sem_wait(&ta_sem);
help_count++;
if(help_count==2)
break;
}
}
printf("\\nStudent %d finished and exiting!",id);
pthread_exit(0);
}
int main()
{
pthread_t ta_thread, student_thread[4];
int i = 1;
initialize();
pthread_create(&ta_thread,0,teacher,0);
for(i=1;i<=4;i++)
{
pthread_create(&student_thread[i-1],0,student, &i);
}
for(i=1;i<=4;i++)
{
pthread_join(student_thread[i-1],0);
}
printf("\\nAll students finished work. Stopping TA thread...\\n");
pthread_cancel(ta_thread);
}
| 0
|
#include <pthread.h>
int chopsticks[5];
pthread_mutex_t lock;
int try_chopstick(int chopstick_num){
int flag=0;
pthread_mutex_lock(&lock);
if(chopsticks[chopstick_num-1]==0){
chopsticks[chopstick_num-1]=1;
flag=1;
}
pthread_mutex_unlock(&lock);
return flag;
}
void release_chopsticks(int chopstick_num1,int chopstick_num2){
pthread_mutex_lock(&lock);
chopsticks[chopstick_num1-1]=0;
chopsticks[chopstick_num2-1]=0;
pthread_mutex_unlock(&lock);
}
int count;
void *start_dine(void *var_args){
int phil_id=(*(int *)var_args);
int flag=0;
long long int deadlock_detector=0;
while(count<10){
deadlock_detector=0;
while(flag!=1){
deadlock_detector++;
if(deadlock_detector > (100000000)){
printf("Deadlock detected.Getting out\\n");
exit(0);
}
flag=try_chopstick(phil_id);
}
if(flag){
deadlock_detector=0;
do{
deadlock_detector++;
if(deadlock_detector > (100000000)){
printf("Deadlock detected.Getting out\\n");
exit(0);
}
flag=try_chopstick((phil_id+1)%(5 +1)+(phil_id+1)/(5 +1));
}while(flag!=1);
if(flag){
pthread_mutex_lock(&lock);
count++;
pthread_mutex_unlock(&lock);
sleep(rand()%3+1);
release_chopsticks(phil_id,(phil_id+1)%6+(phil_id+1)/6);
}
}
}
return 0;
}
int main(){
int i;
count=0;
while(pthread_mutex_init(&lock,0) !=0)
printf("Mutex lock creation failed,trying again\\n");
pthread_t philosophers[5];
int philosopher_id[5];
for(i=0;i<5;i++){
philosopher_id[i]=i+1;
chopsticks[i]=0;
}
for(i=0;i<5;i++){
pthread_create(&philosophers[i],0,start_dine,(void *)&philosopher_id[i]);
}
for(i=0;i<5;i++)
pthread_join(philosophers[i],0);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
int pbs_movejob_err(
int c,
char *jobid,
char *destin,
char *extend,
int *local_errno)
{
int rc;
struct batch_reply *reply;
int sock;
struct tcp_chan *chan = 0;
if ((jobid == (char *)0) || (*jobid == '\\0'))
return (PBSE_IVALREQ);
if (destin == (char *)0)
destin = "";
pthread_mutex_lock(connection[c].ch_mutex);
sock = connection[c].ch_socket;
if ((chan = DIS_tcp_setup(sock)) == 0)
{
pthread_mutex_unlock(connection[c].ch_mutex);
rc = PBSE_PROTOCOL;
return rc;
}
else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_MoveJob, pbs_current_user)) ||
(rc = encode_DIS_MoveJob(chan, jobid, destin)) ||
(rc = encode_DIS_ReqExtend(chan, extend)))
{
connection[c].ch_errtxt = strdup(dis_emsg[rc]);
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(PBSE_PROTOCOL);
}
if (DIS_tcp_wflush(chan))
{
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(PBSE_PROTOCOL);
}
reply = PBSD_rdrpy(local_errno, c);
PBSD_FreeReply(reply);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return(rc);
}
int pbs_movejob(
int c,
char *jobid,
char *destin,
char *extend)
{
pbs_errno = 0;
return(pbs_movejob_err(c, jobid, destin, extend, &pbs_errno));
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.