create threaded class functions with arguments inside class - multithreading

I have an object of class AI, which has a private non static void function which has a lot of arguments: minmax(double& val,double alpha, double beta, unsigned short depth, board* thisTurn); because this is a very time intensive function I want to use a number of threads to run it concurrently, therefor I must create a thread with this function inside another function inside the AI class;
According toThis question to make threads inside member functions containing non static member functions wiht no arguments of said class, one must call:
std::thread t(&myclass::myfunc,this);
And according to this tutorial threads of fucntions with multiple arguments can be created as such:
std::thread t(foo,4,5)
where the function 'foo' has 2 integer arguments
However I desire to mix these to things, to call a function which has arguments, which is also a non static member function, from inside the class that it is a member of, and i am not sure how to mix these to things.
I have off course tried (remember that it is inside a function inside the AI class):
std::thread t(&AI::minmax,val,alpha,beta,depth,thisTurn,this);
and
std::thread t(&AI::minmax,this,val,alpha,beta,depth,thisTurn);
But both cases fails with a compile error like this:
error: no matching constructor for initialization of 'std::thread'
candidate constructor template not viable: requires single argument '__f', but
7 arguments were provided
My question is therefor, if or if not, it is even possiple to -- from inside a member function of a class -- call a non static member function which has several arguments as a thread, and if this is the case, how it is done.
This question is however not wether or not it is a good idea to use multithreading in my specific case.
Edit
After doing some testing i realized that i can not call functions with arguments as threads at all, not even non-member functions with only one argument called directly from main, this was however solved by asking this other question where i realized that i simply need to add the flag -std=c++11 (because apparantly macs don't always use all c++11 features as standard) after doing so the answer works fine.

You need to wrap references using std::ref. The following example compiles fine:
#include <iostream>
#include <thread>
class board;
class AI
{
public:
void minmax(double& val, double alpha, double beta, unsigned short depth, board* thisTurn)
{
std::cout << "minmax" << std::endl;
}
void spawnThread()
{
double val;
double alpha;
double beta;
unsigned short depth;
board* thisTurn;
std::thread t(&AI::minmax, this, std::ref(val), alpha, beta, depth, thisTurn);
t.join();
}
};
int main()
{
AI ai;
ai.spawnThread();
}

Related

Generating XPtr from Rcpp function

I am writing an R package in which one of the functions takes Rcpp::XPtr as an input (as a SEXP). However, the creation of XPtr from Rcpp::Function is something I want to do inside the package (i.e., the user should be able to input Function).
e.g, my package takes input generated as follows, which requires the user to write an additional function (here putFunPtrInXPtr()) and run the function in R to generate the XPtr (here my_ptr).
#include <Rcpp.h>
using namespace Rcpp;
typedef NumericVector (*funcPtr) (NumericVector y);
// [[Rcpp::export]]
NumericVector timesTwo(NumericVector x) {
return x * 2;
}
// [[Rcpp::export]]
XPtr<funcPtr> putFunPtrInXPtr() {
XPtr<funcPtr> testptr(new funcPtr(&timesTwo), false);
return testptr;
}
/*** R
my_xptr <- putFunPtrInXPtr()
*/
How can I write something in which the user provides Function user_fun and I create the XPtr?
I tried
XPtr<funcPtr> package_fun(Function user_fun_input){
XPtr<funcPtr> testptr(new funcPtr(&user_fun_input), false);
}
user_fun_input is the parameter name inside the package function, but I am getting the following error
cannot initialize a new value of type 'funcPtr' (aka 'Vector<14> (*) (Vector<14>') with an rvalue of type 'Rcpp::Function *' (aka 'Function_Impl<PreserveStorage> *')
Also, there is an R step involved in creating the pointer, I am not sure how to implement that in the package (my .cpp file).
I think the creation of XPtr from Function could be confusing to the user, so better to just take Function as input and create the pointer to it, inside the package. I do use the XPtr in my package to gain speed.
Suggestions are most appreciated!

Threads with same argument objects give different values

I have a problem where two threads with different functions and same argument objects result in giving different values for those objects.
To clearify, please observe the following code:
class Player(){
// Definition of Player here
// with get- and set functions
// for a certain value.
}
class Game(){
static void Draw(Player p){
while(1){
gotoxy(p.getValue(), 15);
cout << p.name();
}
}
static void Move(Player p){
int x = p.getValue();
while(1){
if(_kbhit()){
p.setValue(++x);
}
}
}
void startGame(){
Player pl1(5);
thread thd1(Move, pl1);
thread thd2(Draw, pl1);
thd1.join();
thd2.join();
}
}
While the value 'x' is changing in the function 'Move' for every key stroke, when getting that value in function 'Draw' still has the initial value for 'pl1' (which is 5).
How can I get 'Draw' to aquire the same value that 'Move' has given?
I appreciate any help and guidance.
Thank you in advance!
You are passing the player by value
static void Move(Player pl)
rather than by reference/pointer, so both functions have their own, local, copies of the original variable.
static void Move(Player& pl)
will take the variable by reference and give both functions access to the original variable.
Also, unless getValue and setValue implement some form of locking, this code is not thread safe.
The problem is that you are passing pl1 by value, when you want to be passing it by reference. Even though it looks like you are passing pl1 into each function, what's really going on is that the Move and Draw threads are each constructing new Player objects. If you pass by references, then both threads will refer to the same object as opposed to creating their own copies. Try changing the signatures of the functions to the following:
static void Move(Player &p);
static void Draw(Player &p);
Also, consider putting some exit condition into your function. Since while(1) will never exit, the join() functions will wait forever. Hope that helps!

__sync_bool_compare_and_swap with different parameter types in Cython

I am using Cython for fast parallel processing of data, adding items to a shared memory linked list from multiple threads. I use __sync_bool_compare_and_swap, which provides an atomic compare and swap (CAS) operation to compare if the value was not modified (by another thread) before replacing it with a new value.
cdef extern int __sync_bool_compare_and_swap (void **ptr, void *oldval, void *newval) nogil
cdef bint firstAttempt = 1
cdef type *next = NULL
cdef type *newlink = ....
while firstAttempt or not __sync_bool_compare_and_swap( <void**> c, <void*>next, <void*>newlink):
firstAttempt = 0
next = c[0]
newlink.next = next
This works very well. However, now I also want to keep track of the size of the linked list, and want to use the same CAS function for the updates, however, this time it is not pointers that need to be updated but an int. How can use the same external function twice in Cython, once with void** parameter and once with an int* parameter?
EDIT
What I have in mind is two separate atomic operations, in one atomic operation I want to update the linked list, in the other I want to update the size. You can do it in C, but for Cython it means you have to reference the same external function twice with different parameters, can that be done?
CONCLUSION
The answer suggested by DavidW works. In case anyone is thinking to use a similar construction, you should be aware that when using two separate update functions there is no guarantee these are processed in sequence (i.e. another thread can update in between), however, if the objective is to update a cumulative value for instance to monitor progress while multithreading or to create an aggregated result that is not used until all threads are finished, CAS does guarantee that all updates are done exactly once. Unexpectedly, gcc refuses to compile without casting to void*, so either define separate hard-typed versions, or you need to cast. A snippet from my code:
in some_header.h:
#define sync_bool_compare_and_swap_int __sync_bool_compare_and_swap
#define sync_bool_compare_and_swap_vp __sync_bool_compare_and_swap
in some_prog.pxd:
cdef extern from "some_header.h":
cdef extern int sync_bool_compare_and_swap_vp (void **ptr, void *oldval, void *newval) nogil
cdef extern int sync_bool_compare_and_swap_int (int *ptr, int oldval, int newval) nogil
in some_prog.pyx:
cdef void updateInt(int *value, int incr) nogil:
cdef cINT previous = value[0]
cdef cINT updated = previous + incr
while not sync_bool_compare_and_swap_int( c, previous, updated):
previous = value[0]
updated = previous + incr
So the issue (as I understand it) is that it's __sync_bool_compare_and_swap is a compiler intrinsic rather than a function, so doesn't really have a fixed signature, because the compiler just figures it out. However, Cython demands to know the types, and because you want to use it with two different types, you have a problem.
I can't see a simpler way than resorting to a (very) small amount of C to "help" Cython. Create a header file with a bunch of #defines
/* compare_swap.h */
#define sync_bool_compare_swap_voidp __sync_bool_compare_and_swap
#define sync_bool_compare_swap_int __sync_bool_compare_and_swap
You can then tell Cython that each of these is a separate function
cdef extern from "compare_swap.h":
int sync_bool_compare_swap_voidp(void**, void*, void*)
int sync_bool_compare_swap_int(int*, int, int)
At this stage you should be able to use them naturally as plain functions without any type casting (i.e. no <void**> in your code, since this tends to hide real errors). The C preprocessor will generate the code you want and all is well.
Edit: Looking at this a few years later I can see a couple of simpler ways you could probably use (untested, but I don't see why they shouldn't work). First you could use Cython's ability to map a name to a "cname" to avoid the need for an extra header:
cdef extern from *:
int sync_bool_compare_swap_voidp(void**, void*, void*) "__sync_bool_compare_and_swap"
int sync_bool_compare_swap_int(int*, int, int) "__sync_bool_compare_and_swap"
Second (and probably best) you could use a single generic definition (just telling Cython that it's a varargs function):
cdef extern from "compare_swap.h":
int __sync_bool_compare_and_swap(...)
This way Cython won't try to understand the types used, and will just defer it entirely to C (which is what you want).
I wouldn't like to comment on whether it's safe for you to use two atomic operations like this, or whether that will pass through a state with dangerously inconsistent data....

Call a JNI method from another JNI method

Is it possible to call a JNI C function inside another JNI C function? (directly or indirectly), or, a JNI function inside a normal C function?
For example:
int inverse_transform(double real[], double imag[], size_t n) {
return Java_com_example_ffttest_FFTActivity_transform(imag, real, n);
}
and inverse_transform() is later called inside another method.
JNIEXPORT jint JNICALL Java_com_example_ffttest_FFTActivity_convolve(...)
{
....
inverse_transform();
}
Does this work? I tried but it gives me errors about parameters and I don't know how to use *env and obj.
Certainly it's possible. Those are just functions with funny names as far as C is concerned.
One word of caution though - if the JNI function uses its JNIEnv parameter, you need to pass a valid one from a non-JNI function.
At the end JNI methods are normal c++ methods so offcourse you can do it .

trouble with .inl files c++

i have a trouble with a function template implementation in a .inl file (visual c++)
I have this on a header file.
math.h ->>
#ifndef _MATH_H
#define _MATH_H
#include <math.h>
template<class REAL=float>
struct Math
{
// inside this structure , there are a lot of functions , for example this..
static REAL sin ( REAL __x );
static REAL abs ( REAL __x );
};
#include "implementation.inl" // include inl file
#endif
and this is the .inl file.
implementation.inl -->>
template<class REAL>
REAL Math<REAL>::sin (REAL __x)
{
return (REAL) sin ( (double) __x );
}
template<class REAL>
REAL Math<REAL>::abs(REAL __x)
{
if( __x < (REAL) 0 )
return - __x;
return __x;
}
the sine function throw me an error at run time when i call it. However , abs function works
correctly.
i think the trouble is the call to one of the functions of the header math.h inside the .inl files
why I canĀ“t use math.h functions inside .inl file ?
The problem has nothing to do with .inl files - you're simply calling Math<REAL>::sin() recursively until the stack overflows. In MSVC 10 I even get a nice warning pointing that out:
warning C4717: 'Math<double>::sin' : recursive on all control paths, function will cause runtime stack overflow
Try:
return (REAL) ::sin ( (double) __x ); // note the `::` operator
Also, as a side note: the macro name _MATH_H is reserved for use by the compiler implementation. In many cases of using an implementation-reserved identifier you'd be somewhat unlucky to actually run into a conflict (though you should still avoid such names). However, in this case that name has a rather high chance of conflicting with the one that math.h might actually be using to prevent itself from being included multiple times.
You should definitely choose a different name that's unlikely to conflict. See What are the rules about using an underscore in a C++ identifier? for the rules.

Resources