2016-05-08 91 views
0

我有一个范围的数字(即1〜10000)。
我需要创建threads来搜索值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; 
} 

问题至今:

  • 我不知道如何找到thread ID。 (尝试pthread_self(),但我总是得到一个巨大的负数,所以我认为是错误的
  • 我知道pthread_create()创建和初始化线程,也pthread_join将使我的主程序等待线程。代码它似乎并没有运行。
  • 我的threadX如何知道它应该从什么值开始搜索?(即:如果我有10个线程,我不认为我必须创建10个功能oO)

  • 是否有可能让它们同时运行而没有类似Mutex

+0

也许这[SO帖子](http://stackoverflow.com/questions/21091000/how-to-get-thread-id-of-a-pthread-in-linux-c-program)可以提供更多信息。 – user3078414

+0

如果您想要将多个值(例如,X和搜索范围)传递给您的线程函数,您可以将它们放入一个结构中并传递一个指针。 – Dmitri

回答

1

获取线程ID取决于您的操作系统。

参见how to get thread id of a pthread in linux c program? as @ user3078414提到,和why compiler says ‘pthread_getthreadid_np’ was not declared in this scope?

致信@Dmitri,将多个值传递给线程函数的示例。线程并发运行。 Mutexes是处理共享数据以及如何访问它的完整章节。

#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; 
}