Is the Gettimeofday Function Thread Safe in Linux

Is the gettimeofday function thread safe in Linux?

gettimeofday is thread safe.

The (posix) functions listed here might not be, gettimeofday is not one of them.

Is gettimeofday async signal safe ? and can it cause deadlock if used in signal handler?

gettimeofday is not defined as async-signal-safe, but if you pass 0 for the second (timezone) argument, it doesn't have to do anything that time and clock_gettime (both of which are officially async-signal-safe) don't also do, so as a matter of QoI it should be async-signal-safe in that case.

Your deadlock is inside the internal libc function __tz_convert.

#2  0x00007fc1b2d70d47 in __tz_convert () from /lib64/libc.so.6
#3 0x00000000004708f7 in Logger::getCurrentTimestamp(char*) ()

It appears to have been called directly from Logger::getCurrentTimestamp, but that's because it was "tail called" from a documented API function. There are only four functions in GNU libc that call __tz_convert (I grepped the source code): localtime, localtime_r, gmtime, and gmtime_r. Therefore, your problem is not that you are calling gettimeofday, but that you are calling one of those functions.

localtime and gmtime are obviously not async-signal-safe since they write to a global variable. localtime_r and gmtime_r are not async-signal-safe either, because they have to look at the global database of timezone information (yes, even gmtime_r does this — it might be possible to change it not to need to do that, but it still wouldn't be a thing you could rely on cross-platform).

I don't think there's a good workaround. Formatted output from an async signal handler is going to trip over all kinds of other problems; my advice is to restructure your code so that you never need to call logging functions from async signal handlers.

How do I measure time per thread in C?

You can certainly use gettimeofday inside the thread function itself. Using local (stack) variables is completely thread-safe - every thread runs on its own stack (by definition).

void* doSomeThing(void *arg){
struct timeval t0, t1, dt;

gettimeofday(&t0, NULL);

// do work

gettimeofday(&t1, NULL);

timersub(&t1, &t0, &dt);

fprintf(stderr, "doSomeThing (thread %ld) took %d.%06d sec\n",
(long)pthread_self(), dt.tv_sec, dt.tv_usec);
}

If you put the same code around pthread_create(), you would only see the amount of time it took for the thread to be created, not executed. If pthread_create blocked until the thread completed, there would be no point in ever using threads!

how to time the program running time thread included

I think you can use gettimeofday() function to get the start time and end time. While this function work only in Linux. Please refer to [1]:http://linux.die.net/man/2/gettimeofday

For this function in windows, please refer to [2]:Equivalent of gettimeday() for Windows

Is it a good idea to give a real time clock its own thread?

Your best option is to use a threadsafe time getter. gettimeofday is one such function (see here: Is the gettimeofday function thread safe in Linux?). It gives you seconds and microseconds since the unix epoch, so should easily be accurate enough for logging. What you do with the data you get out of that function is up to you, as long as you don't use any functions which have internal buffers, etc.

You should also be careful about how you write your logs. The safest way is to use separate files for each thread, but you can use mutex locks as well.

thread safe writing to a stream in c++ by multiple thread

A little searching on google and it looks like ostringstream is not thread safe.

To get what you want you could roll your own logging.

One method would be to write to the end of a large buffer:

uint64_t offset = 0;
char buffer[ 200000 ];

Write to it using a mutex:

mtx.lock(); 
offset += sprintf( buffer + offset, "\nfoo,%s,%d,%s", str, i, now_str().c_str() );
mtx.unlock();

C: using clock() to measure time in multi-threaded programs

clock() measure the CPU time used by your process, not the wall-clock time. When you have multiple threads running simultaneously, you can obviously burn through CPU time much faster.

If you want to know the wall-clock execution time, you need to use an appropriate function. The only one in ANSI C is time(), which typically only has 1 second resolution.

However, as you've said you're using POSIX, that means you can use clock_gettime(), defined in time.h. The CLOCK_MONOTONIC clock in particular is the best to use for this:

struct timespec start, finish;
double elapsed;

clock_gettime(CLOCK_MONOTONIC, &start);

/* ... */

clock_gettime(CLOCK_MONOTONIC, &finish);

elapsed = (finish.tv_sec - start.tv_sec);
elapsed += (finish.tv_nsec - start.tv_nsec) / 1000000000.0;

(Note that I have done the calculation of elapsed carefully to ensure that precision is not lost when timing very short intervals).

If your OS doesn't provide CLOCK_MONOTONIC (which you can check at runtime with sysconf(_SC_MONOTONIC_CLOCK)), then you can use CLOCK_REALTIME as a fallback - but note that the latter has the disadvantage that it will generate incorrect results if the system time is changed while your process is running.

What is the best way to get tight timing of a thread in c (pthreads)

You're at the mercy of the granularity of the process scheduler you're using. 10ms is probably achievable but remember when sleeping that the operating system will not schedule it immediately when it is available to be woken up. If other processes are ahead of it they may be chosen to run instead so you may be delayed.

Your approach is a good (or as good) of an approximation as you can get.

If you require better scheduling you can look into compiling a Linux kernel with real time options enabled which will give you a finer scheduling granularity.



Related Topics



Leave a reply



Submit