pthread_create Error in Visual Studio - c++

Hi I'm using Visual Studio 2010 and having trouble getting this barber shop program to work.
I get this error
pthread_create : cannot convert parameter 3 from void *(__cdecl *)(void) to void *(__cdecl *)(void *)
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <Windows.h>
#define seats 6
void *customerMaker();
void *barberShop();
void *waitingRoom();
void checkQueue();
pthread_mutex_t queue_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t wait_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t sleep_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t barberSleep_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t barberWorking_cond = PTHREAD_COND_INITIALIZER;
int returnTime=5,current=0, sleeping=0, iseed;
int main(int argc, char *argv[])
{
iseed=time(NULL);
srand(iseed);
//declare barber thread;
pthread_t barber,customerM,timer_thread;
pthread_attr_t barberAttr, timerAttr;
pthread_attr_t customerMAttr;
//define barber, and cutomerMaker default attributes
pthread_attr_init(&timerAttr);
pthread_attr_init(&barberAttr);
pthread_attr_init(&customerMAttr);
printf("\n");
//create cutomerMaker
pthread_create(&customerM,&customerMAttr,customerMaker,NULL);
//create barber
pthread_create(&barber,&barberAttr,barberShop,NULL);
pthread_join(barber,NULL);
pthread_join(customerM,NULL);
return 0;
}
void *customerMaker()
{
int i=0;
printf("*Customer Maker Created*\n\n");
fflush(stdout);
pthread_t customer[seats+1];
pthread_attr_t customerAttr[seats+1];
while(i<(seats+1))
{
i++;
pthread_attr_init(&customerAttr[i]);
while(rand()%2!=1)
{
Sleep(1);
}
pthread_create(&customer[i],&customerAttr[i],waitingRoom,NULL);
}
pthread_exit(0);
}
void *waitingRoom()
{
//take seat
pthread_mutex_lock(&queue_mutex);
checkQueue();
Sleep(returnTime);
waitingRoom();
}
void *barberShop()
{
int loop=0;
printf("The barber has opened the store.\n");
fflush(stdout);
while(loop==0)
{
if(current==0)
{
printf("\tThe shop is empty, barber is sleeping.\n");
fflush(stdout);
pthread_mutex_lock(&sleep_mutex);
sleeping=1;
pthread_cond_wait(&barberSleep_cond,&sleep_mutex);
sleeping=0;
pthread_mutex_unlock(&sleep_mutex);
printf("\t\t\t\tBarber wakes up.\n");
fflush(stdout);
}
else
{
printf("\t\t\tBarber begins cutting hair.\n");
fflush(stdout);
Sleep((rand()%20)/5);
current--;
printf("\t\t\t\tHair cut complete, customer leaving store.\n");
pthread_cond_signal(&barberWorking_cond);
}
}
pthread_exit(0);
}
void checkQueue()
{
current++;
printf("\tCustomer has arrived in the waiting room.\t\t\t\t\t\t\t%d Customers in store.\n",current);
fflush(stdout);
printf("\t\tCustomer checking chairs.\n");
fflush(stdout);
if(current<seats)
{
if(sleeping==1)
{
printf("\t\t\tBarber is sleeping, customer wakes him.\n");
fflush(stdout);
pthread_cond_signal(&barberSleep_cond);
}
printf("\t\tCustomer takes a seat.\n");
fflush(stdout);
pthread_mutex_unlock(&queue_mutex);
pthread_mutex_lock(&wait_mutex);
pthread_cond_wait(&barberWorking_cond,&wait_mutex);
pthread_mutex_unlock(&wait_mutex);
return;
}
if(current>=seats)
{
printf("\t\tAll chairs full, leaving store.\n");
fflush(stdout);
current--;
pthread_mutex_unlock(&queue_mutex);
return;
}
}

waitingRoom must accept a pointer parameter. See the pthread_create documentation.

Related

How to modify the code so that both threads keep printing the same line, so that the terminal shows ’A’ and ’B’ interleaved

