I have used the following code to create two threads:
//header files
#include <pthread.h>
struct thread_arg
{
int var1;
int var2;
};
void *serv_com(void *pass_arg)
{
struct thread_arg *con = pass_arg;
//required statements irrelevant to the issue
pthread_exit(NULL);
}
void *cli_com(void *pass_arg)
{
struct thread_arg *con = pass_arg;
//required statements irrelevant to the issue
pthread_exit(NULL);
}
int main()
{
pthread_t inter_com;
//necessary code
while(1)
{
th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
th_err_c = pthread_create(&inter_com, NULL, cli_com, (void *)&pass_arg);
if (th_err_s || th_err_c)
{
printf("Alert! Error creating thread! Exiting Now!");
exit(-1);
}
}
pthread_exit(NULL);
return 1;
}
Then I compiled the above code in linux using the following command:
gcc -o sample sample.c
It returned the following error message:
inter.c:(.text+0x374): undefined reference to `pthread_create'
inter.c:(.text+0x398): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
What should I do to correctly compile this file. I am sure it is no syntax error or anything since when I commented off everything inside the while loop, the program was compiling correctly and I verified that the pthread_create syntax is correct. Do I have to issue some other command to compile the file?
EDIT: Is there any problem with the creating of two threads in the above code? The program is just exiting with the error message once it is running. What can be the possible issue and how can I solve it? Thanks in advance.
Try doing this :
gcc -lpthread sample.c
or
gcc -pthread sample.c
above 2 commands will directly create executable a.out
Answer after edit:
1) Wait for the two threads to join main thread using call
int pthread_join(pthread_t thread, void **value_ptr);
2) Create both threads with different ids
3) Also avoid calling pthread_exit from main() if you can, although there is no harm doing that
4) you are calling pthread_create in while(1) this will create infinite threads .. I do not know what are you trying to achieve .
Link to pthread Library when compiling...
gcc -o sample -lpthread sample.c
I am not too sure myself but I would think you could do something like
pthread_t inter_com, inter_com2;
and
th_err_s = pthread_create(&inter_com, NULL, serv_com, (void *)&pass_arg);
th_err_c = pthread_create(&inter_com2, NULL, cli_com, (void *)&pass_arg);
I think it should give you 2 ids of threads. But careful when sharing variables etc between threads. But am glad you resolved it yourself.
Related
I am trying to make sense of a program:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int main(int argc, char** argv) {
volatile double fShared = 0.0;
// create pthread structures - one for each thread
pthread_t t0;
pthread_t t1;
//Arbitrary pointer variables - void* is a pointer to anything
void *thread_res0;
void *thread_res1;
int res0,res1;
//create a new thread AND run each function
// we pass the ADDRESS of the thread structure as the first argument
// we pass a function name as the third argument - this is known as a FUNCTION pointer
// you might want to look at the man pages for pthread_create
res0 = pthread_create(&t0, NULL, do_this, (void*)"");
res1 = pthread_create(&t1, NULL, do_that, (void*)"");
// Two threads are now running independently of each other and this main function
// the function main is said to run in the main thread, so we are actually running
// The main code can now continue while the threads run - so we can simply block
res0 = pthread_join(t0, &thread_res0);
res1 = pthread_join(t1, &thread_res1);
printf ("\n\nFinal result is fShared = %f\n",fShared);
return (EXIT_SUCCESS);
}
It should be noted that do_this and do_that are functions created earlier in the program. I am getting the following errors:
seed#ubuntu:~/Programs$ Homework2OS.c
/tmp/cceiRtg8.O: in function 'main'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_create'
Undefined reference to 'pthread_join'
Undefined reference to 'pthread_join'
We were given this bit of code to fix. I have found elsewhere the format for the pthread_create constructor. Do I need to actually define it above the main? I was under the impression it was imported with the library.
I would also venture to guess that it has something to do with the fourth parameter? I understand that the first parameter is the location of the thread (defined above), the second is NULLed, the third is the function call but I do not quite understand what the fourth parameter is supposed to be.
What's wrong?
all the code imports is the header for the pthread library. (pthread.h)
What is missing is the linker needs to actually include the library for gcc the parameter -pthread is needed (AT THE END of the list of parameters to gcc.)
It needs to be at the end because the linker processes parameters in the order given on the command line and if the object files are not already processed, then there will not be any unresolved references for the linker to try to resolve via browsing the pthread library.
I.E. this is wrong:
gcc -g -o myprogram -lpthread myprogram.o
This is correct:
gcc -g -o myprogram myprogram.o -lpthread
Having a Major issue with trying to do a multi-threading project for school
I'm just trying to run sample code to see how pthreads work
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum;
void *runner(void *param);
int main(int argc, char *argv[]) {
pthread_t tid;
pthread_attr_t attr;
if (argc !=2){
fprintf(stderr, "usage: a.out <interger value>\n");
return -1;
}
if (atoi(argv[1]) < 0) {
fprintf(stderr, "%d must be >= 0\n",atoi(argv[1]));
return -1;
}
pthread_attr_init(&attr);//get default attributes
pthread_create(&tid,&attr,runner,argv[1]);//create the thread
pthread_join(tid,NULL);//wait for the thread to exit
printf("sum = %d\n",sum);
}
void *runner(void *param) {
int i, upper = atoi(param);
sum = 0;
for (i =1; i <= upper; i++) {
sum += i;
}
pthread_exit(0);
}
And no matter what I do I can't get the code to compile. I get the following error:
Running "/home/ubuntu/workspace/primefactor/assn3.c"
/tmp/cc58AE5c.o: In function 'main':
assn3.c:(.text+0xc4): undefined reference to 'pthread_create'
assn3.c:(.text+0xd5): undefined reference to 'pthread_join'
collect2: error: ld returned 1 exit status
Process exited with code: 1
I've tried writing my own makefile with the -pthread flag; didn't work....
I've tried running
sudo apt-get install libpthread-stubs0-dev
to install the right library; didn't work...
I'm at my wits end to try and get pthreads_create() and pthreads_join() to work and they're the main requirement for my school project. I've already gotten the project working with a normal C program (take numbers from the command line, get the prime factors for each arg, store them in an array, then pass that array and display the results. ex: ./prime.c.o {1..100} would be run from BASH and it outs 1:1 2: 2 3: 3 4: 2 2 etc...
so that's what the output is supposed to be and I'm supposed to do that with threading, but I can't do that if I can't even compile sample code to see how threads work.
I really have already spent several hours searching, trying, but no luck getting rid of these undefined reference errors for pthread_create() and pthread_join() . Any help would be greatly appreciated in figuring out why I get the above errors.
Edit:
Thanks to those that tried answering for me. I don't know why I got the down vote; I'm not very active here and I do try to be polite when asking for help. Anyways I finally figured it out.
If I am using the make file it had to look like this:
assn3:
gcc -g -Wall -pthread assn3.c -o assn3
Then from the command line: make assn3
It appears you haven't specified to the linker about thread library. For multithreading applications, the usual option for gcc is follows (assume your program file name thread1.c):
gcc -D_REENTRANT -lpthread thread1.c -o thread1
It's also recommended to use -Wall -O3 -pedantic-errors to be pedantic about compiler warnings etc. So this should do:
gcc -Wall -O3 -pedantic-errors -D_REENTRANT -lpthread thread1.c -o thread1
i was trying to learn multithreading program in c and got a linker error which I am not able to solve I have checked the previous problem similar to this but those solutions could not solve my problem.
error :
single_thread.c:(.text+0x15)undefined reference to 'thread_function'
collect2:ld returned 1 exit status
I have checked the typo's
the program goes like this
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
void *thread_functions(void *arg);
char message[]="Hello world";
int main()
{
int res;
pthread_t a_thread;
void *thread_res;
res=pthread_create(&a_thread,NULL,thread_functions,(void*)message);
//i guess error is from the function pointer.
if(res!=0)
{
perror("thread creation:");
exit(EXIT_FAILURE);
}
printf("waiting for thread to finish...\n");
pthread_join(a_thread,NULL);
/* if(res!=0)
{
perror("thread_join failed:");
exit(EXIT_FAILURE);
}*/
// printf("thread joined,it has returned %s\n",(char*)thread_res);
printf("Message:%s\n",message);
exit(EXIT_SUCCESS);
}
void *thread_fucntions(void *arg)
{
printf("thread function is running.argument was %s\n",(char*)arg);
sleep(3);
strcpy(message,"BYE!");
pthread_exit("thank you for the cpu time");
}
You need to name the functions exactly the same as forward declaration and definition time. Your compiler sees the forward declaration of the function thread_functions() and the call to it, but during the linking time, linker does not get to see a definition of the same, as you're having a typo there. So it screams.
Change
void *thread_fucntions(void *arg)
to
void *thread_functions(void *arg)
You need to compile like this
gcc single.thread.c -lpthread
Typo
void *thread_fucntions(void *arg)
^^
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
undefined reference to pthread_create in linux (c programming)
I am trying to implement Thread chain in Ubuntu in C. When I compile the following code, I get the errors of Undefined reference to these thread library function even though I have added the header file.I am also getting segmentation fault error. Why is that? I am not accessing some uninitialized memory anywhere in program. Here is the code:
#include <stdio.h>
#include<stdlib.h>
#include <pthread.h>
void* CreateChain(int*);
int main()
{
int num;
pthread_t tid;
scanf("Enter the number of threads to create\n %d",&num);
pthread_create(&tid,NULL,CreateChain,&num);
pthread_join(tid,NULL);
printf("Thread No. %d is terminated\n",num);
return 0;
}
void* CreateChain(int* num )
{
pthread_t tid;
if(num>0)
{
pthread(&tid,NULL,CreateChain,num);
pthread_join(tid,NULL);
printf("Thread No. %d is terminated\n",*num);
}
else
return NULL;
return NULL;
}
I am getting following warnings and the Scanf prompt is not appearing for some reason.
Regards
The pthread.h header file provides a forward declaration of pthread functions. This tells the compiler than these functions exist and have a certain signature. It doesn't however tell the linker anything about where to find these functions at runtime.
To allow the linker to resolve these calls (decide where to jump to inside your code or in a different shared object), you need to link against the appropriate (pthread) library by adding
-pthread
to your build command line.
[Note that it is also possible to use -lpthread. This previous question expains why -pthread is preferable.]
There are various other issues with the code that will be worthy of attention
The scanf line should be split into printf("Enter number of threads\n");scanf("%d", &num); to get the user prompt displayed
The signature of CreateChain is wrong - it should take a void* argument instead. You can always do something like int num = *(int*)arg; inside the function to retrieve the number of threads.
The logic inside CreateChain looks wrong. You currently compare a pointer against 0 - I presume you mean to compare the number of threads instead? Also, if you don't decrement the number of threads to create somewhere, you'll end up with code that creates threads forever (or until you run out of handles depending on how the different threads get scheduled).
Try compiling like this below :
gcc -Wall -pthread test.c -o test.out
-pthread is an option to tell linker explicitly to resolve the symbols related to <pthread.h>
add -lpthread
gcc -o test test.c -lpthread
I'm trying the code from Tanenbaum's 3e "Modern Operating Systems" and I get compiler errors and warnings:
$ LANG=en_US.UTF-8 cc thread.c
thread.c: In function ‘main’:
thread.c:19:63: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
thread.c:25:1: warning: passing argument 1 of ‘exit’ makes integer from pointer without a cast [enabled by default]
/usr/include/stdlib.h:544:13: note: expected ‘int’ but argument is of type ‘void *’
/tmp/ccqxmMgE.o: In function `main':
thread.c:(.text+0x57): undefined reference to `pthread_create'
collect2: ld returned 1 exit status
This is the code I'm trying
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUMBER_OF_THREADS 10
void *print_hello_world(void *tid)
{
//printf("Hello World. Greetings from thread %d0", tid);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t threads[NUMBER_OF_THREADS];
int status, i;
for(i=0; i<NUMBER_OF_THREADS; i++) {
//printf("Main here creating thread %d0", i);
status = pthread_create(&threads[i], NULL, print_hello_world, (void *)i);
if (status != 0) {
//printf("Oops. pthread_create returned error code %d0", status);
exit(-1);
}
}
exit(NULL);
}
Can you help me improve the state of the code so that it will run? There appears to be some errata since the exact code from the book doesn't compile. Thanks
Please link to pthread library, by specifying -lpthread option to your linker.
Also, you should be using pthread_join to wait for all the created threads to complete.
$gcc thread.c -lpthread
This is to link the pthread shared library.
1) You have to link to libpthread to get rid of the linker error:
gcc ..... -lpthread
(note that the -lpthread option must be the last one)!
2) exit(NULL); is wrong; NULL is for pointer types whereas exit wants an int to be supplied; use simply
exit(0);
instead.
The other warnings are just system-dependent pointer and integer size warnings; they can safely be ignored in most cases.
Pl. do not use the exit statement in your main function in this case, since the main may get exited and your threads also will terminate and you may not get the outputs of the print statement in the thread function.
Pl. use pthread_exit instead of exit in main so that even your main thread terminates the other threads can continue.