我写了一个有两个线程的服务器程序:
1. For sending data to client side.
2. For receiving data from client side
现在,当执行它们时,服务器接受请求并创建发送数据的线程并开始向客户端发送数据,但由于它是可连接的,它将一直执行直到完成执行并且没有创建另一个线程并且控制权仍然存在在这个线程中。
为了使两个线程同时运行,我需要申请什么?
我写了一个有两个线程的服务器程序:
1. For sending data to client side.
2. For receiving data from client side
现在,当执行它们时,服务器接受请求并创建发送数据的线程并开始向客户端发送数据,但由于它是可连接的,它将一直执行直到完成执行并且没有创建另一个线程并且控制权仍然存在在这个线程中。
为了使两个线程同时运行,我需要申请什么?
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;
}
我没有误解这个概念,但问题是我正在执行以下步骤:
1. creating sending thread.
2. Making it joinable.
3. creating receiving thread.
4. Making it joinable.
现在发生了什么,一旦发送线程线程可以加入,接收线程就没有被创建。现在问题解决了正确的顺序是:
1. creating sending thread.
2. creating receiving thread.
3. Making sending thread joinable
4. Making receiving thread joinable.
现在两个线程都是先创建的,然后并行执行。