Program using Boost threads does absolutely nothing - multithreading

This test code is OK, the problem must be in the way I build it:
#include <boost/thread.hpp>
#include <iostream>
void Wait(int seconds)
{
boost::this_thread::sleep(boost::posix_time::seconds(seconds));
}
void Thread()
{
for (int i = 0; i < 5; ++i)
{
Wait(1);
std::cout << i << std::endl;
}
}
int main()
{
std::cout << "Boost threads test:" << std::endl;
boost::thread t(Thread);
t.join();
}
This is the CMakeLists.txt file:
project(BoostThreadsTest)
cmake_minimum_required(VERSION 2.8)
find_package(Boost 1.46 REQUIRED COMPONENTS thread)
set(Boost_USE_STATIC_LIBS ON)
set(Boost_USE_MULTITHREADED ON)
set(Boost_USE_STATIC_RUNTIME OFF)
if(Boost_FOUND)
include_directories(${Boost_INCLUDE_DIRS})
link_directories(${Boost_LIBRARY_DIRS})
message(STATUS "Boost_LIBRARIES = ${Boost_LIBRARIES}")
else()
message(WARNING "Boost headers/libraries not found.")
endif()
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})
target_link_libraries(${PROJECT_NAME}
${Boost_LIBRARIES}
${THREADING_LIBRARY}
)
Built with:
cmake -G "MinGW Makefiles" .
mingw32-make.exe
Everything goes well, with only this warnings:
In file included from C:/boost/include/boost-1_48/boost/thread/win32/thread_data.hpp:12:0,
from C:/boost/include/boost-1_48/boost/thread/thread.hpp:15,
from C:/boost/include/boost-1_48/boost/thread.hpp:13,
from C:\Users\pietro.mele\projects\tests\buildSystem_test\BoostTest\BoostThreadsTest\BoostThreadsTest\main.cpp:4:
C:/boost/include/boost-1_48/boost/thread/win32/thread_heap_alloc.hpp:59:40: warning: inline function 'void* boost::detail::allocate_raw_heap_memory(unsigned int
)' declared as dllimport: attribute ignored [-Wattributes]
C:/boost/include/boost-1_48/boost/thread/win32/thread_heap_alloc.hpp:69:39: warning: inline function 'void boost::detail::free_raw_heap_memory(void*)' declared
as dllimport: attribute ignored [-Wattributes]
I get the executable, but when I run it it does absolutely nothing. Not even the "Boost threads test:" string is printed, which is not involved in multithreading, yet. No error is produced. It is just like pressing the [return] key.
Thank you.

(Just pasting in my comment so question can be marked as closed).
I suspect a DLL is not being found. I have seen this behaviour when executing an exe from cygwin: nothing happens at all. But, when I double-click in the exe in Windows explorer I see a message box complaining about a missing DLL: try that. If this is the cause, adjust you PATH to enable DLL to be located.
I am unsure of the reason that the message box is suppressed, if I discover it (or if someone adds it as a comment) I will update this answer.

Related

How do I disable MSVC warnings from headers included with quotes instead of angle brackets when using /analyze?

I am trying to add the /analyze flag to cl.
I am getting a warnings from external headers I #include "...", even though I am using /analyze:external- and /external:I ....
What am I doing wrong?
Example project:
main.cpp
#include "external.h"
// #include <external.h> <- hides external's warnings
int main() {
int shadowed = 0;
{ float shadowed = 0; }
return 0;
}
external.h
void something() {
int external_shadowed = 0;
{ float external_shadowed = 0; }
}
I run this command from the VS developer prompt:
cl /EHsc /analyze /analyze:external- /I include /external:I external /external:W0 main.cpp
And I proceed to get warnings from both files.
It seems MSVC only considers /external:I directories to actually be external if they are included with <> instead of "". This is not documented anywhere, and I would consider it a bug with the compiler. Third-party libraries should not necessarily always be included with <>.
More info and possibly updates in the future here: https://developercommunity.visualstudio.com/t/analyze:external--and-external:I-flags/1688240
I have not tested myself, but according to Hwi-sung Im [MSFT], <> and "" now act the same w.r.t /external:I in Visual Studio 2022 17.0.

c++ ~ shared object -> get host application offsets

