What is the type of pthread_mutex_t? - pthreads

From: https://www.sourceware.org/pthreads-win32/manual/pthread_mutex_init.html
Variables of type pthread_mutex_t can also be initialized statically,
So, what is the type of pthread_mutex_t?

That is the type. The implementation underneath is often a struct and you can look in the header files if you really care about the specific implementation of the library you're using, but those details don't matter for using it, you just care about the pthread_mutex_t type.
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;

From pthreadtypes.h, in my Linux distribution its definition is pretty clear as a typedef for a union, as defined below:
/* Data structures for mutex handling. The structure of the attribute
type is not exposed on purpose. */
typedef union
{
struct __pthread_mutex_s
{
int __lock;
unsigned int __count;
int __owner;
/* KIND must stay at this position in the structure to maintain
binary compatibility. */
int __kind;
unsigned int __nusers;
__extension__ union
{
int __spins;
__pthread_slist_t __list;
};
} __data;
char __size[__SIZEOF_PTHREAD_MUTEX_T];
long int __align;
} pthread_mutex_t;
You'll want to use it as their defined type, pthread_mutex_t of course -- since this type will vary by OS / distribution / etc.

pthread_mutex_t is a type, so it doesn't have a type itself. If you are curious about what this type is an alias for, on my machine I have:
struct _opaque_pthread_mutex_t {
long __sig;
char __opaque[__PTHREAD_MUTEX_SIZE__];
};
and then
typedef struct _opaque_pthread_mutex_t __darwin_pthread_mutex_t;
and finally:
typedef __darwin_pthread_mutex_t pthread_mutex_t;

Related

How to create a table of linker-resolved data in non-dirty memory

I would like to create a table of data, and keep it in non-dirty memory (so that the table doesn't contribute to them memory usage of the app on iOS and related platforms (tvOS/watchOS)).
The table is an array of two pieces of data: Objective-C class and a numeric value:
#include <Foundation/Foundation.h>
struct TypeMap {
Class class;
int value;
};
I'd like to do something like this:
struct TypeMap map [] = {
{ [NSObject class], 0x1234 }
};
but that obviously doesn't work, clang complains with:
test.m:9:4: error: initializer element is not a compile-time constant
{ [NSObject class], 0x1234 }
^~~~~~~~~~~~~~~~
which makes total sense of course, since [NSObject class] is not a compile-time constant.
But there is a symbol that the dynamic loader is able to resolve: _OBJC_CLASS_$_NSObject, which leads me to something like this:
extern Class OBJC_CLASS_$_NSObject;
struct TypeMap map [] = {
{ OBJC_CLASS_$_NSObject, 0x1234 }
};
The idea being that the dynamic linker can resolve the symbol at runtime, and then mark the memory as read-only (the same way it works for normal code).
Unfortunately it runs into the same problem:
test.m:11:4: error: initializer element is not a compile-time constant
{ OBJC_CLASS_$_NSObject, 0x1234 }
^~~~~~~~~~~~~~~~~~~~~
I'm certain I can express this in assembly code, but I'd like to avoid assembly if possible and stick with Objective-C (no need to implement it once per platform).
Am I completely off track here? Is this even possible?
UPDATE
Working version:
// clang test.m -framework Foundation
#include <Foundation/Foundation.h>
#include <objc/objc.h>
#include <objc/runtime.h>
struct TypeMap {
Class class;
int value;
};
extern void* OBJC_CLASS_$_NSObject;
const struct TypeMap map [] = {
{ (Class) &OBJC_CLASS_$_NSObject, 0x1234 },
};
int main ()
{
printf ("%s %p %i\n", class_getName (map[0].class), map [0].class, map [0].value);
return 0;
}
If I understand correctly, a Class in Objective-C is an aggregate type, in the sense in which the C standard uses that term. Then, given
struct TypeMap {
Class class;
int value;
};
extern Class OBJC_CLASS_$_NSObject;
struct TypeMap map [] = {
{ OBJC_CLASS_$_NSObject, 0x1234 }
};
you are asking the dynamic loader to copy the aggregate into your data structure, at load time, which is not a feature that it has.
What you should be able to do instead is have your TypeMap contain pointers to the OBJC_CLASS_$_... symbols:
struct TypeMap {
Class *class;
int value;
};
extern Class OBJC_CLASS_$_NSObject;
const struct TypeMap map[] = {
{ &OBJC_CLASS_$_NSObject, 0x1234 },
// ...
};
Give that a whirl and see how it goes.
(Note the added const on the declaration of map — you need that to get this data structure put in the read-only data segment in the first place.)

Pre-R16B driver_async_port_key alternative

According to erl_driver documentation for driver_async_port_key function,
Before OTP-R16, the actual port id could be used as a key with proper casting, but after the rewrite of the port subsystem, this is no longer the case. With this function, you can achieve the same distribution based on port id's as before OTP-R16.
What is this proper casting?
The ErlDrvPort type is a typedef of a pointer to a struct. To obtain an unsigned int async key type in older driver applications, you need to convert this pointer type to unsigned int. One way to achieve this is to cast it through the C99 uintptr_t type, which is guaranteed to be large enough to hold a pointer value:
#include <stdint.h>
#include "erl_driver.h"
unsigned int my_port_key(ErlDrvPort port)
{
return (unsigned int) (uintptr_t) port;
}
You can write a portable function to return an async key using driver API versioning information available in erl_driver.h. The driver_async_port_key function was introduced in driver API version 2.2, so we can call driver_async_port_key when using version 2.2 or newer, or fall back to the casting approach for older versions:
#include <stdint.h>
#include "erl_driver.h"
unsigned int my_port_key(ErlDrvPort port)
{
#if ERL_DRV_EXTENDED_MAJOR_VERSION > 2 || \
(ERL_DRV_EXTENDED_MAJOR_VERSION == 2 && ERL_DRV_EXTENDED_MINOR_VERSION >= 2)
return driver_async_port_key(port);
#else
return (unsigned int) (uintptr_t) port;
#endif
}

About the parameter of function pthread_create?

We know that we call pthread like this:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void* arg);
Hi guys, i want to know why the return type of third parameter is void*? why not void?
Because there is no way for a start function to know what kind of data a developer wants to return from the function they use a void* that can point to any type. It is up to the developer of the start function to then cast the void* to appropriate type he actually returned before using whatever the void* points to. So now the start function can return a pointer that may in actually point to anything. If the start function is declared to return void, it means this function returns nothing, then what if the developer wants the start function to return a int, a struct? For example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
struct test {
char str[32];
int x;
};
void *func(void*) {
struct test *eg = (struct test *)malloc(sizeof(struct test));
strcpy(eg->str,"hello world");
eg->x = 42;
pthread_exit(eg);
}
int main (void) {
pthread_t id;
struct test *resp;
pthread_create(&id, NULL, func, NULL);
pthread_join(id,(void**)&resp);
printf("%s %d\n",resp->str,resp->x);
free(resp);
return 0;
}
More details on this post: What does void* mean and how to use it?

