【问题标题】:synchronisation primitives for increment增量同步原语
【发布时间】:2011-07-28 02:45:20
【问题描述】:

我是学习线程的初学者, 我有一个作业来解决 os161 的互斥问题,通过启动几个增加一个公共计数器的线程来从 0 计数到 10000。我不知道如何使用同步原语来改进它,请帮忙。

#include <types.h>
#include <lib.h>
#include <test.h>
#include <thread.h>
#include <synch.h>

enum {
    NADDERS = 10,    /* the number of adder threads */
    NADDS   = 10000, /* the number of overall increments to perform */
};

/*
 * **********************************************************************
 * Declare the counter variable that all the adder() threads increment 
 *
 * Declaring it "volatile" instructs the compiler to always (re)read the
 * variable from memory and not optimise by removing memory references
 * and re-using the content of a register.
 */
volatile unsigned long int counter;


/*
 * Declare an array of adder counters to count per-thread
 * increments. These are used for printing statistics.
 */  
unsigned long int adder_counters[NADDERS];


/* We use a semaphore to wait for adder() threads to finish */
struct semaphore *finished;

/*
 * **********************************************************************
 * ADD YOUR OWN VARIABLES HERE AS NEEDED
 * **********************************************************************
 */

/*
 * adder()
 *
 *  Each adder thread simply keeps incrementing the counter until we
 *  hit the max value.
 *
 * **********************************************************************
 * YOU NEED TO INSERT SYNCHRONISATION PRIMITIVES APPROPRIATELY 
 * TO ENSURE COUNTING IS CORRECTLY PERFORMED.
 * **********************************************************************
 *
 * You should not re-write the existing code.
 *
 * * Only the correct number of increments are performed
 * * Ensure x+1 == x+1 
 * * Ensure that the statistics kept match the number of increments
 * * performed.
 *
 *
 */

static void adder(void * unusedpointer, unsigned long addernumber)
{
    unsigned long int a, b;
    int flag = 1;

    /*
     * Avoid unused variable warnings.
     */
    (void) unusedpointer; /* remove this line if variable is used */

    while (flag) {
        /* loop doing increments until we achieve the overall number
           of increments */

        a = counter;

        if (a < NADDS) {

            counter = counter + 1;

            b = counter;

            /* count the number of increments we perform  for statistics */
            adder_counters[addernumber]++;    

            /* check we are getting sane results */
            if (a + 1 != b) {
                kprintf("In thread %ld, %ld + 1 == %ld?\n", addernumber, a, b) ;
            }
        }
        else {
            flag = 0;
        }
    }

    /* signal the main thread we have finished and then exit */
    V(finished);

    thread_exit();
}

/*
 * math()
 *
 * This function:
 *
 * * Initialises the counter variables
 * * Creates a semaphore to wait for adder threads to complete
 * * Starts the define number of adder threads
 * * waits, prints statistics, cleans up, and exits
 */
int maths (int nargs, char ** args)
{
    int index, error;
    unsigned long int sum;

    /*
     * Avoid unused variable warnings.
     */

    (void) nargs;
    (void) args;

    /* create a semaphore to allow main thread to wait on workers */

    finished = sem_create("finished", 0);

    if (finished == NULL) {
        panic("maths: sem create failed");
    }

    /*
     * **********************************************************************
     * INSERT ANY INITIALISATION CODE YOU REQUIRE HERE
     * **********************************************************************
     */


    /*
     * Start NADDERS adder() threads.
     */


    kprintf("Starting %d adder threads\n", NADDERS);

    for (index = 0; index < NADDERS; index++) {

        error = thread_fork("adder thread", &adder, NULL, index, NULL);

        /*
         * panic() on error.
         */

        if (error) {
            panic("adder: thread_fork failed: %s\n", strerror(error));
        }
    }


    /* Wait until the adder threads complete */

    for (index = 0; index < NADDERS; index++) {
        P(finished);
    }

    kprintf("Adder threads performed %ld adds\n", counter);

    /* Print out some statistics */
    sum = 0;
    for (index = 0; index < NADDERS; index++) {
        sum += adder_counters[index];
        kprintf("Adder %d performed %ld increments.\n", 
                index, adder_counters[index]);
    }
    kprintf("The adders performed %ld increments overall\n", sum);

    /*
     * **********************************************************************
     * INSERT ANY CLEANUP CODE YOU REQUIRE HERE 
     * **********************************************************************
     */


    /* clean up the semaphore we allocated earlier */
    sem_destroy(finished);
    return 0;
}

