Linux Pthread 库,线程参数 [英] Linux Pthread library, thread arguments

查看:37
本文介绍了Linux Pthread 库,线程参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在Linux下使用Pthread库创建线程,我需要使用函数pthread_create,作为它的参数之一void *,所以我可以传递一个指向某物的指针,所以我的线程例程可以访问它,但是做这样的事情是否安全

If I create thread using Pthread library under Linux, I need to use function pthread_create, as one of the arguments it takes void *, so I can pass a pointer to something, so my thread routine can get access to it, but is it safe to do something like this

{//some scope
    int a=5//scope variable
    pthread_create(&id,NULL,some_function,(void*)a);
}//end of scope

在我的日常生活中:

void *some_function(void *_arg)
{
    int a=(int)arg;
    return NULL;
}

我想做这样的事情,所以我可以将变量的值保留在堆栈上,这样我就可以从我的线程例程中访问它,但我不想为单个变量创建结构或手动分配内存.

I want to do something like this, so I can keep the value of a variable on stack so I can access it from my thread routine but I don't want to create struct for single variable or manually allocate memory.

我将创建几个这样的线程,所以我想知道在这种情况下我是否可以避免使用列表或动态数组.

I will be creating few threads like this, so I wanted to know if in situation like this I can get by and don't use list or dynamic array.

推荐答案

你所做的在现实世界中是完全安全的:intvoid * 之间的转换不是未定义的行为,它是实现定义的,并且所有实现都以自然、理智的方式定义它.这也是将单整数参数传递给新线程的唯一有效方法.其他方法都需要昂贵的同步,通过显式锁定或通过在原始线程中使用 malloc 和在新线程中使用 free(在 malloc/free 实现).

What you're doing is perfectly safe in the real world: conversion between int and void * is not undefined behavior, it's implementation-defined, and all implementations define it in the natural, sane way. It's also the only efficient way to pass single-integer arguments to a new thread. Other approaches all require expensive synchronization, either via explicit locking or by using malloc in the original thread and free in the new thread (which has implicit synchronization cost hidden in the malloc/free implementation).

然而,您会发现一件事是,某些编译器会针对转换发出警告.这是因为旧的损坏代码假定 int 可以表示 void * 的全部值;编译器无法区分在 void * 中存储 int 的(有效)实践和存储 void *<的(无效)实践/code> 在 int 中.作为解决方案,您可能希望使用 intptr_t 而不是 int,这将避免警告.如果您的原始变量是 int,只需通过 intptr_t 添加额外的中间转换即可避免警告.

One thing you will discover, however, is that some compilers issue warnings for the conversion. This is because of old broken code that assumes int can represent the full range of values of void *; the compiler is unable to distinguish between the (valid) practice of storing an int in a void *, and the (invalid) practice of storing a void * in an int. As a solution, you might want to use intptr_t instead of int, which will avoid the warning. If your original variables are int, simply adding an extra intermediate cast through intptr_t will avoid the warnings.

这篇关于Linux Pthread 库,线程参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