【问题标题】:How to check if memory is available for read/write operation?如何检查内存是否可用于读/写操作?
【发布时间】:2015-04-28 11:36:10
【问题描述】:

我正在尝试将字符值写入我使用malloc() 定义的内存中,并同时从中读取一个字符值。为此,我全局定义内存,然后启动一个线程。在线程中,我在内存中写入字符值,在 main() 中,我正在从中读取值。这是我的代码:-

char *str = (char *) malloc(90000);
DWORD WINAPI Thread_no_1( LPVOID lpParam ) 
{
    int a=1;
    int c=0;
 LOOP:do
   {
        str[c] = 'a';
            c++;
            goto LOOP;
   }while( a < 2 );

    return 0;
}

int main()
{
int b=0;
char value;

int Data_Of_Thread_1 = 1;
HANDLE Handle_Of_Thread_1 = 0;
Handle_Of_Thread_1 = CreateThread( NULL, 0, Thread_no_1, &Data_Of_Thread_1, 0, NULL);  
if ( Handle_Of_Thread_1 == NULL)
ExitProcess(Data_Of_Thread_1);

    while(1);
    {
    value = str[b];
    printf("%c",value);;
    b++;
    }

    return 0;
}

现在,当我运行这段代码时,我得到了这个错误:- 看来我不能同时读写。所以,我的问题是,如何检查内存是否可用于读取和写入值?

【问题讨论】:

    标签: c windows multithreading visual-studio-2010 malloc


    【解决方案1】:
     LOOP:do
       {
            str[c] = 'a';
                c++;
                goto LOOP;
       }while( a < 2 );
    

    这是一个无限循环,每次迭代都会调用goto LOOP;,没有机会检查while(a &lt; 2)

    【讨论】:

    • 感谢您的回答,但在我的实际项目中,我正在从串行端口读取值,并且主要我正在处理该数据。这就是为什么它应该是一个无限循环
    • 那么,你一定是超出了str的范围,你需要检查if (c &lt; 90000) str[c] = 'a';
    【解决方案2】:

    没有像“不能同时读写”这样的事情。不同的线程分别执行。即使在 2 个内核上,对内存的访问也是由控制器处理的,“同时”访问没有问题。但正如 Alter Mann 所说,第二个线程中的循环没有退出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-28
      • 1970-01-01
      • 1970-01-01
      • 2013-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多