When you create a thread does it automatically start the thread function that's in the parameter?
I'm using
iret1 = pthread_create(&client[i++].tID, NULL, thread_function, NULL);
printf("Thread Created"); //for testing purposes
In my thread function I have a print statement at the very top. ex:
void *thread_function(void *arg){
printf("Entered thread function");
...
}
Instead of printing Entered thread function it prints Thread Created right after
And it doesn't print Entered thread function until I start another thread, is there a reason for this?
You need at least to add a newline \n at the end of every printf(3) format function, and often to call fflush(3), e.g. add a call to fflush(NULL); after each of your two printf ...
Don't forget that <stdio.h> functions are buffered. See setvbuf(3) function and man page.
The reason why your output is not printed as soon as you want it to be is that it is staying in the buffer of stdout.
And you probably have no guarantee on the output. The individual characters might perhaps be intermixed. Read unlocked_stdio(3) and flockfile(3) for details.
You may want to read (several times) some pthread tutorial...
PS you could consider using directly the write(2) syscall (without using any <stdio.h> function).
Related
Lately have been testing out using signals such as SIGINT and SIGHUP and their role on ongoing processes on Linux. Running the following code returned some interesting results.
#include <signal.h>
#include <stdio.h>
void routine(int p){
puts("Not finishing");
sleep(2);
}
main(){
int i = 0;
signal(SIGINT, routine);
signal(SIGHUP, routine);
while(1){
printf("%d \n", i++);
}
}
As you can see, it simply counts from 0 on an infinite loop. Then, by using kill -SIGINT on the process it created, I got the following:
Routine
As you can see, before the line I requested the routine to print, the program repeated the last number (and it does not happen always). I would really like to know why.
It is likely that you are narrowly avoiding horrible bugs by accident.
What I think is happening is that the signal sometimes interrupts while printf is in progress formatting the string into the output buffer. Then the puts in the signal handler inserts more string into the output buffer. Then the handler returns, printf inserts the newline and flushes the buffer.
But guess what would happen if this signal occurred just before the flush of a full 8K output buffer. The buffer positions would be at the end. Then the puts call happens, not realizing that printf is already in process of flushing and clearing the buffer. Where exactly would it be putting the puts string? At the beginning? At the end? Would the excess data printf was in the process of writing write over the string that puts had added? All of those things are possible.
Buffered C output is not reentrant and cannot be used in signal handlers.
I wrote the following code:
#include <pthread.h>
#include <stdio.h>
void* sayHello (void *x){
printf ("Hello, this is %d\n", (int)pthread_self());
return NULL;
}
int main (){
pthread_t thread;
pthread_create (&thread, NULL, &sayHello, NULL);
printf("HERE\n");
return 0;
}
After compiling and running I saw 3 different types of outputs.
Only "Here" was printed.
"Here" and 1 'sayHello' message.
"Here" and 2 'sayHello' messages.
Of course I'm OK with the second option, but I don't understand why the 'sayHello' massege can be printed 0 or 2 times if I created only one thread?
You can't say when the thread starts to run, it might not start until
after you return from main which means the process will end and the thread with it.
You have to wait for the thread to finish, with pthread_join, before leaving main.
The third case, with the message from the thread printed twice, might be because the thread executes, and the buffer is written to stdout as part of the end-of-line flush, but then the thread is preempted before the flush is finished, and then the process exist which means all file streams (like stdout) are flushed so the text is printed again.
For output 1:
your main function only create a pthread, and let it run without waiting for it to finish.
When your main function return, Operating system will collect back all the resources assigned to the pprocess. However the newly created pthread might have not run.
That is why you only got HERE.
For output 2:
your newly created thread finished before main function return. Therefore you can see both the main thread, and the created thread's output.
For output 3
This should be a bug in glibc. Please refer to Unexpected output in a multithreaded program for details.
To make the program always has the same output
pthread_join is needed after pthread_create
I'm testing the behavior of running concurrent threads in C, with a thread function that runs infinitely. My question is why doesn't, in the below code, "HELLO!!!" gets printed? I thought pthread_create() is called and then immediately it goes to the next iteration of the loop, why is the code waiting for the 1st pthread_create() to finish? Aren't multiple threads supposed to be running concurrently?
void main(int argc, char **argv)
{
pthread_t tid;
int i;
//Create 4 inf threads
for (i=0;i< 4;i++)
{
//printf("hello!\n");
//pthread_create(&tid, NULL, thread_incr, (void *)i);
pthread_create(&tid, NULL, t_nostop, (void *)i);
printf("HELLO!!!"); //This linen is NEVER printed!!
}
pthread_exit(NULL);
}
void* t_nostop(void * argp)
{
int i=1;
int t_num=(int) argp;
while(i==1){t_num++;}
}
Multiple threads are supposed to run concurrently. This should be happening in your code.
I'd guess that the printf calls are executed but don't generate output immediately. Console output may be line buffered, so will only be displayed when you print a newline or flush.
Try either adding \n at the end of the string you print or adding fflush(stdout) after the printf.
Edit: A comment asked about line buffering...
Line buffering happens when the standard C library decides that console writes are relatively expensive and should only be attempted for coherent blocks of text. One easy definition for a coherent block is a line. While it is waiting for a newline to be entered, the C lib stores the contents of printf calls in a block of memory, appending subsequent printfs
From my understanding on pthreads, you haven't actually started the thread yet. Try, after the pthread_create, adding pthread_join(tid, NULL); and see if it works.
I am a newbie in Linux programming.I copied the code below from a book:
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch (int sig)
{
printf("OUCH! - I got signal %d\n", sig);
(void) signal(SIGINT, SIG_DFL);
}
int main ()
{
(void) signal(SIGINT, ouch);
while(1)
{
printf("Hello World!\n");
sleep(1);
}
}
It was expected to print something when Ctrl+C was entered.But it do nothing but print Hello World!.
EDIT:
I am so sorry that I have binded the Ctrl+C as a short-cut key for copy.
Sorry for trouble caused.
My Suggestion is don't use printf in siginal handler (ouch), it may be undefined behavior. Async-signal-safe functions: The list of safe functions that can be call in signal handler man page.
It is not safe to call all functions, such as printf, from within a signal handler.
A useful technique is to use a signal handler to set a flag and then check that flag
from the main program and print a message if required.
Reference: Beginning Linux Programming, 4th Edition,In this book exactly your code is explained, Chapter 11: Processes and Signals, page 484
An additional helpful link:
Explanation: Use reentrant functions for safer signal handling
Sorry, I can't see a question here... but I can guess what you are interested in.
printf() is a stateful function, thus not reentrant. It uses a FILE structure (variable name is 'stdin') to keep it's state. (It is like calling fprintf(stdin,format,...)).
That means, dependant on implementation and 'luck', calling printf() from a signal handler may print what you expect, but also may print nothing or may even crash or worse, smash your memory! Anything could happen.
So, just don't call functions from within a signal handler that are not explicitely marked 'signal-safe'. You will avoid lot's of headaches in the long term.
Put an fflush(stdout) in your signal handler. It was just buffered, then the second SIGINT exited the program before the buffer could be flushed.
There's a weird behavior in my threads:
void * foo(void * nic){
printf("foo");
}
void * threadF(void * pointer){
printf("1\n");
pthread_t threadT;
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&threadT,NULL,&foo,(void*)NULL);
printf("2\n");
while (!feof(stdin)){
int id, in, out;
fscanf(stdin,"%d:%d:%d",&id,&in,&out);
}
}
int main(){
pthread_attr_t attr;
pthread_attr_init (&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_t threadT;
pthread_create(&vlaknoVstupu,&attr,&threadF,(void*)&data);
pthread_join(threadT,NULL);
pthread_attr_destroy (&attr);
}
// I skipped irelevant parts of code...
the thing is that sometimes the output is 12foo, but usually just 12.
Then the function waits for input. I would expect it to be always 12foo. Do anybody know why are my expectations wrong?
Edit: when I type some input like 1:1:1, which results in going through the while cycle again, there is always the foo output.
Printf does not have a thread guarantee. You shouldn't just call two functions on the same thing from different threads unless it's explicitly guaranteed to be safe, either by the writer or because you wrote it yourself.
What you should do is store a buffer of string pointers, and use atomic operations to insert strings into this buffer, then printf all of them every so often, free the memory, set to null, or just use a lock if it's ok to make the child threads wait on the printf call.
What happens is that (on most implementations) stdin and stdout are tied together in one practical buffer. This is to allow something like:
printf("Input: ");
scanf("%d", &integer);
to work nicely, the inputted characters will appear after the printf text.
As soon as your scanf will grab the stdin, this will 'lock' that buffer, also preventing the stdout of your other thread to flush its data to the screen. Note that 'lock'. Does not necessarily mean real thread locks.
If you'd call the program from console, input something like 1:2:3, and hit enter, you'd see that foo will be displayed at the end.
Since there is no join call for thread foo, the program is probably ending before it runs.