Unable to create pthread for function in C - c

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;
}

Related

Pthread create is not starting the thread

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.

How to get the id of a pthread which is given when it is created?

When creating an pthread, pthread_create() is used. First parameter of this function is thread_id.
I tried to access this value pthread_self() but this gives something very big and not the numbers I gave while creating.
Is there a way to access this value?
for(int i = 0; i < necessaryThreadCount; i++){
pthread_create(&threadIDs[i], NULL, theFunction, (void*)&requiredStructre[i]);
}
my question is, how can i access the value of given threadID inside theFunction?
Solution:
I just added another variable to the struct I pass as parameter.
First parameter is pointer to thread_id which you need to declare first.
ID will get assigned after you create thread using pthread_create(). refer the below:
int main()
{
pthread_t thread; // declare thread
pthread_create(&thread, NULL, func, NULL);
printf("the thread id = %d\n", thread);
}
thread_id is for the new thread that is created. if you execute pthread_self() in the current thread it returns a different value from the newly created thread.
Hope the below example may help you to understand thread id creation:
[NOTE: not a good idea to have global pthread_t declared]
Example:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_t ctid;
void* thread_function(void* arg)
{
printf("Inside the thread\n");
printf("ctid: %ld, self: %ld", ctid, pthread_self());
// exit the current thread
pthread_exit(NULL);
}
void createthread()
{
pthread_create(&ctid, NULL, &thread_function, NULL);
printf("This line may be printed"
" before thread terminates\n");
// Waiting for the created thread to terminate
pthread_join(ctid, NULL);
pthread_exit(NULL);
}
// Driver code
int main()
{
createthread();
return 0;
}

While loop within thread is causing program to block (C)

The point of threads is to be able to run multiple blocks of code at once. The first thing I think of when this possibility comes into my head is having two infinite loops running at once. Before I tried to get this working with two threads, I tried to get it to work with one, with no success.
So I have a thread like this:
void *myThread(void *args) {
sleep(0.1);
while (1) {
}
return NULL;
}
And I am creating the thread like so:
pthread_t thread_id;
printf("Before Thread\n");
pthread_create(&thread_id, NULL, myThread, args);
pthread_join(thread_id, NULL);
printf("After Thread\n");
When I run this, "After Thread" does not print! Why is this happening? This makes no sense to me.
Because pthread_join(thread_id, NULL); waits for the thread to finish. And a thread running a while (1) {} loop will never finish.

Pthread Run a thread right after it's creation

I have a C program in which I use pthread.
I would like newly created threads to run as soon as they are created.
The reason behind this is that my threads have initialisation code to set up signal handlers, and I must be sure the handlers are ready, before my main thread sends some signals.
I've tried doing pthread_yield just after my pthread_create, but without success.
I doubt it makes a difference, but I am running Linux 3.6 on x86_64.
Thanks
If your goal is to have the main thread wait for all threads to reach the same point before continuing onward, I would suggest using pthread_barrier_wait:
void worker(void*);
int main(int argc, char **argv)
{
pthread_barrier_t b;
pthread_t children[TCOUNT];
int child;
/* +1 for our main thread */
pthread_barrier_init(&b, NULL, TCOUNT+1);
for (child = 0; child < TCOUNT; ++child)
{
pthread_create(&children[child], NULL, worker, &b);
}
printf("main: children created\n");
/* everybody who calls barrier_wait will wait
* until TCOUNT+1 have called it
*/
pthread_barrier_wait(&b);
printf("main: children finished\n");
/* wait for children to finish */
for (child = 0; child < TCOUNT; ++child)
{
pthread_join(&children[child], NULL);
}
/* clean-up */
pthread_barrier_destroy(&b);
return 0;
}
void worker(void *_b)
{
pthread_barrier_t *b = (pthread_barrier_t*)_b;
printf("child: before\n");
pthread_barrier_wait(b);
printf("child: after\n");
}
Or you might use a barrier, i.e. call pthread_barrier_wait (early in the routine of each thread, or at initialization in the main thread), to ensure that every relevant thread has reached the barrier (after which some of your threads could do your naughty signal tricks). See this question.

thread termination issue (c programming)

I'm working on an application for Linux in C which uses multiple threads. The threads which are spawned by the main function do most of the work, and therefore usually finish last. I'm seeing some strange behavior, and I believe it's due to the main thread terminating before the spawned threads have a chance to finish their jobs. Here's some sample code to illustrate what I'm talking about:
#define _POSIX_C_SOURCE 200112L
#define _ISOC99_SOURCE
#define __EXTENSIONS__
#define _GNU_SOURCE
#include <pthread.h>
#include <stdio.h>
void
my_cleanup(void *arg)
{
printf("cleanup: %s\n", (char *)arg);
}
void *
thread_stuff(void *arg)
{
printf("thread started\n");
pthread_cleanup_push(cleanup, "running");
if (arg)
pthread_exit((void *)2);
pthread_cleanup_pop(0);
pthread_exit((void *)2);
}
int
main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
return SUCCESS;
}
When this code is run, the message from the cleanup function is printed twice, as it should be, but other times when it is run, I see the message printed only once sometimes, and other times I see it printed three times or not at all. You add in the sleep function in the main function to play with how long it takes the main function to terminate.
What can I do to make the program run as it should? I suspect it has something to do with joining to the children, but I don't entirely understand the concept of a join or how to apply it to this situation.
Thanks in advance!
Yes, you should "join" the threads. "Joining" a thread simply means waiting until the thread has terminated. In other words, you would do
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
to wait until both threads have terminated.
Edit: What to do if you have a child thread which, in turn, creates a "grandchild" thread? As a rule, whoever created the thread should wait for it to terminate ("join" it). So in this scenario, the child thread would call phtread_join on the grandchild thread, and the main thread would call join on the child thread.
I think you want to run pthread_join on each of the threads when your main thread completes -- this makes the main thread stop until the given thread finishes running. Other threads can still complete first though, so running pthread_join on every thread will prevent the main thread from terminiating until all of the others have terminated.
There is a definite problem if main() finishes before the threads it spawned if you don't call pthread_exit() explicitly. All of the threads it created will terminate because main() is done and no longer exists to support the threads.
By having main() explicitly call pthread_exit() as the last thing it does, main() will block and be kept alive to support the threads it created until they are done.
int main()
{
int err;
pthread_t tid1, tid2;
err = pthread_create(&tid1, NULL, thread_stuff, (void *)1);
err = pthread_create(&tid2, NULL, thread_stuff, (void *)1);
sleep(10); /* change the value here if you want */
/* Add the pthread_exit */
pthread_exit(NULL);
return SUCCESS;
}
Refer for more info here

Resources