从线程外部修改线程数据
如何从线程外部修改线程数据?
如果一个线程正在运行一个在应用程序运行时循环的函数,那么如何设置、更改其数据?
如何调用修改特定线程函数的函数?
这些功能属于哪里?
How does one modify a threads data from outside a thread?
If a thread is running a function that loops for the runtime of the application, how can its data be set, changed?
How does one call functions which modify a specific threads functions?
Where do these functions belong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
线程的优点和缺点是它们与进程中的所有其他线程共享内存空间。您可以使用在单线程应用程序中使用的任何形式的数据传输来在应用程序的各个段之间传递数据。但是,在多线程应用程序中,您必须使用某种类型的同步来确保数据完整性并防止死锁。
The advantage and disadvantage of threads is that they share the memory space with every other thread in the process. You can use any form of data transfer you would use in single threaded applications to pass data betweens segments of you application. However, in a multi-threaded application you must use some type of synchronization to assure data integrity and prevent deadlocks.
如果您要从外部修改的“线程数据”采用线程中运行的函数中的局部变量的形式,或者使用
__thread
扩展名创建的线程特定数据,则 唯一可以从外部修改它们的方法(使用 UB 的模代码从技术上来说只是浪费内存)是让线程获取其变量的地址并将其存储在其他线程可以看到它的地方(或者在全局变量中) ,或者在via传入的位置线程启动函数的void *
参数还请注意,正如 rerun 所指出的,如果多个线程访问相同的数据,则必须使用某种同步方法。 pthread 的:
pthread_mutex_lock
等,但您也可以使用汇编或编译器内在函数(如 gcc 中的__sync_*
)。If the "thread's data" you want to modify from outside is in the form of local variables in a function running in the thread, or thread-specific data created with the
__thread
extension, then the only way you can modify them from outside (modulo code with UB that's technically just trashing memory) is by having the thread take the addresses of its variables and store that somewhere where other threads can see it (either in a global variable, or at a location passed in via the thread start function'svoid *
argument.Also note that, as rerun pointed out, you have to use some method of synchronization if multiple threads are accessing the same data. The only standard/portable synchronization methods are the pthread ones:
pthread_mutex_lock
etc., but you can also use assembly or compiler intrinsics (like__sync_*
in gcc).