2016-05-08 90 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; 
}