创建多个线程的参数传递问题
来源:互联网 发布:网络电视怎么放dvd 编辑:程序博客网 时间:2024/05/16 12:14
先看下面的程序thread1.c:
#include <stdio.h>#include <pthread.h>#include <stdlib.h>void *thread_func(void *var);int main(void){ pthread_t tid; int var; int i; for (i=0; i<20; i++) { var = i; pthread_create(&tid, NULL, thread_func, &var); } pthread_exit(NULL);}void *thread_func(void *var){ int x = *(int*)var; pthread_detach(pthread_self()); printf("thread %d\n", x);}
编译:gcc thread1.c -pthread -o thread1
运行:./thread1
这个程序我们期望的结果是:输出不重复的thread 0~19,但是实际上是有重复的。如果子线程中的赋值语句在主线程中下一个循环var = i之前执行,那么结果是正确的,然而如果是在之后才执行,下一个i就会覆盖掉前一个var,这样就会出现相同的结果。
#include <stdio.h>#include <pthread.h>#include <stdlib.h>void *thread_func(void *var);int main(void){ pthread_t tid; int *var = NULL; int i; for (i=0; i<20; i++) { var = (int*)malloc(sizeof(int)); *var = i; pthread_create(&tid, NULL, thread_func, var); } pthread_exit(NULL);}void *thread_func(void *var){ int x = *(int*)var; if (var) { free(var); var = NULL; } pthread_detach(pthread_self()); printf("thread %d\n", x);}
编译:gcc thread2.c -pthread -o thread2
运行:./thread2
之前是因为在同一块内存上传值会造成覆盖,现在我们为每个新创建的线程都创建一块内存,这样他们每个线程都有一块内存供传值,就不会覆盖别人的内存了。
上面只是举个例子,不用中间变量var而是直接把i作为参数传递也是没什么问题的。关键是这个参数也许不是那么简单,可能是accept客户端socket描述符,所以这样举例子也是可以的。
当然,上面问题利用线程间同步也是可以解决的。
- 创建多个线程的参数传递问题
- 线程Thread传递一个或多个参数问题
- mybatis传递多个参数的问题
- 专门的线程类,多个参数的传递
- pthread_create()给创建的线程传递参数
- MFC中线程传递多个参数的方法
- 向线程传递多个参数的变通方法(c#)
- setTimeout传参数 传递多个参数的问题
- C++线程传递多个参数demo
- 创建线程时候多参数传递方法及参数改变问题--扫雷辅助(三)
- C#创建线程传递参数
- 多个参数的传递
- struts2多个参数传递问题
- js传递汉字类型参数值乱码问题,以及url传递多个参数报违法的参数值
- 【转】传递参数到线程的n个方法
- 传递参数到线程的n个方法
- 【转】传递参数到线程的n个方法
- 传递参数到线程的n个方法
- 第九周任务2
- R树
- CMake 错误
- php高级编程-函数
- rapidsvn "remains in tree conflict"的解决方法
- 创建多个线程的参数传递问题
- 第九周作业任务三
- 关于键盘输入cvWaitKey(0)没有反应
- android parcel
- Android编程经验
- 2B青年答疑:什么是2B青年?如何脱离2B青年行列?
- 黑马程序员—5.0新特性
- 第九周任务5
- SQL语句大全