Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as C by Jaybee ( 7 years ago )
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
#define BUFF_SIZE 10
//const int BUFF_SIZE = 10;
int buffer[BUFF_SIZE];// = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int loc = 0;
//int buffer[] = int[BUFF_SIZE];
void print_ints()
{
for(int i = 0; i < BUFF_SIZE; i++)
{
printf("%d", buffer[i]);
printf("\n");
}
}
void *myThreadFun(void *vargp)
{
sleep(1);
printf("This a thread.\n");
return NULL;
}
void *producer(void *vargp)
{
while(1)
{
sleep(rand() % 4);
printf("producer thread\n");
if(!(loc > BUFF_SIZE))
{
buffer[loc] = rand() % 10;
loc++;
}
print_ints();
}
return NULL;
}
void *consumer(void *vargp)
{
while(1)
{
sleep(rand() % 7);
printf("consumer thread\n");
//loc--;
if(!(loc - 1 < 0))
{
buffer[loc] = -1;//rand() % 9;
loc--;
}
print_ints();
}
return NULL;
}
int main()
{
//pthread_t thread1, thread2;
//pthread_t* threads = new pthread_t[5];
//pthread_t threads[5];
pthread_t producer_thread, consumer_thread;
printf("Testing print_ints\n");
//buffer = new int[BUFF_SIZE];
for(int i = 0; i < BUFF_SIZE; i++)
{
buffer[i] = -1;
}
print_ints();
printf("Before Threads\n");
srand(time(0));
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
/*
for(int i = 0; i < 5; i++)
{
pthread_create(&threads[i], NULL, myThreadFun, NULL);
}
for(int i = 0; i < 5; i++)
{
pthread_join(threads[i], NULL);
}*/
/*
pthread_create(&thread1, NULL, myThreadFun, NULL);
pthread_create(&thread2, NULL, myThreadFun, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
*/
printf("After Threads\n");
exit(0);
}
Revise this Paste
Children: 98334