How to Print Pthread_T

How to print pthread_t

This will print out a hexadecimal representation of a pthread_t, no matter what that actually is:

void fprintPt(FILE *f, pthread_t pt) {
unsigned char *ptc = (unsigned char*)(void*)(&pt);
fprintf(f, "0x");
for (size_t i=0; i<sizeof(pt); i++) {
fprintf(f, "%02x", (unsigned)(ptc[i]));
}
}

To just print a small id for a each pthread_t something like this could be used (this time using iostreams):

void printPt(std::ostream &strm, pthread_t pt) {
static int nextindex = 0;
static std::map<pthread_t, int> ids;
if (ids.find(pt) == ids.end()) {
ids[pt] = nextindex++;
}
strm << ids[pt];
}

Depending on the platform and the actual representation of pthread_t it might here be necessary to define an operator< for pthread_t, because std::map needs an ordering on the elements:

bool operator<(const pthread_t &left, const pthread_t &right) {
...
}

HOw should I print the pthread ID in C++?

    for (int i = 1; i < argv[1]; ++i)

is wrong in your main (and the return ret is wrong in printer), because i is an integer, but argv[1] is of type char* so is a pointer. Perhaps you mean (in your main):

   int n = atoi(argv[1]);
for (int i=1; i<n; i++)

Remember to compile with all warnings and debug info: g++ -Wall -Wextra -g with GCC for C++ code, or gcc -Wall -Wextra -Wmissing-prototypes -g for C code. In C++, you could use <thread>. Improve your code to get no warnings at all. Read How To Debug Small Programs. Learn how to use the gdb debugger.

Notice that return -1 is bad taste inside your main (at least on Linux, see execve(2) and read about the relation between your main and the execve in your shell). You should return EXIT_FAILURE (or use exit on that).

BTW, pthread_t is usually some integral type, but the POSIX standard don't specify which one. If you want to print one, in practice you'll better cast it explicitly to some wide enough integral type such as long long and code printf("This is pthread %lld\n",(long long) self_id); which won't give you any warning.

At last, I recommend first learning a programming language (C is much simpler than C++, and you have to choose between both) and use it for sequential programming, and later learning pthreads. Parallel thread programming is an advanced topic. By starting with multithreaded programming, you put the bar really too high. Before attempting pthreads, learn the basic sequential programming. See also http://norvig.com/21-days.html for a useful insight.
BTW, if you have never programmed, SICP is an excellent introduction (it does not use C or C++ or threads).

Of course, you don't let your other threads run enough time. You could sleep a bit -in the main thread- before returning from main, and you really should wait for your threads, as explained by Martin York.

But I think you need to learn sequential programming before attempting multi-threading.

How to get thread id of a pthread in linux c program?

pthread_self() function will give the thread id of current thread.

pthread_t pthread_self(void);

The pthread_self() function returns the Pthread handle of the calling thread. The pthread_self() function does NOT return the integral thread of the calling thread. You must use pthread_getthreadid_np() to return an integral identifier for the thread.

NOTE:

pthread_id_np_t   tid;
tid = pthread_getthreadid_np();

is significantly faster than these calls, but provides the same behavior.

pthread_id_np_t   tid;
pthread_t self;
self = pthread_self();
pthread_getunique_np(&self, &tid);

print result with Pthread (main) C

The pthread_create function(spec) creates a new thread which will execute the function you pass to it (in this case Utskrift). The value value passed in pthread_create's last parameter is passed to the function.

If you simply wanted to call the Utskrift function in your main thread, you could do it the normal way:

Utskrift((void *)test));

If you want to pass data back from your completed thread to another thread, you can use pthread_join which will return either the value returned by your thread's start routine, or the value that thread passes to pthread_exit:

#include <pthread.h>
#include <stdio.h>

void *checker(void *arg) {
int number = (int) arg;

if (0 == number)
return "number was zero";
else
return "number was not zero";
}