Here is the code that I have so far:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int value = 0;
void *runner(void *param);
int main(){
int pid;
pthread_t tid;
pthread_attr_t attr;
pid = fork();
if (pid == 0) {
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,NULL);
pthread_join(tid,NULL);
printf("A: value = %d\n", value);
}
else if (pid > 0) {
wait(NULL);
printf("B: value = %d\n", value);
}
}
void *runner(void *param){
value = 5;
pthread_exit(0);
}
I have identified the child and parent processes but I am not sure how to make A and B print interleaved.

How to suspend and resume a POSIX thread in C++?

As I came to know creating and terminating thread abruptly
using pthread_kill() everytime is not a good way to do, so I am going
with suspend and resume method for a thread using thread1.suspend() and
thread1.resume(), whenever needed. How to do/implement this?
Take below LED blinking code for reference. During thread1.start() creating thread with suspended = false; is continuing as it is stuck in a while loop.
Calling thread1.suspend() has no effect.
#define on 1
#define off 0
void gpio_write(int fd, int value);
void* led_Flash(void* args);
class PThread {
public:
pthread_t threadID;
bool suspended;
int fd;
pthread_mutex_t m_SuspendMutex;
pthread_cond_t m_ResumeCond;
void start() {
suspended = false;
pthread_create(&threadID, NULL, led_Flash, (void*)this );
}
PThread(int fd1) { this->fd=fd1; }
~PThread() { }
void suspend() {
pthread_mutex_lock(&m_SuspendMutex);
suspended = true;
printf("suspended\n");
do {
pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
} while (suspended);
pthread_mutex_unlock(&m_SuspendMutex);
}
void resume() {
/* The shared state 'suspended' must be updated with the mutex held. */
pthread_mutex_lock(&m_SuspendMutex);
suspended = false;
printf("Resumed\n");
pthread_cond_signal(&m_ResumeCond);
pthread_mutex_unlock(&m_SuspendMutex);
}
};
void* led_Flash(void* args)
{
PThread* pt= (PThread*) args;
int ret=0;
int fd= pt->fd;
while(pt->suspended == false)
{
gpio_write(fd,on);
usleep(1);
gpio_write(fd,off);
usleep(1);
}
return NULL;
}
int main()
{
int fd1=1,fd2=2, fd3=3;
class PThread redLED(fd1);
class PThread amberLED(fd2);
class PThread greenLED(fd3);
redLED.start();
amberLED.start();
greenLED.start();
sleep(1);
redLED.suspend();
return 0;
}
Could some body help me, please?
After a little modification of above code , it seems working . Thanks guy for pointing out issues on above code, the changes are as follow.
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<iostream>
#define on 1
#define off 0
void gpio_write(int fd, int value);
void* led_Flash(void* args);
class PThread {
public:
pthread_t threadID;
volatile int suspended;
int fd;
pthread_mutex_t lock;
PThread(int fd1)
{
this->fd=fd1;
this->suspended =1; //Initial state: suspend blinking untill resume call
pthread_mutex_init(&this->lock,NULL);
pthread_create(&this->threadID, NULL, led_Flash, (void*)this );
}
~PThread()
{
pthread_join(this->threadID , NULL);
pthread_mutex_destroy(&this->lock);
}
void suspendBlink() {
pthread_mutex_lock(&this->lock);
this->suspended = 1;
pthread_mutex_unlock(&this->lock);
}
void resumeBlink() {
pthread_mutex_lock(&this->lock);
this->suspended = 0;
pthread_mutex_unlock(&this->lock);
}
};
void gpio_write(int fd, int value)
{
if(value!=0)
printf("%d: on\n", fd);
else
printf("%d: off\n", fd);
}
void* led_Flash(void* args)
{
PThread* pt= (PThread*) args;
int fd= pt->fd;
while(1)
{
if(!(pt->suspended))
{
gpio_write(fd,on);
usleep(1);
gpio_write(fd,off);
usleep(1);
}
}
return NULL;
}
int main()
{
//Create threads with Initial state: suspend/stop blinking untill resume call
class PThread redLED(1);
class PThread amberLED(2);
class PThread greenLED(3);
// Start blinking
redLED.resumeBlink();
amberLED.resumeBlink();
greenLED.resumeBlink();
sleep(5);
// suspend/stop blinking
amberLED.suspendBlink();
sleep(5);
redLED.suspendBlink();
sleep(5);
amberLED.suspendBlink();
sleep(5);
redLED.resumeBlink();
pthread_exit(NULL);
return 0;
}