Im writing a shared library for a FreeBSD application.
This library gets loaded by LD_PRELOAD.
This application has multiple compile-versions, so some function offsets might change and my library wont work there.
Now i want to read the offsets at loading the library.
The offsets are changing, so i think my only way is to read the offsets of specific function names.
The offsets are simply the offsets of functions or labels.
Now the problem - how to do it?
Example
In the first version, i call the main version like that:
int(*main)(int argc, char *argv[])=(int(*)(int,char*[]))0x081F3XXX;
but in the second, the offset has changed:
int(*main)(int argc, char *argv[])=(int(*)(int,char*[]))0x08233XXX;
Programmers (me) are lazy and don't want to compile their libs for every version.. I want to create a lib, that is for every version!
I simply need the offsets of the functions via function name, the rest is no problem..
Thats how i call the library:
LD_PRELOAD="/path/to/library.so" ./executable
or
env LD_PRELOAD="/path/to/library.so" ./executable
Edit with test code
Here my testcode regarding to the comments:
Main.cpp:
#include <stdio.h>
void test() {
printf("Test done.\n");
}
int main(int argc, char * argv[]) {
printf("Program started\n");
test();
}
lib.cpp
#include <stdio.h>
#include <dlfcn.h>
void __attribute__ ((constructor)) my_load(void);
void my_load(void) {
printf("Library loaded\n");
printf("test - offset: 0x%x\n",dlsym(NULL,"test"));
}
test.sh
g++ main.cpp -o program
g++ -shared lib.cpp -o lib.so
env LD_PRELOAD="lib.so" ./program
-> Result:
Library loaded
test - offset: 0x0
Program started
Test done.
Does not seem as would it work :s
Edit 15:45
printf("test - offset: 0x%x\n",dlsym(dlopen("/home/test/test_proc/program",RTLD_GLOBAL),"test"));
This also does not work.. Maybe dlsym is the wrong way?
I reproduced your program on Mac OS X using Clang, and found a solution. First, the boring parts:
To make it compile cleanly I had to change your %x format specifier to %p for the pointer.
Then, on Mac OS X I had to pass RTLD_MAIN_ONLY as the first argument to dlsym(). I guess this is platform-dependent; on Linux it does seem to be NULL as you have.
Now, the meat of the fix!
You're searching with dlsym() for a symbol called test. But there is no such symbol in your application. Why? Because you're using C++, and C++ does "name mangling." You could use any number of tools to figure out the mangled name and try to load that with dlsym(), but it could change with different compilers. So instead, just inhibit name mangling by enclosing your test() function in extern "C":
extern "C" {
void test() {
printf("Test done.\n");
}
}
This fixed it for me:
$ DYLD_INSERT_LIBRARIES=lib.so ./program
Library loaded
test - offset: 0x1027d1eb0
Program started
Test done.

Cannot find lib file when I've specifed the dll

I'm new to visual c++ and rusty with c++.
I created a dll project following the visual C++ directions. Now I want to test my dll to make sure it's working. I created an empty project and put in tester.cpp. I added the dll to the project references and to the path. Then I try to run it.
Before I included stuff from my dll ("Hello world!") it worked. Now that I've put in my stuff to reference the dll, it fails. The message is:
1>LINK : fatal error LNK1104: cannot open file 'C:\Users\thom\Documents\cworkspace\barnaby\Debug\barnaby.lib'
The thing I don't understand is the reference links to the dll which exists at the path above. Here's my code:
#include <iostream>
#include <string>
#include <vector>
#include "barnaby.h"
int main(int argc, char *argv[]){
std::vector<std::string> tzNames = Barnaby::TimeZoneFunctions::getTimezoneList();
for(std::vector<std::string>::iterator iter = tzNames.begin(); iter != tzNames.end(); iter++){
std::cout << *iter << std::endl;
}
}
ideas?
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ which told me to include the following code in my header for the DLL:
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Then, each function I export you simply precede by:
BARNABY_API int add(){
}
All of this would have been prevented either by click the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for application programmers.
Thanks for the help.

SFML tutorial 1: thread problems

