What is the best way to asynchronously return a result (as a structure) that has not yet been fully "configured" (or processed)

Well, I honestly tried to find "Asynchronous functions in C" (the results for C # are exclusive), but I get nothing for C. Therefore, I am going to ask about it here, but if there is even better, I already asked questions on StackExchange or what- you please direct me to them.

So, I'm learning about concurrency and asynchronous functions, and all that is why I am trying to create my own thread pool. So far, I'm still at the planning stage, and I'm trying to find a clear path for traveling, but I don’t want to hand out the code, I just want to push in the right direction (or the exercise is pointless).

What would be the best way to return asynchronously from a function that is not really "ready"? In this case, it will return almost immediately, even if it is currently processing a task specified by the user. The "task" will be a callback and arguments to match the necessary arguments to pthread_t, although I will work with attributes later. The function returns a structure called "Result", which contains the return value void * and a byte (unsigned char), called "ready", which will contain the values ​​0 and 1. Thus, although the "Result" is not "ready", then the user should not try to process the item yet. Again, “item” can be NULL if the user returns NULL, but “ready” allows the user to know that he has finished.

struct Result {
    /// Determines whether or not it has been processed.
    unsigned char ready;
    /// The return type, NULL until ready.
    void *item;
};

, , , . , , .

, , . , , ( ). . , thread_pool, , , .

, ( , ). add_task (Thread A) sub_process, , . (. ? Thread B) , Thread A Thread B, , . , , .

, 2 , 1, , . ? pthread , ? , Sub_Process .

/// Makes it easier than having to retype everything.
typedef void *(*thread_callback)(void *args);

struct Sub_Process {
    /// Result to be processed.
    Result *result;
    /// Thread callback to be processed
    thread_callback cb;
    /// Arguments to be passed to the callback
    void *args;
};

? , Thread_Pool. : , , ? , , , , , .

,

: , , lemme , - .

: , , .

+4
1

, , , , , .

, Result. , mutex condition Result:

struct Result {
    /// Lock to protect contents of `Result`
    pthread_mutex_t lock;
    /// Condition variable to signal result being ready
    pthread_cond_t cond;
    /// Determines whether or not it has been processed.
    unsigned char ready;
    /// The return type, NULL until ready.
    void *item;
};

, , :

pthread_mutex_lock(&result->lock);
while (!result->ready)
    pthread_cond_wait(&result->cond, &result->lock);
pthread_mutex_unlock(&result->lock);

, , , , Result .

:

pthread_mutex_lock(&result->lock);
result->item = item;
result->ready = 1;
pthread_cond_signal(&result->cond);
pthread_mutex_unlock(&result->lock);

: , , ? , , , , .

, . , , - , , .

+2

All Articles