首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从int数组中取出前三个(或所需数量),将它们存储到一个新的临时数组中,同时删除OG数组中的这三个数组。

从int数组中取出前三个(或所需数量),将它们存储到一个新的临时数组中,同时删除OG数组中的这三个数组。
EN

Stack Overflow用户
提问于 2018-11-02 03:40:21
回答 1查看 27关注 0票数 0

所以从技术上讲,我实际上是在尝试设计其他东西,但在这样做的过程中,我必须找出一种可能的方法来做到这一点。我稍后可以处理所有更复杂的东西,但请允许我详细说明我需要什么:假设我有一个整型数组,比如说: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个。

EN

回答 1

Stack Overflow用户

发布于 2018-11-02 04:26:03

您是否需要初始listofNums来删除每个线程正在获取的三个参数,或者只是不再指向它们?如果您删除它们,您必须创建一个新数组,复制新数组,然后销毁/释放旧数组。在C中没有动态调整数组大小的功能。

更好的方法是让每个线程递增数组指针,并将此逻辑包装在互斥锁中。下面是我的意思的sudo代码示例:

代码语言:javascript
运行
复制
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.

}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53108293

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档