I'm trying to create several thread workers in a function called engine_setup, but every time the function returns, every thread stops as well. I tried to create pthread id as global pointer but didn't help.
here's the global:pthread_t * threadIDs;
the engine_setup function:
query_helper* engine_setup(size_t n_processors) {
//some code that is not relevant
int err;
threadIDs=malloc(n_processors*sizeof(*threadIDs));
for(int i=0;i<n_processors;i++){
err = pthread_create(&threadIDs[i],NULL,tp,(void*)helper);
if (err != 0)
printf("can't create thread \n");
}
printf("end setup\n");
return helper;
}
and the thread function pointer is here:
void* tp(void * ptr){
query_helper * helper=(query_helper*)ptr;
while(1){
printf("1\n");
}
}
the output is something like this:
1
1
1
1
1
1
1
1
1
end setup
which shows that all the threads stopped when engine_setup return. Is there a way to keep them running?
Does your program exit after the function returns? If so you'd want to use pthread_join on each thread so that the program will wait for each thread to terminate before exiting.
Yes, you can call pthread_join(threadIds[i],null); (for all threads i), which will wait until the thred function returns.
You can use the second argument for storing return value from thread.
I.e:
void *results[n_processors];
for(int i=0; i<n_processors; i++){
pthread_join(threadIds[i], &results[i]);
}
Related
I’m using pthread to start a thread, but the create function itself is not starting the thread
But instead if i call pthread join, it starts so actually should i call p thread join?
i heard from some answers that pthread join is not required , my pthread create function is called from main
int main(void) {
printf("-----------Welcome------\n");
Start_Generation();
return 0;
}
int Start_Generation(void)
{
ret=pthread_create(&C_AO_GENERATION_THREAD, NULL, C_Aogeneration_thread,(void*) message1);
if(ret!=0)
{
printf("Error Starting Thread\n");
return -1;
}
else
{
printf("AO Thread Started\n");
}
//ret=pthread_join(C_AO_GENERATION_THREAD, NULL);
return 0;
}
void *C_Aogeneration_thread (void *ptr)
{
char *message;
message = (char *) ptr;
unsigned int prof_gen_count;
unsigned int written_sample=0;
unsigned int curr_idx=0;
int ch=0;
int written=0;
printf("%s",message);
printf(" Generation Started\n");
prof_gen_count=(samplingrate/10);
while(stopflag)
{
printf("Thread is working\n");
}
return 0;
}
enter code here
I’m using pthread to start a thread, but the create function itself is not starting the thread
As presented in the question, your main thread terminates by returning from main immediately after reporting on the success or failure of the pthread_create() call, so
the whole program terminates at that point, apparently before the child progresses far enough to present any evidence that it is running, but also
there is no point in using a separate thread.
But instead if i call pthread join, it starts so actually should i call p thread join?
A call to pthread_join() does not return successfully until the specified thread has terminated. That is, in fact, its purpose. As a rule of thumb, you should either join or detach every thread you create. Joining is usually what you want, and note, too, that detaching a thread does not prevent the process from terminating and taking that thread with it when the main thread returns or exit()s.
Am new to C, am trying to create thread using below code but i unable to create thread, Can any one tell me where i am going wrong...
It is not going into 'if' loop and not calling 'myfunction'
void *myfunction() {
//my code
}
void createThreadForMyFunction(void) {
pthread_t thread_ID;
if(pthread_create(&thread_ID, NULL, myfunction, NULL)) {
printf("pthread_create");
}
}
pthread_create returns 0 on success. So you could add ! to your if statement or do something like:
if (pthread_create...) {
perror("CREATE");
return;
}
/* other code */
To make the main function wait child with id threadID you also may just do pthread_join(threadID, NULL); after thread creation without using sleep and friends.
Read.
Return value of pthread_create is an int that is 0 on success. So if you are not entering in your if function, it is because your thread was successfully created.
So your function myFunction is actually called, in your new thread.
Note that if your main thread (the one executing createThreadForMyFunction) end too quickly, it kills the child thread (the one executing myFunction) before it prints anything, and you won't see if your thread was successfully created. Try to add a usleep after the thread creation in order to give some time to your new thread to show itself.
Try it:
void* myfunction(void *arg)
{
// do somthing
}
int main(void)
{
pthread_t thread_ID;
int err;
err = pthread_create(&thread_ID, NULL, &myfunction, NULL);
if (err != 0)
printf("\ncan't create thread :[%s]", strerror(err));
else
printf("\n Thread created successfully\n");
}
sleep(5);
return 0;
}
I am trying to write a C program that makes use of pThreads. This particular program creates multiple threads (1 to maxNumber) and does something with them (in the method threadMethod). I pass a struct Arguments to the pThread creator that contains necessary information about the threads, and threadNumber is included in that struct. I am trying to make the program print which thread is doing work at that moment, but when I run the program, it always prints maxNumber instead of threadNumber. For example, if I want to make 3 threads, I should have an output like:
I am thread 1
I am thread 2
I am thread 3
But instead of the above, I get an output like:
I am thread 3
I am thread 3
I am thread 3
What is going wrong with my program? I have a feeling it has something to do with the struct, but I am not certain. Below is the relevant code.
Arguments *arg = malloc(sizeof(Arguments));
int i;
for (i = 0; i < maxNumber; i++) {
arg->threadNumber = (i + 1); /* eg. first thread is Thread 1, not Thread 0 */
if (pthread_create(&threads[i], NULL, threadMethod, (void *)arg)) {
printf("Error while creating thread\n");
return 1;
}
}
--------------------
void *threadMethod(void *arg) {
Arguments *argument;
int threadNumber;
argument = (Arguments*)arg;
threadNumber = argument->threadNumber;
printf("I am thread %d\n", threadNumber);
/* do stuff */
return NULL;
}
All your threads are sharing a single arg object, because you are only allocating it once. Move the malloc() inside the loop.
I have a question about pthreads whith this little C source:
int calc = 0;
void func(void* data){
calc = 2 * 2;
return NULL;
}
int main(){
pthread_t t;
if(0==pthread_create(&t,NULL,func,NULL)){
if(0==pthread_join(t,NULL)){
printf("Result: %d\n",calc); // 4 ?
}
}
}
If pthread_join return success, is "func" always executed entirely ? (calc always equal 4 on printf ?).
The function pthread_join returns zero on success.
The documentation says that pthread_join blocks until the thread ends, so, with some applied logic one can easily conclude that the thread has ended.
On the other side, pthread_join fails in different ways:
When the handle is invalid: EINVAL
When a deadlock has been detected: EDEADLK
There is another possible error (recommended by the open group, but depending on the implementation): ESRCH, when it detects that the thread handle is being used past the end of the thread.
If you want to know more you may want to take a look at the documentation.
How can I exit or stop a thread immediately?
How can I make it stop immediately when the user enters an answer?
I want it to reset for every question.
Here's my code where threading is involved
int q1() {
int timer_start;
char ans[] = "lol";
char user_ans[50];
timer_start = pthread_create( &xtimer,NULL,(void*)timer_func,(void*)NULL);
printf("What is the capital city of Peru?\n");
while(limit){
scanf("%s",user_ans);
if(limit)
{
if(!strcmp(user_ans, ans))
{
// printf("YAY!\n");
score++;
// q2();
}
else
{
game_over();
}
}
}
}
You can simply call pthread_cancel on that thread to exit it. And you can send SIGSTOP/SIGCONT signal via pthread_kill to stop/restart it.
But if all you want is a timer, why must you thread?
Based on your code I can give a simple answer:
In this case do not use threads at all.
You do not need them. Store the start time, let the user answer, check the time again after user gives an answer.
{
time_t startTimeSec = time(NULL);
// answering
time_t endTimeSec = time(NULL);
time_t timeTakenSec = endTime-startTime;
if (timeTaken > 10) {
// do your thing
}
}
To answer your question:
You should use a mutex-protected or volatile variable to asynchronously communicate between threads. Set that variable from one thread and check it in another. Then reset its value and repeat. A simple snippet:
int stopIssued = 0;
pthread_mutex_t stopMutex;
int getStopIssued(void) {
int ret = 0;
pthread_mutex_lock(&stopMutex);
ret = stopIssued;
pthread_mutex_unlock(&stopMutex);
return ret;
}
void setStopIssued(int val) {
pthread_mutex_lock(&stopMutex);
stopIssued = val;
pthread_mutex_unlock(&stopMutex);
}
Using pthread_cancel() is an option, but I would not suggest doing it. You will have to check the threads state after this call returns, since pthread_cancel() does not wait for the actual thread stop. And, which to me is even more important, I consider using it ugly.
Using methods to stop a thread is a brute way.
You should rather politely ask the thread to stop by signalling.
Thereby the thread will have an option to tidy after itself e.g. if it has allocated memory, which it will not have any opportunity to do if the thread is cancelled.
The method is relatively simple and comprises no OS signalling:
define a thread state variable or structure outside the thread. Point to it at the pthread_create and dereference the state variable in the thread.
int thread_state = 0; // 0: normal, -1: stop thread, 1: do something
static void *thread_1 (void *arg)
{
int* pthread_state = arg;
... // initialize the thread locals
while(1)
{
switch( *pthread_state )
{
case 0: // normal thread loop
...
break;
case -1:
... // tidy or whatever is necessary
pthread_exit(0); // exit the thread signalling normal return
break;
case 1: //
... // do something special
break;
}
}
}
pthread_create (&t_1, NULL, thread_1, (void*)&thread_state);
...
thread_state = -1; // signal to the thread to stop
// maybe use pthread_exit(0) to exit main.
// this will leave the threads running until they have finished tidy etc.
It is even possible to communicate with the thread using a structure provided that it is simple 'atomic' variables or a simple handshake mechanism is established. Otherwise it may be necessary to use mutex.
Use pthread_join to wait for threads to terminate.
#Naruil's suggestion to call pthread_cancel() is pretty much the best solution i found, but it won't work if you didn't do the following things.
According to the man-page of pthread_cancel the pthread_cancelibility depend on two thing
thread_cancel_state.
thread_cancel_type.
thread_cancel_state is PTHREAD_CANCEL_ENABLE by default, so our main concern is about the thread_cancel_type, it's default value is type PTHREAD_CANCEL_DEFFERED but we need PTHREAD_CANCEL_ASYNCHRONOUS to set on that thread, which we wan't to cancel.
Following an example given::
#include <stdio.h>
#include <pthread.h>
void *thread_runner(void* arg)
{
//catch the pthread_object as argument
pthread_t obj = *((pthread_t*)arg);
//ENABLING THE CANCEL FUNCTIONALITY
int prevType;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &prevType);
int i=0;
for( ; i < 11 ; i++)//1 - > 10
{
if(i == 5)
pthread_cancel(obj);
else
printf("count -- %d", i);
}
printf("done");
}
int main(int argc, char *argv[])
{
pthread_t obj;
pthread_create(&obj, NULL, thread_runner, (void*)&obj);
pthread_join(obj, NULL);
return 0;
}
run it using gcc filename.c -lpthread and output the following::
count -- 0
count -- 1
count -- 2
count -- 3
count -- 4
note that the done is never printed because the thread was canceled when the i became 5 & the running thread was canceled. Special thanks #Naruil for the "pthread_cancel" suggestion.