Call join child pthread in main function

I have the test code:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
pthread_t th_worker, th_worker2;
void * worker2(void *data) {
for(int i = 0; i< 1000000; i++){
printf("thread for worker2----%d\n", i);
usleep(500);
}
}
void * worker(void *data){
pthread_create(&th_worker2, NULL, worker2, data);
for(int i = 0; i< 100; i++){
printf("thread for worker-----%d\n", i);
usleep(500);
}
}
void join(pthread_t _th){
pthread_join(_th, NULL);
}
In main() function, If I call join(the_worker2):
int main() {
char* str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void*) str);
/* problem in here */
join(th_worker2);
return 1;
}
--> Segment Fault error
Else, i call:
join(the_worker);
join(th_worker2);
---> OK
Why have segment fault error in above case?
Thanks for help !!!
If you posted all your code, you have a race condition.
main is synchronized with the start of worker but not worker2.
That is, main is trying to join th_worker2 before worker has had a chance to invoke pthread_create and set up th_worker2 with a valid [non-null] value.
So, th_worker2 will be invalid until the second pthread_create completes, but that's already too late for main. It has already fetched th_worker2, which has a NULL value and main will segfault.
When you add the join for th_worker, it works because it guarantees synchronization and no race condition.
To achieve this guarantee without the join, have main do:
int
main()
{
char *str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void *) str);
// give worker enough time to properly start worker2
while (! th_worker2)
usleep(100);
/* problem in here */
join(th_worker2);
return 1;
}
An even better way to do this is to add an extra variable. With this, the first loop is not needed [but I've left it in]:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int worker_running;
pthread_t th_worker;
int worker2_running;
pthread_t th_worker2;
void *
worker2(void *data)
{
// tell main we're fully functional
worker2_running = 1;
for (int i = 0; i < 1000000; i++) {
printf("thread for worker2----%d\n", i);
usleep(500);
}
return NULL;
}
void *
worker(void *data)
{
// tell main we're fully functional
worker_running = 1;
pthread_create(&th_worker2, NULL, worker2, data);
for (int i = 0; i < 100; i++) {
printf("thread for worker-----%d\n", i);
usleep(500);
}
return NULL;
}
void
join(pthread_t _th)
{
pthread_join(_th, NULL);
}
int
main()
{
char *str = "hello thread";
pthread_create(&th_worker, NULL, worker, (void *) str);
// give worker enough time to properly start worker2
// NOTE: this not necessarily needed as loop below is better
while (! th_worker2)
usleep(100);
// give worker2 enough time to completely start
while (! worker2_running)
usleep(100);
/* problem in here (not anymore!) */
join(th_worker2);
return 1;
}

crashed when using multiple consumer thread

Only one consumer works fine, but multiple consumers will crash, I am wondering why.
#include <iostream>
#include <string>
#include <vector>
#include <pthread.h>
#include <unistd.h>
#include <queue>
using namespace std;
pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t g_qs_notempty = PTHREAD_COND_INITIALIZER;
pthread_cond_t g_qs_notfull = PTHREAD_COND_INITIALIZER;
queue<string> qs;
void *
producer(void *arg)
{
static vector<string> vs{"a ","b ","c ","d ","e "};
static int idx = 0;
while(1){
pthread_mutex_lock(&g_mutex);
if(qs.size()==5)//full
pthread_cond_wait(&g_qs_notfull,&g_mutex);
qs.push(vs[idx]);
idx = (idx+1)%5;
pthread_cond_signal(&g_qs_notempty);
pthread_mutex_unlock(&g_mutex);
}
return NULL;
}
void *
consumer(void *arg)
{
while(1){
pthread_mutex_lock(&g_mutex);
if(qs.empty())
pthread_cond_wait(&g_qs_notempty,&g_mutex);
cout<<qs.front();
qs.pop();
pthread_cond_signal(&g_qs_notfull);
pthread_mutex_unlock(&g_mutex);
}
return NULL;
}
int main()
{
struct thread_info *tinfo;
pthread_attr_t attr;
pthread_t thread_id;
pthread_attr_init(&attr);
pthread_create(&thread_id, &attr, &producer, 0);
pthread_create(&thread_id, &attr, &consumer, 0);
pthread_create(&thread_id, &attr, &consumer, 0); //adding this line will crash
pthread_exit(0);
}
It is not guaranteed that _signal() wakes up only a single thread.
So you must recheck your condition upon wakeup. A simply way to fix your code is to switch the if for while.

Make thread loop for 5 iterations; pthreads, mutex, and semaphors

I have this code in an example for my class, and the instructions from the teacher say to "make each thread loop for 5 iterations". I am confused as to how to do that, wtih this code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <sys/utsname.h>
/* Symbolic Constants*/
#define NUM_THREADS 4
#define BUFFER_SIZE 10
/* Semaphore and Mutex lock */
sem_t cEmpty;
sem_t cFull;
pthread_mutex_t mutex;
/* Threads */
pthread_t tid; /* Thread ID */
pthread_attr_t attr; /* Thread attributes */
//prototypes
void *producer(void *param);
void *consumer(void *param);
int insert_item(int threadID);
int remove_item(int threadID);
void init();
/* Progress Counter and Thread IDs*/
int counter, pthreadID=0, cthreadID=0;
int main()
{
/* Variables */
int c1;
/* Perform initialization */
init();
/* Create the producer threads */
for(c1=0; c1<NUM_THREADS; c1++)
{
pthread_create(&tid, &attr, producer, NULL);
}
/* Create the consumer threads */
for(c1=0; c1<NUM_THREADS; c1++)
{
pthread_create(&tid, &attr, consumer, NULL);
}
/* Ending it */
sleep(2);
printf("All threads are done.\n");
/* Destroy the mutex and semaphors */
pthread_mutex_destroy(&mutex);
sem_destroy(&cEmpty);
sem_destroy(&cFull);
printf("Resources cleaned up.\n");
exit(0);
}
void init()
{
pthread_mutex_init(&mutex, NULL); /* Initialize mutex lock */
pthread_attr_init(&attr); /* Initialize pthread attributes to default */
sem_init(&cFull, 0, 0); /* Initialize full semaphore */
sem_init(&cEmpty, 0, BUFFER_SIZE); /* Initialize empty semaphore */
counter = 0; /* Initialize global counter */
}
void *producer(void *param)
{
int x;
for(x=0; x<5;)
{
sleep(1);
sem_wait(&cEmpty); /* Lock empty semaphore if not zero */
pthread_mutex_lock(&mutex);
if(insert_item(pthreadID))
{
fprintf(stderr, "Producer error.");
}
else
{
pthreadID++;
x++;
}
pthread_mutex_unlock(&mutex);
sem_post(&cFull); /* Increment semaphore for # of full */
}
return 0;
}
void *consumer(void *param)
{
int y;
for(y=0; y<5;)
{
sleep(1);
sem_wait(&cFull); /* Lock empty semaphore if not zero */
pthread_mutex_lock(&mutex);
if(remove_item(cthreadID))
{
fprintf(stderr, "Consumer error.");
}
else
{
cthreadID++;
y++;
}
pthread_mutex_unlock(&mutex);
sem_post(&cEmpty); /* Increments semaphore for # of empty */
}
return 0;
}
int insert_item(int threadID)
{
if(counter < BUFFER_SIZE) /* Buffer has space */
{
counter++;
printf("Producer %d inserted a cookie. Total:%d\n", threadID, counter);
return 0;
}
else /* Buffer full */
{
return -1;
}
}
int remove_item(int threadID)
{
if(counter > 0) /* Buffer has something in it */
{
counter--;
printf("Consumer %d removed a cookie. Total:%d\n", threadID, counter);
return 0;
}
else /* Buffer empty */
{
return -1;
}
}
Anyone have any idea of where I add my for loop to "make each thread loop for 5 iterations"? Thank you so much in advanced.
UPDATE: I changed the while(1) to a for loop with 5 iterations, but I still cant get the messages from the insert_item and remove_item functions to print 5 times, the only print once. Anyone know how I can get it to print 5 times?
The problem was that at the end of main, I call sleep(2). This is not enough time for all of the threads to print their output. I was also not passing the right index to my add_item and remove_item functions. In addition, I needed a join command for all of the threads rather than the sleep command, and the join command ensures that all of the threads finish before the program exits. Here is the updated and corrected code. Hope this helps someone trying to do something similar!
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <sys/utsname.h>
// Symbolic Constants
#define NUM_THREADS 4
#define BUFFER_SIZE 10
// Semaphore and Mutex lock
sem_t cEmpty;
sem_t cFull;
pthread_mutex_t mutex;
// Threads
pthread_t tid[NUM_THREADS]; //Thread ID
pthread_t tid2[NUM_THREADS]; //Thread ID
pthread_attr_t attr; //Thread attributes
//prototypes
void *producer(void *param);
void *consumer(void *param);
int insert_item(long threadID);
int remove_item(long threadID);
void init();
//Progress Counter and Thread IDs
int counter=0;
int main()
{
//Variables
long c1;
//Perform initialization
init();
//Create the producer threads
for(c1=0; c1<NUM_THREADS; c1++)
{
pthread_create(&tid[c1], &attr, producer, (void *)c1);
pthread_create(&tid2[c1], &attr, consumer, (void *)c1);
}
//Ending it
for(c1=0; c1<NUM_THREADS; c1++)
{
pthread_join(tid[c1], NULL);
pthread_join(tid2[c1],NULL);
}
printf("All threads are done.\n");
//Destroy the mutex and semaphors
pthread_mutex_destroy(&mutex);
sem_destroy(&cEmpty);
sem_destroy(&cFull);
printf("Resources cleaned up.\n");
exit(0);
}
//This function performs initialization
void init()
{
pthread_mutex_init(&mutex, NULL); //Initialize mutex lock
pthread_attr_init(&attr); //Initialize pthread attributes to default
sem_init(&cFull, 0, 0); //Initialize full semaphore
sem_init(&cEmpty, 0, BUFFER_SIZE); //Initialize empty semaphore
counter = 0; //Initialize global counter
}
//This function creates the producer thread
void *producer(void *param)
{
long index = (long)param;
for(int x = 0; x<5; x++)
{
sleep(1);
sem_wait(&cEmpty); //Lock empty semaphore if not zero
pthread_mutex_lock(&mutex);
//check to see if item inserted correctly; print error on fail
if(insert_item(index))
{
fprintf(stderr, "Producer error.");
}
pthread_mutex_unlock(&mutex);
sem_post(&cFull); //Increment semaphore for # of full
}
pthread_exit(NULL);
return 0;
}
//This function created the consumer thread
void *consumer(void *param)
{
long index = (long)param;
for(int x = 0; x<5; x++)
{
sleep(1);
sem_wait(&cFull); //Lock empty semaphore if not zero
pthread_mutex_lock(&mutex);
//print error if cookie not decremented correctly
if(remove_item(index))
{
fprintf(stderr, "Consumer error.");
}
pthread_mutex_unlock(&mutex);
sem_post(&cEmpty); //Increments semaphore for # of empty
}
pthread_exit(NULL);
return 0;
}
//Insert item function to increment the cookie count and print thread message
int insert_item(long threadID)
{
if(counter < BUFFER_SIZE) //Buffer has space
{
counter++;
printf("Producer %ld inserted a cookie. Total:%d\n", threadID, counter);
return 0;
}
else //Buffer full
{
return -1;
}
}
//Remove item function to decrement the cookie count and print thread message
int remove_item(long threadID)
{
if(counter > 0) //Buffer has something in it
{
counter--;
printf("Consumer %ld removed a cookie. Total:%d\n", threadID, counter);
return 0;
}
else //Buffer empty
{
return -1;
}
}