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
Related
I'm trying to print infinite lines "Hello, how are you", "I'm fine, and you"
first I use command "vim ex_thread_creation"
then I enter following the code:
#include <pthread.h>
#include <stdio.h>
void *thread_print(void * messenge)
{
while(1) {
printf("Hello, How are you?\n");
}
}
int main()
{
pthread_t idthread;
pthread_create( &idthread,NULL, &thread_print, NULL);
while(1) {
printf("I’m fine, and you?\n");
}
return 0;
}
then I use gcc ex_thread_creation.c -pthread ex_thread_creation
then I meet the error: no such file or directory ex_thread_creation.
someone help me, please
edit 1: after I change -pthread to -o I meet another error: ex_thread_creation.c:(.text+0x4a): undefined reference to pthread_create collect2: error: old returned 1 exit status
There are several problems with your approach.
Regarding your gcc issue, the correct command would be:
gcc ex_thread_creation.c -o ex_thread_creation -lpthread
The -o flag stands for outfile or the file resulted from compiling the source file.
Regarding your code there are several issues too other than your code indentation.
The lines "Hello, how are you" and "I'm fine, and you" might not appear one after the other as intended. The output may appear malformed (the lines being intertwined) or the order could be wrong (Hello -> Hello -> I'm fine -> I'm fine).
If you want to keep the output as intended in your question, I suggest you use synchronization mechanisms.
after research a bit longer, i've found the answer,
the correct command is: gcc -pthread -o term term.c
thank you for reading
#include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
return (int)(100 * pow(n, 2.3));
}
int main(){
int x;
x = exp_for_level(6);
printf("%d", x);
return 0;
}
I receive the following error when I run this code on an online compiler
/tmp/cc28S7ML.o: In function exp_for_level':
main.c:(.text+0x19): undefined reference to `pow'
collect2: error: ld returned 1 exit status
How do I rectify this?
After I couldn't get it to work on the online compiler, I followed advice from some other threads on
The file is stored under a file grades.c on my mac
I've tried entering this
$ gcc - Wall - lm -o grades grade . c
into my terminal and i just get zsh error: command not found
Any ideas on what the issue is here too?
The online compiler I'm using is
https://www.tutorialspoint.com/compile_c_online.php
EDIT: in my post, in main I'd miswritten the function as exp_to_level instead of exp_for_level. Didn't copy paste the entire code as it's too long. I narrowed it down and retyped it to the portion that yields the error.
There are some errors in your code, you have defined a function exp_for_level but you use exp_to_level.
Then your x variable is not defined
If you fix your code like this:
#include <stdio.h>
#include <math.h>
int exp_for_level(int n) {
return (int)(100 * pow(n, 2.3));
}
int main(){
int x = exp_for_level(6);
printf("%d", x);
return 0;
}
and you compile:
gcc -Wall powtest.c -o powtest -lm
it works.
About the error on the online compiler:
The undefined reference error occurs because you are missing -lm linker option.
Edit the online compiler command clicking on Project->Compile Options:
About this problem on your local machine:
After I couldn't get it to work on the online compiler, I followed
advice from some other threads on The file is stored under a file
grades.c on my mac I've tried entering this
$ gcc - Wall - lm -o grades grade . c
into my terminal and i just get zsh error: command not found
you don't have the compiler installed.
You should install clang, Have a look to this question
First of all your function name is wrong in the main take a look here exp_for_level
and in main its exp_to_level change one of them then also add int x in main to solve the issue.
I have some application for which I need to write extension using shared library. In my shared library I need to use threads. And main application neither uses threads neither linked with threads library (libpthread.so, for example).
As first tests showed my library causes crashes of the main application. And if i use LD_PRELOAD hack crashes goes away:
LD_PRELOAD=/path/to/libpthread.so ./app
The only OS where i have no segfaults without LD_PRELOAD hack is OS X. On other it just crashes. I tested: Linux, FreeBSD, NetBSD.
My question is: is there a way to make my threaded shared library safe for non-threaded application without changing of the main application and LD_PRELOAD hacks?
To reproduce the problem i wrote simple example:
mylib.c
#include <pthread.h>
#include <assert.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *_thread(void *arg) {
int i;
struct addrinfo *res;
for (i=0; i<10000; i++) {
if (getaddrinfo("localhost", NULL, NULL, &res) == 0) {
if (res) freeaddrinfo(res);
}
}
pthread_mutex_lock(&mutex);
printf("Just another thread message!\n");
pthread_mutex_unlock(&mutex);
return NULL;
}
void make_thread() {
pthread_t tid[10];
int i, rc;
for (i=0; i<10; i++) {
rc = pthread_create(&tid[i], NULL, _thread, NULL);
assert(rc == 0);
}
void *rv;
for (i=0; i<10; i++) {
rc = pthread_join(tid[i], &rv);
assert(rc == 0);
}
}
main.c
#include <stdio.h>
#include <dlfcn.h>
int main() {
void *mylib_hdl;
void (*make_thread)();
mylib_hdl = dlopen("./libmy.so", RTLD_NOW);
if (mylib_hdl == NULL) {
printf("dlopen: %s\n", dlerror());
return 1;
}
make_thread = (void (*)()) dlsym(mylib_hdl, "make_thread");
if (make_thread == NULL) {
printf("dlsym: %s\n", dlerror());
return 1;
}
(*make_thread)();
return 0;
}
Makefile
all:
cc -pthread -fPIC -c mylib.c
cc -pthread -shared -o libmy.so mylib.o
cc -o main main.c -ldl
clean:
rm *.o *.so main
And all together: https://github.com/olegwtf/sandbox/tree/bbbf76fdefe4bacef8a0de7a2475995719ae0436/threaded-so-for-non-threaded-app
$ make
cc -pthread -fPIC -c mylib.c
cc -pthread -shared -o libmy.so mylib.o
cc -o main main.c -ldl
$ ./main
*** glibc detected *** ./main: double free or corruption (fasttop): 0x0000000001614c40 ***
Segmentation fault
$ ldd libmy.so | grep thr
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fe7e2591000)
$ LD_PRELOAD=/lib/x86_64-linux-gnu/libpthread.so.0 ./main
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
Just another thread message!
My question is: is there a way to make my threaded shared library safe
for non-threaded application without changing of the main application
and LD_PRELOAD hacks?
No, those are the two ways you can make it work. With neither in place, your program is invalid.
dlopen is supposed to do the right thing, and to open all the libraries your own .so depends upon.
In fact, your code is working for me if I comment out the address lookup code that you placed inside your thread function. So loading the pthread library works perfectly.
And if I run the code including the lookup, valgrind shows me that the crash is below getaddrinfo.
So the problem is not that the libraries aren't loaded, somehow their initialization code is not executed or not in the right order.
gdb helped to understand what's goin on with this example.
After 3 tries gdb showed that app always crashed at rewind.c line 36 inside libc. Since tests were run on Debian 7, libc implementation is eglibc. And here you can see line 36 of rewind.c:
http://www.eglibc.org/cgi-bin/viewvc.cgi/branches/eglibc-2_13/libc/libio/rewind.c?annotate=12752
_IO_acquire_lock() is a macros and after grepping eglibc source I found 2 places where it is defined:
bits/stdio-lock.h line 49: http://www.eglibc.org/cgi-bin/viewvc.cgi/branches/eglibc-2_13/libc/bits/stdio-lock.h?annotate=12752
sysdeps/pthread/bits/stdio-lock.h line 91: http://www.eglibc.org/cgi-bin/viewvc.cgi/branches/eglibc-2_13/libc/nptl/sysdeps/pthread/bits/stdio-lock.h?annotate=12752
Comment for first says Generic version and for second NPTL version, where NTPL is Native POSIX Thread Library. So in few words first defines non-threaded implementation for this and several other macroses and second threaded implementation.
When our main application is not linked with pthreads it starts and loads this first non-threaded implementation of _IO_acquire_lock() and others macroses. Then it opens our threaded shared library and executes function from it. And this function uses already loaded and non thread safe version of _IO_acquire_lock(). However in fact should use threads compatible version defined by pthreads. This is where segfault occures.
This is how it works on Linux. On *BSD situation is even more sad. On FreeBSD your program will hang up immediately after your threaded library will try to create new thread. On NetBSD instead of hang up program will be terminated with SIGABRT.
So answering to the main question: is it possible to use threaded shared library from application not linked with pthreads?
In general -- no. And particularly this depends on libc implementation. For OS X, for example, this will work without any problems. For Linux this will work if you'll not use libc functions that uses such special macroses redefined by pthreads. But how to know which uses? Ok, you can make 1+1, this looks safe. On *BSD your program will crash or hang up immediately, no matter what your thread do.
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
When I compile this code, I get the following gcc errors:
/tmp/ccUigsI6.o: In function `main':
/home/matt/Dropbox/school/2011/cs3210/test/sizeterm.c:9: undefined reference to `setupterm'
/home/matt/Dropbox/school/2011/cs3210/test/sizeterm.c:10: undefined reference to `tigetnum'
/home/matt/Dropbox/school/2011/cs3210/test/sizeterm.c:11: undefined reference to `tigetnum'
collect2: ld returned 1 exit status
make: *** [sizeterm] Error 1
Here's the code:
#include <stdio.h>
#include <term.h>
#include <curses.h>
#include <stdlib.h>
int main()
{
int nrows, ncolumns;
setupterm(NULL, fileno(stdout), (int *)0);
nrows = tigetnum("lines");
ncolumns = tigetnum("cols");
printf("This terminal has %d columns and %d rows\n", ncolumns, nrows);
exit(0);
}
Libncurses is installed correctly on my machine. I get the same results from my Arch linux laptop, and the Ubuntu server installed at my school. This particular piece of code is taken directly out of the book. Am I doing something wrong? I've done some googling and it looks as though people have had this problem before, but I can't narrow down a solution.
You forgot to actually link against ncurses. Add -lcurses to the gcc command line.
This is exactly what you find in the same book as where you found this code:
$ cc -o badterm badterm.c -lncurses
Beginning linux programming 4th edition, chapter 5: Terminals, page 196.