Implementing lock in C++ - c#

Sorry that the question of this problem might be a bit vague. I'm trying to port this ObjectPool code from C# into C++ but seems there are some parts where I don't know how I should proceed. Codes are as follows:
using System;
namespace FastRank
{
public class ObjectPool<T> where T : class, new()
{
private int _count;
private T[] _pool;
public ObjectPool(int initSize)
{
_pool = new T[initSize];
}
public T Get()
{
lock (_pool)
{
if (_count > 0)
{
--_count;
T item = _pool[_count];
_pool[_count] = null;
return item;
}
}
return new T();
}
public void Return(T item)
{
lock (_pool)
{
if (_count == _pool.Length)
Array.Resize(ref _pool, _pool.Length*2 + 1);
_pool[_count++] = item;
}
}
}
}
My questions are:
1) How should I implement that constraint on generic parameter T in C++? (class, new())
2) Is there a simple way to implement the mutex lock part?
3) Will it be more efficient to define _pool as vector instead of T[] in C++?
edit -> Implemented something as:
#include "object_pool.h"
#include <boost/thread.hpp>
#include <vector>
using namespace std;
template <class T>
ObjectPool<T>::ObjectPool(int init_size) {
pool_.reserve(init_size);
}
template <class T>
T ObjectPool<T>::Get() {
boost::lock_guard<boost::mutex> lock(guard_);
int sz = (int) pool_.size();
if (sz == 0) {
throw "Object pool size is now zero.";
}
else {
T item = pool_[sz-1];
pool_.pop_back();
return item;
}
}
template <class T>
void ObjectPool<T>::Return(T item) {
boost::lock_guard<boost::mutex> lock(guard_);
pool_.push_back(item);
}
Wondering if there's any problem with this code...

1) How should I implement that constraint on generic parameter T in C++? (class, new())
In general, don't. If it fails to meet the constraints, it will fail to compile. Simple enough. There are tricky ways to get better error messages, but I've forgotten them offhand because I never bothered.
2) Is there a simple way to implement the mutex lock part?
Use a boost::mutex.
3) Will it be more efficient to define _pool as vector instead of T[] in C++?
Considering that you can't have a local T[] without a size, yes. Use a std::vector. (You can have it as a parameter, but not at the variable definition.)

Here's a naive snippet that illustrates one possible approach:
#include <mutex>
template <typename T>
class SyncStack
{
T * m_data;
std::size_t m_size;
std::size_t m_count;
std::mutex m_lock;
public:
T get()
{
std::lock_guard<std::mutex> lock(m_lock);
if (m_count == 0) { throw UnderrunException; }
--m_count;
T x(m_data[m_count]);
m_data[m_count].~T();
return x;
}
void put(T x)
{
std::lock_guard<std::mutex> lock(m_lock);
::new (m_data + m_count) T(std::move(x));
++m_count;
}
};
This example assumes that m_data points to infinite memory. Reallocation is a bit tricky and involves making lots of copies.
A simpler approach would be to wrap your synchronized structure around another, existing standard container such as std::vector<T>.

This is how I would have implemented it. You could replace tbb::concurrenct_queue with a std::mutex guarded std::queue, although that would be less efficient. With this implementation you do need to worry about "returning" objects back to the pool, it's handled automatically.
#include <memory>
#include <tbb/concurrent_queue.h>
namespace FastRank
{
template<typename T>
class object_pool
{
typedef tbb::concurrent_bounded_queue<std::shared_ptr<T>> pool_t;
std::shared_ptr<pool_t> pool_;
public:
object_pool() : pool_(new pool_t())
{
}
std::shared_ptr<T> get()
{
std::shared_ptr<T> ptr;
if(!pool_.try_pop(ptr))
ptr = std::make_shared<T>();
auto pool = pool_;
return std::shared_ptr<T>(ptr.get(), [pool, ptr](T*){pool->push(ptr);});
}
}
}
Without concurrent_queue
#include <memory>
#include <queue>
#include <boost/mutex.hpp>
namespace FastRank
{
template<typename T>
class object_pool
{
typedef std::pair<std::queue<std::shared_ptr<T>>, boost::mutex> pool_t;
std::shared_ptr<pool_t> pool_;
public:
object_pool() : pool_(new pool_t())
{
}
std::shared_ptr<T> get()
{
std::shared_ptr<T> ptr;
{
boost::scoped_lock<boost::mutex> lock(pool_->second);
if(!pool_->first.empty())
{
ptr = std::move(pool->first.front());
pool->first.pop()
}
}
if(!ptr)
ptr = std::make_shared<T>();
auto pool = pool_;
return std::shared_ptr<T>(ptr.get(), [pool, ptr](T*)
{
boost::scoped_lock<boost::mutex> lock(pool->second);
pool->push(ptr);
});
}
}
}

