Cant initialise thread in Xcode , C++11 - xcode

I am trying to implement spsc_queue of boost.
But initialising thread throws error. I cant use both std::thread as well as boost thread.
sharedQueue.hpp
`
#include <stdio.h>
#include <iostream>
#include <queue>
#include <thread>
#include <mutex>
#include <boost/thread.hpp>
#include <boost/lockfree/spsc_queue.hpp>
using namespace std;
class sharedQueue
{
boost::lockfree::spsc_queue<int> lockFreeQ{100};
std::queue<int> comQue;
int head =0;;
int tail = 0;
public:
sharedQueue();
std::mutex lockForQueue;
void write(int writeValue);
int read();
void startTesting();
void TestWrite(int MaxElement);
void lockFreeProduce();
void lockFreeConsume();
void TestLockFreeQueue();
};`
Following is the sharedQueue.cpp
#include "sharedQueue.hpp"
int sharedQueue :: read(){
int readValue;
lockForQueue.lock();
if(!(comQue.empty()))
{
readValue = comQue.front();
comQue.pop();
}
lockForQueue.unlock();
return readValue;
}
void sharedQueue :: write(int writeValue){
lockForQueue.lock();
comQue.push(writeValue);
tail++;
lockForQueue.unlock();
}
void sharedQueue:: startTesting(){
std::cout<<"Size of the que --"<<comQue.size()<<std::endl;
}
void sharedQueue:: TestWrite(int maxEle ){
for(int i = 0 ; i < maxEle; i ++){
write(i);
}
}
void sharedQueue::lockFreeProduce(){
for(int i = 0; i < 10; i++){
cout <<“Produced-- "<< i<<endl;
lockFreeQ.push(i);
}
}
void sharedQueue::lockFreeConsume(){
for(int i = 0; i <10; i++){
lockFreeQ.front();
cout << “ Consume-- "<<lockFreeQ.pop();
}
}
void sharedQueue:: TestLockFreeQueue(){
std::thread t1(lockFreeProduce);
std::thread t2(lockFreeConsume);
t1.join();
t2.join();
} `
I am using Xcode. I have tried changing
C++ Language dialect to c++11 from GNU++11
Standard Library to libc++11 from libstdC++
Please help.
Where am I doing wrong?

You are trying to run a member function as a new thread, not a plain old function. The syntax for member function is different.
void sharedQueue:: TestLockFreeQueue(){
std::thread t1(std::bind(&sharedQueue::lockFreeProduce, this));
std::thread t2(std::bind(&sharedQueue::lockFreeConsume, this));
t1.join();
t2.join();
}
Below answer assumes that we are talking about non-static member function. static member function behaves kind of same way as that of a normal function pointer.
A member function pointer is complex than a plain old function pointer and it cannot be invoked in standalone manner i.e it can only be called when there is an object instance of that class.
See this for an example and read this for better understanding of member function pointers.
An easier way to do it i.e instead of using bind to create a callable object is to use a lambda, C++11 onwards and you should prefer lambda over bind whenever and however possible.
Your example using a lambda:
void sharedQueue:: TestLockFreeQueue(){
std::thread t1([this]() { this->lockFreeProduce(); });
std::thread t2([this]() { this->lockFreeConsume(); });
t1.join();
t2.join();
}
Here I am passing a lambda to the constructor of the thread which creates an anonymous functor structure. The square bracket [...] is the capture list which copies this pointer so that it can be used inside a lambda.
More about lambda can be found here and here.

Related

Does 'this' pointer in bind C++ really matters?

I am trying to experiment bind in C++. Basically I have two class - Invokee. The invokee class registers a test handler that needs to be invoked upon some callbacks. The method here is -
void RegisterTestHandler(int id, TestFunction handler, std::string summary, std::string details);
Similarly, I have another method that actually invokes what has been registered -
void callHandler(int id);
Another class Test which has a function that needs to be invoked on callHandler.
unsigned int globalReset(int val);
In the main function, I am doing the nullptr for the second parameter in the bind. However, it still works and I don't get any crashes. Is it something working because of the compiler optimisation or undefined behaviour or it is something to do with bind concept.
Here is the entire experimental code.
// main.cpp
#include <iostream>
#include "test.h"
#include "invokee.h"
#include <memory>
#include <functional>
// beautify using clang-format in Vscode.
int main(int argc, char **argv)
{
auto *invokeTest = new Invokee();
Test *test = new Test();
std::string summary = "global reset summary";
std::string details = "global reset details";
//Basically there are two object from different class - InvokeTest --> does the registration of the handler.
// Now the InvokeTest has to call the member function of class object - Test.
// ?? How it can do - it can do using bind - basically, the this pointer of Test class is available to invokeTest
// therefore invokeTest can simply invoke the member function of test object.
// until the test point is valid, it can use it to invoke the method of it ?? --> Is it really correct?
delete(test); //experiment deleted the test pointer.
test= nullptr; // explicity set to nullptr
// still it works?? how come ??
invokeTest->RegisterTestHandler(1, std::bind(&Test::globalReset, test, std::placeholders::_1), summary, details);
invokeTest->callHandler(1);
return 0;
}
Here is the invokee.cpp -
#include "invokee.h"
void Invokee::RegisterTestHandler(int id, TestFunction handler, std::string summary, std::string details)
{
this->handlers[id] = handler;
this->summary[id] = summary;
this->details[id] = details;
}
void Invokee::callHandler(int id)
{
auto handler = handlers.find(id);
if (handler != handlers.end())
{
std::cout << "Found the handler --" << std::endl;
handler->second(1);
}
}
Here is the test.cpp
#include <iostream>
#include "test.h"
unsigned int Test::globalReset(int val)
{
std::cout << "global Reset invoked" << std::endl;
return 0;
}

C++ simple mutex using atomic_flag (code not working)

This is an exercise of using atomic_flag with acquire/release memory model to implement a very simple mutex.
There are THREADS number of threads, and each thread increment cou LOOP number of times. The threads are synchronized with this simple mutex. However, the code throws exception in thread.join() function. Could someone please enlighten me why this does not work? Thank you in advance!
#include <atomic>
#include <thread>
#include <assert.h>
#include <vector>
using namespace std;
class mutex_simplified {
private:
atomic_flag flag;
public:
void lock() {
while (flag.test_and_set(memory_order_acquire));
}
void unlock() {
flag.clear(memory_order_release);
}
};
mutex_simplified m_s;
int cou(0);
const int LOOP = 10000;
const int THREADS = 1000;
void increment() {
for (unsigned i = 0; i < LOOP; i++) {
m_s.lock();
cou++;
m_s.unlock();
}
}
int main() {
thread a(increment);
thread b(increment);
vector<thread> threads;
for (int i = 0; i < THREADS; i++)
threads.push_back(thread(increment));
for (auto & t : threads) {
t.join();
}
assert(cou == THREADS*LOOP);
}
You are not joining threads a and b. As the result, they might be still running while your program is finishing its execution.
You should either add a.join() and b.join() somewhere, or probably just remove them as the assertion in your main function will fail if you keep them.
Another issue is that you need to explicitly initialize atomic_flag instance in your mutex constructor. It might not cause issues in your example because global variables are zero-initialized, but this might cause issues later.

Getting wrong output from boost lock free spsc queue

I am trying to implement lock free queue of user defined data type using boost library, but I am getting wrong result.
Please help me out where I am doing wrong.
#include <boost/lockfree/spsc_queue.hpp>
#include <thread>
#include <iostream>
#include <string.h>
#include <time.h>
class Queue
{
private:
unsigned char *m_data;
int m_len;
public:
Queue(unsigned char *data,int len);
Queue(const Queue &obj);
~Queue();
Queue & operator =(const Queue &obj);
unsigned char *getdata()
{
return m_data;
}
int getint()
{
return m_len;
}
};
Queue::Queue(unsigned char* data, int len)
{
m_len=len;
m_data=new unsigned char[m_len];
memcpy(m_data,data,m_len);
}
Queue::Queue(const Queue& obj)
{
m_len= obj.m_len;
m_data=new unsigned char[m_len];
memcpy(m_data,(unsigned char *)obj.m_data,m_len);
}
Queue::~Queue()
{
delete[] m_data;
m_len=0;
}
Queue & Queue::operator =(const Queue &obj)
{
if(this != &obj)
{
m_len=obj.m_len;
m_data=new unsigned char[m_len];
memcpy(m_data,(unsigned char *)obj.m_data,m_len);
}
return *this;
}
boost::lockfree::spsc_queue<Queue*> q(10);
void produce()
{
int i=0;
unsigned char* data=(unsigned char *)malloc(10);
memset(data,1,9);
Queue obj(data,10);
Queue *pqueue=&obj;
printf("%d\n",pqueue->getint());
q.push(pqueue);
}
void consume()
{
Queue *obj;
q.pop(&obj);
printf("%d\n",obj->getint());
}
int main(int argc, char** argv) {
// std::thread t1{produce};
// std::thread t2{consume};
//
// t1.join();
// t2.join();
produce();
consume();
return 0;
}
As per boost::lockfree::queue requirements I created following in class.
Copy Constructor
Assignment Operator
Destructor
Please let me know if anything other requires.
Thanks.
You're using malloc in C++.
You die.
You have 2 lives left.
Seriously, don't do that. Especially since using it with delete[] is clear cut Undefined Behaviour.
Sadly you lose another life here:
Queue obj(data,10);
Queue *pqueue=&obj;
q.push(pqueue);
You store a pointer to a local. More Undefined Behaviour
You have 1 life left.
Last life at
q.pop(&obj);
You pop using an iterator. It will be treated as an output iterator.
You get a return that indicates the number of elements popped, and items
will be written to &obj[0], &obj[1], &obj[2], etc.
Guess what? Undefined Behaviour.
See also: Boost spsc queue segfault
You died.
You're already dead. But you forsake your afterlife with
printf("%d\n",obj->getint());
Since pop might not have popped anything (the queue may have been empty), this in itself is Undefined Behaviour.
The funny part is, you talk about all these constructor requirements but you store pointers in the lockfree queue...?! Just write it:
typedef std::vector<unsigned char> Data;
class Queue {
private:
Data m_data;
public:
Queue(Data data) : m_data(std::move(data)) {}
Queue() : m_data() {}
unsigned char const *getdata() const { return m_data.data(); }
size_t getint() const { return m_data.size(); }
};
boost::lockfree::spsc_queue<Queue> q(10);
Live On Coliru
Notes:
you need to make the consumer check the return code of pop. The push might not have happened, and lock free queues don't block.
you don't need that contraption. Just pass vectors all the way:
C++ Code
Live On Coliru
#include <boost/lockfree/spsc_queue.hpp>
#include <thread>
#include <iostream>
#include <vector>
typedef std::vector<unsigned char> Queue;
boost::lockfree::spsc_queue<Queue> q(10);
void produce() {
Queue obj(10, 1);
std::cout << __FUNCTION__ << " - " << obj.size() << "\n";
q.push(std::move(obj));
}
void consume() {
Queue obj;
while (!q.pop(obj)) { }
std::cout << __FUNCTION__ << " - " << obj.size() << "\n";
}
int main() {
std::thread t1 {produce};
std::thread t2 {consume};
t1.join();
t2.join();
}

How to write a C++ API class that will allow a user to register its own callback functions?

Let's say a user links his app against a library I wrote and I want to let him specify a callback function that I will call whenever an error occurs in my library. The implementation below works but I want to double check that I'm not missing something here:
Thread safety
DLL initialization issues
Public API considerations (I'm giving away a reference to an instance from the DLL is that OK?)
Anything that could be done better to hide implementation details from the public API?
errordispatcher.h:
#pragma once
#include <functional>
#include <memory>
#include <string>
namespace WE
{
class ErrorDispatcher
{
public:
ErrorDispatcher()
{}
explicit ErrorDispatcher(std::function<void(std::string)> user_func)
: error_callback_func{user_func}
{}
virtual ~ErrorDispatcher(){}
static ErrorDispatcher& getInstance()
{
return instance_;
}
void setErrorCallback(std::function<void(std::string)> user_func)
{
error_callback_func = nullptr;
if (user_func)
error_callback_func = user_func;
}
void dispatchError(std::string message)
{
if (error_callback_func)
error_callback_func(message);
}
private:
explicit ErrorDispatcher(const ErrorDispatcher&) = delete;
explicit ErrorDispatcher(ErrorDispatcher&&) = delete;
ErrorDispatcher& operator = (const ErrorDispatcher&) = delete;
ErrorDispatcher& operator = (ErrorDispatcher&&) = delete;
static ErrorDispatcher instance_;
std::function<void(std::string)> error_callback_func = nullptr;
};
}
NOTE: above I have inline implementation details in the public header to make this post shorter but they will be moved to a .cpp and won't be part of the public header
errordispatcher.cpp:
#include "errordispatcher.h"
namespace WE
{
ErrorDispatcher ErrorDispatcher::instance_;
}
apitest.h
namespace WE
{
void dllFunctionThatMightGiveError();
}
apitest.cpp
#include "errordispatcher.h"
#include "apitest.h"
namespace WE
{
void dllFunctionThatMightGiveError()
{
// Some error happens in dll so call user function and give a message to the user!
ErrorDispatcher::getInstance().dispatchError("Error in DLL!");
}
}
main.cpp (USER APP)
#include "errordispatcher.h"
#include "apitest.h"
#include <iostream>
#include <string>
void error_callback(std::string message)
{
std::cout << message << "\n";
}
int main(void)
{
WE::ErrorDispatcher::getInstance().setErrorCallback(error_callback);
WE::ErrorDispatcher::getInstance().dispatchError("Error in APP!");
WE::dllFunctionThatMightGiveError();
return 0;
}
Output is:
Error in APP!
Error in DLL!

i am exporting dll but GetProcAddress returning 127 error ,how to resolve it?

#include "Calc.h"
#include<iostream>
#include <windows.h>
#include <WINERROR.H.>
typedef void (WINAPI * PCTOR) ();
int main()
{
HMODULE hMod = LoadLibrary (L"Calci.dll");
if (NULL == hMod)
{
printf ("LoadLibrary failed\n");
return 1;
}
CCalc *pCCalc = (CCalc *) malloc (sizeof (CCalc));
if (NULL == pCCalc)
{
printf ("memory allocation failed\n");
return 1;
}
PCTOR pCtor = (PCTOR) GetProcAddress (hMod, "CCalc");//127 error
int err = GetLastError();
if (NULL == pCtor)
{
printf ("GetProcAddress failed\n");
return 1;
}
__asm { MOV ECX, pCCalc };
pCtor ();
return 0;
}
//dll file
#include <tchar.h>
#ifdef CALC_EXPORTS
#define CALC_API __declspec (dllexport)
#else
#define CALC_API __declspec (dllimport)
#endif
#define SOME_INSTN_BUF 260
class CALC_API CCalc
{
private:
char m_szLastUsedFunc[SOME_INSTN_BUF];
public:
CCalc ();
int Add (int i, int j);
int Sub (int i, int j);
TCHAR* GetLastUsedFunc ();
};
Use dumpbin.exe to check the exact name of the export in the DLL. Maybe it doesn't exist at all?
If you have a chance to use import library instead of LoadLibrary API, it is better.
You're invoking GetProcAddress (hMod, "CCalc"), however "CCalc" isn't the name of a function: it's the name of a class.
You're trying to load the address of the CCalc::CCalc default constructor: to do that, use a tool (e.g. dumpbin) to discover the "decorated" name of the constructor.
However instead of trying to dynamic-load and invoke the constructor, a more usual way to implement this functionality would be to create a static factory method in the DLL, e.g. like this:
class CALC_API CCalc
{
public:
static CCalc* create() { return new CCalc(); }
private:
//doesn't need to be public because users instantiate this class using
//the static create method
CCalc();
public:
virtual int Add (int i, int j);
virtual int Sub (int i, int j);
virtual TCHAR* GetLastUsedFunc ();
virtual ~CCalc() {}
};
Then use GetProcAddress to get the address of the static CCalc::create function, which because it's static you can invoke without using assembly to mess with ECX.
You can't use GetProcAddress for classes. This does not work. Only functions you can resolve their names are unmangled "C" functions.
For example:
extern "C" __declspec(dllexport) CCalc *create_calc()
{
return new CCalc;
}
Now, you can resolve it using.
GetProcAddress(halnder,"create_calc");
As create_calc is not-mangled function.
Also you will have to provide abstract API class without implementation and make CCalc inherit ACalc, otherwise you'll get unresolved symbols tying to compile your application. Because actual add and remove member functions are not known to the application.
class ACalc {
public:
virtual add(int i,int j) = 0;
...
virtaul ~ACalc() {}
};
class CCalc : public ACalc {
public:
virtual add(int i,int j) { ... };
...
};
And in the main program
ACalc *ptr= call_for_dll_function

Resources