Maybe this questions is easy but I can't figure it out how to resolve it:
I try to compile an example which has pthreas on windows 7 (64bit), with Code Blocks I downloaded the prebuild library and set up building_options: the path for the compiler pthreadLib\include and the linker to pthreadLib\lib\x64
The program is:
extern "C"
{
#include <pthread.h>
#include <unistd.h>
}
#include <iostream>
#include <windows.h>
using namespace std ;
void * function1(void * argument);
void * function2(void * argument);
int main( void )
{
pthread_t t1, t2 ; // declare 2 threads.
pthread_create( &t1, NULL, function1,NULL); // create a thread running function1
pthread_create( &t2, NULL, function2,NULL); // create a thread running function2
Sleep(1);
return 0;
}
void * function1(void * argument)
{
cout << " hello " << endl ;
Sleep(2); // fall alseep here for 2 seconds...
return 0;
}
void * function2(void * argument)
{
cout << " world " << endl ;
return 0;
}
In case I comment pthread_create(); function, than it builds. So pthread_t is recognized as a type.
When I try to compile with pthread_create I get an error:
mingw32-g++.exe -L..\libs\Pre-built.2\lib\x64 -LD:\DropBox\WorkUT\Programs\MyODP\libs -o bin\Release\RIP.exe obj\Release\main.o -s ..\libs\Pre-built.2\lib\x64\libpthreadGC2.a ..\libs\Pre-built.2\lib\x64\pthreadVC2.lib
obj\Release\main.o:main.cpp:(.text.startup+0x36): undefined reference to `_imp__pthread_create'
collect2.exe: error: ld returned 1 exit status
Process terminated with status 1 (0 minute(s), 0 second(s))
1 error(s), 1 warning(s) (0 minute(s), 0 second(s))
Do I have to make additional setups in C::B? I tired to add the linker command -lpthread but is not recognized.
After 2 days I figured it out.
First: I installed the minGW 64 for Windows OS.
Next: I set up C::B to use the minGW_64 after this post.
Moreover: I added to the linker libs ..\libs\Pre-built.2\lib\x64\libpthreadGC2.a and ..\libs\Pre-built.2\lib\x64\pthreadVC2.lib. Finally, I added to my project the pthreadGC2.dll (64bit version!).
Lesson learned, don't mix lib. and compiler with 86 and 64.
For Linux
Use sleep(1) in stead of Sleep(1)
Related
This is my code
#include <pthread.h>
#include <stdio.h>
void cleanup(void *arg) {
printf("cleanup: %s\n", (const char*)arg);
}
void *thr_fn1(void *arg) {
printf("thread 1 strat\n");
pthread_cleanup_push(cleanup, (void*)"thread 1 first handler");
pthread_cleanup_push(cleanup, (void*)"thread 1 first handler");
if(arg)
return (void*)1;
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void*)1;
}
void *thr_fn2(void *arg) {
printf("thread 2 strat\n");
pthread_cleanup_push(cleanup, (void*)"thread 2 first handler");
pthread_cleanup_push(cleanup, (void*)"thread 2 first handler");
if(arg)
return (void*)2;
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return (void*)2;
}
int main() {
int err;
pthread_t tid1, tid2;
void *tret;
pthread_create(&tid1, NULL, thr_fn1, (void*)1);
pthread_create(&tid2, NULL, thr_fn2, (void*)1);
pthread_join(tid1, &tret);
printf("pthread 1 exit code %ld\n", tret);
pthread_join(tid2, &tret);
printf("pthread 2 exit code %ld\n", tret);
return 0;
}
Now I run it using gcc and g++
$ gcc main.c -o main
$ ./main
thread 2 strat
thread 1 strat
pthread 1 exit code 1
pthread 2 exit code 2
$ g++ main.c -o main
$ ./main
thread 1 strat
cleanup: thread 1 first handler
cleanup: thread 1 first handler
thread 2 strat
cleanup: thread 2 first handler
cleanup: thread 2 first handler
pthread 1 exit code 1
pthread 2 exit code 2
$
Why they behave differently?
Any other functions behave like this?
I found the implementations of gcc and g++ are different. So which one is a better implementation?
On Linux, the pthread_cleanup_push() and pthread_cleanup_pop() functions are implemented as macros that expand to text containing { and }, respectively.
# define pthread_cleanup_push(routine, arg) \
do { \
__pthread_cleanup_class __clframe (routine, arg)
If compiled with g++, __pthread_cleanup_class is a C++ class:
#ifdef __cplusplus
/* Class to handle cancellation handler invocation. */
class __pthread_cleanup_class
{
void (*__cancel_routine) (void *);
void *__cancel_arg;
int __do_it;
int __cancel_type;
public:
__pthread_cleanup_class (void (*__fct) (void *), void *__arg)
: __cancel_routine (__fct), __cancel_arg (__arg), __do_it (1) { }
~__pthread_cleanup_class () { if (__do_it) __cancel_routine (__cancel_arg); }
void __setdoit (int __newval) { __do_it = __newval; }
void __defer () { pthread_setcanceltype (PTHREAD_CANCEL_DEFERRED,
&__cancel_type); }
void __restore () const { pthread_setcanceltype (__cancel_type, 0); }
};
It behaves like any class, its destructor runs on scope end.
In C, using gcc, cleanup handlers require pthread_exit(), but your code does return.
When a thread terminates by calling pthread_exit(3), all clean-up handlers are executed as described in the preceding point. (Clean-up handlers are not called if the thread terminates by performing a return from the thread start function.)
I am doing a cross compilation test in Eclipse IDE for meta-toolchain made with Yocto, for arm cortex A9 processor. After performing hello world test, which ran successfully, I created a basic program to test pthreads.
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <pthread.h>
#define MILLION 1000000 /* one million = 10^6*/
#define sec_to_nsec 1000000000 /* ns to s conversion = 10^9 */
#define FILENAME "Schd.txt"
#define FLUSH_TIME 10.0
#define SIG_LLP_TIMER SIGRTMIN+1
int isr_idx; /* counter of ISR occurred -- starts from 0 and increments at each interrupt*/
volatile float clk_k, /* MY_CLOCK() value for the current sample*/
clk_k_1; /* MY_CLOCK() value for the previous sample*/
/*clock and timer values*/
struct itimerspec custom_itimerspec;
timer_t timer_id;
clockid_t USED_CLK;
struct timespec tv;
float a_n;
/*THREAD DATA*/
pthread_t thread0;
pthread_attr_t attr;
struct sched_param param;
using namespace std;
void* thread_scheduler(){
//function pointer
//mainThread
//make thread for scheduling
//exit after max cycle
}
int main(void)
{
cout << "Starting the program!" << endl; /* prints Hello World */
cout<< "Creating a Thread to deploy" << endl;
int status;
param.__sched_priority = 99;
int retc;
/*PTHREAD ATTR setup*/
retc = pthread_attr_init(&attr);
retc |= pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
retc |= pthread_attr_setschedpolicy(&attr, SCHED_FIFO);
retc |= pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
retc |= pthread_attr_setschedparam(&attr,¶m);
if (retc != 0) {
//fail
while(1){}
}
retc = pthread_create(&thread0, &attr, (void * (*)(void *))thread_scheduler, NULL);
printf("Exiting here!");
return 0;
}
But I get this error, undefined reference to `pthread_create', followed with some make errors.
Though after doing some search I found that adding '-pthread' command in configure and autogen settings works for building the project, as described here. But I am puzzled why the compiler can't see these files even if this file is present in 'includes' in the drop down folder of project explorer.
The error about undefined reference is coming from linking step, not from compiling and assembling step, compile step would look for header files and its rightly finding the pthread.h from sysroot include directory as you see as well. After compiling, it has to invoke the linker to create the executable binary and thats where it fails.
When linking it need to add libpthread to linker commandline so linker can find the pthread_create function and link it into final executable, this is usually done via specifying LDFLAGS which then get appended to linker invocation.
compiler driver ( gcc ) can be used to drive both compiling and linking steps.
so when you add -pthread option to compiler and compiler is also used to perform linking then it translates this option into -lpthread to linker cmdline which would then find libpthread and link it in.
I have written this code to capture the photo from webcam using opencv library.
#include <opencv2/highgui/highgui.hpp>
#include<windows.h>
#include<iostream>
using namespace std;
using namespace cv;
void camcapture()
{
VideoCapture cap(0);
char name[100];
int i=0;
while(1){
Sleep(1000);
sprintf(name,"%s%d.jpg","test",i++);
Mat save_img;
cap >> save_img;
if(save_img.empty())
{
std::cerr << "Something is wrong with the webcam, could not get frame." << std::endl;
}
// Save the frame into a file
imwrite(name, save_img); // A JPG FILE IS BEING SAVED
printf("image %s saved\n",name);
}
}
int main()
{
camcapture();
}
then i statically linked with some of the required opencv library to make it portable. when i compile the code the size of the executable is 4.73,
Is there any way to reduce the size of executable without affecting the portability ?
i don't want to link the libraries dynamically.
here is the compilation log.
Build started on: 25-10-2016 at 22:52.58
Build ended on: 25-10-2016 at 22:53.00
-------------- Build: Release in cvtest (compiler: GNU GCC Compiler)---------------
mingw32-g++.exe -Wall -fexceptions -O2 -ID:\open\opencv\mybuild4\install\include -ID:\open\opencv\mybuild4\install\include\opencv -ID:\open\opencv\mybuild4\install\include\opencv2 -c D:\c_cpp_codes\cvtest\main.cpp -o obj\Release\main.o
mingw32-g++.exe -LD:\open\opencv\mybuild4\install\x86\mingw\staticlib -o bin\Release\cvtest.exe obj\Release\main.o -s D:\open\opencv\mybuild4\lib\libopencv_world310.a D:\open\opencv\mybuild4\3rdparty\lib\liblibjpeg.a D:\open\opencv\mybuild4\3rdparty\lib\liblibwebp.a D:\open\opencv\mybuild4\3rdparty\lib\liblibtiff.a D:\open\opencv\mybuild4\3rdparty\lib\liblibpng.a D:\open\opencv\mybuild4\3rdparty\lib\liblibjasper.a D:\open\opencv\mybuild4\3rdparty\lib\libIlmImf.a D:\open\opencv\mybuild4\3rdparty\lib\libzlib.a C:\MinGW\lib\Vfw32.Lib C:\MinGW\lib\Uuid.Lib C:\MinGW\lib\Ole32.Lib C:\MinGW\lib\OleAut32.Lib
Output file is bin\Release\cvtest.exe with size 4.73 MB
Process terminated with status 0 (0 minute(s), 1 second(s))
0 error(s), 0 warning(s) (0 minute(s), 1 second(s))
It depends how you want to use it. In addition to responses in comments, you can use executable packer, like UPX.
When I execute the following program on the my embedded Linux nothing happens:
#include <boost/thread/thread.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <iostream>
#include <boost/atomic.hpp>
void Test(void)
{
std::cout << "Hello World" << std::endl;
}
int main(int argc, char* argv[])
{
std::cout << "init";
boost::thread producer_thread(Test);
producer_thread.join();
std::cout << "end";
}
# ./prog -> nothing happens here
The last few lines from strace output are:
open("/lib/libboost_thread.so.1.55.0", O_RDONLY|O_CLOEXEC) = 3
read(3, "\177ELF\1\1\1\0\0\0\0\0\0\0\0\0\3\0(\0\1\0\0\0\240\272\0\0004\0\0\0"..., 512) = 512
lseek(3, 95536, SEEK_SET) = 95536
read(3, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 1200) = 1200
lseek(3, 95226, SEEK_SET) = 95226
read(3, "A'\0\0\0aeabi\0\1\35\0\0\0\0055T\0\6\3\10\1\t\1\22\4\24\1\25\1"..., 40) = 40
exit_group(1) = ?
+++ exited with 1 +++
#
The cross compiled libbost_thread is right installed at /lib.
The program exit before main() being called. The program runs normal under my Ubuntu.
Target: ARM with buildroot (sama5d3)
Toolchain: arm-linux-gnueabihf-
Regards
Maybe as a hint:
Have you linked against libpthread with compile and link option -pthread for your target?
If not it can have the same effect as seen in your environment: The prog starts, try to start a new thread, have no threading enabled and call the abort() function. Because abort() simply leave the prog with error in exit code nothing else happens.
Can you also add your compile & link commands for debugging purpose please!
In addition:
Your outputs without endl will not be printed because cout is buffered. The buffer will be printed only if you call flush or send a endl. Maybe you change this in your example.
Hope that helps...
strace is a tool that traces system calls. In your example, this consists of calls to open(), lseek(), and read(). Specifically, the snippet that you pasted shows the OS's dynamic library loader opening the libboost_thread.so.1.55.0 file and reading its contents; nothing more. It doesn't really demonstrate anything about your program except that it is linked against that library.
I found the problem.
The boost library was compiled with arm-linux-gnueabi- (elibc) and the buildroot is compiled with uClibc.
I have a problem with compiling a boost integrated source code in my PC. I am working on below environment
OS: CentOs 6.3
Boost version: 1.41
Boost installation header file directory: /usr/include/boost/
IDE: code::block
Program for the compilation:
#include <boost/thread.hpp>
#include <iostream>
using namespace std;
void ThreadFunction()
{
int counter = 0;
for(;;)
{
std::cout << "thread iteration " << ++counter << " Press Enter to stop" << std::endl;
try
{
// Sleep and check for interrupt.
// To check for interrupt without sleep,
// use boost::this_thread::interruption_point()
// which also throws boost::thread_interrupted
boost::this_thread::sleep(boost::posix_time::milliseconds(500));
}
catch(boost::thread_interrupted&)
{
std::cout << "Thread is stopped" << std::endl;
return;
}
}
}
int main()
{
// Start thread
boost::thread t(&ThreadFunction);
// Wait for Enter
char ch;
std::cin.get(ch);
// Ask thread to stop
t.interrupt();
// Join - wait when thread actually exits
t.join();
std::cout << "main: thread ended" << std::endl;
return 0;
}
Error output:
Build: Debug in testPro (compiler: GNU GCC Compiler) ===|
obj/Debug/main.o||In function `main':|
<path to code>/main.cpp|40|undefined reference to `boost::thread::interrupt()'|
<path to code>/main.cpp|43|undefined reference to `boost::thread::join()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
<path to code>/main.cpp|47|undefined reference to `boost::thread::~thread()'|
obj/Debug/main.o||In function `thread_data_base':|
/usr/include/boost/thread/pthread/thread_data.hpp|65|undefined reference to `vtable for boost::detail::thread_data_base'|
obj/Debug/main.o||In function `void boost::this_thread::sleep<boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> >(boost::date_time::subsecond_duration<boost::posix_time::time_duration, 1000l> const&)':|
/usr/include/boost/thread/pthread/thread_data.hpp|122|undefined reference to `boost::this_thread::sleep(boost::posix_time::ptime const&)'|
obj/Debug/main.o||In function `thread<void (*)()>':|
/usr/include/boost/thread/detail/thread.hpp|191|undefined reference to `boost::thread::start_thread()'|
obj/Debug/main.o||In function `~thread_data':|
/usr/include/boost/thread/detail/thread.hpp|40|undefined reference to `boost::detail::thread_data_base::~thread_data_base()'|
]+0x10)||undefined reference to `typeinfo for boost::detail::thread_data_base'|
||=== Build failed: 9 error(s), 0 warning(s) (0 minute(s), 1 second(s)) ===|
As in the error console compiler cannot find the methods declared in boost library. I tried the several sample applications but result was the same. Please help me to find out the problem or suggest me a way to check the status of boost installation.
You need to compile your code with boost_thread library -lboost_thread
for example
gcc test.c -o test -lboost_thread