text
stringlengths 192
6.24k
| label
int64 0
1
|
|---|---|
#include <pthread.h>
pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condition_var = PTHREAD_COND_INITIALIZER;
void *functionCount1();
void *functionCount2();
int count = 0;
int main()
{
pthread_t thread1, thread2;
pthread_create( &thread1, 0, &functionCount1, 0);
pthread_create( &thread2, 0, &functionCount2, 0);
pthread_join( thread1, 0);
pthread_join( thread2, 0);
printf("Final count: %d\\n",count);
exit(0);
}
void *functionCount1()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\\n",count);
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
void *functionCount2()
{
for(;;)
{
pthread_mutex_lock( &count_mutex );
if( count < 3 || count > 6 )
{
pthread_cond_signal( &condition_var );
}
else
{
count++;
printf("Counter value functionCount2: %d\\n",count);
}
pthread_mutex_unlock( &count_mutex );
if(count >= 10) return(0);
}
}
| 1
|
#include <pthread.h>
pthread_mutex_t lock;
int g_request = 0;
int g_serviced = 0;
void* getFile(void* arg);
void cleanUp(int sigNum);
int main(){
signal(SIGINT, cleanUp);
int status;
srand(time(0));
while(1){
char fileName[255];
printf("Enter Filename: ");
scanf(" %s", fileName);
pthread_t thread;
status = pthread_create(&thread, 0, getFile, fileName);
if(0 != status){
printf("thread creation error\\n");
return 1;
}
g_request++;
}
return 0;
}
void* getFile(void* arg){
char fileName[255];
strcpy(fileName, (char*) arg);
int sleepChance = rand() % 5;
int sleepTime;
if(0 == sleepChance){
sleepTime = (rand() % 3) + 7;
sleep(sleepTime);
printf("\\nFile %s read from hard drive after %d seconds.\\n", fileName, sleepTime);
} else {
sleepTime = 1;
sleep(sleepTime);
printf("\\nFile %s found in cache after %d seconds.\\n", fileName, sleepTime);
}
pthread_mutex_lock(&lock);
g_serviced++;
pthread_mutex_unlock(&lock);
return 0;
}
void cleanUp(int sigNum){
pthread_mutex_lock(&lock);
printf("\\n\\n%d files requested\\n%d files serviced\\n", g_request, g_serviced);
pthread_mutex_unlock(&lock);
exit(0);
}
| 0
|
#include <pthread.h>
int sum = 0;
pthread_mutex_t common_mutex = PTHREAD_MUTEX_INITIALIZER;
long tasks[5];
void *worker_thread(void *arg) {
for(int a = 0; a < 5; a++) {
int ret = pthread_mutex_lock(&common_mutex);
if(ret == EINVAL) {
printf("Encountered an error trying to lock mutex\\n");
}
if( sum < 15 ) {
sleep(1);
printf("incrementing sum\\n");
sum++;
} else {
}
pthread_mutex_unlock(&common_mutex);
}
pthread_exit(0);
}
int main() {
pthread_t my_thread[5];
long id;
for (id = 0; id < 5; id++) {
tasks[id] = id;
int ret = pthread_create(&my_thread[id], 0, &worker_thread, (void*) tasks[id]);
}
for (id = 0; id < 5; id++) {
pthread_join(my_thread[id], 0);
printf("thread %ld is done\\n", id);
}
printf("main program done - sum = %d\\n", sum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
static uint16_t g_curId = 0;
static pthread_mutex_t g_idMutex = PTHREAD_MUTEX_INITIALIZER;
int ip_calc_checksum(struct ip *packet)
{
int oldsum = packet->ip_sum;
packet->ip_sum = 0;
packet->ip_sum = ip_sum((char *)packet, sizeof(struct ip));
return oldsum == packet->ip_sum;
}
struct ip *ip_packet_construct(
struct in_addr src, struct in_addr dest,
int DNF, uint8_t timeToLive, uint8_t protocol,
void *data, uint16_t datalen)
{
struct ip *packet;
if (datalen > 65535 - sizeof(struct ip))
{
dbg(DBG_NET, "ip_packet_construct: Can't construct packet. length %d is too large.\\n", datalen);
return 0;
}
packet = (struct ip *)malloc(sizeof(struct ip) + datalen);
memcpy(packet+1, data, datalen);
packet->ip_v = 4;
packet->ip_hl = 5;
packet->ip_tos = 0;
packet->ip_len = sizeof(struct ip) + datalen;
pthread_mutex_lock(&g_idMutex);
packet->ip_id = g_curId;
++g_curId;
pthread_mutex_unlock(&g_idMutex);
packet->ip_off = 0;
(DNF ? (packet->ip_off |= 0x8000) : (packet->ip_off &= 0x7FFF));
packet->ip_ttl = timeToLive;
packet->ip_p = protocol;
packet->ip_src = src;
packet->ip_dst = dest;
packet->ip_sum = 0;
return packet;
}
void ip_packet_destruct(struct ip *packet)
{
if (packet == 0) return;
free(packet);
}
void ip_packet_hton(struct ip *packet)
{
packet->ip_len = htons(packet->ip_len);
packet->ip_id = htons(packet->ip_id);
packet->ip_off = htons(packet->ip_off);
packet->ip_src.s_addr = htonl(packet->ip_src.s_addr);
packet->ip_dst.s_addr = htonl(packet->ip_dst.s_addr );
packet->ip_sum = htons(packet->ip_sum);
}
void ip_packet_ntoh(struct ip *packet)
{
packet->ip_len = ntohs(packet->ip_len);
packet->ip_id = ntohs(packet->ip_id);
packet->ip_off = ntohs(packet->ip_off);
packet->ip_src.s_addr = ntohl(packet->ip_src.s_addr);
packet->ip_dst.s_addr = ntohl(packet->ip_dst.s_addr );
packet->ip_sum = ntohs(packet->ip_sum);
}
void ip_packet_print(struct ip *packet, int printData)
{
static char maxstr[65535];
printf("src: %s\\n", inet_ntoa_host(packet->ip_src));
printf("dst: %s\\n", inet_ntoa_host(packet->ip_dst));
printf("totalLength: %d\\n"
"DNF: %d\\n"
"MF: %d\\n"
"fragOffset: %d\\n"
"id: %d\\n"
"TTL: %d\\n"
"protocol: %d\\n"
"checksum: %x\\n",
packet->ip_len,
((0x8000 & (packet->ip_off)) >> 15),
((0x4000 & (packet->ip_off)) >> 14),
((0x3FFF & (packet->ip_off))),
packet->ip_id,
packet->ip_ttl,
packet->ip_p,
packet->ip_sum);
if (printData) {
printf("data:\\n");
if (printData == 1) {
for (unsigned int i=0; i < packet->ip_len - sizeof(struct ip); ++i)
{
printf("%02x ", ((uint8_t *)(packet+1))[i]);
if (i%20==0) printf("\\n");
}
}
else if (printData == 2) {
memcpy(maxstr, packet+1, packet->ip_len - sizeof(struct ip));
maxstr[packet->ip_len - sizeof(struct ip)] = '\\0';
printf("%s\\n", maxstr);
}
}
}
char *inet_ntoa_host(struct in_addr a)
{
struct in_addr tmp;
tmp.s_addr = htonl(a.s_addr);
return inet_ntoa(tmp);
}
| 0
|
#include <pthread.h>
struct sem_t {
int count;
int access;
pthread_mutex_t mutex;
};
int sem_post(struct sem_t * sem);
int sem_wait(struct sem_t * sem);
int sem_init(struct sem_t * sem, int start_access, int init);
void wait(struct sem_t * sem);
int rem();
void add(int val);
void printbuf();
int sem_init(struct sem_t * sem, int start_access, int init) {
sem->count = init;
sem->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
sem->access = start_access;
}
int sem_post(struct sem_t * sem) {
pthread_mutex_lock(&sem->mutex);
sem->count += 1;
sem->access = 1;
pthread_mutex_unlock(&sem->mutex);
}
int sem_wait(struct sem_t * sem) {
pthread_mutex_lock(&sem->mutex);
sem->count -= 1;
if (sem-> count <= 0) {
wait(sem);
}
sem->access = 0;
pthread_mutex_unlock(&sem->mutex);
}
void wait(struct sem_t * sem) {
while (!sem->access) {
pthread_mutex_unlock(&sem->mutex);
sleep(1);
pthread_mutex_lock(&sem->mutex);
}
}
struct sem_t sem_pro;
struct sem_t sem_con;
pthread_mutex_t mut_buf;
void init_buff_semas(struct sem_t * prod,
struct sem_t * con) {
sem_init(prod, 1, 4);
sem_init(con, 0, 0);
}
int buf[4];
int first_occupied_slot = 0;
int first_empty_slot = 0;
void add(int val) {
buf[first_empty_slot] = val;
first_empty_slot = (first_empty_slot + 1) % 4;
}
int rem() {
int val = buf[first_occupied_slot];
first_occupied_slot = (first_occupied_slot + 1) % 4;
return val;
}
void *producer(void *arg) {
int work_item = 0;
while (1) {
sleep( rand() % 5 );
sem_wait(&sem_pro);
pthread_mutex_lock(&mut_buf);
work_item = work_item + 1;
add(work_item);
pthread_mutex_unlock(&mut_buf);
sem_post(&sem_con);
}
}
void *consumer(void *arg) {
while (1) {
int work_item;
sleep( rand() % 5 );
sem_wait(&sem_con);
pthread_mutex_lock(&mut_buf);
work_item = rem();
pthread_mutex_unlock(&mut_buf);
sem_post(&sem_pro);
printf("%d ", work_item);
fflush(stdout);
}
}
void printbuf() {
printf("[");
for (int i = 0; i < 4; i++) {
printf(",%d", buf[i]);
}
printf("]");
}
int main() {
init_buff_semas(&sem_pro, &sem_con);
mut_buf = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
int threads = 3;
pthread_t tproducers[threads];
pthread_t tconsumers[threads];
for (int i = 0; i < threads; i++) {
pthread_create(&tproducers[i], 0, producer, 0);
pthread_create(&tconsumers[i], 0, consumer, 0);
}
for (int i = 0; i < threads; i++) {
pthread_join(tproducers[i], 0);
pthread_join(tconsumers[i], 0);
}
return 0;
}
| 1
|
#include <pthread.h>
struct queue_root {
struct queue_head *head;
pthread_mutex_t head_lock;
struct queue_head *tail;
pthread_mutex_t tail_lock;
struct queue_head divider;
};
struct queue_root *ALLOC_QUEUE_ROOT()
{
struct queue_root *root =
malloc(sizeof(struct queue_root));
pthread_mutex_init(&root->head_lock, 0);
pthread_mutex_init(&root->tail_lock, 0);
root->divider.next = 0;
root->head = &root->divider;
root->tail = &root->divider;
return root;
}
void INIT_QUEUE_HEAD(struct queue_head *head)
{
head->next = ((void*)0xCAFEBAB5);
}
void queue_put(struct queue_head *new,
struct queue_root *root)
{
new->next = 0;
pthread_mutex_lock(&root->tail_lock);
root->tail->next = new;
root->tail = new;
pthread_mutex_unlock(&root->tail_lock);
}
struct queue_head *queue_get(struct queue_root *root)
{
struct queue_head *head, *next;
while (1) {
pthread_mutex_lock(&root->head_lock);
head = root->head;
next = head->next;
if (next == 0) {
pthread_mutex_unlock(&root->head_lock);
return 0;
}
root->head = next;
pthread_mutex_unlock(&root->head_lock);
if (head == &root->divider) {
queue_put(head, root);
continue;
}
head->next = ((void*)0xCAFEBAB5);
return head;
}
}
struct queue_root *queue;
void Enqueue(int v) {
struct queue_head *item = malloc(sizeof(struct queue_head));
INIT_QUEUE_HEAD(item);
item->value = v;
queue_put(item,queue);
}
int Dequeue() {
struct queue_head *item = queue_get(queue);
if (item == 0) return 2;
else return item->value;
}
void Init() {
queue = ALLOC_QUEUE_ROOT();
}
| 0
|
#include <pthread.h>
void *philosopher (void *id);
void grab_chopstick (int,
int,
char *);
void down_chopsticks (int,
int);
int food_on_table ();
int get_token ();
void return_token ();
pthread_mutex_t chopstick[5];
pthread_t philo[5];
pthread_mutex_t food_lock;
pthread_mutex_t num_can_eat_lock;
int sleep_seconds = 0;
uint32_t num_can_eat = 5 - 1;
int
main (int argn,
char **argv)
{
int i;
pthread_mutex_init (&food_lock, 0);
pthread_mutex_init (&num_can_eat_lock, 0);
for (i = 0; i < 5; i++)
pthread_mutex_init (&chopstick[i], 0);
for (i = 0; i < 5; i++)
pthread_create (&philo[i], 0, philosopher, (void *)i);
for (i = 0; i < 5; i++)
pthread_join (philo[i], 0);
return 0;
}
void *
philosopher (void *num)
{
int id;
int i, left_chopstick, right_chopstick, f;
id = (int)num;
printf ("Philosopher %d is done thinking and now ready to eat.\\n", id);
right_chopstick = id;
left_chopstick = id + 1;
if (left_chopstick == 5)
left_chopstick = 0;
while (f = food_on_table ()) {
get_token ();
grab_chopstick (id, right_chopstick, "right ");
grab_chopstick (id, left_chopstick, "left");
printf ("Philosopher %d: eating.\\n", id);
usleep (5000 * (100 - f + 1));
down_chopsticks (left_chopstick, right_chopstick);
return_token ();
}
printf ("Philosopher %d is done eating.\\n", id);
return (0);
}
int
food_on_table ()
{
static int food = 100;
int myfood;
pthread_mutex_lock (&food_lock);
if (food > 0) {
food--;
}
myfood = food;
pthread_mutex_unlock (&food_lock);
return myfood;
}
void
grab_chopstick (int phil,
int c,
char *hand)
{
pthread_mutex_lock (&chopstick[c]);
printf ("Philosopher %d: got %s chopstick %d\\n", phil, hand, c);
}
void
down_chopsticks (int c1,
int c2)
{
pthread_mutex_unlock (&chopstick[c1]);
pthread_mutex_unlock (&chopstick[c2]);
}
int
get_token ()
{
int successful = 0;
while (!successful) {
pthread_mutex_lock (&num_can_eat_lock);
if (num_can_eat > 0) {
num_can_eat--;
successful = 1;
}
else {
successful = 0;
}
pthread_mutex_unlock (&num_can_eat_lock);
}
}
void
return_token ()
{
pthread_mutex_lock (&num_can_eat_lock);
num_can_eat++;
pthread_mutex_unlock (&num_can_eat_lock);
}
| 1
|
#include <pthread.h>
unsigned long int time_1;
unsigned long int time_2;
char msg_temp[MSG_LEN];
int sec;
char msg[MSG_LEN];
struct st_alarm *next;
} set_alarm;
struct mut {
pthread_mutex_t th_mutex;
pthread_cond_t cond_1;
pthread_cond_t cond_2;
set_alarm *head;
} th_mut = {.th_mutex = PTHREAD_MUTEX_INITIALIZER,
.cond_1 = PTHREAD_COND_INITIALIZER,
.cond_2 = PTHREAD_COND_INITIALIZER};
void insert_node (set_alarm *node) {
set_alarm *temp_curr = 0;
set_alarm *temp_prev = 0;
int count = 0;
static int flag = 0;
if ((temp_curr = (set_alarm *) malloc (sizeof (set_alarm))) == 0)
errno_abort ("malloc() failed\\n");
temp_curr = th_mut.head;
if ((temp_prev = (set_alarm *) malloc (sizeof (set_alarm))) == 0)
errno_abort ("malloc() failed\\n");
if (th_mut.head == 0) {
if ((flag == 1) && ((node -> sec) < (time_1))) {
th_mut.head = node;
node -> next = 0;
pthread_cond_signal (&th_mut.cond_2);
} else {
th_mut.head = node;
node -> next = 0;
pthread_cond_signal (&th_mut.cond_1);
flag = 1;
}
} else {
while ((temp_curr -> next != 0) && ((node -> sec) > (temp_curr -> sec))) {
count++;
temp_prev = temp_curr;
temp_curr = temp_curr -> next;
}
if ((temp_curr -> next == 0) && ((node -> sec) > (temp_curr -> sec))) {
temp_curr -> next = node;
node -> next = 0;
} else if (count == 0) {
if ((temp_curr != 0) && ((node -> sec) <= (temp_curr -> sec))) {
node -> next = temp_curr;
th_mut.head = node;
pthread_cond_signal (&th_mut.cond_2);
} else {
th_mut.head= node;
node -> next = 0;
pthread_cond_signal (&th_mut.cond_2);
}
} else {
temp_curr = temp_prev;
node -> next = temp_curr -> next;
temp_curr -> next = node;
}
}
}
void delete_node (void) {
set_alarm *temp = 0;
temp = (set_alarm *) th_mut.head;
time_1 = temp -> sec;
strcpy (msg_temp, temp -> msg);
th_mut.head = (set_alarm *) temp -> next;
free (temp);
temp = 0;
}
void *alarm_thread (void *arg) {
int th_status;
struct timespec th_time;
while (1) {
pthread_mutex_lock (&th_mut.th_mutex);
if (th_status != 0)
err_abort (th_status, "pthread_thread_lock() failed\\n");
if (th_mut.head == 0) {
th_status = pthread_cond_wait (&th_mut.cond_1, &th_mut.th_mutex);
if (th_status != 0)
err_abort (th_status, "pthread_cond_wait() failed\\n");
}
delete_node ();
time_2 = time_1 - time (0);
th_time.tv_sec = time_1;
if ((pthread_cond_timedwait (&th_mut.cond_2, &th_mut.th_mutex, &th_time)) == 110) {
printf ("(%lu) %s\\n", time_2, msg_temp);
pthread_mutex_unlock(&th_mut.th_mutex);
} else {
set_alarm *back = (set_alarm *) malloc (sizeof (set_alarm));
back -> sec = time_1;
strcpy (back -> msg, msg_temp);
insert_node (back);
pthread_mutex_unlock (&th_mut.th_mutex);
}
}
return 0;
}
int main (void) {
set_alarm *th_alarm = 0;
char line[2 * MSG_LEN];
int status;
pthread_t th_id;
unsigned int seconds;
status = pthread_create (&th_id, 0, alarm_thread, 0);
if (status != 0)
err_abort (status, "pthread_create() failed\\n");
while (1) {
printf ("Alarm : ");
if (fgets (line, sizeof (line), stdin) == 0) exit (1);
if (strlen (line) <= 1) {
continue;
}
if ((th_alarm = (set_alarm *) malloc (sizeof (set_alarm))) == 0)
errno_abort ("malloc() failed\\n");
if ((sscanf (line, "%d %64[^\\n]", &seconds, th_alarm->msg)) < 2) {
fprintf (stderr, "%s", "Bad command\\n");
free (th_alarm);
th_alarm = 0;
continue;
}
th_alarm -> sec = seconds + time (0);
status = pthread_mutex_lock (&th_mut.th_mutex);
if (status != 0)
err_abort (status, "pthread_thread_lock() failed\\n");
insert_node (th_alarm);
status = pthread_mutex_unlock (&th_mut.th_mutex);
if (status != 0)
err_abort (status, "pthread_thread_unlock() failed\\n");
}
pthread_exit (0);
return 0;
}
| 0
|
#include <pthread.h>
{
int pkt,x,y,crc;
char name[20];
}ST;
{
int x,y,crc;
char name[20];
struct frame *next;
}fr;
{
int pkt;
struct node*node_next;
struct frame*frame_next;
}nd;
void make_node();
void print(void);
nd* my_malloc();
nd*h;
ST z;
pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER;
int c=1,nfd;
void* thread_3(void *);
void * thread_1(void *p)
{
for(;;)
{
pthread_mutex_lock(&mtx);
while(c=read(nfd,&z,sizeof(z)))
{
pthread_mutex_unlock(&mtx);
sleep(1);
}
pthread_exit(0);
}
}
void* thread_2(void *p)
{
pthread_t t3;
for(;;)
{
pthread_mutex_lock(&mtx);
while(c==0)
{
pthread_create(&t3,0,thread_3,0);
pthread_exit(0);
}
while(c!=1)
{
nd*t=h,*t1;
fr*temp,*t2;
if(h==0)
{
h=my_malloc();
}
else
{
while(t)
{
if(t->pkt==z.pkt)
break;
t1=t;
t=t->node_next;
}
if(t==0)
{
t1->node_next=my_malloc();
}
else
{
temp=malloc(sizeof(fr));
temp->x=z.x;
temp->y=z.y;
temp->crc=z.crc;
strcpy(temp->name,z.name);
temp->next=0;
if(t->frame_next==0||(h->frame_next->crc)>(temp->crc))
{
temp->next=t->frame_next;
t->frame_next=temp;
}
else
{
t2=h->frame_next;
while(t2)
{
if(t2->next==0)
{
temp->next=t2->next;
t2->next=temp;
break;
}
if(t2->next->crc>temp->crc)
{
temp->next=t2->next;
t2->next=temp;
break;
}
t2=t2->next;
}
}
}
}
c=1;
}
pthread_mutex_unlock(&mtx);
}
}
void* thread_3(void *k)
{
nd *p=h;
fr*t;
while(p)
{
t=p->frame_next;
printf("pkt type=%d\\n",p->pkt);
while(t)
{
printf("x=%d y=%d crc=%d\\n",t->x,t->y,t->crc);
printf("name=%s\\n",t->name);
t=t->next;
}
p=p->node_next;
}
}
nd*my_malloc()
{
nd*temp;
temp=malloc(sizeof(nd));
temp->pkt=z.pkt;
temp->frame_next=malloc(sizeof(fr));
temp->frame_next->x=z.x;
temp->frame_next->y=z.y;
temp->frame_next->crc=z.crc;
strcpy(temp->frame_next->name,z.name);
temp->frame_next->next=0;
temp->node_next=0;
return temp;
}
void main()
{
pthread_t t1,t2;
int fd,len,i=1;
struct sockaddr_in f,f1;
f.sin_family=AF_INET;
f.sin_port=htons(2000);
f.sin_addr.s_addr=inet_addr("0.0.0.0");
len=sizeof(f);
fd=socket(AF_INET,SOCK_STREAM,0);
perror("socket");
bind(fd,(struct sockaddr*)&f,len);
perror("bind");
listen(fd,5);
printf("before\\n");
nfd=accept(fd,(struct sockaddr*)&f1,&len);
perror("accept");
printf("after\\n");
pthread_create(&t1,0,thread_1,0);
pthread_create(&t2,0,thread_2,0);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int ticketcount = 10;
pthread_mutex_t lock;
pthread_cond_t cond;
void* salewinds1(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows1 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
else
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void* salewinds2(void* args)
{
while(1)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
{
printf("windows2 start sale ticket!the ticket is:%d\\n",ticketcount);
ticketcount --;
if(ticketcount == 0)
pthread_cond_signal(&cond);
printf("sale ticket finish!,the last ticket is:%d\\n",ticketcount);
}
else
{
pthread_mutex_unlock(&lock);
break;
}
pthread_mutex_unlock(&lock);
sleep(1);
}
}
void *setticket(void *args)
{
pthread_mutex_lock(&lock);
if(ticketcount > 0)
pthread_cond_wait(&cond,&lock);
ticketcount = 10;
pthread_mutex_unlock(&lock);
sleep(1);
pthread_exit(0);
}
main()
{
pthread_t pthid1,pthid2,pthid3;
pthread_mutex_init(&lock,0);
pthread_cond_init(&cond,0);
pthread_create(&pthid1,0, salewinds1,0);
pthread_create(&pthid2,0, salewinds2,0);
pthread_create(&pthid3,0, setticket,0);
pthread_join(pthid1,0);
pthread_join(pthid2,0);
pthread_join(pthid3,0);
pthread_mutex_destroy(&lock);
pthread_cond_destroy(&cond);
}
| 0
|
#include <pthread.h>
struct timespec diff_timespec(struct timespec start, struct timespec end);
long long millisec_elapsed(struct timespec diff);
int main(int argc, char** argv)
{
struct timespec start;
struct timespec end;
struct timespec diff;
int i;
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
pthread_rwlock_t rwlock;
pthread_rwlock_init(&rwlock, 0);
pthread_spinlock_t spinlock;
pthread_spin_init(&spinlock, 0);
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0 ; i < 50000000; ++i)
{
pthread_mutex_lock(&mutex);
pthread_mutex_unlock(&mutex);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = diff_timespec(start, end);
printf("mutex took %lld milliseconds\\n", millisec_elapsed(diff));
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0 ; i < 50000000; ++i)
{
pthread_rwlock_rdlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = diff_timespec(start, end);
printf("read lock took %lld milliseconds\\n", millisec_elapsed(diff));
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0 ; i < 50000000; ++i)
{
pthread_rwlock_wrlock(&rwlock);
pthread_rwlock_unlock(&rwlock);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = diff_timespec(start, end);
printf("write lock took %lld milliseconds\\n", millisec_elapsed(diff));
clock_gettime(CLOCK_MONOTONIC, &start);
for (i = 0 ; i < 50000000; ++i)
{
pthread_spin_lock(&spinlock);
pthread_spin_unlock(&spinlock);
}
clock_gettime(CLOCK_MONOTONIC, &end);
diff = diff_timespec(start, end);
printf("spin lock took %lld milliseconds\\n", millisec_elapsed(diff));
pthread_mutex_destroy(&mutex);
pthread_rwlock_destroy(&rwlock);
pthread_spin_destroy(&spinlock);
return 0;
}
struct timespec diff_timespec(struct timespec start, struct timespec end)
{
struct timespec result;
if (end.tv_nsec < start.tv_nsec){
result.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
result.tv_sec = end.tv_sec - 1 - start.tv_sec;
}
else{
result.tv_nsec = end.tv_nsec - start.tv_nsec;
result.tv_sec = end.tv_sec - start.tv_sec;
}
return result;
}
long long millisec_elapsed(struct timespec diff){
return ((long long)diff.tv_sec * 1000) + (diff.tv_nsec / 1000000);
}
| 1
|
#include <pthread.h>
int *a, *b;
long sum=0;
pthread_mutex_t bloqueo;
void *dotprod(void *arg)
{
int i, start, end, offset, len;
long tid = (long)arg;
offset = tid;
len = 100000;
start = offset*len;
end = start + len;
printf("thread: %ld starting. start=%d end=%d\\n",tid,start,end-1);
pthread_mutex_lock(&bloqueo);
for (i=start; i<end ; i++)
sum += (a[i] * b[i]);
pthread_mutex_unlock(&bloqueo);
printf("thread: %ld done. Global sum now is=%li\\n",tid,sum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
void *status;
pthread_t threads[8];
pthread_mutex_init(&bloqueo,0);
a = (int*) malloc (8*100000*sizeof(int));
b = (int*) malloc (8*100000*sizeof(int));
for (i=0; i<100000*8; i++)
a[i]= b[i]=1;
for(i=0; i<8; i++)
pthread_create(&threads[i], 0, dotprod, (void *)i);
for(i=0; i<8; i++)
pthread_join(threads[i], &status);
pthread_mutex_destroy(&bloqueo);
printf ("Final Global Sum=%li\\n",sum);
free (a);
free (b);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
static pthread_t tid;
static pthread_mutex_t mut_pending_event = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond_pending_event = PTHREAD_COND_INITIALIZER;
static volatile int pending_event=0;
static volatile int thread_quit_mark=0;
static void *thr_maintainer(void *p)
{
imp_t *imp;
sigset_t allsig;
int err;
sigfillset(&allsig);
pthread_sigmask(SIG_BLOCK, &allsig, 0);
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
while (!thread_quit_mark) {
do {
err = queue_dequeue_nb(dungeon_heart->terminated_queue, &imp);
if (err < 0) {
break;
}
imp_dismiss(imp);
} while (1);
pthread_mutex_lock(&mut_pending_event);
while (pending_event==0) {
pthread_cond_wait(&cond_pending_event, &mut_pending_event);
}
pending_event=0;
pthread_mutex_unlock(&mut_pending_event);
}
return 0;
}
int thr_maintainer_create(void)
{
int err;
err = pthread_create(&tid, 0, thr_maintainer, 0);
if (err) {
return err;
}
return 0;
}
int thr_maintainer_destroy(void)
{
int err;
thread_quit_mark = 1;
thr_maintainer_wakeup();
err = pthread_join(tid, 0);
return err;
}
void thr_maintainer_wakeup(void)
{
pthread_mutex_lock(&mut_pending_event);
pending_event = 1;
pthread_cond_signal(&cond_pending_event);
pthread_mutex_unlock(&mut_pending_event);
}
| 1
|
#include <pthread.h>
int escalar=3;
int matriz[3][3];
pthread_mutex_t bloq;
int *t;
void * matrizporescalar ( void * arg ) {
t=(int *) arg;
printf("t: %s\\n",t );
pthread_mutex_lock (&bloq);
int i;
for ( i = 0 ; i < 3 ; i ++ ) {
matriz [ *t ][ i] = matriz [ *t ][ i] * escalar ;
pthread_mutex_unlock(&bloq);
}
}
int main ( int argc , char * argv []) {
int hilos[3];
pthread_t hil[3] ;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_mutex_init(&bloq, 0);
pthread_create (&hil[0] , &attr , matrizporescalar , ( void *) &hilos[0]);
pthread_create (&hil[1] , &attr , matrizporescalar , ( void *) &hilos[1]);
pthread_create (&hil[2] , &attr , matrizporescalar , ( void *) &hilos[2]);
pthread_join(hil[0], 0);
pthread_join(hil[1], 0);
pthread_join(hil[2], 0);
int j;
int k;
for (j = 0; j < 3; j++)
{
for (k = 0; k < 3; k++)
{
printf("%d", matriz[j][k] );
}
}
pthread_attr_destroy (&attr);
pthread_mutex_destroy (&bloq);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
printf("Thread %ld did %d to %d: mysum=%f global sum=%f\\n",offset,start,end,mysum,dotstr.sum);
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100000*sizeof(double));
b = (double*) malloc (4*100000*sizeof(double));
for (i=0; i<100000*4; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 100000;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<4;i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<4;i++) {
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
int i1,i2,i3,i4,i;
pthread_mutex_t mutex;
void *thread_fun1(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
i1++;
i++;
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread_fun2(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
i2++;
i++;
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread_fun3(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
i3++;
i++;
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread_fun4(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
i4++;
i++;
pthread_mutex_unlock(&mutex);
}
return (void *)0;
}
void *thread_fun5(void *arg)
{
while(1)
{
pthread_mutex_lock(&mutex);
if((i1+i2+i3+i4)!=i)
{
printf("it's wrong:\\ni1=%d\\ni2=%d\\ni3=%d\\ni4=%d\\ni=%d\\n",i1,i2,i3,i4,i);
}
printf("it's true:\\ni1=%d\\ni2=%d\\ni3=%d\\ni4=%d\\ni1+i2+i3+i4=%d\\ni=%d\\n",i1,i2,i3,i4,i1+i2+i3+i4,i);
pthread_mutex_unlock(&mutex);
sleep(5);
}
return (void *)0;
}
int main()
{
pthread_t tid1,tid2,tid3,tid4,tid5;
int err;
i = 0;
i1 = 0;
i2 = 0;
i3 = 0;
i4 = 0;
err = pthread_mutex_init(&mutex,0);
if(err!=0)
{
printf("init mutex failed\\n");
return;
}
err= pthread_create(&tid1,0,thread_fun1,0);
if(err!=0)
{
printf("create new thread failed\\n");
return;
}
err= pthread_create(&tid2,0,thread_fun2,0);
if(err!=0)
{
printf("create new thread failed\\n");
return;
}
err= pthread_create(&tid3,0,thread_fun3,0);
if(err!=0)
{
printf("create new thread failed\\n");
return;
}
err= pthread_create(&tid4,0,thread_fun4,0);
if(err!=0)
{
printf("create new thread failed\\n");
return;
}
err= pthread_create(&tid5,0,thread_fun5,0);
if(err!=0)
{
printf("create new thread failed\\n");
return;
}
pthread_join(tid1,0);
pthread_join(tid2,0);
pthread_join(tid3,0);
pthread_join(tid4,0);
pthread_join(tid5,0);
printf("it's over:\\ni1=%d\\ni2=%d\\ni3=%d\\ni4=%d\\ni=%d",i1,i2,i3,i4,i);
return 0;
}
| 0
|
#include <pthread.h>
char* key;
char* value;
size_t value_len;
struct hash_item** pprev;
struct hash_item* next;
} hash_item;
hash_item* hash[1024];
pthread_mutex_t hash_mutex[1024];
pthread_mutex_t thread_mutex;
pthread_cond_t thread_cond;
int nthreads;
hash_item* hash_get(const char* key, int create) {
unsigned b = string_hash(key) % 1024;
hash_item* h = hash[b];
while (h != 0 && strcmp(h->key, key) != 0) {
h = h->next;
}
if (h == 0 && create) {
h = (hash_item*) malloc(sizeof(hash_item));
h->key = strdup(key);
h->value = 0;
h->value_len = 0;
h->pprev = &hash[b];
h->next = hash[b];
hash[b] = h;
if (h->next != 0) {
h->next->pprev = &h->next;
}
}
return h;
}
void* connection_thread(void* arg) {
int cfd = (int) (uintptr_t) arg;
FILE* fin = fdopen(cfd, "r");
FILE* f = fdopen(cfd, "w");
pthread_detach(pthread_self());
char buf[1024], key[1024], key2[1024];
size_t sz;
while (fgets(buf, 1024, fin)) {
if (sscanf(buf, "get %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
fprintf(f, "VALUE %s %zu %p\\r\\n",
key, h->value_len, h);
fwrite(h->value, 1, h->value_len, f);
fprintf(f, "\\r\\n");
}
fprintf(f, "END\\r\\n");
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "set %s %zu ", key, &sz) == 2) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 1);
free(h->value);
h->value = (char*) malloc(sz);
h->value_len = sz;
fread(h->value, 1, sz, fin);
fprintf(f, "STORED %p\\r\\n", h);
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "delete %s ", key) == 1) {
unsigned b = string_hash(key);
pthread_mutex_lock(&hash_mutex[b]);
hash_item* h = hash_get(key, 0);
if (h != 0) {
free(h->key);
free(h->value);
*h->pprev = h->next;
if (h->next) {
h->next->pprev = h->pprev;
}
free(h);
fprintf(f, "DELETED %p\\r\\n", h);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
} else if (sscanf(buf, "exch %s %s ", key, key2) == 2) {
unsigned b = string_hash(key);
unsigned b2 = string_hash(key2);
if (b < b2) {
unsigned tmp = b;
b = b2;
b2 = tmp;
}
pthread_mutex_lock(&hash_mutex[b]);
if (b2 != b) {
pthread_mutex_lock(&hash_mutex[b2]);
}
hash_item* h = hash_get(key, 0);
hash_item* h2 = hash_get(key2, 0);
if (h != 0 && h2 != 0) {
char* tmp = h->value;
h->value = h2->value;
h2->value = tmp;
size_t tmpsz = h->value_len;
h->value_len = h2->value_len;
h2->value_len = tmpsz;
fprintf(f, "EXCHANGED %p %p\\r\\n", h, h2);
} else {
fprintf(f, "NOT_FOUND\\r\\n");
}
fflush(f);
pthread_mutex_unlock(&hash_mutex[b]);
if (b2 != b) {
pthread_mutex_unlock(&hash_mutex[b2]);
}
} else if (remove_trailing_whitespace(buf)) {
fprintf(f, "ERROR\\r\\n");
fflush(f);
}
}
if (ferror(fin)) {
perror("read");
}
fclose(fin);
(void) fclose(f);
pthread_mutex_lock(&thread_mutex);
--nthreads;
pthread_mutex_unlock(&thread_mutex);
pthread_cond_signal(&thread_cond);
return 0;
}
int main(int argc, char** argv) {
for (int i = 0; i != 1024; ++i) {
pthread_mutex_init(&hash_mutex[i], 0);
}
pthread_mutex_init(&thread_mutex, 0);
pthread_cond_init(&thread_cond, 0);
int port = 6168;
if (argc >= 2) {
port = strtol(argv[1], 0, 0);
assert(port > 0 && port <= 65535);
}
int fd = open_listen_socket(port);
assert(fd >= 0);
while (1) {
int cfd = accept(fd, 0, 0);
if (cfd < 0) {
perror("accept");
exit(1);
}
pthread_mutex_lock(&thread_mutex);
while (nthreads >= 100) {
pthread_cond_wait(&thread_cond, &thread_mutex);
}
++nthreads;
pthread_mutex_unlock(&thread_mutex);
pthread_t t;
int r = pthread_create(&t, 0, connection_thread,
(void*) (uintptr_t) cfd);
if (r != 0) {
perror("pthread_create");
exit(1);
}
}
}
| 1
|
#include <pthread.h>
pthread_t pt;
int i = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void * secondary_func( void * arg );
int main( int argc, char ** argv ) {
pthread_create(&pt, 0, secondary_func, (void*)0);
while (i <= 2000) {
pthread_mutex_lock(&mutex);
printf("\\ni main pthread_mutex_lock: %d\\n", i);
fflush(stdout);
i += 10;
usleep(1000000);
i+=2;
printf("i main doing stuff, DO NOT DISTURB: %d\\n", i);
fflush(stdout);
usleep(1000000);
i+=1;
printf("i main pthread_mutex_unlock: %d\\n", i);
fflush(stdout);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_destroy( &mutex );
return 0;
}
void * secondary_func(void * arg) {
while (1) {
pthread_mutex_lock(&mutex);
i = 0;
printf("\\ni secondary_func: %d\\n", i);
fflush(stdout);
pthread_mutex_unlock(&mutex);
usleep(10000456);
}
return 0;
}
| 0
|
#include <pthread.h>
struct philosopher{
int index;
int first_fork;
int second_fork;
}*p;
pthread_mutex_t f[4];
void philosopher_init(struct philosopher *p, int i){
p->index = i;
int leftfork = i;
int rightfork;
if(p->index == 0)
rightfork = 4 -1;
else
rightfork = i-1;
if(leftfork<rightfork){
p->first_fork = leftfork;
p->second_fork = rightfork;
}
else{
p->first_fork = rightfork;
p->second_fork = leftfork;
}
printf("philospher %d's first_fork is %d, second_fork is %d\\n", p->index, p->first_fork,p->second_fork);
}
void acquire_first_fork(struct philosopher *phil){
pthread_mutex_lock(&f[phil->first_fork]);
}
void acquire_second_fork(struct philosopher *phil){
pthread_mutex_lock(&f[phil->second_fork]);
}
void release_first_fork(struct philosopher *phil){
pthread_mutex_unlock(&f[phil->first_fork]);
}
void release_second_fork(struct philosopher *phil){
pthread_mutex_unlock(&f[phil->second_fork]);
}
void* philosopher(void *arg){
struct philosopher *phil = ((struct philosopher*)arg);
if(phil == 0){
printf("NULL pointer\\n");
}
int i;
for (i = 0; i < 5; ++i)
{
acquire_first_fork(phil);
acquire_second_fork(phil);
sleep(rand()%3);
release_second_fork(phil);
release_first_fork(phil);
}
pthread_exit(0);
}
int main(){
pthread_t phil_threads[4];
int i;
for (i = 0; i < 4; ++i)
{
pthread_mutex_init(&f[i],0);
}
for (i = 0; i < 4; ++i)
{
struct philosopher *phil = (struct philosopher *)malloc(sizeof(struct philosopher));
philosopher_init(phil,i);
pthread_create(&phil_threads[i], 0, philosopher, (void*) phil);
}
for (i = 0; i < 4; ++i)
{
pthread_join(phil_threads[i],0);
}
}
| 1
|
#include <pthread.h>
void *Tackle(void *Dummy) {
extern pthread_cond_t Snap;
extern pthread_mutex_t Mutex;
pthread_mutex_lock(&Mutex);
printf("Waiting for the snap\\n");
pthread_cond_wait(&Snap,&Mutex);
pthread_mutex_unlock(&Mutex);
printf("Tackle!!\\n");
return(0);
}
int main(int argc,char *argv[]) {
extern pthread_cond_t Snap;
extern pthread_mutex_t Mutex;
int Index;
pthread_t NewThread;
pthread_cond_init(&Snap,0);
pthread_mutex_init(&Mutex,0);
for (Index=0;Index<atoi(argv[1]);Index++) {
if (pthread_create(&NewThread,0,Tackle,0) != 0) {
perror("Creating thread");
exit(1);
}
if (pthread_detach(NewThread) != 0) {
perror("Detaching thread");
exit(1);
}
}
fgetc(stdin);
pthread_cond_broadcast(&Snap);
printf("Exiting the main program, leaving the threads running\\n");
pthread_exit(0);
}
pthread_cond_t Snap;
pthread_mutex_t Mutex;
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
char debut_train1[2];
char fin_train1[2];
char debut_train2[2];
char fin_train2[2];
char debut_train3[2];
char fin_train3[2];
char *substring(size_t start, size_t stop, const char *src, char *dst, size_t size)
{
int count = stop - start;
if ( count >= --size ) {
count = size;
}
sprintf(dst, "%.*s", count, src + start);
return dst;
}
int verif(const char *src) {
return 0;
}
void* a(void* p) {
int i = 0;
char train1[4][8] = {"A --> B", "B --> C", "C --> B", "B --> A"};
while (i >= 0) {
substring(0, 1, train1[i%4], debut_train1, sizeof(debut_train1));
substring(6, 1, train1[i%4], fin_train1, sizeof(fin_train1));
if(strcmp(debut_train1, fin_train2) == 0 && strcmp(fin_train1, debut_train2) == 0) {
pthread_mutex_lock(&mutex);
printf("train 1 : bloqué %s\\n", train1[i%4] );
pthread_mutex_unlock(&mutex);
}
else if(strcmp(debut_train1, fin_train3) == 0 && strcmp(fin_train1, debut_train3) == 0) {
pthread_mutex_lock(&mutex);
printf("train 1 : bloqué %s\\n", train1[i%4] );
pthread_mutex_unlock(&mutex);
}
else {
printf("train 1 : %s\\n", train1[i%4]);
sleep(3);
fflush(stdout);
}
i++;
}
return 0;
}
void* b(void* p) {
int i = 0;
char train2[5][8] = {"A --> B", "B --> D", "D --> C", "C --> B", "B --> A"};
while (i >= 0) {
substring(0, 1, train2[i%4], debut_train2, sizeof(debut_train2));
substring(6, 1, train2[i%4], fin_train2, sizeof(fin_train2));
if(strcmp(debut_train2, fin_train3) == 0 && strcmp(fin_train2, debut_train3) == 0) {
pthread_mutex_lock(&mutex);
printf("train 2 : bloqué %s\\n" , train2[i%5]);
pthread_mutex_unlock(&mutex);
}
else if(strcmp(debut_train2, fin_train1) == 0 && strcmp(fin_train2, debut_train1) == 0) {
pthread_mutex_lock(&mutex);
printf("train 2 : bloqué %s\\n" , train2[i%5]);
pthread_mutex_unlock(&mutex);
}
else {
printf("train 2 : %s\\n", train2[(i%5)]);
sleep(3);
fflush(stdout);
}
i++;
}
return 0;
}
void* c(void* p) {
int i = 0;
char train3[5][8] = {"A --> B", "B --> D", "D --> C", "C --> E", "E --> A"};
while (i >= 0) {
substring(0, 1, train3[i%4], debut_train3, sizeof(debut_train3));
substring(6, 1, train3[i%4], fin_train3, sizeof(fin_train3));
if(strcmp(debut_train3, fin_train2) == 0 && strcmp(fin_train3, debut_train2) == 0) {
pthread_mutex_lock(&mutex);
printf("train 3 : bloqué %s\\n", train3[(i%5)] );
pthread_mutex_unlock(&mutex);
}
else if(strcmp(debut_train3, fin_train1) == 0 && strcmp(fin_train3, debut_train1) == 0) {
pthread_mutex_lock(&mutex);
printf("train 3 : bloqué %s\\n", train3[(i%5)]);
pthread_mutex_unlock(&mutex);
} else {
printf("train 3 : %s\\n", train3[(i%5)]);
sleep(3);
fflush(stdout);
}
i++;
}
return 0;
}
int main() {
pthread_t ID[3];
pthread_mutex_init(&mutex, 0);
pthread_create(&ID[0], 0, b, 0);
pthread_create(&ID[1], 0, c, 0);
a(0);
pthread_join(ID[0], 0);
pthread_join(ID[1], 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 1
|
#include <pthread.h>
int const maxQueueLen = 3;
int const shavingTimeMin = 1;
int const shavingTimeMax = 10;
int const customerSleepTimeMin = 1;
int const customerSleepTimeMax = 10;
void sleepInRange( int min, int max )
{
sleep(min + rand() % (max - min));
}
void doShaving()
{
sleepInRange(shavingTimeMin, shavingTimeMax);
}
void sleepForNextShave()
{
sleepInRange(customerSleepTimeMin, customerSleepTimeMax);
}
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t barbersMutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t customersMutex = PTHREAD_MUTEX_INITIALIZER;
static int waiting = 0;
{
pthread_t threadId;
int customersFlowId;
} customer_thread_info_t;
static void *barber( void * )
{
printf("Barber created.\\n");
while (1)
{
printf("Barber: sleeping (locking customersMutex)...\\n");
pthread_mutex_lock(&customersMutex);
printf("Barber: awaked (locked customersMutex), locking waiting queue (locking mutex)...\\n");
pthread_mutex_lock(&mutex);
printf("Barber: locked waiting queue (locked mutex). Selecting customer from queue and starting shaving...\\n");
--waiting;
if (waiting > 0)
{
printf("Barber: Queue to barber is not empty (unlocking customersMutex).\\n");
pthread_mutex_unlock(&customersMutex);
}
printf("Barber: (unlocking barbersMutex).\\n");
pthread_mutex_unlock(&barbersMutex);
printf("Barber: (unlocking mutex).\\n");
pthread_mutex_unlock(&mutex);
printf("Barber: shaving...\\n");
doShaving();
}
return 0;
}
static void *customersFlow( customer_thread_info_t *info )
{
while (1)
{
sleepForNextShave();
pthread_mutex_lock(&mutex);
if (waiting + 1 < maxQueueLen)
{
++waiting;
pthread_mutex_unlock(&customersMutex);
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&barbersMutex);
}
else
{
pthread_mutex_unlock(&mutex);
}
}
return 0;
}
int main( int argc, char const *argv[] )
{
int i;
customer_thread_info_t customersFlowsThreads[4];
pthread_t barberThreadId;
srand(0);
pthread_mutex_lock(&barbersMutex);
pthread_mutex_lock(&customersMutex);
if (pthread_create(&barberThreadId, 0, (thread_routine_t)barber, 0) != 0)
{
perror("pthread_create");
return -1;
}
for (i = 0; i < 4; ++i)
{
customersFlowsThreads[i].customersFlowId = i + 1;
if (pthread_create(&customersFlowsThreads[i].threadId, 0, (thread_routine_t)customersFlow, (void *)&customersFlowsThreads[i]) != 0)
{
perror("pthread_create");
return -1;
}
}
getchar();
return 0;
}
| 0
|
#include <pthread.h>
static volatile int is_receiver_started = 0;
void initialize_event_dispatch() {
pthread_mutex_init(&wait_notify_lock, 0);
pthread_mutex_init(&ready_lock, 0);
pthread_cond_init(&wait_notify_condn, 0);
pthread_cond_init(&ready_condn, 0);
}
void cleanup_event_dispatch() {
pthread_mutex_destroy(&wait_notify_lock);
pthread_mutex_destroy(&ready_lock);
pthread_cond_destroy(&wait_notify_condn);
pthread_cond_destroy(&ready_condn);
}
void wait_till_receiver_started() {
pthread_mutex_lock(&ready_lock);
while (!is_receiver_started) {
pthread_cond_wait(&ready_condn, &ready_lock);
}
is_receiver_started = 0;
pthread_mutex_unlock(&ready_lock);
}
void *signal_sender_start(void * arg) {
int major_iteration, sub_iteration = 0;
struct timespec start_time;
struct timespec end_time;
for (major_iteration = 0; major_iteration
< evt_dispatch_major_iterations; major_iteration++) {
wait_till_receiver_started();
pthread_mutex_lock(&wait_notify_lock);
clock_gettime(CLOCK_MONOTONIC, &start_time);
for (sub_iteration = 0; sub_iteration
< evt_dispatch_sub_iterations; sub_iteration++) {
pthread_cond_signal(&wait_notify_condn);
pthread_cond_wait(&wait_notify_condn,
&wait_notify_lock);
}
clock_gettime(CLOCK_MONOTONIC, &end_time);
pthread_mutex_unlock(&wait_notify_lock);
receiver_end_time[major_iteration] = end_time.tv_sec
* 1000000000LL + end_time.tv_nsec;
sender_start_time[major_iteration] = start_time.tv_sec
* 1000000000LL + start_time.tv_nsec;
}
return 0;
}
void set_receiver_started() {
pthread_mutex_lock(&ready_lock);
is_receiver_started = 1;
pthread_cond_signal(&ready_condn);
pthread_mutex_unlock(&ready_lock);
}
void *signal_receiver_start(void * arg) {
int major_iteration, sub_iteration = 0;
for (major_iteration = 0; major_iteration
< evt_dispatch_major_iterations; major_iteration++) {
pthread_mutex_lock(&wait_notify_lock);
set_receiver_started();
for (sub_iteration = 0; sub_iteration
< evt_dispatch_sub_iterations; sub_iteration++) {
pthread_cond_wait(&wait_notify_condn, &wait_notify_lock);
pthread_cond_signal(&wait_notify_condn);
}
pthread_mutex_unlock(&wait_notify_lock);
}
return 0;
}
void start_thread(pthread_t *thread, void *func(void *), void *arg) {
pthread_attr_t attr;
struct sched_param param;
int policy = SCHED_FIFO;
int detS = PTHREAD_EXPLICIT_SCHED;
pthread_attr_init(&attr);
pthread_attr_setinheritsched(&attr, detS);
param.sched_priority = sched_get_priority_max(SCHED_FIFO) - 10;
pthread_attr_setschedparam(&attr, ¶m);
pthread_attr_setschedpolicy(&attr, policy);
pthread_create(thread, &attr, func, arg);
}
| 1
|
#include <pthread.h>
pthread_t threads[3];
char buf[20];
int count=0;
pthread_mutex_t mutex,mutex2;
pthread_cond_t rdv;
void rdv_fonc(){
pthread_mutex_lock(&mutex2);
count++;
if(count < 3) pthread_cond_wait(&rdv,&mutex2);
if(count >1){
pthread_cond_signal(&rdv);
count--;
}
pthread_mutex_unlock(&mutex2);
}
void *th_fonc (void *arg) {
int is, numero, i,j, m1;
numero = (int)arg;
m1 = 20 + numero*10;
i = m1;
printf("numero= %d, i=%d \\n",numero,i);
switch(numero)
{
case 0 : { pthread_mutex_lock(&mutex);
drawstr (30,125, "_0_", 3);
drawrec (100,100,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,102,100+j*10,26,"yellow");
pthread_mutex_unlock(&mutex);
usleep(500000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
case 1 : {
pthread_mutex_lock(&mutex);
drawstr (30, 175, "_1_", 3);
drawrec (100,150,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,152,100+j*10,26,"white");
pthread_mutex_unlock(&mutex);
usleep(700000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
case 2 : {
pthread_mutex_lock(&mutex);
drawstr (30, 225, "_2_", 3);
drawrec (100,200,100+m1*10,30);
pthread_mutex_unlock(&mutex);
for (j=1;j<=m1;j++) {
if (j==10) rdv_fonc();
printf("num %d j=%d\\n",numero,j);
pthread_mutex_lock(&mutex);
fillrec (100,202,100+j*10,26,"green");
pthread_mutex_unlock(&mutex);
usleep(300000);
}
flushdis ();
return ( (void *)(numero+100) );
break;
}
}
}
int liretty (char *prompt, char *buffer) {
int i;
printf("\\n%s",prompt);
i = scanf ("%s",buffer);
return strlen(buffer);
}
main() {
void *val=0;
int nlu, is,i=0;
is = pthread_mutex_init(&mutex, 0);
if (is==-1) perror("err. init thread_mutex");
is = pthread_cond_init (&rdv, 0);
if (is==-1) perror("err. init thread_cond");
initrec();
pthread_mutex_lock(&mutex);
drawrec (290,50,2,200);
pthread_mutex_unlock(&mutex);
for(i=0; i<3; i++) {
printf("ici main, création thread %d\\n",i);
is = pthread_create( &threads[i], 0, th_fonc, (void *)i );
if (is==-1) perror("err. création thread");
}
for(i=0; i<3; i++) {
is = pthread_join( threads[i], &val);
if (is==-1) perror("err. join thread");
printf("ici main, fin thread %d\\n",(int)val);
}
nlu = liretty("sortir ?",buf);
printf("--fin--\\n");
detruitrec();
exit(0);
}
| 0
|
#include <pthread.h>
int id;
pthread_t threadConsumidor;
}t_consumidor;
int in;
int out;
int buf[5];
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
}BUFFER;
BUFFER sc;
int fibo[25];
int QTD_CONSUMERS;
int cont = 0;
void* consumer(void* thread);
void* producer();
void primo(int primo);
void geraFibo(int* vetor);
int main(int argc, char const *argv[]){
int i;
if( argc < 2 || argc > 2){
printf("\\033[1m\\033[31m""Passe a qtd de Consumidores!\\n""\\033[0m");
exit(-1);
}else{
sscanf(argv[1], "%d", &QTD_CONSUMERS);
t_consumidor* consumers = (t_consumidor*) calloc (QTD_CONSUMERS,sizeof(t_consumidor));
pthread_t threadProdutor;
sem_init(&sc.empty,0,5);
sem_init(&sc.full,0,0);
pthread_mutex_init(&sc.mutex,0);
if (pthread_create(&threadProdutor, 0, producer, 0) != 0){
printf("Erro ao criar a thread\\n");
exit(1);
}
for(i=0; i < QTD_CONSUMERS; i++){
consumers[i].id = i+1;
if(pthread_create(&consumers[i].threadConsumidor, 0, consumer, &consumers[i]) != 0){
printf("Erro ao criar a thread\\n");
exit(1);
}
}
if(pthread_join(threadProdutor, 0) != 0){
printf("Erro ao finalizar a thread\\n");
exit(1);
}
for(i = 0; i < QTD_CONSUMERS; i++){
if(pthread_join(consumers[i].threadConsumidor, 0) != 0){
printf("Erro ao finalizar a thread %d\\n", i);
exit(1);
}
}
}
return(0);
}
void *consumer(void* thread){
int pos;
t_consumidor* con = (t_consumidor*) thread;
int i, item;
for(;;){
sem_wait(&sc.full);
pthread_mutex_lock(&sc.mutex);
item = sc.buf[sc.out];
printf("\\033[1m\\033[31m""Consumidor %d: ""\\033[0m""consumindo item buffer[%d] = %d\\n",con->id ,sc.out, item);
sc.out = (sc.out+1)%5;
primo(item);
pthread_mutex_unlock(&sc.mutex);
sem_post(&sc.empty);
sleep(rand() % 3);
if(cont == 25 -1){
printf("Buffer vazio, acabou o consumo!!\\n");
pthread_exit(0);
}
}
return 0;
}
void* producer(){
geraFibo(fibo);
int i, j, sem_empty, sem_full;
for(i=0; i < 25; i++){
sem_getvalue(&sc.empty, &sem_empty);
if(sem_empty == 0){
for (j = 0; j < 5; j++)
sem_post(&sc.full);
}
sem_wait(&sc.empty);
pthread_mutex_lock(&sc.mutex);
sc.buf[sc.in] = fibo[i];
printf("\\033[1m\\033[36m""Produtor: ""\\033[0m""Inseri o item buffer[%d] = %d\\n", sc.in, sc.buf[sc.in]);
sc.in = (sc.in+1)%5;
pthread_mutex_unlock(&sc.mutex);
sleep(rand() % 4);
}
return 0;
}
void primo(int primo){
int i, count = 0;
for(i=1; i <= primo; i++){
if(primo%i == 0)
count++;
}
if(count == 2 && primo != 1)
printf("--> O número %d eh primo!\\n", primo);
}
void geraFibo(int* vetor){
int i, atual = 0, anterior = 1, fibo = 0;
for(i=0; i < 25; i++){
fibo = anterior + atual;
vetor[i] = fibo;
anterior = atual;
atual = fibo;
}
}
| 1
|
#include <pthread.h>
pthread_t maleTID, femaleTID, makethreadTID1,makethreadTID2, makethreadTID3;
sem_t male_count, female_count, empty, turnstile;
pthread_mutex_t mutex_male = PTHREAD_MUTEX_INITIALIZER, mutex_female = PTHREAD_MUTEX_INITIALIZER,
mutex_thread=PTHREAD_MUTEX_INITIALIZER;
int mcount, fcount, mtime, ftime, muse, fuse;
unsigned int delay_time(unsigned int delaytime, unsigned int stddeviation);
void* makethread(void*);
void* male_routine(void* unused);
void* female_routine(void* unused);
int freq();
int main(void)
{
int i=0;
sem_init(&male_count, 0, 5);
sem_init(&female_count, 0, 5);
sem_init(&empty, 0, 1);
sem_init(&turnstile, 0, 1);
pthread_create(&makethreadTID1, 0, &makethread, 0);
pthread_create(&makethreadTID2, 0, &makethread, 0);
pthread_create(&makethreadTID3, 0, &makethread, 0);
sleep(10);
printf("\\n\\n+-------------------------------+");
printf("\\n+ %5d | %5d +",mtime, ftime);
printf("\\n+ MAN | WOMAN +");
printf("\\n+-------------------------------+\\n\\n");
return 0;
}
void* makethread(void* unused)
{
int n;
static int i=0;
while (i < 100)
{
delay_time(0, 500);
n=freq();
if (n == 0)
pthread_create(&maleTID, 0, &male_routine, 0);
else
pthread_create(&femaleTID, 0, &female_routine, 0);
pthread_mutex_lock(&mutex_thread);
i++;
pthread_mutex_unlock(&mutex_thread);
}
return 0;
}
void* male_routine(void* unused)
{
sem_wait(&turnstile);
pthread_mutex_lock(&mutex_male);
mcount++;
if (mcount ==1)
sem_wait(&empty);
pthread_mutex_unlock(&mutex_male);
sem_post(&turnstile);
sem_wait(&male_count);
printf("\\n---> Man entered");
delay_time(10, 100);
printf("\\nMan exited --->");
sem_post(&male_count);
pthread_mutex_lock(&mutex_male);
mcount--;
if (mcount == 0)
{
printf("\\n\\n\\"Bathroom empty!\\"\\n");
printf("Man used time: %d\\n",muse+1);
muse=0;
sem_post(&empty);
}
else
muse++;
mtime++;
pthread_mutex_unlock(&mutex_male);
return 0;
}
void* female_routine(void* unused)
{
sem_wait(&turnstile);
pthread_mutex_lock(&mutex_female);
fcount++;
if (fcount == 1)
sem_wait(&empty);
pthread_mutex_unlock(&mutex_female);
sem_post(&turnstile);
sem_wait(&female_count);
printf("\\n---> Woman entered");
delay_time(10, 100);
printf("\\nWoman exited --->");
sem_post(&female_count);
pthread_mutex_lock(&mutex_female);
fcount --;
if (fcount ==0)
{
printf("\\n\\n\\"Bathroom empty!\\"\\n");
printf("Woman used time: %d\\n",fuse+1);
fuse=0;
sem_post(&empty);
}
else
fuse++;
ftime++;
pthread_mutex_unlock(&mutex_female);
return 0;
}
int freq()
{
int n;
srand(time(0));
n = rand() % 100;
if (n<50)
return 1;
return 0;
}
unsigned int delay_time(unsigned int delaytime, unsigned int stddeviation)
{
unsigned int n;
if (stddeviation == 0)
stddeviation = 300;
srand(time(0));
n = delaytime * 1000 + rand() % (stddeviation*1000);
usleep(n);
return n;
}
| 0
|
#include <pthread.h>
struct _gg_pthread_lock {
pthread_cond_t cond;
pthread_mutex_t mtx;
int users;
int canceled;
};
void *ggLockCreate(void)
{
struct _gg_pthread_lock *ret;
int ct;
int dummy;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ct);
if ((ret = calloc(1, sizeof(struct _gg_pthread_lock))) != 0) {
if (pthread_mutex_init(&ret->mtx, 0) != 0) goto bail0;
if (pthread_cond_init(&ret->cond, 0) != 0) goto bail1;
}
pthread_setcanceltype(ct, &dummy);
return (void *) ret;
bail1:
pthread_mutex_destroy(&ret->mtx);
bail0:
free((void*)ret);
pthread_setcanceltype(ct, &dummy);
return (void *) 0;
}
int ggLockDestroy(void *lock) {
pthread_mutex_t *l = &((struct _gg_pthread_lock *)lock)->mtx;
pthread_cond_t *c = &((struct _gg_pthread_lock *)lock)->cond;
int ct;
int dummy;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ct);
if (pthread_mutex_destroy(l) != 0) goto busy;
if (pthread_cond_destroy(c) != 0) goto busy;
free(lock);
pthread_setcanceltype(ct, &dummy);
return 0;
busy:
pthread_setcanceltype(ct, &dummy);
return GGI_EBUSY;
}
static void dec(void *thing) { if (*((int *)thing) > 1) (*((int *)thing))--; }
static void _gg_unlock_pt_void(void *arg) {
pthread_mutex_unlock((pthread_mutex_t *)arg);
}
void ggLock(void *lock) {
pthread_mutex_t *l = &((struct _gg_pthread_lock *)lock)->mtx;
pthread_cond_t *c = &((struct _gg_pthread_lock *)lock)->cond;
int *users = &((struct _gg_pthread_lock *)lock)->users;
int ct;
int dummy;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ct);
pthread_cleanup_push(_gg_unlock_pt_void, (void *)(l));
if (pthread_mutex_lock(l)) _gg_death_spiral();
(*users)++;
if (*users > 1) {
pthread_cleanup_push(dec, (void *)users);
if (pthread_cond_wait(c, l)) _gg_death_spiral();
pthread_cleanup_pop(0);
}
pthread_cleanup_pop(1);
pthread_setcanceltype(ct, &dummy);
}
void ggUnlock(void *lock) {
pthread_mutex_t *l = &((struct _gg_pthread_lock *)lock)->mtx;
pthread_cond_t *c = &((struct _gg_pthread_lock *)lock)->cond;
int *users = &((struct _gg_pthread_lock *)lock)->users;
int ct;
int dummy;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ct);
pthread_cleanup_push(_gg_unlock_pt_void, (void *)l);
if (pthread_mutex_lock(l)) _gg_death_spiral();
if (*users && --(*users) && pthread_cond_signal(c)) _gg_death_spiral();
pthread_cleanup_pop(1);
pthread_setcanceltype(ct, &dummy);
}
int ggTryLock(void *lock) {
pthread_mutex_t *l = &((struct _gg_pthread_lock *)lock)->mtx;
int *users = &((struct _gg_pthread_lock *)lock)->users;
int ret = 0;
int ct;
int dummy;
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, &ct);
pthread_cleanup_push(_gg_unlock_pt_void, (void *)l);
if (pthread_mutex_lock(l)) _gg_death_spiral();
if (!*users) (*users)++;
else ret = GGI_EBUSY;
pthread_cleanup_pop(1);
pthread_setcanceltype(ct, &dummy);
return ret;
}
int _ggInitLocks(void) {
return 0;
}
void _ggExitLocks(void) {
return;
}
| 1
|
#include <pthread.h>
struct node_struct* next;
char* data;
pthread_mutex_t mtx;
} node;
pthread_mutex_t head_mtx;
node* head;
node* push_front(node* p, char* buf) {
int len = strlen (buf);
node* q = (node*) malloc (sizeof (node));
pthread_mutex_init (&(q -> mtx), 0);
q -> data = (char*) malloc (len);
strncpy (q->data,buf,len);
q -> data [len] = 0;
pthread_mutex_lock(&head_mtx);
q -> next = p;
head = q;
pthread_mutex_unlock(&head_mtx);
}
void destroy (node* p) {
node* q;
while (p) {
q = p;
p = p -> next;
pthread_mutex_destroy(&q -> mtx);
free (q->data);
free (q);
}
}
void print_all (node* p) {
fprintf (stderr, "Curr elements:\\n");
while (p) {
pthread_mutex_lock(&(p -> mtx));
printf ("- %s\\n", p->data);
node* q = p;
p = p -> next;
pthread_mutex_unlock(&(q -> mtx));
}
}
void sort () {
node* i;
node* j;
char* tmp_str;
int sorted;
do {
sorted = 0;
pthread_mutex_lock(&head_mtx);
i = head;
pthread_mutex_unlock(&head_mtx);
j = i -> next;
for(; i && j; i = i -> next, j = j->next) {
pthread_mutex_lock(&i -> mtx);
pthread_mutex_lock(&j -> mtx);
if( strcmp(i -> data, j -> data) > 0) {
++sorted;
tmp_str = i -> data;
i -> data = j -> data;
j -> data = tmp_str;
pthread_mutex_unlock(&i -> mtx);
pthread_mutex_unlock(&j -> mtx);
sleep(1);
}
else {
pthread_mutex_unlock(&i -> mtx);
pthread_mutex_unlock(&j -> mtx);
}
}
} while(sorted);
}
void* sorter (void* ptr) {
while (1) {
sleep (5);
sort ();
}
}
int main () {
int input_size;
char buf [80];
pthread_t thread;
pthread_t thread2;
pthread_t thread3;
pthread_t thread4;
pthread_mutex_init(&head_mtx, 0);
pthread_create (&thread, 0, sorter, 0);
pthread_create (&thread2, 0, sorter, 0);
pthread_create (&thread3, 0, sorter, 0);
pthread_create (&thread4, 0, sorter, 0);
while ((input_size = read (0, buf, 80)) > 0) {
buf [input_size - 1] = 0;
if (input_size == 1)
print_all (head);
else
push_front (head, buf);
}
pthread_cancel(thread);
pthread_cancel(thread2);
pthread_cancel(thread3);
pthread_cancel(thread4);
pthread_join(thread, 0);
pthread_join(thread2, 0);
pthread_join(thread3, 0);
pthread_join(thread4, 0);
pthread_mutex_destroy (&head_mtx);
destroy (head);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
int thread_count;
int n;
pthread_mutex_t mutex;
void Usage(char* prog_name);
unsigned My_random(unsigned seed);
void *Thread_work(void* rank);
int main(int argc, char* argv[]) {
long thread;
pthread_t* thread_handles;
if (argc != 3) Usage(argv[0]);
thread_count = strtol(argv[1], 0, 10);
n = strtol(argv[2], 0, 10);
thread_handles = malloc(thread_count*sizeof(pthread_t));
pthread_mutex_init(&mutex, 0);
printf("Enter text\\n");
for (thread = 0; thread < thread_count; thread++)
pthread_create(&thread_handles[thread], 0,
Thread_work, (void*) thread);
for (thread = 0; thread < thread_count; thread++)
pthread_join(thread_handles[thread], 0);
free(thread_handles);
pthread_mutex_destroy(&mutex);
return 0;
}
void Usage(char* prog_name) {
fprintf(stderr, "usage: %s <thread count> <number of random vals per thread>\\n",
prog_name);
exit(0);
}
void *Thread_work(void* rank) {
long my_rank = (long) rank;
int i;
My_random(my_rank + 1);
for (i = 0; i < n; i++)
printf("Th %ld > %u\\n", my_rank, My_random(0));
return 0;
}
unsigned My_random(unsigned seed) {
static unsigned z;
unsigned long tmp;
pthread_mutex_lock(&mutex);
if (seed != 0)
z = seed;
tmp = z*279470273;
z = tmp % 4294967291U;
pthread_mutex_unlock(&mutex);
return z;
}
| 1
|
#include <pthread.h>
int arr[1000][1000];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void initArray()
{
int i = 0;
int j = 0;
for (i = 0; i < 1000; i++)
{
for (j = 0; j < 1000; j++)
{
srand(time(0));
arr[i][j] = rand() % 1 + 1;
}
}
}
int main()
{
initArray();
int sum = 0;
omp_set_num_threads(10);
int id;
int privatesum;
int startc;
int finishc;
int i;
int j;
{
id = omp_get_thread_num();
privatesum = 0;
startc = id * 100;
finishc = startc + 100;
for (i = startc; i < finishc; i++)
{
for (j = 0; j < 1000; j++)
{
privatesum += arr[i][j];
}
}
pthread_mutex_lock(&mutex);
sum += privatesum;
pthread_mutex_unlock(&mutex);
}
printf("%d", sum);
}
| 0
|
#include <pthread.h>
int sync_fd[3] = { 0, 1, 2 };
char *const sync_cmd[] = { "mbsync", "-a", 0 };
char *const mutt_cmd[] = { "mutt", 0 };
int done;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *mail_sync(void *d)
{
struct timespec wt;
pthread_mutex_lock(&mutex);
while (!done) {
clock_gettime(CLOCK_REALTIME, &wt);
wt.tv_sec += 300;
pthread_cond_timedwait(&cond, &mutex, &wt);
ecall(sync_cmd, sync_fd);
}
pthread_mutex_unlock(&mutex);
return 0;
}
int main(int argc, char *argv[])
{
int err;
pthread_t t;
progname = strbsnm(argv[0]);
ecall(sync_cmd, sync_fd);
sync_fd[1] = sync_fd[2] = open("/dev/null", O_RDWR | O_CLOEXEC);
if ((err = pthread_create(&t, 0, mail_sync, 0)) != 0)
error(1, err, 0);
ecall(mutt_cmd, 0);
pthread_mutex_lock(&mutex);
done = 1;
sync_fd[1] = 1;
sync_fd[2] = 2;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_join(t, 0);
return 0;
}
| 1
|
#include <pthread.h>
int g_ncount;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
void* threadFunc(void* args){
int i,val;
for(i = 0; i < 5000; i++){
pthread_mutex_lock(&g_mutex);
val = g_ncount;
printf("%x : %d\\n",(unsigned int)pthread_self(),val+1);
g_ncount = val + 1;
pthread_mutex_unlock(&g_mutex);
}
return (void*)0;
}
int main(int argc,const char* argv[]){
pthread_mutex_t mutex;
pthread_mutex_init(&mutex,0);
pthread_t tid1,tid2;
pthread_create(&tid1,0,threadFunc,0);
pthread_create(&tid2,0,threadFunc,0);
pthread_join(tid1,0);
pthread_join(tid2,0);
printf("destroy-mutex:%d\\n",pthread_mutex_destroy(&mutex));
printf("destroy-g_mutex:%d\\n:",pthread_mutex_destroy(&g_mutex));
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int count = 0;
void* function1( void* arg )
{
int tmp = 0;
while( 1 ) {
if(pthread_mutex_trylock(&mutex) == 16)
printf("%d: mutex is already locked\\n", pthread_self());
pthread_mutex_lock( &mutex );
tmp = count--;
sleep(1);
pthread_mutex_unlock( &mutex );
printf( "%d: count is %d\\n", pthread_self(), tmp );
sleep( 2 );
}
return 0;
}
void* function2( void* arg )
{
int tmp = 0;
while( 1 ) {
if(pthread_mutex_trylock(&mutex) == 16)
printf("%d: mutex is already locked\\n", pthread_self());
pthread_mutex_lock( &mutex );
tmp = count++;
pthread_mutex_unlock( &mutex );
printf( "%d: count is %d\\n", pthread_self(), tmp );
sleep( 1 );
}
return 0;
}
int main( void )
{
pthread_create( 0, 0, &function1, 0 );
pthread_create( 0, 0, &function2, 0 );
sleep( 60 );
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t _mutex_disc_access;
int _disc_access_init = 0;
void disc_access_init(){
if(!_disc_access_init){
_disc_access_init = 1;
pthread_mutex_init(&_mutex_disc_access, 0);
}
}
void disc_access_lock(){
pthread_mutex_lock(&_mutex_disc_access);
}
void disc_access_unlock(){
pthread_mutex_unlock(&_mutex_disc_access);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_cond_t emptySlots;
pthread_cond_t filledSlots;
int buffer[10];
int in = 0;
int out = 0;
int count = 0;
void *producer(void *param);
void *consumer(void *param);
int main(int argc, char *argv[])
{
int i = 0;
if (argc != 2) { fprintf(stderr,"usage: bb <integer value>\\n"); return -1; }
pthread_t tid[10];
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&emptySlots, 0);
pthread_cond_init(&filledSlots, 0);
startTimer();
for(i=0;i<10;i++) {
if(i%2 == 0) pthread_create(&tid[i],0,producer,argv[1]);
if(i%2 == 1) pthread_create(&tid[i],0,consumer,argv[1]);
}
for(i=0;i<10;i++) pthread_join(tid[i],0);
printf("Time: %ld\\n",endTimer());
return 0;
}
void *producer(void *param)
{
int i = 0;
int n = atoi(param);
while(n) {
i++;
usleep(5000+rand()%100);
pthread_mutex_lock(&mutex);
while (count == 10) pthread_cond_wait(&emptySlots, &mutex);
count++;
buffer[in] = i;
printf("produced %d and putting it at %d\\n",i,in);
in = (in+1)%10;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&filledSlots);
n--;
}
pthread_exit(0);
}
void *consumer(void *param)
{
int i;
int n = atoi(param);
while(n) {
pthread_mutex_lock(&mutex);
while (count == 0) pthread_cond_wait(&filledSlots, &mutex);
count--;
i = buffer[out];
printf("taken %d from pos %d\\n",i,out);
out = (out+1)%10;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&emptySlots);
usleep(1000+rand()%100);
n--;
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void guppi_thread_args_init(struct guppi_thread_args *a) {
a->priority=0;
a->finished=0;
pthread_cond_init(&a->finished_c,0);
pthread_mutex_init(&a->finished_m,0);
}
void guppi_thread_args_destroy(struct guppi_thread_args *a) {
a->finished=1;
pthread_cond_destroy(&a->finished_c);
pthread_mutex_destroy(&a->finished_m);
}
void guppi_thread_set_finished(struct guppi_thread_args *a) {
pthread_mutex_lock(&a->finished_m);
a->finished=1;
pthread_cond_broadcast(&a->finished_c);
pthread_mutex_unlock(&a->finished_m);
}
int guppi_thread_finished(struct guppi_thread_args *a,
float timeout_sec) {
struct timeval now;
struct timespec twait;
int rv;
pthread_mutex_lock(&a->finished_m);
gettimeofday(&now,0);
twait.tv_sec = now.tv_sec + (int)timeout_sec;
twait.tv_nsec = now.tv_usec * 1000 +
(int)(1e9*(timeout_sec-floor(timeout_sec)));
if (a->finished==0)
rv = pthread_cond_timedwait(&a->finished_c, &a->finished_m, &twait);
rv = a->finished;
pthread_mutex_unlock(&a->finished_m);
return(rv);
}
| 0
|
#include <pthread.h>
void *adc_thread_handler(void *arg)
{
int adc_value;
int gprs_flag;
int led_flag;
int beep_flag;
while (1)
{
read(*((int *)arg), &adc_value, sizeof(adc_value));
pthread_mutex_lock(&SHM->status_mutex_temperature);
SHM->status_temperature = adc_value / 10;
pthread_mutex_unlock(&SHM->status_mutex_temperature);
if (420 < adc_value)
{
pthread_mutex_lock(&SHM->gprs_mutex_start);
gprs_flag = (0 == SHM->gprs_emit_start);
SHM->gprs_emit_start++;
pthread_mutex_unlock(&SHM->gprs_mutex_start);
if (1 == gprs_flag)
{
pthread_cond_signal(&SHM->gprs_cond_start);
}
pthread_mutex_lock(&SHM->gprs_mutex_end);
while (0 == SHM->gprs_emit_end)
{
pthread_cond_wait(&SHM->gprs_cond_end, &SHM->gprs_mutex_end);
}
if (0 < SHM->gprs_emit_end)
{
SHM->gprs_emit_end--;
}
pthread_mutex_unlock(&SHM->gprs_mutex_end);
pthread_mutex_lock(&SHM->led_mutex_status);
if (0 == SHM->led_emit_status)
{
SHM->led_emit_status++;
}
pthread_mutex_unlock(&SHM->led_mutex_status);
pthread_mutex_lock(&SHM->led_mutex_start);
led_flag = (0 == SHM->led_emit_start);
if (0 == SHM->led_emit_start)
{
SHM->led_emit_start++;
}
pthread_mutex_unlock(&SHM->led_mutex_start);
if (1 == led_flag)
{
pthread_cond_signal(&SHM->led_cond_start);
}
pthread_mutex_lock(&SHM->led_mutex_end);
while (0 == SHM->led_emit_end)
{
pthread_cond_wait(&SHM->led_cond_end, &SHM->led_mutex_end);
}
if (0 < SHM->led_emit_end)
{
SHM->led_emit_end--;
}
pthread_mutex_unlock(&SHM->led_mutex_end);
pthread_mutex_lock(&SHM->beep_mutex_status);
if (0 == SHM->beep_emit_status)
{
SHM->beep_emit_status++;
}
pthread_mutex_unlock(&SHM->beep_mutex_status);
pthread_mutex_lock(&SHM->beep_mutex_start);
beep_flag = (0 == SHM->beep_emit_start);
if (0 == SHM->beep_emit_start)
{
SHM->beep_emit_start++;
}
pthread_mutex_unlock(&SHM->beep_mutex_start);
if (1 == beep_flag)
{
pthread_cond_signal(&SHM->beep_cond_start);
}
pthread_mutex_lock(&SHM->beep_mutex_end);
while (0 == SHM->beep_emit_end)
{
pthread_cond_wait(&SHM->beep_cond_end, &SHM->beep_mutex_end);
}
if (0 < SHM->beep_emit_end)
{
SHM->beep_emit_end--;
}
pthread_mutex_unlock(&SHM->beep_mutex_end);
}
usleep(100000);
}
}
| 1
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[4];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
pthread_exit((void*) 0);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (4*100*sizeof(double));
b = (double*) malloc (4*100*sizeof(double));
for (i=0; i<100*4; i++)
{
a[i]=1.0;
b[i]=a[i];
}
dotstr.veclen = 100;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0; i<4; i++)
{
pthread_create(&callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0; i<4; i++)
{
pthread_join(callThd[i], &status);
}
printf ("Sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
{
double *a;
double *b;
double sum;
int veclen;
} DOTDATA;
DOTDATA dotstr;
pthread_t callThd[3];
pthread_mutex_t mutexsum;
void *dotprod(void *arg)
{
int i, start, end, len ;
long offset;
double mysum, *x, *y;
offset = (long)arg;
len = dotstr.veclen;
start = offset*len;
end = start + len;
x = dotstr.a;
y = dotstr.b;
mysum = 0;
for (i=start; i<end ; i++)
{
mysum += (x[i] * y[i]);
}
pthread_mutex_lock (&mutexsum);
printf("Thread %ld adding partial sum of %f to global sum of %f\\n",
offset, mysum, dotstr.sum);
dotstr.sum += mysum;
pthread_mutex_unlock (&mutexsum);
}
int main (int argc, char *argv[])
{
long i;
double *a, *b;
void *status;
pthread_attr_t attr;
a = (double*) malloc (3*10*sizeof(double));
b = (double*) malloc (3*10*sizeof(double));
for (i=0; i<10*3; i++) {
a[i]=1;
b[i]=a[i];
}
dotstr.veclen = 10;
dotstr.a = a;
dotstr.b = b;
dotstr.sum=0;
pthread_mutex_init(&mutexsum, 0);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for(i=0;i<3;i++) {
pthread_create( &callThd[i], &attr, dotprod, (void *)i);
}
pthread_attr_destroy(&attr);
for(i=0;i<3;i++) {
pthread_join( callThd[i], &status);
}
printf ("Done. Threaded version: sum = %f \\n", dotstr.sum);
free (a);
free (b);
pthread_mutex_destroy(&mutexsum);
}
| 1
|
#include <pthread.h>
pthread_mutex_t downloader_mutex, parser_mutex;
unsigned long downloaders[MAX_THREADS];
unsigned long parsers[MAX_THREADS];
int downloader_threads = 0;
int parser_threads = 0;
int wait_for_downloaders = 0;
char *fetch(char *link) {
int fd = open(link, O_RDONLY);
if (fd < 0) {
fprintf(stderr, "failed to open file: %s", link);
return 0;
}
int size = lseek(fd, 0, 2);
assert(size >= 0);
char *buf = Malloc(size+1);
buf[size] = '\\0';
assert(buf);
lseek(fd, 0, 0);
char *pos = buf;
while(pos < buf+size) {
int rv = read(fd, pos, buf+size-pos);
assert(rv > 0);
pos += rv;
}
int i = 0;
unsigned long current_id = (unsigned long) pthread_self();
pthread_mutex_lock(&downloader_mutex);
for(i = 0; i < MAX_THREADS; ++i)
{
if(downloaders[i] == -1)
{
downloader_threads++;
downloaders[i] = current_id;
break;
}
else if(downloaders[i] == current_id)
{
break;
}
}
pthread_mutex_unlock(&downloader_mutex);
if(wait_for_downloaders)
{
while(downloader_threads < 5)
sleep(1);
}
if(strcmp(parseURL(link), "pagea") == 0)
{
wait_for_downloaders = 1;
}
close(fd);
return buf;
}
void edge(char *from, char *to) {
int i = 0;
unsigned long current_id = (unsigned long) pthread_self();
pthread_mutex_lock(&parser_mutex);
for(i = 0; i < MAX_THREADS; ++i)
{
if(parsers[i] == -1)
{
parser_threads++;
parsers[i] = current_id;
break;
}
else if(parsers[i] == current_id)
{
break;
}
}
pthread_mutex_unlock(&parser_mutex);
if(strcmp(parseURL(from), "pagea") != 0)
{
while(parser_threads < 4)
sleep(1);
}
}
int main(int argc, char *argv[]) {
pthread_mutex_init(&downloader_mutex, 0);
pthread_mutex_init(&parser_mutex, 0);
int i = 0;
for(i = 0; i < MAX_THREADS; ++i)
{
downloaders[i] = -1;
parsers[i] = -1;
}
int rc = crawl("/u/c/s/cs537-1/ta/tests/4a/tests/files/num_threads/pagea", 5, 4, 15, fetch, edge);
assert(rc == 0);
printf("\\ndownloader_threads : %d\\n", downloader_threads);
check(downloader_threads == 5, "Expected to spawn 5 download threads\\n");
printf("\\nparser_threads : %d\\n", parser_threads);
check(parser_threads == 4, "Expected to spawn 4 parser threads\\n");
return 0;
}
| 0
|
#include <pthread.h>
pthread_mutex_t lock1, lock2;
void *print_forever12(void *args) {
while (1) {
pthread_mutex_lock(&lock1);
fprintf(stdout, "Locked lock1...");
fprintf(stdout, "processing data...");
pthread_mutex_lock(&lock2);
fprintf(stdout, "Locked lock2...");
fprintf(stdout, "processing data...");
pthread_mutex_unlock(&lock2);
fprintf(stdout, "Unlocked lock2...\\n");
pthread_mutex_unlock(&lock1);
fprintf(stdout, "Unlocked lock1...\\n");
}
}
void *print_forever21(void *args) {
while (1) {
pthread_mutex_lock(&lock2);
fprintf(stdout, "Locked lock2...");
fprintf(stdout, "processing data...");
pthread_mutex_lock(&lock1);
fprintf(stdout, "Locked lock1...");
fprintf(stdout, "processing data...");
pthread_mutex_unlock(&lock1);
fprintf(stdout, "Unlocked lock1...\\n");
pthread_mutex_unlock(&lock2);
fprintf(stdout, "Unlocked lock2...\\n");
}
}
int main(int argc, char *argv[]) {
pthread_t t1, t2;
if (pthread_mutex_init(&lock1, 0) != 0 || pthread_mutex_init(&lock2, 0) != 0) {
fprintf(stderr, "Mutex init failed. Error: %s\\n", strerror(errno));
return 1;
}
if (pthread_create(&t1, 0, print_forever12, 0) != 0) {
fprintf(stderr, "Pthread creation failed for t1. Error: %s\\n", strerror(errno));
return 1;
}
if (pthread_create(&t2, 0, print_forever21, 0) != 0) {
fprintf(stderr, "Pthread creation failed for t2. Error: %s\\n", strerror(errno));
return 1;
}
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_mutex_destroy(&lock1);
pthread_mutex_destroy(&lock2);
return 0;
}
| 1
|
#include <pthread.h>
int
makethread(void *(*fn)(void *), void * arg) {
int err;
pthread_t tid;
pthread_attr_t attr;
err = pthread_attr_init(&attr);
if (err != 0)
return(err);
err = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
if (err == 0)
err = pthread_create(&tid, &attr, fn, arg);
pthread_attr_destroy(&attr);
return(err);
}
extern char **environ;
pthread_mutex_t env_mutex;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
static void
thread_init(void) {
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
pthread_mutex_init(&env_mutex, &attr);
pthread_mutexattr_destroy(&attr);
}
int
getenv_r(const char *name, char *buf, int buflen) {
int i, len, olen;
pthread_once(&init_done, thread_init);
len = strlen(name);
pthread_mutex_lock(&env_mutex);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
environ[i][len] == '=') {
olen = strlen(&environ[i][len + 1]);
if (olen >= buflen) {
pthread_mutex_unlock(&env_mutex);
return(ENOSYS);
}
strcpy(buf, &environ[i][len + 1]);
pthread_mutex_unlock(&env_mutex);
return(0);
}
}
pthread_mutex_unlock(&env_mutex);
return(ENOENT);
}
pthread_key_t key;
static void
thread_init2(void) {
pthread_key_create(&key, free);
}
char *
getenv_rr(const char *name) {
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init2);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if (envbuf == 0) {
envbuf = malloc(ARG_MAX);
if (env_buf == 0) {
pthread_mutex_unlock(&env_mutex);
return(0);
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for (i = 0; environ[i] != 0; i++) {
if ((strncmp(name, environ[i], len) == 0) &&
(environ[i][len] = '=')) {
strcpy(envbuf, &environ[i][len + 1]);
pthread_mutex_unlock(&mutex);
return envbuf;
}
}
pthread_mutex_unlock(&mutex);
return(0);
}
| 0
|
#include <pthread.h>
static int classificacao = 1;
static pthread_mutex_t lock;
static char * resp[200];
static int cont = 0;
void *Correr(void *sapo){
int pulos = 0;
int distanciaJaCorrida = 0;
while (distanciaJaCorrida <= 100)
{
int pulo = rand() % 100;
distanciaJaCorrida += pulo;
pulos++;
printf("Sapo %d pulou\\n", (int) sapo);
int descanso = rand() % 1;
sleep(descanso);
}
pthread_mutex_lock(&lock);
printf("Sapo %d chegou na posicaoo %d com %d pulos\\n", (int) sapo,
classificacao, pulos);
cont++;
classificacao++;
pthread_mutex_unlock(&lock);
pthread_exit(0);
}
int main()
{
classificacao =1;
pthread_t threads[5];
int t;
printf("Corrida iniciada ... \\n");
for(t=0;t < 5;t++) pthread_create(&threads[t], 0, Correr, (void *) t);
for(t=0;t < 5; t++) pthread_join(threads[t],0);
printf("\\n Acabou!!\\n");
pthread_exit(0);
}
| 1
|
#include <pthread.h>
pthread_mutex_t chopstiks[5];
int philoTimeEating[5];
int philoTimeThinking[5];
void makeSemaphore(int size);
void* philosopher(void* philo);
void thinking(const int philo, const int thinkingTime, const int totalThinkingTime);
void eating(const int philo, const int eatingTime, const int totalEatingTime);
void initializeMutexes(int size);
int main(void){
int i, *iPtr;
pthread_t philo[5];
initializeMutexes(5);
for(i = 0; i < 5; i++){
iPtr = (int*) malloc(sizeof(int));
*iPtr = i;
pthread_create(&philo[i], 0, philosopher, (void*)iPtr);
}
for(i = 0; i < 5; i++)
pthread_join(philo[i], 0);
printf("**************************************************************************\\n");
for(i = 0; i < 5; i++){
printf("Philosopher %i: Total eating time [%d s], Total thinking time [%d s]\\n",i
,philoTimeEating[i], philoTimeThinking[i]);
}
return 0;
}
void eating(const int philo, const int eatingTime, const int totalEatingTime){
printf("Philo %d is eating for %d seconds. [Time spent eating = %d]\\n", philo
, eatingTime, totalEatingTime);
sleep(eatingTime);
}
void thinking(const int philo, const int thinkingTime, const int totalThinkingTime){
printf("Philo %d is thinking for %d seconds.[Time spent thinking =%d]\\n", philo, thinkingTime, totalThinkingTime);
sleep(thinkingTime);
}
void* philosopher(void* arg){
int philo = *((int*) arg);
int eatingTime = 0;
int totalEatingTime = 0;
int thinkingTime = 0;
int totalThinkingTime =0;
free(arg);
unsigned int state = philo;
while(totalEatingTime <= 100){
while (1) {
pthread_mutex_lock(&chopstiks[philo]);
int rtrn = pthread_mutex_trylock(&chopstiks[(philo+1) % 5]);
if (rtrn == EBUSY)
pthread_mutex_unlock(&chopstiks[philo]);
else break;
sleep(1);
}
if((eatingTime = randomGaussian_r(9, 3, &state)) < 0)
eatingTime = 0;
eating(philo, eatingTime, totalEatingTime);
totalEatingTime += eatingTime;
pthread_mutex_unlock(&chopstiks[philo]);
pthread_mutex_unlock(&chopstiks[(philo+1) % 5]);
if((thinkingTime = randomGaussian_r(11, 7, &state)) < 0)
thinkingTime = 0;
totalThinkingTime += thinkingTime;
thinking(philo, thinkingTime, totalThinkingTime);
}
printf("Philo %i has finished eating. [Total time spent eating = %i]\\n", philo, totalEatingTime);
philoTimeEating[philo] = totalEatingTime;
philoTimeThinking[philo] = totalThinkingTime;
return 0;
}
void initializeMutexes(int size){
for (int i = 0; i < size; i++)
pthread_mutex_init(&chopstiks[i], 0);
}
| 0
|
#include <pthread.h>
int buffer[16];
int itemsPerConsumer;
int itemsPerProducer;
int counter = 0;
sem_t full;
sem_t empty;
pthread_mutex_t lock;
struct producerThread{
int pid;
int producerAmount;
};
void *consume(void *param){
int numberConsumed = *(int *) param;
int item;
int i = 0;
while(i < numberConsumed){
sem_wait(&full);
pthread_mutex_lock(&lock);
if(counter > 0){
counter--;
item = buffer[counter];
printf("Consume %i from slot: %i\\n", item, counter);
buffer[counter] = 0;
}else{
exit(1);
}
pthread_mutex_unlock(&lock);
sem_post(&empty);
i++;
}
pthread_exit(0);
}
void *produce(void *param){
struct producerThread* pdata = (struct producerThread*) param;
int i = 0;
int item;
while(i < pdata->producerAmount){
item = pdata->pid * pdata->producerAmount + i;
sem_wait(&empty);
pthread_mutex_lock(&lock);
if(counter < 16){
buffer[counter] = item;
printf("Add %i to slot %i\\n", item, counter);
counter++;
}else{
exit(1);
}
pthread_mutex_unlock(&lock);
sem_post(&full);
i++;
}
pthread_exit(0);
}
int main(int argc, const char * argv[]){
int i;
int numberOfProducers, numberOFConsumers, totalItemsProduced;
pthread_t *producers;
pthread_t *consumers;
sem_init(&full, 0, 0);
sem_init(&empty, 0, 16);
if (pthread_mutex_init(&lock, 0) != 0) {
printf("\\nError initializing the mutex\\n");
return 1;
}
numberOfProducers = pow(2, atoi(argv[1]));
numberOFConsumers = pow(2, atoi(argv[2]));
totalItemsProduced = pow(2, atoi(argv[3]));
itemsPerProducer = totalItemsProduced / numberOfProducers;
itemsPerConsumer = totalItemsProduced / numberOFConsumers;
printf("Producers: %i\\n", numberOfProducers);
printf("Consumers: %i\\n", numberOFConsumers);
printf("Items produced: %i\\n\\n", totalItemsProduced);
printf("Items per producer: %i\\n", itemsPerProducer);
printf("Items per consumer: %i\\n\\n", itemsPerConsumer);
producers = (pthread_t *)malloc(numberOfProducers * sizeof(pthread_t));
consumers = (pthread_t *)malloc(numberOFConsumers * sizeof(pthread_t));
struct producerThread pData[numberOfProducers];
for(i = 0; i < numberOfProducers; i++){
pData[i].pid = i;
pData[i].producerAmount = itemsPerProducer;
if(pthread_create(&producers[i], 0, produce, &pData[i]) != 0){
printf("\\nError creating producer threads\\n");
return 1;
}
}
for(i = 0; i < numberOFConsumers; i++){
if(pthread_create(&consumers[i], 0, consume, &itemsPerConsumer) != 0){
printf("\\nError creating consumer threads\\n");
return 1;
}
}
for(i = 0; i < numberOfProducers; i++){
pthread_join(producers[i], 0);
}
for( i=0; i < numberOFConsumers; i++){
pthread_join(consumers[i], 0);
}
free(producers);
free(consumers);
pthread_mutex_destroy(&lock);
sem_destroy(&full);
sem_destroy(&empty);
printf("\\nConsuming/Producing is done!\\n");
return 0;
}
| 1
|
#include <pthread.h>
struct arg_set
{
char* fname;
int count;
};
struct arg_set* mailbox;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t flag = PTHREAD_COND_INITIALIZER;
void* count_words(void*);
int main( int ac, char* av[] )
{
if (ac < 2)
{
printf("\\n::pc14-2 Command::\\n");
printf(" ./pc14-2 File1, File2,.. : Enter one of more filenames\\n");
printf(" Returns the total amount of\\n");
printf(" words in each file\\n\\n");
exit(1);
}
int reports_in = 0;
int total_words = 0;
pthread_mutex_lock( &lock );
pthread_t t[ac-1];
struct arg_set args[ac-1];
int i;
for (i = 0; i < (ac-1); i++)
{
args[i].fname = av[i+1];
args[i].count = 0;
pthread_create(&t[i], 0, count_words, (void*) &args[i]);
}
printf("\\n");
while (reports_in < (ac-1))
{
printf("MAIN: waiting for flag to go up\\n");
pthread_cond_wait(&flag, &lock);
printf("MAIN: Wow! flag was raised, I have the lock\\n");
printf("%10d: %s\\n", mailbox->count, mailbox->fname);
total_words += mailbox->count;
for (i = 0; i < (ac-1); i++)
if (mailbox == &args[i])
pthread_join(t[i], 0);
mailbox = 0;
pthread_cond_signal(&flag);
reports_in++;
}
printf("%10d: totalwords\\n\\n", total_words);
}
void* count_words(void* a)
{
struct arg_set* args = a;
FILE* fp;
int c, prevc = '\\0';
if ( (fp = fopen(args->fname, "r")) != 0 )
{
while ( (c = getc(fp)) != EOF )
{
if (!isalnum(c) && isalnum(prevc))
args->count++;
prevc = c;
}
fclose(fp);
}
else
perror(args->fname);
printf("COUNT: waiting to get lock\\n");
pthread_mutex_lock(&lock);
printf("COUNT: have the lock, storing data\\n");
if (mailbox != 0)
pthread_cond_wait(&flag, &lock);
mailbox = args;
printf("COUNT: raising flag\\n");
pthread_cond_signal(&flag);
pthread_mutex_unlock(&lock);
return 0;
}
| 0
|
#include <pthread.h>
void * thread_read_spi_rx()
{
int ret_val =0;
unsigned char buffer;
sleep(1);
while(1)
{
while( ioctl(fd_spi,READ_GPIO,0) < 0 || SpiFlag != 1)
{
printf("\\n GPIO FAILED");
sleep(1);
}
SpiFlag = 0;
do
{
ret_val = read_data_spi(&buffer,1);
if(ret_val == -1)
{
printf("\\n GPIO READ FAILED");
fflush(stdout);
}
}while(ret_val < 0);
while( ioctl(fd_spi,READ_MSG,0) < 0)
{
printf("\\n IOCTL READ FAILED");
sleep(1);
}
while( ioctl(fd_spi,NUMBR_OF_BITS_8,0) < 0)
{
printf("\\n IOCTL FAILED");
sleep(1);
}
pthread_mutex_lock(&spi_lock);
do
{
ret_val = read_data_spi(&buffer,1);
if(ret_val == -1)
{
printf("\\n DATA READ FAILED");
fflush(stdout);
}
}while(ret_val < 0);
pthread_mutex_unlock(&spi_lock);
printf(" \\n DATA READ SUCCESSFULLY %d",buffer);
}
}
| 1
|
#include <pthread.h>
void printPhilosophers() {
for (int i = 0; i < PHILOSOPHERS; i++) {
if (philosopher_condition[i] == HUNGRY) {
printf("%s", "HUNGRY ");
} else if (philosopher_condition[i] == THINKING) {
printf("%s", "THINKING ");
} else if (philosopher_condition[i] == EATING) {
printf("%s", "EATING ");
}
}
printf("\\n");
}
void pickUpChopstick(int chopstick) {
pthread_mutex_lock(&chopsticks[chopstick]);
if (chopstick_condition[chopstick] < 0) {
printf("*** CRITICAL SECTION VIOLATION; TERMINATING ***\\n");
exit(1);
}
chopstick_condition[chopstick] += 1;
}
void dropChopstick(int chopstick) {
pthread_mutex_unlock(&chopsticks[chopstick]);
chopstick_condition[chopstick] -= 1;
}
int randomWait(int bound) {
int wait = rand() % bound;
sleep(wait);
return wait;
}
void eat(int philosopher) {
pickUpChopstick(philosopher);
pickUpChopstick((philosopher + 1) % PHILOSOPHERS);
philosopher_condition[philosopher] = EATING;
randomWait(10);
}
void think(int philosopher) {
randomWait(10);
philosopher_condition[philosopher] = HUNGRY;
}
void finishedEating(int philosopher) {
dropChopstick(philosopher);
dropChopstick((philosopher + 1) % PHILOSOPHERS);
philosopher_condition[philosopher] = THINKING;
}
| 0
|
#include <pthread.h>
{
int stock;
pthread_t thread_store;
pthread_t thread_clients [2];
pthread_mutex_t mutex_stock;
}
store_t;
static store_t store =
{
.stock = 200,
.mutex_stock = PTHREAD_MUTEX_INITIALIZER,
};
static int get_random (int max)
{
double val;
val = (double) max * rand ();
val = val / (32767 + 1.0);
return ((int) val);
}
static void * fn_store (void * p_data)
{
while (1)
{
pthread_mutex_lock (& store.mutex_stock);
if (store.stock <= 0)
{
store.stock = 200;
printf ("Remplissage du stock de %d articles !\\n", store.stock);
}
pthread_mutex_unlock (& store.mutex_stock);
}
return 0;
}
static void * fn_clients (void * p_data)
{
int nb = (int) p_data;
while (1)
{
int val = get_random (6);
pthread_mutex_lock (& store.mutex_stock);
if (store.stock >= val){
store.stock = store.stock - val;
printf (
"Client %d prend %d du stock, reste %d en stock !\\n",
nb, val, store.stock
);}
else printf ("Client %d demande %d - Stock vide !!!\\n",nb,val );
pthread_mutex_unlock (& store.mutex_stock);
}
return 0;
}
int main (void)
{
int i = 0;
int ret = 0;
printf ("Creation du thread du magasin !\\n");
ret = pthread_create (
& store.thread_store, 0,
fn_store, 0
);
if (! ret)
{
printf ("Creation des threads clients !\\n");
for (i = 0; i < 2; i++)
{
ret = pthread_create (
& store.thread_clients [i], 0,
fn_clients, (void *) i
);
if (ret)
{
fprintf (stderr, "%s", strerror (ret));
}
}
}
else
{
fprintf (stderr, "%s", strerror (ret));
}
i = 0;
for (i = 0; i < 2; i++)
{
pthread_join (store.thread_clients [i], 0);
}
pthread_join (store.thread_store, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct BUFDATA {
int producer_tid;
int data_id;
struct BUFDATA *prev;
struct BUFDATA *next;
};
struct BUFDATA* head = 0;
pthread_mutex_t mutex;
int sema = 0;
int prod_num = 0;
int consum_num = 0;
int buf_size = 0;
int prod_count = 0;
int consum_count = 0;
void* producer(void* arg);
void* consumer(void* arg);
void insert(struct BUFDATA* buf);
struct BUFDATA* delete();
int isfull();
int isempty();
int count_producer();
int main(int argc, char* argv[])
{
int i = 0;
int state;
union semun sem_union;
pthread_t prod_thread[prod_num];
pthread_t comsum_thread[consum_num];
prod_num = atoi(argv[1]);
consum_num = atoi(argv[2]);
buf_size = atoi(argv[3]);
sema = semget((key_t)0x1234, 1, 0666 | IPC_CREAT);
if (sema < 0)
{
printf("semget failed\\n");
return 1;
}
sem_union.val = buf_size;
if (semctl(sema, 0, SETVAL, sem_union) == -1)
{
printf("semctl failed\\n");
return 1;
}
state = pthread_mutex_init(&mutex, 0);
if (state)
{
printf("mutex init error\\n");
return 1;
}
for (i = 0;i < prod_num;++i)
{
pthread_create(&prod_thread[i], 0, producer, 0);
}
for (i = 0;i < consum_num;++i)
{
pthread_create(&comsum_thread[i], 0, consumer, 0);
}
for (i = 0;i < prod_num;++i)
{
pthread_join(prod_thread[i], 0);
}
for (i = 0;i < consum_num;++i)
{
pthread_join(comsum_thread[i], 0);
}
pthread_mutex_destroy(&mutex);
if (semctl(sema, 0, IPC_RMID, 0) == -1)
{
printf("semctl failed\\n");
return 1;
}
return 0;
}
void* producer(void* arg)
{
pid_t tid = syscall(SYS_gettid);
struct BUFDATA* buf;
struct sembuf s;
s.sem_num = 0;
s.sem_flg = SEM_UNDO;
while (1)
{
s.sem_op = -1;
if (semop(sema, &s, 1) == -1)
{
printf("semop fail\\n");
}
pthread_mutex_lock(&mutex);
if (isfull())
{
prod_count++;
buf = (struct BUFDATA*)malloc(sizeof(struct BUFDATA));
buf->producer_tid = tid;
buf->data_id = prod_count;
insert(buf);
printf("[Producer %u] produced %d (buffer state : %d/%d)\\n", tid, count_producer(), prod_count - consum_count, buf_size);
}
pthread_mutex_unlock(&mutex);
sleep(2);
s.sem_op = 1;
if (semop(sema, &s, 1) == -1)
{
printf("semop fail\\n");
}
}
return 0;
}
void* consumer(void* arg)
{
pid_t tid = syscall(SYS_gettid);
struct BUFDATA* buf;
struct sembuf s;
s.sem_num = 0;
s.sem_flg = SEM_UNDO;
while (1)
{
s.sem_op = -1;
if (semop(sema, &s, 1) == -1)
printf("semop fail\\n");
pthread_mutex_lock(&mutex);
if (isempty())
{
consum_count++;
buf = delete();
printf("[Consumer %u] consumed %d, produced from %u (buffer state : %d/%d)\\n", tid, consum_count, buf->producer_tid, prod_count - consum_count, buf_size);
free(buf);
}
pthread_mutex_unlock(&mutex);
sleep(3);
s.sem_op = 1;
if (semop(sema, &s, 1) == -1)
printf("semop fail\\n");
}
return 0;
}
void insert(struct BUFDATA* buf)
{
struct BUFDATA* cur;
if (head == 0)
{
head = buf;
buf->next = 0;
buf->prev = 0;
}
else
{
cur = head;
while (cur->next != 0)
{
cur = cur->next;
}
cur->next = buf;
buf->next = 0;
buf->prev = cur;
}
}
struct BUFDATA* delete()
{
struct BUFDATA* del = head;
if (del->next == 0)
head = 0;
else
{
head = del->next;
head->prev = 0;
}
return del;
}
int count_producer()
{
struct BUFDATA* buf = head;
if (head == 0)
return 0;
else
{
while (buf->next != 0)
{
buf = buf->next;
}
return buf->data_id;
}
}
int isfull()
{
struct BUFDATA* buf = head;
int count = 0;
if (head == 0)
return 1;
while (buf->next != 0)
{
buf = buf->next;
count++;
}
if (count == buf_size)
return 0;
else
return 1;
}
int isempty()
{
if (prod_count == consum_count)
return 0;
else
return 1;
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
pthread_mutex_t mutexProd;
pthread_mutex_t mutexCons;
pthread_cond_t emptySlots;
pthread_cond_t filledSlots;
int buffer[10];
int in = 0;
int out = 0;
int count = 0;
void *producer(void *param);
void *consumer(void *param);
int main(int argc, char *argv[])
{
int i = 0;
if (argc != 2) { fprintf(stderr,"usage: bb <integer value>\\n"); return -1; }
pthread_t tid[1000];
pthread_mutex_init(&mutex, 0);
startTimer();
for(i=0;i<1000;i++) {
if(i%2 == 0) pthread_create(&tid[i],0,producer,argv[1]);
if(i%2 == 1) pthread_create(&tid[i],0,consumer,argv[1]);
}
for(i=0;i<1000;i++) pthread_join(tid[i],0);
printf("Time: %ld\\n",endTimer());
return 0;
}
void *producer(void *param)
{
int i = 0;
int n = atoi(param);
int bNew = 1;
while(n) {
if(bNew) {
i++;
usleep(5000+rand()%100);
}
pthread_mutex_lock(&mutex);
if(count == 10) {
pthread_mutex_unlock(&mutex);
bNew = 0;
continue;
}
count++;
bNew = 1;
buffer[in] = i;
printf("produced %d and putting it at %d\\n",i,in);
in = (in+1)%10;
pthread_mutex_unlock(&mutex);
n--;
}
pthread_exit(0);
}
void *consumer(void *param)
{
int i;
int n = atoi(param);
while(n) {
pthread_mutex_lock(&mutex);
if(count == 0) {
pthread_mutex_unlock(&mutex);
continue;
}
count--;
i = buffer[out];
printf("taken %d from pos %d\\n",i,out);
out = (out+1)%10;
pthread_mutex_unlock(&mutex);
usleep(1000+rand()%100);
n--;
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
struct work_args {
pthread_mutex_t *mutex;
struct timeval *start;
struct timeval *end;
double ***matrix;
int *row;
int id;
};
double do_crazy_computation(int i,int j);
double standard_deviation(double vals[], int length);
double average(double vals[], int length);
double max_deviation(double vals[], int length);
void *do_work(void *arg);
void check_work(double *check[]);
int main(int argc, char **argv) {
int row = 0;
int numthreads = 2;
double mat[10][10];
struct timeval start[numthreads+1], end[numthreads+1];
double elapsed[numthreads+1];
int half = 10/2;
gettimeofday(&start[2], 0);
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, 0);
struct work_args args[numthreads];
pthread_t *threads = (pthread_t *)calloc(numthreads, sizeof(pthread_t));
for(int i = 0; i < numthreads; i++){
args[i].row = &row;
args[i].mutex = &mutex;
args[i].id = i;
args[i].start = &start[i];
args[i].end = &end[i];
args[i].matrix = &mat;
if(pthread_create(&threads[i], 0, do_work, (void*)(&args[i]))){
fprintf(stderr, "Error creating thread, exiting...");
exit(1);
}
}
for(int i = 0; i < numthreads; i++){
pthread_join(threads[i], 0);
}
gettimeofday(&end[2], 0);
for(int thread=0; thread < numthreads + 1; thread++){
elapsed[thread] = ((end[thread].tv_sec*1000000.0 + end[thread].tv_usec) -
(start[thread].tv_sec*1000000.0 + start[thread].tv_usec)) / 1000000.00;
if(thread < numthreads)
}
double av = average(elapsed, numthreads);
double max_dev = max_deviation(elapsed, numthreads);
double std_dev = standard_deviation(elapsed, numthreads);
printf("\\nOverall execution time: %.2f seconds\\n",elapsed[2]);
printf("Load imbalance: %.2f%\\n", (max_dev/av)*100.0);
for(int i = 0; i < 10; i++){
for(int j = 0; j < 10; j++){
check_work("%.2f",mat[i][j]);
}
}
exit(0);
}
void *do_work(void *arg){
struct work_args *args = (struct work_args*)arg;
pthread_mutex_t *mutex = args->mutex;
struct timeval *start = args->start;
struct timeval *end = args->end;
double **matrix = *(args->matrix);
int *row = args->row;
int t = args->id;
int i = t;
gettimeofday(start, 0);
while(i < 10) {
for (int j=0;j<10;j++) {
(matrix+(i))[j] = do_crazy_computation((i),j);
fprintf(stderr,".");
}
pthread_mutex_lock(mutex);
i = (*row)++;
pthread_mutex_unlock(mutex);
}
gettimeofday(end, 0);
}
double do_crazy_computation(int x,int y) {
int iter;
double value=0.0;
for (iter = 0; iter < 5*x*x*x+1 + y*y*y+1; iter++) {
value += (cos(x*value) + sin(y*value));
}
return value;
}
void check_work(double *check[]){
int e = 0.00000001;
for (int i=0;i<10;i++) {
for (int j=0;j<10;j++) {
if(fabs(do_crazy_computation(i,j) - **(check+(i*j))) > e)
fprintf(stderr,"ERROR");
else
fprintf(stderr,".");
}
}
}
double average(double vals[], int length){
double sum = 0;
for(int i = 0; i < length; i++){
sum += vals[i];
}
sum /= length;
return sum;
}
double standard_deviation(double vals[], int length){
double av = average(vals, length);
double sum = 0;
double value = 0;
for(int i = 0; i < length; i++){
value = vals[i] - av;
value *= value;
sum += value;
}
sum /= length;
return sqrt(sum);
}
double max_deviation(double vals[], int length){
double av = average(vals, length);
double max = 0;
double value = 0;
for(int i = 0; i < length; i++){
value = fabs(vals[i] - av);
if(value > max){
max = value;
}
}
return max;
}
| 0
|
#include <pthread.h>
void *thr_sub(void *);
pthread_mutex_t lock;
int main(int argc, char **argv)
{
int thr_count = 100;
if(argc == 2){
thr_count = atoi(argv[1]);
}
printf("Creating %d threads...\\n", thr_count);
pthread_mutex_lock(&lock);
pthread_t threads[thr_count];
int idx;
for(idx = 0; idx < thr_count; ++idx){
if(0 != pthread_create((pthread_t*) &threads[idx], 0, thr_sub, (void*) 2048)){
perror("pthread create failed");
break;
}
}
printf("%d threads have been created and are running!\\n", idx);
printf("Press <return> to join all the threads...\\n");
fgetc(stdin);
printf("Joining %d threads...\\n", thr_count);
pthread_mutex_unlock(&lock);
for( idx = 0; idx < thr_count; ++idx){
pthread_join(threads[idx], 0);
}
printf("All %d threads have been joined, exiting...\\n", thr_count);
exit(0);
}
void *thr_sub(void *arg)
{
pthread_mutex_lock(&lock);
printf("Thread %lu is exiting...\\n", (unsigned long) pthread_self());
pthread_mutex_unlock(&lock);
return((void *)0);
}
| 1
|
#include <pthread.h>
int done = 0;
int count = 0;
int quantum = 2;
int thread_ids[4] = {0,1,2,3};
int thread_runtime[4] = {0,5,4,7};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void * inc_count(void * arg);
static sem_t count_sem;
int quit = 0;
void *inc_count(void *t)
{
long my_id = (long)t;
int i;
sem_wait(&count_sem);
printf("run_thread = %d\\n",my_id);
printf("%d \\n",thread_runtime[my_id]);
for( i=0; i < thread_runtime[my_id];i++)
{
printf("runtime= %d\\n",thread_runtime[my_id]);
pthread_mutex_lock(&count_mutex);
count++;
if (count == 13) {
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) ;
}
sem_post(&count_sem);
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);
if (count<13) {
pthread_cond_wait(&count_threshold_cv, &count_mutex);
printf("watch_count(): thread %ld Condition signal received.\\n", my_id);
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;
long t1=0, t2=1, t3=2, t4=3;
pthread_t threads[4];
pthread_attr_t attr;
sem_init(&count_sem, 0, 1);
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);
pthread_create(&threads[3], &attr, inc_count, (void *)t4);
for (i=0; i<4; i++) {
pthread_join(threads[i], 0);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&count_mutex);
pthread_cond_destroy(&count_threshold_cv);
pthread_exit(0);
}
| 0
|
#include <pthread.h>
const int MAXIMUN_RGB = 255;
struct YUV * LUT_RGB2YUV [64][64][64];
int isInitTableYUV;
pthread_mutex_t mutex;
void rgb2yuv_wiki (double r, double g, double b, double *Y, double *U, double *V)
{
r = r / MAXIMUN_RGB;
g = g / MAXIMUN_RGB;
b = b / MAXIMUN_RGB;
*Y = r * 0.299 + g * 0.587 + b * 0.114;
*U = -0.14713*r - 0.289*g + 0.436*b;
*V = 0.615*r - 0.515*g - 0.100*b;
}
void yuv2rgb(double Y, double U, double V, double *r, double *g, double *b)
{
*r = Y + 1.13983 * V;
*g = Y - 0.39465 * U - 0.58060 * V;
*b = Y + 2.03211 * U;
if (*r>1.0){*r = 1.0;}
if (*g>1.0){*g = 1.0;}
if (*b>1.0){*b = 1.0;}
if (*r<0.0){*r = 0.0;}
if (*g<0.0){*g = 0.0;}
if (*b<0.0){*b = 0.0;}
}
void print_status_HSV(unsigned long status)
{
unsigned int t = 8;
unsigned int i;
unsigned long int j= 1 << (t - 1);
for (i= t; i > 0; --i)
{
printf("%d", (status & j) != 0);
j>>= 1;
if (i==3)
printf(" ");
}
printf(" (%lu)\\n",status);
}
void RGB2YUV_destroyTable ()
{
int r,g,b;
int pos_r, pos_g, pos_b;
int count = 4;
printf("Destroy Table LUT_RGB2YUV .... OK\\n");
for (b=0;b<=MAXIMUN_RGB;b=b+count)
for (g=0;g<=MAXIMUN_RGB;g=g+count)
for (r=0;r<=MAXIMUN_RGB;r=r+count)
{
if (r==0) pos_r=0; else pos_r = r/4;
if (g==0) pos_g=0; else pos_g = g/4;
if (b==0) pos_b=0; else pos_b = b/4;
if (LUT_RGB2YUV[pos_r][pos_g][pos_b])
{
free(LUT_RGB2YUV[pos_r][pos_g][pos_b]);
}
}
pthread_mutex_lock(&mutex);
isInitTableYUV = 0;
pthread_mutex_unlock(&mutex);
}
void RGB2YUV_init()
{
pthread_mutex_lock(&mutex);
if (isInitTableYUV==1)
{
pthread_mutex_unlock(&mutex);
return;
}
pthread_mutex_unlock(&mutex);
printf("Init %s v%s ... \\n",NAME,COLORSPACES_VERSION);
pthread_mutex_lock(&mutex);
isInitTableYUV = 0;
pthread_mutex_unlock(&mutex);
}
void RGB2YUV_createTable()
{
int r,g,b;
int count, index;
int pos_r, pos_g, pos_b;
struct YUV* newYUV;
pthread_mutex_lock(&mutex);
if (isInitTableYUV==1)
{
pthread_mutex_unlock(&mutex);
printf("YUV table already exists\\n");
return;
}
pthread_mutex_unlock(&mutex);
count = 4;
index = 0;
for (b=0;b<=MAXIMUN_RGB;b=b+count)
for (g=0;g<=MAXIMUN_RGB;g=g+count)
for (r=0;r<=MAXIMUN_RGB;r=r+count)
{
newYUV = (struct YUV*) malloc(sizeof(struct YUV));
if (!newYUV)
{
printf("Allocated memory error\\n");
exit(-1);
}
rgb2yuv_wiki(r,g,b,&(newYUV->Y),&(newYUV->U),&(newYUV->V));
if (r==0) pos_r=0; else pos_r = r/4;
if (g==0) pos_g=0; else pos_g = g/4;
if (b==0) pos_b=0; else pos_b = b/4;
LUT_RGB2YUV[pos_r][pos_g][pos_b] = newYUV;
index++;
}
printf("Table 'LUT_RGB2YUV' create with 6 bits (%d values)\\n",index);
pthread_mutex_lock(&mutex);
isInitTableYUV=1;
pthread_mutex_unlock(&mutex);
}
void RGB2YUV_printYUV (struct YUV* yuv)
{
printf("YUV: %.1f,%.1f,%.1f\\n",yuv->Y,yuv->U,yuv->V);
}
void RGB2YUV_test (void)
{
int r,g,b;
const struct YUV* myYUV=0;
struct YUV myYUV2;
char line[16];
while (1)
{
printf("\\nIntroduce R,G,B: ");
fgets(line,16,stdin);
if ( sscanf(line,"%d,%d,%d",&r,&g,&b)!= 3)
break;
myYUV = RGB2YUV_getYUV(r,g,b);
if (myYUV==0)
{
printf ("Error in myYUV=NULL\\n");
continue;
}
printf("[Table] RGB: %d,%d,%d -- YUV: %.1f,%.1f,%.1f\\n",r,g,b,myYUV->Y,myYUV->U,myYUV->V);
rgb2yuv_wiki(r,g,b,&myYUV2.Y,&myYUV2.U,&myYUV2.V);
printf("[Algor] RGB: %d,%d,%d -- YUV: %.1f,%.1f,%.1f\\n",r,g,b,myYUV2.Y,myYUV2.U,myYUV2.V);
}
}
| 1
|
#include <pthread.h>
char write_file[3][10] = {"11.c", "12.c", "13.c"};
char buf[1024];
int over_flag = 0;
int write_flag = 1;
int read_flag[3] = {100, 100, 100};
int src_fd, dest_fd[3],len, size;
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_t read_tid, write_tid[3];
void *read_fun(void *arg)
{
if((src_fd = open("1.c", O_APPEND|O_RDWR)) == -1)
{
printf("open source file wrong\\n");
pthread_cancel(write_tid[0]);
pthread_cancel(write_tid[1]);
pthread_cancel(write_tid[2]);
return 0;
}
len = lseek(src_fd, 0, 2);
printf("file length is %d\\n", len);
lseek(src_fd, 0, 0);
int num = 0;
while(1)
{
if(write_flag==1)
{
pthread_rwlock_wrlock(&rwlock);
over_flag = 0;
read_flag[0] = 0;
read_flag[1] = 1;
read_flag[2] = 2;
memset(buf, 0, 1024);
num++;
printf("read %d\\n", num);
write_flag = 2;
size = read(src_fd, buf, 1024);
if(lseek(src_fd, 0, 1) == len)
{
over_flag = 1;
printf("read end\\n");
pthread_rwlock_unlock(&rwlock);
break;
}
pthread_rwlock_unlock(&rwlock);
}
}
close(src_fd);
}
void *write_fun(void *arg)
{
if((dest_fd[(int)arg] = open(write_file[(int)arg], O_TRUNC |O_CREAT|O_RDWR, S_IRWXU)) == -1)
{
printf("open destination file wrong\\n");
return 0;
}
while(over_flag<4)
{
if(read_flag[(int)arg] == (int)arg)
{
printf("write\\n");
pthread_rwlock_rdlock(&rwlock);
read_flag[(int)arg] = 100;
printf("write result is %d\\n",write(dest_fd[(int)arg], buf, size));
printf("errno is %d\\n", errno);
pthread_mutex_lock(&mutex);
over_flag++;
write_flag++;
if(write_flag>=5)
write_flag = 1;
if(over_flag>=4)
{
pthread_mutex_unlock(&mutex);
pthread_rwlock_unlock(&rwlock);
break;
}
pthread_mutex_unlock(&mutex);
pthread_rwlock_unlock(&rwlock);
}
}
close(dest_fd[(int)arg]);
}
int main()
{
int err;
err = pthread_rwlock_init(&rwlock, 0);
if(err)
{
printf("rwlock init failed\\n");
return;
}
err = pthread_mutex_init(&mutex, 0);
if(err)
{
printf("mutex init failed\\n");
return;
}
err = pthread_create(&read_tid, 0, read_fun, 0);
if(err)
{
printf("create read thread failed\\n");
return;
}
int i;
for(i=0; i<3; i++)
{
err = pthread_create(&write_tid[i], 0, write_fun, (void *)i);
if(err)
{
printf("create write thread failed\\n");
return;
}
}
pthread_join(read_tid, 0);
for(i=0; i<3; i++)
{
pthread_join(write_tid[i], 0);
}
pthread_mutex_destroy(&mutex);
pthread_rwlock_destroy(&rwlock);
return 0;
}
| 0
|
#include <pthread.h>
volatile int count = 0;
pthread_mutex_t count_lock;
void *process(void *arg)
{
int procid = *((char *) arg) - '0';
while (1) {
pthread_mutex_lock(&count_lock);
if (count < 1000) {
count++;
} else {
pthread_mutex_unlock(&count_lock); break;
}
printf("Thread %d updated count: %d\\n", procid, count);
pthread_mutex_unlock(&count_lock);
usleep(1);
}
printf("Thread %d exiting..\\n", procid);
return 0;
}
int main(int argc, char **argv)
{
pthread_t thread0, thread1, thread2;
void *retval;
pthread_mutex_init(&count_lock, 0);
int i;
if (pthread_create(&thread0, 0, process, "0") ||
pthread_create(&thread1, 0, process, "1") ||
pthread_create(&thread2, 0, process, "2")) {
fprintf(stderr, "Cannot create thread\\n");
exit(1);
}
if (pthread_join(thread0, &retval) ||
pthread_join(thread1, &retval) ||
pthread_join(thread2, &retval)) {
fprintf(stderr, "Thread join failed");
exit(1);
}
return 0;
}
| 1
|
#include <pthread.h>
int *table;
int flour=1000;
pthread_mutex_t kitchen;
void *mother() {
int sec=0,i=0;
while(flour>0) {
if(table[i]==0) {
pthread_mutex_lock(&kitchen);
sec=rand()/(32767/100)+1;
if(sec>flour) {
sec=flour;
}
usleep(sec*1000);
flour-=sec;
table[i]=1;
printf("Pasta gotova: %d!\\n", i);
i++;
if(i>=4) {
i=0;
}
pthread_mutex_unlock(&kitchen);
}
}
pthread_exit(0);
}
void *ivancho() {
int sec=0,i=0;
while(flour>0 || table[i]==1) {
if(table[i]==1) {
pthread_mutex_lock(&kitchen);
sec=rand()/(32767/100)+1;
usleep(sec*1000);
table[i]=0;
printf("Pasta izqdena: %d!\\n", i);
i++;
if(i>=4) {
i=0;
}
pthread_mutex_unlock(&kitchen);
}
}
pthread_exit(0);
}
void main() {
int i;
table=malloc(4*sizeof(int));
for(i=0;i<4;++i) {
table[i]=0;
}
pthread_t maika, ivan;
pthread_mutex_init(&kitchen, 0);
pthread_create(&maika, 0, mother, 0);
pthread_create(&ivan, 0, ivancho, 0);
pthread_join(maika, 0);
pthread_join(ivan, 0);
printf("Brashno: %d\\n", flour);
pthread_mutex_destroy(&kitchen);
free(table);
}
| 0
|
#include <pthread.h>
struct thread_content
{
pthread_mutex_t *mutex[2];
};
void *print(void *value)
{
pthread_t selfID = pthread_self();
struct thread_content *ptr = (struct thread_content*)value;
for(int it=0;it<100000;it++)
{
for(;;)
{
pthread_mutex_lock(ptr->mutex[0]);
if(pthread_mutex_trylock(ptr->mutex[1]))
{
break;
}
else
{
pthread_mutex_unlock(ptr->mutex[0]);
}
}
pthread_mutex_unlock(ptr->mutex[1]);
pthread_mutex_unlock(ptr->mutex[0]);
}
pthread_exit(0);
};
int main(int argc, char **argv)
{
pthread_t threads[3];
struct thread_content context[3];
pthread_mutex_t mutex[3];
int noMutex = 3;
int noContext = 2;
pthread_mutex_init(&mutex[0],0);
context[0].mutex[0] = &mutex[0];
context[0].mutex[1] = &mutex[1];
pthread_mutex_init(&mutex[1],0);
context[1].mutex[0] = &mutex[1];
context[1].mutex[1] = &mutex[2];
pthread_mutex_init(&mutex[2],0);
context[2].mutex[0] = &mutex[2];
context[2].mutex[1] = &mutex[0];
for (int i = 0; i < noMutex; i++)
{
pthread_create(&threads[i],0,print,(void*)&context[i]);
}
pthread_join(threads[0],0);
pthread_join(threads[1],0);
pthread_join(threads[2],0);
printf("DONE\\n");
pthread_mutex_destroy(&threads[0]);
pthread_mutex_destroy(&threads[1]);
pthread_mutex_destroy(&threads[2]);
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t id;
int recursive;
pthread_t owner;
} Mutex_t;
Mutex_t *CreateMutex (void)
{
Mutex_t *mutex;
pthread_mutexattr_t attr;
mutex = (Mutex_t *)calloc(1, sizeof(*mutex));
if ( mutex ) {
pthread_mutexattr_init(&attr);
if ( pthread_mutex_init(&mutex->id, &attr) != 0 ) {
SetError("pthread_mutex_init() failed");
free(mutex);
mutex = 0;
}
} else {
OutOfMemory();
}
return(mutex);
}
void DestroyMutex(Mutex_t *mutex)
{
if ( mutex ) {
pthread_mutex_destroy(&mutex->id);
free(mutex);
}
}
int mutexP(Mutex_t *mutex)
{
int retval;
pthread_t this_thread;
if ( mutex == 0 ) {
SetError("Passed a NULL mutex");
return -1;
}
retval = 0;
this_thread = pthread_self();
if ( mutex->owner == this_thread ) {
++mutex->recursive;
} else {
if ( pthread_mutex_lock(&mutex->id) == 0 ) {
mutex->owner = this_thread;
mutex->recursive = 0;
} else {
SetError("pthread_mutex_lock() failed");
retval = -1;
}
}
return retval;
}
int mutexV(Mutex_t *mutex)
{
int retval;
if ( mutex == 0 ) {
SetError("Passed a NULL mutex");
return -1;
}
retval = 0;
if ( pthread_self() == mutex->owner ) {
if ( mutex->recursive ) {
--mutex->recursive;
} else {
mutex->owner = 0;
pthread_mutex_unlock(&mutex->id);
}
} else {
SetError("mutex not owned by this thread");
retval = -1;
}
return retval;
}
| 0
|
#include <pthread.h>
int first_pack = 0;
struct timeval dateInicio, dateFin;
pthread_mutex_t lock;
int mostrarInfo = 0;
int MAX_PACKS = 0;
int NTHREADS = 0;
double segundos;
void print_usage(){
printf("Uso: ./dev_null [--verbose] --packets <num> --threads <num>\\n");
}
void print_config(){
printf("Detalles de la prueba:\\n");
printf("\\tPaquetes a leer:\\t%d de %d bytes\\n", MAX_PACKS, 512);
printf("\\tThreads que leeran concurrentemente:\\t%d\\n", NTHREADS);
}
void parseArgs(int argc, char **argv){
int c;
int digit_optind = 0;
while (1){
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
{"packets", required_argument, 0, 'd'},
{"threads", required_argument, 0, 't'},
{"verbose", no_argument, 0, 'v'},
{0, 0, 0, 0}
};
c = getopt_long (argc, argv, "vd:t:",
long_options, &option_index);
if (c == -1)
break;
switch (c){
case 'v':
printf ("Modo Verboso\\n");
mostrarInfo = 1;
break;
case 'd':
MAX_PACKS = atoi(optarg);
break;
case 't':
NTHREADS = atoi(optarg);
break;
default:
printf("Error: La función getopt_long ha retornado un carácter desconocido. El carácter es = %c\\n", c);
print_usage();
exit(1);
}
}
}
void llamadaHilo(int dev_fd){
char buf[512];
int lectura;
int paquetesParaAtender = MAX_PACKS/NTHREADS;
int i;
for(i = 0; i < paquetesParaAtender; i++) {
lectura = read(dev_fd, buf, 512);
if(first_pack==0) {
pthread_mutex_lock(&lock);
if(first_pack == 0) {
if(mostrarInfo) printf("got first pack\\n");
first_pack = 1;
gettimeofday(&dateInicio, 0);
}
pthread_mutex_unlock(&lock);
}
}
}
int main(int argc, char **argv){
parseArgs(argc, argv);
if(MAX_PACKS < 1 || NTHREADS < 1){
printf("Error en el ingreso de parametros\\n");
print_usage();
exit(1);
}
if(mostrarInfo) print_config();
if(mostrarInfo) printf("El pid es %d\\n", getpid());
pthread_t pids[NTHREADS];
pthread_mutex_init(&lock, 0);
int dev_fd;
dev_fd = open("/dev/null", 0);
if(dev_fd < 0){
fprintf(stderr, "Error al abrir el dispositivo");
exit(1);
}
int i;
for(i=0; i < NTHREADS; i++)
pthread_create(&pids[i], 0, llamadaHilo, dev_fd);
for(i=0; i < NTHREADS; i++)
pthread_join(pids[i], 0);
gettimeofday(&dateFin, 0);
segundos=(dateFin.tv_sec*1.0+dateFin.tv_usec/1000000.)-(dateInicio.tv_sec*1.0+dateInicio.tv_usec/1000000.);
if(mostrarInfo){
printf("Tiempo Total = %g\\n", segundos);
printf("QPS = %g\\n", MAX_PACKS*1.0/segundos);
}else{
printf("%g, \\n", segundos);
}
exit(0);
}
| 1
|
#include <pthread.h>
int w, h;
v2df zero = { 0.0, 0.0 };
v2df four = { 4.0, 4.0 };
v2df nzero;
double inverse_w;
double inverse_h;
char *whole_data;
int y_pick;
pthread_mutex_t y_mutex = PTHREAD_MUTEX_INITIALIZER;
static void * worker(void *_args) {
char *data;
double x, y;
int bit_num;
char byte_acc = 0;
for (;;) {
pthread_mutex_lock(&y_mutex);
y = y_pick;
y_pick++;
pthread_mutex_unlock(&y_mutex);
if (y >= h)
return 0;
data = &whole_data[(w >> 3) * (int)y];
for(bit_num=0,x=0;x<w;x+=2)
{
v2df Crv = { (x+1.0)*inverse_w-1.5, (x)*inverse_w-1.5 };
v2df Civ = { y*inverse_h-1.0, y*inverse_h-1.0 };
v2df Zrv = { 0.0, 0.0 };
v2df Ziv = { 0.0, 0.0 };
v2df Trv = { 0.0, 0.0 };
v2df Tiv = { 0.0, 0.0 };
int i = 0;
int mask;
do {
Ziv = (Zrv*Ziv) + (Zrv*Ziv) + Civ;
Zrv = Trv - Tiv + Crv;
Trv = Zrv * Zrv;
Tiv = Ziv * Ziv;
v2df delta = (v2df)__builtin_ia32_cmplepd( (Trv + Tiv), four );
mask = __builtin_ia32_movmskpd(delta);
} while (++i < 50 && (mask));
byte_acc <<= 2;
byte_acc |= mask;
bit_num+=2;
if(!(bit_num&7)) {
data[(bit_num>>3) - 1] = byte_acc;
byte_acc = 0;
}
}
if(bit_num&7) {
byte_acc <<= (8-w%8);
bit_num += 8;
data[bit_num>>3] = byte_acc;
byte_acc = 0;
}
}
}
int main (int argc, char **argv)
{
pthread_t ids[8];
int i;
nzero = -zero;
w = h = atoi(argv[1]);
inverse_w = 2.0 / w;
inverse_h = 2.0 / h;
y_pick = 0;
whole_data = malloc(w * (w >> 3));
for (i = 0; i < 8; i++)
pthread_create(&ids[i], 0, worker, 0);
for (i = 0; i < 8; i++)
pthread_join(ids[i], 0);
pthread_mutex_destroy(&y_mutex);
printf("P4\\n%d %d\\n",w,h);
fwrite(whole_data, h, w >> 3, stdout);
free(whole_data);
return 0;
}
| 0
|
#include <pthread.h>
void funregister(FILE* fp)
{
if ( !(fp->flags & _FILE_REGISTERED) )
return;
pthread_mutex_lock(&__first_file_lock);
if ( !fp->prev )
__first_file = fp->next;
if ( fp->prev )
fp->prev->next = fp->next;
if ( fp->next )
fp->next->prev = fp->prev;
fp->flags &= ~_FILE_REGISTERED;
pthread_mutex_unlock(&__first_file_lock);
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
void taskA(void *threadid)
{
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&mutex1);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("task A in loopi %d \\n",i );
sleep(1);
pthread_mutex_unlock(&mutex2);
sleep(1);
pthread_mutex_unlock(&mutex1);
sleep(1);
}
printf("task A! thread exit!\\n");
pthread_exit(0);
}
void taskB(void *threadid)
{
int i;
for(i = 0; i < 5; i++) {
pthread_mutex_lock(&mutex2);
sleep(1);
pthread_mutex_lock(&mutex1);
printf("task B in loopi %d \\n",i );
sleep(1);
pthread_mutex_unlock(&mutex1);
sleep(1);
pthread_mutex_unlock(&mutex2);
sleep(1);
}
printf("task B! thread exit!\\n");
pthread_exit(0);
}
int main(int argc, char *argv[])
{
pthread_t a_thread = (pthread_t) 0;
pthread_t b_thread = (pthread_t) 0;
int rc, rc1;
rc = pthread_create(&a_thread,
0,
(void *(*)(void *)) taskA,
(void *) 0);
rc1 = pthread_create(&b_thread,
0,
(void *(*)(void *)) taskB,
(void *) 0);
if(rc == 0)
pthread_join(a_thread, 0);
if(rc1 == 0)
pthread_join(b_thread, 0);
exit(-1);
}
| 0
|
#include <pthread.h>
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t l = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t n = PTHREAD_MUTEX_INITIALIZER;
{
uint64_t number;
int k;
struct node *next;
uint64_t factors[64];
} node_t;
struct arg_struct
{
FILE *arg1;
node_t *arg2;
};
void push(node_t *new_node, node_t **root, uint64_t number, int k, uint64_t factors[])
{
new_node->number = number;
new_node->k = k;
int i;
for (i=0; i<k; i++)
{
new_node->factors[i]=factors[i];
}
new_node->next = *root;
*root = new_node;
}
node_t *check_in_list(uint64_t num, node_t *root)
{
node_t *current = root;
while (current!=0)
{
if (current->number==num)
{
return current;
}
current = current->next;
}
return current;
}
int get_prime_factors(uint64_t num, uint64_t *dest)
{
int count=0;
if (num==1)
{
dest[count]=1;
count++;
}
while (num%2==0)
{
dest[count]=2;
count++;
num=num/2;
}
uint64_t sqroot = 1;
while (sqroot*sqroot<=num)
{
sqroot+=1;
}
uint64_t i=3;
for (; i<=sqroot; i=i+2)
{
while (num%i==0)
{
dest[count]=i;
count++;
num/=i;
}
}
if (num>2)
{
dest[count]=num;
count++;
}
return count;
}
void print_prime_factors(uint64_t num, uint64_t *dest, int k)
{
int j;
printf("%ju: ", num);
for (j=0; j<k; j++)
{
printf("%ju ", dest[j]);
}
printf("\\n");
}
void *read_from_file(void *arguments)
{
struct arg_struct *args = arguments;
FILE *nums = (FILE*) args -> arg1;
node_t *root = (node_t*) args -> arg2;
node_t **rootadd = &root;
int k;
uint64_t num;
char str[100];
pthread_mutex_lock(&m);
while (fgets (str, sizeof(str), nums)!=0)
{
pthread_mutex_unlock(&m);
num = atoll(str);
node_t *checker = check_in_list(num, root);
if (checker!=0)
{
pthread_mutex_lock(&l);
print_prime_factors(num, checker->factors, checker->k);
pthread_mutex_unlock(&l);
}
else
{
uint64_t factors[64];
node_t *new_node;
new_node = malloc(sizeof(node_t));
k = get_prime_factors(num, factors);
pthread_mutex_lock(&n);
push(new_node, rootadd, num, k, factors);
pthread_mutex_unlock(&n);
pthread_mutex_lock(&l);
print_prime_factors(num, new_node->factors, k);
pthread_mutex_unlock(&l);
}
pthread_mutex_lock(&m);
}
pthread_mutex_unlock(&m);
return 0;
}
int main(void)
{
FILE *numbers;
void *status;
node_t *root;
root = malloc(sizeof(node_t));
root->factors[64] = (uint64_t)malloc(sizeof(uint64_t)*64);
numbers = fopen ("small.txt", "r");
struct arg_struct args;
args.arg1 = numbers;
args.arg2 = root;
pthread_t thread1, thread2;
pthread_create(&thread1, 0, read_from_file, (void*) &args);
pthread_create(&thread2, 0, read_from_file, (void*) &args);
pthread_join(thread1, &status);
pthread_join(thread2, &status);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t philosopher[5];
pthread_mutex_t spoon[5];
void *dine(int n)
{ printf("\\nPhilosopher %d is thinking ",n);
pthread_mutex_lock(&spoon[n]);
pthread_mutex_lock(&spoon[(n+1)%5]);
printf("\\nPhilosopher %d is eating ",n);
sleep(1);
pthread_mutex_unlock(&spoon[n]);
pthread_mutex_unlock(&spoon[(n+1)%5]);
printf("\\nPhilosopher %d Finished eating",n);
}
void main()
{ int i,err;
void *msg;
for(i=1;i<=5;i++)
{ err=pthread_mutex_init(&spoon[i],0);
if(err!=0)
{ printf("\\n Mutex initialization for spoon failed");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_create(&philosopher[i],0,(void *)dine,(int *)i);
if(err!=0)
{ printf("\\n Thread creation failed \\n");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_join(philosopher[i],&msg);
if(err!=0)
{ printf("\\n Thread join failed \\n");
exit(1);
}
}
for(i=1;i<=5;i++)
{ err=pthread_mutex_destroy(&spoon[i]);
if(err!=0)
{ printf("\\n Mutex spoon Destroyed \\n");
exit(1);
}
}
}
| 0
|
#include <pthread.h>
int PLPA_NAME(initialized) = 0;
static int refcount = 0;
static pthread_mutex_t mutex;
int PLPA_NAME(init)(void)
{
int ret;
if (PLPA_NAME(initialized)) {
pthread_mutex_lock(&mutex);
++refcount;
pthread_mutex_unlock(&mutex);
return 0;
}
if (0 != (ret = pthread_mutex_init(&mutex, 0)) ||
0 != (ret = PLPA_NAME(api_probe_init)()) ||
0 != (ret = PLPA_NAME(set_cache_behavior)(PLPA_NAME_CAPS(CACHE_USE)))) {
return ret;
}
PLPA_NAME(initialized) = 1;
refcount = 1;
return 0;
}
int PLPA_NAME(finalize)(void)
{
int val;
if (!PLPA_NAME(initialized)) {
return ENOENT;
}
pthread_mutex_lock(&mutex);
val = --refcount;
pthread_mutex_unlock(&mutex);
if (0 != val) {
return 0;
}
PLPA_NAME(set_cache_behavior)(PLPA_NAME_CAPS(CACHE_IGNORE));
pthread_mutex_destroy(&mutex);
PLPA_NAME(initialized) = 0;
return 0;
}
| 1
|
#include <pthread.h>
static int ready = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
static void *
mythr(void *ignore)
{
pthread_mutex_lock(&mutex);
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
sigset_t ss;
sigfillset(&ss);
while (1) {
struct timespec ts = {10000, 0};
pselect(0, 0, 0, 0, &ts, &ss);
}
return 0;
}
int
main()
{
pthread_t thr;
int ret = pthread_create(&thr, 0, mythr, 0);
if (ret != 0) {
fprintf(stderr, "pthread_create failed\\n");
return 1;
}
pthread_mutex_lock(&mutex);
while (ready == 0) {
pthread_cond_wait(&cond, &mutex);
}
pthread_mutex_unlock(&mutex);
alarm(1);
while (1)
sleep(1);
return 0;
}
| 0
|
#include <pthread.h>
void *thread_function(void *arg);
pthread_mutex_t work_mutex;
char work_area[1024];
int time_to_exit = 0;
int main(int argc, const char *argv[])
{
int res;
pthread_t a_thread;
void *thread_result;
res = pthread_mutex_init(&work_mutex, 0);
if(res != 0) {
perror("Mutex initialization failed");
exit(1);
}
res = pthread_create(&a_thread, 0, thread_function, 0);
if(res != 0){
perror("Thread creation failed");
exit(1);
}
pthread_mutex_lock(&work_mutex);
printf("Input some text. Enter 'end' to finish\\n");
while(!time_to_exit){
fgets(work_area, 1024, stdin);
pthread_mutex_unlock(&work_mutex);
while(1){
pthread_mutex_lock(&work_mutex);
if(work_area[0] != '\\0'){
pthread_mutex_unlock(&work_mutex);
sleep(1);
}
else{
break;
}
}
}
pthread_mutex_unlock(&work_mutex);
printf("\\nWaiting for thread to finish...\\n");
res = pthread_join(a_thread, &thread_result);
if(res != 0){
perror("Thread join failed");
exit(1);
}
printf("Thread joined\\n");
pthread_mutex_destroy(&work_mutex);
exit(0);
return 0;
}
void *thread_function(void *arg){
sleep(1);
pthread_mutex_lock(&work_mutex);
while(strncmp("end", work_area, 3) != 0){
printf("You input %d chars\\n", strlen(work_area) - 1);
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
while(work_area[0] == '\\0'){
pthread_mutex_unlock(&work_mutex);
sleep(1);
pthread_mutex_lock(&work_mutex);
}
}
time_to_exit = 1;
work_area[0] = '\\0';
pthread_mutex_unlock(&work_mutex);
pthread_exit(0);
}
| 1
|
#include <pthread.h>
void * Producer();
void * Consumer();
int BufferIndex = 0;
char *BUFFER;
pthread_cond_t Buffer_Not_Full = PTHREAD_COND_INITIALIZER;
pthread_cond_t Buffer_Not_Empty = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mVar = PTHREAD_MUTEX_INITIALIZER;
int main(){
pthread_t ptid, ctid;
BUFFER = (char *) malloc (sizeof (char)* 10);
pthread_create(&ptid, 0, Producer, 0);
pthread_create(&ctid, 0, Consumer, 0);
pthread_join(ptid, 0);
pthread_join(ctid, 0);
return 0;
}
void * Producer(){
while(1){
pthread_mutex_lock(&mVar);
if(BufferIndex == 10){
pthread_cond_wait(&Buffer_Not_Full, &mVar);
}
BUFFER[BufferIndex++]='@';
printf("Produce : %d\\n", BufferIndex);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Empty);
}
}
void * Consumer(){
while(1){
pthread_mutex_lock(&mVar);
if(BufferIndex == -1){
pthread_cond_wait(&Buffer_Not_Empty, &mVar);
}
printf("Consume : %d\\n", BufferIndex--);
pthread_mutex_unlock(&mVar);
pthread_cond_signal(&Buffer_Not_Full);
}
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex;
struct pthread_block
{
int fdin;
int fdout;
int start;
int end;
};
int get_size(const char *filename)
{
struct stat file_stat;
stat(filename,&file_stat);
return file_stat.st_size;
}
void *pthread_func(void *args)
{
struct pthread_block *block = (struct pthread_block *)args;
char buf[1024];
int count = block->start;
int ret;
printf("inthread = %ld,start = %d,end = %d\\n",pthread_self(),block->start,block->end);
pthread_mutex_lock(&mutex);
lseek(block->fdin,block->start,0);
lseek(block->fdout,block->start,0);
while(count < block->end)
{
ret = read(block->fdin,buf,sizeof(buf));
count += ret;
write(block->fdout,buf,ret);
}
pthread_mutex_unlock(&mutex);
printf("---pthread exit %ld\\n",pthread_self());
pthread_exit(0);
}
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("argument error");
exit(1);
}
pthread_mutex_init(&mutex,0);
char *filename = argv[1];
int fd = open(filename,O_RDONLY);
int cpfd = open("copy.mp4",O_CREAT | O_WRONLY | O_TRUNC,0777);
int size = get_size(filename);
int pthread_count = 3;
int down_size = size / pthread_count;
struct pthread_block *blocks = (struct pthread_block *)malloc(sizeof(struct pthread_block)*pthread_count);
printf("filesize = %d,pthread_count = %d\\n",size,pthread_count);
int i;
for(i = 0; i < pthread_count; i++)
{
blocks[i].fdin = fd;
blocks[i].fdout = cpfd;
blocks[i].start = i*down_size;
blocks[i].end = blocks[i].start + down_size;
}
blocks[i-1].end = size;
for(i = 0; i < pthread_count; i++)
{
printf("---%d---%d\\n",blocks[i].start,blocks[i].end);
}
pthread_t tid[3];
for(i = 0; i < pthread_count; i++)
{
pthread_create(&tid[i],0,pthread_func,&blocks[i]);
}
for(i = 0; i < pthread_count; i++)
{
pthread_join(tid[i],0);
}
close(fd);
close(cpfd);
free(blocks);
return 0;
}
| 1
|
#include <pthread.h>
pthread_t thread[3];
pthread_mutex_t mut1,mut2;
pthread_cond_t cond_sum_ready;
pthread_cond_t cond_mut1_ready;
int number=1, serial=1;
char buf1[100] = {0};
char buf2[100] = {0};
char buf3[100] = {0};
char name[30] = {0};
int fd1=0,fd2=0,fd3=0,fd4=0;
sem_t sem;
void *thread1()
{
int k1 = 0;
while(1)
{
if(0!=pthread_mutex_trylock(&mut1))
{
pthread_cond_wait(&cond_mut1_ready, &mut1);
}
if(number >10) {
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
break;
}
sprintf(name,"%d.dat",number);
k1 = number;
number++;
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
sem_wait(&sem);
fd1 = open (name,O_RDONLY);
if(fd1 == -1) {
printf(" Can't open \\n");
return 0;
}
read(fd1,buf1,100);
close(fd1);
sem_post(&sem);
printf("%s\\n",buf1);
loop: pthread_mutex_lock(&mut2);
printf(" thread1:lock(&mut2) \\n");
while(k1 != serial)
{
printf(" thread1:wait(&cond_sum_ready, &mut2) \\n");
pthread_cond_wait(&cond_sum_ready, &mut2);
}
printf("thread1:ready to open result.dat\\n");
fd4 = open ("result.dat",O_RDWR | O_CREAT |O_APPEND ,0600);
if(fd4 == -1) {
printf(" Can't creat \\n");
return 0;
}
printf("thread1:ready to write \\n");
write( fd4,buf1,sizeof(buf1));
close(fd4);
serial++;
pthread_mutex_unlock(&mut2);
pthread_cond_broadcast(&cond_sum_ready);
sleep(2);
}
printf("thread1 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread2()
{
int k2 = 0;
while(1)
{
if(0!=pthread_mutex_trylock(&mut1))
{
pthread_cond_wait(&cond_mut1_ready, &mut1);
}
if(number >10) {
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
break;
}
sprintf(name,"%d.dat",number);
k2 = number;
number++;
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
sem_wait(&sem);
fd2 = open (name,O_RDONLY);
if(fd2 == -1) {
printf(" Can't open \\n");
return 0;
}
read(fd2,buf2,100);
close(fd2);
sem_post(&sem);
printf("%s\\n",buf2);
loop1: pthread_mutex_lock(&mut2);
printf(" thread2:lock(&mut2) \\n");
while(k2 != serial)
{
printf(" thread2:wait(&cond_sum_ready, &mut2) \\n");
pthread_cond_wait(&cond_sum_ready, &mut2);
}
printf("thread2:ready to open result.dat\\n");
fd4 = open ("result.dat",O_RDWR | O_CREAT |O_APPEND ,0600);
if(fd4 == -1) {
printf(" Can't creat \\n");
return 0;
}
printf("thread2:ready to write \\n");
write( fd4,buf2,sizeof(buf2));
close(fd4);
serial++;
pthread_mutex_unlock(&mut2);
pthread_cond_broadcast(&cond_sum_ready);
sleep(2);
}
printf("thread2 :主函数在等待吗?\\n");
pthread_exit(0);
}
void *thread3()
{
int k3 = 0;
while(1)
{
if(0!=pthread_mutex_trylock(&mut1))
{
pthread_cond_wait(&cond_mut1_ready, &mut1);
}
if(number >10) {
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
break;
}
sprintf(name,"%d.dat",number);
k3 = number;
number++;
pthread_mutex_unlock(&mut1);
pthread_cond_broadcast(&cond_mut1_ready);
sem_wait(&sem);
fd3 = open (name,O_RDONLY);
if(fd3 == -1) {
printf(" Can't open \\n");
return 0;
}
read(fd3,buf3,100);
close(fd3);
sem_post(&sem);
printf("%s\\n",buf3);
loop2: pthread_mutex_lock(&mut2);
printf(" thread3:lock(&mut2) \\n");
while(k3 != serial)
{
printf(" thread3:wait(&cond_sum_ready, &mut2) \\n");
pthread_cond_wait(&cond_sum_ready, &mut2);
}
printf("thread3:ready to open result.dat\\n");
fd4 = open ("result.dat",O_RDWR | O_CREAT |O_APPEND ,0600);
if(fd4 == -1) {
printf(" Can't creat \\n");
return 0;
}
printf("thread3:ready to write \\n");
write( fd4,buf3,sizeof(buf3));
close(fd4);
serial++;
pthread_mutex_unlock(&mut2);
pthread_cond_broadcast(&cond_sum_ready);
sleep(2);
}
printf("thread3 :主函数在等待吗?\\n");
pthread_exit(0);
}
void thread_create(void)
{
int temp;
memset(&thread, 0, sizeof(thread));
if((temp = pthread_create(&thread[0], 0, thread1, 0)) != 0)
printf("线程1创建失败!\\n");
else
printf("线程1被创建\\n");
if((temp = pthread_create(&thread[1], 0, thread2, 0)) != 0)
printf("线程2创建失败");
else
printf("线程2被创建\\n");
if((temp = pthread_create(&thread[2], 0, thread3, 0)) != 0)
printf("线程3创建失败");
else
printf("线程3被创建\\n");
}
void thread_wait(void)
{
if(thread[0] !=0)
{
pthread_join(thread[0],0);
printf("线程1已经结束\\n");
}
if(thread[1] !=0)
{
pthread_join(thread[1],0);
printf("线程2已经结束\\n");
}
if(thread[2] !=0)
{
pthread_join(thread[2],0);
printf("线程3已经结束\\n");
}
}
int main()
{
pthread_cond_t cond_sum_ready=PTHREAD_COND_INITIALIZER;
pthread_cond_t cond_mut1_ready=PTHREAD_COND_INITIALIZER;
sem_init(&sem,0,2);
pthread_mutex_init(&mut1,0);
pthread_mutex_init(&mut2,0);
printf("主函数,正在创建线程\\n");
thread_create();
printf("主函数,正在等待线程完成任务\\n");
thread_wait();
return 0;
}
| 0
|
#include <pthread.h>
int *globalvector;
long range;
int nthreads;
int cur_number = 0;
pthread_mutex_t plock;
struct return_values
{
int element;
int nprimes;
int *primes;
};
void *runthread(void *param);
int main(int argc, char *argv[])
{
int total_primes =0, j, number_printed=0;
time_t timestart, timeend;
timestart = time(0);
if(argc != 3)
{
printf("Usage is <pprimes num nthreads>\\n");
printf("where num is range of primes you would like to calculate \\n ");
printf("nthreads is number of threads you would like to run\\n");
}
range = atoi(argv[1]);
if(range <= 2)
{
printf("num should be greater than 2\\n");
exit(0);
}
pthread_t Thid[range];
pthread_mutex_init(&plock, 0);
globalvector = malloc(range *sizeof(globalvector[0]));
if(argv[2]==0)
nthreads = 2;
else
nthreads = atoi(argv[2]);
int x;
int t = 2;;
for(x = 0; x< range; x++)
{
globalvector[x]= t++;
}
struct return_values * thread_values [nthreads];
long i;
for(i=0;i<nthreads;i++)
{
struct return_values * rv = malloc(sizeof(struct return_values));
rv->primes = (int *)malloc(sizeof(int*)*range);
rv->element=i;
rv->nprimes=0;
thread_values[i] = rv;
pthread_create(&Thid[i], 0, runthread, (void *)thread_values[i]);
}
for(i=0;i<nthreads;i++) {
pthread_join(Thid[i], 0);
}
printf("Primes:\\n");
for(i=0;i<nthreads;i++)
{
total_primes+=thread_values[i]->nprimes;
for(j=0;j<thread_values[i]->nprimes;j++)
{
printf("%8d \\t", thread_values[i]->primes[j]);
number_printed++;
if(number_printed%10==0) printf("\\n");
}
}
printf("\\n\\nTotal Primes: %d\\n", total_primes);
timeend = time(0);
printf("Program used %f seconds.\\n", difftime(timeend, timestart));
return 0;
}
void *runthread(void *param) {
int i, flag;
struct return_values * params = (struct return_values *)param;
int local_int;
pthread_mutex_lock(&plock);
if(cur_number < range)
{
local_int = globalvector[cur_number++];
pthread_mutex_unlock(&plock);
}
else
{
pthread_mutex_unlock(&plock);
pthread_exit(0);
}
while(local_int < range)
{
flag = 0;
for(i=2;i<local_int;i++)
{
if( (local_int%i==0) && (i != local_int) ) flag=1;
}
if(flag==0)
{
params->primes[params->nprimes]=local_int;
params->nprimes++;
}
pthread_mutex_lock(&plock);
if(cur_number < range)
{
local_int = globalvector[cur_number++];
pthread_mutex_unlock(&plock);
}
else
{
pthread_mutex_unlock(&plock);
break;
}
}
pthread_exit(0);
}
| 1
|
#include <pthread.h>
FILE * fptr;
extern pthread_mutex_t *m_LOCK;
extern int *s_shm, * c_shm;
struct timespec some_time;
int my_rand(int start, int range){
struct timeval t;
gettimeofday(&t, (struct timezone *)0);
return (int) (start+(float)range*rand_r((unsigned *)&t.tv_usec)/(32767 +1.0));
}
void produce(){
int err, * n;
printf("%u \\t P: attempting to produce \\t %d\\n",(unsigned)pthread_self(),getpid());
fflush(stdout);
if((err=pthread_mutex_trylock(m_LOCK))!=0){
printf("%u \\t P: lock busy(code %d) \\t %d\\n",(unsigned)pthread_self(),err,(int)getpid());
fflush(stdout);
return;
}
n=(int *)malloc(sizeof(int));
(*n)=my_rand(1,MAX);
fptr=fopen(BUFFER,"a");
fwrite(n,sizeof(int),1,fptr);
fclose(fptr);
fflush(stdout);
free(n);
some_time.tv_sec=0;
some_time.tv_nsec=10000;
nanosleep(&some_time,0);
if((err=pthread_mutex_unlock(m_LOCK))!=0){
printf("P: unlock failure %d\\n",err);
fflush(stdout);
exit(102);
}
}
void consume(){
int err, *n;
printf("%u \\t C: attempting to consume \\t %d \\n", (unsigned)pthread_self(),(int)getpid());
fflush(stdout);
if((err=pthread_mutex_trylock(m_LOCK))!=0){
printf("%u\\t C: lock busy(code %d) \\t %d\\n",(unsigned)pthread_self(),err,(int)getpid());
fflush(stdout);
return;
}
fptr=fopen(BUFFER,"r+" );
fseek(fptr,(*c_shm)*sizeof(int),0);
n=(int *)malloc(sizeof(int));
*n=0;
fread(n,sizeof(int),1,fptr);
if((*n)>0){
fflush(stdout);
fseek(fptr, (*c_shm)*sizeof(int),0);
*n=-(*n);
fwrite(n,sizeof(int),1,fptr);
fclose(fptr);
++*c_shm;
}
else{
fflush(stdout);
fclose(fptr);
}
free(n);
some_time.tv_sec=0;
some_time.tv_nsec=10000;
nanosleep(&some_time,0);
if((err=pthread_mutex_unlock(m_LOCK))!=0){
printf("C: unlock failure %d\\n",err);
exit(104);
}
}
void do_work(){
int i;
if(!(*s_shm)){
pthread_mutex_lock(m_LOCK);
if(!(*s_shm)++){
printf("%u \\t :clearing the buffer \\t %d\\n",(unsigned)pthread_self(),(int)getpid());
fptr=fopen(BUFFER, "w");
fclose(fptr);
}
pthread_mutex_unlock(m_LOCK);
}
for(i=0; i<10;i++){
some_time.tv_sec=0;
some_time.tv_nsec=10000;
nanosleep(&some_time, 0);
switch(my_rand(1,2)){
case 1:
produce();
break;
default:
consume();
}
}
}
| 0
|
#include <pthread.h>
char *start=0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int avail = 0;
static void * threadFunc1(void *arg)
{
int ret, i = 0;
char data=64;
sleep(1);
while(data<84) {
pthread_mutex_lock(&mutex);
data++;
memset(start + i ,data,8);
i+=8;
start[i]='\\0';
printf("Produced data successfully \\n");
avail=1;
pthread_mutex_unlock(&mutex);
ret = pthread_cond_signal(&cond);
if (ret != 0)
perror( "pthread_cond_signal");
}
return 0;
}
static void * threadFunc2(void *arg)
{
int ret=0;
while(1) {
pthread_mutex_lock(&mutex);
if(avail==0) {
printf("Wait for data \\n");
ret = pthread_cond_wait(&cond, &mutex);
if (ret != 0)
perror( "pthread_cond_wait");
}
printf("%s\\n",start);
printf("Consumed data successfully\\n");
avail=0;
pthread_mutex_unlock(&mutex);
}
return 0;
}
int
main(int argc, char *argv[])
{
pthread_t t1, t2;
int ret;
start = (char *)malloc(4096);
ret = pthread_create(&t1, 0, threadFunc1, 0);
if (ret != 0)
perror("Pthread Create : ");
ret = pthread_create(&t2, 0, threadFunc2, 0);
if (ret != 0)
perror("Pthread Create: ");
ret = pthread_join(t1, 0);
if (ret != 0)
perror("Pthread Join: ");
ret = pthread_join(t2, 0);
if (ret != 0)
perror("Pthreaf Join : ");
exit(0);
}
| 1
|
#include <pthread.h>
FILE *logFile;
static volatile __u8 logging = 0;
static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static void voltageListener() {
if (logging) {
struct timeval t;
gettimeofday(&t, 0);
double now = t.tv_sec + t.tv_usec / (double) 1000000;
pthread_mutex_lock(&mutex);
fprintf(logFile, "%.3f %.2f %.2f %.1f\\n", now, soc_getInstVoltage(), soc_getInstCurrent(), soc_getSpeed());
pthread_mutex_unlock(&mutex);
}
}
void hiResLogger_init() {
logFile = fopen("hiRes.txt", "a");
soc_registerInstVoltageListener(voltageListener);
}
void hiResLogger_start() {
logging = 1;
}
void hiResLogger_stop() {
logging = 0;
pthread_mutex_lock(&mutex);
fprintf(logFile, "\\n");
fflush(logFile);
pthread_mutex_unlock(&mutex);
}
| 0
|
#include <pthread.h>
int q[5];
int qsiz;
pthread_mutex_t mq;
void queue_init ()
{
pthread_mutex_init (&mq, 0);
qsiz = 0;
}
void queue_insert (int x)
{
int done = 0;
printf ("prod: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz < 5)
{
done = 1;
q[qsiz] = x;
qsiz++;
}
pthread_mutex_unlock (&mq);
}
}
int queue_extract ()
{
int done = 0;
int x = -1, i = 0;
printf ("consumer: trying\\n");
while (done == 0)
{
pthread_mutex_lock (&mq);
if (qsiz > 0)
{
done = 1;
x = q[0];
qsiz--;
for (i = 0; i < qsiz; i++) q[i] = q[i+1];
__VERIFIER_assert (qsiz < 5);
q[qsiz] = 0;
}
pthread_mutex_unlock (&mq);
}
return x;
}
void swap (int *t, int i, int j)
{
int aux;
aux = t[i];
t[i] = t[j];
t[j] = aux;
}
int findmaxidx (int *t, int count)
{
int i, mx;
mx = 0;
for (i = 1; i < count; i++)
{
if (t[i] > t[mx]) mx = i;
}
__VERIFIER_assert (mx >= 0);
__VERIFIER_assert (mx < count);
t[mx] = -t[mx];
return mx;
}
int source[3];
int sorted[3];
void producer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = findmaxidx (source, 3);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
queue_insert (idx);
}
}
void consumer ()
{
int i, idx;
for (i = 0; i < 3; i++)
{
idx = queue_extract ();
sorted[i] = idx;
printf ("m: i %d sorted = %d\\n", i, sorted[i]);
__VERIFIER_assert (idx >= 0);
__VERIFIER_assert (idx < 3);
}
}
void *thread (void * arg)
{
(void) arg;
producer ();
return 0;
}
int main ()
{
pthread_t t;
int i;
__libc_init_poet ();
for (i = 0; i < 3; i++)
{
source[i] = __VERIFIER_nondet_int(0,20);
printf ("m: init i %d source = %d\\n", i, source[i]);
__VERIFIER_assert (source[i] >= 0);
}
queue_init ();
pthread_create (&t, 0, thread, 0);
consumer ();
pthread_join (t, 0);
return 0;
}
| 1
|
#include <pthread.h>
int isEndOfFile;
int isPass;
int threadWorking;
int isTimeTest;
char* passToHack;
char* salt;
int countProcess;
void* source;
long progress;
int iteration;
long fileSize;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void threadFunc(int* args);
int isPassCorrect(char* pass);
void findPass(int sizeThread);
int main (int argc, char **argv) {
if(argc < 3) {
printf(" Podano za mało argumentów.\\n ./test SKROT_HASLA SLOWNIK [ILOSC_WATKOW]\\n");
exit(1);
}
char buff[100];
int i=3;
while(1) {
if(argv[1][i] == '$' ) {
break;
} else {
buff[i-3]=argv[1][i];
}
i++;
}
salt=calloc(strlen(buff),sizeof(buff));
strcpy(salt,buff);
passToHack=argv[1];
countProcess = sysconf(_SC_NPROCESSORS_CONF);
struct stat st;
stat(argv[2], &st);
fileSize = st.st_size;
int file = open(argv[2],O_RDONLY);
if( (source = mmap(0,st.st_size, PROT_READ, MAP_SHARED, file, 0)) == (void*) -1 ) {
fprintf(stderr,"Nie udalo sie zmapowac pliku.");
pthread_mutex_destroy(&mutex);
munmap(source,st.st_size);
close (file);
free(salt);
exit(0);
}
iteration=0;
if(argc<4) {
isTimeTest=1;
struct timespec start, stop;
double accum;
for (int i = 1; i <= countProcess; i++) {
if( clock_gettime( CLOCK_REALTIME, &start) == -1 ) {
fprintf(stderr, "clock gettime" );
exit( 1 );
}
findPass(i);
if( clock_gettime( CLOCK_REALTIME, &stop) == -1 ) {
fprintf(stderr, "clock gettime" );
exit( 1 );
}
printf( "\\nCzas wykonania dla %d watkow: %lld s", i,( stop.tv_sec - start.tv_sec ));
}
} else {
isTimeTest=0;
int a = atoi(argv[3]);
findPass(a);
if(isPass==0) {
printf("\\nNie odnaleziono hasla\\n");
}
}
pthread_mutex_destroy(&mutex);
munmap(source,st.st_size);
close (file);
free(salt);
return 0;
}
void findPass(int sizeT) {
int sizeThread = sizeT;
if(sizeThread > countProcess) {
sizeThread=countProcess;
}
isEndOfFile=0;
isPass=0;
progress = 0;
iteration=0;
threadWorking=sizeThread;
int s =fileSize/sizeT;
printf("\\n");
for (int i = 0; i < sizeThread; i++) {
pthread_t thread_id;
int a[2] = {i,s};
pthread_create ( &thread_id, 0, threadFunc, &a);
}
while(threadWorking);
}
void threadFunc(int* args) {
int index=args[0];
int offset=args[1];
int s =index * offset;
char pass[40];
char buff[20];
while(isEndOfFile==0) {
sscanf(source+s,"%s",pass);
int len = strlen(pass);
if( s > (index+1) * offset ) {
break;
} else if(len<=0) {
isEndOfFile=1;
} else {
s+=len;
}
pthread_mutex_lock( &mutex);
progress += len;
iteration++;
pthread_mutex_unlock( &mutex);
if(isTimeTest==1 && iteration>1000) {
isPass=1;
isEndOfFile=1;
}
if(isEndOfFile==1) {
break;
}
if(isTimeTest==1) {
sprintf(buff,"\\r%.2f%% ",( ((double)iteration/1000)*100 ));
} else {
sprintf(buff,"\\r%.3f%% ",((double)progress/(double)fileSize)*100 );
}
printf("%s",buff);
if(isPassCorrect(pass)==1) {
printf("\\nHaslo to: %s\\n",pass);
isPass=1;
isEndOfFile=1;
}
}
pthread_mutex_lock( &mutex);
threadWorking--;
pthread_mutex_unlock( &mutex);
return;
}
int isPassCorrect(char* pass) {
struct crypt_data data;
data.initialized = 0;
char p[100]="$6$";
sprintf(p,"%s%s",p,salt);
char *res;
res = crypt_r(pass, p, &data);
if(strcmp(passToHack, res) == 0) {
return 1;
}
return 0;
}
| 0
|
#include <pthread.h>
void* arg;
void* (*process)(void* arg);
struct Tasks* next;
}PthreadTasks;
pthread_mutex_t lock;
pthread_cond_t task_sig;
PthreadTasks* head_task;
pthread_t* tid_array;
int status;
int max_thread_num;
int cur_queue_num;
}Thread_pool;
static Thread_pool* pool = 0;
int pool_addtask(void* (*process)(void*),void* arg);
void* pthread_routine(void* arg);
void init_pool(int max_num)
{
int i;
pool = (Thread_pool*)malloc(sizeof(Thread_pool));
pthread_mutex_init( &(pool->lock),0);
pthread_cond_init(&(pool->task_sig),0);
pool->status = 1;
pool->max_thread_num = max_num;
pool->head_task = 0;
pool->tid_array = (pthread_t*)malloc(max_num* sizeof(pthread_t));
for(i=0;i<max_num;i++)
{
pthread_create( &( pool->tid_array[i]),0,pthread_routine,(void*)i );
printf("create pthread:%d success ! \\n",i);
}
printf("create pthread routine success ! \\n");
}
int pool_addtask(void* (*process)(void*),void* arg)
{
if(pool->cur_queue_num == pool->max_thread_num )
{
printf("the pthread pool is full !\\n");
return -1;
}
PthreadTasks* task = malloc(sizeof(PthreadTasks));
task->process = process;
task->arg = (void*)arg;
task->next = 0;
pthread_mutex_lock( &(pool->lock) );
PthreadTasks* task_pointer = malloc(sizeof(PthreadTasks));
task_pointer = pool->head_task;
if(task_pointer != 0){
while(task_pointer->next != 0)
{
task_pointer = task_pointer->next;
}
task_pointer->next = task;
}
else{
pool->head_task = task;
}
assert(pool->head_task != 0);
pool->cur_queue_num++;
pthread_mutex_unlock(&(pool->lock));
pthread_cond_signal(&(pool->task_sig));
return 0;
}
void* pthread_routine(void* arg)
{
printf("starting running pthread is: %d \\n",arg);
while(1)
{
if( !pool->status )
{
printf("pthread will be exit 0x%x ! \\n",pthread_self());
pthread_exit(0);
}
pthread_mutex_lock(&(pool->lock));
while( (pool->cur_queue_num == 0) && (pool->status) )
{
printf("pthread:0x%x is waiting ! \\n",pthread_self());
pthread_cond_wait(&(pool->task_sig),&(pool->lock));
}
printf("pthread:0x%x is starting to work ! \\n",pthread_self());
assert(pool->cur_queue_num != 0);
assert(pool->head_task != 0 );
pool->cur_queue_num--;
PthreadTasks* task = pool->head_task;
pool->head_task = task->next;
pthread_mutex_unlock(&(pool->lock));
(*(task->process))(task->arg);
free(task);
task = 0;
}
pthread_exit(0);
}
void destroy_pool(Thread_pool* pool)
{
if(pool->status)
{
printf("the pool is still active ! \\n");
exit(-1);
}
pthread_cond_broadcast( &(pool->task_sig) );
int i;
for(i=0;i<pool->max_thread_num;i++)
{
pthread_join( pool->tid_array[i],0);
}
free(pool->tid_array);
PthreadTasks* task_pointer =0;
while(pool->head_task != 0)
{
task_pointer = pool->head_task;
pool->head_task = pool->head_task->next;
free(task_pointer);
}
pthread_mutex_destroy( &(pool->lock) );
pthread_cond_destroy( &(pool->task_sig));
free(pool);
pool = 0;
}
void* my_task(void* arg)
{
printf("thread is 0x%x,working on the task %d \\n",pthread_self(),*(int*)arg);
sleep(1);
return 0;
}
int main(int argc,char* argv[])
{
int i;
init_pool(3);
for(i=0;i<10;i++)
{
pool_addtask(my_task,&i);
}
sleep(15);
destroy_pool(pool);
return 0;
}
| 1
|
#include <pthread.h>
static pthread_mutex_t g_logger;
static int g_loglevel;
void hs_init_log(int loglevel)
{
g_loglevel = loglevel;
if (pthread_mutex_init(&g_logger, 0)) {
perror("loger pthread_mutex_init failed");
exit(1);
}
}
int hs_get_log_level()
{
return g_loglevel;
}
void hs_free_log()
{
pthread_mutex_destroy(&g_logger);
}
void
hs_log(void *context, const char *plugin, int severity, const char *fmt, ...)
{
(void)context;
if (severity > g_loglevel) return;
struct timespec ts;
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
ts.tv_sec = time(0);
fprintf(stderr, "%lld [error] hs_log clock_gettime failed\\n",
ts.tv_sec * 1000000000LL);
ts.tv_nsec = 0;
}
const char *level;
switch (severity) {
case 7:
level = "debug";
break;
case 6:
level = "info";
break;
case 5:
level = "notice";
break;
case 4:
level = "warning";
break;
case 3:
level = "error";
break;
case 2:
level = "crit";
break;
case 1:
level = "alert";
break;
case 0:
level = "panic";
break;
default:
level = "debug";
break;
}
va_list args;
__builtin_va_start((args));
pthread_mutex_lock(&g_logger);
fprintf(stderr, "%lld [%s] %s ", ts.tv_sec * 1000000000LL + ts.tv_nsec, level,
plugin ? plugin : "unnamed");
vfprintf(stderr, fmt, args);
fwrite("\\n", 1, 1, stderr);
pthread_mutex_unlock(&g_logger);
;
}
| 0
|
#include <pthread.h>
int readers;
int writer;
pthread_cond_t readers_proceed;
pthread_cond_t writer_proceed;
int pending_writers;
pthread_mutex_t read_write_lock;
} mylib_rwlock_t;
char** theArray;
pthread_mutex_t mutex;
mylib_rwlock_t rwlock;
void* ServerEcho(void *args);
void mylib_rwlock_init (mylib_rwlock_t *l) {
l -> readers = l -> writer = l -> pending_writers = 0;
pthread_mutex_init(&(l -> read_write_lock), 0);
pthread_cond_init(&(l -> readers_proceed), 0);
pthread_cond_init(&(l -> writer_proceed), 0);
}
void mylib_rwlock_rlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> pending_writers > 0) || (l -> writer > 0))
pthread_cond_wait(&(l -> readers_proceed),
&(l -> read_write_lock));
l -> readers ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_wlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
while ((l -> writer > 0) || (l -> readers > 0)) {
l -> pending_writers ++;
pthread_cond_wait(&(l -> writer_proceed),
&(l -> read_write_lock));
l -> pending_writers --;
}
l -> writer ++;
pthread_mutex_unlock(&(l -> read_write_lock));
}
void mylib_rwlock_unlock(mylib_rwlock_t *l) {
pthread_mutex_lock(&(l -> read_write_lock));
if (l -> writer > 0)
l -> writer = 0;
else if (l -> readers > 0)
l -> readers --;
pthread_mutex_unlock(&(l -> read_write_lock));
if ((l -> readers == 0) && (l -> pending_writers > 0))
pthread_cond_signal(&(l -> writer_proceed));
else if (l -> readers > 0)
pthread_cond_broadcast(&(l -> readers_proceed));
}
int main(){
mylib_rwlock_init(&rwlock);
theArray=malloc(100*sizeof(char));
for (int i=0; i<100;i++){
theArray[i]=malloc(100*sizeof(char));
sprintf(theArray[i], "%s%d%s", "String ", i, ": the initial value" );
}
struct sockaddr_in sock_var;
int serverFileDescriptor=socket(AF_INET,SOCK_STREAM,0);
int clientFileDescriptor;
pthread_t* thread_handles;
thread_handles = malloc(1000*sizeof(pthread_t));
sock_var.sin_addr.s_addr=inet_addr("127.0.0.1");
sock_var.sin_port=3000;
sock_var.sin_family=AF_INET;
if(bind(serverFileDescriptor,(struct sockaddr*)&sock_var,sizeof(sock_var))>=0)
{
printf("socket has been created \\n");
listen(serverFileDescriptor,2000);
while(1){
for(int i=0;i<1000;i++){
clientFileDescriptor=accept(serverFileDescriptor,0,0);
printf("Connect to client %d \\n",clientFileDescriptor);
pthread_create(&thread_handles[i],0,ServerEcho,(void*)clientFileDescriptor);
}
for(int i = 0;i<1000;i++){
pthread_join(thread_handles[i],0);
}
printf("All threads have joined. Checking Array \\n");
for(int i=0;i<1000;i++){
printf("%s\\n",theArray[i]);
}
}
}
else{
printf("socket creation failed \\n");
return 1;
}
return 0;
}
void* ServerEcho(void* args){
long clientFileDescriptor = (long) args;
char buff[100];
read(clientFileDescriptor,buff,100);
int pos;
char operation;
sscanf(buff, "%d %c", &pos,&operation);
printf("a Server thread recieved position %d and operation %c from %ld \\n",pos,operation,clientFileDescriptor);
if(operation=='r'){
char msg[100];
mylib_rwlock_rlock(&rwlock);
sprintf(msg, "%s", theArray[pos] );
mylib_rwlock_unlock(&rwlock);
write(clientFileDescriptor,msg,100);
}
else if(operation=='w'){
mylib_rwlock_wlock(&rwlock);
sprintf(theArray[pos], "%s%d%s","String ", pos, " has been modified by a write request\\n" );
mylib_rwlock_unlock(&rwlock);
char msg[100];
sprintf(msg, "%s%d%s","String ", pos, " has been modified by a write request \\n" );
write(clientFileDescriptor,msg,100);
}
else{
printf("there has been an error in recieving operation and position from the client \\n");
}
return 0;
}
| 1
|
#include <pthread.h>
struct Request;
struct Reply;
struct GroupComm;
struct Msg;
struct Request{
int opid;
int gid;
};
struct Reply{
char host[512];
int port;
};
struct GroupComm{
int port;
};
struct Msg{
char data[512];
};
int semkey = -1;
int semid = 0;
struct pollfd cfd[1024];
int numclient = 0;
pthread_mutex_t mut;
void* serve(void *args){
while(1){
pthread_mutex_lock(&mut);
int status = poll(cfd,numclient,-1);
if(status > 0){
struct Msg msg;
int i,j;
for(i=0;i<numclient;i++){
if(cfd[i].revents == POLLIN){
write(1,"POLL: Received\\n",sizeof("POLL: Received\\n"));
if(read(cfd[i].fd,&msg,(sizeof(struct Msg))) <= 0){
write(1,"POLL: client left\\n",sizeof("POLL: client left\\n"));
cfd[i].fd = -1;
continue;
}
for(j=0;j<numclient;j++){
if(i!=j){
if(write(cfd[j].fd,&msg,(sizeof(struct Msg))) <= 0)
write(1,"POLL: client left\\n",sizeof("POLL: client left\\n"));
}
}
}
}
}
pthread_mutex_unlock(&mut);
}
}
int main(int argc, char const *argv[])
{
semkey = ftok("/tmp",64);
assert((semid = semget(semkey,1,IPC_CREAT|0666)) != -1);
char pfifo[512];
int tfd;
sprintf(pfifo,"%d.out",getpid());
assert((tfd = open(pfifo,O_RDWR))!=-1);
struct GroupComm gc;
assert(read(tfd,&gc,(sizeof(struct GroupComm))) >= 0);
sprintf(pfifo,"GSERVER: port no. received: %d\\n",gc.port);
assert(write(1,pfifo,strlen(pfifo)) >= 0);
int sfd,clsize;
struct sockaddr_in servaddr,claddr;
assert((sfd = socket(AF_INET,SOCK_STREAM,0)) != -1);
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(gc.port);
servaddr.sin_addr.s_addr = INADDR_ANY;
assert(bind(sfd,(struct sockaddr*)&servaddr,sizeof(servaddr)) != -1);
assert(listen(sfd,1024) != -1);
semSignal(semid,0);
pthread_t tid;
pthread_mutex_init(&mut,0);
assert(pthread_create(&tid,0,serve,0) != -1);
while(1){
printf("Waiting for clients..........\\n");
int nsfd = accept(sfd,(struct sockaddr*)&claddr,&clsize);
sprintf(pfifo,"GSERVER: Client Received %d.\\n",numclient+1);
assert(write(1,pfifo,strlen(pfifo)) >= 0);
pthread_mutex_lock(&mut);
cfd[numclient].fd = nsfd;
cfd[numclient].events = POLLIN;
cfd[numclient].revents = 0;
numclient++;
pthread_mutex_unlock(&mut);
}
return 0;
}
| 0
|
#include <pthread.h>
void insert(struct tree_node **ptr, struct payload *obj)
{
if (*ptr == 0) {
*ptr = (struct tree_node *)malloc((sizeof(struct tree_node)));
(*ptr)->val = obj->id;
(*ptr)->data = obj->data;
(*ptr)->left = 0;
(*ptr)->right = 0;
(*ptr)->height = -1;
LOG("node %p val %d\\n", *ptr, (*ptr)->val);
return;
}
if (obj->id < (*ptr)->val)
insert(&(*ptr)->left, obj);
else if (obj->id > (*ptr)->val)
insert(&(*ptr)->right, obj);
else if (obj->id == (*ptr)->val)
printf("!!collision!! with id %d\\n", obj->id);
return;
}
void free_tree(struct tree_node *ptr)
{
if (ptr == 0)
return;
free_tree(ptr->left);
free_tree(ptr->right);
LOG("free ptr %p data %d\\n", ptr, ptr->val);
free(ptr);
return;
}
void database_close(struct avl_context *ctxt)
{
pthread_mutex_lock(&ctxt->mutex);
free_tree(ctxt->root);
pthread_mutex_unlock(&ctxt->mutex);
pthread_mutex_destroy(&ctxt->mutex);
ctxt->root = 0;
}
void database_init(struct avl_context *ctxt, struct payload *obj)
{
struct tree_node *rootptr;
rootptr = (struct tree_node*)malloc(sizeof(*rootptr));
rootptr->val = obj->id;
rootptr->data = obj->data;
rootptr->left = 0;
rootptr->right = 0;
rootptr->height = -1;
ctxt->root = rootptr;
pthread_mutex_init(&ctxt->mutex, 0);
}
void database_store(struct avl_context *ctxt, struct payload *obj)
{
pthread_mutex_lock(&ctxt->mutex);
insert((struct tree_node **)&ctxt->root, obj);
height((struct tree_node **)&ctxt->root, 0, (struct tree_node **)&ctxt->root);
pthread_mutex_unlock(&ctxt->mutex);
}
void * find(struct tree_node *root, int key)
{
if (root == 0)
return 0;
if (key == root->val)
return root->data;
if (key < root->val)
return find(root->left, key);
else
return find(root->right, key);
}
void * database_retrieve(struct avl_context *ctxt, int key)
{
void *data;
pthread_mutex_lock(&ctxt->mutex);
data = find(ctxt->root, key);
pthread_mutex_unlock(&ctxt->mutex);
return data;
}
void traverse_preorder(struct tree_node *root)
{
if (root == 0)
return;
printf("%d ", root->val);
traverse_preorder(root->left);
traverse_preorder(root->right);
}
void database_traverse(struct avl_context *ctxt)
{
if (ctxt->root == 0)
return;
traverse_preorder(ctxt->root);
}
| 1
|
#include <pthread.h>
int count = 0;
int thread_ids[3] = {0,1,2};
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
void *inc_count(void *t) {
int i;
long my_id = (long)t;
for (i=0; i<10 && count < 12; 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** matrix;
int order;
int sort_index;
} sort_t;
int** A;
int** B;
int** C;
int order;
int sort_index;
} add_t;
pthread_mutex_t lock;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void * initialize_matrix(void * arg,int flag) {
if (flag == 0){
sort_t * m = (sort_t * ) arg;
int i,j;
for (i = 0; i < m->order; i++){
for (j = 0; j < m->order; j++){
m->matrix[i][j] = (int)(rand() % 100);
printf("%d\\n",m->matrix[i][j]);
}
}
}
else if (flag == 1){
add_t * m = (add_t * ) arg;
int i,j;
for (i = 0; i < m->order; i++){
for (j = 0; j < m->order; j++){
m->A[i][j] = (int)(rand() % 100);
m->B[i][j] = (int)(rand() % 100);
}
}
}
return 0;
}
void * sort(void * arg) {
sort_t * m = (sort_t * ) arg;
int i,j,temp,ind;
pthread_mutex_lock(&lock);
ind = m->sort_index;
m->sort_index ++;
pthread_mutex_unlock(&lock);
for (i = 0; i < m->order; i++){
for (j = i + 1; j < m->order; j++){
if (m->matrix[i][ind] > m->matrix[j][ind]){
temp = m->matrix[i][ind];
m->matrix[i][ind] = m->matrix[j][ind];
m->matrix[j][ind] = temp;
}
else break;
}
}
return 0;
}
void * add(void * arg) {
add_t * m = (add_t * ) arg;
int i,ind;
pthread_mutex_lock(&lock);
ind = m->sort_index;
m->sort_index ++;
pthread_mutex_unlock(&lock);
for (i = 0; i < m->order; i++){
m->C[i][ind] =m->A[i][ind] + m->B[i][ind];
}
return 0;
}
int main() {
sort_t args;
add_t add_args;
int i,j;
int N;
char *ps, s[100];
while (fgets(s, sizeof(s), stdin)) {
N = strtol(s, &ps, 10);
if (ps == s || *ps != '\\n') {
printf("Please enter an integer: ");
} else break;
}
pthread_t p_sort[N],p_add[N];
args.order = N;
add_args.order = N;
args.sort_index = 0;
add_args.sort_index = 0;
args.matrix = (int**)malloc(N * sizeof(int*));
for(i = 0; i < N; i++){
args.matrix[i] = (int*)malloc(N * sizeof(int));
}
add_args.A = (int**)malloc(N * sizeof(int*));
for(i = 0; i < N; i++){
add_args.A[i] = (int*)malloc(N * sizeof(int));
}
add_args.B = (int**)malloc(N * sizeof(int*));
for(i = 0; i < N; i++){
add_args.B[i] = (int*)malloc(N * sizeof(int));
}
add_args.C = (int**)malloc(N * sizeof(int*));
for(i = 0; i < N; i++){
add_args.C[i] = (int*)malloc(N * sizeof(int));
}
initialize_matrix(&args,0);
initialize_matrix(&add_args,1);
for (i = 0; i < N; i++){
pthread_create(&p_sort[i], 0, sort, &args);
pthread_join(p_sort[i],0);
}
printf("printing sorted array :\\n");
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
printf("%d\\n",args.matrix[i][j] );
}
}
for (i = 0; i < N; i++){
pthread_create(&p_add[i], 0, add, &add_args);
pthread_join(p_add[i],0);
}
printf("printing sorted array :\\n");
for (i = 0; i < N; i++){
for (j = 0; j < N; j++){
printf("%d + %d = %d\\n",add_args.A[i][j],add_args.B[i][j],add_args.C[i][j] );
}
}
return 0;
}
| 1
|
#include <pthread.h>
pthread_mutex_t mutex;
void *do_work(void *data)
{
char buf[128];
int count = 0, i;
int fd = *(int *)data;
pthread_mutex_lock(&mutex);
while(1)
{
if (count >= 100)
{
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
snprintf(buf, sizeof(buf), "pthread_id : %lu count : %d\\n", pthread_self(), count++);
for (i = 0; i < strlen(buf); i++)
{
write(fd, &buf[i], 1);
}
}
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
int main(int argc, char **argv)
{
int i;
int fd;
pthread_t pth[10];
pthread_mutex_init(&mutex, 0);
fd = open("./test", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd == -1)
{
return -1;
}
for (i = 0; i < 10; i++)
{
pthread_create(&pth[i], 0, do_work, &fd);
}
for (i = 0; i < 10; i++)
{
pthread_join(pth[i], 0);
}
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
pthread_t tid1;
pthread_t tid2;
int status;
pthread_mutex_t lock;
int mine[17];
int poin;
int lub;
int mine2[17];
int poin2;
int lub2;
int htung;
int htung2;
}pmn;
void* pemain1(void *arg)
{
pthread_mutex_lock(&lock);
struct player *maen = (struct player*)arg;
char t;
int flag;
printf("Player 1 silahkan memilih angka untuk meletakkan ranjau sebanyak 1-4 pada 16 lubang tersedia \\n");
printf("Berapa ranjau yg akan dimasukkan?\\n");
scanf("%d",&flag);
printf("masukkan\\n");
while(flag != 0){
scanf("%d",&maen->lub,&t);
if (maen->mine[maen->lub] == 0) {maen->mine[maen->lub] = 1; maen->htung++;}
else { printf("ranjau sudah ada , pilih lubang lainnya\\n"); flag++; }
flag--;
}
printf("ranjau sudah dipasang\\n");
printf("Player 2 silahkan memilih 4 lubang\\n");
int i, j ;
int x;
for (i = 0 ; i < 4 ; i++)
{
scanf("%d", &x);
if(maen->mine[x] == 1) {printf("anda benar\\n");maen->poin2 += 1;maen->mine[x] = 12;}
else if(maen->mine[x] == 0) {printf("anda salah\\n");maen->poin += 1;}
else{printf("anda sudah memilih sebelumnya , pilih lubang lain\\n");i--;}
}
status = 1;
printf("poin pemain 1 =%d \\n",maen->poin );
printf("poin pemain 2 =%d \\n",maen->poin2 );
if (maen->poin >=10 || maen->poin2 >=10){
exit(1);}
pthread_mutex_unlock(&lock);
return 0;
}
void* pemain2(void *arg)
{
pthread_mutex_lock(&lock);
struct player *maen = (struct player*)arg;
char t;
int flag;
printf("Player 2 silahkan memilih angka untuk meletakkan ranjau sebanyak 1-4 dalam 16 lubang tersedia \\n");
printf("Berapa ranjau yg akan dimasukkan?\\n");
scanf("%d",&flag);
printf("masukkan\\n");
while(flag != 0){
scanf("%d",&maen->lub2,&t);
if (maen->mine2[maen->lub2] == 0) {maen->mine2[maen->lub2] = 1;maen->htung2++;}
else {printf("ranjau sudah ada , pilih lubang lainnya\\n"); flag++;}
flag--;
}
printf("ranjau sudah dipasang\\n");
printf("Player 1 silahkan memilih 4 lubang\\n");
int i, j ;
int x;
for (i = 0 ; i < 4 ; i++)
{
scanf("%d", &x);
if(maen->mine2[x] == 1) {printf("anda benar\\n");maen->poin += 1;maen->mine2[x] = 12;}
else if (maen->mine2[x] == 0){printf("anda salah\\n");maen->poin2 += 1;}
else {printf("anda sudah memilih sebelumnya , pilih lubang lain\\n");i--;}
}
printf("poin pemain 1 =%d \\n",maen->poin );
printf("poin pemain 2 =%d \\n",maen->poin2 );
if (maen->poin >=10 || maen->poin2 >=10 || maen->htung2 == 16 || maen->htung == 16){
exit(1);}
pthread_mutex_unlock(&lock);
return 0;
}
int main(void)
{
pmn plyr;
int i,lol = 2;
plyr.poin = 0;
plyr.poin2 = 0;
plyr.htung = 0;
plyr.htung2 = 0;
for (i = 1 ; i < 17 ; i++){
plyr.mine[i] = 0;
}
for (i = 1 ; i < 17 ; i++){
plyr.mine2[i] = 0;
}
for(i = 0; i < 15 ; i++){
pthread_create(&(tid1), 0, &pemain1, &plyr);
pthread_create(&(tid2), 0, &pemain2, &plyr);
}
pthread_join(tid1, 0);
pthread_join(tid2, 0);
return 0;
}
| 1
|
#include <pthread.h>
struct timeval t0;
struct timeval t1;
static unsigned len = 2000000;
pthread_t tid[16];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int v;
struct p * left;
struct p * right;
} p;
struct p *tree;
struct p * newNode(int value) {
struct p * node = (struct p*)malloc(sizeof(struct p));
node->v = value;
node->left = 0;
node->right = 0;
return(node);
}
struct p * add(int v, struct p * somewhere) {
if (somewhere == 0) {
return(newNode(v));
} else if (v <= somewhere->v) {
somewhere->left = add(v, somewhere->left);
} else {
somewhere->right = add(v, somewhere->right);
}
return(somewhere);
}
struct p * find(int v, struct p * somewhere) {
if (somewhere == 0) {
return 0;
} else if (v == somewhere->v) {
return somewhere;
} else if (v < somewhere->v) {
find(v, somewhere->left);
} else {
find(v, somewhere->right);
}
}
struct p * add_if_not_present(int v, struct p * somewhere) {
if (somewhere == 0) {
return(newNode(v));
} else if (v == somewhere->v) {
return 0;
} else if (v < somewhere->v) {
somewhere->left = add(v, somewhere->left);
} else {
somewhere->right = add(v, somewhere->right);
}
return(somewhere);
}
int size(struct p * somewhere) {
int c = 1;
if (somewhere == 0) {
return 0;
} else {
c += size(somewhere->left);
c += size(somewhere->right);
return c;
}
}
int checkIntegrity(struct p * somewhere, int index, int nodeCount) {
if (somewhere == 0) {
return(0);
} else if (index >= nodeCount) {
return(0);
}
return(checkIntegrity(somewhere->left, 2*index + 1, nodeCount) &&
checkIntegrity(somewhere->right, 2*index + 2, nodeCount));
}
void *baseline() {
int i;
for(i = 0; i<len;i++) {
pthread_mutex_lock(&mutex);
add(random(),tree);
add_if_not_present(random(),tree);
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
void curFunc() {
int i,err;
for(i = 0; i < 16; i++) {
err = pthread_create(&(tid[i]), 0, &baseline, 0);
};
for(i = 0; i < 16; i++) {
err = pthread_join(tid[i],0);
};
};
int main() {
long long values[1];
int eventset;
tree = (p *) malloc(len*sizeof(p));
tree->v = random();
gettimeofday(&t0,0);
curFunc();
gettimeofday(&t1,0);
double elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;
printf("time: %f\\n", elapsed / 1000000 );
return 0;
}
| 0
|
#include <pthread.h>
pthread_t *clientthreads;
int threadscreated;
int numthreads = 1;
int numrequests = 1;
char* ipaddress = "127.0.0.1";
int port = 8080;
pthread_mutex_t count_mutex;
pthread_cond_t count_threshold_cv;
pexit(char * msg)
{
perror(msg);
exit(1);
}
void request(int id)
{
pthread_mutex_lock(&count_mutex);
while (threadscreated < numthreads)
pthread_cond_wait(&count_threshold_cv, &count_mutex);
pthread_mutex_unlock(&count_mutex);
int k;
for(k=0;k<numrequests;k++) {
int i,sockfd;
char buffer[8196];
static struct sockaddr_in serv_addr;
printf("client %d trying to connect to %s and port %d for request %d\\n",id,ipaddress,port, k);
if((sockfd = socket(AF_INET, SOCK_STREAM,0)) <0)
pexit("socket() failed");
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(ipaddress);
serv_addr.sin_port = htons(port);
if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) <0)
pexit("connect() failed");
write(sockfd, "GET /index.html \\r\\n", 18);
while( (i=read(sockfd,buffer,8196)) > 0);
write(1,buffer,i);
printf("client %d finished getting response from %s and port %d for request %d\\n",id,ipaddress,port,k);
}
pthread_exit(0);
}
int main(int argc, char **argv)
{
struct timeval first;
gettimeofday(&first,0);
int c;
opterr = 0;
while ((c = getopt (argc, argv, "i:p:t:r:?")) != -1)
switch (c)
{
case 'i':
ipaddress = optarg;
break;
case 'p':
port = atoi(optarg);
break;
case 't':
numthreads = atoi(optarg);
break;
case 'r':
numrequests = atoi(optarg);
break;
case '?':
printf("This programs can receive up to 4 arguments:\\n-i ip_address (default is 127.0.0.1)\\n-p port_number (default is 8080)\\n-t number_of_threads (default is 1)\\n-r number_of_requests_per_thread (default is 1)\\n");
return 1;
break;
}
int rc;
clientthreads = (pthread_t *)malloc(sizeof(pthread_t)*numthreads);
int i;
pthread_mutex_init(&count_mutex, 0);
pthread_cond_init (&count_threshold_cv, 0);
pthread_mutex_lock(&count_mutex);
threadscreated = 0;
for(i=0; i<numthreads; i++){
rc = pthread_create(&clientthreads[i], 0, (void *(*)(void *))&request, (void*)i);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\\n", rc);
exit(-1);
} else {
threadscreated++;
}
}
pthread_cond_broadcast(&count_threshold_cv);
pthread_mutex_unlock(&count_mutex);
for(i=0; i<numthreads; i++){
rc = pthread_join(clientthreads[i],0);
if (rc) {
printf("ERROR; return code from pthread_join() is %d\\n", rc);
exit(-1);
}
}
struct timeval second;
gettimeofday(&second,0);
double ttime = (second.tv_sec - first.tv_sec)*1000 + (second.tv_usec - first.tv_usec)/1000.0;
printf("Total time: %g miliseconds\\n", ttime);
}
| 1
|
#include <pthread.h>
int *buf;
int size;
int head;
int tail;
pthread_mutex_t mutex;
pthread_cond_t not_full;
pthread_cond_t not_empty;
} buf_t;
static inline bool is_full(buf_t *buf)
{
return buf->head == (buf->tail + 1) % buf->size;
}
static inline bool is_empty(buf_t *buf)
{
return buf->head == buf->tail;
}
static inline int len(buf_t *buf)
{
return (buf->tail - buf->head + buf->size) % buf->size;
}
void buf_init(buf_t *buf, int n)
{
buf->buf = malloc(sizeof(int) * n);
buf->size = n;
buf->head = buf->tail = 0;
pthread_mutex_init(&buf->mutex, 0);
pthread_cond_init(&buf->not_full, 0);
pthread_cond_init(&buf->not_empty, 0);
}
void *producer(void *p)
{
buf_t *buf = p;
pthread_detach(pthread_self());
for (;;) {
pthread_mutex_lock(&buf->mutex);
while (is_full(buf))
pthread_cond_wait(&buf->not_full, &buf->mutex);
buf->buf[buf->tail] = 1;
buf->tail = (buf->tail + 1) % buf->size;
printf("head: %d tail: %d\\n", buf->head, buf->tail);
pthread_cond_signal(&buf->not_empty);
pthread_mutex_unlock(&buf->mutex);
}
return 0;
}
void *consumer(void *p)
{
buf_t *buf = p;
pthread_detach(pthread_self());
for (;;) {
pthread_mutex_lock(&buf->mutex);
while (is_empty(buf))
pthread_cond_wait(&buf->not_empty, &buf->mutex);
buf->buf[buf->head] = 0;
buf->head = (buf->head + 1) % buf->size;
printf("head: %d tail: %d\\n", buf->head, buf->tail);
pthread_cond_signal(&buf->not_full);
pthread_mutex_unlock(&buf->mutex);
}
return 0;
}
int main(void)
{
int i;
buf_t buf;
pthread_t producer_tid;
pthread_t consumer_tid;
buf_init(&buf, 20);
for (i = 0; i < 2; i++) {
pthread_create(&producer_tid, 0, producer, &buf);
pthread_create(&consumer_tid, 0, consumer, &buf);
}
pthread_exit(0);
}
| 0
|
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
phil_state state[5 +1];
sem_t spoon[5 +1];
sem_t phil_sem[5 +1];
void* philosopher(void* p);
void pick_forks(int i);
void put_forks(int i);
void thinking(int i);
void test(int i);
void eat(int i);
int main()
{
int i, j, id[5];
pthread_t phil[5];
pthread_mutex_init(&mutex, 0);
for(i=0 ; i<5 ; ++i)
{
state[i+1] = THINKING;
sem_init(&spoon[i+1], 0, 1);
sem_init(&phil_sem[i+1], 0, 0);
}
for(i=0 ; i<5 ; ++i)
{
id[i] = i+1;
pthread_create(&phil[i], 0, philosopher, (void*)&id[i]);
}
for(i=0 ; i<5 ; ++i)
{
pthread_join(phil[i], 0);
}
return 0;
}
void* philosopher(void *p)
{
int ph = *((int*)p);
printf("philosopher %d started\\n", ph);
while(1)
{
thinking(ph);
pick_forks(ph);
eat(ph);
put_forks(ph);
}
}
void pick_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = HUNGRY;
test(i);
pthread_mutex_unlock(&mutex);
sem_wait(&phil_sem[i]);
}
void put_forks(int i)
{
pthread_mutex_lock(&mutex);
state[i] = THINKING;
test(((i+1)%5 == 0)?5:(i+1)%5);
test(((i-1) == 0)?5:i-1);
pthread_mutex_unlock(&mutex);
}
void thinking(int i)
{
printf("philosopher %d is thinking\\n", i);
sleep(rand()%5);
}
void test(int i)
{
if((state[i] == HUNGRY) && state[(((i+1)%5 == 0)?5:(i+1)%5)] != EATING
&& state[(((i-1) == 0)?5:i-1)] != EATING)
{
state[i] = EATING;
sem_post(&phil_sem[i]);
}
}
void eat(int i)
{
printf("Philosopher %d is eating\\n", i);
sleep(rand()%5);
printf("Philosopher %d finished eating\\n", i);
}
| 1
|
#include <pthread.h>
int idx=0;
int ctr1=1, ctr2=0;
int readerprogress1=0, readerprogress2=0;
pthread_mutex_t mutex;
void __VERIFIER_atomic_use1(int myidx) {
__VERIFIER_assume(myidx <= 0 && ctr1>0);
ctr1++;
}
void __VERIFIER_atomic_use2(int myidx) {
__VERIFIER_assume(myidx >= 1 && ctr2>0);
ctr2++;
}
void __VERIFIER_atomic_use_done(int myidx) {
if (myidx <= 0) { ctr1--; }
else { ctr2--; }
}
void __VERIFIER_atomic_take_snapshot(int *readerstart1, int *readerstart2) {
*readerstart1 = readerprogress1;
*readerstart2 = readerprogress2;
}
void __VERIFIER_atomic_check_progress1(int readerstart1) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart1 == 1 && readerprogress1 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void __VERIFIER_atomic_check_progress2(int readerstart2) {
if (__VERIFIER_nondet_int()) {
__VERIFIER_assume(readerstart2 == 1 && readerprogress2 == 1);
if (!(0)) ERROR: __VERIFIER_error();;
}
return;
}
void *qrcu_reader1(void* arg) {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress1 = 1;
readerprogress1 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void *qrcu_reader2(void* arg) {
int myidx;
while (1) {
myidx = idx;
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use1(myidx);
break;
} else {
if (__VERIFIER_nondet_int()) {
__VERIFIER_atomic_use2(myidx);
break;
} else {}
}
}
readerprogress2 = 1;
readerprogress2 = 2;
__VERIFIER_atomic_use_done(myidx);
return 0;
}
void* qrcu_updater(void* arg) {
int i;
int readerstart1, readerstart2;
int sum;
__VERIFIER_atomic_take_snapshot(&readerstart1, &readerstart2);
if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; };
if (sum <= 1) { if (__VERIFIER_nondet_int()) { sum = ctr1; sum = sum + ctr2; } else { sum = ctr2; sum = sum + ctr1; }; }
else {}
if (sum > 1) {
pthread_mutex_lock(&mutex);
if (idx <= 0) { ctr2++; idx = 1; ctr1--; }
else { ctr1++; idx = 0; ctr2--; }
if (idx <= 0) { while (ctr1 > 0); }
else { while (ctr2 > 0); }
pthread_mutex_unlock(&mutex);
} else {}
__VERIFIER_atomic_check_progress1(readerstart1);
__VERIFIER_atomic_check_progress2(readerstart2);
return 0;
}
int main() {
pthread_t t1, t2, t3;
pthread_mutex_init(&mutex, 0);
pthread_create(&t1, 0, qrcu_reader1, 0);
pthread_create(&t2, 0, qrcu_reader2, 0);
pthread_create(&t3, 0, qrcu_updater, 0);
pthread_join(t1, 0);
pthread_join(t2, 0);
pthread_join(t3, 0);
pthread_mutex_destroy(&mutex);
return 0;
}
| 0
|
#include <pthread.h>
void*
thread_func(void *arg)
{
pthread_mutex_t locl_lock;
int err;
if((err = pthread_mutex_lock(&locl_lock)) != 0){
printf("lock error: %s\\n", strerror(err));
}
pthread_mutex_lock(&locl_lock);
if((err = pthread_mutex_lock(&locl_lock)) != 0){
printf("lock error: %s\\n", strerror(err));
}
pthread_mutex_unlock(&locl_lock);
pthread_mutex_unlock(&locl_lock);
pthread_mutex_destroy(&locl_lock);
return ((void*)0);
}
int
main(void)
{
pthread_t tid;
int err;
void *ret;
if((err = pthread_create(&tid, 0, thread_func, 0)) != 0){
printf("can't create thread for: %s\\n", strerror(err));
return -1;
}
if((err = pthread_join(tid, &ret)) != 0){
printf("can't join thread for: %s\\n", strerror(err));
return -2;
}
printf("thead exited with: %d\\n", (int)ret);
return 0;
}
| 1
|
#include <pthread.h>
struct Node {
int value;
struct Node *next;
}*head;
pthread_mutex_t inserter;
pthread_mutex_t searcher;
pthread_mutex_t deleter;
void ins()
{
struct Node * temp;
while(1)
{
if (!pthread_mutex_lock(&inserter))
{
int input = (rand() % 10) + 1;
temp = (struct Node *)malloc(sizeof(struct Node));
printf("Inserting: [%d] \\n" , input);
append_node(input);
pthread_mutex_unlock(&inserter);
sleep(4);
}
}
}
void ser()
{
struct Node * temp;
while(1)
{
if (!pthread_mutex_trylock(&searcher))
{
temp = head;
if (temp == 0)
{
printf("List is empty\\n");
continue;
}
else
{
printf ("Current List (searching): ");
while (temp != 0)
{
printf("[%d] ", temp->value);
temp = temp->next;
}
printf("\\n");
}
pthread_mutex_unlock(&searcher);
}
sleep(3);
}
}
void del()
{
struct Node * temp, * prev;
while(1)
{
int delete = rand() % 10;
if (!pthread_mutex_trylock(&inserter))
{
if(!pthread_mutex_trylock(&searcher))
{
temp = head;
while(temp != 0)
{
if (temp->value == delete)
{
printf("Deleting [%d] from the list. \\n" , delete);
if (temp == head)
{
head = temp->next;
free(temp);
break;
}
else
{
prev->next = temp->next;
free(temp);
break;
}
}
else
{
prev = temp;
temp = temp->next;
}
}
pthread_mutex_unlock(&searcher);
}
pthread_mutex_unlock(&inserter);
}
sleep(2);
}
}
void append_node(int newvalue)
{
struct Node *new = (struct Node*) malloc(sizeof(struct Node));
struct Node *temp = head;
new->value = newvalue;
new->next = 0;
if (head == 0)
{
head = new;
return;
}
while (temp->next != 0)
{
temp = temp->next;
}
temp->next = new;
return;
}
int main()
{
srand(time(0));
struct Node * list;
list = (struct Node *)malloc(sizeof(struct Node));
list->value = (rand() % 10) + 1;
head = list;
head->next = 0;
printf("Starting value in the list: [%d]\\n" , list->value);
pthread_t search[4];
pthread_t insert[4];
pthread_t delete[4];
int i;
for(i = 0; i < 4; ++i)
{
int ithread = pthread_create(&insert[i], 0, (void *)ins, (void *)0);
if (ithread)
{
fprintf(stderr, "Error with insertion thread.\\n");
return 1;
}
int sthread = pthread_create(&search[i], 0, (void *)ser, (void *)0);
if (sthread)
{
fprintf(stderr, "Error with search thread.\\n");
return 1;
}
int dthread = pthread_create(&delete[i], 0, (void *)del, (void *)0);
if (dthread)
{
fprintf(stderr, "Error with deleter thread.\\n");
return 1;
}
}
for(i = 0; i < 4; ++i)
{
pthread_join(insert[i], 0);
pthread_join(search[i], 0);
pthread_join(delete[i], 0);
}
return 0;
}
| 0
|
#include <pthread.h>
int max = 1000000000;
int sharedResource = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* fooAPI(void* param)
{
int i;
pthread_mutex_lock(&mutex);
printf("Changing the shared resource now.\\n");
for(i = 0; i < max; i++){
sharedResource += 1;
}
pthread_mutex_unlock(&mutex);
return 0;
}
int main()
{
struct timespec ts, te;
clock_gettime(CLOCK_REALTIME, &ts);
pthread_t thread, thread2;
pthread_create(&thread, 0, fooAPI, 0);
pthread_create(&thread2, 0, fooAPI, 0);
pthread_join(thread, 0);
pthread_join(thread2, 0);
printf("loop should run %d ,real run %d\\n",max*2, sharedResource);
clock_gettime(CLOCK_REALTIME, &te);
printf("use time %lu.%09lu\\n", te.tv_sec - ts.tv_sec, te.tv_nsec - ts.tv_nsec);
return 0;
}
| 1
|
#include <pthread.h>
struct worker_queue {
pthread_t tid;
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_attr_t attr;
void (*func)(void *priv);
int done;
void *priv;
struct worker_queue *next;
};
struct work {
struct worker_queue *queue_head, *queue_tail;
struct work *next;
};
static void *__sapi_worker_thread(void *work)
{
struct worker_queue *mywork = work;
pthread_mutex_lock(&mywork->mutex);
pthread_cond_signal(&mywork->cond);
pthread_mutex_unlock(&mywork->mutex);
for (; ;) {
pthread_mutex_lock(&mywork->mutex);
pthread_cond_wait(&mywork->cond, &mywork->mutex);
if (!mywork->done) {
mywork->func(mywork->priv);
mywork->done = 1;
}
pthread_mutex_unlock(&mywork->mutex);
}
return 0;
}
void *sapi_worker_create(void (*func)(void *priv), void *usr_priv)
{
struct work *work;
struct worker_queue *queue;
work = calloc(1, sizeof(struct work));
if (!work) {
return 0;
}
queue = calloc(1, sizeof(struct worker_queue));
if (!queue) {
free(work);
return 0;
}
queue->priv = usr_priv;
queue->func = func;
queue->done = 0;
queue->next = 0;
pthread_mutex_init(&queue->mutex, 0);
pthread_cond_init(&queue->cond, 0);
pthread_attr_init(&queue->attr);
pthread_attr_setdetachstate(&queue->attr, PTHREAD_CREATE_DETACHED);
if (!work->queue_head) {
work->queue_head = queue;
work->queue_tail = queue;
} else {
work->queue_tail->next = queue;
work->queue_tail = queue;
}
int ret;
ret = pthread_create(&queue->tid, &queue->attr, __sapi_worker_thread, queue);
if (ret < 0) {
free(work);
free(queue);
return 0;
}
pthread_mutex_lock(&queue->mutex);
pthread_cond_wait(&queue->cond, &queue->mutex);
pthread_mutex_unlock(&queue->mutex);
return work;
}
int sapi_queue_work(void *work_priv, void (*func)(void *priv), void *usr_priv)
{
struct work *work = work_priv;
struct worker_queue *queue;
queue = calloc(1, sizeof(struct worker_queue));
if (!queue) {
return -1;
}
queue->done = 0;
queue->priv = usr_priv;
queue->func = func;
queue->next = 0;
pthread_mutex_init(&queue->mutex, 0);
pthread_cond_init(&queue->cond, 0);
pthread_attr_init(&queue->attr);
pthread_attr_setdetachstate(&queue->attr, PTHREAD_CREATE_DETACHED);
if (!work->queue_head) {
work->queue_head = queue;
work->queue_tail = queue;
} else {
work->queue_tail->next = queue;
work->queue_tail = queue;
}
int ret;
ret = pthread_create(&queue->tid, &queue->attr, __sapi_worker_thread, queue);
if (ret < 0) {
free(queue);
return -1;
}
return 0;
}
int sapi_start_work_for(void *priv, void (*func)(void *priv))
{
struct work *work = priv;
int started = 0;
for (; work; work = work->next) {
struct worker_queue *queue = work->queue_head;
for (; queue; queue = queue->next) {
pthread_mutex_lock(&queue->mutex);
if (queue->func == func) {
pthread_cond_signal(&queue->cond);
started = 1;
}
pthread_mutex_unlock(&queue->mutex);
}
}
return started;
}
int sapi_start_work_all(void *priv)
{
struct work *work = priv;
for (; work; work = work->next) {
struct worker_queue *queue = work->queue_head;
for (; queue; queue = queue->next) {
pthread_mutex_lock(&queue->mutex);
pthread_cond_signal(&queue->cond);
pthread_mutex_unlock(&queue->mutex);
}
}
return 1;
}
| 0
|
#include <pthread.h>
struct prevList {
struct prevList *prev;
int pos;
int no;
};
int x(int);
int y(int);
void *backtrace(void *);
int movex[] = {1, 2, 2, 1, -1, -2, -2, -1};
int movey[] = { -2, -1, 1, 2, 2, 1, -1, -2};
int threads;
int solutions;
pthread_mutex_t printLock;
pthread_mutex_t cntrsLock;
int main() {
struct prevList head;
head.pos = 0;
head.prev = 0;
head.no = 0;
solutions = 0;
threads = 0;
pthread_mutex_init(&printLock, 0);
backtrace(&head);
printf("Solutions: %d\\nThreads: %d\\n",solutions, threads);
return 0;
}
void *backtrace(void *args) {
struct prevList *prev = (struct prevList*)args;
struct prevList *tmp;
struct prevList next[8];
pthread_t thrdz[8];
int i, px, py;
if(prev->no == 5*5 -1) {
{pthread_mutex_lock(&cntrsLock); {++solutions;} pthread_mutex_unlock(&cntrsLock); }
pthread_mutex_lock(&printLock);
printf("Sol: ");
while(prev->prev) {
printf("%d <-- ", prev->pos);
prev = prev->prev;
}
printf("%d\\n", prev->pos);
pthread_mutex_unlock(&printLock);
} else {
px = x(prev->pos);
py = y(prev->pos);
for(i=0;i<8;++i) {
thrdz[i] = 0;
next[i].no = prev->no + 1;
next[i].prev = prev;
if(movex[i]>0) {
if(px>=5 -movex[i]) continue;
} else {
if(px<-movex[i]) continue;
}
if(movey[i]>0) {
if(py>=5 -movey[i]) continue;
} else {
if(py<-movey[i]) continue;
}
next[i].pos = prev->pos + movey[i]*5 + movex[i];
for(tmp = prev; tmp != 0 && tmp->pos != next[i].pos; tmp = tmp->prev) ;
if(tmp == 0) {
{pthread_mutex_lock(&printLock); {{ printf("prop%d:%2d -- ",i,next[i].pos); for(tmp=prev;tmp;tmp=tmp->prev) printf("%2d < ",tmp->pos); printf("\\n"); };} pthread_mutex_unlock(&printLock); }
pthread_create(&(thrdz[i]), 0, backtrace, (void*)&next[i]);
{pthread_mutex_lock(&cntrsLock); {++threads;} pthread_mutex_unlock(&cntrsLock); }
}
}
for(i=0;i<8;++i) {
if(thrdz[i] != 0) {
pthread_join(thrdz[i], 0);
}
}
}
return 0;
}
int x(int p) { return p%5; }
int y(int p) { return p/5; }
| 1
|
#include <pthread.h>
FILE *arquivo;
unsigned int id;
char nome[256];
char sexo;
float salario;
} funcionario;
int contM, contF, num_threads = 2;
float salarioM, salarioF;
char* base_funcionarios;
pthread_mutex_t calculo;
void inserir_funcionario(){
funcionario fc;
printf("\\nInsira o id:\\n");
int novoId;
scanf("%d", &novoId);
if(novoId <= 0){
printf("O id do funcionário não pode ser menor que 0!\\n");
return;
}
while(1){
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
break;
}
if(fc.id == novoId){
printf("Já existe funcionário com o id %u!\\n", novoId);
return;
}
}
fc.id = novoId;
printf("Insira o nome:\\n");
scanf(" %[^\\n]s", fc.nome);
printf("Insira o sexo(M para masculino ou F para feminino):\\n");
scanf(" %c", &fc.sexo);
printf("Insira o salário:\\n");
scanf("%f", &fc.salario);
fwrite(&fc, sizeof(funcionario), 1, arquivo);
printf("\\nFuncionário cadastrado com sucesso!\\n");
}
void remover_funcionario(){
unsigned int idFuncionario;
printf("\\nInsira o id do funcionário que será removido:\\n");
scanf("%u", &idFuncionario);
funcionario fc;
while(1){
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
printf("\\nFuncionário não encontrado.\\n");
break;
}
if(fc.id == idFuncionario){
fc.id = 0;
fseek(arquivo, -1*sizeof(funcionario), 1);
fwrite(&fc, sizeof(funcionario), 1, arquivo);
printf("\\nFuncionário excluído.\\n");
break;
}
}
}
void calcula(void * arg){
int* id = (int*) arg;
int totalM = 0, totalF = 0, posicao = 0, i = 0;
float somaSalarioM = 0, somaSalarioF = 0;
funcionario fc;
while(1){
posicao = i * num_threads + *id;
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
break;
}else{
if(fc.id && (fc.sexo == 'M' || fc.sexo == 'm')){
totalM++;
somaSalarioM += fc.salario;
}else if(fc.id && (fc.sexo == 'F' || fc.sexo == 'f')){
totalF++;
somaSalarioF += fc.salario;
}
}
i++;
}
pthread_mutex_lock(&calculo);
contM += totalM;
salarioM += somaSalarioM;
contF += totalF;
salarioF += somaSalarioF;
pthread_mutex_unlock(&calculo);
}
void calcular_media_sexo(){
pthread_mutex_init(&calculo, 0);
salarioM = 0;
salarioF = 0;
contM = 0;
contF = 0;
int i, id[num_threads];
pthread_t thread[num_threads];
printf("\\nCalculando média por sexo\\n");
for(i = 0; i < num_threads; i++){
id[i] = i;
pthread_create(&thread[i], 0, calcula, &id[i]);
}
for(i = 0; i < num_threads; i++){
pthread_join(thread[i], 0);
}
printf("Média dos salários masculinos: %.2f\\n", salarioM/contM);
printf("Média dos salários femininos: %.2f\\n", salarioF/contF);
pthread_mutex_destroy(&calculo);
}
void listar_usuarios(){
printf("\\nListando usuários:\\n");
printf("ID\\t\\tNome\\t\\tSexo\\t\\tSalário\\n");
funcionario fc;
while(1){
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
break;
}
printf("%u\\t\\t%s\\t\\t%c\\t\\t%.2f\\n", fc.id, fc.nome, fc.sexo, fc.salario);
}
}
void exportar_dados(){
funcionario fc;
char nomeArquivo[256];
FILE *arquivoExport;
printf("\\nDigite o nome desejado para o arquivo que será exportado:\\n");
scanf(" %[^\\n]s", nomeArquivo);
arquivoExport = fopen(nomeArquivo, "a+");
while(1){
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
break;
}
if(fc.id){
fprintf(arquivoExport, "%u\\t\\t%s\\t\\t%c\\t\\t%.2f\\n", fc.id, fc.nome, fc.sexo, fc.salario);
}
}
fclose(arquivoExport);
printf("\\nDados exportados com sucesso!\\n");
}
void compactar_base(){
funcionario fc;
FILE *baseNova;
baseNova = fopen("troca", "a+b");
while(1){
int cont = fread(&fc, sizeof(funcionario), 1, arquivo);
if(!cont){
break;
}
if(fc.id){
fwrite(&fc, sizeof(funcionario), 1, baseNova);
}
}
remove(base_funcionarios);
rename("troca", base_funcionarios);
arquivo = baseNova;
printf("\\nBase compactada com sucesso!\\n");
}
int main(int argc, char** argv[]){
int opt = 0, executando = 1;
base_funcionarios = (char*) argv[1];
arquivo = fopen(base_funcionarios, "a+b");
fclose(arquivo);
arquivo = fopen(base_funcionarios, "r+b");
printf("\\n=== PROGRAMA DE CADASTRO DE FUNCIONÁRIOS ===\\n");
while(executando){
rewind(arquivo);
printf("\\nSELECIONE A OPÇÃO DESEJADA:\\n");
printf("1 - Inserir Funcionário\\n");
printf("2 - Remover Funcionário\\n");
printf("3 - Calcular média salarial dos funcionários\\n");
printf("4 - Exportar Dados\\n");
printf("5 - Compactar Base\\n");
printf("6 - Listar Funcionários\\n");
printf("7 - Sair\\n");
scanf("%d", &opt);
switch(opt){
case 1:
inserir_funcionario();
break;
case 2:
remover_funcionario();
break;
case 3:
calcular_media_sexo();
break;
case 4:
exportar_dados();
break;
case 5:
compactar_base();
break;
case 6:
listar_usuarios();
break;
case 7:
printf("OBRIGADO POR USAR O NOSSO SISTEMA!\\n");
executando = 0;
break;
default:
printf("OPÇÃO INVÁLIDA!\\n");
}
}
fclose(arquivo);
pthread_exit(0);
return 0;
}
| 0
|
#include <pthread.h>
int stoj = 0;
int smeVsetci = 0;
int volnePece = 4, oddychujuci = 0;
int chleby[10] = {0}, pocetChlebov = 0;
pthread_mutex_t mutexChleby = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexSynchronizacia = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexOddychovanie = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t condPecenie = PTHREAD_COND_INITIALIZER;
pthread_cond_t condOddych = PTHREAD_COND_INITIALIZER;
void priprava(int pekar) {
sleep(4);
}
void pecenie(int pekar) {
if(stoj){
return;
}
pthread_mutex_lock(&mutexSynchronizacia);
while(volnePece == 0){
if(stoj){
return ;
}
pthread_cond_wait(&condPecenie, &mutexSynchronizacia);
}
printf("Pekar %d : idem piect | volne pece: %d \\n", pekar, volnePece);
volnePece--;
pthread_mutex_unlock(&mutexSynchronizacia);
sleep(2);
pthread_mutex_lock(&mutexSynchronizacia);
chleby[pekar]++;
pocetChlebov++;
printf("Pekar %d : Huraa mam %d. chlebik \\n", pekar, chleby[pekar]);
volnePece++;
pthread_cond_broadcast(&condPecenie);
pthread_mutex_unlock(&mutexSynchronizacia);
if(chleby[pekar] % 2 == 0 && chleby[pekar] > 0){
pthread_mutex_lock(&mutexOddychovanie);
oddychujuci++;
printf("Pekar %d : Cakam na oddych ako %d. \\n", pekar, oddychujuci);
if(oddychujuci == 10){
smeVsetci = 1;
printf("Pekar %d : Uz sme vsetci !\\n", pekar);
pthread_cond_broadcast(&condOddych);
} else {
while(!smeVsetci){
if(stoj){
return;
}
pthread_cond_wait(&condOddych, &mutexOddychovanie);
}
}
oddychujuci--;
printf("Pekar %d : Odchadzzam oddychovat ako %d. \\n", pekar, 10 - oddychujuci);
if( oddychujuci == 0){
smeVsetci = 0;
printf("Pekar %d : A uz oddychujeme vsetci !\\n", pekar);
}
pthread_mutex_unlock(&mutexOddychovanie);
sleep(4);
}
}
void *pekar( void *ptr ) {
int pekar = (int) ptr;
while(!stoj) {
priprava(pekar);
pecenie(pekar);
}
return 0;
}
int main(void) {
int i;
pthread_t pekari[10];
for (i=0;i<10;i++) pthread_create( &pekari[i], 0, &pekar, (void *)i);
sleep(30);
pthread_mutex_lock(&mutexChleby);
stoj = 1;
printf("Koniec simulacie !!!!!\\n");
pthread_cond_broadcast(&condOddych);
pthread_cond_broadcast(&condPecenie);
pthread_mutex_unlock(&mutexChleby);
for (i=0;i<10;i++) pthread_join( pekari[i], 0);
printf("Pocet chlebov: %d\\n", pocetChlebov);
for (i=0;i<10;i++) printf("Pekar %d spravil %d chlebov.\\n", i, chleby[i]);
exit(0);
}
| 1
|
#include <pthread.h>
static pthread_key_t key;
static pthread_once_t init_done = PTHREAD_ONCE_INIT;
pthread_mutex_t env_mutex = PTHREAD_MUTEX_INITIALIZER;
extern char **environ;
static void thread_init(void)
{
pthread_key_create(&key, free);
}
char getenv_r(const char *name)
{
int i, len;
char *envbuf;
pthread_once(&init_done, thread_init);
pthread_mutex_lock(&env_mutex);
envbuf = (char *)pthread_getspecific(key);
if(envbuf == 0) {
envbuf = malloc(4096);
if(envbuf == 0) {
pthread_mutex_unlock(&env_mutex);
return 0;
}
pthread_setspecific(key, envbuf);
}
len = strlen(name);
for(i=0; environ[i]!=0; i++) {
if((strncmp(name, environ[i], len) == 0) && (environ[i][len] == '=')) {
strncpy(envbuf, &environ[i][len+1], 4096 -1);
pthread_mutex_unlock(&env_mutex);
return envbuf;
}
}
pthread_mutex_unlock(&env_mutex);
return 0;
}
int main(void)
{
printf("Current login user: %s", getenv_r("USER"));
exit(0);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.