GNU Guile SCM to char*

I am relative new to FFI and GNU Guile, and I am writing bindings to a library that heavily uses char* variables. Here is code from function, that wraps C function:
static inline char*
scm_to_ascii_string(SCM string)
{
return SCM_UNBNDP(SCM) ? NULL
: scm_to_stringn(string, NULL, "ascii", SCM_FAILED_CONVERSION_ERROR);
}
SCM_DEFINE(func, "func", ...)
{
...
char *server_pass = scm_to_ascii_string(scm_server_pass);
char *username = scm_to_ascii_string(scm_username);
char *realname = scm_to_ascii_string(scm_realname);
}
Problem is that any call to conversion function can throw error, leaving me with memory leak.
What can I do about it?
You could make the output part an argument eg:
void scm_to_ascii_string(SCM string, char* &out);
edit:
I guess you meant what exception handler methods are there on the c side, I think there might be something on that in the manual in one of the two sections on programming stuff in C.

OpenCV Mat element types and their sizes

I'm confused by the OpenCV Mat element types. This is from the docs:
There is a limited fixed set of primitive data types the library can operate on.
That is, array elements should have one of the following types:
8-bit unsigned integer (uchar)
8-bit signed integer (schar)
16-bit unsigned integer (ushort)
16-bit signed integer (short)
32-bit signed integer (int)
32-bit floating-point number (float)
64-bit floating-point number (double)
...
For these basic types, the following enumeration is applied:
enum { CV_8U=0, CV_8S=1, CV_16U=2, CV_16S=3, CV_32S=4, CV_32F=5, CV_64F=6 };
It's known that C++ standard doesn't define the size of basic types in bytes, so how do they use such assumptions? And what type should I expect from, let's say, CV_32S, is it int32_t or int?
Developing from Miki's answer,
In OpenCV 3 definition has moved to modules/core/include/opencv2/core/traits.hpp, where you can find:
/** #brief A helper class for cv::DataType
The class is specialized for each fundamental numerical data type supported by OpenCV. It provides
DataDepth<T>::value constant.
*/
template<typename _Tp> class DataDepth
{
public:
enum
{
value = DataType<_Tp>::depth,
fmt = DataType<_Tp>::fmt
};
};
template<int _depth> class TypeDepth
{
enum { depth = CV_USRTYPE1 };
typedef void value_type;
};
template<> class TypeDepth<CV_8U>
{
enum { depth = CV_8U };
typedef uchar value_type;
};
template<> class TypeDepth<CV_8S>
{
enum { depth = CV_8S };
typedef schar value_type;
};
template<> class TypeDepth<CV_16U>
{
enum { depth = CV_16U };
typedef ushort value_type;
};
template<> class TypeDepth<CV_16S>
{
enum { depth = CV_16S };
typedef short value_type;
};
template<> class TypeDepth<CV_32S>
{
enum { depth = CV_32S };
typedef int value_type;
};
template<> class TypeDepth<CV_32F>
{
enum { depth = CV_32F };
typedef float value_type;
};
template<> class TypeDepth<CV_64F>
{
enum { depth = CV_64F };
typedef double value_type;
};
In most of the cases/compilers you should be fine using C++ exact data types. You wouldn't have problems with single byte data types (CV_8U -> uint8_t and CV_8U -> int8_t) as unambiguously defined in C++. The same for float (32bit) and double (64bit). However, it is true that for other data types to be completely sure you use the correct data type (for example when using the at<> method) you should use for example:
typedef TypeDepth<CV_WHATEVER_YOU_USED_TO_CREATE_YOUR_MAT>::value_type access_type;
myMat.at<access_type>(y,x) = 0;
As a side note, I am surprised they decided to take such an ambiguous approach, instead of simply using exact data types.
Therefore, regarding your last question:
What type should I expect from, let's say, CV_32S?
I believe the most precise answer, in OpenCV 3, is:
TypeDepth<CV_32S>::value_type
In core.hpp you can find the following:
/*!
A helper class for cv::DataType
The class is specialized for each fundamental numerical data type supported by OpenCV.
It provides DataDepth<T>::value constant.
*/
template<typename _Tp> class DataDepth {};
template<> class DataDepth<bool> { public: enum { value = CV_8U, fmt=(int)'u' }; };
template<> class DataDepth<uchar> { public: enum { value = CV_8U, fmt=(int)'u' }; };
template<> class DataDepth<schar> { public: enum { value = CV_8S, fmt=(int)'c' }; };
template<> class DataDepth<char> { public: enum { value = CV_8S, fmt=(int)'c' }; };
template<> class DataDepth<ushort> { public: enum { value = CV_16U, fmt=(int)'w' }; };
template<> class DataDepth<short> { public: enum { value = CV_16S, fmt=(int)'s' }; };
template<> class DataDepth<int> { public: enum { value = CV_32S, fmt=(int)'i' }; };
// this is temporary solution to support 32-bit unsigned integers
template<> class DataDepth<unsigned> { public: enum { value = CV_32S, fmt=(int)'i' }; };
template<> class DataDepth<float> { public: enum { value = CV_32F, fmt=(int)'f' }; };
template<> class DataDepth<double> { public: enum { value = CV_64F, fmt=(int)'d' }; };
template<typename _Tp> class DataDepth<_Tp*> { public: enum { value = CV_USRTYPE1, fmt=(int)'r' }; };
You can see that CV_32S is the value for the type int, not int32_t.
While C++ doesn't define the size of an element, the question is hypothetical: for systems OpenCV is run on, the sizes are known. Given
cv::Mat m(32,32,CV_32SC1, cv:Scalar(0));
std::cout << "size of the element in bytes: " << m.depth() << std::endl;
std::cout << "or " << m.step.p[ m.dims-1 ]/m.channels() << std::endl;
So how can you be sure it is int?
An attempt to call
int pxVal = m.at<int>(0,0);
will
CV_DbgAssert( elemSize()==sizeof(int) );
Where the left hand is defined via the cv::Mat::flags -- in this example as the predefined depth of the CV_32SC1 equal to
CV_DbgAssert( m.depth() == sizeof(int) )
or
CV_DbgAssert( 4 == sizeof(int) )
So if you succeeded you are left only the endianness. And that was checked when the cvconfig.h was generated (by CMake).
TL;DR, expect the types given in the header and you'll be fine.
You can find all definitions on your questions in opencv's sources.
See https://github.com/Itseez/opencv/blob/master/modules/core/include/opencv2/core/cvdef.h file.
I have found several #define in OpenCV's code related to CV_8UC1, CV_32SC1, etc. To make the enumerations work, OpenCV put additional codes to convert the plain numbers together as a parameter (i.e, CV_8UC1, CV_16UC2...are all represented by their respective numbers), and break the depth and channels apart in the definition of CvMat(I guess Mat may have similar codes in its definition). Then, it uses create() to allocate spaces for the matrix. Since create() is inline, I can only guess that it is similar to malloc() or something.
As source codes changes a lot from 2.4.9 to 3.0.0, I need to post more evidence later. Please allow me a little time to find out more and edit my answer.
In short the table you provided is correct.
If you want to directly access a pixel, you typecast it to the specifier to the right, for example CV_32S is a signed 32-bit.
The S always means a signed integral number (signed char, signed short, signed int)
The F always means a floating point number (float, double)
The U always means an unsigned integral number.
The enumeration is used only when creating or converting a Mat. It's a way of telling the mat which is the desired type, as I understand it it's the C predecessor to when templates were not used.
I use the C functionality exclusively, and in order to create an image, it would be an error to pass the following:
cvCreateImage(mySize,char, nChannels);
Instead, I pass the following:
cvCreateImage(mySize, IPL_DEPTH_8U, nChannels);
Here, the IPL_DEPTH_8U is a flag that is used by the function. The function itself has a switch-type statement that checks the flag. The actual value of the flag is most often meaningless as it's most often controlled by conditional, not algebraic statements.

Resources