- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个数字范围(即 1~10000)。
我需要创建线程
来搜索值X。
每个线程都有自己的搜索间隔(即 10000/threadNumber)。
我猜让线程按顺序运行是没有意义的。我无法让它们同时运行...
到目前为止我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define limit 10000
#define n_threads 2
void* func1(void* arg)
{
int i=0, *value = (int *)arg;
//How may I know which thread is running and make the thread search for the right range of values ?
for(i=1; i<=limit/n_threads; i++)
{
if(*value == i){
//Print the thread ID and the value found.
}
else
//Print the thread ID and the value 0.
}
return NULL;
}
int main(int argc, char const *argv[])
{
if(argc < 2)
printf("Please, informe the value you want to search...\n");
else{
pthread_t t1, t2;
int x = atoi(argv[1]); //Value to search
pthread_create(&t1, NULL, func1, (void *)(&x));
pthread_create(&t2, NULL, func1, (void *)(&x));
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
return 0;
}
到目前为止的问题:
线程 ID
。 (尝试使用 pthread_self()
但我总是得到一个巨大的负数,所以我认为出了问题。pthread_create()
创建并初始化线程,而且 pthread_join
将使我的主程序等待线程。但查看我的代码,它似乎没有同时运行。 我的 threadX
如何知道它应该从什么范围的值开始搜索? (即:如果我有 10 个线程,我认为我不必创建 10 个函数 o.O )。
是否可以使它们同时运行,而不需要像 Mutex
这样的东西?
最佳答案
获取线程 ID 根据您的操作系统而有所不同。
参见how to get thread id of a pthread in linux c program?正如@user3078414提到的,和why compiler says ‘pthread_getthreadid_np’ was not declared in this scope? .
感谢@Dmitri,这是一个将多个值传递给线程函数的示例。线程同时运行。互斥体是另一章,专门讨论共享数据以及如何访问它。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define limit 10000
#define n_threads 2
struct targs {
int from;
int to;
};
void *func1(void *arg) {
struct targs *args = (struct targs *) arg;
printf("%d => %d\n", args->from, args->to);
// free(arg)
return NULL;
}
int main(int argc, char const *argv[]) {
struct targs *args;
pthread_t t1;
pthread_t t2;
args = (struct targs *) malloc(sizeof(args));
args->from = 0;
args->to = 100;
pthread_create(&t1, NULL, func1, (void *) args);
args = (struct targs *) malloc(sizeof(args));
args->from = 100;
args->to = 200;
pthread_create(&t2, NULL, func1, (void *) args);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
关于c - 执行 'paralelism'中的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37101987/
前言 简单整理一下paralel,以上是并行的意思。 正文 我们在工作中常常使用task await 和 async,也就是将线程池进行了封装,那么还有一些更高级的应用。 是
我有一个非常特殊的问题。我需要为我的学校项目审查 NASA Parallel Benchmarks,但我发现这是一个非常有问题的任务 :-) 起初,我尝试使用 IS(整数排序),但代码无法编译,并且我
我是一名优秀的程序员,十分优秀!