클라이언트의 데이터를 처리하는 다른 서버로 보내는 서버 프로그램이 있습니다. 하지만 함수가 실행되기까지 오랜 시간이 걸리고 프로그램이 다른 클라이언트의 데이터에서 작동하지 못하기 때문에 pthread를 사용하거나 프로세스를 만들지 않고도 다른 사람들의 데이터에 대해 동일한 함수를 동시에 실행하려고합니다.스레드를 사용하지 않고 동시에 함수를 실행하는 방법
나는 그것을 할 수있는 무언가를 만들려고했으나 추악하고 확실하게 최선의 방법은 아닙니다. 여기에 내 코드입니다 :
#include <stdio.h>
#include <string.h>
#include <vector>
struct userdata {
int rt; //The 'func' function uses it to resume work where it returned the last time
int len; //The length of 'data'
char data[16384]; //Client's data
};
int func(userdata *ud)
{
//The gotos are here to jump to the code where the function returned the last time
if(ud->rt==1)goto P1;
if(ud->rt==2)goto P2;
ud->len=0;
//Code to calculate the length of 'data'
while(ud->data[ud->len]!=0)
{
ud->rt=1; //Set to 1 to indicate where to resume execution the next time we will process the same data
return 0;
P1:
ud->len++;
}
// Work
ud->rt=2;
return 0;
P2:
// Work
return 1;
}
int main(int argc, char *argv[])
{
userdata ud;
memset(ud.data,1,16383);
ud.data[16383]=0;
std::vector<userdata> vec;
for(int i=0;i!=200;i++)vec.push_back(ud); //Add 200 times the structure in the vector
unsigned int Sz=vec.size(); //I'll use Sz in the for loop to avoid calling size()
bool Loop=true;
do
{
for(int i=0;i!=Sz;i++)
{
if(func(&vec.at(i))==1) //If the function returned 1 this means that there's no more work to do
{
printf("str length = %i\n",vec.at(i).len); //Display the result
vec.erase(vec.begin() + i); //Remove element from vector because there's no more work to do
i--, Sz--; //Decrement Sz (size of the vector) and i (vector index) to avoid out_of_range exception
if(Sz==0)Loop=false; //If there are no elements in the vector, leave Loop
}
}
}
while(Loop);
return 0;
}
여기에서의 문제는이, 나는 구조에서 마지막 상태로 복원해야하며,이 벡터 시간이 많이 걸릴 수있는 변수를 배치해야합니다 동시 실행이되지 않는 것입니다 수천 개의 요소를 포함합니다.
여기서 동시성은 어디에 있습니까? 나는이 질문이 무엇에 관한 지 전혀 모른다. 귀하의 코드는 진흙처럼 명확하고 코멘트를 기록하지 않습니다. 왜? –
글쎄, 일종의 _ 시그널 인터럽트/반응 _ 방법을 [co-routines]라고 불리는 실행을 조직하는 방법이 있습니다. (http://stackoverflow.com/questions/121757/how-do-you-implement-coroutines-in- 기음). 나는 이것이 당신이하려는 것을 실제로 도울 것이라고 확신하지는 않지만. –
@LightnessRacesinOrbit _ "동시성은 어디에 있습니까?"OP는 그것을 피할 수 있었기 때문에 분명하지 않습니다. –