How to use PAPI with C++11 std:thread? - c++11

I would like to use PAPI to get the overall counters of all C++11 std::thread threads in a program.
PAPI documentation on Threads says that:
Thread support in the PAPI library can be initialized by calling the following low-level function in C: int PAPI_thread_init(unsigned long(*handle)(void));
where the handle is a
Pointer to a routine that returns the current thread ID as an unsigned long.
For example, for pthreads the handle is pthread_self.
But, I have no idea what it should be with C++11 std::thread.
Nor if it makes more sense to use something different from PAPI.

C++11 threading support has the std::this_thread::get_id() function that returns a std::thread::id instance which can be serialized to a stream. Then you coud try to read an unsigned long from the stream and return ir. Something like this:
#include <thread>
#include <iostream>
#include <sstream>
unsigned long current_thread_id()
{
std::stringstream id_stream;
id_stream << std::this_thread::get_id();
unsigned long id;
id_stream >> id;
return id;
}
int main(int argc, char** argv)
{
std::cout << current_thread_id();
return 0;
}
So in this snippet the current_thread_id function is what you are looking for, but you should add proper error handling (the thread id may not always be a number, in that case you will not be able to read a number from the stream and you should handle that accordingly).
That being said, maybe just use GetCurrentThreadId , since you are already introducing the Linux specific pthread_self.

Related

how to using gtest in OpenMP parallel block?

I want to using gtest in openmp.
I want calculation something in parallel block, and check the thread private variable's result, and do more calculation.
Here is an example.
#include "gmock.h"
#include <iostream>
using namespace testing;
TEST(SimpleGtest, OpenMP)
{
#pragma omp parallel
{
// some thread private variable
int thread_index = omp_get_thread_num();
int z;
// some calculation
// ...
// check result of thread private variable
ASSERT_THAT(z, Eq(13));
// other calculation
// ...
}
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
but when I compile the code, the compiler complaint that:
error: "return" branches to or from an OpenMP structured block are illegal
ASSERT_THAT(z, Eq(13));
^
The code above is just a simple example.
I know we can not using "thread private variable" but using "thread shared variable" so we can do the assert out of parallel block.
But is there any solution that we can using gtest to check the thread private variable's result in OpenMP parallel block?
Thanks in advance!
do not using ASSERT_THAT in parallel block. EXPECT_EQ can help.

How do I convert a WCHAR * to a regular string?

So in Win32 API, I have my main function defined thus:
wmain(int argc, WCHAR* argv[])
I'm passing some arguments to it, and I'd like to execute a switch case based on the value of the argument, something like this.
wmain(int argc, WCHAR* argv[])
{
char* temp = argv[];
switch (temp) {
case "one": blah blah;
...
}
Of course, the temp=argv[] doesn't work, I'm looking for a suggestion to convert it. Right now I have an if-else-if thing going on, and it's VERY inefficient!
The reason I need to convert it is because I cannot execute a switch case on a WCHAR*.
Thanks for looking.
You can't execute a switch on a char* either. (But when you actually need to convert WCHAR* to char*, use WideCharToMultiByte)
You need to use if/else if with lstrcmpi, CompareString or some other string compare function.
Alternatively, use one of the parameter parser libraries like argtable or getopt
I am not sure if this is a good idea to do. A WCHAR* could contain unicode characters which cannot be mapped to a char* in a meaningful way. In case you want to ignore this, there is a forum post at http://www.codeguru.com/forum/showthread.php?t=336106 which has some suggestions for converting from WCHAR* to char*.
Try converting it from std::wstring to std::string, its easy, maybe there is a shorter way.
Convert WCHAR* to std::wstring using std::wstring constractor, and then use one of std::wstring method to convert to std::String
Here's a quick example I wrote some time ago.
Create a new win32 console application and select ATL support. Add this and compile/run...
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
// A _TCHAR is a typedef'd, depending on whether you've got a unicode or MBCS build
// ATL Conversion macros are documented here
// http://msdn.microsoft.com/en-us/library/87zae4a3(VS.80).aspx
// Declare USES_CONVERSION in your function before using the ATL conversion macros
// e.g. T2A(), A2T()
USES_CONVERSION;
TCHAR* pwHelloWorld = _T("hello world!");
wcout << pwHelloWorld << endl;
// convert to char
char* pcHelloWorld = T2A(pwHelloWorld);
cout << pcHelloWorld << endl;
cin.get();
return 0;
}
Of course, you can't switch on a string, but this should give you the info you need in order to read a WCHAR into a char. From there, you can convert to int easily enough..
Hope this helps ;)