【问题讨论】:

  • 一种方法是使用 乐观并发Compare And Swap 或类似方法——再加上自旋锁,这可以避免完全互斥体的开销/像这样的简单情况下的信号量。但是,我不知道这些概念在 C-land 中是如何工作的 :)

标签: c multithreading synchronisation os161


【解决方案1】:

请注意,如果计数器位于内存中并标记为“易失性”,则“计数器 = 计数器 + 1”不是原子操作。所以加一操作必须受到某种互斥体的保护。

您可以使用 os161 的锁定功能来保护线程之间的共享数据。代码可能如下所示:

// declare a global lock variable so every threads can access it
static struct lock* counter_lock;

// initialize the lock before you fork threads
counter_lock = lock_create("counter lock");

// when each thread tries to access the counter, use lock to protect it
lock_acquire(counter_lock);
counter++;
lock_release(counter_lock);

// destroy the lock after all threads are done
lock_destroy(counter_lock);

当然,作为赋值,你必须自己实现/kern/thread/synch.c中的ss锁接口。

【讨论】:

    【解决方案2】:

    一些小事;

    1. 不要对这些值使用枚举 - 使用定义 - 枚举用于 类似类型的事物,例如结果,错误类型等。线程数和增量数不同。

    2. volatile 不会对任何事情产生任何影响——它只是指示编译器永远不要优化读取;但是你在递增,所以你总是要在写入之前读取变量

    关于主要问题;

    1. 最简单的解决方案是互锁增量; GCC 的 instrincs 提供了这样的功能

    【讨论】:

    • +1 有 GCC 中互锁增量的示例或链接吗?其他 C 编译器呢?
    • 您必须将 asm 与其他编译器一起使用。或者你可以在修改变量时使用互斥锁,然后只是一个正常的增量。
    • 我还以为互斥锁用来锁定某个进程,稍后再唤醒它,它怎么能与“修改变量”相关?os161或c语言有互锁增量功能吗?
    • @R:MS C 编译器也有这方面的本能。
    • 我不确定,我的任务是通过添加锁、互斥锁等来改进代码。我无法更改整个代码..
    【解决方案3】:

    既然您是该领域的初学者,请不要使用花哨的东西。只需通过互斥锁保护您的计数器即可。

    // with static linkage somewhere
    pthread_mutex_t countMut = PTHREAD_MUTEX_INITIALIZER;
    size_t count = 0;
    
    // in the functions
    pthread_mutex_lock(&countMut);
    ++count;
    pthread_mutex_unlock(&countMut);
    

    【讨论】:

    • 能否提供thread.h形式的互斥代码,而不是pthread.h,我的编译器没有pthread.h,谢谢
    • @user688550:不抱歉,我对此一无所知。首先,如果需要,您应该添加一个特定于操作系统的标志。然后,因为这是家庭作业,我可能也不会。这些是关于线程计算的最基本的东西。为自己提供文档、书籍、讲座笔记等等。
    • 你知道POSIX线程中的方式是不是有点冲突,但对普通线程一无所知(thread.h);感谢您的建议,但您应该知道,大多数资源都是关于理论而不是编码机制...除了我需要使用 thread.h 正确初始化互斥锁,因为我在使用互联网上的那些时一直出错...
    • @user688550:我们似乎对“正常”有不同的看法。我拥有的系统都符合 POSIX,因此它们都有“pthread.h”而没有“thread.h”(“pthread”代表 POSIX 线程)。你仍然没有说你在哪个操作系统上工作。对于所有操作系统,都有很多 的编程资源文档。请学习使用搜索引擎。
    • @user688550,从未听说过。所以这真的是一个教学操作系统吗?询问您的教师他们将文档隐藏在哪里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 2011-04-18
    • 2014-12-27
    • 2020-10-24
    相关资源
    最近更新 更多