Hi so i am using msVS++2010 and have been attempting to set up SFML all day....
I downloaded 1.6 from the site, then rebuilt it in VS2010, but sad to find that this did not result in a sfml-system-d.lib file, which is what i am used to using, and only produced new system-s and system-s-d libs.
I then closely watched this Video to find that he ran his test code by adding the external lib of sfml-system-s-d and so i added the sfml-system-d.dll next the .exe and got the following exact same code the video showed to work:
#include <iostream>
#include <SFML/System.hpp>
int main(int argc, char **argv)
{
sf::Clock clock;
sf::Sleep(0.1f);
while(clock.GetElapsedTime() < 5.0f)
{
std::cout << clock.GetElapsedTime() << std::endl;
sf::Sleep(0.5f);
}
}
obviously clock and sleep are working, but when i add the simple line of code 'sf::Thread thread();' an error box pops up saying "unable to start program," "configuration is incorrect," "Review the manifest file for possible errors," "renstalling my fix it."
Also: when trying to run the first program of the tutorials regarding threads:
#include <SFML/System.hpp>
#include <iostream>
void ThreadFunction(void* UserData)
{
// Print something...
for (int i = 0; i < 10; ++i)
std::cout << "I'm the thread number 1" << std::endl;
}
int main()
{
// Create a thread with our function
sf::Thread Thread(&ThreadFunction);
// Start it !
Thread.Launch();
// Print something...
for (int i = 0; i < 10; ++i)
std::cout << "I'm the main thread" << std::endl;
return EXIT_SUCCESS;
}
I get 8 unresovled external symbols like this one:
1>sfml-system-s-d.lib(Thread.obj) : error LNK2001: unresolved external symbol "__declspec(dllimport) public: int __thiscall std::ios_base::width(int)" (__imp_?width#ios_base#std##QAEHH#Z)
fatal error LNK1120: 8 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Lastly this is how my project is set up:
include directory to out of the box, freshly downloaded SFML 1.6/include
lib directory to the VS2010 rebuilt SFML (debug/release DLL setting, and static).
extra dependency on sfml-system-s-d.lib file.
out of frusteration i placed every dll file next to the .exe
It sounds like you might not be linking to the CRT when building SFML. (ios_width is iostream, which requires the CRT library.)
You need to rebuild SFML, except this time do the following:
0. copy this list of libs
kernel32.lib
user32.lib
gdi32.lib
winspool.lib
comdlg32.lib
advapi32.lib
shell32.lib
ole32.lib
oleaut32.lib
uuid.lib
odbc32.lib
odbccp32.lib
go into each
individual Project's Properties ->
Configuration -> Linker -> Input.
or if it doesn't have 'Linker' go
into Properties -> Configuration ->
Librarian.
Set "Ignore Default Libraries" to
"no" and it will probably work
If you wanna be 100% safe, click on additional dependencies, expand it, and click "edit." now just paste in the libs above
If your in the 'librarian' tab, set
Link Library Dependencies to YES
repeat steps 1-4 each time you
change the build setting of Debug
DLL, Debug static, etc.
When I recompiled SFML (granted, I have a static compile because 1.6 is the last of the 1.x line, and 2.0 isn't compatible ;)) I had to add those references. It will ignore (and 'warn' about ignoring) anything it doesn't need, but they are the defaults ;)
Unfortunately you'll need to update everything in the SFML solution, as, if I recall correctly, they are all missing the default libraries.

C++ Delete Error -- _unlock_fhandle throwing exception?

I have a straightforward problem but I don't understand why I have it.
I would greatly appreciate any insight.
I wrote this code to test that I was correctly creating and using DLLs in Visual Studio 2010 under Win 7 64bit that could execute on Windows XP. The code executes correctly, and because it is a small test program freeing the allocated memory is not critical, but certainly will be in the future.
I am implicitly calling the DLL, as I say, it appears to work just fine. When I add the line "delete dllMsg;" to toyUseDLL.cpp it crashes, and the debugger shows _unlock_fhandle in osfinfo.c.
If it's relevant I am compiling the program with /MT to embed the runtime library (for a small handful of not important reasons).
It seems pretty obvious that I'm deallocating something not allocated, but the program output is correct since the pointers are passing the referenced memory locations. The only thing I can think of is that my pointer isn't valid, and it's only working by pure chance that the memory wasn't overwritten.
Thanks for any help, I'm pretty new to C++ and have already found a lot of great help on this site, so thanks for everyone who has posted in the past!! :-)
msgDLL.h
#include <string>
using namespace std;
namespace toyMsgs {
class myToyMsgs {
public:
static __declspec(dllexport) string* helloMsg(void);
static __declspec(dllexport) string* goodbyeMsg(void);
};
}
msgDLL.cpp
#include <iostream>
#include <string>
#include "msgDLL.h"
using namespace std;
namespace toyMsgs {
string* myToyMsgs::helloMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Hello from the DLL");
cout << "Here in helloMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
string* myToyMsgs::goodbyeMsg(void) {
string *dllMsg = new string;
dllMsg->assign("Good bye from the DLL");
cout << "Here in goodbyeMsg, dllMsg is: \"" << *(dllMsg) << "\"" << endl;
return (dllMsg);
}
}
toyUseDLL.cpp
#include <iostream>
#include <string>
#include "stdafx.h"
#include "msgDLL.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[]) {
string myMsg;
string *dllMsg;
myMsg.assign ("This is a hello from the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::helloMsg();
cout << "Saying Hello? " << *(dllMsg) << endl;
delete dllMsg;
myMsg.assign ("This is the middle of the toy program");
cout << myMsg << endl;
dllMsg = toyMsgs::myToyMsgs::goodbyeMsg();
cout << "Saying goodbye? " << *(dllMsg) << endl;
myMsg.assign ("This is a goodbye from the toy program");
cout << myMsg << endl;
return 0;
}
Program Output:
This is a hello from the toy program
Here in helloMsg, dllMsg is: "Hello from the DLL"
Saying Hello? Hello from the DLL
This is the middle of the toy program
Here in goodbyeMsg, dllMsg is: "Good bye from the DLL"
Saying goodbye? Good bye from the DLL
This is a goodbye from the toy program
The problem is that you are using /MT to compile your EXE and DLL. When you use /MT, each executable gets its own copy of the C runtime library, which is a separate and independent context. CRT and Standard C++ Library types can't safely be passed across the DLL boundary when both DLLs are compiled /MT. In your case the string is allocated by one CRT (on its private OS Heap), and freed by the EXE (which has a different heap) causing the crash in question.
To make the program work, simply compile /MD.
General advice: /MT is almost never the right thing to do (for a large handful of relatively important reasons including memory cost, performance, servicing, security and others).
Martyn
There is some good analysis here Why does this program crash: passing of std::string between DLLs

Resources