OpenSSL and multi-threads

I've been reading about the requirement that if OpenSSL is used in a multi-threaded application, you have to register a thread identification function (and also a mutex creation function) with OpenSSL.
On Linux, according to the example provided by OpenSSL, a thread is normally identified by registering a function like this:
static unsigned long id_function(void){
return (unsigned long)pthread_self();
}
pthread_self() returns a pthread_t, and this works on Linux since pthread_t is just a typedef of unsigned long.
On Windows pthreads, FreeBSD, and other operating systems, pthread_t is a struct, with the following structure:
struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
}
This can't be simply cast to an unsigned long, and when I try to do so, it throws a compile error. I tried taking the void *p and casting that to an unsigned long, on the theory that the memory pointer should be consistent and unique across threads, but this just causes my program to crash a lot.
What can I register with OpenSSL as the thread identification function when using Windows pthreads or FreeBSD or any of the other operating systems like this?
Also, as an additional question:
Does anyone know if this also needs to be done if OpenSSL is compiled into and used with QT, and if so how to register QThreads with OpenSSL? Surprisingly, I can't seem to find the answer in QT's documentation.
I will just put this code here. It is not panacea, as it doesn't deal with FreeBSD, but it is helpful in most cases when all you need is to support Windows and and say Debian. Of course, the clean solution assumes usage of CRYPTO_THREADID_* family introduced recently. (to give an idea, it has a CRYPTO_THREADID_cmp callback, which can be mapped to pthread_equal)
#include <pthread.h>
#include <openssl/err.h>
#if defined(WIN32)
#define MUTEX_TYPE HANDLE
#define MUTEX_SETUP(x) (x) = CreateMutex(NULL, FALSE, NULL)
#define MUTEX_CLEANUP(x) CloseHandle(x)
#define MUTEX_LOCK(x) WaitForSingleObject((x), INFINITE)
#define MUTEX_UNLOCK(x) ReleaseMutex(x)
#define THREAD_ID GetCurrentThreadId()
#else
#define MUTEX_TYPE pthread_mutex_t
#define MUTEX_SETUP(x) pthread_mutex_init(&(x), NULL)
#define MUTEX_CLEANUP(x) pthread_mutex_destroy(&(x))
#define MUTEX_LOCK(x) pthread_mutex_lock(&(x))
#define MUTEX_UNLOCK(x) pthread_mutex_unlock(&(x))
#define THREAD_ID pthread_self()
#endif
/* This array will store all of the mutexes available to OpenSSL. */
static MUTEX_TYPE *mutex_buf=NULL;
static void locking_function(int mode, int n, const char * file, int line)
{
if (mode & CRYPTO_LOCK)
MUTEX_LOCK(mutex_buf[n]);
else
MUTEX_UNLOCK(mutex_buf[n]);
}
static unsigned long id_function(void)
{
return ((unsigned long)THREAD_ID);
}
int thread_setup(void)
{
int i;
mutex_buf = malloc(CRYPTO_num_locks() * sizeof(MUTEX_TYPE));
if (!mutex_buf)
return 0;
for (i = 0; i < CRYPTO_num_locks( ); i++)
MUTEX_SETUP(mutex_buf[i]);
CRYPTO_set_id_callback(id_function);
CRYPTO_set_locking_callback(locking_function);
return 1;
}
int thread_cleanup(void)
{
int i;
if (!mutex_buf)
return 0;
CRYPTO_set_id_callback(NULL);
CRYPTO_set_locking_callback(NULL);
for (i = 0; i < CRYPTO_num_locks( ); i++)
MUTEX_CLEANUP(mutex_buf[i]);
free(mutex_buf);
mutex_buf = NULL;
return 1;
}
I only can answer the Qt part. Use QThread::currentThreadId(), or even QThread::currentThread() as the pointer value should be unique.
From the OpenSSL doc you linked:
threadid_func(CRYPTO_THREADID *id) is needed to record the currently-executing thread's identifier into id. The implementation of this callback should not fill in id directly, but should use CRYPTO_THREADID_set_numeric() if thread IDs are numeric, or CRYPTO_THREADID_set_pointer() if they are pointer-based. If the application does not register such a callback using CRYPTO_THREADID_set_callback(), then a default implementation is used - on Windows and BeOS this uses the system's default thread identifying APIs, and on all other platforms it uses the address of errno. The latter is satisfactory for thread-safety if and only if the platform has a thread-local error number facility.
As shown providing your own ID is really only useful if you can provide a better ID than OpenSSL's default implementation.
The only fail-safe way to provide IDs, when you don't know whether pthread_t is a pointer or an integer, is to maintain your own per-thread IDs stored as a thread-local value.