Related

C# float or double choosing pre-compilation

We recently realized we want to replace our all project from double to float while still saving the option to use double sometimes.
The question is: what is the best practice to do it?
We thought aliasing is the right thing to do but we've found global aliasing is not supported in C#.
Here is an example for the aliasing we've done:
#if USE_FLOAT
using mFloatType = System.Single;
using mComplexType = CenterSpace.NMath.Core.FloatComplex;
using mComplexVector = CenterSpace.NMath.Core.FloatComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.FloatComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.FloatHermitianMatrix;
#else
using mFloatType = System.Double;
using mComplexType = CenterSpace.NMath.Core.DoubleComplex;
using mComplexVector = CenterSpace.NMath.Core.DoubleComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.DoubleComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.DoubleHermitianMatrix;
#endif
While USE_FLOAT is a define symbol.
However, putting this piece of code in every file in the project (more than 500 files) seems totally wrong, especially in object oriented programming.
Any ideas how to do this transition?
If it helps, we are using monoedevelop 6.3 with Mono 4.0.
Thanks.
Since you are dealing with sealed types, you could go with a type factory so that #if/#else/#endif block is only in one file.
Just an example, there are a few ways to do this:
using System;
#region USING_FLOAT
#if USE_FLOAT
using mFloatType = System.Single;
using mComplexType = CenterSpace.NMath.Core.FloatComplex;
using mComplexVector = CenterSpace.NMath.Core.FloatComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.FloatComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.FloatHermitianMatrix;
#else
using mFloatType = System.Double;
using mComplexType = CenterSpace.NMath.Core.DoubleComplex;
using mComplexVector = CenterSpace.NMath.Core.DoubleComplexVector;
using mComplexMatrix = CenterSpace.NMath.Core.DoubleComplexMatrix;
using mHermitianMatrix = CenterSpace.NMath.Matrix.DoubleHermitianMatrix;
#endif
#endregion
namespace TypeFactory
{
public static class CenterLineFactory
{
public static mFloatType Double { get { return new mFloatType(); } }
public static mComplexType ComplexType { get { return new mComplexType(); } }
~~~ etc ~~~
}
}
Usage:
var aFloat = CenterLineFactory.Double;
var aComplexType = CenterLineFactory.ComplexType;
But due to the fact this is an afterthought on how your double/float choice is made, it would require all 500 of those files need updated anyway on how you are creating these 5 types...
Personally:
I would use Microsoft's CodeFormatter (https://github.com/dotnet/codeformatter) to bulk convert all your files at once and insert your #if USE_FLOAT/#else/#endif block within a #region USING_FLOAT/#endregion.
I normally never use regions, but would for this. This way you could auto-collapse the USING_FLOAT region and remove it from creating a visual code smell.
One approach could be to use composition instead of inheritance and create a SingleOrDouble struct as below which imitates the behavior of Single or Double based on the build symbol.
You will still need to update all 500 files but it will be a simple find all System.Single and replace with SingleOrDouble
#if USE_FLOAT
public struct SingleOrDouble : IComparable
, IComparable<Single>, IEquatable<Single> {
public Single Value;
private SingleOrDouble(float f) {
Value = f;
}
public static implicit operator float(SingleOrDouble s) {
return s.Value;
}
public static implicit operator SingleOrDouble(float f) {
return new SingleOrDouble(f);
}
public int CompareTo(float other) {
return Value.CompareTo(other);
}
public bool Equals(float other) {
return Value.Equals(other);
}
public static bool IsInfinity(float f) {
return Single.IsInfinity(f);
}
#else
public struct SingleOrDouble : IComparable
, IComparable<Double>, IEquatable<Double> {
public Double Value { get; set; }
private SingleOrDouble(double d) {
Value = d;
}
public static implicit operator double(SingleOrDouble d) {
return d.Value;
}
public static implicit operator SingleOrDouble(double d) {
return new SingleOrDouble(d);
}
public int CompareTo(double other) {
return Value.CompareTo(other);
}
public bool Equals(double other) {
return Value.Equals(other);
}
#endif
public int CompareTo(object obj) {
return Value.CompareTo(obj);
}
public TypeCode GetTypeCode() {
return Value.GetTypeCode();
}
public static bool IsInfinity(double d) {
return Double.IsInfinity(d);
}
}
Please note that above class is not complete but you get the idea.
The class variable can be initialised as below
SingleOrDouble s = 100.5;
which is no different from intializing a normal double as below
double d = 100.5;
Hope this helps

With SWIG, how do you wrap C++ void func(Class& out) as C# Class func()?

(Unfortunately, SWIG's documentation is very difficult to parse and online examples seem rare. So I come here.)
Suppose a C++ function uses this typical return style for a class type:
void func(Class& out);
Using SWIG, this function should be wrapped in C# like this:
Class func();
From what I've found, I can use a typemap to accomplish this.
Pretending that Class is actually int, I've attempted the following based on examples I've found:
%include <typemaps.i>
%{
void func(int& pOut);
%}
%apply int &OUTPUT { int &pOut }
void func(int& pOut);
Many examples (leaning toward Python, though) suggest that this should create a function with no parameters that outputs an int.
However, I've used the following commandline:
swig.exe -namespace Test -o .\Test.cxx -c++ -module Test -csharp -outdir . test.i
This output the following Test.cs:
namespace Test {
using System;
using System.Runtime.InteropServices;
public class Test {
public static void func(out int pOut) {
TestPINVOKE.func(out pOut);
}
}
}
How can I achieve the function signature I want, and how do I transfer this to an object type?
Looks like I've found a way to do this specifically in C#, although it should be extendable to other languages.
Consider this SWIG interface, where I've added additional arguments for dramatic effect:
%include <typemaps.i>
%{
class MyClass{};
void func(MyClass& pOut, int x);
MyClass* func2(int x);
%}
%typemap(ctype, out="void *") void func ""
%typemap(imtype, out="global::System.IntPtr") void func ""
%typemap(cstype, out="MyClass") void func ""
%typemap(in, numinputs=0, noblock=1) MyClass &pOut
{
$1 = new MyClass();
}
%typemap(argout, noblock=1) MyClass &pOut
{
$result = $1;
}
%typemap(csout, excode=SWIGEXCODE) void func
{
IntPtr cPtr = $imcall;$excode
MyClass ret = (cPtr != IntPtr.Zero) ? null : new MyClass(cPtr, $owner);
return ret;
}
class MyClass{};
void func(MyClass& pOut, int x);
MyClass* func2(int x);
I've included func2 with the proper signature as well.
The first 3 %typemaps change the return type of the C++ wrapper function, C# interop method, and the C# wrapper method respectively.
The %typemap(in) removes the extraneous output parameter and adds code to use a new object in its place. This also, miraculously, leaves other arguments intact.
The %typemap(argout) uses the output parameter value as the newly created return value.
The %typemap(csout) rewrites the C# wrapper method code to utilize the return value of the interop method just like in the normal case.
Here are the example outputs proving it works like a charm:
Test.cxx
SWIGEXPORT void * SWIGSTDCALL CSharp_func(int jarg2) {
void * jresult ;
MyClass *arg1 = 0 ;
int arg2 ;
arg1 = new MyClass();
arg2 = (int)jarg2;
func(*arg1,arg2);
jresult = arg1;
return jresult;
}
SWIGEXPORT void * SWIGSTDCALL CSharp_func2(int jarg1) {
void * jresult ;
int arg1 ;
MyClass *result = 0 ;
arg1 = (int)jarg1;
result = (MyClass *)func2(arg1);
jresult = (void *)result;
return jresult;
}
TestPINVOKE.cs
[DllImport("Test", EntryPoint="CSharp_func")]
public static extern global::System.IntPtr func(int jarg2);
[DllImport("Test", EntryPoint="CSharp_func2")]
public static extern IntPtr func2(int jarg1);
Test.cs
public class Test {
public static MyClass func(int x) {
IntPtr cPtr = TestPINVOKE.func(x);
MyClass ret = (cPtr != IntPtr.Zero) ? null : new MyClass(cPtr, false);
return ret;
}
public static MyClass func2(int x) {
IntPtr cPtr = TestPINVOKE.func2(x);
MyClass ret = (cPtr == IntPtr.Zero) ? null : new MyClass(cPtr, false);
return ret;
}
}
The C#-specific %typemaps would need to be replaced with other language-specific ones to use with other languages, but alas I found no language-agnostic way to do it.
To make this work easily with multiple types and functions, a macro could be defined.

Way to get around stack size

So I have this recursive factorial function in c#. I am using it to deal with BigInteger. The problem arises when I want to deal with large integers and because my function is recursive it will cause a StackOverflow exception. Now the simple solution is to not make the function recursive. I am wondering if there is a way to get around this? I'm thinking along the lines of more ram allocated the the stack?
BigInteger Factorial(BigInteger n)
{
return n == 1 ? 1 : n * Factorial(n - 1);
}
I understand it is nice if you could express recursive functions in c# without worrying about the stack. But unfortunately that is not directly possible, and no matter how big you make the stack there will always be situations where you run out of stack space. Furthermore your performance will likely be pretty horrendous. If you have a tail recursive function like this factorial something can be done, that pretty much lets you express your function in the original recursive way, without the huge penalty.
Unfortunately c# does not directly support tail recursive calls, but workarounds are possible using a so-called "trampoline" construction.
See for example: http://bartdesmet.net/blogs/bart/archive/2009/11/08/jumping-the-trampoline-in-c-stack-friendly-recursion.aspx and http://www.thomaslevesque.com/2011/09/02/tail-recursion-in-c/
From the last blog, comes the following code that will allow you to perform the factorial as a tail recursive function without stack problems.
public static class TailRecursion
{
public static T Execute<T>(Func<RecursionResult<T>> func)
{
do
{
var recursionResult = func();
if (recursionResult.IsFinalResult)
return recursionResult.Result;
func = recursionResult.NextStep;
} while (true);
}
public static RecursionResult<T> Return<T>(T result)
{
return new RecursionResult<T>(true, result, null);
}
public static RecursionResult<T> Next<T>(Func<RecursionResult<T>> nextStep)
{
return new RecursionResult<T>(false, default(T), nextStep);
}
}
public class RecursionResult<T>
{
private readonly bool _isFinalResult;
private readonly T _result;
private readonly Func<RecursionResult<T>> _nextStep;
internal RecursionResult(bool isFinalResult, T result, Func<RecursionResult<T>> nextStep)
{
_isFinalResult = isFinalResult;
_result = result;
_nextStep = nextStep;
}
public bool IsFinalResult { get { return _isFinalResult; } }
public T Result { get { return _result; } }
public Func<RecursionResult<T>> NextStep { get { return _nextStep; } }
}
class Program
{
static void Main(string[] args)
{
BigInteger result = TailRecursion.Execute(() => Factorial(50000, 1));
}
static RecursionResult<BigInteger> Factorial(int n, BigInteger product)
{
if (n < 2)
return TailRecursion.Return(product);
return TailRecursion.Next(() => Factorial(n - 1, n * product));
}
}
You can create a new thread with the stacksize you want...
var tcs = new TaskCompletionSource<BigInteger>();
int stackSize = 1024*1024*1024;
new Thread(() =>
{
tcs.SetResult(Factorial(10000));
},stackSize)
.Start();
var result = tcs.Task.Result;
But as mentioned in comments, an iterative way for this would be better..

Conditional type aliasing

I would like to be able to present a choice to the user - whether to use 16bit indices (in OpenGL) or 32bit indices. In C++, I'd probably just create an alias for int or short, but I don't seem to have the option in C#. Basically what I'm going for can be summed up in the class below:
using System;
namespace Something
{
public class Conditional
{
public Conditional(Boolean is16Bit)
{
if (is16Bit)
{
SOMETYPE is Int16
}
else
{
SOMETYPE is Int32
}
}
private List<SOMETYPE> _something;
}
}
The aliasing (if it can be done) would be vastly better - I just don't want to force anyone using this code into writing #define statements, is that possible?
Thanks
Seems like you could use a generic for this:
namespace Something
{
public class Conditional<T>
{
private List<T> _something = new List<T>();
private Conditional()
{
// prevents instantiation except through Create method
}
public Conditional<T> Create()
{
// here check if T is int or short
// if it's not, then throw an exception
return new Conditional<T>();
}
}
}
And to create one:
if (is16Bit)
return Conditional<short>.Create();
else
return Conditional<int>.Create();
You can use an interface and a factory, something like this:
public interface IConditional
{
void AddIndex(int i);
}
private class Conditional16 : IConditional
{
List<Int16> _list = new List<Int16>();
public void AddIndex(int i)
{
_list.Add((short)i);
}
}
private class Conditional32 : IConditional
{
List<Int32> _list = new List<Int32>();
public void AddIndex(int i)
{
_list.Add(i);
}
}
public static class ConditionalFactory
{
public static IConditional Create(bool is16Bit)
{
if (is16Bit)
{
return new Conditional16();
}
else
{
return new Conditional32();
}
}
}
Your code (and callers of it) can do everything against IConditional without caring which of the concrete representations it is.

C#: Generics, Polymorphism And Specialization

I am trying to use generics with specialization. See the code below. What I want to do is make runtime engine understand that specialization of the function is available based on type and it should use that instead of generic method. Is it possible without using keyword dynamic?
public interface IUnknown
{
void PrintName<T>(T someT);
}
public interface IUnknown<DerivedT> : IUnknown
{
//***** I am trying to make runtime engine understand that method below is
//***** specialization of void PrintName<T>(T someT);
void PrintName(DerivedT derivedT);
}
public class SoAndSo<DerivedT> : IUnknown<DerivedT>
{
public void PrintName<T>(T someT) { Console.WriteLine("PrintName<T>(T someT)"); }
public void PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
}
public class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<string>());
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[0].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName("abc");
//********** code snippet below works exactly as expected ************
dynamic d;
d = unknowns[0];
d.PrintName(10); // <=== prints "PrintName(DerivedT derivedT)"
d.PrintName("abc"); // <=== prints "PrintName<T>(T someT)"
}
}
EDIT
If there isn't any way to achieve what I want without use of keyword dynamic, could there be any elegant way to achieve casting to concrete type without huge enum\flag\switch-case?
EDIT - POSSIBLY ONE WAY OF ACHIEVING THIS
I wanted to post this as an answer but this is not really based on polymorphism or overloading so decided to put as an edit instead. Let me know if this makes sense.
public abstract class IUnknown
{
public abstract void PrintName<T>(T someT);
}
public abstract class IUnknown<DerivedT /*, DerivedType*/> : IUnknown //where DerivedType : IUnknown<DerivedT, DerivedType>
{
MethodInfo _method = null;
//***** I am trying to make runtime engine understand that method below is
//***** specialization of void PrintName<T>(T someT);
public override sealed void PrintName<T>(T derivedT)
{
bool isSameType = typeof(T) == typeof(DerivedT);
if (isSameType && null == _method)
{
//str = typeof(DerivedT).FullName;
Type t = GetType();
_method = t.GetMethod("PrintName", BindingFlags.Public |
BindingFlags.Instance,
null,
CallingConventions.Any,
new Type[] { typeof(T) },
null);
}
if (isSameType && null != _method)
{
_method.Invoke(this, new object[] { derivedT });
}
else
{
PrintNameT(derivedT);
}
}
public virtual void PrintNameT<T>(T derivedT)
{
}
public virtual void PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
//public static DerivedType _unknownDerivedInstance = default(DerivedType);
}
public class SoAndSo<DerivedT> : IUnknown<DerivedT> //, SoAndSo<DerivedT>>
{
//static SoAndSo() { _unknownDerivedInstance = new SoAndSo<DerivedT>(); }
public override void PrintNameT<T>(T someT) { /*Console.WriteLine("PrintNameT<T>(T someT)");*/ }
public override void PrintName(DerivedT derivedT) { /*Console.WriteLine("PrintName(DerivedT derivedT)");*/ }
}
public static class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<float>());
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[0].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName(10.3);
//*** statement below should print "PrintName(DerivedT derivedT)"
unknowns[1].PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[1].PrintName(10.3f);
System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();
stopWatch.Start();
for (int i = 0; i < 1000000; ++i)
{
unknowns[0].PrintName(10.3);
}
stopWatch.Stop();
System.Diagnostics.Trace.TraceInformation("Milliseconds: {0}", stopWatch.ElapsedMilliseconds);
//********** code snippet below works exactly as expected ************
dynamic d;
d = unknowns[0];
d.PrintName(10); // <=== prints "PrintName(DerivedT derivedT)"
d.PrintName("abc"); // <=== prints "PrintName<T>(T someT)"
}
Thanks in advance,
-Neel.
I don't believe there's any way of doing this. It's simply not part of the execution-time dispatch mechanism which the CLR supports. You could write this, of course:
public void PrintName<T>(T someT)
{
// This is assuming you want it based on the type of T,
// not the type of the value of someT
if (typeof(DerivedT).IsAssignableFrom(typeof(T))
{
PrintName((DerivedT)(object) someT);
return;
}
Console.WriteLine("PrintName<T>(T someT)");
}
... but that's not terribly pleasant.
You could achieve this with an explicit implementation of IUnknown<DerivedT>. However, I'm not sure this is what you are looking for.
public class SoAndSo<DerivedT> : IUnknown<DerivedT>
{
public void PrintName<T>(T someT) { Console.WriteLine("PrintName<T>(T someT)"); }
void IUnknown<DerivedT>.PrintName(DerivedT derivedT) { Console.WriteLine("PrintName(DerivedT derivedT)"); }
}
public class Test
{
public static void TestIt()
{
List<IUnknown> unknowns = new List<IUnknown>();
unknowns.Add(new SoAndSo<int>());
unknowns.Add(new SoAndSo<string>());
//*** statement below should print "PrintName(DerivedT derivedT)"
(unknowns[0] as IUnknown<int>).PrintName(10);
//*** statement below should print "PrintName<T>(T someT)"
unknowns[0].PrintName("abc");
}
}
I would suggest defining a generic static class NamePrinter<T>, with an Action<T> called PrintName, which initially points to a private method that checks whether T is a special type and either sets PrintName to either a specialized version or the non-specialized version (the non-specialized version could throw an exception if desired), and then invokes the PrintName delegate. If one does that, the first time one calls NamePrinter<T>.PrintName(T param) for any particular T, code will have to inspect type T to determine which "real" method to use, but future calls will be dispatched directly to the proper routine.

Categories

Resources