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.
Related
See the following code:
I am having some library file like libexample.so
And in my code i am using some function X(inputbuffer , outputbuffer)present in library
/*
Assume for each thread there are corresponding input buffers and output buffers
example if there are 50 threads 50 input buffers and out buffers are available
i.e input buffers are unique to each other so as output buffers....
*/
void* threadFunX(void *num)
{
Mutex lock();
int ret = X(inputBuffer,outputbuffer,length);
if(ret)
{
//store the output buffer in afile
}
else
error occured.....
Mutex unlock();
pthread_exit(NULL);
}
int main()
{
pthread_t thread1[100];
for(i=0;i<100;i++){
p1 = pthread_create(&thread1[i],NULL,threadFunX,(void *)i);
if(p1)
printf("Error occurred while creating thread.....\n");
//pthread_join( thread1[i], NULL);
}
for(i=0;i<100;i++)
pthread_join( thread1[i], NULL);
}
My question:
If we are not using Mutex we are getting output buffer corrupted.... for this reason we are using mutex....
Is there any alternative method other than mutex....
I want to use this library function efficiently.....
My main moto is I want to reduce running time taken by mutex method also...
for example...if my code with mutex is running with 0.2 seconds..... I want better alternative method which takes lesser time than mutex with thread parallel programming...
Thanks in advance...
Check the library function X. Are you sure it is creating a new OutputBuffer everytime you are calling the function. Because as per your saying that "without mutex outputbuffer is getting corrupted", it seems to me that only one outputbuffer is created and it is returning the same to each thread.
I've been reading and learning about POSIX threads, and tried to write some simple codes to understand it better.
#include <stdio.h> /* standard I/O routines */
#include <pthread.h> /* pthread functions and data structures */
/* function to be executed by the new thread */
void* PrintHello(void* data)
{
pthread_t tid = (pthread_t)data;
printf("Hello from new thread %d - got %d\n", pthread_self(), tid);
pthread_exit(NULL); /* terminate the thread */
}
int main(int argc, char* argv[])
{
int rc; /* return value */
pthread_t thread_id;
int tid;
thread_id = pthread_self();
printf("FLAG = %d ", thread_id);
/* create a new thread that will execute 'PrintHello' */
rc = pthread_create(&thread_id, NULL, PrintHello, (void*)thread_id);
if(rc) /* could not create thread */
{
printf("\n ERROR: return code from pthread_create is %u \n", rc);
exit(1);
}
printf("\n Created new thread (%d) ... \n", thread_id);
pthread_exit(NULL); /* terminate the thread */
}
For this code I get the following output:
FLAG = 363480832
Created new thread (355198720) ...
Hello from new thread 355198720 - got 363480832
What is bothering me is why thread_id which is 363480832, becomes 355198720, same as thread_id of a function that was called from main (PrintHello()). I assumed that thread id doesn't change throughout the program execution. Or is it something inside the function that changes it?
If you're doing anything with a pthread_t other than passing it to a function that takes one, you're doing something wrong. Only the pthreads API knows how to use a pthread_t correctly. They can have any internal structure that's convenient for the implementation.
Being a C language construct, pthread_t behaves more like char *. The necessary language constructs to make it behave like std::string don't exist. So you have to treat it like char *.
A char * contains a string somehow, but you have to understand its implementation to get that value out. Consider:
char *j = "hello";
char *k = strdup (j);
if (j == k)
printf ("This won't happen\n");
printf ("%d\n", j);
printf ("%d\n", k); // these won't be equal
You can't compare char *'s with == to see if they refer to the same string. And if you print out j and k, you'll get different values.
Similarly, a pthread_t refers to one particular thread somehow. But you have to understand how to get the value out. Two pthread_ts can have different apparent values but still refer to the same thread just as two char *s can have different apparent values but still refer to the same string.
Just as you compare two char *'s with strcmp if you want to tell if they refer to the same string value, you compare two pthread_ts with pthread_equal to tell if they refer to the same thread.
So this line of code makes no sense:
printf("FLAG = %d ", thread_id);
A pthread_t is not an integer and you can't print it with a %d format specifier. POSIX has no printable thread IDs. If you want one, you need to code one (perhaps using pthread_getspecific).
In C, arguments are passed by value. In particular, the argument (void *)thread_id is an expression that's evaluated before calling pthread_create, so the fact that pthread_create writes to thread_id as a result of &thread_id being passed as the first argument is irrelevant. If you were instead passing &thread_id rather than (void *)thread_id as the argument to the new thread start function, and dereferencing it there, then you may see the effects you want; however, it's not clear to me that pthread_create's writing of the new thread id via its first argument is required to take place before the new thread starts, so there is probably a data race if you do it that way.
Further, note that David's answer is also correct. It's invalid to print thread ids this way since they are formally an opaque type.
In this line:
rc = pthread_create(&thread_id, NULL, PrintHello, (void*)thread_id);
as the manual says, pthread_create() shall store the ID of the created thread in the location referenced by thread_id. In this example, it would be modified to 355198720, which is the tid of new thread PrintHello().
Besides, it may be better to change the argument for PrintHello to:
rc = pthread_create(&thread_id, NULL, PrintHello, (void*)&thread_id);
and in PrintHello(), it would be:
void* PrintHello(void* data)
{
pthread_t tid = (pthread_t)(*data);
...
}
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 have just had a really good use for multithreading. As such.... I have to learn multithreading. I have a very simple program:
void *listenloop(void *arg){
while (1){
Sleep(2000);
puts("testing 123\n");
}
return NULL;
}
int main(){
pthread_t listener;
pthread_create(&listener,NULL,listenloop,"foo");
char testinput[200];
while(1){
puts("Scanning: ");
scanf("%s",testinput);
puts("\n\n");
printf("You typed: %s: ",testinput);
}
}
The theory is that it waits for user input, echos it, all while periodically printing.
None to my surprise, actually (and presumably obviously to my betters in the matter) the output is "messed up."
Now I can think of several ways around this problem, but no actual solutions. How should something of this nature be implemented? Can it just be done by manipulating the output of the program after it is displayed to the user?
Thanks!
So just wrap the prints in pthread_mutex_lock/unlocks with a single pthread_mutex_t and you should be fine.
http://linux.die.net/man/3/pthread_mutex_lock
pthread_mutex_t = PTHREAD_MUTEX_INITIALIZER;
void *listenloop(void *arg){
while (1){
Sleep(2000);
pthread_mutex_lock(&mutex);
puts("testing 123\n");
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(){
pthread_t listener;
pthread_create(&listener,NULL,listenloop,"foo");
char testinput[200];
while(1){
pthread_mutex_lock(&mutex);
puts("Scanning: ");
pthread_mutex_unlock(&mutex);
scanf("%s",testinput);
pthread_mutex_lock(&mutex);
puts("\n\n");
printf("You typed: %s: ",testinput);
pthread_mutex_unlock(&mutex);
}
}
In your original code, there should be no "messed up" output (caused by threading, anyway) in that code as only the one thread (the main one) is doing any output.
The only thing the other thread does is infinitely loop with a delay of some sort.
Now that you've updated the question to output from the other thread then, yes, it is possible for the output to intermix.
There are several ways around this, two spring to mind immediately.
Have all output go through a series of functions which mutex-protect the output stream, such as mutexed_printf()/mutexed_puts() (which you'll need to provide) (a).
Do all output from one of the threads, meaning the other will have to send data to it via some means (inter-thread communications like a queue) - that way all output can be properly mixed, such as on newline boundaries.
(a) Also keep in mind that, if you want to mutex protect the output stream for the user input operation, you'll probably want to protect the puts/scanf atomically so that the testing output doesn't mess up your input (by outputting messages after the prompt but before/during your input). That won't be possible with a mutexed_puts() function, you'll need an expanded mutexed_prompt_and_input() one.
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).