GetUserDefaultLocaleName() API is crashing

I have one application which reads user default locale in Windows Vista and above. When i tried calling the API for getting User default Locale API is crashing. Below is the code, It will be helpfull if any points the reason
#include <iostream>
#include <WinNls.h>
#include <Windows.h>
int main()
{
LPWSTR lpLocaleName=NULL;
cout << "Calling GetUserDefaultLocaleName";
int ret = GetUserDefaultLocaleName(lpLocaleName, LOCALE_NAME_MAX_LENGTH);
cout << lpLocaleName<<endl;
}
You need to have lpLocaleName initialized to a buffer prior to calling the API. As a general consensus, if an API has a LPWSTR data type parameter, call malloc or new on it first, to the desired length, in this case, LOCALE_NAME_MAX_LENGTH. Setting it to NULL and passing it to the API function is a guaranteed way to crash!
Hope this helps,
Best regards,
Tom.
In addition to the previous answers, you should also be aware that you can't print a wide string with cout; instead, you should use wcout.
So:
#include <iostream>
#include <WinNls.h>
#include <Windows.h>
#define ARRSIZE(arr) (sizeof(arr)/sizeof(*(arr)))
using namespace std;
int main()
{
WCHAR_T localeName[LOCALE_NAME_MAX_LENGTH]={0};
cout<<"Calling GetUserDefaultLocaleName";
int ret = GetUserDefaultLocaleName(localeName,ARRSIZE(localeName));
if(ret==0)
cout<<"Cannot retrieve the default locale name."<<endl;
else
wcout<<localeName<<endl;
return 0;
}
I believe you need to initialise lpLocaleName to an empty string of 256 chars (for example) then pass the length (256) where you have LOCALE_NAME_MAX_LENGTH

Getting System Date in MSVC 6.0

I am trying to get system date in a C program on a MSVC++ 6.0 compiler. I am using a system call:
system("date /T") (output is e.g. 13-Oct-08 which is date on my system in the format i have set)
but this prints the date to the i/o console.
How do i make take this date as returned by above system call and store it as a string value to a string defined in my code?
Or
Is there any other API i can use to get the date in above mentioned format (13-Oct-08, or 13-10-08) ?
-AD
#include <windows.h>
#include <iostream>
int main() {
SYSTEMTIME systmDateTime = {};
::GetLocalTime(&systmDateTime);
wchar_t wszDate[64] = {};
int const result = ::GetDateFormatW(
LOCALE_USER_DEFAULT, DATE_SHORTDATE,
&systmDateTime, 0, wszDate, _countof(wszDate));
if (result) {
std::wcout << wszDate;
}
}
There are a couple of ways to do this using API functions, two that jump to mind are strftime and GetDateFormat.
I'd like to provide examples but I'm afraid I don't have a Win32 compiler handy at the moment. Hopefully the examples in the above documentation are sufficient.
Have a read of Win32 Time functions; GetLocalTime may be your friend. There are also the standard C time functions, time and strftime.
For future reference, in a C program, it is almost always the wrong answer to invoke an external utility and capture it's STDOUT.
Thanks for the pointers.
I used this and it served my purpose:
#include <time.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/timeb.h>
#include <string.h>
int main()
{
char tmpbuf[128];
time_t ltime;
struct tm *today;
_strdate( tmpbuf );
printf("\n before formatting date is %s",tmpbuf);
time(&ltime);
today = localtime( &ltime );
strftime(tmpbuf,128,"%d-%m-%y",today);
printf( "\nafter formatting date is %s\n", tmpbuf );
}
-AD

Resources