I am using pthread_t to print out the pid of a thread that I manually create in C. However, I print it before I create my new thread (passing it by ref as a parameter) and it prints a different value (presumably the thread that my main function is executing on). I would have expected it to default to be 0 or unitialised. Any ideas?
Thanks,
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id;/* ID returned by pthread_create() */
};
static void *thread_1_start(void *arg) {
struct thread_info *myInfo = arg;
printf("Started thread id: %d\n", myInfo->thread_id);
pthread_exit(0);
}
int main() {
struct thread_info tinfo;
int s;
printf("Main thread id: %d\n", tinfo.thread_id);
s = pthread_create(&tinfo.thread_id,
NULL, // was address of attr, error as this was not initialised.
&thread_1_start,
&tinfo);
pthread_join(tinfo.thread_id,NULL);
}
Actual output:
Main thread id: 244580352
Started thread id: 245325824
Expected output:
Main thread id: // 0 or undefined
Started thread id: 245325824
The problem is you are not initialising tinfo structure.
In local variables (as opposed to global/heap variables), values are not initialised in C Programming Language.
So, if you do something like:
int c;
printf("%d", c);
You should not expect a coherent value since it will depend on what's on that memory location in that moment.
You need to initialize tinfo variable. Using memset or assigning tinfo.thread_id = 0 explicitly.
There is no thread-specific logic to initialize tinfo; it is just a regular C struct. It will have whatever data was in that memory address at the initialization. You need to explicitly initialize it.
You can initialize the value to zero by:
struct thread_info tinfo = { 0 };
Declare struct thread_info tinfo; global and see what happens.
There's a number of important things you need to know.
First, pthread_t is opaque. You can't reliably print it with printf because nowhere in the POSIX standard is pthread_t specified as beinban into, struct or whatever. By definition you can't print it and get a meaningful output.
Second, if a thread needs to know it's pthread_t ID it can call pthread_self(). You don't need to tell the thread what its ID is externally like you're trying to do.
But never mind that! The condition you describe where the printed output is close to what you're expecting is because you have a race between the thread printing out and pthread_create assigning the pthread_t to thread_info.thread_id, and due to pthread_t actually being an integer type on Linux (so it's likely that they're allocated sequentially, and you're just getting an old value).
Related
My program uses an enum as a semaphore. There are two possible values/states(Because it's a binary semaphore). The program compiles fine. signal() and wait() look logical. Why is program behavior so unpredictable? Even the integer printf is buggy. Here's the code:
#include <stdio.h>
#include <pthread.h>
typedef enum {IN_USE,NOT_IN_USE} binary_semaphore;
binary_semaphore s=NOT_IN_USE;
struct parameters{
int thread_num;
};
void wait(){
while(s==IN_USE);
s=IN_USE;
}
void signal(){
s=NOT_IN_USE;
}
void resource(void *params){
//assuming parameter is a parameters struct.
struct parameters *p=(struct parameters*)params;
wait();
printf("Resource is being used by thread %d\n",(*p).thread_num);
signal();
}
int main(void){
pthread_t threads[4];
struct parameters ps[4]={{1},{2},{3},{4}};
register int counter=0;
while(counter++<4){
pthread_create(&threads[counter],NULL,resource,(void*)&ps[counter]);
}
return 0;
}
What's wrong with my code?
Some of the outputs(Yes, they're different every time):-
(NOTHING)
Resource is being used by thread 32514
Resource is being used by thread 0
Resource is being used by thread 0
Resource is being used by thread 32602
Resource is being used by thread -24547608
Is it a garbage value issue?
What's wrong with my code?
Multiple things, largely discussed in comments already. The most significant one is that your code is rife with data races. That is one of the things that semaphores are often used to protect against, but in this case it is your semaphores themselves that are racy. Undefined behavior results.
Additional issues include
A pthreads thread function must return void *, but yours returns void
You overrun the bounds of your main()'s ps and threads arrays
You do not join your threads before the program exits.
You define functions with the same names as a C standard library function (signal()) and a standard POSIX function (wait()).
Nevertheless, if your C implementation supports the atomics option then you can use that to implement a working semaphore not too different from your original code:
#include <stdio.h>
#include <pthread.h>
#include <stdatomic.h>
// This is used only for defining the enum constants
enum sem_val { NOT_IN_USE, IN_USE };
// It is vital that sem be *atomic*.
// With `stdatomic.h` included, "_Atomic int" could also be spelled "atomic_int".
_Atomic int sem = ATOMIC_VAR_INIT(NOT_IN_USE);
struct parameters{
int thread_num;
};
void my_sem_wait() {
int expected_state = NOT_IN_USE;
// See discussion below
while (!atomic_compare_exchange_strong(&sem, &expected_state, IN_USE)) {
// Reset expected_state
expected_state = NOT_IN_USE;
}
}
void my_sem_signal() {
// This assignment is performed atomically because sem has atomic type
sem = NOT_IN_USE;
}
void *resource(void *params) {
//assuming parameter is a parameters struct.
struct parameters *p = params;
my_sem_wait();
printf("Resource is being used by thread %d\n", p->thread_num);
my_sem_signal();
return NULL;
}
int main(void) {
pthread_t threads[4];
struct parameters ps[4] = {{1},{2},{3},{4}};
for (int counter = 0; counter < 4; counter++) {
pthread_create(&threads[counter], NULL, resource, &ps[counter]);
}
// It is important to join the threads if you care that they run to completion
for (int counter = 0; counter < 4; counter++) {
pthread_join(threads[counter], NULL);
}
return 0;
}
Most of that is pretty straightforward, but the my_sem_wait() function bears a little more explanation. It uses an atomic compare-and-swap to make sure that threads proceed only if they change the value of the semaphore from NOT_IN_USE to IN_USE, with the comparison and conditional assignment being performed as a single atomic unit. Specifically, this ...
atomic_compare_exchange_strong(&sem, &expected_state, IN_USE)
... says "Atomically, compare the value of sem to the value of expected_state and if they compare equal then assign value IN_USE to to sem." The function additionally sets the value of expected_state to the one read from sem if they differ, and returns the result of the equality comparison that was performed (equivalently: returns 1 if the specified value was assigned to sem and 0 if not).
It is essential that the comparison and swap be performed as an atomic unit. Individual atomic reads and writes would ensure that there is no data race, but they would not ensure correct program behavior, because two threads waiting on the semaphore could both see it available at the same time, each before the other had a chance to mark it unavailable. Both would then proceed. The atomic compare and swap prevents one thread reading the value of the semaphore between another's read and update of that value.
Do note, however, that unlike a pthreads mutex or a POSIX semaphore, this semaphore waits busily. That means threads waiting to acquire the semaphore consume CPU while they do, rather than going to sleep as threads waiting on a pthreads mutex do. That may be ok if semaphore access is usually uncontended or if threads never hold it locked very long, but under other circumstances it can make your program much more resource-hungry than it needs to be.
You are encountering race conditions as well as undefined behavior. When you use a regular int as a semaphore in multithreaded applications, there's no guarantee that a process will read a variable's value and modify it before another process is able to read it, which is why you must use a concurrency library designed for your operating system. Furthermore, the function pointer you passed to pthread_create is not the right type, which is undefined behavior.
I replaced your "semaphore" enum with a pointer to pthread_mutex_t which is initialized on the stack of main(), and each thread gets a pointer to it as a member of their struct parameter.
I also changed the definition of void resource(void* params) to void* resource(void *params) as that is a prototype that matches what pthread_create expects as its third parameter.
Your wait() and signal() functions were able to be replaced one-to-one with pthread_mutex_lock() and pthread_mutex_unlock() from pthread.h which you have already included.
#include <stdio.h>
#include <pthread.h>
struct parameters{
int thread_num;
pthread_mutex_t *mutex; //mutex could be global if you prefer
};
void* resource(void *params){ //pthread_create expects a pointer to a function that takes a void* and returns a void*
//assuming parameter is a parameters struct.
struct parameters *p = (struct parameters*)params;
pthread_mutex_lock(p->mutex);
printf("Resource is being used by thread %d\n", p->thread_num);
pthread_mutex_unlock(p->mutex);
return NULL;
}
int main(void){
pthread_t threads[4];
pthread_mutex_t mutex;
pthread_mutex_init(&mutex, NULL);
struct parameters ps[4]={{1, &mutex},{2, &mutex},{3, &mutex},{4, &mutex}};
for(int counter = 0; counter < 4; ++counter)
pthread_create(&threads[counter], NULL, resource, &ps[counter]);
//Threads should be joined
for(int counter = 0; counter < 4; ++counter)
pthread_join(threads[counter], NULL);
}
This will eliminate the stochasticity that you are experiencing.
I'm new to using pthreads. I want to create a program where six different threads will each output a different number. The threads can run in any order, however, each thread should run only once.
So, a possible output would be:
Thread: 5
Thread: 2
Thread: 3
Thread: 6
Thread: 1
Thread: 4
Or it could be in any other order.
#include<stdio.h>
#include<pthread.h>
void *apples(void *void_apple_num){
int *thread_num = (int *) void_apple_num;
printf("Thread: %d\n", *thread_num);
return NULL;
}
int main(){
pthread_t threads[6];
int apple_num;
for(apple_num=0; apple_num<6; apple_num++){
pthread_create(&threads[apple_num], NULL, apples, &apple_num);
}
for(apple_num=0; apple_num<6; apple_num++){
pthread_join(threads[apple_num], NULL);
}
return 0;
}
When I run the program, I have this problem of the threads interfering with each other. I am not sure if some of the threads are running twice? However, I think the problem is some of the threads are using the apple_num pointer from a different thread.
Here are two sample outputs I got:
Output 1:
Thread: 5
Thread: 0
Thread: 1
Thread: 1
Thread: 2
Thread: 2
Output 2:
Thread: 1
Thread: 4
Thread: 4
Thread: 5
Thread: 1
Thread: 1
I don't fully understand what is causing the problem. I've heard that threads can sometimes share variables? I don't know if I should use a mutex lock to somehow get the threads to run one-at-a-time.
How can I edit my code to solve this?
If somebody else has asked a similar question, please direct me to their question. I couldn't find anything when I researching.
Each of your threads gets a pointer to the very same local variable apple_num which is being changed in the loop by the main thread. Since threads start asynchronously, the value of local variable apple_num in the main thread is indeterminate from the perspective of any other thread.
You need to pass a copy of that variable to each thread.
One fix is to cast int to void* and back:
void *apples(void* apple_num){
int thread_num = (int)void_apple_num;
...
pthread_create(&threads[apple_num], NULL, apples, (void*)apple_num);
As they mention in the comments, intptr_t and uintptr_t (from <stdint.h>) may be more appropriate for round-trip without loss, e.g. uintptr_t -> void* -> uintptr_t. But C standard doesn't require any integers to round-trip to void* and back, it only requires void* -> intptr_t and back.
In a more realistic scenario, you may like to pass more than just one integer to a thread, namely, a struct. And that's the rationale for the thread start function to receive a single void* argument - it can point to an object of any data type (POSIX requires void* to also be able to store function pointers).
An example of passing a structure to a thread (without relying on implementation-defined conversion of integers to void* and back):
struct ThreadArgs {
int thread_num;
// More data members, as needed.
};
void* apples(void* arg){
struct ThreadArgs* a = arg;
printf("Thread: %d\n", a->thread_num);
free(arg);
return NULL;
}
int main() {
pthread_t threads[6];
struct ThreadArgs* a;
int apple_num;
for(apple_num=0; apple_num<6; apple_num++){
a = malloc(sizeof *a);
a->thread_num = apple_num;
pthread_create(&threads[apple_num], NULL, apples, a);
}
for(apple_num=0; apple_num<6; apple_num++)
pthread_join(threads[apple_num], NULL);
return 0;
}
Note, that you don't have to allocate the thread arguments structure on the heap (malloc). If you pass an automatic variable (on the stack) to a thread, you must make sure that the variable is unchanged and still exists when the thread accesses it. Allocating the thread arguments structure from the heap is the safest and solves this problem at the expense of malloc/free calls.
This question already has answers here:
How to "multithread" C code
(13 answers)
Closed 3 years ago.
This is my first contact with c and Multithreading.
I look for an example how to use it in Basic.
This is what I want to to parallel:
PseudoCode that should run on different Threads
Code1
int main(){
int i =1000;
while(i>0){
i--;
}
}
Code2
int main(){
int x =0;
if(i%5){
x++;
}
}
I also didn't know how to pass Objects, maybe someone can explaine this too.
Please use only lowercase in C to declaring variables and functions
as struct,typeof,sizeof,int,char,void,for,while,etc....
EDIT:
Sorry for not to understand "I thought you need help to do that code in C"
Now i know that you want multi-threading functions to do two jobs or more at the same time without waiting for other to finish.
Okay, to do that you have to
include pthread.h which means POSIX Thread
Note: you should notice from this name that this library for Linux OS only
and you compile it with gcc compiler
declare variable pthread to for example: tid in your main() as the most popular name
Create your function in void *() and type stuff whatever it does then create your thread in main() and assign it your function through that code:
pthread_create(&tid, NULL, MyThread, NULL);
pthread_create() arguments:
A pointer to a pthread_t structure that we created to fill it with the upcoming arguments.
A pointer to a pthread_attr_t with parameters for the thread. You can safely just pass NULL most of the time.
Note: The pthread_attr_t > "arg 2" should be treated as opaque: any access to
the object other than via pthreads functions is nonportable and
produces undefined results.
Take the function that you created as thread and shall be with no return and
points to >> void, that's why we created void *()
Note: Type only the name of function without (), you will know why in the next argument
Here you passing your arguments to your function!, if there's no arguments just pass NULL
Example Code:
#include <stdio.h>
#include <pthread.h>
int i=0,x=0; //Initialize our variables
void *MyThread(void *ANYarg) //arguments must be a pointers to point from `pthread_create` with `NULL` if no need
{
while(1) //background thread
{
i++;
x++;
}
return NULL;
}
int main()
{
char *input;
pthread_t tid; //Declare a thread
pthread_create(&tid, NULL, MyThread, NULL); //Create the thread
while(1) //Printing thread , Uncover increamting of variables
{
scanf("%s",&input); //whenever you input a value
printf("i: %d, x: %d\n",i,x);//will print the i,x values now
}
return 0;
}
Note: You should at least create one pointer variable specifically to your thread function cause fourth argument of pthread_create() need at least one to pass the NULL value
You can wait for an thread to finish instead of doing work at the same time through that code line:
pthread_join(tid, NULL);
Should return 0 when success
An Example:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *MyCoolthread(void *vargp)
{
printf("Yes..see me printing success after 3 seconds \n");
sleep(3);
printf("Success! \n");
return NULL;
}
int main()
{
pthread_t tid;
printf("Hello, are you there? \n");
sleep(1);
pthread_create(&tid, NULL, MyCoolthread, NULL);
pthread_join(tid, NULL);
printf("Yup i see!\n");
return 0;
}
Try to comment pthread_join(tid, NULL); with // to see what happens
and to terminate your thread is through code line:
pthread_exit(&tid);
Doesn't return to its caller any value
Edit: I noticed now that you use windows so i advice you to dual boot with Ubuntu instead if you really interested in C
otherwise you can use multi-threading in windows.h header that called winapi library but i'm not expert in so you can find an simple example here and you should mentioned in your post that you want for windows by the way you can edit to improve it
I tried my best to get it clear, hope it helps.
I am trying to create a thread library and my thread is a struct type. Have to follow a certain interface and in that I need to pass the thread by value. For ex: to join on a thread my code is as follows:
int thread_join(thread_t thread, void **status1)
{
printf("Joining thread\n");
long int thId = thread.id;
printf("Thread id: %ld\n", thId);
gtthread_t * thrd = getThreadFromID(thId);
while(thrd->status != EXIT)
{
}
status1 = &(thrd->ret_value);
return 0;
}
And I an passing a struct of type thread_t to this function. My problem is when I see the thread's ID in the calling function, its displayed properly but when I check it in the thread_join function its displayed as 0. The caller function is as follows:
void* caller(void* arg)
{
thread_t th;
thread_create(&th, some_function, NULL);
thread_join(th, NULL);
while(1);
}
Thread create initializes the ID of the thread to a non-zero value and starts the function associated with it.
My thread structure (and other relevant structure is):
typedef enum
{
RUNNING,
WAITING,
CANCEL,
EXIT
} stat;
//Thread
typedef struct
{
ucontext_t t_ctxt;
long int id;
stat status;
void * ret_value;
int isMain;
} thread_t;
int thread_create(thread_t *thread, void *(*start_routine)(void *), void *arg)
{
thread = (thread_t *)malloc(sizeof(thread_t));
thread->id = ++count;
thread->status = RUNNING;
thread->ret_value = NULL;
thread->isMain = 0;
if(getcontext(&(thread->t_ctxt)) == -1)
handle_error("getcontext");
thread->t_ctxt.uc_stack.ss_sp = malloc(SIGSTKSZ);
thread->t_ctxt.uc_stack.ss_size = SIGSTKSZ;
thread->t_ctxt.uc_link = &sched_ctxt;
makecontext(&thread->t_ctxt, (void (*)(void))wrap_func, 2, (void (*)(void))start_routine, arg);
enqueue(gQ, thread);
printf("Thread id: %ld\n", thread->id);
swapcontext(&(curr_thread->t_ctxt),&sched_ctxt);
return 0;
}
Why does this happen? After all, I am passing by value and this should create a copy of the thread with the same values. Thanks.
EDIT:
Basically I am having a queue of threads and there is a scheduler which round-robins. I can post that code here too but I'm sure that's needless and that code works fine.
EDIT2:
I am making a header file from this code and including that header in another file to test it. All my thread_t variables are static. The caller is a function which includes my header file.
What is this line:
thread = (thread_t *)malloc(sizeof(thread_t));
for?
You pass in to thread_create() an address which referrs to a struct thread_t defined in caller() as auto variable.
Doing as you do, you allocate memory to the pointer passed in to thread_create() initialise it and forget the address on return.
The code never writes to the memory being referenced by the address passed in! Besides this it is a memory leak.
To fix this simply remove the line of code quoted above.
You have no mutex guard on thread id getter. Presumably, there is no guard on setter. What can be happening is that the variable is not visible in the other thread yet. And, without a critical section, it may never become visible.
Each variable which is accessed for both read and write from different threads has to be accessed in a critical section (pthread_mutex_lock / unlock).
Another possibility is that you are setting the thread id inside the running thread and you are accessing the variable even before it is set. If you attempt to join immediately after starting a thread it is possible, that the other thread hasn't been run at all yet and the variable is not set.
side note: do yourself a favor and use calloc:)
In caller function,
thread_create(&th, some_function, NULL);
should be
gtthread_create(&th, some_function, NULL);
I've got a simple C program that uses mutex's to collect a char from the standard input on one thread and print it out on another thread. Both threads start correctly (the printf in the below saying that the thread started runs), but then neither of the while's get run since I introduced Mutex'. Does anyone have an idea as to why? (I collect two chars in my char array as I am collecting the return char as well.)
Thanks!
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id;/* ID returned by pthread_create() */
char passedChar[2];
pthread_mutex_t passedCharMutex;
pthread_cond_t conditionalSignal;
};
static void *thread_1_start(void *arg) {
struct thread_info *myInfo = arg;
printf("Started thread id: %d\n", myInfo->thread_id);
while (1) {
printf("thread1 while ran");
pthread_mutex_lock(&myInfo->passedCharMutex);
int rid = read(0,myInfo->passedChar,2);
pthread_mutex_unlock(&myInfo->passedCharMutex);
}
pthread_exit(0);
}
int main() {
struct thread_info tinfo;
printf("Main thread id: %d\n", tinfo.thread_id);
int s = pthread_create(&tinfo.thread_id,
NULL, // was address of attr, error as this was not initialised.
&thread_1_start,
&tinfo);
pthread_join(tinfo.thread_id,NULL);
while (1) {
printf("thread2 while ran");
pthread_mutex_lock(&tinfo.passedCharMutex);
write(1,tinfo.passedChar,2);
pthread_mutex_unlock(&tinfo.passedCharMutex);
}
}
pthread_mutex_t and pthread_cond_t must be intitialized before you can use them.
struct thread_info tinfo;
pthread_mutex_init(&tinfo.passedCharMutex, NULL);
pthread_cond_init(&tinfo.conditionalSignal, NULL);
In this case you could initialize them when initializing the tinfo variable too:
struct thread_info tinfo = {
.passedCharMutex = PTHREAD_MUTEX_INITIALIZER,
.conditionalSignal = PTHREAD_COND_INITIALIZER
};
You also have a
pthread_join(tinfo.thread_id,NULL);
after you create your first thread, that will cause you wait until your thread ends, which it never does since thread_1_start() runs an infinite loop - you'll never reach the while loop in main().
While not part of your question, there's additional problems:
There's no synchronization of the logic of your two threads. As it currently stands, they both run without any regard to eachother, so your main() might print out passedChar many times before your thread_1_start() reads anything.
Likewise, thread_1_start() might read a lot of data before your main() thread have a chance to print it.
What you probably want is:
Thread A: read 2 chars
Thread A: signal Thread B that there is 2 chars to process
Thread A: wait until Thread B has processed the 2 chars.
Thread B: wait for thread A to signal that there's 2 chars to process
Thread B: process the 2 chars
Thread B: signal Thread A that we're done process
When thread 1 comes to this line,
int rid = read(0,myInfo->passedChar,2);
it holds the lock and then blocks for input. Tread 2 waits for the thread 1 to exit. And if no input ever comes neither thread will make progress.