text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
int students = 0;
int inRoom = 0;
int capacity = 0;
int globalID = 0;
int pflag = 0;
pthread_mutex_t roomlock, capslock, idlock, proflock;
pthread_cond_t profcond;
void QuestionDone();
void QuestionStart();
void AnswerStart();
void AnswerDone();
void LeaveOffice();
void EnterOffice();
void * profthread()
{
while(students > 0)
{
pthread_cond_wait(&profcond, &proflock);
AnswerStart(globalID);
AnswerDone(globalID);
pthread_cond_init(&profcond, 0);
if(students == 0)
exit(0);
}
}
void *professor()
{
pthread_t prof;
pthread_mutex_init(&roomlock, 0);
pthread_mutex_init(&capslock, 0);
pthread_mutex_init(&idlock, 0);
pthread_mutex_init(&proflock, 0);
pthread_cond_init(&profcond, 0);
if(pthread_create(&prof, 0, profthread, 0) != 0)
{
perror("Failed to create thread");
exit(0);
}
}
void *sthread(void * id)
{
int able = 0;
int questions = numQuestions((int) id);
while(!able)
{
pthread_mutex_lock(&roomlock);
if(inRoom < capacity){able = 1;}
else pthread_mutex_unlock(&roomlock);
}
while(able){
inRoom++;
globalID = (int) id;
EnterOffice();
pthread_mutex_unlock(&roomlock);
break;
}
while(questions>0 && able)
{
pthread_mutex_lock(&idlock);
globalID = (int) id;
QuestionStart();
pthread_cond_signal(&profcond);
usleep(1);
QuestionDone();
questions--;
pthread_mutex_unlock(&idlock);
usleep(10);
}
while(questions == 0 && able)
{
pthread_mutex_lock(&capslock);
globalID = (int) id;
LeaveOffice();
students--;
inRoom--;
pthread_mutex_unlock(&capslock);
break;
}
}
int numQuestions(int id)
{
return id % 4 + 1;
}
void *Student(int amount_of_students, int cap)
{
capacity = cap;
students = amount_of_students;
pthread_t student_threads [amount_of_students];
int i;
for(i = 0; i < amount_of_students; i++)
{
if(pthread_create(&student_threads[i], 0, sthread, (void *) i) != 0)
{
perror("Failed to create thread");
exit(0);
}
}
}
void AnswerStart(int id)
{
printf("Professor starts to answer the question for student %d\\n",
globalID);
}
void AnswerDone(int id)
{
printf("Professor is done with answer for student %d\\n", globalID);
}
void EnterOffice()
{
printf("Student %d shows up in the office\\n" , globalID);
}
void LeaveOffice()
{
printf("Student %d leaves the office\\n", globalID);
}
void QuestionStart()
{
printf("Student %d asks a question\\n", globalID);
}
void QuestionDone()
{
printf("Student %d is satisfied\\n", globalID);
}
int main(int argc, char *argv[])
{
if((argc != 3) || atoi(argv[1]) < 1 || atoi(argv[2]) < 1)
{
printf("Must have 3 arguments and have an integer argument for 2nd and 3rd arguments\\n");
return -1;
}
else
{
Student(atoi(argv[1]), atoi(argv[2]));
professor();
pthread_exit(0);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER ;
pthread_t pth1,pth2;
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;
int count=0;
void * even()
{
while(1)
{
pthread_mutex_lock(&lock);
if(count % 2 == 0)
{
printf("count %d\\n",count);
count++;
pthread_cond_signal(&cond);
}
else
{
pthread_cond_wait(&cond,&lock);
}
pthread_mutex_unlock(&lock);
if(count >= 100) return 0;
}
}
void * odd()
{
while(1)
{
pthread_mutex_lock(&lock);
if(count % 2 == 1)
{
printf("count %d\\n",count);
count++;
pthread_cond_signal(&cond);
}
else
{
pthread_cond_wait(&cond,&lock);
}
pthread_mutex_unlock(&lock);
if(count >= 100) return 0;
}
}
int main()
{
printf("Started\\n");
pthread_create(&pth1,0,&even,0);
pthread_create(&pth2,0,&even,0);
pthread_join(pth2,0);
return 0;
}
| 0
|
#include <pthread.h>
int memory[(2*320+1)];
int next_alloc_idx = 1;
pthread_mutex_t m;
int top;
int index_malloc(){
int curr_alloc_idx = -1;
pthread_mutex_lock(&m);
if(next_alloc_idx+2-1 > (2*320+1)){
pthread_mutex_unlock(&m);
curr_alloc_idx = 0;
}else{
curr_alloc_idx = next_alloc_idx;
next_alloc_idx += 2;
pthread_mutex_unlock(&m);
}
return curr_alloc_idx;
}
void EBStack_init(){
top = 0;
}
int isEmpty() {
if(top == 0)
return 1;
else
return 0;
}
int push(int d) {
int oldTop = -1, newTop = -1, casret = -1;
newTop = index_malloc();
if(newTop == 0){
return 0;
}else{
memory[newTop+0] = d;
while (1) {
oldTop = top;
memory[newTop+1] = oldTop;
if(__sync_bool_compare_and_swap(&top,oldTop,newTop)){
return 1;
}
}
}
}
void __VERIFIER_atomic_assert(int r)
{
__atomic_begin();
assert(!(!r || !isEmpty()));
__atomic_end();
}
void push_loop(){
int r = -1;
int arg = __nondet_int();
while(1){
r = push(arg);
__VERIFIER_atomic_assert(r);
}
}
pthread_mutex_t m2;
int state = 0;
void* thr1(void* arg)
{
pthread_mutex_lock(&m2);
switch(state)
{
case 0:
EBStack_init();
state = 1;
case 1:
pthread_mutex_unlock(&m2);
push_loop();
break;
}
return 0;
}
int main()
{
pthread_t t1,t2;
pthread_create(&t1, 0, thr1, 0);
pthread_create(&t2, 0, thr1, 0);
return 0;
}
| 1
|
#include <pthread.h>
char *smackfs_mnt = 0;
int smackfs_mnt_dirfd = -1;
static pthread_mutex_t smackfs_mnt_lock = PTHREAD_MUTEX_INITIALIZER;
static int verify_smackfs_mnt(const char *mnt);
static int smackfs_exists(void);
int init_smackfs_mnt(void)
{
char *buf = 0;
char *startp;
char *endp;
FILE *fp = 0;
size_t len;
ssize_t num;
int ret = 0;
if (smackfs_mnt ||
verify_smackfs_mnt("/sys/fs/smackfs/") == 0 ||
verify_smackfs_mnt("/smack") == 0)
return 0;
if (!smackfs_exists())
return -1;
fp = fopen("/proc/mounts", "r");
if (!fp)
return -1;
__fsetlocking(fp, FSETLOCKING_BYCALLER);
while ((num = getline(&buf, &len, fp)) != -1) {
startp = strchr(buf, ' ');
if (!startp) {
ret = -1;
break;
}
startp++;
endp = strchr(startp, ' ');
if (!endp) {
ret = -1;
break;
}
if (!strncmp(endp + 1, "smackfs"" ", strlen("smackfs") + 1)) {
*endp = '\\0';
ret = verify_smackfs_mnt(startp);
break;
}
}
free(buf);
fclose(fp);
return ret;
}
static int verify_smackfs_mnt(const char *mnt)
{
struct statfs sfbuf;
int rc;
int fd;
fd = open(mnt, O_RDONLY, 0);
if (fd < 0)
return -1;
do {
rc = fstatfs(fd, &sfbuf);
} while (rc < 0 && errno == EINTR);
if (rc == 0) {
if ((uint32_t) sfbuf.f_type == (uint32_t) 0x43415d53) {
pthread_mutex_lock(&smackfs_mnt_lock);
if (smackfs_mnt_dirfd == -1) {
smackfs_mnt = strdup(mnt);
smackfs_mnt_dirfd = fd;
} else {
close(fd);
}
pthread_mutex_unlock(&smackfs_mnt_lock);
return 0;
}
}
close(fd);
return -1;
}
static int smackfs_exists(void)
{
int exists = 0;
FILE *fp = 0;
char *buf = 0;
size_t len;
ssize_t num;
fp = fopen("/proc/filesystems", "r");
if (!fp)
return 1;
__fsetlocking(fp, FSETLOCKING_BYCALLER);
num = getline(&buf, &len, fp);
while (num != -1) {
if (strstr(buf, "smackfs")) {
exists = 1;
break;
}
num = getline(&buf, &len, fp);
}
free(buf);
fclose(fp);
return exists;
}
static void fini_lib(void) ;
static void fini_lib(void)
{
if (smackfs_mnt_dirfd >= 0)
close(smackfs_mnt_dirfd);
free(smackfs_mnt);
smackfs_mnt = 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void fillBuffer(int *bufferIn, int TID, int *laststate, int *pages,
int *wrTOP, int *wrLOW, int *last, long *readIdx, int *reading)
{
int totalWritten = 0,lToken;
while(*laststate > 0 && *pages > 0 && totalWritten < FDBY_HF)
{
nextToken(readIdx, laststate, pages, wrTOP, wrLOW, last, &lToken);
if(lToken > 0)
{
lToken += (lToken << 12);
lToken ^= (lToken >> 22);
lToken += (lToken << 4);
lToken ^= (lToken >> 9);
lToken += (lToken << 10);
lToken ^= (lToken >> 2);
lToken += (lToken << 7);
lToken ^= (lToken >> 12);
pthread_mutex_lock(&lock);
bufferIn[lToken & LANG_BITS_MSK] += 1;
pthread_mutex_unlock(&lock);
}
}
if(*laststate > 0 && *pages > 0)
*reading = 1;
else
*reading = 0;
}
| 1
|
#include <pthread.h>
static int iTThreads = 9;
static int iRThreads = 1;
static int data1Value = 0;
static int data2Value = 0;
pthread_mutex_t data1Lock;
pthread_mutex_t data2Lock;
void lock(pthread_mutex_t *);
void unlock(pthread_mutex_t *);
void *funcA(void *param) {
pthread_mutex_lock(&data1Lock);
data1Value = 1;
pthread_mutex_unlock(&data1Lock);
pthread_mutex_lock(&data2Lock);
data2Value = data1Value + 1;
pthread_mutex_unlock(&data2Lock);
return 0;
}
void *funcB(void *param) {
int t1 = -1;
int t2 = -1;
pthread_mutex_lock(&data1Lock);
if (data1Value == 0) {
pthread_mutex_unlock(&data1Lock);
return 0;
}
t1 = data1Value;
pthread_mutex_unlock(&data1Lock);
pthread_mutex_lock(&data2Lock);
t2 = data2Value;
pthread_mutex_unlock(&data2Lock);
assert(t2 == (t1 + 1));
return 0;
}
int main(int argc, char *argv[]) {
int i,err;
pthread_t tPool[iTThreads];
pthread_t rPool[iRThreads];
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_create(&tPool[i], 0, &funcA, 0))) {
fprintf(stderr, "Error [%d] found creating 2stage thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_create(&rPool[i], 0, &funcB, 0))) {
fprintf(stderr, "Error [%d] found creating read thread.\\n", err);
exit(-1);
}
}
for (i = 0; i < iTThreads; i++) {
if (0 != (err = pthread_join(tPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
for (i = 0; i < iRThreads; i++) {
if (0 != (err = pthread_join(rPool[i], 0))) {
fprintf(stderr, "pthread join error: %d\\n", err);
exit(-1);
}
}
return 0;
}
void lock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_lock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_lock.\\n", err);
exit(-1);
}
}
void unlock(pthread_mutex_t *lock) {
int err;
if (0 != (err = pthread_mutex_unlock(lock))) {
fprintf(stderr, "Got error %d from pthread_mutex_unlock.\\n", err);
exit(-1);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t space_available = PTHREAD_COND_INITIALIZER;
pthread_cond_t data_available = PTHREAD_COND_INITIALIZER;
int b[10];
int size = 0;
int front = 0, rear = 0;
void add_buffer(int i) {
b[rear] = i;
rear = (rear + 1) % 10;
size++;
}
int get_buffer(){
int v;
v = b[front];
front= (front+1) % 10;
size--;
return v ;
}
void* producer(void *arg) {
int i = 0;
printf("producter starting...\\n");
while (1) {
pthread_mutex_lock(&mutex);
if (size == 10) {
pthread_cond_wait(&space_available, &mutex);
}
printf("producer adding %i...\\n", i);
add_buffer(i);
pthread_cond_signal(&data_available);
pthread_mutex_unlock(&mutex);
i = i + 1;
}
pthread_exit(0);
}
void* consumer(void *arg) {
int i,v;
printf("consumer starting...\\n");
for (i=0;i<100;i++) {
pthread_mutex_lock(&mutex);
if (size == 0) {
pthread_cond_wait(&data_available, &mutex);
}
v = get_buffer();
printf("consumer getting %i...\\n", v);
pthread_cond_signal(&space_available);
pthread_mutex_unlock(&mutex);
}
printf("consuming finishing...\\n");
pthread_exit(0);
}
int main(int argc, char* argv[]) {
pthread_t producer_thread;
pthread_t consumer_thread;
pthread_create(&consumer_thread, 0, consumer, 0);
pthread_create(&producer_thread, 0, producer, 0);
pthread_join(consumer_thread, 0);
return 0;
}
| 1
|
#include <pthread.h>
void Qaullib_Topo_LL_Add (union olsr_ip_addr *src_ip, union olsr_ip_addr *dest_ip, float lq)
{
struct qaul_topo_LL_item *new_item;
new_item = (struct qaul_topo_LL_item *)malloc(sizeof(struct qaul_topo_LL_item));
if(QAUL_DEBUG)
printf("Qaullib_Topo_LL_Add\\n");
memcpy((char *)&new_item->src_ip, src_ip, sizeof(union olsr_ip_addr));
memcpy((char *)&new_item->dest_ip, dest_ip, sizeof(union olsr_ip_addr));
new_item->lq = lq;
pthread_mutex_lock( &qaullib_mutex_topoLL );
new_item->next = qaul_topo_LL_first;
qaul_topo_LL_first = new_item;
pthread_mutex_unlock( &qaullib_mutex_topoLL );
}
void Qaullib_Topo_LL_Delete_Item ()
{
struct qaul_topo_LL_item *item;
if(QAUL_DEBUG)
printf("Qaullib_Topo_LL_Delete_Item\\n");
pthread_mutex_lock( &qaullib_mutex_topoLL );
item = qaul_topo_LL_first;
qaul_topo_LL_first = item->next;
pthread_mutex_unlock( &qaullib_mutex_topoLL );
free(item);
}
| 0
|
#include <pthread.h>
int bb_buf[2];
int count=0;
int in, out;
int waiting;
pthread_mutex_t bbmutex;
pthread_cond_t bbcond;
pthread_barrier_t pbarrier;
void bb_init()
{
int i;
pthread_mutex_init(&bbmutex, 0);
pthread_cond_init(&bbcond, 0);
in=0;
out=0;
waiting=0;
for(i=0;i<=2 -1;i++){
bb_buf[i]=0;
}
}
int bb_get()
{
pthread_mutex_lock(&bbmutex);
int val;
while(1){
if(count==0)
{
pthread_cond_wait(&bbcond,&bbmutex);
}else{
val=bb_buf[out];
out=(out+1)%2;
count--;
pthread_cond_signal(&bbcond);
break;
}
}
pthread_mutex_unlock(&bbmutex);
return val;
}
void bb_put(int val)
{
pthread_mutex_lock(&bbmutex);
while(1){
if(count>=2)
{
pthread_cond_wait(&bbcond,&bbmutex);
}else{
bb_buf[in]=val;
count++;
in=(in+1)%2;
pthread_cond_signal(&bbcond);
break;
}
}
pthread_mutex_unlock(&bbmutex);
}
void *producer(void *arg)
{
int ret = 0;
int i;
pthread_barrier_wait(&pbarrier);
for(i=0;i<(5*3)/5;i++){
bb_put(i);
}
pthread_exit(&ret);
return 0;
}
void *consumer(void *arg)
{
int ret = 0;
int i;
int val;
pthread_barrier_wait(&pbarrier);
for(i=0;i<3;i++){
val = bb_get();
printf("bb_get=()=%d\\n", val);
}
pthread_exit(&ret);
return 0;
}
int main()
{
int i,cc,cc2;
cc=0;
cc2=0;
pthread_t pth[5 +5];
void *retval;
bb_init();
pthread_barrier_init(&pbarrier, 0, 5 +5);
for(i=0;i<5;i++){
cc = pthread_create(&pth[i], 0, producer, 0);
if(cc != 0){
perror("producer error");
return -1;
}
}
for(i=0;i<5;i++){
cc2 = pthread_create(&pth[i], 0, consumer, 0);
if(cc2 !=0){
perror("comsumer error");
return -1;
}
}
for(i=0;i<(5 +5);i++){
pthread_join(pth[i], &retval);
pthread_detach(pth[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex, mutex2, w_or_r;
int writer_is_waiting = 0;
int reader_count = 0;
int flag_sigint = 0;
pthread_cond_t cond;
void writer() {
pthread_mutex_lock(&mutex2);
writer_is_waiting = 1;
pthread_mutex_unlock(&mutex2);
pthread_mutex_lock(&w_or_r);
printf("This is a writing task.\\n");
pthread_mutex_unlock(&w_or_r);
pthread_mutex_lock(&mutex2);
writer_is_waiting = 0;
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex2);
}
void reader(int no_starvation) {
pthread_mutex_lock(&mutex2);
if (no_starvation && writer_is_waiting) pthread_cond_wait(&cond, &mutex2);
pthread_mutex_unlock(&mutex2);
pthread_mutex_lock(&mutex);
reader_count++;
if (reader_count == 1) pthread_mutex_lock(&w_or_r);
pthread_mutex_unlock(&mutex);
sleep(1);
pthread_mutex_lock(&mutex);
reader_count--;
if (reader_count == 0) pthread_mutex_unlock(&w_or_r);
pthread_mutex_unlock(&mutex);
}
void *thread(void *arg) {
while (!flag_sigint) reader(*(int *)arg);
return 0;
}
handler_t *Signal(int signum, handler_t *handler) {
struct sigaction action, old_action;
action.sa_handler = handler;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_RESTART;
if (sigaction(signum, &action, &old_action) < 0)
printf("Signal: error.\\n");
return (old_action.sa_handler);
}
void sigtstp_handler(int sig) {
writer();
}
void sigint_handler(int sig) {
pthread_mutex_lock(&mutex2);
flag_sigint = 1;
pthread_mutex_unlock(&mutex2);
exit(0);
}
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("usage: writer_and_reader NUM_TASKS no_starvation\\n");
exit(0);
}
pthread_mutex_init(&mutex, 0);
pthread_mutex_init(&mutex2, 0);
pthread_mutex_init(&w_or_r, 0);
pthread_cond_init(&cond, 0);
Signal(SIGTSTP, sigtstp_handler);
Signal(SIGINT, sigint_handler);
const int NUM_TASKS = atoi(argv[1]);
int no_starvation = atoi(argv[2]);
pthread_t tids[NUM_TASKS];
for (int i = 0; i < NUM_TASKS; i++) {
int ret = pthread_create(&tids[i], 0, &thread, (void *)&no_starvation);
if (ret) {
printf("pthread_create: error.\\n");
return ret;
};
}
while (!flag_sigint) {
printf("%d reads are running.\\n", reader_count);
usleep(0.4 * 1000 * 1000);
}
for (int i = 0; i < NUM_TASKS; i++)
pthread_join(tids[i], 0);
}
| 0
|
#include <pthread.h>
void * serverthread(void * parm);
void sendFile(int sock, char *filename);
pthread_mutex_t mut;
int visits = 0;
int main (int argc, char *argv[])
{
struct protoent *ptrp;
struct sockaddr_in sad;
struct sockaddr_in cad;
int sd, sd2;
int port;
unsigned int alen;
pthread_t tid;
pthread_mutex_init(&mut, 0);
memset((char *)&sad,0,sizeof(sad));
sad.sin_family = AF_INET;
sad.sin_addr.s_addr = INADDR_ANY;
if (argc > 1) {
port = atoi (argv[1]);
} else {
port = 1999;
}
if (port > 0)
sad.sin_port = htons((u_short)port);
else {
fprintf (stderr, "bad port number %s/n",argv[1]);
exit (1);
}
if ( ((ptrp = getprotobyname("tcp"))) == 0) {
fprintf(stderr, "cannot map \\"tcp\\" to protocol number");
exit (1);
}
sd = socket (PF_INET, SOCK_STREAM, ptrp->p_proto);
if (sd < 0) {
fprintf(stderr, "socket creation failed\\n");
exit(1);
}
if (bind(sd, (struct sockaddr *)&sad, sizeof (sad)) < 0) {
fprintf(stderr,"bind failed\\n");
exit(1);
}
if (listen(sd, 6) < 0) {
fprintf(stderr,"listen failed\\n");
exit(1);
}
alen = sizeof(cad);
fprintf( stderr, "Server up and running.\\n");
while (1) {
printf("SERVER: Waiting for contact ...\\n");
if ( (sd2=accept(sd, (struct sockaddr *)&cad, &alen)) < 0) {
fprintf(stderr, "accept failed\\n");
exit (1);
}
pthread_create(&tid, 0, serverthread, (void *) &sd2 );
}
close(sd);
}
void * serverthread(void * psock)
{
int tvisits;
int sock = *((int *) psock);
ssize_t numBytes = 0;
char buf[1280000];
numBytes = recv(sock, buf, 1280000 - 1, 0);
if(numBytes <= 0) {
printf("Number of bytes in response is less than or equal to zero\\n");
exit(1);
}
buf[numBytes] = '\\0';
sendFile(sock, buf);
pthread_mutex_lock(&mut);
tvisits = ++visits;
pthread_mutex_unlock(&mut);
sprintf(buf,"This server has been contacted %d time%s\\n",
tvisits, tvisits==1?".":"s.");
printf("SERVER thread: %s", buf);
close(sock);
pthread_exit(0);
}
void sendFile(int sock, char *filename) {
fprintf(stderr, "The requested file is %s\\n", filename);
FILE *fp = fopen(filename, "r");
if (fp == 0) {
fprintf(stderr, "Cannot send back a file because it does not exist\\n");
return;
}
fseek(fp, 0, 2);
long fpSize = ftell(fp);
fprintf(stderr, "The size of the file is %ld\\n", fpSize);
rewind(fp);
char *fileBytes;
fileBytes = (char *) malloc(fpSize + 1);
uint64_t fileSize = htonl(fpSize);
send(sock, &fileSize, sizeof(uint64_t), 0);
fread(fileBytes, fpSize, 1, fp);
int sent = send(sock, fileBytes, fpSize, 0);
fprintf(stderr, "But it only sent %d bytes \\n", sent);
fclose(fp);
return;
}
| 1
|
#include <pthread.h>
struct timespec ts_checkAt;
void check_in() {
clock_gettime(CLOCK_REALTIME, &ts_checkAt);
}
long check_out() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
long nGap = ( ts.tv_sec - ts_checkAt.tv_sec ) * 1000000000 + ( ts.tv_nsec - ts_checkAt.tv_nsec );
printf("Time elapsed %8ld us\\n", nGap / 1000 );
return nGap;
}
int main(void) {
const int TEST_COUNT = 10000;
int counter;
sem_t sem;
sem_init(&sem, 0, 1);
counter = TEST_COUNT;
long elapse_wait = 0;
long elapse_post = 0;
while(--counter) {
check_in();
sem_wait(&sem);
elapse_wait += check_out();
usleep(100);
check_in();
sem_post(&sem);
elapse_post += check_out();
}
sem_destroy(&sem);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
counter = TEST_COUNT;
long elapse_lock = 0;
long elapse_unlock = 0;
while(--counter) {
check_in();
pthread_mutex_lock(&mutex);
elapse_lock += check_out();
usleep(100);
check_in();
pthread_mutex_unlock(&mutex);
elapse_unlock += check_out();
}
printf("WAIT : %ld\\nPOST : %ld\\nLOCK : %ld\\nUNLOCK : %ld\\n",
elapse_wait, elapse_post, elapse_lock, elapse_unlock);
}
| 0
|
#include <pthread.h>
int a;
int *b;
}Dong;
pthread_mutex_t mutex;
void func(Dong *i){
for(int j = 0; j < 20; ++j){
pthread_mutex_lock(&mutex);
++i->a;
++*i->b;
printf("%d %d\\n", i->a, *i->b);
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
pthread_mutexattr_t mutex_shared_attr;
pthread_mutexattr_init(&mutex_shared_attr);
pthread_mutexattr_setpshared(&mutex_shared_attr,PTHREAD_PROCESS_SHARED);
if( pthread_mutex_init(&mutex, &mutex_shared_attr) != 0 ) {
printf("error pthread_mutex_init\\n");
return 0;
}
Dong *i = (Dong *)mmap(0,sizeof(Dong),PROT_READ|PROT_WRITE,
MAP_SHARED|MAP_ANONYMOUS,-1,0);
i->b = (int *)malloc(sizeof(int));
pid_t pid;
pid=fork();
if(pid==-1) {
printf("fork error");
return 1;
}
else if(0==pid){
func(i);
}
else{
func(i);
}
pthread_mutex_destroy( &mutex );
return 0;
}
| 1
|
#include <pthread.h>
void * handle_clnt(void * arg);
void error_handling(char *buf);
char buf[100];
pthread_mutex_t mutx;
int main(int argc, char *argv[])
{
int serv_sock, clnt_sock;
struct sockaddr_in serv_adr, clnt_adr;
int clnt_adr_sz;
pthread_t t_id;
if(argc!=2) {
printf("Usage : %s <port>\\n", argv[0]);
exit(1);
}
pthread_mutex_init(&mutx, 0);
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
memset(&serv_adr, 0, sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_adr, sizeof(serv_adr))==-1)
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
while(1)
{
clnt_adr_sz=sizeof(clnt_adr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_adr,&clnt_adr_sz);
pthread_create(&t_id, 0, handle_clnt, (void*)&clnt_sock);
pthread_detach(t_id);
printf("Connected client IP: %s \\n", inet_ntoa(clnt_adr.sin_addr));
}
close(serv_sock);
return 0;
}
void * handle_clnt(void * arg)
{
int clnt_sock=*((int*)arg);
int str_len=0;
while(1)
{
pthread_mutex_lock(&mutx);
str_len=read(clnt_sock, buf, sizeof(buf));
if(str_len<=0)
break;
else
write(clnt_sock, buf, str_len);
pthread_mutex_unlock(&mutx);
}
close(clnt_sock);
return 0;
}
void error_handling(char *buf)
{
fputs(buf, stderr);
fputc('\\n', stderr);
exit(1);
}
| 0
|
#include <pthread.h>
int (*blkin_init_new_trace)(struct blkin_trace *new_trace, char *name,
struct blkin_endpoint *endpoint);
int (*blkin_init_child)(struct blkin_trace *child, struct blkin_trace *parent,
struct blkin_endpoint *endpoint, char *child_name);
int (*blkin_init_child_info)(struct blkin_trace *child,
struct blkin_trace_info *info, struct blkin_endpoint *endpoint,
char *child_name);
int (*blkin_init_endpoint)(struct blkin_endpoint * endp, char *ip,
int port, char *name);
int (*blkin_init_string_annotation)(struct blkin_annotation *annotation,
char *key, char *val, struct blkin_endpoint * endpoint);
int (*blkin_init_timestamp_annotation)(struct blkin_annotation *annot,
char *event, struct blkin_endpoint * endpoint);
int (*blkin_record)(struct blkin_trace *trace,
struct blkin_annotation *annotation);
int (*blkin_get_trace_info)(struct blkin_trace *trace,
struct blkin_trace_info *info);
int (*blkin_set_trace_info)(struct blkin_trace *trace,
struct blkin_trace_info *info);
int (*blkin_pack_trace_info)(struct blkin_trace_info *info,
struct blkin_trace_info_packed *pinfo);
int (*blkin_unpack_trace_info)(struct blkin_trace_info_packed *pinfo,
struct blkin_trace_info *info);
static int resolve_symbols()
{
void *handle;
char *error;
handle = dlopen("libzipkin-c.so", RTLD_LAZY);
if (!handle) {
fprintf(stderr, "%s\\n", dlerror());
return -ENOENT;
}
dlerror();
*(void **) (&blkin_init_new_trace) = dlsym(handle, "_blkin_init_new_trace");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_init_child) = dlsym(handle, "_blkin_init_child");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_init_child_info) = dlsym(handle, "_blkin_init_child_info");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_init_endpoint) = dlsym(handle, "_blkin_init_endpoint");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_init_string_annotation) = dlsym(handle, "_blkin_init_string_annotation");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_init_timestamp_annotation) = dlsym(handle, "_blkin_init_timestamp_annotation");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_record) = dlsym(handle, "_blkin_record");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_set_trace_info) = dlsym(handle, "_blkin_set_trace_info");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_get_trace_info) = dlsym(handle, "_blkin_get_trace_info");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_pack_trace_info) = dlsym(handle, "_blkin_pack_trace_info");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
*(void **) (&blkin_unpack_trace_info) = dlsym(handle, "_blkin_unpack_trace_info");
if ((error = dlerror()) != 0) {
fprintf(stderr, "%s\\n", error);
return -ENXIO;
}
return 0;
}
static pthread_mutex_t blkin_init_mutex = PTHREAD_MUTEX_INITIALIZER;
static int initialized = 0;
int blkin_init(void)
{
int inf, seed;
inf = open("/dev/urandom", O_RDONLY);
read(inf, &seed, sizeof(int));
srand(seed);
int ret;
pthread_mutex_lock(&blkin_init_mutex);
if (!initialized) {
ret = resolve_symbols();
if (ret >= 0) {
initialized = 1;
}
}
pthread_mutex_unlock(&blkin_init_mutex);
return ret;
}
| 1
|
#include <pthread.h>
int nitems;
struct {
pthread_mutex_t mutex;
int buff[10000000];
int nput;
int nval;
} shared={
PTHREAD_MUTEX_INITIALIZER
};
struct{
pthread_mutex_t mutex;
pthread_cond_t cond;
int nready;
}ready={PTHREAD_MUTEX_INITIALIZER,
PTHREAD_COND_INITIALIZER
};
void consume_wait(int i){
for(;;){
pthread_mutex_lock(&shared.mutex);
if(i<shared.nput){
pthread_mutex_unlock(&shared.mutex);
return;
}
pthread_mutex_unlock(&shared.mutex);
}
}
void* produce(void*),*consume(void*);
int min(int a,int b){
return (a>=b)?b:a;
}
int main(int argc,char* argv[]){
int i,nthreads,count[100];
pthread_t tid_produce[100],tid_consume;
nitems=min(atoi(argv[1]),10000000);
nthreads=min(atoi(argv[2]),100);
clock_t st,ed;
double gap;
st=clock();
for(i=0;i<nthreads;i++){
count[i]=0;
pthread_create(&tid_produce[i],0,produce,&count[i]);
}
pthread_create(&tid_consume,0,consume,0);
for(i=0;i<nthreads;i++){
pthread_join(tid_produce[i],0);
printf("count[%d]=%d\\n",i,count[i]);
}
pthread_join(tid_consume,0);
ed=clock();
gap=(double)(ed-st);
printf("gap time %f\\n",gap/CLOCKS_PER_SEC);
return 0;
}
void* produce(void* arg){
for(;;){
pthread_mutex_lock(&shared.mutex);
if(shared.nput>=nitems){
pthread_mutex_unlock(&shared.mutex);
break;
}
shared.buff[shared.nput]=shared.nval;
shared.nval++;
shared.nput++;
pthread_mutex_unlock(&shared.mutex);
pthread_mutex_lock(&ready.mutex);
if(ready.nready==0)
pthread_cond_signal(&ready.cond);
ready.nready++;
pthread_mutex_unlock(&ready.mutex);
*((int*)arg)+=1;
}
}
void* consume(void* arg){
int i;
for(i=0;i<nitems;i++){
pthread_mutex_lock(&ready.mutex);
while(ready.nready==0)
pthread_cond_wait(&ready.cond,&ready.mutex);
ready.nready--;
pthread_mutex_unlock(&ready.mutex);
if(shared.buff[i]!=i)
printf("buff[%d]=%d\\n",i,shared.buff[i]);
}
}
| 0
|
#include <pthread.h>
char *value;
} Line;
int size;
int start;
int count;
Line *items;
} Buffer;
void bufInit(Buffer *b, int maxSize);
bool bufIsFull(Buffer *b);
bool bufIsEmpty(Buffer *b);
void bufWrite(Buffer *b, Line *l);
Line *bufRead(Buffer *b, int pos);
void bufFree(Buffer *b);
void *screenDrawingThread(void *);
void gracefulExit();
void initScreen();
void updateScreen();
void sigIntHandler(int);
void calculateTermSize();
void putLineInBuffer(Line *line);
int rowsForLine(Line *l, int maxCols);
extern int errno;
bool volatile hasToExit = 0;
bool volatile hasToRedraw = 0;
pthread_t drawingThread;
pthread_mutex_t lock;
Buffer buffer;
int main(int argc, char **argv) {
signal(SIGINT, sigIntHandler);
if (pthread_mutex_init(&lock, 0) != 0) {
gracefulExit();
fprintf(stderr, "Error creating mutex\\n");
return 1;
}
bufInit(&buffer, 512);
initScreen();
if (pthread_create(&drawingThread, 0, screenDrawingThread, 0)) {
gracefulExit();
fprintf(stderr, "Error creating thread\\n");
return 1;
}
fcntl(STDIN_FILENO, F_SETFL, fcntl(STDIN_FILENO, F_GETFL) | O_NONBLOCK);
char *line = (char *)malloc(sizeof(char) * 2048);
while (!hasToExit) {
if (fgets(line, 2048, stdin) != 0) {
pthread_mutex_lock(&lock);
Line *l = (Line *)malloc(sizeof(Line));
l->value = strdup(line);
putLineInBuffer(l);
pthread_mutex_unlock(&lock);
}
}
free(line);
gracefulExit();
return 0;
}
void sigIntHandler(int dummy) {
hasToExit = 1;
fprintf(stdout, "\\n");
}
void putLineInBuffer(Line *line) {
bufWrite(&buffer, line);
hasToRedraw = 1;
}
void gracefulExit() {
if (drawingThread) {
pthread_cancel(drawingThread);
}
pthread_mutex_destroy(&lock);
endwin();
bufFree(&buffer);
}
void initScreen() {
initscr();
cbreak();
noecho();
}
void* screenDrawingThread (void *ptr) {
while (!hasToExit) {
if (hasToRedraw) {
pthread_mutex_lock(&lock);
updateScreen();
hasToRedraw = 0;
pthread_mutex_unlock(&lock);
}
}
return 0;
}
int rowsForLine(Line *l, int maxCols) {
int len = strlen(l->value);
return len / maxCols;
}
void updateScreen() {
Buffer *b = &buffer;
int mCols = 0;
int mRows = 0;
int rowsLeft = 0;
int iterations = 0;
long iterator = (b->start + b->count - 1) % b->size;
clear();
getmaxyx(stdscr, mCols, mRows);
rowsLeft = mRows;
if (b->count > 0) {
while (iterations < b->count && rowsLeft > 0) {
Line *l = bufRead(b, iterator);
if (l != 0) {
int rowsLine = rowsForLine(l, mCols);
printw("%s", l->value);
iterations++;
iterator--;
if (iterator < 0) {
iterator = b->start + b->count - 1;
}
rowsLeft -= rowsLine;
}
}
}
refresh();
}
void bufInit(Buffer *b, int maxSize) {
b->size = maxSize;
b->start = 0;
b->count = 0;
b->items = (Line *)(malloc(sizeof(Line) * maxSize));
}
bool bufIsFull(Buffer *b) {
return b->count == b->size;
}
bool bufIsEmpty(Buffer *b) {
return b->count == 0;
}
void bufWrite(Buffer *b, Line *l) {
int end = (b->start + b->count) % b->size;
if (b->count == b->size) {
b->start = (b->start + 1) % b->size;
Line *l = &b->items[end];
if (l != 0) {
free(l->value);
}
} else {
b->count++;
}
b->items[end] = *l;
}
Line *bufRead(Buffer *b, int pos) {
int itemPos = (b->start + pos) % b->size;
return &b->items[itemPos];
}
void bufFree(Buffer *b) {
int i = 0;
for (i = 0; i < b->count; i++) {
Line *l = &b->items[i];
if (l != 0 && l->value != 0) {
free(l->value);
}
}
free(b->items);
}
| 1
|
#include <pthread.h>
{
int* dataPoint;
int index;
}
DataInfo;
pthread_mutex_t g_Mutex;
pthread_cond_t g_Condition;
int* Datas;
int Sums[(1024)];
void* ThreadFunction(void* Data);
int main(int argc, char** argv)
{
int ThreadResult = (0);
Datas = malloc(sizeof(int) * (1024));
if(Datas == 0)
{
printf("Datas allocation failed!\\n");
return (-1);
}
ThreadResult = pthread_mutex_init(&g_Mutex, 0);
if(ThreadResult != (0))
{
printf("Thread initialize failed!\\n");
return (-1);
}
ThreadResult = pthread_mutex_init(&g_Condition, 0);
if(ThreadResult != (0))
{
printf("Thread initialize failed!\\n");
return (-1);
}
pthread_t Threads[(4)];
DataInfo CalculateData;
for(int Index = 0; Index < (4); ++Index)
{
CalculateData.dataPoint = Datas;
CalculateData.index = Index;
int ThreadResult = pthread_create(&Threads[Index],
0,
ThreadFunction,
(void*)&CalculateData);
usleep(100);
}
for(int Index = 0; Index < (1024); ++Index)
{
*Datas = Index;
*Datas++;
}
pthread_cond_broadcast(&g_Condition);
int Sum = 0;
for(int Index = 0; Index < (4); ++Index)
{
pthread_join(Threads[Index], 0);
Sum += Sums[Index];
}
printf("SUM (0-99) : %d\\n", Sum);
return (0);
}
void* ThreadFunction(void* Data)
{
DataInfo CalculateData;
CalculateData = *((DataInfo*)Data);
pthread_mutex_lock(&g_Mutex);
pthread_cond_wait(&g_Condition, &g_Mutex);
printf("Start %d Thread\\n", CalculateData.index);
pthread_mutex_unlock(&g_Mutex);
int Sum = 0;
for(int Index = 0; Index < 25; ++Index)
{
int DataPointIndex = (CalculateData.index * 25) + Index;
Sum += CalculateData.dataPoint[DataPointIndex];
}
printf("(%d) %d\\n", CalculateData.index, Sum);
Sums[CalculateData.index] = Sum;
return 0;
}
| 0
|
#include <pthread.h>
int counter = 0;
pthread_mutex_t counter_mutex;
void *thread_foo(void *args)
{
int i = 0;
for(i = 0; i < 5; i++)
{
pthread_mutex_lock(&counter_mutex);
{
counter = counter + 1;
printf("foo: counter is %d\\n", counter);
fflush(0);
}
pthread_mutex_unlock(&counter_mutex);
}
pthread_exit(0);
}
void *thread_bar(void *args)
{
int i = 0;
for(i = 0; i < 5; i++)
{
pthread_mutex_lock(&counter_mutex);
{
counter = counter + 1;
printf("bar: counter is %d\\n", counter);
fflush(0);
}
pthread_mutex_unlock(&counter_mutex);
}
pthread_exit(0);
}
int main()
{
pthread_t tid_foo;
pthread_t tid_bar;
if (0 != pthread_mutex_init(&counter_mutex, 0))
{
printf("init mutex failed...\\n");
return -1;
}
if (0 != pthread_create(&tid_foo, 0, thread_foo, 0))
{
printf("create thread foo failed...\\n");
return -1;
}
if (0 != pthread_create(&tid_bar, 0, thread_bar, 0))
{
printf("create thread bar failed...\\n");
return -1;
}
if (0 != pthread_join(tid_foo, 0))
{
printf("join thread foo failed...\\n");
return -1;
}
if (0 != pthread_join(tid_bar, 0))
{
printf("join thread bar failed...\\n");
return -1;
}
if (0 != pthread_mutex_destroy(&counter_mutex))
{
printf("destory mutex failed...\\n");
return -1;
}
return 0;
}
| 1
|
#include <pthread.h>
int mediafirefs_readlink(const char *path, char *buf, size_t bufsize)
{
printf("FUNCTION: readlink. path: %s\\n", path);
(void)path;
(void)buf;
(void)bufsize;
struct mediafirefs_context_private *ctx;
ctx = fuse_get_context()->private_data;
pthread_mutex_lock(&(ctx->mutex));
fprintf(stderr, "readlink not implemented\\n");
pthread_mutex_unlock(&(ctx->mutex));
return -ENOSYS;
}
| 0
|
#include <pthread.h>
int global_counter = 0;
pthread_mutex_t lock;
void* inc(void* pid){
pthread_mutex_lock(&lock);
for(int i = 0; i < 100; i++){
global_counter++;
}
pthread_mutex_unlock(&lock);
}
int main(int argc, const char* argv[]){
int nt;
sscanf(argv[1],"%d",&nt);
pthread_t threads[nt];
int info_thread;
long unsigned int pid = pthread_self();
for(int i = 0; i < nt; i++){
info_thread = pthread_create(&threads[i], 0, inc, (void*)pid);
if(info_thread != 0){
printf("Erro ao criar a thread!\\n");
return -1;
}
}
for(int i = 0; i < nt; i++){
info_thread = pthread_join(threads[i], 0);
if(info_thread != 0){
printf("Erro ao unir as threads!\\n");
return -1;
}
}
printf("Valor total dos incrementos é: %d\\n", global_counter);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_t task1_thread;
static pthread_mutex_t task1_mtx = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t task1_cond = PTHREAD_COND_INITIALIZER;
static int task1_running;
static int task1_exit;
static int task1(void)
{
int i;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGINT);
sigaddset(&mask, SIGTERM);
sigaddset(&mask, SIGQUIT);
sigaddset(&mask, SIGABRT);
sigprocmask(SIG_BLOCK, &mask, 0);
DBG(DBG_TRACE, "PID: %d, PPID: %d", getpid(), getppid());
task1_exit = 0;
while (task1_exit == 0) {
pthread_mutex_lock(&task1_mtx);
DBG(DBG_TRACE, "task1 stopped, waiting...");
pthread_cond_wait(&task1_cond, &task1_mtx);
pthread_mutex_unlock(&task1_mtx);
if (task1_exit == 1)
break;
task1_running = 1;
printf("fazendo algo...");
while (task1_running == 1) {
for (i = 5; i; i--) {
printf("%d ", i);
fflush(stdout);
sleep(1);
}
}
printf("voltando a dormir.");
fflush(stdout);
}
DBG(DBG_TRACE, "fim da task1");
pthread_exit(0);
return 0;
}
int task1_run(void)
{
if (task1_running == 1)
return 1;
pthread_mutex_lock(&task1_mtx);
pthread_cond_signal(&task1_cond);
pthread_mutex_unlock(&task1_mtx);
return 0;
}
int task1_stop(void)
{
if (task1_running == 0)
return 1;
pthread_mutex_lock(&task1_mtx);
task1_running = 0;
pthread_cond_signal(&task1_cond);
pthread_mutex_unlock(&task1_mtx);
return 0;
}
int tasks_start(void)
{
int ret;
DBG(DBG_TRACE, "pthread_create()...");
ret = pthread_create(&task1_thread, 0,
(void * (*)(void *))task1,
(void *)0);
return ret;
}
int tasks_stop(void)
{
pthread_mutex_lock(&task1_mtx);
task1_exit = 1;
pthread_cond_signal(&task1_cond);
pthread_mutex_unlock(&task1_mtx);
pthread_join(task1_thread, 0);
DBG(DBG_TRACE, "bye-bye!");
return 0;
}
| 0
|
#include <pthread.h>
int pbs_stagein(
int c,
char *jobid,
char *location,
char *extend)
{
int rc;
int local_errno = 0;
struct batch_reply *reply;
int sock;
struct tcp_chan *chan = 0;
if ((jobid == (char *)0) || (*jobid == '\\0'))
return (PBSE_IVALREQ);
if (location == (char *)0)
location = "";
pthread_mutex_lock(connection[c].ch_mutex);
sock = connection[c].ch_socket;
if ((chan = DIS_tcp_setup(sock)) == 0)
{
pthread_mutex_unlock(connection[c].ch_mutex);
rc = PBSE_PROTOCOL;
return rc;
}
else if ((rc = encode_DIS_ReqHdr(chan, PBS_BATCH_StageIn, pbs_current_user)) ||
(rc = encode_DIS_RunJob(chan, jobid, location, 0)) ||
(rc = encode_DIS_ReqExtend(chan, extend)))
{
connection[c].ch_errtxt = strdup(dis_emsg[rc]);
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return (PBSE_PROTOCOL);
}
if (DIS_tcp_wflush(chan))
{
pthread_mutex_unlock(connection[c].ch_mutex);
DIS_tcp_cleanup(chan);
return (PBSE_PROTOCOL);
}
reply = PBSD_rdrpy(&local_errno, c);
rc = connection[c].ch_errno;
pthread_mutex_unlock(connection[c].ch_mutex);
PBSD_FreeReply(reply);
DIS_tcp_cleanup(chan);
return(rc);
}
| 1
|
#include <pthread.h>
int total_words;
pthread_mutex_t counter_lock = PTHREAD_MUTEX_INITIALIZER;
void count_words(char *f);
main(int argc, char *argv[])
{
pthread_t t1, t2;
if (argc != 3)
{
printf("usage:%s file file2\\n", argv[0]);
exit(1);
}
total_words = 0;
pthread_create(&t1, 0, count_words, argv[1]);
pthread_create(&t2, 0, count_words, argv[2]);
pthread_join(t1, 0);
pthread_join(t2, 0);
printf("%5d:total words\\n", total_words);
}
void count_words(char *f)
{
char *filename = f;
FILE *fp;
int c, prevc = '\\0';
if ((fp = fopen(filename, "r")) != 0)
{
while ((c = getc(fp)) != EOF)
{
if (!isalnum(c) && isalnum(prevc))
{
pthread_mutex_lock(&counter_lock);
total_words++;
pthread_mutex_unlock(&counter_lock);
}
prevc = c;
}
fclose(fp);
}else
{
perror(filename);
}
return;
}
| 0
|
#include <pthread.h>
NEW,
PROCESSING,
DONE
} statuses;
int time;
int id;
statuses status;
pthread_t worker;
} task_t;
pthread_mutex_t lock;
task_t tasks[100];
static int sum = 0;
void* work(void* x) {
int done_tasks = 0, i;
int j;
while(!j){
j = 1;
for (i = 0; i < 100; i++) {
pthread_mutex_lock( &lock );
if(tasks[i].status == NEW) {
tasks[i].status = PROCESSING;
tasks[i].worker = pthread_self();
pthread_mutex_unlock( &lock );
printf("Task is %d sleep for %d\\n",tasks[i].id,tasks[i].time);
usleep(tasks[i].time);
tasks[i].status = DONE;
done_tasks++;
j = 0;
break;
}
else pthread_mutex_unlock( &lock );
}
}
sum = done_tasks + sum;
printf("I thread %u, have done %d tasks, sum is %d \\n", (unsigned int)pthread_self(),done_tasks,sum);
return 0;
}
int main() {
statuses status;
pthread_mutex_init(&lock, 0);
int i;
int *thread_args,all_tasks_done=0;
pthread_t thread_id[10];
for (i = 0; i < 100; i++) {
tasks[i].id = i;
tasks[i].time = abs(random() % 1000);
tasks[i].status = NEW;
}
for(i = 0; i< 10;i++){
pthread_create(
&(thread_id[i]),
(pthread_attr_t *)0,
work,
(void *)(tasks));
}
for (i = 0; i < 10; i++) {
pthread_join(thread_id[i], 0);
}
pthread_mutex_destroy( &lock );
return 0;
}
| 1
|
#include <pthread.h>
struct reg {
int *inicio;
int *fim;
int *vet;
int n;
};
int somatorio[4];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * function (void *arg) {
int soma;
struct reg *valor;
valor = (struct reg*) arg;
printf("inicio %d\\n",valor->inicio[valor->n]);
printf("fim %d\\n",valor->fim[valor->n]);
int i;
for (i = valor->inicio[valor->n]; i < valor->fim[valor->n] ; i++) {
pthread_mutex_lock(&mutex);
soma += valor->vet[i];
pthread_mutex_unlock(&mutex);
}
somatorio[valor->n] = soma;
}
int* geradorDeNumeros(int M, int K){
unsigned short seed[]={12,1,2};
int i;
int *vetor = malloc(sizeof(int)*M);
for(i=0;i<M;i++)
vetor[i] = 1 + K * erand48(seed);
return vetor;
}
int main () {
clock_t time1, time2, time_diff;
int qtdnum, intervalo, *vet;
struct timeval antes, depois ;
float delta, delta2 ;
int K = (2048*1024) ;
qtdnum = K;
intervalo = 10000;
vet = geradorDeNumeros(qtdnum, intervalo);
pthread_t threads[4];
int vetFim[4];
int vetIni[4];
int result = K / 4;
vetFim[0] = result;
vetIni[0] = 0;
int l = 1;
while(l < 4){
vetIni[l] = vetFim[l-1];
vetFim[l] = vetFim[l-1] + result;
l++;
}
struct reg x;
x.inicio = vetIni;
x.fim = vetFim;
x.vet = vet;
struct reg aux[4];
for(int i = 0 ; i < 4 ; i++){
aux[i] = x;
aux[i].n = i;
}
int i = 0;
gettimeofday (&antes, 0) ;
for(i = 0 ; i < 4 ; i++){
pthread_create(&threads[i], 0, function, (void *)(&aux[i]));
}
for(i = 0 ; i < 4 ; i++){
pthread_join(threads[i], 0);
}
gettimeofday (&depois, 0) ;
printf("Somatorio %d\\n",somatorio[0]);
delta = (depois.tv_sec + depois.tv_usec/1000000.0) -
(antes.tv_sec + antes.tv_usec /1000000.0) ;
delta2 = ((depois.tv_sec * 1000000 + depois.tv_usec)
- (antes.tv_sec * 1000000 + antes.tv_usec));
printf("Tempo de execução em segundos %f segundos & Diferenca de %f microsegundos\\n\\n", delta , delta2);
exit(0);
}
| 0
|
#include <pthread.h>
int tid;
double stuff;
} thread_data_t;
char temp;
pthread_mutex_t lock_x;
char buf[30*4096];
void *thr_func_1(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
char *buf = 0;
int i = 0;
printf("hello from thr_func, thread id: %d\\n", data->tid);
for(; i<100000; i++)
{
buf = (char*)malloc(8192);
*buf = i;
*buf = *buf * *buf;
pthread_mutex_lock(&lock_x);
temp = *buf;
*buf = ++temp;
pthread_mutex_unlock(&lock_x);
mprotect(buf, 4096, PROT_READ);
free(buf);
}
pthread_mutex_lock(&lock_x);
temp = data->tid;
pthread_mutex_unlock(&lock_x);
pthread_exit(0);
}
void *thr_func(void *arg) {
thread_data_t *data = (thread_data_t *)arg;
int i = 0;
printf("hello from thr_func, thread id: %d\\n", data->tid);
for (;i<30;i++){
pthread_mutex_lock(&lock_x);
memset(buf,(char)data->tid,sizeof(buf));
pthread_mutex_unlock(&lock_x);
sleep(1);
pthread_mutex_lock(&lock_x);
mprotect(&buf[data->tid*4096], 4096, PROT_READ);
pthread_mutex_unlock(&lock_x);
}
pthread_exit(0);
}
int main(int argc, char **argv) {
struct timeval begin;
struct timeval end;
pthread_t thr[30];
int i, rc;
thread_data_t thr_data[30];
memset(buf, 0, sizeof(buf));
pthread_mutex_init(&lock_x, 0);
gettimeofday(&begin, 0);
for (i = 0; i < 30; ++i) {
thr_data[i].tid = i;
if ((rc = pthread_create(&thr[i], 0, thr_func, &thr_data[i]))) {
fprintf(stderr, "error: pthread_create, rc: %d\\n", rc);
return 1;
}
}
for (i = 0; i < 30; ++i) {
pthread_join(thr[i], 0);
}
gettimeofday(&end, 0);
int used = (end.tv_sec-begin.tv_sec)*1000000 + end.tv_usec - begin.tv_usec;
printf("time used %d us\\n", used);
printf("TEMP = %d", (int)temp);
return 0;
}
| 1
|
#include <pthread.h>
int hasEaten[5] = {0};
struct timeval te,tf;
int totalTime =0;
int philCount =0;
int peakTime = 0;
void *function(int n);
pthread_t philosophers[5];
pthread_mutex_t forks[5];
pthread_mutex_t total = PTHREAD_MUTEX_INITIALIZER;
int main(){
int i,k;
for(i=0;i<5;i++){
pthread_mutex_init(&forks[i],0);
}
for(i=0;i<5;i++){
pthread_create(&philosophers[i],0,(void *)function,(void *)i);
}
for(i=0;i<5;i++){
pthread_join(philosophers[i],0);
}
printf("All of the philsosophers are done eating! \\n");
printf("Average waiting time was %d ms \\n",totalTime / 5);
}
void *function(int n){
while(1){
clock_t start_time, end_time, elapsed;
printf("philosopher %d is thinking \\n", n);
int randomThinking;
randomThinking = rand()%15;
sleep(randomThinking);
int s,m;
printf("philosopher %d is HUNGRY!!!!!\\n",n);
gettimeofday(&te, 0);
long long millisecondsStart = te.tv_sec*1000LL + te.tv_usec/1000;
if(hasEaten[n]==1){
sleep(rand()%15+1);
printf("phil %d has to wait \\n", n );
}
pthread_mutex_lock(&forks[n]);
printf("philosopher %d got right fork-forkNO.->%d\\n", n,n);
pthread_mutex_lock(&forks[(n+1)%(5 )]);
printf("philosopher %d got left fork-forkNO.->%d\\n", n,(n+1)%(5 ));
gettimeofday(&tf, 0);
long long millisecondsEnd = tf.tv_sec*1000LL + tf.tv_usec/1000;
long long diff = millisecondsEnd - millisecondsStart;
printf("waiting time for philosopher %d is : %lld ms \\n", n,diff) ;
pthread_mutex_lock(&total);
if(diff>peakTime){
peakTime = diff;
}
totalTime += diff;
philCount++;
printf("philCount: %d \\n",philCount);
if(philCount == 5){
philCount =0;
printf("average waiting time is: %d \\n",totalTime/5);
printf("peak time is:%d \\n", peakTime);
peakTime = 0;
int i;
for( i=0;i<5;i++){
hasEaten[i] =0;
}
printf("array reinitialized \\n");
}
pthread_mutex_unlock(&total);
elapsed = (end_time - start_time) ;
int msec = elapsed * 1000 /CLOCKS_PER_SEC;
int randomEat;
randomEat = rand()%10;
printf("philosopher %d is going to eat for %d s! \\n", n,randomEat +1);
sleep(randomEat + 1);
pthread_mutex_unlock(&forks[n]);
printf("philosopher %d has put down fork no. %d \\n", n, n);
pthread_mutex_unlock(&forks[(n+1)%(5 )]);
printf("philosopher %d has put down fork no. %d \\n", n, (n+1)%5);
printf("philosopher %d is done eating! \\n", n);
hasEaten[n] = 1;
}
}
| 0
|
#include <pthread.h>
int npos;
pthread_mutex_t mut=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t vmut=PTHREAD_MUTEX_INITIALIZER;
int buf[10000000], pos=0, val=0, ver=0;
void *fill(void *nr) {
while (1) {
pthread_mutex_lock(&mut);
if (pos >= npos) {
pthread_mutex_unlock(&mut);
return 0;
}
buf[pos] = val;
pos++; val++;
pthread_mutex_unlock(&mut);
*(int *)nr += 1;
}
}
void *verify(void *arg) {
while (1) {
pthread_mutex_lock(&vmut);
if (ver >= npos) {
pthread_mutex_unlock(&vmut);
return 0;
}
if (ver < pos) {
if (buf[ver] != ver)
printf("ERROR: buf[%d] = %d\\n", ver, buf[ver]);
ver++;
pthread_mutex_unlock(&vmut);
*(int *)arg += 1;
}
else
pthread_mutex_unlock(&vmut);
}
}
int main(int argc, char *argv[]) {
int k, nthr, nv, count[100], v[100];
pthread_t tidf[100], tidv[100];
int total, tver;
if (argc != 4) {
printf("Usage: %s <nr_pos> <nr_thrs> <nr_tverify>\\n",argv[0]);
return 1;
}
npos = (atoi(argv[1]))<(10000000)?(atoi(argv[1])):(10000000);
nthr = (atoi(argv[2]))<(100)?(atoi(argv[2])):(100);
nv = (atoi(argv[3]))<(100)?(atoi(argv[3])):(100);
for (k=0; k<nthr; k++) {
count[k] = 0;
pthread_create(&tidf[k], 0, fill, &count[k]);
}
for (k=0; k<nv; k++) {
v[k] = 0;
pthread_create(&tidv[k], 0, verify, &v[k]);
}
total = 0;
for (k=0; k<nthr; k++) {
pthread_join(tidf[k], 0);
printf("count[%d] = %d\\n", k, count[k]);
total += count[k];
}
tver = 0;
for (k=0; k<nv; k++) {
pthread_join(tidv[k], 0);
printf("ver[%d] = %d\\n", k, v[k]);
tver += v[k];
}
pthread_mutex_destroy(&mut);
pthread_mutex_destroy(&vmut);
printf("total count = %d total verified = %d\\n",total, tver);
return 0;
}
| 1
|
#include <pthread.h>
char buffer[7];
int nextin = 0, nextout = 0;
int count = 0;
pthread_cond_t notfull = PTHREAD_COND_INITIALIZER;
pthread_cond_t notempty = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void produce_char(void **argument){
char produced = 97+rand()%27;
if (count == 7)
pthread_cond_wait(¬full,&mutex);
pthread_mutex_lock(&mutex);
printf("I produced %c\\n", produced);
buffer [nextin] = produced;
nextin = (nextin + 1) % 7;
count ++;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(¬empty);
pthread_exit(0);
}
void take(void *args) {
char tooked;
if (count == 0)
pthread_cond_wait(¬empty, &mutex) ;
pthread_mutex_lock(&mutex);
tooked = buffer [nextout] ;
printf("I'm taking %c\\n", tooked);
nextout = (nextout + 1) % 7;
count --;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(¬full);
pthread_exit(0);
}
int main(int argc, char const *argv[]) {
pthread_t producer[3];
pthread_t consumer[3];
printf("\\nCreating Threads\\n");
for (int i = 0; i < 3; i++) {
if(pthread_create(&producer[i],0,(void *)produce_char,0)){
printf("Error creating thread \\n");
exit(-1);
}
if(pthread_create(&consumer[i],0,(void *)take,0)){
printf("Error creating thread\\n");
exit(-1);
}
}
printf("Waiting producer to finish\\n");
for (int i = 0; i < 3; i++) {
pthread_join(producer[i],0);
}
printf("Waiting consumer to finish\\n");
for (int i = 0; i < 3; i++) {
pthread_join(consumer[i],0);
}
pthread_cond_destroy(¬full);
pthread_cond_destroy(¬empty);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
char* dir;
struct Item* next;
} Item;
int fd, numDir[4];
Item* head;
pthread_mutex_t mep, mec, mef;
sem_t *full;
struct timespec ts;
void* exploreDirectory(void* arg);
Item* get(void);
void put(char* item);
int main(int argc, char** argv) {
char *directory, *filename;
int *arg, i;
pthread_t th;
struct stat statBuf;
if (argc != 3) {
fprintf(stderr, "Wrong number of arguments. Syntax: %s directory filename\\n", argv[0]);
return -1;
}
directory = argv[1];
filename = argv[2];
if (stat(directory, &statBuf) == -1) {
fprintf(stderr, "ERROR. stat() failed.\\n");
return -1;
}
if (!S_ISDIR(statBuf.st_mode)) {
fprintf(stderr, "ERROR. %s is not a directory.\\n", directory);
return -1;
}
if ((fd = open(filename, O_CREAT | O_RDWR, 0777)) == -1) {
fprintf(stderr, "ERROR. open() failed.\\n");
return -1;
}
pthread_mutex_init(&mep, 0);
pthread_mutex_init(&mec, 0);
pthread_mutex_init(&mef, 0);
full = (sem_t*)malloc(sizeof(sem_t));
sem_init(full, 0, 0);
put(directory);
for (i=0; i<4; i++) {
arg = (int*)malloc(sizeof(int));
*arg = i;
pthread_create(&th, 0, (void*)exploreDirectory, (void*)arg);
}
pthread_exit((void*)0);
}
Item* get(void) {
Item* item;
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1;
if (sem_timedwait(full, &ts) == -1) {
return (Item*)0;
}
pthread_mutex_lock(&mec);
item = head;
head = head->next;
pthread_mutex_unlock(&mec);
return item;
}
void put(char* itemData) {
Item* item;
pthread_mutex_lock(&mep);
item = (Item*)malloc(sizeof(Item));
item->dir = strdup(itemData);
item->next = head;
head = item;
pthread_mutex_unlock(&mep);
sem_post(full);
return;
}
void* exploreDirectory(void* arg) {
int* id = (int*)arg;
char dirName[1023 + 1], *pathName, row[1023 + 6];
DIR *dp;
Item* item;
struct dirent *dirEntry;
struct stat statBuf;
pthread_detach(pthread_self());
while(1) {
item = get();
if (item == 0) {
fprintf(stdout, "Thread %d explored %d directories.\\n", *id, numDir[*id]);
pthread_exit((void*)0);
}
pathName = item->dir;
if ((dp = opendir(pathName)) == 0) {
fprintf(stderr, "ERROR. opendir() failed.\\n");
exit(1);
}
numDir[*id]++;
while((dirEntry = readdir(dp)) != 0) {
sprintf(dirName, "%s/%s", pathName, dirEntry->d_name);
if (lstat(dirName, &statBuf) == -1) {
fprintf(stderr, "ERROR. lstat() failed.\\n");
exit(1);
}
switch(statBuf.st_mode & S_IFMT) {
case S_IFDIR:
if (strcmp(dirEntry->d_name, ".") && strcmp(dirEntry->d_name, "..")) {
fprintf(stdout, "%s is a directory explored by thread %d.\\n", dirName, *id);
put(dirName);
sleep(1);
}
break;
case S_IFREG:
fprintf(stdout, "%s is a file processed by thread %d.\\n", dirName, *id);
pthread_mutex_lock(&mef);
sprintf(row, "%d %s\\n", *id, dirName);
write(fd, row, strlen(row));
write(fd, "\\n", 1);
pthread_mutex_unlock(&mef);
break;
default:
break;
}
}
closedir(dp);
free(item);
}
pthread_exit((void*)0);
}
| 1
|
#include <pthread.h>
int count = 0, 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);
}
| 0
|
#include <pthread.h>
int fd;
int thrdzCnt;
int bufSize;
int dl;
char *str;
pthread_t* thrdz;
pthread_attr_t thrdzAttrs;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t kanselejszynMooteks = PTHREAD_MUTEX_INITIALIZER;
struct thrdInfo{
char* buf;
int idx;
};
void* searchForThatNeedle(void* args);
void thrdzCleanup(void *bufor);
void myatexit(void);
int main(int argc, char* argv[]){
int i;
int tmp;
if(argc != 5)
thrdzCnt = atoi(argv[1]);
if(thrdzCnt < 1)
tmp = sysconf(_SC_THREAD_THREADS_MAX);
if(tmp != -1 && thrdzCnt > tmp) {
fprintf(stderr, "Maksymalna ilość wątków (sysconf(_SC_THREAD_THREADS_MAX)) : %d\\n",tmp);
}
fd = open(argv[2], O_RDONLY);
if(fd == -1)
bufSize = atoi(argv[3]);
if(bufSize < 1)
str = argv[4];
atexit(myatexit);
thrdz = ((pthread_t*)malloc((uint)thrdzCnt*sizeof(pthread_t)));
tmp = pthread_attr_init(&thrdzAttrs);
if(tmp != 0)
for(i=0; i<thrdzCnt; ++i){
tmp = pthread_create (&thrdz[i], &thrdzAttrs, &searchForThatNeedle, (void*)i);
if(tmp == -1)
}
sleep(3);
for(i=0; i<thrdzCnt; ++i) {
if((thrdz[i] != 0) && pthread_join(thrdz[i], 0) != 0)
}
return 0;
}
void thrdzCleanup(void *dane){
free(((struct thrdInfo*)dane)->buf);
}
void myatexit(){
if(close(fd) == -1)
fprintf(stderr,"Błąd close(2)!\\n");
free(thrdz);
if(pthread_attr_destroy(&thrdzAttrs) != 0)
fprintf(stderr,"Błąd pthread_attr_destroy(3p)!\\n");
}
void* searchForThatNeedle(void* args){
int i;
int j;
int k;
int tmp;
struct thrdInfo myThreadyData;
int readLen;
int readBegin;
int readEnd;
int ok;
int cntr;
tmp = pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
if(tmp != 0)
myThreadyData.idx = (int)args;
myThreadyData.buf = ((char*)malloc((uint)bufSize*sizeof(char)));
pthread_cleanup_push(thrdzCleanup, &myThreadyData);
for(;;) {
pthread_mutex_lock(&mutex);
readBegin = lseek(fd, 0, 1);
readLen = read(fd,myThreadyData.buf,sizeof(char)*(uint)bufSize);
pthread_mutex_unlock(&mutex);
if(readLen == -1) {
} else if(!readLen)
return 0;
for(i=0; i<readLen; i++) {
for(j=i; ((uint)(j-i)<strlen(str)) && (j<readLen); ++j)
if(myThreadyData.buf[j] != str[j-i])
break;
ok = (uint)(j-i) >= strlen(str);
if(((uint)(j-i) == strlen(str))) {
printf("I IZ %d, CAN HAZ STRZ HERZ: %d\\n", (int)pthread_self(), readBegin + i);
if(pthread_mutex_trylock(&kanselejszynMooteks) != EBUSY){
for(k=0; k<thrdzCnt; k++){
if((k != myThreadyData.idx)&& (thrdz[k] != 0)){
pthread_cancel(thrdz[k]);
thrdz[k] = 0;
}
}
}
thrdz[myThreadyData.idx] = 0;
pthread_exit((void*)0);
}
}
for(i=readLen-(int)strlen(str); i<readLen; ++i){
ok = 1;
for(j=i; j<readLen; ++j)
if(myThreadyData.buf[j] != str[j-i])
break;
dl = j-i;
if(j>=readLen) {
cntr = (int)strlen(str)+j-i;
pthread_mutex_lock(&mutex);
readEnd = lseek(fd,0,1);
lseek(fd, readBegin + readLen,0);
readLen = read(fd, myThreadyData.buf, sizeof(char)*(uint)bufSize);
lseek(fd, readEnd, 0);
pthread_mutex_unlock(&mutex);
if (readLen == -1)
pthread_exit((void*)1);
else if(!readLen) {
thrdz[myThreadyData.idx] = 0;
pthread_exit((void*)0);
}
for (j=0; (j<cntr) && (j<readLen) && ((uint)dl<strlen(str)); ++j){
if(myThreadyData.buf[j]!= str[dl++]){
ok=0;
break;
}
}
if(ok && ((uint)dl == strlen(str))){
printf("I IZ %d, CAN HAZ STRZ HERZ: %d\\n", (int)pthread_self(), readBegin + i);
if(pthread_mutex_trylock(&kanselejszynMooteks) != EBUSY) {
for(k=0; k<thrdzCnt; k++){
if((k != myThreadyData.idx) && thrdz[k]){
pthread_cancel(thrdz[k]);
thrdz[k] = 0;
}
}
}
thrdz[myThreadyData.idx] = 0;
pthread_exit((void*)0);
}
}
}
}
pthread_cleanup_pop(1);
return 0;
}
| 1
|
#include <pthread.h>
int cpt = 0;
pthread_mutex_t mut;
pthread_cond_t cond;
void* increm1(void* arg){
int i = 0;
for ( i = 0; i < 4; i++){
pthread_mutex_lock(&mut);
cpt++;
printf("compteur : %d\\n", cpt);
if (cpt == 3)
pthread_cond_signal(&cond);
sleep(3);
pthread_mutex_unlock(&mut);
}
pthread_exit(0);
}
void* increm2(void* arg){
int j = 0;
for ( j = 0; j < 4; j++){
pthread_mutex_lock(&mut);
cpt++;
printf("compteur : %d\\n", cpt);
if (cpt == 3)
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mut);
}
pthread_exit(0);
}
void* attente(void* arg){
pthread_cond_wait(&cond, &mut);
printf("On a atteint 3\\n");
pthread_exit(0);
}
int main(){
pthread_t id1, id2, id3;
pthread_mutex_init(&mut, 0);
pthread_cond_init(&cond, 0);
pthread_mutex_lock(&mut);
pthread_create(&id1, 0, increm1, 0);
pthread_create(&id2, 0, increm2, 0);
pthread_create(&id3, 0, attente, 0);
pthread_mutex_unlock(&mut);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m;
void *thread3 (void *arg)
{
int i;
for (i = 0; i < 2; i++)
{
pthread_mutex_lock (&m);
pthread_mutex_unlock (&m);
}
return 0;
}
void *thread2 (void *arg)
{
long i = (long) arg;
printf ("u: running, i %ld!\\n", i);
return 0;
}
void *thread (void *arg)
{
long i = (long) arg;
pthread_t th;
int ret;
printf ("t%ld: running!\\n", i);
ret = pthread_create (&th, 0, thread2, arg);
assert (ret == 0);
if (i % 2 == 0)
{
ret = pthread_join (th, 0);
assert (ret == 0);
}
return 0;
}
int main (int argc, char ** argv)
{
int ret;
long i;
pthread_t th[2];
(void) argc;
(void) argv;
ret = pthread_mutex_init (&m, 0);
assert (ret == 0);
for (i = 0; i < 2; i++)
{
ret = pthread_create (th + i, 0, thread, (void*) i);
assert (ret == 0);
}
for (i = 0; i < 2; i++)
{
ret = pthread_join (th[i], 0);
assert (ret == 0);
}
ret = pthread_create (th, 0, thread3, 0);
assert (ret == 0);
for (i = 0; i < 2; i++)
{
pthread_mutex_lock (&m);
pthread_mutex_unlock (&m);
}
pthread_exit (0);
}
| 1
|
#include <pthread.h>
extern int tiempo_actual;
extern int tiempo_respuesta;
extern int inventario;
extern pthread_mutex_t mutex;
extern FILE *LOG;
int numeroRn;
extern int ips[MAX_SERVERS];
extern int cuotas [MAX_SERVERS];
extern unsigned char *retos[MAX_SERVERS];
char **pedir_gasolina_1_svc(char ** bomba, struct svc_req *rqstp)
{
static char *result;
result= (char *) malloc(sizeof(char)*20);
while(result == 0){
printf("Memoria no reservada, esperare un segundo");
sleep(1);
result = (char *) malloc (sizeof(char) * 128);
}
int i = 0 ;
while (i < MAX_SERVERS && ips[i]!= -1){
if (ips[i]==rqstp->rq_xprt->xp_raddr.sin_addr.s_addr){
break;
}
i=i+1;
}
if (i == MAX_SERVERS){
strcpy(result,"noDisponible");
return &(result);
} else {
if (cuotas[i] < tiempo_actual){
strcpy(result,"noTicket");
}
else {
pthread_mutex_lock(&mutex);
if( inventario >= 38000 ){
inventario= inventario - 38000;
if(inventario==0)fprintf(LOG,"Tanque vacío: %d minutos \\n",tiempo_actual);
strcpy(result,"enviando");
fprintf(LOG,"Suministro: %d minutos, %s, OK, %d litros \\n"
,tiempo_actual,*bomba,inventario);
}else{
fprintf(LOG,"Suministro: %d minutos, %s, No disponible, %d litros \\n"
,tiempo_actual,*bomba,inventario);
strcpy(result,"noDisponible");
}
pthread_mutex_unlock(&mutex);
}
return &(result);
}
}
int *pedir_tiempo_1_svc(void *argp, struct svc_req *rqstp)
{
int k = 0;
while (k < MAX_SERVERS){
if (ips[k]==-1){
ips[k] = rqstp->rq_xprt->xp_raddr.sin_addr.s_addr;
break;
}
k=k+1;
}
return &tiempo_respuesta;
}
int *pedir_reto_1_svc(void *argp, struct svc_req *rqstp)
{
time_t reloj;
time (&reloj);
srand((unsigned int ) reloj);
numeroRn = (int) reloj;
char numeroStr[10];
sprintf(&numeroStr[0],"%d",numeroRn);
unsigned char resultado[16];
MDString (&numeroStr[0],&resultado[0]);
char *md5string= (char *) malloc(sizeof(char)*33);
int i;
for(i = 0; i < 16; ++i)
sprintf(&md5string[i*2], "%02x", (unsigned int)resultado[i]);
int k = 0;
while (k < MAX_SERVERS){
if (ips[k]==rqstp->rq_xprt->xp_raddr.sin_addr.s_addr ){
retos[k]= md5string;
break;
}
k=k+1;
}
return &numeroRn;
}
int *enviar_respuesta_1_svc(char ** resp, struct svc_req *rqstp)
{
static int u = -1;
int i = 0;
int ip;
while (i < MAX_SERVERS){
if (ips[i]==rqstp->rq_xprt->xp_raddr.sin_addr.s_addr ){
if( strcmp (retos[i], *resp) == 0){
cuotas[i]= tiempo_actual + 5 ;
fprintf(LOG,"Autenticado al tiempo : %d \\n", tiempo_actual);
u = 0;
break;
} else {
u = -1;
fprintf(LOG,"Autenticacion fallida al tiempo : %d \\n", tiempo_actual);
break;
}
}
i = i +1;
}
return &(u);
}
| 0
|
#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(;;){
printf("\\n\\ncan give siangl on terminal\\n\\n");
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);
exit(1);
}
}
}
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);
}
| 1
|
#include <pthread.h>
void *produce(void *arg);
void *consume(void *arg);
struct {
pthread_mutex_t mutex;
int buf[1000000];
int nput;
int nval;
int nitems;
} shared = {
PTHREAD_MUTEX_DEFAULT
};
int main(int argc, char *argv[])
{
int i, errcode, nitems, nthread, count[100];
pthread_t threads[100], consume_thread;
if (argc < 2) {
printf("usage:%s items, threads\\n", argv[0]);
return 0;
}
nitems = (atoi(argv[1]) < 1000000 ? atoi(argv[1]) : 1000000);
nthread = (atoi(argv[2]) < 100 ? atoi(argv[2]) : 100);
shared.nitems = nitems;
for (i = 0; i < nthread; i++) {
count[i] = 0;
errcode = pthread_create(&threads[i], 0, produce, (void *)&count[i]);
if ( errcode != 0) {
printf("pthread_create:%s\\n", strerror(errno));
abort();
}
}
for (i = 0; i < nthread; i++) {
pthread_join(threads[i], 0);
printf("count[%d] = %d\\n", i, count[i]);
}
pthread_create(&consume_thread, 0, consume, 0);
pthread_join(consume_thread, 0);
sleep(1000);
return 0;
}
void *produce(void *arg)
{
for(;;) {
pthread_mutex_lock(&shared.mutex);
if (shared.nput > shared.nitems) {
pthread_mutex_unlock(&shared.mutex);
return;
}
shared.buf[shared.nput++] = shared.nval++;
pthread_mutex_unlock(&shared.mutex);
*(int *)arg += 1;
}
}
void *consume(void *arg)
{
int i;
for (i = 0; i < shared.nitems; i++) {
if (shared.buf[i] != i) {
printf("buf[%d] = %d\\n", i, shared.buf[i]);
}
}
}
| 0
|
#include <pthread.h>
void *page_fault_func(void *t);
void *tlb_thrashing_func(void *t);
static int exec_size;
static sigjmp_buf senv[4];
static volatile int jump_ok[4];
static volatile int total = 0;
static void *exec_mem[4];
static pthread_t create_thread[4];
static pthread_t destroy_thread[4];
static pthread_mutex_t mutex[4];
static bool destroy_page = 0;
static int get_thread_index(pthread_t threads[])
{
pthread_t tid;
int id;
int i;
tid = pthread_self();
id = -1;
for (i = 0; i < 4; i++) {
if (tid == threads[i]) {
id = i;
break;
}
}
if (id == -1) {
printf("cannot find thread index for thread %x\\n",
(unsigned int) tid);
exit(1);
}
return id;
}
static void sigact_handler(int signo, siginfo_t *si, void *data)
{
char *str;
int id;
id = get_thread_index(create_thread);
do {} while(0);
str = "";
if (signo == SIGILL) {
switch(si->si_code) {
case ILL_ILLOPC:
str = "illegal opcode"; break;
case ILL_ILLOPN:
str = "illegal operand"; break;
case ILL_ILLADR:
str = "illegal address mode"; break;
case ILL_ILLTRP:
str = "illegal trap"; break;
default:
str = "more error code?";
}
}
if (signo == SIGSEGV) {
switch(si->si_code) {
case SEGV_MAPERR:
str = "mapping error"; break;
case SEGV_ACCERR:
str = "invalid permissios for mapped object"; break;
default:
str = "wrong sigsegv si code";
}
}
do {} while(0)
;
if (1 != jump_ok[id])
printf("jump to thread %d is not ready\\n", id);
else
siglongjmp(senv[id], id + 1);
}
static void *create_func(void *t)
{
int id;
int ret;
id = get_thread_index(create_thread);
ret = sigsetjmp(senv[id], 1);
if (ret == 0) {
jump_ok[id] = 1;
do {} while(0);
} else if (ret > 0) {
do {} while(0);
if ((ret - 1) != id)
do { printf("jump back to the wrong thread %d -> %d\\n", ret - 1, id); exit(1); } while(0)
;
}
pthread_mutex_lock(&mutex[id]);
if (exec_mem[id] == 0) {
exec_mem[id] = mmap(0, exec_size, PROT_READ | PROT_WRITE |
PROT_EXEC, MAP_ANON | MAP_PRIVATE, -1, 0);
if (exec_mem[id] == MAP_FAILED)
do { printf("cannot do mmap on thread %d\\n", id); exit(1); } while(0);
memset(exec_mem[id], 0xFF, exec_size);
do {} while(0)
;
}
total++;
do {} while(0);
if ((total % 1000) == 0) {
printf("."); fflush(stdout);
total = 0;
}
pthread_mutex_unlock(&mutex[id]);
((void(*)(void)) exec_mem[id]) ();
pthread_exit(0);
return 0;
}
static void *destroy_func(void *t)
{
int id;
id = get_thread_index(destroy_thread);
while (1) {
pthread_mutex_lock(&mutex[id]);
if (destroy_page == 1 && exec_mem[id] != 0) {
munmap(exec_mem[id], exec_size);
exec_mem[id] = 0;
}
pthread_mutex_unlock(&mutex[id]);
}
pthread_exit(0);
return 0;
}
void set_signal_handler(void)
{
struct sigaction sa, osa;
memset(&sa, 0, sizeof(sa));
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = sigact_handler;
sigaction(SIGILL, &sa, &osa);
if (destroy_page == 1)
sigaction(SIGSEGV, &sa, &osa);
}
int handle_parameters(int argc, char *argv[])
{
if (argv[1] != 0 && 0 == (strncmp("--destroy", argv[1], 9))) {
destroy_page = 1;
printf("destroy exec page too\\n");
}
if (argv[1] != 0 && 0 == (strncmp("-h", argv[1], 2))) {
printf("%s --destroy\\n", argv[0]);
return 0;
}
return 0;
}
int main(int argc, char *argv[])
{
int t;
pthread_t tlb_thrashing_thread;
pthread_t page_fault_thread;
handle_parameters(argc, argv);
set_signal_handler();
exec_size = sysconf(_SC_PAGE_SIZE);
for (t = 0; t < 4; t++) {
pthread_mutex_init(&mutex[t], 0);
pthread_create(&create_thread[t], 0, create_func, &t);
pthread_create(&destroy_thread[t], 0, destroy_func, &t);
}
pthread_create(&tlb_thrashing_thread, 0, tlb_thrashing_func, 0);
pthread_create(&page_fault_thread, 0, page_fault_func, 0);
pthread_join(tlb_thrashing_thread, 0);
pthread_join(page_fault_thread, 0);
for (t = 0; t < 4; t++) {
pthread_mutex_destroy(&mutex[t]);
pthread_join(create_thread[t], 0);
pthread_join(destroy_thread[t], 0);
}
pthread_exit(0);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t chopstick[6] ;
void *eat_think(void *arg)
{
int i;
char phi = *(char *)arg;
int left,right;
switch (phi){
case 'A':
left = 5;
right = 1;
break;
case 'B':
left = 1;
right = 2;
break;
case 'C':
left = 2;
right = 3;
break;
case 'D':
left = 3;
right = 4;
break;
case 'E':
left = 4;
right = 5;
break;
}
for(;;){
usleep(3);
pthread_mutex_lock(&chopstick[left]);
printf("Philosopher %c fetches chopstick %d\\n", phi, left);
if (pthread_mutex_trylock(&chopstick[right]) == EBUSY){
pthread_mutex_unlock(&chopstick[left]);
continue;
}
printf("Philosopher %c fetches chopstick %d\\n", phi, right);
printf("Philosopher %c is eating.\\n",phi);
usleep(3);
pthread_mutex_unlock(&chopstick[left]);
printf("Philosopher %c release chopstick %d\\n", phi, left);
pthread_mutex_unlock(&chopstick[right]);
printf("Philosopher %c release chopstick %d\\n", phi, right);
pthread_exit(0);
}
}
int main(){
pthread_t A,B,C,D,E;
int i;
for (i = 0; i < 5; i++)
pthread_mutex_init(&chopstick[i],0);
pthread_create(&A,0, eat_think, (void*)"A");
pthread_create(&B,0, eat_think, (void*)"B");
pthread_create(&C,0, eat_think, (void*)"C");
pthread_create(&D,0, eat_think, (void*)"D");
pthread_create(&E,0, eat_think, (void*)"E");
pthread_join(A,0);
pthread_join(B,0);
pthread_join(C,0);
pthread_join(D,0);
pthread_join(E,0);
for (i = 0; i < 5; i++)
pthread_mutex_destroy(&chopstick[i]);
return 0;
}
| 0
|
#include <pthread.h>
struct ppball the_ball;
struct obstacle the_obstacle[MAXMSG];
void set_up();
void init_ball();
void add_boundary();
void add_road();
void ball_move();
void within_boundary(struct ppball*);
int set_up_obs(struct obstacle the_obstacle[]);
void *animate();
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
int num_msg = 6;
int main(){
int c;
int i;
int set_up_obs(struct obstacle the_obstacle[]);
pthread_t threads[MAXMSG];
struct obstacle the_obstacle[MAXMSG];
set_up_obs(the_obstacle);
set_up();
for(i = 1 ; i < num_msg-1; i++)
if(pthread_create(&threads[i], 0, animate, &the_obstacle[i])){
fprintf(stderr,"Error with creating thread");
endwin();
exit(0);
}
while((c=getchar()) !='Q'){
if(c=='w') {the_ball.y_dir = -2; the_ball.x_dir = 0;}
else if(c=='s') {the_ball.y_dir = 2; the_ball.x_dir = 0;}
else if(c=='a') {the_ball.x_dir = -2; the_ball.y_dir = 0;}
else if(c=='d') {the_ball.x_dir = 2; the_ball.y_dir = 0;}
ball_move();
}
pthread_mutex_lock(&mx);
for(i = 1; i <num_msg-1; i++)
pthread_cancel(threads[i]);
endwin();
return 0;
}
void set_up(){
init_ball();
initscr();
noecho();
crmode();
clear();
signal(SIGINT, SIG_IGN);
mvaddstr(5, 9, "SCORE: ");
mvaddstr(5, 16, "0");
add_boundary();
add_road();
mvaddch(the_ball.y_pos, the_ball.x_pos, the_ball.symbol);
refresh();
}
int set_up_obs(struct obstacle the_obstacle[]){
int num_msg = 6;
int i;
srand(getpid());
for(i = 1; i < num_msg-1; i++){
the_obstacle[i].str = OBS_SYMBOL;
the_obstacle[i].row = X_INIT-(2*i+2);
the_obstacle[i].delay = 1+(rand()%15);
the_obstacle[i].dir = ((rand()%2)?1:-1);
}
return num_msg;
}
void init_ball(){
the_ball.y_pos = Y_INIT;
the_ball.x_pos = X_INIT;
the_ball.y_dir = 0;
the_ball.x_dir = 0;
the_ball.symbol = BALL_SYMBOL;
}
void *animate(void *arg){
struct obstacle *info = arg;
int len = strlen(info->str)+2;
int col = LEFT_EDGE+2;
while(1)
{
usleep(info->delay*TIME);
pthread_mutex_lock(&mx);
move(info->row, col);
addch(' ');
addstr(info->str);
addch(' ');
move(LINES-1, COLS-1);
refresh();
pthread_mutex_unlock(&mx);
col += info->dir;
if(col == LEFT_EDGE+1 && info->dir == -1)
info->dir = 1;
else if(col+len>=RIGHT_EDGE && info->dir == 1 )
info->dir = -1;
}
}
void add_boundary(){
int i;
for(i=LEFT_EDGE+1; i<RIGHT_EDGE; i+=2) mvaddch(TOP_ROW, i, BNDR_SYMBOL);
for(i=LEFT_EDGE+1; i<RIGHT_EDGE; i+=2) mvaddch(BOT_ROW, i, BNDR_SYMBOL);
for(i=TOP_ROW+1; i<BOT_ROW; i++) mvaddch(i, LEFT_EDGE, BNDR_SYMBOL);
for(i=TOP_ROW+1; i<BOT_ROW; i++) mvaddch(i, RIGHT_EDGE, BNDR_SYMBOL);
}
void add_road(){
int i;
for(i=11; i<20; i+=2) mvaddstr(i, 10, ROAD_SYMBOL);
}
void ball_move(){
int y_cur, x_cur;
static int back_cnt = 0;
static int score = 0;
char str_score[3];
y_cur = the_ball.y_pos;
x_cur = the_ball.x_pos;
within_boundary(&the_ball);
if(y_cur < the_ball.y_pos)
back_cnt++;
else if(y_cur > the_ball.y_pos){
if(back_cnt > 0)
back_cnt--;
else if(back_cnt == 0){
score++;
sprintf(str_score, "%d", score);
mvaddstr(5, 16, " ");
mvaddstr(5, 16, str_score);
}
}
mvaddch(y_cur, x_cur, BLANK);
mvaddch(the_ball.y_pos, the_ball.x_pos, the_ball.symbol);
move(LINES-1, COLS-1);
refresh();
}
void within_boundary(struct ppball *bp){
int y, x;
y = bp->y_pos + bp->y_dir;
x = bp->x_pos + bp->x_dir;
if(y>TOP_ROW && y<BOT_ROW && x>LEFT_EDGE && x<RIGHT_EDGE){
bp->y_pos = y;
bp->x_pos = x;
}
}
| 1
|
#include <pthread.h>
buffer_item buffer[6];
int index_counter = 0;
void *thread_Insert(void *arg);
void *thread_Remove(void *arg);
sem_t bin_sem;
pthread_mutex_t mutx;
char thread1[]="Thread A";
char thread2[]="Thread B";
char thread3[]="Thread C";
int main(int argc, char **argv)
{
pthread_t t1, t2, t3;
void *thread_result;
int state1, state2;
state1 = pthread_mutex_init(&mutx, 0);
state2 = sem_init(&bin_sem, 0 ,0);
if(state1||state2!=0)
puts("Error mutex & semaphore initialization!!!");
pthread_create(&t1, 0, thread_Insert, &thread1);
pthread_create(&t2, 0, thread_Remove, &thread2);
pthread_create(&t3, 0, thread_Remove, &thread3);
pthread_join(t1, &thread_result);
pthread_join(t2, &thread_result);
pthread_join(t3, &thread_result);
printf("Terminate => %s, %s, %s!!!\\n", &thread1, &thread2, &thread3);
printf("Final Index: %d\\n", index_counter);
sem_destroy(&bin_sem);
pthread_mutex_destroy(&mutx);
return 0;
}
void *thread_Insert(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0;i<6;i++)
{
pthread_mutex_lock(&mutx);
if(index_counter<6)
{
buffer[index_counter] = index_counter;
index_counter++;
printf("%s: INSERT item to BUFFER %d\\n", (char*)arg, index_counter);
sem_post(&bin_sem);
}
else
{
sleep(2);
}
pthread_mutex_unlock(&mutx);
}
}
void *thread_Remove(void *arg)
{
int i;
printf("Creating Thread: %s\\n", (char*)arg);
for(i=0;i<6/2;i++)
{
sem_wait(&bin_sem);
pthread_mutex_lock(&mutx);
sleep(1);
printf("%s: REMOVE item from BUFFER %d\\n", (char*)arg, index_counter);
buffer[index_counter] = 0;
index_counter--;
pthread_mutex_unlock(&mutx);
}
}
| 0
|
#include <pthread.h>
char name[100];
char search[100];
pthread_t tid;
int *cont;
int nt;
} mystruct;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t sig;
void* sfun(void *arg){
mystruct *sfile= (mystruct *) arg;
int fd=open(sfile->name,O_RDONLY);
if(fd<0){
printf("Erro a abrir ficheiro %s\\n", sfile->name);
pthread_exit(0);
}
int n=1;
pthread_mutex_lock(&mutex);
while(n!=0){
n=match_line(fd,sfile->search);
if(n!=0)
printf("%s:\\t%d\\n",sfile->name,n);
}
++*(sfile->cont);
if(*(sfile->cont)==sfile->nt)
pthread_cond_signal(&sig);
pthread_mutex_unlock(&mutex);
close(fd);
pthread_exit(0);
return 0;
}
int main(int argc, char *argv[]){
if(argc<3){
printf("Erro, foram passados menos que 3 argumentos\\n");
exit(1);
}
mystruct file[10];
int c;
int conta=0;
for(c=0;c<argc-2;c++){
strcpy(file[c].search,argv[1]);
strcpy(file[c].name,argv[c+2]);
file[c].cont=&conta;
file[c].nt=argc-2;
pthread_create(&file[c].tid,0,sfun,&file[c]);
pthread_detach(file[c].tid);
}
pthread_cond_wait(&sig,&condition);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&condition);
return 0;
}
| 1
|
#include <pthread.h>
static char *page;
static int page_nr = 10;
static int page_len;
static pthread_mutex_t _syscall_mtx;
void usage(const char *argv0)
{
fprintf(stderr, "usage:%s ip port num_page\\n", argv0);
exit(1);
}
static void recover(void)
{
printf("hello: recovered from pagefault\\n");
exit(0);
}
static void pgflt_handler(uintptr_t addr, uint64_t fec, struct dune_tf *tf)
{
int ret;
ptent_t *pte;
pthread_mutex_lock(&_syscall_mtx);
ret = dune_vm_lookup(pgroot, (void *) addr, CREATE_NORMAL, &pte);
assert(ret==0);
long offset = 0;
*pte = PTE_P | PTE_W | PTE_ADDR(dune_va_to_pa((void *) addr));
rdma_read_offset((void *)addr, (__u64)addr - (__u64) page );
pthread_mutex_unlock(&_syscall_mtx);
}
int main(int argc, char *argv[])
{
int i,n;
volatile int ret;
char* val;
struct timeval t0, t1, t2, t3;
ret = dune_init_and_enter();
if (ret) {
printf("failed to initialize dune\\n");
return ret;
}
dune_register_pgflt_handler(pgflt_handler);
if (argc != 4){
usage(argv[0]);
}
page_nr = atoi(argv[3]);
page_len = ( 1<<12 )*page_nr;
rdma_init(argv[1], argv[2] , ( 1<<12 ));
gettimeofday(&t0, 0);
if (posix_memalign((void **)&page, ( 1<<12 ), page_len)) {
perror("init page memory failed");
return -1;
}
memset( page,0, page_len);
val= (char*) malloc(page_len);
memcpy(val, page, page_len);
pthread_mutex_lock(&_syscall_mtx);
for (i=0; i<page_nr; i++)
rdma_write_offset( &page[i*( 1<<12 )], i*( 1<<12 ));
dune_vm_unmap(pgroot, (void *)page, page_len);
pthread_mutex_unlock(&_syscall_mtx);
gettimeofday(&t1, 0);
assert(!memcmp(val, page, page_len));
gettimeofday(&t2, 0);
rdma_done();
long pagefault = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
long total = (t2.tv_sec-t0.tv_sec)*1000000 + t2.tv_usec-t0.tv_usec;
fprintf(stdout, "%ld\\t%ld\\n", pagefault, total);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void* ptr;
} reaction_struct;
static reaction_struct x;
static reaction_struct y;
static bool even = 1;
static bool mutex_even = 0;
INIT_REACTION()
{
pthread_mutex_init(&x.mutex, 0);
pthread_mutex_init(&y.mutex, 0);
pthread_mutex_lock(&y.mutex);
x.ptr = malloc(27);
}
START_DEGRADATION(complex)
{
even = !even;
mutex_even = !mutex_even;
}
MECHANISM(double_free)
{
if (even)
{
free(x.ptr);
y.ptr = malloc(27);
}
else
{
free(y.ptr);
x.ptr = malloc(27);
}
even = !even;
return first;
}
MECHANISM(mutex_lock)
{
if (mutex_even)
{
pthread_mutex_unlock(&x.mutex);
pthread_mutex_lock(&y.mutex);
}
else
{
pthread_mutex_unlock(&y.mutex);
pthread_mutex_lock(&x.mutex);
}
mutex_even = !mutex_even;
return first;
}
| 1
|
#include <pthread.h>
pthread_mutex_t the_mutex;
pthread_cond_t condc,condp;
int buffer=0;
int total=0;
void *producer(void *ptr)
{
int i=1;
while(total<50)
{
pthread_mutex_lock(&the_mutex);
printf("生产者%lu第%d次使用缓冲区\\n",pthread_self(),i);
while(buffer==10&&total<50)
{
printf("生产者%lu等待消费者消费\\n",pthread_self());
pthread_cond_wait(&condp,&the_mutex);
}
buffer++;
printf("%d\\n",buffer);
pthread_cond_broadcast(&condc);
pthread_mutex_unlock(&the_mutex);
printf("生产者%lu第%d次释放缓冲区\\n",pthread_self(),i);
i++;
}
pthread_exit(0);
}
void *consumer(void *ptr)
{
int i=1;
while(total<50)
{
pthread_mutex_lock(&the_mutex);
printf("消费者%lu第%d次使用缓冲区\\n",pthread_self(),i);
while(buffer==0&&total<50)
{
printf("消费者%lu等待生产者生产\\n",pthread_self());
pthread_cond_wait(&condc,&the_mutex);
}
buffer--;
total++;
printf("%d\\n",buffer);
pthread_cond_broadcast(&condp);
pthread_mutex_unlock(&the_mutex);
printf("消费者%lu第%d次释放缓冲区\\n",pthread_self(),i);
i++;
}
pthread_cond_broadcast(&condp);
pthread_exit(0);
}
int main()
{
pthread_t pro1,pro2,pro3,con1,con2;
pthread_mutex_init(&the_mutex,0);
pthread_cond_init(&condc,0);
pthread_cond_init(&condp,0);
pthread_create(&pro1,0,producer,0);
pthread_create(&pro2,0,producer,0);
pthread_create(&pro3,0,producer,0);
pthread_create(&con1,0,consumer,0);
pthread_create(&con2,0,consumer,0);
pthread_join(pro1,0);
pthread_join(pro2,0);
pthread_join(pro3,0);
pthread_join(con1,0);
pthread_join(con2,0);
pthread_cond_destroy(&condc);
pthread_cond_destroy(&condp);
pthread_mutex_destroy(&the_mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_barrier_t barrier1;
int SharedVariable = 0;
void *SimpleThread(void *args)
{
int num,val;
int which = (int)args;
for(num = 0; num < 20; num++) {
pthread_mutex_lock(&mutex1);
val = SharedVariable;
printf("*** thread %d sees value %d\\n", which, val);
SharedVariable = val + 1;
pthread_mutex_unlock(&mutex1);
}
pthread_barrier_wait(&barrier1);
val = SharedVariable;
printf("Thread %d sees final value %d\\n", which, val);
return 0;
}
int main (int argc, char *argv[])
{
int num_threads = argc > 1 ? atoi(argv[1]) : 0;
if (num_threads > 0) {
pthread_t threads[num_threads];
int rc;
long t;
rc = pthread_barrier_init(&barrier1, 0, num_threads);
if (rc) {
fprintf(stderr, "pthread_barrier_init: %s\\n", strerror(rc));
exit(1);
}
for (t = 0; t < num_threads; t++) {
printf("In main: creating thread %ld\\n", t);
rc = pthread_create(&threads[t], 0, SimpleThread, (void * )t);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
}
}
for (t = 0; t < num_threads; t++) {
pthread_join(threads[t], 0);
}
}
else {
printf("ERROR: The parameter should be a valid positive number.\\n");
exit(-1);
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t stats = PTHREAD_MUTEX_INITIALIZER;
unsigned int reqCount = 0, reqAccepted = 0, reqRefused = 0,localReqReplied = 0, externReqReplied = 0;
struct tm startTime;
struct tm lastUpdateTime;
int fd;
void exit_stats()
{
printf("Exited stats manager, %d\\n",getpid());
close(fd);
exit(0);
}
void show_stats()
{
pthread_mutex_lock(&stats);
printf("Server start time %d:%d:%d\\n",startTime.tm_hour, startTime.tm_min, startTime.tm_sec);
printf(" -Total requests: %d\\n",reqCount);
printf(" -Total accepted requests: %d\\n",reqAccepted);
printf(" -Total refused requests: %d\\n",reqRefused);
printf(" -Total local requests replied to: %d\\n",localReqReplied);
printf(" -Total external requests replied to: %d\\n",externReqReplied);
printf(" -Time of last information update: %d:%d:%d\\n",lastUpdateTime.tm_hour, lastUpdateTime.tm_min, lastUpdateTime.tm_sec);
pthread_mutex_unlock(&stats);
}
void *show_stats_time(void* args)
{
while(1)
{
sleep(30);
show_stats();
}
}
void updateTime()
{
time_t t = time(0);
struct tm *currentTime;
currentTime = localtime(&t);
lastUpdateTime.tm_hour = currentTime->tm_hour;
lastUpdateTime.tm_min = currentTime->tm_min;
lastUpdateTime.tm_sec = currentTime->tm_sec;
}
void stats_manager_main(struct configuration *config)
{
pthread_t showStats;
time_t t = time(0);
struct tm *currentTime;
char recv;
pthread_create(&showStats,0,show_stats_time,0);
currentTime = localtime(&t);
startTime.tm_hour = currentTime->tm_hour;
startTime.tm_min = currentTime->tm_min;
startTime.tm_sec = currentTime->tm_sec;
if((fd = open(config->stats_pipe, O_RDONLY)) == -1 )
printf("Error opening stats pipe for reading, errno n %d\\n",errno);
signal(SIGUSR2, exit_stats);
signal(SIGUSR1, show_stats);
while(1)
{
read(fd,&recv,1);
pthread_mutex_lock(&stats);
switch(recv)
{
case 0: {
reqCount++;
updateTime();
}break;
case 1: {
reqAccepted++;
updateTime();
}break;
case 2: {
reqRefused++;
updateTime();
}break;
case 3: {
localReqReplied++;
updateTime();
}break;
case 4: {
externReqReplied++;
updateTime();
}break;
}
pthread_mutex_unlock(&stats);
}
}
| 0
|
#include <pthread.h>
int * px = 0;
int * py = 0;
pthread_mutex_t mutex_px = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex_py = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_fin12 = PTHREAD_COND_INITIALIZER;
void * mon_thread1 (void * arg){
int i;
printf("[Thread1] Deb\\n");
for (i=0;i<*(int*)arg;i++){
pthread_mutex_lock(&mutex_px);
printf("[Thread1] Valeur px: %d\\n", *px);
pthread_mutex_unlock(&mutex_px);
usleep(100);
}
printf("[Thread1]Fin\\n");
pthread_exit(0);
return 0;
}
void * mon_thread2 (void * arg){
int i;
printf("[Thread2] Deb\\n");
for (i=0;i<*(int*)arg;i++){
pthread_mutex_lock(&mutex_py);
printf("[Thread2] Valeur py: %d\\n", *py);
pthread_mutex_unlock(&mutex_py);
usleep(100);
}
printf("[Thread2] Fin\\n");
pthread_exit(0);
return 0;
}
int main(){
int x = 1;
int y = 2;
pthread_t tid1,tid2;
int max = 5;
int i = 0;
px = &x;
py = &y;
pthread_create(&tid1, 0, mon_thread1, &max);
pthread_create(&tid2, 0, mon_thread2, &max);
usleep(100);
while(i<max){
pthread_mutex_lock(&mutex_px);
if (pthread_mutex_trylock(&mutex_py) != 0){
printf("[Thread main] Lock px py\\n");
px = 0;
py = 0;
printf("[Thread main] Valeur i: %d\\n", i);
px = &x;
py = &y;
i++;
pthread_mutex_unlock(&mutex_py);
}
pthread_mutex_unlock(&mutex_px);
usleep(100);
}
pthread_exit(0) ;
printf("Fin main\\n");
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t _parcAtomicInteger_PthreadMutex = PTHREAD_MUTEX_INITIALIZER;
uint32_t
parcAtomicInteger_Uint32IncrementPthread(uint32_t *value)
{
pthread_mutex_lock(&_parcAtomicInteger_PthreadMutex);
*value = *value + 1;
uint32_t result = *value;
pthread_mutex_unlock(&_parcAtomicInteger_PthreadMutex);
return result;
}
uint32_t
parcAtomicInteger_Uint32DecrementPthread(uint32_t *value)
{
pthread_mutex_lock(&_parcAtomicInteger_PthreadMutex);
*value = *value - 1;
uint32_t result = *value;
pthread_mutex_unlock(&_parcAtomicInteger_PthreadMutex);
return result;
}
uint64_t
parcAtomicInteger_Uint64IncrementPthread(uint64_t *value)
{
pthread_mutex_lock(&_parcAtomicInteger_PthreadMutex);
*value = *value + 1;
uint64_t result = *value;
pthread_mutex_unlock(&_parcAtomicInteger_PthreadMutex);
return result;
}
uint64_t
parcAtomicInteger_Uint64DecrementPthread(uint64_t *value)
{
pthread_mutex_lock(&_parcAtomicInteger_PthreadMutex);
*value = *value - 1;
uint64_t result = *value;
pthread_mutex_unlock(&_parcAtomicInteger_PthreadMutex);
return result;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
sem_t isEmpty;
char val;
struct Node *next;
struct Node *prev;
}Elemento;
{
Elemento *inicio;
Elemento *fin;
int tamanho;
}LL;
Lista T;
void init(Lista * lista);
int insercion(Lista * lista, char *dato);
char supresion(Lista * lista, int pos);
void *productor(){
while(1){
pthread_mutex_lock(&mutex);
char c = (char)('a' + rand()%26);
int pos = insercion(&T, &c);
printf(">> insertado: %c en la posicion %d\\n", c, pos);
pthread_mutex_unlock(&mutex);
sleep(1);
sem_post(&isEmpty);
}
}
void *consumidor(){
while(1){
sem_wait(&isEmpty);
pthread_mutex_lock(&mutex);
int pos = 1 + rand()%((T)->tamanho);
char c = supresion(&T, 1);
printf("<< suprimido: %c de la posicion %d\\n", c, pos);
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(){
init(&T);
pthread_t productor1;
pthread_t productor2;
pthread_t productor3;
pthread_t consumidor1;
pthread_t consumidor2;
pthread_t consumidor3;
pthread_mutex_init(&mutex, 0);
sem_init(&isEmpty, 0, 0);
pthread_create(&productor1, 0, &productor, 0);
pthread_create(&productor2, 0, &productor, 0);
pthread_create(&consumidor1, 0, &consumidor, 0);
pthread_create(&consumidor2, 0, &consumidor, 0);
pthread_create(&consumidor3, 0, &consumidor, 0);
pthread_join(productor1, 0);
}
void init(Lista * lista){
*lista = malloc(sizeof(lista));
Elemento *p = malloc(sizeof(Elemento));
(*lista)->inicio = p;
((*lista)->inicio)->next = 0;
((*lista)->inicio)->prev = 0;
Elemento *q = malloc(sizeof(Elemento));
(*lista)->fin = q;
((*lista)->fin)->next = 0;
((*lista)->fin)->prev = 0;
(*lista)->tamanho = 0;
}
int insercion(Lista * lista, char *dato)
{
Elemento *p = malloc(sizeof(Elemento));
p->val = *dato;
p->next = 0;
p->prev = (*lista)->fin;
((*lista)->fin)->next = p;
(*lista)->fin = p;
if((*lista)->tamanho == 0){
(*lista)->inicio = p;
p->prev = (*lista)->inicio;
}
(*lista)->tamanho += 1;
return (*lista)->tamanho;
}
char supresion(Lista * lista, int pos){
Elemento *p = malloc(sizeof(Elemento));
Elemento *q = malloc(sizeof(Elemento));
p = (*lista)->inicio;
q = 0;
pos--;
while(pos>0){
q = p;
p = p->next;
pos--;
}
char r;
r = p->val;
if(p->next != 0)
(p->next)->prev = q;
if(q == 0)
(*lista)->inicio = p->next;
else
q->next = p->next;
(*lista)->tamanho -= 1;
return r;
}
| 1
|
#include <pthread.h>
inline void worker_queue_lock(struct worker_queue *worker_queue) {
pthread_mutex_lock(&worker_queue->mutex);
}
inline void worker_queue_unlock(struct worker_queue *worker_queue) {
pthread_mutex_unlock(&worker_queue->mutex);
}
inline void worker_queue_wakeup_all(struct worker_queue *worker_queue) {
pthread_cond_broadcast(&worker_queue->cond);
}
inline void worker_queue_wakeup_one(struct worker_queue *worker_queue) {
pthread_cond_signal(&worker_queue->cond);
}
inline void worker_queue_wait(struct worker_queue *worker_queue) {
pthread_cond_wait(&worker_queue->cond, &worker_queue->mutex);
}
static void *worker_run(void *ctx)
{
struct worker *worker = (struct worker*)ctx;
struct worker_queue *worker_queue = worker->worker_queue;
struct job *job;
while (1)
{
worker_queue_lock(worker_queue);
while (!worker_queue->job_list) {
if (worker->terminated) break;
worker_queue_wait(worker_queue);
}
if (worker->terminated) break;
job = worker_queue->job_list;
if (job) {
{ if (job->prev) job->prev->next = job->next; if (job->next) job->next->prev = job->prev; if (worker_queue->job_list == job) worker_queue->job_list = job->next; job->prev = job->next = 0; };
}
worker_queue_unlock(worker_queue);
if (!job) continue;
job->run(job);
}
free(worker);
pthread_exit(job);
}
int worker_queue_init(struct worker_queue *worker_queue, int num_workers)
{
int i;
struct worker *worker;
if (num_workers < 1) num_workers = 1;
memset(worker_queue, 0, sizeof(struct worker_queue));
pthread_mutex_init(&worker_queue->mutex, 0);
pthread_cond_init(&worker_queue->cond, 0);
for (i=0; i<num_workers; i++) {
worker = (struct worker *)malloc(sizeof(struct worker));
if (!worker) {
perror("worker_queue_init()");
return -1;
}
memset(worker, 0, sizeof(struct worker));
worker->worker_queue = worker_queue;
if (pthread_create(&worker->pid, 0, worker_run, (void *)worker)) {
perror("pthread_create()");
free(worker);
return -1;
}
{ worker->prev = 0; worker->next = worker_queue->worker_list; worker_queue->worker_list = worker; };
}
return 0;
}
void worker_queue_shutdown(struct worker_queue *worker_queue)
{
struct worker *worker;
for (worker = worker_queue->worker_list;
worker != 0;
worker = worker->next) {
worker->terminated = 1;
}
worker_queue_lock(worker_queue);
{
worker_queue->worker_list = 0;
worker_queue->job_list = 0;
worker_queue_wakeup_all(worker_queue);
}
worker_queue_unlock(worker_queue);
}
void worker_queue_add_job(struct worker_queue *worker_queue, struct job *job)
{
worker_queue_lock(worker_queue);
{
{ job->prev = 0; job->next = worker_queue->job_list; worker_queue->job_list = job; };
worker_queue_wakeup_one(worker_queue);
}
worker_queue_unlock(worker_queue);
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
void prepare(void)
{
printf("prepareing locks...... \\n");
pthread_mutex_lock(&lock1);
pthread_mutex_lock(&lock2);
}
void parent(void)
{
printf("parent unlocking...... \\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void child(void)
{
printf("child unlocking .... \\n");
pthread_mutex_unlock(&lock1);
pthread_mutex_unlock(&lock2);
}
void *thr_fn(void *arg)
{
printf("thread started ... \\n");
pause();
return 0;
}
int main(void)
{
int err;
pid_t pid;
pthread_t tid;
if ((err = pthread_atfork(prepare,parent,child)) < 0) {
err_exit(err,"can't install fork handlers.");
}
err = pthread_create(&tid,0,thr_fn,0);
if (err != 0) {
err_exit(err,"can't create thread");
}
sleep(2);
printf("partent about to fork...\\n");
if ((pid = fork()) <0) {
err_quit("fork failed");
} else if(0 == pid) {
printf("child returned from fork\\n");
} else {
printf("partent returned from fork\\n");
}
exit(0);
}
| 1
|
#include <pthread.h>
void * whattodo( void * arg );
void critical_section( int time );
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
pthread_t tid[ 8 ];
int i, rc;
int * t;
for ( i = 0 ; i < 8; i++ )
{
t = (int *)malloc( sizeof( int ) );
*t = 2 + i * 2;
printf( "MAIN: Next thread will nap for %d seconds.\\n", *t );
rc = pthread_create( &tid[i], 0, whattodo, t );
if ( rc != 0 )
{
fprintf( stderr, "MAIN: Could not create child thread (%d)\\n", rc );
}
}
for ( i = 0 ; i < 8 ; i++ )
{
unsigned int * x;
pthread_join( tid[i], (void **)&x );
printf( "MAIN: Joined a child thread that returned %u.\\n", *x );
free( x );
}
printf( "MAIN: All threads successfully joined.\\n" );
return 0;
}
void critical_section( int time )
{
printf( "THREAD %u: Entering my critical section.\\n",
(unsigned int)pthread_self() );
sleep( time );
printf( "THREAD %u: Leaving my critical section.\\n",
(unsigned int)pthread_self() );
}
void * whattodo( void * arg )
{
int t = *(int *)arg;
free( arg );
printf( "THREAD %u: I'm gonna nap for %d seconds.\\n",
(unsigned int)pthread_self(), t );
pthread_mutex_lock( &mutex );
critical_section( t );
pthread_mutex_unlock( &mutex );
unsigned int * x = (unsigned int *)malloc( sizeof( unsigned int ) );
*x = pthread_self();
pthread_exit( x );
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t getpw_mutex = PTHREAD_MUTEX_INITIALIZER;
static int
convert (struct passwd *ret, struct passwd *result,
char *buf, int buflen)
{
int len;
if (!buf) return -1;
*result = *ret;
result->pw_name = (char *) buf;
len = strlen (ret->pw_name) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->pw_name, ret->pw_name);
result->pw_passwd = (char *) buf;
len = strlen (ret->pw_passwd) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->pw_passwd, ret->pw_passwd);
result->pw_gecos = (char *) buf;
len = strlen (ret->pw_gecos) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->pw_gecos, ret->pw_gecos);
result->pw_dir = (char *) buf;
len = strlen (ret->pw_dir) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->pw_dir, ret->pw_dir);
result->pw_shell = (char *) buf;
len = strlen (ret->pw_shell) + 1;
if (len > buflen) return -1;
buflen -= len;
buf += len;
strcpy (result->pw_shell, ret->pw_shell);
return 0;
}
int getpwnam_r (const char *name, struct passwd *result,
char *buffer, size_t buflen,
struct passwd ** resptr)
{
struct passwd * p;
int retval;
pthread_mutex_lock (&getpw_mutex);
p = getpwnam (name);
if (p == 0) {
*resptr = 0;
retval = ESRCH;
} else
if (convert (p, result, buffer, buflen) != 0) {
*resptr = 0;
retval = ERANGE;
} else {
*resptr = result;
retval = 0;
}
pthread_mutex_unlock (&getpw_mutex);
return retval;
}
int getpwuid_r (uid_t uid, struct passwd *result,
char *buffer, size_t buflen,
struct passwd ** resptr)
{
struct passwd * p;
int retval;
pthread_mutex_lock (&getpw_mutex);
p = getpwuid (uid);
if (p == 0) {
*resptr = 0;
retval = ESRCH;
} else
if (convert (p, result, buffer, buflen) != 0) {
*resptr = 0;
retval = ERANGE;
} else {
*resptr = result;
retval = 0;
}
pthread_mutex_unlock (&getpw_mutex);
return retval;
}
| 1
|
#include <pthread.h>
int recordSize = 1024;
int threadsNr;
char *fileName;
int fd;
int numOfRecords;
int creatingFinished = 0;
char *word;
int rc;
int someonefound = 0;
int detachedNr = 0;
pthread_key_t key;
pthread_t *threads;
int *wasJoin;
pthread_mutex_t mutexForRecords = PTHREAD_MUTEX_INITIALIZER;
long gettid() {
return syscall(SYS_gettid);
}
void signalHandler(int signal){
if(signal == SIGUSR1) {
printf("Received SIGUSR1\\n");
} else if(signal == SIGTERM) {
printf("Received SIGTERM\\n");
}
printf("PID: %d TID: %ld\\n", getpid(), pthread_self());
return;
}
void* threadFun(void *oneArg)
{
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
pthread_t threadHandle = pthread_self();
pthread_t threadID = gettid();
printf("new thread with handle: %ld with tid: %ld\\n", threadHandle,threadID);
char **readRecords;
readRecords = calloc(numOfRecords, sizeof(char*));
for(int i = 0;i<numOfRecords;i++)
readRecords[i] = calloc(1024, sizeof(char));
pthread_setspecific(key, readRecords);
readRecords = pthread_getspecific(key);
while(!creatingFinished);
int finish = 0;
int moreBytesToRead = 1;
int numOfReadedBytes;
while(!finish && moreBytesToRead)
{
pthread_mutex_lock(&mutexForRecords);
for(int i=0;i<numOfRecords;i++)
{
numOfReadedBytes = read(fd, readRecords[i], 1024);
if(numOfReadedBytes==-1)
{
perror("error while reading in threadFun");
exit(1);
}
if(numOfReadedBytes<1024)
moreBytesToRead = 0;
}
pthread_mutex_unlock(&mutexForRecords);
for(int i = 0; i<numOfRecords; i++)
{
if(strstr(readRecords[i], word) != 0)
{
char recID[10];
strncpy(recID, readRecords[i], 10);
printf("%ld: found word in record number %d\\n", threadID, atoi(recID));
}
}
}
if(pthread_detach(threadHandle) != 0)
{
perror("pthread_detach error");
exit(1);
}
detachedNr++;
pthread_exit(0);
}
int openFile(char *fileName)
{
int fd = open(fileName, O_RDONLY);
if(fd == -1)
{
perror("file open error");
exit(-1);
}
else
return fd;
}
void createThread(pthread_t *thread)
{
rc = pthread_create(thread, 0, threadFun, 0);
if(rc != 0)
{
perror("thread create error");
exit(-1);
}
}
int main(int argc, char *argv[])
{
if(argc!=6)
{
puts("Bad number of arguments");
puts("Appropriate arguments:");
printf("[program] [threads nr] [file] \\n");
printf("[records nr] [word to find] [test nr]");
return 1;
}
printf("MAIN -> PID: %d TID: %ld\\n", getpid(), pthread_self());
threadsNr = atoi(argv[1]);
fileName = calloc(1,sizeof(argv[2]));
fileName = argv[2];
numOfRecords = atoi(argv[3]);
word = calloc(1,sizeof(argv[4]));
word = argv[4];
int test = atoi(argv[5]);
if(test != 1 && test != 2)
{
puts("wrong test number");
exit(1);
}
fd = openFile(fileName);
char **readRecords = calloc(numOfRecords, sizeof(char*));
for(int i = 0;i<numOfRecords;i++)
readRecords[i] = calloc(1024, sizeof(char));
pthread_key_create(&key, 0);
threads = calloc(threadsNr, sizeof(pthread_t));
wasJoin = calloc(threadsNr, sizeof(int));
for(int i=0; i<threadsNr; i++)
{
createThread(&threads[i]);
}
creatingFinished = 1;
usleep(100);
if(test == 1)
{
puts("sending SIGUSR1 signal");
signal(SIGUSR1, signalHandler);
kill(getpid(),SIGUSR1);
}
if(test == 2)
{
puts("sending SIGTERM signal");
signal(SIGTERM, signalHandler);
kill(getpid(),SIGTERM);
}
while(detachedNr != threadsNr)
{
usleep(100);
}
printf("End of program\\n\\n");
if(close(fd)<0)
{
perror("close error");
return 1;
}
free(threads);
return 0;
}
| 0
|
#include <pthread.h>
long* a;
long sum;
int veclen;
} CommonData;
CommonData data;
pthread_t threads[4];
pthread_mutex_t mutex;
void* calc(void* arg);
int main (int argc, char *argv[]){
long i, sum = 0;
void* status;
long* a = (long*) malloc (4*100*sizeof(long));
pthread_attr_t attr;
int rc;
for (i=0; i<100*4; i++) {
a[i] = i;
sum += i;
}
data.veclen = 100;
data.a = a;
data.sum = 0;
pthread_mutex_init(&mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++){
rc = pthread_create(&threads[i], 0, calc, (void*)i);
if (rc){
printf("Return code: %d\\n", rc);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(i=0;i<4;i++) {
pthread_join(threads[i], &status);
}
printf ("Correct result is: %ld \\n", sum);
printf ("Function result is: %ld \\n", data.sum);
free (a);
pthread_mutex_destroy(&mutex);
return 0;
}
void* calc(void* arg)
{
int id = (int)arg;
long* x = data.a;
long mysum = 0;
int i;
int start, end;
start = x[id * 100];
end = start + 100;
for (i=start;i<end;i++){
mysum += x[i];
}
pthread_mutex_lock(&mutex);
data.sum += mysum;
pthread_mutex_unlock(&mutex);
pthread_exit((void*) 0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t exclusion;
int sum = 0;
void *computeThread(void *arg) {
int nr = *(int *) arg;
printf("Receiving: %d\\n", nr);
pthread_mutex_lock(&exclusion);
sum += nr;
pthread_mutex_unlock(&exclusion);
free(arg);
}
int main(int argc, char *argv[]) {
pthread_t threads[100];
if(pthread_mutex_init(&exclusion, 0) != 0) {
perror("Error creating mutex");
exit(1);
}
int i;
for(i = 1; i < argc; i++) {
int j, nr = 0;
char auxp[100];
strcpy(auxp, argv[i]);
for(j = 0; j < strlen(auxp); j++)
nr = nr * 10 + auxp[j] - '0';
int *toSend = malloc(sizeof(int));
*toSend = nr;
printf("Sending: %d\\n", nr);
pthread_create(&threads[i], 0, computeThread, toSend);
}
for(i = 1; i < argc; i++) {
pthread_join(threads[i], 0);
}
pthread_mutex_destroy(&exclusion);
printf("Result: %d\\n", sum);
}
| 0
|
#include <pthread.h>
void join_threads(pthread_t *, int);
void spawn_threads(pthread_t *, int);
void initialize(int *, int, char *[]);
void * collatz(void *);
int compute_stopping_time(unsigned int);
void generate_csv();
int HISTOGRAM[1000];
int COUNTER = 2;
int COLLATZ_UPPER;
int MEMO[1000000];
pthread_mutex_t count_mutex;
pthread_mutexattr_t count_mtr;
pthread_mutexattr_t memo_mtr;
pthread_mutex_t memo_mutex;
int main(int argc, char *argv[]){
int thread_count;
struct timespec start;
clock_gettime(CLOCK_REALTIME, &start);
initialize(&thread_count, argc, argv);
pthread_t threads[thread_count];
spawn_threads(threads, thread_count);
join_threads(threads, thread_count);
struct timespec end;
clock_gettime(CLOCK_REALTIME, &end);
generate_csv();
double real_time = (end.tv_sec - start.tv_sec) + (double)(end.tv_nsec - start.tv_nsec)/(double)1000000000L;
fprintf(stderr, "%i,%i,%lf\\n",COLLATZ_UPPER, thread_count, real_time);
int i;
int sum = 0;
for (i = 0; i < 1000; i++){
sum += HISTOGRAM[i];
}
fprintf(stderr, "%i\\n", sum);
return 0;
}
void spawn_threads(pthread_t *threads, int thread_count){
int i;
for (i = 0; i < thread_count; i++){
if(pthread_create(&threads[i], 0, collatz, 0) != 0) {
fprintf(stderr, "Error creating thread. Exiting.\\n");
exit(0);
}
}
}
void generate_csv(){
int i;
for (i = 1; i < 1000; i++)
printf("%i,%i\\n", i, HISTOGRAM[i]);
return;
}
void join_threads(pthread_t *threads, int thread_count){
int i;
for (i = 0; i < thread_count; i++){
if(pthread_join(threads[i], 0) != 0) {
fprintf(stderr, "Error joining thread. Exiting.\\n");
exit(0);
}
}
}
void *collatz(void *param){
while(COUNTER < COLLATZ_UPPER){
pthread_mutex_lock(&count_mutex);
int counter = COUNTER;
COUNTER++;
pthread_mutex_unlock(&count_mutex);
int stopping_time = compute_stopping_time((unsigned int) counter);
pthread_mutex_lock(&memo_mutex);
HISTOGRAM[stopping_time]++;
pthread_mutex_unlock(&memo_mutex);
}
pthread_exit(0);
return 0;
}
int compute_stopping_time(unsigned int num){
if (num < 1000000 && MEMO[num] != -1)
return MEMO[num];
int ans = 0;
if (num == 1) return 1;
if (num % 2 == 0)
ans = 1 + compute_stopping_time (num/2);
else
ans = 1 + compute_stopping_time ((3*num)+1);
if (num < 1000000){
pthread_mutex_lock(&memo_mutex);
MEMO[num] = ans;
pthread_mutex_unlock(&memo_mutex);
}
return ans;
}
void initialize(int * thread_count, int argc, char *argv[]){
if (argc < 3){
fprintf(stderr, "Improper amount of arguments. Exiting.\\n");
exit(0);
}
COLLATZ_UPPER =atoi(argv[1]);
*thread_count = atoi(argv[2]);
if (COLLATZ_UPPER == 0 || *thread_count == 0){
fprintf(stderr, "Error on arguments. Exiting.\\n");
exit(0);
}
int i;
for (i = 0; i < 1000; ++i){
HISTOGRAM[i] = 0;
}
for (i = 0; i < 1000000; i++){
MEMO[i] = -1;
}
pthread_mutexattr_init(&count_mtr);
pthread_mutexattr_init(&memo_mtr);
pthread_mutex_init(&count_mutex, &count_mtr);
pthread_mutex_init(&memo_mutex, &memo_mtr);
MEMO[2] = 1;
return;
}
| 1
|
#include <pthread.h>
{
int buf[10];
int in;
int out;
sem_t full;
sem_t empty;
pthread_mutex_t mutex;
} sbuf_t;
sbuf_t shared;
void *Producer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=0; i < 6; i++)
{
item = i;
sem_wait(&shared.empty);
pthread_mutex_lock(&shared.mutex);
shared.buf[shared.in] = item;
shared.in = (shared.in+1)%10;
printf("[P%d] Producing %d ...\\n", index, item);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.full);
if (i % 2 == 1) sleep(1);
}
return 0;
}
void *Consumer(void *arg)
{
int i, item, index;
index = (int)arg;
for (i=6; i > 0; i--) {
sem_wait(&shared.full);
pthread_mutex_lock(&shared.mutex);
item=i;
item=shared.buf[shared.out];
shared.out = (shared.out+1)%10;
printf("[C%d] Consuming %d ...\\n", index, item);
fflush(stdout);
pthread_mutex_unlock(&shared.mutex);
sem_post(&shared.empty);
if (i % 2 == 1) sleep(1);
}
return 0;
}
int main()
{
pthread_t prod, cons;
int i;
sem_init(&shared.full, 0, 0);
sem_init(&shared.empty, 0, 10);
pthread_mutex_init(&shared.mutex, 0);
for (i = 0; i < 5; i++)
{
pthread_create(&prod, 0, Producer, (void*)i);
}
for(i=0; i<5; i++)
{
pthread_create(&cons, 0, Consumer, (void*)i);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t cond;
void * thread1(void * arg)
{
pthread_cleanup_push(pthread_mutex_unlock,&mutex);
while(1){
printf("thread1 is running.\\n");
pthread_mutex_lock(&mutex);
printf("==>there is lock1\\n");
pthread_cond_wait(&cond,&mutex);
printf("thread1 applied the condition.\\n");
pthread_mutex_unlock(&mutex);
sleep(3);
}
pthread_cleanup_pop(0);
}
void * thread2(void * arg)
{
while(1){
printf("thread2 is running\\n");
pthread_mutex_lock(&mutex);
printf("==>there is lock2\\n");
pthread_cond_wait(&cond,&mutex);
printf("thread2 applied the condition.\\n");
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
int main(void)
{
pthread_t tid1,tid2;
printf("condition variable study!\\n");
pthread_mutex_init(&mutex,0);
pthread_cond_init(&cond,0);
pthread_create(&tid1,0,thread1,0);
pthread_create(&tid2,0,thread2,0);
do{
pthread_cond_signal(&cond);
printf(">>>main is going on!\\n");
sleep(1);
}while(1);
sleep(50);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct readerArgs
{
int fd;
size_t number;
};
ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset);
void getCurrentTime(char *str, size_t maxLength);
void* readerFunc(readerArgs *args);
void* writerFunc(void *fd);
void clearResources(int fd);
pthread_mutex_t fileMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t stdoutMutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
int fd = open("File", O_CREAT | O_RDWR | O_TRUNC, 00777);
pthread_t readers[10], writer;
readerArgs args[10];
if (fd == -1)
{
printf("Error: %s", strerror(errno));
clearResources(fd);
return -1;
}
errno = pthread_create(&writer, 0, writerFunc, &fd);
if (errno != 0)
{
printf("Error: %s\\n", strerror(errno));
clearResources(fd);
return -1;
}
for (int i = 0; i < 10; i++)
{
args[i].fd = fd;
args[i].number = i + 1;
errno = pthread_create(readers + i, 0,
(void* (*)(void*)) readerFunc, args + i);
if (errno != 0)
{
printf("Error: %s\\n", strerror(errno));
clearResources(fd);
return -1;
}
}
pthread_join(writer, 0);
for (int i = 0; i < 10; i++)
pthread_join(readers[i], 0);
clearResources(fd);
return 0;
}
ssize_t pgetLine(int fd, char *str, size_t maxLength, off_t offset)
{
char buf[maxLength];
ssize_t retVal = pread(fd, buf, maxLength, offset);
size_t newLinePos;
if (retVal == -1)
return -1;
newLinePos = strcspn(buf, "\\n");
if (newLinePos == strlen(buf))
return 0;
newLinePos++;
strncpy(str, buf, newLinePos);
return newLinePos;
}
void* readerFunc(readerArgs *args)
{
char str[100];
int fd = args->fd;
ssize_t number = args->number, bytesCount;
off_t offset = 0;
do
{
pthread_mutex_lock(&fileMutex);
bytesCount = pgetLine(fd, str, 100, offset);
pthread_mutex_unlock(&fileMutex);
if (bytesCount <= 0)
{
pthread_mutex_lock(&stdoutMutex);
printf("Thread%lu wait for data...\\n", number);
pthread_mutex_unlock(&stdoutMutex);
sleep(1);
continue;
}
offset += bytesCount;
if (strncmp(str, "END", 3) == 0)
break;
pthread_mutex_lock(&stdoutMutex);
printf("Thread%lu %s", number, str);
fflush(stdout);
pthread_mutex_unlock(&stdoutMutex);
if (offset > 100*10)
return 0;
}
while (1);
pthread_mutex_lock(&stdoutMutex);
printf("Thread%lu END\\n", number);
fflush(stdout);
pthread_mutex_unlock(&stdoutMutex);
return 0;
}
void* writerFunc(void *fd)
{
int _fd = *(int*)fd;
char str[100], timeStr[50];
for (int i = 1; i < 10 + 1; i++)
{
getCurrentTime(timeStr, 50);
sprintf(str, "Line %d Current time %s\\n", i, timeStr);
pthread_mutex_lock(&fileMutex);
write(_fd, str, strlen(str));
pthread_mutex_unlock(&fileMutex);
}
pthread_mutex_lock(&fileMutex);
write(_fd, "END\\n", 4);
pthread_mutex_unlock(&fileMutex);
return 0;
}
void getCurrentTime(char *str, size_t maxLength)
{
static struct timeval timer;
gettimeofday(&timer, 0);
strftime(str, maxLength, "%T.", localtime(&timer.tv_sec));
sprintf(str + strlen(str), "%ld", timer.tv_usec);
}
void clearResources(int fd)
{
close(fd);
pthread_mutex_destroy(&fileMutex);
pthread_mutex_destroy(&stdoutMutex);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t notfull = PTHREAD_COND_INITIALIZER;
pthread_cond_t notempty = PTHREAD_COND_INITIALIZER;
int top = 0;
int bottom = 0;
void *produce(void *arg) {
int i;
for (i = 0; i < 5 * 2; i++) {
pthread_mutex_lock(&mutex);
while ((top + 1) % 5 == bottom) {
printf("full! producer is waiting\\n");
pthread_cond_wait(¬full, &mutex);
}
top = (top + 1) % 5;
printf("now top is %d\\n", top);
pthread_cond_signal(¬empty);
pthread_mutex_unlock(&mutex);
}
return (void *)1;
}
void *consume(void *arg) {
int i;
for (i = 0; i < 5 * 2; i++) {
pthread_mutex_lock(&mutex);
while (top % 5 == bottom) {
printf("empty! consumer is waiting\\n");
pthread_cond_wait(¬empty, &mutex);
}
bottom = (bottom + 1) % 5;
printf("now bottom is %d\\n", bottom);
pthread_cond_signal(¬full);
pthread_mutex_unlock(&mutex);
}
return (void *)2;
}
int main(int argc, char *argv[]) {
pthread_t thid1;
pthread_t thid2;
pthread_t thid3;
pthread_t thid4;
int ret1;
int ret2;
int ret3;
int ret4;
pthread_create(&thid1, 0, produce, 0);
pthread_create(&thid2, 0, consume, 0);
pthread_create(&thid3, 0, produce, 0);
pthread_create(&thid4, 0, consume, 0);
pthread_join(thid1, (void **)&ret1);
pthread_join(thid2, (void **)&ret2);
pthread_join(thid3, (void **)&ret3);
pthread_join(thid4, (void **)&ret4);
return 0;
}
| 1
|
#include <pthread.h>
int j;
int tab[10];
}soma;
soma *soma_init(int ide){
soma *p;
p = malloc(sizeof(soma));
p->j=ide;
p->tab[p->j]=ide;
return p;
}
soma *modifier(soma*p1,soma*p2){
p1->tab[p2->j]=p2->j;
return p1;
}
int tabu(soma*p1,int l){
int i;
int s;
for (i=0;i<l+1;i++){
s=s+(p1->tab[i]);
}
s=s-1;
return s;
}
void *hello(void *arg){
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int p;
int *id=(int*)arg;
pthread_mutex_lock(& mutex);
printf("%d:hello world et mon numero est %d\\n",*id,p);
pthread_mutex_unlock(& mutex);
int i;
printf("mon pid est %d\\n",getpid());
printf("%p\\n", (void *) pthread_self());
pthread_exit(0);
}
int main( int argc,char *argv[]){
pthread_t thread[3];
int j=atoi(argv[1]);
int i;
int id[j];
for(i=0;i<j;i++){
id[i]=i;
}
soma *p4=soma_init(j);
soma *p5=soma_init(j-1);
soma*p7=soma_init(j-2);
soma*p8=soma_init(j-3);
soma*p10=modifier(p4,p5);
soma*p11=modifier(p10,p7);
soma*p6=modifier(p11,p8);
int k=tabu(p6,6);
for(i=0;i<j;i++){
printf("Cree thread %d\\n",i);
pthread_create (&thread[i],0,hello,(void *)k);
pthread_join(thread[i],0);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t turn = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cons, prod;
int itens = 100;
void* consumidor() {
while(1) {
pthread_mutex_lock(&turn);
if (itens == 0) pthread_cond_broadcast(&prod);
itens--;
if (itens < 100) pthread_cond_wait(&cons, &turn);
printf("Consumindo 1\\n");
sleep(1);
pthread_mutex_unlock(&turn);
}
}
void* produtor() {
while(1) {
pthread_mutex_lock(&turn);
if (itens == 100) pthread_cond_wait(&prod, &turn);
itens++;
if (itens > 0) pthread_cond_broadcast(&cons);
printf("Produzindo 1\\n");
pthread_mutex_unlock(&turn);
}
}
int main() {
pthread_t consumidores[4];
pthread_t produtores[2];
for (int i = 0; i < 4; i++) {
pthread_create(&consumidores[i], 0, consumidor, 0);
}
for (int i = 0; i < 2; i++) {
pthread_create(&produtores[i], 0, produtor, 0);
}
for (int i = 0; i < 4; i++) {
pthread_join(consumidores[i], 0);
}
for (int i = 0; i < 2; i++) {
pthread_join(produtores[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
struct unit_s
{
pthread_mutex_t rarex;
unsigned int value[1];
};
struct unit_s unit_arr[4];
clock_t time_usage[4];
void *
accessor(void *data)
{
int i;
unsigned int norand = lrand48();
unsigned int value[1];
int thread_number = *(int *)data;
time_usage[thread_number] = -clock();
for (i = 0; i < 2000000/(4*(100 + 1)); ++i) {
int j;
for (j = 0; j < 100; ++j) {
int k = norand % 4;
norand *= 7;
int r;
pthread_mutex_lock(&unit_arr[k].rarex);
memcpy(value, unit_arr[k].value, sizeof(value));
r = memcmp(value, unit_arr[k].value, sizeof(value));
assert(r == 0);
pthread_mutex_unlock(&unit_arr[k].rarex);
}
for (j = 0; j < 1; ++j) {
int k = norand % 4;
norand *= 7;
int l;
int r;
pthread_mutex_lock(&unit_arr[k].rarex);
for (l = 0; l < 1; ++l)
unit_arr[k].value[l] = value[l] = lrand48();
r = memcmp(value, unit_arr[k].value, sizeof(value));
assert(r == 0);
pthread_mutex_unlock(&unit_arr[k].rarex);
}
}
time_usage[thread_number] += clock();
return 0;
}
int main()
{
int i;
pthread_t th[4];
double total_time;
int thread_data[4];
cu_init();
srand48(time(0));
for (i = 0; i < 4; ++i)
pthread_mutex_init(&unit_arr[i].rarex, 0);
for (i = 0; i < 4; ++i) {
thread_data[i] = i;
int err = cu_pthread_create(&th[i], 0, accessor, &thread_data[i]);
if (err != 0) {
i, strerror(err));
return 1;
}
}
total_time = 0.0;
for (i = 0; i < 4; ++i) {
pthread_join(th[i], 0);
total_time += time_usage[i]/(double)CLOCKS_PER_SEC;
}
printf("CPU time: %lg s\\n", total_time);
return 0;
}
| 0
|
#include <pthread.h>
int entradasAbtas=0;
int valvulasAbtas=0;
int abrirentrada=0;
int cerrarentrada=0;
pthread_mutex_t me;
pthread_mutex_t mv;
pthread_cond_t abrirE;
pthread_cond_t cerrarE;
pthread_cond_t vValvula;
void * valvula (void *n){
while(1) {
pthread_mutex_lock(&mv);
while( entradasAbtas<=valvulasAbtas ) {
pthread_cond_wait(&vValvula,&mv);
}
valvulasAbtas++;
pthread_mutex_unlock(&mv);
sleep(3);
pthread_mutex_lock(&mv);
valvulasAbtas--;
pthread_cond_signal(&vValvula);
pthread_mutex_unlock(&mv);
sleep(1);
}
}
void * entrada (void *n){
while(1) {
pthread_mutex_lock(&me);
while(abrirentrada==0 ) {
pthread_cond_wait(&abrirE,&me);
}
abrirentrada=0;
pthread_mutex_lock(&mv);
entradasAbtas++;
pthread_cond_signal(&vValvula);
pthread_mutex_unlock(&mv);
pthread_mutex_unlock(&me);
pthread_mutex_lock(&me);
while(cerrarentrada==0 ) {
pthread_cond_wait(&cerrarE,&me);
}
cerrarentrada=0;
entradasAbtas--;
pthread_mutex_unlock(&me);
}
pthread_exit(0);
}
int main() {
int i;
char resp[10];
pthread_t identrada[3];
pthread_t idvalvula[5];
pthread_mutex_init(&me,0);
pthread_mutex_init(&mv,0);
pthread_cond_init(&abrirE,0);
pthread_cond_init(&cerrarE,0);
pthread_cond_init(&vValvula,0);
for (i=0; i< 5; i++)
pthread_create(&idvalvula[i],0,valvula,0);
for (i=0; i< 3; i++)
pthread_create(&identrada[i],0,entrada,0);
while(1) {
printf ("Ahora hay %d entradas abiertas y %d valvulas abtas\\n",entradasAbtas,valvulasAbtas);
printf ("Si quieres abrir una entrada pulse A si quiere cerrar una valvula pulse C:");
scanf ("%s", resp);
if (resp[0] == 'A' ) {
pthread_mutex_lock(&me);
abrirentrada=1;
pthread_cond_signal(&abrirE);
pthread_mutex_unlock(&me);
}
if (resp[0] == 'C' ) {
pthread_mutex_lock(&me);
cerrarentrada=1;
pthread_cond_signal(&cerrarE);
pthread_mutex_unlock(&me);
}
}
pthread_mutex_destroy(&me);
pthread_mutex_destroy(&mv);
}
| 1
|
#include <pthread.h>
_dataType data;
struct _node* next;
}node,*nodep,**nodepp;
nodep head = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
nodep buyNode(_dataType val)
{
nodep tmp = (nodep)malloc(sizeof(node));
if(tmp!= 0)
{
tmp->data = val;
tmp->next = 0;
return tmp;
}
return 0;
}
void init(nodepp head)
{
*head = buyNode(0);
}
void push_list(nodep head,_dataType val)
{
nodep tmp = buyNode(val);
tmp->next = head->next;
head->next = tmp;
}
int pop_back_list(nodep head,_dataType_p pval)
{
if(0 == head->next)
return -1;
nodep index = head;
while(0 != index->next->next)
{
index = index->next;
}
nodep del = index->next;
*pval = del->data;
index->next = del->next;
free(del);
return 0;
}
void* product(void* arg)
{
_dataType i = 0;
while(1)
{
sleep(1);
pthread_mutex_lock(&mutex);
push_list(head,i++);
pthread_mutex_unlock(&mutex);
}
pthread_exit((void *)1);
}
void* consumer(void *arg)
{
_dataType val = 0;
while(1){
sleep(2);
pthread_mutex_lock(&mutex);
if(pop_back_list(head,&val) == -1)
{
pthread_mutex_unlock(&mutex);
continue;
}
printf("data:%d\\n",val);
pthread_mutex_unlock(&mutex);
}
pthread_exit((void *)1);
}
int main()
{
pthread_t tid1,tid2;
init(&head);
pthread_create(&tid1,0,product,0);
pthread_create(&tid2,0,consumer,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
free(head);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex[8];
void unit_work(void)
{
volatile int i;
volatile int f,f1,f2;
f1 =12441331;
f2 = 3245235;
for (i = 47880000; i > 0; i--) {
f *= f1;
f1 *= f2;
f1 *= f2;
f2 *= f;
f2 *= f;
f *= f1;
f *= f1;
f1 *= f2;
f1 *= f2;
f2 *= f;
f2 *= f;
f *= f1;
}
}
void * child_thread(void * data)
{
unsigned long threadid = (unsigned long)data;
int rounds = 3;
int i;
int j;
for(i = 0; i < rounds; i++)
{
pthread_mutex_lock(&mutex[threadid]);
fprintf (stderr, "threadid:%d\\n", threadid);
fflush (stderr);
for(j = 0; j < 1; j++) {
unit_work();
}
pthread_mutex_unlock(&mutex[threadid]);
}
return 0;
}
int main(int argc,char**argv)
{
int i;
pthread_t threads[8];
for(int i = 0; i < 8; i++)
{
pthread_mutex_init(&mutex[i], 0);
}
for(int i = 0; i < 8; i++)
pthread_create (&threads[i], 0, child_thread, (void *)i);
for(i = 0; i < 8; i++) {
pthread_join (threads[i], 0);
}
}
| 1
|
#include <pthread.h>extern void __VERIFIER_error() ;
int element[(400)];
int head;
int tail;
int amount;
} QType;
pthread_mutex_t m;
int __VERIFIER_nondet_int();
int stored_elements[(400)];
_Bool enqueue_flag, dequeue_flag;
QType queue;
int init(QType *q)
{
q->head=0;
q->tail=0;
q->amount=0;
}
int empty(QType * q)
{
if (q->head == q->tail)
{
printf("queue is empty\\n");
return (-1);
}
else
return 0;
}
int full(QType * q)
{
if (q->amount == (400))
{
printf("queue is full\\n");
return (-2);
}
else
return 0;
}
int enqueue(QType *q, int x)
{
q->element[q->tail] = x;
q->amount++;
if (q->tail == (400))
{
q->tail = 1;
}
else
{
q->tail++;
}
return 0;
}
int dequeue(QType *q)
{
int x;
x = q->element[q->head];
q->amount--;
if (q->head == (400))
{
q->head = 1;
}
else
q->head++;
return x;
}
void *t1(void *arg)
{
int value, i;
pthread_mutex_lock(&m);
if (enqueue_flag)
{
for(
i=0; i<(400); i++)
{
value = __VERIFIER_nondet_int();
enqueue(&queue,value);
stored_elements[i]=value;
}
enqueue_flag=(0);
dequeue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
void *t2(void *arg)
{
int i;
pthread_mutex_lock(&m);
if (dequeue_flag)
{
for(
i=0; i<(400); i++)
{
if (empty(&queue)!=(-1))
if (!dequeue(&queue)==stored_elements[i]) {
ERROR:
__VERIFIER_error();
}
}
dequeue_flag=(0);
enqueue_flag=(1);
}
pthread_mutex_unlock(&m);
return 0;
}
int main(void)
{
pthread_t id1, id2;
enqueue_flag=(1);
dequeue_flag=(0);
init(&queue);
if (!empty(&queue)==(-1)) {
ERROR:
__VERIFIER_error();
}
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, &queue);
pthread_create(&id2, 0, t2, &queue);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 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 -1;
}
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 put(pc_st *pt, int key)
{
pthread_mutex_lock(&pt->mutex);
if(pt->write_pos >= 8 -1)
{
pthread_cond_wait(&pt->notfull, &pt->mutex);
pt->write_pos = 0;
}
pt->buffer[pt->write_pos] = key;
pt->write_pos++;
pthread_cond_signal(&pt->notempty);
pthread_mutex_unlock(&pt->mutex);
}
void get(pc_st *pt)
{
pthread_mutex_lock(&pt->mutex);
if(pt->read_pos == pt->write_pos)
{
pthread_cond_wait(&pt->notempty, &pt->mutex);
if(pt->read_pos == 8 -1)
pt->read_pos = 0;
else
pt->read_pos++;
}
pt->read_pos++;
pthread_cond_signal(&pt->notfull);
pthread_mutex_unlock(&pt->mutex);
}
void* producer(void *arg)
{
int i;
for(i = 1; i <= 20; ++i)
{
put(&pc, i);
}
put(&pc, -1);
}
void* consumer(void *arg)
{
while(1)
{
get(&pc);
if(pc.buffer[pc.read_pos-1] == -1)
break;
printf("value = %d\\n",pc.buffer[pc.read_pos-1]);
}
}
int main()
{
init_pc(&pc, 0);
int i;
pthread_t pro_id, con_id[5];
pthread_create(&pro_id, 0, producer, 0);
sleep(1);
for(i = 0; i < 5; ++i)
{
pthread_create(&con_id[i], 0, consumer, 0);
}
pthread_join(pro_id, 0);
for(i = 0; i < 5; ++i)
{
pthread_join(con_id[i], 0);
}
destroy_pc(&pc);
return 0;
}
| 1
|
#include <pthread.h>
{
char user[5];
char process;
int arrival;
int duration;
struct node *next;
}node;
{
node *R,*F;
}Q;
struct display
{
char user[5];
int timeLastCalculated;
struct display *next;
} *frontDisplay, *tempDisplay, *rearDisplay;
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
Q q;
void initialise(Q *);
int empty(Q *);
void enqueue(Q *, char[5], char, int, int);
void* jobDisplay();
struct node* nextTaskInQueue();
void addToSummary(char[], int);
void summaryDisplay();
int main( int argc, char *argv[] )
{
int n;
if( argc == 2 )
{
if ( strcmp(argv[1],"2") == 0 )
{
n = atoi(argv[1]);
}
else
{
printf("The argument supplied is not 2.\\n");
return 0;
}
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\\n");
return 0;
}
else
{
printf("One argument expected.\\n");
return 0;
}
char user[5], process;
int arrivalInput, durationInput;
initialise(&q);
printf("\\n\\tUser\\tProcess\\tArrival\\tDuration\\n");
int i = 1;
while ( i < 5 )
{
printf("\\t");
if ( scanf("%s\\t%c\\t%d\\t%d", user, &process, &arrivalInput, &durationInput) < 4 )
{
printf("\\nThe arguments supplied are incorrect. Try again.\\n");
return 0;
}
enqueue(&q, user, process, arrivalInput, durationInput);
i++;
}
printf("\\nThis would result in:\\n\\n\\tTime\\tJob\\n");
pthread_t threadID[n];
i = 0;
for ( i = 0; i < n; i++ )
{
pthread_create(&(threadID[i]),0,&jobDisplay,0);
}
pthread_join(threadID[0],0);
pthread_join(threadID[1],0);
pthread_mutex_destroy(&m1);
pthread_mutex_destroy(&m2);
summaryDisplay();
return 0;
}
void initialise(Q *qPointer)
{
qPointer->R=0;
qPointer->F=0;
rearDisplay=0;
tempDisplay=0;
frontDisplay=0;
}
void enqueue(Q *qPointer, char user[5], char process, int arrivalE, int durationE)
{
node *eP;
eP=(node*)malloc(sizeof(node));
strcpy(eP->user, user);
eP->process=process;
eP->arrival=arrivalE;
eP->duration=durationE;
eP->next=0;
if ( empty(qPointer) )
{
qPointer->R=eP;
qPointer->F=eP;
}
else
{
(qPointer->R)->next=eP;
qPointer->R=eP;
}
}
void* jobDisplay()
{
int myTime = 0;
struct node* placeholder = 0;
placeholder = nextTaskInQueue();
while ( placeholder != 0 )
{
if ( myTime < placeholder->arrival )
{
sleep( placeholder->arrival - myTime );
myTime = placeholder->arrival;
}
printf("\\t%d\\t%c\\n", myTime, placeholder->process);
sleep(placeholder->duration);
myTime += placeholder->duration;
addToSummary(placeholder->user, myTime);
placeholder = nextTaskInQueue();
}
counter++;
printf("\\t%d\\tCPU %d IDLE\\n", myTime, counter);
return 0;
}
struct node* nextTaskInQueue()
{
struct node* placeholder = 0;
pthread_mutex_lock(&m1);
struct Q* qPointer=&q;
if ( qPointer->F != 0 )
{
placeholder = qPointer->F;
qPointer->F = placeholder->next;
}
pthread_mutex_unlock(&m1);
return placeholder;
}
void addToSummary(char name[], int timeLeft)
{
pthread_mutex_lock(&m2);
if ( rearDisplay == 0 )
{
rearDisplay = (struct display *)malloc(1*sizeof(struct display));
rearDisplay->next = 0;
strcpy(rearDisplay->user, name);
rearDisplay->timeLastCalculated = timeLeft;
frontDisplay = rearDisplay;
}
else
{
tempDisplay = frontDisplay;
while ( tempDisplay != 0 )
{
if ( strcmp(tempDisplay->user, name) == 0 )
{
tempDisplay->timeLastCalculated = timeLeft;
break;
}
tempDisplay = tempDisplay->next;
}
if ( tempDisplay == 0 )
{
tempDisplay = (struct display *)malloc(1*sizeof(struct display));
rearDisplay->next = tempDisplay;
strcpy(tempDisplay->user, name);
tempDisplay->timeLastCalculated = timeLeft;
tempDisplay->next = 0;
rearDisplay = tempDisplay;
}
}
pthread_mutex_unlock(&m2);
}
void summaryDisplay()
{
printf("\\n\\tSummary\\n");
while ( frontDisplay != 0 )
{
printf("\\t%s\\t%d\\n", frontDisplay->user, frontDisplay->timeLastCalculated);
tempDisplay = frontDisplay->next;
free(frontDisplay);
frontDisplay = tempDisplay;
}
printf("\\n");
}
int empty(Q *qPointer)
{
if ( qPointer->R==0 )
return 1;
return 0;
}
| 0
|
#include <pthread.h>
int *input;
int *pOutput;
int *sOutput;
int *bias;
int *partials;
int n;
int numProc;
int thread_count=0;
int chunk;
pthread_mutex_t sync_mutex;
pthread_cond_t sync_cv, main_cv;
pthread_attr_t attr;
void sequential( int *, int , int * );
void* parallel( void * );
void print_scan( int*, int );
int main( int argc, char **argv ) {
void *status;
struct timespec start, stop;
int sTime, pTime;
int padding, size;
sscanf( argv[1], "%d", &n );
sscanf( argv[2], "%d", &numProc );
padding = n % numProc;
size = sizeof(int) * (n + padding);
chunk = ( n + padding ) / numProc;
input = (int*) malloc( size );
sOutput = (int*) malloc( size );
pOutput = (int*) malloc( size );
bias = (int*) malloc( sizeof(int) * numProc );
partials = (int*) malloc( sizeof(int) * numProc );
memset( input , 0, size );
memset( sOutput , 0, size );
memset( pOutput , 0, size );
memset( bias , 0, sizeof(int) * numProc );
memset( partials , 0, sizeof(int) * numProc );
int i;
for( i = 0; i < n; i++ ) {
input[i] = abs(rand() % 1000);
}
clock_gettime( CLOCK_MONOTONIC, &start );
sequential( input, n, sOutput );
clock_gettime( CLOCK_MONOTONIC, &stop );
sTime = stop.tv_nsec - start.tv_nsec;;
printf("Sequential version took: %d nanoseconds\\n", sTime );
pthread_t *threads = (pthread_t*) malloc( sizeof(pthread_t) * numProc );
pthread_cond_init (&sync_cv, 0);
pthread_cond_init (&main_cv, 0);
pthread_mutex_init(&sync_mutex, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for( i = 0; i < numProc; ++i ){
pthread_create( &threads[i], &attr, parallel, 0 );
}
pthread_attr_destroy(&attr);
pthread_mutex_lock( &sync_mutex );
while( thread_count < numProc ){
pthread_cond_wait( &main_cv, &sync_mutex );
}
clock_gettime( CLOCK_MONOTONIC, &start );
pthread_cond_broadcast( &sync_cv );
pthread_cond_wait( &main_cv, &sync_mutex );
sequential( partials, numProc, bias );
pthread_cond_broadcast( &sync_cv );
pthread_mutex_unlock( &sync_mutex );
for( i = 0; i < numProc; ++i ){
pthread_join( threads[i], &status );
}
clock_gettime( CLOCK_MONOTONIC, &stop );
pTime = stop.tv_nsec - start.tv_nsec;
printf( "Parallel version took: %d nanoseconds\\n", pTime );
for( i = 0; i < n; ++i ){
if( sOutput[i] != pOutput[i] ){
printf( "Output does not match!" );
}
}
printf( "Speedup = %f \\n", (sTime * 1.0) / (pTime * 1.0) );
return 0;
}
void sequential( int *input, int n, int *output ) {
output[0] = input[0];
int i;
for( i = 1; i < n; ++i ) {
output[i] = input[i] + output[i-1];
}
}
void* parallel( void *thread_num ) {
pthread_mutex_lock( &sync_mutex );
int thread = thread_count++;
int offset = thread * chunk;
pthread_cond_signal( &main_cv );
pthread_cond_wait( &sync_cv, &sync_mutex );
pthread_mutex_unlock( &sync_mutex );
sequential( input + offset, chunk, pOutput + offset );
partials[thread] = pOutput[offset + chunk - 1];
pthread_mutex_lock( &sync_mutex );
thread_count--;
if( thread_count == 0) {
pthread_cond_signal( &main_cv);
}
pthread_cond_wait( &sync_cv, &sync_mutex );
pthread_mutex_unlock( &sync_mutex );
int i;
if( thread == 0 ) pthread_exit(0);
for( i = 0; i < chunk; ++i) {
pOutput[offset+i] += bias[thread-1];
}
pthread_exit(0);
}
void print_scan( int* array, int size ) {
int i;
for( i = 0; i < size; ++i ){
printf( "%d, ", array[i] );
}
printf( "\\n");
}
| 1
|
#include <pthread.h>
struct pParam {
int tid, tsize;
int bound;
int mrank, msize;
int *primecount;
pthread_mutex_t *lock;
};
void *findPrime(void *param)
{
int i, j, test, start, increment, runningcount = 0;
struct pParam *p = (struct pParam *)param;
start = (((p->tid * p->msize) + p->mrank) * 2) + 3;
increment = (p->tsize * p->msize) * 2;
printf("|| pThread %d starting at %d incrementing by %d.\\n", p->tid, start, increment);
for(i = start; i < p->bound; i += increment){
test = (int)sqrt((double)i);
for(j = 2; j <= test; j++){
if(i % j == 0){
runningcount--;
break;
}
}
if(i != p->bound){
runningcount++;
}
}
pthread_mutex_lock(p->lock);
*(p->primecount) += runningcount;
pthread_mutex_unlock(p->lock);
pthread_exit((void *) p->tid);
}
int main(int argc, char *argv[])
{
int i, ubound = 0, tPrimeCount = 0, FinalPrimeCount = 0, tSize = atoi(argv[1]);
pthread_t thread[tSize];
struct pParam *param[tSize];
pthread_attr_t attr;
pthread_mutex_t lock;
long rc;
void *status;
int mpiRank = 0, mpiSize = 1;
int namelen;
double time;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank);
MPI_Comm_size(MPI_COMM_WORLD, &mpiSize);
MPI_Get_processor_name(processor_name, &namelen);
printf("Process %d started on host %s.\\n", mpiRank, processor_name);
if (!mpiRank){
if (argc > 2){
ubound = atoi(argv[2]);
}
if (!ubound) {
printf("Upper bound not supplied, terminating.\\n");
}
}
MPI_Bcast(&ubound, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (!ubound){
MPI_Finalize();
return 255;
}
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&lock, 0);
time = MPI_Wtime();
for (i = 0; i < tSize; i++) {
printf("[%s] creating pThread %d.\\n", processor_name, i);
param[i] = (struct pParam *)malloc(sizeof(struct pParam));
param[i]->tid = i;
param[i]->tsize = tSize;
param[i]->bound = ubound;
param[i]->mrank = mpiRank;
param[i]->msize = mpiSize;
param[i]->lock = &lock;
param[i]->primecount = &tPrimeCount;
rc = pthread_create(&thread[i], &attr, findPrime, (void *)(param[i]));
}
pthread_attr_destroy(&attr);
for (i = 0; i < tSize; i++) {
rc = pthread_join(thread[i], &status);
printf("[%s] completed join with pThread %d.\\n", processor_name, i);
}
pthread_mutex_destroy(&lock);
time = MPI_Wtime() - time;
printf("[Host: %s] process %d completed computation in %f.\\n", processor_name, mpiRank, time);
if (!mpiRank){
FinalPrimeCount++;
FinalPrimeCount += tPrimeCount;
for(i=1;i<mpiSize;i++){
MPI_Recv(&tPrimeCount, 1, MPI_INT, i, 31337, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
FinalPrimeCount += tPrimeCount;
}
}
else{
MPI_Send(&tPrimeCount, 1, MPI_INT, 0, 31337, MPI_COMM_WORLD);
}
if (!mpiRank){
printf("All computation has finished.\\n Found %d primes in the range 0 - %d.\\nExiting.\\n", FinalPrimeCount, ubound);
}
MPI_Finalize();
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int quit,sum;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t waitloc =PTHREAD_COND_INITIALIZER;
void *thr_fn(void *arg)
{
int i = *(int *)arg;
printf("thr_fn\\n");
if (i==0){
printf("the transfer the param success\\n");
while(i<=100){
pthread_mutex_lock(&lock);
sum += i;
pthread_mutex_unlock(&lock);
i++;
}
pthread_mutex_lock(&lock);
printf("the sum:%d\\n", sum);
pthread_mutex_unlock(&lock);
}
pthread_exit((void *)0);
}
int main(int argc, char **argv) {
int i,err,num =0;
pthread_t tid[i];
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err)
return(err);
err = pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
if (err==0){
for (int i = 0; i < 5; ++i)
{
err = pthread_create(&tid[i],&attr,thr_fn,(void *)&num);
if (err) {
printf("craete err\\n");
}
}
}else
printf("set pthread detach failed\\n");
pthread_attr_destroy(&attr);
sleep(1);
for (int i = 5; i >0; --i)
{
printf("wait the thread:%d\\n", i);
err = pthread_join(tid[i],(void *)&err);
if (!err)
{
printf("wait success thread :%d\\n",i);
}
}
return 0;
}
| 1
|
#include <pthread.h>
static inline int sht21_temp_ticks_to_millicelsius(int ticks){
ticks &= ~0x0003;
return ((21965 * ticks) >> 13) - 46850;
}
inline int sht21_rh_ticks_to_per_cent_mille(int ticks){
ticks &= ~0x0003;
return ((15625 * ticks) >> 13) - 6000;
}
int sht21_functionality(int fd){
unsigned long funcs;
if(ioctl(fd, I2C_FUNCS, &funcs) < 0) {
printf("Error: Could not get the adapter functionality matrix: %s\\n", strerror(errno));
return 1;
}
if(!(funcs & (I2C_FUNC_SMBUS_WRITE_BYTE_DATA|I2C_FUNC_SMBUS_READ_WORD_DATA))){
printf("Error: Can't use SMBus Read/Write Byte/Word Data command on this bus; %s\\n", strerror(errno));
return 1;
}
return 0;
}
int sht21_read_value(int fd, int addr, __u8 reg){
if( ioctl(fd, I2C_SLAVE, addr) < 0 ){
printf("Failed to configure the device; %s\\n", strerror(errno));
return 1;
}
if(reg == 0xe7)
return i2c_smbus_read_byte_data(fd, reg);
else
return __swab16(i2c_smbus_read_word_data(fd, reg));
}
int sht21_write_value(int fd, int addr, __u8 reg, __u8 val){
if( ioctl(fd, I2C_SLAVE, addr) < 0 ){
printf("Failed to configure the device; %s\\n", strerror(errno));
return 1;
}
if(reg == 0xfe)
return i2c_smbus_write_byte(fd, reg);
else
return i2c_smbus_write_byte_data(fd, reg, val);
}
pthread_mutex_t lock;
int sht21_measur(int fd, int addr, __u8 reg){
int data[2];
if(pthread_mutex_init(&lock, 0) != 0){
printf("Failed to mutex init\\n");
return 1;
}
pthread_mutex_lock(&lock);
if( ioctl(fd, I2C_SLAVE, addr) < 0 ){
printf("Failed to configure the device; %s\\n", strerror(errno));
return 1;
}
if(i2c_smbus_write_byte(fd, reg) < 0){
printf("Failed writing to device; %s\\n", strerror(errno));
return 1;
}
if(reg == 0xf3 || reg == 0xe3)
usleep(85000);
else if(reg == 0xf5 || reg == 0xe5)
usleep(29000);
else
return 1;
data[0] = i2c_smbus_read_byte(fd);
data[1] = i2c_smbus_read_byte(fd);
usleep(500000);
pthread_mutex_unlock(&lock);
pthread_mutex_destroy(&lock);
return (data[0]<<8) | data[1];
}
int sht21_humid(int fd, int addr, __u16 *data){
data[0] = sht21_measur(fd, addr, 0xf5);
return 0;
}
void sht21_print_val(__u16 val[8], float lsb, float conv_param[8],
char *data_type[8],
int ch, int log,
int log_p){
float humid = sht21_rh_ticks_to_per_cent_mille(val[0])/1000;
if(log){
char str[16];
sprintf(str, "%0.3f ", humid);
write(log_p, str, strlen(str));
}
else
printf("%s%d: %0.3f %%\\n", data_type[0], ch, humid);
}
| 0
|
#include <pthread.h>
int auti_na_mostu = 0, proslo = 0;
int smjer_most = 2;
int *smjer_auta;
int cekaju[2] = {0};
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t uvjet_lijevi = PTHREAD_COND_INITIALIZER;
pthread_cond_t uvjet_desni = PTHREAD_COND_INITIALIZER;
void popniSeNaMost (int smjer) {
pthread_mutex_lock(&m);
cekaju[smjer]++;
while ((smjer_most == 1-smjer) || (auti_na_mostu == 3) || ((cekaju[1-smjer] > 0) && proslo >= 5)) {
if (smjer == 0)
pthread_cond_wait(&uvjet_lijevi, &m);
else
pthread_cond_wait(&uvjet_desni, &m);
}
cekaju[smjer]--;
auti_na_mostu++;
smjer_most = smjer;
proslo++;
pthread_mutex_unlock(&m);
return;
}
void sidjiSaMosta (int smjer) {
pthread_mutex_lock(&m);
auti_na_mostu--;
if (auti_na_mostu == 0) {
proslo = 0;
smjer_most = 2;
if (cekaju[1-smjer] > 0) {
smjer_most = 1-smjer;
if (smjer == 0)
pthread_cond_broadcast(&uvjet_desni);
else
pthread_cond_broadcast(&uvjet_lijevi);
}
}
if (smjer == 0)
pthread_cond_broadcast(&uvjet_lijevi);
else
pthread_cond_broadcast(&uvjet_desni);
pthread_mutex_unlock(&m);
return;
}
void *Auto (void *thread_id) {
int id, moj_smjer;
id = *(int *)thread_id;
moj_smjer = smjer_auta[id];
if (moj_smjer == 0)
printf("Auto %d čeka na prelazak preko mosta, smjer: lijevo\\n", id+1);
else
printf("Auto %d čeka na prelazak preko mosta, smjer: desno\\n", id+1);
popniSeNaMost(moj_smjer);
printf("Auto %d prelazi most\\n", id+1);
sleep(1);
sidjiSaMosta(moj_smjer);
printf("Auto %d je prešao most.\\n", id+1);
return 0;
}
int main (int argc, char *argv[]) {
pthread_t *thread;
int *thread_id;
int i, koliko, x;
koliko = atoi(argv[1]);
printf("Broj auta: %d\\n", koliko);
printf("Pravila:\\n1. Najviše 3 auta na mostu\\n2. Auti smiju ići samo u jednom smjeru\\n3. Pušta se po 5 auta sa svake strane ako obje strane čekaju\\n");
sleep(5);
thread_id = (int *) malloc(sizeof(int)*koliko);
thread = (pthread_t *) malloc(sizeof(pthread_t)*koliko);
smjer_auta = (int *) malloc(sizeof(int)*koliko);
srand(time(0));
for (i = 0; i < koliko; i++) {
thread_id[i] = 0;
x = rand() % 2;
smjer_auta[i] = x;
}
for (i = 0; i < koliko; i++) {
thread_id[i] = i;
if (pthread_create(&thread[i], 0, Auto, ((void *)&thread_id[i]))) {
printf("Ne može se stvoriti nova dretva\\n");
exit(1);
}
usleep(500000);
}
for (i = 0; i < koliko; i++) {
pthread_join(thread[i], 0);
}
printf("Svi su auti prešli preko mosta, kraj programa.\\n");
free(thread_id);
free(thread);
free(smjer_auta);
return 0;
}
| 1
|
#include <pthread.h>
static int fd;
pthread_t tid1,tid2;
struct task task1,task2;
pthread_mutex_t mutex;
struct task tt;
void my_signal_fun(int signum)
{
struct task t;
int ret;
t.pid=getpid();
ret=ioctl(fd,IO_READ_TASK,&t);
if(ret!=0)
return ;
pthread_mutex_lock(&mutex);
tt=t;
pthread_mutex_unlock(&mutex);
pthread_kill(t.tid, SIGALRM);
}
void pthread_signal_fun(int signum)
{
pthread_mutex_lock(&mutex);
printf("line:%d current pid=%d tid=%ld \\t get_task: pid=%d tid=%ld data=%d\\n",47,getpid(),pthread_self(),tt.pid,tt.tid,tt.data);
pthread_mutex_unlock(&mutex);
}
void delay_1s(){
int i ,j;
for(i=0;i<10000;i++)
for(j=0;j<10000*2;j++);
}
void * thread_func1(void * data)
{
int ret;
struct task task0;
signal(SIGALRM, pthread_signal_fun);
printf("thread func1 tid1=%ld current=%ld \\n",tid1,pthread_self());
task0.pid=getpid();
task0.tid=pthread_self();
task0.data=0;
while(1){
ret=ioctl(fd,IO_WRITE_TASK,&task0);
if(ret<0){
printf("send task error! function : %s line : %d\\n",__FUNCTION__,74);
}
delay_1s();
}
}
void * thread_func2(void * data)
{
int ret;
struct task task0;
signal(SIGALRM, pthread_signal_fun);
printf("thread func2 tid2=%ld current=%ld \\n",tid2,pthread_self());
task0.pid=getpid();
task0.tid=pthread_self();
task0.data=0;
while(1){
ret=ioctl(fd,IO_WRITE_TASK,&task0);
if(ret<0){
printf("send task error! function : %s line : %d\\n",__FUNCTION__,99);
}
delay_1s();
}
}
int main(int argc, char **argv)
{
int ret;
int Oflags;
pthread_mutex_init(&mutex,0);
signal(SIGIO, my_signal_fun);
fd = open("/dev/hello_device", O_RDWR);
if (fd < 0)
{
printf("can't open!\\n");
}
fcntl(fd, F_SETOWN, getpid());
Oflags = fcntl(fd, F_GETFL);
fcntl(fd, F_SETFL, Oflags | FASYNC);
ret=pthread_create(&tid1, 0, thread_func1, "thread1");
if(ret<0){
perror("pthread_create error\\n");
return -1;
}
pthread_create(&tid2, 0, thread_func2, "thread2");
if(ret<0){
perror("pthread_create error\\n");
return -1;
}
while(1);
return 0;
}
| 0
|
#include <pthread.h>
extern int makepthread(void *(*)(void*), void *);
struct to_info{
void (*to_fn)(void *);
void *to_arg;
struct timespec to_wait;
};
void *timeout_helper(void*arg)
{
struct to_info *tip;
tip = (struct to_info*)arg;
nanosleep(&tip->to_wait, 0);
(*tip->to_fn)(tip->to_arg);
return (0);
}
void timeout(const struct timespec *when, void (*func)(void *), void *arg)
{
struct timespec now;
struct timeval tv;
struct to_info *tip;
int err;
gettimeofday(&tv, 0);
now.tv_sec = tv.tv_sec;
now.tv_nsec = tv.tv_usec * 1000;
if((when->tv_sec > now.tv_sec) ||
(when->tv_sec == now.tv_sec && when->tv_nsec > now.tv_nsec)){
tip = malloc(sizeof(struct to_info));
if(tip != 0){
tip->to_fn = func;
tip->to_arg = arg;
tip->to_wait.tv_sec = when->tv_sec - now.tv_sec;
if(when->tv_nsec >= now.tv_nsec){
tip->to_wait.tv_nsec = when->tv_nsec - now.tv_nsec;
}else{
tip->to_wait.tv_sec --;
tip->to_wait.tv_nsec = 1000000000 - now.tv_nsec + when->tv_nsec;
}
err = makepthread(timeout_helper, (void*)tip);
if(err != 0){
return ;
}
}
}
(*func)(arg);
}
pthread_mutexattr_t attr;
pthread_mutex_t mutex;
void retry(void *arg)
{
pthread_mutex_lock(&mutex);
printf("pthread function retry() get the lock and go to sleep ...\\n");
sleep(4);
pthread_mutex_unlock(&mutex);
printf("pthread function unlock the lock\\n");
}
int main(void)
{
int err, condition = 1, arg = 1;
struct timespec when;
if((err = pthread_mutex_init(&mutex,0)) != 0){
perror("pthread_mutex_init");
exit(1);
}
pthread_mutex_lock(&mutex);
printf("main get the lock already\\n");
if(condition){
timeout(&when, retry, (void*)arg);
}
printf("timeout returned \\n");
pthread_mutex_unlock(&mutex);
printf("main unlock the mutex\\n");
exit(0);
}
| 1
|
#include <pthread.h>
extern struct protoent_data _protoent_data;
struct protoent *
getprotobynumber(int proto)
{
struct protoent *p;
pthread_mutex_lock(&_protoent_mutex);
p = getprotobynumber_r(proto, &_protoent_data.proto, &_protoent_data);
pthread_mutex_unlock(&_protoent_mutex);
return (p);
}
| 0
|
#include <pthread.h>
int A[1000][1000],
B[1000][1000],
noOfOnes,
countOperation = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t operation = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t opcond = PTHREAD_COND_INITIALIZER;
{
int threadID;
}thread_data;
int CountNoOfOnes(int row)
{
int i, j,
count = 0;
for(i = row; i < row + 1000 / 4; i++)
{
for(j = 0; j < 1000; j++)
{
count += (A[i][j] == 1);
}
}
return count;
}
void TransitiveClosure(int row)
{
int i, j, k, flag;
for(i = row; i < row + 1000 / 4; i++)
{
flag = 0;
for(j = 0; j < 1000; j++)
{
for(k = 0; k < 1000; k++)
{
if(A[i][k] == 1 && A[k][j] == 1)
flag = 1;
}
if(flag) B[i][j] = 1;
else B[i][j] = 0;
}
}
}
void CopyPartialMatrix(int row)
{
int i, j;
for(i = row; i < row + 1000 / 4; i++)
{
for(j = 0; j < 1000; j++)
{
A[i][j] = B[i][j];
}
}
for(i = row; i < row + 1000 / 4; i++)
{
for(j = 0; j < 1000; j++)
{
B[i][j] = 0;
}
}
}
void *WorkerFunction(void *workerFnArgs)
{
int i, j, e;
pthread_mutex_lock(&mutex);
noOfOnes += CountNoOfOnes(((thread_data *)workerFnArgs)->threadID * 1000 / 4);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&operation);
countOperation++;
if(countOperation % 4 != 0)
{
pthread_mutex_unlock(&operation);
pthread_cond_wait(&opcond, &operation);
}
else
{
pthread_cond_broadcast(&opcond);
}
pthread_mutex_unlock(&operation);
for(e = 1; pow(2, e) <= 1000; e++)
{
TransitiveClosure(((thread_data *)workerFnArgs)->threadID * 1000 / 4);
pthread_mutex_lock(&mutex);
countOperation++;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&operation);
countOperation++;
if(countOperation % 4 != 0)
{
pthread_mutex_unlock(&operation);
pthread_cond_wait(&opcond, &operation);
}
else
{
pthread_cond_broadcast(&opcond);
}
pthread_mutex_unlock(&operation);
CopyPartialMatrix(((thread_data *)workerFnArgs)->threadID * 1000 / 4);
pthread_mutex_lock(&mutex);
countOperation++;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&operation);
countOperation++;
if(countOperation % 4 != 0)
{
pthread_mutex_unlock(&operation);
pthread_cond_wait(&opcond, &operation);
}
else
{
pthread_cond_broadcast(&opcond);
}
pthread_mutex_unlock(&operation);
}
pthread_exit(0);
}
void DisplayMatrix()
{
int i, j;
for(i = 0; i < 1000; i++)
{
for(j = 0; j < 1000; j++)
{
printf("%d ", A[i][j]);
}
printf("\\n");
}
}
int main()
{
int i, j,
rc;
pthread_t threadList[4];
pthread_attr_t attr;
thread_data workerFnArgsList[4];
void *status;
srand((unsigned int)time(0));
for(i = 0; i < 1000; i++)
{
for(j = 0; j < 1000; j++)
{
A[i][j] = (rand() % 2 == 0);
}
}
printf("Original matrix:\\n");
DisplayMatrix();
noOfOnes = 0;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i = 0; i < 4; i++)
{
workerFnArgsList[i].threadID = i;
rc = pthread_create(&threadList[i], &attr, WorkerFunction, (void*)&workerFnArgsList[i]);
if(rc)
{
printf("\\nError: Cannot create thread: Code %d", rc);
exit(1);
}
}
pthread_attr_destroy(&attr);
for(i = 0; i < 4; i++)
{
rc = pthread_join(threadList[i], &status);
if(rc)
{
printf("\\nError: Cannot join thread: Code %d", rc);
exit(1);
}
}
printf("\\nNumber of ones in the matrix = %d\\n", noOfOnes);
printf("\\nTransitive Closure of matrix:\\n");
DisplayMatrix();
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int __po_hi_transport_need_receiver_task();
void __po_hi_initialize_transport ();
pthread_cond_t cond_init;
pthread_mutex_t mutex_init;
int initialized_tasks;
int nb_tasks_to_init;
int __po_hi_initialize ()
{
if (pthread_mutex_init (&mutex_init, 0) != 0 )
{
return (__PO_HI_ERROR_PTHREAD_MUTEX);
}
nb_tasks_to_init = __PO_HI_NB_TASKS + 1;
initialized_tasks = 0;
if (pthread_cond_init (&cond_init,
0) != 0)
{
return (__PO_HI_ERROR_PTHREAD_COND);
}
__po_hi_initialize_tasking ();
return (__PO_HI_SUCCESS);
}
int __po_hi_wait_initialization ()
{
if (pthread_mutex_lock (&mutex_init) != 0)
return (__PO_HI_ERROR_PTHREAD_MUTEX);
initialized_tasks++;
while (initialized_tasks < nb_tasks_to_init)
{
pthread_cond_wait (&cond_init, &mutex_init);
}
pthread_cond_broadcast (&cond_init);
pthread_mutex_unlock (&mutex_init);
return (__PO_HI_SUCCESS);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutexPoolLista = PTHREAD_MUTEX_INITIALIZER;
struct Poolstruct * listaPools [1000];
int listaPoolTop;
struct Poolstruct * listaPool_newPool (){
pthread_mutex_lock( &mutexPoolLista );
int listaPoolTopActual = listaPoolTop ;
listaPoolTop++;
pthread_mutex_unlock( &mutexPoolLista );
struct Poolstruct *nuevoPool = calloc(1, sizeof (struct Poolstruct));
listaPools[listaPoolTopActual] = nuevoPool;
nuevoPool->poolCounter =0;
nuevoPool->poolTop =0;
nuevoPool->id = listaPoolTopActual;
return nuevoPool;
}
struct Poolstruct * listaPools_getPoolstruct (int index){
return listaPools[index];
}
struct Poolstruct **listaPools_getlistaPools(){
return listaPools;
}
int listaPools_getlistaPoolTop (){
return listaPoolTop;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t stream_mutex[STREAM_SEM_NUM];
int Sem_Creat( int index )
{
if( index < 0 || index >= STREAM_SEM_NUM)
{
fprintf(stderr, "Error: " "Sem_Creat index faill!!\\n");
return -1;
}
if( pthread_mutex_init(&stream_mutex[index], 0) != 0 )
{
fprintf(stderr, "Error: " "Sem_Creat init faill!!\\n");
return -1;
}else{
return index;
}
}
int Sem_unlock( int index )
{
if( index < 0 || index >= STREAM_SEM_NUM)
{
fprintf(stderr, "Error: " "Sem_unlock faill!!!!!!!!!!!!!!!!!!!!!!!!!\\n");
return -1;
}
pthread_mutex_unlock(&stream_mutex[index]);
return 0;
}
int Sem_lock( int index )
{
if( index < 0 || index >= STREAM_SEM_NUM)
{
fprintf(stderr, "Error: " "Sem_lock faill!!!!!!!!!!!!!!!!!!!!!!!!!!!\\n");
return -1;
}
pthread_mutex_lock(&stream_mutex[index]);
return 0;
}
int Sem_kill( int index )
{
if( index < 0 || index >= STREAM_SEM_NUM)
{
fprintf(stderr, "Error: " "Sem_kill index faill!!\\n");
return -1;
}
if( pthread_mutex_destroy(&stream_mutex[index])!= 0 )
{
fprintf(stderr, "Error: " "Sem_kill faill!!\\n");
return -1;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
void *thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time = 0, count = 0;
int res;
res = pthread_mutex_lock(&mutex);
if (res)
{
printf("Thread %d lock failed\\n", thrd_num);
pthread_exit(0);
}
printf("Thread %d is starting\\n", thrd_num);
for (count = 0; count < 3; count++)
{
delay_time = (int)(rand() * 10.0/(32767)) + 1;
sleep(delay_time);
printf("\\tThread %d: job %d delay = %d\\n",
thrd_num, count, delay_time);
}
printf("Thread %d finished\\n", thrd_num);
pthread_exit(0);
}
int main(void)
{
pthread_t thread[3];
int no = 0, res;
void * thrd_ret;
srand(time(0));
pthread_mutex_init(&mutex, 0);
for (no = 0; no < 3; no++)
{
res = pthread_create(&thread[no], 0, thrd_func, (void*)no);
if (res != 0)
{
printf("Create thread %d failed\\n", no);
exit(res);
}
}
printf("Create treads success\\n Waiting for threads to finish...\\n");
for (no = 0; no < 3; no++)
{
res = pthread_join(thread[no], &thrd_ret);
if (!res)
{
printf("Thread %d joined\\n", no);
}
else
{
printf("Thread %d join failed\\n", no);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
char * tasks[200];
int consumerIndex = 0;
int producerIndex = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t fill = PTHREAD_COND_INITIALIZER;
pthread_cond_t empty = PTHREAD_COND_INITIALIZER;
void put(char inputBuffer[80]) {
pthread_mutex_lock(&mutex);
while(producerIndex - consumerIndex > 0 || consumerIndex - producerIndex > 5){
pthread_cond_wait(&empty, &mutex);
}
strncpy(tasks[producerIndex], inputBuffer, 80);
producerIndex = (producerIndex + 1) % 200;
printf("after strncpy\\n");
pthread_cond_signal(&fill);
pthread_mutex_unlock(&mutex);
}
char * get() {
char * buffer = malloc(sizeof(char) * 80);
pthread_mutex_lock(&mutex);
while(producerIndex != consumerIndex){
pthread_cond_wait(&fill, &mutex);
}
strncpy(buffer, tasks[consumerIndex], 80);
pthread_cond_signal(&empty);
pthread_mutex_unlock(&mutex);
return buffer;
}
| 0
|
#include <pthread.h>
{
char car[5];
char direction;
int arrival;
struct node *next;
}node;
{
node *R,*F;
}Q;
struct display
{
char car[5];
char direction;
struct display *next;
} *northDisplay, *tempDisplay, *southDisplay;
pthread_mutex_t m1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t m2 = PTHREAD_MUTEX_INITIALIZER;
int counter = 0;
int myTime;
Q q;
void initialise(Q *);
int empty(Q *);
void enqueue(Q *, char[5], char, int);
void* carThread();
struct node* nextCarOnBridge();
void addToOutput(char[], char);
void arriveBridge(int);
void exitBridge(char);
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
myTime = atoi(argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\\n");
return 0;
}
else
{
printf("One argument expected.\\n");
return 0;
}
char car[5], direction;
int arrivalInput;
initialise(&q);
printf("\\n\\tCar\\tCourse\\tArrival\\n");
int i = 1;
while ( i < 5 )
{
printf("\\t");
if ( scanf("%s\\t%c\\t%d", car, &direction, &arrivalInput) < 3 )
{
printf("\\nThe arguments supplied are incorrect. Try again.\\n");
return 0;
}
if ( direction == 'N' || direction == 'S' )
{
enqueue(&q, car, direction, arrivalInput);
i++;
}
else
{
printf("\\nThe direction supplied is not N or S. Please try again.\\n");
return 0;
}
}
pthread_t threadID[i];
int myCounter;
for ( myCounter = 0; myCounter < i; myCounter++ )
{
pthread_create(&(threadID[myCounter]),0,&carThread,0);
}
for ( myCounter = 0; myCounter < i; myCounter++ )
{
pthread_join(threadID[myCounter],0);
}
pthread_mutex_destroy(&m1);
pthread_mutex_destroy(&m2);
arriveBridge(myTime);
printf("\\n");
return 0;
}
void initialise(Q *qPointer)
{
qPointer->R=0;
qPointer->F=0;
southDisplay=0;
tempDisplay=0;
northDisplay=0;
}
void enqueue(Q *qPointer, char car[5], char direction, int arrivalE)
{
node *eP;
eP=(node*)malloc(sizeof(node));
strcpy(eP->car, car);
eP->direction=direction;
eP->arrival=arrivalE;
eP->next=0;
if ( empty(qPointer) )
{
qPointer->R=eP;
qPointer->F=eP;
}
else
{
(qPointer->R)->next=eP;
qPointer->R=eP;
}
}
void* carThread()
{
struct node* placeholder = 0;
placeholder = nextCarOnBridge();
while ( placeholder != 0 )
{
addToOutput(placeholder->car, placeholder->direction);
placeholder = nextCarOnBridge();
}
return 0;
}
struct node* nextCarOnBridge()
{
struct node* placeholder = 0;
pthread_mutex_lock(&m1);
struct Q* qPointer=&q;
if ( qPointer->F != 0 )
{
placeholder = qPointer->F;
qPointer->F = placeholder->next;
}
pthread_mutex_unlock(&m1);
return placeholder;
}
void addToOutput(char name[], char direction)
{
pthread_mutex_lock(&m2);
if ( southDisplay == 0 )
{
southDisplay = (struct display *)malloc(1*sizeof(struct display));
southDisplay->next = 0;
strcpy(southDisplay->car, name);
southDisplay->direction = direction;
northDisplay = southDisplay;
}
else
{
tempDisplay = northDisplay;
while ( tempDisplay != 0 )
{
if ( strcmp(tempDisplay->car, name) == 0 )
{
tempDisplay->direction = direction;
break;
}
tempDisplay = tempDisplay->next;
}
if ( tempDisplay == 0 )
{
tempDisplay = (struct display *)malloc(1*sizeof(struct display));
southDisplay->next = tempDisplay;
strcpy(tempDisplay->car, name);
tempDisplay->direction = direction;
tempDisplay->next = 0;
southDisplay = tempDisplay;
}
}
pthread_mutex_unlock(&m2);
}
void arriveBridge(int paramTime)
{
printf("\\n\\tDirection: North\\n");
while ( northDisplay != 0 )
{
if ( northDisplay->direction == 'N' )
{
printf("\\t%s\\n", northDisplay->car);
exitBridge(northDisplay->direction);
}
else
{
tempDisplay = northDisplay->next;
southDisplay = northDisplay;
northDisplay = tempDisplay;
}
}
sleep(paramTime);
printf("\\tDirection: South\\n");
while ( southDisplay != 0 )
{
if ( southDisplay->direction == 'S' )
{
printf("\\t%s\\n", southDisplay->car);
}
exitBridge(southDisplay->direction);
}
sleep(paramTime);
return;
}
void exitBridge(char direction)
{
if ( direction == 'N' )
{
tempDisplay = northDisplay->next;
free(northDisplay);
northDisplay = tempDisplay;
}
else
{
tempDisplay = southDisplay->next;
free(southDisplay);
southDisplay = tempDisplay;
}
}
int empty(Q *qPointer)
{
if ( qPointer->R==0 )
return 1;
return 0;
}
| 1
|
#include <pthread.h>
struct foo *fh[29];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
};
struct foo* foo_alloc(void) {
struct foo *fp;
int idx;
if ((fp = malloc(sizeof(struct foo))) != 0) {
fp->f_count = 1;
if (pthread_mutex_init(&fp->f_lock, 0) != 0) {
free(fp);
return 0;
}
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp->f_next;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
}
return fp;
}
void foo_hold(struct foo *fp) {
pthread_mutex_lock(&fp->f_lock);
fp->f_count++;
pthread_mutex_unlock(&fp->f_lock);
}
struct foo* foo_find(int id) {
struct foo *fp;
int idx;
idx = (((unsigned long)fp)%29);
pthread_mutex_lock(&hashlock);
for (fp = fh[idx]; fp != 0; fp = fp->f_next) {
if (fp->f_id == id) {
foo_hold(fp);
break;
}
}
pthread_mutex_unlock(&hashlock);
return fp;
}
void foo_rele(struct foo *fp) {
struct foo *tfp;
int idx;
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count == 1) {
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_lock(&hashlock);
pthread_mutex_lock(&fp->f_lock);
if (fp->f_count != 1) {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
return;
}
idx = (((unsigned long)fp)%29);
tfp = fh[idx];
if (tfp == fp) {
fh[idx] = fp->f_next;
} else {
while (tfp->f_next != fp)
tfp = tfp->f_next;
tfp->f_next = fp->f_next;
}
pthread_mutex_unlock(&hashlock);
pthread_mutex_unlock(&fp->f_lock);
pthread_mutex_destroy(&fp->f_lock);
free(fp);
} else {
fp->f_count--;
pthread_mutex_unlock(&fp->f_lock);
}
}
int main() {
return 0;
}
| 0
|
#include <pthread.h>
static pthread_mutex_t ntx = PTHREAD_MUTEX_INITIALIZER;
struct _zhead;
struct list_hdr list;
struct _zhead *head;
int nr;
} znode_t;
struct list_hdr list;
struct _znode *curr;
} zhead_t;
static struct list_hdr free_node = {&free_node, &free_node};
static zhead_t nhead;
static zhead_t ahead;
static znode_t *nrptr[MAXZ] = {0};
void
zhead_init(void)
{
U_INIT_LIST_HEAD(&nhead.list);
nhead.curr = 0;
U_INIT_LIST_HEAD(&ahead.list);
ahead.curr = 0;
}
static znode_t *
znode_new(int z)
{
znode_t *zl = 0;
struct list_hdr *list;
if (!u_list_empty(&free_node)) {
list = free_node.next;
u_list_del(list);
zl = (znode_t *)list;
zl->nr = z;
} else {
zl = calloc(1, sizeof(znode_t));
if (zl) {
zl->nr = z;
U_INIT_LIST_HEAD(&zl->list);
}
}
return zl;
}
static inline void
znode_free(znode_t *zl)
{
memset(zl, 0, sizeof(znode_t));
zl->head = 0;
U_INIT_LIST_HEAD(&zl->list);
u_list_append(&zl->list, &free_node);
}
static void
znode_put(int z, zhead_t *head)
{
znode_t *zl = nrptr[z&0xffff];
DBG("--- z = %d, a = %d ---\\n", z&0xffff, z>>16);
pthread_mutex_lock(&ntx);
if (zl) {
zl->nr = z;
DBG("--- znode exists ---\\n");
if (zl->head != head) {
u_list_del(&zl->list);
u_list_add(&zl->list, &head->list);
zl->head = head;
}
} else {
zl = znode_new(z);
nrptr[z&0xffff] = zl;
u_list_add(&zl->list, &head->list);
zl->head = head;
}
head->curr = zl;
pthread_mutex_unlock(&ntx);
}
static void
znode_del(int z, zhead_t *head)
{
znode_t *zl = nrptr[z&0xffff];
struct list_hdr *list = 0;
if (!zl||zl->head != head) return;
nrptr[z&0xffff] = 0;
pthread_mutex_lock(&ntx);
if (head->curr == zl) {
list = head->curr->list.next;
}
u_list_del(&zl->list);
znode_free(zl);
if (u_list_empty(&head->list)) {
head->curr = 0;
} else if (list != 0) {
if (list == &head->list) {
list = head->list.next;
}
head->curr = (znode_t*)list;
}
pthread_mutex_unlock(&ntx);
}
void
znode_remove(int z)
{
znode_t *zl = nrptr[z&0xffff];
struct list_hdr *list = 0;
zhead_t *head;
if (!zl) return;
nrptr[z&0xffff] = 0;
head = zl->head;
pthread_mutex_lock(&ntx);
if (head->curr == zl) {
list = head->curr->list.next;
}
u_list_del(&zl->list);
znode_free(zl);
if (u_list_empty(&head->list)) {
head->curr = 0;
} else if (list != 0) {
if (list == &head->list) {
list = head->list.next;
}
head->curr = (znode_t*)list;
}
pthread_mutex_unlock(&ntx);
}
static void
znode_delp(int p, zhead_t *head)
{
struct list_hdr *list;
znode_t *zl;
int z;
pthread_mutex_lock(&ntx);
list = head->list.next;
while (list != &head->list) {
zl = (znode_t *)list;
list = list->next;
z = zl->nr & 0xffff;
if (p == pnrofz(z)) {
DBG("--- delete the arm zone-%d in pzone-%d ---\\n", z, p+1);
nrptr[z] = 0;
u_list_del(&zl->list);
znode_free(zl);
}
}
if (u_list_empty(&head->list)) {
head->curr = 0;
} else {
head->curr = (znode_t *)head->list.next;
}
pthread_mutex_unlock(&ntx);
}
static void
zlink_clear(zhead_t *head)
{
struct list_hdr *list;
znode_t *zl;
pthread_mutex_lock(&ntx);
while (!u_list_empty(&head->list)) {
list = head->list.next;
zl = (znode_t *)list;
nrptr[zl->nr&0xffff] = 0;
u_list_del(list);
znode_free(zl);
}
head->curr = 0;
pthread_mutex_unlock(&ntx);
}
static int
znode_get(zhead_t *head, int *last)
{
int z = -1;
struct list_hdr *list;
pthread_mutex_lock(&ntx);
if (head->curr != 0) {
z = head->curr->nr;
DBG("--- z = %d, a = %d ---\\n", z&0xffff, z>>16);
list = head->curr->list.next;
if (list == &head->list) {
if (last)
*last = 1;
list = head->list.next;
DBG("--- end of the list ---\\n");
}
head->curr = (znode_t*)list;
}
pthread_mutex_unlock(&ntx);
return z;
}
void
nready_put(int z)
{
znode_put(z, &nhead);
}
void
nready_del(int z)
{
znode_del(z, &nhead);
}
void
nready_clear(void)
{
zlink_clear(&nhead);
}
int
nready_get(int *last)
{
return znode_get(&nhead, last);
}
int
nready_yet(void)
{
return (!u_list_empty(&nhead.list));
}
void
alarmst_put(int z, int a)
{
DBG("--- z = %d, a = %d ---\\n", z, a);
znode_put(z|(a<<16), &ahead);
}
void
alarmst_del(int z)
{
znode_del(z, &ahead);
}
void
alarmst_clear(void)
{
zlink_clear(&ahead);
}
int
alarmst_get(int *last)
{
return znode_get(&ahead, last);
}
void
alarmst_clearpz(int p)
{
znode_delp(p, &ahead);
}
| 1
|
#include <pthread.h>
char buffer[100];
pthread_t ctid[10];
pthread_t ptid[5];
FILE *fpprod,*fpcons;
pthread_mutex_t mutex;
sem_t full,empty;
int counter,flag;
void *prod(void *arg);
void *cons(void *arg);
void initialize();
void insert_item();
void delete_item();
char switchBuffer();
int main()
{
initialize();
int i,rv;
for (i = 0;i < 5;i++)
{
rv = pthread_create(&ptid[i],0,prod,0);
if (rv)
{
printf("ERROR; return code from pthread_create() is %d\\n", rv);
exit(-1);
}
}
for (i = 0;i < 10;i++)
{
rv = pthread_create(&ctid[i],0,cons,0);
if (rv)
{
printf("ERROR; return code from pthread_create() is %d\\n", rv);
exit(-1);
}
}
sleep(10);
fclose(fpprod);
fclose(fpcons);
}
void initialize()
{
fpprod = fopen("input.txt","r");
fpcons = fopen("output.txt","w");
pthread_mutex_init(&mutex,0);
sem_init(&empty,0,100);
sem_init(&full,0,0);
counter = 0;
flag =0;
}
void *prod(void *arg)
{
while(1)
{
sem_wait(&empty);
pthread_mutex_lock(&mutex);
insert_item();
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *cons(void *arg)
{
while(1)
{
sem_wait(&full);
pthread_mutex_lock(&mutex);
delete_item();
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
void insert_item()
{
char ch;
if (counter<100&&flag==0)
{
ch = fgetc(fpprod);
if (ch==EOF)
{
flag =1;
return;
}
buffer[counter++]=ch;
}
}
void delete_item()
{
char ch;
if (counter>0)
{
ch = switchBuffer();
fputc(ch,fpcons);
}
}
char switchBuffer()
{
int i;
char ch = buffer[0];
for (i =0 ;i<counter;i++)
{
buffer[i]=buffer[i+1];
}
counter--;
return ch;
}
| 0
|
#include <pthread.h>
int SharedVariable = 0;
pthread_mutex_t mutex;
pthread_barrier_t barr;
void SimpleThread(int which) {
int num, val;
for(num = 0; num < 20; num++) {
if (random() > 32767 / 2){
usleep(10);
}
pthread_mutex_lock(&mutex);
val = SharedVariable;
printf("*** thread %d sees value %d\\n", which, val);
SharedVariable = val + 1;
pthread_mutex_unlock(&mutex);
}
pthread_barrier_wait(&barr);
val = SharedVariable;
printf("Thread %d sees final value %d\\n", which, val);
}
int main(int argc, char const *argv[])
{
int threads = 0;
pthread_t thread_ID;
if(argc != 2)
{
perror("Wrong number of arguments.\\n");
exit(1);
}
else
{
if (sscanf(argv[1], "%d", &threads) != 1)
{
perror("Invalid input\\n");
exit(1);
}
pthread_t thr[threads];
if(pthread_barrier_init(&barr, 0, threads))
{
printf("Could not create a barrier\\n");
return -1;
}
if(pthread_mutex_init(&mutex, 0))
{
printf("Unable to initialize a mutex\\n");
return -1;
}
for(int i = 0; i < threads; i++)
{
if(pthread_create(&thr[i], 0, (void *) SimpleThread, (void *)(intptr_t) i))
{
printf("Could not create thread %d\\n", i);
return -1;
}
}
for(int i = 0; i < threads; i++)
{
if(pthread_join(thr[i], 0))
{
printf("Could not join thread %d\\n", i);
return -1;
}
}
}
return 0;
}
| 1
|
#include <pthread.h>
int shared_var = 0;
int readcount = 0;
sem_t sem_readers_done;
sem_t sem_access;
pthread_mutex_t mutex_readcount;
void initialize()
{
sem_init(&sem_readers_done,0,1);
sem_init(&sem_access,0,1);
pthread_mutex_init(&mutex_readcount,0);
}
void* reader(void *data)
{
sem_wait(&sem_access);
pthread_mutex_lock(&mutex_readcount);
readcount++;
if (readcount == 1)
{
sem_wait(&sem_readers_done);
}
pthread_mutex_unlock(&mutex_readcount);
sem_post(&sem_access);
printf("reading shared var : %d\\n",shared_var);
pthread_mutex_lock(&mutex_readcount);
readcount--;
if (readcount == 0)
{
sem_post(&sem_readers_done);
}
pthread_mutex_unlock(&mutex_readcount);
}
void* writer(void *data)
{
sem_wait(&sem_access);
sem_wait(&sem_readers_done);
shared_var = (int)data;
printf("writing shared var : %d\\n", shared_var);
sem_post(&sem_access);
sem_post(&sem_readers_done);
}
int main(int argc,char *argv[])
{
if (argc !=3)
{
fprintf(stderr, "Error : use the following format <executable> num_readers num_writers. eg : ./a.out 3 4\\n");
return 0;
}
initialize();
int num_readers = atoi(argv[1]);
int num_writers = atoi(argv[2]);
num_readers = (num_readers < (30>>1)) ? num_readers : 30>>1;
num_writers = (num_writers < (30>>1)) ? num_writers : 30>>1;
pthread_t reader_threads[num_readers];
pthread_t writer_threads[num_writers];
int i=0;
for(i=0;i<num_writers;i++)
{
pthread_create(&writer_threads[i],0,writer,(void*)i);
}
for(i=0;i<num_readers;i++)
{
pthread_create(&reader_threads[i],0,reader,0);
}
for(i=0;i<num_readers;i++)
{
pthread_join(reader_threads[i],0);
}
for(i=0;i<num_writers;i++)
{
pthread_join(writer_threads[i],0);
}
return 0;
}
| 0
|
#include <pthread.h>
char *nombre, *pareja;
int listo;
struct nodo *prox;
} Nodo;
void bailar_con(char * pareja){}
void alimentarse(){}
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
Nodo *mujeres;
Nodo *hombres;
void emparejar(char sexo, char *nombre, char *pareja){
Nodo nodo;
nodo.nombre = nombre;
nodo.pareja = pareja;
nodo.listo = 0;;
pthread_mutex_lock(&m);
if(sexo=='m'){
if(mujeres != 0){
strcpy(pareja, mujeres->nombre);
strcpy(mujeres->pareja, nombre);
mujeres->listo = 1;;
mujeres = mujeres->prox;
}
else{
nodo.prox = hombres;
hombres = &nodo;
while(!nodo.listo)
pthread_cond_wait(&cond,&m);
}
}
else{
if(hombres != 0){
strcpy(pareja, hombres->nombre);
strcpy(hombres->pareja, nombre);
hombres->listo = 1;;
hombres = hombres->prox;
}
else{
nodo.prox = mujeres;
mujeres = &nodo;
while(!nodo.listo)
pthread_cond_wait(&cond,&m);
}
}
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&m);
}
void hombre(char *nombre){
for(;;){
char pareja[100];
emparejar('m', nombre, pareja);
bailar_con(pareja);
alimentarse();
}
}
void mujer(char *nombre){
for(;;){
char pareja[100];
emparejar('f', nombre, pareja);
bailar_con(pareja);
alimentarse();
}
}
int main(int argc, char* argv[]){
hombres = (Nodo*)malloc(sizeof(Nodo));
mujeres = (Nodo*)malloc(sizeof(Nodo));
}
| 1
|
#include <pthread.h>
data_t input_vec[4];
data_t ***SV;
int NUM_EL[4];
int MAX_EL = 800;
pthread_t thread[4 - 1];
pthread_barrier_t barr;
pthread_mutex_t lock;
float GLOB_SUM = 0;
void get_data(int rank, data_t** SV)
{
char filename[256] = {"input_svm/model_"};
int base_fname_length = 16, i, j;
char rank_str[20];
int curr_index = 0;
int ret_val;
sprintf(rank_str, "%d", rank);
for(i = 0; rank_str[i] != '\\0'; i++)
filename[base_fname_length + i] = rank_str[i];
filename[base_fname_length + i] = '\\0';
FILE *fp = fopen(filename, "r");
assert(fp);
while (fscanf(fp, "%f", &SV[curr_index][0]) != EOF) {
for(j = 1; j < 4 +1; j++)
ret_val = fscanf(fp, "%f", &SV[curr_index][j]);
if(ret_val <= 0)
printf("error reading file\\n");
curr_index++;
if(curr_index == 100)
break;
}
NUM_EL[rank] = curr_index/4;
fclose(fp);
}
void get_input()
{
char filename[256] = {"input_svm/input"};
int curr_index = 0;
FILE *fp = fopen(filename, "r");
assert(fp);
while (fscanf(fp, "%f", &input_vec[curr_index]) != EOF) {
curr_index++;
}
fclose(fp);
}
float compute_svm_sum(int rank, float gamma, data_t ** SV)
{
int i, j;
float sum = 0;
for(i = 0; i < NUM_EL[rank]; i++)
{
float dot_prod = 0;
for(j = 1; j < 4 +1; j++)
dot_prod += (input_vec[j-1] - SV[i][j]) * (input_vec[j-1] - SV[i][j]);
sum += SV[i][0] * exp(-gamma*dot_prod);
}
return sum;
}
void free_data(data_t **SV)
{
int i = 0;
for(i=0; i<MAX_EL; i++)
free(SV[i]);
free(SV);
}
void* thread_function(void* thread_id)
{
int id = (int)thread_id;
float sum;
int i;
float gamma = 0.25;
float rho = -0.495266;
for (i = 0; i < 50; ++i) {
pthread_barrier_wait(&barr);
sum = compute_svm_sum(id, gamma, SV[id%4]);
pthread_mutex_lock(&lock);
GLOB_SUM += sum;
pthread_mutex_unlock(&lock);
pthread_barrier_wait(&barr);
if(id==0){
pthread_mutex_lock(&lock);
GLOB_SUM -= rho;
pthread_mutex_unlock(&lock);
}
}
}
int main(int argc, char *argv[])
{
int rank;
int n_ranks;
get_input();
int i;
int j;
SV = (data_t***)malloc(4*sizeof(data_t**));
for (i = 0; i < 4; ++i)
{
SV[i] = (data_t**)malloc(MAX_EL*sizeof(data_t*));
for(j=0; j<MAX_EL; j++)
SV[i][j] = (data_t*)malloc((4 +1)*sizeof(data_t));
}
pthread_mutex_init(&lock, 0);
for (i=0; i<4; i++){
get_data(i%4, SV[i%4]);
}
pthread_barrier_init(&barr, 0, 4);
int thread_id;
for(thread_id=0; thread_id < 4 - 1; thread_id++)
{
pthread_create( &thread[thread_id], 0, thread_function, (void*) thread_id);
}
thread_function((void*) (thread_id));
for (i = 0; i < 4; ++i)
{
free_data(SV[i]);
}
free(SV);
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t order_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t condition_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_cond = PTHREAD_COND_INITIALIZER;
void *functionorder1();
void *functionorder2();
int order = 1;
main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionorder1, 0);
pthread_create( &thread2, 0, &functionorder2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
exit(0);
}
void *functionorder1()
{
int sleep_time;
for(;;)
{
printf("functionorder1 1\\n");
pthread_mutex_lock( &condition_mutex );
if( order != 1 ){
printf("functionorder1 2\\n");
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
printf("functionorder1 3\\n");
sleep_time = rand() % 10;
printf("functionorder1 sleep %d\\n",sleep_time);
sleep(sleep_time);
pthread_mutex_lock( &order_mutex );
order = 2;
pthread_mutex_unlock( &order_mutex );
printf("functionorder1 4\\n");
pthread_mutex_lock( &condition_mutex );
pthread_cond_signal(&condition_cond);
pthread_mutex_unlock( &condition_mutex );
printf("functionorder1 5\\n");
}
}
void *functionorder2()
{
int sleep_time;
for(;;)
{
printf("functionorder2 1\\n");
pthread_mutex_lock( &condition_mutex );
if( order != 2){
printf("functionorder2 2\\n");
pthread_cond_wait( &condition_cond, &condition_mutex );
}
pthread_mutex_unlock( &condition_mutex );
printf("functionorder2 3\\n");
sleep_time = 3;
printf("functionorder2 sleep %d\\n",sleep_time);
sleep(sleep_time);
pthread_mutex_lock( &order_mutex );
order = 1;
pthread_mutex_unlock( &order_mutex );
printf("functionorder2 4\\n");
pthread_mutex_lock( &condition_mutex );
pthread_cond_signal(&condition_cond);
pthread_mutex_unlock( &condition_mutex );
printf("functionorder2 5\\n");
}
}
| 1
|
#include <pthread.h>
int host_handler(int sig){
printf("SIGUSR2 catched\\n");
return 0;
}
void hostPlSend(struct sthread* ptr){
msg_send(ptr->desc, MSG_HOST_PL, sizeof(int), &team_arr[ptr->team_id].pl_cnt);
}
void hoStatSend(struct sthread* ptr){
}
void team_gameplay(struct sthread* ptr){
int poll_ret;
int flag = 1;
struct pollfd polls;
size_t size = 0;
int type = 0;
int msg_ret = 0;
void* buf = 0;
printf("Team_game\\n");
polls.fd = ptr->desc;
polls.events = POLLIN | POLLERR | POLLHUP;
polls.revents = 0;
while (flag)
{
printf("POLL\\n");
fflush(stdout);
poll_ret = poll(&polls, 1, -1);
if (poll_ret == -1)
{
hostPlSend(ptr);
}
if (polls.revents & POLLERR) {
err_report("poll returned POLLERR\\n", 0);
return;
}
if (polls.revents & POLLHUP) {
err_report("poll returned POLLHUP\\n", 0);
return;
}
if (polls.revents & POLLIN)
{
msg_ret = msg_rec(ptr->desc, &type, &size, &buf);
if (type == MSG_INFO_STRING && !strcmp((char*)buf,start))
{
pthread_mutex_lock(&team_arr[ptr->team_id].mutex);
team_arr[ptr->team_id].status = ST_PLAYING;
flag = 0;
pthread_mutex_unlock(&team_arr[ptr->team_id].mutex);
}
if (type == MSG_INFO_STRING && !strcmp((char*)buf,disc))
{
free(buf);
buf = 0;
disconnect(ptr);
return;
}
}
polls.revents = 0;
}
polls.revents = 0;
mapClone(&team_arr[ptr->team_id]);
wakeSign(ptr->team_id);
pause();
wakeCond(ptr->team_id);
msg_send(ptr->desc, MSG_INFO_STRING, strlen(start) + 1, start);
msg_ret = clock_gettime(CLOCK_MONOTONIC, &team_arr[ptr->team_id].start);
flag = 1;
while (flag){
poll_ret = poll(&polls, 1, -1);
if (poll_ret == -1)
{
err_report("signal caught\\n", 1);
}
if (polls.revents & POLLERR) {
err_report("poll returned POLLERR\\n", 0);
return;
}
if (polls.revents & POLLHUP) {
err_report("poll returned POLLHUP\\n", 0);
return;
}
if (polls.revents & POLLIN){
msg_ret = msg_rec(ptr->desc, &type, &size, &buf);
if (type == MSG_INFO_STRING || !strcmp((char*)buf, disc)){
flag = 0;
}
}
polls.revents = 0;
}
free(buf);
disconnect(ptr);
}
| 0
|
#include <pthread.h>
void* thread_task(void* param);
static const unsigned g_UNSIGNED_NBITS = sizeof(unsigned) * CHAR_BIT;
static const unsigned g_PID_ARR_LENGTH =
((5000 - 300) + sizeof(unsigned)*CHAR_BIT - 1)/(sizeof(unsigned)*CHAR_BIT);
static unsigned* g_pid_table;
static pthread_mutex_t mutex;
int allocate_map(void) {
g_pid_table = malloc(g_PID_ARR_LENGTH * sizeof(*g_pid_table));
for (int i = 0; i < g_PID_ARR_LENGTH; i++) {
g_pid_table[i] = 0;
}
return 1;
}
int allocate_pid(void) {
unsigned current_pid = 300;
unsigned track_unsigned;
for (int i = 0; i < g_PID_ARR_LENGTH; i++) {
track_unsigned = g_pid_table[i];
for (int j = 0; j < g_UNSIGNED_NBITS; j++) {
if (current_pid > 5000)
return 1;
if (!(track_unsigned & 1)) {
g_pid_table[i] |= (1 << j);
return current_pid;
}
current_pid += 1;
track_unsigned >>= 1;
}
}
return 1;
}
void release_pid(int pid) {
int pid_table_index;
int pid_bit_num;
unsigned mask_pid = ~0;
if (pid > 5000 || pid < 300)
return;
pid -= 300;
pid_bit_num = pid % g_UNSIGNED_NBITS;
pid_table_index = pid/g_UNSIGNED_NBITS;
mask_pid ^= (1 << pid_bit_num);
g_pid_table[pid_table_index] &= mask_pid;
}
void print_map() {
printf("Bitmap:\\n");
printf("Bitmap length: %x sizeof unsigned: %lu\\n", g_PID_ARR_LENGTH, sizeof(unsigned));
for (int i = 0; i < g_PID_ARR_LENGTH; i++) {
unsigned current_entry = g_pid_table[i];
if (current_entry)
printf("%d: %x\\n", i, g_pid_table[i]);
}
printf("\\n");
}
void* thread_task(void* param) {
pthread_mutex_lock(&mutex);
int pid = allocate_pid();
print_map();
pthread_mutex_unlock(&mutex);
sleep(3);
pthread_mutex_lock(&mutex);
release_pid(pid);
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main()
{
int i;
int num_threads = 5;
pthread_t threads[num_threads];
allocate_map();
pthread_mutex_init(&mutex, 0);
for (i = 0; i < num_threads; i++) {
if (pthread_create(&threads[i], 0, thread_task, 0) != 0) {
printf("ERROR: Pthread created incorrectly.\\n");
exit(0);
}
}
for (i = 0; i < num_threads; i++) {
pthread_join(threads[i], 0);
}
print_map();
free(g_pid_table);
return 0;
}
| 1
|
#include <pthread.h>
struct threadSafeList* threadList;
struct threadSafeList* SHList;
struct threadSafeList * listCreate() {
struct threadSafeList *list = (struct threadSafeList *) malloc(sizeof(struct threadSafeList));
list->count = 0;
list->head = 0;
list->tail = 0;
pthread_mutex_init(&(list->mutex), 0 );
return list;
}
void listDestroy(struct threadSafeList *l) {
struct listItem *listItem, *tempListItem;
pthread_mutex_lock(&(l->mutex));
if (l != 0 ) {
listItem = l->head;
while (listItem != 0 ) {
tempListItem = listItem->next;
free(listItem);
listItem = tempListItem;
}
}
pthread_mutex_unlock(&(l->mutex));
pthread_mutex_destroy(&(l->mutex));
free(l);
}
struct listItem * listAdd(struct threadSafeList *l, void *content) {
struct listItem *listItem;
pthread_mutex_lock(&(l->mutex));
listItem = (struct listItem *) malloc(sizeof(struct listItem));
listItem->value = content;
listItem->next = 0;
listItem->prev = l->tail;
if (l->tail == 0 ) {
l->head = l->tail = listItem;
} else {
l->tail->next = listItem;
l->tail = listItem;
}
l->count++;
pthread_mutex_unlock(&(l->mutex));
return listItem;
}
int listRemove(struct threadSafeList *l, void *content) {
int result = 0;
struct listItem *listItem = l->head;
pthread_mutex_lock(&(l->mutex));
while (listItem != 0 ) {
if (listItem->value == content) {
if (listItem->prev == 0 ) {
l->head = listItem->next;
} else {
listItem->prev->next = listItem->next;
}
if (listItem->next == 0 ) {
l->tail = listItem->prev;
} else {
listItem->next->prev = listItem->prev;
}
l->count--;
free(listItem);
result = 1;
break;
}
listItem = listItem->next;
}
pthread_mutex_unlock(&(l->mutex));
return result;
}
void listJoinThreads(struct threadSafeList *l) {
struct listItem *listItem;
void *status;
listItem = l->head;
while (listItem != 0 ) {
pthread_join((pthread_t) listItem->value, &status);
listItem = listItem->next;
}
}
void * listGetMemoryLocation(struct threadSafeList *l, pthread_t thread_id) {
struct listItem *listItem;
listItem = l->head;
while (listItem != 0 ) {
struct shMapType * shMapItem = (struct shMapType *) listItem->value;
if ((unsigned) shMapItem->thread_id == (unsigned) thread_id) {
return shMapItem;
}
listItem = listItem->next;
}
return 0;
}
void * listGetMallocedMemoryAdr(struct threadSafeList *l, void * adr) {
struct listItem *listItem;
listItem = l->head;
while (listItem != 0 ) {
if (adr == listItem->value) {
return adr;
}
listItem = listItem->next;
}
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t locki[26];
pthread_mutex_t lockb[26];
int busy[26];
int inode[32];
pthread_t tids[26];
void *thread_routine(void * arg)
{
int i,b;
int tid;
tid = (int)arg;
i = tid % 32;
pthread_mutex_lock( &locki[i] );
if( inode[i]==0 )
{
b = (i*2) % 26;
while(1)
{
pthread_mutex_lock( &lockb[b] );
if( !busy[b] )
{
busy[b] = 1;
inode[i] = b+1;
printf(" ");
pthread_mutex_unlock( &lockb[b] );
break;
}
pthread_mutex_unlock( &lockb[b] );
b = (b+1) % 26;
}
}
pthread_mutex_unlock( &locki[i] );
pthread_exit(0);
}
int main()
{
int i;
for(i = 0; i < 26;i++)
{
pthread_mutex_init(&locki[i],0);
pthread_mutex_init(&lockb[i],0);
busy[i] = 0;
}
for(i=0;i<26;i++)
pthread_create(&tids[i], 0, thread_routine, (void *)(i));
for(i=0;i<26;i++)
pthread_join(tids[i], 0);
for(i=0;i<26;i++)
{
pthread_mutex_destroy(&locki[i]);
pthread_mutex_destroy(&lockb[i]);
}
return 0;
}
| 1
|
#include <pthread.h>
void __VERIFIER_error() { abort(); };
int __VERIFIER_nondet_int() {int n; return n;}
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 (get_top()==0)
{
printf("stack underflow\\n");
return (-2);
}
else
{
dec_top();
return stack[get_top()];
}
return 0;
}
void *t1(void *arg)
{
int i;
unsigned int tmp;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
tmp = __VERIFIER_nondet_uint()%(800);
if (push(arr,tmp)==(-1))
error();
flag=(1);
pthread_mutex_unlock(&m);
}
}
void *t2(void *arg)
{
int i;
for(i=0; i<(800); i++)
{
pthread_mutex_lock(&m);
if (flag)
{
if (!(pop(arr)!=(-2)))
error();
}
pthread_mutex_unlock(&m);
}
}
int main(void)
{
pthread_t id1, id2;
pthread_mutex_init(&m, 0);
pthread_create(&id1, 0, t1, 0);
pthread_create(&id2, 0, t2, 0);
pthread_join(id1, 0);
pthread_join(id2, 0);
return 0;
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.