I need to use pthreat but I dont need to pass any argument to the function. Therefore, I pass NULL to the function on pthread_create. I have 7 pthreads, so gcc compiler warns me that I have 7 unsued parameters. How can I define these 7 parameters as unused in C programming? If I do not define these parameters as unused, would it cause any problem? Thank you in advance for the responses.
void *timer1_function(void * parameter1){
//<statement>
}
int main(int argc,char *argv[]){
int thread_check1;
pthread_t timer1;
thread_check1 = pthread_create( &timer1, NULL, timer1_function, NULL);
if(thread_check1 !=0){
perror("thread creation failed");
exit(EXIT_FAILURE);
}
while(1){}
return 0;
}
You can cast the parameter to void like this:
void *timer1_function(void * parameter1) {
(void) parameter1; // Suppress the warning.
// <statement>
}
GCC has an "attributes" facility that can be used to mark unused parameters. Use
void *timer1_function(__attribute__((unused))void *parameter1)
Two commonly used techniques:
1) Omit the name of the unused parameter:
void *timer1_function(void *) { ... }
2) Comment out the parameter name:
void *timer1_function(void * /*parameter1*/) { ... }
-- Chris
By default, GCC does not produce this warning, not even with -Wall. I think the workaround shown in other question might be needed when you have no control over the environment, but if you do, just remove the flag (-Wunused-parameter).
It is perfectly fine not using a parameter in a function body.
To avoid the compiler warning (if any in your implementation), you can do this:
void *timer1_function(void * parameter1)
{
// no operation, will likely be optimized out by the compiler
parameter1 = parameter1;
}
Related
I'm trying to pass this function: void* checkMatrix(); as an argument to this function: void createThreads(void*(*f));.
I've read a post here so my decleration above is a result of this.
I'm calling the function like this: createThreads(checkMatrix); but it gives me a warning that type is incompatible [void** and void*()]. I can get around with a fast cast but it won't fix the problem.
Finally I write the function like this (simple initialization):
void createThreads(void* (*f)) {
pthread_t* a;
int i;
a = (pthread_t*) malloc(*arr.l * sizeof(pthread_t));
if (a == NULL) {
fprintf(stderr, "ERROR!\n");
exit(1);
}
for (i = 0; i < *arr.l; i++) {
if (pthread_create((a + i), NULL, (void*) &f, NULL)) {
fprintf(stderr, "ERROR IN THREAD CREATION!\n");
exit(2);
}
}
for (i = 0; i < *arr.l; i++)
pthread_join(*(a + i), NULL);
}
In conclusion, the problem is that it stops, with memory problem, but the cause is the creation of the threads and espacially in the 3rd argument that I specify the function that the thread will work on. I think I'm doing something wrong with the calling. I can't find the answer and can't get around it.
Thanks for your time!
void* (*f) is just void **f with a set of redundant parentheses. You probably wanted to use this for the parameter type:
void* (*f)()
However, that is not what pthread_create expects. The thread's main function is supposed to return void* and take a void* parameter. So what you really want is probably this:
void createThreads(void* (*f)(void*)) {
/* ... as before ... */
if (pthread_create((a + i), NULL, f, NULL)) {
/* ... as before ... */
}
To begin with void* checkMatrix(); is obsolete style and shouldn't be used. Second, pthread callback functions take void* as parameter. So use void* checkMatrix(void*); instead.
To pass it to a function, simply do
void createThreads (void* (*f)(void*))
Recommended practice when using function pointers is otherwise to use typedefs, to increase readability. For example you could cook up something like
typedef void* pthread_callback (void*);
void createThreads (pthread_callback* f)
Try changing the function signature to void createThreads(void* (*f)(void *))
and change the pthread_create function call topthread_create((a + i), NULL, f, NULL)
I have read that C does not support dynamic function calls. My program has an ever growing number of test cases implemented as separate functions like -
int testcase1(void);
int testcase2(void);
int testcase3(void);
Each time I add a new test case, I also have have to add the call to my main function like -
int main(int argc, char **argv){
assert(!testcase1());
assert(!testcase2());
assert(!testcase3());
}
I would prefer to call something like assert(!testcase*()) where * matches any string which resolves to a valid function name in my program.
Can you think of a more convenient solution?
If you all your testcases have same signature then you can use an array of function pointers:
void (*func[])() = { testcase1, testcase2 };
for (size_t i = 0; i < sizeof(func)/sizeof(func[0]); i++) {
assert(!func[i]());
}
The best solution is likely to write a few extra lines of code when you add new test cases - it really isn't a big issue. I would recommend something along the lines of the function pointer array, as suggested in another answer.
However, just to show that everything is possible in C if you throw ugly macros at the problem, here is a not recommended alternative:
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#define TEST_CASES \ // list of "x macros"
X(testcase1) \
X(testcase2) \
X(testcase3)
#define X(func) bool func (void); // declare function prototypes
TEST_CASES
#undef X
bool (*const test_cases[])(void) = // array of read-only function pointers
{
#define X(func) &func, // point at each function
TEST_CASES
#undef X
};
int main (void)
{
for(size_t i=0; i<sizeof(test_cases)/sizeof(test_cases[0]); i++)
{
assert(test_cases[i]());
}
}
bool testcase1 (void) { puts(__func__); return true; }
bool testcase2 (void) { puts(__func__); return true; }
bool testcase3 (void) { puts(__func__); return false; }
Output:
testcase1
testcase2
testcase3
Assertion failed!
For each new test case, you would only have to write a function definition and then add it to the "x macro" list TEST_CASES. However, you need very good reasons to introduce ugly tricks like these in production code!
You can use function pointers. Read also about closures (but C99 or C11 don't have them) and callbacks.
Many operating systems provide dynamic loading. On POSIX operating systems (such as Linux or MacOSX) you can get a function pointer (actually an address) from its name in some library (or in the program executable) using dlopen & dlsym. Other operating systems may provide similar functionalities.
At last, you should consider having your testing main function be generated by some script (or some program emitting C code), using metaprogramming techniques. So you would write something which generates the C code of your testing main having a long sequence of assert, and improve your build procedure (e.g. your Makefile if using make) to run appropriately that specialized C code generator. Details are of course specific to your code. You might add some conventions (e.g. add some special comment to be parsed by your test generator, etc...).
I decided to follow #Nominal Animal and #Basile Starynkevitch's approach. In mymainprog.c, I added -
int runtests(void){
void *testh;
int (*testp)(void);
char *dlmsg;
int rc;
char funcname[8];
int testnum;
testh = dlopen("libsmtests.so", RTLD_LAZY);
if (!testh){
printf("%s\n", dlerror());
return 1;
}
dlerror();
for (testnum =1; testnum < 1000; testnum++){
sprintf(funcname,"testcase%d", testnum);
*(void **) (&testp) = dlsym(testh, funcname);
dlmsg = dlerror();
if (dlmsg == NULL) {
rc = (*testp)();
printf("%s called, rc=%d\n", funcname, rc);
}
}
dlclose(testh);
return 0;
}
I add my testcases to a separate file (testcases.c) like this -
int testcase1(void){
return [some testcase expression]
}
int testcase2(void){
return [another testcase expression]
}
and then compile it as a shared library with position-independant code (-fPIC) to libsmtests.so. The advantage is slightly less typing since I don't need to code a call to testNNNN() after adding the implementation of a new functionint testcaseNNN(void) to testcases.c
I have a C program main routine which calls heirarchically several levels of functions. Eg :
main -> MyFunc -> MySubFunc -> MySub2Func
and I have a condition in MySub2Func which needs to be checked against a command line argument. Eg:
if (myvar == argv[1])
Other than passing argv as a parameter to subfunction , is there any other way I could acheive this. (because I need to do this in several functions lying at different heirarchical levels)
Each of the sub-functions lie in different C files. My aim is to perform a debug by temporarily checking a particular local variable against a cmd line argument (and taking further actions accordingly) .. hence modifying the entire heirarchy is unfortunately not desirable for my purpose.
[update from comment]
sorry that I forgot to mention .. i am trying to perform a debug by temporarily checking a particular local variable against a cmd line argument (and taking further actions accordingly) .. hence modifying the entire heirarchy is unfortunately not desirable for my purpose ..
The common approach is to "decouple" the two; the functions further down the call tree really shouldn't care or know about main()'s arguments, i.e. the command argument vector itself.
Instead, it should be abstracted into application-specific options, which are passed from main(), which parses the options out of the command line arguments, down to all application-specific functions that need them.
You might use global variables that are set in the main() function:
int g_argc;
char **g_argv;
int main(int argc, char **argv) {
g_argc = argc;
g_argv = argv;
MyFunc();
}
...
void MyFunc() {
MySubFunc();
}
...
void MySubFunc() {
MySub2Func();
}
...
void MySub2Func() {
if (myvar == g_argv[1]) {
do_the_thing();
}
}
As unwind said, the functions further down the chain should really not know anything about main's arguments. You should parse the command line arguments once setting the program's configuration. Additionally you should provide query functions for this configuration e.g.
/* --- config.c */
typedef struct {
int debug_enabled;
} config_t;
static config_t configuration;
int debug_enabled() {
return configuration->debug_enabled;
}
void initialize_config() {
/* set default parameters */
}
int set_config_from_cmd(int argc, char** argv){
/* parse CMD parameters and set config */
}
/* --- main.c */
int main(int argc, char** argv)
{
initialize_config();
if ( set_config_from_cmd(argc, argv) == -1 ) {
exit(-1);
}
/* do stuff, call functions */
}
int myfunction() {
if ( debug_enabled() ) {
printf("debug!");
}
/* do stuff */
}
Notice that I put the configuration related stuff into a separate file in order to hide the internals of the configuration structure. Only the interface e.g. debug_enabled() etc is exposed.
[for debugging]
Put this in a header included by all modules involved:
extern int g_argc;
extern char ** g_argv;
Define g_argc and g_argv globally in the main module
int g_argc = 0;
char ** g_argv = NULL;
Then in main() just do
int main(int argv, char ** argv)
{
g_argc = argc;
g_argv = argv;
and access g_argc and g_argv from the modules in question.
Hello. I am trying to make a fully thread-safe initialization function for my library and I couldn't easily find an alternative to pthread_once, which should solve the problem very easily. I've come to this code:
void libInit (void)
{
#ifdef WIN32
static volatile int initialized = 0;
static HANDLE mtx;
if (!initialized)
{
if (!mtx)
{
HANDLE mymtx;
mymtx = CreateMutex(NULL, 0, NULL);
if (InterlockedCompareExchangePointer(&mtx, mymtx, NULL) != NULL)
CloseHandle(mymtx);
}
WaitForSingleObject(mtx);
if (!initialized)
{
libInitInternal();
initialized = 1;
}
ReleaseMutex(mtx);
}
#else
static pthread_once_t initialized = PTHREAD_ONCE_INIT;
pthread_once(&initialized, libInitInternal);
#endif
}
The libInitInternal() call leads to a thread-unsafe function, that initializes the library.
I would like to hear any suggestions on what I could be doing wrong or whether you know about a better solution.
I think you want to use the One-Time Initialization functionality. In synchronous mode, all threads block until the first thread to call it completes. Seems analogous to pthread_once().
There is sample code here.
So in your case, you would say:
BOOL CALLBACK CallLibInitInternal(PINIT_ONCE InitOnce, PVOID Parameter, PVOID *lpContex) {
libInitInternal();
return TRUE;
}
void libInit() {
#ifdef WIN32
static INIT_ONCE s_init_once;
InitOnceExecuteOnce(&s_init_once, CallLibInitInternal, NULL, NULL);
#else
...
#endif
}
You might want to check what pthreads-win32 does in its pthread_once() implementaion. or just use that, if that proves to be easier.
After looking at the following source code for pthread_once() (from here), It looks like you're on the right track.
int pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
{
/* Check first for speed */
if (once_control->state == PTHREAD_NEEDS_INIT) {
pthread_mutex_lock(&(once_control->mutex));
if (once_control->state == PTHREAD_NEEDS_INIT) {
init_routine();
once_control->state = PTHREAD_DONE_INIT;
}
pthread_mutex_unlock(&(once_control->mutex));
}
return(OK);
}
btw, I'll be using pthread_once() to replace some rather convoluted functions in my code.
When using GCC or clang, you can use constructor and destructor attributes. These work for both shared and static libraries, and execute code before and after main is run, respectively. Additionally, you can specify multiple constructor and destructor functions. Much cleaner than the singleton approach, and doesn't require you to remember to call libInit() from your main().
static void __attribute__((constructor))
your_lib_init(void)
{
fprintf(stderr, "library init\n");
}
static void __attribute__((destructor))
vensim_ctx_destroy(void)
{
fprintf(stderr, "library destroy\n");
}
I would check out this article. It is a solution for C++ singletons, but I believe you can use the solution for your code as well: http://www.ddj.com/cpp/199203083?pgno=1
Sadly the listing for the QLock itself is missing, it looks as if they are trying to sell the CD, but there appears to be enough description of it to write one yourself.
I'm trying to execute something at the end of a function just before it returns to the caller.
To Do so, I would like to override return in a certain context. The behavior should be the same as __cyg_profile_func_exit, but I would like to activate it only for some functions.
I don't know if it's possible using gcc builtins or this kind of thing.
Thanks.
GCC has an attribute for this, which calls a function when an automatic variable goes out of scope, passing it the address of that variable
void cleanup_fn(int *p) {
puts("cleanup called...");
}
void f(void) {
int p __attribute__((cleanup(cleanup_fn)));
puts("in f...");
}
int main(void) {
puts("calling f...");
f();
puts("out of it...");
return 0;
}
Output:
calling f...
in f...
cleanup called...
out of it...
Nope, not in C per se.
What you could do is write a #define macro RETURN:
#define RETURN(func) if(_DEBUG_) func; return ;
#define RETURNV(func, val) if(_DEBUG_) func; return val ;
(Warning, you probably want to think a little more about guarding special cases than I have.)
Otherwise, you would need to write something that mangled the code behind the scenes, which is what profilers do.