Can multithreading be implemented on a single processor system?

前端 未结 6 1064
走了就别回头了
走了就别回头了 2020-12-04 08:16

I have always followed the concept that multithreading can only be implemented on multiple processors system where there are more than one processor to be assigned to each t

6条回答
  •  误落风尘
    2020-12-04 09:09

    Here's a very simplified example. It's actually a prototype for a program I'm building. It's a implementation of cooperative multitasking in a single thread.

    main simply sets the quit flag to false, and populates an array of function pointers (the tasks), and then calls loop.

    loop uses setjmp to set a return point for a non-local jump (a jump out of the function back to a previous location in the execution) and then proceeds to call the first task (function).

    Each task ends with yield(). That is, none of the task functions actually return. Not only do they not contain a return; statement (which would be fine since they are void functions, ie. procedures), but they wouldn't reach the return even if it was there because yield jumps back to the setjmp call, this time yielding a 1 to the if statement in loop. The statement controlled by the if statement selects a different task before re-entering the while loop.

    So each task function runs multiple times, yielding to the dispatcher (the if(setjmp... statement) which selects a new task to run.

    #include  
    #include  
    
    jmp_buf dispatch; 
    int ntasks; 
    void (*task[10])(void); 
    int quit; 
    
    void yield(void) { 
        longjmp(dispatch, 1); 
    } 
    
    void loop() { 
        static int i = 0; 
        if(setjmp(dispatch)) 
            i = (i+1) % ntasks; 
        while(!quit) 
            task[i](); 
    } 
    
    int acc = 0; 
    
    void a(void) { 
        if (acc > 10) quit = 1; 
        printf("A\n"); 
        yield(); 
    } 
    void b(void) { 
        acc *= 2; 
        printf("B\n"); 
        yield(); 
    } 
    void c(void) { 
        acc += 1; 
        printf("C\n"); 
        yield(); 
    } 
    
    int main() { 
        quit = 0; 
        ntasks = 3; 
        task[0] = a; 
        task[1] = b; 
        task[2] = c; 
        loop(); 
        return 0; 
    } 
    

    The difference between this example and a single-processor multitasking computer system is the real processor supports interrupting a task in the middle of execution and resuming it later from the same spot. This isn't really possible in a C simulation with tasks as single functions. However, the tasks could be composed of a sequence of C functions which each yield to the dispatcher (an array of function pointers, maybe, or a linked-list).

提交回复
热议问题