所以从技术上讲,我实际上是在尝试设计其他东西,但在这样做的过程中,我必须找出一种可能的方法来做到这一点。我稍后可以处理所有更复杂的东西,但请允许我详细说明我需要什么:假设我有一个整型数组,比如说:int listofNums[]
,内容是1 2 3 4 5 6 7 8 9 10 100 101 102 103 104 105 106 107
,我想将这些内容的一部分传递到多个线程中,所以假设线程1将获得数组[1,2,3]
,线程2将获得[4,5,6]
.....so。我可以做线程部分,但我只是想知道他们是否有任何函数或方法,我可以调用,可以在每次迭代中获取前3个,同时从原始中删除这3个。
发布于 2018-11-02 04:26:03
您是否需要初始listofNums来删除每个线程正在获取的三个参数,或者只是不再指向它们?如果您删除它们,您必须创建一个新数组,复制新数组,然后销毁/释放旧数组。在C中没有动态调整数组大小的功能。
更好的方法是让每个线程递增数组指针,并将此逻辑包装在互斥锁中。下面是我的意思的sudo代码示例:
int main(){
int listofNums[SIZE] = {1,2,3,4,5,6,100,101,102, 111, 112, 113};
int * first_element = &listofNums[0];
p_thread_create(Thread_1_entry_function, listofNums,0,0,etc);
p_thread_create(Thread_2_entry_function, listofNums,0,0,etc);
p_thread_create(Thread_3_entry_function, listofNums,0,0,etc);
p_thread_create(Thread_4_entry_function, listofNums,0,0,etc);
//listofNums should now be pointing to the listofNums[12], should not be used unless you re assign it to listofNums[0] explcitly.
listofNums = first_element; //array decay has happened, sizeof listofNums should be sizeof int instead of sizeof int * SIZE (num of array elements).
p_thread_join(all_threads);
}
void Thread_1_entry_function(void* listofNums, void* arg2, etc){
mutex_acquire(Some_mutex);
int Thread_1_listofNums[3] = {*listofNums++, *listofNums++, *listofNums++};
mutex_release(Some_mutex);
//other thread stuff that uses Thread_1_listofNums. listofNums is now pointing to the index [3] instead of [0] for the next thread.
}
void Thread_2_entry_function(void* listofNums, void* arg2, etc){
mutex_acquire(Some_mutex);
int Thread_2_listofNums[3] = {*listofNums++, *listofNums++, *listofNums++};
mutex_release(Some_mutex);
//other thread stuff that uses Thread_2_listofNums. listofNums is now pointing to the index [6] instead of [0] for the next thread.
}
void Thread_3_entry_function(void* listofNums, void* arg2, etc){
mutex_acquire(Some_mutex);
int Thread_3_listofNums[3] = {*listofNums++, *listofNums++, *listofNums++};
mutex_release(Some_mutex);
//other thread stuff that uses Thread_3_listofNums. listofNums is now pointing to the index [9] instead of [0] for the next thread.
}
void Thread_4_entry_function(void* listofNums, void* arg2, etc){
mutex_acquire(Some_mutex);
int Thread_4_listofNums[3] = {*listofNums++, *listofNums++, *listofNums++};
mutex_release(Some_mutex);
//other thread stuff that uses Thread_4_listofNums. listofNums is now pointing to the index [12] instead of [0] for the next thread.
}
https://stackoverflow.com/questions/53108293
复制相似问题