c - 线程安全唯一事务ID

标签 c multithreading

谢谢大家帮助我,我分享下面的代码,因为它可以提供线程安全的 4 字节事务/ session ID,或者至少我认为它是:)。它将为 16 个线程/16 个进程提供大量的唯一 ID。 下面是对该功能的基本测试,p_no是进程号。

int get_id(int choice, unsigned int pid);
    int start_(int id);
    void *print_message_function( void *ptr );
    void *print_message_function2( void *ptr );

      unsigned int pid_arr[15][2];
    int p_no = 1;
    int main()
    {
         pthread_t thread1, thread2;
         char *message1 = "Thread 1";
         char *message2 = "Thread 2";    
         int  iret1, iret2;
    int s,f;
        for (s=0;s<15;s++)
        {
        for (f=0;f<2;f++)
        pid_arr[s][f]= 0;

        }

         iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
         iret2 = pthread_create( &thread2, NULL, print_message_function2, (void*) message2);

         pthread_join( thread1, NULL);
         pthread_join( thread2, NULL); 
         exit(0);
    }

    void *print_message_function( void *ptr )
    {
    int one=0;

    get_id(1/*register*/,(unsigned int)pthread_self());
    while (1)
    {

    int ret = get_id(0,(unsigned int)pthread_self());
    printf("thread 1 = %u\n",ret);
    sleep(1);
    }

    }
    void *print_message_function2( void *ptr )
    {
    int one=0;

    get_id(1/*register*/,(unsigned int)pthread_self());

    while (1)
    {

    int ret = get_id(0,(unsigned int)pthread_self());
    printf("thread 2 = %u\n",ret);
    sleep(1);
    }

    }


    int get_id(int choice, unsigned int pid)
    {
    int x;


       if (choice==1) // thread registeration part 
        {
           for(x=0;x<15;x++)
        {
            if (pid_arr[x][0] == 0) 
            {
            pid_arr[x][0] = pid;     
           pid_arr[x][1] = ((p_no<<4) | x) << 24;   

           break;
            }
         }

        }

    int y;
           for(y=0;y<15;y++) // tranaction ID part 
        {
           if (pid_arr[y][0]==pid)  
            {

             if(pid_arr[y][1] >= ((((p_no<<4) | y) << 24) | 0xfffffd) )
            ((p_no<<4) | x) << 24; 
            else 
            pid_arr[y][1]++;
            return (unsigned int) pid_arr[y][1];
            break;
           }
        }

    }

最佳答案

它不是线程安全的。例如,在注册部分,以下几行最终会出现问题:

1:     if ( pid_arr[x][0] == 0 )
        {
2:        pid_arr[x][0] = pid;     

如果线程 1 执行第 1 行,然后在执行第 2 行之前发生上下文切换,则线程 2 可以运行并执行第 1 行。此时,两个线程最终都可以在 pid_arr 中“拥有”相同的位置。/ 数组。或者,更确切地说,执行第 2 行的最后一个将拥有该位置,而另一个将不拥有数组中的任何位置。

关于c - 线程安全唯一事务ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200471/

相关文章:

java - 多个套接字导致 ConnectException : Connection refused: connect

iphone - PerformselectorinBackground 不起作用

java - Java 中使用信号量的多线程

c - 使用 objdump 查看时,GCC 调试选项不考虑预处理器 #if

c - 二维数组的操作: add rows and columns

c - 为什么指针为所有数组 block 提供相同的地址?

multithreading - WCF支持的最大并发线程数?

java - native a方法中的参数传递

c - 嵌入式系统开发为什么要烧录根文件系统

python - 多进程池与 asyncio.run_in_executor