我想編寫一個示例程序,其中16個線程可以訪問像10gb這樣巨大大小的共享對象。我知道我可以使用pthread_mutex_t
來獲取對象的鎖定,但是如何使其有效,以便兩個或多個線程可以同時修改共享對象的不相交部分?pthread中的共享對象
0
A
回答
2
也許你可以創建一個10個pthread_mutex_t的數組,每個1gb範圍一個,並且鎖定你將要修改的範圍的適當的互斥鎖?
1
怎麼樣使用sempahore。您可以使用共享資源的線程數初始化信號量。
/* Includes */
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <semaphore.h> /* Semaphore */
void semhandler (void *ptr);
sem_t mutex;
int cntr=0; /* shared variable */
int main()
{
int arg[2];
pthread_t thread1;
pthread_t thread2;
arg[0] = 0;
arg[1] = 1;
/* initialize mutex to 2 to share resource with two threads*/
/* Seconds Argumnet "0" makes the semaphore local to the process */
sem_init(&mutex, 0, 2);
pthread_create (&thread1, NULL, (void *) &semhandler, (void *) &arg[0]);
pthread_create (&thread2, NULL, (void *) &semhandler, (void *) &arg[1]);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
sem_destroy(&mutex);
exit(0);
} /* main() */
void semhandler (void *ptr)
{
int x;
x = *((int *) ptr);
printf("Thrd %d: Waiting to enter critical region...\n", x);
sem_wait(&mutex); /* down semaphore */
if(x == 1)
cntr++;
/* START CRITICAL REGION */
printf("Thrd %d: Now in critical region...\n", x);
printf("Thrd %d: New Counter Value: %d\n", x, cntr);
printf("Thrd %d: Exiting critical region...\n", x);
/* END CRITICAL REGION */
sem_post(&mutex); /* up semaphore */
pthread_exit(0); /* exit thread */
}
+0
謝謝,但巨大的共享對象呢? – Sara
+0
如何在對象內添加一個「互斥體」變量?在使用該對象之前先取出該互斥體,然後在完成後釋放它 –
相關問題
- 1. 多處理共享對象中的共享對象
- 2. 共享對象
- 3. R中的共享對象
- 4. Cocoa中的共享對象
- 5. 鏈接到另一個共享對象的共享對象
- 6. 在php中共享對象
- 7. 在堆中共享對象
- 8. 從共享對象
- 9. 在共享對象
- 10. Java共享對象
- 11. C++共享對象
- 12. TraitsUI,共享對象
- 13. 共享對象的位置
- 14. pthread從共享內存讀取
- 15. pthread進程共享互斥死鎖
- 16. 不同請求中的共享對象
- 17. 鏈接QTP中的共享對象庫
- 18. AIX中的共享對象加載?
- 19. C#和Android中的類對象共享
- 20. Flash中的共享對象到Javascript?
- 21. 從共享對象中的類繼承
- 22. C++:創建一個共享的對象,而不是共享的對象指針
- 23. Python對象屬性共享
- 24. 共享對象和線程
- 25. Servlets之間共享對象
- 26. 任務共享對象 - salesforce
- 27. 共享對象協議
- 28. 引用共享對象AS3
- 29. Web API對象共享
- 30. 共享對象語法
謝謝。你知道任何例子,因爲我不知道如何管理範圍! – Sara
在不瞭解應用程序的情況下很難舉一個例子。你對線程如何訪問共享對象的各個部分有什麼想法嗎? – faffaffaff
他們只是寫一些信息。 – Sara