text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
{
void* ptr;
unsigned int size;
const char* file;
int line;
struct _MtmNode *prev, *next;
}MtmNode;
{
int nodeCnt;
MtmNode *head, *tail;
pthread_mutex_t mutex;
void* (*mallocImpl)(unsigned int size);
void (*freeImpl)(void* ptr);
}MtmHeader;
static MtmHeader *g_mtm = 0;
int mtm_init()
{
if(!(g_mtm==0)){UMLOG_INFO("Warning: %s failed.", "g_mtm==NULL");return -1;};
g_mtm = (MtmHeader*)malloc(sizeof(MtmHeader));
if(g_mtm!=0)
{
g_mtm->nodeCnt = 0;
g_mtm->head = g_mtm->tail = 0;
pthread_mutex_init(&g_mtm->mutex, 0);
g_mtm->mallocImpl = malloc;
g_mtm->freeImpl = free;
}
return (g_mtm!=0) ? 0 : -1;
}
void mtm_fini()
{
if(g_mtm != 0)
{
if(mtm_is_memLeak() != 0)
{
mtm_list_free();
}
pthread_mutex_destroy(&g_mtm->mutex);
free(g_mtm);
g_mtm = 0;
}
}
int mtm_list_add(void* ptr, unsigned int size, const char* file, int line)
{
MtmNode *node = 0;
if(!(g_mtm!=0 && ptr!=0)){UMLOG_INFO("Warning: %s failed.", "g_mtm!=NULL && ptr!=NULL");return -1;};
pthread_mutex_lock(&g_mtm->mutex);
node = (MtmNode*)g_mtm->mallocImpl(sizeof(MtmNode));
if(node!=0)
{
if(g_mtm->head==0)
{
g_mtm->head = g_mtm->tail = node;
node->prev = 0;
}
else
{
node->prev = g_mtm->tail;
g_mtm->tail->next = node;
g_mtm->tail = node;
}
node->ptr = ptr;
node->file = file;
node->line = line;
node->size = size;
node->next = 0;
++g_mtm->nodeCnt;
}
pthread_mutex_unlock(&g_mtm->mutex);
return (node!=0) ? 0 : -1;
}
int mtm_list_remove(void* ptr, const char* file, int line)
{
int count;
MtmNode *cur, *nd1, *nd2;
if(!(g_mtm!=0 && ptr!=0)){UMLOG_INFO("Warning: %s failed.", "g_mtm!=NULL && ptr!=NULL");return -1;};
pthread_mutex_lock(&g_mtm->mutex);
nd1 = g_mtm->head;
nd2 = g_mtm->tail;
cur = 0;
count = g_mtm->nodeCnt;
while(count>0)
{
if(nd1->ptr==ptr)
{
cur = nd1;
break;
}
if(nd2->ptr==ptr)
{
cur = nd2;
break;
}
nd1 = nd1->next;
nd2 = nd2->prev;
count -= 2;
}
if(cur==0)
{
UMLOG_INFO("fail to free 0x%08X [%s:%d]", ptr, file, line);
goto done;
}
if(cur->prev != 0)
{
cur->prev->next = cur->next;
}
if(cur->next !=0)
{
cur->next->prev = cur->prev;
}
if(cur == g_mtm->head)
{
g_mtm->head = cur->next;
assert(g_mtm->head==0 || (g_mtm->head!=0 && g_mtm->head->prev==0));
}
if(cur == g_mtm->tail)
{
g_mtm->tail = cur->prev;
assert(g_mtm->tail==0 || (g_mtm->tail!=0 && g_mtm->tail->next == 0));
}
g_mtm->freeImpl(cur);
--g_mtm->nodeCnt;
done:
pthread_mutex_unlock(&g_mtm->mutex);
return (cur!=0) ? 0 : -1;
}
int mtm_is_memLeak()
{
if(!(g_mtm!=0)){UMLOG_INFO("Warning: %s failed.", "g_mtm!=NULL");return -1;};
return ((g_mtm->nodeCnt!=0)||(g_mtm->head!=0)) ? 1 : 0;
}
void mtm_list_free()
{
MtmNode *cur, *nxt;
int ret = 0;
if(!(g_mtm!=0)){UMLOG_INFO("Warning: %s failed.", "g_mtm!=NULL");return;};
cur = g_mtm->head;
while(cur!=0)
{
UMLOG_INFO("memory leak at 0x%08X, size=%d, [%s:%d]", cur->ptr, cur->size, cur->file, cur->line);
nxt = cur->next;
g_mtm->freeImpl(cur);
cur = nxt;
++ret;
}
g_mtm->head = 0;
g_mtm->nodeCnt = 0;
if(ret>0)
{
UMLOG_INFO("warning: There are %d pointer not freed!", ret);
}
}
void mtm_list_print()
{
MtmNode *cur;
if(!(g_mtm!=0)){UMLOG_INFO("Warning: %s failed.", "g_mtm!=NULL");return;};
cur = g_mtm->head;
while(cur!=0)
{
UMLOG_INFO("record at 0x%08X, size=%d, [%s:%d]", cur->ptr, cur->size, cur->file, cur->line);
cur = cur->next;
}
}
void* mtm_malloc(unsigned int size,const char* file,int line)
{
void* ptr = malloc(size);
mtm_list_add(ptr, size, file, line);
return ptr;
}
void* mtm_calloc(unsigned int num, unsigned int size, const char* file, int line)
{
void* ptr = calloc(num, size);
mtm_list_add(ptr, num*size, file, line);
return ptr;
}
void* mtm_realloc(void *ptr, unsigned int size, const char* file, int line)
{
void* ret = realloc(ptr, size);
if(!(ret!=0)){UMLOG_INFO("Warning: %s failed.", "ret!=NULL");return ptr;};
mtm_list_remove(ptr, file, line);
mtm_list_add(ret, size, file, line);
return ret;
}
char* mtm_strdup(const char* str, const char* file, int line)
{
char* newStr = strdup(str);
mtm_list_add(newStr, (unsigned int)strlen(newStr), file, line);
return newStr;
}
void mtm_free(void *ptr, const char* file, int line)
{
mtm_list_remove(ptr, file, line);
free(ptr);
}
| 1
|
#include <pthread.h>
int quitflag;
sigset_t mask;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t wait = PTHREAD_COND_INITIALIZER;
void *
thr_fn(void *arg)
{
int err, signo;
for (;;) {
err = sigwait(&mask, &signo);
if (err != 0) {
err_exit(err, "sigwait failed");
}
switch (signo) {
case SIGINT:
printf("\\ninterrupt\\n");
break;
case SIGQUIT:
pthread_mutex_lock(&lock);
quitflag = 1;
pthread_mutex_unlock(&lock);
pthread_cond_signal(&wait);
return(0);
default:
printf("unexpected signal %d\\n", signo);
break;
}
}
}
int
main(void)
{
int err;
sigset_t oldmask;
pthread_t tid;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGQUIT);
if ((err = pthread_sigmask(SIG_BLOCK, &mask, &oldmask)) != 0) {
err_exit(err, "SIG_BLOCK error");
}
err = pthread_create(&tid, 0, thr_fn, 0);
if (err != 0) {
err_exit(err, "can't create thread");
}
pthread_mutex_lock(&lock);
while (quitflag == 0) {
pthread_cond_wait(&wait, &lock);
}
pthread_mutex_unlock(&lock);
quitflag = 0;
if (sigprocmask(SIG_SETMASK, &oldmask, 0) < 0) {
err_sys("SIG_SETMASK, error");
}
exit(0);
}
| 0
|
#include <pthread.h>
{
int buffer[8];
pthread_mutex_t mutex;
pthread_cond_t notfull;
pthread_cond_t notempty;
int write_pos;
int read_pos;
}pc_st;
pc_st pc;
int init_pc(pc_st *pt, pc_st *attr)
{
if(0 != attr)
{
printf("attr is error value!\\n");
return 0;
}
memset(pt->buffer, 0, sizeof(pt->buffer));
pthread_mutex_init(&pt->mutex, 0);
pthread_cond_init(&pt->notfull, 0);
pthread_cond_init(&pt->notempty, 0);
pt->write_pos = 0;
pt->read_pos = 0;
return 0;
}
void destroy_pc(pc_st *pt)
{
memset(pt->buffer, 0, sizeof(pt->buffer));
pthread_mutex_destroy(&pt->mutex);
pthread_cond_destroy(&pt->notfull);
pthread_cond_destroy(&pt->notempty);
pt->write_pos = 0;
pt->read_pos = 0;
}
void *clean_up(void *arg)
{
pthread_mutex_t *mt = (pthread_mutex_t*)arg;
pthread_mutex_unlock(mt);
}
void put(pc_st *pt, int key)
{
pthread_mutex_lock(&pt->mutex);
if((pt->write_pos+1) % 8 == pt->read_pos)
{
pthread_cleanup_push(clean_up, &pt->mutex);
pthread_cond_wait(&pt->notfull, &pt->mutex);
pthread_cleanup_pop(0);
}
pt->buffer[pt->write_pos] = key;
pt->write_pos = (pt->write_pos+1) % 8;
pthread_cond_signal(&pt->notempty);
pthread_mutex_unlock(&pt->mutex);
}
int get(pc_st *pt)
{
int value;
pthread_mutex_lock(&pt->mutex);
if(pt->read_pos == pt->write_pos)
{
pthread_cleanup_push(clean_up, &pt->mutex);
pthread_cond_wait(&pt->notempty, &pt->mutex);
pthread_cleanup_pop(0);
}
value = pt->buffer[pt->read_pos];
pt->read_pos = (pt->read_pos+1) % 8;
pthread_cond_signal(&pt->notfull);
pthread_mutex_unlock(&pt->mutex);
return value;
}
void *producer()
{
int i;
for(i = 1; i <= 20; ++i)
{
put(&pc, i);
}
put(&pc, -1);
}
void *consumer()
{
int value;
while(1)
{
value = get(&pc);
if(value == -1)
break;
printf("value = %d\\n", value);
}
}
int main()
{
init_pc(&pc, 0);
pthread_t pro_id, con_id;
pthread_create(&pro_id, 0, producer, 0);
sleep(1);
pthread_create(&con_id, 0, consumer, 0);
pthread_join(pro_id, 0);
pthread_join(con_id, 0);
destroy_pc(&pc);
return 0;
}
| 1
|
#include <pthread.h>
buffer_t buffer[5];
int buffer_index;
pthread_mutex_t buffer_mutex;
sem_t full_sem;
sem_t empty_sem;
void insertbuffer(buffer_t value) {
if (buffer_index < 5) {
buffer[buffer_index++] = value;
} else {
printf("Buffer overflow\\n");
}
}
buffer_t dequeuebuffer() {
if (buffer_index > 0) {
return buffer[--buffer_index];
} else {
printf("Buffer underflow\\n");
}
return 0;
}
void *producer(void *thread_n) {
int thread_numb = *(int *)thread_n;
buffer_t value;
int i=0;
while (i++ < 2) {
sleep(rand() % 10);
value = rand() % 100;
sem_wait(&full_sem);
pthread_mutex_lock(&buffer_mutex);
insertbuffer(value);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&empty_sem);
printf("Producer %d added %d to buffer\\n", thread_numb, value);
}
pthread_exit(0);
}
void *consumer(void *thread_n) {
int thread_numb = *(int *)thread_n;
buffer_t value;
int i=0;
while (i++ < 2) {
sem_wait(&empty_sem);
pthread_mutex_lock(&buffer_mutex);
value = dequeuebuffer(value);
pthread_mutex_unlock(&buffer_mutex);
sem_post(&full_sem);
printf("Consumer %d dequeue %d from buffer\\n", thread_numb, value);
}
pthread_exit(0);
}
int main(int argc, int **argv) {
buffer_index = 0;
pthread_mutex_init(&buffer_mutex, 0);
sem_init(&full_sem,
0,
5);
sem_init(&empty_sem,
0,
0);
pthread_t thread[6];
int thread_numb[6];
int i;
for (i = 0; i < 6; ) {
thread_numb[i] = i;
pthread_create(thread + i,
0,
producer,
thread_numb + i);
i++;
thread_numb[i] = i;
pthread_create(&thread[i],
0,
consumer,
&thread_numb[i]);
i++;
}
for (i = 0; i < 6; i++)
pthread_join(thread[i], 0);
pthread_mutex_destroy(&buffer_mutex);
sem_destroy(&full_sem);
sem_destroy(&empty_sem);
return 0;
}
| 0
|
#include <pthread.h>
struct thread_arg {
pthread_t tid;
int idx;
} *t_arg;
pthread_mutex_t mutex;
void *start_thread(void *);
void clean_thread(struct thread_arg *);
void cleanup_mutex(void *);
int main()
{
int i, ret;
t_arg = (struct thread_arg *)calloc(7, sizeof(struct thread_arg));
pthread_mutex_init(&mutex, 0);
for(i=0; i<7; i++) {
t_arg[i].idx = i;
if ((ret = pthread_create(&t_arg[i].tid, 0,
start_thread, (void *)&t_arg[i]))) {
pr_err("pthread_create : %s", strerror(ret));
return 0;
}
}
clean_thread(t_arg);
return 0;
}
void *start_thread(void *arg)
{
struct thread_arg *t_arg = (struct thread_arg *)arg;
int ret;
sleep(t_arg->idx);
if ((ret = pthread_mutex_lock(&mutex))) {
printf("\\tThread:%d : Error : %s\\n", t_arg->idx, strerror(ret));
}
pthread_cleanup_push(cleanup_mutex, (void *)&mutex);
pr_out("[Thread:%d] holding mutex", t_arg->idx);
sleep(1);
sleep(1);
sleep(1);
sleep(1);
pthread_cleanup_pop(0);
pthread_mutex_unlock(&mutex);
if (t_arg->idx == 1) {
pr_out("[Thread:%d] pthread_cancel(Thread:2)", t_arg->idx);
sleep(1);
pthread_cancel( (t_arg+1)->tid );
}
return t_arg;
}
void clean_thread(struct thread_arg *t_arg)
{
int i;
struct thread_arg *t_arg_ret;
for (i=0; i<7; i++, t_arg++) {
pthread_join(t_arg->tid, (void **)&t_arg_ret);
pr_out("pthread_join : %d - %lu", t_arg->idx, t_arg->tid);
}
}
void cleanup_mutex(void *arg)
{
pthread_mutex_t *lock = (pthread_mutex_t *)arg;
pr_out("cleanup : mutex lock");
pthread_mutex_unlock(lock);
}
| 1
|
#include <pthread.h>
static pid_t linphone_pid = -1;
static pid_t child_process_pid = -1;
static int linphone_work_status =LINPHONE_ON_IDLE;
static pthread_mutex_t linphone_work_status_mutex;
static pthread_t linphone_init_t;
static pthread_t linphone_read_status_t;
static time_t start_linphone_time = 0;
static int fd1[2];
static int fd2[2];
static void set_linphone_status(int status)
{
pthread_mutex_lock(&linphone_work_status_mutex);
linphone_work_status = status;
pthread_mutex_unlock(&linphone_work_status_mutex);
}
void* linphone_init_proc(void* arg)
{
pid_t pid = fork();
if(0 == pid)
{
close(fd1[0]);
close(fd2[1]);
if (dup2(fd1[1], STDOUT_FILENO) != STDOUT_FILENO)
{
printf("error:dup2(fd1[1],STDOUT_FILENO) failed\\n");
return 0;
}
if (dup2(fd2[0], STDIN_FILENO) != STDIN_FILENO)
{
printf("error:dup2(fd2[0],STDIN_FILENO) failed\\n");
return 0;
}
system("linphonec");
return 0;
}
else
{
linphone_pid = pid +1;
child_process_pid = pid;
close(fd1[1]);
close(fd2[0]);
return 0;
}
}
void* linphone_read_status_proc(void* arg)
{
char read_buff[100] = {0};
while(LINPHONE_NOT_INIT != get_linphone_status())
{
memset(read_buff,0,sizeof(read_buff));
read(fd1[0],read_buff,100);
if(strstr(read_buff, "Connected"))
{
if(LINPHONE_ON_WAIT_FOR_ACCEPT == get_linphone_status())
{
set_linphone_status(LINPHONE_ON_CALL);
}
else if(LINPHONE_ON_INCOMING == get_linphone_status())
{
set_linphone_status(LINPHONE_ON_ANSWER);
}
printf("phone connected \\n");
time(&start_linphone_time);
}
else if(strstr(read_buff,"Call ended") || strstr(read_buff,"Call terminated"))
{
set_linphone_status(LINPHONE_ON_IDLE);
printf("call ended \\n");
time_t terminate_time;
time(&terminate_time);
printf("time:%ds\\n",terminate_time - start_linphone_time);
}
else if(strstr(read_buff, "Call declined"))
{
set_linphone_status(LINPHONE_ON_IDLE);
printf("call declined \\n");
}
else if(strstr(read_buff, "Timeout"))
{
set_linphone_status(LINPHONE_ON_IDLE);
printf("call Timeout \\n");
}
else if(strstr(read_buff, "not reach destination"))
{
set_linphone_status(LINPHONE_ON_IDLE);
printf("call Timeout \\n");
}
else if(strstr(read_buff, "is contacting you"))
{
set_linphone_status(LINPHONE_ON_INCOMING);
printf("%s\\n",read_buff);
}
usleep(100*1000);
}
}
int linphone_init()
{
int ret = 0;
pthread_mutex_init(&linphone_work_status_mutex,0);
if(pipe(fd1) < 0 || pipe(fd2) < 0)
{
printf("create pipe failed!\\n");
return -1;
}
ret = pthread_create(&linphone_init_t,0,linphone_init_proc,0);
if(0 != ret)
{
printf("create linphone init proc failed!\\n");
return ret;
}
set_linphone_status(LINPHONE_ON_IDLE);
ret = pthread_create(&linphone_read_status_t,0,linphone_read_status_proc,0);
if(0 != ret)
{
printf("create linphone read status proc failed!\\n");
return ret;
}
return 0;
}
int linphone_release()
{
pthread_join(linphone_init_t,0);
printf("start to release linphonec:\\n");
if(write(fd2[1],"quit\\n",5) != 5)
{
printf("write quit command failed,please retry!\\n");
return -1;
}
usleep(100*1000);
set_linphone_status(LINPHONE_NOT_INIT);
pthread_join(linphone_read_status_t,0);
printf("exit linphonec process ok.\\n");
pthread_mutex_destroy(&linphone_work_status_mutex);
char stop_command_buffer[50] = {0};
sprintf(stop_command_buffer,"kill %d",child_process_pid);
system(stop_command_buffer);
printf("exit child process ok.\\n");
return 0;
}
int get_linphone_status()
{
int ret = 0;
pthread_mutex_lock(&linphone_work_status_mutex);
ret = linphone_work_status;
pthread_mutex_unlock(&linphone_work_status_mutex);
return ret;
}
int linphone_call(char* ip_address)
{
char call_cmd[50] = {0};
if(LINPHONE_ON_IDLE == get_linphone_status())
{
sprintf(call_cmd,"call sip:toto@%s\\n",ip_address);
if(write(fd2[1],call_cmd,strlen(call_cmd)) != strlen(call_cmd))
{
printf("call command failed!");
return -1;
}
set_linphone_status(LINPHONE_ON_WAIT_FOR_ACCEPT);
}
else
{
printf("Warning:linphone is busy now!\\n");
return -1;
}
return 0;
}
int linphone_answer()
{
if(LINPHONE_ON_INCOMING == get_linphone_status())
{
set_linphone_status(LINPHONE_ON_ANSWER);
if(write(fd2[1],"answer\\n",7) != 7)
{
printf("answer failed!");
return -1;
}
}
else
{
printf("Warning:there are no incomming now!\\n");
return -1;
}
return 0;
}
int linphone_terminate()
{
if(LINPHONE_ON_CALL == get_linphone_status()||
LINPHONE_ON_ANSWER == get_linphone_status()||
LINPHONE_ON_WAIT_FOR_ACCEPT == get_linphone_status()||
LINPHONE_ON_INCOMING==get_linphone_status())
{
printf("start to terminate:\\n");
if(write(fd2[1],"terminate\\n",10) != 10)
{
printf("write terminate command failed!\\n");
return -1;
}
printf("terminate ok!\\n");
}
else
{
printf("linphone is not working.\\n");
return -1;
}
return 0;
}
int linphone_duration_time()
{
if(LINPHONE_ON_CALL == get_linphone_status()||LINPHONE_ON_ANSWER == get_linphone_status())
{
time_t time_now = 0;
time(&time_now);
return time_now - start_linphone_time;
}
else
{
printf("linphone is not working\\n");
return -1;
}
}
| 0
|
#include <pthread.h>
int count=0;
pthread_mutex_t inSem ;
int a,b;
pthread_mutexattr_t myAttr;
void *calcFun(void *data)
{
int sum=0;
pthread_mutex_lock(&inSem);
pthread_mutex_lock(&inSem);
sum=a+b;
printf("Sum=%d\\n",sum);
pthread_mutex_unlock(&inSem);
pthread_mutex_unlock(&inSem);
}
void *inputFun(void *data)
{
pthread_mutex_lock(&inSem);
pthread_mutex_lock(&inSem);
printf("Enter 2 values\\n");
scanf("%d%d",&a,&b);
pthread_mutex_unlock(&inSem);
pthread_mutex_unlock(&inSem);
}
int main()
{
pthread_t inputThread,calcThread;
pthread_mutexattr_init (&myAttr);
pthread_mutexattr_settype (&myAttr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&inSem,&myAttr);
pthread_create(&inputThread,0,inputFun,0);
pthread_create(&calcThread,0,calcFun,0);
pthread_join(inputThread,0);
pthread_join(calcThread,0);
pthread_mutex_destroy(&inSem);
pthread_mutexattr_destroy (&myAttr);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t phil[5];
static pthread_mutex_t forks[5];
short timeout = 1;
void eat(int tid) {
int left = tid, right = (tid + 1) % 5;
int r = 0;
printf("Philosopher %d waiting for fork %d\\n", tid, left);
pthread_mutex_lock(&forks[left]);
if (pthread_mutex_trylock(&forks[right])) {
printf("Philosopher %d could not grab fork %d and is therefore continuing to think\\n",
tid, right);
} else {
r = rand() % 5 + 1;
printf("Philosopher %d is eating for %d s\\n", tid, r);
sleep(r);
printf("Philosopher %d has finished eating\\n", tid);
pthread_mutex_unlock(&forks[right]);
}
pthread_mutex_unlock(&forks[left]);
return;
}
void think(int tid) {
int r = 0;
r = rand() % 5 + 1;
printf("Philosopher %d is thinking for %d s\\n", tid, r);
sleep(r);
return;
}
void *philosophise(void *arg) {
int *tid = (int *) arg;
while (timeout) {
think(*tid);
eat(*tid);
}
pthread_exit(0);
}
int main() {
int i, tids[5];
for (i = 0; i < 5; i++) {
if(pthread_mutex_init(&forks[i], 0))
exit(-1);
}
sleep(1);
for (i = 0; i < 5; i++) {
tids[i] = i;
if(pthread_create(&phil[i], 0, philosophise, (void *) &tids[i]))
exit(-2);
}
sleep(20);
timeout = 0;
for (i = 0; i < 5; i++) {
pthread_join(phil[i], 0);
}
for (i = 0; i < 5; i++) {
pthread_mutex_destroy(&forks[i]);
}
return 0;
}
| 0
|
#include <pthread.h>
struct message_t{
int data;
int row;
int col;
int command;
struct message_t *next;
} typedef message;
pthread_mutex_t text_ = PTHREAD_MUTEX_INITIALIZER;
int row;
int col;
int view_min;
int view_max;
message* pop(){
}
void push(message* m_){
}
int redraw(int min_line, int max_line,int r_, int c_, int insert_){
erase();
if(max_line - min_line != LINES-1){
perror("HELP");
pthread_exit(0);
}
move(0,0);
pthread_mutex_lock(&text_);
for(;min_line < max_line;min_line++){
char *line;
if(getLine(min_line,&line) == 0)
break;
int j;
for(j=0;j < strlen(line);j++){
addch(*(line+j));
}
addch('\\n');
}
pthread_mutex_unlock(&text_);
if(insert_){
standout();
mvaddstr(LINES-1, COLS-20, "INPUT MODE");
standend();
}
move(r_,c_);
refresh();
return 1;
}
void input_mode(){
int c;
redraw(view_min, view_max, row, col, 1);
refresh();
for(;;){
c = getch();
if(c == (('D') & 037)){
break;
}
int insert_row = row+view_min;
int insert_col = col;
if((col<COLS-1) && (col<LINEMAX-1)){
col++;
}else{
col = 0;
if(row < LINES - 2){
row++;
}else{
view_min++;
view_max++;
}
}
redraw(view_min,view_max,row,col,1);
}
redraw(view_min,view_max,row,col,0);
}
void loop(){
int c;
while(1){
move(row,col);
refresh();
c = getch();
switch(c){
case 'h':
case KEY_LEFT:
if(col > 0)
col--;
else
flash();
break;
case 'j':
case KEY_DOWN:
if(row < LINES -2)
row++;
else
if(view_max+1<=getLineLength())
redraw(++view_min,++view_max,row,col,0);
else
flash();
break;
case 'k':
case KEY_UP:
if(row > 0)
row--;
else
if(view_min-1 > -1)
redraw(--view_min,--view_max,row,col,0);
else
flash();
break;
case 'l':
case KEY_RIGHT:
if((col<COLS-1) && (col<LINEMAX-1))
col++;
else
flash();
break;
case 'i':
case KEY_IC:
input_mode();
break;
case 'x':
flash();
int del_row = row+view_min;
int del_col = col;
redraw(view_min,view_max,row,col,0);
break;
case 'w':
flash();
break;
case 'q':
endwin();
default:
flash();
break;
}
}
}
void *start_UI(void *threadid){
initscr();
cbreak();
nonl();
noecho();
idlok(stdscr, TRUE);
keypad(stdscr,TRUE);
view_min = 0;
view_max = LINES-1;
redraw(view_min,view_max,row,col,0);
refresh();
loop();
}
void *autosave(void *threadid){
}
int main(int argc, char **argv){
row = 0;
col = 0;
}
| 1
|
#include <pthread.h>
int ans = 0, a, b, n, intensity, thread_ans[20], number_of_threads, choice = 1;
int loop_done = 0, granularity, current_iteration = 0;
pthread_mutex_t thread_granularity_lock, thread_ans_lock, thread_current_iteration_lock, thread_ans_array_lock;
int get_start_iteration()
{
return current_iteration;
}
int get_end_iteration()
{
pthread_mutex_lock(&thread_current_iteration_lock);
current_iteration += granularity;
pthread_mutex_unlock(&thread_current_iteration_lock);
return current_iteration;
}
void* run_thread()
{
int begin,end;
double intermediate_result;
pthread_t thread_id = pthread_self();
pthread_mutex_lock(&thread_ans_array_lock);
thread_ans[thread_id]=0;
pthread_mutex_unlock(&thread_ans_array_lock);
while(loop_done != 1)
{
pthread_mutex_lock(&thread_granularity_lock);
begin = get_start_iteration();
end = get_end_iteration();
pthread_mutex_unlock(&thread_granularity_lock);
double loop_ans;
loop_ans = 0;
for (int i = begin; i < end; ++i)
{
intermediate_result = (a+(i+0.5)*((b-a)/n));
intermediate_result = intermediate_result * intermediate_result;
intermediate_result = intermediate_result*((b-a)/n);
if(choice == 1)
{
pthread_mutex_lock(&thread_ans_lock);
ans += intermediate_result;
pthread_mutex_unlock(&thread_ans_lock);
}
if(choice == 2)
{
loop_ans += intermediate_result;
}
if(choice == 3)
{
pthread_mutex_lock(&thread_ans_array_lock);
thread_ans[thread_id] += intermediate_result;
pthread_mutex_unlock(&thread_ans_array_lock);
}
for (int k = 0; k < intensity; ++k)
{
printf("\\n %lf", intermediate_result);
intermediate_result = intermediate_result * intermediate_result;
intermediate_result = sqrt(intermediate_result);
}
}
if(choice == 2)
{
pthread_mutex_lock(&thread_ans_lock);
ans += loop_ans;
pthread_mutex_unlock(&thread_ans_lock);
}
}
}
int main(int argc, char *argv[]) {
a = atoi(argv[1]);
b = atoi(argv[2]);
n = atoi(argv[3]);
intensity = atoi(argv[4]);
number_of_threads = atoi(argv[5]);
choice = atoi(argv[6]);
if (argc < 7)
{
printf("\\n Please input 6 arguments.");
exit(0);
}
pthread_t thread_array[number_of_threads];
pthread_mutex_init(&thread_ans_lock, 0);
pthread_mutex_init(&thread_granularity_lock, 0);
pthread_mutex_init(&thread_current_iteration_lock, 0);
pthread_mutex_init(&thread_ans_array_lock, 0);
clock_t begin = clock();
for (int i = 0; i < number_of_threads; ++i)
{
pthread_create(&thread_array[i], 0, run_thread, 0);
}
for (int i = 0; i < number_of_threads; ++i)
{
pthread_join(thread_array[i], 0);
ans += thread_ans[i];
}
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("FInal Answer is: %lf", ans);
return 0;
}
| 0
|
#include <pthread.h>
size_t k;
int file;
char* word;
int N;
pthread_t* threads;
sigset_t mask;
pthread_mutex_t mutex;
pthread_t main_thread_id;
struct thread_args {
int id;
} **args;
void exit_program(int status, char* message) {
if(status == 0) {
printf("%s\\n",message);
} else {
perror(message);
}
exit(status);
}
int seek_for_word(char *buffer) {
char id_str[sizeof(int)], text[RECORDSIZE+1];
char *strtok_pointer;
char strtok_buf[RECORDSIZE*k];
strtok_pointer = strtok_buf;
for(int i =0;i<k;++i) {
char *p = strtok_r(buffer, SEPARATOR,&strtok_pointer);
strcpy(id_str, p);
int id = atoi(id_str);
p = strtok_r(0, "\\n",&strtok_pointer);
if(p!=0) {
strncpy(text, p, RECORDSIZE+1);
if (strstr(text, word) != 0) {
return id;
}
}
}
return -1;
}
void signal_handler(int signum) {
pthread_mutex_lock(&mutex);
pthread_t id = pthread_self();
printf("Catched singal %d, my id: %zu", signum, id);
if(id == main_thread_id) {
printf(" I'm main thread\\n");
} else {
printf(" I'm worker thread\\n");
}
fflush(stdin);
pthread_mutex_unlock(&mutex);
}
void init_signals() {
struct sigaction sa;
sigemptyset(&(sa.sa_mask));
sa.sa_flags = 0;
sa.sa_handler = signal_handler;
if(sigaction(SIGUSR1,&sa, 0) == -1) {
exit_program(1,"Couldn't initialize signal handlers for SIGUSR1");
}
struct sigaction sa2;
sigemptyset(&(sa2.sa_mask));
sa2.sa_flags = 0;
sa2.sa_handler = signal_handler;
if(sigaction(SIGTERM,&sa2,0) == -1) {
exit_program(1,"Couldn't initialize signal handlers for SIGTERM");
}
}
void *parallel_reader(void *arg) {
int id;
char buffer[1024*k];
struct thread_args *tmp = arg;
int jump = tmp->id;
long multiplier = RECORDSIZE*jump*k;
while(pread(file,buffer,RECORDSIZE*k,multiplier) > 0) {
if((id = seek_for_word(buffer)) != -1) {
printf("Found the word %s! Record id: %d, thread id: %zu\\n",word,id,pthread_self());
}
multiplier += (N*RECORDSIZE*k);
}
printf("End of thread life.\\n");
while(1);
}
void exit_handler() {
if(file!=0) {
close(file);
}
if(threads != 0) {
free(threads);
}
if(args !=0) {
for (int i = 0; i < N; ++i) {
if (args[i] != 0)
free(args[i]);
}
free(args);
}
}
void init_mask() {
sigemptyset(&mask);
sigaddset(&mask, SIGUSR1);
sigaddset(&mask, SIGTERM);
}
int get_signal(int n) {
switch(n) {
case 1:
return SIGUSR1;
case 2:
return SIGTERM;
case 3:
return SIGKILL;
default:
return SIGSTOP;
}
}
char *get_signal_str(int n) {
switch(n) {
case 1:
return "SIGUSR1";
case 2:
return "SIGTERM";
case 3:
return "SIGKILL";
default:
return "SIGSTOP";
}
}
int main(int argc, char ** argv) {
if(argc != 6) {
exit_program(0, "Pass 4 arguments: N - the number of threads, filename - the name of the file to read records from"
"k - the number of records read by a thread in a single access, word - the word we seek in the file for, signal - the type of signal to send "
"1 - SIGUSR1, 2 - SIGTERM, 3 - SIGKILL, 4 - SIGSTOP\\n");
}
atexit(exit_handler);
N = atoi(argv[1]);
char *filename = argv[2];
k = (size_t) atoi(argv[3]);
if(k<=0 || N <= 0) {
exit_program(0,"Pass the N and k parameters > 0");
}
word = argv[4];
init_signals();
if((file = open(filename, O_RDONLY)) == -1) {
exit_program(1, "Couldn't open the file to read records from");
}
main_thread_id = pthread_self();
pthread_mutex_init(&mutex,0);
threads = malloc(sizeof(int)*N);
args = malloc(sizeof(struct thread_args*)*N);
for(int i=0;i<N;++i) {
args[i] = malloc(sizeof(struct thread_args));
args[i]->id = i;
if(pthread_create(&threads[i],0,parallel_reader,args[i])) {
exit_program(1,"Failed to create thread");
}
}
int signal = atoi(argv[5]);
printf("Sending %s to process...\\n",get_signal_str(signal));
kill(getpid(),get_signal(signal));
printf("Sent!\\n");
pthread_mutex_destroy(&mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(800)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR:
__VERIFIER_error(); return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(800))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if ((push(arr,tmp)==(-1)))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(
i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
struct Triangle{
float base,height;
};
struct SemiCircle{
float radius;
};
struct Rectangle{
float breadth,length;
};
struct Square{
float side;
};
struct Trapezium{
float p1,p2,height;
};
float totalArea=0;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void *AreaOfSemiCircle(void *dimension){
float area;
int rc;
struct SemiCircle temp = *((struct SemiCircle *) dimension);
area=3.141592654*temp.radius*temp.radius/2;
pthread_mutex_lock(&mutex);
totalArea+=area;
pthread_mutex_unlock(&mutex);
printf("AreaOfSemiCircle: %f and totalArea: %f\\n",area,totalArea);
}
void *AreaOfTriangle(void * dimension){
struct Triangle temp=*(struct Triangle*)dimension;
float area=(temp.base*temp.height)/2;
pthread_mutex_lock(&mutex);
totalArea+=area;
pthread_mutex_unlock(&mutex);
printf("AreaOfTriangle: %f and totalArea: %f\\n",area,totalArea);
}
void *AreaOfTrapezium(void * dimension){
struct Trapezium temp=*(struct Trapezium*)dimension;
float area=((temp.p1+temp.p2)*temp.height)/2;
pthread_mutex_lock(&mutex);
totalArea+=area;
pthread_mutex_unlock(&mutex);
printf("AreaOfTrapezium: %f and totalArea: %f\\n",area,totalArea);
}
void main (void){
pthread_t th[6];
struct Triangle t1,t2;
t1.base=50; t1.height=20;
t2.base=100; t2.height=20;
struct SemiCircle sc1;
sc1.radius=45/2;
struct Trapezium tz1,tz2,tz3;
tz1.p1=50; tz1.p2=80; tz1.height=20;
tz2.p1=80; tz2.p2=65; tz2.height=45;
tz3.p1=65; tz3.p2=100; tz3.height=30;
pthread_create(&th[0],0,AreaOfTriangle,(void*)&t1);
pthread_create(&th[1],0,AreaOfTriangle,(void*)&t2);
pthread_create(&th[2],0,AreaOfSemiCircle,(void*)&sc1);
pthread_create(&th[3],0,AreaOfTrapezium,(void*)&tz1);
pthread_create(&th[4],0,AreaOfTrapezium,(void*)&tz2);
pthread_create(&th[5],0,AreaOfTrapezium,(void*)&tz3);
pthread_exit("succces");
}
| 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 somme_alea;
int cpt;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_cpt = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_cpt = PTHREAD_COND_INITIALIZER;
void* thread_rand(void * arg){
int random_val = (int) ((float) 10 * rand() /(32767 + 1.0));
printf("Mon num d'ordre : %d \\t mon tid %d \\t valeur generee : %d\\n", (*(int *)arg), (int)pthread_self(), random_val);
pthread_mutex_lock(&mutex);
somme_alea += random_val;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex_cpt);
cpt++;
if (cpt == 5){
pthread_cond_signal(&cond_cpt);
}
pthread_mutex_unlock(&mutex_cpt);
pthread_exit((void *)0);
}
void * print_thread(void * arg){
pthread_mutex_lock(&mutex_cpt);
pthread_cond_wait(&cond_cpt, &mutex_cpt);
pthread_mutex_unlock(&mutex_cpt);
printf("La somme des valeurs generees par les threads est : %d \\n", somme_alea);
pthread_exit((void *)0);
}
int main(int argc, char * argv[]){
int i, p, status;
int tab[5];
pthread_t tid[5];
pthread_t pt_print_tid;
somme_alea = 0;
cpt = 0;
srand(time(0));
if (pthread_create(&pt_print_tid, 0, print_thread, 0) != 0){
perror("pthread_create");
exit(1);
}
for(i=0; i<5; i++){
tab[i]=i;
if((p=pthread_create(&(tid[i]), 0, thread_rand, &tab[i])) != 0){
perror("pthread_create");
exit(1);
}
}
for(i=0; i<5; i++){
if(pthread_join(tid[i],(void**) &status) != 0){
perror("pthread_join");
exit(1);
}
}
return 0;
}
| 1
|
#include <pthread.h>
void header();
void tail();
unsigned short crc16(char *data_p, unsigned short length);
unsigned long long int samp;
FILE *vfp;
long double startTime;
void *vlbiData(void *pa)
{
int j=0,ii=0;
int check;
int flag;
double ts;
int err=0;
unsigned long long int temp,bufferLen = adc.segment*1024*1024,i=0,length;
char *tempData,*block;
char tempName[50],vfilename[50];
startTime = mjdnow();
samp=0;
if(adc.mark5 == 1) block = (char *) malloc(2500);
if(adc.rdf==1)
{
datenow(tempName,utc);
strcpy(sWord,"RDF1");
strcpy(stationName,"ORT");
strcpy(sourceName,adc.nameOfSource);
strcpy(expName,"TEST");
strcpy(&receiveMode,"I");
strcpy(rdrMode,"DAS");
totalFlowRate = (unsigned short)(adc.samplingRate);
strcpy(vfilename,"ORT_");
strcat(vfilename,tempName);
strcat(vfilename,".rdf");
vfp = fopen(vfilename,"wb");
chown(vfilename,1000,1000);
rdfHeader(vfp);
}
else
{
strcpy(vfilename,filename);
strcat(vfilename,"_ort.vlbi");
vfp = fopen(vfilename,"wb");
chown(vfilename,1000,1000);
}
if(adc.lChannel==2) tempData = (char *) malloc(bufferLen/2);
else tempData = (char *) malloc(bufferLen);
pthread_mutex_lock(&vlbiStop_mutex);
flag = vlbiStop;
pthread_mutex_unlock(&vlbiStop_mutex);
printf("\\n loop started......... \\n ");
while(flag ==1 && adc.mark5 == 0)
{
semaphore_p(sem_fft2);
if(fft2Status[0]==1)
{
if(adc.lChannel==2)
{
for(i=0;i<(bufferLen/2);i++)
{
tempData[i] = (char)(int)(((float)data[2*i] + (float)data[2*i+1])/2);
if(i==0) printf("\\n %d %d %d\\n",tempData[i],data[2*i+1],data[2*i]);
}
fwrite(tempData,1,bufferLen/2,vfp);
}
if(adc.lChannel==0 || adc.lChannel == 1)
{
fwrite(data,1,bufferLen,vfp);
if(i==0) printf("\\n %d \\n",data[i]);
}
}
fft2Status[0]=0;
semaphore_v(sem_fft2);
pthread_mutex_lock(&vlbiStop_mutex);
flag = vlbiStop;
pthread_mutex_unlock(&vlbiStop_mutex);
}
while(flag ==1 && adc.mark5 == 1)
{
semaphore_p(sem_fft2);
if(fft2Status[0]==1)
{
if(adc.lChannel==2)
{
for(i=0;i<(bufferLen/2);i++)
{
tempData[i] = (char)(int)(((float)data[2*i] + (float)data[2*i+1])/2);
if(i==0) printf("\\n %d %d %d\\n",tempData[i],data[2*i+1],data[2*i]);
}
length = bufferLen/2;
}
if(adc.lChannel==0 || adc.lChannel == 1)
{
memcpy(tempData,data,bufferLen);
if(i==0) printf("\\n %d \\n",tempData[i]);
length = bufferLen;
}
for(i=0;i<length;i++)
{
if(samp%2500==0) header();
block[samp%2500]=tempData[i];
samp++;
if(samp%2500==0)
{
fwrite(block,1,2500,vfp);
tail();
}
}
}
fft2Status[0]=0;
semaphore_v(sem_fft2);
pthread_mutex_lock(&vlbiStop_mutex);
flag = vlbiStop;
pthread_mutex_unlock(&vlbiStop_mutex);
}
return;
}
void header()
{
char *tempTime,*bcdTime;
long double time,decimal;
char *finalTime;
char *c;
int i;
unsigned int syncWord = 0xffff;
unsigned short crc;
unsigned long long int shift;
tempTime = (char *) malloc(24);
finalTime = (char *) malloc(24);
bcdTime = (char *) malloc(12);
c = (char *) malloc(1);
time = startTime+((long double)samp/(long double)(adc.samplingRate*86400*(pow(10,6))));
sprintf(tempTime,"%6.16Lf",time);
decimal = time-((long double)(int)(time));
shift = (pow(10,9)*decimal);
for(i=0;i<23;i++)
{
if(i==0) finalTime[i] = (char)(int)0;
if(i>0 && i<6)
{
c[0]=(int)tempTime[i-1];
finalTime[i] = (char)(int)atoi(c);
if(finalTime[i] > 10) printf("\\nsome thing is wrong here %s %d \\n",c,finalTime[i]);
}
if(i>6 && i<24)
{
c[0]=(int)tempTime[i-1];
finalTime[i-1] = (char)(int)atoi(c);
}
}
for(i=0;i<12;i++)
{
bcdTime[i] = (finalTime[2*i]<<4) + finalTime[2*i+1];
}
crc = crc16(bcdTime,11);
fwrite(&syncWord,sizeof(unsigned int),1,vfp);
fwrite(bcdTime,1,12,vfp);
fwrite(&crc,sizeof(unsigned short),1,vfp);
free(tempTime);
free(finalTime);
free(bcdTime);
free(c);
return;
}
void tail()
{
char rr,ss,bb,f;
ss = 16;
bb = 15;
f = 4;
f <<=4;
fwrite(&rr,1,1,vfp);
fwrite(&ss,1,1,vfp);
fwrite(&bb,1,1,vfp);
fwrite(&f,1,1,vfp);
}
| 0
|
#include <pthread.h>
char buf[200];
int size;
} Message;
pthread_mutex_t mutex= PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond= PTHREAD_COND_INITIALIZER;
Message messages[10];
int next_message= 0;
void broadcast(char *buf, int size) {
Message *msg;
pthread_mutex_lock(&mutex);
msg= &messages[next_message%10];
memcpy(msg->buf, buf, size);
msg->size= size;
next_message++;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
int get_message(char *buf, int msg_id) {
int size;
Message *msg;
pthread_mutex_lock(&mutex);
while (msg_id>=next_message) {
printf("waiting\\n");
pthread_cond_wait(&cond, &mutex);
}
printf("got message\\n");
msg= &messages[msg_id%10];
size= next_message-msg_id>10 ? 0 : msg->size;
memcpy(buf, msg->buf, size);
pthread_mutex_unlock(&mutex);
return size;
}
void *writer_fun(long s) {
char buf[200];
int curr= next_message;
for (;;) {
int cnt= get_message(buf, curr);
if (cnt>0) {
printf("writing message %d (%d bytes)\\n", curr, cnt);
if (write(s, buf, cnt)<=0) {
printf("broken pipe\\n");
return 0;
}
}
curr++;
}
}
void *serv(long s) {
int cnt, size = 200;
char buf[200];
pthread_t writer;
if (pthread_create(&writer, 0, (Thread_fun)writer_fun, (void*)s) != 0) {
fprintf(stderr, "No pude crear un writer\\n");
return 0;
}
fprintf(stderr, "cliente conectado\\n");
while ((cnt= read(s, buf, size)) > 0) {
fwrite(buf, cnt, 1, stdout);
broadcast(buf, cnt);
}
close(s);
pthread_join(writer, 0);
fprintf(stderr, "cliente desconectado\\n");
return 0;
}
int main(int argc, char **argv) {
long s, s2;
pthread_t pid;
int port= argc>=2 ? atoi(argv[1]) : 1818;
signal(SIGPIPE, SIG_IGN);
s = j_socket();
if(j_bind(s, port) < 0) {
fprintf(stderr, "bind failed\\n");
exit(1);
}
for(;;) {
pthread_attr_t attr;
s2= j_accept(s);
pthread_attr_init(&attr);
if (pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0) {
fprintf(stderr, "No se puede establecer el atributo\\n");
}
if ( pthread_create(&pid, &attr, (Thread_fun)serv, (void *)s2) != 0) {
fprintf(stderr, "No pude crear thread para nuevo cliente %ld!!!\\n", s2);
close(s2);
}
pthread_attr_destroy(&attr);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t thread_count_lock = PTHREAD_MUTEX_INITIALIZER;
int thread_count = 0;
int num_threads = 0;
int initialized = 0;
int global_sense = 1;
int test = 0;
int *local_sense = 0;
int use_busy_wait =0;
int omp_thread_count =4;
int num_barriers = 1;
int busy_wait_count =100;
void barrier(){
int i,thread_id;
while(!initialized){
{
thread_count = omp_get_num_threads();
num_threads = thread_count;
local_sense = (int *)calloc(num_threads, sizeof(int));
for(i=0;i<num_threads;i++)
local_sense[i] = 1;
initialized = 1;
}
}
thread_id = omp_get_thread_num();
pthread_mutex_lock(&thread_count_lock);
thread_count--;
if(thread_count == 0){
thread_count = num_threads;
global_sense ^= 1;
local_sense[thread_id] ^= 1;
pthread_mutex_unlock(&thread_count_lock);
return;
}
else{
pthread_mutex_unlock(&thread_count_lock);
while (local_sense[thread_id] == global_sense){
if(use_busy_wait)
for(i=0;i<busy_wait_count;i++);
else
;
}
local_sense[thread_id] ^= 1;
return;
}
}
void usage(){
printf("Please check arguments!\\n");
printf("Usage: ./cntg <omp_thread_count> <num_barriers> <use_busy_wait> <busy_wait_count>\\n\\n");
printf("omp_thread_count: Number of threads in the omp parallel region (<50)\\n");
printf("num_barriers: Number of barriers to simulate (<1000)\\n");
printf("use_busy_wait: Use busy wait while spinning to reduce memory contention (1 or 0)\\n");
printf("busy_wait_count: Ceiling for the busy wait\\n");
exit(0);
}
int main(int argc, char* argv[]){
if(argc!=5){
usage();
}
omp_set_dynamic(0);
omp_thread_count = atoi(argv[1]);
if(omp_thread_count > 50 || omp_thread_count <=1)
usage();
num_barriers = atoi(argv[2]);
if(num_barriers > 1000 || num_barriers <1)
usage();
use_busy_wait = atoi(argv[3]);
if(use_busy_wait!=0 && use_busy_wait!=1)
usage();
busy_wait_count = atoi(argv[4]);
struct timeval start,end;
omp_set_num_threads(omp_thread_count);
gettimeofday(&start, 0);
{
int i;
for(i=0;i<num_barriers;i++){
test++;
barrier();
}
fprintf(stderr,"%3d\\t",test);
}
gettimeofday(&end, 0);
fprintf(stderr,"%10.4f\\tusec\\n",(((end.tv_sec*1000000)+end.tv_usec)-((start.tv_sec*1000000)+start.tv_usec))/(double)num_barriers);
}
| 0
|
#include <pthread.h>
struct student{
int id;
int numQuestions;
int questionNum;
};
int totalStudents;
int inOffice, studentZ;
sem_t readyForQuestion, questionWait, answerWait, capacity;
pthread_t professor;
pthread_mutex_t question_lock;
int identification;
void Professor();
void *StartProfessor();
void AnswerStart();
void AnswerDone();
void Student(int id);
void * StartStudent(void * student);
void QuestionStart();
void QuestionDone();
void nap();
void EnterOffice();
void LeaveOffice();
void Professor()
{
pthread_mutex_init(&question_lock, 0);
sem_init(&readyForQuestion,1,0);
sem_init(&questionWait,1,0);
sem_init(&answerWait,1,0);
sem_init(&capacity,0,inOffice);
studentZ = 0;
pthread_create(&professor, 0, StartProfessor, 0);
}
void * StartProfessor()
{
while(1)
{
sem_post(&readyForQuestion);
sem_wait(&questionWait);
AnswerStart();
AnswerDone();
sem_post(&answerWait);
}
}
void AnswerStart()
{
printf("Professor starts to answer question for student %d\\n", identification);
}
void AnswerDone()
{
printf("Professor is done with answer for student %d\\n", identification);
}
void Student(int id)
{
struct student * newStd = malloc(sizeof(struct student));
newStd->id = id;
newStd->numQuestions = (id % 4) + 1;
newStd->questionNum = 0;
pthread_t stack;
pthread_create(&stack, 0, (void *) StartStudent, (void *) newStd);
}
void *StartStudent(void * student)
{
struct student * std = student;
studentZ++;
while(std->numQuestions > std->questionNum)
{
sem_wait(&readyForQuestion);
pthread_mutex_lock(&question_lock);
identification = std->id;
QuestionStart();
sem_post(&questionWait);
sem_wait(&answerWait);
QuestionDone();
pthread_mutex_unlock(&question_lock);
std->questionNum++;
if(std->questionNum == std->numQuestions)
{
LeaveOffice();
studentZ--;
if(studentZ == 0)
nap();
}
}
}
void QuestionStart()
{
printf("Student %d asks a question\\n", identification);
}
void QuestionDone()
{
printf("Student %d is satisfied\\n", identification);
}
void nap()
{
printf("professor is napping...\\n");
}
void EnterOffice()
{
printf("student %d shows up in the office\\n", identification);
}
void LeaveOffice()
{
printf("Student %d leaves the office\\n", identification);
}
int main(int argc, char *argv[])
{
totalStudents = atoi(argv[1]);
inOffice = atoi(argv[2]);
int i;
Professor();
for(i = 0 ; i < totalStudents; i++)
{
Student(i);
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void printCalEvDebug(struct calendarEvent_t c){
printf("Type: %c, Title: %s, Date: %s, Time: %s, location: %s\\n",c.type, c.calItem.title, c.calItem.date, c.calItem.time, c.calItem.location);
}
int parseEmail(char * buffer, struct calendarEvent_t *c){
char *pch = strtok (buffer," ");
unsigned int counter = 0;
while (pch != 0){
switch(counter++) {
case 0: break;
case 1: c->type = pch[0]; break;
case 2: memcpy(c->calItem.title,pch, strlen(pch)+1); break;
case 3: memcpy(c->calItem.date,pch, strlen(pch)+1); break;
case 4: memcpy(c->calItem.time,pch, strlen(pch)+1); break;
case 5: memcpy(c->calItem.location,pch, strlen(pch)-1); break;
}
pch = strtok (0, ",");
}
if (counter != 6) return -1;
return 0;
}
void * producer(void * arg) {
struct circularBuffer *circbuf = (struct circularBuffer*) arg;
char *buffer = 0;
int charsRead = 0;
long unsigned int len = 0;
struct calendarEvent_t c;
while(1) {
char charsRead = getline(&buffer,&len,stdin);
int parsed = 0;
if ( charsRead != -1 )
parsed = parseEmail(buffer, &c);
else
c.type = 'E';
if (charsRead == -1 || parsed != -1) {
DEBUG_PRINT( ("Type: %c, Title: %s, Date: %s, Time: %s, location: %s\\n",c.type, c.calItem.title, c.calItem.date, c.calItem.time, c.calItem.location) );
pthread_mutex_lock(&mtx);
{
while ( circbuf->numItems == circbuf->size )
pthread_cond_wait(&prodCond,&mtx);
memcpy( &(circbuf->buffer[circbuf->in]), &c, sizeof(struct calendarEvent_t) );
circbuf->in = (circbuf->in + 1) % circbuf->size;
circbuf->numItems++;
if (circbuf->numItems == 1)
pthread_cond_signal(&consCond);
}
pthread_mutex_unlock(&mtx);
}
if (charsRead == -1)
break;
}
free(buffer);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
struct substring_t {
char *s1, *s2;
int n1, n2, start, end, id;
};
int main(int argc, char **argv);
int open_file(FILE **fd, char *fn);
int read_line(FILE *fd, char **result);
void tcount_substrings(substring sub);
void *pcount_substrings(void *args);
int total;
pthread_mutex_t mutex;
int open_file(FILE **fd, char *fn)
{
*fd=fopen(fn, "r");
if(!fd)
{
perror("[-] Failed to open file!\\n");
return -1;
}
return 0;
}
int read_line(FILE *fd, char **result)
{
int len;
*result=(char *)malloc(sizeof(char)*1024);
if(!(*result))
{
perror("[-] Out of memory!\\n");
return -1;
}
*result = fgets(*result, 1024, fd);
len = strlen(*result);
if(len > 0)
{
(*result)[len-1] = 0;
len--;
}
if(!(*result))
{
return -1;
}
return len;
}
void tcount_substrings(substring sub)
{
pthread_t thread[12];
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
int block_size, tcount;
void *status;
block_size = (sub.n1)/12;
tcount = 0;
assert(sub.n2 < block_size);
assert(sub.n1 % 12 == 0);
if (sub.n1 < sub.n2)
{
perror("[-] Size of first string must be greater than or equal to size of second string!\\n");
return;
}
substring *args;
args = (substring *)malloc(sizeof(substring)*12);
for(int i = 0; i < 12; i++)
{
substring *arg;
arg = args + i;
int start, end, block_count;
start = i*block_size;
end = start + block_size;
arg->s1 = sub.s1;
arg->n1 = sub.n1;
arg->s2 = sub.s2;
arg->n2 = sub.n2;
arg->id = tcount;
arg->start = start;
arg->end = end;
if(!!pthread_create(&thread[tcount], &attr, pcount_substrings, (void *)arg))
{
printf("[-] Failed to create thread %d\\n", i);
break;
}
tcount++;
}
pthread_attr_destroy(&attr);
for(int i = 0; i < tcount; i++)
{
if(pthread_join(thread[i], &status))
{
perror("[-] Failed to join thread!\\n");
}
}
free(args);
}
void *pcount_substrings(void *args)
{
substring sub = *((substring *)args);
int count;
count = 0;
for(int i = sub.start; i <= sub.end; i++)
{
count = 0;
for(int j = 0; j < sub.n2; j++)
{
if(*(sub.s1+i+j)!=*(sub.s2+j))
{
break;
}
else
{
count++;
}
if(count == sub.n2)
{
pthread_mutex_lock(&mutex);
total++;
pthread_mutex_unlock(&mutex);
}
}
}
}
int main(int argc, char **argv)
{
int n1, n2;
char *s1, *s2;
FILE *fd;
substring sub;
char *fn = "strings.txt";
pthread_mutex_init(&mutex, 0);
if(open_file(&fd,fn))
{
exit(-1);
}
if((n1 = read_line(fd, &s1)) == -1)
{
perror("[-] Failed to read line 1 from file\\n");
exit(-1);
}
if((n2 = read_line(fd, &s2)) == -1)
{
perror("[-] Failed to read line 2 from file\\n");
exit(-1);
}
if(n2>n1)
{
sub.s1 = s2;
sub.n1 = n2;
sub.s2 = s1;
sub.n2 = n1;
tcount_substrings(sub);
printf("[+] Found %d total occurances of %s in %s...\\n", total, s1, s2);
}
else
{
sub.s1 = s1;
sub.n1 = n1;
sub.s2 = s2;
sub.n2 = n2;
tcount_substrings(sub);
printf("[+] Found %d total occurances of %s in %s...\\n", total, s2, s1);
}
pthread_mutex_destroy(&mutex);
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
int fila[5];
int head = 0;
int tail = 0;
sem_t s_item, s_vaga;
pthread_mutex_t s_buffer;
void insertItem(int item){
fila[head] = item;
head = (head + 1) % 5;
}
int removeItem(){
int item = fila[tail];
tail = (tail + 1) % 5;
return item;
}
void *producer(void *id) {
int item;
while(1) {
sleep(1 / ((rand() % 10) + 1) );
sem_wait(&s_vaga);
pthread_mutex_lock(&s_buffer);
item = rand() % 100;
insertItem(item);
printf("P%01ld produziu %d\\n", (long)id, item);
pthread_mutex_unlock(&s_buffer);
sem_post(&s_item);
}
}
void *consumer(void *id) {
int item;
while(1) {
sleep(1 / ((rand() % 10) + 1) );
sem_wait(&s_item);
pthread_mutex_lock(&s_buffer);
item = removeItem();
printf(" C%01ld consumiu %d\\n", (long)id, item);
pthread_mutex_unlock(&s_buffer);
sem_post(&s_vaga);
}
}
void init(){
srand(time(0));
pthread_mutex_init(&s_buffer, 0);
sem_init(&s_vaga, 0, 5);
sem_init(&s_item, 0, 0);
}
int main (){
int i;
init();
pthread_t thread [2 + 3] ;
for (i = 0; i < 2; ++i)
pthread_create (&thread[i], 0, consumer, (void *) i) ;
for (i = 2; i < 2 + 3; ++i)
pthread_create (&thread[i], 0, producer, (void *) i) ;
sleep(10);
pthread_exit (0) ;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t *mptr;
int main(int argc, char **argv) {
int fd;
pid_t pid;
key_t key;
int shmid;
char *shm;
pthread_mutexattr_t mattr;
fd = open("/dev/zero", O_RDWR, 0);
mptr = (pthread_mutex_t *)mmap(0, sizeof(pthread_mutex_t), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
close(fd);
pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(mptr, &mattr);
pid = fork();
if(pid == 0) {
if(pthread_mutex_lock(mptr) == 0) {
printf("Process %d lock success\\n", getpid());
sleep(10);
pthread_mutex_unlock(mptr);
}
else
perror("lock");
exit(0);
}
if(pthread_mutex_lock(mptr) == 0) {
printf("Process %d lock success\\n", getpid());
sleep(10);
pthread_mutex_unlock(mptr);
}
else
perror("lock");
pthread_mutex_destroy(mptr);
munmap(mptr, sizeof(pthread_mutex_t));
return 0;
}
| 1
|
#include <pthread.h>
static int count = 0;
static pthread_mutex_t countlock = PTHREAD_MUTEX_INITIALIZER;
static int i;
int compile(char *s1, char *s2){
char *filename;
pid_t childpid;
int status;
printf("%s %s\\n", s1, s2);
if((filename = malloc(strlen(s2) + 3)) == 0)
return 0;
strcpy(filename, s2);
strcat(filename, ".c");
childpid = fork();
if(childpid == -1){
printf("Fail to fork\\n");
return 0;
}
if(childpid == 0){
execl(s1, "gcc", "-c", filename, 0);
printf("child fail to use execl to compile\\n");
return 0;
}
free(filename);
while(wait(&status) > 0){
if(WIFEXITED(status) && !WEXITSTATUS(status)){
return 1;
}
else
return 0;
}
}
void *threadcompile(void *arg){
char *filename;
int error;
filename = (char *)(arg);
if(compile("/usr/bin/gcc", filename) == 1){
increment();
}
return 0;
}
int increment(void) {
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
count++;
return pthread_mutex_unlock(&countlock);
}
int clearcount(void){
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
count = 0;
return pthread_mutex_unlock(&countlock);
}
int getcount(int *countp){
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
*countp = count;
return pthread_mutex_unlock(&countlock);
}
void *threadcompilereturn(void *arg){
char *filename;
int error;
i = 1;
filename = (char *)(arg);
if(compile("/usr/bin/gcc", filename) == 1){
perror("Compiled");
if(error = pthread_mutex_lock(&countlock)){
perror("Failed to lock");
return;
}
i = 0;
pthread_mutex_unlock(&countlock);
return &i;
}
return &i;
}
int getvalue(int *valuep){
int error;
if (error = pthread_mutex_lock(&countlock))
return error;
*valuep = i;
return pthread_mutex_unlock(&countlock);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexid;
int commonCounter= 0;
void * thread_function(void *);
int main(void)
{
pthread_t tID_1;
pthread_t tID_2;
if(pthread_mutex_init(&mutexid, 0) != 0 ) {
perror("pthread_mutex_init");
exit(1);
}
if ((pthread_create( &tID_1, 0, thread_function, (void *)1)) ||
(pthread_create( &tID_2, 0, thread_function, (void *)2))) {
perror("pthread_create");
exit (errno);
}
pthread_join(tID_1, (void **)0);
pthread_join(tID_2, (void **)0);
pthread_mutex_destroy(&mutexid);
}
void * thread_function(void *arg)
{
int loopCount;
int temp;
char buffer[80];
int i;
for (loopCount = 0; loopCount < 20; loopCount++) {
pthread_mutex_lock(&mutexid);
sprintf (buffer, "Common counter(%u) : from %d to ", (unsigned int)pthread_self(), commonCounter);
write(1, buffer, strlen(buffer));
temp = commonCounter;
for(i=0; i<500000; i++);
commonCounter = temp + 1;
sprintf (buffer, "%d\\n", commonCounter);
write(1, buffer, strlen(buffer));
for(i=0; i<500000; i++);
pthread_mutex_unlock(&mutexid);
}
}
| 1
|
#include <pthread.h>
static int gsum = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void *thread_func(void *arg)
{
int *start = (int *)arg;
int i;
for(i = *start; i < *start + 100; i++) {
pthread_mutex_lock(&mutex);
gsum += i;
pthread_mutex_unlock(&mutex);
}
return 0;
}
void pthread_sync()
{
pthread_t t1, t2;
int s;
int start1, start2;
start1 = 0;
s = pthread_create(&t1, 0, thread_func, &start1);
if(s != 0)
errExitEN(s, "pthread_create");
start2 = 100;
s = pthread_create(&t2, 0, thread_func, &start2);
if(s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(t1, 0);
s = pthread_join(t2, 0);
printf("result = %d\\n", gsum);
}
int start;
pthread_mutex_t *mtx;
}param;
static void *thread_func_error_checking_mutex(void *arg)
{
param *p = (param *)arg;
int i;
int s;
for(i = p->start; i < p->start + 100; i++) {
s = pthread_mutex_lock(p->mtx);
if(s != 0)
errExitEN(s, "pthread_mutex_lock");
gsum += i;
s = pthread_mutex_unlock(p->mtx);
if(s != 0)
errExitEN(s, "pthread_mutex_unlock");
}
return 0;
}
void pthread_sync_error_checking_mutex()
{
pthread_t t1, t2;
int s;
pthread_mutex_t mtx;
pthread_mutexattr_t mtx_attr;
s = pthread_mutexattr_init(&mtx_attr);
s = pthread_mutexattr_settype(&mtx_attr, PTHREAD_MUTEX_ERRORCHECK);
s = pthread_mutex_init(&mtx, &mtx_attr);
param p1, p2;
p1.mtx = &mtx;
p1.start = 0;
s = pthread_create(&t1, 0, thread_func_error_checking_mutex, &p1);
if(s != 0)
errExitEN(s, "pthread_create");
p2.mtx = &mtx;
p2.start = 100;
s = pthread_create(&t2, 0, thread_func_error_checking_mutex, &p2);
if(s != 0)
errExitEN(s, "pthread_create");
s = pthread_join(t1, 0);
s = pthread_join(t2, 0);
s = pthread_mutexattr_destroy(&mtx_attr);
s = pthread_mutex_destroy(&mtx);
printf("result = %d\\n", gsum);
}
| 0
|
#include <pthread.h>
struct generic_buffer * init_generic_buffers(int nb_buffers) {
int i;
struct generic_buffer *gb;
struct generic_buffer *next;
gb=malloc(sizeof(struct generic_buffer));
memset(gb,0,sizeof(struct generic_buffer));
next=gb;
for (i=0;i<nb_buffers-1;i++) {
gb=malloc(sizeof(struct generic_buffer));
memset(gb,0,sizeof(struct generic_buffer));
gb->next=next;
next=gb;
}
return gb;
}
struct generic_buffer *get_generic_buffer(struct buffer_pool * pool) {
struct generic_buffer *result;
pthread_mutex_lock(&pool->generic_buffers_mutex);
if (pool->generic_buffer_head!=0) {
result=pool->generic_buffer_head;
pool->generic_buffer_head=result->next;
pthread_mutex_unlock(&pool->generic_buffers_mutex);
return result;
} else {
pthread_mutex_unlock(&pool->generic_buffers_mutex);
return 0;
}
}
void leave_generic_buffer(struct buffer_pool * pool,struct generic_buffer *gb) {
pthread_mutex_lock(&pool->generic_buffers_mutex);
gb->next=pool->generic_buffer_head;
pool->generic_buffer_head=gb;
pthread_mutex_unlock(&pool->generic_buffers_mutex);
}
struct buffer_pool *init_buffer_pool(int nb_bufs) {
struct buffer_pool *result=malloc(sizeof(struct buffer_pool));
pthread_mutex_init(&result->generic_buffers_mutex, 0);
result->generic_buffer_head=init_generic_buffers(nb_bufs);
return result;
}
struct data_descriptor* init_data_descriptor_list(int nb_buffers) {
int i;
struct data_descriptor *result;
struct data_descriptor *dd;
struct data_descriptor *prev;
result=malloc(sizeof(struct data_descriptor));
memset(result,0,sizeof(struct data_descriptor));
result->id=-1;
prev=result;
for (i=0;i<nb_buffers-1;i++) {
dd=malloc(sizeof(struct data_descriptor));
memset(dd,0,sizeof(struct data_descriptor));
dd->id=-1;
prev->next=dd;
dd->prev=prev;
prev=dd;
}
result->prev=dd;
dd->next=result;
return result;
}
| 1
|
#include <pthread.h>
ssize_t jread(struct jfs *fs, void *buf, size_t count)
{
ssize_t rv;
off_t pos;
pthread_mutex_lock(&(fs->lock));
pos = lseek(fs->fd, 0, 1);
plockf(fs->fd, F_LOCKR, pos, count);
rv = spread(fs->fd, buf, count, pos);
plockf(fs->fd, F_UNLOCK, pos, count);
if (rv > 0)
lseek(fs->fd, rv, 1);
pthread_mutex_unlock(&(fs->lock));
return rv;
}
ssize_t jpread(struct jfs *fs, void *buf, size_t count, off_t offset)
{
ssize_t rv;
plockf(fs->fd, F_LOCKR, offset, count);
rv = spread(fs->fd, buf, count, offset);
plockf(fs->fd, F_UNLOCK, offset, count);
return rv;
}
ssize_t jreadv(struct jfs *fs, const struct iovec *vector, int count)
{
ssize_t rv;
off_t pos;
pthread_mutex_lock(&(fs->lock));
pos = lseek(fs->fd, 0, 1);
if (pos < 0)
return -1;
plockf(fs->fd, F_LOCKR, pos, count);
rv = readv(fs->fd, vector, count);
plockf(fs->fd, F_UNLOCK, pos, count);
pthread_mutex_unlock(&(fs->lock));
return rv;
}
ssize_t jwrite(struct jfs *fs, const void *buf, size_t count)
{
ssize_t rv;
off_t pos;
struct jtrans *ts;
ts = jtrans_new(fs, 0);
if (ts == 0)
return -1;
pthread_mutex_lock(&(fs->lock));
if (fs->open_flags & O_APPEND)
pos = lseek(fs->fd, 0, 2);
else
pos = lseek(fs->fd, 0, 1);
rv = jtrans_add_w(ts, buf, count, pos);
if (rv < 0)
goto exit;
rv = jtrans_commit(ts);
if (rv >= 0)
lseek(fs->fd, count, 1);
exit:
pthread_mutex_unlock(&(fs->lock));
jtrans_free(ts);
return (rv >= 0) ? count : rv;
}
ssize_t jpwrite(struct jfs *fs, const void *buf, size_t count, off_t offset)
{
ssize_t rv;
struct jtrans *ts;
ts = jtrans_new(fs, 0);
if (ts == 0)
return -1;
rv = jtrans_add_w(ts, buf, count, offset);
if (rv < 0)
goto exit;
rv = jtrans_commit(ts);
exit:
jtrans_free(ts);
return (rv >= 0) ? count : rv;
}
ssize_t jwritev(struct jfs *fs, const struct iovec *vector, int count)
{
int i;
size_t sum;
ssize_t rv;
off_t ipos, t;
struct jtrans *ts;
ts = jtrans_new(fs, 0);
if (ts == 0)
return -1;
pthread_mutex_lock(&(fs->lock));
if (fs->open_flags & O_APPEND)
ipos = lseek(fs->fd, 0, 2);
else
ipos = lseek(fs->fd, 0, 1);
t = ipos;
sum = 0;
for (i = 0; i < count; i++) {
rv = jtrans_add_w(ts, vector[i].iov_base,
vector[i].iov_len, t);
if (rv < 0)
goto exit;
sum += vector[i].iov_len;
t += vector[i].iov_len;
}
rv = jtrans_commit(ts);
if (rv >= 0)
lseek(fs->fd, sum, 1);
exit:
pthread_mutex_unlock(&(fs->lock));
jtrans_free(ts);
return (rv >= 0) ? sum : rv;
}
int jtruncate(struct jfs *fs, off_t length)
{
int rv;
plockf(fs->fd, F_LOCKW, length, 0);
rv = ftruncate(fs->fd, length);
plockf(fs->fd, F_UNLOCK, length, 0);
return rv;
}
off_t jlseek(struct jfs *fs, off_t offset, int whence)
{
off_t rv;
pthread_mutex_lock(&(fs->lock));
rv = lseek(fs->fd, offset, whence);
pthread_mutex_unlock(&(fs->lock));
return rv;
}
| 0
|
#include <pthread.h>
static void do_nothing(void *);
static int cs_add_unsafe(struct cs *set, const void *key);
static int cs_remove_unsafe(struct cs *set, const void *key);
static void *cs_find_unsafe(const struct cs *set, const void *key);
static void *cs_search_unsafe(struct cs *set, const void *key);
static void *cs_delete_unsafe(struct cs *set, const void *key);
struct cs {
int size_;
void *root_;
int (*cmpr_)(const void *, const void *);
void (*dtor_)(void *);
pthread_mutex_t mutex_;
};
struct cs *cs_new(
int (*cmpr)(const void *, const void *),
void (*dtor)(void *))
{
if (__builtin_expect(!!(!cmpr), 0)) {
errno = EINVAL;
return 0;
}
struct cs *const set = malloc(sizeof(struct cs));
if (__builtin_expect(!!(!set), 0))
return 0;
set->size_ = 0;
set->root_ = 0;
set->cmpr_ = cmpr;
set->dtor_ = dtor ? dtor : do_nothing;
pthread_mutex_init(&set->mutex_, 0);
return set;
}
int cs_size(struct cs *set)
{
pthread_mutex_lock(&set->mutex_);
const int ret = set->size_;
pthread_mutex_unlock(&set->mutex_);
return ret;
}
int cs_add(struct cs *set, const void *key)
{
if (__builtin_expect(!!(!key), 0))
return -EINVAL;
pthread_mutex_lock(&set->mutex_);
const int ret = cs_add_unsafe(set, key);
pthread_mutex_unlock(&set->mutex_);
return ret;
}
int cs_remove(struct cs *set, const void *key)
{
if (__builtin_expect(!!(!key), 0))
return -EINVAL;
pthread_mutex_lock(&set->mutex_);
const int ret = cs_remove_unsafe(set, key);
pthread_mutex_unlock(&set->mutex_);
return ret;
}
bool cs_contains(struct cs *set, const void *key)
{
if (__builtin_expect(!!(!key), 0))
return 0;
pthread_mutex_lock(&set->mutex_);
const bool ret = cs_find_unsafe(set, key);
pthread_mutex_unlock(&set->mutex_);
return ret;
}
void cs_destroy(struct cs *set)
{
tdestroy(set->root_, set->dtor_);
free(set);
}
static void do_nothing(void *dummy)
{
(void)dummy;
}
static inline int cs_add_unsafe(struct cs *set, const void *key)
{
if (cs_find_unsafe(set, key))
return EEXIST;
if (__builtin_expect(!!(!cs_search_unsafe(set, key)), 0))
return -ENOMEM;
++set->size_;
return 0;
}
static inline int cs_remove_unsafe(struct cs *set, const void *key)
{
void **const found = cs_find_unsafe(set, key);
if (!found)
return ENOENT;
void *const tobefree = *found;
if (__builtin_expect(!!(!cs_delete_unsafe(set, key)), 0))
return -ENOENT;
set->dtor_(tobefree);
--set->size_;
return 0;
}
static inline void *cs_find_unsafe(const struct cs *set, const void *key)
{
return tfind(key, &set->root_, set->cmpr_);
}
static inline void *cs_search_unsafe(struct cs *set, const void *key)
{
return tsearch(key, &set->root_, set->cmpr_);
}
static inline void *cs_delete_unsafe(struct cs *set, const void *key)
{
return tdelete(key, &set->root_, set->cmpr_);
}
| 1
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_t threads[OS_MAX_SIMUL_THREADS];
static unsigned numThreads = 0;
static void *
myfunc(void *arg)
{
pthread_mutex_lock(&lock);
numThreads++;
pthread_mutex_unlock(&lock);
pte_osThreadSleep(1000);
return 0;
}
int pthread_test_count1()
{
int i;
int maxThreads = sizeof(threads) / sizeof(pthread_t);
numThreads = 0;
lock = PTHREAD_MUTEX_INITIALIZER;
for (i = 0; i < maxThreads; i++)
{
assert(pthread_create(&threads[i], 0, myfunc, 0) == 0);
}
for (i = 0; i < maxThreads; i++)
{
assert(pthread_join(threads[i], 0) == 0);
}
assert((int) numThreads == maxThreads);
assert(pthread_mutex_destroy(&lock) == 0);
return 0;
}
| 0
|
#include <pthread.h>
int philID[5];
int currentlyEating = 0;
pthread_mutex_t eatingMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t forks[5];
pthread_cond_t canEat = PTHREAD_COND_INITIALIZER;
pthread_t philosopherThreads[5];
int isEating[5];
int forkOwner[5];
void printTable(){
printf("Eating philosophers' ids: ");
int i;
for (i = 0; i < 5; i++) {
if (isEating[i]) {
printf("%d, ", i);
}
}
printf("\\nFork owners: ");
for (i = 0; i < 5; i++) {
if (forkOwner[i] != -1) {
printf("\\n\\t<<Fork %d owned by %d>>", i, forkOwner[i]);
} else {
printf("\\n\\t<<Fork %d is free>>", i);
}
}
printf("\\n\\n");
}
void pickUp(int id, int forkID) {
pthread_mutex_lock(&forks[forkID]);
forkOwner[forkID] = id;
}
void putDown(int forkID) {
forkOwner[forkID] = -1;
pthread_mutex_unlock(&forks[forkID]);
}
void * philosopherRun(void * arg){
int id = *((int*) arg);
int leftFork = id;
int rightFork = (id + 1) % 5;
while (1) {
usleep(rand() % 1000);
pthread_mutex_lock(&eatingMutex);
if(currentlyEating > 3) {
pthread_cond_wait(&canEat, &eatingMutex);
}
currentlyEating++;
pthread_mutex_unlock(&eatingMutex);
pickUp(id, leftFork);
pickUp(id, rightFork);
isEating[id] = 1;
usleep(rand() % 100);
isEating[id] = 0;
putDown(leftFork);
putDown(rightFork);
pthread_mutex_lock(&eatingMutex);
currentlyEating--;
if (currentlyEating < 4) {
pthread_cond_signal(&canEat);
}
pthread_mutex_unlock(&eatingMutex);
}
return 0;
}
int main(int argc, char ** argv) {
srand(time(0));
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
int i;
for (i = 0; i < 5; i++) {
philID[i] = i;
isEating[i] = 0;
forkOwner[i] = -1;
pthread_mutex_init(&forks[i], &attr);
}
for (i = 0; i < 5; i++) {
pthread_create(&philosopherThreads[i], 0, philosopherRun, &philID[i]);
}
while (1) {
printTable();
usleep(100000);
}
for (i = 0; i < 5; i++) {
pthread_join(philosopherThreads[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
void *Th_piece(pthread_t code_piece, pthread_t numero_machine)
{
pthread_mutex_t mutex_machine = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_convoyeur = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex_machine);
pthread_mutex_lock(&mutex_convoyeur);
char *message;
message= malloc(sizeof(char));
send("deposer piece brute sur convoyeur\\n", Th_robot_alimentation);
if((message == 0) ||strcmp(message, "defaillance"))
{
pthread_kill(Th_dialogue, SIGUSR1);
erreur("arret du systeme de supervision: le robot d'alimentation ne repond pas ou bien il n'a pas pu retirer la pièce au bout de 20s.\\n");
}
else
{
send("deposer piece brute sur table\\n",Th_machine[1]);
receive();
}
if (message == 0)
{
pthread_kill(Th_dialogue,SIGUSR1);
erreur("arret du systeme de supervision: la machine n'a pas fini de retirer la piece du convoyeur apres 50sec.\\n");
}
pthread_mutex_unlock(&mutex_convoyeur);
receive();
if(message == 0)
{
pthread_mutex_lock(&Mutex1);
Machine_etat= fonctionne;
pthread_mutex_unlock(&Mutex1);
pthread_kill(Th_dialogue, SIGUSR2);
erreur("La machine n'a pas fini son operation d'usinage après 10 minutes\\n");
}
pthread_mutex_lock(&mutex_convoyeur);
send("deposer piece usinee sur convoyeur",Th_machine[1]);
receive();
if(message == 0)
{
pthread_kill(Th_dialogue, SIGUSR1);
erreur("arret du systeme de supervision, la machine n'a pas fini de retirer la piece au bout de 50sec\\n");
}
else
{
send("retirer piece usinee du convoyeur", Th_robot_retrait);
receive();
}
if(message == 0)
{
pthread_kill(Th_dialogue,SIGUSR1);
erreur("le robot de retrait n'a pas fini le retrait de la piece usine après 30 sec\\n");
}
else
{
pthread_mutex_unlock(&mutex_convoyeur);
pthread_mutex_unlock(&mutex_machine);
pthread_kill(Th_dialogue, SIGUSR2);
printf("usinage de la piece, code piece: OK\\n");
}
return 0;
}
| 0
|
#include <pthread.h>
struct mountmanager_struct {
pthread_mutex_t mutex;
pthread_cond_t cond;
unsigned char status;
unsigned char readers;
};
static struct mountmanager_struct mountmanager={PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER, 0, 0};
static struct mountentry_s *rootmount=0;
static unsigned long uniquectr=1;
static pthread_mutex_t ctr_mutex=PTHREAD_MUTEX_INITIALIZER;
static unsigned long generation=0;
unsigned long get_uniquectr()
{
unsigned long result=0;
pthread_mutex_lock(&ctr_mutex);
result=uniquectr;
uniquectr++;
pthread_mutex_unlock(&ctr_mutex);
return result;
}
unsigned long generation_id()
{
return generation;
}
void increase_generation_id()
{
generation++;
}
int compare_mount_entries(struct mountentry_s *a, struct mountentry_s *b)
{
int diff=0;
diff=g_strcmp0(a->mountpoint, b->mountpoint);
if (diff==0) {
diff=g_strcmp0(a->source, b->source);
if (diff==0) diff=g_strcmp0(a->fs, b->fs);
}
return diff;
}
static int lock_mountlist_read(unsigned int *error)
{
pthread_mutex_lock(&mountmanager.mutex);
while(mountmanager.status & 2) {
pthread_cond_wait(&mountmanager.cond, &mountmanager.mutex);
}
mountmanager.readers++;
*error=0;
pthread_cond_signal(&mountmanager.cond);
pthread_mutex_unlock(&mountmanager.mutex);
return 0;
}
static int unlock_mountlist_read(unsigned int *error)
{
pthread_mutex_lock(&mountmanager.mutex);
mountmanager.readers--;
*error=0;
pthread_cond_signal(&mountmanager.cond);
pthread_mutex_unlock(&mountmanager.mutex);
return 0;
}
static int lock_mountlist_write(unsigned int *error)
{
pthread_mutex_lock(&mountmanager.mutex);
*error=0;
while ((mountmanager.status & 2) || mountmanager.readers>0) {
pthread_cond_wait(&mountmanager.cond, &mountmanager.mutex);
}
mountmanager.status|=2;
unlock:
pthread_mutex_unlock(&mountmanager.mutex);
return 0;
}
static int unlock_mountlist_write(unsigned int *error)
{
pthread_mutex_lock(&mountmanager.mutex);
if (mountmanager.status & 2) mountmanager.status-=2;
pthread_cond_signal(&mountmanager.cond);
pthread_mutex_unlock(&mountmanager.mutex);
return 0;
}
int lock_mountlist(const char *what, unsigned int *error)
{
*error=0;
if (strcmp(what, "read")==0) {
return lock_mountlist_read(error);
} else if (strcmp(what, "write")==0) {
return lock_mountlist_write(error);
}
*error=EINVAL;
return -1;
}
int unlock_mountlist(const char *what, unsigned int *error)
{
*error=0;
if (strcmp(what, "read")==0) {
return unlock_mountlist_read(error);
} else if (strcmp(what, "write")==0) {
return unlock_mountlist_write(error);
}
*error=EINVAL;
return -1;
}
void check_mounted_by_autofs(struct mountentry_s *mountentry)
{
}
void set_rootmount(struct mountentry_s *mountentry)
{
rootmount=mountentry;
}
struct mountentry_s *get_rootmount()
{
return rootmount;
}
struct mountentry_s *get_containing_mountentry(struct list_element_s *list)
{
if (! list) return 0;
return (struct mountentry_s *) ( ((char *) list) - offsetof(struct mountentry_s, list));
}
| 1
|
#include <pthread.h>
struct fq {
struct fq *nxt;
struct dbf *df;
} *fq=0, *fql=0;
struct fqwrk {
struct dbf *df;
char end;
fncwrk fwrk;
pthread_t pt;
pthread_mutex_t mt;
};
void fqadd(struct dbf *df){
struct fq *fi=malloc(sizeof(struct fq));
fi->df=df;
fi->nxt=0;
if(fql){ fql->nxt=fi; fql=fi; }else fq=fql=fi;
}
void *fqwrk(void *arg){
struct fqwrk *fqw=(struct fqwrk *)arg;
while(1){
struct dbf *df;
while(!fqw->df){
if(fqw->end) return 0;
usleep(100);
}
pthread_mutex_lock(&fqw->mt);
df=fqw->df;
fqw->df=0;
pthread_mutex_unlock(&fqw->mt);
fqw->fwrk(df);
}
}
void fqrun(struct dbt *dt,char (*fana)(struct dbt *dt,struct dbf *df),void (*fwrk)(struct dbf *df)){
struct fqwrk fqw={.df=0,.end=0,.fwrk=fwrk};
pthread_mutex_init(&fqw.mt,0);
pthread_create(&fqw.pt,0,fqwrk,&fqw);
for(;fq;fq=fq->nxt) if(fana(dt,fq->df)){
while(fqw.df) usleep(100);
pthread_mutex_lock(&fqw.mt);
fqw.df=fq->df;
pthread_mutex_unlock(&fqw.mt);
}
fql=0;
fqw.end=1;
pthread_join(fqw.pt,0);
pthread_mutex_destroy(&fqw.mt);
}
| 0
|
#include <pthread.h>
void* thread_work(void* pvoid)
{
thread_run = 1;
while (thread_run)
{
if (cmd_list != 0 && cmd_list->iAllNum > 0 && cmd_list->iAllNum < MAXLISTSIZE)
{
tagTaskItem *item ;
pthread_mutex_lock(&down_work_mutex);
item= list_begin(cmd_list);
printf("list first item data = %s,length = %d,iallnum=%d\\n",item->data,item->length,cmd_list->iAllNum);
if ((strstr(item->data,"Control") != 0))
{
printf("control test1111!!!!!!!\\n");
if (0 == getDownDriver3())
{
setDownDriver3(1);
setDownCmdLengthCom1(item->length);
setDownCmdCom1(item->data);
printf("control test2222!!!!!!!\\n");
}
}
else if ((strstr(item->data,"Control2") != 0))
{
if (0 == getDownDriver4())
{
setDownDriver4(1);
setDownCmdLengthCom2(item->length);
setDownCmdCom2(item->data);
}
}
if ((strstr(item->data,"UploadAll") != 0))
{
printf("UploadAll\\n");
if(!getDownDriver1())
{
setDownDriver1(2);
setDownCmdLengthCom1(item->length);
setDownCmdCom1(item->data);
}
}
pop_front(cmd_list);
printf("delete first item \\n");
pthread_mutex_unlock(&down_work_mutex);
}
sleep(THREAD_SLEEP_SPAN);
}
printf("thread is stop\\n");
}
int down_thread_init()
{
int res = pthread_mutex_init(&down_work_mutex, 0);
if ( 0 != res)
{
printf("Mutex init failed!");
return 0;
}
res = pthread_create(&thread_down, 0, thread_work, 0);
if ( 0 != res)
{
printf("Thread creation failed!");
return 0;
}
return 1;
}
| 1
|
#include <pthread.h>
FILE *debug_file_desc;
pthread_mutex_t debug_mutex;
int log_open(const char *file)
{
if ((debug_file_desc = fopen(file,"w")) == 0){
fprintf(stderr, "Fail to open log file %s\\n", file);
return 1;
}
pthread_mutex_init(&debug_mutex, 0);
return 0;
}
void log_close()
{
fclose(debug_file_desc);
pthread_mutex_destroy(&debug_mutex);
}
void Info_put(const char *format, ...)
{
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&debug_mutex);
fprintf(debug_file_desc,"%s", "INfo: ");
vfprintf(debug_file_desc,format,ap);
pthread_mutex_unlock(&debug_mutex);
;
}
void __Debug_put(const char *format, ...)
{
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&debug_mutex);
fprintf(debug_file_desc,"%s", "Debug:");
vfprintf(debug_file_desc,format,ap);
pthread_mutex_unlock(&debug_mutex);
;
}
void Err_put(const char *format, ...)
{
va_list ap;
__builtin_va_start((ap));
pthread_mutex_lock(&debug_mutex);
fprintf(debug_file_desc,"%s", "Err: ");
vfprintf(debug_file_desc,format,ap);
pthread_mutex_unlock(&debug_mutex);
;
}
| 0
|
#include <pthread.h>
int
ports_count_bucket (struct port_bucket *bucket)
{
int ret;
pthread_mutex_lock (&_ports_lock);
ret = bucket->count;
bucket->flags |= PORT_BUCKET_NO_ALLOC;
pthread_mutex_unlock (&_ports_lock);
return ret;
}
| 1
|
#include <pthread.h>
static char *root;
static int workers;
static int trials;
static int record_absolute;
static struct timeval asbolute_start;
static pthread_mutex_t worker_sync_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t worker_sync_cond = PTHREAD_COND_INITIALIZER;
static volatile int worker_sync_t = -1;
static volatile int workers_alive = 0;
int timeval_subtract(struct timeval *result, struct timeval *x,
struct timeval *y) {
if(x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if(x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
return x->tv_sec < y->tv_sec;
}
static void pthread_usleep(unsigned int usecs) {
int result;
pthread_cond_t timercond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t timerlock = PTHREAD_MUTEX_INITIALIZER;
struct timespec timerexpires;
clock_gettime(CLOCK_REALTIME, &timerexpires);
timerexpires.tv_nsec += usecs * 1000;
if(timerexpires.tv_nsec >= 1000000000) {
timerexpires.tv_sec += timerexpires.tv_nsec / 1000000000;
timerexpires.tv_nsec = timerexpires.tv_nsec % 1000000000;
}
pthread_mutex_lock(&timerlock);
result = ~ETIMEDOUT;
while(result != ETIMEDOUT)
result = pthread_cond_timedwait(&timercond, &timerlock, &timerexpires);
pthread_mutex_unlock(&timerlock);
}
void *worker_run(void *data) {
int id = (int) data;
char clkpath[256];
sprintf(clkpath, "%s/clock", root);
int clkfd = open(clkpath, O_RDONLY);
if(clkfd < 0) {
perror("open");
exit(1);
}
char testpath[256];
sprintf(testpath, "%s/%d", root, id);
int fd = open(testpath, O_RDWR | O_CREAT, 0777);
if(fd < 0) {
perror("open");
exit(1);
}
char buf[1024];
memset(buf, 'x', sizeof(buf));
((int *) buf)[0] = id;
uint64_t *deltas = malloc(sizeof(uint64_t) * trials * 2);
pthread_mutex_lock(&worker_sync_lock);
workers_alive++;
pthread_mutex_unlock(&worker_sync_lock);
if(id == 0) {
while(workers_alive < workers)
pthread_usleep(100000);
struct stat statbuf;
if(fstat(clkfd, &statbuf) < 0) {
perror("fstat");
exit(1);
}
}
int t;
for(t = 0; ; t++) {
if(id == 0) {
if(t >= trials && workers_alive == 1)
break;
} else {
if(t >= trials)
break;
pthread_mutex_lock(&worker_sync_lock);
while(worker_sync_t < t)
pthread_cond_wait(&worker_sync_cond, &worker_sync_lock);
pthread_mutex_unlock(&worker_sync_lock);
}
struct timeval before;
gettimeofday(&before, 0);
if(lseek(fd, 0, 0) < 0) {
perror("lseek");
exit(1);
}
if(write(fd, buf, sizeof(buf)) < 0) {
perror("write");
exit(1);
}
struct timeval after;
gettimeofday(&after, 0);
struct timeval diff;
if(record_absolute)
timeval_subtract(&diff, &after, &asbolute_start);
else
timeval_subtract(&diff, &after, &before);
deltas[t] = (diff.tv_sec * 1000000) + diff.tv_usec;
if(id == 0) {
pthread_mutex_lock(&worker_sync_lock);
worker_sync_t = t;
pthread_cond_broadcast(&worker_sync_cond);
pthread_mutex_unlock(&worker_sync_lock);
pthread_usleep(49000);
}
}
pthread_mutex_lock(&worker_sync_lock);
workers_alive--;
pthread_mutex_unlock(&worker_sync_lock);
return deltas;
}
int main(int argc, char *argv[]) {
if(argc < 4 || argc > 5) {
printf("Usage: concurio [mount-point] [workers] [trials] [-a]\\n");
exit(1);
}
root = argv[1];
workers = strtol(argv[2], 0, 10);
trials = strtol(argv[3], 0, 10);
if(argc == 5 && strcmp(argv[4], "-a") == 0)
record_absolute = 1;
else
record_absolute = 0;
gettimeofday(&asbolute_start, 0);
pthread_t *worker_threads = malloc(sizeof(pthread_t) * workers);
int w;
for(w = 0; w < workers; w++)
pthread_create(&worker_threads[w], 0, worker_run, (void *) w);
uint64_t **worker_deltas = malloc(sizeof(uint64_t *) * workers);
for(w = 0; w < workers; w++)
pthread_join(worker_threads[w], (void **) &worker_deltas[w]);
if(record_absolute)
printf("absolute\\n");
else
printf("write-time\\n");
int t;
for(w = 0; w < workers; w++) {
for(t = 0; t < trials; t++)
printf("%d: %llu\\n", w, worker_deltas[w][t]);
free(worker_deltas[w]);
}
exit(0);
}
| 0
|
#include <pthread.h>
int NUM_READERS = 0;
int NUM_WRITERS = 0;
int SHARED_VARIABLE = 0;
int reader_has_priority = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t write_ok = PTHREAD_COND_INITIALIZER;
pthread_cond_t read_ok = PTHREAD_COND_INITIALIZER;
void *writer (void *param);
void *reader (void *param);
int main (void) {
int i;
pthread_t writer_threads[5];
pthread_t reader_threads[5];
for (i = 0; i < 5; i++) {
if (pthread_create(&writer_threads[i], 0, writer, 0) != 0) {
fprintf(stderr, "Unable to create writer thread\\n");
}
if(pthread_create(&reader_threads[i], 0, reader, 0) != 0) {
fprintf(stderr, "Unable to create reader thread\\n");
}
}
for (i = 0; i < 5; i++) {
pthread_join(writer_threads[i], 0);
pthread_join(reader_threads[i], 0);
}
fprintf(stdout, "Parent thread quitting\\n");
return 0;
}
void *writer (void *param) {
++NUM_WRITERS;
int r = rand() % 30;
fprintf(stdout, "Writer thread sleeping for %d seconds\\n", r);
sleep(r);
pthread_mutex_lock(&m);
if (reader_has_priority == 1) {
pthread_cond_wait(&write_ok, &m);
}
SHARED_VARIABLE = r;
printf(
"Write: Variable value is: %d, and the number of readers present when writing is: %d (should be 0)\\n", r, NUM_READERS);
pthread_mutex_unlock(&m);
--NUM_WRITERS;
return 0;
}
void *reader (void *param) {
int r = rand() % 30;
fprintf(stdout, "Reader thread sleeping for %d seconds\\n", r);
sleep(r);
pthread_mutex_lock(&m);
++NUM_READERS;
reader_has_priority = 1;
printf("Read: The value read is %d, and the number of readers is %d\\n",
SHARED_VARIABLE, NUM_READERS);
--NUM_READERS;
reader_has_priority = 0;
pthread_mutex_unlock(&m);
pthread_cond_signal(&write_ok);
return 0;
}
| 1
|
#include <pthread.h>
cell_t** prev;
cell_t** next;
int maxth, steps, cont = 0, size;
pthread_mutex_t m;
pthread_barrier_t barreira;
cell_t ** allocate_board (int size) {
cell_t ** board = (cell_t **) malloc(sizeof(cell_t*)*size);
for (int i = 0; i < size; i++)
board[i] = (cell_t *) malloc(sizeof(cell_t)*size);
return board;
}
void free_board (cell_t ** board, int size) {
for (int i = 0; i < size; i++){
free(board[i]);
}
free(board);
}
int adjacent_to (cell_t ** board, int size, int i, int j) {
int count = 0;
int sk = (i>0) ? i-1 : i;
int ek = (i+1 < size) ? i+1 : i;
int sl = (j>0) ? j-1 : j;
int el = (j+1 < size) ? j+1 : j;
for (int k = sk; k <= ek; k++) {
for (int l = sl; l <= el; l++) {
count+=board[k][l];
}
}
count -= board[i][j];
return count;
}
void print (cell_t ** board, int size) {
for (int j = 0; j < size; j++) {
for (int i = 0; i < size; i++){
printf ("%c", board[i][j] ? 'x' : ' ');
}
printf ("\\n");
}
}
void *play () {
int i, j, a, q;
cell_t** tmp;
while (steps > 0) {
while (cont < size) {
pthread_mutex_lock(&m);
i = cont;
cont++;
pthread_mutex_unlock(&m);
if (i >= size)
break;
for (j = 0; j < size; j++) {
a = adjacent_to (prev, size, i, j);
if (a == 2) next[i][j] = prev[i][j];
if (a == 3) next[i][j] = 1;
if (a < 2) next[i][j] = 0;
if (a > 3) next[i][j] = 0;
}
}
q = pthread_barrier_wait(&barreira);
if (q == PTHREAD_BARRIER_SERIAL_THREAD) {
steps--;
tmp = next;
next = prev;
prev = tmp;
cont = 0;
}
pthread_barrier_wait(&barreira);
}
pthread_exit(0);
}
void read_file (FILE * f, cell_t ** board, int size) {
char *s = (char *) malloc(size+10);
fgets (s, size+10,f);
for (int j = 0; j < size; j++) {
fgets (s, size+10,f);
for (int i = 0; i < size; i++)
board[i][j] = s[i] == 'x';
}
}
int main (int argc, char *argv[]) {
pthread_mutex_init(&m,0);
int j, a;
maxth = argc > 1? atoi(argv[1]) : 1;
FILE *f;
f = stdin;
fscanf(f,"%d %d", &size, &steps);
prev = allocate_board (size);
read_file (f, prev,size);
fclose(f);
next = allocate_board (size);
cell_t ** tmp;
pthread_t threads[maxth];
pthread_barrier_init (&barreira, 0, maxth);
for (a = 0; a < maxth; a++)
pthread_create(&threads[a], 0, play, 0);
for (j = 0; j < maxth; j++)
pthread_join(threads[j], 0);
pthread_barrier_destroy(&barreira);
pthread_mutex_destroy(&m);
free_board(prev,size);
free_board(next,size);
}
| 0
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 1
|
#include <pthread.h>
void
*inqueue_new(char *sender, char *reciever, char *data, int cmd,
ssize_t sender_size, ssize_t reciever_size, ssize_t data_size)
{
struct inqueue_s *inque = malloc(sizeof(struct inqueue_s));
assert(inque);
inque->sender = malloc_copy(sender, sender_size);
inque->reciever = malloc_copy(reciever, reciever_size);
inque->data = malloc_copy(data, data_size);
printf("SENDER: %s\\n", inque->sender);
inque->cmd = cmd;
inque->data_size = data_size;
if (INQUEUE_LIST == 0) {
INQUEUE_LIST = inque;
INQUEUE_HEAD = inque;
inque->inque_next = 0;
inque->inque_prev = 0;
} else {
INQUEUE_HEAD->inque_next = inque;
inque->inque_prev = INQUEUE_HEAD;
INQUEUE_HEAD = inque;
}
return inque;
}
void
inqueue_free(struct inqueue_s *inque)
{
assert(inque);
if (inque == INQUEUE_LIST) {
INQUEUE_LIST = inque->inque_next;
}
if (inque == INQUEUE_HEAD)
INQUEUE_HEAD = inque->inque_prev;
if (inque->inque_next != 0)
inque->inque_next->inque_prev = inque->inque_prev;
if (inque->inque_prev != 0)
inque->inque_prev->inque_next = inque->inque_next;
assert(inque->sender);
free(inque->sender);
assert(inque->reciever);
free(inque->reciever);
assert(inque->data);
free(inque->data);
free(inque);
return;
}
void
inqueue_lock()
{
pthread_mutex_lock(&inqueue_mutex);
return;
}
void
inqueue_unlock()
{
pthread_mutex_unlock(&inqueue_mutex);
return;
}
| 0
|
#include <pthread.h>
pthread_mutex_t m[5];
pthread_mutex_t m2;
int s = 1000;
void * functie(void* arg){
int id = *(int*)arg;
printf("Filozoful %d se aseaza la masa \\n", id);
int gata = 0;
do{
int st = (id == 0 ? 5 -1 : id - 1);
int dr = id;
pthread_mutex_lock(&m[st]);
if(pthread_mutex_trylock(&m[dr]) == 1){
pthread_mutex_lock(&m2);
printf("Filozoful %d mananca\\n", id);
s -= rand() % (5 - 1 + 1) + 1;
sleep(rand() % (5 - 1 + 1) + 1);
if(s < 0)
gata = 1;
pthread_mutex_unlock(&m2);
pthread_mutex_unlock(&m[st]);
pthread_mutex_unlock(&m[dr]);
printf("Filozoful %d elibereaza betele\\n", id);
}
else{
printf("Filozoful %d elibereaza betisorul stang\\n", id);
pthread_mutex_unlock(&m[st]);
}
}while(gata == 0);
free(arg);
return 0;
}
int main(){
int i;
pthread_t th[5];
for(i=0;i<5;i++)
pthread_mutex_init(&m[i], 0);
pthread_mutex_init(&m2, 0);
for(i=0;i<5;i++){
int *k = (int*) malloc(sizeof(int));
*k = i;
if(pthread_create(&th[i], 0, functie, (void*) k)){perror("Erroare creare filozof"); exit(-1);}
}
for(i=0;i<5;i++)
pthread_join(th[i], 0);
for(i=0;i<5;i++)
pthread_mutex_destroy(&m[i]);
pthread_mutex_destroy(&m2);
return 0;
}
| 1
|
#include <pthread.h>
void *Train();
void * Passenger();
int timesToRun, passLeft,noBoard, capacity, flag;
pthread_mutex_t entry, board, end, ready, ride;
int main (int argc, char* argv[]){
int i, noPass, thrCheck;
pthread_t *pasThread;
noBoard=0;
flag=0;
printf ("How many passengers? ");
scanf (" %d", &noPass);
printf ("\\n");
timesToRun= noPass/10;
passLeft= noPass%10;
capacity= 10;
if (pthread_mutex_init(&end, 0) != 0)
{
perror ("Mutex error");
return 1;
}
pthread_mutex_lock (&end);
if (pthread_mutex_init(&ready, 0) != 0)
{
perror ("Mutex error");
return 1;
}
pthread_mutex_lock (&ready);
if (pthread_mutex_init(&ride, 0) != 0)
{
perror ("Mutex error");
return 1;
}
pthread_mutex_lock (&ride);
if (pthread_mutex_init(&entry, 0) != 0)
{
perror ("Mutex error");
return 1;
}
if (pthread_mutex_init(&board, 0) != 0)
{
perror ("Mutex error");
return 1;
}
pthread_mutex_lock (&board);
if (0==(pasThread= (pthread_t*)malloc(sizeof(pthread_t)*(noPass+1)))){
perror ("Memory allocation error!!!");
return (1);
}
for (i=0; i<noPass; i++){
thrCheck = pthread_create( &pasThread[i], 0, Passenger , 0);
if(thrCheck){
fprintf(stderr,"Error - pthread_create() return code: %d\\n",thrCheck);
exit(1);
}
}
thrCheck = pthread_create( &pasThread[i], 0, Train , 0);
if(thrCheck){
fprintf(stderr,"Error - pthread_create() return code: %d\\n",thrCheck);
exit(1);
}
pthread_mutex_lock (&end);
pthread_mutex_destroy (&end);
pthread_mutex_destroy (&entry);
pthread_mutex_destroy (&board);
pthread_mutex_destroy (&ready);
pthread_mutex_destroy (&ride);
free (pasThread);
return (0);
}
void * Train(){
int i;
while (1){
pthread_mutex_lock (&ride);
printf ("YOOOOOHOOOOOOO Starting RIDE!!!!!\\n");
printf ("With %d Passengers!!!!!\\n", capacity);
for (i=0; i<3; i++){
printf ("CHOOF CHOOF CHOOF CHOOF\\n");
sleep (1);
}
printf ("End of the ride :(\\n");
timesToRun--;
if(flag==1){
printf ("Nothing else to do... I'm Going Home\\n");
pthread_mutex_unlock (&end);
break;
}
else if (flag!=1){
printf ("Returning back\\n");
for (i=0;i<3; i++){
printf (".\\n");
sleep (1);
}
printf ("Waiting for Passengers\\n");
pthread_mutex_unlock (&entry);
}
if ((timesToRun==0)&&(passLeft==0)){
printf ("Nothing else to do... I'm Going Home\\n");
pthread_mutex_unlock (&end);
break;
}
}
return (0);
}
void *Passenger(){
pthread_mutex_lock (&entry);
if ((timesToRun==0)&&(passLeft!=0)){
capacity=passLeft;
flag=1;
}
noBoard++;
if (noBoard!=capacity){
pthread_mutex_unlock (&entry);
}else {
pthread_mutex_unlock(&board);
}
pthread_mutex_lock(&board);
noBoard--;
if (noBoard==0){
pthread_mutex_unlock (&ride);
}
if (noBoard!=0){
pthread_mutex_unlock (&board);
}
return (0);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t m_trace = PTHREAD_MUTEX_INITIALIZER;
void output_init()
{
return;
}
void output( char * string, ... )
{
va_list ap;
char *ts="[??:??:??]";
struct tm * now;
time_t nw;
pthread_mutex_lock(&m_trace);
nw = time(0);
now = localtime(&nw);
if (now == 0)
printf(ts);
else
printf("[%2.2d:%2.2d:%2.2d]", now->tm_hour, now->tm_min, now->tm_sec);
__builtin_va_start((ap));
vprintf(string, ap);
;
pthread_mutex_unlock(&m_trace);
}
void output_fini()
{
return;
}
| 1
|
#include <pthread.h>
int
sem_init(sem_t* s, int pshared, unsigned int val)
{
int r;
(void)pshared;
s->s_val = val;
pthread_mutex_init(&s->s_lock, 0);
if (0 != (r = pthread_cond_init(&s->s_cond, 0)))
return r;
return 0;
}
int
sem_wait(sem_t* s)
{
pthread_mutex_lock(&s->s_lock);
while (s->s_val == 0)
pthread_cond_wait(&s->s_cond, &s->s_lock);
s->s_val--;
pthread_mutex_unlock(&s->s_lock);
return 0;
}
int
sem_post(sem_t* s)
{
pthread_mutex_lock(&s->s_lock);
s->s_val++;
pthread_mutex_unlock(&s->s_lock);
pthread_cond_broadcast(&s->s_cond);
return 0;
}
int
sem_destroy(sem_t* s)
{
pthread_mutex_destroy(&s->s_lock);
pthread_cond_destroy(&s->s_cond);
return 0;
}
int
sem_trywait(sem_t* s)
{
int r = -1;
pthread_mutex_lock(&s->s_lock);
if (s->s_val > 0)
{
s->s_val--;
r = 0;
}
pthread_mutex_unlock(&s->s_lock);
if (r != 0)
errno = EAGAIN;
return r;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t s_mutex;
static pthread_cond_t s_cond;
static int s_i;
static const char* err_to_str(int errnum)
{
switch (errnum) {
case 0: return "success";
case EBUSY: return "EBUSY";
case EINVAL: return "EINVAL";
default: return "?";
}
}
static void* thread_func(void* thread_arg)
{
pthread_mutex_lock(&s_mutex);
s_i = 1;
pthread_cond_signal(&s_cond);
while (s_i == 1)
pthread_cond_wait(&s_cond, &s_mutex);
pthread_mutex_unlock(&s_mutex);
return 0;
}
int main(int argc, char** argv)
{
pthread_t threadid;
int ret;
pthread_mutex_init(&s_mutex, 0);
pthread_cond_init(&s_cond, 0);
pthread_create(&threadid, 0, thread_func, 0);
pthread_mutex_lock(&s_mutex);
while (s_i == 0)
pthread_cond_wait(&s_cond, &s_mutex);
pthread_mutex_unlock(&s_mutex);
ret = pthread_cond_destroy(&s_cond);
fprintf(stderr, "First pthread_cond_destroy() call returned %s.\\n",
err_to_str(ret));
pthread_mutex_lock(&s_mutex);
s_i = 2;
pthread_cond_signal(&s_cond);
pthread_mutex_unlock(&s_mutex);
pthread_join(threadid, 0);
ret = pthread_cond_destroy(&s_cond);
fprintf(stderr, "Second pthread_cond_destroy() call returned %s.\\n",
err_to_str(ret));
pthread_mutex_destroy(&s_mutex);
return 0;
}
| 1
|
#include <pthread.h>
int main(int argc, char **argv)
{
if (nps_main_init(argc, argv)) {
return 1;
}
if (nps_main.fg_host) {
pthread_create(&th_flight_gear, 0, nps_flight_gear_loop, 0);
}
pthread_create(&th_display_ivy, 0, nps_main_display, 0);
pthread_create(&th_main_loop, 0, nps_main_loop, 0);
pthread_join(th_main_loop, 0);
return 0;
}
void nps_update_launch_from_dl(uint8_t value ) {}
void nps_radio_and_autopilot_init(void)
{
enum NpsRadioControlType rc_type;
char *rc_dev = 0;
if (nps_main.js_dev) {
rc_type = JOYSTICK;
rc_dev = nps_main.js_dev;
} else if (nps_main.spektrum_dev) {
rc_type = SPEKTRUM;
rc_dev = nps_main.spektrum_dev;
} else {
rc_type = SCRIPT;
}
nps_autopilot_init(rc_type, nps_main.rc_script, rc_dev);
}
void nps_main_run_sim_step(void)
{
nps_atmosphere_update(SIM_DT);
nps_autopilot_run_systime_step();
nps_fdm_run_step(autopilot.launch, autopilot.commands, NPS_COMMANDS_NB);
nps_sensors_run_step(nps_main.sim_time);
nps_autopilot_run_step(nps_main.sim_time);
}
void *nps_main_loop(void *data )
{
struct timespec requestStart;
struct timespec requestEnd;
struct timespec waitFor;
long int period_ns = HOST_TIMEOUT_MS * 1000000LL;
long int task_ns = 0;
struct timeval tv_now;
double host_time_now;
while (TRUE) {
if (pauseSignal) {
char line[128];
double tf = 1.0;
double t1, t2, irt;
gettimeofday(&tv_now, 0);
t1 = time_to_double(&tv_now);
irt = t1 - (t1 - nps_main.scaled_initial_time) * nps_main.host_time_factor;
printf("Press <enter> to continue (or CTRL-Z to suspend).\\nEnter a new time factor if needed (current: %f): ",
nps_main.host_time_factor);
fflush(stdout);
if (fgets(line, 127, stdin)) {
if ((sscanf(line, " %le ", &tf) == 1)) {
if (tf > 0 && tf < 1000) {
nps_main.host_time_factor = tf;
}
}
printf("Time factor is %f\\n", nps_main.host_time_factor);
}
gettimeofday(&tv_now, 0);
t2 = time_to_double(&tv_now);
irt += t2 - t1;
nps_main.real_initial_time += t2 - t1;
nps_main.scaled_initial_time = t2 - (t2 - irt) / nps_main.host_time_factor;
pauseSignal = 0;
}
clock_gettime(CLOCK_REALTIME, &requestStart);
gettimeofday(&tv_now, 0);
host_time_now = time_to_double(&tv_now);
double host_time_elapsed = nps_main.host_time_factor * (host_time_now - nps_main.scaled_initial_time);
int cnt = 0;
static int prev_cnt = 0;
static int grow_cnt = 0;
while (nps_main.sim_time <= host_time_elapsed) {
pthread_mutex_lock(&fdm_mutex);
nps_main_run_sim_step();
nps_main.sim_time += SIM_DT;
pthread_mutex_unlock(&fdm_mutex);
cnt++;
}
if (cnt > (prev_cnt)) {grow_cnt++;}
else { grow_cnt--;}
if (grow_cnt < 0) {grow_cnt = 0;}
prev_cnt = cnt;
if (grow_cnt > 10) {
printf("Warning: The time factor is too large for efficient operation! Please reduce the time factor.\\n");
}
clock_gettime(CLOCK_REALTIME, &requestEnd);
task_ns = (requestEnd.tv_sec - requestStart.tv_sec) * 1000000000L + (requestEnd.tv_nsec - requestStart.tv_nsec);
if (task_ns > 0) {
waitFor.tv_sec = 0;
waitFor.tv_nsec = period_ns - task_ns;
nanosleep(&waitFor, 0);
} else {
printf("MAIN THREAD: task took longer than one period, exactly %f [ms], but the period is %f [ms]\\n",
(double)task_ns / 1E6, (double)period_ns / 1E6);
}
}
return(0);
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *idp)
{
int j,i;
double result=0.0;
int *my_id = idp;
for (i=0; i < 10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %d, count = %d Threshold reached.\\n",
*my_id, count);
}
printf("inc_count(): thread %d, count = %d, unlocking mutex\\n",
*my_id, count);
pthread_mutex_unlock(&count_mutex);
for (j=0; j < 1000; j++)
result = result + (double)random();
}
pthread_exit(0);
}
void *watch_count(void *idp)
{
int *my_id = idp;
printf("Starting watch_count(): thread %d\\n", *my_id);
pthread_mutex_lock(&count_mutex);
while (count < 12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %d Condition signal received.\\n", *my_id);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, inc_count, (void *)&thread_ids[0]);
pthread_create(&threads[1], &attr, inc_count, (void *)&thread_ids[1]);
pthread_create(&threads[2], &attr, watch_count, (void *)&thread_ids[2]);
for (i = 0; i < 3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t udp_send_mutex;
struct udp_conn socket_conn;
char *double_to_char(double u_value,char u_arr[]){
sprintf(u_arr, "%f", u_value);
}
int udp_init(){
pthread_mutex_init(&udp_send_mutex,0);
return udp_init_client(&socket_conn,9999,"192.168.0.1");
}
int send_start(){
char msg[] = "START";
pthread_mutex_lock(&udp_send_mutex);
int ret = udp_send(&socket_conn,msg,strlen(msg)+1);
pthread_mutex_unlock(&udp_send_mutex);
return ret;
}
int send_get(){
char msg[] = "GET";
pthread_mutex_lock(&udp_send_mutex);
int ret = udp_send(&socket_conn,msg,strlen(msg)+1);
pthread_mutex_unlock(&udp_send_mutex);
return ret;
}
int send_set(double u_value){
char number[22];
double_to_char(u_value,number);
char msg[22 + 5];
sprintf(msg,"%s","SET:\\0");
strcat(msg,number);
int ret;
pthread_mutex_lock(&udp_send_mutex);
ret = udp_send(&socket_conn, msg, strlen(msg)+1);
pthread_mutex_unlock(&udp_send_mutex);
return ret;
}
int send_signal_ack(){
char msg[] = "SIGNAL_ACK";
pthread_mutex_lock(&udp_send_mutex);
int ret = udp_send(&socket_conn,msg,strlen(msg)+1);
pthread_mutex_unlock(&udp_send_mutex);
return ret;
}
int send_stop(){
char msg[] = "STOP";
pthread_mutex_lock(&udp_send_mutex);
int ret = udp_send(&socket_conn,msg,5);
pthread_mutex_unlock(&udp_send_mutex);
return ret;
}
int receive_get(char buf[]){
return udp_receive(&socket_conn,buf,256);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock;
pthread_cond_t cond;
int oddDone = 1;
int shared_var;
int cnt = 10;
void* print_even(void *foo) {
while (cnt > 0) {
pthread_mutex_lock(&lock);
if (!oddDone)
pthread_cond_wait(&cond, &lock);
printf("cond = %d evenThread:%2d\\n", cond, shared_var++);
oddDone = 0;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
cnt--;
}
}
void* print_odd(void *foo) {
while (cnt > 0) {
pthread_mutex_lock(&lock);
if (oddDone)
pthread_cond_wait(&cond, &lock);
printf("cond = %d oddThread:%2d\\n", cond, shared_var++);
oddDone = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
cnt--;
}
}
int main() {
pthread_t even_t, odd_t;
int ret;
pthread_mutex_init(&lock, 0);
pthread_cond_init(&cond, 0);
ret = pthread_create(&even_t, 0, print_even, 0);
if (ret < 0) {
printf("failed to create the thread.\\n");
}
ret = pthread_create(&odd_t, 0, print_odd, 0);
if (ret < 0) {
printf("failed to create the thread.\\n");
}
pthread_join(even_t, 0);
pthread_join(odd_t, 0);
pthread_mutex_destroy(&lock);
return 0;
}
| 1
|
#include <pthread.h>
int a[100];
int g_index = 0;
int min;
pthread_mutex_t mutex1, mutex2;
void *min_routine(void *nothing)
{
int l_index;
do
{
pthread_mutex_lock(&mutex1);
l_index = g_index;
g_index++;
pthread_mutex_unlock(&mutex1);
if (l_index < 100)
{
if(*(a + l_index) < min)
{
pthread_mutex_lock(&mutex2);
if(*(a + l_index) < min) min = *(a + l_index);
pthread_mutex_unlock(&mutex2);
}
}
}while(l_index < 100);
}
int main(int argc, char **argv)
{
pthread_t thread[4];
pthread_mutex_init(&mutex1, 0);
pthread_mutex_init(&mutex2, 0);
int i;
for (i=0; i < 100; i++)
a[100 - i -1] = i;
min = a[0];
for (i=0; i < 4; i++)
{
pthread_create(&thread[i], 0, min_routine, 0);
}
for(i=0; i < 4; i++)
pthread_join(thread[i], 0);
printf("Min value between 100 numbers is %d\\n",min);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t t1, t2;
pthread_mutex_t m1, m2;
int i1, i2;
} program;
void *thread1(void *data)
{
program *p = (program *)data;
struct timespec wait;
wait.tv_sec = 1;
wait.tv_nsec = 0;
printf("Starting t1\\n");
while(42)
{
pthread_mutex_lock(&p->m1);
pthread_mutex_lock(&p->m2);
printf("t1 has locks\\n");
pthread_mutex_unlock(&p->m1);
nanosleep(&wait, 0);
pthread_mutex_unlock(&p->m2);
}
return (void *)0;
}
void *thread2(void *data)
{
program *p = (program *)data;
struct timespec wait;
wait.tv_sec = 0;
wait.tv_nsec = 10000000;
printf("Starting t2\\n");
while(42)
{
pthread_mutex_lock(&p->m1);
pthread_mutex_lock(&p->m2);
printf("t2 has locks\\n");
pthread_mutex_unlock(&p->m1);
nanosleep(&wait, 0);
pthread_mutex_unlock(&p->m2);
}
return (void *)0;
}
int main(int ac, char **av)
{
program *p;
p = (program *)malloc(sizeof(program));
p->i1 = p->i2 = 0;
pthread_mutex_init(&p->m1, 0);
pthread_mutex_init(&p->m2, 0);
pthread_create(&p->t1, 0, thread1, (void *)p);
pthread_create(&p->t2, 0, thread2, (void *)p);
pthread_join(p->t1, 0);
return 0;
}
| 1
|
#include <pthread.h>
const void *ident;
pthread_cond_t cond;
int32_t ref;
int32_t sig;
}tsleep_entry_t;
static tsleep_entry_t sleepTable[16];
static pthread_mutex_t tsleep_mutex;
static void timeout_ticks_to_abs_timespec(clock_t ticks, struct timespec *tmspec)
{
ticks += bsdticks;
tmspec->tv_sec = (long)(ticks / bsdtick);
tmspec->tv_nsec = (long)(((ticks % bsdtick) * 1000000000ll) / bsdtick);
return;
}
void bsd_tsleep_init(void)
{
int32_t i;
memset(sleepTable, 0, sizeof(sleepTable));
for(i=0;i<(sizeof(sleepTable)/sizeof(tsleep_entry_t));i++){
pthread_cond_init(&sleepTable[i].cond, 0);
}
{
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init( &mutexattr );
mutexattr.type = PTHREAD_MUTEX_RECURSIVE;
pthread_mutex_init(&tsleep_mutex, &mutexattr);
}
}
static tsleep_entry_t *get_ident_slot(const void *ident, bool ref, bool create, bool sig)
{
int32_t i;
tsleep_entry_t *p=0;
for(i=0;i<(sizeof(sleepTable)/sizeof(tsleep_entry_t));i++){
if(sleepTable[i].ident == ident){
if(ref) sleepTable[i].ref++;
p = &sleepTable[i];
goto done;
}
}
if(create){
for(i=0;i<(sizeof(sleepTable)/sizeof(tsleep_entry_t));i++){
if(sleepTable[i].ident == 0){
sleepTable[i].ident = ident;
sleepTable[i].ref = 1;
sleepTable[i].sig = sig;
p = &sleepTable[i];
goto done;
}
}
}
done:
return p;
}
static void free_ident_slot(tsleep_entry_t *s)
{
if(--s->ref <= 0){
s->ident = 0;
s->ref = 0;
s->sig = 0;
pthread_cond_init(&s->cond, 0);
}
}
int tsleep(const void *ident, int priority, const char *wmesg, int timo)
{
int32_t retVal;
struct timespec ts;
tsleep_entry_t *s;
pthread_cond_t testcond = PTHREAD_COND_INITIALIZER;
pthread_mutex_lock(&tsleep_mutex);
if((s = get_ident_slot(ident, 1, 1, 0))==0){
return -1;
}
if(!s->sig){
if(timo){
timeout_ticks_to_abs_timespec(timo, &ts);
retVal = pthread_cond_timedwait(&s->cond, &tsleep_mutex, &ts);
}else{
retVal = pthread_cond_wait(&s->cond, &tsleep_mutex);
}
}else{
s->sig = 0;
retVal = 0;
}
free_ident_slot(s);
pthread_mutex_unlock(&tsleep_mutex);
return retVal;
}
void wakeup(const void *chan)
{
tsleep_entry_t *s;
pthread_mutex_lock(&tsleep_mutex);
if((s = get_ident_slot(chan, 0, 1, 1))!=0){
pthread_cond_broadcast(&s->cond);
}
pthread_mutex_unlock(&tsleep_mutex);
}
| 0
|
#include <pthread.h>
{
char name[20];
char number[20];
struct phone *next;
}PHONE;
pthread_mutex_t mutex;
PHONE *tail = 0;
PHONE *head[26];
void
read_insert(char *book)
{
FILE *fp;
char number5[20];
char name5[20];
fp=fopen(book, "r");
if(fp==0)
{
printf("Error with file \\n");
return;
}
fseek(fp, 14, 0);
while(fscanf(fp, "%s %s", name5, number5)==2)
{
input(name5, number5);
}
fclose(fp);
return;
}
void
save_file(char *book)
{
FILE *fp;
PHONE *p;
int i;
fp=fopen(book, "w");
if(fp==0)
{
printf("Error with file \\n");
return;
}
fprintf(fp, "Name Number\\n");
for(i=0; i<26; i++)
{
p=head[i];
while(p!=0)
{
fprintf(fp, "%s %s \\n", p->name, p->number);
p=p->next;
}
}
fclose(fp);
return;
}
void
bin_read(char *binbook)
{
FILE *fp;
PHONE temp;
int i;
fp=fopen("binbook", "rb");
if(fp==0)
{
printf("Error with file \\n");
return;
}
while((fread(&temp, sizeof(PHONE),1,fp))>0)
{
printf("%s %s \\n", temp.name, temp.number);
}
fclose(fp);
return;
}
int
input (char name1[20], char number2[20])
{
int i;
int x;
PHONE *list, * tlist, *temp;
tlist = (PHONE *)malloc(sizeof(PHONE));
strcpy (tlist->name, name1);
strcpy (tlist->number, number2);
for(i=0; i<26; i++)
{
list=head[i];
}
x=tlist->name[0]-'a';
list=head[x];
if(head[x]==0)
{
head[x]=tlist;
return;
}
while (list!=0)
{
if (strcmp(tlist->name, list->name)==0)
{
printf("No Duplicates Allowed\\n");
return;
}
else if (strcmp(tlist->name, list->name)<0)
break;
temp=list;
list=list->next;
}
if (list==head[x])
{
tlist->next=head[x];
head[x]=tlist;
}
else if(list==0)
{
temp->next=tlist;
tlist->next=0;
tail=tlist;
}
else
{
temp->next=tlist;
tlist->next=list;
}
}
int
delete()
{
PHONE *xprev;
PHONE *xnext;
PHONE *xname;
int x;
xname=(PHONE *)malloc(sizeof(PHONE));
printf("What name would you like to delete? \\n");
scanf("%s", xname->name);
x=xname->name[0]-'a';
xname=head[x];
if(head==0)
{
printf("You have no friends. \\n");
return;
}
if (strcmp(head[x]->name, xname->name)==0)
{
head[x] = head[x]->next;
return;
}
xprev=head[x];
xnext=head[x]->next;
while(xnext!=0)
{
if(strcmp(xnext->name, xname->name)==0)
{
xprev->next=xnext->next;
return;
}
xprev=xnext;
xnext=xnext->next;
}
if(xnext == 0)
printf("No Such name found!\\n");
}
int
show()
{
PHONE *p;
int k;
for(k=0; k<26; k++)
{
p=head[k];
while(p!=0)
{
printf("%s %s\\n", p->name, p->number);
p = p->next;
}
}
}
int
letter()
{
PHONE *p;
char y;
int z;
printf("What letter would you like to display?\\n");
scanf("%c", &y);
scanf("%c", &y);
z=y-'a';
p=head[z];
while(p!=0)
{
printf("%s %s \\n", p->name, p->number);
p = p->next;
}
}
void* bin_save(void* x)
{
FILE *fp;
PHONE *p;
int i;
while (1)
{
sleep(5);
fp=fopen("binbook", "wb");
for(i=0; i<26; i++)
{
p=head[i];
while(p!=0)
{
fwrite(p, sizeof(PHONE), 1, fp);
p=p->next;
}
}
fclose(fp);
}
}
int
main (int argc, char *argv[])
{
int i;
char zed[20];
int y;
char name3[20];
char number3[20];
for(i=0; i<26; i++)
{
head[i]=0;
}
if(argc == 1)
{
printf("No Such File.\\n");
return;
}
else
{
read_insert(argv[1]);
}
pthread_t thr;
pthread_mutex_init(&mutex, 0);
pthread_create(&thr, 0, bin_save, (void *) 5);
for( ; ; )
{
printf("Welcome to your Phone Book. \\n Press 1 to add a contact. \\n Press 2 to delete a contact. \\n Press 3 to list all entries. \\n Press 4 to list all entries under a certain letter. \\n Press 5 to close your Phone book. \\n Press 6 to read binary file \\n");
scanf("%d", &y);
switch(y)
{
case 1:
{
printf("Please enter the name \\n");
scanf("%s", name3);
printf("Please enter the number\\n");
scanf("%s", number3);
pthread_mutex_lock(&mutex);
input(name3, number3);
pthread_mutex_unlock(&mutex);
break;
}
case 2:
{
pthread_mutex_lock(&mutex);
delete();
pthread_mutex_unlock(&mutex);
break;
}
case 3: show();
break;
case 4: letter();
break;
case 5:
{
printf("Saving File.\\n");
pthread_mutex_lock(&mutex);
save_file(argv[1]);
pthread_mutex_unlock(&mutex);
printf("Saved.\\n");
return 0;
}
case 6:
{
printf("Reading Binary File\\n");
pthread_mutex_lock(&mutex);
bin_read(argv[2]);
pthread_mutex_unlock(&mutex);
break;
}
default: return 0;
}
}
}
| 1
|
#include <pthread.h>
int value;
pthread_mutex_t mutex;
pthread_cond_t cond;
} sema_t;
int in;
int out;
int space[4];
sema_t mutext_sema;
sema_t empty_buffer_sema;
sema_t full_buffer_sema;
}buff;
buff buffer1, buffer2;
void sema_init(sema_t *sema, int value)
{
sema->value = value;
pthread_cond_init(&sema->cond, 0);
pthread_mutex_init(&sema->mutex, 0);
}
void sema_wait(sema_t *sema)
{
pthread_mutex_lock(&sema->mutex);
--sema->value;
while (sema->value < 0)
pthread_cond_wait(&sema->cond, &sema->mutex);
pthread_mutex_unlock(&sema->mutex);
}
void sema_signal(sema_t *sema)
{
pthread_mutex_lock(&sema->mutex);
++sema->value;
pthread_cond_signal(&sema->cond);
pthread_mutex_unlock(&sema->mutex);
}
int get_item(buff *buffer)
{
int item;
sema_wait(&buffer->full_buffer_sema);
sema_wait(&buffer->mutext_sema);
item = buffer->space[buffer->out ];
buffer->out = (buffer->out + 1) % 4;
sema_signal(&buffer->mutext_sema);
sema_signal(&buffer->empty_buffer_sema);
return item;
}
void put_item(buff *buffer, int item)
{
sema_wait(&buffer->empty_buffer_sema);
sema_wait(&buffer->mutext_sema);
buffer->space[buffer->in] = item;
buffer->in = (buffer->in + 1) % 4;
sema_signal(&buffer->mutext_sema);
sema_signal(&buffer->full_buffer_sema);
printf("Produce item: %c\\n", item);
}
void produce()
{
int item;
for(int i = 0; i< 4 * 2; i++)
{
item = 'a' + i;
put_item(&buffer1, item);
}
}
void *consume(void *arg)
{
for (int i =0; i< 4 * 2; i++)
printf("Consume item: %c\\n", get_item(&buffer1));
return 0;
}
int main(){
pthread_t consumer_id;
sema_init(&buffer1.mutext_sema, 1);
sema_init(&buffer1.empty_buffer_sema, 4 - 1);
sema_init(&buffer1.full_buffer_sema, 0);
pthread_create(&consumer_id, 0, consume, 0);
produce();
pthread_join(consumer_id, 0);
return 0;
}
| 0
|
#include <pthread.h>
int
pthread_mutex_getprioceiling(pthread_mutex_t *mutexp, int *prioceiling)
{
pthread_mutex_t mutex = *mutexp;
if (mutex->prioceiling == -1)
return (EINVAL);
*prioceiling = mutex->prioceiling;
return (0);
}
int
pthread_mutex_setprioceiling(pthread_mutex_t *mutexp, int prioceiling,
int *old_ceiling)
{
pthread_mutex_t mutex = *mutexp;
int ret;
if (mutex->prioceiling == -1 ||
prioceiling < PTHREAD_MIN_PRIORITY ||
prioceiling > PTHREAD_MAX_PRIORITY) {
ret = EINVAL;
} else if ((ret = pthread_mutex_lock(mutexp)) == 0) {
*old_ceiling = mutex->prioceiling;
mutex->prioceiling = prioceiling;
pthread_mutex_unlock(mutexp);
}
return (ret);
}
| 1
|
#include <pthread.h>
static int fd = 0;
static pthread_mutex_t rw_lock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t fd_lock = PTHREAD_MUTEX_INITIALIZER;
void pci_init()
{
pthread_mutex_lock(&fd_lock);
if (!fd) {
if (alt_up_pci_open(&fd, "/dev/alt_up_pci0")) {
pthread_mutex_unlock(&fd_lock);
exit(1);
}
}
pthread_mutex_unlock(&fd_lock);
}
void pci_close()
{
alt_up_pci_close(fd);
fd = 0;
}
void pci_read_direct(void *buf, int len, int offset)
{
if (!fd) {
pci_init();
}
pthread_mutex_lock(&rw_lock);
if (alt_up_pci_read(fd, 0, offset, buf, len)) {
pthread_mutex_unlock(&rw_lock);
exit(1);
}
pthread_mutex_unlock(&rw_lock);
}
void pci_write_direct(void *buf, int len, int offset)
{
if (!fd) {
pci_init();
}
pthread_mutex_lock(&rw_lock);
if (alt_up_pci_write(fd, 0, offset, buf, len)) {
pthread_mutex_unlock(&rw_lock);
exit(1);
}
pthread_mutex_unlock(&rw_lock);
}
void pci_read_dma(void *buf, int len, int offset)
{
pci_read_dma_with_ctrller(buf, len, offset, 0);
}
void pci_write_dma(void *buf, int len, int offset)
{
pci_write_dma_with_ctrller(buf, len, offset, 0);
}
void pci_dma_go()
{
pci_dma_go_with_ctrller(0);
}
void pci_read_dma_with_ctrller(void *buf, int len, int offset, int ctrller)
{
if (alt_up_pci_dma_add(fd, ctrller, offset, buf, len, FROM_DEVICE)) {
exit(1);
}
}
void pci_write_dma_with_ctrller(void *buf, int len, int offset, int ctrller)
{
if (!fd) {
pci_init();
}
if (alt_up_pci_dma_add(fd, ctrller, offset, buf, len, TO_DEVICE)) {
exit(1);
}
}
void pci_dma_go_with_ctrller(int ctrller)
{
if (alt_up_pci_dma_go(fd, ctrller, AUTO)) {
exit(1);
}
}
| 0
|
#include <pthread.h>
int dev_lkgdb_fd = -1;
unsigned int lkgdb_cmd;
static void *lkgdb_kwork (void*);
static pthread_mutex_t lkgdb_lock;
static pthread_cond_t lkgdb_cond;
int lkgdb_init()
{
pthread_t lkgdb_tid;
dev_lkgdb_fd = open_dev();
if (dev_lkgdb_fd < 0) {
return -1;
}
if (pthread_create(&lkgdb_tid, 0, lkgdb_kwork, 0) < 0)
return -1;
return 0;
}
int open_dev()
{
int fd = 0;
fd = open("/dev/lkgdb", O_RDWR);
if (fd < 0) {
perror ("lkgdb");
return -1;
}
return fd;
}
static void *lkgdb_kwork (void *)
{
start_lkgdb:
lkgdb_wait ();
switch (lkgdb_cmd) {
case SYSCALL_STEPI:
break;
default:
break;
}
goto start_lkgdb;
}
void lkgdb_wait ()
{
pthread_mutex_lock(&lkgdb_lock);
pthread_cond_wait(&lkgdb_cond, &lkgdb_lock);
pthread_mutex_unlock(&lkgdb_lock);
}
void lkgdb_wakeup(unsigned int cmd)
{
lkgdb_cmd = cmd;
pthread_cond_signal(&lkgdb_cond);
}
| 1
|
#include <pthread.h>
ssize_t Readline(int sockd, void *vptr, size_t maxlen)
{
ssize_t n, rc;
char c, *buffer;
buffer = vptr;
for ( n = 1; n < maxlen; n++ )
{
if ( (rc = read(sockd, &c, 1)) == 1 )
{
*buffer++ = c;
if ( c == '\\n' )
break;
}
else if ( rc == 0 )
{
if ( n == 1 )
return 0;
else
break;
}
else
{
if ( errno == EINTR )
continue;
return -1;
}
}
*buffer = 0;
return n;
}
ssize_t Writeline(int sockd, const void *vptr, size_t n)
{
size_t nleft;
ssize_t nwritten;
const char *buffer;
buffer = vptr;
nleft = n;
while ( nleft > 0 )
{
if ( (nwritten = write(sockd, buffer, 1)) <= 0 )
{
if ( errno == EINTR )
nwritten = 0;
else
return -1;
}
nleft -= nwritten;
buffer += nwritten;
}
return n;
}
inline int fnWriteSocket(int tSocket, char *szBuffer, size_t soBuffer)
{
return send(tSocket, szBuffer, soBuffer, 0);
}
inline int fnReadSocket(int tSocket, char *szBuffer, size_t soBuffer)
{
ssize_t n, rc;
char c, *buffer;
buffer = szBuffer;
for ( n = 1; n < soBuffer; n++ )
{
if ( (rc = read(tSocket, &c, 1)) == 1 )
{
*buffer++ = c;
if ( c == '\\n' )
break;
}
else if ( rc == 0 )
{
if ( n == 1 )
return 0;
else
break;
}
else
{
if ( errno == EINTR )
continue;
return -1;
}
}
return 0;
}
void *fnSocketEngine( void )
{
int list_s;
int conn_s;
short int port;
struct sockaddr_in servaddr;
char szBuffer[MULTICAST_BUFFER_SIZE];
char szSocketBuffer[MULTICAST_BUFFER_SIZE];
char szServerIP[CONFIG_BUFFER_SIZE];
struct pollfd sPoll;
double fPrice;
int iStock;
int iFound;
pthread_mutex_lock( &config_mutex );
fnGetConfigSetting( szBuffer, "SERVERSOCKETPORT", "2994" );
port = atoi( szBuffer );
fnGetConfigSetting( szBuffer, "SERVERSOCKETADDRESS", "127.0.0.1" );
strcpy ( szServerIP, szBuffer );
pthread_mutex_unlock( &config_mutex );
iSocket = 0;
if ( (list_s = socket(AF_INET, SOCK_STREAM, 0)) < 0 )
{
fnHandleError ( "fnSocketEngine", "Error creating listening socket");
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(szServerIP);
servaddr.sin_port = htons(port);
if ( bind(list_s, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 )
{
fnHandleError( "fnSocketEngine", "Error calling bind()");
}
if ( listen(list_s, LISTENQ) < 0 )
{
fnHandleError( "fnSocketEngine", "Error calling listen()");
}
while ( TRUE )
{
fnDebug( "Socket Server Initialized - waiting for connection" );
sched_yield();
if ( (conn_s = accept(list_s, 0, 0) ) < 0 )
{
fnHandleError ( "fnSocketEngine", "Error calling accept()");
continue;
}
iSocket = conn_s;
fnDebug ( "Client Connected, streaming data" );
iClientConnected = TRUE;
sPoll.fd = conn_s;
sPoll.events = POLLOUT;
if( iSendTU == TRUE )
{
for( iStock=0; iStock<INDEX_COUNT_PLUS_2; iStock++ )
{
fPrice = fnGetStockPrice(iStock);
if ( fPrice > 0.00 )
{
poll( &sPoll, 1, 1 );
if (sPoll.revents&POLLHUP)
goto SocketClosed;
snprintf( szSocketBuffer, sizeof(szSocketBuffer), "TU %s 0 %.3f @ S 100 S\\n",
fnGetStockSymbol(iStock), fPrice );
if ( send( conn_s, szSocketBuffer,strlen(szSocketBuffer), 0) < strlen(szSocketBuffer) )
{
fnHandleError( "fnSocketEngine", "Error writing to socket" );
goto SocketClosed;
}
usleep(25);
}
}
}
while( TRUE )
{
if( iOutboundQueueSize > 0 )
{
memset( szSocketBuffer, 0, sizeof(szSocketBuffer) );
pthread_mutex_lock( &qOutMessages_mutex );
iFound = fnSrvGet( &qOutMessages, szSocketBuffer );
pthread_mutex_unlock( &qOutMessages_mutex );
if ( iFound == TRUE )
{
poll( &sPoll, 1, 1 );
if (sPoll.revents&POLLHUP)
goto SocketClosed;
if ( fnWriteSocket ( conn_s, szSocketBuffer,strlen(szSocketBuffer)) < strlen(szSocketBuffer) )
{
fnHandleError( "fnSocketEngine", "Error writing to socket" );
goto SocketClosed;
}
}
else
sched_yield();
}
else
sched_yield();
}
SocketClosed:
sched_yield();
iClientConnected = FALSE;
fnDebug( "Client Disconnected" );
fnSrvInit( &qOutMessages );
sched_yield();
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_t threads[10 + 1];
int waitTime = 0;
sem_t customerSem;
sem_t barberSem;
pthread_mutex_t barberShopLock = PTHREAD_MUTEX_INITIALIZER;
void cut_hair(int ID){
printf("\\t\\tThe Barber is cutting hair!\\n");
int rand_num = rand() % 3;
sleep(2);
printf("\\t\\tThe Barber is done!\\n");
}
void get_hair_cut(int ID){
int rand_num = rand() % 2;
sleep(2);
}
void* customer(void* ID){
int customerID = *((int*)ID);
while(1){
pthread_mutex_lock(&barberShopLock);
if(waitTime < 10){
waitTime++;
sem_post(&customerSem);
pthread_mutex_unlock(&barberShopLock);
if(sem_trywait(&barberSem) == 0){
}else{
sem_wait(&barberSem);
}
get_hair_cut(customerID);
}else {
pthread_mutex_unlock(&barberShopLock);
}
}
}
void* barber(void* ID){
int barberID = *((int*)ID);
while(1){
if(sem_trywait(&customerSem) == 0)
printf("\\t\\tThe Barber is waking up.\\n");
else{
printf("\\t\\tThe Barber has no customers and fell assleep!");
sem_wait(&customerSem);
printf("\\t\\tThe Barber is waking up.\\n");
}
pthread_mutex_lock(&barberShopLock);
if(waitTime > 0)
waitTime--;
else
waitTime = 0;
sem_post(&barberSem);
pthread_mutex_unlock(&barberShopLock);
cut_hair(barberID);
}
}
int main(){
sem_init(&customerSem, 0 , 0);
sem_init(&barberSem, 0, 0);
pthread_mutex_init(&barberShopLock,0);
int i = 0;
for(i = 0; i < 10; i++){
pthread_create(&threads[i],0, customer, &i);
}
pthread_create(&threads[i], 0, barber, &i);
for(i = 0; i < 10 +1; i++)
pthread_join(threads[i], 0);
while(1);
}
| 1
|
#include <pthread.h>
struct glob{
int a;
int b;
}obj;
pthread_mutex_t r_mutex;
void *threadFunc1(void *arg){
printf("thread1 has created, tid = %lu\\n",pthread_self());
printf("thread1 locked the semaphore\\n");
pthread_mutex_lock(&r_mutex);
obj.a = 10;
sleep(5);
pthread_exit(0);
obj.b = 20;
pthread_mutex_unlock(&r_mutex);
printf("thread1 unlocked the semaphore\\n");
}
void *threadFunc2(void *arg){
printf("thread2 has created, tid = %lu\\n",pthread_self());
printf("waiting....\\n");
if(errno = pthread_mutex_lock(&r_mutex)) perror("pthread_mutex_lock");
printf("mem1:%d\\n",obj.a);
printf("mem2:%d\\n",obj.b);
pthread_mutex_unlock(&r_mutex);
}
main(int argc,char *argv[]){
pthread_mutexattr_t mutexattr;
pthread_mutexattr_init(&mutexattr);
pthread_mutexattr_setrobust_np(&mutexattr,PTHREAD_MUTEX_ROBUST_NP);
pthread_mutex_init(&r_mutex,&mutexattr);
pthread_t tid1,tid2;
pthread_create(&tid1,0,threadFunc1,0);
sleep(1);
pthread_create(&tid2,0,threadFunc2,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
}
| 0
|
#include <pthread.h>
struct name_type_conv{
enum MON_CONTROLLER_TYPE type;
char dev_name[128];
};
static struct name_type_conv n2t[] = {
{MT_MAIN, "main"},
{MT_EXPANDER1, "expander-1"},
{MT_EXPANDER2, "expander-2"},
{MT_EXPANDER3, "expander-3"},
{MT_EXPANDER4, "expander-4"}
};
void name2type(char *name, int *type){
int i, items;
if (0==name)
return;
if (0==type)
return;
items = (int)(sizeof(n2t)/sizeof(struct name_type_conv));
for (i=0; i<items; i++)
{
if (!strcmp(name, n2t[i].dev_name))
{
*type = n2t[i].type;
return;
}
}
}
struct Thread_Name {
pthread_t thread;
pthread_mutex_t mut;
};
void loginfo(char *msg)
{
if (msg)
{
syslog(LOG_ERR, "wis_report: system EVENT_ERR %s\\n", msg);
}
}
static struct Thread_Name tn;
void *thread1(void *name)
{
pthread_mutex_lock(&tn.mut);
int ret1, ret2, i;
struct mon_controller con1;
struct mon_backplane con2;
name2type((char*)name, &con1.type);
name2type((char*)name, &con2.type);
while(1)
{
ret1 = mon_get_controller(&con1);
if (MON_RET_SUCCESS==ret1)
{
for (i=0; i<MON_CTRL_TEMP_POINT; i++)
{
if ((0<=con1.temp[i]) && (con1.temp[i]<=50))
{
}
else
{
loginfo("控制器温度超出阀值! ");
}
}
for (i=0; i<MON_CTRL_VOL_POINT; i++)
{
if ((0<=con1.vol[i]) && (con1.vol[i]<=50))
{
}
else
{
loginfo("控制器温度超出阀值! ");
}
}
}
else if (MON_RET_FAILED==ret1)
{
loginfo("获取组件列表失败!");
}
else if (MON_RET_NONE==ret1)
{
loginfo("无法获取组件列表!");
}
ret2 = mon_get_backplane(&con2);
if (MON_RET_SUCCESS==ret2)
{
for (i=0; i<MON_BP_TEMP_POINT; i++)
{
if ((0<=con2.temp[i]) && (con2.temp[i]<=50))
{
}
else
{
loginfo("背板温度超出阀值! ");
}
}
for (i=0; i<MON_BP_VOL_POINT; i++)
{
if ((0<=con2.vol[i]) && (con2.vol[i]<=50))
{
}
else
{
loginfo("背板温度超出阀值! ");
}
}
}
else if (MON_RET_FAILED==ret2)
{
loginfo("获取组件列表失败!");
}
else if (MON_RET_NONE==ret2)
{
loginfo("无法获取组件列表!");
}
pthread_mutex_unlock(&tn.mut);
sleep(60);
}
pthread_exit(0);
}
void thread_create(void)
{
int tmp;
pthread_mutex_init(&tn.mut, 0);
char *name = "main";
if ((tmp = pthread_create(&tn.thread, 0, thread1, (void*)name)) != 0)
{
loginfo("线程创建失败 ");
}
else
{
loginfo("main线程创建成功 ");
}
}
void thread_wait(void)
{
if (tn.thread != 0)
{
pthread_join(tn.thread, 0);
loginfo("线程执行结束 ");
}
}
int main(int argc, char *argv[])
{
daemon(1, 1);
signal(SIGTTOU,SIG_IGN);
signal(SIGTTIN,SIG_IGN);
signal(SIGTSTP,SIG_IGN);
signal(SIGHUP,SIG_IGN);
openlog("daemonlogs", LOG_CONS | LOG_PID, 0);
thread_create();
thread_wait();
closelog();
return 0;
}
| 1
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
int sillas[5]= {0, 0, 0, 0, 0};
int buscarSilla() {
pthread_mutex_lock(&mutex);
for (;;) {
if (sillas[0] == 0 && sillas[1] == 0 && sillas[4] == 0){
sillas[0] = 1;
pthread_mutex_unlock(&mutex);
return 0;
}
else if (sillas[1] == 0 && sillas[2] == 0 && sillas[0] == 0){
sillas[1] = 1;
pthread_mutex_unlock(&mutex);
return 1;
}
else if (sillas[2] == 0 && sillas[3] == 0 && sillas[1] == 0){
sillas[2] = 1;
pthread_mutex_unlock(&mutex);
return 2;
}
else if (sillas[3] == 0 && sillas[4] == 0 && sillas[2] == 0){
sillas[3] = 1;
pthread_mutex_unlock(&mutex);
return 3;
}
else if (sillas[4] == 0 && sillas[0] == 0 && sillas[3] == 0){
sillas[4] = 1;
pthread_mutex_unlock(&mutex);
return 4;
}
else{
pthread_cond_wait(&cond, &mutex);
}
}
}
void desocuparSilla(int k){
pthread_mutex_lock(&mutex);
sillas[k] = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
| 1
|
#include <pthread.h>
pthread_mutex_t verrou;
sem_t sem1,sem2,sem3;
int medium_executed = 0;
int inversion = 0;
void Thread1()
{
sem_wait(&sem1);
pthread_mutex_lock(&verrou);
printf("Thread_1 : HIGH Pritority\\n");
sem_post(&sem3);
pthread_mutex_unlock(&verrou);
if(medium_executed) inversion = 1;
}
void Thread2()
{
sem_wait(&sem2);
pthread_mutex_lock(&verrou);
printf("Thread_2 : MEDIUM Pritority\\n");
pthread_mutex_unlock(&verrou);
medium_executed = 1;
}
void Thread3()
{
sem_wait(&sem3);
pthread_mutex_lock(&verrou);
printf("Thread_3 : LOW Pritority\\n");
sem_post(&sem2);
sem_post(&sem1);
pthread_mutex_unlock(&verrou);
}
int main(int argc, char* argv[])
{
pthread_t ppid1,ppid2,ppid3;
struct sched_param param;
pthread_attr_t attr1,attr2,attr3;
sem_init(&sem1, 0, 0);
sem_init(&sem2, 0, 0);
sem_init(&sem3, 0, 1);
pthread_mutex_init(&verrou, 0);
pthread_attr_init(&attr1);
pthread_attr_init(&attr2);
pthread_attr_init(&attr3);
int policy;
if(argc > 1){
policy = PTHREAD_INHERIT_SCHED;
}else{
policy = PTHREAD_EXPLICIT_SCHED;
}
param.sched_priority = 30;
pthread_attr_setschedpolicy(&attr1,SCHED_FIFO);
pthread_attr_setschedparam(&attr1,¶m);
pthread_attr_setinheritsched(&attr1, policy);
param.sched_priority = 20;
pthread_attr_setschedpolicy(&attr2,SCHED_FIFO);
pthread_attr_setschedparam(&attr2,¶m);
pthread_attr_setinheritsched(&attr2, policy);
param.sched_priority = 10;
pthread_attr_setschedpolicy(&attr3,SCHED_FIFO);
pthread_attr_setschedparam(&attr3,¶m);
pthread_attr_setinheritsched(&attr3, policy);
pthread_create(&ppid1,&attr1,(void *)Thread1, 0);
pthread_create(&ppid2,&attr2,(void *)Thread2, 0);
pthread_create(&ppid3,&attr3,(void *)Thread3, 0);
pthread_join(ppid1,0);
pthread_join(ppid2,0);
pthread_join(ppid3,0);
pthread_attr_destroy(&attr1);
pthread_attr_destroy(&attr2);
pthread_attr_destroy(&attr3);
if(inversion){
printf("%s\\n", "Inversion détectée");
}else{
printf("%s\\n", "Inversion non détectée");
}
return 0;
}
| 0
|
#include <pthread.h>
int arr[10];
int gindex = 0;
int sum = 0;
pthread_mutex_t sum_mutex;
void *sumf(void *t){
int lindex = 0;
int partial_sum = 0;
while(lindex < 10 ) {
pthread_mutex_lock(&sum_mutex);
lindex = gindex;
gindex++;
pthread_mutex_unlock(&sum_mutex);
partial_sum += arr[lindex];
}
pthread_mutex_lock(&sum_mutex);
sum += partial_sum;
pthread_mutex_unlock(&sum_mutex);
pthread_exit(0);
}
int main(int argc , char *argv[]) {
int i ;
pthread_mutex_init(&sum_mutex , 0);
pthread_t threads[5];
int tid[5];
for(i = 0 ; i < 10 ; i++)
scanf("%d",&arr[i]);
for(i = 0 ; i < 5 ; i++) {
tid[i] = i ;
if(pthread_create(&threads[i] , 0 , sumf ,(void *) &tid[i] ) != 0 )
perror("Pthread create fails");
}
for (i=0; i<5; i++) {
pthread_join(threads[i], 0);
}
printf("Sum of array is = %d\\n" , sum);
pthread_mutex_destroy(&sum_mutex);
pthread_exit (0);
}
| 1
|
#include <pthread.h>
int atomic_fprintf(FILE * pFile, const char * format, ...)
{
pthread_mutex_lock(&fprintf_mutex);
va_list args;
__builtin_va_start((args));
int ret = vfprintf(pFile, format, args);
;
pthread_mutex_unlock(&fprintf_mutex);
return ret;
}
FILE * file_open(const char * pPath, const char * pFilename,
const char * pMode)
{
char file[BUFFER_SIZE];
ZERO(file, BUFFER_SIZE);
BCPY(pPath, file, LEN_PATH);
BCPY(pFilename, &file[LEN_PATH], SLEN(pFilename));
BSET(&file[LEN_PATH + SLEN(pFilename)], 0x0, SOC);
return fopen(file, pMode);
}
char file_close(FILE * pFile)
{
if(pFile == 0)
{
atomic_fprintf(stderr, "[err] Unable to close the file ...\\n");
return FAILURE;
}
fclose(pFile);
return SUCCESS;
}
char * getAddress(char * pAddress)
{
atomic_fprintf(stdout, "[i|o] Please enter the address : ");
scanf("%s", pAddress);
return pAddress;
}
char * getFilename(char * pFilename)
{
atomic_fprintf(stdout, "[i|o] Please enter the filename : ");
scanf("%s", pFilename);
return pFilename;
}
unsigned short getPort()
{
unsigned int port = 0;
atomic_fprintf(stdout, "[i|o] Please enter the port : ");
scanf("%u", &port);
return (unsigned short)port;
}
uint64_t getFileLenght(FILE * pFile)
{
rewind(pFile);
fseek(pFile, 0L, 2);
uint64_t size = (uint64_t)ftell(pFile);
rewind(pFile);
return size;
}
void SLEEP(double seconds)
{
}
| 0
|
#include <pthread.h>
int readersInQueue = 0;
int writersInQueue = 0;
int readersInLibrary = 0;
int writersInLibrary = 0;
pthread_mutex_t varMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t readerMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t libraryMutex = PTHREAD_MUTEX_INITIALIZER;
unsigned long uSecSleep = 2000000;
perror_exit(char* errorStr) {
perror(errorStr);
exit(1);
}
void *readerF(void* arg) {
while (1) {
pthread_mutex_lock(&varMutex);
readersInQueue++;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
pthread_mutex_unlock(&varMutex);
pthread_mutex_lock(&readerMutex);
if (readersInLibrary == 0) {
pthread_mutex_lock(&libraryMutex);
}
pthread_mutex_lock(&varMutex);
readersInLibrary++;
readersInQueue--;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
pthread_mutex_unlock(&varMutex);
pthread_mutex_unlock(&readerMutex);
usleep(rand() % uSecSleep);
pthread_mutex_lock(&readerMutex);
pthread_mutex_lock(&varMutex);
readersInLibrary--;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
if (readersInLibrary == 0) {
pthread_mutex_unlock(&libraryMutex);
}
pthread_mutex_unlock(&varMutex);
pthread_mutex_unlock(&readerMutex);
usleep(rand() % uSecSleep);
}
}
void *writerF(void* arg){
while (1) {
pthread_mutex_lock(&varMutex);
writersInQueue++;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
pthread_mutex_unlock(&varMutex);
pthread_mutex_lock(&libraryMutex);
pthread_mutex_lock(&varMutex);
writersInLibrary++;
writersInQueue--;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
pthread_mutex_unlock(&varMutex);
usleep(rand() % uSecSleep);
pthread_mutex_lock(&varMutex);
writersInLibrary--;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
pthread_mutex_unlock(&varMutex);
pthread_mutex_unlock(&libraryMutex);
usleep(rand() % uSecSleep);
}
}
int main(int argc, char** argv) {
int readersCount, writersCount;
printf("\\nReaders - writers 1st problem (readers priority)\\n");
if ((argv[1] == 0) || (argv[2]) == 0 ) {
printf("Number of readers > ");
if (scanf("%d", &readersCount) == EOF) perror_exit("scanf");
printf("Number of writers > ");
if (scanf("%d", &writersCount) == EOF) perror_exit("scanf");
printf("Starting in 1 sec...\\n\\n");
sleep(1);
} else {
readersCount = atoi(argv[1]);
writersCount = atoi(argv[2]);
printf("Number of Readers = %d\\n", readersCount);
printf("Number of Writers = %d\\n", writersCount);
printf("Starting in 2 sec...\\n\\n");
sleep(2);
}
srand(time(0));
pthread_t *readerThread = calloc(readersCount, sizeof(pthread_t));
pthread_t *writerThread = calloc(writersCount, sizeof(pthread_t));
long i = 0;
printf("ReaderQ: %d WriterQ: %d [in: R:%d W:%d]\\n",
readersInQueue, writersInQueue, readersInLibrary, writersInLibrary);
for (i = 0; i < readersCount; ++i) {
if (pthread_create(&readerThread[i], 0, readerF, (void*)i)) {
perror_exit("Error while creating reader thread (pthread_create)");
}
}
for (i = 0; i < writersCount; ++i) {
if (pthread_create(&writerThread[i], 0, writerF, (void*)i)) {
perror_exit("Error while creating writer thread (pthread_create)");
}
}
for (i = 0; i < readersCount; ++i) {
if (pthread_join(readerThread[i], 0)) {
perror_exit("Error while waiting for reader thread termination (pthread_join)");
}
}
free(readerThread);
for (i = 0; i < writersCount; ++i) {
if (pthread_join(writerThread[i], 0)) {
perror_exit("Error while waiting for writer thread termination (pthread_join)");
}
}
free(writerThread);
pthread_mutex_destroy(&varMutex);
pthread_mutex_destroy(&readerMutex);
pthread_mutex_destroy(&libraryMutex);
}
| 1
|
#include <pthread.h>
static int sigNum = 0;
pthread_t hdlthreadSignalProcessor = 0;
pthread_mutex_t signalMutex = PTHREAD_MUTEX_INITIALIZER;
static int staticSimpleSigaction(int signum, sighandler_t act)
{
struct sigaction sigConf = {};
if (0 == act)
{
errno = EIO;
return -1;
}
sigemptyset(&(sigConf.sa_mask));
sigConf.sa_handler = act;
sigConf.sa_flags = 0;
return sigaction(signum, &sigConf, 0);
}
static void staticSignalCatcher(int sig)
{
pthread_mutex_lock(&signalMutex);
sigNum = sig;
pthread_mutex_unlock(&signalMutex);
}
static void *threadSignalProcessor(void *arg)
{
int sigNumCopy = 0;
do
{
if (0 != sigNum)
{
pthread_mutex_lock(&signalMutex);
sigNumCopy = sigNum;
sigNum = 0;
pthread_mutex_unlock(&signalMutex);
switch (sigNumCopy)
{
case SIGALRM:
printf("<SIGALRM>\\n");
break;
case SIGFPE:
printf ("<SIGFPE>\\n");
exit(1);
break;
case SIGHUP:
printf ("<SIGHUP>\\n");
exit(1);
break;
case SIGILL:
printf ("<SIGILL>\\n");
exit(1);
break;
case SIGINT:
printf ("<SIGINT>\\n");
exit(1);
break;
case SIGPIPE:
printf ("<SIGPIPE>\\n");
exit(1);
break;
case SIGQUIT:
printf ("<SIGQUIT>\\n");
exit(1);
break;
case SIGSEGV:
printf ("<SIGSEGV>\\n");
exit(1);
break;
case SIGTERM:
printf ("<SIGTERM>\\n");
exit(1);
break;
case SIGUSR1:
printf ("<SIGUSR1>\\n");
exit(1);
break;
case SIGUSR2:
printf ("<SIGUSR2>\\n");
exit(1);
break;
default:
printf ("Catch unknown signal %d.\\n", sigNumCopy);
exit(1);
break;
}
}
else
{
}
}
while(1);
}
int AMCSignalRegister()
{
int funcCallStat;
int tmp;
const int validSignal[] = {
SIGALRM,
SIGFPE,
SIGHUP,
SIGILL,
SIGINT,
SIGPIPE,
SIGQUIT,
SIGSEGV,
SIGTERM,
SIGUSR1,
SIGUSR2,
};
funcCallStat = pthread_mutex_init(&signalMutex, 0);
if (0 != funcCallStat)
{
return -1;
}
funcCallStat = pthread_create(&hdlthreadSignalProcessor, 0, threadSignalProcessor, 0);
if (0 != funcCallStat)
{
return -1;
}
for (tmp = 0; tmp < (sizeof(validSignal) / sizeof(int)); tmp++)
{
funcCallStat = staticSimpleSigaction(validSignal[tmp], staticSignalCatcher);
if (funcCallStat < 0)
{
break;
}
}
return funcCallStat;
}
| 0
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t)
{
int i;
long my_id = (long)t;
for (i=0; i<10; i++) {
pthread_mutex_lock(&count_mutex);
count++;
if (count == 12) {
pthread_cond_signal(&count_threshold_cv);
printf("inc_count(): thread %ld, count = %d Threshold reached.\\n",
my_id, count);
}
printf("inc_count(): thread %ld, count = %d, unlocking mutex\\n",
my_id, count);
pthread_mutex_unlock(&count_mutex);
sleep(1);
}
pthread_exit(0);
}
void *watch_count(void *t)
{
long my_id = (long)t;
printf("Starting watch_count(): thread %ld\\n", my_id);
pthread_mutex_lock(&count_mutex);
while (count<12) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
count += 125;
printf("watch_count(): thread %ld count now = %d.\\n", my_id, count);
}
pthread_mutex_unlock(&count_mutex);
pthread_exit(0);
}
int main (int argc, char *argv[])
{
int i, rc;
long t1=1, t2=2, t3=3;
pthread_t threads[3];
pthread_attr_t attr;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threads[0], &attr, watch_count, (void *)t1);
pthread_create(&threads[1], &attr, inc_count, (void *)t2);
pthread_create(&threads[2], &attr, inc_count, (void *)t3);
for (i=0; i<3; i++) {
pthread_join(threads[i], 0);
}
printf ("Main(): Waited on %d threads. Done.\\n", 3);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct msg {
struct msg *next;
int num;
};
void print_list(struct msg *head);
struct msg *head;
struct msg *tail;
pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *consumer(void *p)
{
struct msg *mp;
for (;;) {
pthread_mutex_lock(&lock);
while (head == 0)
pthread_cond_wait(&has_product, &lock);
mp = head;
head = mp->next;
pthread_mutex_unlock(&lock);
printf("Consume %d\\n", mp->num);
free(mp);
int sec = rand() % 5;
printf("consumer gonna sleep %d secs.\\n", sec);
sleep(sec);;
}
}
void *producer(void *p)
{
struct msg *mp;
for (;;) {
mp = malloc(sizeof(struct msg));
mp->num = rand() % 1000 + 1;
printf("Produce %d\\n", mp->num);
pthread_mutex_lock(&lock);
if (tail != 0) tail->next = mp;
tail = mp;
tail->next = 0;
if (head == 0) head = tail;
print_list(head);
pthread_mutex_unlock(&lock);
pthread_cond_signal(&has_product);
int sec = rand() % 5;
printf("producer gonna sleep %d secs.\\n", sec);
sleep(sec);;
}
}
int main(int argc, char *argv[])
{
pthread_t pid, cid;
srand(time(0));
pthread_create(&pid, 0, producer, 0);
pthread_create(&cid, 0, consumer, 0);
pthread_join(pid, 0);
pthread_join(cid, 0);
return 0;
}
void print_list(struct msg *head)
{
for (; head != 0; head = head->next) {
printf("%d->", head->num);
}
printf("NULL\\n");
}
| 0
|
#include <pthread.h>
char* key;
char* value;
size_t value_len;
struct hash_item** pprev;
struct hash_item* next;
} hash_item;
hash_item* hash[1024];
pthread_mutex_t hash_mutex[1024];
hash_item* hash_get(const char* key, int create) {
unsigned b = string_hash(key) % 1024;
hash_item* h = hash[b];
while (h != 0 && strcmp(h->key, key) != 0) {
h = h->next;
}
if (h == 0 && create) {
h = (hash_item*) malloc(sizeof(hash_item));
h->key = strdup(key);
h->value = 0;
h->value_len = 0;
h->pprev = &hash[b];
h->next = hash[b];
hash[b] = h;
if (h->next != 0) {
h->next->pprev = &h->next;
}
}
return h;
}
void* connection_thread(void* arg) {
int cfd = (int) (uintptr_t) arg;
FILE* fin = fdopen(cfd, "r");
FILE* f = fdopen(cfd, "w");
pthread_detach(pthread_self());
char buf[1024], key[1024], key2[1024];
size_t sz;
while (fgets(buf, 1024, fin)) {
if (sscanf(buf, "get %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
fprintf(f, "VALUE %s %zu %p\\r\\n",
key, h->value_len, h);
fwrite(h->value, 1, h->value_len, f);
fprintf(f, "\\r\\n");
}
fprintf(f, "END\\r\\n");
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 1);
free(h->value);
h->value = (char*) malloc(sz);
h->value_len = sz;
fread(h->value, 1, sz, fin);
fprintf(f, "STORED %p\\r\\n", h);
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "delete %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
free(h->key);
free(h->value);
*h->pprev = h->next;
if (h->next) {
h->next->pprev = h->pprev;
}
free(h);
fprintf(f, "DELETED %p\\r\\n", h);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "exch %s %s ", key, key2) == 2) {
unsigned b = string_hash(key);
unsigned b2 = string_hash(key2);
pthread_mutex_lock(&hash_mutex[b]);
if (b2 != b) {
pthread_mutex_lock(&hash_mutex[b2]);
}
hash_item* h = hash_get(key, 0);
hash_item* h2 = hash_get(key2, 0);
if (h != 0 && h2 != 0) {
char* tmp = h->value;
h->value = h2->value;
h2->value = tmp;
size_t tmpsz = h->value_len;
h->value_len = h2->value_len;
h2->value_len = tmpsz;
fprintf(f, "EXCHANGED %p %p\\r\\n", h, h2);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
if (b2 != b) {
pthread_mutex_unlock(&hash_mutex[b2]);
}
} else if (remove_trailing_whitespace(buf)) {
fprintf(f, "ERROR\\r\\n");
fflush(f);
}
}
if (ferror(fin)) {
perror("read");
}
fclose(fin);
(void) fclose(f);
return 0;
}
int main(int argc, char** argv) {
for (int i = 0; i != 1024; ++i) {
pthread_mutex_init(&hash_mutex[i], 0);
}
int port = 6168;
if (argc >= 2) {
port = strtol(argv[1], 0, 0);
assert(port > 0 && port <= 65535);
}
int fd = open_listen_socket(port);
assert(fd >= 0);
while (1) {
int cfd = accept(fd, 0, 0);
if (cfd < 0) {
perror("accept");
exit(1);
}
pthread_t t;
int r = pthread_create(&t, 0, connection_thread,
(void*) (uintptr_t) cfd);
if (r != 0) {
perror("pthread_create");
exit(1);
}
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t user_lock;
struct user_info {
char user[32];
char pass[32];
unsigned char pril;
pthread_mutex_t lock;
int ref;
unsigned char used;
} user_db[100];
int mgr_cnt;
void inline get_word(char* line, char* word)
{
while (*line != ' ' && *line != '\\t' && *line) {
*word = *line;
word ++;
line ++;
}
word = 0;
}
void inline get_lword(char* line, char* word)
{
int i = strlen(line) - 1;
while (line[i] != '/' && i >= 0) i--;
strcpy(word, &line[i+1]);
}
void inline mgr_trim(char* buf){
buf[strlen(buf)-1] = 0;
}
void mgr_init()
{
int i, retval;
FILE* fd;
char null[10];
memset(user_db, 0, sizeof(user_db));
for (i = 0; i < 100; i++)
pthread_mutex_init(&user_db[i].lock, 0);
auth_init();
fd = fopen("conf/passwd", "r");
i = 0;
memset(user_db, 0, sizeof(user_db));
while (1)
{
i++;
if (fscanf(fd, "%s %s",user_db[i].user, user_db[i].pass) == EOF) break;
user_db[i].used = 1;
}
fclose(fd);
printf("end\\n");
}
int inline mgr_find_name(char* name)
{
return auth_get_uid(name);
}
void mgr_add(char* buf)
{
}
void mgr_del(char* buf)
{
}
int mgr_cntcur(){
int i, cnt = 0;
for (i = 0; i < 100; i++)
if (user_db[i].ref > 0)
cnt ++;
return cnt;
}
int inline mgr_cntall(){
return mgr_cnt;
}
int mgr_kill(char* name)
{
int i = mgr_find_name(name);
if (i >= 0) {
pthread_mutex_lock(&user_db[i].lock);
user_db[i].ref --;
pthread_mutex_unlock(&user_db[i].lock);
}
}
int mgr_check(char* name, char* pass, unsigned char first)
{
int i = auth_user(name,pass);
if (i>0) {
pthread_mutex_lock(&user_db[i].lock);
user_db[i].ref ++;
pthread_mutex_unlock(&user_db[i].lock);
if (first) {
mgr_cnt ++;
return mgr_cnt;
}
return 1;
}
return 0;
}
void mgr_statall()
{
int i;
for (i = 0; i < 100; i++)
if (user_db[i].used)
printf("%s has %d links now.\\n", user_db[i].user, user_db[i].ref);
}
void mgr_stat(char* name)
{
int i = mgr_find_name(name);
if (i == S_NO_USER)
printf("No such user.\\n");
printf("%s has %d links now.\\n", name, user_db[i].ref);
}
| 0
|
#include <pthread.h>
static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ti = 0;
struct node {
int n_number;
struct node *n_next;
} *head = 0;
static void cleanup_handler(void *arg)
{
printf("cleanup handler of second thread.\\n");
free(arg);
(void)pthread_mutex_unlock(&mtx);
}
static void *thread_func(void *arg)
{
struct node *p = 0;
printf("enter thread_func\\n");
pthread_cleanup_push(cleanup_handler, p);
while(1) {
printf("while cycle %d\\n", getpid());
pthread_mutex_lock(&mtx);
while(head == 0) {
printf("in the sub_while cycle\\n");
pthread_cond_wait(&cond, &mtx);
}
p = head;
head = head->n_next;
printf("Got %d from front of queue\\n", p->n_number);
free(p);
pthread_mutex_unlock(&mtx);
}
pthread_cleanup_pop(0);
return 0;
}
int main(void)
{
pthread_t tid;
int i;
struct node *p;
pthread_create(&tid, 0, thread_func, 0);
for(i = 0; i < 10; i++) {
p = malloc(sizeof(struct node));
p->n_number = i;
pthread_mutex_lock(&mtx);
p->n_next = head;
head = p;
pthread_mutex_unlock(&mtx);
sleep(1);
}
printf("thread 1 wanna end the line.So cancel therad 2.\\n");
pthread_cancel(tid);
pthread_join(tid, 0);
printf("All done -- exiting\\n");
return 0;
}
| 1
|
#include <pthread.h>
void *Process(void *p);
void Receive(int *connfd);
void Reply(int *connfd, char *file);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int sfd;
struct sockaddr_in addr;
sfd = socket(PF_INET, SOCK_STREAM, 0);
if (sfd == -1)
{
printf("Initialize socket error\\n");
return 1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(50790);
addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
printf("Bind port error\\n");
return 1;
}
int thread_id;
pthread_t thread;
int connfd;
while (1)
{
if (listen(sfd, 10) == -1)
{
printf("Setup port error\\n");
return 1;
}
connfd = accept(sfd, 0, 0);
thread_id = pthread_create(&thread, 0, Process, &connfd);
pthread_join(thread, 0);
close(connfd);
}
close(sfd);
return 0;
}
void *Process(void *p)
{
pthread_mutex_lock(&mutex);
int *connfd = (int *)p;
Receive(connfd);
pthread_mutex_unlock(&mutex);
}
void Receive(int *connfd)
{
char buf[1024];
char file[1024];
recv(*connfd, buf, 1024, 0);
if (strncmp(buf, "GET ", 4) == 0)
{
int i;
for (i = 0; i < 1024; i++)
{
if (buf[i+5] == ' ' || buf[i+5] == '\\n' || buf[i+5] == '\\0')
break;
file[i] = buf[i+5];
}
file[i] = '\\0';
Reply(connfd, file);
}
FILE *f = fopen("stats.txt", "a");
fprintf(f, "\\n%s\\n", buf);
fclose(f);
memset(buf, 0, sizeof(buf));
}
void Reply(int *connfd, char *file)
{
FILE *f;
f = fopen(file, "r");
char *message;
if (f == 0)
{
message = (char *)malloc(25*sizeof(char));
strcpy(message, "HTTP/1.1 404 Not Found\\n");
}
else
{
fseek(f, 0, 2);
int length = (int)ftell(f);
fseek(f, 0, 0);
message = (char *)malloc((200+length)*sizeof(char));
strcpy(message, "HTTP/1.1 200 OK\\n");
time_t curtime;
struct tm *loctime;
curtime = time(0);
loctime = localtime(&curtime);
char strtime[100];
strftime(strtime, 100, "Date: %A, %d %B %Y %X %Z\\n", loctime);
strcat(message, strtime);
char c[100];
sprintf(c, "Content-Length: %d\\nConnection: close\\nContent-Type: text/html\\n\\n", length);
strcat(message, c);
char *filecontent = (char *)malloc(length*sizeof(char));
fread(filecontent, 1, length, f);
strcat(message, filecontent);
fclose(f);
free(filecontent);
}
send(*connfd, message, strlen(message), 0);
free(message);
}
| 0
|
#include <pthread.h>
{
pthread_mutex_t pid_mutex;
pid_t pid;
}pid_data;
int set_priority(int priority){
int policy;
struct sched_param param;
if(priority < 1 || priority > 63) return -1;
pthread_getschedparam(pthread_self(),&policy,¶m);
param.sched_priority = priority;
return pthread_setschedparam(pthread_self(),policy,¶m);
}
int get_priority(){
int policy;
struct sched_param param;
pthread_getschedparam(pthread_self(),&policy,¶m);
return param.sched_curpriority;
}
int main(int argc, char *argv[])
{
set_priority(30);
pthread_mutexattr_t mutex_attributes;
pid_data * server_pid;
char recieve_buffer[1024];
memset(recieve_buffer,'\\0',sizeof(recieve_buffer));
char send_buffer[1024];
memset(send_buffer,'\\0',sizeof(send_buffer));
struct _msg_info message_info;
int file_descriptor = shm_open("/sharedpid", O_RDWR | O_CREAT, S_IRWXU);
ftruncate(file_descriptor, sizeof(pid_data));
void * shared_memory_ptr = mmap(0, sizeof(pid_data), PROT_READ | PROT_WRITE, MAP_SHARED, file_descriptor, 0);
server_pid = (pid_data*)shared_memory_ptr;
pthread_mutexattr_init(&mutex_attributes);
pthread_mutexattr_setpshared(&mutex_attributes, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&server_pid->pid_mutex, &mutex_attributes);
pthread_mutex_lock(&server_pid->pid_mutex);
server_pid->pid = getpid();
pthread_mutex_unlock(&server_pid->pid_mutex);
int pid_int = (int)getpid();
printf("Server: server PID is: %i\\n", pid_int);
printf("Server: Creating channel..\\n");
int channel_id = ChannelCreate(_NTO_CHF_FIXED_PRIORITY);
printf("Server: Channel created: %i \\n\\n", channel_id);
while(1)
{
printf("Server: current priority before MsgReceive: %i\\n", get_priority());
int message_id = MsgReceive(channel_id,&recieve_buffer, 1024, &message_info);
printf("Server: New message - from PID %i and TID %i\\n", message_info.pid, message_info.tid);
printf("Server: current priority after MsgReceive: %i\\n", get_priority());
printf("Server: client message: %s\\n\\n", recieve_buffer);
sprintf(send_buffer, "Thank, bro!");
MsgReply(message_id, EOK, &send_buffer, sizeof(send_buffer));
}
return 0;
}
| 1
|
#include <pthread.h>
unsigned int __VERIFIER_nondet_uint();
static int top=0;
static unsigned int arr[(5)];
pthread_mutex_t m;
_Bool flag=(0);
void error(void)
{
ERROR: ;
goto ERROR;
return;
}
void inc_top(void)
{
top++;
}
void dec_top(void)
{
top--;
}
int get_top(void)
{
return top;
}
int stack_empty(void)
{
(top==0) ? (1) : (0);
}
int push(unsigned int *stack, int x)
{
if (top==(5))
{
printf("stack overflow\\n");
return (-1);
}
else
{
stack[get_top()] = x;
inc_top();
}
return 0;
}
int pop(unsigned int *stack)
{
if (top==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(5);
if (push(arr,tmp)==(-1))
error();
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<(5); i++)
{
pthread_mutex_lock(&m);
if (top>0)
{
if ((pop(arr)==(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
#include <pthread.h>
void * start_routine1(void *arg);
void * start_routine2(void *arg);
pthread_mutex_t lock;
int i;
int
main(int argc, char const *argv[])
{
pthread_t tid1, tid2;
pthread_mutex_init(&lock,0);
if (pthread_create(&tid1, 0,start_routine1,0) != 0)
perror("pthread_create");
if (pthread_create(&tid2, 0,start_routine2,0) != 0)
perror("pthread_create");
if (pthread_detach(tid1) !=0 )
perror("pthread_detach");
if (pthread_detach(tid2) !=0 )
perror("pthread_detach");
srand(time(0));
while(1) {
pthread_mutex_lock(&lock);
sleep(rand() % 3);
printf("main thread: i = %d\\n", i);
i++;
pthread_mutex_unlock(&lock);
sleep(rand() % 3);
}
pthread_mutex_destroy(&lock);
return 0;
}
void *
start_routine1(void *arg)
{
while(1) {
pthread_mutex_lock(&lock);
sleep(rand() % 3);
printf("1 thread: i = %d\\n", i);
i++;
pthread_mutex_unlock(&lock);
sleep(rand() % 3);
}
pthread_mutex_destroy(&lock);
return (void *)1;
}
void *
start_routine2(void *arg)
{
while(1) {
pthread_mutex_lock(&lock);
sleep(rand() % 3);
printf("2 thread: i = %d\\n", i);
i++;
pthread_mutex_unlock(&lock);
sleep(rand() % 3);
}
pthread_mutex_destroy(&lock);
return (void *)2;
}
| 1
|
#include <pthread.h>
pthread_mutex_t LOCK;
pthread_mutex_t TRIGGER;
pthread_cond_t COND;
volatile unsigned int cs_count = 0;
void * function(void *id){
int t_id = *(int *)id;
pthread_mutex_lock(&TRIGGER);
pthread_mutex_unlock(&TRIGGER);
pthread_mutex_lock(&LOCK);
if (cs_count > 0){
pthread_cond_signal(&COND);
}
while(cs_count < ITERATIONS) {
cs_count++;
pthread_cond_wait(&COND, &LOCK);
pthread_cond_signal(&COND);
}
pthread_mutex_unlock(&LOCK);
pthread_exit(0);
}
int main(){
pthread_t threads[2];
int rc, i,id1=1, id2=2;
unsigned long long int t;
pthread_mutex_init(&LOCK, 0);
pthread_mutex_init(&TRIGGER, 0);
pthread_cond_init(&COND, 0);
pthread_mutex_lock(&TRIGGER);
rc = pthread_create(&threads[0], 0, function, (void*)&id1);
if (rc){
perror("Thread creation failed!");
}
rc = pthread_create(&threads[1], 0, function, (void*)&id2);
if (rc){
perror("Thread creation failed!");
}
t = rdtsc();
pthread_mutex_unlock(&TRIGGER);
for(i=0; i<2; i++) {
pthread_join(threads[i], 0);
}
t = rdtsc() - t;
printf("%f\\n",(t/(CPU_FREQ*ITERATIONS)) - TIME_MEASUREMENT_OVERHEAD);
pthread_mutex_destroy(&LOCK);
pthread_mutex_destroy(&TRIGGER);
pthread_cond_destroy(&COND);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
void* threadFunction( void* rank );
pthread_mutex_t mutex;
double globalSum = 0.0;
int main( void )
{
double startTime, finishTime;
pthread_mutex_init( &mutex, ( pthread_mutexattr_t* ) 0 );
pthread_t* threadHandles = ( pthread_t* )malloc( 8 * sizeof( pthread_t ) );
GET_TIME( startTime );
for( long threadIndex = 0; threadIndex < 8; threadIndex++ )
{
pthread_create( ( threadHandles + threadIndex ), 0, threadFunction, ( void* )threadIndex );
}
for( long threadIndex = 0; threadIndex < 8; threadIndex++ )
{
pthread_join( *( threadHandles + threadIndex ), 0 );
}
GET_TIME( finishTime );
printf( "phi value: %f \\n", 4.0 * globalSum );
printf( "total elapsed time %f milliseconds\\n", finishTime - startTime );
pthread_mutex_destroy( &mutex );
}
void* threadFunction( void* rank )
{
long threadRank = ( long ) rank;
long termsPerThread = 4096 / 8;
long lowerBound = threadRank * termsPerThread;
long upperBound = lowerBound + termsPerThread;
double factor;
double threadSum = 0.0;
if( lowerBound % 2 == 0 )
{
factor = 1.0;
}
else
{
factor = -1.0;
}
for( long index = lowerBound; index < upperBound; index++ )
{
threadSum = threadSum + factor / ( 2.0 * index + 1.0 );
factor = factor * ( -1.0 );
}
pthread_mutex_lock( &mutex );
globalSum = globalSum + threadSum;
printf( "thread %ld was used the mutex..\\n", threadRank );
pthread_mutex_unlock( &mutex );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t sumLock = PTHREAD_MUTEX_INITIALIZER;
int *vk;
int *vTrue;
pthread_t thread;
int state;
int toVector;
int startPosition;
int endPosition;
}Boundary_t;
void* sumThread(void* bd){
Boundary_t *boundary = (Boundary_t*)bd;
int localSum=0;
for(int i = boundary->startPosition; i <= boundary->endPosition; ++i){
localSum += vk[i];
}
pthread_mutex_lock(&sumLock);
vTrue[boundary->toVector] = localSum;
pthread_mutex_unlock(&sumLock);
return 0;
}
void buildVector(int **vector, int length){
(*vector) = malloc(sizeof(int)*length);
do{
length--;
(*vector)[length] = rand() % 100;
}while(length>=0);
}
void buildSumVector(int **vector, int length){
(*vector) = malloc(sizeof(int)*length);
do{
length--;
(*vector)[length] = 0;
}while(length>=0);
}
void buildBoundaries(Boundary_t **tVector, int numThreads, int length){
const int pass = length / numThreads;
(*tVector) = malloc(sizeof(Boundary_t)*numThreads);
for(int i=0; i < numThreads ; i++){
(*tVector)[i].startPosition = i*(pass);
(*tVector)[i].endPosition = ((*tVector)[i].startPosition+pass)-1;
(*tVector)[i].toVector = i;
}
(*tVector)[numThreads-1].endPosition = (length-1);
}
int main(int argc, char *argv[]){
int length = atoi(argv[1]);
int threads = atoi(argv[2]);
int threshold = atoi(argv[3]);
double sumptr = 0;
int *vector, *sumVector = 0;
Boundary_t *threadVector = 0;
srand(time(0));
buildVector(&vector, length);
buildBoundaries(&threadVector, threads, length);
buildSumVector(&sumVector, threads);
vk = vector;
vTrue = sumVector;
for(int i=0; i < threshold; i++){
clock_t ping = clock();
for(int i=0;i<threads;i++){
threadVector[i].state = pthread_create(&threadVector[i].thread, 0, sumThread, &threadVector[i]);
}
for(int i=0;i<threads;i++){
pthread_join(threadVector[i].thread, 0);
}
clock_t pong = clock();
sumptr += ((double)(pong-ping));
}
printf("%.6lf;", (sumptr/(threshold*CLOCKS_PER_SEC)));
}
| 0
|
#include <pthread.h>
int stoj = 0;
int cakaju = 0, volneMiesta = 10;
int vsetciCakaju = 0;
int pocetPiv = 0;
pthread_mutex_t mutexPivo = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexCakanie = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condPivo = PTHREAD_COND_INITIALIZER;
pthread_cond_t condCakaj = PTHREAD_COND_INITIALIZER;
void robotnik_pracuj(void) {
sleep(3);
}
void robotnik_pi(void) {
pthread_mutex_lock(&mutexPivo);
while(volneMiesta == 0){
if(stoj){
pthread_mutex_unlock(&mutexPivo);
return;
}
pthread_cond_wait(&condPivo, &mutexPivo);
}
if(stoj){
pthread_mutex_unlock(&mutexCakanie);
return;
}
volneMiesta--;
pthread_mutex_unlock(&mutexPivo);
sleep(5);
pthread_mutex_lock(&mutexPivo);
pocetPiv++;
volneMiesta++;
printf("ROB: vypil som pivo (celkovo %d)\\n", pocetPiv);
pthread_cond_signal(&condPivo);
pthread_mutex_unlock(&mutexPivo);
pthread_mutex_lock(&mutexCakanie);
cakaju++;
printf("Cakaju: %d\\n", cakaju);
if(cakaju == 20){
vsetciCakaju = 1;
printf("Uz cakame vsetci !\\n");
pthread_cond_broadcast(&condCakaj);
} else {
while(!vsetciCakaju){
if(stoj){
pthread_mutex_unlock(&mutexCakanie);
return;
}
pthread_cond_wait(&condCakaj, &mutexCakanie);
}
}
if(stoj){
pthread_mutex_unlock(&mutexCakanie);
return;
}
cakaju--;
printf("Cakaju: %d\\n", cakaju);
if(cakaju == 0){
vsetciCakaju = 0;
printf("Uz odisli vsetci\\n");
}
pthread_mutex_unlock(&mutexCakanie);
}
void *robotnik(void *ptr) {
while(!stoj) {
robotnik_pracuj();
robotnik_pi();
}
return 0;
}
int main(void) {
int i;
pthread_t robotnici[20];
for (i=0;i<20;i++) pthread_create(&robotnici[i], 0, &robotnik, 0);
sleep(30);
pthread_mutex_lock(&mutexPivo);
pthread_mutex_lock(&mutexCakanie);
stoj = 1;
printf("Koniec simulacie !!!\\n");
pthread_cond_broadcast(&condCakaj);
pthread_cond_broadcast(&condPivo);
pthread_mutex_unlock(&mutexCakanie);
pthread_mutex_unlock(&mutexPivo);
for (i=0;i<20;i++) pthread_join(robotnici[i], 0);
printf("Celkovy pocet vypitych piv: %d\\n", pocetPiv);
exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *thread1(void *);
void *thread2(void *);
int i=1;
int main(void)
{
pthread_t t_a;
pthread_t t_b;
pthread_create(&t_a,0,thread2,(void *)0);
pthread_create(&t_b,0,thread1,(void *)0);
pthread_join(t_b, 0);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
exit(0);
}
void *thread1(void *junk)
{
for(i=1;i<=9;i++)
{
pthread_mutex_lock(&mutex);
if(i%3==0)
pthread_cond_signal(&cond);
else
printf("pthead1:%d\\n",i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *thread2(void *junk)
{
while(i<9)
{
pthread_mutex_lock(&mutex);
if(i%3!=0)
pthread_cond_wait(&cond,&mutex);
printf("thread2:%d\\n",i);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
| 0
|
#include <pthread.h>
sem_t sem;
int semVal;
pthread_mutex_t mut;
pthread_cond_t condC;
pthread_cond_t condA;
void utiliserPont(int type){
if (type == 1){
sem_wait(&sem);
sem_getvalue(&sem, &semVal);
}
else{
int i = 0;
for(i=0; i<3; i++){
sem_wait(&sem);
sem_getvalue(&sem, &semVal);
}
}
}
void libererPont(int type){
if (type == 1){
sem_post(&sem);
sem_getvalue(&sem, &semVal);
}
else{
int i = 0;
for(i=0; i<3; i++){
sem_post(&sem);
sem_getvalue(&sem, &semVal);
}
}
}
void* voiture(void* arg){
printf("Voiture %d en attente d'un coté du pont !\\n", (int)pthread_self());
sleep(1);
pthread_mutex_lock(&mut);
if (semVal != 0){
pthread_cond_wait(&condA, &mut);
pthread_mutex_unlock(&mut);
utiliserPont(1);
printf("Voiture %d utilise le pont !\\n", (int)pthread_self());
sleep(3);
libererPont(1);
}
if (semVal == 3)
pthread_cond_broadcast(&condC);
printf("Voiture %d a fini d'utiliser le pont !\\n\\n", (int)pthread_self());
sleep(1);
pthread_exit(0);
}
void* camion(void* arg){
printf("Camion %d en attente d'un coté du pont !\\n", (int)pthread_self());
sleep(1);
pthread_mutex_lock(&mut);
if(semVal != 0){
pthread_cond_wait(&condC, &mut);
utiliserPont(2);
printf("Camion %d utilise le pont !\\n", (int)pthread_self());
sleep(3);
libererPont(2);
}
pthread_mutex_unlock(&mut);
if (semVal == 3)
pthread_cond_broadcast(&condA);
printf("Camion %d a fini d'utiliser le pont !\\n\\n", (int)pthread_self());
sleep(1);
pthread_exit(0);
}
int main(){
pthread_t v1, v2, v3, v4;
pthread_t c1, c2, c3, c4;
sem_init(&sem, 0, 3);
sem_getvalue(&sem, &semVal);
pthread_mutex_init(&mut, 0);
pthread_cond_init(&condC, 0);
pthread_cond_init(&condA, 0);
pthread_create(&v1, 0, voiture, 0);
pthread_create(&v2, 0, voiture, 0);
pthread_create(&v3, 0, voiture, 0);
pthread_create(&v4, 0, voiture, 0);
pthread_create(&c1, 0, camion, 0);
pthread_create(&c2, 0, camion, 0);
pthread_create(&c3, 0, camion, 0);
pthread_create(&c4, 0, camion, 0);
sleep(3);
pthread_cond_broadcast(&condC);
pthread_join(v1, 0);
pthread_join(v2, 0);
pthread_join(v3, 0);
pthread_join(v4, 0);
pthread_join(c1, 0);
pthread_join(c2, 0);
pthread_join(c3, 0);
pthread_join(c4, 0);
printf("fin main\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_cond_t adultBoardOahu;
pthread_cond_t kidsBoardOahu;
pthread_cond_t onBoat;
pthread_cond_t onMolo;
int boatLoc;
int kidsOnBoard;
int adultsOnBoard;
int adultGoes;
int canBoard;
void init() {
pthread_mutex_init(&lock, 0);
pthread_cond_init(&allReady, 0);
pthread_cond_init(&mayStart, 0);
pthread_cond_init(&allDone, 0);
pthread_cond_init(&adultBoardOahu, 0);
pthread_cond_init(&kidsBoardOahu, 0);
pthread_cond_init(&onBoat, 0);
pthread_cond_init(&onMolo, 0);
boatLoc = OAHU;
kidsOnBoard = 0;
adultsOnBoard = 0;
adultGoes = 0;
canBoard = 1;
}
void* childThread(void* args) {
pthread_mutex_lock(&lock);
kidsOahu++;
pthread_cond_signal(&allReady);
while (!start) {
pthread_cond_wait(&mayStart, &lock);
}
while(kidsOahu != 0) {
while(boatLoc == MOLO || kidsOnBoard > 1) {
pthread_cond_wait(&kidsBoardOahu, &lock);
}
if(kidsOahu > 0) {
boardBoat(KID, OAHU);
kidsOahu--;
kidsOnBoard++;
printf("%i\\n", kidsOnBoard);
fflush(stdout);
}
if(kidsOnBoard == 1) {
if(kidsOahu == 0) {
boatCross(OAHU, MOLO);
boatLoc = MOLO;
printf("%i", kidsOnBoard);
fflush(stdout);
leaveBoat(KID, MOLO);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
pthread_cond_signal(&allDone);
pthread_mutex_unlock(&lock);
}
while(boatLoc == OAHU || kidsOnBoard == 2){
pthread_cond_wait(&onBoat, &lock);
}
leaveBoat(KID, MOLO);
kidsOnBoard--;
boatLoc = OAHU;
pthread_cond_signal(&kidsBoardOahu);
pthread_cond_signal(&allDone);
pthread_mutex_unlock(&lock);
} else {
boatCross(OAHU, MOLO);
boatLoc = MOLO;
printf("%i", kidsOnBoard);
fflush(stdout);
leaveBoat(KID, MOLO);
printf("left");
fflush(stdout);
kidsOnBoard--;
pthread_cond_signal(&onBoat);
pthread_mutex_unlock(&lock);
}
}
return 0;
}
void *adultThread(void* args) {
return 0;
}
| 0
|
#include <pthread.h>
static char *self = "018";
static char *set = "01689";
int count = 0;
pthread_mutex_t output_mutex;
void real_output(int len, char *current){
int mid = len >> 1,
tail = len - 1,
i;
char c;
for(i = 0; i <= mid; ++i){
switch(current[i]){
case '0':
c = '0';
break;
case '1':
c = '1';
break;
case '8':
c = '8';
break;
case '6':
c = '9';
break;
case '9':
c = '6';
break;
}
current[tail - i] = c;
}
current[len] = 0;
__sync_fetch_and_add(&count, 1);
}
struct output_work {
int vacant;
int len;
char current[32];
};
struct output_workerbox {
struct output_work work;
pthread_mutex_t work_mutex;
pthread_cond_t work_available_cond;
};
void *output_worker(void *d){
struct output_workerbox *box = (struct output_workerbox *)d;
struct output_work *work = &(box->work);
pthread_mutex_t *mx = &(box->work_mutex);
pthread_cond_t *work_available = &(box->work_available_cond);
pthread_mutex_lock(mx);
if(work->vacant){
pthread_cond_wait(work_available, mx);
}
while(work->len > 0){
real_output(work->len, work->current);
work->vacant = 1;
pthread_cond_signal(work_available);
pthread_cond_wait(work_available, mx);
}
pthread_cond_signal(work_available);
pthread_mutex_unlock(mx);
pthread_exit(0);
}
void broker_send_work(struct output_workerbox *box, int len, char *current){
pthread_mutex_lock(&(box->work_mutex));
if(!box->work.vacant){
pthread_cond_wait(
&(box->work_available_cond),
&(box->work_mutex));
}
box->work.vacant = 0;
box->work.len = len;
memcpy(box->work.current, current, 32);
pthread_cond_signal(&(box->work_available_cond));
pthread_mutex_unlock(&(box->work_mutex));
}
struct output_work broker_workbox;
pthread_mutex_t broker_workbox_mutex;
pthread_cond_t broker_available_cond;
void *output_broker(void *d){
struct output_workerbox workerboxes[12];
pthread_t output_worker_thread[12];
int i;
for(i = 0; i < 12; ++i){
pthread_mutex_init(&(workerboxes[i].work_mutex), 0);
pthread_cond_init(&(workerboxes[i].work_available_cond), 0);
workerboxes[i].work.vacant = 1;
pthread_create(&output_worker_thread[i], 0, output_worker, &workerboxes[i]);
}
pthread_mutex_lock(&broker_workbox_mutex);
if(broker_workbox.vacant){
pthread_cond_wait(&broker_available_cond, &broker_workbox_mutex);
}
i = 0;
while(broker_workbox.len > 0){
i = (i + 1) % 12;
broker_send_work(&(workerboxes[i]), broker_workbox.len,
broker_workbox.current);
broker_workbox.vacant = 1;
pthread_cond_broadcast(&broker_available_cond);
pthread_cond_wait(&broker_available_cond, &broker_workbox_mutex);
}
pthread_cond_signal(&broker_available_cond);
pthread_mutex_unlock(&broker_workbox_mutex);
for(i = 0; i < 12; ++i) {
broker_send_work(&workerboxes[i], -1, broker_workbox.current);
}
for(i = 0; i < 12; ++i) {
pthread_join(output_worker_thread[i], 0);
}
pthread_exit(0);
}
void output(int len, char *current){
pthread_mutex_lock(&broker_workbox_mutex);
while(!broker_workbox.vacant){
pthread_cond_wait(&broker_available_cond, &broker_workbox_mutex);
}
broker_workbox.vacant = 0;
broker_workbox.len = len;
memcpy(broker_workbox.current, current, 32);
pthread_cond_signal(&broker_available_cond);
pthread_mutex_unlock(&broker_workbox_mutex);
}
struct work {
int pos;
int len;
char current[32];
};
void recurs(int pos, int len, char *current){
char *p;
if(pos >= (len >> 1)){
if(len & 1){
for(p = self; *p; ++p){
current[pos] = *p;
real_output(len, current);
}
}
else {
real_output(len, current);
}
return;
}
if(pos) p = set;
else p = set + 1;
for(; *p; ++p){
current[pos] = *p;
recurs(pos + 1, len, current);
}
return;
}
void *Worker(void *d){
struct work *w = (struct work *)d;
recurs(w->pos, w->len, w->current);
pthread_exit (0);
}
void workon(int len){
pthread_t threads[6];
struct work thread_args[6];
char *bruce[] = {
"10", "11", "16", "18", "19",
"60", "61", "66", "68", "69",
"80", "81", "86", "88", "89",
"90", "91", "96", "98", "99" };
int i, next;
for(i=0; i<6; ++i){
thread_args[i].pos = 2;
thread_args[i].len = len;
thread_args[i].current[0] = bruce[i][0];
thread_args[i].current[1] = bruce[i][1];
pthread_create(&threads[i], 0, Worker, (void *) &thread_args[i]);
}
while(i < 20){
next = i%6;
pthread_join(threads[next], 0);
thread_args[next].pos = 2;
thread_args[next].len = len;
thread_args[next].current[0] = bruce[i][0];
thread_args[next].current[1] = bruce[i][1];
pthread_create(&threads[next], 0, Worker, (void *) &thread_args[next]);
++i;
}
for (i=0; i<6; ++i) {
pthread_join(threads[i], 0);
}
return;
}
int main() {
int len;
char stack[32];
pthread_t broker_thread;
pthread_mutex_init(&output_mutex, 0);
pthread_mutex_init(&broker_workbox_mutex, 0);
pthread_cond_init(&broker_available_cond, 0);
broker_workbox.vacant = 1;
pthread_create(&broker_thread, 0, output_broker, 0);
recurs(0, 1, stack);
recurs(0, 2, stack);
recurs(0, 3, stack);
recurs(0, 4, stack);
for(len = 5; len < 22; ++len){
workon(len);
}
output(-1, stack);
pthread_join(broker_thread, 0);
printf("%d\\n", count);
return 0;
}
| 1
|
#include <pthread.h>
int MyTurn = 0;
{
pthread_mutex_t *lock;
int id;
int size;
int iterations;
char *s;
int nthreads;
} Thread_struct;
void *infloop(void *x)
{
int i, j, k;
Thread_struct *t;
t = (Thread_struct *) x;
for (i = 0; i < t->iterations; i++)
{
pthread_mutex_lock(t->lock);
while((MyTurn % t->nthreads) != t->id)
{
pthread_mutex_unlock(t->lock);
pthread_mutex_lock(t->lock);
}
for (j = 0; j < t->size-1; j++)
{
t->s[j] = 'A'+t->id;
for(k=0; k < 50000; k++);
}
t->s[j] = '\\0';
printf("Thread %d: %s\\n", t->id, t->s);
MyTurn++;
pthread_mutex_unlock(t->lock);
}
return(0);
}
int
main(int argc, char **argv)
{
pthread_mutex_t lock;
pthread_t *tid;
pthread_attr_t *attr;
Thread_struct *t;
void *retval;
int nthreads, size, iterations, i;
char *s;
if (argc != 4)
{
fprintf(stderr, "usage: race nthreads stringsize iterations\\n");
exit(1);
}
pthread_mutex_init(&lock, 0);
nthreads = atoi(argv[1]);
size = atoi(argv[2]);
iterations = atoi(argv[3]);
tid = (pthread_t *) malloc(sizeof(pthread_t) * nthreads);
attr = (pthread_attr_t *) malloc(sizeof(pthread_attr_t) * nthreads);
t = (Thread_struct *) malloc(sizeof(Thread_struct) * nthreads);
s = (char *) malloc(sizeof(char *) * size);
for (i = 0; i < nthreads; i++)
{
t[i].nthreads = nthreads;
t[i].id = i;
t[i].size = size;
t[i].iterations = iterations;
t[i].s = s;
t[i].lock = &lock;
pthread_attr_init(&(attr[i]));
pthread_attr_setscope(&(attr[i]), PTHREAD_SCOPE_SYSTEM);
pthread_create(&tid[i], &(attr[i]), infloop, (void *)&(t[i]));
}
for (i = 0; i < nthreads; i++)
{
pthread_join(tid[i], &retval);
}
return(0);
}
| 0
|
#include <pthread.h>
void Test();
void Test_Mutex1();
void Test_Mutex2();
int main(void)
{
Test_Mutex2();
return 0;
}
void * Fun1(void * param)
{
int * p = (int *)param;
int n = 10;
for(int i = 0; i < n; i++)
{
*p += i;
usleep(1000);
}
printf("Fun1 param: %d\\n", *(int *)param);
return 0;
}
void * Fun2(void * param)
{
int n = *(int *)param;
usleep(10000);
printf("Fun2 param: %d\\n", n);
*(int *)param = 0;
return 0;
}
void Test()
{
pthread_t tid1, tid2;
int x = 0;
pthread_create(&tid1, 0, Fun1, (void *)&x);
pthread_create(&tid2, 0, Fun2, (void *)&x);
sleep(1);
printf("%d\\n", x);
}
pthread_mutex_t lock;
void * FunLock1(void * param)
{
pthread_mutex_lock(&lock);
int * p = (int *)param;
while(*p)
{
if(!(*p & 1))
{
printf("FunLock1: 偶数:%d\\n", *p);
}
(*p)--;
usleep(500);
}
*p = 10;
pthread_mutex_unlock(&lock);
return 0;
}
void * FunLock2(void * param)
{
pthread_mutex_lock(&lock);
int * p = (int *)param;
while(*p)
{
if(*p & 1)
{
printf("FunLock2: 奇数:%d\\n", *p);
}
(*p)--;
}
*p = 10;
pthread_mutex_unlock(&lock);
return 0;
}
void Test_Mutex1()
{
pthread_mutex_init(&lock, 0);
int x = 10;
pthread_t tid1, tid2;
pthread_create(&tid1, 0, FunLock1, (void *)&x);
pthread_create(&tid2, 0, FunLock2, (void *)&x);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
int g_x;
void * test1()
{
printf("test1: %d\\n", g_x);
int ret = pthread_mutex_lock(&lock);
if(ret)
{
printf("test1: 重复锁定\\n");
return 0;
}
for(int i = 0; i < g_x; i++)
{
usleep(10000);
printf("test1: %d\\n", i);
}
pthread_mutex_unlock(&lock);
return 0;
}
void * test2()
{
int ret = pthread_mutex_lock(&lock);
if(ret)
{
printf("test2: 重复锁定\\n");
return 0;
}
g_x = 10;
for(int i = 0; i < g_x; i++)
{
usleep(10000);
printf("tes2: %d\\n", i);
}
test1();
pthread_mutex_unlock(&lock);
return 0;
}
void * test3()
{
int ret = pthread_mutex_lock(&lock);
if(ret)
{
printf("test3: 重复锁定\\n");
return 0;
}
g_x = 5;
for(int i = 0; i < g_x; i++)
{
usleep(10000);
printf("test3: %d\\n", i);
}
pthread_mutex_unlock(&lock);
return 0;
}
void Test_Mutex2()
{
pthread_mutexattr_t attr;
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&lock, &attr);
pthread_t tid1, tid2;
pthread_create(&tid1, 0, test2, 0);
pthread_create(&tid2, 0, test3, 0);
pthread_join(tid1, 0);
pthread_join(tid2, 0);
}
| 1
|
#include <pthread.h>
enum Colour
{
blue = 0,
red = 1,
yellow = 2,
Invalid = 3
};
const char* ColourName[] = {"blue", "red", "yellow"};
const int STACK_SIZE = 32*1024;
const BOOL TRUE = 1;
const BOOL FALSE = 0;
int CreatureID = 0;
enum Colour doCompliment(enum Colour c1, enum Colour c2)
{
switch (c1)
{
case blue:
switch (c2)
{
case blue:
return blue;
case red:
return yellow;
case yellow:
return red;
default:
goto errlb;
}
case red:
switch (c2)
{
case blue:
return yellow;
case red:
return red;
case yellow:
return blue;
default:
goto errlb;
}
case yellow:
switch (c2)
{
case blue:
return red;
case red:
return blue;
case yellow:
return yellow;
default:
goto errlb;
}
default:
break;
}
errlb:
printf("Invalid colour\\n");
exit( 1 );
}
char* formatNumber(int n, char* outbuf)
{
int ochar = 0, ichar = 0;
int i;
char tmp[64];
const char* NUMBERS[] =
{
"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"
};
ichar = sprintf(tmp, "%d", n);
for (i = 0; i < ichar; i++)
ochar += sprintf( outbuf + ochar, " %s", NUMBERS[ tmp[i] - '0' ] );
return outbuf;
}
struct MeetingPlace
{
pthread_mutex_t mutex;
int meetingsLeft;
struct Creature* firstCreature;
};
struct Creature
{
pthread_t ht;
pthread_attr_t stack_att;
struct MeetingPlace* place;
int count;
int sameCount;
enum Colour colour;
int id;
BOOL two_met;
BOOL sameid;
};
void MeetingPlace_Init(struct MeetingPlace* m, int meetings )
{
pthread_mutex_init( &m->mutex, 0 );
m->meetingsLeft = meetings;
m->firstCreature = 0;
}
BOOL Meet( struct Creature* cr)
{
BOOL retval = TRUE;
struct MeetingPlace* mp = cr->place;
pthread_mutex_lock( &(mp->mutex) );
if ( mp->meetingsLeft > 0 )
{
if ( mp->firstCreature == 0 )
{
cr->two_met = FALSE;
mp->firstCreature = cr;
}
else
{
struct Creature* first;
enum Colour newColour;
first = mp->firstCreature;
newColour = doCompliment( cr->colour, first->colour );
cr->sameid = cr->id == first->id;
cr->colour = newColour;
cr->two_met = TRUE;
first->sameid = cr->sameid;
first->colour = newColour;
first->two_met = TRUE;
mp->firstCreature = 0;
mp->meetingsLeft--;
}
}
else
retval = FALSE;
pthread_mutex_unlock( &(mp->mutex) );
return retval;
}
void* CreatureThreadRun(void* param)
{
struct Creature* cr = (struct Creature*)param;
while (TRUE)
{
if ( Meet(cr) )
{
while (cr->two_met == FALSE)
sched_yield();
if (cr->sameid)
cr->sameCount++;
cr->count++;
}
else
break;
}
return 0;
}
void Creature_Init( struct Creature *cr, struct MeetingPlace* place, enum Colour colour )
{
cr->place = place;
cr->count = cr->sameCount = 0;
cr->id = ++CreatureID;
cr->colour = colour;
cr->two_met = FALSE;
pthread_attr_init( &cr->stack_att );
pthread_attr_setstacksize( &cr->stack_att, STACK_SIZE );
pthread_create( &cr->ht, &cr->stack_att, &CreatureThreadRun, (void*)(cr) );
}
char* Creature_getResult(struct Creature* cr, char* str)
{
char numstr[256];
formatNumber(cr->sameCount, numstr);
sprintf( str, "%u%s", cr->count, numstr );
return str;
}
void runGame( int n_meeting, int ncolor, const enum Colour* colours )
{
int i;
int total = 0;
char str[256];
struct MeetingPlace place;
struct Creature *creatures = (struct Creature*) calloc( ncolor, sizeof(struct Creature) );
MeetingPlace_Init( &place, n_meeting );
for (i = 0; i < ncolor; i++)
{
printf( "%s ", ColourName[ colours[i] ] );
Creature_Init( &(creatures[i]), &place, colours[i] );
}
printf("\\n");
for (i = 0; i < ncolor; i++)
pthread_join( creatures[i].ht, 0 );
for (i = 0; i < ncolor; i++)
{
printf( "%s\\n", Creature_getResult(&(creatures[i]), str) );
total += creatures[i].count;
}
printf( "%s\\n\\n", formatNumber(total, str) );
pthread_mutex_destroy( &place.mutex );
free( creatures );
}
void printColours( enum Colour c1, enum Colour c2 )
{
printf( "%s + %s -> %s\\n",
ColourName[c1],
ColourName[c2],
ColourName[doCompliment(c1, c2)] );
}
void printColoursTable(void)
{
printColours(blue, blue);
printColours(blue, red);
printColours(blue, yellow);
printColours(red, blue);
printColours(red, red);
printColours(red, yellow);
printColours(yellow, blue);
printColours(yellow, red);
printColours(yellow, yellow);
}
int main(int argc, char** argv)
{
int n = (argc == 2) ? atoi(argv[1]) : 6000000;
printColoursTable();
printf("\\n");
const enum Colour r1[] = { blue, red, yellow };
const enum Colour r2[] = { blue, red, yellow,
red, yellow, blue,
red, yellow, red, blue };
runGame( n, sizeof(r1) / sizeof(r1[0]), r1 );
runGame( n, sizeof(r2) / sizeof(r2[0]), r2 );
return 0;
}
| 0
|
#include <pthread.h>
int N ;
int D;
int P;
pthread_t *threads;
pthread_mutex_t lock;
float** a ;
float* b ;
float* x ;
double time_start, time_end;
void* do_work(void*);
main (int argc, char *argv[] ) {
if(argc != 3) {printf("wrong number of arguments") ; exit(2) ;}
N = atoi(argv[1]);
P = atoi(argv[2]);
D = sqrt(P);
pthread_mutex_init(&lock, 0);
printf("Array size = %d \\n ", N);
printf("Number of Threads = %d \\n", P);
printf("Submatrix is %d x %d \\n", D, D);
int mid = (N+1)/2;
int i, j;
a = malloc(sizeof(float*)*N);
for (i = 0; i < N; i++) {
a[i] = malloc(sizeof(float)*N);
}
b = malloc(sizeof(float)*N);
x = malloc(sizeof(float)*N);
for (i=0; i<N; i++) {
for (j=0; j<N; j++) {
if (j == i) { a[i][j] = 2.0; }
else if (j == i-1 || j == i+1) { a[i][j] = 1.0; }
else { a[i][j] = 0.01; }
}
b[i] = mid - abs(i-mid+1);
}
for(i=0; i<N; i++)
x[i] = 0.0;
threads = malloc(sizeof(pthread_t) * P);
for(i=0; i<P; i++)
pthread_create(&threads[i], 0, do_work, (void *)(long)i);
for(i=0; i<P; i++)
pthread_join(threads[i], 0);
for (i=0; i<N; i+=N/10) { printf(" %10.6f",x[i]); }
printf("\\n");
printf ("time = %lf\\n", time_end - time_start);
free(threads);
free(a);
free(b);
free(x);
}
void* do_work(void* args)
{
struct timeval tv;
struct timezone tz;
int thread_id = (int)(long)args;
int i, j;
int row = thread_id % D;
int column = thread_id / D;
gettimeofday (&tv , &tz);
time_start = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
for (i=row*(N/D); i<((row+1)*(N/D)); i++)
{
for (j=column*(N/D); j<((column+1)*(N/D)); j++)
{
pthread_mutex_lock(&lock);
x[i] += a[i][j] * b[j];
pthread_mutex_unlock(&lock);
}
}
gettimeofday (&tv , &tz);
time_end = (double)tv.tv_sec + (double)tv.tv_usec / 1000000.0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock2;
int main(int argc, char* argv[]) {
int id;
SharedMem *ptr;
id = shmget (atoi(argv[1]), 0, 0);
if (id == -1){
perror ("child shmget failed");
exit (1);
}
ptr = shmat (id, (void *) 0, 1023);
if (ptr == (void *) -1){
perror ("child shmat failed");
exit (2);
}
int file, i;
struct timeval tv;
struct timespec tim, tim2;
char Stringtime[4], writing[12];
if ((file = open("prod_black.txt", O_WRONLY)) <= -1)
exit(1);
for(i = 0; i < 1000; i++){
pthread_mutex_lock(&ptr->lock);
while (ptr->count1 == bufferSize && ptr->count2 == bufferSize)
while (pthread_cond_wait(&ptr->SpaceAvailable, &ptr->lock) != 0);
gettimeofday(&tv, 0);
sprintf(writing, "Black %d \\n", tv.tv_usec);
tim.tv_sec = 0;
tim.tv_nsec = (rand() % 101) * 100;
nanosleep(&tim, &tim2);
write(file, writing, strlen(writing));
if (ptr->count1 == bufferSize) {
strcpy (ptr->Buffer2[ptr->in2], writing);
ptr->in2 = (ptr->in2 + 1) % bufferSize;
ptr->count2++;
} else {
strcpy (ptr->Buffer1[ptr->in1], writing);
ptr->in1 = (ptr->in1 + 1) % bufferSize;
ptr->count1++;
}
writing[0] = '\\0';
pthread_mutex_unlock(&ptr->lock);
pthread_cond_signal(&ptr->ItemAvailable);
}
pthread_mutex_lock(&ptr->lock2);
ptr->end--;
pthread_mutex_unlock(&ptr->lock2);
close(file);
}
| 0
|
#include <pthread.h>
static inline void can_execute(struct userid *id, struct ext2inode *ino)
{
}
static inline void can_read(struct userid *id, struct ext2inode *ino)
{
}
static inline void can_write(struct userid *id, struct ext2inode *ino)
{
}
int check_name(char *dest, uint8_t nlen, char *src)
{
int i=0,j=0, srclen;
srclen = strlen(src);
for(i=0,j=0;i<srclen;i++,j++)
{
if(src[i] == '?')
continue;
if(src[i] == '*')
{
for(;src[i] != '.';i++)
if(src[i] == '\\0')
return 0;
for(;dest[j] != '.';j++)
if(src[j] == '\\0')
return 0;
}
if(src[i] != dest[j])
return 1;
}
if(i != nlen)
return 1;
return 0;
}
static inline uint32_t get_file_blk(struct vnode *vn)
{
struct ext2inode *in = &vn->v_ino.ext2inode;
return (in->i_blocks * 512);
}
static inline char *follow_symlink(struct vnode *parent, uint32_t inum)
{
char *path;
struct vnode *vlink;
vlink = vget(parent, inum, parent->v_rdev);
path = (char *)vlink->v_ino.ext2inode.i_block;
return path;
}
int ext2_readdir(struct vnode *parent, char *path, struct nameidata *nm)
{
uint32_t block_no, blkindex = 0, blksz;
struct ext2inode *eino = &parent->v_ino.ext2inode;
struct bcache *entry;
struct ext2dirent *dir;
struct vnode *vnode = parent;
uint32_t last_sym= 0, entrysz;
char name[EXT2_NAME_LEN];
char *pth = path;
int ret= -EINVAL , comp = 0, index = 0;
again:
do{
while(*pth == '/')
pth++;
while (*pth != '/')
{
if(*pth == '\\0')
break;
name[index] = *pth++;
index++;
}
name[index] = 0;
if((*pth == '\\0') || (*(pth + 1) == '\\0'))
comp = 1;
pthread_mutex_lock(&vnode->smlock);
do{
if(!(vnode->v_type & VNODE_DIR))
{
ret = -EINVAL;
goto err;
}
if(vnode->v_fsmounted)
{
nm->vfs = vnode->v_fsmounted;
return 1;
}
can_execute(&nm->id, eino);
block_no = ext2_bmap(vnode, blkindex);
entry = (struct bcache *)bread(vnode->v_rdev, block_no, vnode->vfsp->blk_size);
if(!entry)
return -EINTR;
dir = (struct ext2dirent *)entry->b_data;
entrysz = ((uint32_t)entry->b_data + entry->b_datasz);
while((dir->rec_len != 0))
{
if(dir->namelen > EXT2_NAME_LEN)
return (-ENAMETOOLONG);
ret = check_name(dir->name, dir->namelen, name);
if(ret == 0)
goto fileok;
dir = (struct ext2dirent *)(((uint32_t)dir)+dir->rec_len);
if((uint32_t)dir >= entrysz)
break;
}
brelse(entry);
blksz = get_file_blk(vnode);
blkindex++;
if((blkindex * vnode->vfsp->blk_size) >= blksz)
break;
}while(1);
if(comp == 1)
nm->vn = vnode;
pthread_mutex_unlock(&vnode->smlock);
return -1;
fileok:
pthread_mutex_unlock(&vnode->smlock);
vnode = vget(vnode, dir->inum, vnode->v_rdev);
if(vnode == 0)
return -1;
eino = &vnode->v_ino.ext2inode;
can_execute(&nm->id, eino);
blkindex = 0;
index = 0;
}while(comp == 0);
nm->vn = vnode;
pthread_mutex_lock(&vnode->smlock);
return 0;
err:
pthread_mutex_unlock(&vnode->smlock);
return ret;
}
| 1
|
#include <pthread.h>
double sum=0.0, a[1000000];
pthread_mutex_t sum_mutex;
void *do_work(void *tid)
{
int i, start, *mytid, end;
double mysum=0.0;
mytid = (int *) tid;
start = (*mytid * 1000000 / 4);
end = start + 1000000 / 4;
printf ("Thread %d doing iterations %d to %d\\n",*mytid,start,end-1);
for (i=start; i < end ; i++) {
a[i] = i * 1.0;
mysum = mysum + a[i];
}
pthread_mutex_lock (&sum_mutex);
sum = sum + mysum;
pthread_mutex_unlock (&sum_mutex);
pthread_exit(0);
}
int main(int argc, char *argv[])
{
int i, start, tids[4];
pthread_t threads[4];
pthread_attr_t attr;
pthread_mutex_init(&sum_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (i=0; i<4; i++) {
tids[i] = i;
pthread_create(&threads[i], &attr, do_work, (void *) &tids[i]);
}
for (i=0; i<4; i++) {
pthread_join(threads[i], 0);
}
printf ("Done. Sum= %e \\n", sum);
sum=0.0;
for (i=0;i<1000000;i++){
a[i] = i*1.0;
sum = sum + a[i]; }
printf("Check Sum= %e\\n",sum);
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&sum_mutex);
pthread_exit (0);
}
| 0
|
#include <pthread.h>
const long NUM_PHILOSOPHERS = 5;
pthread_mutex_t chopstick_mutex[5];
void* grab_chopsticks(void* rank);
int main(void)
{
long i, j;
pthread_t* threads = (pthread_t*)malloc(NUM_PHILOSOPHERS * sizeof(pthread_t));
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_mutex_init(&chopstick_mutex[i], 0);
printf("Philosopher %d is thinking.\\n", i);
}
for(j = 0; j < 10; ++j)
{
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_create(&threads[i], 0, grab_chopsticks, (void*)i);
}
for(i = 0; i < NUM_PHILOSOPHERS; ++i)
{
pthread_join(threads[i], 0);
}
}
free(threads);
return 0;
}
void* grab_chopsticks(void* rank)
{
long thread_rank = (long)rank;
pthread_mutex_lock(&chopstick_mutex[thread_rank]);
printf("Philosopher %ld picked up chopstick %ld.\\n", thread_rank, thread_rank);
sleep(10);
pthread_mutex_lock(&chopstick_mutex[(thread_rank + 1) % NUM_PHILOSOPHERS]);
printf("Philosopher %ld picked up chopstick %ld.\\n", thread_rank, (thread_rank + 1) % NUM_PHILOSOPHERS);
printf("Philosopher %ld is eating.\\n", thread_rank);
sleep(5);
pthread_mutex_unlock(&chopstick_mutex[(thread_rank + 1) % NUM_PHILOSOPHERS]);
printf("Philosopher %ld put down chopstick %ld.\\n", thread_rank, (thread_rank + 1) % NUM_PHILOSOPHERS);
pthread_mutex_unlock(&chopstick_mutex[thread_rank]);
printf("Philosopher %ld put down chopstick %ld.\\n", thread_rank, thread_rank);
printf("Philosopher %ld is thinking.\\n", thread_rank);
}
| 1
|
#include <pthread.h>
char user_input;
int user_move = -1;
pthread_mutex_t mutex;
pthread_t thr_read, thr_right, thr_left, thr_quit;
void err_msg(int err_type, const char* string)
{
printf("%s with a error code of: %d\\n", string, err_type);
}
void* user_go_left(void *args){
if(user_input == 'a') {
printf("%s\\n", "i guess you enter a");
user_move = 0;
}
pthread_exit((void*)0);
}
void* user_go_right(void* args){
if(user_input == 'd'){
printf("%s\\n", "i guess you enter d");
user_move = 1;
}
pthread_exit((void*)0);
}
void* user_quits(void *args){
if(user_input == 'q')
printf("%s\\n", "i guess you enter q");
user_move = 2;
pthread_exit((void*)0);
}
void* read_user_input(void *args){
int err;
while((user_input = getchar())){
pthread_mutex_lock(&mutex);
if (user_input == 'q') {
err = pthread_create(&thr_quit, 0, user_quits, 0);
if (err) err_msg(err, "Couldn't not create Thread");
err = pthread_join(thr_quit, 0);
if (err) err_msg(err, "Couldn't not join Thread");
pthread_exit((void*)0);
} else if(user_input == 'a') {
err = pthread_create(&thr_left, 0, user_go_left, 0);
if (err) err_msg(err, "Couldn't not create Thread");
err = pthread_join(thr_left, 0);
if (err) err_msg(err, "Couldn't not join Thread");
} else if(user_input == 'd') {
err = pthread_create(&thr_right, 0, user_go_right, 0);
if (err) err_msg(err, "Couldn't not create Thread");
err = pthread_join(thr_right, 0);
if (err) err_msg(err, "Couldn't not join Thread");
}
pthread_mutex_unlock(&mutex);
}
pthread_exit((void*)0);
}
int main(int argc, char const *argv[]) {
int quit;
int err;
pthread_mutex_init(&mutex, 0);
err = pthread_create(&thr_read, 0, read_user_input, 0);
if(err) if (err) err_msg(err, "Couldn't not create Thread");
while(!quit){
if (user_move == 2) {
quit = 1;
}
}
printf("%s\\n", "bye");
pthread_join(thr_read, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
enum {
KEY_OK,
KEY_FAIL,
DATA_OK,
DATA_FAIL
};
struct server_answ {
unsigned code;
};
struct login_data {
unsigned id;
char key[65];
};
struct meteo_data {
float temp;
float hum;
};
static struct {
pthread_mutex_t mutex;
struct tcp_server server;
struct database db;
} mserver;
static void exit_fail(const char *message)
{
pthread_mutex_lock(&mserver.mutex);
printf("%s\\n", "FAIL!");
log_local(message, LOG_ERROR);
pthread_mutex_unlock(&mserver.mutex);
}
static void new_session(struct tcp_client *s_client, void *data)
{
struct login_data ldata;
struct meteo_data mdata;
struct server_answ answ;
pthread_mutex_lock(&mserver.mutex);
puts("New client connected.");
printf("%s", "Client login...");
pthread_mutex_unlock(&mserver.mutex);
if (!tcp_client_recv(s_client, (void *)&ldata, sizeof(ldata))) {
exit_fail("Fail receiving key data.");
return;
}
struct database_cfg *db = configs_get_database();
if (!database_connect(&mserver.db, db->ip, db->user, db->passwd, db->base)) {
pthread_mutex_lock(&mserver.mutex);
log_local("Fail connecting to database.", LOG_ERROR);
pthread_mutex_unlock(&mserver.mutex);
return;
}
if (!database_check_user(&mserver.db, ldata.id, ldata.key)) {
char msg[255];
char num[20];
sprintf(num, "%u", ldata.id);
strcpy(msg, "Fail user authentication. ID: ");
strcat(msg, num);
pthread_mutex_lock(&mserver.mutex);
log_local(msg, LOG_ERROR);
pthread_mutex_unlock(&mserver.mutex);
answ.code = KEY_FAIL;
}
answ.code = KEY_OK;
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(answ))) {
exit_fail("Fail sending key checking answare.");
database_close(&mserver.db);
return;
}
if (answ.code != KEY_OK) {
char msg[255];
char id[9];
sprintf(msg, "%u", ldata.id);
strcpy(msg, "Fail client authentication. ID:");
strcat(msg, id);
exit_fail(msg);
database_close(&mserver.db);
return;
}
pthread_mutex_lock(&mserver.mutex);
printf("%s\\n", "OK.");
pthread_mutex_unlock(&mserver.mutex);
printf("%s", "Receiving meteo data...");
if (!tcp_client_recv(s_client, (void *)&mdata, sizeof(mdata))) {
exit_fail("Fail receiving meteo answare.");
answ.code = DATA_FAIL;
database_close(&mserver.db);
return;
}
answ.code = DATA_OK;
if (!tcp_client_send(s_client, (const void *)&answ, sizeof(answ))) {
exit_fail("Fail sending meteo answare.");
database_close(&mserver.db);
return;
}
if (answ.code != DATA_OK) {
exit_fail("Fail meteo data.");
database_close(&mserver.db);
return;
}
pthread_mutex_lock(&mserver.mutex);
printf("%s\\n", "OK.");
puts("================================");
printf("ID: %u\\n", ldata.id);
printf("Temp: %.2f Hum: %.2f\\n", mdata.temp, mdata.hum);
puts("================================");
pthread_mutex_unlock(&mserver.mutex);
if (!database_add_meteo(&mserver.db, ldata.id, mdata.temp, mdata.hum)) {
pthread_mutex_lock(&mserver.mutex);
log_local("Fail adding meteo data to database.", LOG_ERROR);
pthread_mutex_unlock(&mserver.mutex);
}
database_close(&mserver.db);
}
bool meteo_server_start()
{
struct server_cfg *sc = configs_get_server();
puts("Starting server...");
pthread_mutex_init(&mserver.mutex, 0);
tcp_server_set_newsession_cb(&mserver.server, new_session, 0);
if (!tcp_server_bind(&mserver.server, sc->port, sc->max_users)) {
log_local("Fail binding tcp server.", LOG_ERROR);
return 0;
}
pthread_mutex_destroy(&mserver.mutex);
return 1;
}
| 1
|
#include <pthread.h>
int g_num;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_cond = PTHREAD_COND_INITIALIZER;
void* thread_add(void *param)
{
sleep(1);
for (;;) {
pthread_mutex_lock(&g_mutex);
printf("thread 1 lock,");
g_num++;
printf("add num: %d,", g_num);
pthread_cond_signal(&g_cond);
pthread_mutex_unlock(&g_mutex);
printf("thread 1 unlock\\n");
sleep(1);
}
}
void* thread_sub(void *param)
{
for (;;) {
pthread_mutex_lock(&g_mutex);
printf("thread 2 lock,");
pthread_cond_wait(&g_cond, &g_mutex);
printf("cond waited,");
g_num--;
printf("sub num: %d,", g_num);
pthread_mutex_unlock(&g_mutex);
printf("thread 2 unlock\\n\\n");
sleep(1);
}
}
int main(int argc, char **argv)
{
pthread_t thread1, thread2;
g_num = 0;
if (pthread_create(&thread1, 0, thread_add, (void*)0) < 0) {
perror("thread 1 error\\n");
exit(1);
}
if (pthread_create(&thread2, 0, thread_sub, (void*)0) < 0) {
perror("thread 2 error\\n");
exit(1);
}
for (;;) {
sleep(10);
}
return 0;
}
| 0
|
#include <pthread.h>
void UpdateAttitude( );
void ReadAttitude( );
static void ( *ThreadFunctions[ NUM_THREADS ] ) =
{ UpdateAttitude,
ReadAttitude };
int main( int argc, char** argv )
{
pthread_t threads[ NUM_THREADS ];
int thread_args[ NUM_THREADS ];
int result_code;
unsigned index;
char log[10] = "[ MAIN ]";
attitude.valid = 0;
for( index = 0; index < NUM_THREADS; ++index )
{
thread_args[ index ] = index;
printf("%s creating thread %d\\n", log_time(log),index);
result_code = pthread_create( &threads[ index ],
0,
ThreadFunctions[ index ],
&thread_args[index] );
assert( !result_code );
}
for( index = 0; index < NUM_THREADS; ++index )
{
result_code = pthread_join( threads[ index ], 0 );
assert( !result_code );
printf( "%s thread %d has completed\\n", log_time(log),index );
}
printf( "%s All threads completed successfully\\n",log_time(log) );
exit( 0 );
}
void UpdateAttitude( void* argument )
{
char log[10] = "[UPDATE]";
while( 1 )
{
printf( "%s Waiting for lock.\\n",log_time(log) );
pthread_mutex_lock( &attitudeMut );
printf( "%s Lock obtained.\\n",log_time(log) );
printf( "%s Attitude data is being updated\\n",log_time(log) );
sleep( 14 );
clock_gettime( CLOCK_REALTIME, &attitude.sampleTime );
srand( ( unsigned ) attitude.sampleTime.tv_nsec );
attitude.x = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.y = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.z = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.acceleration = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.roll = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.pitch = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.yaw = rand( ) + ( ( double ) rand( ) / ( double ) 32767 );
attitude.valid = 1;
printf( "%s Update complete.\\n",log_time(log) );
printf( "%s Releasing lock.\\n",log_time(log) );
pthread_mutex_unlock( &attitudeMut );
sleep( 1 );
}
}
void ReadAttitude( )
{
char log[10] = "[READER]";
struct timespec currentTimeSpec;
struct tm *currentTime;
struct tm *attitude_timestamp;
struct timespec timeout;
timeout.tv_sec = 10;
timeout.tv_nsec = 0;
while( 1 )
{
printf( "%s Waiting for lock.\\n",log_time(log) );
clock_gettime( CLOCK_REALTIME, &timeout );
timeout.tv_sec += 10;
if( pthread_mutex_timedlock( &attitudeMut, &timeout ) != 0 ) {
clock_gettime( CLOCK_REALTIME, ¤tTimeSpec );
currentTime = localtime( ¤tTimeSpec );
printf( "%s No new data at time %02d:%02d:%02d\\n", log_time(log),
currentTime->tm_hour, currentTime->tm_min, currentTime->tm_sec );
}else{
printf( "%s Lock obtained.\\n",log_time(log) );
if( attitude.valid ) {
attitude_timestamp = localtime( &attitude.sampleTime );
printf( "%s Data valid\\n",log_time(log) );
printf( "%s Reading Attitude data\\n",log_time(log) );
printf( "%s Attitude data:\\n"
"\\t\\t\\t\\ttimestamp = %02d:%02d:%02d.%lu\\n"
"\\t\\t\\t\\tx = %lf\\n"
"\\t\\t\\t\\ty = %lf\\n"
"\\t\\t\\t\\tz = %lf\\n"
"\\t\\t\\t\\tacceleration = %lf\\n"
"\\t\\t\\t\\troll = %lf\\n"
"\\t\\t\\t\\tpitch = %lf\\n"
"\\t\\t\\t\\tyaw = %lf\\n",
log_time(log),
attitude_timestamp->tm_hour,
attitude_timestamp->tm_min,
attitude_timestamp->tm_sec,
attitude.sampleTime.tv_nsec,
attitude.x,
attitude.y,
attitude.z,
attitude.acceleration,
attitude.roll,
attitude.pitch,
attitude.yaw
);
}else{
printf( "%s Data not valid\\n",log_time(log) );
}
printf( "%s Releasing lock.\\n",log_time(log) );
pthread_mutex_unlock( &attitudeMut );
sleep( 1 );
}
}
}
| 1
|
#include <pthread.h>
int event_filter(const struct inotify_event *event)
{
int n = 0;
if ((event->mask) & IN_IGNORED)
n = 1;
if (!((event->mask) & IN_ISDIR) && ((event->mask) & IN_CREATE))
n = 1;
if (strchr((event->name), '.') == (event->name))
n = 1;
if (strchr((event->name), '~') == ((event->name) +
strlen(event->name) - 1))
n = 1;
if (strcmp((event->name), "4913") == 0)
n = 1;
return n;
}
void add_watch_for_new_dir(const struct inotify_event *event)
{
struct watch_entry *watch = search_watch_in_watch_list(start_watch_list,
event->wd);
char* parent_loc = watch->loc;
char* dir_path = calloc(strlen(parent_loc) + (event->len) + 1,
sizeof(char));
strcpy(dir_path, parent_loc);
strcat(dir_path, "/");
strcat(dir_path, event->name);
int mode = IN_CREATE | IN_DELETE | IN_CLOSE_WRITE | IN_MOVE;
int w = inotify_add_watch(inotify_instance, dir_path, mode);
struct watch_entry *new_watch = create_watch_entry(dir_path, w);
pthread_mutex_lock(&mutex_watch);
add_watch_entry_to_list(&start_watch_list, new_watch);
pthread_mutex_unlock(&mutex_watch);
free(dir_path);
}
void* monitor_file_system_thread(void* arg)
{
analyse_dir_to_monitor("/home/kevin/Projekte/Legion/TestEnv");
char buf[4096]
;
const struct inotify_event *event;
ssize_t len;
char *ptr;
int changes = 0;
while(1) {
len = read(inotify_instance, buf, sizeof(buf));
if (len <= 0) {
sd_journal_print(LOG_ERR, "couldn't read event!\\n");
exit(1);
}
for (ptr = buf; ptr < buf + len;
ptr += sizeof(struct inotify_event) + event->len) {
event = (const struct inotify_event *) ptr;
if (event_filter(event) == 1)
continue;
if((event->mask & IN_ISDIR) &&
(event->mask & IN_CREATE)) {
add_watch_for_new_dir(event);
}
add_event_to_list(&curr_event_list, event);
changes = 1;
}
if((changes != 0)) {
pthread_cond_signal(&cond_mutex_2);
changes = 0;
}
}
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.