简体   繁体   English

如何验证线程创建(C程序)

[英]How To Verify Thread Creation (C-Program)

I'm creating a program that will require n-specified threads that will each act as a "mole" (I'm making whack-a-mole). 我正在创建一个程序,该程序将需要n个指定线程,每个线程都将充当“痣”(我正在制作w鼠痣)。 Now.. I think I have something that does that, but I'm not convinced that my print statements actually verify that I have n-different threads... how exactly can I know that this has worked? 现在..我想我可以做到这一点,但是我不相信我的打印语句实际上可以验证我是否拥有n个不同的线程……我怎么能知道这确实有效?

my code is as follows: 我的代码如下:

#include <stdio.h>
#include <pthread.h>

int k = 0;

void* thread_function()
{
    k++;
    printf("Mole #%d\n", k);
}

int main(int argc,char *argv[])
{
    int mole_count= atoi(argv[1]);
    pthread_t thread_id[mole_count];
    int i;

    for(i=0;i<mole_count;i++)
    {
        pthread_create (&thread_id[i], NULL , &thread_function, NULL);

    }  

    for(i=0;i<mole_count;i++){
        pthread_join(thread_id[i],NULL);   
    }

    return 0;
}

Thanks 谢谢

The pthread_create() function will return 0 on success, so you know whether or not the thread was successfully created. pthread_create()函数成功时将返回0,因此您知道线程是否成功创建。 (What happens after that depends on the thread function itself, obviously.) (之后发生的事情显然取决于线程函数本身。)

Every thread within a process has a unique ID associated with it (just as all processes in the OS have a unique process iD). 进程中的每个线程都有一个与之关联的唯一ID(就像OS中的所有进程都有唯一的进程iD一样)。 You can query the ID of the thread by calling pthread_t pthread_self() . 您可以通过调用pthread_t pthread_self()来查询线程的ID。 So you could print out this arbitrary but unique value in each thread function, showing you each different thread running. 因此,您可以在每个线程函数中打印出这个任意但唯一的值,向您显示每个不同的线程正在运行。

Note that your counter k is shared, but is not protected by a mutex. 请注意,您的计数器k是共享的,但不受互斥量保护。 Since it is updated (read-modify-update) in each thread, there is the potential for race condition and thus buggy behaviour. 由于在每个线程中都对其进行了更新(读取,修改,更新),因此存在争用情况并因此可能会引起错误的行为。 Use an atomic variable to avoid these problems. 使用原子变量可以避免这些问题。

Also, your thread function should return NULL since it has the return type of void* . 另外,您的线程函数应返回NULL因为它的返回类型为void*

Now having explained all that, I'm not sure that a "whack-a-mole" game is a good candidate for multiple threads. 在解释了所有这些内容之后,我不确定“轻击”游戏是否适合多线程游戏。 Threads can be very useful, but bring with them complexities of their own. 线程可能非常有用,但是带来了它们自己的复杂性。 For example, how do you communicate between threads, maintain shared state, and coordinate events? 例如,如何在线程之间通信,维护共享状态以及协调事件? Threads can also make debugging significantly more difficult. 线程也会使调试变得更加困难。 Consider a simpler design with a round-robin approach to begin with. 首先考虑采用循环方法的简单设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM