Reputation: 47
I have written a server program with two threads:
1. For sending data to client side.
2. For receiving data from client side
Now when execute them, the server accepts the request and thread to send data is created and it starts sending data to client but since it is joinable, it will execute until it completes its execution and the other thread does not get created and the control remains in this thread.
What I need to apply in order to make both the threads run simultaneously?
Upvotes: 0
Views: 2607
Reputation: 47
I had not misunderstood the concept but the problem was that I was performing following steps:
1. creating sending thread.
2. Making it joinable.
3. creating receiving thread.
4. Making it joinable.
Now what was happening ,Once the sending threading thread was joinable ,receiving thread was not being created. Now the problem is resolved The correct sequence is:
1. creating sending thread.
2. creating receiving thread.
3. Making sending thread joinable
4. Making receiving thread joinable.
Now both the threads are created first and then executes parallely.
Upvotes: 0
Reputation: 73
I think you might be looking for pthread. Here is a sample code I wrote when I learned how threads work. Its a counter. The first thread adds one to a variable each secound, and the other prints it out.
#include<pthread.h> //for simultanius threads
#include<stdio.h>
#include<stdlib.h> //for the _sleep function
//global variables, both thread can reach thease.
int a = 0;
int run = 1;
void *fv(void)
{
while( run )
{
_sleep(1000);
a++;
}
}
int main(){
pthread_t thread;
pthread_create( &thread, 0, fv, 0 );
printf( "%d", a );
while( a < 60 )
{
int last = a;
while( last == a )
_sleep(50); //let's not burn the cpu.
printf( "\r%d", a );
_sleep(500); //a won't change for a while
}
run = 0;
pthread_join( thread, NULL );
return 0;
}
Upvotes: 2