int main(void) {
int test = 0;
pthread_t thread_id;
char *s;

pthread_create (&thread_id, NULL, checker,(void *) test);
pthread_join(thread_id, &s);
printf("%s\n", s);

test = 1;

pthread_create (&thread_id, NULL, checker,(void *) test);
pthread_join(thread_id, &s);
printf("%s\n", s);

return 0;
}

C: Printing out multiple threads' ID's before they execute anything?

One simple way to implement a thread pool with each thread having an opportunity to do preparatory work, before all threads will start actual work, is to have an additional startup mutex, associated condition variable, and a counter for ready threads:

static pthread_mutex_t  prep_mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t prep_cond = PTHREAD_COND_INITIALIZER;
static volatile size_t prep_count = 0;

static pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
static volatile size_t thread_count = 0;

static inline pid_t gettid(void) { return syscall(SYS_gettid); }

static void *thread_function(void *idref)
{
/* Get the number/index of this thread. */
const size_t num = *(pid_t *)idref;
const pid_t tid = gettid();

/* Replace it with the Linux tid. */
*(pid_t *)idref = tid;

/* Block here until preparatory work can be done. */
pthread_mutex_lock(&prep_mutex);

printf("Thread %zu of %zu has started.\n", id + 1, thread_count);
fflush(stdout);

prep_count++;
pthread_cond_signal(&prep_cond);
pthread_mutex_unlock(&prep_mutex);

/* Block until actual work can start. */
pthread_mutex_lock(&thread_mutex);
...

When creating the thread pool, the creator holds both mutexes. When it is ready to let the threads start the prep work, it releases the prep_mutex, waiting on the prep_cond until sufficient number of threads have completed preparatory work (prep_count is high enough). Then, it releases the thread_mutex.

int start_threads(size_t max_count)
{
pthread_t thread_id[max_count];
pid_t linux_tid[max_count];
pthread_attr_t attrs;
int err = 0;

/* Assume no threads currently running */
prep_count = thread_count = 0;

/* Shrink stack size; the default is too large. */
pthread_attr_init(&attrs);
pthread_attr_setstacksize(&attrs, 2*PTHREAD_STACK_MIN);

/* Grab the mutexes, so the threads will block initially. */
pthread_mutex_lock(&prep_mutex);
pthread_mutex_lock(&thread_mutex);

while (thread_count < max_count) {
linux_tid[thread_count] = thread_count;
err = pthread_create(thread_id + thread_count, &attrs,
thread_function, linux_tid + thread_count);
if (err)
break;

thread_count++;
}

/* Attributes are no longer needed. */
pthread_attr_destroy(&attrs);

/* No threads created at all? */
if (thread_count < 1) {
pthread_mutex_unlock(&prep_mutex);
pthread_mutex_unlock(&thread_mutex);
/* Return failure. */
return err;
}

/* All threads have now been created; let them do prep work. */
while (prep_count < thread_count) {
pthread_cond_wait(&prep_cond, &prep_mutex);
}
pthread_mutex_unlock(&prep_mutex);

/* All threads have finished their prep work; start working. */
pthread_mutex_unlock(&thread_mutex);

...

The above creates up to max_num threads, with their pthread IDs in thread_id[], and their Linux tids in linux_tid[].

When the thread starts, it gets a pointer to the location to store the Linux tid to. Initially, that contains the index of the thread ("thread number", starting at 0), so thread_function grabs that as num, obtains the Linux tid as tid, and stores it to the location given as a parameter. This way, both the original thread and the created thread know the index (num), pthread ID (thread_id[], pthread_self()), and Linux tid (linux_tid[] and tid).

Note how the arrays are dereferenced in the pthread_create() call. If array is an array, and index is an index to it, then &(array[index]) == array + index.

Above, the start_threads() function does not assume it can start all max_num threads. It does return with nonzero errno number if it cannot create any, but if it can create at least one thread, as soon as the threads can grab prep_mutex, the thread_count will reflect the correct number of threads in their gang. (There is no reason to fail just because you were only able to create 53 worker threads instead of 54, say.)

How do I get a thread ID from an arbitrary pthread_t?

Since pthreads do not need to be implemented with Linux threads (or kernel threads at all, for that matter), and some implementations are entirely user-level or mixed, the pthreads interface does not provide functions to access these implementation details, as those would not be portable (even across pthreads implementations on Linux). Thread libraries that use those could provide this as an extension, but there do not seem to be any that do.

Other than accessing internal data structures of the threading library (which you understandably do not want, although with your assumptions about processor affinity and Linux thread IDs, your code will not be portable anyway), you may be able to play a trick at creation time, if you control the code that creates the threads:

Give pthread_create() an entry function that calls gettid() (which by the way you are likely to have to do using the syscall macro directly because it is not always exported by libc), stores the result somewhere, and then calls the original entry function. If you have multiple threads with the same entry function, you can pass an incremented pointer into an array in the arg argument to pthread_create, which will then be passed to the entry function you created to store the thread ID in. Store the pthread_t return value of pthread_create in the same order, and then you will be able to look up the Linux thread IDs of all threads you created given their pthread_t value.

Whether this trick is worth it, depends on how important setting the CPU affinity is in your case, versus not accessing internal structures of the thread library or depending on a thread library that provides pthread_setaffinity_np.

Print passed argument to pthread_create

As @Some programmer dude mentioned, you should always wait for the termination of your single child threads in your main function (except you detach your threads). The reason why some of your arrayelements are printed twice or more often is because before your buffer is cleared the thread may gets killed. (In your case the thread 8). To avoid that the processes are shut-down before they have finished their work you have to waitfor your threads, or in other words you have to join your threads.

That is done by adding the function: pthread_join(pthread_t thread, void **retvalue);

The pthread_join() function waits for the thread specified by thread to terminate.

Just put it in a separate loopafter your pthread_create() function and the parent thread (main) will wait for his childs.

Edit:
To wait for each thread you could change your pthread_tvariable to an array of threads: pthread_t thread[10] so you could wait for each thread in relation to the index.

int arr[10]={0,1,2,3,4,5,6,7,8,9};
pthread_t thread[10];

for(int i=0;i<10;i++){
pthread_create(&thread[i], NULL, &thr_func,&arr[i]);
}

for(int i=0;i<10;i++){
pthread_join(thread[i],NULL);
}

C: is pthread_self() and pthread_t variable one and the same?

Return type of pthread_self is pthread_t which is basically a pointer not of integer type.

So, it is printing its address(typecasted to int), not pthread_t structure.

You can use pthread_equal function to check if these pthread_t are same or not. Means, in another thread, use

 printf("%d\n", pthread_equal(mythreadId, pthread_self()));

It should print a non-zero number indicating that they correspond to the same thread.

If they are not same, then it is a problem.

Print mythreadId in the thread what is spawns. It must match with main's pthread_t. If they are different, then there is a problem.

Why does printing the pointer to structure of type pthread, gives us thread ID?

From pthread.h file (above), pthread is a structure, thread in the
code is a pointer to the structure pthread (since pthread_t is typdef
struct pthread*
).

To be clear: in that implementation, pthread_t is a pointer-to-structure type. I imagine that's very common for pthreads implementations, but do be careful to avoid mistaking the details of a particular implementation for a general characteristic of the specifications or of all implementations. For example, it could just as well be an integer index in some other implementation, among various other possibilities.

Why does printing this pointer gives us the thread
ID?

Because it is the thread ID. And because you're lucky that the undefined behavior arising from printing it with a %d formatting directive manifested the same way in both places.

You probably have done yourself a disservice by looking under the covers at the definition of your implementation's pthread_t. You don't need to know those details to use pthreads, and in fact they do not help you in the slightest. The type is meant to be treated as opaque.

All you really need to understand to answer the question is that the value written into variable thread by pthread_create() is the created thread's ID, and the value returned by pthread_self() is the calling thread's thread ID. Naturally, each mechanism for obtaining a thread ID yields the same ID for the same thread.



Related Topics



Leave a reply



Submit